Move Cockpit onto the camera and frame ports

Cockpit now places its eye with the geo maths and moves the camera
through the camera port on the frame port's preUpdate, so cockpitCamera.js
and cockpitController.js no longer load Cesium and leave the allow-list.
Whether the aircraft still draws comes from a trackedEntityDrawn service,
which the application shell answers from the viewer's entities. The mesh
floor probe accepts the viewer as well as its scene.
This commit is contained in:
Sameh Khamis committed 2026-11-07 16:12:43 -08:00
1 parent b47aa5f3de
commit 2a9a2d5be8
11 files changed
+433 -159

No files matched your search

-2
View File
@@ -72,7 +72,5 @@
"src/services/meshFloorSampler.js",
"src/sky/starrySky.js",
"src/ui/applicationShell.js",
"src/ui/cockpitCamera.js",
"src/ui/cockpitController.js",
"src/ui/shareFollow.js"
]
+4
View File
@@ -100,6 +100,10 @@ const DRAW_FROM_CALLER = new Set([
* `./render/cesium/unbound`.
*/
const CAMERA_FROM_CALLER = new Set([
// Not wholly Cesium-free (its pointer input still is), but it loads no
// factory: Cockpit moves the camera on the frame port's preUpdate, and
// `frameOf` throws, naming the export, until the caller has loaded it.
'./ui/cockpit',
'./ui/navigation',
'./voice/commands',
'./voice/controller',
+4 -2
View File
@@ -87,7 +87,8 @@ export function createMeshFloorSampler({
* layer poll (never per contact, never per frame). Synchronous — Cesium's
* sampleHeight is a CPU-side query against loaded tiles.
*
* @param {Cesium.Scene|undefined} scene - The scene (skipped when absent/torn down).
* @param {Cesium.Scene|object|undefined} host - The scene, or the viewer
* whose scene it is (skipped when absent/torn down).
* @param {Array<{lat: number, lon: number}>} points - Contact/waypoint coords.
* @param {object} [options]
* @param {Array<object>} [options.excludeObjects] - Own billboards/models to
@@ -97,10 +98,11 @@ export function createMeshFloorSampler({
* Viewer subpoint (computed once by the caller's poll).
*/
function sampleMeshFloorCells(
scene,
host,
points,
{ excludeObjects = [], viewerLat, viewerLon } = {},
) {
const scene = host?.scene ?? host;
if (!meshFloorPreferred()) return;
// Without depth-texture support every probe throws: nothing to latch.
if (!scene || !heightsFor(scene).supported().surface) return;
+6 -2
View File
@@ -33,8 +33,9 @@ import {
import { toDegrees, toRadians } from '../geo/index.js';
import { cameraOf, findCamera } from '../render/cesium/camera.js';
// Loads the effects factory, so visual settings on a viewer with no renderer
// bound still get an effects port. Loading the camera and effects factories
// is all that keeps this module on the Cesium allow-list.
// bound still get an effects port. Loading the camera and effects factories,
// and asking the viewer's entities whether Cockpit's aircraft still draws,
// keep this module on the Cesium allow-list.
import '../render/cesium/effects.js';
import { aircraftTrackingTarget } from '../cockpitTracking.js';
@@ -376,6 +377,9 @@ export class StyleManager extends ShellFacade {
meshFloorPreferred: services.meshFloorPreferred,
warmGroundFloor: services.warmGroundFloor,
sampleMeshFloorCells: services.sampleMeshFloorCells,
// Whether the aircraft entity Cockpit flies still draws: the flight
// layers draw it as an entity of the viewer's own.
trackedEntityDrawn: (entity) => viewer.entities.contains(entity),
holdContinuousRender: services.holdContinuousRender,
releaseContinuousRender: services.releaseContinuousRender,
fetchRegionalBrief: services.fetchRegionalBrief,
+90 -133
View File
@@ -1,6 +1,22 @@
/** Camera placement, ground acquisition and motion correction for the Cockpit controller. */
import * as Cesium from 'cesium';
import { cameraOf } from '../render/cesium/camera.js';
import { cameraOf, findFrame } from '../render/rendererOf.js';
import { followedPosition } from '../data/followed.js';
import { trackedEntityDrawn } from './cockpitTrackingController.js';
import {
add,
clone,
eastNorthUp,
frameVector,
fromRadians,
magnitude,
normalize,
scale,
sub,
toCartographicRadians,
toDegrees,
toRadians,
vec,
} from '../geo/index.js';
import {
cockpitAnchorCorrectionStep,
cockpitGroundSafeHeight,
@@ -20,6 +36,17 @@ import {
COCKPIT_GROUND_WAIT_TIMEOUT_MS,
} from './cockpitPresentation.js';
/**
* Where the aircraft Cockpit flies is now: its follow target's position at
* scene time (what the drawn entity's position reads), or, for a target
* with none, where it is shown.
*/
function trackedPositionNow(viewer, followed) {
if (typeof followed?.position === 'function')
return followed.position(findFrame(viewer)?.time() ?? Date.now());
return followedPosition(viewer, followed);
}
export function update() {
if (this.destroyed) return false;
if (!this.active) {
@@ -46,7 +73,7 @@ export function update() {
if (
!info ||
!this.trackedEntity ||
!this.viewer.entities.contains(this.trackedEntity)
!trackedEntityDrawn.call(this, this.trackedEntity)
) {
if (nowMs < this.contextNavigationDeadlineMs) return;
this.exit({ restoreTracking: false });
@@ -62,10 +89,7 @@ export function update() {
return;
this.lastCameraUpdateMs = nowMs;
const target = this.trackedEntity.position.getValue(
this.viewer.clock.currentTime,
this.scratchTarget,
);
const target = trackedPositionNow(this.viewer, this.trackedFollow);
if (!target) return;
const dtSec = Math.min(0.1, Math.max(0, (nowMs - this.lastFrameMs) / 1000));
this.lastFrameMs = nowMs;
@@ -78,7 +102,7 @@ export function update() {
}
if (!this.cockpitAnchorValid) {
Cesium.Cartesian3.clone(target, this.cockpitAnchor);
this.cockpitAnchor = clone(target);
this.cockpitAnchorValid = true;
}
@@ -89,8 +113,8 @@ export function update() {
// display position at a bounded rate. This preserves the layer's required
// 15/30-second interpolation and per-frame cache without exposing its
// sample-boundary corrections to the camera.
const headingRad = Cesium.Math.toRadians(this.heading ?? 0);
const pitchRad = Cesium.Math.toRadians(COCKPIT_VIEW_PITCH_DEG);
const headingRad = toRadians(this.heading ?? 0);
const pitchRad = toRadians(COCKPIT_VIEW_PITCH_DEG);
const speedMps = Number.isFinite(info.velocityMps)
? Math.max(0, info.velocityMps)
: 0;
@@ -99,55 +123,29 @@ export function update() {
// A feed backoff has no authoritative velocity epoch to advance from.
// Hold the cockpit on the exact layer-rendered position so the camera
// cannot coast away while the icon correctly remains fixed.
Cesium.Cartesian3.clone(target, this.cockpitAnchor);
this.cockpitAnchor = clone(target);
} else {
Cesium.Transforms.eastNorthUpToFixedFrame(
const horizontal = normalize(
frameVector(
eastNorthUp(this.cockpitAnchor),
vec(Math.sin(headingRad), Math.cos(headingRad), 0),
),
);
this.cockpitAnchor = add(
this.cockpitAnchor,
Cesium.Ellipsoid.WGS84,
this.scratchEnu,
);
this.scratchLocal.x = Math.sin(headingRad);
this.scratchLocal.y = Math.cos(headingRad);
this.scratchLocal.z = 0;
Cesium.Matrix4.multiplyByPointAsVector(
this.scratchEnu,
this.scratchLocal,
this.scratchHorizontal,
);
Cesium.Cartesian3.normalize(this.scratchHorizontal, this.scratchHorizontal);
Cesium.Cartesian3.multiplyByScalar(
this.scratchHorizontal,
speedMps * dtSec,
this.scratchAdvance,
);
Cesium.Cartesian3.add(
this.cockpitAnchor,
this.scratchAdvance,
this.cockpitAnchor,
);
Cesium.Cartesian3.subtract(
target,
this.cockpitAnchor,
this.scratchCorrection,
);
const correctionDistanceM = Cesium.Cartesian3.magnitude(
this.scratchCorrection,
scale(horizontal, speedMps * dtSec),
);
const correction = sub(target, this.cockpitAnchor);
const correctionDistanceM = magnitude(correction);
const correctionStepM = cockpitAnchorCorrectionStep(
correctionDistanceM,
speedMps,
dtSec,
);
if (correctionStepM > 0 && correctionDistanceM > 0) {
Cesium.Cartesian3.multiplyByScalar(
this.scratchCorrection,
correctionStepM / correctionDistanceM,
this.scratchCorrection,
);
Cesium.Cartesian3.add(
this.cockpitAnchor,
this.scratchCorrection,
this.cockpitAnchor = add(
this.cockpitAnchor,
scale(correction, correctionStepM / correctionDistanceM),
);
}
}
@@ -157,16 +155,8 @@ export function update() {
// between fixes. Clamp it against the same mesh-first shared floor used by
// aircraft rendering. For a slow contact whose floor cell is still cold,
// its already-clamped render position is a conservative temporary floor.
const anchorCartographic = Cesium.Cartographic.fromCartesian(
this.cockpitAnchor,
Cesium.Ellipsoid.WGS84,
this.scratchAnchorCartographic,
);
const targetCartographic = Cesium.Cartographic.fromCartesian(
target,
Cesium.Ellipsoid.WGS84,
this.scratchTargetCartographic,
);
const anchorCartographic = toCartographicRadians(this.cockpitAnchor);
const targetCartographic = toCartographicRadians(target);
let cockpitFloorM = this.services.cachedGroundFloor(
info.latitude,
info.longitude,
@@ -187,11 +177,11 @@ export function update() {
)
) {
this.lastGroundProbeMs = nowMs;
const viewerCartographic = this.viewer.camera.positionCartographic;
this.services.sampleMeshFloorCells(this.viewer.scene, groundPoint, {
const eye = cameraOf(this.viewer).pose();
this.services.sampleMeshFloorCells(this.viewer, groundPoint, {
excludeObjects: [this.trackedEntity],
viewerLat: Cesium.Math.toDegrees(viewerCartographic.latitude),
viewerLon: Cesium.Math.toDegrees(viewerCartographic.longitude),
viewerLat: eye.lat,
viewerLon: eye.lon,
});
}
cockpitFloorM = this.services.cachedMeshFloor(
@@ -252,83 +242,50 @@ export function update() {
COCKPIT_MIN_GROUND_CLEARANCE_M - COCKPIT_UP_OFFSET_M,
);
if (minimumAnchorHeightM !== anchorCartographic.height) {
anchorCartographic.height = minimumAnchorHeightM;
Cesium.Ellipsoid.WGS84.cartographicToCartesian(
anchorCartographic,
this.cockpitAnchor,
this.cockpitAnchor = fromRadians(
anchorCartographic.lon,
anchorCartographic.lat,
minimumAnchorHeightM,
);
}
}
// Rebuild the local frame at the stabilized anchor after advancing it.
Cesium.Transforms.eastNorthUpToFixedFrame(
this.cockpitAnchor,
Cesium.Ellipsoid.WGS84,
this.scratchEnu,
const enu = eastNorthUp(this.cockpitAnchor);
const horizontal = normalize(
frameVector(enu, vec(Math.sin(headingRad), Math.cos(headingRad), 0)),
);
this.scratchLocal.x = Math.sin(headingRad);
this.scratchLocal.y = Math.cos(headingRad);
this.scratchLocal.z = 0;
Cesium.Matrix4.multiplyByPointAsVector(
this.scratchEnu,
this.scratchLocal,
this.scratchHorizontal,
const forward = normalize(
frameVector(
enu,
vec(
Math.sin(headingRad) * Math.cos(pitchRad),
Math.cos(headingRad) * Math.cos(pitchRad),
Math.sin(pitchRad),
),
),
);
Cesium.Cartesian3.normalize(this.scratchHorizontal, this.scratchHorizontal);
this.scratchLocal.x = Math.sin(headingRad) * Math.cos(pitchRad);
this.scratchLocal.y = Math.cos(headingRad) * Math.cos(pitchRad);
this.scratchLocal.z = Math.sin(pitchRad);
Cesium.Matrix4.multiplyByPointAsVector(
this.scratchEnu,
this.scratchLocal,
this.scratchForward,
const up = normalize(
frameVector(
enu,
vec(
-Math.sin(headingRad) * Math.sin(pitchRad),
-Math.cos(headingRad) * Math.sin(pitchRad),
Math.cos(pitchRad),
),
),
);
Cesium.Cartesian3.normalize(this.scratchForward, this.scratchForward);
this.scratchLocal.x = -Math.sin(headingRad) * Math.sin(pitchRad);
this.scratchLocal.y = -Math.cos(headingRad) * Math.sin(pitchRad);
this.scratchLocal.z = Math.cos(pitchRad);
Cesium.Matrix4.multiplyByPointAsVector(
this.scratchEnu,
this.scratchLocal,
this.scratchUp,
);
Cesium.Cartesian3.normalize(this.scratchUp, this.scratchUp);
Cesium.Cartesian3.multiplyByScalar(
this.scratchHorizontal,
COCKPIT_FORWARD_OFFSET_M,
this.scratchCamera,
);
Cesium.Cartesian3.add(
this.cockpitAnchor,
this.scratchCamera,
this.scratchCamera,
);
Cesium.Matrix4.getTranslation(this.scratchEnu, this.scratchTarget);
Cesium.Cartesian3.normalize(this.scratchTarget, this.scratchTarget);
Cesium.Cartesian3.multiplyByScalar(
this.scratchTarget,
COCKPIT_UP_OFFSET_M,
this.scratchTarget,
);
Cesium.Cartesian3.add(
this.scratchCamera,
this.scratchTarget,
this.scratchCamera,
let eye = add(
add(this.cockpitAnchor, scale(horizontal, COCKPIT_FORWARD_OFFSET_M)),
scale(normalize(enu.origin), COCKPIT_UP_OFFSET_M),
);
// Recheck at the final forward-offset camera coordinate because a taxiing
// aircraft can cross into an adjacent coarse floor cell between updates.
const cameraCartographic = Cesium.Cartographic.fromCartesian(
this.scratchCamera,
Cesium.Ellipsoid.WGS84,
this.scratchCameraCartographic,
);
const cameraCartographic = toCartographicRadians(eye);
if (cameraCartographic) {
const cameraLat = Cesium.Math.toDegrees(cameraCartographic.latitude);
const cameraLon = Cesium.Math.toDegrees(cameraCartographic.longitude);
const cameraLat = toDegrees(cameraCartographic.lat);
const cameraLon = toDegrees(cameraCartographic.lon);
const cameraFloorM = this.services.cachedGroundFloor(cameraLat, cameraLon);
if (Number.isFinite(cameraFloorM)) {
cockpitFloorM = Math.max(
@@ -342,17 +299,17 @@ export function update() {
COCKPIT_MIN_GROUND_CLEARANCE_M,
);
if (safeHeightM !== cameraCartographic.height) {
cameraCartographic.height = safeHeightM;
Cesium.Ellipsoid.WGS84.cartographicToCartesian(
cameraCartographic,
this.scratchCamera,
eye = fromRadians(
cameraCartographic.lon,
cameraCartographic.lat,
safeHeightM,
);
}
}
cameraOf(this.viewer).setView({
destination: this.scratchCamera,
orientation: { direction: this.scratchForward, up: this.scratchUp },
destination: eye,
orientation: { direction: forward, up },
});
if (cockpitUiUpdateDue(nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS)) {
this.lastHudUpdateMs = nowMs;
+6 -15
View File
@@ -1,5 +1,6 @@
/** Coordinate Cockpit lifecycle through supplied aircraft, terrain, rendering and briefing operations. */
import { onFollowChanged } from '../data/followed.js';
import { frameOf } from '../render/rendererOf.js';
import {
readAircraftInfo,
dispatchCockpitModeChanged,
@@ -62,7 +63,6 @@ import {
syncSignalLayout,
} from './cockpitLayout.js';
import { onKeyDown } from './cockpitInput.js';
import * as Cesium from 'cesium';
export class CockpitViewController {
constructor(
@@ -80,6 +80,8 @@ export class CockpitViewController {
publish = {},
} = {},
) {
// Before anything subscribes: a viewer with no frame port throws here.
const frame = frameOf(viewer);
this.viewer = viewer;
this.services = services;
this.destroyed = false;
@@ -183,27 +185,16 @@ export class CockpitViewController {
this.regionalBriefSubjectId = null;
this.contextLayoutFrame = null;
this.contextLayoutStamp = null;
this.scratchTarget = new Cesium.Cartesian3();
this.cockpitAnchor = new Cesium.Cartesian3();
/** Where the Cockpit eye is carried from, as ECEF; see cockpitCamera.js. */
this.cockpitAnchor = null;
this.cockpitAnchorValid = false;
this.scratchCamera = new Cesium.Cartesian3();
this.scratchAdvance = new Cesium.Cartesian3();
this.scratchCorrection = new Cesium.Cartesian3();
this.scratchForward = new Cesium.Cartesian3();
this.scratchHorizontal = new Cesium.Cartesian3();
this.scratchUp = new Cesium.Cartesian3();
this.scratchLocal = new Cesium.Cartesian3();
this.scratchEnu = new Cesium.Matrix4();
this.scratchAnchorCartographic = new Cesium.Cartographic();
this.scratchCameraCartographic = new Cesium.Cartographic();
this.scratchTargetCartographic = new Cesium.Cartographic();
this._listenerRemovers = [onLocaleChange(() => this.relocalize())];
// Camera mutations belong before scene update/culling. Changing the camera
// from preRender makes 3D Tiles discover a new view after traversal and can
// create a self-sustaining refinement loop under a moving cockpit camera.
this._listenerRemovers.push(
viewer.scene.preUpdate.addEventListener(() => this.update()),
frame.on('preUpdate', () => this.update()),
onFollowChanged(viewer, () => {
if (this.active) this._adoptTrackedEntity(performance.now());
else this.syncEntry();
+298
View File
@@ -3,6 +3,17 @@ import assert from 'node:assert/strict';
import { CockpitViewController } from './cockpitController.js';
import { withEntityRecord } from '../data/entityRecords.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import {
cockpitAnchorCorrectionStep,
cockpitGroundSafeHeight,
} from '../cockpitMath.js';
import {
COCKPIT_FORWARD_OFFSET_M,
COCKPIT_MIN_GROUND_CLEARANCE_M,
COCKPIT_UP_OFFSET_M,
COCKPIT_VIEW_PITCH_DEG,
} from './cockpitPresentation.js';
function environment() {
const original = { document: globalThis.document, window: globalThis.window };
@@ -29,6 +40,13 @@ function environment() {
trackedEntityChanged: event,
entities: { contains: () => false },
};
// The renderer's frame port: Cockpit moves the camera on its preUpdate.
bindRenderer(viewer, {
frame: {
on: (phase, fn) =>
phase === 'preUpdate' ? event.addEventListener(fn) : () => {},
},
});
return {
viewer,
callbacks,
@@ -259,3 +277,283 @@ test('the weather toggle flips from its own state, however fast it is pressed',
env.restore();
}
});
/**
* The Cockpit eye as cockpitCamera.js computed it with Cesium's own maths,
* for one update: the anchor advanced along the heading and pulled toward
* the target (held on it when stale), lifted to the floor, then the eye
* set forward and up from it and lifted again.
*/
function cesiumCockpitEye(
Cesium,
{ target, anchor, info, heading, dtSec, floorM, liftM },
) {
const { Cartesian3, Matrix4, Transforms, Cartographic, Ellipsoid } = Cesium;
const h = Cesium.Math.toRadians(heading);
const p = Cesium.Math.toRadians(COCKPIT_VIEW_PITCH_DEG);
const speed = Math.max(0, info.velocityMps);
const along = (origin, x, y, z) =>
Cartesian3.normalize(
Matrix4.multiplyByPointAsVector(
Transforms.eastNorthUpToFixedFrame(origin, Ellipsoid.WGS84),
new Cartesian3(x, y, z),
new Cartesian3(),
),
new Cartesian3(),
);
let a = Cartesian3.clone(anchor ?? target);
if (info.stale) a = Cartesian3.clone(target);
else {
const horizontal = along(a, Math.sin(h), Math.cos(h), 0);
a = Cartesian3.add(
a,
Cartesian3.multiplyByScalar(horizontal, speed * dtSec, new Cartesian3()),
new Cartesian3(),
);
const correction = Cartesian3.subtract(target, a, new Cartesian3());
const distance = Cartesian3.magnitude(correction);
const step = cockpitAnchorCorrectionStep(distance, speed, dtSec);
if (step > 0 && distance > 0)
a = Cartesian3.add(
a,
Cartesian3.multiplyByScalar(
correction,
step / distance,
new Cartesian3(),
),
new Cartesian3(),
);
}
const anchorCarto = Cartographic.fromCartesian(a);
let floor = floorM;
const targetCarto = Cartographic.fromCartesian(target);
if (!Number.isFinite(floor) && speed < 90) floor = targetCarto.height - liftM;
if (Number.isFinite(floor)) {
const minimum = cockpitGroundSafeHeight(
anchorCarto.height,
floor,
COCKPIT_MIN_GROUND_CLEARANCE_M - COCKPIT_UP_OFFSET_M,
);
if (minimum !== anchorCarto.height) {
anchorCarto.height = minimum;
a = Ellipsoid.WGS84.cartographicToCartesian(anchorCarto);
}
}
const horizontal = along(a, Math.sin(h), Math.cos(h), 0);
const forward = along(
a,
Math.sin(h) * Math.cos(p),
Math.cos(h) * Math.cos(p),
Math.sin(p),
);
const up = along(
a,
-Math.sin(h) * Math.sin(p),
-Math.cos(h) * Math.sin(p),
Math.cos(p),
);
let eye = Cartesian3.add(
Cartesian3.add(
a,
Cartesian3.multiplyByScalar(
horizontal,
COCKPIT_FORWARD_OFFSET_M,
new Cartesian3(),
),
new Cartesian3(),
),
Cartesian3.multiplyByScalar(
Cartesian3.normalize(a, new Cartesian3()),
COCKPIT_UP_OFFSET_M,
new Cartesian3(),
),
new Cartesian3(),
);
const eyeCarto = Cartographic.fromCartesian(eye);
const safe = cockpitGroundSafeHeight(
eyeCarto.height,
floor,
COCKPIT_MIN_GROUND_CLEARANCE_M,
);
if (safe !== eyeCarto.height) {
eyeCarto.height = safe;
eye = Ellipsoid.WGS84.cartographicToCartesian(eyeCarto);
}
return { eye, forward, up, anchor: a };
}
/** A Cockpit flying `info` over `target`, its camera writes in `views`. */
function cockpitOver({ info, target, services = {} }) {
const views = [];
const viewer = {
trackedEntityChanged: { addEventListener: () => () => {} },
};
bindRenderer(viewer, {
frame: { on: () => () => {}, time: () => 0 },
camera: {
followed: null,
on: () => () => {},
pose: () => ({ lat: 30.2, lon: -97.7 }),
setView: (view) => views.push(view),
},
});
const owner = new CockpitViewController(viewer, {
services: {
flightsLayer: { getTrackedInfo: () => info },
militaryFlightsLayer: {},
cachedGroundFloor: () => null,
trackedEntityDrawn: () => true,
releaseContinuousRender() {},
...services,
},
});
owner.updateHud = () => {};
owner.active = true;
owner.heading = info.track;
owner.trackedEntity = {};
owner.trackedFollow = { key: 'flights:abc123', position: () => target };
return { owner, viewer, views };
}
const near = (a, b, eps, what) =>
assert.ok(
Math.abs(a.x - b.x) <= eps &&
Math.abs(a.y - b.y) <= eps &&
Math.abs(a.z - b.z) <= eps,
`${what}: ${JSON.stringify(a)} vs ${JSON.stringify(b)}`,
);
test('Cockpit places the eye at its aircraft as the Cesium maths did', async () => {
const Cesium = await import('cesium');
const env = environment();
const realNow = performance.now;
try {
const target = Cesium.Cartesian3.fromDegrees(-97.67, 30.19, 1200);
const info = {
icao24: 'abc123',
layerId: 'flights',
track: 72,
velocityMps: 200,
latitude: 30.19,
longitude: -97.67,
onGround: false,
stale: true,
};
const { owner, views } = cockpitOver({ info, target });
// Held on the target while the feed is stale.
owner.update();
let expected = cesiumCockpitEye(Cesium, {
target,
info,
heading: 72,
dtSec: 0,
liftM: 0,
});
near(views[0].destination, expected.eye, 1e-6, 'stale eye');
near(views[0].orientation.direction, expected.forward, 1e-12, 'direction');
near(views[0].orientation.up, expected.up, 1e-12, 'up');
// Live: the anchor coasts 80 ms along the heading and is pulled toward
// where the layer now shows the aircraft.
info.stale = false;
const anchor = Cesium.Cartesian3.clone(expected.anchor);
const moved = Cesium.Cartesian3.fromDegrees(-97.6698, 30.1901, 1210);
owner.trackedFollow.position = () => moved;
let now = owner.lastFrameMs + 80;
performance.now = () => now;
owner.update();
expected = cesiumCockpitEye(Cesium, {
target: moved,
anchor,
info,
heading: 72,
dtSec: 0.08,
liftM: 0,
});
assert.equal(views.length, 2);
near(views[1].destination, expected.eye, 1e-6, 'live eye');
near(views[1].orientation.direction, expected.forward, 1e-12, 'direction');
near(views[1].orientation.up, expected.up, 1e-12, 'up');
// An aircraft its layer no longer draws ends Cockpit.
owner.services.trackedEntityDrawn = () => false;
now += 80;
owner.update();
assert.equal(owner.active, false);
assert.equal(views.length, 2);
owner.dispose();
} finally {
performance.now = realNow;
env.restore();
}
});
test('a grounded Cockpit probes the mesh from the camera and keeps the eye above the floor', async () => {
const Cesium = await import('cesium');
const env = environment();
try {
// Reported below the apron: the floor lifts the anchor and the eye.
const target = Cesium.Cartesian3.fromDegrees(-97.67, 30.19, 120);
const info = {
icao24: 'abc123',
layerId: 'flights',
track: 300,
velocityMps: 0,
latitude: 30.19,
longitude: -97.67,
onGround: true,
stale: true,
};
const probes = [];
const { owner, viewer, views } = cockpitOver({
info,
target,
services: {
cachedGroundFloor: () => 140,
warmGroundFloor() {},
cachedMeshFloor: () => null,
meshFloorPreferred: () => true,
sampleMeshFloorCells: (...args) => probes.push(args),
GROUND_FLOOR_LIFT_M: 0,
},
});
// The surface wait is over: Cockpit flies on the ground floor.
owner.surfaceWaitStartedMs = -1e9;
owner.update();
assert.equal(probes.length, 1);
const [host, points, options] = probes[0];
assert.equal(host, viewer);
assert.deepEqual(points, [{ lat: 30.19, lon: -97.67 }]);
assert.deepEqual(options, {
excludeObjects: [owner.trackedEntity],
viewerLat: 30.2,
viewerLon: -97.7,
});
const expected = cesiumCockpitEye(Cesium, {
target,
info,
heading: 300,
dtSec: 0,
floorM: 140,
liftM: 0,
});
assert.equal(views.length, 1);
// The floor lifts round-trip through geodetic heights: the shared geo helpers' and
// Cesium's agree to well under a millimetre there.
near(views[0].destination, expected.eye, 1e-4, 'eye');
const height = Cesium.Cartographic.fromCartesian(
new Cesium.Cartesian3(
views[0].destination.x,
views[0].destination.y,
views[0].destination.z,
),
).height;
assert.ok(
height >= 140 + COCKPIT_MIN_GROUND_CLEARANCE_M - 1e-6,
`${height}`,
);
owner.dispose();
} finally {
env.restore();
}
});
+2
View File
@@ -48,6 +48,7 @@ export class CockpitCoordinator {
meshFloorPreferred,
warmGroundFloor,
sampleMeshFloorCells,
trackedEntityDrawn,
holdContinuousRender,
releaseContinuousRender,
fetchRegionalBrief,
@@ -69,6 +70,7 @@ export class CockpitCoordinator {
meshFloorPreferred,
warmGroundFloor,
sampleMeshFloorCells,
trackedEntityDrawn,
holdContinuousRender,
releaseContinuousRender,
fetchRegionalBrief,
+1 -1
View File
@@ -52,7 +52,7 @@ function fixture(t) {
},
trackedEntityChanged: listeners(),
};
bindFakeCesiumCamera(viewer);
bindFakeCesiumCamera(viewer, { frame: { on: () => () => {} } });
const cockpit = new CockpitViewController(viewer, {
services: {
flightsLayer: { getTrackedInfo: () => INFO, refreshTr3b() {} },
+14 -4
View File
@@ -13,6 +13,15 @@ import {
} from '../data/followed.js';
import { inputFor } from '../input/dispatcher.js';
/**
* Whether the aircraft entity Cockpit holds still draws, as its services
* say; true when they cannot say.
*/
export function trackedEntityDrawn(entity) {
const drawn = this.services.trackedEntityDrawn;
return typeof drawn === 'function' ? drawn(entity) !== false : true;
}
export function readAircraftInfo() {
// In cockpit mode the controller stops the camera following (see enter()),
// so the cockpit's own handle is the tracked identity there.
@@ -125,7 +134,7 @@ export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
return false;
const info = suppliedInfo || this.readAircraftInfo();
if (!info) return false;
if (this.trackedEntity && this.viewer.entities.contains(this.trackedEntity)) {
if (this.trackedEntity && trackedEntityDrawn.call(this, this.trackedEntity)) {
this.trackedEntity.show = this.trackedEntityWasShown;
}
this.trackedEntity = nextEntity;
@@ -253,11 +262,12 @@ export function exit({ restoreTracking = true } = {}) {
this.setVisionMode('optical');
this.releaseCameraInput?.();
this.releaseCameraInput = null;
if (entity && this.viewer.entities.contains(entity))
entity.show = this.trackedEntityWasShown;
const present = () =>
Boolean(entity) && trackedEntityDrawn.call(this, entity);
if (present()) entity.show = this.trackedEntityWasShown;
this.trackedEntityWasShown = true;
this.dispatchCockpitModeChanged(false);
if (restoreTracking && entity && this.viewer.entities.contains(entity)) {
if (restoreTracking && present()) {
resumeFollowing(this.viewer, followed);
this.restoreTrackingFrame(entity);
}