Aircraft drawn as far behind real time as their feed is late, along one curve their trail follows

Civil and military aircraft were drawn a fixed 30 s (15 s) behind real time
while anonymous feed reports arrive about 90 s old every 30 s, so every
contact dead reckoned about a minute past its newest report and snapped
when the next one landed (several km on a turn), and the tracked trail,
recorded from those drawn positions and patched as reports arrived, kinked.

- The display delay (data/displayDelay.js) is the 90th percentile of the
  newest 256 report lags plus 5 s, between the layer's floor (30 s, 15 s)
  and five minutes, slewed at most 0.2 s/s up and 0.05 s/s down. Icons,
  the renderer's live motion clock, labels, HUD, detection, the tracked
  camera and the trail read the one delay; following the world clock
  draws with none and deliveries leave it alone.
- Between two reports an aircraft flies a biarc (data/fixCurve.js) that
  passes through both and leaves each along its track, sent as contract
  arc segments; the trail is the reports joined along the same curve, so
  the icon sits on it. Nothing drawn between reports is kept.
- A report a coasting contact missed is eased onto from where it would
  have been that frame (at least 3 s, at most 30% over its speed, within
  20 s); over 5 km it jumps. Past its newest report a contact coasts
  straight on: a turn rate averaged over earlier reports outlived the turn.
- Forward synthetic fixes no longer block real reports older than them,
  and a history keeps 24 fixes.
- A feed simulation (testSupport/aircraftFeedSim.mjs) checks both layers
  against a 90 s late feed, a fallback switch, repeated reports, outages
  and the world clock.
This commit is contained in:
Sameh Khamis committed 2026-11-14 00:31:29 -08:00
1 parent c57eb74506
commit 5f98f8bdf3
40 files changed
+2606 -1238

No files matched your search

