mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 01:02:23 +00:00
refactor(flights): Cesium rendering behind a renderer interface
Task 10a. The flights logic no longer imports Cesium: every Cesium object it
built moved one for one into the shared aircraft renderer
(src/layers/aircraft/render/cesium.js; contract in render/contract.js), with
the flights' parameters in src/layers/flights/render/cesium.js, registered
for 'cesium' in the renderer registry and created at init(viewer, {engine}).
- Fleet: BillboardCollection + sprite-order slot; sprites stay Billboard
handles (field vocabulary documented for the Navara renderer).
- Models: fleet/tracked/preload glTF loads (asynchronous:false, MIX tint, IR
boost as `unlit` → the UNLIT CustomShader), the model collection, setPose
(same HPR frame with airplane.glb's 180° offset).
- Tracked: the ENU billboard Entity with its position/colour/rotation
callbacks, viewFrom, followed through viewer.trackedEntity + the one exact
tracked frame (kept as is; engine.camera.follow on Cesium would also end
the follow on any camera command, a behaviour change).
- Trail: the entity trail (data/trailRenderer, unchanged: its Primitive
predecessor failed below the mesh) and the live head segment.
- View: camera/scene reads, frame number, frustum and horizon tests,
projection, render requests, frame events, evidence render-loop hold.
- Clicks and Escape go through the engine's selection dispatcher (the
ScreenSpaceEventHandler and keydown listener are gone); the cross-layer
untrack watches the renderer's follow.
- Colours are engine-neutral Rgba (src/layers/shared/color.js), bit-equal to
the Cesium.Color constants they replace; NearFarScalar → nearFarScale.
- Cesium math in the logic → src/geo.
- check-import-directions: cesium only in render/cesium*.js and three/Navara
only in render/navara*.js for flights, aircraft and shared; a layer's
Navara renderer only through navaraMode's import().
Source-text tests updated with the moved code, same meaning:
- readLayerSource reads a layer's render/*.js and, for the aircraft layers,
aircraft/render/*.js (GLB-load, tracked-entity, CallbackProperty checks).
- modelScale.test: _normalBillboardScaleByDistance reads nearFarScale(...).
- spriteOrder.test: flights' enable calls fleet.restoreOrderOnEnable(); the
renderer wires it to restoreSpriteOrderOnEnable('flights', viewer).
- trackingClickGesture.test: the flights gesture rules are the dispatcher's
(selection gesture before select, click classifier before the empty-space
clear); flights answers the empty click with a user-origin clear.
- militaryAwareness.test: flights' hasContact guard reads fleet.visible().
- ownership.test: the services fixture names selection and renderer.
New tests: color, the Cesium aircraft renderer (contract, collections, pose,
loads, frustum/horizon, tracked entity, follow, trail head, adopted
collections), the flights logic over a plain-data renderer and a fake engine
(fleet, click-select, no-op on the tracked visual, empty-click release), the
boundary rule.
W1 replay vs 7c7422e2: counts, known objects, screen points (0 px), tracking
poses (0 m), requests and shots (same sha256) identical. Main chunk
2,890,982 B (+6.2 KB, +0.21 %: the renderer indirection).
This commit is contained in:
1 parent
8e702f0c3b
commit
7f13ef4a87
33 files changed
+1974
-748
No files matched your search
@@ -0,0 +1,420 @@
|
||||
// The aircraft renderer on Cesium (contract: ./contract.js): the Cesium
|
||||
// objects the aircraft layers used to build themselves, moved here one for
|
||||
// one — the fleet BillboardCollection and its sprite-order slot, the model
|
||||
// PrimitiveCollection and its glTF loads, the tracked Entity (billboard with
|
||||
// per-frame CallbackProperties, followed through viewer.trackedEntity and
|
||||
// the one exact tracked frame), the trail entity and its live head
|
||||
// segment, and the camera/frame reads. Nothing here decides anything: the
|
||||
// layer's logic decides, this draws.
|
||||
|
||||
import * as Cesium from 'cesium';
|
||||
import { createTrail } from '../../../data/trailRenderer.js';
|
||||
import {
|
||||
registerSpriteCollection,
|
||||
restoreSpriteOrder,
|
||||
restoreSpriteOrderOnEnable,
|
||||
} from '../../../data/spriteOrder.js';
|
||||
import { horizonOccluder } from '../../../data/iconOrientation.js';
|
||||
import { engineFromViewer } from '../../../globe/cesium/engineFromViewer.js';
|
||||
import { applyTrackedCameraFrame } from '../../../globe/cesium/follow.js';
|
||||
|
||||
// The model shader of the IR boost (owner playtest 2026-08-16): boosted
|
||||
// models render UNLIT so a side-lit airframe does not go black in FLIR/NVG.
|
||||
// Assigning a customShader to a ready model is a silent no-op, so the layer
|
||||
// reloads boosted models and the shader is set at creation. One stateless
|
||||
// instance, shared.
|
||||
let unlitShader = null;
|
||||
const irUnlitShader = () =>
|
||||
(unlitShader ??= new Cesium.CustomShader({
|
||||
lightingModel: Cesium.LightingModel.UNLIT,
|
||||
}));
|
||||
|
||||
// A colour from the layer (an Rgba or a Cesium.Color) as a Cesium.Color, for
|
||||
// the entity properties that keep what they are given. Constants convert
|
||||
// once.
|
||||
const cesiumColors = new WeakMap();
|
||||
function cesiumColor(color) {
|
||||
if (color instanceof Cesium.Color) return color;
|
||||
let converted = cesiumColors.get(color);
|
||||
if (!converted) {
|
||||
converted = new Cesium.Color(
|
||||
color.red,
|
||||
color.green,
|
||||
color.blue,
|
||||
color.alpha,
|
||||
);
|
||||
if (Object.isFrozen(color)) cesiumColors.set(color, converted);
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
|
||||
const cesiumNearFar = (scalar) =>
|
||||
scalar instanceof Cesium.NearFarScalar
|
||||
? scalar
|
||||
: new Cesium.NearFarScalar(
|
||||
scalar.near,
|
||||
scalar.nearValue,
|
||||
scalar.far,
|
||||
scalar.farValue,
|
||||
);
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {Cesium.Viewer} options.viewer
|
||||
* @param {object} [options.engine] The globe engine (default: the viewer's).
|
||||
* @param {string} options.spriteLayer The fleet's slot in data/spriteOrder.
|
||||
* @param {number} [options.headingOffsetDeg=0] Model nose vs Cesium heading 0.
|
||||
* @param {{ billboardCollection?: object, modelCollection?: object }} [options.adopt]
|
||||
* Test seam: drive existing (fake) collections instead of creating them.
|
||||
* @returns {import('./contract.js').AircraftRenderer}
|
||||
*/
|
||||
export function createAircraftCesiumRenderer({
|
||||
viewer,
|
||||
engine = null,
|
||||
spriteLayer,
|
||||
headingOffsetDeg = 0,
|
||||
adopt = null,
|
||||
}) {
|
||||
let billboards = adopt?.billboardCollection ?? null;
|
||||
let models = adopt?.modelCollection ?? null;
|
||||
const scratchHpr = new Cesium.HeadingPitchRoll(0, 0, 0);
|
||||
const scratchSphere = new Cesium.BoundingSphere(new Cesium.Cartesian3(), 1.0);
|
||||
// The frame's culling volume and one tester over it (no closure per call).
|
||||
let cullingVolume = null;
|
||||
const inFrustum = (position) => {
|
||||
Cesium.Cartesian3.clone(position, scratchSphere.center);
|
||||
return (
|
||||
cullingVolume.computeVisibility(scratchSphere) !==
|
||||
Cesium.Intersect.OUTSIDE
|
||||
);
|
||||
};
|
||||
const scratchSize = {
|
||||
width: undefined,
|
||||
height: undefined,
|
||||
scale: undefined,
|
||||
scaleByDistance: undefined,
|
||||
};
|
||||
|
||||
const scene = () => viewer?.scene;
|
||||
const camera = () => viewer?.camera;
|
||||
|
||||
const view = {
|
||||
get camera() {
|
||||
return camera();
|
||||
},
|
||||
get scene() {
|
||||
return scene();
|
||||
},
|
||||
get surfaceOwner() {
|
||||
return viewer;
|
||||
},
|
||||
get surfaceScene() {
|
||||
return viewer?.scene;
|
||||
},
|
||||
frameNumber: () => viewer?.scene?.frameState?.frameNumber ?? -1,
|
||||
viewportHeightPx: () => viewer.scene.canvas.clientHeight,
|
||||
// The tester stays valid until the next frustumTester() call.
|
||||
frustumTester() {
|
||||
const cam = viewer.camera;
|
||||
cullingVolume = cam.frustum.computeCullingVolume(
|
||||
cam.positionWC,
|
||||
cam.directionWC,
|
||||
cam.upWC,
|
||||
);
|
||||
return inFrustum;
|
||||
},
|
||||
horizon: () => horizonOccluder(viewer.camera),
|
||||
worldToWindow: (position, result) =>
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
viewer.scene,
|
||||
position,
|
||||
result,
|
||||
),
|
||||
requestRender: () => viewer?.scene?.requestRender?.(),
|
||||
on(event, listener) {
|
||||
const source =
|
||||
event === 'moveEnd'
|
||||
? viewer?.camera?.moveEnd
|
||||
: event === 'preRender'
|
||||
? viewer?.scene?.preRender
|
||||
: event === 'preUpdate'
|
||||
? viewer?.scene?.preUpdate
|
||||
: null;
|
||||
return source ? source.addEventListener(listener) : null;
|
||||
},
|
||||
isDestroyed: () => !viewer || viewer.isDestroyed?.() === true,
|
||||
// Evidence capture (qa-focus-evidence): Cesium's own render loop off,
|
||||
// then its pending-loop latch closed so manual renders start at once.
|
||||
holdFrames() {
|
||||
viewer.useDefaultRenderLoop = false;
|
||||
},
|
||||
closeFrameLatch() {
|
||||
if (viewer?._cesiumWidget)
|
||||
viewer._cesiumWidget._renderLoopRunning = false;
|
||||
},
|
||||
releaseFrames() {
|
||||
if (viewer) viewer.useDefaultRenderLoop = true;
|
||||
},
|
||||
};
|
||||
|
||||
const fleet = {
|
||||
attach() {
|
||||
billboards = new Cesium.BillboardCollection();
|
||||
viewer.scene.primitives.add(billboards);
|
||||
registerSpriteCollection(spriteLayer, billboards);
|
||||
models = new Cesium.PrimitiveCollection();
|
||||
viewer.scene.primitives.add(models);
|
||||
},
|
||||
// `owner`: the viewer the layer's destroy() was given (the same one).
|
||||
detach(owner) {
|
||||
const host = owner ?? viewer;
|
||||
if (billboards) {
|
||||
host.scene.primitives.remove(billboards);
|
||||
billboards = null;
|
||||
}
|
||||
if (models) {
|
||||
host.scene.primitives.remove(models); // removing destroys it + its models
|
||||
models = null;
|
||||
}
|
||||
},
|
||||
attached: () => !!billboards,
|
||||
visible: () => !!billboards && billboards.show,
|
||||
setVisible(visible) {
|
||||
if (billboards) billboards.show = visible;
|
||||
},
|
||||
add: (spec) => billboards.add(spec),
|
||||
remove: (sprite) => billboards.remove(sprite),
|
||||
restoreOrder: () => restoreSpriteOrder(viewer),
|
||||
restoreOrderOnEnable: () => restoreSpriteOrderOnEnable(spriteLayer, viewer),
|
||||
};
|
||||
|
||||
const modelSet = {
|
||||
live: () => !!models && !models.isDestroyed(),
|
||||
setVisible(visible) {
|
||||
if (models) models.show = visible;
|
||||
},
|
||||
loadFleet: ({
|
||||
url,
|
||||
minimumPixelSize,
|
||||
scale,
|
||||
color,
|
||||
blendAmount,
|
||||
unlit,
|
||||
id,
|
||||
}) =>
|
||||
Cesium.Model.fromGltfAsync({
|
||||
url,
|
||||
asynchronous: false,
|
||||
minimumPixelSize,
|
||||
scale,
|
||||
color,
|
||||
colorBlendMode: Cesium.ColorBlendMode.MIX,
|
||||
colorBlendAmount: blendAmount,
|
||||
customShader: unlit ? irUnlitShader() : undefined,
|
||||
id, // so scene.pick returns the icao for click-to-track
|
||||
}),
|
||||
loadTracked: ({
|
||||
url,
|
||||
minimumPixelSize,
|
||||
scale,
|
||||
color,
|
||||
blendAmount,
|
||||
unlit,
|
||||
id,
|
||||
}) =>
|
||||
Cesium.Model.fromGltfAsync({
|
||||
url,
|
||||
asynchronous: false,
|
||||
minimumPixelSize,
|
||||
scale,
|
||||
color,
|
||||
colorBlendMode: Cesium.ColorBlendMode.MIX,
|
||||
colorBlendAmount: blendAmount,
|
||||
customShader: unlit ? irUnlitShader() : undefined,
|
||||
// Pick id (H1): clicking the tracked plane's own model must read as
|
||||
// that plane, not as empty space.
|
||||
id,
|
||||
}),
|
||||
// Warms Cesium's glTF cache (the retained instance is never drawn).
|
||||
preload: (url) =>
|
||||
Cesium.Model.fromGltfAsync({
|
||||
url,
|
||||
asynchronous: false,
|
||||
}),
|
||||
add: (model) => models.add(model),
|
||||
remove(model) {
|
||||
if (models && !models.isDestroyed()) {
|
||||
try {
|
||||
models.remove(model);
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
}
|
||||
},
|
||||
destroy(model) {
|
||||
try {
|
||||
model.destroy();
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
},
|
||||
/**
|
||||
* World transform from a position and a course (pitch/roll 0, ENU frame),
|
||||
* written into the model's OWN modelMatrix: Model.modelMatrix is a plain
|
||||
* field Cesium clones per frame, so models never share one mutable
|
||||
* matrix (a shared scratch stacked every model on the last-written
|
||||
* plane: the "flickering like mad" bug).
|
||||
*/
|
||||
setPose(model, position, headingDeg) {
|
||||
scratchHpr.heading = Cesium.Math.toRadians(
|
||||
(headingDeg || 0) + headingOffsetDeg,
|
||||
);
|
||||
scratchHpr.pitch = 0;
|
||||
scratchHpr.roll = 0;
|
||||
return Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
position,
|
||||
scratchHpr,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
undefined,
|
||||
model.modelMatrix,
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const tracked = {
|
||||
/**
|
||||
* The tracked aircraft as an Entity: a pure billboard (no model or label
|
||||
* graphic, so viewer.trackedEntity always has a ready bounding sphere),
|
||||
* in the ENU tracking frame the close-range camera guard also uses.
|
||||
* Cesium generates its id: an explicit one would throw when a re-init
|
||||
* briefly overlaps collections.
|
||||
*/
|
||||
create(spec) {
|
||||
return viewer.entities.add({
|
||||
position: new Cesium.CallbackProperty(() => spec.position(), false),
|
||||
trackingReferenceFrame: Cesium.TrackingReferenceFrame.ENU,
|
||||
billboard: {
|
||||
image: spec.image,
|
||||
width: spec.width,
|
||||
height: spec.height,
|
||||
scale: spec.scale,
|
||||
color: new Cesium.CallbackProperty(
|
||||
() => cesiumColor(spec.color()),
|
||||
false,
|
||||
),
|
||||
sizeInMeters: false,
|
||||
scaleByDistance: cesiumNearFar(spec.scaleByDistance),
|
||||
alignedAxis: Cesium.Cartesian3.ZERO,
|
||||
disableDepthTestDistance: spec.disableDepthTestDistance,
|
||||
rotation: new Cesium.CallbackProperty(() => spec.rotation(), false),
|
||||
},
|
||||
});
|
||||
},
|
||||
remove(handle) {
|
||||
viewer.entities.remove(handle);
|
||||
},
|
||||
isLive: (handle) => !!viewer?.entities?.contains?.(handle),
|
||||
setImage(handle, image) {
|
||||
if (handle?.billboard) handle.billboard.image = image;
|
||||
},
|
||||
setViewFrom(handle, offset) {
|
||||
handle.viewFrom = new Cesium.Cartesian3(offset.x, offset.y, offset.z);
|
||||
},
|
||||
/**
|
||||
* The tracked billboard's drawn size inputs, at the viewer's time. The
|
||||
* result is reused (read it before the next call).
|
||||
*/
|
||||
billboardSize(handle) {
|
||||
const billboard = handle?.billboard;
|
||||
if (!billboard) return null;
|
||||
const time = viewer.clock.currentTime;
|
||||
scratchSize.width = billboard.width?.getValue(time);
|
||||
scratchSize.height = billboard.height?.getValue(time);
|
||||
scratchSize.scale = billboard.scale?.getValue(time);
|
||||
scratchSize.scaleByDistance = billboard.scaleByDistance?.getValue(time);
|
||||
return scratchSize;
|
||||
},
|
||||
};
|
||||
|
||||
const follow = {
|
||||
// Cancel any flight first: Cesium applies the entity's viewFrom on the
|
||||
// first frame only from an idle camera.
|
||||
start(handle) {
|
||||
viewer.camera.cancelFlight();
|
||||
viewer.trackedEntity = handle;
|
||||
return applyTrackedCameraFrame(viewer, handle, handle.viewFrom) || null;
|
||||
},
|
||||
refocus(handle) {
|
||||
viewer.camera.cancelFlight();
|
||||
viewer.trackedEntity = handle;
|
||||
return applyTrackedCameraFrame(viewer, handle, handle.viewFrom) || null;
|
||||
},
|
||||
// Releasing trackedEntity leaves the camera where the follow put it.
|
||||
release() {
|
||||
if (viewer) viewer.trackedEntity = undefined;
|
||||
},
|
||||
isFollowing: (handle) => !!viewer && viewer.trackedEntity === handle,
|
||||
current: () => viewer?.trackedEntity,
|
||||
onChanged: (listener) =>
|
||||
viewer.trackedEntityChanged.addEventListener(listener),
|
||||
};
|
||||
|
||||
const trails = {
|
||||
create: ({ color, width }) => createTrail(viewer, { color, width }),
|
||||
/**
|
||||
* The live head segment: last fix → the dead-reckoned aircraft, updated
|
||||
* per frame through a CallbackProperty (entity polylines update cheaply,
|
||||
* the trail body rebuilds on setPositions). The 'gev-trail' id namespace
|
||||
* is claimed by trailRenderer's pick owner.
|
||||
*/
|
||||
createHead({ id, show, positions, color, width }) {
|
||||
if (!viewer) return null;
|
||||
return viewer.entities.add({
|
||||
id,
|
||||
show,
|
||||
polyline: {
|
||||
positions: new Cesium.CallbackProperty(() => positions(), false),
|
||||
width,
|
||||
material: Cesium.Color.fromCssColorString(color).withAlpha(0.9),
|
||||
// The head never vanishes into the mesh (dimmed when occluded).
|
||||
depthFailMaterial:
|
||||
Cesium.Color.fromCssColorString(color).withAlpha(0.45),
|
||||
arcType: Cesium.ArcType.GEODESIC,
|
||||
},
|
||||
});
|
||||
},
|
||||
removeHead(head) {
|
||||
if (head && viewer && !viewer.isDestroyed()) {
|
||||
try {
|
||||
viewer.entities.remove(head);
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
kind: 'cesium',
|
||||
get engine() {
|
||||
return engine ?? engineFromViewer(viewer);
|
||||
},
|
||||
viewer,
|
||||
view,
|
||||
fleet,
|
||||
models: modelSet,
|
||||
tracked,
|
||||
follow,
|
||||
trails,
|
||||
/**
|
||||
* Everything a vertical surface probe must not hit: Cesium excludes
|
||||
* picked objects, and the layer's billboards and models are its own.
|
||||
*/
|
||||
surfaceExclusions: ({ sprites = [], models: modelHandles = [] }) =>
|
||||
[...sprites, ...modelHandles].filter(Boolean),
|
||||
destroy() {
|
||||
billboards = null;
|
||||
models = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createAircraftCesiumRenderer } from './cesium.js';
|
||||
import { missingAircraftRendererMembers } from './contract.js';
|
||||
import { CYAN, nearFarScale, rgbaFromCss } from '../../shared/color.js';
|
||||
|
||||
/** A viewer with what the renderer touches: primitives, entities, camera. */
|
||||
function stubViewer() {
|
||||
const added = [];
|
||||
const removed = [];
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(-73.78, 40.0, 50_000),
|
||||
directionWC: Cesium.Cartesian3.normalize(
|
||||
Cesium.Cartesian3.negate(
|
||||
Cesium.Cartesian3.fromDegrees(-73.78, 40.0, 50_000),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
upWC: Cesium.Cartesian3.UNIT_Z,
|
||||
frustum: new Cesium.PerspectiveFrustum({ fov: 1, aspectRatio: 1.5 }),
|
||||
moveEnd: new Cesium.Event(),
|
||||
cancelled: 0,
|
||||
cancelFlight() {
|
||||
this.cancelled += 1;
|
||||
},
|
||||
};
|
||||
camera.frustum.near = 1;
|
||||
camera.frustum.far = 1e8;
|
||||
const viewer = {
|
||||
camera,
|
||||
scene: {
|
||||
primitives: {
|
||||
add: (p) => added.push(p) && p,
|
||||
remove: (p) => removed.push(p),
|
||||
},
|
||||
preRender: new Cesium.Event(),
|
||||
preUpdate: new Cesium.Event(),
|
||||
canvas: { clientHeight: 800 },
|
||||
frameState: { frameNumber: 42 },
|
||||
screenSpaceCameraController: {},
|
||||
requestRender() {},
|
||||
},
|
||||
entities: new Cesium.EntityCollection(),
|
||||
clock: { currentTime: Cesium.JulianDate.now() },
|
||||
trackedEntity: undefined,
|
||||
trackedEntityChanged: new Cesium.Event(),
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
return { viewer, added, removed };
|
||||
}
|
||||
|
||||
const renderer = (viewer, options = {}) =>
|
||||
createAircraftCesiumRenderer({
|
||||
viewer,
|
||||
spriteLayer: 'flights',
|
||||
headingOffsetDeg: 180,
|
||||
...options,
|
||||
});
|
||||
|
||||
test('the Cesium aircraft renderer has every member of the contract', () => {
|
||||
const { viewer } = stubViewer();
|
||||
assert.deepEqual(missingAircraftRendererMembers(renderer(viewer)), []);
|
||||
assert.equal(renderer(viewer).kind, 'cesium');
|
||||
});
|
||||
|
||||
test('the fleet is one BillboardCollection and one model collection, in that order', () => {
|
||||
const { viewer, added, removed } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
assert.equal(r.fleet.attached(), false);
|
||||
r.fleet.attach();
|
||||
assert.ok(added[0] instanceof Cesium.BillboardCollection);
|
||||
assert.ok(added[1] instanceof Cesium.PrimitiveCollection);
|
||||
assert.equal(r.fleet.visible(), true);
|
||||
const sprite = r.fleet.add({
|
||||
position: geo.cartesian3.fromDegrees(0, 0, 1000),
|
||||
color: rgbaFromCss('#FFB800').withAlpha(0.5),
|
||||
scaleByDistance: nearFarScale(1000, 3, 8_000_000, 0.5),
|
||||
id: 'abc123',
|
||||
});
|
||||
assert.ok(sprite instanceof Cesium.Billboard);
|
||||
assert.equal(sprite.id, 'abc123');
|
||||
r.fleet.setVisible(false);
|
||||
assert.equal(r.fleet.visible(), false);
|
||||
r.models.setVisible(false);
|
||||
assert.equal(added[1].show, false);
|
||||
assert.equal(r.models.live(), true);
|
||||
r.fleet.detach();
|
||||
assert.deepEqual(removed, [added[0], added[1]]);
|
||||
assert.equal(r.fleet.attached(), false);
|
||||
});
|
||||
|
||||
test('a model pose is the old heading-pitch-roll frame with the nose offset', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const model = { modelMatrix: new Cesium.Matrix4() };
|
||||
const position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
const written = r.models.setPose(model, position, 75);
|
||||
assert.equal(written, model.modelMatrix, 'written into the model own matrix');
|
||||
const expected = Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
position,
|
||||
new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(75 + 180), 0, 0),
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...Cesium.Matrix4.toArray(model.modelMatrix)],
|
||||
[...Cesium.Matrix4.toArray(expected)],
|
||||
);
|
||||
});
|
||||
|
||||
test('model loads carry the layer spec; the IR boost loads an UNLIT model', async () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const calls = [];
|
||||
const realFrom = Cesium.Model.fromGltfAsync;
|
||||
Cesium.Model.fromGltfAsync = (options) => {
|
||||
calls.push(options);
|
||||
return Promise.resolve({ options });
|
||||
};
|
||||
try {
|
||||
const spec = {
|
||||
url: '/models/airplane.glb',
|
||||
minimumPixelSize: 24,
|
||||
scale: 1,
|
||||
color: CYAN,
|
||||
blendAmount: 0.94,
|
||||
unlit: false,
|
||||
id: 'abc123',
|
||||
};
|
||||
await r.models.loadFleet(spec);
|
||||
await r.models.loadTracked({ ...spec, unlit: true, minimumPixelSize: 40 });
|
||||
await r.models.preload('/models/airplane.glb');
|
||||
} finally {
|
||||
Cesium.Model.fromGltfAsync = realFrom;
|
||||
}
|
||||
assert.equal(calls.length, 3);
|
||||
for (const call of calls) assert.equal(call.asynchronous, false);
|
||||
assert.equal(calls[0].colorBlendMode, Cesium.ColorBlendMode.MIX);
|
||||
assert.equal(calls[0].colorBlendAmount, 0.94);
|
||||
assert.equal(calls[0].customShader, undefined);
|
||||
assert.equal(calls[0].id, 'abc123');
|
||||
assert.equal(calls[1].minimumPixelSize, 40);
|
||||
assert.equal(calls[1].customShader.lightingModel, Cesium.LightingModel.UNLIT);
|
||||
assert.deepEqual(Object.keys(calls[2]).sort(), ['asynchronous', 'url']);
|
||||
});
|
||||
|
||||
test('the frustum and horizon tests are the Cesium ones', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const inFrustum = r.view.frustumTester();
|
||||
const below = Cesium.Cartesian3.fromDegrees(-73.78, 40.0, 0);
|
||||
const behind = Cesium.Cartesian3.fromDegrees(106.22, -40.0, 0);
|
||||
const aboveCamera = Cesium.Cartesian3.fromDegrees(-73.78, 40.0, 200_000);
|
||||
assert.equal(inFrustum(below), true);
|
||||
assert.equal(inFrustum(aboveCamera), false);
|
||||
assert.equal(r.view.horizon().isPointVisible(below), true);
|
||||
assert.equal(r.view.horizon().isPointVisible(behind), false);
|
||||
assert.equal(r.view.frameNumber(), 42);
|
||||
assert.equal(r.view.viewportHeightPx(), 800);
|
||||
});
|
||||
|
||||
test('the tracked aircraft is an ENU-framed billboard entity with live callbacks', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
let position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
let color = CYAN;
|
||||
const handle = r.tracked.create({
|
||||
position: () => position,
|
||||
image: 'data:image/png;base64,',
|
||||
width: 28,
|
||||
height: 28,
|
||||
scale: 1.2,
|
||||
color: () => color,
|
||||
scaleByDistance: nearFarScale(1000, 3.0, 8000000, 0.5),
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
rotation: () => 0.25,
|
||||
});
|
||||
assert.ok(handle instanceof Cesium.Entity);
|
||||
assert.equal(r.tracked.isLive(handle), true);
|
||||
const time = viewer.clock.currentTime;
|
||||
assert.equal(
|
||||
handle.trackingReferenceFrame,
|
||||
Cesium.TrackingReferenceFrame.ENU,
|
||||
);
|
||||
assert.equal(handle.position.getValue(time), position);
|
||||
const billboardColor = handle.billboard.color.getValue(time);
|
||||
assert.ok(billboardColor instanceof Cesium.Color);
|
||||
assert.ok(billboardColor.equals(Cesium.Color.CYAN));
|
||||
color = CYAN.withAlpha(0);
|
||||
assert.equal(handle.billboard.color.getValue(time).alpha, 0);
|
||||
assert.equal(handle.billboard.rotation.getValue(time), 0.25);
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.equals(
|
||||
handle.billboard.alignedAxis.getValue(time),
|
||||
Cesium.Cartesian3.ZERO,
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
handle.billboard.scaleByDistance.getValue(time) instanceof
|
||||
Cesium.NearFarScalar,
|
||||
);
|
||||
assert.deepEqual(r.tracked.billboardSize(handle), {
|
||||
width: 28,
|
||||
height: 28,
|
||||
scale: 1.2,
|
||||
scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8000000, 0.5),
|
||||
});
|
||||
r.tracked.setViewFrom(handle, { x: 0, y: -2400, z: 1650 });
|
||||
assert.ok(handle.viewFrom.getValue(time) instanceof Cesium.Cartesian3);
|
||||
position = geo.cartesian3.fromDegrees(-97.6, 30.2, 3000);
|
||||
assert.equal(handle.position.getValue(time), position);
|
||||
r.tracked.remove(handle);
|
||||
assert.equal(r.tracked.isLive(handle), false);
|
||||
});
|
||||
|
||||
test('follow tracks the handle after cancelling a flight; release leaves the camera', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const handle = r.tracked.create({
|
||||
position: () => geo.cartesian3.fromDegrees(-97.7, 30.2, 3000),
|
||||
image: 'x',
|
||||
width: 28,
|
||||
height: 28,
|
||||
scale: 1,
|
||||
color: () => CYAN,
|
||||
scaleByDistance: nearFarScale(1000, 3.0, 8000000, 0.5),
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
rotation: () => 0,
|
||||
});
|
||||
r.tracked.setViewFrom(handle, { x: 0, y: -2400, z: 1650 });
|
||||
const changes = [];
|
||||
const remove = r.follow.onChanged(() => changes.push(r.follow.current()));
|
||||
viewer.trackedEntityChanged.raiseEvent(); // the viewer raises on assignment
|
||||
const stop = r.follow.start(handle);
|
||||
assert.equal(viewer.camera.cancelled, 1);
|
||||
assert.equal(viewer.trackedEntity, handle);
|
||||
assert.equal(r.follow.isFollowing(handle), true);
|
||||
assert.equal(typeof stop, 'function', 'the one exact tracked frame');
|
||||
stop();
|
||||
r.follow.release();
|
||||
assert.equal(viewer.trackedEntity, undefined);
|
||||
assert.equal(r.follow.isFollowing(handle), false);
|
||||
remove();
|
||||
assert.equal(changes.length, 1);
|
||||
});
|
||||
|
||||
test('the trail head is a geodesic entity polyline in the trail namespace', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const ends = [
|
||||
geo.cartesian3.fromDegrees(0, 0, 1000),
|
||||
geo.cartesian3.fromDegrees(0.1, 0, 1000),
|
||||
];
|
||||
const head = r.trails.createHead({
|
||||
id: 'gev-trail:fl-head-1',
|
||||
show: true,
|
||||
positions: () => ends,
|
||||
color: '#00d4ff',
|
||||
width: 2.5,
|
||||
});
|
||||
const time = viewer.clock.currentTime;
|
||||
assert.equal(head.id, 'gev-trail:fl-head-1');
|
||||
assert.equal(head.polyline.positions.getValue(time), ends);
|
||||
assert.equal(head.polyline.arcType.getValue(time), Cesium.ArcType.GEODESIC);
|
||||
const base = Cesium.Color.fromCssColorString('#00d4ff');
|
||||
assert.ok(
|
||||
head.polyline.material.getValue(time).color.equals(base.withAlpha(0.9)),
|
||||
);
|
||||
assert.ok(
|
||||
head.polyline.depthFailMaterial
|
||||
.getValue(time)
|
||||
.color.equals(base.withAlpha(0.45)),
|
||||
);
|
||||
r.trails.removeHead(head);
|
||||
assert.equal(viewer.entities.contains(head), false);
|
||||
});
|
||||
|
||||
test('an adopted (test) collection is driven as the fleet', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const removed = [];
|
||||
const billboardCollection = {
|
||||
show: true,
|
||||
remove: (sprite) => removed.push(sprite),
|
||||
};
|
||||
const modelCollection = {
|
||||
added: [],
|
||||
add(model) {
|
||||
this.added.push(model);
|
||||
},
|
||||
remove() {},
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
const r = renderer(viewer, {
|
||||
adopt: { billboardCollection, modelCollection },
|
||||
});
|
||||
assert.equal(r.fleet.visible(), true);
|
||||
r.fleet.remove('sprite');
|
||||
assert.deepEqual(removed, ['sprite']);
|
||||
r.models.add('model');
|
||||
assert.deepEqual(modelCollection.added, ['model']);
|
||||
assert.deepEqual(
|
||||
r.surfaceExclusions({ sprites: ['a'], models: ['b', null] }),
|
||||
['a', 'b'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
// The aircraft renderer: what the aircraft layers' logic (flights now,
|
||||
// military and local ADS-B after it) asks of an engine to draw a fleet of
|
||||
// aircraft, its 3D models, the tracked aircraft, its trail, and to follow it.
|
||||
// render/cesium.js implements it over Cesium (the objects the layers used
|
||||
// to build themselves, one for one); render/navara.js implements it on the
|
||||
// Navara engine over engine.movers / engine.lines / engine.camera.follow.
|
||||
// Nothing here imports an engine.
|
||||
//
|
||||
// The logic holds HANDLES and writes plain fields on them; the field names
|
||||
// are Cesium's (the extraction is a pure move), and an engine other than
|
||||
// Cesium implements them as setters:
|
||||
//
|
||||
// SpriteHandle (fleet.add) — one aircraft glyph:
|
||||
// position (Cartesian3), show, rotation (screen angle, rad),
|
||||
// scale, width, height (CSS px), color ({red, green, blue, alpha} with
|
||||
// withAlpha(); an Rgba of src/layers/shared/color.js or what the engine
|
||||
// stored), image (canvas or URL), scaleByDistance ({near, nearValue,
|
||||
// far, farValue}), id. Reads return what was last written (color and
|
||||
// scaleByDistance as the engine's own copy). The logic may keep its own
|
||||
// bookkeeping fields on a handle (prefixed _gev).
|
||||
// ModelHandle (models.load*) — one glTF instance:
|
||||
// show, ready (read-only), scale, computedScale (read-only: scale after
|
||||
// minimumPixelSize), color, id, modelMatrix (16 numbers, column-major,
|
||||
// written by models.setPose and read for anchors), sceneGraph? (Cesium).
|
||||
// TrackedHandle (tracked.create) — the selected aircraft's glyph and the
|
||||
// follow target: viewFrom (ENU offset, read), and the annotation fields
|
||||
// the shell reads: gevSelectionOrigin, gevTrackedId, gevLabelModel,
|
||||
// gevDisplayPosition(), gevVisualPosition().
|
||||
// Trail (trails.create): setPositions(Cartesian3[]), setVisible(bool),
|
||||
// clear(), destroy(). TrailHead (trails.createHead): show (bool).
|
||||
//
|
||||
// The view: what the logic reads of the camera and the frame. `camera` is
|
||||
// camera-shaped (positionWC, positionCartographic, directionWC, upWC,
|
||||
// rightWC, heading, pitch, roll, frustum.fovy) and `scene` scene-shaped
|
||||
// ({ camera, canvas.clientHeight, frameState.frameNumber }) for the shared
|
||||
// helpers that take them (iconOrientation, focusDeemphasis); on Navara
|
||||
// they are adapters over engine.camera.pose(), with the engine registered
|
||||
// for the scene (engineFromViewer) so projections go through its projector.
|
||||
|
||||
/**
|
||||
* @typedef {object} AircraftView
|
||||
* @property {object} camera
|
||||
* @property {object} scene
|
||||
* @property {() => number} frameNumber One value per rendered frame.
|
||||
* @property {() => number} viewportHeightPx
|
||||
* @property {() => ((position: object) => boolean)} frustumTester For this
|
||||
* frame: is a point (1 m sphere) inside or on the view frustum.
|
||||
* @property {() => { isPointVisible(position: object): boolean }} horizon
|
||||
* For this frame: the ellipsoid horizon test.
|
||||
* @property {(position: object, result?: object) => ({x: number, y: number} | undefined)} worldToWindow
|
||||
* @property {() => void} requestRender
|
||||
* @property {(event: 'preRender'|'preUpdate'|'moveEnd', listener: Function) => () => void} on
|
||||
* @property {object} surfaceOwner What groundSnap/meshFloor sample through
|
||||
* (a viewer registered with its engine, or the engine).
|
||||
* @property {object} surfaceScene What sampleMeshFloorCells takes.
|
||||
* @property {() => void} holdFrames Evidence capture: stop the engine's own
|
||||
* frame loop (QA only).
|
||||
* @property {() => void} closeFrameLatch Evidence capture, one task later:
|
||||
* let manual renders start without waiting for the loop's next frame.
|
||||
* @property {() => void} releaseFrames
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} AircraftRenderer
|
||||
* @property {'cesium'|'navara'} kind
|
||||
* @property {object|null} engine The globe engine (null in unit tests that
|
||||
* drive a bare viewer).
|
||||
* @property {AircraftView} view
|
||||
* @property {object} fleet attach(), detach(), attached(), visible(),
|
||||
* setVisible(bool), add(spec) → SpriteHandle, remove(sprite),
|
||||
* restoreOrder(), restoreOrderOnEnable().
|
||||
* @property {object} models live(), setVisible(bool), loadFleet(spec),
|
||||
* loadTracked(spec), preload(url) → Promise<ModelHandle>, add(model),
|
||||
* remove(model), destroy(model), setPose(model, position, headingDeg).
|
||||
* spec: { url, minimumPixelSize, scale, color, blendAmount, unlit, id }.
|
||||
* @property {object} tracked create(spec) → TrackedHandle, remove(handle),
|
||||
* isLive(handle), setImage(handle, image), setViewFrom(handle, enu),
|
||||
* billboardSize(handle) → { width, height, scale, scaleByDistance } | null.
|
||||
* spec: { image, width, height, scale, scaleByDistance,
|
||||
* disableDepthTestDistance, position(), color() → colour, rotation() }.
|
||||
* @property {object} follow start(handle) → stop, refocus(handle) → stop,
|
||||
* release(), isFollowing(handle), current(), onChanged(listener) → remove.
|
||||
* @property {object} trails create({ color, width }) → Trail,
|
||||
* createHead({ id, show, positions() → Cartesian3[], color, width }) →
|
||||
* TrailHead, removeHead(head).
|
||||
* @property {(objects: { sprites: Iterable, models: Iterable }) => object[]} surfaceExclusions
|
||||
* What a vertical surface probe must not hit: the layer's own drawings.
|
||||
* @property {() => void} destroy
|
||||
*/
|
||||
|
||||
/** The members every aircraft renderer has (shape checks, tests). */
|
||||
export const AIRCRAFT_RENDERER_SHAPE = Object.freeze({
|
||||
view: [
|
||||
'frameNumber',
|
||||
'viewportHeightPx',
|
||||
'frustumTester',
|
||||
'horizon',
|
||||
'worldToWindow',
|
||||
'requestRender',
|
||||
'on',
|
||||
'holdFrames',
|
||||
'closeFrameLatch',
|
||||
'releaseFrames',
|
||||
],
|
||||
fleet: [
|
||||
'attach',
|
||||
'detach',
|
||||
'attached',
|
||||
'visible',
|
||||
'setVisible',
|
||||
'add',
|
||||
'remove',
|
||||
'restoreOrder',
|
||||
'restoreOrderOnEnable',
|
||||
],
|
||||
models: [
|
||||
'live',
|
||||
'setVisible',
|
||||
'loadFleet',
|
||||
'loadTracked',
|
||||
'preload',
|
||||
'add',
|
||||
'remove',
|
||||
'destroy',
|
||||
'setPose',
|
||||
],
|
||||
tracked: [
|
||||
'create',
|
||||
'remove',
|
||||
'isLive',
|
||||
'setImage',
|
||||
'setViewFrom',
|
||||
'billboardSize',
|
||||
],
|
||||
follow: [
|
||||
'start',
|
||||
'refocus',
|
||||
'release',
|
||||
'isFollowing',
|
||||
'current',
|
||||
'onChanged',
|
||||
],
|
||||
trails: ['create', 'createHead', 'removeHead'],
|
||||
});
|
||||
|
||||
/**
|
||||
* The members of AIRCRAFT_RENDERER_SHAPE that `renderer` lacks
|
||||
* (['group.member', …]); empty for a complete renderer.
|
||||
*/
|
||||
export function missingAircraftRendererMembers(renderer) {
|
||||
const missing = [];
|
||||
for (const key of ['kind', 'view', 'surfaceExclusions', 'destroy'])
|
||||
if (renderer?.[key] === undefined) missing.push(key);
|
||||
for (const [group, members] of Object.entries(AIRCRAFT_RENDERER_SHAPE))
|
||||
for (const member of members)
|
||||
if (typeof renderer?.[group]?.[member] !== 'function')
|
||||
missing.push(`${group}.${member}`);
|
||||
return missing;
|
||||
}
|
||||
Reference in new issue
Block a user