diff --git a/CHANGELOG.md b/CHANGELOG.md index f9b5b5ae6..ed7bfe9d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## [Unreleased] +- Selecting an aircraft, a vessel, a train or a transit vehicle no longer + makes it bigger: it keeps the size and form it had and changes colour (a + transit vehicle only widens its dark ring). A click on an aircraft, a + vessel or a train no longer moves the camera to a new framing either: the + camera keeps its distance and viewing angle, the contact slides to the + centre over one second, and the camera then follows it from there (a + vessel, which is never followed, is left centred). A + follow target asks for this glide with `transitionS` (renderer contract, + conformance check `camera.follow.transition`); without it a follow frames + at once, as before. An aircraft chosen by voice, search or a shared link + is still framed as before (samehkhamis). - The renderer contract's `models` capability draws the procedural fleet models: a model item can carry its glTF bytes (`gltf`, drawn without a fetch), a per-axis stretch (`axisScale`), a colour for its tinted parts diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 54a84fd9c..2d1b31803 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -157,6 +157,18 @@ one. The stub's is a frame along the ground track, so an autodetect pins what both share (the range kept, north-up when still, the frame on the target standing up). +A follow target's `transitionS` makes the first framing a move instead of a +jump: from its first frame the eye is in the target's frame, and over +`transitionS` seconds of wall time it goes from where it stood to +`viewFrom`, by the one rule in `src/render/camera/followTransition.js` +(its offset and its view each turned and eased with smoothstep, the view +ending on the target with no roll). The Cesium port, the stub and a camera +controller import that rule rather than restating it. The tracked aircraft +aircraft and followed trains use it with a `viewFrom` taken from the camera +at the click: the eye's own view direction at its own range from the target, +so neither changes and only the eye's place moves, sliding the target to the +centre. The check `camera.follow.transition` pins it. + The Cesium port draws clamped shapes of every kind. A clamped outline is a draped line (a ground polyline a ring, under the shape's pick id; an outlined clamped shape is rebuilt on any change; a pulsing one pulses through its line's diff --git a/package.json b/package.json index 8e23c6849..3ee38cfeb 100644 --- a/package.json +++ b/package.json @@ -325,6 +325,7 @@ "./render/stub": "./src/render/stub/index.js", "./render/occlusion": "./src/render/occlusion/index.js", "./render/camera/events": "./src/render/camera/events.js", + "./render/camera/followTransition": "./src/render/camera/followTransition.js", "./render/cesium/plugin": "./src/render/cesium/plugin.js", "./render/cesium/unbound": "./src/render/cesium/unbound.js", "./render/conformance": "./src/render/conformance/index.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index b8c391ad9..7ee370ad9 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -41,6 +41,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/index.js", "src/geo/celestial.js", "src/geo/quaternion.js", @@ -1081,6 +1082,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -1282,6 +1284,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/render/cesium/internals.js", "src/render/cesium/common.js", "src/ui/localePicker.js", @@ -1642,6 +1645,7 @@ "src/geo/index.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -1783,7 +1787,6 @@ "src/data/renderAltitude.js", "src/data/routePlausible.js", "src/geoDistance.js", - "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", @@ -1866,6 +1869,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/quaternion.js", "src/geo/celestial.js", "src/geo/frames.js", @@ -1920,7 +1924,6 @@ "src/data/motionModel.js", "src/geo/julian.js", "src/data/renderAltitude.js", - "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", "src/layers/military/controller.js", "src/layers/military/index.js", @@ -1998,6 +2001,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -2052,7 +2056,6 @@ "src/data/renderAltitude.js", "src/data/routePlausible.js", "src/geoDistance.js", - "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", "src/layers/aircraft/classification.js", "src/layers/aircraft/index.js", @@ -2136,6 +2139,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/camera.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -2245,6 +2249,7 @@ "src/render/cesium/follow.js", "src/render/cesium/cameraControls.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/render/creditMarkup.js", "src/render/cesium/nativeClick.js", "src/data/iconSegment.js", @@ -2336,6 +2341,7 @@ "src/render/motion/iconMotion.js", "src/render/cesium/camera.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/index.js", "src/geo/geodesic.js", "src/geo/celestial.js", @@ -2456,6 +2462,7 @@ "src/queries/heights.js", "src/render/cesium/camera.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -2610,6 +2617,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/ellipsoid.js", "src/geo/quaternion.js", @@ -2690,6 +2698,7 @@ "src/layers/launches/policyHelpers.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -2776,6 +2785,7 @@ "src/geo/index.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -2880,6 +2890,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -2984,6 +2995,7 @@ "src/data/iconAtlas.js", "src/render/cesium/camera.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -3106,7 +3118,8 @@ "src/render/cesium/cameraControls.js", "src/render/input/router.js", "src/queries/heights.js", - "src/render/cesium/zoomOutGuard.js" + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, @@ -3171,6 +3184,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/ellipsoid.js", @@ -3279,6 +3293,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -3391,6 +3406,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -3500,6 +3516,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -3580,6 +3597,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -3705,6 +3723,7 @@ "src/render/cesium/camera.js", "src/render/cesium/cameraControls.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -3990,6 +4009,7 @@ "src/render/cesium/cameraControls.js", "src/render/cesium/follow.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/render/contract/index.js", "src/sources/sourceSlot.js", "src/app/sources.js", @@ -4133,7 +4153,6 @@ "src/data/tileBudget.js", "src/data/tr3bRegistry.js", "src/data/trackedCamera.js", - "src/data/trackedModelRegime.js", "src/data/trackedReadout.js", "src/data/trackingClickGesture.js", "src/data/traffic.js", @@ -5420,7 +5439,6 @@ "src/data/tileBudget.js", "src/data/tr3bRegistry.js", "src/data/trackedCamera.js", - "src/data/trackedModelRegime.js", "src/data/trackedReadout.js", "src/data/trackingClickGesture.js", "src/data/trafficBounds.js", @@ -5675,6 +5693,7 @@ "src/locations.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/render/cesium/common.js", "src/cityPois.js", "src/navigationPolicy.js", @@ -6129,6 +6148,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/index.js", "src/geo/geodesic.js", "src/geo/celestial.js", @@ -6233,7 +6253,8 @@ "src/data/pickRegistry.js", "src/data/scenePick.js", "src/render/rendererOf.js", - "src/render/cesium/zoomOutGuard.js" + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, @@ -6294,6 +6315,7 @@ "src/i18n/index.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -6571,7 +6593,8 @@ "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js", - "src/render/cesium/zoomOutGuard.js" + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, @@ -6908,6 +6931,7 @@ "src/render/cesium/follow.js", "src/render/rendererOf.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -7066,6 +7090,7 @@ "src/render/cesium/frame.js", "src/render/cesium/camera.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -7277,7 +7302,8 @@ "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js", - "src/render/cesium/zoomOutGuard.js" + "src/render/cesium/zoomOutGuard.js", + "src/render/camera/followTransition.js" ], "external": ["cesium"] }, @@ -7412,6 +7438,7 @@ "src/data/iconAtlas.js", "src/render/cesium/camera.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -7808,6 +7835,7 @@ "./render/stub", "./render/occlusion", "./render/camera/events", + "./render/camera/followTransition", "./render/conformance" ], "modules": [ @@ -7841,6 +7869,7 @@ "src/render/stub/camera.js", "src/geo/geodesic.js", "src/render/camera/events.js", + "src/render/camera/followTransition.js", "src/render/stub/viewRectangle.js", "src/render/input/router.js", "src/render/conformance/goldens/camera.json", diff --git a/scripts/track-regression.mjs b/scripts/track-regression.mjs index 086dbb655..4e163cd39 100644 --- a/scripts/track-regression.mjs +++ b/scripts/track-regression.mjs @@ -3269,23 +3269,18 @@ async function main() { walk(v.scene.primitives); return h; }; - // Tracked-contact model regime (2026-08-20). The tracked contact's model - // is NOT governed by the DISPLAY-rail 3D toggle — that toggle owns the - // FLEET's draw-call budget. The tracked model is default-on and driven by - // camera distance, entering below TRACKED_MODEL_ENTER_ALT_M and handing - // back to the billboard only above TRACKED_MODEL_EXIT_ALT_M (the - // anti-flap band). The CAMERA is therefore what decides whether a model - // or a billboard is the visual for a tracked contact, which is exactly - // what the display floor stands aside for — so these pins drive the - // camera explicitly instead of the toggle. + // Tracked-contact model regime. The tracked contact draws as a model + // exactly when the fleet's rule would draw it so: 3D on, the camera + // below the fleet ceiling, and the contact inside the nearest-first + // add/keep band from the eye. These pins drive the camera across that + // band: a model inside the ADD radius, the billboard past the KEEP one. // - // Read the thresholds from the app's own policy module so a later retune - // of the swap distance moves these pins with it rather than stranding - // them on stale numbers. - const reg = await import(`${window.__gevQaSourceBase || '/src'}/data/trackedModelRegime.js`); + // Read the radii from the app's own policy module so a retune moves + // these pins with it rather than stranding them on stale numbers. + const reg = await import(`${window.__gevQaSourceBase || '/src'}/layers/flights/policy.js`); window.__dfRegime = { - enter: reg.TRACKED_MODEL_ENTER_ALT_M, - exit: reg.TRACKED_MODEL_EXIT_ALT_M, + enter: reg.MODEL_PROX_ADD_M, + exit: reg.MODEL_PROX_KEEP_M, }; // Zooming while following is safe: the tracked-camera framer positions // the camera ONCE per selection and is deliberately read-only on normal diff --git a/src/data/aircraftIconLayer.js b/src/data/aircraftIconLayer.js index eee6babf2..a1d2728cc 100644 --- a/src/data/aircraftIconLayer.js +++ b/src/data/aircraftIconLayer.js @@ -31,6 +31,8 @@ import { cockpitContactDotImage } from './cockpitContactDot.js'; /** Raster size of the cockpit contact pip (cockpitContactDot.js draws 16 px). */ const COCKPIT_DOT_PX = 16; /** Fleet glyphs keep the established close-range 3× scale. */ +/** A contact icon's size before its scale, CSS px. */ +const FLEET_ICON_SIZE_PX = 20; const NORMAL_SCALE_BY_DISTANCE = Object.freeze({ near: 1000, nearValue: 3.0, @@ -670,6 +672,36 @@ export function createAircraftIcons({ state._iconFocusActive = active; } + /** + * How a contact's icon is drawn outside Cockpit: its image (and the sharper + * one it switches to up close), size, scale and scale by distance. The + * tracked contact's own icon is drawn with this too, so selecting a contact + * changes its colour and nothing else. + * @param {string} icao24 + * @param {object} [info] Its record. + * @returns {{image: string, imageLod: {near: string, switchPx: number}, + * size: [number, number], scale: number, scaleByDistance: object}} + */ + function _fleetLook(icao24, info = state.records.data.get(icao24)) { + const rendering = parts.rendering; + return { + image: aircraftIcon( + rendering._iconKind(icao24, info?.klass), + FLEET_ICON_PX, + ), + imageLod: { + near: aircraftIcon( + rendering._iconKind(icao24, info?.klass), + TRACKED_ICON_PX, + ), + switchPx, + }, + size: [FLEET_ICON_SIZE_PX, FLEET_ICON_SIZE_PX], + scale: rendering._fleetBillboardScale(icao24, info?.klass), + scaleByDistance: NORMAL_SCALE_BY_DISTANCE, + }; + } + /** Image, size, scale, tint and freshness for one row under the current * normal/cockpit contract. Motion and course stay with `_planIcon`. */ function _applyIconPresentation(icao24) { @@ -693,20 +725,7 @@ export function createAircraftIcons({ rotationMode: 'screen', } : { - image: aircraftIcon( - rendering._iconKind(icao24, info?.klass), - FLEET_ICON_PX, - ), - imageLod: { - near: aircraftIcon( - rendering._iconKind(icao24, info?.klass), - TRACKED_ICON_PX, - ), - switchPx, - }, - size: tracked ? [24, 24] : [20, 20], - scale: rendering._fleetBillboardScale(icao24, info?.klass), - scaleByDistance: NORMAL_SCALE_BY_DISTANCE, + ..._fleetLook(icao24, info), color: rgba(rendering._fleetBillboardColor(icao24, info)), rotationMode: 'course', }; @@ -777,6 +796,7 @@ export function createAircraftIcons({ _replanExpired, _focusIcons, _applyIconPresentation, + _fleetLook, _addIcon, _forgetContact, _iconIds, @@ -795,7 +815,7 @@ function baseContactItem(layerId, icao24, show) { pos: { x: 0, y: 0, z: 0 }, motion: { kind: 'hold', courseDeg: 0 }, course: 0, - size: [20, 20], + size: [FLEET_ICON_SIZE_PX, FLEET_ICON_SIZE_PX], rotationMode: 'course', recede: true, disableDepthTest: Infinity, diff --git a/src/data/aircraftModelLayer.js b/src/data/aircraftModelLayer.js index 7081dae56..e9c91e634 100644 --- a/src/data/aircraftModelLayer.js +++ b/src/data/aircraftModelLayer.js @@ -110,7 +110,6 @@ export function createAircraftModels({ afterReplan = () => {}, }) { const { isTr3b } = services.aircraftPresentation; - const { trackedModelScaleForPixelCap } = services.camera; const { focusNowMs, getFocusTarget } = services.focus; const writeEpsilon = DEFAULT_AIRCRAFT_RECESSION_PARAMS.writeEpsilon; let instances = 0; @@ -228,9 +227,8 @@ export function createAircraftModels({ * budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in * view. The toggle still OWNS the fleet — an operator who wants every in-view plane arms * `all`, and one who wants none turns 3D off — this predicate is unchanged. The TRACKED - * contact does not route through here: it is one model, it is what the camera is aimed at, - * and it takes its own default-on, hysteretic zoom regime - * (`_trackedModelRegimeActive`). */ + * contact routes through here too (`_trackedModelRegimeActive`), with its place in the + * fleet's cap, so selecting a contact never changes its form. */ function _modelRegimeActive(pose = _pose()) { if (!state._models3dEnabled) return false; @@ -467,7 +465,8 @@ export function createAircraftModels({ * flip take effect on the same frame rather than waiting for * `_updateTrackedModel` to clear `show`; the rendering test is what keeps a * null or still-loading tracked model from claiming a visual it is not - * drawing yet. + * drawing yet. Until the tracked model draws, the fleet model the contact + * had when it was selected still draws it, and owns the visual. * @param {string} icao24 * @param {import('./modelRecord.js').ModelRecord|null} [record] Resolved * fleet model record; null means absent. @@ -476,9 +475,11 @@ export function createAircraftModels({ function _modelOwnsVisual(icao24, record) { if (icao24 === state._trackedIcao) { + // Its fleet model draws it until the tracked model takes over. return ( parts.tracking._trackedModelRegimeActive() && - modelIsRendering(state._trackedModel) + (modelIsRendering(state._trackedModel) || + modelIsRendering(state._models.get(icao24))) ); } return modelIsRendering( @@ -673,10 +674,24 @@ export function createAircraftModels({ ); } + /** A fleet model still drawing the tracked contact (it was a model when + * it was selected) lets go once the tracked model draws, or once the + * contact is no longer drawn as a model at all. */ + function _releaseTrackedFleetModel() { + if (state._trackedIcao && state._models.has(state._trackedIcao)) + _releaseModel(state._trackedIcao); + } + /** Per-frame driver for the standalone tracked model. Runs every preUpdate (not the 80 ms fleet * cadence) so the centered plane moves smoothly. The tracked entity stays a pure billboard, so the * follow-camera's bounding sphere is ALWAYS ready — toggling 3D, or tracking while already zoomed - * in, can never stall or freeze the centering (the old model-graphic-on-entity failure mode). */ + * in, can never stall or freeze the centering (the old model-graphic-on-entity failure mode). + * + * The model draws exactly as the fleet would draw this contact: the same + * asset at the same scale and `minPixelSize` (`MODEL_MIN_PX`), only its + * tint the tracked colour; whether it draws at all is the fleet's rule too + * (`_trackedModelRegimeActive`). Selecting a contact changes its colour, + * never its size or form. */ function _updateTrackedModel() { // A failed load is let go (the icon carries the contact); the budget @@ -688,6 +703,7 @@ export function createAircraftModels({ state._modelSets; if (!active) { _hideTrackedModel(); + _releaseTrackedFleetModel(); return; } // Ask the frame-cached source directly. If the entity callback already ran, @@ -699,6 +715,7 @@ export function createAircraftModels({ parts.icons._iconPosition(state._trackedIcao); if (!pos) { _hideTrackedModel(); + _releaseTrackedFleetModel(); return; } const icao24 = state._trackedIcao; @@ -707,14 +724,17 @@ export function createAircraftModels({ if (state._trackedModel && state._trackedModel.id !== icao24) _releaseTrackedModel(); if (!state._trackedModel) { - if (!_trackedModelLoadAllowed()) return; // the icon carries it - // Until the fleet model set has loaded the icon carries it. - if (!spec.url) return; + // The icon carries it: after the load budget is spent, or until the + // fleet model set has loaded. + if (!_trackedModelLoadAllowed() || !spec.url) { + _releaseTrackedFleetModel(); + return; + } const record = createModelRecord({ specKey: _specKeyFor(meta), // type-change sync compares against this bellyM: spec.bellyM, scale: spec.scale, - minPixelSize: policy.TRACKED_MODEL_MIN_PX, + minPixelSize: policy.MODEL_MIN_PX, }); record.id = icao24; record.url = resolveAsset(spec.url); @@ -736,6 +756,7 @@ export function createAircraftModels({ const displayPos = _modelDisplayPosition(icao24, pos); if (!displayPos) { _hideTrackedModel(); // no ground evidence → the icon carries it + _releaseTrackedFleetModel(); return; } placeModel( @@ -743,19 +764,9 @@ export function createAircraftModels({ displayPos, _modelHeading(parts.motion._trackedDisplayCourse(), meta), ); - if (record.ready) { - const pose = _pose(); - record.scale = trackedModelScaleForPixelCap({ - baseScale: spec.scale, - nativeRadiusM: spec.nativeRadiusM, - rangeM: pose?.position ? distance(pose.position, displayPos) : NaN, - viewportHeightPx: _viewport().height, - fovyRad: pose?.fovy, - maximumPixelSize: policy.TRACKED_MODEL_MAX_PX, - }); - } showModel(record, record.ready); _send(state._modelSets.tracked, icao24, record, spec); + if (record.ready) _releaseTrackedFleetModel(); } /** @@ -830,7 +841,10 @@ export function createAircraftModels({ // Drop all models the moment we leave it (toggled off / zoomed out) so icons resume. const useModels = _modelRegimeActive(pose); if (!useModels && state._models.size) _releaseModels(); - if (!useModels) return; + if (!useModels) { + state._trackedModelEligible = false; + return; + } // 3D-model eligibility: by DISTANCE (the mode's add/keep band), with ON-SCREEN PRIORITY under the // cap. FOUR passes, visible-first, so the slots are spent on what you can see: (1) KEEP on-screen @@ -850,7 +864,10 @@ export function createAircraftModels({ // Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness. const cand = []; for (const icao of icons.ids()) { - if (icao === state._trackedIcao) continue; + // The tracked contact competes like any other (its model is drawn by + // `_updateTrackedModel`), so selecting it never changes its form; in + // cockpit it is the airframe you sit in, and takes no slot. + if (icao === state._trackedIcao && state._cockpitContactMode) continue; // A converted TR-3B renders as an icon and can never take a model, so // it must not occupy a CAP SLOT either — excluded here at selection time, // not just at the handoff below, or accumulated conversions would starve @@ -876,8 +893,12 @@ export function createAircraftModels({ const modelEligible = selectModelEligible(cand, { cap, addDistSq, - isModeled: (icao) => state._models.has(icao), + isModeled: (icao) => + state._models.has(icao) || + (icao === state._trackedIcao && state._trackedModelEligible), }); + state._trackedModelEligible = + Boolean(state._trackedIcao) && modelEligible.has(state._trackedIcao); const toRelease = []; for (const icao of state._models.keys()) { if (icao !== state._trackedIcao && !modelEligible.has(icao)) @@ -894,6 +915,8 @@ export function createAircraftModels({ const items = pendingItems; for (const icao24 of modelEligible) { if (isTr3b(icao24)) continue; + // The tracked contact's model is `_updateTrackedModel`'s. + if (icao24 === state._trackedIcao) continue; if (!icons.has(icao24)) continue; const position = icons.position(icao24, t); if (!parts.icons._aboveHorizon(position, occluder)) { diff --git a/src/data/flights.js b/src/data/flights.js index 06aa57d1d..b98f28af6 100644 --- a/src/data/flights.js +++ b/src/data/flights.js @@ -9,7 +9,6 @@ const flightsLayer = createApplicationFlights({ source: createFlightSource(), militaryRegistry, }); -export { TRACKED_MODEL_MAX_PX } from '../layers/flights/policy.js'; export const _floorGroundedDisplayPositionForTest = flightsLayer.testing._floorGroundedDisplayPositionForTest; export const _clearDisplayFloorStateForTest = @@ -41,6 +40,8 @@ export const _driveFleetModelHandoffForTest = export const _ensureFleetModelForTest = flightsLayer.testing._ensureFleetModelForTest; export const _trackedModelForTest = flightsLayer.testing._trackedModelForTest; +export const _trackedIconLookForTest = + flightsLayer.testing._trackedIconLookForTest; export const _modelSetIdsForTest = flightsLayer.testing._modelSetIdsForTest; export const _iconForTest = flightsLayer.testing._iconForTest; export const _setIconForTest = flightsLayer.testing._setIconForTest; diff --git a/src/data/militaryFlights.js b/src/data/militaryFlights.js index ea4dff7be..cf73a9462 100644 --- a/src/data/militaryFlights.js +++ b/src/data/militaryFlights.js @@ -9,7 +9,6 @@ const militaryFlightsLayer = createApplicationMilitary({ source: createMilitarySource(), militaryRegistry, }); -export { TRACKED_MODEL_MAX_PX } from '../layers/military/policy.js'; export const _setTrackedMilitaryRefreshStateForTest = militaryFlightsLayer.testing._setTrackedMilitaryRefreshStateForTest; export const _setMilitaryTrackingRefreshOutcomeForTest = @@ -34,6 +33,8 @@ export const _ensureFleetModelForTest = militaryFlightsLayer.testing._ensureFleetModelForTest; export const _trackedModelForTest = militaryFlightsLayer.testing._trackedModelForTest; +export const _trackedIconLookForTest = + militaryFlightsLayer.testing._trackedIconLookForTest; export const _modelSetIdsForTest = militaryFlightsLayer.testing._modelSetIdsForTest; export const _iconForTest = militaryFlightsLayer.testing._iconForTest; diff --git a/src/data/tr3bRegistry.test.mjs b/src/data/tr3bRegistry.test.mjs index 883f51178..e56925549 100644 --- a/src/data/tr3bRegistry.test.mjs +++ b/src/data/tr3bRegistry.test.mjs @@ -235,11 +235,9 @@ test('both flight layers keep a converted contact 2D and visible (render invaria // no TR-3B GLB, so the triangle icon stays the visual. assert.match(source, /for \(const icao24 of modelEligible\) \{\s*if \(isTr3b\(icao24\)\) continue;/, `${name}: fleet model handoff skips converted contacts`); - // The tracked regime became default-on and camera-distance driven - // (2026-08-19), so the suppression moved from a conjunct on - // `_modelRegimeActive()` to an explicit early return. The invariant is - // unchanged: a converted contact never reaches the model handoff. - assert.match(source, /if\s*\(\s*!(?:flightState\.)?_trackedIcao\s*\|\|\s*(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isTr3b\(\s*(?:flightState\.)?_trackedIcao,?\s*\),?\s*\)\s*\{/, + // The tracked regime's suppression is an explicit early return: a + // converted contact never reaches the model handoff. + assert.match(source, /if\s*\(\s*!(?:flightState\.)?_trackedIcao\s*\|\|\s*(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isTr3b\(\s*(?:flightState\.)?_trackedIcao,?\s*\),?\s*\)\s*(?:\{|return false;)/, `${name}: the standalone tracked model is suppressed for a converted contact`); // 2. The icon is never hidden by that suppression — it must keep diff --git a/src/data/trackedAircraftIcon.js b/src/data/trackedAircraftIcon.js index ca1a2948c..b9fd33219 100644 --- a/src/data/trackedAircraftIcon.js +++ b/src/data/trackedAircraftIcon.js @@ -83,6 +83,7 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) { pos: pos ? { x: pos.x, y: pos.y, z: pos.z } : { x: 0, y: 0, z: 0 }, show: Boolean(pos) && visible, image: shown.image, + ...(shown.imageLod ? { imageLod: shown.imageLod } : {}), size: [shown.sprite.width, shown.sprite.height], scale: shown.sprite.scale, scaleByDistance: shown.sprite.scaleByDistance, @@ -99,6 +100,10 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) { written.pos.y === item.pos.y && written.pos.z === item.pos.z && written.image === item.image && + written.imageLod?.near === item.imageLod?.near && + written.imageLod?.switchPx === item.imageLod?.switchPx && + written.size[0] === item.size[0] && + written.size[1] === item.size[1] && written.scale === item.scale && written.rotation === item.rotation && sameColor(written.color, item.color) @@ -115,8 +120,10 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) { * @param {object} target * @param {string} target.id The contact's id. * @param {string} target.image + * @param {{near: string, switchPx: number}} [target.imageLod] The + * sharper image it switches to once drawn larger than `switchPx`. * @param {{width: number, height: number, scale: number, - * scaleByDistance: object}} target.sprite + * scaleByDistance: object}} target.sprite Read each frame. * @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. @@ -131,9 +138,10 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) { }, /** Draw it from a new image (the class or conversion changed) next frame. */ - setImage(image) { + setImage(image, imageLod) { if (!shown) return; shown.image = image; + shown.imageLod = imageLod; requestFrame('tracked icon image'); }, diff --git a/src/data/trackedCamera.js b/src/data/trackedCamera.js index 4f6f26699..5ba9fdba5 100644 --- a/src/data/trackedCamera.js +++ b/src/data/trackedCamera.js @@ -1,3 +1,11 @@ +import { + distance, + eastNorthUp, + inverseFrameVector, + normalize, + scale, +} from '../geo/index.js'; + /** * Closest a follow camera comes to a tracked aircraft, metres: the camera * port's `minRange` for the aircraft layers' FollowTargets. @@ -5,44 +13,26 @@ export const FOLLOW_MIN_RANGE_M = 150; /** - * Preserve real-world model scale except when a very close tracked camera - * would make the selected aircraft dominate the viewport. - * - * @param {object} options - * @param {number} options.baseScale Asset's calibrated real-world scale. - * @param {number} options.nativeRadiusM Asset bounding radius before scale. - * @param {number} options.rangeM Camera-to-aircraft range. - * @param {number} options.viewportHeightPx Rendered viewport height. - * @param {number} options.fovyRad Vertical field of view. - * @param {number} options.maximumPixelSize Maximum selected-model diameter. - * @returns {number} Scale to apply to the model. + * Seconds a follow started by a click on a target takes to slide the target + * to the centre: the FollowTarget's `transitionS`. */ -export function trackedModelScaleForPixelCap({ - baseScale, - nativeRadiusM, - rangeM, - viewportHeightPx, - fovyRad, - maximumPixelSize, -}) { - if ( - !Number.isFinite(baseScale) || - baseScale <= 0 || - !Number.isFinite(nativeRadiusM) || - nativeRadiusM <= 0 || - !Number.isFinite(rangeM) || - rangeM <= 0 || - !Number.isFinite(viewportHeightPx) || - viewportHeightPx <= 0 || - !Number.isFinite(fovyRad) || - fovyRad <= 0 || - !Number.isFinite(maximumPixelSize) || - maximumPixelSize <= 0 - ) - return baseScale; - const focalLengthPx = viewportHeightPx / (2 * Math.tan(fovyRad / 2)); - const projectedDiameterPx = - (2 * nativeRadiusM * baseScale * focalLengthPx) / rangeM; - if (projectedDiameterPx <= maximumPixelSize) return baseScale; - return baseScale * (maximumPixelSize / projectedDiameterPx); +export const SELECTION_FOLLOW_TRANSITION_S = 1; + +/** + * A follow offset that keeps the camera's view of a target it starts + * following: the eye's own view direction, at its own distance from `at`, in + * `at`'s east-north-up frame (an `enu` FollowTarget's `viewFrom`). Followed + * from there, the camera neither zooms nor turns; only the eye moves, so the + * target comes to the centre. Null without an eye, or with the eye at `at`. + * @param {{position: object, direction: object}|null|undefined} pose The + * camera port's pose. + * @param {{x: number, y: number, z: number}|null|undefined} at The target. + * @returns {{x: number, y: number, z: number}|null} + */ +export function keptViewFrom(pose, at) { + if (!pose?.position || !pose?.direction || !at) return null; + const range = distance(pose.position, at); + if (!(range > 0) || !Number.isFinite(range)) return null; + const look = normalize(inverseFrameVector(eastNorthUp(at), pose.direction)); + return scale(look, -range); } diff --git a/src/data/trackedCamera.test.mjs b/src/data/trackedCamera.test.mjs index 95e542eca..60e452b11 100644 --- a/src/data/trackedCamera.test.mjs +++ b/src/data/trackedCamera.test.mjs @@ -1,7 +1,17 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { trackedModelScaleForPixelCap } from './trackedCamera.js'; +import { keptViewFrom } from './trackedCamera.js'; +import { + distance, + eastNorthUp, + framePoint, + frameVector, + fromDegrees, + magnitude, + normalize, + scale, +} from '../geo/index.js'; import { clampFollowEye as clampTrackedCameraPosition } from '../render/cesium/follow.js'; test('tracked camera origin crossing returns to the prior side at the minimum range', () => { @@ -12,7 +22,9 @@ test('tracked camera origin crossing returns to the prior side at the minimum ra const previous = new Cesium.Cartesian3(0, -1000, 600); assert.equal(clampTrackedCameraPosition(camera, previous, 150), true); assert.ok(Cesium.Cartesian3.dot(camera.position, previous) > 0); - assert.ok(Math.abs(Cesium.Cartesian3.magnitude(camera.position) - 150) < 1e-9); + assert.ok( + Math.abs(Cesium.Cartesian3.magnitude(camera.position) - 150) < 1e-9, + ); }); test('tracked camera clamps a too-close approach along the current sight line', () => { @@ -41,29 +53,24 @@ test('tracked camera leaves a safe approach unchanged', () => { assert.deepEqual(camera.position, before); }); -test('tracked model keeps calibrated scale when it projects below the pixel cap', () => { - const scale = trackedModelScaleForPixelCap({ - baseScale: 24, - nativeRadiusM: 1.43, - rangeM: 1000, - viewportHeightPx: 800, - fovyRad: Math.PI / 3, - maximumPixelSize: 104, - }); - assert.equal(scale, 24); +test('a kept view follows from the eye: its own view direction at its own range', () => { + const at = fromDegrees(-122.2, 37.7, 600); + const enu = eastNorthUp(at); + // An eye 2 km off, looking a little beside the target. + const eye = framePoint(enu, { x: 300, y: -1600, z: 1100 }); + const direction = normalize(frameVector(enu, { x: -250, y: 1600, z: -1150 })); + const viewFrom = keptViewFrom({ position: eye, direction }, at); + assert.ok(Math.abs(magnitude(viewFrom) - distance(eye, at)) < 1e-6); + // Followed from there, the eye looks the way it looked. + const followedLook = normalize(frameVector(enu, scale(viewFrom, -1))); + assert.ok(distance(followedLook, direction) < 1e-12); }); -test('tracked model shrinks smoothly when close enough to exceed the pixel cap', () => { - const scale = trackedModelScaleForPixelCap({ - baseScale: 24, - nativeRadiusM: 1.43, - rangeM: 150, - viewportHeightPx: 800, - fovyRad: Math.PI / 3, - maximumPixelSize: 104, - }); - const focalLengthPx = 800 / (2 * Math.tan(Math.PI / 6)); - const projectedDiameterPx = (2 * 1.43 * scale * focalLengthPx) / 150; - assert.ok(scale < 24); - assert.ok(Math.abs(projectedDiameterPx - 104) < 1e-9); +test('a kept view needs an eye apart from the target', () => { + const at = fromDegrees(-122.2, 37.7, 600); + assert.equal(keptViewFrom(null, at), null); + assert.equal( + keptViewFrom({ position: at, direction: { x: 0, y: 0, z: -1 } }, at), + null, + ); }); diff --git a/src/data/trackedModelRegime.test.mjs b/src/data/trackedModelForm.test.mjs similarity index 50% rename from src/data/trackedModelRegime.test.mjs rename to src/data/trackedModelForm.test.mjs index 09e56ca62..4c7f533dc 100644 --- a/src/data/trackedModelRegime.test.mjs +++ b/src/data/trackedModelForm.test.mjs @@ -1,31 +1,15 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs'; -// src/data/trackedModelRegime.test.mjs +// src/data/trackedModelForm.test.mjs // -// Zoom-driven 2D↔3D for the TRACKED contact (owner directive 2026-08-19). -// -// Two things are pinned here, and both are behavioural rather than cosmetic: -// -// 1. The POLICY — thresholds and hysteresis — as pure math in -// trackedModelRegime.js. The enter ceiling is the owner's playtested swap -// distance, deliberately much NEARER than the fleet ceiling, and the exit -// ceiling is deliberately higher than the enter ceiling. A regression that -// collapsed the two thresholds back into one would silently reintroduce -// billboard↔model flapping for a camera orbiting the boundary, which no -// unit test would otherwise catch. -// -// 2. The WIRING in both flight layers — that the tracked contact takes its -// model with the fleet `models3d` toggle OFF (the whole point of the -// feature), that cockpit and TR-3B suppression survived the rewrite, and -// that deselecting drops the regime. +// The TRACKED contact's form and size: selecting an aircraft changes its +// colour, never its size or form. The tracked model draws exactly when the +// fleet's own model rule would draw the contact (3D on, below the ceiling, a +// place in the nearest-first cap), at the fleet's scale and minimum pixel +// size; otherwise the tracked icon carries it, drawn as its fleet icon is. +// Both flight layers are pinned, with cockpit and TR-3B suppression, the +// load-failure budget and the grounded snap. import test from 'node:test'; import assert from 'node:assert/strict'; -import { - trackedModelZoomActive, - TRACKED_MODEL_ENTER_ALT_M, - TRACKED_MODEL_EXIT_ALT_M, - FLEET_MODEL_ALT_CEIL_M, - TRACKED_MODEL_EXIT_RATIO, -} from './trackedModelRegime.js'; import * as Cesium from 'cesium'; import flightsLayer, { _setTrackedFlightRefreshStateForTest, @@ -35,6 +19,7 @@ import flightsLayer, { _driveFleetModelHandoffForTest as flightsDriveFleetModel, _ensureFleetModelForTest as flightsEnsureFleetModel, _trackedModelForTest as flightsTrackedModel, + _trackedIconLookForTest as flightsTrackedIconLook, _modelSetIdsForTest as flightsModelSetIds, _iconForTest as flightsIcon, _setIconForTest as flightsSetIcon, @@ -47,12 +32,16 @@ import militaryFlightsLayer, { _driveFleetModelHandoffForTest as militaryDriveFleetModel, _ensureFleetModelForTest as militaryEnsureFleetModel, _trackedModelForTest as militaryTrackedModel, + _trackedIconLookForTest as militaryTrackedIconLook, _modelSetIdsForTest as militaryModelSetIds, _iconForTest as militaryIcon, _setIconForTest as militarySetIcon, } from './militaryFlights.js'; import { clearTr3bRegistry, setTr3b } from './tr3bRegistry.js'; -import { reportMeshFloorCell, _clearMeshFloorCellsForTest } from './groundFloor.js'; +import { + reportMeshFloorCell, + _clearMeshFloorCellsForTest, +} from './groundFloor.js'; import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; import { loadFleetModelSet } from './fleetModels.js'; @@ -67,101 +56,8 @@ console.info = _silentInfo; const FLIGHTS_META = Object.freeze({ typeCode: 'A320', klass: 'airliner' }); const MILITARY_META = Object.freeze({ typeCode: 'F16', klass: 'fastjet' }); -// Sample altitudes are expressed RELATIVE to the band rather than as absolute -// offsets. The thresholds have already been retuned once (1_000_000 → 150_000 -// on the owner's playtest), and the fixed ±50 km / ±100 km offsets that were -// fine against a 150 km-wide band silently landed on the WRONG SIDE of the exit -// ceiling against a 22.5 km one. Deriving them keeps the next retune honest. -const BAND_WIDTH_M = TRACKED_MODEL_EXIT_ALT_M - TRACKED_MODEL_ENTER_ALT_M; -/** Strictly between enter and exit: latched → holds, fresh → does not. */ -const INSIDE_BAND_M = TRACKED_MODEL_ENTER_ALT_M + BAND_WIDTH_M / 2; -/** Unambiguously past the exit ceiling. */ -const FAR_OUTSIDE_M = TRACKED_MODEL_EXIT_ALT_M * 2; -/** Unambiguously below the enter ceiling. */ -const WELL_INSIDE_M = TRACKED_MODEL_ENTER_ALT_M / 2; - // --------------------------------------------------------------------------- -// 1. Policy: thresholds + hysteresis math -// --------------------------------------------------------------------------- - -test('the tracked 3D takeover sits at the owner-playtested swap distance', () => { - // Owner playtest 2026-08-20: an earlier 1_000_000 m ceiling "pops to 3D far - // too early" — 2D still reads correctly at ~600_000 m and the swap belongs at - // ~150_000 m. These are the numbers the operator judged by eye, so they are - // pinned literally rather than derived from anything. - assert.equal(TRACKED_MODEL_ENTER_ALT_M, 150_000); - assert.equal(trackedModelZoomActive(600_000, false), false, - 'the owner explicitly called 2D correct at ~600 km — it must not model there'); - assert.equal(trackedModelZoomActive(140_000, false), true, - 'inside the ruled swap distance the model owns the visual'); -}); - -test('the tracked contact swaps NEARER than the fleet — a recorded inversion, not a bug', () => { - // Consequence of the owner's number, spelled out so it cannot be "tidied - // away": with the DISPLAY-rail 3D toggle ON, camera altitudes between the - // tracked ceiling and the fleet ceiling draw surrounding contacts as models - // while the SELECTED one is still a billboard. The fleet pass skips the - // tracked icao, so nothing double-draws — this is purely an ordering - // difference. Aligning them is a fleet-side decision, out of scope here. - assert.equal(FLEET_MODEL_ALT_CEIL_M, 800_000, - 'mirror of MODEL_ALT_CEIL_M in both flight layers'); - assert.ok(TRACKED_MODEL_ENTER_ALT_M < FLEET_MODEL_ALT_CEIL_M, - 'the tracked contact deliberately enters 3D closer in than the fleet does'); - assert.equal(trackedModelZoomActive(FLEET_MODEL_ALT_CEIL_M - 1, false), false, - 'just inside the fleet ceiling the tracked contact is still 2D'); -}); - -test('enter and exit thresholds are ASYMMETRIC — the anti-flap band', () => { - assert.equal(TRACKED_MODEL_EXIT_RATIO, 1.15); - assert.equal(TRACKED_MODEL_EXIT_ALT_M, 172_500); - assert.equal(TRACKED_MODEL_EXIT_ALT_M, TRACKED_MODEL_ENTER_ALT_M * TRACKED_MODEL_EXIT_RATIO, - 'the exit ceiling stays derived from enter, so retuning enter carries the band with it'); - assert.ok(TRACKED_MODEL_EXIT_ALT_M > TRACKED_MODEL_ENTER_ALT_M, - 'a single shared threshold is exactly the flapping bug this prevents'); -}); - -test('the regime enters at the enter ceiling and leaves only past the exit ceiling', () => { - // Coming in from far out: nothing below the enter ceiling → still 2D. - assert.equal(trackedModelZoomActive(TRACKED_MODEL_EXIT_ALT_M + 1, false), false); - assert.equal(trackedModelZoomActive(TRACKED_MODEL_ENTER_ALT_M + 1, false), false); - assert.equal(trackedModelZoomActive(TRACKED_MODEL_ENTER_ALT_M, false), false, - 'the ceiling itself is still outside — the regime is strictly below it'); - assert.equal(trackedModelZoomActive(TRACKED_MODEL_ENTER_ALT_M - 1, false), true); - - // Already inside: the model holds the visual all the way out to the exit ceiling. - assert.equal(trackedModelZoomActive(TRACKED_MODEL_ENTER_ALT_M + 1, true), true, - 'crossing back over the ENTER ceiling must not hand back — that is the flap'); - assert.equal(trackedModelZoomActive(TRACKED_MODEL_EXIT_ALT_M - 1, true), true); - assert.equal(trackedModelZoomActive(TRACKED_MODEL_EXIT_ALT_M, true), false); - assert.equal(trackedModelZoomActive(TRACKED_MODEL_EXIT_ALT_M + 1, true), false); -}); - -test('an orbit sitting AT the boundary never flaps', () => { - // Simulate a camera loitering on the enter ceiling with orbital - // wobble. Under a single threshold this alternates every sample. - let active = trackedModelZoomActive(TRACKED_MODEL_ENTER_ALT_M - BAND_WIDTH_M / 4, false); - assert.equal(active, true, 'the orbit begins inside the regime'); - let transitions = 0; - for (let i = 0; i < 40; i++) { - const wobble = (i % 2 === 0 ? 1 : -1) * (BAND_WIDTH_M / 8); - const next = trackedModelZoomActive(TRACKED_MODEL_ENTER_ALT_M + wobble, active); - if (next !== active) transitions++; - active = next; - } - assert.equal(transitions, 0, 'the hysteresis band absorbs boundary wobble entirely'); - assert.equal(active, true); -}); - -test('a missing camera height reads as infinitely far out, never as "zoomed in"', () => { - for (const height of [undefined, null, NaN, Infinity]) { - assert.equal(trackedModelZoomActive(height, false), false); - assert.equal(trackedModelZoomActive(height, true), false, - 'a torn-down viewer must not latch the model on'); - } -}); - -// --------------------------------------------------------------------------- -// 2. Wiring: both flight layers +// Both flight layers // --------------------------------------------------------------------------- const ICAO = 'abc123'; @@ -170,20 +66,29 @@ const ICAO = 'abc123'; * `window`. Give it somewhere to land so the test drives production code * rather than a stand-in. */ if (typeof globalThis.window === 'undefined') { - globalThis.window = { dispatchEvent() { return true; }, addEventListener() {}, removeEventListener() {} }; + globalThis.window = { + dispatchEvent() { + return true; + }, + addEventListener() {}, + removeEventListener() {}, + }; } /** A viewer stub whose camera altitude the test can move between evaluations. * Its renderer has a fake draw port (`viewer.draw`) the layer's model sets * are made on, a globe whose drawn tiles settle as `viewer.tileset` says, and * a query port whose height samples are `sampleHeight`'s. */ -function viewerAtHeight(height, { tilesLoaded = true, sampleHeight = () => undefined } = {}) { +function viewerAtHeight( + height, + { tilesLoaded = true, sampleHeight = () => undefined, eye } = {}, +) { const tileset = { show: true, tilesLoaded }; const draw = fakeDrawPort(); const viewer = { camera: { positionCartographic: { height }, - positionWC: Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 5000), + positionWC: eye ?? Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 5000), frustum: { fovy: Cesium.Math.toRadians(60) }, }, scene: { @@ -211,7 +116,11 @@ function modelSet(fixture, viewer, which) { /** Where a model record places its model (its placement's translation). */ function placedAt(record) { - return new Cesium.Cartesian3(record.matrix[12], record.matrix[13], record.matrix[14]); + return new Cesium.Cartesian3( + record.matrix[12], + record.matrix[13], + record.matrix[14], + ); } /** A billboard with a real position, so the tracked-model driver has somewhere @@ -256,9 +165,17 @@ const LAYERS = [ trackedModel: flightsTrackedModel, modelSetIds: flightsModelSetIds, trackedBillboardColor: flightsTrackedBillboardColor, + trackedIconLook: flightsTrackedIconLook, /** How far a grounded A320 stands its origin above the ground (scaled wheel clearance). */ bellyM: aircraftLayerModelSpec(FLIGHTS_META).bellyM, - seed({ viewer, tracked = true, icao24 = ICAO, onGround = false, models = [] }) { + seed({ + viewer, + tracked = true, + icao24 = ICAO, + onGround = false, + models = [], + trackedModelEligible = true, + }) { const billboard = contactBillboard(); _setTrackedFlightRefreshStateForTest({ icao24, @@ -269,7 +186,13 @@ const LAYERS = [ tracked, models, draw: viewer.draw, - meta: { callsign: 'TEST123 ', altitude: 10_668, ...FLIGHTS_META, onGround }, + trackedModelEligible, + meta: { + callsign: 'TEST123 ', + altitude: 10_668, + ...FLIGHTS_META, + onGround, + }, }); return iconView(icao24, flightsIcon, flightsSetIcon); }, @@ -284,8 +207,16 @@ const LAYERS = [ trackedModel: militaryTrackedModel, modelSetIds: militaryModelSetIds, trackedBillboardColor: militaryTrackedBillboardColor, + trackedIconLook: militaryTrackedIconLook, bellyM: aircraftLayerModelSpec(MILITARY_META).bellyM, - seed({ viewer, tracked = true, icao24 = ICAO, onGround = false, models = [] }) { + seed({ + viewer, + tracked = true, + icao24 = ICAO, + onGround = false, + models = [], + trackedModelEligible = true, + }) { const billboard = contactBillboard(); _setTrackedMilitaryRefreshStateForTest({ icao24, @@ -296,7 +227,13 @@ const LAYERS = [ tracked, models, draw: viewer.draw, - meta: { callsign: 'TEST123 ', altitudeFt: 35_000, ...MILITARY_META, onGround }, + trackedModelEligible, + meta: { + callsign: 'TEST123 ', + altitudeFt: 35_000, + ...MILITARY_META, + onGround, + }, }); return iconView(icao24, militaryIcon, militarySetIcon); }, @@ -323,35 +260,77 @@ for (const fixture of LAYERS) { const admitted = fixture.ensureFleetModel(loadingIcao); assert.ok(admitted, 'the production fleet admission records a model'); assert.equal(admitted.ready, false, 'nothing has loaded yet'); - assert.equal(admitted.show, false, 'admission records the model hidden until it is placed'); - assert.equal(billboard.show, true, 'the 2D billboard owns the cold loading state'); + assert.equal( + admitted.show, + false, + 'admission records the model hidden until it is placed', + ); + assert.equal( + billboard.show, + true, + 'the 2D billboard owns the cold loading state', + ); - const nearby = fixture.layer.getNearby(billboard.position, 1_000, 50) + const nearby = fixture.layer + .getNearby(billboard.position, 1_000, 50) .find((object) => object.icao24 === loadingIcao); - assert.ok(nearby, 'fleet proximity retains the billboard-owned loading contact'); - assert.ok(Cesium.Cartesian3.equalsEpsilon(nearby.position, billboard.position, 0, 1e-6), - 'fleet proximity stays at the billboard rather than the unplaced model'); + assert.ok( + nearby, + 'fleet proximity retains the billboard-owned loading contact', + ); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + nearby.position, + billboard.position, + 0, + 1e-6, + ), + 'fleet proximity stays at the billboard rather than the unplaced model', + ); fixture.driveFleetModel({ icao24: loadingIcao, position, course: 92 }); const fleet = modelSet(fixture, viewer, 'fleet'); const item = fleet.items.get(loadingIcao); assert.ok(item, 'the model set loads the contact from its first write'); - assert.equal(item.show, false, 'and draws nothing while there is no safe placement'); + assert.equal( + item.show, + false, + 'and draws nothing while there is no safe placement', + ); assert.equal(admitted.show, false); - assert.equal(billboard.show, true, 'cold terrain preserves the same visible 2D owner'); + assert.equal( + billboard.show, + true, + 'cold terrain preserves the same visible 2D owner', + ); // A load that never finishes (a missing or broken GLB) never fires // `ready`, so the billboard stays the visual for as long as it lasts. viewer.draw.ready(fleet.spec.id, 'someone-else'); - assert.equal(admitted.ready, false, 'another item loading does not ready this one'); + assert.equal( + admitted.ready, + false, + 'another item loading does not ready this one', + ); fixture.driveFleetModel({ icao24: loadingIcao, position, course: 92 }); - assert.equal(billboard.show, true, 'an unready model leaves the 2D owner visible'); - assert.ok(fixture.layer.getNearby(billboard.position, 1_000, 50) - .some((object) => object.icao24 === loadingIcao), - 'an unready model leaves the contact in the billboard proximity cohort'); + assert.equal( + billboard.show, + true, + 'an unready model leaves the 2D owner visible', + ); + assert.ok( + fixture.layer + .getNearby(billboard.position, 1_000, 50) + .some((object) => object.icao24 === loadingIcao), + 'an unready model leaves the contact in the billboard proximity cohort', + ); viewer.draw.ready(fleet.spec.id, loadingIcao); - assert.equal(admitted.ready, true, "the set's ready marks the contact's model loaded"); + assert.equal( + admitted.ready, + true, + "the set's ready marks the contact's model loaded", + ); } finally { fixture.layer.setParams({ models3d: false }); fixture.layer.stopTracking(); @@ -361,7 +340,7 @@ for (const fixture of LAYERS) { test(`${fixture.name}: a tracked model that fails to load is retried within a per-selection budget`, () => { clearTr3bRegistry(); fixture.layer.stopTracking(); - fixture.layer.setParams({ models3d: false }); + fixture.layer.setParams({ models3d: true }); const realNow = Date.now; const realWarn = console.warn; const warnings = []; @@ -379,16 +358,33 @@ for (const fixture of LAYERS) { for (let attempt = 1; attempt <= 3; attempt++) { fail(); fixture.driveTrackedModel(); - assert.equal(tracked.items.has(icao24), false, `failure ${attempt}: let go`); + assert.equal( + tracked.items.has(icao24), + false, + `failure ${attempt}: let go`, + ); assert.equal(fixture.trackedModel(), null); - assert.equal(fixture.trackedBillboardColor()[3], 1, 'the icon carries the contact'); + assert.equal( + fixture.trackedBillboardColor()[3], + 1, + 'the icon carries the contact', + ); now += 1499; fixture.driveTrackedModel(); - assert.equal(tracked.items.has(icao24), false, 'not before the backoff'); + assert.equal( + tracked.items.has(icao24), + false, + 'not before the backoff', + ); now += 1; fixture.driveTrackedModel(); - assert.equal(tracked.items.has(icao24), attempt < 3, - attempt < 3 ? 'loaded again after the backoff' : 'given up after the third failure'); + assert.equal( + tracked.items.has(icao24), + attempt < 3, + attempt < 3 + ? 'loaded again after the backoff' + : 'given up after the third failure', + ); } assert.equal(warnings.length, 1, 'giving up is said once'); now += 60_000; @@ -406,7 +402,11 @@ for (const fixture of LAYERS) { fail(); viewer.draw.ready(tracked.spec.id, icao24); fixture.driveTrackedModel(); - assert.equal(fixture.trackedModel(), recovered, 'a model that loaded after all is kept'); + assert.equal( + fixture.trackedModel(), + recovered, + 'a model that loaded after all is kept', + ); assert.ok(tracked.items.has(icao24)); fixture.layer.stopTracking(); fixture.seed({ viewer, icao24 }); @@ -428,10 +428,14 @@ for (const fixture of LAYERS) { fixture.driveTrackedModel(); now += 1500; fixture.driveTrackedModel(); - assert.ok(tracked.items.has(icao24), 'two failures after a good load are under the budget'); + assert.ok( + tracked.items.has(icao24), + 'two failures after a good load are under the budget', + ); } finally { Date.now = realNow; console.warn = realWarn; + fixture.layer.setParams({ models3d: false }); fixture.layer.stopTracking(); } }); @@ -452,7 +456,10 @@ for (const fixture of LAYERS) { const normal = fleet.items.get(icao24); assert.equal(normal.shading, 'pbr'); assert.equal(normal.show, true); - assert.ok(normal.colorBlend.amount < 1, 'the asset keeps a hint of its own colour'); + assert.ok( + normal.colorBlend.amount < 1, + 'the asset keeps a hint of its own colour', + ); fixture.layer.setParams({ irBoost: true }); fixture.driveFleetModel({ icao24, position, course: 92 }); @@ -461,7 +468,11 @@ for (const fixture of LAYERS) { assert.equal(boosted.shading, 'unlit'); assert.deepEqual(boosted.tint, [1, 1, 1, 1]); assert.deepEqual(boosted.colorBlend, { mode: 'mix', amount: 1 }); - assert.equal(fixture.ensureFleetModel(icao24), record, 'the same model restyles; nothing reloads'); + assert.equal( + fixture.ensureFleetModel(icao24), + record, + 'the same model restyles; nothing reloads', + ); assert.equal(boosted.url, normal.url); } finally { fixture.layer.setParams({ models3d: false, irBoost: false }); @@ -480,7 +491,10 @@ for (const fixture of LAYERS) { const sampledHeight = 187.5; const viewer = viewerAtHeight(30_000, { tilesLoaded: false, - sampleHeight: () => { sampleCalls++; return sampledHeight; }, + sampleHeight: () => { + sampleCalls++; + return sampledHeight; + }, }); const icao24 = fixture.name === 'flights' ? 'a0f101' : 'b0f101'; const model = { @@ -500,39 +514,96 @@ for (const fixture of LAYERS) { }); billboard.show = false; - let ownsVisual = fixture.driveFleetModel({ icao24, position, course: 92 }); - assert.equal(ownsVisual, false, 'cold terrain cannot transfer ownership to 3D'); - assert.equal(model.show, false, 'the ready primitive is hidden until ground resolves'); - assert.equal(billboard.show, true, 'the 2D contact returns in the same handoff turn'); - assert.ok(model.show || billboard.show, 'the contact never has both visuals hidden'); + let ownsVisual = fixture.driveFleetModel({ + icao24, + position, + course: 92, + }); + assert.equal( + ownsVisual, + false, + 'cold terrain cannot transfer ownership to 3D', + ); + assert.equal( + model.show, + false, + 'the ready primitive is hidden until ground resolves', + ); + assert.equal( + billboard.show, + true, + 'the 2D contact returns in the same handoff turn', + ); + assert.ok( + model.show || billboard.show, + 'the contact never has both visuals hidden', + ); assert.equal(sampleCalls, 0, 'cold tiles do not force sampleHeight'); now += 1000; viewer.tileset.tilesLoaded = true; ownsVisual = fixture.driveFleetModel({ icao24, position, course: 92 }); - assert.equal(ownsVisual, false, 'the miss backoff remains in force before two seconds'); - assert.equal(sampleCalls, 0, 'backoff prevents an early synchronous sample'); - assert.ok(model.show || billboard.show, 'backoff still leaves a visible owner'); + assert.equal( + ownsVisual, + false, + 'the miss backoff remains in force before two seconds', + ); + assert.equal( + sampleCalls, + 0, + 'backoff prevents an early synchronous sample', + ); + assert.ok( + model.show || billboard.show, + 'backoff still leaves a visible owner', + ); now += 1500; ownsVisual = fixture.driveFleetModel({ icao24, position, course: 92 }); - assert.equal(ownsVisual, true, 'the model takes over after a valid terrain sample'); - assert.equal(sampleCalls, 1, 'the settled terrain is sampled exactly once'); + assert.equal( + ownsVisual, + true, + 'the model takes over after a valid terrain sample', + ); + assert.equal( + sampleCalls, + 1, + 'the settled terrain is sampled exactly once', + ); assert.equal(model.show, true); assert.equal(billboard.show, false); - assert.ok(model.show || billboard.show, 'successful handoff keeps a visible owner'); + assert.ok( + model.show || billboard.show, + 'successful handoff keeps a visible owner', + ); const placed = placedAt(model); const placedHeight = Cesium.Cartographic.fromCartesian(placed).height; - assert.ok(Math.abs(placedHeight - (sampledHeight + fixture.bellyM)) < 0.001, - `placement uses the exact ${fixture.bellyM} m asset-measured belly offset`); + assert.ok( + Math.abs(placedHeight - (sampledHeight + fixture.bellyM)) < 0.001, + `placement uses the exact ${fixture.bellyM} m asset-measured belly offset`, + ); viewer.tileset.tilesLoaded = false; const datumShifted = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, -500); - ownsVisual = fixture.driveFleetModel({ icao24, position: datumShifted, course: 92 }); - assert.equal(ownsVisual, true, - 'a poll-time vertical datum change does not invalidate a stationary snap'); - assert.equal(sampleCalls, 1, 'the height-normalized cache does not resample vertically'); - assert.ok(model.show || billboard.show, 'datum transition keeps a visible owner'); + ownsVisual = fixture.driveFleetModel({ + icao24, + position: datumShifted, + course: 92, + }); + assert.equal( + ownsVisual, + true, + 'a poll-time vertical datum change does not invalidate a stationary snap', + ); + assert.equal( + sampleCalls, + 1, + 'the height-normalized cache does not resample vertically', + ); + assert.ok( + model.show || billboard.show, + 'datum transition keeps a visible owner', + ); // Taxi past the 50 m resample threshold while the tiles are gone. The old // snap stops being the direct answer, but it is still a MEASUREMENT of @@ -540,26 +611,55 @@ for (const fixture of LAYERS) { // model here would pop a taxiing aircraft from 3D to 2D for a whole retry // backoff (2–30 s), which is the one thing the gate must not introduce. const taxied = Cesium.Cartesian3.fromDegrees(-97.709, 30.21, -500); - ownsVisual = fixture.driveFleetModel({ icao24, position: taxied, course: 92 }); - assert.equal(ownsVisual, true, - 'a taxi-invalidated snap is HELD through the resample outage, not dropped'); - assert.equal(model.show, true, 'no 3D→2D pop while the resample is backing off'); + ownsVisual = fixture.driveFleetModel({ + icao24, + position: taxied, + course: 92, + }); + assert.equal( + ownsVisual, + true, + 'a taxi-invalidated snap is HELD through the resample outage, not dropped', + ); + assert.equal( + model.show, + true, + 'no 3D→2D pop while the resample is backing off', + ); assert.equal(billboard.show, false); - assert.equal(sampleCalls, 1, 'and the hold costs no extra synchronous sample'); + assert.equal( + sampleCalls, + 1, + 'and the hold costs no extra synchronous sample', + ); const held = placedAt(model); - assert.ok(Math.abs(Cesium.Cartographic.fromCartesian(held).height - - (sampledHeight + fixture.bellyM)) < 0.001, - 'the hold places the model on the last MEASURED floor, not on the feed altitude'); + assert.ok( + Math.abs( + Cesium.Cartographic.fromCartesian(held).height - + (sampledHeight + fixture.bellyM), + ) < 0.001, + 'the hold places the model on the last MEASURED floor, not on the feed altitude', + ); // Past the drift bound the memory stops describing anywhere this contact // has been, so it is dropped rather than stretched and the gate takes over. const farTaxied = Cesium.Cartesian3.fromDegrees(-97.707, 30.21, -500); // ~289 m out - ownsVisual = fixture.driveFleetModel({ icao24, position: farTaxied, course: 92 }); - assert.equal(ownsVisual, false, - 'past HELD_SNAP_MAX_DRIFT_M the hold is released and the model is withheld'); + ownsVisual = fixture.driveFleetModel({ + icao24, + position: farTaxied, + course: 92, + }); + assert.equal( + ownsVisual, + false, + 'past HELD_SNAP_MAX_DRIFT_M the hold is released and the model is withheld', + ); assert.equal(model.show, false); assert.equal(billboard.show, true); - assert.ok(model.show || billboard.show, 'release returns atomically to 2D'); + assert.ok( + model.show || billboard.show, + 'release returns atomically to 2D', + ); const failedIcao = fixture.name === 'flights' ? 'a0f102' : 'b0f102'; const failedBillboard = fixture.seed({ @@ -575,8 +675,16 @@ for (const fixture of LAYERS) { position, course: 92, }); - assert.equal(ownsVisual, false, 'a missing/failed model never claims ownership'); - assert.equal(failedBillboard.show, true, 'load failure keeps the billboard visible'); + assert.equal( + ownsVisual, + false, + 'a missing/failed model never claims ownership', + ); + assert.equal( + failedBillboard.show, + true, + 'load failure keeps the billboard visible', + ); } finally { Date.now = realNow; fixture.layer.stopTracking(); @@ -605,7 +713,10 @@ for (const fixture of LAYERS) { let sampled = 120; const viewer = viewerAtHeight(30_000, { tilesLoaded: true, - sampleHeight: () => { sampleCalls++; return sampled; }, + sampleHeight: () => { + sampleCalls++; + return sampled; + }, }); const icao24 = fixture.name === 'flights' ? 'a0f103' : 'b0f103'; const model = { @@ -614,9 +725,8 @@ for (const fixture of LAYERS) { show: true, }; /** Height (m) the model's matrix currently places it at. */ - const placedHeightM = () => Cesium.Cartographic.fromCartesian( - placedAt(model), - ).height; + const placedHeightM = () => + Cesium.Cartographic.fromCartesian(placedAt(model)).height; const LAT = 30.21; const A_LON = -97.71; @@ -639,18 +749,36 @@ for (const fixture of LAYERS) { const atA = Cesium.Cartesian3.fromDegrees(A_LON, LAT, 0); const atB = Cesium.Cartesian3.fromDegrees(B_LON, LAT, 0); const taxiM = Cesium.Cartesian3.distance( - Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(atA, new Cesium.Cartesian3()), - Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(atB, new Cesium.Cartesian3()), + Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface( + atA, + new Cesium.Cartesian3(), + ), + Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface( + atB, + new Cesium.Cartesian3(), + ), + ); + assert.ok( + taxiM > 50 && taxiM < 250, + `the repro must sit INSIDE the drift bound to be a repro (taxi ${taxiM.toFixed(1)} m)`, ); - assert.ok(taxiM > 50 && taxiM < 250, - `the repro must sit INSIDE the drift bound to be a repro (taxi ${taxiM.toFixed(1)} m)`); // A: the snap resolves and the model takes the visual. - let ownsVisual = fixture.driveFleetModel({ icao24, position: atA, course: 92 }); - assert.equal(ownsVisual, true, 'a measured snap at A hands the visual to the model'); + let ownsVisual = fixture.driveFleetModel({ + icao24, + position: atA, + course: 92, + }); + assert.equal( + ownsVisual, + true, + 'a measured snap at A hands the visual to the model', + ); assert.equal(sampleCalls, 1); - assert.ok(Math.abs(placedHeightM() - (sampled + fixture.bellyM)) < 0.001, - 'the model stands on the measured 120 m at A'); + assert.ok( + Math.abs(placedHeightM() - (sampled + fixture.bellyM)) < 0.001, + 'the model stands on the measured 120 m at A', + ); // Something measures B's surface — the mesh-floor cells the billboard // chain and meshFloorSampler share. This is the fresh evidence. @@ -659,20 +787,37 @@ for (const fixture of LAYERS) { // B, with the resample missing: tiles gone, so no sample can land. viewer.tileset.tilesLoaded = false; now += 60_000; - ownsVisual = fixture.driveFleetModel({ icao24, position: atB, course: 92 }); + ownsVisual = fixture.driveFleetModel({ + icao24, + position: atB, + course: 92, + }); assert.equal(sampleCalls, 1, 'the missing resample fires no new sample'); - assert.equal(ownsVisual, false, - 'a held measurement contradicted by measured ground must not place the model'); + assert.equal( + ownsVisual, + false, + 'a held measurement contradicted by measured ground must not place the model', + ); assert.equal(model.show, false, 'nothing is drawn 30 m under the apron'); - assert.equal(billboard.show, true, 'the floored 2D billboard is the honest fallback'); - assert.ok(model.show || billboard.show, 'the release is atomic — never both hidden'); + assert.equal( + billboard.show, + true, + 'the floored 2D billboard is the honest fallback', + ); + assert.ok( + model.show || billboard.show, + 'the release is atomic — never both hidden', + ); // "If the contact remains at B, misses can preserve that burial forever." // They cannot: the hold is gone, so every later miss re-answers COLD. for (let i = 0; i < 5; i++) { now += 60_000; - assert.equal(fixture.driveFleetModel({ icao24, position: atB, course: 92 }), false, - 'repeated misses must not resurrect the dropped hold'); + assert.equal( + fixture.driveFleetModel({ icao24, position: atB, course: 92 }), + false, + 'repeated misses must not resurrect the dropped hold', + ); assert.equal(model.show, false); } @@ -680,11 +825,17 @@ for (const fixture of LAYERS) { sampled = B_GROUND_M; viewer.tileset.tilesLoaded = true; now += 60_000; - ownsVisual = fixture.driveFleetModel({ icao24, position: atB, course: 92 }); + ownsVisual = fixture.driveFleetModel({ + icao24, + position: atB, + course: 92, + }); assert.equal(ownsVisual, true, 'a fresh sample at B restores the model'); assert.equal(sampleCalls, 2); - assert.ok(Math.abs(placedHeightM() - (B_GROUND_M + fixture.bellyM)) < 0.001, - "the restored model stands on B's 150 m, not on the stale 120 m"); + assert.ok( + Math.abs(placedHeightM() - (B_GROUND_M + fixture.bellyM)) < 0.001, + "the restored model stands on B's 150 m, not on the stale 120 m", + ); // The rule is ONE-SIDED, and this is the half that keeps it useful. Roll // on to C, where the measured cell reads BELOW the held value, and let the @@ -697,20 +848,41 @@ for (const fixture of LAYERS) { const C_LON = -97.7064; // ~144 m further on, still inside the drift bound const atC = Cesium.Cartesian3.fromDegrees(C_LON, LAT, 0); const rollM = Cesium.Cartesian3.distance( - Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(atB, new Cesium.Cartesian3()), - Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(atC, new Cesium.Cartesian3()), + Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface( + atB, + new Cesium.Cartesian3(), + ), + Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface( + atC, + new Cesium.Cartesian3(), + ), + ); + assert.ok( + rollM > 50 && rollM < 250, + `the downhill leg must also sit inside the bound (roll ${rollM.toFixed(1)} m)`, ); - assert.ok(rollM > 50 && rollM < 250, - `the downhill leg must also sit inside the bound (roll ${rollM.toFixed(1)} m)`); reportMeshFloorCell(LAT, C_LON, B_GROUND_M - 50); // measured LOWER than the hold viewer.tileset.tilesLoaded = false; now += 60_000; - ownsVisual = fixture.driveFleetModel({ icao24, position: atC, course: 92 }); - assert.equal(ownsVisual, true, - 'a cell reading BELOW the hold is the floor chain under-reading, not burial — the hold stands'); - assert.equal(model.show, true, 'the contact keeps its model through a downhill taxi'); - assert.ok(Math.abs(placedHeightM() - (B_GROUND_M + fixture.bellyM)) < 0.001, - 'and it keeps standing on the measurement it actually has'); + ownsVisual = fixture.driveFleetModel({ + icao24, + position: atC, + course: 92, + }); + assert.equal( + ownsVisual, + true, + 'a cell reading BELOW the hold is the floor chain under-reading, not burial — the hold stands', + ); + assert.equal( + model.show, + true, + 'the contact keeps its model through a downhill taxi', + ); + assert.ok( + Math.abs(placedHeightM() - (B_GROUND_M + fixture.bellyM)) < 0.001, + 'and it keeps standing on the measurement it actually has', + ); } finally { Date.now = realNow; fixture.layer.stopTracking(); @@ -721,7 +893,7 @@ for (const fixture of LAYERS) { test(`${fixture.name}: grounded tracked model waits for a valid terrain snap with no visual gap`, () => { clearTr3bRegistry(); fixture.layer.stopTracking(); - fixture.layer.setParams({ models3d: false }); + fixture.layer.setParams({ models3d: true }); const realNow = Date.now; let now = 3_000_000; @@ -730,7 +902,10 @@ for (const fixture of LAYERS) { let sampledHeight = undefined; const viewer = viewerAtHeight(30_000, { tilesLoaded: false, - sampleHeight: () => { sampleCalls++; return sampledHeight; }, + sampleHeight: () => { + sampleCalls++; + return sampledHeight; + }, }); const icao24 = fixture.name === 'flights' ? 'a0f001' : 'b0f001'; @@ -745,210 +920,441 @@ for (const fixture of LAYERS) { const model = fixture.trackedModel(); const tracked = modelSet(fixture, viewer, 'tracked'); assert.ok(model, 'the driver records the tracked model'); - assert.deepEqual([...tracked.items.keys()], [icao24], - 'the tracked set loads the one model for the contact'); + assert.deepEqual( + [...tracked.items.keys()], + [icao24], + 'the tracked set loads the one model for the contact', + ); assert.equal(model.ready, false, 'the model is still loading'); - assert.equal(model.show, false, 'the loading model is drawn hidden, not zero-scaled'); + 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()[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 }) - .find((object) => object.sourceId === (fixture.name === 'flights' ? 'a0f001' : 'b0f001')); - assert.ok(loadingDetection, 'the tracked billboard remains detectable while its model loads'); - assert.ok(Cesium.Cartesian3.equalsEpsilon( - loadingDetection.position, - billboard.position, + assert.equal( + fixture.trackedBillboardColor()[3], + 1, + 'the tracked billboard remains opaque while the model lacks safe placement', + ); + assert.equal( + sampleCalls, 0, - 1e-6, - ), 'a hidden tracked model cannot steal the detection anchor'); + 'cold tiles do not force a synchronous sample', + ); + const loadingDetection = fixture.layer + .getDetectableObjects({ maxCount: 50 }) + .find( + (object) => + object.sourceId === + (fixture.name === 'flights' ? 'a0f001' : 'b0f001'), + ); + assert.ok( + loadingDetection, + 'the tracked billboard remains detectable while its model loads', + ); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + loadingDetection.position, + billboard.position, + 0, + 1e-6, + ), + 'a hidden tracked model cannot steal the detection anchor', + ); billboard.show = false; // tracking hides the fleet sprite; the tracked entity remains the 2D owner - const loadingNearby = fixture.layer.getNearby(billboard.position, 1_000, 50) - .find((object) => object.icao24 === (fixture.name === 'flights' ? 'a0f001' : 'b0f001')); - assert.ok(loadingNearby, 'the tracked contact remains in proximity while its model loads'); - assert.ok(Cesium.Cartesian3.equalsEpsilon( - loadingNearby.position, - billboard.position, - 0, - 1e-6, - ), 'a hidden tracked model cannot steal the proximity position'); + const loadingNearby = fixture.layer + .getNearby(billboard.position, 1_000, 50) + .find( + (object) => + object.icao24 === + (fixture.name === 'flights' ? 'a0f001' : 'b0f001'), + ); + assert.ok( + loadingNearby, + 'the tracked contact remains in proximity while its model loads', + ); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + loadingNearby.position, + billboard.position, + 0, + 1e-6, + ), + 'a hidden tracked model cannot steal the proximity position', + ); now += 1000; viewer.tileset.tilesLoaded = true; sampledHeight = 187.5; 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()[3], 1, - 'retry backoff leaves the tracked billboard opaque'); + 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()[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()[3], 1, - 'the billboard retains ownership until GPU readiness too'); + assert.equal( + model.show, + false, + 'terrain alone does not reveal an unready model', + ); + 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'); + assert.equal( + model.scale, + baseScale, + 'its scale is left to the pixel-cap driver', + ); viewer.draw.ready(tracked.spec.id, icao24); fixture.driveTrackedModel(); - assert.equal(model.show, true, 'the model appears only after its snapped matrix is written'); + 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()[3], 0, - 'the billboard becomes transparent only when the model actually owns the visual'); + 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; - assert.ok(Math.abs(placedHeight - (sampledHeight + fixture.bellyM)) < 0.001, - `tracked placement uses the exact ${fixture.bellyM} m asset-measured belly offset`); + assert.ok( + Math.abs(placedHeight - (sampledHeight + fixture.bellyM)) < 0.001, + `tracked placement uses the exact ${fixture.bellyM} m asset-measured belly offset`, + ); viewer.tileset.tilesLoaded = false; sampledHeight = undefined; billboard.position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, -500); fixture.driveTrackedModel(); - assert.equal(model.show, true, - 'a successful cached snap survives a poll-time vertical datum change'); - assert.equal(sampleCalls, 1, - 'a stationary vertical-only change does not consume another terrain sample'); + assert.equal( + model.show, + true, + 'a successful cached snap survives a poll-time vertical datum change', + ); + assert.equal( + sampleCalls, + 1, + 'a stationary vertical-only change does not consume another terrain sample', + ); // Taxi past the resample threshold with the tiles gone: the tracked model // holds its last measured floor rather than handing the operator's own // selection back to a 2D glyph for a retry backoff. billboard.position = Cesium.Cartesian3.fromDegrees(-97.709, 30.21, -500); fixture.driveTrackedModel(); - assert.equal(model.show, true, - 'a taxi-invalidated tracked snap is HELD through the resample outage'); - 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'); + assert.equal( + model.show, + true, + 'a taxi-invalidated tracked snap is HELD through the resample outage', + ); + 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', + ); // Past the drift bound the memory is released and the gate takes over. billboard.position = Cesium.Cartesian3.fromDegrees(-97.707, 30.21, -500); 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()[3], 1, - 'there is no invisible-owner gap while the replacement snap is unavailable'); + assert.equal( + model.show, + false, + 'past HELD_SNAP_MAX_DRIFT_M the hold is released and the model is withheld', + ); + assert.equal( + fixture.trackedBillboardColor()[3], + 1, + 'there is no invisible-owner gap while the replacement snap is unavailable', + ); } finally { Date.now = realNow; fixture.layer.stopTracking(); } }); - test(`${fixture.name}: the tracked contact goes 3D with the fleet 3D toggle OFF`, () => { + test(`${fixture.name}: the tracked contact draws as a model exactly when the fleet would`, () => { clearTr3bRegistry(); - fixture.layer.setParams({ models3d: false }); - assert.equal(fixture.layer.getParams().models3d, false, 'the fleet toggle really is off'); + try { + fixture.layer.setParams({ models3d: true }); + const viewer = viewerAtHeight(30_000); + fixture.seed({ viewer, trackedModelEligible: true }); + assert.equal( + fixture.regimeActive(), + true, + 'a place in the fleet cap: a model', + ); + fixture.seed({ viewer, trackedModelEligible: false }); + assert.equal( + fixture.regimeActive(), + false, + 'no place in the fleet cap: its icon, however close the camera', + ); - // Zoomed out past the ceiling → the billboard still owns the visual. - fixture.seed({ viewer: viewerAtHeight(INSIDE_BAND_M) }); - assert.equal(fixture.regimeActive(), false); - - // Zoom in past the ceiling → the model takes over, toggle untouched. - fixture.seed({ viewer: viewerAtHeight(WELL_INSIDE_M) }); - assert.equal(fixture.regimeActive(), true, - 'zoom-driven 2D↔3D is DEFAULT for the tracked contact'); - assert.equal(fixture.layer.getParams().models3d, false, - 'and it never arms the fleet toggle as a side effect'); + // The fleet's own regime: 3D on and the camera below the ceiling. + fixture.seed({ + viewer: viewerAtHeight(900_000), + trackedModelEligible: true, + }); + assert.equal( + fixture.regimeActive(), + false, + 'above the fleet ceiling: its icon', + ); + fixture.layer.setParams({ models3d: false }); + fixture.seed({ viewer, trackedModelEligible: true }); + assert.equal( + fixture.regimeActive(), + false, + 'with 3D off the fleet draws icons, and so does the selected contact', + ); + } finally { + fixture.layer.setParams({ models3d: false }); + fixture.layer.stopTracking(); + } }); - test(`${fixture.name}: the tracked regime is hysteretic across a live zoom in/out`, () => { + test(`${fixture.name}: selecting a contact keeps the form its fleet visual had`, () => { clearTr3bRegistry(); - fixture.layer.setParams({ models3d: false }); - const viewer = viewerAtHeight(FAR_OUTSIDE_M); - fixture.seed({ viewer }); - assert.equal(fixture.regimeActive(), false, 'starts far out, in 2D'); - - // Zoom in through the boundary. - viewer.camera.positionCartographic.height = TRACKED_MODEL_ENTER_ALT_M - 1; - assert.equal(fixture.regimeActive(), true, '3D at the enter ceiling'); - - // Drift back over the ENTER ceiling — must HOLD (this is the flap guard). - viewer.camera.positionCartographic.height = INSIDE_BAND_M; - assert.equal(fixture.regimeActive(), true, 'the exit band holds the model'); - - // Zoom all the way back out — the billboard returns. - viewer.camera.positionCartographic.height = TRACKED_MODEL_EXIT_ALT_M + 1; - assert.equal(fixture.regimeActive(), false, 'past the exit ceiling, 2D returns'); - - // And a second round trip behaves identically (no stuck latch). - viewer.camera.positionCartographic.height = TRACKED_MODEL_ENTER_ALT_M - 1; - assert.equal(fixture.regimeActive(), true); - viewer.camera.positionCartographic.height = TRACKED_MODEL_EXIT_ALT_M + 1; - assert.equal(fixture.regimeActive(), false); + try { + fixture.layer.setParams({ models3d: true }); + const viewer = viewerAtHeight(30_000); + // A contact the fleet drew as a model stays a model... + fixture.seed({ + viewer, + models: [[ICAO, { ready: true }]], + trackedModelEligible: null, + }); + assert.equal( + fixture.regimeActive(), + true, + 'a fleet model: the tracked model', + ); + // ...and one it drew as an icon stays an icon. + fixture.layer.stopTracking(); + fixture.seed({ viewer, models: [], trackedModelEligible: null }); + assert.equal( + fixture.regimeActive(), + false, + 'a fleet icon: the tracked icon', + ); + } finally { + fixture.layer.setParams({ models3d: false }); + fixture.layer.stopTracking(); + } }); - test(`${fixture.name}: deselect + re-track the SAME contact re-enters at the ENTER ceiling`, () => { - // The regression this pins: a deselect followed by a same-turn re-track of - // the SAME icao (Contacts re-entry, a cross-layer round trip back to this - // layer) never makes `_trackedIcao` observably change, so the predicate's - // icao-change guard never fires. The reset therefore has to live in the - // PRODUCTION teardown — which is why nothing below touches a test-only - // latch reset; the seam re-seeds state but deliberately leaves the latches - // alone, and `stopTracking()` is the real deselect path. + test(`${fixture.name}: the fleet model keeps drawing the selected contact until its tracked model draws`, () => { clearTr3bRegistry(); - fixture.layer.setParams({ models3d: false }); + try { + fixture.layer.setParams({ models3d: true }); + const viewer = viewerAtHeight(30_000); + const position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668); + fixture.seed({ + viewer, + models: [ + [ + ICAO, + { + ready: true, + show: true, + modelMatrix: Cesium.Matrix4.fromTranslation(position), + }, + ], + ], + trackedModelEligible: null, + }); + fixture.driveTrackedModel(); + const tracked = fixture.trackedModel(); + assert.ok(tracked, 'the tracked model loads'); + assert.equal(tracked.ready, false); + assert.ok( + fixture.ensureFleetModel(ICAO), + 'the fleet model is kept while it loads', + ); + assert.equal( + fixture.trackedBillboardColor()[3], + 0, + 'and it is the visual: the tracked icon stays clear, no icon flash', + ); - // Latch the regime on close in... - const viewer = viewerAtHeight(TRACKED_MODEL_ENTER_ALT_M - 1); - fixture.seed({ viewer }); - assert.equal(fixture.regimeActive(), true); - - // ...drift into the hysteresis band, where the model legitimately holds. - viewer.camera.positionCartographic.height = INSIDE_BAND_M; - assert.equal(fixture.regimeActive(), true, 'the ORIGINAL selection still holds in the band'); - - // Deselect through the production path, then re-track the SAME contact. - fixture.layer.stopTracking(); - fixture.seed({ viewer }); // same icao, still inside the band - assert.equal(fixture.regimeActive(), false, - 'a re-tracked contact must pass the ENTER ceiling again, not inherit the exit band'); - - // And it still enters normally once actually zoomed in. - viewer.camera.positionCartographic.height = TRACKED_MODEL_ENTER_ALT_M - 1; - assert.equal(fixture.regimeActive(), true); - fixture.layer.stopTracking(); + viewer.draw.ready(modelSet(fixture, viewer, 'tracked').spec.id, ICAO); + fixture.driveTrackedModel(); + assert.equal( + fixture.ensureFleetModel(ICAO), + null, + 'once the tracked model draws, the fleet model lets go', + ); + assert.equal( + fixture.trackedBillboardColor()[3], + 0, + 'the tracked model is the visual', + ); + } finally { + fixture.layer.setParams({ models3d: false }); + fixture.layer.stopTracking(); + } }); - test(`${fixture.name}: a converted TR-3B never takes the model, at any zoom`, () => { + test(`${fixture.name}: the tracked model draws at the fleet's scale and minimum pixel size, even up close`, () => { clearTr3bRegistry(); - fixture.layer.setParams({ models3d: false }); - const viewer = viewerAtHeight(1); // as zoomed in as it gets - fixture.seed({ viewer }); - assert.equal(fixture.regimeActive(), true, 'control: an unconverted contact does model'); + try { + fixture.layer.setParams({ models3d: true }); + const position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668); + // The eye 120 m off the aircraft: the old tracked pixel cap shrank it here. + const viewer = viewerAtHeight(30_000, { + eye: Cesium.Cartesian3.fromDegrees(-97.71, 30.211, 10_668), + }); + const icao24 = fixture.name === 'flights' ? 'a0f501' : 'b0f501'; - setTr3b(ICAO, true); - fixture.seed({ viewer }); - assert.equal(fixture.regimeActive(), false, - 'there is no TR-3B GLB — the triangle billboard stays the visual all the way in'); + // The fleet's model of the contact, unselected. + fixture.seed({ viewer, tracked: false, icao24 }); + const fleetRecord = fixture.ensureFleetModel(icao24); + fixture.driveFleetModel({ icao24, position }); + const fleetSet = modelSet(fixture, viewer, 'fleet'); + viewer.draw.ready(fleetSet.spec.id, icao24); + fixture.driveFleetModel({ icao24, position }); + const fleetItem = fleetSet.items.get(icao24); + assert.ok(fleetRecord && fleetItem); - setTr3b(ICAO, false); - fixture.seed({ viewer }); - assert.equal(fixture.regimeActive(), true, 'un-converting restores the handoff'); - clearTr3bRegistry(); + // The same contact selected. + fixture.seed({ viewer, icao24 }); + fixture.driveTrackedModel(); + const trackedSet = modelSet(fixture, viewer, 'tracked'); + viewer.draw.ready(trackedSet.spec.id, icao24); + fixture.driveTrackedModel(); + const trackedItem = trackedSet.items.get(icao24); + assert.equal(fixture.trackedModel().ready, true); + assert.equal(trackedItem.show, true); + assert.equal(trackedItem.url, fleetItem.url, 'the same model'); + assert.equal(trackedItem.scale, fleetItem.scale, 'the same scale'); + assert.equal( + trackedItem.minPixelSize, + fleetItem.minPixelSize, + 'the same minimum pixel size', + ); + assert.notDeepEqual( + trackedItem.tint, + fleetItem.tint, + 'only the colour differs', + ); + } finally { + fixture.layer.setParams({ models3d: false }); + fixture.layer.stopTracking(); + } }); - test(`${fixture.name}: deselecting drops the regime even zoomed all the way in`, () => { + test(`${fixture.name}: the tracked icon is drawn as its fleet icon is`, () => { clearTr3bRegistry(); - fixture.layer.setParams({ models3d: false }); - const viewer = viewerAtHeight(1); - fixture.seed({ viewer }); - assert.equal(fixture.regimeActive(), true); - - fixture.seed({ viewer, tracked: false }); // nothing selected - assert.equal(fixture.regimeActive(), false, - 'with no selection there is no tracked model to own the visual'); + try { + const viewer = viewerAtHeight(30_000); + fixture.seed({ viewer }); + const { tracked, fleet } = fixture.trackedIconLook(ICAO); + assert.equal(tracked.image, fleet.image, 'the same glyph'); + assert.deepEqual( + tracked.imageLod, + fleet.imageLod, + 'the same close-up glyph', + ); + assert.deepEqual( + [tracked.sprite.width, tracked.sprite.height], + fleet.size, + 'the same size', + ); + assert.equal(tracked.sprite.scale, fleet.scale, 'the same scale'); + assert.deepEqual( + tracked.sprite.scaleByDistance, + fleet.scaleByDistance, + 'the same scale by distance', + ); + // A landing changes the fleet icon's scale, and the tracked one's with it. + fixture.seed({ viewer, onGround: true }); + const grounded = fixture.trackedIconLook(ICAO); + assert.notEqual(grounded.fleet.scale, fleet.scale); + assert.equal(grounded.tracked.sprite.scale, grounded.fleet.scale); + } finally { + fixture.layer.stopTracking(); + } }); - test(`${fixture.name}: turning the fleet toggle ON does not disturb the tracked regime`, () => { + test(`${fixture.name}: a converted TR-3B never takes the model`, () => { clearTr3bRegistry(); - const viewer = viewerAtHeight(WELL_INSIDE_M); - fixture.seed({ viewer }); - fixture.layer.setParams({ models3d: true }); - assert.equal(fixture.regimeActive(), true); - fixture.layer.setParams({ models3d: false }); - assert.equal(fixture.regimeActive(), true, - 'the fleet toggle owns the FLEET; the selected contact is independent of it'); + try { + fixture.layer.setParams({ models3d: true }); + const viewer = viewerAtHeight(1); // as zoomed in as it gets + fixture.seed({ viewer }); + assert.equal( + fixture.regimeActive(), + true, + 'control: an unconverted contact does model', + ); + + setTr3b(ICAO, true); + fixture.seed({ viewer }); + assert.equal( + fixture.regimeActive(), + false, + 'there is no TR-3B GLB — the triangle billboard stays the visual all the way in', + ); + + setTr3b(ICAO, false); + fixture.seed({ viewer }); + assert.equal( + fixture.regimeActive(), + true, + 'un-converting restores the handoff', + ); + } finally { + clearTr3bRegistry(); + fixture.layer.setParams({ models3d: false }); + fixture.layer.stopTracking(); + } + }); + + test(`${fixture.name}: deselecting drops the tracked model`, () => { + clearTr3bRegistry(); + try { + fixture.layer.setParams({ models3d: true }); + const viewer = viewerAtHeight(1); + fixture.seed({ viewer }); + assert.equal(fixture.regimeActive(), true); + + fixture.seed({ viewer, tracked: false }); // nothing selected + assert.equal( + fixture.regimeActive(), + false, + 'with no selection there is no tracked model to own the visual', + ); + } finally { + fixture.layer.setParams({ models3d: false }); + fixture.layer.stopTracking(); + } }); } @@ -956,25 +1362,44 @@ test('both layers reset the per-selection tracked-model state', async () => { for (const name of ['flights.js', 'militaryFlights.js']) { const source = readLayerSource(new URL(`./${name}`, import.meta.url)); // The reset must be reachable from the real teardown, not only a test seam. - assert.match(source, /(?:parts\.\w+\.)?_releaseTrackedModel\(\s*,?\s*\);\n\s*(?:parts\.\w+\.)?_resetTrackedSelectionState\(\s*,?\s*\);/, - `${name}: deselect clears the per-selection latches in the production path`); - assert.match(source, /(?:(?:flightState|state)\.)?_trackedIcao\s*=\s*icao24;\n\s*(?:parts\.\w+\.)?_resetTrackedSelectionState\(\s*,?\s*\);/, - `${name}: selecting a contact starts from a clean per-selection state`); + assert.match( + source, + /(?:parts\.\w+\.)?_releaseTrackedModel\(\s*,?\s*\);\n\s*(?:parts\.\w+\.)?_resetTrackedSelectionState\(\s*,?\s*\);/, + `${name}: deselect clears the per-selection state in the production path`, + ); + assert.match( + source, + /(?:(?:flightState|state)\.)?_trackedIcao\s*=\s*icao24;\n\s*(?:parts\.\w+\.)?_resetTrackedSelectionState\(\s*,?\s*\);/, + `${name}: selecting a contact starts from a clean per-selection state`, + ); } }); -test('the tracked regime never consults the fleet models3d toggle', async () => { +test('the tracked model follows the fleet model rule, and the fleet the 3D toggle', async () => { for (const name of ['flights.js', 'militaryFlights.js']) { const source = readLayerSource(new URL(`./${name}`, import.meta.url)); - const regime = /^([ \t]*)function _trackedModelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; + const regime = + /^([ \t]*)function _trackedModelRegimeActive\b[\s\S]*?\n\1\}/m.exec( + source, + )?.[0]; assert.ok(regime, `${name}: _trackedModelRegimeActive is defined`); - assert.doesNotMatch(regime, /(?:(?:flightState|state)\.)?_models3dEnabled|(?:parts\.\w+\.)?_modelRegimeActive\(\s*,?\s*\)/, - `${name}: the tracked contact's handoff is default-on, not gated on the fleet toggle`); - assert.match(regime, /trackedModelZoomActive\(/, - `${name}: the tracked contact uses the shared hysteretic zoom policy`); - // The FLEET must still obey the toggle — the budget decision stays the operator's. - const fleet = /^([ \t]*)function _modelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; - assert.match(fleet, /if\s*\(\s*!(?:(?:flightState|state)\.)?_models3dEnabled,?\s*\)\s*return\s*false;/, - `${name}: the fleet regime still obeys the DISPLAY-rail 3D toggle`); + assert.match( + regime, + /_trackedModelEligible === true/, + `${name}: the tracked contact takes its place in the fleet cap`, + ); + assert.match( + regime, + /(?:parts\.\w+\.)?_modelRegimeActive\(\s*\)/, + `${name}: and the fleet's regime`, + ); + const fleet = /^([ \t]*)function _modelRegimeActive\b[\s\S]*?\n\1\}/m.exec( + source, + )?.[0]; + assert.match( + fleet, + /if\s*\(\s*!(?:(?:flightState|state)\.)?_models3dEnabled,?\s*\)\s*return\s*false;/, + `${name}: the fleet regime still obeys the DISPLAY-rail 3D toggle`, + ); } }); diff --git a/src/data/trackedModelRegime.js b/src/data/trackedModelRegime.js deleted file mode 100644 index 3fc58cf5e..000000000 --- a/src/data/trackedModelRegime.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Zoom-driven 2D↔3D policy for the TRACKED contact (both flight layers). - * - * The fleet's 3D models stay behind the DISPLAY-rail "3D" toggle (`models3d`) - * — hundreds of GLBs are a draw-call budget decision the operator owns. Since - * 2026-08-22 that toggle DEFAULTS ON in `proximity` (owner directive), so the - * fleet is armed on a fresh boot; proximity is itself the budget, admitting only - * the nearest MODEL_MAX in view below the fleet ceiling. The contact you have - * SELECTED is still a separate case: it is exactly one model, it is what the - * camera is pointed at, and the operator's expectation is that zooming in on a - * target resolves it into an aircraft. So the tracked contact's handoff is - * DEFAULT behaviour, driven purely by camera distance and never consulting the - * toggle at all (owner directive, 2026-08-19). - * - * Threshold history — the tracked contact used to inherit the fleet ceiling - * `MODEL_ALT_CEIL_M = 800_000` m, and a first pass raised it to 1_000_000 m to - * make the airframe arrive sooner. Owner playtest 2026-08-20 rejected that: the - * model "pops to 3D far too early" — a 26 m airframe held at its minimum pixel - * size from ~1 Mm out reads as a floating toy, not an aircraft. The ruling is a - * MUCH closer swap: 2D is correct at ~600_000 m, and the handoff belongs at - * ~150_000 m. That is the constant below. - * - * NOTE — the tracked contact now enters 3D *later* (nearer) than the FLEET does. - * Cruise altitudes between 150_000 m and the fleet's 800_000 m ceiling draw the - * surrounding contacts as models while the SELECTED one is still a billboard - * (the fleet pass skips the tracked icao, so nothing double-draws — it is purely - * an ordering difference). As of the 2026-08-22 default flip this is what an - * operator sees WITHOUT arming anything, where before it needed the toggle on; - * the inversion itself is unchanged and is still a consequence of the owner's - * number, not an accident. It is pinned in trackedModelRegime.test.mjs so a - * later "cleanup" cannot erase it without reading this note. Aligning the two is - * a fleet-side decision and is explicitly out of scope here (fleet-wide auto-3D - * is a separate post-launch change). - * - * HYSTERESIS — the enter and exit thresholds are deliberately asymmetric. A - * single threshold makes an orbit AT the boundary flap billboard↔model every - * time the camera's altitude wobbles across it (the tracked orbit is a real - * camera motion, not a static pose), which is the same flicker the fleet's - * ADD/KEEP radii exist to prevent. Once the model owns the visual it keeps it - * until the camera climbs 15% past the enter ceiling. - * - * Pure functions + constants so the policy is unit-testable without a viewer; - * the layers own the latch (one per selection) and the Cesium plumbing. - */ - -/** The FLEET's ceiling (`MODEL_ALT_CEIL_M` in both layers), duplicated here only - * so the relationship in the note above is assertable. The fleet's own constant - * is unchanged and remains the single source for fleet behaviour. */ -export const FLEET_MODEL_ALT_CEIL_M = 800_000; - -/** Camera altitude (m) at or below which the TRACKED contact takes its 3D model. - * Owner playtest ruling 2026-08-20: 2D still reads correctly at ~600_000 m, and - * the swap belongs at ~150_000 m. */ -export const TRACKED_MODEL_ENTER_ALT_M = 150_000; - -/** Exit is 15% looser than enter — the anti-flap band for a boundary orbit. */ -export const TRACKED_MODEL_EXIT_RATIO = 1.15; - -/** Camera altitude (m) the camera must climb past before the model hands back to the billboard. */ -export const TRACKED_MODEL_EXIT_ALT_M = - TRACKED_MODEL_ENTER_ALT_M * TRACKED_MODEL_EXIT_RATIO; // 172_500 - -/** - * Whether the tracked contact's 3D model owns the visual at this camera altitude. - * - * Hysteretic: the caller feeds back the previous answer, and that selects which - * threshold applies. Inside the band [enter, exit) the answer is simply "whatever - * it already was", so a camera loitering on the boundary never toggles. - * - * A non-finite height (no viewer yet, camera not positioned) reads as "infinitely - * far out" → inactive, matching the `?? Infinity` the layers used before. - * - * @param {number} cameraHeightM - Camera altitude above the ellipsoid, in metres. - * @param {boolean} [wasActive=false] - The regime's answer on the previous evaluation. - * @returns {boolean} True when the tracked 3D model should own the visual. - */ -export function trackedModelZoomActive(cameraHeightM, wasActive = false) { - if (!Number.isFinite(cameraHeightM)) return false; - return ( - cameraHeightM < - (wasActive ? TRACKED_MODEL_EXIT_ALT_M : TRACKED_MODEL_ENTER_ALT_M) - ); -} diff --git a/src/data/trackingClickGesture.test.mjs b/src/data/trackingClickGesture.test.mjs index f148ee8d9..51ee0074c 100644 --- a/src/data/trackingClickGesture.test.mjs +++ b/src/data/trackingClickGesture.test.mjs @@ -6,8 +6,6 @@ import { isTrackingSelectionGesture, } from './trackingClickGesture.js'; import { FAKE_EVENT_TYPES as TYPES, fakeInput } from '../input/testDoubles.mjs'; -import { TRACKED_MODEL_MAX_PX as CIVIL_TRACKED_MODEL_MAX_PX } from './flights.js'; -import { TRACKED_MODEL_MAX_PX as MILITARY_TRACKED_MODEL_MAX_PX } from './militaryFlights.js'; /** A dispatcher on a fake handler, with `onClick(click, gesture)` as the layers read it. */ function gestureInput(now, onClick) { @@ -111,7 +109,20 @@ test('civilian and military click handlers apply duration only at the deselect b ); }); -test('civilian and military tracked model caps both expose the owner-selected 200 px feel', () => { - assert.equal(CIVIL_TRACKED_MODEL_MAX_PX, 200); - assert.equal(MILITARY_TRACKED_MODEL_MAX_PX, 200); +test('a click on an aircraft follows it keeping the camera’s view; other selections frame it', () => { + const sources = [ + readLayerSource(new URL('./flights.js', import.meta.url)), + readLayerSource(new URL('./militaryFlights.js', import.meta.url)), + ]; + for (const source of sources) { + assert.match( + source, + /_trackFlight\(pickedIcao, \{ origin: 'user', keepView: true \}\)/, + ); + assert.match( + source, + /keepView\s*\?\s*keptViewFrom\(camera\.pose\(\), getTrackedPosition\(\)\)/, + ); + assert.match(source, /transitionS: SELECTION_FOLLOW_TRANSITION_S/); + } }); diff --git a/src/data/transitIcons.js b/src/data/transitIcons.js index c6ad963e1..453414a6c 100644 --- a/src/data/transitIcons.js +++ b/src/data/transitIcons.js @@ -170,7 +170,10 @@ const _b64 = (s) => * little minification. */ const FLEET_RASTER_PX = 48; -/** The selected vehicle draws bigger and deserves a crisper source. */ +/** + * Source size for the selected vehicle: drawn at the fleet's size, from a + * crisper raster under its wider halo. + */ export const SELECTED_ICON_PX = 96; /** @@ -240,7 +243,8 @@ export function transitIcon(kind, px = FLEET_RASTER_PX, options = {}) { ); const style = profile === 'mono' ? 'thermal' : profile === 'crt' ? 'retro' : 'normal'; - const displayPx = (selected ? 30 : 20) * presetSpriteScale(style, selected); + // Selected or not, the glyph is drawn at the fleet's size. + const displayPx = FLEET_SCREEN_PX * presetSpriteScale(style, selected); const frame = haloFrame(presetSpriteOutlinePx(style, selected), displayPx); const heading = options.heading !== false; const bodies = heading ? HEADING_BODIES : NEUTRAL_BODIES; diff --git a/src/data/transitIcons.test.mjs b/src/data/transitIcons.test.mjs index 758b1d04b..a23b6bf56 100644 --- a/src/data/transitIcons.test.mjs +++ b/src/data/transitIcons.test.mjs @@ -69,8 +69,7 @@ test('all 72 variants retain the specified final halo at both display sizes', as for (const selected of [false, true]) { for (const style of ['normal', 'thermal', 'retro']) for (const heading of [true, false]) { - const display = - (selected ? 30 : 20) * presetSpriteScale(style, selected); + const display = 20 * presetSpriteScale(style, selected); const svg = decode( transitIcon(kind, selected ? 96 : 48, { style, heading }), ); @@ -157,10 +156,8 @@ test('every mono raster preserves the normal silhouette mask and aspect at CRT d Math.abs(mono.aspect / normal.aspect - 1) <= 0.05, `${kind}/${style}: aspect`, ); - const display = - (selected ? 30 : 20) * presetSpriteScale(style, selected); - const crt = - (selected ? 30 : 20) * presetSpriteScale('retro', selected); + const display = 20 * presetSpriteScale(style, selected); + const crt = 20 * presetSpriteScale('retro', selected); assert.equal(display, crt); const frame = haloFrame( presetSpriteOutlinePx(style, selected), @@ -202,8 +199,7 @@ test('sensor raster halo stays dark across its screen-space band on a white roof for (const selected of [false, true]) { const pixels = []; for (const kind of TRANSIT_ICON_KINDS) { - const display = - (selected ? 30 : 20) * presetSpriteScale('thermal', selected); + const display = 20 * presetSpriteScale('thermal', selected); const frame = haloFrame( presetSpriteOutlinePx('thermal', selected), display, diff --git a/src/layers/aircraft/index.js b/src/layers/aircraft/index.js index e5f048164..ae3ca0c34 100644 --- a/src/layers/aircraft/index.js +++ b/src/layers/aircraft/index.js @@ -14,5 +14,4 @@ export * from '../../data/modelVisualAnchor.js'; export * from '../../data/motionModel.js'; export * from '../../data/renderAltitude.js'; export * from '../../data/routePlausible.js'; -export * from '../../data/trackedModelRegime.js'; export * from '../../data/trackingClickGesture.js'; diff --git a/src/layers/flights/index.js b/src/layers/flights/index.js index a2af78193..49bf09770 100644 --- a/src/layers/flights/index.js +++ b/src/layers/flights/index.js @@ -85,4 +85,3 @@ export function createCivilFlightLayer({ Object.defineProperty(layer, 'testing', { value: parts.testing }); return layer; } -export { TRACKED_MODEL_MAX_PX } from './policy.js'; diff --git a/src/layers/flights/lifecycle.js b/src/layers/flights/lifecycle.js index 6d0ab107d..9e7aaf9f3 100644 --- a/src/layers/flights/lifecycle.js +++ b/src/layers/flights/lifecycle.js @@ -273,7 +273,7 @@ export function createLifecycle({ source: flightState.feed._lastSource, coverage: flightState.feed._lastCoverage, }; - parts.tracking._resetTrackedSelectionState(); // next lifecycle re-evaluates against the ENTER ceiling + parts.tracking._resetTrackedSelectionState(); // the next lifecycle starts a fresh selection flightState._viewer = null; }, }; diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index 9e3924a62..9d8264fda 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -41,8 +41,7 @@ import { } from '../../data/modelVisualAnchor.js'; import { FOCUS_EVIDENCE_DEV, - TRACKED_MODEL_MAX_PX, - TRACKED_MODEL_MIN_PX, + MODEL_MIN_PX, TRACKED_BILLBOARD_SCALE_BY_DISTANCE, DR_CORRECTION_MS, COURSE_SLEW_DT_MAX_SEC, @@ -113,7 +112,6 @@ export function createMotion({ corridorFloorCells, allocateCorridorCells, } = services.groundFloor; - const { trackedModelScaleForPixelCap } = services.camera; const { nearFarScalarValueAtDistance, clearFocusTarget, @@ -375,21 +373,11 @@ export function createMotion({ const spec = parts.rendering._modelSpec( flightState.records.data.get(icao24), ); - const scale = trackedModelScaleForPixelCap({ - baseScale: spec.scale, - nativeRadiusM: spec.nativeRadiusM, - rangeM, - viewportHeightPx, - fovyRad: pose.fovy, - maximumPixelSize: TRACKED_MODEL_MAX_PX, - }); + // Drawn as the fleet draws it: its own size, never under MODEL_MIN_PX. const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2)); const projectedDiameterPx = - (2 * spec.nativeRadiusM * scale * focalLengthPx) / rangeM; - return Math.max( - TRACKED_MODEL_MIN_PX, - Math.min(TRACKED_MODEL_MAX_PX, projectedDiameterPx), - ); + (2 * spec.nativeRadiusM * spec.scale * focalLengthPx) / rangeM; + return Math.max(MODEL_MIN_PX, projectedDiameterPx); } const sprite = readEntityRecord(flightState._trackedEntity)?.sprite; diff --git a/src/layers/flights/policy.js b/src/layers/flights/policy.js index 74d476487..b098067bf 100644 --- a/src/layers/flights/policy.js +++ b/src/layers/flights/policy.js @@ -52,12 +52,6 @@ export const MODEL_MIN_PX = 24; // min-pixel blob (was 54 — far planes at the All radius became white // star-bursts); ~matches the 2D icon size so the model↔billboard read is consistent -export const TRACKED_MODEL_MIN_PX = 40; -// keep the glTF silhouette comparable to the selected 2D glyph at handoff - -export const TRACKED_MODEL_MAX_PX = 200; -// owner-selected close-range tracked-target feel - // Per-mode caps. Each model is its own draw call (no instancing yet), so these bound the frame cost. export const MODEL_MAX = 150; diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index 0f9a59a9f..0c21f5fc4 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -317,8 +317,8 @@ export function createQueries({ * Live layer params. * `models3d` toggles 3D glTF model rendering for the FLEET (altitude-gated): when on, * surrounding aircraft become 3D models once the camera is zoomed in past MODEL_ALT_CEIL_M. - * The TRACKED contact is NOT gated by this — it takes its 3D model by camera distance - * regardless (see `_trackedModelRegimeActive` / trackedModelRegime.js). + * The TRACKED contact follows the same rule (`_trackedModelRegimeActive`), so selecting + * a contact never turns its icon into a model or its model into an icon. * `models3dMode` is 'proximity' (nearest MODEL_MAX in view) or 'all' (every in-view plane). * @param {{models3d?: boolean, models3dMode?: 'proximity'|'all', selectedFlightsTrackingId?: string|null}} params */ diff --git a/src/layers/flights/state.js b/src/layers/flights/state.js index 202e404a6..d803ca2fb 100644 --- a/src/layers/flights/state.js +++ b/src/layers/flights/state.js @@ -358,13 +358,13 @@ export function createFlightState({ source, services }) { 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 - * ceiling instead of inheriting the previous target's looser EXIT band. */ + /** Whether the fleet's model rule (3D on, below the ceiling, inside the + * nearest-first cap) gives the tracked contact a model: the tracked model + * draws only then, so selecting a contact never changes its form. Seeded + * from the contact's fleet model when it is selected, then kept by the + * fleet pass. */ - flightState._trackedZoomLatched = false; - - flightState._trackedZoomLatchIcao = null; + flightState._trackedModelEligible = false; /** The tracked-model load-failure budget: the selection it counts for, * its failures, and when it may load again (`TRACKED_MODEL_*`). */ diff --git a/src/layers/flights/testing.js b/src/layers/flights/testing.js index d903548b6..bf2362a52 100644 --- a/src/layers/flights/testing.js +++ b/src/layers/flights/testing.js @@ -99,6 +99,7 @@ export function createTesting({ tracked = true, models = [], draw = null, + trackedModelEligible = true, }) { flightState._viewer = viewer; parts.rendering._disposeModelSets(); @@ -120,11 +121,17 @@ export function createTesting({ flightState._trackedIcao = tracked ? icao24 : null; flightState._trackedEntity = tracked ? entity : null; flightState._trackedModel = null; + // Whether the fleet's model rule gives the tracked contact a model (the + // fleet pass keeps it): a model unless the test says otherwise. + flightState._trackedModelEligible = tracked && trackedModelEligible; + // `null`: as a selection seeds it (from the contact's fleet model). + if (trackedModelEligible === null) + parts.tracking._resetTrackedSelectionState(); parts.tracking._cancelPendingTrackingRestore(); - // NOTE: deliberately does NOT reset the per-selection latches. They are - // production state owned by the tracking lifecycle (_resetTrackedSelectionState), - // and clearing them here would mask exactly the deselect→re-track hole this - // seam is used to test. + // NOTE: deliberately does NOT reset the load-failure budget. It is + // production state owned by the tracking lifecycle + // (_resetTrackedSelectionState), and clearing it here would mask exactly + // the deselect→re-track hole this seam is used to test. flightState.feed._backoff = false; flightState.feed._retryAt = 0; } @@ -193,9 +200,8 @@ export function createTesting({ parts.tracking._applyCockpitState({ active, subjectId }); } - /** Evaluate the TRACKED contact's zoom regime through the production predicate. - * The decision is latch-bearing (default-on, hysteretic, cockpit/TR-3B-suppressed) - * and otherwise only observable through a live scene, so tests drive it here. */ + /** Evaluate whether the TRACKED contact draws as its model, through the + * production predicate (the fleet's rule; cockpit/TR-3B-suppressed). */ function _trackedModelRegimeActiveForTest() { return parts.tracking._trackedModelRegimeActive(); @@ -247,6 +253,19 @@ export function createTesting({ return flightState._models.get(icao24) ?? null; } + /** How the tracked billboard is drawn (`_trackedBillboardLook`, + * `_trackedSprite`) next to how the contact's fleet icon is (`_fleetLook`). */ + + function _trackedIconLookForTest(icao24) { + return { + tracked: { + ...parts.tracking._trackedBillboardLook(), + sprite: parts.tracking._trackedSprite(icao24), + }, + fleet: parts.icons._fleetLook(icao24), + }; + } + /** The tracked model's record, or null. */ function _trackedModelForTest() { @@ -289,6 +308,7 @@ export function createTesting({ _iconForTest, _ensureFleetModelForTest, _trackedModelForTest, + _trackedIconLookForTest, _modelSetIdsForTest, _resetEnrichmentForTest, }; diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index 02bc8fa0c..ecab8655b 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -7,7 +7,6 @@ import { import { formatNumber, t } from '../../i18n/index.js'; import { unitLabel } from '../../ui/unitLabels.js'; import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js'; -import { trackedModelZoomActive } from '../../data/trackedModelRegime.js'; import { courseScreenRotation, stabilizeScreenRotation, @@ -22,9 +21,7 @@ import { julianToEpochMs } from '../../geo/julian.js'; import { renderedFrames } from '../../data/renderedFrames.js'; import { clone, distance, distanceSquared, vec } from '../../geo/vector.js'; import { trailHeadStart } from '../../data/modelVisualAnchor.js'; -import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js'; import { routePlausible } from '../../data/routePlausible.js'; -import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { isTrackingSelectionGesture, isTrackingClickGesture, @@ -36,7 +33,6 @@ import { TRAIL_COLOR, CYAN_TRANSPARENT, TRACKED_CYAN, - TRACKED_BILLBOARD_SCALE_BY_DISTANCE, STALE_ALPHA, displayDelayMs, followsClock, @@ -93,7 +89,8 @@ export function createTracking({ const { clearFocusTarget } = services.focus; const { isMilitaryLayerActive, isMilitaryIcao } = services.militaryRegistry; const { trackedLabelModelFromText, refreshTrackedReadout } = services.readout; - const { FOLLOW_MIN_RANGE_M } = services.camera; + const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, keptViewFrom } = + services.camera; const { resolvePickId, isOwnedByOtherLayer } = services.picking; const flightsLayer = layer; /** The tracked contact's billboard (an icon set on the draw port). */ @@ -272,67 +269,42 @@ export function createTracking({ _setCockpitContactMode(active); } - /** Clear the per-SELECTION tracked-model latches: the zoom hysteresis band - * and the load-failure budget. - * Called from each path that changes which contact is - * selected — deselect, re-track, cross-layer handoff, init, destroy. - * - * This must live in the production lifecycle, not only in the predicate's - * icao-change guard: a deselect followed by a same-turn re-track of the SAME - * icao (Contacts re-entry, a cross-layer round trip back to the original - * layer) never makes `_trackedIcao` *observably* change, so the guard never - * fires. Without the reset, a contact dropped inside the hysteresis band comes - * back as a MODEL above the ENTER ceiling. */ + /** Start a selection's tracked-model state afresh: the model it draws + * with (whatever the fleet drew it with, a model or its icon) and the + * load-failure budget. Called from each path that changes which contact + * is selected — deselect, re-track, cross-layer handoff, init, destroy. */ function _resetTrackedSelectionState() { - flightState._trackedZoomLatched = false; - flightState._trackedZoomLatchIcao = null; + flightState._trackedModelEligible = Boolean( + flightState._trackedIcao && + flightState._models?.has(flightState._trackedIcao), + ); flightState._trackedModelFailIcao = null; flightState._trackedModelFailCount = 0; flightState._trackedModelRetryAtMs = 0; } /** - * The TRACKED aircraft's own model regime — DEFAULT-ON, camera-distance driven - * (owner directive 2026-08-19). Unlike the fleet, this does NOT consult the - * DISPLAY-rail `models3d` toggle: the selected contact is a single model, it is - * what the camera is pointed at, and zooming in on a target should resolve it - * into an aircraft without the operator arming anything. The toggle keeps - * owning the FLEET (`_modelRegimeActive`), which is the draw-call budget. - * - * Thresholds + hysteresis live in trackedModelRegime.js: enter at - * TRACKED_MODEL_ENTER_ALT_M (150_000 m — the owner's playtested swap distance, - * deliberately NEARER than the fleet's 800 km ceiling this used to inherit), - * hand back only above TRACKED_MODEL_EXIT_ALT_M, so orbiting AT the boundary - * cannot flap billboard↔model. See that module's header for why the tracked - * contact now goes 3D closer in than the fleet does. - * - * In cockpit you are sitting 7 m behind and 2.6 m above your own aircraft's - * origin, so its ~26 m airframe would fill the visor. First-person means your - * own airframe is not drawn. + * Whether the TRACKED aircraft draws as its 3D model: exactly when the + * fleet's own rule would draw it so (`_modelRegimeActive` — 3D on and the + * camera below the ceiling — and a place in the nearest-first cap, which + * the fleet pass keeps in `_trackedModelEligible`). Selecting a contact + * therefore never turns its icon into a model or its model into an icon. + * A converted TR-3B has no 3D asset, and in cockpit you sit in your own + * airframe, so neither draws one. */ function _trackedModelRegimeActive() { - if (flightState._trackedZoomLatchIcao !== flightState._trackedIcao) { - flightState._trackedZoomLatchIcao = flightState._trackedIcao; - flightState._trackedZoomLatched = false; - } - // A converted TR-3B has no 3D asset — suppressing the regime keeps its - // tracked billboard fully opaque (the colour callback reads this too), so - // the triangle stays the visual all the way in. if ( !flightState._trackedIcao || flightState._cockpitContactMode || isTr3b(flightState._trackedIcao) - ) { - flightState._trackedZoomLatched = false; + ) return false; - } - flightState._trackedZoomLatched = trackedModelZoomActive( - _pose()?.height, - flightState._trackedZoomLatched, + return ( + flightState._trackedModelEligible === true && + parts.rendering._modelRegimeActive() ); - return flightState._trackedZoomLatched; } /** Seed the tracked billboard's 2D orientation before a 3D→2D handoff. */ @@ -967,22 +939,40 @@ export function createTracking({ refreshTrackedSubjectContext(_contextSubjectMetadata(icao24)); } - /** 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, - ), - TRACKED_ICON_PX, - ); + /** The tracked billboard's images, from the current class/conversion: the + * fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */ + function _trackedBillboardLook() { + return parts.icons._fleetLook(flightState._trackedIcao); + } + + /** + * What the tracked billboard is drawn at: the size, scale and scale by + * distance its fleet icon has (the scale read live: a landing changes it). + * Kept in its entity record too, so the camera guard and screen + * annotations size it from the app's own state. + * @param {string} icao24 + */ + function _trackedSprite(icao24) { + const look = parts.icons._fleetLook(icao24); + return { + width: look.size[0], + height: look.size[1], + get scale() { + return parts.rendering._fleetBillboardScale( + icao24, + flightState.records.data.get(icao24)?.klass, + ); + }, + scaleByDistance: look.scaleByDistance, + }; } /** Re-image the tracked billboard from the current class/conversion. */ function _syncTrackedBillboardImage() { if (!flightState._trackedIcao || !flightState._trackedEntity) return; - trackedIcon.setImage(_trackedBillboardImage()); + const look = _trackedBillboardLook(); + trackedIcon.setImage(look.image, look.imageLod); } /** @@ -1059,9 +1049,15 @@ export function createTracking({ * camera follows a target that reads it. * * @param {string} icao24 - ICAO 24-bit transponder address to track. + * @param {{origin?: string, keepView?: boolean}} [options] `keepView` (a + * click on the plane): follow from the camera's own distance and angle, + * the plane sliding to the centre, rather than the calibrated framing. */ - function _trackFlight(icao24, { origin = 'programmatic' } = {}) { + function _trackFlight( + icao24, + { origin = 'programmatic', keepView = false } = {}, + ) { _clearTracking(false, { origin }); // switching planes — the new follow-camera takes over const icons = flightState._icons; @@ -1079,10 +1075,9 @@ export function createTracking({ flightState._cachedDRFrame = -1; flightState._lastTrackedRotation = 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. - parts.rendering._releaseModel(icao24); + // A fleet 3D model this aircraft had keeps drawing it until the tracked + // model is ready (`_updateTrackedModel` lets it go then), so it never + // turns into its icon for the frames the tracked model takes to load. // Hide the icon — the tracked entity replaces it visually icons.setShown(icao24, false); @@ -1106,17 +1101,7 @@ export function createTracking({ // 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, - height: 28, - scale: - CLASS_SCALE_2D[ - flightState.records.data.get(flightState._trackedIcao)?.klass - ] || 1, - scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE, - }; + const sprite = _trackedSprite(icao24); // 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( @@ -1135,7 +1120,8 @@ export function createTracking({ }; trackedIcon.show({ id: icao24, - image: _trackedBillboardImage(), + image: _trackedBillboardLook().image, + imageLod: _trackedBillboardLook().imageLod, sprite, position: getTrackedPosition, // Solid cyan (faded while stale) when the billboard is the visual (zoomed out, 3D off, @@ -1172,9 +1158,11 @@ export function createTracking({ entityRecord(flightState._trackedEntity).labelModel = trackedLabelModelFromText(_trackedLabelText(icao24), '#39d0ff'); - // 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 + // A click on the plane follows it from where the camera is (`keepView`, + // below). A selection from elsewhere (a search, voice, a share link) has no + // view of the plane to keep: a billboard has a ~zero bounding sphere, so the + // renderer's default follow distance is far too tight. It gets 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), @@ -1202,11 +1190,17 @@ export function createTracking({ // label, sprite, display position) reads the tracked entity's record. const camera = cameraOf(flightState._viewer); camera.cancelFlight(); + const kept = keepView + ? keptViewFrom(camera.pose(), getTrackedPosition()) + : null; flightState._followTarget = entityFollowTarget(flightState._trackedEntity, { position: getTrackedPosition, frame: 'enu', - viewFrom, + viewFrom: kept ?? viewFrom, minRange: FOLLOW_MIN_RANGE_M, + // A click keeps the camera's distance and angle: the plane slides to + // the centre from where the camera is, and is followed from there. + ...(kept ? { transitionS: SELECTION_FOLLOW_TRANSITION_S } : {}), }); camera.follow(flightState._followTarget); @@ -1338,7 +1332,7 @@ export function createTracking({ if (pickedIcao && flightState._icons?.has(pickedIcao)) { _cancelPendingTrackingRestore(); - _trackFlight(pickedIcao, { origin: 'user' }); + _trackFlight(pickedIcao, { origin: 'user', keepView: true }); return; } } @@ -1374,6 +1368,8 @@ export function createTracking({ _applyCockpitState, _resetTrackedSelectionState, _trackedModelRegimeActive, + _trackedBillboardLook, + _trackedSprite, _syncTracked2dRotation, _appendTrailFix, _trailTick, diff --git a/src/layers/military/index.js b/src/layers/military/index.js index e0bb58745..10c636297 100644 --- a/src/layers/military/index.js +++ b/src/layers/military/index.js @@ -78,4 +78,3 @@ export function createMilitaryFlightLayer({ Object.defineProperty(layer, 'testing', { value: parts.testing }); return layer; } -export { TRACKED_MODEL_MAX_PX } from './policy.js'; diff --git a/src/layers/military/lifecycle.js b/src/layers/military/lifecycle.js index 0185b0498..084460277 100644 --- a/src/layers/military/lifecycle.js +++ b/src/layers/military/lifecycle.js @@ -240,7 +240,7 @@ export function createLifecycle({ ids: new Set(), source: flightState.feed._lastSource, }; - parts.tracking._resetTrackedSelectionState(); // next lifecycle re-evaluates against the ENTER ceiling + parts.tracking._resetTrackedSelectionState(); // the next lifecycle starts a fresh selection flightState._viewer = null; }, }; diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js index 490ae7091..ad4d3eec5 100644 --- a/src/layers/military/motion.js +++ b/src/layers/military/motion.js @@ -35,8 +35,7 @@ import { import { displayDelayMs, followsClock, - TRACKED_MODEL_MAX_PX, - TRACKED_MODEL_MIN_PX, + MODEL_MIN_PX, BILLBOARD_SCALE, TRACKED_BILLBOARD_SCALE_BY_DISTANCE, DR_CORRECTION_MS, @@ -70,7 +69,6 @@ export function createMotion({ layer, resolveAsset, }) { - const { trackedModelScaleForPixelCap } = services.camera; const { nearFarScalarValueAtDistance, clearFocusTarget, @@ -275,21 +273,11 @@ export function createMotion({ const spec = parts.rendering._modelSpec( flightState.records.data.get(icao24), ); - const scale = trackedModelScaleForPixelCap({ - baseScale: spec.scale, - nativeRadiusM: spec.nativeRadiusM, - rangeM, - viewportHeightPx, - fovyRad: pose.fovy, - maximumPixelSize: TRACKED_MODEL_MAX_PX, - }); + // Drawn as the fleet draws it: its own size, never under MODEL_MIN_PX. const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2)); const projectedDiameterPx = - (2 * spec.nativeRadiusM * scale * focalLengthPx) / rangeM; - return Math.max( - TRACKED_MODEL_MIN_PX, - Math.min(TRACKED_MODEL_MAX_PX, projectedDiameterPx), - ); + (2 * spec.nativeRadiusM * spec.scale * focalLengthPx) / rangeM; + return Math.max(MODEL_MIN_PX, projectedDiameterPx); } const sprite = readEntityRecord(flightState._trackedEntity)?.sprite; diff --git a/src/layers/military/policy.js b/src/layers/military/policy.js index ff12c9d3e..49ff6ab3a 100644 --- a/src/layers/military/policy.js +++ b/src/layers/military/policy.js @@ -71,12 +71,6 @@ export const MODEL_ALT_CEIL_M = 800000; export const MODEL_MIN_PX = 24; // floor so distant models stay visible without ballooning into a min-pixel blob (mirror of flights.js) -export const TRACKED_MODEL_MIN_PX = 40; -// keep the glTF silhouette comparable to the selected 2D glyph at handoff - -export const TRACKED_MODEL_MAX_PX = 200; -// owner-selected close-range tracked-target feel - // Per-mode caps + radii — mirror of flights.js. Modes differ by RADIUS (not just cap) so Proximity // and All aren't identical when few planes are in range; on-screen planes win the cap (see flights.js). diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index 898252848..ce1a011aa 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -250,8 +250,8 @@ export function createQueries({ * Live layer params. * `models3d` toggles 3D glTF jet-model rendering for the FLEET (altitude-gated): when on, * surrounding military aircraft become 3D models once the camera is zoomed in past - * MODEL_ALT_CEIL_M. The TRACKED contact is NOT gated by this — it takes its 3D model by - * camera distance regardless (see `_trackedModelRegimeActive` / trackedModelRegime.js). + * MODEL_ALT_CEIL_M. The TRACKED contact follows the same rule (`_trackedModelRegimeActive`), + * so selecting a contact never turns its icon into a model or its model into an icon. * `models3dMode` is 'proximity' (nearest MODEL_MAX in view) or 'all' (every in-view plane). * @param {{models3d?: boolean, models3dMode?: 'proximity'|'all', selectedMilitaryTrackingId?: string|null}} params */ diff --git a/src/layers/military/state.js b/src/layers/military/state.js index 432faa2d2..80b385861 100644 --- a/src/layers/military/state.js +++ b/src/layers/military/state.js @@ -293,13 +293,13 @@ export function createFlightState({ source, services }) { 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 - * ceiling instead of inheriting the previous target's looser EXIT band. */ + /** Whether the fleet's model rule (3D on, below the ceiling, inside the + * nearest-first cap) gives the tracked contact a model: the tracked model + * draws only then, so selecting a contact never changes its form. Seeded + * from the contact's fleet model when it is selected, then kept by the + * fleet pass. */ - flightState._trackedZoomLatched = false; - - flightState._trackedZoomLatchIcao = null; + flightState._trackedModelEligible = false; /** The tracked-model load-failure budget: the selection it counts for, * its failures, and when it may load again (`TRACKED_MODEL_*`). */ diff --git a/src/layers/military/testing.js b/src/layers/military/testing.js index 574aaf039..642d1ca87 100644 --- a/src/layers/military/testing.js +++ b/src/layers/military/testing.js @@ -71,6 +71,7 @@ export function createTesting({ tracked = true, models = [], draw = null, + trackedModelEligible = true, }) { flightState._viewer = viewer; parts.rendering._disposeModelSets(); @@ -90,11 +91,17 @@ export function createTesting({ flightState._trackedIcao = tracked ? icao24 : null; flightState._trackedEntity = tracked ? entity : null; flightState._trackedModel = null; + // Whether the fleet's model rule gives the tracked contact a model (the + // fleet pass keeps it): a model unless the test says otherwise. + flightState._trackedModelEligible = tracked && trackedModelEligible; + // `null`: as a selection seeds it (from the contact's fleet model). + if (trackedModelEligible === null) + parts.tracking._resetTrackedSelectionState(); parts.tracking._cancelPendingTrackingRestore(); - // NOTE: deliberately does NOT reset the per-selection latches. They are - // production state owned by the tracking lifecycle (_resetTrackedSelectionState), - // and clearing them here would mask exactly the deselect→re-track hole this - // seam is used to test. + // NOTE: deliberately does NOT reset the load-failure budget. It is + // production state owned by the tracking lifecycle + // (_resetTrackedSelectionState), and clearing it here would mask exactly + // the deselect→re-track hole this seam is used to test. flightState.feed._backoff = false; flightState.feed._retryAt = 0; } @@ -146,9 +153,8 @@ export function createTesting({ parts.tracking._applyCockpitState({ active, subjectId }); } - /** Evaluate the TRACKED contact's zoom regime through the production predicate. - * The decision is latch-bearing (default-on, hysteretic, cockpit/TR-3B-suppressed) - * and otherwise only observable through a live scene, so tests drive it here. */ + /** Evaluate whether the TRACKED contact draws as its model, through the + * production predicate (the fleet's rule; cockpit/TR-3B-suppressed). */ function _trackedModelRegimeActiveForTest() { return parts.tracking._trackedModelRegimeActive(); @@ -187,6 +193,19 @@ export function createTesting({ return flightState._models.get(icao24) ?? null; } + /** How the tracked billboard is drawn (`_trackedBillboardLook`, + * `_trackedSprite`) next to how the contact's fleet icon is (`_fleetLook`). */ + + function _trackedIconLookForTest(icao24) { + return { + tracked: { + ...parts.tracking._trackedBillboardLook(), + sprite: parts.tracking._trackedSprite(icao24), + }, + fleet: parts.icons._fleetLook(icao24), + }; + } + /** The tracked model's record, or null. */ function _trackedModelForTest() { @@ -215,6 +234,7 @@ export function createTesting({ _setIconForTest, _ensureFleetModelForTest, _trackedModelForTest, + _trackedIconLookForTest, _modelSetIdsForTest, }; } diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index 61dbdaeaf..e0d388260 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -7,8 +7,6 @@ import { import { formatNumber, t } from '../../i18n/index.js'; import { unitLabel } from '../../ui/unitLabels.js'; import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js'; -import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js'; -import { trackedModelZoomActive } from '../../data/trackedModelRegime.js'; import { courseScreenRotation, stabilizeScreenRotation, @@ -23,7 +21,6 @@ import { julianToEpochMs } from '../../geo/julian.js'; import { renderedFrames } from '../../data/renderedFrames.js'; import { clone, distance, distanceSquared, vec } from '../../geo/vector.js'; import { trailHeadStart } from '../../data/modelVisualAnchor.js'; -import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { isTrackingSelectionGesture, isTrackingClickGesture, @@ -36,10 +33,8 @@ import { followsClock, STALE_ALPHA, TRAIL_COLOR, - BILLBOARD_SCALE, AMBER_TRANSPARENT, TRACKED_ICON_COLOR, - TRACKED_BILLBOARD_SCALE_BY_DISTANCE, } from './policy.js'; import { drawTrailSegments, @@ -95,7 +90,8 @@ export function createTracking({ const { createTrail } = services.trails; const { ensureGeoidReady, geoidHeight } = services.geoid; const { clearFocusTarget } = services.focus; - const { FOLLOW_MIN_RANGE_M } = services.camera; + const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, keptViewFrom } = + services.camera; const { resolvePickId, isOwnedByOtherLayer } = services.picking; /** The tracked contact's billboard (an icon set on the draw port). */ const trackedIcon = createTrackedAircraftIcon({ @@ -394,22 +390,40 @@ export function createTracking({ refreshTrackedSubjectContext(_contextSubjectMetadata(icao24)); } - /** 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, - ), - TRACKED_ICON_PX, - ); + /** The tracked billboard's images, from the current class/conversion: the + * fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */ + function _trackedBillboardLook() { + return parts.icons._fleetLook(flightState._trackedIcao); + } + + /** + * What the tracked billboard is drawn at: the size, scale and scale by + * distance its fleet icon has (the scale read live: a landing changes it). + * Kept in its entity record too, so the camera guard and screen + * annotations size it from the app's own state. + * @param {string} icao24 + */ + function _trackedSprite(icao24) { + const look = parts.icons._fleetLook(icao24); + return { + width: look.size[0], + height: look.size[1], + get scale() { + return parts.rendering._fleetBillboardScale( + icao24, + flightState.records.data.get(icao24)?.klass, + ); + }, + scaleByDistance: look.scaleByDistance, + }; } /** Re-image the tracked billboard from the current class/conversion. */ function _syncTrackedBillboardImage() { if (!flightState._trackedIcao || !flightState._trackedEntity) return; - trackedIcon.setImage(_trackedBillboardImage()); + const look = _trackedBillboardLook(); + trackedIcon.setImage(look.image, look.imageLod); } /** @@ -453,60 +467,42 @@ export function createTracking({ } } - /** Clear the per-SELECTION tracked-model latches: the zoom hysteresis band - * and the load-failure budget. - * Called from each path that changes which contact is - * selected — deselect, re-track, cross-layer handoff, init, destroy. - * - * This must live in the production lifecycle, not only in the predicate's - * icao-change guard: a deselect followed by a same-turn re-track of the SAME - * icao (Contacts re-entry, a cross-layer round trip back to this layer) never - * makes `_trackedIcao` *observably* change, so the guard never fires. Without - * the reset, a contact dropped inside the hysteresis band comes back as a - * MODEL above the ENTER ceiling. Mirror of flights.js. */ + /** Start a selection's tracked-model state afresh: the model it draws + * with (whatever the fleet drew it with, a model or its icon) and the + * load-failure budget. Called from each path that changes which contact + * is selected — deselect, re-track, cross-layer handoff, init, destroy. */ function _resetTrackedSelectionState() { - flightState._trackedZoomLatched = false; - flightState._trackedZoomLatchIcao = null; + flightState._trackedModelEligible = Boolean( + flightState._trackedIcao && + flightState._models?.has(flightState._trackedIcao), + ); flightState._trackedModelFailIcao = null; flightState._trackedModelFailCount = 0; flightState._trackedModelRetryAtMs = 0; } /** - * The TRACKED aircraft's own model regime — DEFAULT-ON, camera-distance driven - * (owner directive 2026-08-19). Mirror of flights.js: this does NOT consult the - * DISPLAY-rail `models3d` toggle, which keeps owning the FLEET - * (`_modelRegimeActive`) and its draw-call budget. Thresholds + hysteresis live - * in trackedModelRegime.js — enter at TRACKED_MODEL_ENTER_ALT_M (150_000 m, the - * owner's playtested swap distance, deliberately NEARER than the fleet's 800 km - * ceiling this used to inherit), hand back only above - * TRACKED_MODEL_EXIT_ALT_M so a boundary orbit cannot flap billboard↔model. - * First-person means your own airframe is not drawn in cockpit — the eye sits - * metres from its origin. + * Whether the TRACKED aircraft draws as its 3D model: exactly when the + * fleet's own rule would draw it so (`_modelRegimeActive` — 3D on and the + * camera below the ceiling — and a place in the nearest-first cap, which + * the fleet pass keeps in `_trackedModelEligible`). Selecting a contact + * therefore never turns its icon into a model or its model into an icon. + * A converted TR-3B has no 3D asset, and in cockpit you sit in your own + * airframe, so neither draws one. */ function _trackedModelRegimeActive() { - if (flightState._trackedZoomLatchIcao !== flightState._trackedIcao) { - flightState._trackedZoomLatchIcao = flightState._trackedIcao; - flightState._trackedZoomLatched = false; - } - // A converted TR-3B has no 3D asset — suppressing the regime keeps its - // tracked billboard fully opaque (the colour callback reads this too), so - // the triangle stays the visual all the way in. Mirror of flights.js. if ( !flightState._trackedIcao || flightState._cockpitContactMode || isTr3b(flightState._trackedIcao) - ) { - flightState._trackedZoomLatched = false; + ) return false; - } - flightState._trackedZoomLatched = trackedModelZoomActive( - _pose()?.height, - flightState._trackedZoomLatched, + return ( + flightState._trackedModelEligible === true && + parts.rendering._modelRegimeActive() ); - return flightState._trackedZoomLatched; } /** Seed the tracked billboard's 2D orientation before a 3D→2D handoff. */ @@ -1016,9 +1012,15 @@ export function createTracking({ * smooth continuous motion, and sets the viewer's trackedEntity so the camera * follows. * @param {string} icao24 - ICAO hex identifier of the aircraft to track + * @param {{origin?: string, keepView?: boolean}} [options] `keepView` (a + * click on the plane): follow from the camera's own distance and angle, + * the plane sliding to the centre, rather than the calibrated framing. */ - function _trackFlight(icao24, { origin = 'programmatic' } = {}) { + function _trackFlight( + icao24, + { origin = 'programmatic', keepView = false } = {}, + ) { _clearTracking(false, { origin }); // switching planes — the new follow-camera takes over const icons = flightState._icons; @@ -1036,10 +1038,9 @@ export function createTracking({ flightState._cachedDRFrame = -1; flightState._lastTrackedRotation = 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. - parts.rendering._releaseModel(icao24); + // A fleet 3D model this aircraft had keeps drawing it until the tracked + // model is ready (`_updateTrackedModel` lets it go then), so it never + // turns into its icon for the frames the tracked model takes to load. // Hide the icon -- the tracked entity replaces it visually icons.setShown(icao24, false); @@ -1063,18 +1064,7 @@ export function createTracking({ // 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, - height: 28, - scale: - BILLBOARD_SCALE * - (CLASS_SCALE_2D[ - flightState.records.data.get(flightState._trackedIcao)?.klass - ] || 1), - scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE, - }; + const sprite = _trackedSprite(icao24); // 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( @@ -1093,7 +1083,8 @@ export function createTracking({ }; trackedIcon.show({ id: icao24, - image: _trackedBillboardImage(), + image: _trackedBillboardLook().image, + imageLod: _trackedBillboardLook().imageLod, sprite, position: getTrackedPosition, // Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading); @@ -1131,9 +1122,11 @@ export function createTracking({ entityRecord(flightState._trackedEntity).labelModel = trackedLabelModelFromText(_buildTrackedLabel(info, icao24), '#ffd166'); - // 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 + // A click on the plane follows it from where the camera is (`keepView`, + // below). A selection from elsewhere (a search, voice, a share link) has no + // view of the plane to keep: a billboard has a ~zero bounding sphere, so the + // renderer's default follow distance is far too tight. It gets 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); @@ -1157,11 +1150,17 @@ export function createTracking({ // label, sprite, display position) reads the tracked entity's record. const camera = cameraOf(flightState._viewer); camera.cancelFlight(); + const kept = keepView + ? keptViewFrom(camera.pose(), getTrackedPosition()) + : null; flightState._followTarget = entityFollowTarget(flightState._trackedEntity, { position: getTrackedPosition, frame: 'enu', - viewFrom, + viewFrom: kept ?? viewFrom, minRange: FOLLOW_MIN_RANGE_M, + // A click keeps the camera's distance and angle: the plane slides to + // the centre from where the camera is, and is followed from there. + ...(kept ? { transitionS: SELECTION_FOLLOW_TRANSITION_S } : {}), }); camera.follow(flightState._followTarget); @@ -1249,7 +1248,7 @@ export function createTracking({ if (pickedIcao && flightState._icons?.has(pickedIcao)) { _cancelPendingTrackingRestore(); - _trackFlight(pickedIcao, { origin: 'user' }); + _trackFlight(pickedIcao, { origin: 'user', keepView: true }); return; } } @@ -1293,6 +1292,8 @@ export function createTracking({ _refreshTr3bForStyle, _resetTrackedSelectionState, _trackedModelRegimeActive, + _trackedBillboardLook, + _trackedSprite, _syncTracked2dRotation, _trailFloorPosition, _appendTrailFix, diff --git a/src/layers/rail/follow.js b/src/layers/rail/follow.js index 2f1208089..db9033134 100644 --- a/src/layers/rail/follow.js +++ b/src/layers/rail/follow.js @@ -1,5 +1,9 @@ import { findCamera } from '../../render/rendererOf.js'; -import { FOLLOW_MIN_RANGE_M } from '../../data/trackedCamera.js'; +import { + FOLLOW_MIN_RANGE_M, + keptViewFrom, + SELECTION_FOLLOW_TRANSITION_S, +} from '../../data/trackedCamera.js'; import { copyInto, lerpInto } from '../../geo/vector.js'; import { FOLLOW_HANDOVER_MS, @@ -14,12 +18,14 @@ export const RAIL_FOCUS_KIND = 'train'; * The selected train's camera. * * A moving train is followed as a tracked aircraft is: the layer hands the - * camera port a follow target that stands on the train's marker, framed by - * the shared world-focus framing for a train and never closer than the - * aircraft's readable minimum, so the camera rides with the train and the - * user still orbits and zooms around it. Any other train gets one fly-to - * through the shared world-focus request, as a vessel does. Inside the - * Cockpit that request is refused with its toast. + * camera port a follow target that stands on the train's marker, seen from + * where the camera is (its distance and angle kept, the train sliding to + * the centre) and never closer than the aircraft's readable minimum, so the + * camera rides with the train and the user still orbits and zooms around it. + * Any other train gets one fly-to through the shared world-focus request, + * keeping the view as a vessel's does. Inside the Cockpit that request is + * refused with its toast. Without a view to keep (no camera pose), the + * shared world-focus framing for a train frames it. * * The follow lets go when the train is deselected (an empty click, Escape, its * category hidden, the train leaving its feed, the layer turned off), when @@ -106,7 +112,9 @@ export function createFollow({ state, services, parts }) { } function startFollow(entry, position, port) { - const offset = railFollowOffset(camera.framing, port.pose()?.heading); + const offset = + keptViewFrom(port.pose(), position) ?? + railFollowOffset(camera.framing, port.pose()?.heading); const follow = { key: entry.key, target: null, @@ -119,8 +127,9 @@ export function createFollow({ state, services, parts }) { position: () => followedPosition(follow), frame: 'enu', viewFrom: { x: offset.x, y: offset.y, z: offset.z }, - // Framed exactly once, as a tracked aircraft is, and never closer. + // Framed once, as a tracked aircraft is, and never closer. minRange: FOLLOW_MIN_RANGE_M, + transitionS: SELECTION_FOLLOW_TRANSITION_S, selectionOrigin: 'user', }; state._follow = follow; @@ -158,6 +167,7 @@ export function createFollow({ state, services, parts }) { id: entry.key, label: label || entry.key, position: { x: position.x, y: position.y, z: position.z }, + keepView: true, }) === true ); } diff --git a/src/layers/rail/follow.test.mjs b/src/layers/rail/follow.test.mjs index da03cc443..52075a824 100644 --- a/src/layers/rail/follow.test.mjs +++ b/src/layers/rail/follow.test.mjs @@ -4,7 +4,11 @@ // distance while the rest of the network hides as before. import test from 'node:test'; import assert from 'node:assert/strict'; -import { FOLLOW_MIN_RANGE_M } from '../../data/trackedCamera.js'; +import { + FOLLOW_MIN_RANGE_M, + keptViewFrom, + SELECTION_FOLLOW_TRANSITION_S, +} from '../../data/trackedCamera.js'; import { fromDegrees } from '../../geo/ellipsoid.js'; import { distance } from '../../geo/vector.js'; import { @@ -147,19 +151,24 @@ test('selecting a moving train hands the camera a follow target that rides on it const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON); app.moveCameraQuietly({ heading: Math.PI / 4 }); const cancelled = app.camera.flightsCancelled; + const pose = app.camera.pose(); + const at = { ...app.entry(key).marker.position }; app.parts().selection.selectAndFocusTrain(key); const target = app.camera.followed; assert.ok(target, 'the camera follows a target'); assert.equal(app.focusRequests.length, 0, 'no one-shot fly-to'); assert.equal(app.camera.flightsCancelled, cancelled + 1); - // Framed as the aircraft are (exactly once, never closer than their - // minimum), from the train's own framing seen along the camera's heading. + // Framed as the aircraft are (once, never closer than their minimum), + // from where the camera already is: its distance and angle kept, the train + // gliding to the centre. assert.equal(app.follows.length, 1); assert.equal(target.frame, 'enu'); assert.equal(target.minRange, FOLLOW_MIN_RANGE_M); - const expected = railFollowOffset(WORLD_FOCUS_FRAMING.train, Math.PI / 4); + assert.equal(target.transitionS, SELECTION_FOLLOW_TRANSITION_S); + const expected = keptViewFrom(pose, at); assert.ok(Math.abs(target.viewFrom.x - expected.x) < 1e-6); + assert.ok(Math.abs(target.viewFrom.y - expected.y) < 1e-6); assert.ok(Math.abs(target.viewFrom.z - expected.z) < 1e-6); // The target stands where the marker is drawn, frame after frame. diff --git a/src/layers/rail/policy.js b/src/layers/rail/policy.js index 9d2faa28a..ecb312176 100644 --- a/src/layers/rail/policy.js +++ b/src/layers/rail/policy.js @@ -152,7 +152,6 @@ export const TRACK_MAX_GRADE = 0.05; export const TRACK_SETTLE_MPS = 0.5; export const TRACK_SNAP_M = 2_000; export const MARKER_PIXEL_SIZE = 18; -export const SELECTED_PIXEL_SIZE = 28; export const SELECTED_CARD_REFRESH_MS = 250; /** While a train is selected, every other train is drawn at this opacity. */ export const UNSELECTED_TRAIN_ALPHA = 0.35; diff --git a/src/layers/rail/rendering.js b/src/layers/rail/rendering.js index 2838c9544..92f514ce7 100644 --- a/src/layers/rail/rendering.js +++ b/src/layers/rail/rendering.js @@ -34,7 +34,6 @@ import { FLOOR_WARM_MAX_DIST_KM, MARKER_PIXEL_SIZE, RAIL_CATEGORY_COLORS, - SELECTED_PIXEL_SIZE, UNSELECTED_TRAIN_ALPHA, } from './policy.js'; import { placeOnPath } from './pathBinding.js'; @@ -736,11 +735,10 @@ export function createRendering({ state, services, parts }) { function paint(entry) { if (!entry.marker) return; - const selected = entry.key === state._selectedKey; - const size = selected ? SELECTED_PIXEL_SIZE : MARKER_PIXEL_SIZE; + // Selection dims the other trains; the selected one keeps its size. entry.marker.image = spriteFor(entry.category, entry.railMode); - entry.marker.width = size; - entry.marker.height = size; + entry.marker.width = MARKER_PIXEL_SIZE; + entry.marker.height = MARKER_PIXEL_SIZE; entry.marker.color = tintFor(entry); entry.marker.show = markerShown(entry); touch(entry); diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index 7b300f740..fea12a71f 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -166,6 +166,14 @@ function colourOf(c) { : new Cesium.Color(c[0], c[1], c[2], c[3]); } +// A marker's glyph size on screen, CSS pixels: its width less the halo the +// raster pads it with (the SVG's viewBox is the padded frame at 96 units per +// glyph). +function glyphPx(marker) { + const svg = Buffer.from(marker.image.split(',')[1], 'base64').toString(); + return (marker.width * 96) / Number(svg.match(/viewBox="-\d+ -\d+ (\d+)/)[1]); +} + // A camera `height` metres above a place, looking straight down at it or, // with `away`, straight out to space. function viewFrom(lon, lat, height, away = false) { @@ -2365,15 +2373,17 @@ test('under FLIR and NVG every sprite is white-hot with a dark halo, and selecti ); assert.ok(entry.marker.width > plainWidth * 1.2, 'and larger'); } - // Selecting under FLIR grows the sprite and keeps it white — cyan would dim it. + // Selecting under FLIR keeps the sprite white (cyan would dim it) and its + // size: a selected vehicle is drawn no bigger than its neighbours. app.layer._transitPartsForTest().selection.selectVehicle(bus.key); assert.ok( Cesium.Color.equals(colourOf(bus.marker.color), Cesium.Color.WHITE), 'still white when selected', ); - assert.ok( - bus.marker.width > byRoute.get('Red').marker.width, - 'and bigger than its neighbours', + assert.equal( + Math.round(glyphPx(bus.marker) * 1e6), + Math.round(glyphPx(byRoute.get('Red').marker) * 1e6), + 'and no bigger than its neighbours', ); app.layer._transitPartsForTest().selection.clearSelection(); assert.ok( @@ -3019,21 +3029,22 @@ test('every styling path retains the mode palette and exact unpadded size', asyn const width = Number(svg.match(/viewBox="-\d+ -\d+ (\d+)/)[1]); assert.ok(Math.abs((entry.marker.width * 96) / width - display) < 1e-9); }; + // Selection never changes the drawn size. check('#5EF08A', 20); parts.selection.selectVehicle(entry.key); - check('#5EF08A', 30); + check('#5EF08A', 20); parts.rendering.paintMode(entry, 'subway'); - check('#FF4538', 30); + check('#FF4538', 20); app.style('thermal'); - check('#FFFFFF', 39); + check('#FFFFFF', 26); parts.selection.clearSelection(); check('#FFFFFF', 26); app.vision('nvg', true); check('#FFFFFF', 26); parts.selection.selectVehicle(entry.key); - check('#FFFFFF', 39); + check('#FFFFFF', 26); app.vision('normal', false); - check('#FF4538', 30); + check('#FF4538', 20); parts.selection.clearSelection(); check('#FF4538', 20); }); diff --git a/src/layers/transit/policy.js b/src/layers/transit/policy.js index 6b3a8a5ff..40e0be872 100644 --- a/src/layers/transit/policy.js +++ b/src/layers/transit/policy.js @@ -81,7 +81,6 @@ export const FLOOR_REREAD_ATTEMPTS = 6; // --- Rendering --- /** On-screen glyph size in CSS px at the near end of the distance ramp. */ export const MARKER_PIXEL_SIZE = 20; -export const SELECTED_PIXEL_SIZE = 30; /** * How often the fleet's screen-space rotations may be recomputed. Projecting a * course into screen space depends on the camera, so a moving camera would diff --git a/src/layers/transit/rendering.js b/src/layers/transit/rendering.js index 317249f77..91c2ee75a 100644 --- a/src/layers/transit/rendering.js +++ b/src/layers/transit/rendering.js @@ -32,7 +32,6 @@ import { MARKER_PIXEL_SIZE, ROTATION_REFRESH_MS, VISIBILITY_REFRESH_MS, - SELECTED_PIXEL_SIZE, TRANSIT_MODE_COLORS, vehicleNearView, } from './policy.js'; @@ -595,7 +594,8 @@ export function createRendering({ state, services, parts }) { * Under a mono preset (NVG, FLIR, noir) the sprite is white-hot with a dark * halo sized in screen pixels; under CRT a saturated mode colour with a * thinner halo; otherwise the shipped mode colour and hairline. Selection - * grows the glyph and retains the mode colour; sensors use opaque white. + * keeps the glyph's size and mode colour, widening only its halo and + * drawing from a crisper raster; sensors use opaque white. * @param {object} entry */ function applySpriteStyle(entry) { @@ -603,7 +603,7 @@ export function createRendering({ state, services, parts }) { if (!marker) return; const style = state._stylePreset; const selected = state._selectedKey === entry.key; - const basePx = selected ? SELECTED_PIXEL_SIZE : MARKER_PIXEL_SIZE; + const basePx = MARKER_PIXEL_SIZE; const halo = presetSpriteOutlinePx(style, selected); const displayPx = basePx * presetSpriteScale(style, selected); const frame = haloFrame(halo, displayPx); diff --git a/src/layers/vessels/rendering.js b/src/layers/vessels/rendering.js index c2a3bcc9f..da8e268e6 100644 --- a/src/layers/vessels/rendering.js +++ b/src/layers/vessels/rendering.js @@ -212,7 +212,8 @@ export function createRendering({ pos: visual.position, image: shipIcon(record, selected), size: [SHIP_ICON_PX, SHIP_ICON_PX], - scale: shipScale(record) * (selected ? 1.2 : 1), + // Selection changes the colour only, never the size. + scale: shipScale(record), rotationMode: 'course', // Held on course; `course` for renderers without motion segments. course: courseDeg, diff --git a/src/layers/vessels/selection.js b/src/layers/vessels/selection.js index e2137a7d2..7f8ddab83 100644 --- a/src/layers/vessels/selection.js +++ b/src/layers/vessels/selection.js @@ -125,6 +125,8 @@ export function createSelection({ id: record.id, label: record.name || record.mmsi || record.id, position: components.rendering.iconPosition(record), + // The camera keeps its distance and angle; the vessel slides to the centre. + keepView: true, }); return true; } diff --git a/src/render/camera/followTransition.js b/src/render/camera/followTransition.js new file mode 100644 index 000000000..20865958b --- /dev/null +++ b/src/render/camera/followTransition.js @@ -0,0 +1,103 @@ +/** + * @module render/camera/followTransition + * @description A follow's `transitionS` (`camera.d.ts`), shared by every + * renderer and by camera controllers (the package's + * `./render/camera/followTransition` export): the eye's way from where it + * stood when the follow began to the follow's first framing. + * + * Everything is in the target's frame, which moves with the target, so the + * eye rides along with it from the first frame. Over the transition the eye's + * offset turns from the offset it had towards `viewFrom` (its length going + * from the one to the other), and its view turns from the way it looked to + * the framing's, which looks at the target with no roll. An offset that + * equals the eye's own direction and range from the target (the camera's + * current view, kept) leaves the view direction and the range unchanged + * throughout: only the eye's place moves, and the target slides to the + * centre. + */ +import { + cross, + dot, + magnitude, + normalize, + scale, + vec, +} from '../../geo/index.js'; + +const EPSILON10 = 1e-10; + +/** + * The eased fraction of a transition `elapsedMs` into `durationMs`: + * smoothstep, 0 before it starts and 1 from its end on. + * @param {number} elapsedMs + * @param {number} durationMs + * @returns {number} + */ +export function followTransitionFraction(elapsedMs, durationMs) { + if (!(durationMs > 0)) return 1; + const t = Math.min(1, Math.max(0, elapsedMs / durationMs)); + return t * t * (3 - 2 * t); +} + +/** `(1 - s) a + s b`, normalized; `fallback` when that has no length. */ +function blendUnit(a, b, s, fallback) { + const v = vec( + (1 - s) * a.x + s * b.x, + (1 - s) * a.y + s * b.y, + (1 - s) * a.z + s * b.z, + ); + return dot(v, v) > EPSILON10 ? normalize(v) : fallback; +} + +/** + * The eye a follow's first framing places at `offset` in the target's frame: + * there, looking at the target, its right level with the frame's x-y plane + * (east-north for an `enu` follow). + * @param {{x: number, y: number, z: number}} offset + */ +export function followFramingEye(offset) { + const direction = normalize(scale(offset, -1)); + let right = cross(direction, vec(0, 0, 1)); + right = dot(right, right) < EPSILON10 ? vec(1, 0, 0) : normalize(right); + return { + position: { x: offset.x, y: offset.y, z: offset.z }, + direction, + up: normalize(cross(right, direction)), + right, + }; +} + +/** + * The eye at eased fraction `s` of a follow's transition, in the target's + * frame. + * @param {{position: object, direction: object, up: object}} start The eye + * where the transition began, in the target's frame. + * @param {{x: number, y: number, z: number}} offset The framing's offset + * (`viewFrom`, put out to the least range). + * @param {number} s Eased fraction, 0 to 1 (`followTransitionFraction`). + * @returns {{position: object, direction: object, up: object, right: object}} + */ +export function followTransitionEye(start, offset, s) { + const end = followFramingEye(offset); + if (s >= 1) return end; + const startRange = magnitude(start.position); + const endRange = magnitude(offset); + const along = blendUnit( + startRange > 0 ? scale(start.position, 1 / startRange) : end.direction, + scale(end.direction, -1), + s, + scale(end.direction, -1), + ); + const position = scale(along, (1 - s) * startRange + s * endRange); + const direction = blendUnit(start.direction, end.direction, s, end.direction); + // The up blended, then made square to the view. + const blendedUp = blendUnit(start.up, end.up, s, end.up); + let up = vec( + blendedUp.x - direction.x * dot(direction, blendedUp), + blendedUp.y - direction.y * dot(direction, blendedUp), + blendedUp.z - direction.z * dot(direction, blendedUp), + ); + up = dot(up, up) > EPSILON10 ? normalize(up) : end.up; + const right = normalize(cross(direction, up)); + return { position, direction, up, right }; +} diff --git a/src/render/cesium/camera.js b/src/render/cesium/camera.js index 2cb7af7d7..00f140a9d 100644 --- a/src/render/cesium/camera.js +++ b/src/render/cesium/camera.js @@ -151,6 +151,7 @@ export function createCesiumCamera({ camera, onChanged: () => cameraEvents.emit('followChanged'), itemPosition, + now, }) : null; diff --git a/src/render/cesium/follow.js b/src/render/cesium/follow.js index 43c10b72e..16e95b094 100644 --- a/src/render/cesium/follow.js +++ b/src/render/cesium/follow.js @@ -18,6 +18,10 @@ import * as Cesium from 'cesium'; import { toCartesian } from './common.js'; import { trackedEntityViewEntity } from './internals.js'; +import { + followTransitionEye, + followTransitionFraction, +} from '../camera/followTransition.js'; /** Frames to wait for a target's first position before giving up framing. */ const MAX_FRAME_ATTEMPTS = 120; @@ -155,6 +159,9 @@ export function clampFollowEye(camera, previousPosition, minimumRangeM) { return false; } +/** A Cartesian3 as a plain vector. */ +const plain = (c) => ({ x: c.x, y: c.y, z: c.z }); + const gregorianScratch = new Cesium.GregorianDate(); /** * Scene time in epoch ms, sub-millisecond included: `JulianDate.toDate` @@ -196,6 +203,8 @@ function startOffset(target, viewFrom, result) { * `onChanged` runs on every change of what it tracks; `itemPosition`, * where the draw port draws an item at a scene time (null when it does * not), which a target naming a drawn `item` is followed at. + * @param {() => number} [options.now] Wall clock, ms, for a target's + * `transitionS`. */ export function createCesiumFollow({ widget, @@ -203,6 +212,7 @@ export function createCesiumFollow({ camera, onChanged, itemPosition, + now = () => performance.now(), }) { /** Where a target is at a scene time: its drawn item, else `position`. */ const positionOf = (target, time) => @@ -323,16 +333,45 @@ export function createCesiumFollow({ giveUp(entry); return; } - camera.lookAtTransform( - Cesium.Transforms.eastNorthUpToFixedFrame( - toCartesian(at), - Cesium.Ellipsoid.WGS84, - ), - offset, + const enu = Cesium.Transforms.eastNorthUpToFixedFrame( + toCartesian(at), + Cesium.Ellipsoid.WGS84, ); + if (target.transitionS > 0 && transitionStep(entry, enu, offset)) return; + camera.lookAtTransform(enu, offset); entry.framed = true; } + /** + * One frame of a target's `transitionS`: the eye on its way from where it + * stood to the framing at `offset`, in the target's frame `enu`. + * @returns {boolean} Whether the transition is still under way. + */ + function transitionStep(entry, enu, offset) { + // Into the target's frame, keeping the world pose. + camera.lookAtTransform(enu); + entry.transition ??= { + startMs: now(), + eye: { + position: plain(camera.position), + direction: plain(camera.direction), + up: plain(camera.up), + }, + }; + const s = followTransitionFraction( + now() - entry.transition.startMs, + entry.target.transitionS * 1000, + ); + if (s >= 1) return false; + const eye = followTransitionEye(entry.transition.eye, plain(offset), s); + Cesium.Cartesian3.clone(toCartesian(eye.position), camera.position); + Cesium.Cartesian3.clone(toCartesian(eye.direction), camera.direction); + Cesium.Cartesian3.clone(toCartesian(eye.up), camera.up); + Cesium.Cartesian3.clone(toCartesian(eye.right), camera.right); + scene.requestRender(); + return true; + } + /** * With no position to frame for MAX_FRAME_ATTEMPTS frames, the follow * leaves the camera to Cesium: no framing, no zoom hold, no clamp. diff --git a/src/render/conformance/checks/camera.js b/src/render/conformance/checks/camera.js index 0b53951ad..52d0532df 100644 --- a/src/render/conformance/checks/camera.js +++ b/src/render/conformance/checks/camera.js @@ -11,6 +11,14 @@ import { import { contractDriver, runCameraScript } from '../cameraRunner.js'; import { deepEqual, equal, near, nearAngle, nearVec, ok } from '../expect.js'; import { eyeMoved } from '../../../geo/eyeMoves.js'; +import { + cross, + eastNorthUp, + framePoint, + frameVector, + normalize, + scale, +} from '../../../geo/index.js'; const lonLatToEcef = (h) => h.toEcef; @@ -472,6 +480,72 @@ export function cameraChecks() { r.destroy(); }, }, + { + id: 'camera.follow.transition', + port: 'camera', + title: + 'a follow with transitionS moves the eye from where it stood to viewFrom; a viewFrom along its own view keeps view and range', + async run(h) { + const r = await fresh(h); + const target = h.toEcef({ lon: -97.74, lat: 30.27, height: 1000 }); + const enu = eastNorthUp(target); + // The eye 1.8 km off the target, looking a little beside it. + const local = { x: 400, y: -1500, z: 900 }; + const range = Math.hypot(local.x, local.y, local.z); + const look = normalize({ + x: -local.x + 150, + y: -local.y, + z: -local.z - 120, + }); + const right = normalize(cross(look, { x: 0, y: 0, z: 1 })); + const lookUp = normalize(cross(right, look)); + const eye = framePoint(enu, local); + const direction = normalize(frameVector(enu, look)); + r.camera.setView({ + destination: eye, + orientation: { direction, up: normalize(frameVector(enu, lookUp)) }, + }); + await h.frame(r); + const viewFrom = scale(look, -range); + r.camera.follow({ + key: 'test:transition', + position: () => target, + frame: 'enu', + viewFrom, + transitionS: 1, + }); + const startedAt = h.now(r); + await h.frame(r); + ok(!r.camera.followFramed, 'not framed on the first frame'); + nearVec( + r.camera.pose().position, + eye, + 1e-3, + 'the eye starts where it stood', + ); + let midway = false; + for (let i = 0; i < 600 && !r.camera.followFramed; i++) { + const pose = r.camera.pose(); + near(dist(pose.position, target), range, 1e-6 * range, `range ${i}`); + nearVec(pose.direction, direction, 1e-6, `view ${i}`); + if (dist(pose.position, eye) > 1) midway = true; + await h.frame(r); + } + ok(midway, 'the eye moved before it arrived'); + ok(r.camera.followFramed, 'framed on arrival'); + ok(h.now(r) - startedAt >= 1000 - 1e-6, 'arrived after transitionS'); + const pose = r.camera.pose(); + nearVec( + pose.position, + framePoint(enu, viewFrom), + 1e-3, + 'the eye at viewFrom', + ); + nearVec(pose.direction, direction, 1e-6, 'the same view'); + r.camera.follow(null); + r.destroy(); + }, + }, { id: 'camera.follow.autodetect', port: 'camera', diff --git a/src/render/contract/camera.d.ts b/src/render/contract/camera.d.ts index e2a1967e8..9f2da4435 100644 --- a/src/render/contract/camera.d.ts +++ b/src/render/contract/camera.d.ts @@ -155,6 +155,17 @@ export interface FollowTarget { viewFrom: Vec3 | ((t: number) => Vec3); minRange?: number; boundingRadius?: number; + /** + * Seconds of wall time the first framing takes; without it the eye is + * placed at `viewFrom` on the first frame. With it the eye stays in the + * target's frame from the first frame (riding along with the target) and + * moves from where it stood to the framing, both its offset and its view + * turning, eased (`render/camera/followTransition.js`, the one rule every + * renderer follows); `followFramed` turns true on arrival. A `viewFrom` + * along the eye's own view at its own range keeps the view and the range + * throughout, so the target slides to the centre. + */ + transitionS?: number; } /** diff --git a/src/render/stub/camera.js b/src/render/stub/camera.js index 95a849401..dd98d0d3a 100644 --- a/src/render/stub/camera.js +++ b/src/render/stub/camera.js @@ -44,6 +44,10 @@ import { zeroToTwoPi, } from './math.js'; import { createCameraEvents } from '../camera/events.js'; +import { + followTransitionEye, + followTransitionFraction, +} from '../camera/followTransition.js'; import { geodesicAt } from '../../geo/geodesic.js'; const DEFAULT_FOV = Math.PI / 3; @@ -116,6 +120,8 @@ export function createStubCamera({ let flight = null; let followed = null; let followFramed = false; + /** A follow's transition under way: where the eye began, and when. */ + let transition = null; let coast = Object.freeze({ drag: 0.4, zoom: 0.2 }); const controls = { @@ -666,6 +672,7 @@ export function createStubCamera({ const changed = followed !== target; followed = target; followFramed = false; + transition = null; if (!target) setFrame(IDENTITY); if (changed) emit('followChanged'); requestRender('follow'); @@ -689,6 +696,28 @@ export function createStubCamera({ ); if (range < minRange && range > 0) offset = scale(offset, minRange / range); + if (followed.transitionS > 0 && range > 0) { + // The eye moves from where it is to the framing (`transitionS`). + setFrame(targetFrame); + transition ??= { + startMs: now(), + eye: { position, direction, up }, + }; + const s = followTransitionFraction( + now() - transition.startMs, + followed.transitionS * 1000, + ); + if (s < 1) { + const eye = followTransitionEye(transition.eye, offset, s); + position = eye.position; + direction = eye.direction; + up = eye.up; + right = eye.right; + requestRender('follow'); + return; + } + transition = null; + } lookAtFrame(targetFrame, offset); followFramed = true; return; diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index 61cd618ef..75a7a063e 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -1799,7 +1799,7 @@ export class StyleManager extends ShellFacade { * altitude ceiling, and only the nearest MODEL_MAX in view are admitted, so * the default costs nothing at globe scale. `all` is the deliberate opt-in; * turning the toggle off returns the fleet to flat billboards. The TRACKED - * contact is independent of this toggle (see trackedModelRegime.js). + * contact follows the same rule: selecting a contact never changes its form. * @returns {void} */ diff --git a/src/worldFocus.js b/src/worldFocus.js index 05ebf52f9..af50b2f30 100644 --- a/src/worldFocus.js +++ b/src/worldFocus.js @@ -1,8 +1,12 @@ /** * One-click camera transfer for layer-owned world targets. */ -import { WGS84, toRadians } from './geo/index.js'; +import { WGS84, eastNorthUp, framePoint, toRadians } from './geo/index.js'; import { findCamera } from './render/rendererOf.js'; +import { + keptViewFrom, + SELECTION_FOLLOW_TRANSITION_S, +} from './data/trackedCamera.js'; export const WORLD_FOCUS_REQUEST_EVENT = 'gev:world-request-focus'; export const WORLD_CLICK_FOCUS_DURATION_SEC = 1.9; @@ -76,18 +80,38 @@ export function routeWorldFocusRequest(event, runExplicitFocus, fly) { return runExplicitFocus(detail, () => fly(detail)); } -/** Fly to a world target after ownership has been released. */ +/** + * Fly to a world target after ownership has been released. A target with + * `keepView` (a click on it) keeps the camera's distance and angle: the eye + * moves, on a straight path, to where it sees the target in the centre with + * the view it has now (`keptViewFrom`). Any other is framed by its kind + * (`WORLD_FOCUS_FRAMING`). + */ export function flyToWorldTarget(viewer, target = {}) { const camera = findCamera(viewer); const framing = WORLD_FOCUS_FRAMING[target.kind]; if (!camera || !framing || !isValidWorldFocusTarget(target)) return false; - const poseHeading = camera.pose().heading; - const heading = Number.isFinite(poseHeading) ? poseHeading : 0; + const pose = camera.pose(); + const kept = target.keepView ? keptViewFrom(pose, target.position) : null; + camera.cancelFlight(); + if (kept) { + camera.flyTo(framePoint(eastNorthUp(target.position), kept), { + orientation: { direction: pose.direction, up: pose.up }, + durationS: + target.durationSec > 0 + ? target.durationSec + : SELECTION_FOLLOW_TRANSITION_S, + easing: 'cubicInOut', + // Below both ends: no arc, so the camera does not climb on the way. + maxHeight: 0, + }); + return true; + } + const heading = Number.isFinite(pose.heading) ? pose.heading : 0; const duration = target.durationSec > 0 ? target.durationSec : WORLD_CLICK_FOCUS_DURATION_SEC; - camera.cancelFlight(); camera.flyToBounds( { center: target.position, radius: framing.radiusM }, {