+81 -10
View File
@@ -2,13 +2,18 @@ import {
COAST_FLOOR_LIFT_M,
COURSE_HOLD_SPEED_MPS,
courseSlewCapDps,
RECOVER_MIN_M,
RECOVER_SNAP_M,
recoveryMs,
} from './motionModel.js';
import { straightSegment } from './fixCurve.js';
import {
norm180,
distance,
clone,
copyInto,
toDegrees,
vec,
} from '../geo/vector.js';
import { fromRadians, toCartographicRadians } from '../geo/ellipsoid.js';
import { horizonFrom, liftedForHorizon } from '../geo/horizon.js';
@@ -349,6 +354,14 @@ export function floorCoastArc(arc, t, cachedGroundFloor) {
let instances = 0;
/** A plan that ran out longer ago than this (ms) is not eased away from. */
const RECOVER_STALE_PLAN_MS = 1_000;
/** A display delay that never changes (ms). */
function fixedDelay(ms) {
return { currentMs: ms, step: () => ms };
}
/**
* An aircraft layer's contacts as one icon draw set: each item's motion
* segment mirrors the layer's dead reckoning for the delayed display time,
@@ -369,7 +382,10 @@ let instances = 0;
* @param {object} options.services The layer's services (`focus`).
* @param {object} options.parts The layer's parts (`motion`, `rendering`).
* @param {string} options.layerId Pick and focus owner id.
* @param {number} options.renderDelaySec How far behind real time contacts draw.
* @param {{currentMs: number, step: (nowMs: number) => number}} [options.displayDelay]
* How far behind real time contacts draw (`data/displayDelay`), stepped
* once a frame; the renderer's motion clock follows it.
* @param {number} [options.renderDelaySec] A fixed delay instead.
* @param {() => boolean} [options.followsClock] True while the layer follows
* the world clock: contacts draw at the world's time (`state.now()`, the
* scene's time) with no delay.
@@ -389,7 +405,8 @@ export function createAircraftIcons({
services,
parts,
layerId,
renderDelaySec,
renderDelaySec = 0,
displayDelay = fixedDelay(renderDelaySec * 1000),
followsClock = () => false,
staleAlpha = 0.45,
courseMaxDps,
@@ -400,29 +417,40 @@ export function createAircraftIcons({
onForget = () => {},
}) {
const { focusPassIsNeeded } = services.focus;
const delayMs = renderDelaySec * 1000;
// The near-image switch the rows were last written with (CSS px).
let switchPx = nearImageSwitchPx(1);
/** The delayed instant (epoch ms) every untracked contact is drawn at. */
const _displayMs = () =>
followsClock() ? state.now() : Date.now() - delayMs;
/** The live draw set, and whether its motion clock is the scene's. */
followsClock() ? state.now() : Date.now() - displayDelay.currentMs;
/** The live draw set, whether its motion clock is the scene's, and the
* delay its live clock was last given. */
let liveSet = null;
let sceneClock = false;
let sentDelayMs = NaN;
/** The motion clock for whether the layer follows the world clock. */
const motionClock = (scene) =>
scene ? { kind: 'scene' } : { kind: 'live', delayMs };
scene
? { kind: 'scene' }
: { kind: 'live', delayMs: displayDelay.currentMs };
/**
* Put the set's motion on the scene's clock (the world's time) while the
* layer follows the world clock, on the delayed live clock otherwise.
* Once a frame: move the display delay on, and put the set's motion on
* the scene's clock (the world's time) while the layer follows the world
* clock, on the delayed live clock otherwise, with the delay as it is now.
*/
function _syncMotionClock() {
const scene = followsClock();
if (!liveSet || scene === sceneClock) return;
if (!scene) displayDelay.step(Date.now());
if (!liveSet) return;
if (
scene === sceneClock &&
(scene || sentDelayMs === displayDelay.currentMs)
)
return;
sceneClock = scene;
sentDelayMs = scene ? NaN : displayDelay.currentMs;
liveSet.setOptions({ motionClock: motionClock(scene) });
}
@@ -443,6 +471,7 @@ export function createAircraftIcons({
set.setColumns?.({ ids: [] });
liveSet = set;
sceneClock = followsClock();
sentDelayMs = sceneClock ? NaN : displayDelay.currentMs;
switchPx = _imageSwitchPx(viewer);
state._icons = createContactIcons(set, {
capabilities: rendererOf(viewer)?.capabilities ?? null,
@@ -537,7 +566,15 @@ export function createAircraftIcons({
let pos;
let course;
let expiresAt = Infinity;
if (regime.kind === 'between') {
if (regime.kind === 'between' && regime.piece) {
// Along the curve between the two reports, a piece at a time.
const segment = regime.piece.segment;
speed = segment.speedMps;
motion = { ...segment, fix: clone(segment.fix) };
pos = clone(segment.fix);
course = motionCourse(motion, undefined, t);
expiresAt = regime.piece.t1;
} else if (regime.kind === 'between') {
const { a, b, span, trackFrom, trackTo, chordCourse } = regime;
speed = regime.speed;
const blend = chordCourse == null ? 0 : regime.blend;
@@ -597,6 +634,40 @@ export function createAircraftIcons({
}
}
}
// A new report that puts a moving contact somewhere else than it is
// drawn now (it was coasting past its newest report): it eases from
// where it is onto the new path instead of jumping, unless that is
// farther than a jump would be anyway.
// Only a row on screen whose plan is still running (a hidden row, or one
// whose motion ran out long ago, is simply drawn where it is now).
if (
fromCourseDeg == null &&
icons.shown(icao24) &&
icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS
) {
const prev = icons.item(icao24);
const drawn = motionPosition(prev.motion, prev.pos, t);
const next = motionPosition(motion, pos, t);
const errorM = distance(drawn, next);
if (
errorM > RECOVER_MIN_M &&
errorM < RECOVER_SNAP_M &&
speed >= COURSE_HOLD_SPEED_MPS &&
!same(prev.motion, motion)
) {
const end = t + recoveryMs(errorM, speed);
// Where the new path has it by then, past this plan if need be.
const target = parts.motion._deadReckon(
icao24,
vec(),
parts.motion._displayTimeAt(end),
);
motion = straightSegment(drawn, t, end, target ?? next);
pos = clone(drawn);
course = motionCourse(motion, undefined, t);
expiresAt = end;
}
}
// Below hover speed the nose holds what is on screen (or, for a new row,
// where this motion starts); above it, it glides on at the slew cap.
const hold = speed < COURSE_HOLD_SPEED_MPS;
+43
View File
@@ -9,6 +9,7 @@ import {
import { COAST_FLOOR_LIFT_M } from './motionModel.js';
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { createDisplayDelay } from './displayDelay.js';
const WORLD_MS = Date.UTC(2026, 10, 1, 12, 0);
@@ -46,6 +47,48 @@ test('following the world clock, contacts draw at the world’s time on the scen
icons._disposeIcons();
});
test('as the display delay moves, the renderer’s live clock and the layer’s display time move with it; the world clock ignores it', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const viewer = {};
const { draw } = bindFakeDraw(viewer);
let following = false;
const state = { _viewer: viewer, now: () => Date.now() };
const delay = createDisplayDelay({ floorMs: 30_000, pollMs: 30_000 });
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {},
layerId: 'flights',
displayDelay: delay,
followsClock: () => following,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
// Reports 90 s old every 30 s: the delay heads for about two minutes.
for (let i = 0; i < 20; i++)
delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000);
delay.settle(WORLD_MS);
t.mock.timers.setTime(WORLD_MS + 10_000);
icons._syncMotionClock();
// 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 });
assert.equal(icons._displayMs(), Date.now() - 32_000);
// Following the world clock: no delay, and it is not moved on meanwhile.
following = true;
t.mock.timers.setTime(WORLD_MS + 20_000);
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
assert.equal(icons._displayMs(), Date.now());
assert.equal(delay.currentMs, 32_000);
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 });
icons._disposeIcons();
});
test('a coasting icon is kept above rising ground, as the CPU coast is', () => {
const T0 = WORLD_MS;
let now = T0;
+75 -13
View File
@@ -7,6 +7,7 @@ import {
secondsDifference,
} from '../geo/julian.js';
import { clone, distance } from '../geo/vector.js';
import { curvePieceAt, fixCurveCached } from './fixCurve.js';
import {
COAST_MAX_SPEED_MPS,
courseBetweenCartesians,
@@ -76,12 +77,54 @@ export function historyFix(epochMs, position, velocity, track) {
};
}
/**
* Whether a history fix is a forward synthetic fix (a motion aid built from
* a repeated report's new speed or course, `synthesizeForwardKinematicsFix`)
* rather than a report.
*/
export const isSyntheticFix = (fix) => Number.isFinite(fix?.reportEpochMs);
/**
* Put a new report at the end of a contact's history: forward synthetic
* fixes after the previous report go (the report supersedes them), and past
* `limit` the oldest fixes go.
* @param {Array<object>} history Oldest first; mutated.
* @param {object} fix The report's history fix.
* @param {number} limit
*/
export function pushReport(history, fix, limit) {
while (history.length && isSyntheticFix(history[history.length - 1]))
history.pop();
history.push(fix);
while (history.length > limit) history.shift();
}
/** The newest report in a history (not a synthetic fix), or undefined. */
export function newestReport(history) {
for (let i = history.length - 1; i >= 0; i--)
if (!isSyntheticFix(history[i])) return history[i];
return undefined;
}
/** The curve a contact is drawn along between two history fixes, or null. */
export function historyCurve(a, b) {
return fixCurveCached(
a.position,
fixEpochMs(a),
a.track,
b.position,
fixEpochMs(b),
b.track,
);
}
/** A reusable result for `aircraftMotionRegime`. */
export function createMotionRegime() {
return {
kind: 'fix',
a: null,
b: null,
piece: null,
span: 0,
speed: 0,
trackFrom: 0,
@@ -100,8 +143,11 @@ export function createMotionRegime() {
* Which motion an aircraft's history gives at `renderTime` — the one choice
* the CPU dead reckoning and the icon planner (GPU segment) both draw from.
*
* - `between`: interpolate the bracketing pair `a`→`b`, no extrapolation
* error and no snap-back. The course of the DISPLAYED motion blends the
* - `between`: between the bracketing pair `a`→`b`, no extrapolation
* error and no snap-back. Along their curve (`data/fixCurve`) when the
* pair describes one: `piece` is the curve's piece at `renderTime`, a
* contract `arc` segment with its times. Otherwise straight from `a` to
* `b` (`piece` null), and the course of the DISPLAYED motion blends the
* time-interpolated reported track toward the chord by `blend`: the chord
* is only trustworthy when the segment covers real ground (at hover its
* direction is GPS jitter; on a slow tight turn it STEPS the whole
@@ -136,43 +182,59 @@ export function aircraftMotionRegime(
result,
{ cachedGroundFloor } = {},
) {
for (let i = history.length - 1; i >= 1; i--) {
const a = history[i - 1];
const b = history[i];
// A synthetic fix a later report superseded is not on the path: the
// contact is drawn report to report, as its trail is.
let report = history.length - 1;
while (report >= 0 && isSyntheticFix(history[report])) report--;
let b = null;
for (let i = history.length - 1; i >= 0; i--) {
const a = history[i];
if (i < report && isSyntheticFix(a)) continue;
const pairB = b;
b = a;
if (!pairB) continue;
if (
!julianLessThanOrEquals(a.time, renderTime) ||
!julianLessThanOrEquals(renderTime, b.time)
!julianLessThanOrEquals(renderTime, pairB.time)
)
continue;
const span = secondsDifference(b.time, a.time);
const chordLenM = distance(a.position, b.position);
const span = secondsDifference(pairB.time, a.time);
const chordLenM = distance(a.position, pairB.position);
const speed =
span > 0 ? chordLenM / span : (info && info[fields.speed]) || 0;
const fallbackTrack = (info && info[fields.track]) || 0;
const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack;
const blend = info && info.klass === 'helicopter' ? 0 : speedRamp(speed);
const curve = span > 0 ? historyCurve(a, pairB) : null;
result.kind = 'between';
result.a = a;
result.b = b;
result.b = pairB;
result.piece = curve
? curvePieceAt(curve, julianToEpochMs(renderTime))
: null;
result.span = span;
result.speed = speed;
result.trackFrom = trackFrom;
result.trackTo = Number.isFinite(b.track) ? b.track : trackFrom;
result.trackTo = Number.isFinite(pairB.track) ? pairB.track : trackFrom;
result.chordCourse =
blend > 0 ? courseBetweenCartesians(a.position, b.position) : null;
blend > 0 ? courseBetweenCartesians(a.position, pairB.position) : null;
result.blend = blend;
return result;
}
const newest = history[history.length - 1];
const warming = julianLessThan(renderTime, history[0].time);
result.kind = 'fix';
result.piece = null;
result.fix = warming ? history[0] : newest;
result.speed = fixSpeedMps(result.fix, info, fields);
result.heading = fixTrackDeg(result.fix, info, fields);
result.turnRateDps = (info && info.turnRateDps) || 0;
// Past the newest report it flies straight on along its course: a turn
// rate averaged over earlier reports outlives the turn it measured, and
// coasting on it put contacts kilometres off a straight path.
result.turnRateDps = 0;
result.minDt = -60;
// A warm-up ends when real time reaches the oldest fix; a single fix keeps
// coasting forward on the same arc.
// coasting forward on the same line.
result.maxDt =
warming && history.length > 1
? 0
+164
View File
@@ -0,0 +1,164 @@
/**
* @module data/displayDelay
* @description How far behind real time a live aircraft feed is drawn.
*
* Contacts are drawn at `now − delay` so that, at the time drawn, every
* contact has a report on both sides and is placed between two real reports
* instead of dead reckoned past its newest one. The delay has to cover how
* late the feed really is: a feed whose reports arrive 90 s old every 30 s
* needs about two minutes, a fresh one about half a minute.
*
* Each time a contact's report moves on, the feed's lag is how long the
* display had to wait for it: its receipt time less the contact's previous
* report time (lateness, the gap between reports and the wait for the next
* poll together). The delay aimed at is the 90th percentile of the newest 256
* lags plus 5 s, within the layer's floor and a five-minute cap. Before a
* feed has given 16 lags, its first reports stand in: their age plus one poll
* interval.
*
* The delay drawn with moves toward that aim at a bounded rate, rising by at
* most 0.2 s and falling by at most 0.05 s per second, so every contact
* slows or speeds up a little rather than the whole fleet jumping; an aim
* within 2 s of where it is leaves it there. Until a layer has drawn a
* contact, it takes its aim at once.
*/
/** @constant {number} Percentile of the recent lags the delay covers. */
export const DISPLAY_DELAY_RANK = 0.9;
/** @constant {number} How many recent lags the percentile is taken over. */
export const DISPLAY_DELAY_LAGS = 256;
/** @constant {number} Lags before they, rather than first reports, set the aim. */
export const DISPLAY_DELAY_MIN_LAGS = 16;
/** @constant {number} Added to the percentile for jitter (ms). */
export const DISPLAY_DELAY_MARGIN_MS = 5_000;
/** @constant {number} The longest delay (ms). */
export const DISPLAY_DELAY_CAP_MS = 300_000;
/** @constant {number} Delay gained per unit of real time, at most. */
export const DISPLAY_DELAY_RISE = 0.2;
/** @constant {number} Delay shed per unit of real time, at most. */
export const DISPLAY_DELAY_FALL = 0.05;
/** @constant {number} An aim this close (ms) to the delay leaves it be. */
export const DISPLAY_DELAY_DEADBAND_MS = 2_000;
function createWindow(capacity) {
return { values: new Float64Array(capacity), count: 0, cursor: 0 };
}
function add(window, value) {
if (!Number.isFinite(value) || value < 0) return;
window.values[window.cursor] = value;
window.cursor = (window.cursor + 1) % window.values.length;
window.count = Math.min(window.count + 1, window.values.length);
}
function percentile(window, rank) {
const sorted = window.values.slice(0, window.count).sort();
return sorted[Math.max(0, Math.ceil(sorted.length * rank) - 1)];
}
/**
* One live feed's display delay.
* @param {object} options
* @param {number} options.floorMs The shortest delay (ms), and where it starts.
* @param {number} options.pollMs How often the feed is asked (ms).
* @param {number} [options.capMs] The longest delay (ms).
*/
export function createDisplayDelay({
floorMs,
pollMs,
capMs = DISPLAY_DELAY_CAP_MS,
}) {
const lags = createWindow(DISPLAY_DELAY_LAGS);
const firstAges = createWindow(DISPLAY_DELAY_LAGS);
let aimMs = floorMs;
let fromMs = floorMs;
let fromAtMs = NaN;
let currentMs = floorMs;
const clamp = (ms) => Math.max(floorMs, Math.min(capMs, ms));
/** The delay at `nowMs` on its way from `fromMs` toward the aim. */
function delayAt(nowMs) {
if (!Number.isFinite(fromAtMs)) return fromMs;
const elapsed = Math.max(0, nowMs - fromAtMs);
const change = Math.max(
-DISPLAY_DELAY_FALL * elapsed,
Math.min(DISPLAY_DELAY_RISE * elapsed, aimMs - fromMs),
);
return fromMs + change;
}
return {
/** The delay contacts are drawn with now (whole ms), as last stepped. */
get currentMs() {
return currentMs;
},
/** The delay it is moving toward (ms). */
get aimMs() {
return aimMs;
},
/** Lags seen so far, up to the window. */
get lagCount() {
return lags.count;
},
/**
* A contact's report received at `receiptMs`: its time, and the
* contact's previous report time (none for a contact seen first).
*/
noteReport(receiptMs, reportMs, previousReportMs) {
if (Number.isFinite(previousReportMs)) {
if (reportMs > previousReportMs)
add(lags, receiptMs - previousReportMs);
} else if (Number.isFinite(reportMs))
add(firstAges, receiptMs - reportMs);
},
/**
* Aim again after a delivery. `jump`: nothing is drawn yet, so the delay
* takes the aim at once.
* @param {number} nowMs
* @param {{jump?: boolean}} [options]
* @returns {number} The delay now (whole ms).
*/
settle(nowMs, { jump = false } = {}) {
let next = aimMs;
if (lags.count >= DISPLAY_DELAY_MIN_LAGS)
next = clamp(
percentile(lags, DISPLAY_DELAY_RANK) + DISPLAY_DELAY_MARGIN_MS,
);
else if (firstAges.count)
next = clamp(
percentile(firstAges, DISPLAY_DELAY_RANK) +
pollMs +
DISPLAY_DELAY_MARGIN_MS,
);
const now = delayAt(nowMs);
fromMs = jump ? next : now;
fromAtMs = nowMs;
// An aim this close leaves the delay where it is.
aimMs =
Math.abs(next - now) < DISPLAY_DELAY_DEADBAND_MS && !jump ? now : next;
currentMs = Math.round(fromMs);
return currentMs;
},
/**
* Move the delay on to `nowMs`: what the contacts are drawn with until
* the next step.
* @returns {number} Whole ms.
*/
step(nowMs) {
currentMs = Math.round(delayAt(nowMs));
return currentMs;
},
/** Forget the feed: back to the floor, nothing learned. */
reset() {
lags.count = lags.cursor = 0;
firstAges.count = firstAges.cursor = 0;
aimMs = fromMs = currentMs = floorMs;
fromAtMs = NaN;
},
};
}
+170
View File
@@ -0,0 +1,170 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
createDisplayDelay,
DISPLAY_DELAY_CAP_MS,
DISPLAY_DELAY_DEADBAND_MS,
DISPLAY_DELAY_FALL,
DISPLAY_DELAY_LAGS,
DISPLAY_DELAY_MARGIN_MS,
DISPLAY_DELAY_MIN_LAGS,
DISPLAY_DELAY_RISE,
} from './displayDelay.js';
// A live feed is drawn far enough behind real time that every contact has a
// report on both sides of the time drawn.
const SEC = 1000;
const FLOOR = 30 * SEC;
const POLL = 30 * SEC;
/**
* A feed polled every 30 s whose reports arrive `ageMs` old, one new report
* per contact per poll: each lag is the age plus the poll interval.
*/
function feed(delay, { contacts = 20, polls = 4, ageMs, startMs = 0 }) {
let now = startMs;
for (let p = 0; p < polls; p++) {
now += POLL;
for (let c = 0; c < contacts; c++) {
const reportMs = now - ageMs - c * 10;
delay.noteReport(now, reportMs, reportMs - POLL);
}
}
return now;
}
test('the aim is the 90th percentile of recent lags plus the margin', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 90 * SEC });
assert.ok(delay.lagCount >= DISPLAY_DELAY_MIN_LAGS);
delay.settle(now, { jump: true });
// Lags 120 s (plus the spread of 0–190 ms): 125 s and a little.
assert.ok(
Math.abs(delay.currentMs - (120 * SEC + DISPLAY_DELAY_MARGIN_MS)) < 300,
`${delay.currentMs}`,
);
});
test('a fresh feed stays at the floor', () => {
// Polled every 10 s, reports 2 s old: lags of 12 s, aim 17 s, under the floor.
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: 10 * SEC });
for (let i = 1; i <= 40; i++)
delay.noteReport(
i * 10 * SEC,
i * 10 * SEC - 2 * SEC,
(i - 1) * 10 * SEC - 2 * SEC,
);
assert.equal(delay.settle(400 * SEC, { jump: true }), FLOOR);
});
test('the delay never passes the cap', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 20 * 60 * SEC });
assert.equal(delay.settle(now, { jump: true }), DISPLAY_DELAY_CAP_MS);
});
test('before enough lags, first reports stand in: their age plus a poll', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
for (let c = 0; c < 10; c++)
delay.noteReport(1_000 * SEC, 1_000 * SEC - 90 * SEC);
assert.equal(delay.lagCount, 0);
assert.equal(
delay.settle(1_000 * SEC, { jump: true }),
90 * SEC + POLL + DISPLAY_DELAY_MARGIN_MS,
);
});
test('a report that did not move on gives no lag', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
delay.noteReport(100 * SEC, 50 * SEC, 50 * SEC);
delay.noteReport(100 * SEC, 40 * SEC, 50 * SEC);
assert.equal(delay.lagCount, 0);
});
test('only the newest lags count', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, {
ageMs: 200 * SEC,
contacts: DISPLAY_DELAY_LAGS,
polls: 1,
});
now = feed(delay, {
ageMs: 10 * SEC,
contacts: DISPLAY_DELAY_LAGS,
polls: 1,
startMs: now,
});
assert.ok(delay.settle(now, { jump: true }) < 50 * SEC);
});
test('the delay rises toward its aim at most 0.2 s per second, then holds there', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 90 * SEC });
assert.equal(delay.settle(now), FLOOR, 'not jumped once drawing');
const aim = delay.aimMs;
let prev = delay.currentMs;
for (let s = 1; s <= 600; s++) {
const d = delay.step(now + s * SEC);
assert.ok(d - prev <= DISPLAY_DELAY_RISE * SEC + 1, `rose ${d - prev} ms`);
assert.ok(d >= prev);
prev = d;
}
assert.equal(prev, aim);
// Rising by 0.2 s a second, the time drawn still moves forward at 0.8×.
assert.ok(DISPLAY_DELAY_RISE < 1);
});
test('the delay falls at most 0.05 s per second', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now, { jump: true });
const high = delay.currentMs;
now = feed(delay, {
ageMs: 0,
polls: 13,
startMs: now,
});
delay.settle(now);
assert.ok(Math.abs(delay.aimMs - 35 * SEC) < 300, `${delay.aimMs}`);
const later = delay.step(now + 100 * SEC);
assert.equal(high - later, DISPLAY_DELAY_FALL * 100 * SEC);
});
test('an aim within the deadband leaves the delay where it is', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now, { jump: true });
const was = delay.currentMs;
now = feed(delay, {
ageMs: 90 * SEC + DISPLAY_DELAY_DEADBAND_MS / 2,
polls: 13,
startMs: now,
});
delay.settle(now);
assert.equal(delay.aimMs, was);
assert.equal(delay.step(now + 60 * SEC), was);
});
test('a delivery mid-slew carries on from where the delay is', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now);
const mid = delay.step(now + 100 * SEC);
now = feed(delay, {
ageMs: 90 * SEC,
polls: 1,
startMs: now + 100 * SEC - POLL,
});
assert.equal(delay.settle(now), mid);
});
test('reset forgets the feed', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now, { jump: true });
delay.reset();
assert.equal(delay.currentMs, FLOOR);
assert.equal(delay.lagCount, 0);
assert.equal(delay.settle(now, { jump: true }), FLOOR);
});
+310
View File
@@ -0,0 +1,310 @@
/**
* @module data/fixCurve
* @description The path an aircraft is drawn along between two of its
* reports, and the trail drawn behind it: a smooth curve that passes through
* both reports and leaves each one along its reported track.
*
* The curve is a biarc: two constant-rate turns, each a renderer `arc`
* motion segment (`render/contract/draw.d.ts`), joined where they share a
* course. So the renderer draws exactly this curve, the app reads it back with
* `render/motion/iconMotion`, and the trail samples the same segments: the
* icon always sits on its own trail. Speed is constant between the two
* reports, height changes evenly with time.
*
* The straight line between the reports is drawn instead (no curve) when
* either report has no track, the pair is slower than 40 m/s (taxiing,
* hovering, holding still), or a track points more than 75° off the line
* between them: the reports do not describe one smooth turn.
*
* Each segment runs on for two seconds past its end along the same turn, so
* when the next segment comes a little late the renderer keeps the icon moving
* instead of holding it.
*/
import { eastNorthUp } from '../geo/frames.js';
import { motionCourse, motionPosition } from '../render/motion/iconMotion.js';
import { norm180, norm360 } from '../geo/vector.js';
/** @constant {number} Pairs slower than this (m/s) are joined straight. */
export const CURVE_MIN_SPEED_MPS = 40;
/** @constant {number} A track further than this (°) off the chord is joined straight. */
export const CURVE_MAX_TRACK_OFF_DEG = 75;
/** @constant {number} How long (s) a segment runs on past its end. */
export const CURVE_RUN_ON_S = 2;
/** @constant {number} Turn (°) between points a trail samples along a curve. */
export const CURVE_POINT_STEP_DEG = 1;
const DEG = Math.PI / 180;
/** Turn rates under this (rad/s) fly straight, as `iconMotion` draws them. */
const STRAIGHT_BELOW_RAD_PER_S = 1e-4;
function sinc(x) {
return Math.abs(x) < 1e-4 ? 1 - (x * x) / 6 : Math.sin(x) / x;
}
const dot3 = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const sub3 = (a, b) => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });
/** A course (degrees) at `from`'s frame, read in `to`'s frame. */
function courseIn(courseDeg, fromFrame, toFrame) {
const s = Math.sin(courseDeg * DEG);
const c = Math.cos(courseDeg * DEG);
const t = {
x: s * fromFrame.x.x + c * fromFrame.y.x,
y: s * fromFrame.x.y + c * fromFrame.y.y,
z: s * fromFrame.x.z + c * fromFrame.y.z,
};
return Math.atan2(dot3(t, toFrame.x), dot3(t, toFrame.y)) / DEG;
}
/**
* A constant-rate turn from `from` at `t0` setting off on `courseDeg`, that
* reaches `to` at `t1` (epoch ms): an `arc` segment, straight when the turn
* is too slow to draw as one.
* @returns {{segment: object, endCourseDeg: number}}
*/
function arcThrough(from, frame, t0, t1, courseDeg, to) {
const d = sub3(to, from);
const e = dot3(d, frame.x);
const n = dot3(d, frame.y);
const u = dot3(d, frame.z);
const seconds = (t1 - t0) / 1000;
const chord = Math.hypot(e, n);
const bearing = Math.atan2(e, n) / DEG;
let turn = 2 * norm180(bearing - courseDeg);
let track = courseDeg;
if (Math.abs((turn * DEG) / seconds) < STRAIGHT_BELOW_RAD_PER_S) {
turn = 0;
track = bearing;
}
const length = chord / sinc((turn * DEG) / 2);
return {
segment: {
kind: 'arc',
fix: { x: from.x, y: from.y, z: from.z },
t0,
minDtS: 0,
maxDtS: seconds + CURVE_RUN_ON_S,
speedMps: length / seconds,
trackDeg: norm360(track),
turnRateDps: turn / seconds,
climbMps: u / seconds,
},
endCourseDeg: track + turn,
};
}
/**
* A straight `arc` segment from `from` at `t0` that reaches `to` at `t1`
* (epoch ms) and runs on past it for CURVE_RUN_ON_S.
*/
export function straightSegment(from, t0, t1, to) {
const frame = eastNorthUp(from);
const d = sub3(to, from);
const bearing = Math.atan2(dot3(d, frame.x), dot3(d, frame.y)) / DEG;
return arcThrough(from, frame, t0, t1, bearing, to).segment;
}
/**
* The curve between two reports, or null to join them straight.
* @param {{x: number, y: number, z: number}} fromPos The earlier report (ECEF).
* @param {number} fromMs Its time, epoch ms.
* @param {number} fromTrackDeg Its reported track.
* @param {{x: number, y: number, z: number}} toPos The later report.
* @param {number} toMs
* @param {number} toTrackDeg
* @returns {{pieces: Array<{segment: object, t0: number, t1: number}>}|null}
* One or two pieces in time order, together running from `fromMs` to
* `toMs`; each `segment` is a contract `arc` motion segment.
*/
export function fixCurve(
fromPos,
fromMs,
fromTrackDeg,
toPos,
toMs,
toTrackDeg,
) {
if (!Number.isFinite(fromTrackDeg) || !Number.isFinite(toTrackDeg))
return null;
if (!(toMs > fromMs) || !fromPos || !toPos) return null;
const seconds = (toMs - fromMs) / 1000;
const frame = eastNorthUp(fromPos);
const d = sub3(toPos, fromPos);
const e = dot3(d, frame.x);
const n = dot3(d, frame.y);
const u = dot3(d, frame.z);
const chord = Math.hypot(e, n);
if (!(chord / seconds >= CURVE_MIN_SPEED_MPS)) return null;
const toFrame = eastNorthUp(toPos);
const startDeg = fromTrackDeg;
// The later report's track, read in the earlier report's frame.
const endDeg = courseIn(toTrackDeg, toFrame, frame);
const bearing = Math.atan2(e, n) / DEG;
if (
Math.abs(norm180(startDeg - bearing)) > CURVE_MAX_TRACK_OFF_DEG ||
Math.abs(norm180(endDeg - bearing)) > CURVE_MAX_TRACK_OFF_DEG
)
return null;
// The biarc's join with equal tangent lengths: p0 = 0, p1 = (e, n),
// unit tangents t0 and t1.
const t0x = Math.sin(startDeg * DEG);
const t0y = Math.cos(startDeg * DEG);
const t1x = Math.sin(endDeg * DEG);
const t1y = Math.cos(endDeg * DEG);
const vv = e * e + n * n;
const vt = e * (t0x + t1x) + n * (t0y + t1y);
const tt = t0x * t1x + t0y * t1y;
const denom = 2 * (1 - tt);
const reach =
denom < 1e-9
? vv / (4 * (e * t1x + n * t1y))
: (-vt + Math.sqrt(vt * vt + denom * vv)) / denom;
if (!(reach > 0) || !Number.isFinite(reach)) return null;
const jx = (reach * t0x + e - reach * t1x) / 2;
const jy = (reach * t0y + n - reach * t1y) / 2;
// Each arc's length from its chord and turn, to share the time by.
const arcLength = (cx, cy, courseDeg) => {
const c = Math.hypot(cx, cy);
const turn = 2 * norm180(Math.atan2(cx, cy) / DEG - courseDeg);
return { length: c / sinc((turn * DEG) / 2), turn };
};
const first = arcLength(jx, jy, startDeg);
const second = arcLength(e - jx, n - jy, startDeg + first.turn);
const total = first.length + second.length;
if (!(total > 0)) return null;
// One arc where a piece would be under a metre.
if (first.length < 1 || second.length < 1) {
const only = arcThrough(fromPos, frame, fromMs, toMs, startDeg, toPos);
return { pieces: [{ segment: only.segment, t0: fromMs, t1: toMs }] };
}
const joinMs = fromMs + (toMs - fromMs) * (first.length / total);
const share = first.length / total;
const join = {
x: fromPos.x + frame.x.x * jx + frame.y.x * jy + frame.z.x * u * share,
y: fromPos.y + frame.x.y * jx + frame.y.y * jy + frame.z.y * u * share,
z: fromPos.z + frame.x.z * jx + frame.y.z * jy + frame.z.z * u * share,
};
const a = arcThrough(fromPos, frame, fromMs, joinMs, startDeg, join);
// The second arc starts exactly where the first is drawn to end.
const joined = motionPosition(a.segment, null, joinMs);
const joinFrame = eastNorthUp(joined);
const b = arcThrough(
joined,
joinFrame,
joinMs,
toMs,
courseIn(a.endCourseDeg, frame, joinFrame),
toPos,
);
return {
pieces: [
{ segment: a.segment, t0: fromMs, t1: joinMs },
{ segment: b.segment, t0: joinMs, t1: toMs },
],
};
}
const cache = new WeakMap();
/**
* `fixCurve` for two report objects that keep their position object, kept
* per earlier report's position until either report changes.
*/
export function fixCurveCached(
fromPos,
fromMs,
fromTrackDeg,
toPos,
toMs,
toTrackDeg,
) {
if (!fromPos || typeof fromPos !== 'object') return null;
const hit = cache.get(fromPos);
if (
hit &&
hit.toPos === toPos &&
hit.fromMs === fromMs &&
hit.toMs === toMs &&
hit.fromTrackDeg === fromTrackDeg &&
hit.toTrackDeg === toTrackDeg &&
hit.fx === fromPos.x &&
hit.fy === fromPos.y &&
hit.fz === fromPos.z &&
hit.tx === toPos.x &&
hit.ty === toPos.y &&
hit.tz === toPos.z
)
return hit.curve;
const curve = fixCurve(
fromPos,
fromMs,
fromTrackDeg,
toPos,
toMs,
toTrackDeg,
);
cache.set(fromPos, {
toPos,
fromMs,
toMs,
fromTrackDeg,
toTrackDeg,
fx: fromPos.x,
fy: fromPos.y,
fz: fromPos.z,
tx: toPos?.x,
ty: toPos?.y,
tz: toPos?.z,
curve,
});
return curve;
}
/** The piece of `curve` drawn at `tMs` (the last one past its end). */
export function curvePieceAt(curve, tMs) {
const pieces = curve.pieces;
for (let i = 0; i < pieces.length - 1; i++)
if (tMs < pieces[i].t1) return pieces[i];
return pieces[pieces.length - 1];
}
/** Where the curve puts the aircraft at `tMs`, and its course. */
export function curvePositionAt(curve, tMs) {
const piece = curvePieceAt(curve, tMs);
const t = Math.min(tMs, piece.t1);
return {
position: motionPosition(piece.segment, null, t),
courseDeg: motionCourse(piece.segment, undefined, t),
};
}
/**
* Points along the curve from `fromMs` to `toMs` (exclusive of both ends),
* one at least every CURVE_POINT_STEP_DEG of turn, so the line drawn
* through them stays within a couple of metres of the curve.
* @returns {Array<{x: number, y: number, z: number}>}
*/
export function curvePoints(curve, fromMs, toMs) {
const out = [];
for (const piece of curve.pieces) {
const start = Math.max(fromMs, piece.t0);
const end = Math.min(toMs, piece.t1);
if (!(end > start)) continue;
const seconds = (end - start) / 1000;
const turned = Math.abs(piece.segment.turnRateDps * seconds);
const steps = Math.max(1, Math.ceil(turned / CURVE_POINT_STEP_DEG));
// The piece's start, unless it is the curve's own start.
if (start > fromMs) out.push(motionPosition(piece.segment, null, start));
for (let k = 1; k < steps; k++)
out.push(
motionPosition(
piece.segment,
null,
start + ((end - start) * k) / steps,
),
);
}
return out;
}
+141
View File
@@ -0,0 +1,141 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
CURVE_RUN_ON_S,
curvePieceAt,
curvePoints,
curvePositionAt,
fixCurve,
straightSegment,
} from './fixCurve.js';
import { motionPosition } from '../render/motion/iconMotion.js';
// Between two reports an aircraft is drawn along a curve through both that
// leaves each along its reported track, made of contract `arc` segments.
const SEC = 1000;
const T0 = Date.UTC(2026, 10, 9, 12);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
Cesium.Cartesian3.fromDegrees(-122.4, 37.6, 0),
);
const at = (e, n, u = 3_000) =>
Cesium.Matrix4.multiplyByPoint(
enu,
new Cesium.Cartesian3(e, n, u),
new Cesium.Cartesian3(),
);
const near = (a, b, m, label) => {
const d = Cesium.Cartesian3.distance(a, b);
assert.ok(d < m, `${label}: ${d.toFixed(2)} m`);
};
const angleDiff = (a, b) => Math.abs(((a - b + 540) % 360) - 180);
// A 100 m/s left turn on a 2 km circle centred at (0, R), heading east at
// the origin.
const R = 2_000;
const W = 100 / R;
const circle = (t) => at(R * Math.sin(W * t), R - R * Math.cos(W * t));
const trackAt = (t) => (90 - (W * t * 180) / Math.PI + 360) % 360;
test('the curve passes through both reports and leaves each along its track', () => {
const curve = fixCurve(
circle(0),
T0,
trackAt(0),
circle(15),
T0 + 15 * SEC,
trackAt(15),
);
assert.ok(curve);
near(curvePositionAt(curve, T0).position, circle(0), 0.01, 'start');
near(curvePositionAt(curve, T0 + 15 * SEC).position, circle(15), 0.01, 'end');
assert.ok(angleDiff(curvePositionAt(curve, T0).courseDeg, trackAt(0)) < 0.1);
assert.ok(
angleDiff(curvePositionAt(curve, T0 + 15 * SEC).courseDeg, trackAt(15)) <
0.1,
);
// A true turn: the curve is the turn, within a couple of metres.
for (let s = 0; s <= 15; s += 0.5)
near(curvePositionAt(curve, T0 + s * SEC).position, circle(s), 3, `${s} s`);
});
test('its pieces are contiguous arc segments in time order', () => {
// Tracks that need an S: the first turn and the second do not agree.
const curve = fixCurve(at(0, 0), T0, 45, at(3_000, 0), T0 + 30 * SEC, 45);
assert.ok(curve);
assert.equal(curve.pieces.length, 2);
assert.equal(curve.pieces[0].t0, T0);
assert.equal(curve.pieces.at(-1).t1, T0 + 30 * SEC);
for (const piece of curve.pieces) assert.equal(piece.segment.kind, 'arc');
const [a, b] = curve.pieces;
assert.equal(a.t1, b.t0);
near(
motionPosition(a.segment, null, a.t1),
motionPosition(b.segment, null, b.t0),
0.01,
'join',
);
assert.equal(curvePieceAt(curve, a.t1 - 1), a);
assert.equal(curvePieceAt(curve, a.t1), b);
assert.equal(curvePieceAt(curve, T0 + 60 * SEC), b);
});
test('each segment runs on past its end rather than holding', () => {
const curve = fixCurve(
circle(0),
T0,
trackAt(0),
circle(15),
T0 + 15 * SEC,
trackAt(15),
);
const last = curve.pieces.at(-1);
const end = motionPosition(last.segment, null, last.t1);
const later = motionPosition(
last.segment,
null,
last.t1 + CURVE_RUN_ON_S * SEC,
);
near(later, circle(15 + CURVE_RUN_ON_S), 3, 'run on');
assert.ok(Cesium.Cartesian3.distance(end, later) > 150);
});
test('no curve without tracks, below 40 m/s, or with a track far off the line', () => {
const a = at(0, 0);
const b = at(1_500, 0);
assert.equal(fixCurve(a, T0, undefined, b, T0 + 15 * SEC, 90), null);
assert.equal(fixCurve(a, T0, 90, b, T0 + 60 * SEC, 90), null, 'slow');
assert.equal(fixCurve(a, T0, 180, b, T0 + 15 * SEC, 90), null, 'off line');
assert.equal(fixCurve(a, T0, 90, b, T0, 90), null, 'no time between');
});
test('trail points follow the curve, exclusive of both ends, a degree of turn apart', () => {
const curve = fixCurve(
circle(0),
T0,
trackAt(0),
circle(15),
T0 + 15 * SEC,
trackAt(15),
);
const points = curvePoints(curve, T0, T0 + 15 * SEC);
// 15 s at 2.86°/s: about 43° of turn.
assert.ok(points.length >= 42 && points.length <= 46, `${points.length}`);
for (const p of points)
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R)) - R) < 3,
'off the turn',
);
assert.ok(Cesium.Cartesian3.distance(points[0], circle(0)) > 1);
assert.ok(Cesium.Cartesian3.distance(points.at(-1), circle(15)) > 1);
});
test('a straight segment reaches its end at its time and runs on along the same line', () => {
const a = at(0, 0);
const b = at(1_000, 0);
const segment = straightSegment(a, T0, T0 + 10 * SEC, b);
near(motionPosition(segment, null, T0), a, 0.01, 'start');
near(motionPosition(segment, null, T0 + 5 * SEC), at(500, 0), 1, 'middle');
near(motionPosition(segment, null, T0 + 10 * SEC), b, 0.01, 'end');
});
+33
View File
@@ -220,6 +220,39 @@ export function trailHeadStart(start, anchor, center, radiusM, result) {
return result;
}
/**
* The live head line from the last trail report through `points` (on the
* way to the aircraft) to `head`, as drawn: points inside the model's
* envelope are left out, and the link into the model slides as
* `trailHeadStart` decides (nothing on a contact that has not moved).
* @param {{x:number,y:number,z:number}} start The last body report.
* @param {Array<{x:number,y:number,z:number}>} points Between it and the head.
* @param {{x:number,y:number,z:number}} head The aircraft's trail anchor.
* @param {{x:number,y:number,z:number}|null} center Model origin, or null.
* @param {number|null} radiusM Rendered bounding radius.
* @param {{x:number,y:number,z:number}} result Scratch for the slid start.
* @returns {Array<{x:number,y:number,z:number}>} Empty when nothing is drawn.
*/
export function trailHeadLine(start, points, head, center, radiusM, result) {
const outside = (p) =>
!center ||
!(radiusM > 0) ||
Math.hypot(p.x - center.x, p.y - center.y, p.z - center.z) >= radiusM;
const line = [start];
for (const p of points) if (outside(p)) line.push(p);
// On a contact that has not moved the last link 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 START is what
// slides, from nothing on a parked contact out to the whole link once it
// has cleared its own envelope.
const from = trailHeadStart(line.pop(), head, center, radiusM, result);
if (!from)
return line.length ? [...line, { x: head.x, y: head.y, z: head.z }] : [];
line.push(from === result ? { x: from.x, y: from.y, z: from.z } : from);
line.push({ x: head.x, y: head.y, z: head.z });
return line;
}
/**
* Transform a model-local visual centre into world coordinates without
* allocating. `modelMatrix` continues to own the model origin (including
+28
View File
@@ -621,3 +621,31 @@ export function synthesizeForwardKinematicsFix(newest, next = {}) {
track: Number.isFinite(next.track) ? next.track : previousTrack,
};
}
/** @constant {number} The shortest ease (ms) from where a contact was drawn onto where a new report puts it. */
export const RECOVER_MIN_MS = 3_000;
/** @constant {number} An ease never moves a contact faster than its speed by more than this share... */
export const RECOVER_MAX_EXTRA_SPEED = 0.3;
/** @constant {number} ...unless that would take longer than this (ms). */
export const RECOVER_MAX_MS = 20_000;
/** @constant {number} Farther than this (m) from where a new report puts it, a contact jumps there. */
export const RECOVER_SNAP_M = 5_000;
/** @constant {number} Closer than this (m), it is simply drawn there. */
export const RECOVER_MIN_M = 5;
/**
* How long (ms) a contact drawn `errorM` off where a new report puts it eases
* onto that place: at least RECOVER_MIN_MS, and long enough that the ease
* adds at most RECOVER_MAX_EXTRA_SPEED of its speed, so it never looks like
* a jump, up to RECOVER_MAX_MS.
* @param {number} errorM
* @param {number} speedMps
* @returns {number}
*/
export function recoveryMs(errorM, speedMps) {
const extraMps = RECOVER_MAX_EXTRA_SPEED * Math.max(speedMps || 0, 10);
return Math.min(
RECOVER_MAX_MS,
Math.max(RECOVER_MIN_MS, (errorM / extraMps) * 1000),
);
}
+79 -355
View File
@@ -1,12 +1,15 @@
/**
* @module trailContinuity
* @description Where a tracked aircraft's trail lifts the pen.
* @description A tracked aircraft's trail, and where it lifts the pen.
*
* A trail is a chronological list of fixes `{position, timeMs, nullAltitude,
* breakBefore, drawn}`: reports, and (`drawn`) points where the tracked icon
* was drawn between them. Between two consecutive fixes that are not one path, a new
* segment starts and nothing is drawn between them: no dashes, no arcs.
* Nothing is dropped except the oldest fixes past the layer's point limit.
* A trail is a chronological list of reports `{position, timeMs, track,
* nullAltitude, breakBefore}`. Between two consecutive reports that are one
* path, the line follows the curve the aircraft is drawn along between them
* (`data/fixCurve`), so the icon always sits on its own trail and no guess
* about where it went between reports is ever kept: a late report can never
* leave a kink. Between two that are not one path, a new segment starts and
* nothing is drawn between them: no dashes, no arcs. Nothing is dropped
* except the oldest reports past the layer's point limit.
*
* Two points are not one path when time does not advance, when the gap is
* longer than 48 minutes (a coverage hole or a separate flight), when the
@@ -20,16 +23,8 @@
* Civil and military flight tracking share these rules.
*/
import { julianToEpochMs } from '../geo/julian.js';
import {
cross,
distance,
dot,
magnitude,
normalize,
scale,
sub,
toRadians,
} from '../geo/vector.js';
import { cross, distance, dot, magnitude, normalize } from '../geo/vector.js';
import { curvePoints, fixCurveCached } from './fixCurve.js';
/** @constant {number} A gap longer than this is a coverage hole or a separate flight. */
export const TRAIL_CONTINUITY_MAX_GAP_MS = 48 * 60_000;
@@ -115,10 +110,6 @@ export function trailDistanceM(a, b) {
*/
export function trailFixBreaks(prev, next) {
if (!prev || prev.nullAltitude || next.nullAltitude) return true;
// A recorded point is where the icon was drawn; the speed between it and a
// report it was eased onto is not a flight speed, so only the gap counts.
if (prev.drawn || next.drawn)
return Math.abs(next.timeMs - prev.timeMs) > TRAIL_CONTINUITY_MAX_GAP_MS;
return trailPairBreaks(
next.timeMs - prev.timeMs,
trailDistanceM(prev.position, next.position),
@@ -129,19 +120,20 @@ export function trailFixBreaks(prev, next) {
* Build backfill fixes from chronological waypoints. Every waypoint with a
* position is kept. A waypoint without one (no altitude and no known ground)
* is skipped, and the line still breaks there.
* @param {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean}[]} waypoints
* @param {{position: {x: number, y: number, z: number}|null, timeMs: number, nullAltitude: boolean, track?: number}[]} waypoints
* @returns {{fixes: object[], breakAfter: boolean}} The fixes, and whether the
* line breaks after the last one because trailing waypoints were skipped.
*/
export function trailBackfillFixes(waypoints) {
const fixes = [];
let skipped = false;
for (const { position, timeMs, nullAltitude } of waypoints) {
for (const { position, timeMs, nullAltitude, track } of waypoints) {
if (!position) {
skipped = true;
continue;
}
const fix = { position, timeMs, nullAltitude: !!nullAltitude };
if (Number.isFinite(track)) fix.track = track;
fix.breakBefore = skipped || trailFixBreaks(fixes[fixes.length - 1], fix);
skipped = false;
fixes.push(fix);
@@ -176,7 +168,7 @@ export function trailGroundTransitionBreaks(
* not join it either. A live report that does not say uses the aircraft's
* state now; with no live fix to start after it, the backfill is checked
* against now and left out, so the head never draws that line. Past `maxPoints` the oldest
* recorded points go first, then the oldest reports.
* reports go.
* @param {{fixes: object[], breakAfter: boolean}} backfill
* @param {object[]} live - Live fixes; the first one's break is recomputed.
* @param {number} maxPoints - Point limit across all segments.
@@ -239,50 +231,68 @@ export function trailBodyCount(fixes, displayMs) {
}
/**
* Leave out the newest recorded points that lie inside the aircraft's 3D
* model, so the body never runs through the fuselage; the head then runs
* from the newest point outside the model to the plane. Reports are kept.
* @param {object[]} fixes
* @param {number} count - From `trailBodyCount`.
* @param {{x: number, y: number, z: number}|null} modelCenter - The model's centre, or null
* when no model is the visual.
* @param {number|null} envelopeM - The model's radius (m).
* @returns {number}
*/
export function trailBodyCountOutsideModel(
fixes,
count,
modelCenter,
envelopeM,
) {
if (!modelCenter || !(envelopeM > 0)) return count;
while (
count > 0 &&
fixes[count - 1].drawn &&
distance(fixes[count - 1].position, modelCenter) < envelopeM
)
count -= 1;
return count;
}
/**
* The drawn trail body, split at breaks: the first `count` fixes.
* The drawn trail body, split at breaks: the first `count` reports, each
* pair that is one path joined along its curve (`data/fixCurve`).
* @param {object[]} fixes
* @param {number} count - From `trailBodyCount`.
* @returns {{x: number, y: number, z: number}[][]}
*/
export function trailBodySegments(fixes, count) {
const segments = [];
let prev = null;
for (let i = 0; i < count; i++) {
const fix = fixes[i];
// A live report with no altitude keeps no position; it only breaks the line.
if (!fix.position) continue;
if (fix.breakBefore || !segments.length) segments.push([]);
if (!fix.position) {
prev = null;
continue;
}
if (fix.breakBefore || !segments.length || !prev) segments.push([]);
else {
const curve = trailPairCurve(prev, fix);
if (curve)
segments[segments.length - 1].push(
...curvePoints(curve, prev.timeMs, fix.timeMs),
);
}
segments[segments.length - 1].push(fix.position);
prev = fix;
}
return segments;
}
/** The curve between two consecutive trail reports, or null for a straight line. */
export function trailPairCurve(prev, next) {
return fixCurveCached(
prev.position,
prev.timeMs,
prev.track,
next.position,
next.timeMs,
next.track,
);
}
/**
* The points of the live head between the last body report and the time the
* aircraft is drawn: along the curve to the next report, which the aircraft
* is on its way to, when that pair is one path; none otherwise (the head is
* then a straight line to the aircraft).
* @param {object[]} fixes
* @param {number} count - Body reports, from `trailBodyCount`.
* @param {number} displayMs - Time the aircraft is drawn at.
* @returns {{x: number, y: number, z: number}[]}
*/
export function trailHeadCurvePoints(fixes, count, displayMs) {
const last = fixes[count - 1];
const next = fixes[count];
if (!last?.position || !next?.position || next.breakBefore) return [];
const curve = trailPairCurve(last, next);
if (!curve) return [];
// Exclusive of the display time: the point there is the aircraft's own.
return curvePoints(curve, last.timeMs, displayMs);
}
/**
* Draw body segments. A trail without breaks support draws only the newest
* segment, never a line across a break.
@@ -331,176 +341,13 @@ export function historyFixEpochMs(fix) {
return fix?.time ? julianToEpochMs(fix.time) : NaN;
}
/** @constant {number} The tracked icon's drawn position is recorded at least this often (ms of display time)... */
export const TRAIL_RECORD_STEP_MS = 1_000;
/** @constant {number} ...or whenever it has moved this far (m), whichever comes first. */
export const TRAIL_RECORD_STEP_M = 150;
/** @constant {number} A recorded point is kept only where dropping it would move the line by more than this (m) across the track or in height. */
export const TRAIL_THIN_TOLERANCE_M = 30;
/** @constant {number} A recorded point is kept where dropping it would leave a straight piece longer than this (m), so a long leg still has vertices. */
export const TRAIL_THIN_MAX_SPAN_M = 10_000;
/** @constant {number} A kept point stands in for at most this many dropped positions; past it the point is kept. */
const TRAIL_THIN_MAX_ABSORBED = 512;
/** @constant {number} A recorded point is dropped where the line turns back sharper than this (degrees)... */
export const TRAIL_SPUR_TURN_DEG = 120;
/** @constant {number} ...over a step shorter than this (m). */
export const TRAIL_SPUR_MAX_STEP_M = 500;
/** @constant {number} A recorded point closer than this (m) to the previous one is not kept: the aircraft is holding. */
const TRAIL_RECORD_MIN_STEP_M = 1;
/** Cosine of the turn at `b` on the way a → b → c, or NaN for a zero step. */
function turnCos(a, b, c) {
const u = sub(b, a);
const v = sub(c, b);
const lu = magnitude(u);
const lv = magnitude(v);
if (!(lu > 0 && lv > 0)) return NaN;
return dot(u, v) / (lu * lv);
}
const SPUR_COS = Math.cos(toRadians(TRAIL_SPUR_TURN_DEG));
/** Whether entry `i` and its neighbours are one drawn piece of line. */
function joinedAt(fixes, i) {
const a = fixes[i - 1];
const b = fixes[i];
const c = fixes[i + 1];
return (
a?.position &&
b?.position &&
c?.position &&
!b.breakBefore &&
!c.breakBefore
);
}
/** Whether the line turns back on itself at entry `i` over a short step. */
function spurAt(fixes, i) {
if (!joinedAt(fixes, i)) return false;
const a = fixes[i - 1].position;
const b = fixes[i].position;
const c = fixes[i + 1].position;
if (Math.min(distance(a, b), distance(b, c)) > TRAIL_SPUR_MAX_STEP_M)
return false;
return turnCos(a, b, c) < SPUR_COS;
}
/** Remove entry `i` and re-judge the break before the entry that takes its place. */
function removeAt(fixes, i) {
fixes.splice(i, 1);
if (i < fixes.length)
fixes[i].breakBefore = trailFixBreaks(fixes[i - 1], fixes[i]);
}
/**
* Keep the point limit: drop the oldest recorded point first, and the oldest
* report only when no recorded point is left.
* @param {object[]} fixes - The trail, mutated.
* @param {number} maxPoints
* @returns {object[]} `fixes`.
*/
/** Keep the point limit: the oldest reports go first. */
function keepTrailLimit(fixes, maxPoints) {
let excess = fixes.length - maxPoints;
if (excess <= 0) return fixes;
for (let i = 0; i < fixes.length && excess > 0;) {
if (fixes[i].drawn) {
removeAt(fixes, i);
excess -= 1;
} else i += 1;
}
const excess = fixes.length - maxPoints;
if (excess > 0) fixes.splice(0, excess);
return fixes;
}
/** Whether `p` lies within the thinning tolerance of segment a → b, across the track and in height. */
function nearSegment(p, a, b) {
const ab = sub(b, a);
const ap = sub(p, a);
const len2 = dot(ab, ab);
const t = len2 > 0 ? Math.max(0, Math.min(1, dot(ap, ab) / len2)) : 0;
const off = sub(ap, scale(ab, t));
const vertical = dot(off, normalize(p));
const across = Math.sqrt(Math.max(0, dot(off, off) - vertical * vertical));
return (
Math.abs(vertical) <= TRAIL_THIN_TOLERANCE_M &&
across <= TRAIL_THIN_TOLERANCE_M
);
}
/**
* Drop recorded point `i` when the line without it stays within the
* tolerance of every position it stood for, and the straight piece left is
* no longer than TRAIL_THIN_MAX_SPAN_M. The positions it stood for go on to
* the next entry. Reports are never dropped.
* @returns {boolean} Whether it was dropped.
*/
function thinAt(fixes, i) {
const entry = fixes[i];
if (!entry?.drawn || entry.sealed || !joinedAt(fixes, i)) return false;
const a = fixes[i - 1].position;
const next = fixes[i + 1];
if (next.sealed) return false;
const b = next.position;
if (distance(a, b) > TRAIL_THIN_MAX_SPAN_M) return false;
const stood = entry.absorbed ?? [];
const nextStood = next.absorbed ?? [];
if (stood.length + nextStood.length + 1 > TRAIL_THIN_MAX_ABSORBED)
return false;
if (!nearSegment(entry.position, a, b)) return false;
for (const p of stood) if (!nearSegment(p.position, a, b)) return false;
for (const p of nextStood) if (!nearSegment(p.position, a, b)) return false;
next.absorbed = stood.concat(
[{ position: entry.position, timeMs: entry.timeMs }],
nextStood,
);
removeAt(fixes, i);
return true;
}
/**
* Thin the recorded points either side of entry `i`, reaching past a
* neighbouring report: the point recorded just before a report is only
* judged once the line goes on beyond it.
*/
function thinAround(fixes, i) {
if (!thinAt(fixes, i + 1) && fixes[i + 1] && !fixes[i + 1].drawn)
thinAt(fixes, i + 2);
if (thinAt(fixes, i - 1)) i -= 1;
else if (fixes[i - 1] && !fixes[i - 1].drawn) thinAt(fixes, i - 2);
}
/**
* Drop recorded points that make a spur next to entry `i`. Reports are never
* dropped; at a report the recorded neighbour is dropped instead.
* @returns {number} The index entry `i` ends up at.
*/
function removeSpursAround(fixes, i) {
for (let guard = 0; guard < 64; guard++) {
let changed = false;
for (const j of [i - 1, i, i + 1]) {
if (!spurAt(fixes, j)) continue;
let drop = -1;
if (fixes[j].drawn) drop = j;
else if (fixes[j + 1]?.drawn) drop = j + 1;
else if (fixes[j - 1]?.drawn) drop = j - 1;
if (drop < 0) continue;
removeAt(fixes, drop);
if (drop < i) i -= 1;
changed = true;
break;
}
if (!changed) break;
}
return i;
}
/** Index a fix at `timeMs` goes in at: after every entry at or before it. */
function insertionIndex(fixes, timeMs) {
let i = fixes.length;
@@ -509,65 +356,16 @@ function insertionIndex(fixes, timeMs) {
}
/**
* Insert an entry at `i`, judge both breaks, remove spurs, thin the recorded
* points either side and keep the limit.
*/
function insertAt(fixes, i, entry, maxPoints) {
fixes.splice(i, 0, entry);
entry.breakBefore = trailFixBreaks(fixes[i - 1], entry);
const after = fixes[i + 1];
if (after) {
after.breakBefore = trailFixBreaks(entry, after);
// Positions the next entry stood for that come before this one are now
// on this entry's side.
if (after.absorbed?.length) {
const mine = after.absorbed.filter((p) => p.timeMs < entry.timeMs);
if (mine.length) {
entry.absorbed = mine;
after.absorbed = after.absorbed.filter((p) => p.timeMs >= entry.timeMs);
}
}
}
i = removeSpursAround(fixes, i);
thinAround(fixes, i);
keepTrailLimit(fixes, maxPoints);
}
/** Index of the newest report before entry `i`, or -1. */
function reportBefore(fixes, i) {
let j = i - 1;
while (j >= 0 && fixes[j].drawn) j -= 1;
return j;
}
/** Index of the oldest report at or after `i`, or `fixes.length`. */
function reportFrom(fixes, i) {
let j = i;
while (j < fixes.length && fixes[j].drawn) j += 1;
return j;
}
/**
* Put a report into the trail in time order. Reports are the record: they
* are kept as anchors among the recorded points.
*
* - A report the display has already passed replaces the guess drawn after
* it: the recorded points timed after it go, and nothing is recorded until
* the icon has eased onto the correction (`displayMs` + `settleMs`), so the
* line reads arc, report, corrected path.
* - Recorded points never join two reports that break under
* `trailPairBreaks` (too long or too fast apart to be one flight): the
* points between them go and the line breaks.
* - A live report with no altitude keeps no position and only breaks the
* line.
* Put a report into the trail in time order and judge the breaks on both
* sides of it. A live report with no altitude keeps no position and only
* breaks the line.
* @param {object[]} fixes - The trail, mutated.
* @param {{x: number, y: number, z: number}} position - Owned position.
* @param {number} timeMs - The report's epoch ms.
* @param {number} maxPoints - Point limit across all segments.
* @param {{nullAltitude?: boolean, displayMs?: number, settleMs?: number, onGround?: boolean}} [options]
* `displayMs`: the time the aircraft is drawn at as the report arrives;
* `settleMs`: how long the icon takes to ease onto a correction;
* `onGround`: whether the report was on the ground, when known.
* @param {{nullAltitude?: boolean, onGround?: boolean, track?: number}} [options]
* `onGround`: whether the report was on the ground, when known;
* `track`: its reported track, which the curve leaves it along.
* @returns {object[]} `fixes`.
*/
export function insertTrailFix(
@@ -575,97 +373,23 @@ export function insertTrailFix(
position,
timeMs,
maxPoints,
{
nullAltitude = false,
displayMs = NaN,
settleMs = 0,
onGround = undefined,
} = {},
{ nullAltitude = false, onGround = undefined, track = undefined } = {},
) {
const entry = {
position: nullAltitude ? null : position,
timeMs,
nullAltitude,
drawn: false,
breakBefore: false,
};
if (Number.isFinite(track)) entry.track = track;
// Whether the report was on the ground, when known: a history backfill
// joins it only across a landing or take-off it saw.
if (typeof onGround === 'boolean') entry.onGround = onGround;
let i = insertionIndex(fixes, timeMs);
// The guess drawn after a report the display already passed.
fixes.splice(i, reportFrom(fixes, i) - i);
if (displayMs > timeMs) entry.settleUntilMs = displayMs + settleMs;
// Recorded points across a pair of reports that are not one flight.
const before = reportBefore(fixes, i);
if (before >= 0 && trailFixBreaks(fixes[before], entry)) {
fixes.splice(before + 1, i - before - 1);
i = before + 1;
}
insertAt(fixes, i, entry, maxPoints);
const i = insertionIndex(fixes, timeMs);
fixes.splice(i, 0, entry);
entry.breakBefore = trailFixBreaks(fixes[i - 1], entry);
const after = fixes[i + 1];
if (after) after.breakBefore = trailFixBreaks(entry, after);
keepTrailLimit(fixes, maxPoints);
return fixes;
}
/**
* Record where the tracked aircraft was drawn at a display time. Between
* reports this recorded path is the trail, so the line follows every turn
* the icon made instead of a straight chord between two reports. Points are
* thinned by shape: one stays only where dropping it would move the line by
* more than TRAIL_THIN_TOLERANCE_M across the track or in height, or leave a
* straight piece longer than TRAIL_THIN_MAX_SPAN_M. Nothing is recorded
* while the aircraft holds.
* @param {object[]} fixes - The trail, mutated.
* @param {{x: number, y: number, z: number}} position - Owned drawn position.
* @param {number} timeMs - Display time it was drawn for.
* @param {number} maxPoints - Point limit across all segments.
* @returns {boolean} Whether the trail changed.
*/
export function recordTrailPoint(fixes, position, timeMs, maxPoints) {
const i = insertionIndex(fixes, timeMs);
const prev = fixes[i - 1];
if (
prev?.position &&
distance(prev.position, position) < TRAIL_RECORD_MIN_STEP_M
)
return false;
const entry = {
position,
timeMs,
nullAltitude: false,
drawn: true,
breakBefore: false,
};
insertAt(fixes, i, entry, maxPoints);
// Entries before the second report behind this point can never be thinned
// again, so they let go of the positions they stood for.
const passed = reportBefore(fixes, fixes.lastIndexOf(entry));
if (passed >= 0) sealThrough(fixes, reportBefore(fixes, passed));
return true;
}
/** Release the absorbed positions of entry `i` and everything before it. */
function sealThrough(fixes, i) {
for (let j = i; j >= 0 && !fixes[j].sealed; j--) {
fixes[j].sealed = true;
delete fixes[j].absorbed;
}
}
/**
* Whether the icon's drawn position must not be recorded at a display time:
* a report on either side of it has no altitude (the icon is drawn at an
* invented height), the reports on either side are not one flight
* (`trailPairBreaks`), or the icon is still easing onto a report that
* arrived after the display had passed it.
* @param {object[]} fixes
* @param {number} displayMs
* @returns {boolean}
*/
export function trailRecordingBlocked(fixes, displayMs) {
const i = insertionIndex(fixes, displayMs);
const before = fixes[reportBefore(fixes, i)];
const after = fixes[reportFrom(fixes, i)];
if (before?.nullAltitude || after?.nullAltitude) return true;
if (before?.settleUntilMs > displayMs) return true;
return !!(before && after && trailFixBreaks(before, after));
}
+106 -135
View File
@@ -3,163 +3,134 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
insertTrailFix,
recordTrailPoint,
trailBodySegments,
trailPairBreaks,
trailDistanceM,
trailRecordingBlocked,
trailHeadCurvePoints,
} from './trailContinuity.js';
// Reports decide where the line may run: recorded points never join two
// reports too far apart to be one flight, a report the display has already
// passed replaces the guess drawn after it, and old entries let go of the
// positions they stood for.
// A trail is the aircraft's reports and nothing else, each pair that is one
// path joined along the curve the icon is drawn along between them: no
// stretch it was drawn at between reports is kept, so a late report can
// never leave a kink.
const SEC = 1000;
const LIMIT = 2_000;
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
Cesium.Cartesian3.fromDegrees(-100, 40, 0),
);
const at = (e, n, u = 10) =>
const at = (e, n, u = 3_000) =>
Cesium.Matrix4.multiplyByPoint(
enu,
new Cesium.Cartesian3(e, n, u),
new Cesium.Cartesian3(),
);
/** No two neighbours in one drawn segment are too far apart to be one flight. */
function assertNoBrokenJoin(fixes) {
const reports = fixes.filter((fix) => !fix.drawn && fix.position);
for (const segment of trailBodySegments(fixes, fixes.length)) {
const inSegment = reports.filter((r) =>
segment.some((p) => Cesium.Cartesian3.distance(p, r.position) < 0.01),
);
for (let i = 1; i < inSegment.length; i++)
assert.equal(
trailPairBreaks(
inSegment[i].timeMs - inSegment[i - 1].timeMs,
trailDistanceM(inSegment[i - 1].position, inSegment[i].position),
),
false,
`one segment joins reports at ${inSegment[i - 1].timeMs / SEC} s and ${
inSegment[i].timeMs / SEC
} s`,
);
/** The sharpest turn (degrees) at any vertex of `line`, steps under 1 m skipped. */
function sharpestTurnDeg(line) {
const u = new Cesium.Cartesian3();
const v = new Cesium.Cartesian3();
let worst = 0;
for (let i = 1; i < line.length - 1; i++) {
Cesium.Cartesian3.subtract(line[i], line[i - 1], u);
Cesium.Cartesian3.subtract(line[i + 1], line[i], v);
const lu = Cesium.Cartesian3.magnitude(u);
const lv = Cesium.Cartesian3.magnitude(v);
if (!(lu > 1 && lv > 1)) continue;
const cos = Math.min(1, Cesium.Cartesian3.dot(u, v) / (lu * lv));
worst = Math.max(worst, (Math.acos(cos) * 180) / Math.PI);
}
return worst;
}
test('two reports 60 s and 51 km apart are not joined, even by recorded points', () => {
const A = Cesium.Cartesian3.fromDegrees(-100, 40, 9_000);
const B = Cesium.Cartesian3.fromDegrees(-99.4, 40, 9_000);
const fixes = [];
insertTrailFix(fixes, A, 0, LIMIT);
insertTrailFix(fixes, B, 60 * SEC, LIMIT); // ahead of the display
for (let t = 1; t < 60; t++) {
// Nothing is recorded across the pair.
assert.equal(trailRecordingBlocked(fixes, t * SEC), true);
}
assert.equal(trailBodySegments(fixes, fixes.length).length, 2);
// Points recorded before the far report was known are dropped.
const late = [];
insertTrailFix(late, A, 0, LIMIT);
for (let t = 1; t < 60; t++)
recordTrailPoint(
late,
Cesium.Cartesian3.lerp(A, B, t / 60, new Cesium.Cartesian3()),
t * SEC,
LIMIT,
);
insertTrailFix(late, B, 60 * SEC, LIMIT);
assert.equal(late.filter((fix) => fix.drawn).length, 0);
assert.equal(trailBodySegments(late, late.length).length, 2);
assertNoBrokenJoin(late);
});
// A 100 m/s aircraft in a left turn on a 2 km circle centred at (0, R),
// heading east at the origin, reporting every 15 s with its track.
const R = 2_000;
const W = 100 / R;
const circle = (t) => at(R * Math.sin(W * t), R - R * Math.cos(W * t));
const trackAt = (t) => (90 - (W * t * 180) / Math.PI + 360) % 360;
test('a coast, a hold and then a far report: nothing is drawn across', () => {
const A = at(0, 0, 9_000);
test('reports in a turn are joined along a smooth curve through each report', () => {
const fixes = [];
insertTrailFix(fixes, A, 0, LIMIT);
// The icon coasts east for 90 s at 230 m/s, then holds.
for (let t = 1; t <= 200; t++)
recordTrailPoint(
fixes,
at(230 * Math.min(t, 90), 0, 9_000),
t * SEC,
LIMIT,
);
assert.ok(fixes.filter((fix) => fix.drawn).length > 0);
// The next report is 150 km away two minutes later: over 1,500 kt.
const B = at(0, 150_000, 9_000);
insertTrailFix(fixes, B, 120 * SEC, LIMIT);
assertNoBrokenJoin(fixes);
const segments = trailBodySegments(fixes, fixes.length);
const segmentOf = (p) =>
segments.findIndex((s) =>
s.some((q) => Cesium.Cartesian3.distance(p, q) < 0.01),
);
assert.notEqual(segmentOf(A), segmentOf(B));
// No recorded point between the two reports remains.
assert.equal(
fixes.filter((fix) => fix.drawn && fix.timeMs < 120 * SEC).length,
0,
for (let t = 0; t <= 60; t += 15)
insertTrailFix(fixes, circle(t), t * SEC, LIMIT, { track: trackAt(t) });
assert.deepEqual(
fixes.map((f) => f.timeMs),
[0, 15, 30, 45, 60].map((s) => s * SEC),
);
const [line] = trailBodySegments(fixes, fixes.length);
for (const f of fixes)
assert.ok(
line.some((p) => Cesium.Cartesian3.distance(p, f.position) < 0.01),
'every report is on the line',
);
assert.ok(sharpestTurnDeg(line) < 3, `${sharpestTurnDeg(line)}°`);
// On the circle, not across its chords.
for (const p of line)
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R)) - R) < 20,
'a point off the turn',
);
});
for (const off of [200, 400, 600, 1_000]) {
test(`a report the display already passed, ${off} m off a 2 km turn, leaves no spike`, () => {
const R = 2_000;
const w = 100 / R;
const pos = (t, r = R) =>
at(r * Math.sin(w * t), R - r * Math.cos(w * t), 3_000);
const fixes = [];
insertTrailFix(fixes, pos(0), 0, LIMIT);
for (let t = 1; t <= 60; t++)
recordTrailPoint(fixes, pos(t), t * SEC, LIMIT);
const report = pos(50, R - off);
// It arrives with the display at 60 s; the ease takes 900 ms.
insertTrailFix(fixes, report, 50 * SEC, LIMIT, {
displayMs: 60 * SEC,
settleMs: 900,
});
// The guess drawn after the report is gone...
assert.deepEqual(
fixes.filter((fix) => fix.drawn && fix.timeMs > 50 * SEC),
[],
);
// ...nothing is recorded while the icon eases onto the correction...
assert.equal(trailRecordingBlocked(fixes, 60.5 * SEC), true);
assert.equal(trailRecordingBlocked(fixes, 61 * SEC), false);
// ...and the line reads arc, report, corrected path.
for (let t = 61; t <= 70; t++)
recordTrailPoint(fixes, pos(t, R - off), t * SEC, LIMIT);
const line = trailBodySegments(fixes, fixes.length).flat();
const r = line.findIndex(
(p) => Cesium.Cartesian3.distance(p, report) < 0.01,
);
assert.ok(r > 0);
for (const p of line.slice(0, r))
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R, 3_000)) - R) < 31,
'a point before the report is off the arc',
);
for (const p of line.slice(r + 1))
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R, 3_000)) - (R - off)) <
31,
'a point after the report is off the corrected path',
);
});
}
test('entries behind the report before the display let go of the positions they stood for', () => {
test('reports with no track are joined straight, report to report', () => {
const fixes = [];
for (let s = 0; s <= 2 * 3_600; s++) {
const p = at(230 * s, 0, 10_000);
if (s % 15 === 0) insertTrailFix(fixes, p, s * SEC, LIMIT);
else recordTrailPoint(fixes, p, s * SEC, LIMIT);
}
let held = 0;
for (const fix of fixes) held += fix.absorbed?.length ?? 0;
// Only the newest stretch, up to two reports back, keeps what it stood for.
assert.ok(held <= 30, `${held} positions still held`);
for (let t = 0; t <= 60; t += 15)
insertTrailFix(fixes, circle(t), t * SEC, LIMIT);
const [line] = trailBodySegments(fixes, fixes.length);
assert.equal(line.length, fixes.length);
});
test('two reports 60 s and 51 km apart are not joined', () => {
const fixes = [];
insertTrailFix(
fixes,
Cesium.Cartesian3.fromDegrees(-100, 40, 9_000),
0,
LIMIT,
{ track: 90 },
);
insertTrailFix(
fixes,
Cesium.Cartesian3.fromDegrees(-99.4, 40, 9_000),
60 * SEC,
LIMIT,
{ track: 90 },
);
assert.equal(trailBodySegments(fixes, fixes.length).length, 2);
// Nor is the head drawn along a curve across them.
assert.deepEqual(trailHeadCurvePoints(fixes, 1, 30 * SEC), []);
});
test('a report with no altitude keeps no position and breaks the line', () => {
const fixes = [];
insertTrailFix(fixes, circle(0), 0, LIMIT, { track: trackAt(0) });
insertTrailFix(fixes, circle(15), 15 * SEC, LIMIT, { nullAltitude: true });
insertTrailFix(fixes, circle(30), 30 * SEC, LIMIT, { track: trackAt(30) });
assert.equal(fixes[1].position, null);
assert.equal(trailBodySegments(fixes, fixes.length).length, 2);
});
test('a report arriving late goes in time order and the curve stays smooth', () => {
const fixes = [];
for (const t of [0, 30, 15, 45])
insertTrailFix(fixes, circle(t), t * SEC, LIMIT, { track: trackAt(t) });
assert.deepEqual(
fixes.map((f) => f.timeMs / SEC),
[0, 15, 30, 45],
);
const [line] = trailBodySegments(fixes, fixes.length);
assert.ok(sharpestTurnDeg(line) < 3);
});
test('the head runs along the curve to the next report and stops before the display time', () => {
const fixes = [];
insertTrailFix(fixes, circle(0), 0, LIMIT, { track: trackAt(0) });
insertTrailFix(fixes, circle(15), 15 * SEC, LIMIT, { track: trackAt(15) });
const head = trailHeadCurvePoints(fixes, 1, 10 * SEC);
assert.ok(head.length > 5);
const drawnAt = circle(10);
const [body] = trailBodySegments(fixes, 1);
// Body, head points, then the aircraft: one smooth line.
assert.ok(sharpestTurnDeg([...body, ...head, drawnAt]) < 3);
for (const p of head)
assert.ok(Math.abs(Cesium.Cartesian3.distance(p, at(0, R)) - R) < 20);
});
-180
View File
@@ -1,180 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
insertTrailFix,
joinTrailBackfill,
recordTrailPoint,
TRAIL_THIN_MAX_SPAN_M,
TRAIL_THIN_TOLERANCE_M,
} from './trailContinuity.js';
// Recorded points are thinned by shape: a point stays only where the line
// would move without it. Reports always stay.
const SEC = 1000;
const LIMIT = 2_000;
const LAT0 = 40;
const LON0 = -100;
const M_PER_DEG_LAT = 111_320;
const mPerDegLon = (lat) => M_PER_DEG_LAT * Math.cos((lat * Math.PI) / 180);
/** Straight and level east at `speed` m/s, `tSec` after the start. */
const eastbound = (speed, tSec, heightM = 10_000) =>
Cesium.Cartesian3.fromDegrees(
LON0 + (speed * tSec) / mPerDegLon(LAT0),
LAT0,
heightM,
);
/** A standard-rate (3°/s) left turn from north, radius v / ω, `tSec` in. */
function turning(speed, tSec, heightM = 10_000) {
const omega = (3 * Math.PI) / 180;
const radius = speed / omega;
// Centre west of the start; heading north, turning left (towards west).
const angle = omega * tSec;
const east = -radius + radius * Math.cos(angle);
const north = radius * Math.sin(angle);
return Cesium.Cartesian3.fromDegrees(
LON0 + east / mPerDegLon(LAT0),
LAT0 + north / M_PER_DEG_LAT,
heightM,
);
}
/** Distance from p to the nearest point of a polyline. */
function distanceToPath(p, path) {
let best = Infinity;
const ab = new Cesium.Cartesian3();
const ap = new Cesium.Cartesian3();
const closest = new Cesium.Cartesian3();
for (let i = 1; i < path.length; i++) {
Cesium.Cartesian3.subtract(path[i], path[i - 1], ab);
Cesium.Cartesian3.subtract(p, path[i - 1], ap);
const len2 = Cesium.Cartesian3.magnitudeSquared(ab);
const t =
len2 > 0
? Math.max(0, Math.min(1, Cesium.Cartesian3.dot(ap, ab) / len2))
: 0;
Cesium.Cartesian3.add(
path[i - 1],
Cesium.Cartesian3.multiplyByScalar(ab, t, closest),
closest,
);
best = Math.min(best, Cesium.Cartesian3.distance(p, closest));
}
return best;
}
const drawnCount = (fixes) => fixes.filter((fix) => fix.drawn).length;
test('one hour straight and level with a report every 15 s adds under 60 recorded points', () => {
const speed = 230;
const fixes = [];
for (const t of [0, 15, 30])
insertTrailFix(fixes, eastbound(speed, t), t * SEC, LIMIT);
// Live order: a report arrives 30 s before the display reaches it, and the
// drawn icon is recorded once a second.
for (let t = 1; t <= 3_600; t++) {
const reportAt = t + 30;
if (reportAt % 15 === 0 && reportAt <= 3_600)
insertTrailFix(fixes, eastbound(speed, reportAt), reportAt * SEC, LIMIT);
recordTrailPoint(fixes, eastbound(speed, t), t * SEC, LIMIT);
}
assert.ok(
drawnCount(fixes) < 60,
`${drawnCount(fixes)} recorded points kept`,
);
assert.equal(fixes.filter((fix) => !fix.drawn).length, 241);
});
test('with no report at all, a straight leg keeps one point per 10 km and no more', () => {
const speed = 230;
const fixes = [];
insertTrailFix(fixes, eastbound(speed, 0), 0, LIMIT);
for (let t = 1; t <= 3_600; t++)
recordTrailPoint(fixes, eastbound(speed, t), t * SEC, LIMIT);
const legKm = (speed * 3_600) / 1_000;
assert.equal(TRAIL_THIN_MAX_SPAN_M, 10_000);
assert.ok(
drawnCount(fixes) <= Math.ceil(legKm / 10) + 1,
`${drawnCount(fixes)} points over ${legKm} km`,
);
for (let i = 1; i < fixes.length; i++)
assert.ok(
Cesium.Cartesian3.distance(fixes[i - 1].position, fixes[i].position) <=
TRAIL_THIN_MAX_SPAN_M + speed,
);
});
test('a standard-rate 180° turn keeps its curve: every recorded position stays within 30 m of the kept line', () => {
const speed = 230;
const fixes = [];
const recorded = [];
insertTrailFix(fixes, turning(speed, 0), 0, LIMIT);
for (let t = 1; t <= 60; t++) {
const position = turning(speed, t);
recorded.push(position);
recordTrailPoint(fixes, position, t * SEC, LIMIT);
}
const line = fixes.map((fix) => fix.position);
assert.equal(TRAIL_THIN_TOLERANCE_M, 30);
for (const position of recorded) {
const off = distanceToPath(position, line);
assert.ok(off <= TRAIL_THIN_TOLERANCE_M + 1, `${off.toFixed(1)} m off`);
}
assert.ok(drawnCount(fixes) < recorded.length, 'nothing was thinned');
assert.ok(drawnCount(fixes) >= 6, 'the curve was flattened');
});
test('a climb off the straight line keeps its vertices', () => {
const fixes = [];
insertTrailFix(fixes, eastbound(200, 0, 1_000), 0, LIMIT);
// 30 s level, then a 60 s climb of 20 m/s, then level again.
const height = (t) => 1_000 + 20 * Math.min(60, Math.max(0, t - 30));
const recorded = [];
for (let t = 1; t <= 150; t++) {
const position = eastbound(200, t, height(t));
recorded.push(position);
recordTrailPoint(fixes, position, t * SEC, LIMIT);
}
const line = fixes.map((fix) => fix.position);
for (const position of recorded)
assert.ok(distanceToPath(position, line) <= TRAIL_THIN_TOLERANCE_M + 1);
});
test('at the limit, old recorded points go before any report from the backfill', () => {
const max = 300;
const backfill = [];
for (let i = 0; i < 100; i++)
backfill.push({
position: eastbound(200, i * 60 - 20_000),
timeMs: (i * 60 - 20_000) * SEC,
nullAltitude: false,
});
let fixes = [];
insertTrailFix(fixes, turning(150, 0), 0, max);
// A long series of turns keeps many recorded points.
for (let t = 1; t <= 2_000; t++)
recordTrailPoint(fixes, turning(150, t), t * SEC, max);
assert.ok(drawnCount(fixes) > 150);
fixes = joinTrailBackfill(
{
fixes: backfill.map((b) => ({ ...b, breakBefore: false })),
breakAfter: false,
},
fixes,
max,
);
assert.ok(fixes.length <= max);
const reports = fixes.filter((fix) => !fix.drawn);
assert.equal(reports.length, 101, 'a report was dropped');
// More recording at the limit drops recorded points, never reports.
for (let t = 2_001; t <= 2_400; t++)
recordTrailPoint(fixes, turning(150, t), t * SEC, max);
assert.ok(fixes.length <= max);
assert.equal(fixes.filter((fix) => !fix.drawn).length, 101);
// The recorded points that remain are the newest.
const drawnTimes = fixes.filter((fix) => fix.drawn).map((fix) => fix.timeMs);
assert.ok(Math.min(...drawnTimes) > 1_000 * SEC);
});