mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Move the flights and military layers onto the renderer ports
The flights and military layers now reach the renderer only through its ports: motion, queries, state, tracking, enrichment, evidence and policy read the camera pose, project through the query port, request and suspend frames through the frame port, and key per-frame caches on the frames drawn rather than the scene's frame number. Policy is plain data, the enrichment view test is pose-based, and the tracked aircraft is an icon in a draw-port set with a plain holder standing in for the entity that Cockpit, the tracked card and share links read. The mesh floor sampler can sample through the query port, excluding named draw sets, and both layers use it that way. A pick of another layer's tracked icon is never taken for one of a layer's own contacts. Twelve layer files leave the Cesium allow-list.
This commit is contained in:
1 parent
00a0a0dbc7
commit
23d56f8393
40 files changed
+1638
-908
No files matched your search
@@ -1,6 +1,8 @@
|
||||
import { classifyAircraft } from '../../data/aircraftClass.js';
|
||||
import { horizonOccluder } from '../../data/iconOrientation.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { findCamera } from '../../render/rendererOf.js';
|
||||
import { frustumPlanes, sphereOutside } from '../../geo/frustum.js';
|
||||
import { horizonFrom } from '../../geo/horizon.js';
|
||||
import { distanceSquared, vec } from '../../geo/vector.js';
|
||||
import {
|
||||
ENRICH_MAX_INFLIGHT,
|
||||
ENRICH_DISPATCH_GAP_MS,
|
||||
@@ -10,6 +12,9 @@ import {
|
||||
ENRICH_AMBIENT_PER_SWEEP,
|
||||
} from './policy.js';
|
||||
|
||||
/** A contact counts as on screen while a sphere this big around it is (m). */
|
||||
const AMBIENT_CULL_RADIUS_M = 1;
|
||||
|
||||
export function createEnrichment({
|
||||
flightState,
|
||||
services,
|
||||
@@ -183,14 +188,14 @@ export function createEnrichment({
|
||||
)
|
||||
return;
|
||||
try {
|
||||
const camera = flightState._viewer.camera;
|
||||
const camPos = camera.positionWC;
|
||||
const occluder = horizonOccluder(camera);
|
||||
const cull = camera.frustum.computeCullingVolume(
|
||||
camPos,
|
||||
camera.directionWC,
|
||||
camera.upWC,
|
||||
);
|
||||
// What is on screen, from the camera's pose: past the limb or outside
|
||||
// the view frustum is not looked at.
|
||||
const pose = findCamera(flightState._viewer)?.pose();
|
||||
if (!pose) return;
|
||||
const camPos = pose.position;
|
||||
const occluder = horizonFrom(camPos);
|
||||
const planes = frustumPlanes(pose);
|
||||
const position = vec();
|
||||
const cand = [];
|
||||
const icons = flightState._icons;
|
||||
const t = parts.icons._displayMs();
|
||||
@@ -198,21 +203,10 @@ export function createEnrichment({
|
||||
if (flightState._enrichSeen.has(`t:${icao24}`)) continue; // answered / queued / negative this session
|
||||
if (!/^[0-9a-f]{6}$/i.test(icao24)) continue; // adsbdb keys are 6-char hex only
|
||||
if (flightState.records.data.get(icao24)?.onGround) continue; // ground traffic never spends ambient budget (click-to-enrich still works)
|
||||
const position = icons.position(
|
||||
icao24,
|
||||
t,
|
||||
flightState._scratchModelBS.center,
|
||||
);
|
||||
if (!icons.position(icao24, t, position)) continue;
|
||||
if (!occluder.isPointVisible(position)) continue; // beyond the limb
|
||||
if (
|
||||
cull.computeVisibility(flightState._scratchModelBS) ===
|
||||
Cesium.Intersect.OUTSIDE
|
||||
)
|
||||
continue; // off-screen
|
||||
cand.push([
|
||||
icao24,
|
||||
Cesium.Cartesian3.distanceSquared(camPos, position),
|
||||
]);
|
||||
if (sphereOutside(planes, position, AMBIENT_CULL_RADIUS_M)) continue; // off-screen
|
||||
cand.push([icao24, distanceSquared(camPos, position)]);
|
||||
}
|
||||
cand.sort((a, b) => a[1] - b[1]); // nearest first — what the user is looking at resolves first
|
||||
const n = Math.min(
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { findCamera, findFrame, findQuery } from '../../render/rendererOf.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { distance, vec } from '../../geo/vector.js';
|
||||
import { FOCUS_EVIDENCE_DEV } from './policy.js';
|
||||
import {
|
||||
aircraftRecessionFactors,
|
||||
@@ -21,18 +23,14 @@ export function createEvidence({
|
||||
cartesian.length >= 3 &&
|
||||
cartesian.slice(0, 3).every(Number.isFinite)
|
||||
) {
|
||||
return Cesium.Cartesian3.fromElements(
|
||||
cartesian[0],
|
||||
cartesian[1],
|
||||
cartesian[2],
|
||||
);
|
||||
return vec(cartesian[0], cartesian[1], cartesian[2]);
|
||||
}
|
||||
if (
|
||||
!Number.isFinite(record?.longitude) ||
|
||||
!Number.isFinite(record?.latitude)
|
||||
)
|
||||
return null;
|
||||
return Cesium.Cartesian3.fromDegrees(
|
||||
return fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
Number.isFinite(record.altitudeM) ? record.altitudeM : 3_000,
|
||||
@@ -75,7 +73,7 @@ export function createEvidence({
|
||||
const klass = record.klass || 'airliner';
|
||||
const altitudeM = Number.isFinite(record.altitudeM)
|
||||
? record.altitudeM
|
||||
: Cesium.Cartographic.fromCartesian(position)?.height || 3_000;
|
||||
: toLonLatH(position)?.height || 3_000;
|
||||
const meta = {
|
||||
callsign: String(record.callsign || id).toUpperCase(),
|
||||
altitude: altitudeM,
|
||||
@@ -99,7 +97,7 @@ export function createEvidence({
|
||||
}
|
||||
flightState.feed._count = icons.count;
|
||||
flightState._lastFleetTickMs = 0;
|
||||
flightState._viewer.scene.requestRender?.();
|
||||
findFrame(flightState._viewer)?.requestRender('flights: focus evidence');
|
||||
return { ok: true, count: flightState.feed._count };
|
||||
}
|
||||
|
||||
@@ -127,7 +125,8 @@ export function createEvidence({
|
||||
moved += 1;
|
||||
}
|
||||
flightState._lastFleetTickMs = 0;
|
||||
flightState._viewer?.scene?.requestRender?.();
|
||||
if (flightState._viewer)
|
||||
findFrame(flightState._viewer)?.requestRender('flights: focus evidence');
|
||||
return { ok: true, moved };
|
||||
}
|
||||
|
||||
@@ -136,19 +135,19 @@ export function createEvidence({
|
||||
function _focusEvidenceSnapshot() {
|
||||
if (!FOCUS_EVIDENCE_DEV || !flightState._viewer) return [];
|
||||
const icons = flightState._icons;
|
||||
const { scene, camera } = flightState._viewer;
|
||||
const pose = findCamera(flightState._viewer)?.pose();
|
||||
const query = findQuery(flightState._viewer);
|
||||
if (!pose || !query) return [];
|
||||
const occluder = parts.icons._occluder();
|
||||
const cameraHeightM = camera.positionCartographic?.height;
|
||||
const cameraHeightM = pose.height;
|
||||
return [...flightState._focusEvidenceIds].map((id) => {
|
||||
const position = icons?.has(id)
|
||||
? parts.icons._iconPosition(id, new Cesium.Cartesian3())
|
||||
? parts.icons._iconPosition(id, vec())
|
||||
: null;
|
||||
const cameraDistanceM = position
|
||||
? Cesium.Cartesian3.distance(camera.positionWC, position)
|
||||
: null;
|
||||
const screen = position
|
||||
? Cesium.SceneTransforms.worldToWindowCoordinates(scene, position)
|
||||
? distance(pose.position, position)
|
||||
: null;
|
||||
const screen = position ? query.project(position) : null;
|
||||
// What the icon shader composes: base scale × limb taper, and base
|
||||
// alpha × max(floor, focus × limb haze).
|
||||
const factors = position
|
||||
|
||||
@@ -240,6 +240,7 @@ export function createLifecycle({
|
||||
}
|
||||
parts.rendering._releaseModels();
|
||||
parts.icons._disposeIcons();
|
||||
parts.tracking._disposeTrackedIcon();
|
||||
parts.rendering._disposeModelSets();
|
||||
flightState._grounded.clear();
|
||||
flightState._floorPinned.clear();
|
||||
|
||||
+119
-120
@@ -1,4 +1,29 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { findCamera, rendererOf } from '../../render/rendererOf.js';
|
||||
import { renderedFrames } from '../../data/renderedFrames.js';
|
||||
import {
|
||||
fromDegrees,
|
||||
fromRadians,
|
||||
toCartographicRadians,
|
||||
toLonLatH,
|
||||
} from '../../geo/ellipsoid.js';
|
||||
import { eastNorthUp, framePoint } from '../../geo/frames.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThan,
|
||||
julianNow,
|
||||
secondsDifference,
|
||||
} from '../../geo/julian.js';
|
||||
import {
|
||||
add,
|
||||
clamp,
|
||||
copyInto,
|
||||
distance,
|
||||
lerpInto,
|
||||
scale,
|
||||
sub,
|
||||
toDegrees,
|
||||
vec,
|
||||
} from '../../geo/vector.js';
|
||||
import {
|
||||
COURSE_HOLD_SPEED_MPS,
|
||||
lerpAngleDeg,
|
||||
@@ -45,6 +70,9 @@ import {
|
||||
fixTrackDeg,
|
||||
} from '../../data/aircraftMotionRegime.js';
|
||||
|
||||
/** Whether two ECEF points are the same point, component for component. */
|
||||
const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;
|
||||
|
||||
/** Where a flights record carries its reported speed and track. */
|
||||
const RECORD_FIELDS = { speed: 'velocity', track: 'true_track' };
|
||||
|
||||
@@ -69,9 +97,27 @@ export function createMotion({
|
||||
const {
|
||||
nearFarScalarValueAtDistance,
|
||||
clearFocusTarget,
|
||||
publishFocusTargetFromCachedPosition,
|
||||
publishFocusTargetAt,
|
||||
} = services.focus;
|
||||
|
||||
/** The camera's pose, or null without a camera to ask. */
|
||||
function _pose() {
|
||||
const viewer = flightState._viewer;
|
||||
try {
|
||||
return (viewer && findCamera(viewer)?.pose()) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The renderer canvas's CSS height (the viewer's own canvas when no
|
||||
* renderer is bound), or 0 without either. */
|
||||
function _viewportHeightPx() {
|
||||
const viewer = flightState._viewer;
|
||||
const canvas = rendererOf(viewer)?.canvas ?? viewer?.canvas;
|
||||
return Number(canvas?.clientHeight) || 0;
|
||||
}
|
||||
|
||||
// Fixes leave the cache with their history; corrected positions invalidate
|
||||
// the local frame even when the existing Cartesian is mutated in place.
|
||||
const fixFrames = new WeakMap();
|
||||
@@ -112,15 +158,10 @@ export function createMotion({
|
||||
)
|
||||
continue;
|
||||
info.renderAltitudeM = lifted;
|
||||
const position = Cesium.Cartesian3.fromDegrees(
|
||||
info.rawLon,
|
||||
info.rawLat,
|
||||
lifted,
|
||||
);
|
||||
const position = fromDegrees(info.rawLon, info.rawLat, lifted);
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const newest = history?.[history.length - 1];
|
||||
if (newest)
|
||||
newest.position = Cesium.Cartesian3.clone(position, newest.position);
|
||||
if (newest) newest.position = copyInto(position, newest.position);
|
||||
// Above the ellipsoid now (or floors say otherwise next poll).
|
||||
parts.icons._applyIconPresentation(icao24);
|
||||
parts.icons._planIcon(icao24);
|
||||
@@ -139,24 +180,19 @@ export function createMotion({
|
||||
* position toward the corrected fix before projecting forward.
|
||||
*
|
||||
* @param {string} icao24 - ICAO 24-bit transponder address of the aircraft.
|
||||
* @returns {Cesium.Cartesian3|null} Estimated ECEF position, or null if no history exists.
|
||||
* @returns {{x: number, y: number, z: number}|null} Estimated ECEF position, or null if no history exists.
|
||||
*/
|
||||
|
||||
function _deadReckon(icao24, result, sampledRenderTime) {
|
||||
const info = flightState.records.data.get(icao24);
|
||||
if (FOCUS_EVIDENCE_DEV && flightState._focusEvidenceIds.has(icao24)) {
|
||||
const position = parts.icons._iconPosition(
|
||||
icao24,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const position = parts.icons._iconPosition(icao24, vec());
|
||||
flightState._drCourseDeg = info?.true_track || 0;
|
||||
flightState._drSpeedMps = info?.velocity || 0;
|
||||
flightState._drCourseHold =
|
||||
flightState._drSpeedMps < COURSE_HOLD_SPEED_MPS;
|
||||
flightState._drExtrapolating = false;
|
||||
return position
|
||||
? Cesium.Cartesian3.clone(position, result || new Cesium.Cartesian3())
|
||||
: null;
|
||||
return position ? copyInto(position, result || vec()) : null;
|
||||
}
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
if (!history || history.length === 0) {
|
||||
@@ -167,13 +203,13 @@ export function createMotion({
|
||||
return null;
|
||||
}
|
||||
|
||||
const out = result || new Cesium.Cartesian3();
|
||||
const out = result || vec();
|
||||
// Render one poll interval behind real time so we interpolate between
|
||||
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
|
||||
const renderTime =
|
||||
sampledRenderTime ??
|
||||
Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(flightState._scratchRenderTime),
|
||||
addSeconds(
|
||||
julianNow(flightState._scratchRenderTime),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
@@ -181,10 +217,7 @@ export function createMotion({
|
||||
const regime = _motionRegime(history, info, renderTime);
|
||||
if (regime.kind === 'between') {
|
||||
const { a, b, span } = regime;
|
||||
const t =
|
||||
span > 0
|
||||
? Cesium.JulianDate.secondsDifference(renderTime, a.time) / span
|
||||
: 1.0;
|
||||
const t = span > 0 ? secondsDifference(renderTime, a.time) / span : 1.0;
|
||||
const trackCourse = lerpAngleDeg(regime.trackFrom, regime.trackTo, t);
|
||||
flightState._drCourseDeg =
|
||||
regime.chordCourse != null
|
||||
@@ -193,10 +226,10 @@ export function createMotion({
|
||||
flightState._drSpeedMps = regime.speed;
|
||||
flightState._drCourseHold = regime.speed < COURSE_HOLD_SPEED_MPS;
|
||||
flightState._drExtrapolating = false;
|
||||
return Cesium.Cartesian3.lerp(a.position, b.position, t, out);
|
||||
return lerpInto(a.position, b.position, t, out);
|
||||
}
|
||||
const dt = Cesium.Math.clamp(
|
||||
Cesium.JulianDate.secondsDifference(renderTime, regime.fix.time),
|
||||
const dt = clamp(
|
||||
secondsDifference(renderTime, regime.fix.time),
|
||||
regime.minDt,
|
||||
regime.maxDt,
|
||||
);
|
||||
@@ -238,43 +271,26 @@ export function createMotion({
|
||||
flightState._drExtrapolating = true;
|
||||
if (speed === 0 || dt === 0) {
|
||||
flightState._drCourseDeg = heading;
|
||||
return Cesium.Cartesian3.clone(fix.position, out);
|
||||
return copyInto(fix.position, out);
|
||||
}
|
||||
// Constant-rate-turn arc (straight line when turnRateDps ≈ 0) — a plane in a
|
||||
// standard-rate turn is ~90° of arc wrong per 30 s if extrapolated straight.
|
||||
arcOffsetEnu(speed, heading, turnRateDps, dt, flightState._scratchArc);
|
||||
flightState._drCourseDeg = flightState._scratchArc.endCourseDeg;
|
||||
Cesium.Cartesian3.fromElements(
|
||||
flightState._scratchArc.east,
|
||||
flightState._scratchArc.north,
|
||||
0,
|
||||
flightState._scratchOffset,
|
||||
);
|
||||
const offset = flightState._scratchOffset;
|
||||
offset.x = flightState._scratchArc.east;
|
||||
offset.y = flightState._scratchArc.north;
|
||||
offset.z = 0;
|
||||
let frame = fixFrames.get(fix);
|
||||
if (!frame) {
|
||||
frame = {
|
||||
position: new Cesium.Cartesian3(),
|
||||
matrix: new Cesium.Matrix4(),
|
||||
};
|
||||
frame = { position: vec(), enu: null };
|
||||
fixFrames.set(fix, frame);
|
||||
}
|
||||
if (
|
||||
!frame.valid ||
|
||||
!Cesium.Cartesian3.equals(frame.position, fix.position)
|
||||
) {
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
fix.position,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
frame.matrix,
|
||||
);
|
||||
Cesium.Cartesian3.clone(fix.position, frame.position);
|
||||
frame.valid = true;
|
||||
if (!frame.enu || !samePoint(frame.position, fix.position)) {
|
||||
frame.enu = eastNorthUp(fix.position);
|
||||
copyInto(fix.position, frame.position);
|
||||
}
|
||||
return Cesium.Matrix4.multiplyByPoint(
|
||||
frame.matrix,
|
||||
flightState._scratchOffset,
|
||||
out,
|
||||
);
|
||||
return copyInto(framePoint(frame.enu, offset), out);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -289,21 +305,21 @@ export function createMotion({
|
||||
if (!flightState._trackedIcao) return false;
|
||||
const history = flightState._positionHistory.get(flightState._trackedIcao);
|
||||
if (!history || history.length === 0) return true;
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
const renderTime = addSeconds(
|
||||
julianNow(),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
return Cesium.JulianDate.lessThan(renderTime, history[0].time);
|
||||
return julianLessThan(renderTime, history[0].time);
|
||||
}
|
||||
|
||||
/** Resolve the selected aircraft's actual rendered square extent this frame. */
|
||||
|
||||
function _trackedFocusSizePx(icao24, position) {
|
||||
const camera = flightState._viewer?.camera;
|
||||
const scene = flightState._viewer?.scene;
|
||||
if (!camera?.positionWC || !position || !scene) return 28;
|
||||
const rangeM = Cesium.Cartesian3.distance(camera.positionWC, position);
|
||||
const pose = _pose();
|
||||
if (!pose || !position) return 28;
|
||||
const rangeM = distance(pose.position, position);
|
||||
const viewportHeightPx = _viewportHeightPx();
|
||||
if (parts.rendering._modelOwnsVisual(icao24)) {
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(icao24)?.klass,
|
||||
@@ -312,12 +328,11 @@ export function createMotion({
|
||||
baseScale: spec.scale,
|
||||
nativeRadiusM: spec.nativeRadiusM,
|
||||
rangeM,
|
||||
viewportHeightPx: scene.canvas.clientHeight,
|
||||
fovyRad: camera.frustum.fovy,
|
||||
viewportHeightPx,
|
||||
fovyRad: pose.fovy,
|
||||
maximumPixelSize: TRACKED_MODEL_MAX_PX,
|
||||
});
|
||||
const focalLengthPx =
|
||||
scene.canvas.clientHeight / (2 * Math.tan(camera.frustum.fovy / 2));
|
||||
const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2));
|
||||
const projectedDiameterPx =
|
||||
(2 * spec.nativeRadiusM * scale * focalLengthPx) / rangeM;
|
||||
return Math.max(
|
||||
@@ -339,16 +354,16 @@ export function createMotion({
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by Cesium
|
||||
* frame number so the position / rotation / trail-head callbacks share ONE computation
|
||||
* Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by drawn
|
||||
* frame (see renderedFrames.js) so the position / rotation / trail-head callbacks share ONE computation
|
||||
* (and one reconciliation-state update) per frame. Returns a stable module holder, or
|
||||
* null when the aircraft has no fix.
|
||||
* @param {string} icao24
|
||||
* @returns {Cesium.Cartesian3|null}
|
||||
* @returns {{x: number, y: number, z: number}|null}
|
||||
*/
|
||||
|
||||
function _trackedDisplayPosition(icao24) {
|
||||
const frame = flightState._viewer?.scene?.frameState?.frameNumber ?? -1;
|
||||
const frame = renderedFrames(flightState._viewer);
|
||||
if (
|
||||
frame === flightState._cachedDRFrame &&
|
||||
icao24 === flightState._drReconcileIcao
|
||||
@@ -379,29 +394,26 @@ export function createMotion({
|
||||
const speed = (info && info.velocity) || 0;
|
||||
// Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base.
|
||||
const plausible = speed * dtSec * 4 + 25;
|
||||
if (Cesium.Cartesian3.distance(raw, flightState._drPrevRaw) > plausible) {
|
||||
if (distance(raw, flightState._drPrevRaw) > plausible) {
|
||||
// Discontinuity — re-anchor so the DISPLAYED position stays continuous, then decay.
|
||||
Cesium.Cartesian3.subtract(
|
||||
flightState._drPrevDisplay,
|
||||
raw,
|
||||
copyInto(
|
||||
sub(flightState._drPrevDisplay, raw),
|
||||
flightState._drCorrection,
|
||||
);
|
||||
flightState._drCorrectionStartMs = nowMs;
|
||||
}
|
||||
} else {
|
||||
Cesium.Cartesian3.fromElements(0, 0, 0, flightState._drCorrection);
|
||||
copyInto(vec(), flightState._drCorrection);
|
||||
flightState._drCorrectionStartMs = nowMs - DR_CORRECTION_MS; // fully decayed
|
||||
}
|
||||
|
||||
const elapsed = nowMs - flightState._drCorrectionStartMs;
|
||||
const factor =
|
||||
elapsed >= DR_CORRECTION_MS ? 0 : 1 - elapsed / DR_CORRECTION_MS;
|
||||
let display = Cesium.Cartesian3.multiplyByScalar(
|
||||
flightState._drCorrection,
|
||||
factor,
|
||||
let display = copyInto(
|
||||
add(raw, scale(flightState._drCorrection, factor)),
|
||||
flightState._trackedPosHolder,
|
||||
);
|
||||
Cesium.Cartesian3.add(raw, display, display);
|
||||
// Same display floor the fleet pass applies — otherwise selecting a correctly
|
||||
// floored grounded billboard swapped it for an unfloored tracked entity and
|
||||
// dropped the cyan target back under the mesh. Applied HERE, at the single
|
||||
@@ -420,8 +432,8 @@ export function createMotion({
|
||||
nowMs,
|
||||
);
|
||||
|
||||
Cesium.Cartesian3.clone(raw, flightState._drPrevRaw);
|
||||
Cesium.Cartesian3.clone(display, flightState._drPrevDisplay);
|
||||
copyInto(raw, flightState._drPrevRaw);
|
||||
copyInto(display, flightState._drPrevDisplay);
|
||||
flightState._drPrevMs = nowMs;
|
||||
flightState._drReconcileValid = true;
|
||||
flightState._cachedDRPosition = display;
|
||||
@@ -429,14 +441,13 @@ export function createMotion({
|
||||
icao24,
|
||||
flightState._cachedDRPosition,
|
||||
);
|
||||
// Publish only the exact per-frame display cache the tracked entity/camera
|
||||
// Publish only the exact per-frame display cache the tracked billboard/camera
|
||||
// consumes. Re-running DR from a later frame phase recreates the historical
|
||||
// target-vs-camera jitter bug.
|
||||
publishFocusTargetFromCachedPosition({
|
||||
publishFocusTargetAt({
|
||||
ownerLayer: 'flights',
|
||||
id: icao24,
|
||||
scene: flightState._viewer?.scene,
|
||||
camera: flightState._viewer?.camera,
|
||||
viewer: flightState._viewer,
|
||||
displayPosition: flightState._cachedDRPosition,
|
||||
widthPx: focusSizePx,
|
||||
heightPx: focusSizePx,
|
||||
@@ -446,7 +457,7 @@ export function createMotion({
|
||||
|
||||
/** The tracked plane's current display position WITHOUT recomputing — the exact value the
|
||||
* follow-camera already settled on this frame (in the Viewer _onTick). getDetectableObjects + the
|
||||
* readout run in postRender at a LATER frameNumber, so calling _trackedDisplayPosition there would
|
||||
* readout run in postRender, later in the same frame, so calling _trackedDisplayPosition there would
|
||||
* re-run the dead-reckon on a fresh sample and double-advance the reconciliation → the label jitters
|
||||
* against the now-stable plane (the model's jitter fix, resurfacing in the labels). Returns null when
|
||||
* there's no valid fix for the tracked aircraft, so callers fall back to the icon position. */
|
||||
@@ -509,10 +520,12 @@ export function createMotion({
|
||||
!parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
)
|
||||
return null;
|
||||
return Cesium.Matrix4.getTranslation(
|
||||
flightState._trackedModel.matrix,
|
||||
flightState._scratchTrailClip,
|
||||
);
|
||||
const m = flightState._trackedModel.matrix;
|
||||
const out = flightState._scratchTrailClip;
|
||||
out.x = m[12];
|
||||
out.y = m[13];
|
||||
out.z = m[14];
|
||||
return out;
|
||||
}
|
||||
|
||||
function _trackedModelEnvelopeM() {
|
||||
@@ -747,7 +760,7 @@ export function createMotion({
|
||||
state.probeMs = null; // re-ground may probe immediately
|
||||
state.out = null;
|
||||
state.effectiveM = null;
|
||||
Cesium.Cartesian3.clone(Cesium.Cartesian3.ZERO, state.in); // invalidate the memo
|
||||
copyInto(vec(), state.in); // invalidate the memo
|
||||
} else if (_seedExpired(state, nowMs)) {
|
||||
flightState._displayFloorState.delete(icao24); // airborne long enough to be anywhere
|
||||
}
|
||||
@@ -792,11 +805,11 @@ export function createMotion({
|
||||
*
|
||||
* @param {string} icao24 - Contact key (owns one `_displayFloorState` entry).
|
||||
* @param {object|null|undefined} info - `_flightData` record for this contact.
|
||||
* @param {Cesium.Cartesian3|null} pos - Dead-reckoned display position.
|
||||
* @param {{x: number, y: number, z: number}|null} pos - Dead-reckoned display position.
|
||||
* @param {boolean} modelOwnsVisual - Whether a 3D model is drawing this contact.
|
||||
* @param {number} [nowMs] - Tick clock, passed by both callers so the release
|
||||
* ease advances on the same clock the rest of the tick uses.
|
||||
* @returns {Cesium.Cartesian3|null} `pos` itself when nothing moves (the common
|
||||
* @returns {{x: number, y: number, z: number}|null} `pos` itself when nothing moves (the common
|
||||
* case — no allocation, no rebuild), otherwise the lifted position.
|
||||
*/
|
||||
|
||||
@@ -812,22 +825,18 @@ export function createMotion({
|
||||
return pos;
|
||||
}
|
||||
const state = flightState._displayFloorState.get(icao24);
|
||||
const carto = Cesium.Cartographic.fromCartesian(
|
||||
pos,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchDisplayCarto,
|
||||
);
|
||||
const carto = toCartographicRadians(pos);
|
||||
// Boundary hysteresis: a position jittering across a cell edge would flip
|
||||
// floors at fleet-tick rate (see stickyFloorCell).
|
||||
const cell = stickyFloorCell(
|
||||
Cesium.Math.toDegrees(carto.latitude),
|
||||
Cesium.Math.toDegrees(carto.longitude),
|
||||
toDegrees(carto.lat),
|
||||
toDegrees(carto.lon),
|
||||
state?.cell,
|
||||
);
|
||||
const floor = cachedGroundFloor(cell.lat, cell.lon);
|
||||
const next = state || {
|
||||
cell,
|
||||
in: new Cesium.Cartesian3(),
|
||||
in: vec(),
|
||||
out: null,
|
||||
effectiveM: null,
|
||||
heldM: null,
|
||||
@@ -920,28 +929,21 @@ export function createMotion({
|
||||
// never adopted. One owned entry per grounded
|
||||
// contact — O(grounded), dropped on eviction, on destroy, and the moment the
|
||||
// contact stops being a grounded billboard.
|
||||
if (
|
||||
state &&
|
||||
state.effectiveM === effective &&
|
||||
Cesium.Cartesian3.equals(pos, state.in)
|
||||
) {
|
||||
if (state && state.effectiveM === effective && samePoint(pos, state.in)) {
|
||||
return state.out || pos;
|
||||
}
|
||||
const lifted = displayFloorHeightM(carto.height, effective);
|
||||
next.cell = cell;
|
||||
next.effectiveM = effective;
|
||||
Cesium.Cartesian3.clone(pos, next.in);
|
||||
copyInto(pos, next.in);
|
||||
if (lifted == null) {
|
||||
next.out = null;
|
||||
} else {
|
||||
// The cache OWNS its output: returning a shared scratch would let the next
|
||||
// contact in the fleet loop overwrite a position already handed out.
|
||||
next.out = Cesium.Cartesian3.fromRadians(
|
||||
carto.longitude,
|
||||
carto.latitude,
|
||||
lifted,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
next.out || new Cesium.Cartesian3(),
|
||||
next.out = copyInto(
|
||||
fromRadians(carto.lon, carto.lat, lifted),
|
||||
next.out || vec(),
|
||||
);
|
||||
}
|
||||
if (!state) flightState._displayFloorState.set(icao24, next);
|
||||
@@ -1024,13 +1026,10 @@ export function createMotion({
|
||||
flightState._drCourseDeg != null
|
||||
? flightState._drCourseDeg
|
||||
: info.true_track || 0;
|
||||
const c = Cesium.Cartographic.fromCartesian(
|
||||
dr,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchCorridorCarto,
|
||||
);
|
||||
const lat = Cesium.Math.toDegrees(c.latitude);
|
||||
const lon = Cesium.Math.toDegrees(c.longitude);
|
||||
const c = toLonLatH(dr);
|
||||
if (!c) continue;
|
||||
const lat = c.lat;
|
||||
const lon = c.lon;
|
||||
const cells = corridorFloorCells(
|
||||
corridorPathLatLon({
|
||||
extrapolating,
|
||||
@@ -1063,7 +1062,7 @@ export function createMotion({
|
||||
out.push(cell);
|
||||
}
|
||||
}
|
||||
/** The display instant `epochMs` as a JulianDate, for `_motionRegime`. */
|
||||
/** The display instant `epochMs` as a Julian date, for `_motionRegime`. */
|
||||
const _displayTimeAt = (epochMs, result) => julianAt(epochMs, result);
|
||||
|
||||
return {
|
||||
|
||||
@@ -10,8 +10,8 @@ function fixture() {
|
||||
_positionHistory: new Map(),
|
||||
_focusEvidenceIds: new Set(),
|
||||
_scratchArc: {},
|
||||
_scratchOffset: new Cesium.Cartesian3(),
|
||||
_scratchRenderTime: new Cesium.JulianDate(),
|
||||
_scratchOffset: { x: 0, y: 0, z: 0 },
|
||||
_scratchRenderTime: { dayNumber: 0, secondsOfDay: 0 },
|
||||
};
|
||||
const motion = createMotion({
|
||||
flightState,
|
||||
@@ -35,64 +35,55 @@ function close(actual, expected) {
|
||||
assert.ok(Cesium.Cartesian3.distance(actual, expected) < 1e-8);
|
||||
}
|
||||
|
||||
test('extrapolation reuses fixed frames and invalidates corrected coordinates', (t) => {
|
||||
test('extrapolation follows the fix frame, a corrected or replaced fix included', () => {
|
||||
const { motion } = fixture();
|
||||
const transform = Cesium.Transforms.eastNorthUpToFixedFrame;
|
||||
const spy = t.mock.method(
|
||||
Cesium.Transforms,
|
||||
'eastNorthUpToFixedFrame',
|
||||
transform,
|
||||
);
|
||||
const fix = {
|
||||
position: Cesium.Cartesian3.fromDegrees(-97, 30, 200),
|
||||
velocity: 90,
|
||||
track: 70,
|
||||
};
|
||||
const out = new Cesium.Cartesian3();
|
||||
const out = { x: 0, y: 0, z: 0 };
|
||||
for (const dt of [-30, 5, 30, 60]) {
|
||||
motion._extrapolateFix(fix, {}, dt, out, 1.5);
|
||||
close(out, expectedPosition(fix, dt, 1.5, transform));
|
||||
}
|
||||
assert.equal(spy.mock.callCount(), 1);
|
||||
|
||||
// Ground reflooring mutates an existing fix's Cartesian in place.
|
||||
// Ground reflooring mutates an existing fix's position in place: the
|
||||
// frame kept for the fix must not answer for the old coordinates.
|
||||
Cesium.Cartesian3.fromDegrees(-97, 30, 350, undefined, fix.position);
|
||||
motion._extrapolateFix(fix, {}, 30, out, 1.5);
|
||||
close(out, expectedPosition(fix, 30, 1.5, transform));
|
||||
assert.equal(spy.mock.callCount(), 2);
|
||||
|
||||
fix.position = Cesium.Cartesian3.fromDegrees(140, 80, 1000);
|
||||
motion._extrapolateFix(fix, {}, 30, out, -2);
|
||||
close(out, expectedPosition(fix, 30, -2, transform));
|
||||
assert.equal(spy.mock.callCount(), 3);
|
||||
|
||||
fix.velocity = 210;
|
||||
fix.track = 359;
|
||||
motion._extrapolateFix(fix, {}, 15, out, -1);
|
||||
close(out, expectedPosition(fix, 15, -1, transform));
|
||||
assert.equal(spy.mock.callCount(), 3);
|
||||
|
||||
const replacement = { ...fix };
|
||||
motion._extrapolateFix(replacement, {}, 15, out, -1);
|
||||
close(out, expectedPosition(replacement, 15, -1, transform));
|
||||
assert.equal(spy.mock.callCount(), 4);
|
||||
});
|
||||
|
||||
test('stationary fixes do not build a frame until motion needs it', (t) => {
|
||||
test('stationary fixes stay at the fix', () => {
|
||||
const { motion } = fixture();
|
||||
const spy = t.mock.method(Cesium.Transforms, 'eastNorthUpToFixedFrame');
|
||||
const fix = {
|
||||
position: Cesium.Cartesian3.fromDegrees(0, 0, 0),
|
||||
velocity: 0,
|
||||
track: 90,
|
||||
};
|
||||
const out = new Cesium.Cartesian3();
|
||||
const out = { x: 0, y: 0, z: 0 };
|
||||
close(motion._extrapolateFix(fix, {}, 30, out), fix.position);
|
||||
fix.velocity = 10;
|
||||
close(motion._extrapolateFix(fix, {}, 0, out), fix.position);
|
||||
assert.equal(spy.mock.callCount(), 0);
|
||||
motion._extrapolateFix(fix, {}, 30, out);
|
||||
assert.equal(spy.mock.callCount(), 1);
|
||||
close(
|
||||
motion._extrapolateFix(fix, {}, 30, out),
|
||||
expectedPosition(fix, 30, 0, Cesium.Transforms.eastNorthUpToFixedFrame),
|
||||
);
|
||||
});
|
||||
|
||||
test('fleet render time is shared without resampling or mutating the supplied instant', (t) => {
|
||||
@@ -121,7 +112,7 @@ test('fleet render time is shared without resampling or mutating the supplied in
|
||||
flightState.records.data.set(id, { velocity: 100, true_track: 90 });
|
||||
flightState._positionHistory.set(id, history);
|
||||
}
|
||||
t.mock.method(Cesium.JulianDate, 'now', () => {
|
||||
t.mock.method(Date, 'now', () => {
|
||||
throw new Error('unexpected per-contact clock read');
|
||||
});
|
||||
const expected = Cesium.Cartesian3.lerp(
|
||||
@@ -156,10 +147,8 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
|
||||
flightState.records.data.set('tracked', { velocity: 100, true_track: 90 });
|
||||
flightState._positionHistory.set('tracked', history);
|
||||
let elapsed = 60;
|
||||
const spy = t.mock.method(Cesium.JulianDate, 'now', (result) => {
|
||||
assert.equal(result, flightState._scratchRenderTime);
|
||||
return Cesium.JulianDate.addSeconds(start, elapsed, result);
|
||||
});
|
||||
const startMs = Cesium.JulianDate.toDate(start).getTime();
|
||||
const spy = t.mock.method(Date, 'now', () => startMs + elapsed * 1000);
|
||||
const out = new Cesium.Cartesian3();
|
||||
close(
|
||||
motion._deadReckon('tracked', out),
|
||||
@@ -181,4 +170,11 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
|
||||
),
|
||||
);
|
||||
assert.equal(spy.mock.callCount(), 2);
|
||||
// Sampled into the layer's scratch, not a new date.
|
||||
assert.ok(
|
||||
Cesium.JulianDate.equals(
|
||||
flightState._scratchRenderTime,
|
||||
Cesium.JulianDate.addSeconds(start, 45, new Cesium.JulianDate()),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -64,7 +64,7 @@ test('flight state owns distinct mutable records, scratch objects and floor samp
|
||||
'_positionHistory',
|
||||
'_displayFloorState',
|
||||
'_groundSnap',
|
||||
'_scratchCarto',
|
||||
'_scratchNearbyPos',
|
||||
'_models',
|
||||
'lifetime',
|
||||
]) {
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
|
||||
/** A CSS colour as frozen `[r, g, b, a]`, 0..1 (the renderer's `Color`). */
|
||||
const rgba = (css, alpha) =>
|
||||
Object.freeze(
|
||||
alpha === undefined ? cssColor(css) : [...cssColor(css).slice(0, 3), alpha],
|
||||
);
|
||||
|
||||
export const FOCUS_EVIDENCE_DEV = import.meta.env?.DEV === true;
|
||||
|
||||
/** Amber tint for known-military aircraft rendered by this layer (matches the military layer's icon color). */
|
||||
|
||||
export const MIL_TINT = Cesium.Color.fromCssColorString('#FFB800');
|
||||
export const MIL_TINT = rgba('#FFB800');
|
||||
|
||||
/** Red tint for aircraft broadcasting an emergency (7500/7600/7700 or ADS-B status). */
|
||||
|
||||
export const EMERGENCY_TINT =
|
||||
Cesium.Color.fromCssColorString(EMERGENCY_TINT_CSS);
|
||||
export const EMERGENCY_TINT = rgba(EMERGENCY_TINT_CSS);
|
||||
|
||||
// --- Ground traffic (owner reversal 2026-07-03: "absolutely we should see planes
|
||||
// taxiing and landing") -----------------------------------------------------------
|
||||
@@ -90,7 +95,7 @@ export const MODEL_ALL_KEEP_M = 450000;
|
||||
// all: KEEP modeled planes out to 450 km
|
||||
|
||||
export const MODEL_HEADING_OFFSET_DEG = 180;
|
||||
// airplane.glb nose is opposite Cesium heading-0
|
||||
// airplane.glb nose is opposite the renderer's heading 0
|
||||
// Owner launch-polish direction: models should read as clean light silhouettes,
|
||||
// with only a weak diffuse contribution from the existing approved textures.
|
||||
|
||||
@@ -106,22 +111,22 @@ export const MODEL_COLOR_BLEND_AMOUNT = 0.94;
|
||||
export const MODEL_BELLY_OFFSET_NATIVE = 6.719;
|
||||
|
||||
/** The tracked contact's tint, and its billboard once a model takes over. */
|
||||
export const TRACKED_CYAN = Cesium.Color.CYAN;
|
||||
export const CYAN_TRANSPARENT = Cesium.Color.CYAN.withAlpha(0);
|
||||
export const TRACKED_CYAN = rgba('#00FFFF');
|
||||
export const CYAN_TRANSPARENT = rgba('#00FFFF', 0);
|
||||
/** An ordinary fleet contact's tint. */
|
||||
export const FLEET_TINT = Cesium.Color.WHITE;
|
||||
export const FLEET_TINT = rgba('#FFFFFF');
|
||||
|
||||
export const COCKPIT_CONTACT_SIZE_PX = 6;
|
||||
|
||||
export const COCKPIT_CIVILIAN_COLOR =
|
||||
Cesium.Color.fromCssColorString('#DCEEFF');
|
||||
export const COCKPIT_CIVILIAN_COLOR = rgba('#DCEEFF');
|
||||
|
||||
export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = new Cesium.NearFarScalar(
|
||||
1000,
|
||||
3.0,
|
||||
8000000,
|
||||
0.5,
|
||||
);
|
||||
/** The tracked billboard's size by eye distance (the renderer's `NearFar`). */
|
||||
export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = Object.freeze({
|
||||
near: 1000,
|
||||
nearValue: 3.0,
|
||||
far: 8000000,
|
||||
farValue: 0.5,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Track-history trail state (PRD WS-F F1/F4): a fading polyline behind the
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { cameraOf } from '../../render/cesium/camera.js';
|
||||
import { cameraOf, findFrame } from '../../render/rendererOf.js';
|
||||
import { followedOf } from '../../data/followed.js';
|
||||
import { approxDistanceKm as _approxDistanceKm } from './recordPolicy.js';
|
||||
import { displayedKinematics } from '../../data/motionModel.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { closeRenderLoopLatch } from '../../render/cesium/internals.js';
|
||||
import { toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { clone, distance as distanceBetween, vec } from '../../geo/vector.js';
|
||||
import { isExplicitLayerStateOrigin } from '../../data/layerState.js';
|
||||
import { modelVisualAnchor } from '../../data/modelVisualAnchor.js';
|
||||
import {
|
||||
@@ -116,7 +116,7 @@ export function createQueries({
|
||||
* Build a public descriptor for one aircraft using its best current position
|
||||
* (dead-reckoned when history exists, billboard position otherwise).
|
||||
* @param {string} icao24 - ICAO 24-bit transponder address.
|
||||
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
|
||||
* @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
|
||||
* Descriptor with a cloned position, or null if the aircraft is unknown.
|
||||
*/
|
||||
|
||||
@@ -136,7 +136,7 @@ export function createQueries({
|
||||
const info = flightState.records.data.get(icao24);
|
||||
const basePos =
|
||||
parts.motion._deadReckon(icao24) ||
|
||||
parts.icons._iconPosition(icao24, new Cesium.Cartesian3());
|
||||
parts.icons._iconPosition(icao24, vec());
|
||||
if (!basePos) return null;
|
||||
const displayed = displayedKinematics({
|
||||
derivedSpeedMps: flightState._drSpeedMps,
|
||||
@@ -144,18 +144,14 @@ export function createQueries({
|
||||
reportedSpeedMps: info?.velocity,
|
||||
reportedTrackDeg: info?.true_track,
|
||||
});
|
||||
const carto = Cesium.Cartographic.fromCartesian(
|
||||
basePos,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchCarto,
|
||||
);
|
||||
const carto = toLonLatH(basePos);
|
||||
if (!carto) return null;
|
||||
return {
|
||||
icao24,
|
||||
callsign: String(info?.callsign || '').trim() || null,
|
||||
position: Cesium.Cartesian3.clone(basePos),
|
||||
latitude: Cesium.Math.toDegrees(carto.latitude),
|
||||
longitude: Cesium.Math.toDegrees(carto.longitude),
|
||||
position: clone(basePos),
|
||||
latitude: carto.lat,
|
||||
longitude: carto.lon,
|
||||
// The cockpit instrument reports aviation altitude, not the Cesium
|
||||
// ellipsoid height of the camera/ground-clamped render position. The
|
||||
// latter can be slightly negative over terrain near the surface.
|
||||
@@ -414,7 +410,7 @@ export function createQueries({
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.maxCount] - Maximum number of objects to return.
|
||||
* @param {number} [options.seed] - Deterministic offset into the stride pattern.
|
||||
* @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean}>}
|
||||
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean}>}
|
||||
*/
|
||||
getDetectableObjects(options = {}) {
|
||||
const icons = flightState._icons;
|
||||
@@ -457,8 +453,8 @@ export function createQueries({
|
||||
object = {
|
||||
sourceId: icao24,
|
||||
type: 'AIR',
|
||||
_weldPos: new Cesium.Cartesian3(),
|
||||
_iconPos: new Cesium.Cartesian3(),
|
||||
_weldPos: vec(),
|
||||
_iconPos: vec(),
|
||||
};
|
||||
flightState._detectionObjects.set(icao24, object);
|
||||
}
|
||||
@@ -485,7 +481,7 @@ export function createQueries({
|
||||
spec,
|
||||
(view ??= parts.rendering._drawnScaleView()),
|
||||
),
|
||||
object._weldPos || (object._weldPos = new Cesium.Cartesian3()),
|
||||
object._weldPos || (object._weldPos = vec()),
|
||||
)
|
||||
: icons.position(icao24, t, object._iconPos);
|
||||
// An icon past the horizon is not drawn, so it is not detectable.
|
||||
@@ -533,7 +529,7 @@ export function createQueries({
|
||||
* Match priority: exact icao24 hex, exact callsign, callsign prefix,
|
||||
* then callsign substring (all case-insensitive, trimmed).
|
||||
* @param {string} query - ICAO24 hex or full/partial callsign.
|
||||
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
|
||||
* @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
|
||||
* Best match with a cloned, dead-reckoned position, or null if none.
|
||||
*/
|
||||
findByQuery(query) {
|
||||
@@ -574,12 +570,12 @@ export function createQueries({
|
||||
/**
|
||||
* Find aircraft near a given ECEF position, sorted ascending by distance.
|
||||
* Return shape mirrors militaryFlightsLayer.getNearby (id/icao24/position/distance).
|
||||
* @param {Cesium.Cartesian3} center - Reference position in ECEF coordinates.
|
||||
* @param {{x: number, y: number, z: number}} center - Reference position in ECEF coordinates.
|
||||
* @param {number} range - Maximum distance in meters (Infinity if not finite).
|
||||
* @param {number} [maxCount=50] - Maximum number of results to return.
|
||||
* @param {object} [options] Query membership options.
|
||||
* @param {boolean} [options.includeHidden=false] Include loaded horizon-hidden aircraft.
|
||||
* @returns {Array<{id: string, icao24: string, callsign: string|null, position: Cesium.Cartesian3, distance: number, aircraftClass: string|null, altitudeM: number|null, velocityMps: number|null, track: number|null}>}
|
||||
* @returns {Array<{id: string, icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, distance: number, aircraftClass: string|null, altitudeM: number|null, velocityMps: number|null, track: number|null}>}
|
||||
*/
|
||||
getNearby(center, range, maxCount = 50, { includeHidden = false } = {}) {
|
||||
const icons = flightState._icons;
|
||||
@@ -615,9 +611,9 @@ export function createQueries({
|
||||
)
|
||||
continue;
|
||||
|
||||
const distance = Cesium.Cartesian3.distance(center, drawn);
|
||||
const distance = distanceBetween(center, drawn);
|
||||
if (distance > maxRange) continue;
|
||||
const pos = trackedPos || Cesium.Cartesian3.clone(drawn);
|
||||
const pos = trackedPos || clone(drawn);
|
||||
|
||||
const info = flightState.records.data.get(icao24);
|
||||
const callsign = info?.callsign?.trim() || null;
|
||||
@@ -652,7 +648,7 @@ export function createQueries({
|
||||
* Cheap snapshot for voice-tool framing — drawn icon positions, no
|
||||
* extra dead reckoning.
|
||||
* @param {number} [maxCount=500] - Maximum number of entries to return.
|
||||
* @returns {Array<{id: string, label: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number}>}
|
||||
* @returns {Array<{id: string, label: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number}>}
|
||||
*/
|
||||
/**
|
||||
* Whether this layer still carries a contact, in O(1).
|
||||
@@ -686,20 +682,16 @@ export function createQueries({
|
||||
|
||||
const result = [];
|
||||
for (const icao24 of icons.ids()) {
|
||||
const pos = icons.position(icao24, t, new Cesium.Cartesian3());
|
||||
const carto = Cesium.Cartographic.fromCartesian(
|
||||
pos,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchCarto,
|
||||
);
|
||||
const pos = icons.position(icao24, t, vec());
|
||||
const carto = toLonLatH(pos);
|
||||
if (!carto) continue;
|
||||
const info = flightState.records.data.get(icao24);
|
||||
result.push({
|
||||
id: icao24, // identity (trackById resolves this)
|
||||
label: _contactLabel(icao24, info),
|
||||
position: pos,
|
||||
latitude: Cesium.Math.toDegrees(carto.latitude),
|
||||
longitude: Cesium.Math.toDegrees(carto.longitude),
|
||||
latitude: carto.lat,
|
||||
longitude: carto.lon,
|
||||
altitudeM: carto.height,
|
||||
airline: info?.airline ?? null,
|
||||
typeName: info?.typeName ?? null,
|
||||
@@ -831,7 +823,6 @@ export function createQueries({
|
||||
if (!flightState._icons?.has(id)) id = id.toLowerCase();
|
||||
if (
|
||||
id !== flightState._trackedIcao ||
|
||||
!flightState._viewer.entities?.contains?.(flightState._trackedEntity) ||
|
||||
followedOf(flightState._viewer) !== flightState._followTarget
|
||||
)
|
||||
return false;
|
||||
@@ -873,7 +864,7 @@ export function createQueries({
|
||||
/**
|
||||
* Return the current aircraft as a Context subject without changing
|
||||
* tracking or camera ownership.
|
||||
* @returns {{layerId: string, id: string, label: string, position: Cesium.Cartesian3}|null}
|
||||
* @returns {{layerId: string, id: string, label: string, position: {x: number, y: number, z: number}}|null}
|
||||
* Detached subject descriptor, or null when no aircraft is tracked.
|
||||
*/
|
||||
getTrackedSubject() {
|
||||
@@ -889,7 +880,7 @@ export function createQueries({
|
||||
described.callsign ||
|
||||
_toCleanText(described.registration) ||
|
||||
described.icao24,
|
||||
position: Cesium.Cartesian3.clone(described.position),
|
||||
position: clone(described.position),
|
||||
};
|
||||
},
|
||||
|
||||
@@ -914,17 +905,14 @@ export function createQueries({
|
||||
takeFrameClock(startMs = 1_000_000_000) {
|
||||
if (!flightState._viewer || !Number.isFinite(startMs))
|
||||
return { ok: false, nowMs: null };
|
||||
flightState._viewer.useDefaultRenderLoop = false;
|
||||
// The loop stops ticking; evidence frames are drawn by hand.
|
||||
findFrame(flightState._viewer)?.suspend(true);
|
||||
setFocusEvidenceNowMs(startMs);
|
||||
flightState._lastFleetTickMs = startMs - FLEET_DR_INTERVAL_MS;
|
||||
// Cross a browser task boundary, then close Cesium's pending-loop
|
||||
// latch. Any already-queued callback still observes the false gate,
|
||||
// while manual evidence renders can begin without waiting on VSYNC.
|
||||
// Cross a browser task boundary, so a loop callback already
|
||||
// queued has seen the stopped loop before manual renders begin.
|
||||
return new Promise((resolve) =>
|
||||
setTimeout(() => {
|
||||
closeRenderLoopLatch(flightState._viewer);
|
||||
resolve({ ok: true, nowMs: startMs });
|
||||
}, 0),
|
||||
setTimeout(() => resolve({ ok: true, nowMs: startMs }), 0),
|
||||
);
|
||||
},
|
||||
advanceFrameClock(deltaMs = FLEET_DR_INTERVAL_MS) {
|
||||
@@ -933,7 +921,7 @@ export function createQueries({
|
||||
releaseFrameClock() {
|
||||
setFocusEvidenceNowMs(null);
|
||||
if (flightState._viewer)
|
||||
flightState._viewer.useDefaultRenderLoop = true;
|
||||
findFrame(flightState._viewer)?.suspend(false);
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
@@ -79,8 +79,7 @@ function fixture() {
|
||||
formats: () => formats,
|
||||
place,
|
||||
show: (shown) => icons.setShown('abc123', shown),
|
||||
drawn: () =>
|
||||
parts.icons._iconPosition('abc123', new Cesium.Cartesian3()),
|
||||
drawn: () => parts.icons._iconPosition('abc123', { x: 0, y: 0, z: 0 }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -92,7 +91,7 @@ test('candidate text follows in-place enrichment without freezing identity or po
|
||||
f.place(new Cesium.Cartesian3(4, 5, 6));
|
||||
assert.equal(f.queries.getDetectableObjects()[0], first);
|
||||
assert.deepEqual(first.position, f.drawn());
|
||||
assert.deepEqual(first.position, new Cesium.Cartesian3(4, 5, 6));
|
||||
assert.deepEqual(first.position, { x: 4, y: 5, z: 6 });
|
||||
assert.equal(f.formats(), 1);
|
||||
f.info.callsign = ' NEW456 ';
|
||||
assert.equal(f.queries.getDetectableObjects()[0].id, 'NEW456');
|
||||
@@ -141,10 +140,10 @@ test('candidate collection resolves models once and keeps handoffs live', (t) =>
|
||||
assert.deepEqual(f.queries.getDetectableObjects(), []);
|
||||
record.ready = true;
|
||||
assert.equal(f.queries.getDetectableObjects()[0], candidate);
|
||||
assert.deepEqual(candidate.position, new Cesium.Cartesian3(10, 20, 30));
|
||||
assert.deepEqual(candidate.position, { x: 10, y: 20, z: 30 });
|
||||
placeAt(record, new Cesium.Cartesian3(40, 50, 60));
|
||||
f.queries.getDetectableObjects();
|
||||
assert.deepEqual(candidate.position, new Cesium.Cartesian3(40, 50, 60));
|
||||
assert.deepEqual(candidate.position, { x: 40, y: 50, z: 60 });
|
||||
showModel(record, false);
|
||||
assert.deepEqual(f.queries.getDetectableObjects(), []);
|
||||
f.show(true);
|
||||
@@ -175,7 +174,10 @@ test('tracked ownership and live anchors remain independent of fleet models', ()
|
||||
]) {
|
||||
f.flightState._trackedModel = tracked;
|
||||
assert.equal(
|
||||
f.parts.rendering._modelOwnsVisual('abc123', modelRecord({ ready: true, show: true })),
|
||||
f.parts.rendering._modelOwnsVisual(
|
||||
'abc123',
|
||||
modelRecord({ ready: true, show: true }),
|
||||
),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -102,19 +102,15 @@ export function createRendering({
|
||||
|
||||
/**
|
||||
* Sample the rendered mesh under the collected floor cells (see
|
||||
* meshFloorSampler.js), leaving this layer's own icons out of the probe so
|
||||
* it cannot land on an aircraft instead of the pavement.
|
||||
* meshFloorSampler.js), leaving this layer's own icon and model sets out
|
||||
* of the probe so it cannot land on an aircraft instead of the pavement.
|
||||
*/
|
||||
function _sampleMeshFloor(points, viewerLat, viewerLon) {
|
||||
services.meshFloor.sampleMeshFloorCells(
|
||||
flightState._viewer?.scene,
|
||||
points,
|
||||
{
|
||||
excludeObjects: parts.icons._iconIds(),
|
||||
viewerLat,
|
||||
viewerLon,
|
||||
},
|
||||
);
|
||||
services.meshFloor.sampleMeshFloorCells(flightState._viewer, points, {
|
||||
sets: models._groundSampleExclusions().sets,
|
||||
viewerLat,
|
||||
viewerLon,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
+29
-45
@@ -1,6 +1,5 @@
|
||||
import { FlightRecords } from './records.js';
|
||||
import { createFlightFeed } from './ingestion.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { ENRICH_AMBIENT_BUDGET_CEIL } from './policy.js';
|
||||
|
||||
export function createFlightState({ source, services }) {
|
||||
@@ -53,11 +52,6 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._lastModelCapWarnMs = 0;
|
||||
// throttle the "more planes in view than the cap" console notice
|
||||
flightState._scratchModelBS = new Cesium.BoundingSphere(
|
||||
new Cesium.Cartesian3(),
|
||||
1.0,
|
||||
);
|
||||
// frustum-visibility test
|
||||
// keep last N positions per aircraft
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -93,7 +87,7 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._focusEvidenceIds = new Set();
|
||||
|
||||
/** @type {Map<string, Array<{time:Cesium.JulianDate, position:Cesium.Cartesian3}>>} */
|
||||
/** @type {Map<string, Array<{time:object, position:{x: number, y: number, z: number}}>>} */
|
||||
|
||||
flightState._positionHistory = new Map();
|
||||
|
||||
@@ -109,7 +103,7 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._trackingIntentGeneration = 0;
|
||||
|
||||
/** @type {Cesium.Entity|null} Entity used for camera tracking */
|
||||
/** @type {object|null} The tracked aircraft's record holder (its entity record is what the app shows; the camera follows a target reading it) */
|
||||
|
||||
flightState._trackedEntity = null;
|
||||
|
||||
@@ -127,7 +121,7 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._clickSubscription = null;
|
||||
|
||||
/** @type {Cesium.Viewer|null} Cached viewer reference */
|
||||
/** @type {object|null} Cached viewer reference */
|
||||
|
||||
flightState._viewer = null;
|
||||
|
||||
@@ -157,7 +151,7 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._trailHeadOff = null;
|
||||
|
||||
/** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */
|
||||
/** @type {{x: number, y: number, z: number}[]} Chronological tracked-aircraft fixes (oldest first) */
|
||||
|
||||
flightState._trailPositions = [];
|
||||
|
||||
@@ -173,17 +167,17 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._lastTrackedRotation = 0;
|
||||
|
||||
/** @type {Cesium.Event.RemoveCallback|null} preRender listener disposer */
|
||||
/** @type {() => void|null} preRender listener disposer */
|
||||
|
||||
flightState._preRenderRemove = null;
|
||||
|
||||
flightState._trackedModelPreUpdateRemove = null;
|
||||
|
||||
/** @type {Cesium.Event.RemoveCallback|null} camera.moveEnd listener disposer (arrival rotation pass) */
|
||||
/** @type {() => void|null} camera.moveEnd listener disposer (arrival rotation pass) */
|
||||
|
||||
flightState._moveEndRemove = null;
|
||||
|
||||
/** @type {Cesium.Event.RemoveCallback|null} trackedEntityChanged listener disposer (cross-layer untrack) */
|
||||
/** @type {() => void|null} trackedEntityChanged listener disposer (cross-layer untrack) */
|
||||
|
||||
flightState._trackedEntityChangedRemove = null;
|
||||
|
||||
@@ -195,29 +189,27 @@ export function createFlightState({ source, services }) {
|
||||
// Scratch (reusable) variables — avoid per-frame heap allocation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
flightState._scratchOffset = new Cesium.Cartesian3();
|
||||
|
||||
flightState._scratchCarto = new Cesium.Cartographic();
|
||||
flightState._scratchOffset = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchArc = { east: 0, north: 0, endCourseDeg: 0 };
|
||||
|
||||
flightState._scratchRenderTime = new Cesium.JulianDate();
|
||||
flightState._scratchRenderTime = { dayNumber: 0, secondsOfDay: 0 };
|
||||
|
||||
flightState._scratchFleetRenderTime = new Cesium.JulianDate();
|
||||
flightState._scratchFleetRenderTime = { dayNumber: 0, secondsOfDay: 0 };
|
||||
|
||||
flightState._scratchFleetPos = new Cesium.Cartesian3();
|
||||
flightState._scratchFleetPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchCockpitPos = new Cesium.Cartesian3();
|
||||
flightState._scratchCockpitPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchNearbyPos = new Cesium.Cartesian3();
|
||||
flightState._scratchNearbyPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchSonarScreen = new Cesium.Cartesian2();
|
||||
flightState._scratchSonarScreen = { x: 0, y: 0 };
|
||||
|
||||
flightState._scratchDrRaw = new Cesium.Cartesian3();
|
||||
flightState._scratchDrRaw = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchWarmupTime = new Cesium.JulianDate();
|
||||
flightState._scratchWarmupTime = { dayNumber: 0, secondsOfDay: 0 };
|
||||
|
||||
flightState._trackedPosHolder = new Cesium.Cartesian3();
|
||||
flightState._trackedPosHolder = { x: 0, y: 0, z: 0 };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-frame cache for the tracked entity's dead-reckoned position.
|
||||
@@ -225,7 +217,7 @@ export function createFlightState({ source, services }) {
|
||||
// render frame; caching avoids running _deadReckon three times.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** @type {Cesium.Cartesian3|null} */
|
||||
/** @type {{x: number, y: number, z: number}|null} */
|
||||
|
||||
flightState._cachedDRPosition = null;
|
||||
|
||||
@@ -302,13 +294,13 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._enrichAmbientRefillAnchorMs = 0;
|
||||
|
||||
flightState._drCorrection = new Cesium.Cartesian3(0, 0, 0);
|
||||
flightState._drCorrection = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._drCorrectionStartMs = 0;
|
||||
|
||||
flightState._drPrevRaw = new Cesium.Cartesian3();
|
||||
flightState._drPrevRaw = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._drPrevDisplay = new Cesium.Cartesian3();
|
||||
flightState._drPrevDisplay = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._drPrevMs = 0;
|
||||
|
||||
@@ -318,20 +310,20 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._drReconcileIcao = null;
|
||||
|
||||
/** @type {Cesium.Cartesian3} Scratch for the tracked model's rendered translation. */
|
||||
/** @type {{x: number, y: number, z: number}} Scratch for the tracked model's rendered translation. */
|
||||
|
||||
flightState._trackedVisualPos = new Cesium.Cartesian3();
|
||||
flightState._trackedVisualPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._trackedTrailPos = new Cesium.Cartesian3();
|
||||
flightState._trackedTrailPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
/** Scratch for the tracked model's world-space origin (the envelope centre). */
|
||||
|
||||
flightState._scratchTrailClip = new Cesium.Cartesian3();
|
||||
flightState._scratchTrailClip = { x: 0, y: 0, z: 0 };
|
||||
|
||||
/** Scratch for the shortened trail-head start. Owned by the head-segment
|
||||
* callback alone, so nothing else can overwrite it mid-frame. */
|
||||
|
||||
flightState._scratchTrailHead = new Cesium.Cartesian3();
|
||||
flightState._scratchTrailHead = { x: 0, y: 0, z: 0 };
|
||||
|
||||
/** Hysteresis latch for the tracked contact's zoom regime, plus the selection it
|
||||
* belongs to. Scoped per selection so a NEW target re-evaluates against the ENTER
|
||||
@@ -341,12 +333,8 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._trackedZoomLatchIcao = null;
|
||||
|
||||
/** @type {Cesium.Cartographic} Scratch for the grounded display-floor read. */
|
||||
|
||||
flightState._scratchDisplayCarto = new Cesium.Cartographic();
|
||||
|
||||
/** @type {Map<string, {cell: {lat: number, lon: number}, effectiveM: number|null,
|
||||
* in: Cesium.Cartesian3, out: Cesium.Cartesian3|null, heldM: number|null,
|
||||
* in: {x: number, y: number, z: number}, out: {x: number, y: number, z: number}|null, heldM: number|null,
|
||||
* heldCell: {lat: number, lon: number}|null,
|
||||
* heldTier: 'own'|'neighbor'|null, heldActive: boolean, seeded: boolean,
|
||||
* probeMs: number|null, retiredMs: number|null,
|
||||
@@ -368,13 +356,9 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._corridorEpoch = 0;
|
||||
|
||||
/** @type {Cesium.Cartographic} Scratch for the corridor's display-end read. */
|
||||
/** @type {{x: number, y: number, z: number}} Scratch for the corridor's dead-reckon probe. */
|
||||
|
||||
flightState._scratchCorridorCarto = new Cesium.Cartographic();
|
||||
|
||||
/** @type {Cesium.Cartesian3} Scratch for the corridor's dead-reckon probe. */
|
||||
|
||||
flightState._scratchCorridorPos = new Cesium.Cartesian3();
|
||||
flightState._scratchCorridorPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
/** IR hot-target mode (owner playtest 2026-08-16): the NVG/FLIR post-styles
|
||||
* map LUMINANCE, so mid-gray textured models read cold and vanish into
|
||||
|
||||
+148
-165
@@ -1,19 +1,30 @@
|
||||
import { cameraOf } from '../../render/cesium/camera.js';
|
||||
import { findFrame } from '../../render/rendererOf.js';
|
||||
import { cameraOf, findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import {
|
||||
entityFollowTarget,
|
||||
onFollowChanged,
|
||||
stopFollowing,
|
||||
} from '../../data/followed.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { 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 {
|
||||
screenProjectedRotation,
|
||||
courseScreenRotation,
|
||||
stabilizeScreenRotation,
|
||||
} from '../../data/iconOrientation.js';
|
||||
} from '../../data/screenRotation.js';
|
||||
import {
|
||||
createTrackedAircraftIcon,
|
||||
isOtherTrackedIconSet,
|
||||
trackedContactHolder,
|
||||
} from '../../data/trackedAircraftIcon.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThanOrEquals,
|
||||
julianNow,
|
||||
julianToEpochMs,
|
||||
} from '../../geo/julian.js';
|
||||
import { clone, distanceSquared, vec } from '../../geo/vector.js';
|
||||
import { trailHeadStart } from '../../data/modelVisualAnchor.js';
|
||||
import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js';
|
||||
import { routePlausible } from '../../data/routePlausible.js';
|
||||
@@ -28,6 +39,7 @@ import {
|
||||
RENDER_DELAY_SEC,
|
||||
TRAIL_COLOR,
|
||||
CYAN_TRANSPARENT,
|
||||
TRACKED_CYAN,
|
||||
TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
|
||||
} from './policy.js';
|
||||
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
@@ -41,7 +53,7 @@ function aircraftPickId(picked) {
|
||||
const id = picked?.id;
|
||||
if (typeof id === 'string') return id;
|
||||
if (id && typeof id.set === 'string' && typeof id.id === 'string')
|
||||
return id.id;
|
||||
return isOtherTrackedIconSet(id.set, 'flights') ? undefined : id.id;
|
||||
return picked?.primitive?.id;
|
||||
}
|
||||
|
||||
@@ -69,6 +81,21 @@ export function createTracking({
|
||||
const { FOLLOW_MIN_RANGE_M } = services.camera;
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
const flightsLayer = layer;
|
||||
/** The tracked contact's billboard (an icon set on the draw port). */
|
||||
const trackedIcon = createTrackedAircraftIcon({
|
||||
viewer: () => flightState._viewer,
|
||||
setPrefix: 'flights',
|
||||
});
|
||||
|
||||
/** The camera's pose, or null without a camera to ask. */
|
||||
function _pose() {
|
||||
const viewer = flightState._viewer;
|
||||
try {
|
||||
return (viewer && findCamera(viewer)?.pose()) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function _emitAwarenessEvent(type, detail) {
|
||||
if (
|
||||
@@ -81,7 +108,7 @@ export function createTracking({
|
||||
}
|
||||
|
||||
function _publishTrackedSelection(icao24, origin = 'programmatic') {
|
||||
const position = parts.icons._iconPosition(icao24, new Cesium.Cartesian3());
|
||||
const position = parts.icons._iconPosition(icao24, vec());
|
||||
const info = flightState.records.data.get(icao24);
|
||||
if (!position || !info) return false;
|
||||
if (flightState._trackedEntity)
|
||||
@@ -169,10 +196,8 @@ export function createTracking({
|
||||
*/
|
||||
|
||||
function _refreshCockpitNearContacts() {
|
||||
if (
|
||||
!flightState._cockpitContactMode ||
|
||||
!flightState._viewer?.camera?.positionWC
|
||||
) {
|
||||
const eye = flightState._cockpitContactMode ? _pose()?.position : null;
|
||||
if (!eye) {
|
||||
if (flightState._cockpitNearContacts.size)
|
||||
flightState._cockpitNearContacts = new Set();
|
||||
return;
|
||||
@@ -188,13 +213,7 @@ export function createTracking({
|
||||
t,
|
||||
flightState._scratchCockpitPos,
|
||||
);
|
||||
distancesSquared.push([
|
||||
icao24,
|
||||
Cesium.Cartesian3.distanceSquared(
|
||||
flightState._viewer.camera.positionWC,
|
||||
position,
|
||||
),
|
||||
]);
|
||||
distancesSquared.push([icao24, distanceSquared(eye, position)]);
|
||||
}
|
||||
const next = nextCockpitNearContacts(
|
||||
previous,
|
||||
@@ -291,7 +310,7 @@ export function createTracking({
|
||||
return false;
|
||||
}
|
||||
flightState._trackedZoomLatched = trackedModelZoomActive(
|
||||
flightState._viewer?.camera?.positionCartographic?.height,
|
||||
_pose()?.height,
|
||||
flightState._trackedZoomLatched,
|
||||
);
|
||||
return flightState._trackedZoomLatched;
|
||||
@@ -303,13 +322,10 @@ export function createTracking({
|
||||
if (!flightState._trackedIcao || !flightState._viewer) return;
|
||||
const pos =
|
||||
parts.motion._trackedDisplayCached() ||
|
||||
parts.icons._iconPosition(
|
||||
flightState._trackedIcao,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
parts.icons._iconPosition(flightState._trackedIcao, vec());
|
||||
if (!pos) return;
|
||||
const projected = screenProjectedRotation(
|
||||
flightState._viewer.scene,
|
||||
const projected = courseScreenRotation(
|
||||
_pose(),
|
||||
pos,
|
||||
parts.motion._trackedDisplayCourse(),
|
||||
flightState._lastTrackedRotation,
|
||||
@@ -325,7 +341,7 @@ export function createTracking({
|
||||
/**
|
||||
* Append one fix to the tracked aircraft's trail accumulation and refresh
|
||||
* the rendered trail. Caller passes an owned (cloned) Cartesian3.
|
||||
* @param {Cesium.Cartesian3} position - New fix position, appended at the head.
|
||||
* @param {{x: number, y: number, z: number}} position - New ECEF fix, appended at the head.
|
||||
*/
|
||||
|
||||
function _appendTrailFix(position) {
|
||||
@@ -361,7 +377,7 @@ export function createTracking({
|
||||
/**
|
||||
* The live head: the last DISPLAYED body point to the delayed head, or no
|
||||
* positions while there is none.
|
||||
* @returns {Cesium.Cartesian3[]}
|
||||
* @returns {Array<{x: number, y: number, z: number}>}
|
||||
*/
|
||||
function _trailHeadPositions() {
|
||||
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
|
||||
@@ -398,7 +414,7 @@ export function createTracking({
|
||||
flightState._scratchTrailHead,
|
||||
);
|
||||
if (!from) return [];
|
||||
return [from, Cesium.Cartesian3.clone(head)];
|
||||
return [from, clone(head)];
|
||||
}
|
||||
|
||||
/** Each drawn frame, before it draws: the live head where the aircraft is now. */
|
||||
@@ -421,14 +437,14 @@ export function createTracking({
|
||||
// newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them
|
||||
// would draw the trail in front of the plane. They join the trail via _appendTrailFix
|
||||
// as they age past the delay.
|
||||
const seedRenderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
const seedRenderTime = addSeconds(
|
||||
julianNow(),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
for (const fix of history) {
|
||||
if (Cesium.JulianDate.lessThanOrEquals(fix.time, seedRenderTime)) {
|
||||
flightState._trailPositions.push(Cesium.Cartesian3.clone(fix.position));
|
||||
if (julianLessThanOrEquals(fix.time, seedRenderTime)) {
|
||||
flightState._trailPositions.push(clone(fix.position));
|
||||
}
|
||||
}
|
||||
if (!flightState._trail && flightState._viewer) {
|
||||
@@ -449,7 +465,7 @@ export function createTracking({
|
||||
_refreshTrailDisplay();
|
||||
|
||||
const oldestFixEpochSec = history.length
|
||||
? Cesium.JulianDate.toDate(history[0].time).getTime() / 1000
|
||||
? julianToEpochMs(history[0].time) / 1000
|
||||
: Infinity;
|
||||
_backfillTrail(icao24, flightState._trailBackfillToken, oldestFixEpochSec);
|
||||
}
|
||||
@@ -541,7 +557,7 @@ export function createTracking({
|
||||
// with nothing to carry keep the old 10 km airborne default.
|
||||
if (altM == null) altM = lastAltM != null ? lastAltM : 10000;
|
||||
lastAltM = altM;
|
||||
older.push(Cesium.Cartesian3.fromDegrees(lon, lat, altM));
|
||||
older.push(fromDegrees(lon, lat, altM));
|
||||
}
|
||||
|
||||
flightState._trailPositions = older.concat(flightState._trailPositions);
|
||||
@@ -614,18 +630,16 @@ export function createTracking({
|
||||
// release never flips it.
|
||||
const trackedCourseDeg = flightState._displayCourse.get(clearedIcao);
|
||||
|
||||
// Stop tracking and remove the entity. skipViewerUntrack: when ANOTHER layer just grabbed the
|
||||
// follow-camera, we tear down our own state but must NOT clear the camera's follow (the new owner
|
||||
// controls it now — clearing it would yank the camera off their plane). Releasing trackedEntity
|
||||
// does NOT move the camera: Cesium resets the lookAt transform in place, so the view stays where
|
||||
// the follow left it and the user can immediately orbit/zoom.
|
||||
// Stop tracking and hide the tracked billboard. skipViewerUntrack: when ANOTHER layer just
|
||||
// grabbed the follow-camera, we tear down our own state but must NOT clear the camera's follow
|
||||
// (the new owner controls it now — clearing it would yank the camera off their plane).
|
||||
// Releasing the follow does NOT move the camera: the view stays where the follow left it and
|
||||
// the user can immediately orbit/zoom.
|
||||
if (flightState._viewer && !skipViewerUntrack) {
|
||||
stopFollowing(flightState._viewer);
|
||||
}
|
||||
if (flightState._trackedEntity) {
|
||||
flightState._viewer.entities.remove(flightState._trackedEntity);
|
||||
flightState._trackedEntity = null;
|
||||
}
|
||||
trackedIcon.hide();
|
||||
flightState._trackedEntity = null;
|
||||
parts.rendering._releaseTrackedModel();
|
||||
_resetTrackedSelectionState(); // the zoom band belongs to the selection we just dropped
|
||||
flightState._trackedIcao = null;
|
||||
@@ -756,12 +770,9 @@ export function createTracking({
|
||||
refreshTrackedSubjectContext(_contextSubjectMetadata(icao24));
|
||||
}
|
||||
|
||||
/** Re-image the tracked entity's billboard from the current class/conversion. */
|
||||
|
||||
function _syncTrackedBillboardImage() {
|
||||
if (!flightState._trackedIcao || !flightState._trackedEntity?.billboard)
|
||||
return;
|
||||
flightState._trackedEntity.billboard.image = aircraftIcon(
|
||||
/** The tracked billboard's image, from the current class/conversion. */
|
||||
function _trackedBillboardImage() {
|
||||
return aircraftIcon(
|
||||
parts.rendering._iconKind(
|
||||
flightState._trackedIcao,
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
@@ -770,6 +781,13 @@ export function createTracking({
|
||||
);
|
||||
}
|
||||
|
||||
/** Re-image the tracked billboard from the current class/conversion. */
|
||||
|
||||
function _syncTrackedBillboardImage() {
|
||||
if (!flightState._trackedIcao || !flightState._trackedEntity) return;
|
||||
trackedIcon.setImage(_trackedBillboardImage());
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-render one contact after its TR-3B conversion (or the active IR style)
|
||||
* changed. Converting drops any 3D model so the triangle owns the visual; the
|
||||
@@ -799,7 +817,8 @@ export function createTracking({
|
||||
_syncTrackedBillboardImage();
|
||||
_updateTrackedLabelModel(id);
|
||||
}
|
||||
flightState._viewer?.scene?.requestRender?.();
|
||||
if (flightState._viewer)
|
||||
findFrame(flightState._viewer)?.requestRender('flights: TR-3B restyle');
|
||||
return flightState._icons?.has(id) || id === flightState._trackedIcao;
|
||||
}
|
||||
|
||||
@@ -818,17 +837,13 @@ export function createTracking({
|
||||
|
||||
function _routeIsPlausible(icao24, route) {
|
||||
const info = flightState.records.data.get(icao24);
|
||||
const position = parts.icons._iconPosition(icao24, new Cesium.Cartesian3());
|
||||
const position = parts.icons._iconPosition(icao24, vec());
|
||||
if (!info || !position) return true;
|
||||
const carto = Cesium.Cartographic.fromCartesian(
|
||||
position,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchCarto,
|
||||
);
|
||||
const carto = toLonLatH(position);
|
||||
if (!carto) return true;
|
||||
return routePlausible({
|
||||
latDeg: Cesium.Math.toDegrees(carto.latitude),
|
||||
lonDeg: Cesium.Math.toDegrees(carto.longitude),
|
||||
latDeg: carto.lat,
|
||||
lonDeg: carto.lon,
|
||||
altitudeM: info.altitude ?? null,
|
||||
verticalRateMps: info.verticalRate ?? null,
|
||||
origin: route.origin,
|
||||
@@ -839,16 +854,12 @@ export function createTracking({
|
||||
/**
|
||||
* Begin tracking a specific aircraft by ICAO24 address.
|
||||
*
|
||||
* Clears any existing tracked flight, hides its billboard, and creates a
|
||||
* new Entity with:
|
||||
* - A CallbackProperty position driven by dead-reckoning (_deadReckon).
|
||||
* - A CallbackProperty alignedAxis set to the surface normal at the
|
||||
* dead-reckoned position (keeps the icon tangent to the earth).
|
||||
* - A CallbackProperty rotation from the aircraft's true_track heading.
|
||||
* - An explicit host presentation model with callsign, flight level, speed,
|
||||
* identity, and plausible route text.
|
||||
*
|
||||
* The viewer's trackedEntity is set to this entity so the camera follows it.
|
||||
* Clears any existing tracked flight, hides its fleet icon, and shows the
|
||||
* tracked billboard (`createTrackedAircraftIcon`), drawn each frame at the
|
||||
* dead-reckoned display position, screen-rotated along the displayed
|
||||
* course. The tracked record carries the host presentation model
|
||||
* (callsign, flight level, speed, identity, plausible route text), and the
|
||||
* camera follows a target that reads it.
|
||||
*
|
||||
* @param {string} icao24 - ICAO 24-bit transponder address to track.
|
||||
*/
|
||||
@@ -863,19 +874,14 @@ export function createTracking({
|
||||
// The tracked limiter continues from the nose the icon was drawn with, and
|
||||
// the entity starts with the rotation the icon had on screen.
|
||||
const t = parts.icons._displayMs();
|
||||
const iconPosition = icons.position(icao24, t, new Cesium.Cartesian3());
|
||||
const iconPosition = icons.position(icao24, t, vec());
|
||||
const iconCourse = icons.course(icao24, t);
|
||||
flightState._displayCourse.set(icao24, iconCourse);
|
||||
flightState._trackedIcao = icao24;
|
||||
_resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._lastTrackedRotation =
|
||||
screenProjectedRotation(
|
||||
flightState._viewer.scene,
|
||||
iconPosition,
|
||||
iconCourse,
|
||||
0,
|
||||
) ?? 0;
|
||||
courseScreenRotation(_pose(), iconPosition, iconCourse, 0) ?? 0;
|
||||
// Drop any fleet 3D model for this aircraft — the tracked entity now owns its visual (its
|
||||
// own billboard + model graphic), and the fleet tick skips the tracked icao, so a leftover
|
||||
// fleet model would be orphaned + double-rendered.
|
||||
@@ -890,28 +896,20 @@ export function createTracking({
|
||||
// the aircraft has no fix.
|
||||
const getTrackedPosition = () =>
|
||||
parts.motion._trackedDisplayPosition(icao24) ||
|
||||
parts.icons._iconPosition(icao24, new Cesium.Cartesian3()) ||
|
||||
parts.icons._iconPosition(icao24, vec()) ||
|
||||
iconPosition;
|
||||
|
||||
// Dead-reckoning position property — smooth continuous motion between API updates.
|
||||
const positionProperty = new Cesium.CallbackProperty(() => {
|
||||
return getTrackedPosition();
|
||||
}, false);
|
||||
|
||||
// Create tracked entity: a 2D billboard when zoomed out, a 3D model when zoomed in past the
|
||||
// TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on the
|
||||
// DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always
|
||||
// The tracked billboard: a 2D icon when zoomed out, handing over to the 3D model when zoomed
|
||||
// in past the TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on
|
||||
// the DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always
|
||||
// resolves into an aircraft.
|
||||
//
|
||||
// The billboard stays SHOWN at all times and is hidden by going TRANSPARENT (alpha 0), not by
|
||||
// show=false: it drops its alpha only once the tracked model is drawing, so
|
||||
// there's neither a billboard+model double-image nor a gap. The camera follows its own target
|
||||
// through the camera port, so nothing here frames the camera.
|
||||
// The tracked entity is a PURE BILLBOARD — no label or model graphic. The 3D model for the
|
||||
// tracked plane is a standalone primitive driven by _updateTrackedModel(); it stays off the entity (see _trackedModel).
|
||||
// Keep Cesium's generated entity ID: re-init without destroy can temporarily
|
||||
// overlap collections, and an explicit ICAO ID would throw on that duplicate.
|
||||
// What the tracked billboard is drawn at, kept in its entity record so the
|
||||
// show=false: it drops its alpha only once the tracked model is drawing, so there's neither a
|
||||
// billboard+model double-image nor a gap. The camera follows its own target through the camera
|
||||
// port, so nothing here frames the camera. The 3D model for the tracked plane is a draw-set
|
||||
// item driven by _updateTrackedModel() (see _trackedModel).
|
||||
// What the tracked billboard is drawn at, kept in its record so the
|
||||
// camera guard and screen annotations size it from the app.
|
||||
const sprite = {
|
||||
width: 28,
|
||||
@@ -922,58 +920,49 @@ export function createTracking({
|
||||
] || 1,
|
||||
scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
|
||||
};
|
||||
flightState._trackedEntity = flightState._viewer.entities.add({
|
||||
position: positionProperty,
|
||||
billboard: {
|
||||
image: aircraftIcon(
|
||||
parts.rendering._iconKind(
|
||||
flightState._trackedIcao,
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
),
|
||||
TRACKED_ICON_PX,
|
||||
),
|
||||
width: sprite.width,
|
||||
height: sprite.height,
|
||||
scale: sprite.scale,
|
||||
// Solid cyan when the billboard is the visual (zoomed out, 3D off, or model still loading);
|
||||
// transparent once the STANDALONE tracked model is actually up (ready + shown).
|
||||
color: new Cesium.CallbackProperty(
|
||||
() =>
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
? CYAN_TRANSPARENT
|
||||
: Cesium.Color.CYAN,
|
||||
false,
|
||||
),
|
||||
sizeInMeters: false,
|
||||
scaleByDistance: sprite.scaleByDistance,
|
||||
alignedAxis: Cesium.Cartesian3.ZERO,
|
||||
// The tracked target must never vanish into tile geometry — tracking a
|
||||
// taxiing plane at street level would otherwise bury the cyan icon inside
|
||||
// the runway skin, so it draws depth-test-free like the fleet icon set;
|
||||
// its shared-host tracked card is top-composited separately.
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
// Screen-projected rotation, evaluated per frame: exact in tracked-orbit
|
||||
// mode where camera.heading lives in the entity's reference frame.
|
||||
rotation: new Cesium.CallbackProperty(() => {
|
||||
const tracked = flightState.records.data.get(
|
||||
flightState._trackedIcao,
|
||||
);
|
||||
const pos = getTrackedPosition();
|
||||
if (!tracked || !pos || !flightState._viewer)
|
||||
return flightState._lastTrackedRotation;
|
||||
const projected = screenProjectedRotation(
|
||||
flightState._viewer.scene,
|
||||
pos,
|
||||
parts.motion._trackedDisplayCourse(),
|
||||
flightState._lastTrackedRotation,
|
||||
);
|
||||
const rot = stabilizeScreenRotation(
|
||||
flightState._lastTrackedRotation,
|
||||
projected,
|
||||
);
|
||||
if (rot !== null) flightState._lastTrackedRotation = rot;
|
||||
// The tracked contact as its readers see it (the tracked card, Cockpit, share links): a
|
||||
// plain holder of its entity record, drawn while it is the one tracked.
|
||||
const holder = trackedContactHolder(
|
||||
`flights:${icao24}`,
|
||||
trackedIcon,
|
||||
parts.motion._trackedDisplayCached,
|
||||
);
|
||||
flightState._trackedEntity = holder;
|
||||
entityRecord(holder).drawn = () => flightState._trackedEntity === holder;
|
||||
trackedIcon.show({
|
||||
id: icao24,
|
||||
image: _trackedBillboardImage(),
|
||||
sprite,
|
||||
position: getTrackedPosition,
|
||||
// Solid cyan when the billboard is the visual (zoomed out, 3D off, or model still loading);
|
||||
// transparent once the tracked model is actually up (ready + shown).
|
||||
color: () =>
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
? CYAN_TRANSPARENT
|
||||
: TRACKED_CYAN,
|
||||
// Screen-projected rotation, evaluated per frame on the camera's own
|
||||
// axes, so it stays exact through a tracked orbit. The tracked target
|
||||
// must never vanish into tile geometry — tracking a taxiing plane at
|
||||
// street level would otherwise bury the cyan icon inside the runway
|
||||
// skin, so it draws over depth like the fleet icon set; its
|
||||
// shared-host tracked card is top-composited separately.
|
||||
rotation: () => {
|
||||
const tracked = flightState.records.data.get(flightState._trackedIcao);
|
||||
const pos = getTrackedPosition();
|
||||
if (!tracked || !pos || !flightState._viewer)
|
||||
return flightState._lastTrackedRotation;
|
||||
}, false),
|
||||
const projected = courseScreenRotation(
|
||||
_pose(),
|
||||
pos,
|
||||
parts.motion._trackedDisplayCourse(),
|
||||
flightState._lastTrackedRotation,
|
||||
);
|
||||
const rot = stabilizeScreenRotation(
|
||||
flightState._lastTrackedRotation,
|
||||
projected,
|
||||
);
|
||||
if (rot !== null) flightState._lastTrackedRotation = rot;
|
||||
return flightState._lastTrackedRotation;
|
||||
},
|
||||
});
|
||||
entityRecord(flightState._trackedEntity).selectionOrigin = origin;
|
||||
@@ -982,22 +971,18 @@ export function createTracking({
|
||||
entityRecord(flightState._trackedEntity).labelModel =
|
||||
trackedLabelModelFromText(_trackedLabelText(icao24), '#39d0ff');
|
||||
|
||||
// A billboard has a ~zero bounding sphere, so Cesium's default follow distance is
|
||||
// far too tight (the user had to scroll out to read the plane). Give the entity a
|
||||
// A billboard has a ~zero bounding sphere, so the renderer's default follow distance is
|
||||
// far too tight (the user had to scroll out to read the plane). Give the target a
|
||||
// calibrated viewFrom — behind + above, distance scaled to altitude — for a readable
|
||||
// initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.)
|
||||
const followRange = Math.min(
|
||||
Math.max((info.altitude || 1500) * 1.1 + 2500, 3000),
|
||||
30000,
|
||||
);
|
||||
const viewFrom = new Cesium.Cartesian3(
|
||||
0,
|
||||
-followRange * 0.8,
|
||||
followRange * 0.55,
|
||||
);
|
||||
const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55);
|
||||
|
||||
// Cancel any in-progress camera flight first — otherwise Cesium won't apply the
|
||||
// tracked entity's viewFrom on the first frame, so voice-initiated tracking (which
|
||||
// Cancel any in-progress camera flight first — otherwise the camera won't apply the
|
||||
// follow target's viewFrom on the first frame, so voice-initiated tracking (which
|
||||
// often fires mid-fly_to_location) would follow the plane WITHOUT centering/framing it
|
||||
// the way a click (idle camera) does.
|
||||
// Expose the camera's already-settled position to cross-module HUD consumers (the tracked-target
|
||||
@@ -1092,15 +1077,13 @@ export function createTracking({
|
||||
}
|
||||
|
||||
/**
|
||||
* Install a LEFT_CLICK handler on the scene canvas for flight selection.
|
||||
*
|
||||
* Picking logic checks both `picked.primitive` and `picked.id` because
|
||||
* different CesiumJS versions surface BillboardCollection hits differently.
|
||||
* Also registers a global keydown listener for the Escape key.
|
||||
* Install a click handler for flight selection: a pick names a draw-set
|
||||
* item by the contact's icao (see `aircraftPickId`). Also registers a
|
||||
* global keydown listener for the Escape key.
|
||||
*
|
||||
* Idempotent — returns immediately if a handler is already installed.
|
||||
*
|
||||
* @param {Cesium.Viewer} viewer
|
||||
* @param {object} viewer
|
||||
*/
|
||||
|
||||
function _installClickHandler(viewer) {
|
||||
@@ -1142,14 +1125,11 @@ export function createTracking({
|
||||
const picked = event.hit;
|
||||
|
||||
if (picked) {
|
||||
// Clicking the tracked entity itself — ignore (don't deselect)
|
||||
if (picked.id === flightState._trackedEntity) return;
|
||||
|
||||
// Clicking the plane we're ALREADY tracking (its standalone 3D model or
|
||||
// any pick carrying its icao) — same no-op as the 2D tracked-entity click
|
||||
// above. H1: the model used to have no pick id, so this fell through to
|
||||
// Clicking the plane we're ALREADY tracking (its tracked billboard, its
|
||||
// 3D model, or any pick carrying its icao) — ignore, don't deselect.
|
||||
// H1: the model used to have no pick id, so this fell through to
|
||||
// "empty space" and deselected the very plane being tracked.
|
||||
// Its models are draw-set items keyed by icao, like its icons.
|
||||
// Its billboard and models are draw-set items keyed by icao, like its icons.
|
||||
const pickedIcao = aircraftPickId(picked);
|
||||
if (flightState._trackedIcao && pickedIcao === flightState._trackedIcao)
|
||||
return;
|
||||
@@ -1199,6 +1179,9 @@ export function createTracking({
|
||||
_backfillTrail,
|
||||
_clearTrail,
|
||||
_destroyTrail,
|
||||
/** Let the tracked billboard's set go (layer teardown). */
|
||||
_disposeTrackedIcon: () => trackedIcon.dispose(),
|
||||
/** The tracked billboard's set id, or null before one is made. */
|
||||
_clearTracking,
|
||||
_militaryLayerSuppresses,
|
||||
_applyPendingTrackingRestore,
|
||||
|
||||
@@ -218,6 +218,7 @@ export function createLifecycle({
|
||||
}
|
||||
parts.rendering._releaseModels();
|
||||
parts.icons._disposeIcons();
|
||||
parts.tracking._disposeTrackedIcon();
|
||||
parts.rendering._disposeModelSets();
|
||||
flightState._iconFocusActive = 0;
|
||||
flightState._detectionObjects.clear();
|
||||
|
||||
+113
-82
@@ -1,4 +1,23 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { findCamera, rendererOf } from '../../render/rendererOf.js';
|
||||
import { renderedFrames } from '../../data/renderedFrames.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { eastNorthUp, framePoint } from '../../geo/frames.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThan,
|
||||
julianNow,
|
||||
secondsDifference,
|
||||
} from '../../geo/julian.js';
|
||||
import {
|
||||
add,
|
||||
clamp,
|
||||
copyInto,
|
||||
distance,
|
||||
lerpInto,
|
||||
scale,
|
||||
sub,
|
||||
vec,
|
||||
} from '../../geo/vector.js';
|
||||
import {
|
||||
lerpAngleDeg,
|
||||
COURSE_HOLD_SPEED_MPS,
|
||||
@@ -37,6 +56,9 @@ import {
|
||||
/** Where a military record carries its reported speed and track. */
|
||||
const RECORD_FIELDS = { speed: 'speedMps', track: 'track' };
|
||||
|
||||
/** Whether two ECEF points are the same point, component for component. */
|
||||
const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;
|
||||
|
||||
export function createMotion({
|
||||
flightState,
|
||||
services,
|
||||
@@ -48,11 +70,33 @@ export function createMotion({
|
||||
const {
|
||||
nearFarScalarValueAtDistance,
|
||||
clearFocusTarget,
|
||||
publishFocusTargetFromCachedPosition,
|
||||
publishFocusTargetAt,
|
||||
} = services.focus;
|
||||
/** `_motionRegime`'s reused result. */
|
||||
const regime = createMotionRegime();
|
||||
|
||||
/** The camera's pose, or null without a camera to ask. */
|
||||
function _pose() {
|
||||
const viewer = flightState._viewer;
|
||||
try {
|
||||
return (viewer && findCamera(viewer)?.pose()) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The renderer canvas's CSS height (the viewer's own canvas when no
|
||||
* renderer is bound), or 0 without either. */
|
||||
function _viewportHeightPx() {
|
||||
const viewer = flightState._viewer;
|
||||
const canvas = rendererOf(viewer)?.canvas ?? viewer?.canvas;
|
||||
return Number(canvas?.clientHeight) || 0;
|
||||
}
|
||||
|
||||
// Fixes leave the cache with their history; a corrected position
|
||||
// invalidates the local frame even when the fix's point is changed in place.
|
||||
const fixFrames = new WeakMap();
|
||||
|
||||
/**
|
||||
* Dead-reckon an aircraft's current position using ENU (East-North-Up) frame math.
|
||||
*
|
||||
@@ -63,8 +107,8 @@ export function createMotion({
|
||||
* source contact plus a bounded grace window.
|
||||
*
|
||||
* @param {string} icao24 - ICAO hex identifier of the aircraft
|
||||
* @param {Cesium.Cartesian3} [result] - Optional out-parameter to write into.
|
||||
* @returns {Cesium.Cartesian3|null} Estimated current ECEF position, or null if no history
|
||||
* @param {{x: number, y: number, z: number}} [result] - Optional out-parameter to write into.
|
||||
* @returns {{x: number, y: number, z: number}|null} Estimated current ECEF position, or null if no history
|
||||
*/
|
||||
|
||||
function _deadReckon(icao24, result) {
|
||||
@@ -77,11 +121,11 @@ export function createMotion({
|
||||
return null;
|
||||
}
|
||||
|
||||
const out = result || new Cesium.Cartesian3();
|
||||
const out = result || vec();
|
||||
// Render one poll interval behind real time so we interpolate between
|
||||
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
const renderTime = addSeconds(
|
||||
julianNow(),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchRenderTime,
|
||||
);
|
||||
@@ -89,10 +133,7 @@ export function createMotion({
|
||||
const regime = _motionRegime(history, info, renderTime);
|
||||
if (regime.kind === 'between') {
|
||||
const { a, b, span } = regime;
|
||||
const t =
|
||||
span > 0
|
||||
? Cesium.JulianDate.secondsDifference(renderTime, a.time) / span
|
||||
: 1.0;
|
||||
const t = span > 0 ? secondsDifference(renderTime, a.time) / span : 1.0;
|
||||
const trackCourse = lerpAngleDeg(regime.trackFrom, regime.trackTo, t);
|
||||
flightState._drCourseDeg =
|
||||
regime.chordCourse != null
|
||||
@@ -100,10 +141,10 @@ export function createMotion({
|
||||
: trackCourse;
|
||||
flightState._drSpeedMps = regime.speed;
|
||||
flightState._drCourseHold = regime.speed < COURSE_HOLD_SPEED_MPS;
|
||||
return Cesium.Cartesian3.lerp(a.position, b.position, t, out);
|
||||
return lerpInto(a.position, b.position, t, out);
|
||||
}
|
||||
const dt = Cesium.Math.clamp(
|
||||
Cesium.JulianDate.secondsDifference(renderTime, regime.fix.time),
|
||||
const dt = clamp(
|
||||
secondsDifference(renderTime, regime.fix.time),
|
||||
regime.minDt,
|
||||
regime.maxDt,
|
||||
);
|
||||
@@ -144,24 +185,26 @@ export function createMotion({
|
||||
flightState._drCourseHold = speed < COURSE_HOLD_SPEED_MPS;
|
||||
if (speed === 0 || dt === 0) {
|
||||
flightState._drCourseDeg = heading;
|
||||
return Cesium.Cartesian3.clone(fix.position, out);
|
||||
return copyInto(fix.position, out);
|
||||
}
|
||||
// Constant-rate-turn arc (straight line when turnRateDps ≈ 0) — a plane in a
|
||||
// standard-rate turn is ~90° of arc wrong per 30 s if extrapolated straight.
|
||||
arcOffsetEnu(speed, heading, turnRateDps, dt, flightState._scratchArc);
|
||||
flightState._drCourseDeg = flightState._scratchArc.endCourseDeg;
|
||||
Cesium.Cartesian3.fromElements(
|
||||
flightState._scratchArc.east,
|
||||
flightState._scratchArc.north,
|
||||
0,
|
||||
flightState._scratchOffset,
|
||||
);
|
||||
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
fix.position,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchEnu,
|
||||
);
|
||||
return Cesium.Matrix4.multiplyByPoint(enu, flightState._scratchOffset, out);
|
||||
const offset = flightState._scratchOffset;
|
||||
offset.x = flightState._scratchArc.east;
|
||||
offset.y = flightState._scratchArc.north;
|
||||
offset.z = 0;
|
||||
let frame = fixFrames.get(fix);
|
||||
if (!frame) {
|
||||
frame = { position: vec(), enu: null };
|
||||
fixFrames.set(fix, frame);
|
||||
}
|
||||
if (!frame.enu || !samePoint(frame.position, fix.position)) {
|
||||
frame.enu = eastNorthUp(fix.position);
|
||||
copyInto(fix.position, frame.position);
|
||||
}
|
||||
return copyInto(framePoint(frame.enu, offset), out);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -175,21 +218,21 @@ export function createMotion({
|
||||
if (!flightState._trackedIcao) return false;
|
||||
const history = flightState._positionHistory.get(flightState._trackedIcao);
|
||||
if (!history || history.length === 0) return true;
|
||||
const renderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
const renderTime = addSeconds(
|
||||
julianNow(),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
return Cesium.JulianDate.lessThan(renderTime, history[0].time);
|
||||
return julianLessThan(renderTime, history[0].time);
|
||||
}
|
||||
|
||||
/** Resolve the selected aircraft's actual rendered square extent this frame. */
|
||||
|
||||
function _trackedFocusSizePx(icao24, position) {
|
||||
const camera = flightState._viewer?.camera;
|
||||
const scene = flightState._viewer?.scene;
|
||||
if (!camera?.positionWC || !position || !scene) return 28;
|
||||
const rangeM = Cesium.Cartesian3.distance(camera.positionWC, position);
|
||||
const pose = _pose();
|
||||
if (!pose || !position) return 28;
|
||||
const rangeM = distance(pose.position, position);
|
||||
const viewportHeightPx = _viewportHeightPx();
|
||||
if (parts.rendering._modelOwnsVisual(icao24)) {
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(icao24)?.klass,
|
||||
@@ -198,12 +241,11 @@ export function createMotion({
|
||||
baseScale: spec.scale,
|
||||
nativeRadiusM: spec.nativeRadiusM,
|
||||
rangeM,
|
||||
viewportHeightPx: scene.canvas.clientHeight,
|
||||
fovyRad: camera.frustum.fovy,
|
||||
viewportHeightPx,
|
||||
fovyRad: pose.fovy,
|
||||
maximumPixelSize: TRACKED_MODEL_MAX_PX,
|
||||
});
|
||||
const focalLengthPx =
|
||||
scene.canvas.clientHeight / (2 * Math.tan(camera.frustum.fovy / 2));
|
||||
const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2));
|
||||
const projectedDiameterPx =
|
||||
(2 * spec.nativeRadiusM * scale * focalLengthPx) / rangeM;
|
||||
return Math.max(
|
||||
@@ -226,16 +268,16 @@ export function createMotion({
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by Cesium
|
||||
* frame number so the position / rotation / trail-head callbacks share ONE computation
|
||||
* Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by drawn
|
||||
* frame (see renderedFrames.js) so the position / rotation / trail-head callbacks share ONE computation
|
||||
* (and one reconciliation-state update) per frame. Returns a stable module holder, or
|
||||
* null when the aircraft has no fix.
|
||||
* @param {string} icao24
|
||||
* @returns {Cesium.Cartesian3|null}
|
||||
* @returns {{x: number, y: number, z: number}|null}
|
||||
*/
|
||||
|
||||
function _trackedDisplayPosition(icao24) {
|
||||
const frame = flightState._viewer?.scene?.frameState?.frameNumber ?? -1;
|
||||
const frame = renderedFrames(flightState._viewer);
|
||||
if (
|
||||
frame === flightState._cachedDRFrame &&
|
||||
icao24 === flightState._drReconcileIcao
|
||||
@@ -266,32 +308,29 @@ export function createMotion({
|
||||
const speed = (info && info.speedMps) || 0;
|
||||
// Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base.
|
||||
const plausible = speed * dtSec * 4 + 25;
|
||||
if (Cesium.Cartesian3.distance(raw, flightState._drPrevRaw) > plausible) {
|
||||
if (distance(raw, flightState._drPrevRaw) > plausible) {
|
||||
// Discontinuity — re-anchor so the DISPLAYED position stays continuous, then decay.
|
||||
Cesium.Cartesian3.subtract(
|
||||
flightState._drPrevDisplay,
|
||||
raw,
|
||||
copyInto(
|
||||
sub(flightState._drPrevDisplay, raw),
|
||||
flightState._drCorrection,
|
||||
);
|
||||
flightState._drCorrectionStartMs = nowMs;
|
||||
}
|
||||
} else {
|
||||
Cesium.Cartesian3.fromElements(0, 0, 0, flightState._drCorrection);
|
||||
copyInto(vec(), flightState._drCorrection);
|
||||
flightState._drCorrectionStartMs = nowMs - DR_CORRECTION_MS; // fully decayed
|
||||
}
|
||||
|
||||
const elapsed = nowMs - flightState._drCorrectionStartMs;
|
||||
const factor =
|
||||
elapsed >= DR_CORRECTION_MS ? 0 : 1 - elapsed / DR_CORRECTION_MS;
|
||||
const display = Cesium.Cartesian3.multiplyByScalar(
|
||||
flightState._drCorrection,
|
||||
factor,
|
||||
const display = copyInto(
|
||||
add(raw, scale(flightState._drCorrection, factor)),
|
||||
flightState._trackedPosHolder,
|
||||
);
|
||||
Cesium.Cartesian3.add(raw, display, display);
|
||||
|
||||
Cesium.Cartesian3.clone(raw, flightState._drPrevRaw);
|
||||
Cesium.Cartesian3.clone(display, flightState._drPrevDisplay);
|
||||
copyInto(raw, flightState._drPrevRaw);
|
||||
copyInto(display, flightState._drPrevDisplay);
|
||||
flightState._drPrevMs = nowMs;
|
||||
flightState._drReconcileValid = true;
|
||||
flightState._cachedDRPosition = display;
|
||||
@@ -299,14 +338,13 @@ export function createMotion({
|
||||
icao24,
|
||||
flightState._cachedDRPosition,
|
||||
);
|
||||
// Publish the exact frame cache shared by entity + follow camera. A second
|
||||
// Publish the exact frame cache shared by billboard + follow camera. A second
|
||||
// DR sample here would advance reconciliation in a different frame phase
|
||||
// and visibly jitter the focus rectangle against the tracked aircraft.
|
||||
publishFocusTargetFromCachedPosition({
|
||||
publishFocusTargetAt({
|
||||
ownerLayer: 'militaryFlights',
|
||||
id: icao24,
|
||||
scene: flightState._viewer?.scene,
|
||||
camera: flightState._viewer?.camera,
|
||||
viewer: flightState._viewer,
|
||||
displayPosition: flightState._cachedDRPosition,
|
||||
widthPx: focusSizePx,
|
||||
heightPx: focusSizePx,
|
||||
@@ -315,8 +353,8 @@ export function createMotion({
|
||||
}
|
||||
|
||||
/** The tracked plane's display position WITHOUT recomputing — the value the follow-camera already
|
||||
* settled on this frame. Mirror of flights.js: getDetectableObjects + the readout run in postRender at
|
||||
* a later frameNumber, so recomputing _trackedDisplayPosition there jitters the label against the
|
||||
* settled on this frame. Mirror of flights.js: getDetectableObjects + the readout run in postRender,
|
||||
* later in the frame, so recomputing _trackedDisplayPosition there jitters the label against the
|
||||
* now-stable plane. Null when no valid fix (callers fall back to the icon position). */
|
||||
|
||||
function _trackedDisplayCached() {
|
||||
@@ -368,10 +406,12 @@ export function createMotion({
|
||||
!parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
)
|
||||
return null;
|
||||
return Cesium.Matrix4.getTranslation(
|
||||
flightState._trackedModel.matrix,
|
||||
flightState._scratchTrailClip,
|
||||
);
|
||||
const m = flightState._trackedModel.matrix;
|
||||
const out = flightState._scratchTrailClip;
|
||||
out.x = m[12];
|
||||
out.y = m[13];
|
||||
out.z = m[14];
|
||||
return out;
|
||||
}
|
||||
|
||||
function _trackedModelEnvelopeM() {
|
||||
@@ -471,7 +511,7 @@ export function createMotion({
|
||||
flightState._cachedDRHold = false;
|
||||
flightState._trackedCourseMs = 0;
|
||||
}
|
||||
/** The display instant `epochMs` as a JulianDate, for `_motionRegime`. */
|
||||
/** The display instant `epochMs` as a Julian date, for `_motionRegime`. */
|
||||
const _displayTimeAt = (epochMs, result) => julianAt(epochMs, result);
|
||||
|
||||
/**
|
||||
@@ -497,15 +537,10 @@ export function createMotion({
|
||||
)
|
||||
continue;
|
||||
info.renderAltitudeM = lifted;
|
||||
const liftedPos = Cesium.Cartesian3.fromDegrees(
|
||||
info.rawLon,
|
||||
info.rawLat,
|
||||
lifted,
|
||||
);
|
||||
const liftedPos = fromDegrees(info.rawLon, info.rawLat, lifted);
|
||||
const hist = flightState._positionHistory.get(icao24);
|
||||
const newest = hist?.[hist.length - 1];
|
||||
if (newest)
|
||||
newest.position = Cesium.Cartesian3.clone(liftedPos, newest.position);
|
||||
if (newest) newest.position = copyInto(liftedPos, newest.position);
|
||||
if (flightState._icons.has(icao24)) {
|
||||
parts.icons._applyIconPresentation(icao24);
|
||||
parts.icons._planIcon(icao24);
|
||||
@@ -515,19 +550,15 @@ export function createMotion({
|
||||
|
||||
/**
|
||||
* Sample the rendered mesh under the collected floor cells (see
|
||||
* meshFloorSampler.js), leaving this layer's own icons and models out of
|
||||
* the probe so it cannot land on an aircraft instead of the pavement.
|
||||
* meshFloorSampler.js), leaving this layer's own icon and model sets out
|
||||
* of the probe so it cannot land on an aircraft instead of the pavement.
|
||||
*/
|
||||
function _sampleMeshFloor(points, viewerLat, viewerLon) {
|
||||
services.meshFloor.sampleMeshFloorCells(
|
||||
flightState._viewer?.scene,
|
||||
points,
|
||||
{
|
||||
excludeObjects: parts.icons._iconIds(),
|
||||
viewerLat,
|
||||
viewerLon,
|
||||
},
|
||||
);
|
||||
services.meshFloor.sampleMeshFloorCells(flightState._viewer, points, {
|
||||
sets: parts.rendering._groundSampleExclusions().sets,
|
||||
viewerLat,
|
||||
viewerLon,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -90,7 +90,7 @@ test('military state owns separate contact maps, motion scratch and ground sampl
|
||||
'_displayCourse',
|
||||
'_positionHistory',
|
||||
'_groundSnap',
|
||||
'_scratchCarto',
|
||||
'_scratchNearbyPos',
|
||||
'_models',
|
||||
'lifetime',
|
||||
]) {
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
|
||||
/** A CSS colour as frozen `[r, g, b, a]`, 0..1 (the renderer's `Color`). */
|
||||
const rgba = (css, alpha) =>
|
||||
Object.freeze(
|
||||
alpha === undefined ? cssColor(css) : [...cssColor(css).slice(0, 3), alpha],
|
||||
);
|
||||
|
||||
/**
|
||||
* @module militaryFlights
|
||||
@@ -21,18 +27,17 @@ import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js';
|
||||
|
||||
export const BILLBOARD_SCALE = 0.7;
|
||||
|
||||
/** @constant {Cesium.Color} Default amber tint for untracked military icons */
|
||||
/** @constant {number[]} Default amber tint for untracked military icons */
|
||||
|
||||
export const MIL_ICON_COLOR = Cesium.Color.fromCssColorString('#FFB800');
|
||||
export const MIL_ICON_COLOR = rgba('#FFB800');
|
||||
|
||||
/** @constant {Cesium.Color} Lighter amber tint applied to the actively tracked aircraft */
|
||||
/** @constant {number[]} Lighter amber tint applied to the actively tracked aircraft */
|
||||
|
||||
export const TRACKED_ICON_COLOR = Cesium.Color.fromCssColorString('#FFD166');
|
||||
export const TRACKED_ICON_COLOR = rgba('#FFD166');
|
||||
|
||||
/** @constant {Cesium.Color} Red tint for aircraft broadcasting an emergency (mirror of flights) */
|
||||
/** @constant {number[]} Red tint for aircraft broadcasting an emergency (mirror of flights) */
|
||||
|
||||
export const EMERGENCY_ICON_COLOR =
|
||||
Cesium.Color.fromCssColorString(EMERGENCY_TINT_CSS);
|
||||
export const EMERGENCY_ICON_COLOR = rgba(EMERGENCY_TINT_CSS);
|
||||
|
||||
// --- Ground traffic (owner reversal 2026-07-03; mirror of flights.js) ---------------
|
||||
// adsb.lol/readsb flags ground traffic with alt_baro === "ground" (no separate
|
||||
@@ -143,16 +148,17 @@ export const MODEL_BELLY_OFFSET_NATIVE = 5.631;
|
||||
|
||||
/** Amber fade target for the tracked billboard once the model takes over (mirrors flights.js CYAN_TRANSPARENT). */
|
||||
|
||||
export const AMBER_TRANSPARENT = MIL_ICON_COLOR.withAlpha(0);
|
||||
export const AMBER_TRANSPARENT = rgba('#FFB800', 0);
|
||||
|
||||
export const COCKPIT_CONTACT_SIZE_PX = 6;
|
||||
|
||||
export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = new Cesium.NearFarScalar(
|
||||
1000,
|
||||
3.0,
|
||||
8000000,
|
||||
0.5,
|
||||
);
|
||||
/** The tracked billboard's size by eye distance (the renderer's `NearFar`). */
|
||||
export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = Object.freeze({
|
||||
near: 1000,
|
||||
nearValue: 3.0,
|
||||
far: 8000000,
|
||||
farValue: 0.5,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Track-history trail state (PRD WS-F F2/F4): a fading polyline behind the
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { cameraOf } from '../../render/cesium/camera.js';
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
import { followedOf } from '../../data/followed.js';
|
||||
import { displayedKinematics } from '../../data/motionModel.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { clone, distance as distanceBetween, vec } from '../../geo/vector.js';
|
||||
import { isExplicitLayerStateOrigin } from '../../data/layerState.js';
|
||||
import { aircraftIncludedInNearby } from '../../data/aircraftNearbyPolicy.js';
|
||||
import { modelVisualAnchor } from '../../data/modelVisualAnchor.js';
|
||||
@@ -89,7 +90,7 @@ export function createQueries({
|
||||
* Build a public descriptor for one aircraft using its best current position
|
||||
* (dead-reckoned when history exists, icon position otherwise).
|
||||
* @param {string} icao24 - ICAO hex identifier of the aircraft.
|
||||
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
|
||||
* @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
|
||||
* Descriptor with a cloned position, or null if the aircraft is unknown.
|
||||
*/
|
||||
|
||||
@@ -97,7 +98,7 @@ export function createQueries({
|
||||
const info = flightState.records.data.get(icao24);
|
||||
const basePos =
|
||||
parts.motion._deadReckon(icao24) ||
|
||||
parts.icons._iconPosition(icao24, new Cesium.Cartesian3());
|
||||
parts.icons._iconPosition(icao24, vec());
|
||||
if (!basePos) return null;
|
||||
const displayed = displayedKinematics({
|
||||
derivedSpeedMps: flightState._drSpeedMps,
|
||||
@@ -105,11 +106,7 @@ export function createQueries({
|
||||
reportedSpeedMps: info?.speedMps,
|
||||
reportedTrackDeg: info?.track,
|
||||
});
|
||||
const carto = Cesium.Cartographic.fromCartesian(
|
||||
basePos,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchCarto,
|
||||
);
|
||||
const carto = toLonLatH(basePos);
|
||||
if (!carto) return null;
|
||||
return {
|
||||
icao24,
|
||||
@@ -118,9 +115,9 @@ export function createQueries({
|
||||
// getTrackedSubject and the voice narration can read it straight off the
|
||||
// descriptor instead of reaching back into `_flightData`.
|
||||
registration: _toCleanText(info?.registration) || null,
|
||||
position: Cesium.Cartesian3.clone(basePos),
|
||||
latitude: Cesium.Math.toDegrees(carto.latitude),
|
||||
longitude: Cesium.Math.toDegrees(carto.longitude),
|
||||
position: clone(basePos),
|
||||
latitude: carto.lat,
|
||||
longitude: carto.lon,
|
||||
// Keep the cockpit readout on the reported aviation altitude. Render
|
||||
// terrain height is a separate visual datum and may be below zero.
|
||||
altitudeM: Number.isFinite(info?.altitudeM)
|
||||
@@ -342,7 +339,7 @@ export function createQueries({
|
||||
/**
|
||||
* Find military aircraft near a given ECEF position, sorted by distance.
|
||||
* Used by proximity-based features (e.g. detection overlay, spatial queries).
|
||||
* @param {Cesium.Cartesian3} center - Reference position in ECEF coordinates
|
||||
* @param {{x: number, y: number, z: number}} center - Reference position in ECEF coordinates
|
||||
* @param {number} range - Maximum distance in meters (Infinity if not specified)
|
||||
* @param {number} [maxCount=50] - Maximum number of results to return
|
||||
* @param {object} [options] Query membership options.
|
||||
@@ -383,9 +380,9 @@ export function createQueries({
|
||||
)
|
||||
continue;
|
||||
|
||||
const distance = Cesium.Cartesian3.distance(center, drawn);
|
||||
const distance = distanceBetween(center, drawn);
|
||||
if (distance > maxRange) continue;
|
||||
const pos = trackedPos || Cesium.Cartesian3.clone(drawn);
|
||||
const pos = trackedPos || clone(drawn);
|
||||
|
||||
const info = flightState.records.data.get(icao24);
|
||||
nearby.push({
|
||||
@@ -423,7 +420,7 @@ export function createQueries({
|
||||
* @param {Object} [options={}] - Options
|
||||
* @param {number} [options.maxCount] - Maximum objects to return (defaults to all)
|
||||
* @param {number} [options.seed] - Seed offset for stride sampling (for frame variation)
|
||||
* @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean}>}
|
||||
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean}>}
|
||||
*/
|
||||
getDetectableObjects(options = {}) {
|
||||
const icons = flightState._icons;
|
||||
@@ -464,8 +461,8 @@ export function createQueries({
|
||||
sourceId: icao24,
|
||||
type: 'AIR',
|
||||
tier: 'military',
|
||||
_weldPos: new Cesium.Cartesian3(),
|
||||
_iconPos: new Cesium.Cartesian3(),
|
||||
_weldPos: vec(),
|
||||
_iconPos: vec(),
|
||||
};
|
||||
flightState._detectionObjects.set(icao24, object);
|
||||
}
|
||||
@@ -488,7 +485,7 @@ export function createQueries({
|
||||
spec,
|
||||
(view ??= parts.rendering._drawnScaleView()),
|
||||
),
|
||||
object._weldPos || (object._weldPos = new Cesium.Cartesian3()),
|
||||
object._weldPos || (object._weldPos = vec()),
|
||||
)
|
||||
: icons.position(icao24, t, object._iconPos);
|
||||
// An icon past the horizon is not drawn, so it is not detectable.
|
||||
@@ -530,7 +527,7 @@ export function createQueries({
|
||||
* Match priority: exact icao24 hex, exact callsign, callsign prefix,
|
||||
* then callsign substring (all case-insensitive, trimmed).
|
||||
* @param {string} query - ICAO hex or full/partial callsign.
|
||||
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
|
||||
* @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
|
||||
* Best match with a cloned, dead-reckoned position, or null if none.
|
||||
*/
|
||||
findByQuery(query) {
|
||||
@@ -574,7 +571,7 @@ export function createQueries({
|
||||
* Cheap snapshot for voice-tool framing — drawn icon positions, no
|
||||
* extra dead reckoning.
|
||||
* @param {number} [maxCount=500] - Maximum number of entries to return.
|
||||
* @returns {Array<{id: string, label: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number}>}
|
||||
* @returns {Array<{id: string, label: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number}>}
|
||||
*/
|
||||
/**
|
||||
* Whether this layer still carries a contact, in O(1).
|
||||
@@ -606,12 +603,8 @@ export function createQueries({
|
||||
|
||||
const result = [];
|
||||
for (const icao24 of icons.ids()) {
|
||||
const pos = icons.position(icao24, t, new Cesium.Cartesian3());
|
||||
const carto = Cesium.Cartographic.fromCartesian(
|
||||
pos,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchCarto,
|
||||
);
|
||||
const pos = icons.position(icao24, t, vec());
|
||||
const carto = toLonLatH(pos);
|
||||
if (!carto) continue;
|
||||
const info = flightState.records.data.get(icao24);
|
||||
result.push({
|
||||
@@ -623,8 +616,8 @@ export function createQueries({
|
||||
_toCleanText(info?.registration) ||
|
||||
icao24,
|
||||
position: pos,
|
||||
latitude: Cesium.Math.toDegrees(carto.latitude),
|
||||
longitude: Cesium.Math.toDegrees(carto.longitude),
|
||||
latitude: carto.lat,
|
||||
longitude: carto.lon,
|
||||
altitudeM: carto.height,
|
||||
});
|
||||
if (result.length >= limit) break;
|
||||
@@ -735,7 +728,6 @@ export function createQueries({
|
||||
if (!flightState._icons?.has(id)) id = id.toLowerCase();
|
||||
if (
|
||||
id !== flightState._trackedIcao ||
|
||||
!flightState._viewer.entities?.contains?.(flightState._trackedEntity) ||
|
||||
followedOf(flightState._viewer) !== flightState._followTarget
|
||||
)
|
||||
return false;
|
||||
@@ -777,7 +769,7 @@ export function createQueries({
|
||||
/**
|
||||
* Return the current aircraft as a Context subject without changing
|
||||
* tracking or camera ownership.
|
||||
* @returns {{layerId: string, id: string, label: string, position: Cesium.Cartesian3}|null}
|
||||
* @returns {{layerId: string, id: string, label: string, position: {x: number, y: number, z: number}}|null}
|
||||
* Detached subject descriptor, or null when no aircraft is tracked.
|
||||
*/
|
||||
getTrackedSubject() {
|
||||
@@ -790,7 +782,7 @@ export function createQueries({
|
||||
// Same label chain as getNearby/getDetectableObjects: a callsign-less
|
||||
// contact reads as its registration, never as the raw ICAO hex.
|
||||
label: described.callsign || described.registration || described.icao24,
|
||||
position: Cesium.Cartesian3.clone(described.position),
|
||||
position: clone(described.position),
|
||||
};
|
||||
},
|
||||
|
||||
|
||||
@@ -32,7 +32,11 @@ function harness({ viewer = null, floor = null } = {}) {
|
||||
records: { data: new Map() },
|
||||
};
|
||||
const parts = {
|
||||
rendering: { _modelOwnsVisual: () => false, _syncModelToClass() {} },
|
||||
rendering: {
|
||||
_modelOwnsVisual: () => false,
|
||||
_syncModelToClass() {},
|
||||
_groundSampleExclusions: () => ({ sets: ['fleet-models', 'icons'] }),
|
||||
},
|
||||
icons: {
|
||||
_iconIds: () => ['icon-primitive'],
|
||||
_addIcon: (id) => iconIds.add(id),
|
||||
@@ -115,10 +119,10 @@ test('the mesh floor probe takes the camera subpoint from the camera port', () =
|
||||
h.apply(CONTACT, 1_700_000_000_000);
|
||||
assert.equal(h.meshCalls.length, 1);
|
||||
const [call] = h.meshCalls;
|
||||
assert.equal(call.scene, viewer.scene);
|
||||
assert.equal(call.scene, viewer);
|
||||
assert.equal(call.options.viewerLat, 30.5);
|
||||
assert.equal(call.options.viewerLon, -97.25);
|
||||
assert.deepEqual(call.options.excludeObjects, ['icon-primitive']);
|
||||
assert.deepEqual(call.options.sets, ['fleet-models', 'icons']);
|
||||
});
|
||||
|
||||
test('without a viewer the mesh floor probe has no camera subpoint', () => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { MilitaryFlightRecords } from './records.js';
|
||||
import { createMilitaryFeed } from './ingestion.js';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
export function createFlightState({ source, services }) {
|
||||
const { createGroundSnap } = services.groundSnap;
|
||||
@@ -50,10 +49,6 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._lastModelCapWarnMs = 0;
|
||||
// throttle the "more planes in view than the cap" console notice
|
||||
flightState._scratchModelBS = new Cesium.BoundingSphere(
|
||||
new Cesium.Cartesian3(),
|
||||
1.0,
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Module-level state
|
||||
@@ -72,7 +67,7 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._detectionObjects = new Map();
|
||||
|
||||
/** @type {Map<string, Array<{time: Cesium.JulianDate, position: Cesium.Cartesian3}>>} ICAO hex -> recent position samples for dead reckoning */
|
||||
/** @type {Map<string, Array<{time: object, position: {x: number, y: number, z: number}}>>} ICAO hex -> recent position samples for dead reckoning */
|
||||
|
||||
flightState._positionHistory = new Map();
|
||||
|
||||
@@ -85,7 +80,7 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._trackingIntentGeneration = 0;
|
||||
|
||||
/** @type {Cesium.Entity|null} Entity created for the tracked aircraft (camera follows this) */
|
||||
/** @type {object|null} The tracked aircraft's record holder (its entity record is what the app shows; the camera follows a target reading it) */
|
||||
|
||||
flightState._trackedEntity = null;
|
||||
|
||||
@@ -102,7 +97,7 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._clickSubscription = null;
|
||||
|
||||
/** @type {Cesium.Viewer|null} Cached viewer reference */
|
||||
/** @type {object|null} Cached viewer reference */
|
||||
|
||||
flightState._viewer = null;
|
||||
|
||||
@@ -132,7 +127,7 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._trailHeadOff = null;
|
||||
|
||||
/** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */
|
||||
/** @type {{x: number, y: number, z: number}[]} Chronological tracked-aircraft fixes (oldest first) */
|
||||
|
||||
flightState._trailPositions = [];
|
||||
|
||||
@@ -148,50 +143,46 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._lastTrackedRotation = 0;
|
||||
|
||||
/** @type {Cesium.Event.RemoveCallback|null} preRender listener disposer */
|
||||
/** @type {() => void|null} preRender listener disposer */
|
||||
|
||||
flightState._preRenderRemove = null;
|
||||
|
||||
flightState._trackedModelPreUpdateRemove = null;
|
||||
|
||||
/** @type {Cesium.Event.RemoveCallback|null} camera.moveEnd listener disposer (arrival rotation pass) */
|
||||
/** @type {() => void|null} camera.moveEnd listener disposer (arrival rotation pass) */
|
||||
|
||||
flightState._moveEndRemove = null;
|
||||
|
||||
/** @type {Cesium.Event.RemoveCallback|null} trackedEntityChanged listener disposer (cross-layer untrack) */
|
||||
/** @type {() => void|null} trackedEntityChanged listener disposer (cross-layer untrack) */
|
||||
|
||||
flightState._trackedEntityChangedRemove = null;
|
||||
|
||||
// -- Scratch variables (reused each frame to avoid GC pressure) --
|
||||
|
||||
flightState._scratchOffset = new Cesium.Cartesian3();
|
||||
|
||||
flightState._scratchCarto = new Cesium.Cartographic();
|
||||
|
||||
flightState._scratchEnu = new Cesium.Matrix4();
|
||||
flightState._scratchOffset = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchArc = { east: 0, north: 0, endCourseDeg: 0 };
|
||||
|
||||
flightState._scratchRenderTime = new Cesium.JulianDate();
|
||||
flightState._scratchRenderTime = { dayNumber: 0, secondsOfDay: 0 };
|
||||
|
||||
flightState._scratchFleetRenderTime = new Cesium.JulianDate();
|
||||
flightState._scratchFleetRenderTime = { dayNumber: 0, secondsOfDay: 0 };
|
||||
|
||||
flightState._scratchFleetPos = new Cesium.Cartesian3();
|
||||
flightState._scratchFleetPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchCockpitPos = new Cesium.Cartesian3();
|
||||
flightState._scratchCockpitPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchNearbyPos = new Cesium.Cartesian3();
|
||||
flightState._scratchNearbyPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchSonarScreen = new Cesium.Cartesian2();
|
||||
flightState._scratchSonarScreen = { x: 0, y: 0 };
|
||||
|
||||
flightState._scratchDrRaw = new Cesium.Cartesian3();
|
||||
flightState._scratchDrRaw = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._scratchWarmupTime = new Cesium.JulianDate();
|
||||
flightState._scratchWarmupTime = { dayNumber: 0, secondsOfDay: 0 };
|
||||
|
||||
flightState._trackedPosHolder = new Cesium.Cartesian3();
|
||||
flightState._trackedPosHolder = { x: 0, y: 0, z: 0 };
|
||||
|
||||
// -- Per-frame dead-reckoning cache for the tracked entity --
|
||||
/** @type {Cesium.Cartesian3|null} Cached DR position for the current render frame */
|
||||
/** @type {{x: number, y: number, z: number}|null} Cached DR position for the current render frame */
|
||||
|
||||
flightState._cachedDRPosition = null;
|
||||
|
||||
@@ -240,13 +231,13 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._displayCourse = new Map();
|
||||
|
||||
flightState._drCorrection = new Cesium.Cartesian3(0, 0, 0);
|
||||
flightState._drCorrection = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._drCorrectionStartMs = 0;
|
||||
|
||||
flightState._drPrevRaw = new Cesium.Cartesian3();
|
||||
flightState._drPrevRaw = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._drPrevDisplay = new Cesium.Cartesian3();
|
||||
flightState._drPrevDisplay = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._drPrevMs = 0;
|
||||
|
||||
@@ -256,20 +247,20 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._drReconcileIcao = null;
|
||||
|
||||
/** @type {Cesium.Cartesian3} Scratch for the tracked model's rendered translation. */
|
||||
/** @type {{x: number, y: number, z: number}} Scratch for the tracked model's rendered translation. */
|
||||
|
||||
flightState._trackedVisualPos = new Cesium.Cartesian3();
|
||||
flightState._trackedVisualPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
flightState._trackedTrailPos = new Cesium.Cartesian3();
|
||||
flightState._trackedTrailPos = { x: 0, y: 0, z: 0 };
|
||||
|
||||
/** Scratch for the tracked model's world-space origin (the envelope centre). */
|
||||
|
||||
flightState._scratchTrailClip = new Cesium.Cartesian3();
|
||||
flightState._scratchTrailClip = { x: 0, y: 0, z: 0 };
|
||||
|
||||
/** Scratch for the shortened trail-head start. Owned by the head-segment
|
||||
* callback alone, so nothing else can overwrite it mid-frame. */
|
||||
|
||||
flightState._scratchTrailHead = new Cesium.Cartesian3();
|
||||
flightState._scratchTrailHead = { x: 0, y: 0, z: 0 };
|
||||
|
||||
/** Hysteresis latch for the tracked contact's zoom regime, plus the selection it
|
||||
* belongs to. Scoped per selection so a NEW target re-evaluates against the ENTER
|
||||
@@ -285,8 +276,5 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._irBoost = false;
|
||||
|
||||
/** @type {Cesium.Cartographic} Scratch for _trailFloorPosition (per-frame safe). */
|
||||
|
||||
flightState._scratchTrailCarto = new Cesium.Cartographic();
|
||||
return flightState;
|
||||
}
|
||||
+139
-151
@@ -1,19 +1,30 @@
|
||||
import { cameraOf } from '../../render/cesium/camera.js';
|
||||
import { findFrame } from '../../render/rendererOf.js';
|
||||
import { cameraOf, findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import {
|
||||
entityFollowTarget,
|
||||
onFollowChanged,
|
||||
stopFollowing,
|
||||
} from '../../data/followed.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js';
|
||||
import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js';
|
||||
import { trackedModelZoomActive } from '../../data/trackedModelRegime.js';
|
||||
import {
|
||||
screenProjectedRotation,
|
||||
courseScreenRotation,
|
||||
stabilizeScreenRotation,
|
||||
} from '../../data/iconOrientation.js';
|
||||
} from '../../data/screenRotation.js';
|
||||
import {
|
||||
createTrackedAircraftIcon,
|
||||
isOtherTrackedIconSet,
|
||||
trackedContactHolder,
|
||||
} from '../../data/trackedAircraftIcon.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import {
|
||||
addSeconds,
|
||||
julianLessThanOrEquals,
|
||||
julianNow,
|
||||
julianToEpochMs,
|
||||
} from '../../geo/julian.js';
|
||||
import { clone, distanceSquared, vec } from '../../geo/vector.js';
|
||||
import { trailHeadStart } from '../../data/modelVisualAnchor.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import {
|
||||
@@ -41,7 +52,7 @@ function aircraftPickId(picked) {
|
||||
const id = picked?.id;
|
||||
if (typeof id === 'string') return id;
|
||||
if (id && typeof id.set === 'string' && typeof id.id === 'string')
|
||||
return id.id;
|
||||
return isOtherTrackedIconSet(id.set, 'military') ? undefined : id.id;
|
||||
return picked?.primitive?.id;
|
||||
}
|
||||
|
||||
@@ -67,6 +78,21 @@ export function createTracking({
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const { FOLLOW_MIN_RANGE_M } = services.camera;
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
/** The tracked contact's billboard (an icon set on the draw port). */
|
||||
const trackedIcon = createTrackedAircraftIcon({
|
||||
viewer: () => flightState._viewer,
|
||||
setPrefix: 'military',
|
||||
});
|
||||
|
||||
/** The camera's pose, or null without a camera to ask. */
|
||||
function _pose() {
|
||||
const viewer = flightState._viewer;
|
||||
try {
|
||||
return (viewer && findCamera(viewer)?.pose()) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function _emitAwarenessEvent(type, detail) {
|
||||
if (
|
||||
@@ -79,7 +105,7 @@ export function createTracking({
|
||||
}
|
||||
|
||||
function _publishTrackedSelection(icao24, origin = 'programmatic') {
|
||||
const position = parts.icons._iconPosition(icao24, new Cesium.Cartesian3());
|
||||
const position = parts.icons._iconPosition(icao24, vec());
|
||||
const info = flightState.records.data.get(icao24);
|
||||
if (!position || !info) return false;
|
||||
if (flightState._trackedEntity)
|
||||
@@ -157,10 +183,8 @@ export function createTracking({
|
||||
/** Refresh the AIR-only Cockpit near band independently from model admission. */
|
||||
|
||||
function _refreshCockpitNearContacts() {
|
||||
if (
|
||||
!flightState._cockpitContactMode ||
|
||||
!flightState._viewer?.camera?.positionWC
|
||||
) {
|
||||
const eye = flightState._cockpitContactMode ? _pose()?.position : null;
|
||||
if (!eye) {
|
||||
if (flightState._cockpitNearContacts.size)
|
||||
flightState._cockpitNearContacts = new Set();
|
||||
return;
|
||||
@@ -176,13 +200,7 @@ export function createTracking({
|
||||
t,
|
||||
flightState._scratchCockpitPos,
|
||||
);
|
||||
distancesSquared.push([
|
||||
icao24,
|
||||
Cesium.Cartesian3.distanceSquared(
|
||||
flightState._viewer.camera.positionWC,
|
||||
position,
|
||||
),
|
||||
]);
|
||||
distancesSquared.push([icao24, distanceSquared(eye, position)]);
|
||||
}
|
||||
const next = nextCockpitNearContacts(
|
||||
previous,
|
||||
@@ -284,12 +302,9 @@ export function createTracking({
|
||||
refreshTrackedSubjectContext(_contextSubjectMetadata(icao24));
|
||||
}
|
||||
|
||||
/** Re-image the tracked entity's billboard from the current class/conversion. */
|
||||
|
||||
function _syncTrackedBillboardImage() {
|
||||
if (!flightState._trackedIcao || !flightState._trackedEntity?.billboard)
|
||||
return;
|
||||
flightState._trackedEntity.billboard.image = aircraftIcon(
|
||||
/** The tracked billboard's image, from the current class/conversion. */
|
||||
function _trackedBillboardImage() {
|
||||
return aircraftIcon(
|
||||
parts.rendering._iconKind(
|
||||
flightState._trackedIcao,
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
@@ -298,6 +313,13 @@ export function createTracking({
|
||||
);
|
||||
}
|
||||
|
||||
/** Re-image the tracked billboard from the current class/conversion. */
|
||||
|
||||
function _syncTrackedBillboardImage() {
|
||||
if (!flightState._trackedIcao || !flightState._trackedEntity) return;
|
||||
trackedIcon.setImage(_trackedBillboardImage());
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-render one contact after its TR-3B conversion (or the active IR style)
|
||||
* changed. Mirror of flights.js: converting drops any 3D model so the triangle
|
||||
@@ -325,7 +347,8 @@ export function createTracking({
|
||||
_syncTrackedBillboardImage();
|
||||
_updateTrackedLabelModel(id);
|
||||
}
|
||||
flightState._viewer?.scene?.requestRender?.();
|
||||
if (flightState._viewer)
|
||||
findFrame(flightState._viewer)?.requestRender('military: TR-3B restyle');
|
||||
return flightState._icons?.has(id) || id === flightState._trackedIcao;
|
||||
}
|
||||
|
||||
@@ -384,7 +407,7 @@ export function createTracking({
|
||||
return false;
|
||||
}
|
||||
flightState._trackedZoomLatched = trackedModelZoomActive(
|
||||
flightState._viewer?.camera?.positionCartographic?.height,
|
||||
_pose()?.height,
|
||||
flightState._trackedZoomLatched,
|
||||
);
|
||||
return flightState._trackedZoomLatched;
|
||||
@@ -396,13 +419,10 @@ export function createTracking({
|
||||
if (!flightState._trackedIcao || !flightState._viewer) return;
|
||||
const pos =
|
||||
parts.motion._trackedDisplayCached() ||
|
||||
parts.icons._iconPosition(
|
||||
flightState._trackedIcao,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
parts.icons._iconPosition(flightState._trackedIcao, vec());
|
||||
if (!pos) return;
|
||||
const projected = screenProjectedRotation(
|
||||
flightState._viewer.scene,
|
||||
const projected = courseScreenRotation(
|
||||
_pose(),
|
||||
pos,
|
||||
parts.motion._trackedDisplayCourse(),
|
||||
flightState._lastTrackedRotation,
|
||||
@@ -423,31 +443,27 @@ export function createTracking({
|
||||
* invariant), so every position entering the TRAIL subsystem (seed, append,
|
||||
* per-frame head) goes through this instead — the visible taxi history sits
|
||||
* on the surface without touching the billboard/model machinery.
|
||||
* @param {Cesium.Cartesian3} position - Owned position (mutated/replaced freely).
|
||||
* @returns {Cesium.Cartesian3} The same or a lifted position.
|
||||
* @param {{x: number, y: number, z: number}} position - Owned ECEF position (mutated/replaced freely).
|
||||
* @returns {{x: number, y: number, z: number}} The same or a lifted position.
|
||||
*/
|
||||
|
||||
function _trailFloorPosition(position) {
|
||||
const carto = Cesium.Cartographic.fromCartesian(
|
||||
position,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
flightState._scratchTrailCarto,
|
||||
);
|
||||
const carto = toLonLatH(position);
|
||||
if (!carto) return position;
|
||||
const latDeg = Cesium.Math.toDegrees(carto.latitude);
|
||||
const lonDeg = Cesium.Math.toDegrees(carto.longitude);
|
||||
const latDeg = carto.lat;
|
||||
const lonDeg = carto.lon;
|
||||
const floored = floorAltitudeM(
|
||||
carto.height,
|
||||
cachedGroundFloor(latDeg, lonDeg),
|
||||
);
|
||||
if (floored == null || floored === carto.height) return position;
|
||||
return Cesium.Cartesian3.fromDegrees(lonDeg, latDeg, floored);
|
||||
return fromDegrees(lonDeg, latDeg, floored);
|
||||
}
|
||||
|
||||
/**
|
||||
* Append one fix to the tracked aircraft's trail accumulation and refresh
|
||||
* the rendered trail. Caller passes an owned (cloned) Cartesian3.
|
||||
* @param {Cesium.Cartesian3} position - New fix position, appended at the head.
|
||||
* @param {{x: number, y: number, z: number}} position - New ECEF fix, appended at the head.
|
||||
*/
|
||||
|
||||
function _appendTrailFix(position) {
|
||||
@@ -478,7 +494,7 @@ export function createTracking({
|
||||
/**
|
||||
* The live head: the last DISPLAYED body point to the delayed head, or no
|
||||
* positions while there is none.
|
||||
* @returns {Cesium.Cartesian3[]}
|
||||
* @returns {Array<{x: number, y: number, z: number}>}
|
||||
*/
|
||||
function _trailHeadPositions() {
|
||||
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
|
||||
@@ -503,7 +519,7 @@ export function createTracking({
|
||||
// Floor the head too (round 2): a grounded tracked contact's DR
|
||||
// display height is the pre-datum default — without this the last
|
||||
// segment dives underground while taxiing.
|
||||
const end = _trailFloorPosition(Cesium.Cartesian3.clone(head));
|
||||
const end = _trailFloorPosition(clone(head));
|
||||
// On a contact that has not moved this segment runs from inside the
|
||||
// model out to its own anchor — a line through the fuselage. The END
|
||||
// never gives, so a moving trail still terminates on the tail; the
|
||||
@@ -541,18 +557,18 @@ export function createTracking({
|
||||
// Seed only fixes at/behind the DELAYED display time (now − RENDER_DELAY_SEC). The
|
||||
// newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them
|
||||
// would draw the trail in front of the plane. They join via _appendTrailFix as they age.
|
||||
const seedRenderTime = Cesium.JulianDate.addSeconds(
|
||||
Cesium.JulianDate.now(),
|
||||
const seedRenderTime = addSeconds(
|
||||
julianNow(),
|
||||
-RENDER_DELAY_SEC,
|
||||
flightState._scratchWarmupTime,
|
||||
);
|
||||
for (const fix of history) {
|
||||
if (Cesium.JulianDate.lessThanOrEquals(fix.time, seedRenderTime)) {
|
||||
if (julianLessThanOrEquals(fix.time, seedRenderTime)) {
|
||||
// Floor grounded-history seeds (round 2): a grounded contact's stored
|
||||
// fixes carry the pre-datum default height — the trail copy sits on
|
||||
// the surface instead (pure lift; airborne fixes pass through).
|
||||
flightState._trailPositions.push(
|
||||
_trailFloorPosition(Cesium.Cartesian3.clone(fix.position)),
|
||||
_trailFloorPosition(clone(fix.position)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -574,7 +590,7 @@ export function createTracking({
|
||||
_refreshTrailDisplay();
|
||||
|
||||
const oldestFixEpochSec = history.length
|
||||
? Cesium.JulianDate.toDate(history[0].time).getTime() / 1000
|
||||
? julianToEpochMs(history[0].time) / 1000
|
||||
: Infinity;
|
||||
_backfillTrail(icao24, flightState._trailBackfillToken, oldestFixEpochSec);
|
||||
}
|
||||
@@ -664,7 +680,7 @@ export function createTracking({
|
||||
// sentinel (an arbitrary placeholder, never a reported altitude).
|
||||
if (altM == null) altM = lastAltM != null ? lastAltM : 50;
|
||||
lastAltM = altM;
|
||||
older.push(Cesium.Cartesian3.fromDegrees(lon, lat, altM));
|
||||
older.push(fromDegrees(lon, lat, altM));
|
||||
}
|
||||
|
||||
// Stride-thin the backfill so it plus the live fine segment fit the cap.
|
||||
@@ -749,17 +765,15 @@ export function createTracking({
|
||||
// release never flips it.
|
||||
const trackedCourseDeg = flightState._displayCourse.get(clearedIcao);
|
||||
|
||||
// Stop tracking and remove the entity. skipViewerUntrack: another layer just grabbed the
|
||||
// follow-camera, so tear down our state but DON'T clear the camera's follow (they own it now).
|
||||
// Releasing trackedEntity does NOT move the camera: Cesium resets the lookAt transform in
|
||||
// place, so the view stays where the follow left it and the user can immediately orbit/zoom.
|
||||
// Stop tracking and hide the tracked billboard. skipViewerUntrack: another layer just grabbed
|
||||
// the follow-camera, so tear down our state but DON'T clear the camera's follow (they own it
|
||||
// now). Releasing the follow does NOT move the camera: the view stays where the follow left it
|
||||
// and the user can immediately orbit/zoom.
|
||||
if (flightState._viewer && !skipViewerUntrack) {
|
||||
stopFollowing(flightState._viewer);
|
||||
}
|
||||
if (flightState._trackedEntity) {
|
||||
flightState._viewer.entities.remove(flightState._trackedEntity);
|
||||
flightState._trackedEntity = null;
|
||||
}
|
||||
trackedIcon.hide();
|
||||
flightState._trackedEntity = null;
|
||||
parts.rendering._releaseTrackedModel();
|
||||
_resetTrackedSelectionState(); // the zoom band belongs to the selection we just dropped
|
||||
flightState._trackedIcao = null;
|
||||
@@ -820,19 +834,14 @@ export function createTracking({
|
||||
// The tracked limiter continues from the nose the icon was drawn with, and
|
||||
// the entity starts with the rotation the icon had on screen.
|
||||
const t = parts.icons._displayMs();
|
||||
const iconPosition = icons.position(icao24, t, new Cesium.Cartesian3());
|
||||
const iconPosition = icons.position(icao24, t, vec());
|
||||
const iconCourse = icons.course(icao24, t);
|
||||
flightState._displayCourse.set(icao24, iconCourse);
|
||||
flightState._trackedIcao = icao24;
|
||||
_resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._lastTrackedRotation =
|
||||
screenProjectedRotation(
|
||||
flightState._viewer.scene,
|
||||
iconPosition,
|
||||
iconCourse,
|
||||
0,
|
||||
) ?? 0;
|
||||
courseScreenRotation(_pose(), iconPosition, iconCourse, 0) ?? 0;
|
||||
// Drop any fleet 3D model for this aircraft — the tracked entity now owns its visual (its
|
||||
// own billboard + model graphic), and the fleet tick skips the tracked icao, so a leftover
|
||||
// fleet model would be orphaned + double-rendered.
|
||||
@@ -847,28 +856,20 @@ export function createTracking({
|
||||
// aircraft has no fix.
|
||||
const getTrackedPosition = () =>
|
||||
parts.motion._trackedDisplayPosition(icao24) ||
|
||||
parts.icons._iconPosition(icao24, new Cesium.Cartesian3()) ||
|
||||
parts.icons._iconPosition(icao24, vec()) ||
|
||||
iconPosition;
|
||||
|
||||
// Dead-reckoning position property evaluated every render frame.
|
||||
// isConstant = false so CesiumJS re-evaluates each frame.
|
||||
const positionProperty = new Cesium.CallbackProperty(() => {
|
||||
return getTrackedPosition();
|
||||
}, false);
|
||||
|
||||
// World-space orientation for the 3D model: nose along the course heading (ENU, pitch/roll 0).
|
||||
// Create tracked entity: a 2D billboard when zoomed out, a 3D model when zoomed in past the
|
||||
// TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on the
|
||||
// DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always
|
||||
// The tracked billboard: a 2D icon when zoomed out, handing over to the 3D model when zoomed
|
||||
// in past the TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on
|
||||
// the DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always
|
||||
// resolves into an aircraft.
|
||||
//
|
||||
// The billboard stays SHOWN at all times and is hidden by going TRANSPARENT (alpha 0), not by
|
||||
// show=false: it drops its alpha only once the tracked model is drawing, so
|
||||
// there's neither a billboard+model double-image nor a gap. The camera follows its own target
|
||||
// through the camera port, so nothing here frames the camera.
|
||||
// The tracked entity is a PURE BILLBOARD — no label or model graphic. The tracked plane's 3D
|
||||
// model is the standalone primitive driven by _updateTrackedModel(); it stays off the entity (see _trackedModel).
|
||||
// What the tracked billboard is drawn at, kept in its entity record so the
|
||||
// show=false: it drops its alpha only once the tracked model is drawing, so there's neither a
|
||||
// billboard+model double-image nor a gap. The camera follows its own target through the camera
|
||||
// port, so nothing here frames the camera. The tracked plane's 3D model is a draw-set item
|
||||
// driven by _updateTrackedModel() (see _trackedModel).
|
||||
// What the tracked billboard is drawn at, kept in its record so the
|
||||
// camera guard and screen annotations size it from the app.
|
||||
const sprite = {
|
||||
width: 28,
|
||||
@@ -880,58 +881,49 @@ export function createTracking({
|
||||
] || 1),
|
||||
scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
|
||||
};
|
||||
flightState._trackedEntity = flightState._viewer.entities.add({
|
||||
position: positionProperty,
|
||||
billboard: {
|
||||
image: aircraftIcon(
|
||||
parts.rendering._iconKind(
|
||||
flightState._trackedIcao,
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
),
|
||||
TRACKED_ICON_PX,
|
||||
),
|
||||
width: sprite.width,
|
||||
height: sprite.height,
|
||||
scale: sprite.scale,
|
||||
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
|
||||
// transparent once the STANDALONE tracked model is actually up (ready + shown).
|
||||
color: new Cesium.CallbackProperty(
|
||||
() =>
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
? AMBER_TRANSPARENT
|
||||
: TRACKED_ICON_COLOR,
|
||||
false,
|
||||
),
|
||||
sizeInMeters: false,
|
||||
scaleByDistance: sprite.scaleByDistance,
|
||||
alignedAxis: Cesium.Cartesian3.ZERO,
|
||||
// The tracked target must never vanish into tile geometry — tracking a
|
||||
// taxiing plane at street level would otherwise bury the amber icon inside
|
||||
// the runway skin, so it draws depth-test-free like the fleet icon set;
|
||||
// its shared-host tracked card is top-composited separately.
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
// Screen-projected rotation, evaluated per frame: exact in tracked-orbit
|
||||
// mode where camera.heading lives in the entity's reference frame.
|
||||
rotation: new Cesium.CallbackProperty(() => {
|
||||
const tracked = flightState.records.data.get(
|
||||
flightState._trackedIcao,
|
||||
);
|
||||
const pos = getTrackedPosition();
|
||||
if (!tracked || !pos || !flightState._viewer)
|
||||
return flightState._lastTrackedRotation;
|
||||
const projected = screenProjectedRotation(
|
||||
flightState._viewer.scene,
|
||||
pos,
|
||||
parts.motion._trackedDisplayCourse(),
|
||||
flightState._lastTrackedRotation,
|
||||
);
|
||||
const rot = stabilizeScreenRotation(
|
||||
flightState._lastTrackedRotation,
|
||||
projected,
|
||||
);
|
||||
if (rot !== null) flightState._lastTrackedRotation = rot;
|
||||
// The tracked contact as its readers see it (the tracked card, Cockpit, share links): a
|
||||
// plain holder of its entity record, drawn while it is the one tracked.
|
||||
const holder = trackedContactHolder(
|
||||
`military:${icao24}`,
|
||||
trackedIcon,
|
||||
parts.motion._trackedDisplayCached,
|
||||
);
|
||||
flightState._trackedEntity = holder;
|
||||
entityRecord(holder).drawn = () => flightState._trackedEntity === holder;
|
||||
trackedIcon.show({
|
||||
id: icao24,
|
||||
image: _trackedBillboardImage(),
|
||||
sprite,
|
||||
position: getTrackedPosition,
|
||||
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
|
||||
// transparent once the tracked model is actually up (ready + shown).
|
||||
color: () =>
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
? AMBER_TRANSPARENT
|
||||
: TRACKED_ICON_COLOR,
|
||||
// Screen-projected rotation, evaluated per frame on the camera's own
|
||||
// axes, so it stays exact through a tracked orbit. The tracked target
|
||||
// must never vanish into tile geometry — tracking a taxiing plane at
|
||||
// street level would otherwise bury the amber icon inside the runway
|
||||
// skin, so it draws over depth like the fleet icon set; its
|
||||
// shared-host tracked card is top-composited separately.
|
||||
rotation: () => {
|
||||
const tracked = flightState.records.data.get(flightState._trackedIcao);
|
||||
const pos = getTrackedPosition();
|
||||
if (!tracked || !pos || !flightState._viewer)
|
||||
return flightState._lastTrackedRotation;
|
||||
}, false),
|
||||
const projected = courseScreenRotation(
|
||||
_pose(),
|
||||
pos,
|
||||
parts.motion._trackedDisplayCourse(),
|
||||
flightState._lastTrackedRotation,
|
||||
);
|
||||
const rot = stabilizeScreenRotation(
|
||||
flightState._lastTrackedRotation,
|
||||
projected,
|
||||
);
|
||||
if (rot !== null) flightState._lastTrackedRotation = rot;
|
||||
return flightState._lastTrackedRotation;
|
||||
},
|
||||
});
|
||||
entityRecord(flightState._trackedEntity).selectionOrigin = origin;
|
||||
@@ -940,20 +932,16 @@ export function createTracking({
|
||||
entityRecord(flightState._trackedEntity).labelModel =
|
||||
trackedLabelModelFromText(_buildTrackedLabel(info, icao24), '#ffd166');
|
||||
|
||||
// A billboard has a ~zero bounding sphere, so Cesium's default follow distance is
|
||||
// far too tight (the user had to scroll out to read the plane). Give the entity a
|
||||
// A billboard has a ~zero bounding sphere, so the renderer's default follow distance is
|
||||
// far too tight (the user had to scroll out to read the plane). Give the target a
|
||||
// calibrated viewFrom — behind + above, distance scaled to altitude — for a readable
|
||||
// initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.)
|
||||
const altM = info?.altitudeFt ? info.altitudeFt * 0.3048 : 1500;
|
||||
const followRange = Math.min(Math.max(altM * 1.1 + 2500, 3000), 30000);
|
||||
const viewFrom = new Cesium.Cartesian3(
|
||||
0,
|
||||
-followRange * 0.8,
|
||||
followRange * 0.55,
|
||||
);
|
||||
const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55);
|
||||
|
||||
// Cancel any in-progress camera flight first — otherwise Cesium won't apply the tracked
|
||||
// entity's viewFrom on the first frame, so voice-initiated tracking (which often fires
|
||||
// Cancel any in-progress camera flight first — otherwise the camera won't apply the follow
|
||||
// target's viewFrom on the first frame, so voice-initiated tracking (which often fires
|
||||
// mid-fly_to_location) would follow the plane WITHOUT centering it like a click does.
|
||||
// Cross-module HUD consumers (tracked-target readout) read the camera's settled position, not a
|
||||
// postRender recompute, so the label doesn't jitter against the now-stable plane (mirror of flights).
|
||||
@@ -1011,7 +999,7 @@ export function createTracking({
|
||||
* Clicking a military billboard starts tracking that aircraft; clicking empty
|
||||
* space or a non-military object deselects. Also attaches the Escape key
|
||||
* listener via {@link _onKeyDown}. Idempotent -- no-ops if already installed.
|
||||
* @param {Cesium.Viewer} viewer - The Cesium viewer instance
|
||||
* @param {object} viewer - The viewer
|
||||
*/
|
||||
|
||||
function _installClickHandler(viewer) {
|
||||
@@ -1051,14 +1039,11 @@ export function createTracking({
|
||||
const picked = event.hit;
|
||||
|
||||
if (picked) {
|
||||
// Clicking the tracked entity itself -- ignore (don't deselect)
|
||||
if (picked.id === flightState._trackedEntity) return;
|
||||
|
||||
// Clicking the plane we're ALREADY tracking (its standalone 3D model or
|
||||
// any pick carrying its icao) — same no-op as the 2D tracked-entity click
|
||||
// above. H1: the model used to have no pick id, so this fell through to
|
||||
// Clicking the plane we're ALREADY tracking (its tracked billboard, its
|
||||
// 3D model, or any pick carrying its icao) — ignore, don't deselect.
|
||||
// H1: the model used to have no pick id, so this fell through to
|
||||
// "empty space" and deselected the very plane being tracked.
|
||||
// Its models are draw-set items keyed by icao, like its icons.
|
||||
// Its billboard and models are draw-set items keyed by icao, like its icons.
|
||||
const pickedIcao = aircraftPickId(picked);
|
||||
if (flightState._trackedIcao && pickedIcao === flightState._trackedIcao)
|
||||
return;
|
||||
@@ -1114,6 +1099,9 @@ export function createTracking({
|
||||
_backfillTrail,
|
||||
_clearTrail,
|
||||
_destroyTrail,
|
||||
/** Let the tracked billboard's set go (layer teardown). */
|
||||
_disposeTrackedIcon: () => trackedIcon.dispose(),
|
||||
/** The tracked billboard's set id, or null before one is made. */
|
||||
_clearTracking,
|
||||
_applyPendingTrackingRestore,
|
||||
_cancelPendingTrackingRestore,
|
||||
|
||||
Reference in new issue
Block a user