diff --git a/src/data/trailRenderer.js b/src/data/trailRenderer.js index d71120293..f5eeb5a6d 100644 --- a/src/data/trailRenderer.js +++ b/src/data/trailRenderer.js @@ -1,29 +1,27 @@ /** * @module trailRenderer * @description Shared track-history renderer (PRD WS-F F4; rebuilt round 6, - * 2026-07-06). + * 2026-07-06; drawn through the renderer's draw port since 2026-11). * - * One trail = one ENTITY polyline. Round 6 replaced the faded per-vertex - * Primitive for two owner directives from the field: - * - "the line must ALWAYS be visible": the Primitive's depthFailAppearance - * did not reliably render segments below the photoreal mesh — entity - * polylines with `depthFailMaterial` DO (in-repo proof: CCTV's frustum - * wireframes read through geometry with exactly this), so occluded - * segments now draw dimmed instead of vanishing. - * - "show actual tracks, don't style them too much": the tail-fade is gone; - * the whole history renders at one readable alpha (dimmer where it passes - * behind/below geometry). + * One trail = one line set on the viewer's draw port: the history line and, + * for layers that draw one, the live head from the last history point to + * the moving contact. Two owner directives from the field shape it: + * - "the line must ALWAYS be visible": where the trail passes behind or + * below scene geometry it draws dimmed (the line's depth-fail colour) + * instead of vanishing. + * - "show actual tracks, don't style them too much": the whole history + * renders at one readable alpha (dimmer where it is hidden). * - * Trails update at poll cadence (~15-60 s) plus once on history backfill, so - * assigning a fresh positions array per update is cheap. `allowPicking` has - * no entity equivalent; the polyline entity is excluded from clicks by never - * carrying a pick id the layers' click handlers resolve. + * The history changes at poll cadence (~15-60 s) plus once on backfill; the + * head may change every frame. Either is rebuilt alone, under the same pick + * id, without rebuilding the other. */ -import * as Cesium from 'cesium'; +import { cssColor } from '../render/color.js'; +import { findDraw } from '../render/rendererOf.js'; import { registerPickOwner } from './pickRegistry.js'; -// Round 6: trail ENTITIES are pickable (the old Primitive had -// allowPicking:false). A trail hugs its aircraft, so an unclaimed pick would +// Trail lines are pickable (a click on one must not fall through to the +// ground under it). A trail hugs its aircraft, so an unclaimed pick would // read as "empty space" in every layer's click handler and deselect the very // plane being tracked. Claiming the 'gev-trail:' id namespace makes // isOwnedByOtherLayer() true for every layer — clicking a trail is a no-op @@ -32,7 +30,7 @@ registerPickOwner('trails', (pickedId) => String(pickedId).startsWith('gev-trail:'), ); -/** @type {number} Uniquifier for trail entity ids (Cesium requires unique entity ids). */ +/** @type {number} Uniquifier for trail set and line ids. */ let _trailSeq = 0; /** @constant {number} Alpha where the trail passes the depth test. */ @@ -40,108 +38,171 @@ const TRAIL_ALPHA = 0.85; /** @constant {number} Alpha where the trail is behind/below scene geometry — * visible (owner: never vanish) but readable as occluded. */ const TRAIL_OCCLUDED_ALPHA = 0.4; +/** @constant {number} Alpha of the live head, and where it is hidden. */ +const HEAD_ALPHA = 0.9; +const HEAD_OCCLUDED_ALPHA = 0.45; /** @constant {number} Squared distance (m^2) below which consecutive points are merged. */ const MIN_SEGMENT_DISTANCE_SQ = 0.01; +/** `css` (any CSS colour) at `alpha`, as a renderer colour. */ +function colorAt(css, alpha) { + const [r, g, b] = cssColor(css) ?? [1, 1, 1]; + return [r, g, b, alpha]; +} + +const distanceSq = (a, b) => + (a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2; + +/** + * Consecutive near-duplicates dropped (zero-length segments add nothing), + * as plain ECEF; empty when fewer than 2 distinct positions remain. + * @param {Array<{x: number, y: number, z: number}|null|undefined>} given + */ +function trailPositions(given) { + const positions = []; + for (const position of Array.isArray(given) ? given : []) { + if (!position) continue; + const last = positions[positions.length - 1]; + if (last && distanceSq(last, position) < MIN_SEGMENT_DISTANCE_SQ) continue; + positions.push({ x: position.x, y: position.y, z: position.z }); + } + return positions.length >= 2 ? positions : []; +} + /** * Create an always-visible polyline trail bound to a viewer. - * @param {Cesium.Viewer} viewer - Viewer whose entity collection owns the trail. + * @param {object} viewer - Viewer whose renderer draws the trail. * @param {object} options - Trail options. - * @param {string} options.color - CSS color string for the trail hue. - * @param {number} [options.width=2.5] - Polyline width in pixels. - * @returns {{setPositions: function(Array): void, setVisible: function(boolean): void, clear: function(): void, destroy: function(): void}} - * Trail handle: setPositions replaces the geometry, setVisible temporarily - * hides it without discarding history, clear empties it, and destroy removes - * the entity permanently. + * @param {string} options.color - CSS colour of the trail. + * @param {number} [options.width=2.5] - Line width in pixels. + * @returns {{setPositions: function(Array<{x: number, y: number, z: number}>): void, setHead: function(Array<{x: number, y: number, z: number}>|null): void, setVisible: function(boolean): void, clear: function(): void, destroy: function(): void}} + * Trail handle: setPositions replaces the history, setHead the live head + * (null or fewer than 2 positions: none), setVisible temporarily hides + * both without discarding them, clear empties both, and destroy removes + * the trail permanently. */ export function createTrail(viewer, { color, width = 2.5 }) { - const baseColor = Cesium.Color.fromCssColorString(color); - /** @type {Cesium.Cartesian3[]} Current deduped positions (owned copy). */ - let current = []; + const seq = ++_trailSeq; + const bodyId = `gev-trail:${seq}`; + const headId = `gev-trail:${seq}:head`; let destroyed = false; let visible = true; - /** @type {Cesium.Entity|null} */ - let entity = null; + /** @type {import('../render/contract/draw').DrawSet|null} */ + let set = null; + /** Each line as last drawn and its positions' key, by id, to skip a redraw that changes nothing. */ + const drawn = new Map(); + /** The head given while the trail is hidden, drawn once it shows. */ + let pendingHead = null; - function ensureEntity() { - if (entity || destroyed || !viewer || viewer.isDestroyed()) return; - entity = viewer.entities.add({ - id: `gev-trail:${++_trailSeq}`, - show: visible, - polyline: { - // CallbackProperty so a positions swap never rebuilds the entity — - // Cesium re-reads on change; `false` marks it non-constant. - positions: new Cesium.CallbackProperty(() => current, false), - width, - material: baseColor.withAlpha(TRAIL_ALPHA), - // The owner-locked rule (round 6): a segment below the photoreal - // mesh renders dimmed — it must never disappear into the ground. - depthFailMaterial: baseColor.withAlpha(TRAIL_OCCLUDED_ALPHA), - // Round 8 (owner: UAL1104's Pacific trail "cutting through the - // globe"): NONE draws straight 3D chords between waypoints — over a - // sparse trans-oceanic trace a single segment spans hundreds of km - // and tunnels through the planet. GEODESIC subdivides each segment - // along the curved surface (heights interpolated), so long legs hug - // the globe instead of chording through it. - arcType: Cesium.ArcType.GEODESIC, - }, - }); + function ensureSet() { + if (set || destroyed || !viewer || viewer.isDestroyed?.()) return set; + set = + findDraw(viewer)?.lines({ id: `trail:${seq}`, show: visible }) ?? null; + return set; + } + + /** + * Draw one of the trail's lines, or with no positions hide it. A hidden + * line stays in the set, so the other is never rebuilt for it. + */ + function draw(id, positions, alpha, occludedAlpha, mode = 'geodesic') { + if (destroyed || !viewer || viewer.isDestroyed?.()) return; + const lines = ensureSet(); + if (!lines) return; + const key = positions.map(({ x, y, z }) => `${x},${y},${z}`).join(';'); + const was = drawn.get(id); + if ((was?.key ?? '') === key) return; + if (!positions.length) { + const hidden = { ...was.item, show: false }; + drawn.set(id, { key, item: hidden }); + lines.upsert([hidden]); + return; + } + const item = { + id, + positions, + widthPx: width, + mode, + style: { kind: 'solid', color: colorAt(color, alpha) }, + // The owner-locked rule (round 6): a segment below the photoreal + // mesh renders dimmed — it must never disappear into the ground. + depthFailColor: colorAt(color, occludedAlpha), + }; + drawn.set(id, { key, item }); + lines.upsert([item]); + } + + /** + * Replace the live head: the segment from the last drawn history point + * to where the contact is drawn now. It may change every frame: while + * the trail is hidden it is only kept, and drawn once the trail shows. + * @param {Array<{x: number, y: number, z: number}>|null} cartesians + */ + function setHead(cartesians) { + if (!visible) { + pendingHead = cartesians ?? []; + return; + } + pendingHead = null; + // One poll interval long at most: straight is the geodesic to the + // pixel, and a frame's rebuild stays two positions. + draw( + headId, + trailPositions(cartesians), + HEAD_ALPHA, + HEAD_OCCLUDED_ALPHA, + '3d', + ); } return { /** * Replace the trail geometry with a chronological position list * (oldest first). Fewer than 2 distinct positions clears the trail. - * @param {Array} cartesians + * @param {Array<{x: number, y: number, z: number}>} cartesians * ECEF positions, oldest -> newest. */ setPositions(cartesians) { - if (destroyed || !viewer || viewer.isDestroyed()) return; - // Drop consecutive near-duplicates: zero-length segments add nothing. - const positions = []; - for (const position of Array.isArray(cartesians) ? cartesians : []) { - if (!position) continue; - const last = positions[positions.length - 1]; - if ( - last && - Cesium.Cartesian3.distanceSquared(last, position) < - MIN_SEGMENT_DISTANCE_SQ - ) - continue; - // Callers may hand plain ECEF {x, y, z}: the polyline gets Cartesian3s. - positions.push( - position instanceof Cesium.Cartesian3 - ? position - : new Cesium.Cartesian3(position.x, position.y, position.z), - ); - } - current = positions.length >= 2 ? positions : []; - ensureEntity(); + // Round 8 (owner: UAL1104's Pacific trail "cutting through the + // globe"): straight 3D chords between sparse trans-oceanic + // waypoints tunnel through the planet; a geodesic line follows the + // curved surface (heights interpolated) instead. + draw( + bodyId, + trailPositions(cartesians), + TRAIL_ALPHA, + TRAIL_OCCLUDED_ALPHA, + ); }, + setHead, + /** Temporarily hide/show the trail without discarding accumulated history. */ setVisible(nextVisible) { visible = nextVisible !== false; - if (entity) entity.show = visible; + if (set) set.show = visible; + if (visible && pendingHead) setHead(pendingHead); }, - /** Empty the trail without removing the entity (cheap re-arm). */ + /** Empty the trail, keeping its set (cheap re-arm). */ clear() { - current = []; + pendingHead = null; + if (!destroyed && set && !viewer?.isDestroyed?.() && drawn.size) { + drawn.clear(); + set.clear(); + } }, - /** Remove the trail entity permanently (layer disable/teardown). */ + /** Remove the trail permanently (layer disable/teardown). */ destroy() { destroyed = true; - current = []; - if (entity && viewer && !viewer.isDestroyed()) { - try { - viewer.entities.remove(entity); - } catch { - /* torn down */ - } + try { + set?.dispose(); + } catch { + /* torn down */ } - entity = null; + set = null; + drawn.clear(); }, }; } diff --git a/src/data/trailRenderer.test.mjs b/src/data/trailRenderer.test.mjs index 08799c895..b89ecf242 100644 --- a/src/data/trailRenderer.test.mjs +++ b/src/data/trailRenderer.test.mjs @@ -1,62 +1,151 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { createTrail } from './trailRenderer.js'; +import { findPickOwner } from './pickRegistry.js'; -test('trail visibility can change without discarding its accumulated geometry', () => { - const added = []; - const removed = []; - const viewer = { - isDestroyed: () => false, - entities: { - add(definition) { - added.push(definition); - return definition; - }, - remove(entity) { - removed.push(entity); - }, - }, - }; +function viewerWithDraw(t) { + const viewer = { isDestroyed: () => false }; + const { draw, unbind } = bindFakeDraw(viewer); + t.after(unbind); + return { viewer, draw }; +} + +test('a trail draws its history as one dimmed-when-hidden geodesic line', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const trail = createTrail(viewer, { color: '#00d4ff', width: 2.5 }); + trail.setPositions([ + { x: 1, y: 2, z: 3 }, + { x: 1, y: 2, z: 3.01 }, + { x: 4, y: 5, z: 6 }, + ]); + const set = draw.find('trail:'); + assert.equal(set.kind, 'lines'); + assert.equal(set.items.size, 1); + const [line] = set.items.values(); + assert.match(line.id, /^gev-trail:/, 'claimed by the trail pick owner'); + assert.equal(findPickOwner(line.id), 'trails'); + // The near-duplicate merges. + assert.deepEqual(line.positions, [ + { x: 1, y: 2, z: 3 }, + { x: 4, y: 5, z: 6 }, + ]); + assert.equal(line.widthPx, 2.5); + assert.equal(line.mode, 'geodesic'); + assert.equal(line.style.kind, 'solid'); + assert.deepEqual(line.style.color, [0, 212 / 255, 1, 0.85]); + assert.deepEqual(line.depthFailColor, [0, 212 / 255, 1, 0.4]); + + // The same positions again change nothing; fewer than two distinct hide it. + const writes = set.writes; + trail.setPositions([ + { x: 1, y: 2, z: 3 }, + { x: 4, y: 5, z: 6 }, + ]); + assert.equal(set.writes, writes); + trail.setPositions([{ x: 1, y: 2, z: 3 }]); + assert.equal(set.items.get(line.id).show, false, 'hidden, kept in place'); +}); + +test('a trail head is a line of its own beside the history, at the head alphas', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const trail = createTrail(viewer, { color: '#ffb800' }); + trail.setPositions([ + { x: 0, y: 0, z: 0 }, + { x: 10, y: 0, z: 0 }, + ]); + trail.setHead([ + { x: 10, y: 0, z: 0 }, + { x: 20, y: 0, z: 0 }, + ]); + const set = draw.find('trail:'); + assert.equal(set.items.size, 2); + const head = [...set.items.values()].find((line) => + line.id.endsWith(':head'), + ); + assert.equal(findPickOwner(head.id), 'trails'); + assert.equal(head.style.color[3], 0.9); + assert.equal(head.depthFailColor[3], 0.45); + assert.equal(head.mode, '3d', 'short: straight, two positions a frame'); + // No head: hidden once, then nothing more to write. + trail.setHead(null); + assert.equal(set.items.get(head.id).show, false); + const writes = set.writes; + trail.setHead([]); + assert.equal(set.writes, writes); + trail.clear(); + assert.equal(set.items.size, 0); +}); + +test('trail visibility can change without discarding its accumulated geometry', (t) => { + const { viewer, draw } = viewerWithDraw(t); const trail = createTrail(viewer, { color: '#ffffff' }); - const positions = [ - new Cesium.Cartesian3(1, 2, 3), - new Cesium.Cartesian3(4, 5, 6), - ]; - trail.setVisible(false); - trail.setPositions(positions); - assert.equal(added.length, 1); - assert.equal(added[0].show, false); - assert.deepEqual(added[0].polyline.positions.getValue(), positions); - + trail.setPositions([ + { x: 1, y: 2, z: 3 }, + { x: 4, y: 5, z: 6 }, + ]); + const set = draw.find('trail:'); + assert.equal(set.show, false, 'made hidden'); trail.setVisible(true); - assert.equal(added[0].show, true); - assert.deepEqual(added[0].polyline.positions.getValue(), positions); - + assert.equal(set.show, true); + assert.equal(set.items.size, 1, 'history kept'); trail.destroy(); - assert.deepEqual(removed, [added[0]]); + assert.equal(set.disposed, true); + trail.setPositions([ + { x: 1, y: 2, z: 3 }, + { x: 4, y: 5, z: 6 }, + ]); + assert.equal(draw.find('trail:'), undefined, 'nothing after destroy'); }); -test('trail positions may be plain ECEF: the polyline still draws Cartesian3s', () => { - const added = []; - const viewer = { - isDestroyed: () => false, - entities: { - add(definition) { - added.push(definition); - return definition; - }, - remove() {}, - }, - }; - const trail = createTrail(viewer, { color: '#ffffff' }); - const given = new Cesium.Cartesian3(1, 2, 3); - trail.setPositions([given, { x: 1, y: 2, z: 3.01 }, { x: 4, y: 5, z: 6 }]); - const drawn = added[0].polyline.positions.getValue(); - // The near-duplicate merges; a Cartesian3 given passes through as it is. - assert.equal(drawn.length, 2); - assert.equal(drawn[0], given); - assert.ok(drawn[1] instanceof Cesium.Cartesian3); - assert.deepEqual([drawn[1].x, drawn[1].y, drawn[1].z], [4, 5, 6]); +test('a head given while the trail is hidden is drawn once it shows', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const trail = createTrail(viewer, { color: '#fff' }); + trail.setPositions([ + { x: 0, y: 0, z: 0 }, + { x: 10, y: 0, z: 0 }, + ]); + const set = draw.find('trail:'); + trail.setVisible(false); + const writes = set.writes; + for (let i = 1; i <= 3; i++) + trail.setHead([ + { x: 10, y: 0, z: 0 }, + { x: 10 + i, y: 0, z: 0 }, + ]); + assert.equal(set.writes, writes, 'nothing drawn while hidden'); + trail.setVisible(true); + const head = [...set.items.values()].find((line) => + line.id.endsWith(':head'), + ); + assert.deepEqual(head.positions.at(-1), { x: 13, y: 0, z: 0 }, 'the last'); + // Any CSS colour, at the trail's alphas. + assert.deepEqual(head.style.color, [1, 1, 1, 0.9]); +}); + +test('a hidden line shows again where it is next given', (t) => { + const { viewer, draw } = viewerWithDraw(t); + const trail = createTrail(viewer, { color: '#39ffd5' }); + const line = (x) => [ + { x: 0, y: 0, z: 0 }, + { x, y: 0, z: 0 }, + ]; + trail.setPositions(line(10)); + trail.setPositions([]); + trail.setPositions(line(20)); + const [body] = draw.find('trail:').items.values(); + assert.notEqual(body.show, false); + assert.deepEqual(body.positions, line(20)); +}); + +test('a viewer with nothing to draw with draws no trail', () => { + const trail = createTrail({ isDestroyed: () => false }, { color: '#fff' }); + assert.doesNotThrow(() => + trail.setPositions([ + { x: 1, y: 2, z: 3 }, + { x: 4, y: 5, z: 6 }, + ]), + ); + trail.destroy(); }); diff --git a/src/layers/flights/ownership.test.mjs b/src/layers/flights/ownership.test.mjs index 1a6bf7b66..e4c3343c5 100644 --- a/src/layers/flights/ownership.test.mjs +++ b/src/layers/flights/ownership.test.mjs @@ -161,3 +161,96 @@ test('a flight layer without an icon set declines contact refreshes', () => { assert.equal(layer.refreshTr3b('abc123'), false); assert.equal(layer.trackById('abc123'), false); }); + +test('the tracked trail head is drawn each frame while tracked and stops with the trail', async () => { + const Cesium = await import('cesium'); + const { bindFakeDraw } = await import('../../testSupport/fakeDrawPort.mjs'); + const trails = await import('../../data/trailRenderer.js'); + const listeners = new Set(); + const frame = { + on(phase, cb) { + const entry = { phase, cb }; + listeners.add(entry); + return () => listeners.delete(entry); + }, + }; + const tick = () => { + for (const { phase, cb } of [...listeners]) if (phase === 'preRender') cb(); + }; + const viewer = { isDestroyed: () => false }; + const { draw, unbind } = bindFakeDraw(viewer, { frame }); + const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 1000); + const old = Cesium.JulianDate.addSeconds( + Cesium.JulianDate.now(), + -600, + new Cesium.JulianDate(), + ); + let headLon = 0.03; + const flightState = { + _viewer: viewer, + _trackedIcao: 'abc123', + _trail: null, + _trailPositions: [], + _trailBackfillToken: 0, + _trailHeadOff: null, + _cockpitContactMode: false, + _positionHistory: new Map([ + [ + 'abc123', + [0, 0.01, 0.02].map((lon) => ({ time: old, position: at(lon) })), + ], + ]), + _scratchWarmupTime: new Cesium.JulianDate(), + _scratchTrailHead: new Cesium.Cartesian3(), + feed: { _source: {} }, + records: { data: new Map() }, + lifetime: new AbortController(), + }; + const supplied = services(); + supplied.trails = trails; + const tracking = createTracking({ + flightState, + services: supplied, + parts: { + motion: { + _isTrackWarmingUp: () => false, + _trackedTrailCached: () => at(headLon), + _trackedDisplayPosition: () => null, + _trackedModelCenterWorld: () => null, + _trackedModelEnvelopeM: () => 0, + }, + }, + layer: {}, + }); + try { + tracking._startTrail('abc123'); + assert.equal(listeners.size, 1, 'one frame listener'); + tick(); + const set = draw.find('trail:'); + const head = () => set.items.get(`${[...set.items.keys()][0]}:head`); + assert.ok( + Cesium.Cartesian3.equals( + new Cesium.Cartesian3(...Object.values(head().positions[1])), + at(0.03), + ), + ); + headLon = 0.04; + tick(); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + new Cesium.Cartesian3(...Object.values(head().positions[1])), + at(0.04), + 1e-6, + ), + ); + // Tracked again: still one listener. + tracking._clearTrail(); + assert.equal(listeners.size, 0, 'cleared with the trail'); + tracking._startTrail('abc123'); + assert.equal(listeners.size, 1); + tracking._destroyTrail(); + assert.equal(listeners.size, 0, 'gone with the trail'); + } finally { + unbind(); + } +}); diff --git a/src/layers/flights/state.js b/src/layers/flights/state.js index 2562f92c6..0383db1e6 100644 --- a/src/layers/flights/state.js +++ b/src/layers/flights/state.js @@ -189,15 +189,11 @@ export function createFlightState({ source, services }) { flightState._trail = null; - /** @type {Cesium.Entity|null} Cheap 2-point head segment bridging the last fix to the LIVE - * dead-reckoned icon, updated per frame via a CallbackProperty — so the trail head stays - * glued to the 12 Hz icon without rebuilding the 400-point trail primitive every frame. */ + /** @type {(() => void)|null} Stops the per-frame live head (last body point → live + * icon), drawn as the trail's head line so the head stays glued to the 12 Hz icon + * without rebuilding the 400-point trail body every frame. */ - flightState._trailHeadEntity = null; - - /** @type {number} Uniquifier for head-segment entity ids (Cesium requires unique ids). */ - - flightState._trailHeadSeq = 0; + flightState._trailHeadOff = null; /** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */ diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index 6679d9078..272eb1f7a 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -1,4 +1,5 @@ import { cameraOf } from '../../render/cesium/camera.js'; +import { findFrame } from '../../render/rendererOf.js'; import { entityFollowTarget, onFollowChanged, @@ -224,7 +225,6 @@ export function createTracking({ // synchronously blocked Chrome's renderer into Page Unresponsive. if (flightState._modelCollection) flightState._modelCollection.show = true; flightState._trail?.setVisible(!next); - if (flightState._trailHeadEntity) flightState._trailHeadEntity.show = !next; for (const icao24 of flightState._icons?.ids() ?? []) parts.icons._applyIconPresentation(icao24); flightState._lastFleetTickMs = 0; @@ -382,7 +382,7 @@ export function createTracking({ // The trail BODY is the accumulated fixes EXCLUDING the newest raw one — that newest // fix is at ~now, ~one poll interval AHEAD of the delayed icon (rendered at // now − RENDER_DELAY_SEC), so drawing it would push the trail in front of the plane. - // The cheap per-frame _trailHeadEntity segment bridges the last body point to the + // The cheap per-frame trail head segment bridges the last body point to the // delayed dead-reckoned head, so the body primitive only rebuilds on a real fix // (poll cadence), never at motion cadence. if (!flightState._trail) return; @@ -393,6 +393,54 @@ 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[]} + */ + function _trailHeadPositions() { + // Need ≥2 accumulated points: the body draws all-but-newest, so the head must + // start at the last DISPLAYED body point (index n−2). With a single fix that + // point would be the sole raw fix — which is ~now, AHEAD of the delayed icon — + // so the segment would draw IN FRONT of the plane. Likewise during warm-up the + // icon predates all real history, so there is no valid body point behind it. + if ( + !flightState._trackedIcao || + flightState._trailPositions.length < 2 || + parts.motion._isTrackWarmingUp() + ) + return []; + const head = + parts.motion._trackedTrailCached() || + parts.motion._trackedDisplayPosition(flightState._trackedIcao); + if (!head) return []; + // body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a + // backward/reversing segment. + const start = + flightState._trailPositions[flightState._trailPositions.length - 2]; + // 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 + // START is what slides, from nothing on a parked contact out to the + // whole segment once it has cleared its own envelope. + // See trailHeadStart. Read `head` in place and clone only on the draw + // path — a suppressed parked contact runs this every frame. + const from = trailHeadStart( + start, + head, + parts.motion._trackedModelCenterWorld(), + parts.motion._trackedModelEnvelopeM(), + flightState._scratchTrailHead, + ); + if (!from) return []; + return [from, Cesium.Cartesian3.clone(head)]; + } + + /** Each drawn frame, before it draws: the live head where the aircraft is now. */ + function _drawTrailHead() { + flightState._trail?.setHead(_trailHeadPositions()); + } + /** * Start the trail for a newly tracked aircraft: seed it with the short * dead-reckoning history (chronological), render immediately, then @@ -425,65 +473,13 @@ export function createTracking({ }); } flightState._trail?.setVisible(!flightState._cockpitContactMode); - // Live head segment: last fix → current dead-reckoned icon, updated every frame via - // a CallbackProperty (Cesium updates entity-polyline positions cheaply, unlike the - // trail primitive which fully rebuilds on setPositions). Keeps the head glued to the - // 12 Hz icon instead of lagging ~1 s behind it. - if (!flightState._trailHeadEntity && flightState._viewer) { - flightState._trailHeadEntity = flightState._viewer.entities.add({ - // 'gev-trail' namespace (round 6): claimed by trailRenderer's pick - // owner so a click on the head segment never reads as empty space. - id: `gev-trail:fl-head-${++flightState._trailHeadSeq}`, - show: !flightState._cockpitContactMode, - polyline: { - positions: new Cesium.CallbackProperty(() => { - // Need ≥2 accumulated points: the body draws all-but-newest, so the head must - // start at the last DISPLAYED body point (index n−2). With a single fix that - // point would be the sole raw fix — which is ~now, AHEAD of the delayed icon — - // so the segment would draw IN FRONT of the plane. Likewise during warm-up the - // icon predates all real history, so there is no valid body point behind it. - if ( - !flightState._trackedIcao || - flightState._trailPositions.length < 2 || - parts.motion._isTrackWarmingUp() - ) - return []; - const head = - parts.motion._trackedTrailCached() || - parts.motion._trackedDisplayPosition(flightState._trackedIcao); - if (!head) return []; - // body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a - // backward/reversing segment. - const start = - flightState._trailPositions[ - flightState._trailPositions.length - 2 - ]; - // 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 - // START is what slides, from nothing on a parked contact out to the - // whole segment once it has cleared its own envelope. - // See trailHeadStart. Read `head` in place and clone only on the draw - // path — a suppressed parked contact runs this every frame. - const from = trailHeadStart( - start, - head, - parts.motion._trackedModelCenterWorld(), - parts.motion._trackedModelEnvelopeM(), - flightState._scratchTrailHead, - ); - if (!from) return []; - return [from, Cesium.Cartesian3.clone(head)]; - }, false), - width: 2.5, - material: Cesium.Color.fromCssColorString(TRAIL_COLOR).withAlpha(0.9), - // Round 4: the head must never vanish into the mesh either (dimmed - // when occluded so depth still reads). - depthFailMaterial: - Cesium.Color.fromCssColorString(TRAIL_COLOR).withAlpha(0.45), - arcType: Cesium.ArcType.GEODESIC, // round 8: consistent with the trail body (no chords) - }, - }); + // Live head segment: last displayed body point → current dead-reckoned icon, drawn + // again each frame before it draws, so it stays glued to the 12 Hz icon instead of + // lagging ~1 s behind it. Only the head line is rebuilt; the body rebuilds on a real + // fix (poll cadence). Dimmed where occluded (round 4), geodesic as the body (round 8). + if (!flightState._trailHeadOff && flightState._viewer) { + flightState._trailHeadOff = + findFrame(flightState._viewer)?.on('preRender', _drawTrailHead) ?? null; } _refreshTrailDisplay(); @@ -600,18 +596,8 @@ export function createTracking({ flightState._trailBackfillToken += 1; flightState._trailPositions = []; if (flightState._trail) flightState._trail.clear(); - if ( - flightState._trailHeadEntity && - flightState._viewer && - !flightState._viewer.isDestroyed() - ) { - try { - flightState._viewer.entities.remove(flightState._trailHeadEntity); - } catch { - /* already gone */ - } - } - flightState._trailHeadEntity = null; + flightState._trailHeadOff?.(); + flightState._trailHeadOff = null; } /** diff --git a/src/layers/localAdsb/index.js b/src/layers/localAdsb/index.js index f2afc52f7..137707c4e 100644 --- a/src/layers/localAdsb/index.js +++ b/src/layers/localAdsb/index.js @@ -138,9 +138,10 @@ export function createLocalAdsbLayer({ let viewer = null; /** * The layer's draw sets on its viewer's renderer (`drawOf`), made at - * `init`: the markers, the 978 MHz rings and the selected aircraft's live - * trail head. Shown while the layer is enabled. - * @type {{markers: object, rings: object, head: object}|null} + * `init`: the markers and the 978 MHz rings. Shown while the layer is + * enabled. The selected aircraft's trail and its live head draw through + * the shared trail renderer. + * @type {{markers: object, rings: object}|null} */ let sets = null; let enabled = false; @@ -153,7 +154,6 @@ export function createLocalAdsbLayer({ let renderHeld = false; let selectedId = null; let selectedTrail = null; - let trailHeadSeq = 0; let models = null; let geoidReady = false; let rejectedFixes = 0; @@ -406,7 +406,6 @@ export function createLocalAdsbLayer({ function releaseTrail() { if (!selectedTrail) return; selectedTrail.trail?.destroy(); - sets?.head.clear(); selectedTrail = null; } @@ -420,35 +419,24 @@ export function createLocalAdsbLayer({ * costs nothing a frame. */ function drawTrailHead() { - if (!sets || !selectedTrail?.headId) return; + if (!selectedTrail?.trail?.setHead) return; const current = markers.get(selectedTrail.id); const from = selectedTrail.lastFix; const positions = current?.position && from ? [from, { ...current.position }] : []; - const key = positions.map(({ x, y, z }) => `${x},${y},${z}`).join(';'); - if (key === selectedTrail.drawnKey) return; const at = now(); if ( + positions.length && from === selectedTrail.drawnFrom && at - selectedTrail.drawnAt < HEAD_REDRAW_MS ) return; - selectedTrail.drawnKey = key; selectedTrail.drawnFrom = from; selectedTrail.drawnAt = at; - sets.head.upsert([ - { - // 'gev-trail' namespace: claimed by the trail pick owner so a click - // on the head segment never reads as empty space. - id: selectedTrail.headId, - positions, - widthPx: 2.5, - // Metres to a few km: straight is the ellipsoid's arc to the pixel. - mode: '3d', - style: { kind: 'solid', color: hexColor(LOCAL_ADSB_COLOR, 0.9) }, - depthFailColor: hexColor(LOCAL_ADSB_COLOR, 0.45), - }, - ]); + // The trail's head line: 'gev-trail' ids, claimed by the trail pick + // owner so a click on it never reads as empty space; dimmed where the + // surface hides it. A head that has not moved is not drawn again. + selectedTrail.trail.setHead(positions); } function refreshTrail() { @@ -464,15 +452,13 @@ export function createLocalAdsbLayer({ function startTrail(marker) { releaseTrail(); const createTrail = services.trails?.createTrail; - if (typeof createTrail !== 'function' || !viewer || !sets) return; + if (typeof createTrail !== 'function' || !viewer) return; selectedTrail = { id: marker.id, trail: createTrail(viewer, { color: LOCAL_ADSB_COLOR, width: 2.5 }), // Live head: last heard fix → the extrapolated marker, every frame. - headId: `gev-trail:local-adsb-head-${++trailHeadSeq}`, lastFix: null, - // Where, from which fix and when the head was last drawn. - drawnKey: null, + // From which fix and when the head was last drawn. drawnFrom: null, drawnAt: -Infinity, }; @@ -772,7 +758,6 @@ export function createLocalAdsbLayer({ show: false, pickable: false, }), - head: draw.lines({ id: `${prefix}:trail-head`, show: false }), }; models = createLocalAdsbModels({ viewer, diff --git a/src/layers/localAdsb/index.test.mjs b/src/layers/localAdsb/index.test.mjs index 4ef87193d..75f113a73 100644 --- a/src/layers/localAdsb/index.test.mjs +++ b/src/layers/localAdsb/index.test.mjs @@ -445,6 +445,7 @@ test('selecting an aircraft draws a magenta trail of the fixes the receiver hear }); test('the trail head runs from the last fix to the marker every frame, dimmed behind the surface', async (t) => { + const trails = await import('../../data/trailRenderer.js'); const receiver = fakeReceiver({ mode: 'adsb', connected: true }); const clock = { now: 100_000 }; const listeners = new Map(); @@ -462,19 +463,24 @@ test('the trail head runs from the last fix to the marker every frame, dimmed be const input = fakeInput(viewer); const { layer } = await enabledLayer(receiver, clock, null, { viewer: { draw, viewer, input }, - services: { - trails: { - createTrail: () => ({ setPositions() {}, destroy() {} }), - }, - }, + services: { trails }, }); t.after(() => layer.destroy()); receiver.set({ aircraft: [record()] }); await layer.update(); assert.equal(layer.selectAircraft('abc123'), true); - const heads = () => [...layerSet(draw, ':trail-head').items.values()]; + // The head is the shared trail's head line. + const trailSet = () => draw.find('trail:'); + const heads = () => + [...(trailSet()?.items.values() ?? [])].filter( + (line) => line.id.endsWith(':head') && line.show !== false, + ); + // Selected at its fix, the head has no length yet. + assert.equal(heads().length, 0); + clock.now = 100_500; + listeners.get('preRender')(); const [head] = heads(); - assert.match(head.id, /^gev-trail:local-adsb-head-\d+$/); + assert.match(head.id, /^gev-trail:\d+:head$/); assert.equal(head.mode, '3d'); assert.equal(head.widthPx, 2.5); assert.deepEqual(head.style, { @@ -505,9 +511,9 @@ test('the trail head runs from the last fix to the marker every frame, dimmed be ); // A frame where nothing moved leaves the head alone. - const writes = layerSet(draw, ':trail-head').writes; + const writes = trailSet().writes; listeners.get('preRender')(); - assert.equal(layerSet(draw, ':trail-head').writes, writes); + assert.equal(trailSet().writes, writes); await layer.disable(); assert.equal(listeners.has('preRender'), false, 'frames stop when off'); @@ -889,7 +895,7 @@ test('the layer draws into sets of its own, shown while it is enabled and let go .filter((record) => !record.disposed) .map((record) => record.spec.id); const mine = ids(draw); - assert.equal(mine.length, 3, 'markers, rings and the trail head'); + assert.equal(mine.length, 2, 'markers and rings'); assert.ok( ids(other.draw).every((id) => !mine.includes(id)), 'a second layer has ids of its own', diff --git a/src/layers/military/state.js b/src/layers/military/state.js index 558702454..7ee9638d2 100644 --- a/src/layers/military/state.js +++ b/src/layers/military/state.js @@ -162,13 +162,11 @@ export function createFlightState({ source, services }) { flightState._trail = null; - /** @type {Cesium.Entity|null} Per-frame head segment: last body point → live icon */ + /** @type {(() => void)|null} Stops the per-frame live head (last body point → live + * icon), drawn as the trail's head line so the head stays glued to the 12 Hz icon + * without rebuilding the 400-point trail body every frame. */ - flightState._trailHeadEntity = null; - - /** @type {number} Uniquifier for head-segment entity ids (Cesium requires unique ids). */ - - flightState._trailHeadSeq = 0; + flightState._trailHeadOff = null; /** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */ diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index 090c24590..c6e789a9a 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -1,4 +1,5 @@ import { cameraOf } from '../../render/cesium/camera.js'; +import { findFrame } from '../../render/rendererOf.js'; import { entityFollowTarget, onFollowChanged, @@ -211,7 +212,6 @@ export function createTracking({ // Never bulk-destroy here: that stalls the renderer exactly as cockpit begins. if (flightState._modelCollection) flightState._modelCollection.show = true; flightState._trail?.setVisible(!next); - if (flightState._trailHeadEntity) flightState._trailHeadEntity.show = !next; const icons = flightState._icons; for (const icao24 of icons?.ids() ?? []) parts.icons._applyIconPresentation(icao24); @@ -497,7 +497,7 @@ export function createTracking({ * Renders the trail BODY — the accumulated fixes EXCLUDING the newest raw one. That * newest fix is at ~now, ~one poll interval AHEAD of the delayed icon (rendered at * now − RENDER_DELAY_SEC), so drawing it would push the trail in FRONT of the plane. - * The cheap per-frame _trailHeadEntity segment bridges the last body point to the + * The cheap per-frame trail head segment bridges the last body point to the * delayed dead-reckoned head, so this primitive only rebuilds on a real fix (poll * cadence), never at motion cadence. */ @@ -511,6 +511,58 @@ 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[]} + */ + function _trailHeadPositions() { + // Need ≥2 accumulated points: the body draws all-but-newest, so the head must + // start at the last DISPLAYED body point (index n−2). With a single fix that + // point would be the sole raw fix — ~now, AHEAD of the delayed icon — so the + // segment would draw IN FRONT of the plane. Likewise during warm-up the icon + // predates all real history, so there is no valid body point behind it. + if ( + !flightState._trackedIcao || + flightState._trailPositions.length < 2 || + parts.motion._isTrackWarmingUp() + ) + return []; + const head = + parts.motion._trackedTrailCached() || + parts.motion._trackedDisplayPosition(flightState._trackedIcao); + if (!head) return []; + // body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a + // backward/reversing segment. + const start = + flightState._trailPositions[flightState._trailPositions.length - 2]; + // 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)); + // 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 + // START is what slides, from nothing on a parked contact out to the + // whole segment once it has cleared its own envelope. Measured against + // the FLOORED endpoint, which is the one actually drawn. + // See trailHeadStart. + const from = trailHeadStart( + start, + end, + parts.motion._trackedModelCenterWorld(), + parts.motion._trackedModelEnvelopeM(), + flightState._scratchTrailHead, + ); + if (!from) return []; + return [from, end]; + } + + /** Each drawn frame, before it draws: the live head where the aircraft is now. */ + function _drawTrailHead() { + flightState._trail?.setHead(_trailHeadPositions()); + } + /** * Start the trail for a newly tracked aircraft: seed it with the short * dead-reckoning history (chronological), render immediately, then @@ -547,69 +599,13 @@ export function createTracking({ }); } flightState._trail?.setVisible(!flightState._cockpitContactMode); - // Live head segment: last DISPLAYED body point → current dead-reckoned icon, updated - // every frame via a CallbackProperty (Cesium updates entity-polyline positions cheaply, - // unlike the trail primitive which fully rebuilds on setPositions). Keeps the head glued - // to the 12 Hz icon instead of lagging ~1 s behind it. - if (!flightState._trailHeadEntity && flightState._viewer) { - flightState._trailHeadEntity = flightState._viewer.entities.add({ - // 'gev-trail' namespace (round 6): claimed by trailRenderer's pick - // owner so a click on the head segment never reads as empty space. - id: `gev-trail:mil-head-${++flightState._trailHeadSeq}`, - show: !flightState._cockpitContactMode, - polyline: { - positions: new Cesium.CallbackProperty(() => { - // Need ≥2 accumulated points: the body draws all-but-newest, so the head must - // start at the last DISPLAYED body point (index n−2). With a single fix that - // point would be the sole raw fix — ~now, AHEAD of the delayed icon — so the - // segment would draw IN FRONT of the plane. Likewise during warm-up the icon - // predates all real history, so there is no valid body point behind it. - if ( - !flightState._trackedIcao || - flightState._trailPositions.length < 2 || - parts.motion._isTrackWarmingUp() - ) - return []; - const head = - parts.motion._trackedTrailCached() || - parts.motion._trackedDisplayPosition(flightState._trackedIcao); - if (!head) return []; - // body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a - // backward/reversing segment. - const start = - flightState._trailPositions[ - flightState._trailPositions.length - 2 - ]; - // 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)); - // 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 - // START is what slides, from nothing on a parked contact out to the - // whole segment once it has cleared its own envelope. Measured against - // the FLOORED endpoint, which is the one actually drawn. - // See trailHeadStart. - const from = trailHeadStart( - start, - end, - parts.motion._trackedModelCenterWorld(), - parts.motion._trackedModelEnvelopeM(), - flightState._scratchTrailHead, - ); - if (!from) return []; - return [from, end]; - }, false), - width: 2.5, - material: Cesium.Color.fromCssColorString(TRAIL_COLOR).withAlpha(0.9), - // Round 4: the head must never vanish into the mesh either (dimmed - // when occluded so depth still reads). - depthFailMaterial: - Cesium.Color.fromCssColorString(TRAIL_COLOR).withAlpha(0.45), - arcType: Cesium.ArcType.GEODESIC, // round 8: consistent with the trail body (no chords) - }, - }); + // Live head segment: last displayed body point → current dead-reckoned icon, drawn + // again each frame before it draws, so it stays glued to the 12 Hz icon instead of + // lagging ~1 s behind it. Only the head line is rebuilt; the body rebuilds on a real + // fix (poll cadence). Dimmed where occluded (round 4), geodesic as the body (round 8). + if (!flightState._trailHeadOff && flightState._viewer) { + flightState._trailHeadOff = + findFrame(flightState._viewer)?.on('preRender', _drawTrailHead) ?? null; } _refreshTrailDisplay(); @@ -736,18 +732,8 @@ export function createTracking({ flightState._trailBackfillToken += 1; flightState._trailPositions = []; if (flightState._trail) flightState._trail.clear(); - if ( - flightState._trailHeadEntity && - flightState._viewer && - !flightState._viewer.isDestroyed() - ) { - try { - flightState._viewer.entities.remove(flightState._trailHeadEntity); - } catch { - /* already gone */ - } - } - flightState._trailHeadEntity = null; + flightState._trailHeadOff?.(); + flightState._trailHeadOff = null; } /** diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 04ad76f12..a90c083f7 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -135,6 +135,12 @@ const ANCHORS = { top: Cesium.VerticalOrigin.TOP, }; +/** The longest straight step of a geodesic line, metres: a degree of arc. */ +const GEODESIC_STEP_M = + Cesium.Ellipsoid.WGS84.maximumRadius * Cesium.Math.RADIANS_PER_DEGREE; +/** The fewest straight steps a geodesic line is drawn in. */ +const GEODESIC_LINE_STEPS = 64; + /** The `flow` line material's type. */ const FLOW_MATERIAL = 'DrawFlowLine'; @@ -1175,8 +1181,15 @@ export function createCesiumDraw({ const a = Cesium.Cartographic.fromCartesian(points[i]); const b = Cesium.Cartographic.fromCartesian(points[i + 1]); const geodesic = new Cesium.EllipsoidGeodesic(a, b); - for (let k = 0; k < 64; k++) { - const s = k / 64; + // At least a step a degree of arc, as Cesium's own geodesic + // polylines are cut, and 64 steps over the whole line: a long trail + // of short legs stays as light as its positions. + const steps = Math.max( + Math.ceil((geodesic.surfaceDistance || 0) / GEODESIC_STEP_M), + Math.ceil(GEODESIC_LINE_STEPS / (points.length - 1)), + ); + for (let k = 0; k < steps; k++) { + const s = k / steps; const at = geodesic.interpolateUsingFraction(s); dense.push( Cesium.Cartesian3.fromRadians( diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index a4c5cf108..c5dd8ec97 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -2787,7 +2787,7 @@ test('the local ADS-B layer draws its aircraft, 978 MHz rings and trail head on removeEntityContextsForLayer: noop, }, picking: { registerPickOwner: noop, unregisterPickOwner: noop }, - trails: { createTrail: () => ({ setPositions: noop, destroy: noop }) }, + trails: await import('../../data/trailRenderer.js'), }, now: () => clock.now, }); @@ -2821,9 +2821,10 @@ test('the local ADS-B layer draws its aircraft, 978 MHz rings and trail head on assert.equal(ring.outlineWidth, 1.5); assert.equal(ring.color.alpha, 0); assert.equal(ring.distanceDisplayCondition.far, 2_000_000); - // Selected at its fix, the head has no length yet. - const head = hostOf(':trail-head'); - assert.equal(head.get(1).length, 0); + // Selected at its fix, the trail and its head have no length yet. + const trailHost = () => + scene.added.find((host) => host.drawSetId?.startsWith('trail:')); + assert.equal(trailHost(), undefined); // A frame flies them on, in place. const before = toLonLatH(icon.position).lat; @@ -2834,12 +2835,11 @@ test('the local ADS-B layer draws its aircraft, 978 MHz rings and trail head on assert.equal(rings.get(0).id.id, 'local-adsb:a1b2c3'); // The head now runs from the fix to the aircraft, dimmed, not hidden, // behind the surface. - assert.equal(hostOf(':trail-head'), head, 'the same lines'); - const deep = head.get(1); + const deep = trailHost().get(1); assert.equal(deep.length, 1); const line = deep.get(0); assert.ok(line instanceof Cesium.Primitive); - assert.match(line.geometryInstances.id.id, /^gev-trail:local-adsb-head-/); + assert.match(line.geometryInstances.id.id, /^gev-trail:\d+:head$/); const fail = line.depthFailAppearance.material.uniforms.color; assert.ok( fail.equals(Cesium.Color.fromCssColorString('#ff4fd8').withAlpha(0.45)), @@ -3281,3 +3281,72 @@ test('a draped line moved while its set rebuilds is no longer drawn where it was set.dispose(); }), )); + +test('a contact trail draws its history and moving head as depth-fail geodesic lines on a viewer of its own', async () => { + const { createTrail } = await import('../../data/trailRenderer.js'); + withImageClasses(() => { + const scene = fakeScene(); + const viewer = { scene, isDestroyed: () => false }; + const trail = createTrail(viewer, { color: '#00d4ff', width: 2.5 }); + // 400 fixes about a kilometre apart: a degree of arc per step keeps + // each leg one straight piece. + const fixes = Array.from({ length: 400 }, (_, i) => + Cesium.Cartesian3.fromDegrees(-97 + i * 0.01, 30, 10000), + ); + trail.setPositions(fixes); + const host = scene.added[0]; + const deep = host.get(1); + const body = deep.get(0); + assert.ok(body instanceof Cesium.Primitive); + assert.equal(body.geometryInstances.geometry._positions.length, 400); + assert.ok( + Cesium.Color.equals( + body.depthFailAppearance.material.uniforms.color, + Cesium.Color.fromCssColorString('#00d4ff').withAlpha(0.4), + ), + ); + // A long leg follows the globe instead of chording through it. + trail.setPositions([ + Cesium.Cartesian3.fromDegrees(-150, 20, 10000), + Cesium.Cartesian3.fromDegrees(-120, 30, 10000), + ]); + const long = deep.get(0); + const arc = long.geometryInstances.geometry._positions; + assert.equal(arc.length, 65, 'a lone leg in 64 steps'); + // A long leg among short ones still takes a step a degree. + trail.setPositions([ + ...fixes, + Cesium.Cartesian3.fromDegrees(-63, 30, 10000), + ]); + const mixed = deep.get(0).geometryInstances.geometry._positions; + assert.ok(mixed.length > 400 + 25 && mixed.length < 400 + 40, `${mixed.length}`); + // The head moves every frame alone, under one pick id. + const head = (lon) => [ + Cesium.Cartesian3.fromDegrees(-120, 30, 10000), + Cesium.Cartesian3.fromDegrees(lon, 30, 10000), + ]; + // Its first head is a new line: the set is built again, once. + trail.setHead(head(-119.99)); + const host2 = scene.added[0]; + const deep2 = host2.get(1); + assert.equal(deep2.length, 2); + const first = deep2.get(1); + const id = first.geometryInstances.id; + assert.match(id.id, /^gev-trail:\d+:head$/); + const history = deep2.get(0); + trail.setHead(head(-119.98)); + assert.equal(scene.added[0], host2, 'the set is not rebuilt'); + assert.equal(deep2.get(0), history, 'the history is not rebuilt'); + assert.notEqual(deep2.get(1), first); + assert.equal(deep2.get(1).geometryInstances.id, id); + // No head for a while: hidden in place. + trail.setHead(null); + assert.equal(scene.added[0], host2); + assert.equal(deep2.get(0), history); + assert.equal(deep2.get(1).show, false); + trail.setVisible(false); + assert.equal(host2.show, false); + trail.destroy(); + assert.equal(scene.added.length, 0); + }); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index c386112a5..6244f9e9a 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -25,7 +25,6 @@ "src/data/modelRecord.js", "src/data/modelVisualAnchor.js", "src/data/motionModel.js", - "src/data/trailRenderer.js", "src/input/dispatcher.js", "src/input/sensorPick.js", "src/layers/cctv/projection.js",