Merge main into german/i18n-plurals-context

The catalogs conflicted only on neighbouring lines: no key changed on both
sides, so they are merged key by key in main's order. Main removed the rail
timeline, the other user of plain "Latest", so that entry is pruned and the
News test no longer checks the timeline's wording.
This commit is contained in:
German Khokhlov committed 2026-11-16 16:58:37 +04:00
commit 49409ba8f1
1502 files changed
+180715 -47887

No files matched your search

+7 -9
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { findCamera } from '../render/rendererOf.js';
import {
feedProvenanceEnvelope,
layerSnapshot,
@@ -104,14 +104,12 @@ export function getWorldPacket(options = {}) {
// A default parameter only covers undefined; null or NaN would age every
// feed against the epoch and report stale data as "just now".
const now = Number.isFinite(requestedNow) ? requestedNow : Date.now();
if (!viewer?.camera?.positionWC)
throw new TypeError('World Packet requires a viewer camera');
const pose = findCamera(viewer)?.pose();
if (!pose) throw new TypeError('World Packet requires a viewer camera');
if (!dataManager || typeof dataManager.getAll !== 'function')
throw new TypeError('World Packet requires a data manager');
const cartographic = Cesium.Cartographic.fromCartesian(
viewer.camera.positionWC,
);
const eye = { lon: pose.lon, lat: pose.lat, height: pose.height };
// Read the roster once. Voice must not rewalk disabled layers: preserving the
// current enabled-only view keeps the model's context budget bounded.
const rows = dataManager.getAll();
@@ -126,9 +124,9 @@ export function getWorldPacket(options = {}) {
ok: true,
action: 'get_current_view_state',
camera: {
latitude: Cesium.Math.toDegrees(cartographic.latitude),
longitude: Cesium.Math.toDegrees(cartographic.longitude),
heightM: cartographic.height,
latitude: eye.lat,
longitude: eye.lon,
heightM: eye.height,
},
style: styleManager?.activeStyle || 'normal',
context: contextState
+13
View File
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { getWorldPacket } from './worldPacket.js';
import { bindRenderer } from '../render/rendererOf.js';
import { createStubRenderer } from '../render/stub/index.js';
import { createGevActionRunner } from '../voice/gevActions.js';
function withoutVoicePresentation(result) {
@@ -18,6 +20,9 @@ function harness() {
const viewer = {
trackedEntity: undefined,
clock: { onTick: { addEventListener: () => () => {} } },
get canvas() {
return this.scene.canvas;
},
scene: {
canvas: {
clientWidth: 1200,
@@ -60,6 +65,14 @@ function harness() {
getCockpitState: () => null,
getControlState: () => ({ hud: { visible: 'auto' } }),
};
// The packet reads the eye from the camera port of the renderer bound to
// the scene object.
const renderer = createStubRenderer();
renderer.camera.setView({
destination: { lon: -97.74, lat: 30.26, height: 500 },
orientation: { heading: 0, pitch: Cesium.Math.toRadians(-45), roll: 0 },
});
bindRenderer(viewer, renderer);
return { viewer, dataManager, styleManager };
}
+4 -2
View File
@@ -4,11 +4,13 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
import { createAnnotationResolver } from './resolver.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { createAnnotationEngine } from './annotationEngine.js';
import { _resetRenderGovernorForTest } from '../renderGovernor.js';
function viewerAt(lat, lon, height = 20_000) {
return {
// The resolver reads the camera through the renderer's camera port.
return bindFakeCesiumCamera({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
@@ -16,7 +18,7 @@ function viewerAt(lat, lon, height = 20_000) {
height,
},
},
};
});
}
/** A resolver whose boundary lookups and geocoder record every call. */
+88 -63
View File
@@ -1,6 +1,9 @@
import { isUnavailableCapability } from '../sources/capability.js';
import { defaultGeospatial } from '../search/defaults.js';
import * as Cesium from 'cesium';
import { cameraOf, findCamera, findQuery } from '../render/rendererOf.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import { sphereFromPoints } from '../geo/sphere.js';
import { distance, toRadians } from '../geo/vector.js';
import { greatCircleMeters } from '../geoDistance.js';
import {
holdContinuousRender,
@@ -20,11 +23,6 @@ import {
} from '../sources/phaseTiming.js';
import { formatDistanceText } from '../data/distanceFormat.js';
// Dev convenience: expose the app's Cesium instance for console/preview probing
// (single shared module instance — avoids dual-Cesium state bugs when testing).
if (typeof window !== 'undefined' && !window.__CESIUM__)
window.__CESIUM__ = Cesium;
/**
* Annotation engine — the voice agent's "whiteboard" over the 3D world.
*
@@ -1717,18 +1715,20 @@ export function createAnnotationEngine({
frameAnnotation(marks[0]);
return;
}
const cart = points.map((p) =>
Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0),
const cart = points.map((p) => fromDegrees(p.lon, p.lat, p.height || 0));
const sphere = sphereFromPoints(cart);
const camera = cameraOf(viewer);
camera.flyToBounds(
{ center: sphere.center, radius: sphere.radius },
{
offset: {
heading: camera.pose().heading,
pitch: toRadians(-35),
range: Math.max(900, sphere.radius * 2.6),
},
durationS: 1.6,
},
);
const sphere = Cesium.BoundingSphere.fromPoints(cart);
viewer.camera.flyToBoundingSphere(sphere, {
offset: new Cesium.HeadingPitchRange(
viewer.camera.heading,
Cesium.Math.toRadians(-35),
Math.max(900, sphere.radius * 2.6),
),
duration: 1.6,
});
} catch {
/* camera assist is best-effort */
}
@@ -1738,23 +1738,35 @@ export function createAnnotationEngine({
* globe. On any API hiccup, report visible — bad data must never move the camera. */
function isPointOnScreen(p) {
try {
const camera = viewer.camera;
const pos = Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0);
const cv = camera.frustum.computeCullingVolume(
camera.position,
camera.direction,
camera.up,
);
if (
cv.computeVisibility(new Cesium.BoundingSphere(pos, 1)) ===
Cesium.Intersect.OUTSIDE
)
return false;
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
camera.position,
);
return occluder.isPointVisible(pos);
const camera = findCamera(viewer);
const query = findQuery(viewer);
if (!camera || !query) return true;
const pos = fromDegrees(p.lon, p.lat, p.height || 0);
// Inside the view frustum: a 1 m sphere at the point is not wholly
// outside any of its six planes, read off the view-projection (depth
// runs -1..1). An invalid matrix measures no distance and reads as
// visible.
const { view, projection } = camera.matrices();
const m = new Float64Array(16);
for (let col = 0; col < 4; col++)
for (let row = 0; row < 4; row++) {
let sum = 0;
for (let k = 0; k < 4; k++)
sum += projection[k * 4 + row] * view[col * 4 + k];
m[col * 4 + row] = sum;
}
const at = (row, col) => m[col * 4 + row];
for (const [axis, sign] of FRUSTUM_PLANES) {
const a = at(3, 0) + sign * at(axis, 0);
const b = at(3, 1) + sign * at(axis, 1);
const c = at(3, 2) + sign * at(axis, 2);
const d = at(3, 3) + sign * at(axis, 3);
const distanceM =
(a * pos.x + b * pos.y + c * pos.z + d) / Math.hypot(a, b, c);
if (distanceM < -1) return false;
}
// On the near side of the globe.
return !query.isOccluded(pos);
} catch {
return true;
}
@@ -1778,22 +1790,23 @@ export function createAnnotationEngine({
: anno.ring,
)
: viewportRange(anno.viewport) || 600;
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(
Cesium.Cartesian3.fromDegrees(
target.lon,
target.lat,
anno.anchor.height || 0,
),
range,
),
const camera = cameraOf(viewer);
camera.flyToBounds(
{
offset: new Cesium.HeadingPitchRange(
viewer.camera.heading,
Cesium.Math.toRadians(-35),
range * 2.4,
),
duration: 1.8,
center: {
lon: target.lon,
lat: target.lat,
height: anno.anchor.height || 0,
},
radius: range,
},
{
offset: {
heading: camera.pose().heading,
pitch: toRadians(-35),
range: range * 2.4,
},
durationS: 1.8,
},
);
} catch {
@@ -2005,15 +2018,17 @@ export function createAnnotationEngine({
}) {
if (destroyed) return;
try {
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, height),
orientation: {
heading: Cesium.Math.toRadians(heading),
pitch: Cesium.Math.toRadians(pitch),
roll: 0,
cameraOf(viewer).flyTo(
{ lon, lat, height },
{
orientation: {
heading: toRadians(heading),
pitch: toRadians(pitch),
roll: 0,
},
durationS: duration,
},
duration,
});
);
} catch {
/* camera flight best-effort */
}
@@ -2175,13 +2190,23 @@ function pendingAnimation(anno, now) {
// fly_to_location natural-region heuristic uses (owner field test 2026-07-23).
const VIEWPORT_ASSIST_RANGE_CAP_M = 120000;
/** The view frustum's planes as `row 3 ± row axis` of the view-projection. */
const FRUSTUM_PLANES = [
[0, 1],
[0, -1],
[1, 1],
[1, -1],
[2, 1],
[2, -1],
];
/** flyTo range from a Places viewport box (low/high lat-lng corners), or null. */
function viewportRange(vp) {
if (!vp?.low || !vp?.high) return null;
try {
const span = Cesium.Cartesian3.distance(
Cesium.Cartesian3.fromDegrees(vp.low.longitude, vp.low.latitude),
Cesium.Cartesian3.fromDegrees(vp.high.longitude, vp.high.latitude),
const span = distance(
fromDegrees(vp.low.longitude, vp.low.latitude),
fromDegrees(vp.high.longitude, vp.high.latitude),
);
return Number.isFinite(span) && span > 0
? Math.max(300, Math.min(span * 0.7, VIEWPORT_ASSIST_RANGE_CAP_M))
@@ -2206,9 +2231,9 @@ function ringRange(ring) {
if (lon < minLon) minLon = lon;
if (lon > maxLon) maxLon = lon;
}
const span = Cesium.Cartesian3.distance(
Cesium.Cartesian3.fromDegrees(minLon, minLat),
Cesium.Cartesian3.fromDegrees(maxLon, maxLat),
const span = distance(
fromDegrees(minLon, minLat),
fromDegrees(maxLon, maxLat),
);
return Math.max(300, span * 0.7);
}
+70 -4
View File
@@ -1,3 +1,4 @@
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { createStandalonePlaceSearch } from '../standalone/placeSearch.js';
// Voice-annotation resilience contract tests — pure logic, no network, no browser.
//
@@ -25,6 +26,7 @@ import {
installRenderGovernor,
_resetRenderGovernorForTest,
} from '../renderGovernor.js';
import { framePortFor } from '../testSupport/fakeFramePort.mjs';
// A resolver that replays a scripted sequence of outcomes (undefined = transient,
// null = definitive miss, object = footprint) and counts its invocations.
@@ -1471,7 +1473,7 @@ test('hand-drawn marks: one mark can be hidden, renamed, recoloured, framed and
const { renderer, calls } = fakeRenderer();
const flights = [];
const engine = createAnnotationEngine({
viewer: { camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } },
viewer: bindFakeCesiumCamera({ camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } }),
renderer,
});
let changes = 0;
@@ -1540,12 +1542,12 @@ test('hand-drawn marks: remove, hide, clear, expiry and framing have their effec
const { renderer, calls } = fakeRenderer();
const flights = [];
const engine = createAnnotationEngine({
viewer: {
viewer: bindFakeCesiumCamera({
camera: {
heading: 0,
flyToBoundingSphere: (sphere) => flights.push(sphere),
},
},
}),
renderer,
});
let changes = 0;
@@ -1757,7 +1759,7 @@ test('hand-drawn marks: with every mark hidden the scene idles, and showing one
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
let renders = 0;
installRenderGovernor({ scene: { requestRenderMode: true, requestRender: () => (renders += 1) } });
installRenderGovernor(framePortFor({ requestRenderMode: true, requestRender: () => (renders += 1) }));
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
await engine.annotate([
@@ -1898,3 +1900,67 @@ test('plain recaption keeps the old mark addressable when its removal throws', a
);
assert.equal(engine.count(), 0);
});
// The camera assist frames a fresh mark only when none of it is in view:
// off the frustum or behind the globe, as the renderer's camera and query
// ports see it. A camera that cannot answer leaves the view alone.
test('camera assist frames marks out of view and leaves visible ones alone', async (t) => {
installAnimationFrameStubs(t);
const { bindRenderer } = await import('../render/rendererOf.js');
const { horizonFrom } = await import('../geo/horizon.js');
const viewerOver = (lon, lat, height, { broken = false } = {}) => {
const position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
const direction = Cesium.Cartesian3.negate(
Cesium.Cartesian3.normalize(position, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(direction, Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3());
const view = Cesium.Matrix4.computeView(position, direction, up, right, new Cesium.Matrix4());
const frustum = new Cesium.PerspectiveFrustum({
fov: Cesium.Math.toRadians(60), aspectRatio: 16 / 9, near: 1, far: 5e7,
});
const flights = [];
const viewer = {};
const horizon = horizonFrom(position);
bindRenderer(viewer, {
camera: {
pose: () => ({ heading: 0 }),
matrices() {
if (broken) throw new Error('no camera');
return {
view: Float64Array.from(Cesium.Matrix4.toArray(view)),
projection: Float64Array.from(Cesium.Matrix4.toArray(frustum.projectionMatrix)),
};
},
flyTo: (...args) => flights.push(['flyTo', ...args]),
flyToBounds: (...args) => flights.push(['flyToBounds', ...args]),
},
query: { isOccluded: (p) => !horizon.isPointVisible(p) },
});
return { viewer, flights };
};
const pinAt = async (viewer, lon, lat) => {
const engine = createAnnotationEngine({ viewer, renderer: fakeRenderer().renderer });
await engine.annotate([{ type: 'pin', manual: true, latitude: lat, longitude: lon }], { persist: true, flyTo: false });
};
const inView = viewerOver(-97.74, 30.27, 9000);
await pinAt(inView.viewer, -97.742, 30.268);
assert.equal(inView.flights.length, 0, 'a mark in view is left alone');
const aside = viewerOver(-97.74, 30.27, 9000);
await pinAt(aside.viewer, -97.5, 30.6);
assert.equal(aside.flights.length, 1, 'a mark off the frustum is framed');
const behind = viewerOver(60, 30, 9_000_000);
await pinAt(behind.viewer, -120, -30);
assert.equal(behind.flights.length, 1, 'a mark behind the globe is framed');
const broken = viewerOver(-97.74, 30.27, 9000, { broken: true });
await pinAt(broken.viewer, -97.5, 30.6);
assert.equal(broken.flights.length, 0, 'a camera that cannot answer moves nothing');
});
+6 -4
View File
@@ -13,6 +13,7 @@ import { createPlaceSearch } from '../search/placeSearch.js';
// Run with: npm test (node --test)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import {
resolveAnnotationTarget as resolveTarget,
selectFootprint,
@@ -157,7 +158,8 @@ test('refineScope: entityKind refines only an unresolved (auto) scope', () => {
});
function closeViewportViewer() {
return {
// The resolver reads the camera through the renderer's camera port.
return bindFakeCesiumCamera({
camera: {
positionCartographic: {
latitude: 30.2672 * Math.PI / 180,
@@ -165,7 +167,7 @@ function closeViewportViewer() {
height: 1000,
},
},
};
});
}
function geocodePayload({ lat, lon, types, label }) {
@@ -369,11 +371,11 @@ test('ask-side admin bypass: admin level 2/3 result types never grant a township
// Synthetic footprints reproduce the real Capitol/YOTEL selection without live APIs.
const CAPITOL_ANCHOR = { lat: 38.8899389, lon: -77.0090505 };
function capitolViewer() {
return { camera: { positionCartographic: {
return bindFakeCesiumCamera({ camera: { positionCartographic: {
latitude: CAPITOL_ANCHOR.lat * Math.PI / 180,
longitude: CAPITOL_ANCHOR.lon * Math.PI / 180,
height: 1000,
} } };
} } });
}
function installCapitolMocks(t, elements, components = [
{ long_name: 'Washington', types: ['locality', 'political'] },
+150 -175
View File
@@ -1,5 +1,5 @@
/**
* Manual whiteboard drawing: the Cesium + DOM half.
* Manual whiteboard drawing: the scene + DOM half.
*
* UTILITIES ▸ Draw turns the globe into a whiteboard you draw on by hand: pick a
* shape (area, line or pin) and a colour, click the vertices on the real world,
@@ -15,12 +15,13 @@
* (`src/data/inputOwnership.js`), and every ambient selection handler yields,
* so a vertex clicked on top of an aircraft or a camera is a vertex and
* nothing else. It is one claim consulted by all of them, not a list of
* exceptions inside each.
* exceptions inside each. Turning Draw on takes the pointer from any tool
* holding it; a newer tool taking it turns Draw off.
* - Cesium's Viewer binds its OWN left click (select the entity under the
* pointer) and double click (track it) on the viewer's handler, outside every
* layer and therefore outside the shared claim. Both are borrowed for the
* layer and therefore outside the shared claim. Both are suppressed for the
* session and given back on the way out, and `destroy()` gives back every
* listener, the Cesium handler, the preview data source and the window
* listener, the pointer subscriptions, the preview draw sets and the window
* handle, so the tool can be turned off or the shell disposed without leaving
* anything behind.
*
@@ -30,14 +31,13 @@
* drapes finished areas and routes onto the surface, so the height is dropped
* at finish, deliberately and in one place — see `finishSpec` in drawMode.js.
*/
import * as Cesium from 'cesium';
import { pickWorldFromScreen } from './annotationResolver.js';
import {
claimPointer,
pointerOwner,
releasePointer,
} from '../data/inputOwnership.js';
import { pointerOwnerName } from '../data/pointerOwnerNames.js';
import { inputFor } from '../input/dispatcher.js';
import {
DRAW_SHAPES,
MAX_VERTICES,
@@ -59,7 +59,14 @@ import {
presentDrawMarks,
} from './drawMarks.js';
import { onLocaleChange, t, translateKnown } from '../i18n/index.js';
import { onLocaleChange, t } from '../i18n/index.js';
import { fromDegrees } from '../geo/index.js';
import { cssColor } from '../render/color.js';
import {
canvasOf as sceneCanvasOf,
drawOf,
findFrame,
} from '../render/rendererOf.js';
/** The longest note a row action leaves under its row, in characters. */
const NOTE_MAX = 200;
/** An action's answer as a row note: trimmed, and cut at a word with an ellipsis. */
@@ -74,7 +81,15 @@ function noteText(text) {
/** The id this tool claims the pointer under. */
const DRAW_POINTER_OWNER = 'draw';
const PREVIEW_DATA_SOURCE_NAME = 'gev-draw-preview';
/** Each tool's preview sets get their own ids. */
let previewSerial = 0;
/**
* Preview sets drawn on each viewer by its live tools, so a tool left
* undestroyed beside its replacement shows up in `diagnostics()`.
*/
const livePreviewSets = new WeakMap();
const countPreviewSets = (viewer, delta) =>
livePreviewSets.set(viewer, (livePreviewSets.get(viewer) ?? 0) + delta);
const PREVIEW = DRAW_COLOR_CSS;
@@ -89,7 +104,7 @@ const PREVIEW = DRAW_COLOR_CSS;
* `markActions` are the application's own buttons on an area's or a line's
* row (drawMarks.js `drawMarkActions`); a press runs the action with the
* shape's id, kind, name and geometry (drawMarks.js `drawMarkGeometry`).
* @param {{viewer: Cesium.Viewer, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps
* @param {{viewer: object, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function, markActions?: object[]}} deps
* @returns {{destroy: Function}|null}
*/
export function initDrawTool({
@@ -115,16 +130,13 @@ export function initDrawTool({
let shape = 'area';
let color = 'primary';
let hint = '';
let handler = null;
let unbindScene = null;
let lease = null;
let savedDoubleClick = null;
let savedSingleClick = null;
let cursor = null; // last mouse position on the canvas, for the rubber band
// Bumped by anything that supersedes an in-flight finish: cancelling, clearing
// the board, leaving draw mode, teardown. An `annotate()` that resolves after
// one of those must not write its outcome over the newer state.
let generation = 0;
const previewEntities = [];
// Every DOM listener this tool adds (the session's keydown), so teardown is
// one loop rather than a list that can fall out of step with the bindings.
const domListeners = [];
@@ -133,14 +145,26 @@ export function initDrawTool({
domListeners.push([target, type, listener, options]);
};
const dataSource = new Cesium.CustomDataSource(PREVIEW_DATA_SOURCE_NAME);
// `add()` resolves on the NEXT tick, so an init-then-immediate-destroy would
// remove a source that had not been attached yet and leave the attachment to
// land afterwards — a preview data source nobody owns. Chain the removal onto
// the attachment instead of racing it.
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
() => null,
);
// The preview: one dashed rubber band and a dot per vertex, drawn through
// the renderer's draw port. Both sets live as long as the tool.
const draw = drawOf(viewer);
const previewId = `draw-preview:${++previewSerial}`;
const previewLines = draw.lines({ id: `${previewId}:line` });
const previewPoints = draw.points({ id: `${previewId}:vertices` });
countPreviewSets(viewer, 2);
let previewReleased = false;
const releasePreview = () => {
if (previewReleased) return;
previewReleased = true;
countPreviewSets(viewer, -2);
previewLines.dispose();
previewPoints.dispose();
};
/** The canvas the renderer draws in (the viewer's own when none is bound). */
const canvasOf = () => sceneCanvasOf(viewer);
const requestRender = () => findFrame(viewer)?.requestRender('draw-preview');
// Teardown finishes synchronously; `whenSettled()` keeps its promise.
const attaching = Promise.resolve();
const present = () => {
const marks = annotations.list?.() || [];
@@ -169,70 +193,71 @@ export function initDrawTool({
// ---- preview ---------------------------------------------------------
const vertexPositions = () =>
session.vertices.map((v) =>
Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
);
const previewLine = dataSource.entities.add({
show: false,
polyline: {
positions: new Cesium.CallbackProperty(() => {
if (!session) return [];
const pts = vertexPositions();
if (cursor && session.shape !== 'pin') pts.push(cursor);
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
return pts;
}, false),
width: 3,
material: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.9),
dashLength: 16,
}),
depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.35),
dashLength: 16,
}),
clampToGround: false,
},
});
const syncPreview = () => {
session.vertices.map((v) => fromDegrees(v.lon, v.lat, v.height || 0));
/** The rubber band, from the vertices to the pointer (and closed for an area). */
const syncPreviewLine = () => {
if (destroyed) return;
previewEntities.forEach((e) => dataSource.entities.remove(e));
previewEntities.length = 0;
if (!session) {
previewLine.show = false;
setHint(() => drawHint(null));
viewer.scene.requestRender();
if (!session || session.shape === 'pin') {
previewLines.clear();
return;
}
const stroke = Cesium.Color.fromCssColorString(
PREVIEW[color] || PREVIEW.primary,
);
previewLine.polyline.material = new Cesium.PolylineDashMaterialProperty({
color: stroke.withAlpha(0.9),
dashLength: 16,
});
previewLine.show = session.shape !== 'pin';
for (const v of session.vertices) {
previewEntities.push(
dataSource.entities.add({
position: Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
point: {
pixelSize: 8,
color: stroke,
outlineColor: Cesium.Color.BLACK.withAlpha(0.6),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
}),
);
const pts = vertexPositions();
if (cursor) pts.push(cursor);
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
if (pts.length < 2) {
previewLines.clear();
return;
}
previewLines.upsert([
{
id: 'band',
positions: pts,
widthPx: 3,
// Along the ellipsoid between vertices, as the entity polyline was.
mode: 'geodesic',
style: {
kind: 'dash',
color: withAlpha(cssColor(PREVIEW[color] || PREVIEW.primary), 0.9),
length: 16,
},
// Dashed behind the surface too, as the band in front of it is.
depthFail: {
kind: 'dash',
color: withAlpha(cssColor(PREVIEW.primary), 0.35),
length: 16,
},
},
]);
};
const syncPreview = () => {
if (destroyed) return;
if (!session) {
previewPoints.clear();
previewLines.clear();
setHint(() => drawHint(null));
requestRender();
return;
}
const stroke = cssColor(PREVIEW[color] || PREVIEW.primary);
previewPoints.set(
session.vertices.map((v, index) => ({
id: String(index),
pos: { lon: v.lon, lat: v.lat, height: v.height || 0 },
pixelSize: 8,
color: stroke,
outlineColor: [0, 0, 0, 0.6],
outlineWidth: 2,
disableDepthTest: Number.POSITIVE_INFINITY,
})),
);
syncPreviewLine();
setHint(() => drawHint(session));
viewer.scene.requestRender();
requestRender();
};
// ---- vertices from clicks --------------------------------------------
const worldAt = (position) => {
const canvas = viewer.scene.canvas;
const canvas = canvasOf();
const w = canvas.clientWidth || canvas.width || 1;
const h = canvas.clientHeight || canvas.height || 1;
return pickWorldFromScreen(viewer, position.x / w, position.y / h);
@@ -260,11 +285,12 @@ export function initDrawTool({
};
const onMove = (event) => {
if (!session || session.shape === 'pin' || destroyed) return;
const p = worldAt(event.endPosition);
cursor = p
? Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0)
: null;
viewer.scene.requestRender();
// The click's own position is sensor-corrected; the rubber band must
// follow the same point the click would place.
const p = worldAt(event.pickPosition ?? event.endPosition);
cursor = p ? fromDegrees(p.lon, p.lat, p.height || 0) : null;
syncPreviewLine();
requestRender();
};
// ---- finish / cancel -------------------------------------------------
@@ -344,9 +370,7 @@ export function initDrawTool({
t.closest('button, a, select, [role="button"], [role="radio"]')
)
return false;
return (
t === document.body || t === viewer.scene.canvas || t.tagName === 'CANVAS'
);
return t === document.body || t === canvasOf() || t.tagName === 'CANVAS';
};
const onKey = (event) => {
if (!active || destroyed || typingElsewhere(event)) return;
@@ -383,18 +407,15 @@ export function initDrawTool({
function setActive(next) {
if (destroyed || next === active) return active;
if (next) {
lease = claimPointer(DRAW_POINTER_OWNER);
if (!lease) {
// Somebody else is using the pointer — possibly an older instance of
// this same tool that has not finished tearing down. Say so instead of
// half-starting.
setHint(() =>
t('{owner} is using the pointer — close it first.', {
owner: translateKnown(pointerOwnerName(pointerOwner())),
}),
);
return active;
}
// The newest claim takes over: a tool holding the pointer is told and
// turns itself off, and a newer one turns Draw off as if the person had.
const claimed = claimPointer(DRAW_POINTER_OWNER, {
onLost: () => {
if (lease === claimed) setActive(false);
},
});
if (!claimed) return active;
lease = claimed;
}
active = next;
present();
@@ -416,50 +437,29 @@ export function initDrawTool({
}
function bindSceneHandler() {
if (handler) return;
handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(onClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
handler.setInputAction(onMove, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
handler.setInputAction(() => {
void finish();
}, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
// Cesium's Viewer binds BOTH stock click actions on its own handler: the
// single click picks an entity into `viewer.selectedEntity`, the double
// click tracks it. Neither goes through a layer, so neither can be fixed by
// the shared pointer claim — they have to be borrowed outright for the
// session and given back on the way out. Borrowing the single click is what
// stops a vertex placed on a contact from also selecting it.
const stock = viewer.screenSpaceEventHandler;
savedSingleClick =
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null;
savedDoubleClick =
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
null;
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
if (unbindScene) return;
const input = inputFor(viewer);
const held = { lease: () => lease };
const offs = [
input.onPointer('click', onClick, held),
input.onPointer('move', onMove, held),
input.onPointer('dblclick', () => void finish(), held),
// Cesium's Viewer binds BOTH stock click actions on its own handler: the
// single click picks an entity into `viewer.selectedEntity`, the double
// click tracks it. Neither goes through a layer, so neither yields to the
// shared pointer claim — they are suppressed for the session and given
// back on the way out. Suppressing the single click is what stops a
// vertex placed on a contact from also selecting it.
input.suppressStockClicks(),
];
unbindScene = () => offs.forEach((off) => off());
listen(document, 'keydown', onKey, true);
}
function releaseSceneHandler() {
if (handler) {
handler.destroy();
handler = null;
}
if (savedSingleClick) {
viewer.screenSpaceEventHandler.setInputAction(
savedSingleClick,
Cesium.ScreenSpaceEventType.LEFT_CLICK,
);
savedSingleClick = null;
}
if (savedDoubleClick) {
viewer.screenSpaceEventHandler.setInputAction(
savedDoubleClick,
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
);
savedDoubleClick = null;
}
// Drop the keydown listener bound alongside this handler.
unbindScene?.();
unbindScene = null;
// Drop the keydown listener bound alongside the pointer subscriptions.
for (let i = domListeners.length - 1; i >= 0; i -= 1) {
const [target, type, listener, options] = domListeners[i];
if (listener !== onKey) continue;
@@ -608,26 +608,18 @@ export function initDrawTool({
return {
active,
destroyed,
sceneHandler: Boolean(handler),
sceneHandler: Boolean(unbindScene),
domListeners: domListeners.length,
previewDataSources: countPreviewDataSources(viewer),
previewEntities: destroyed ? 0 : dataSource.entities.values.length,
// Every live tool's on this viewer: 2 while one tool lives.
previewSets: livePreviewSets.get(viewer) ?? 0,
previewItems: previewReleased
? 0
: previewLines.size() + previewPoints.size(),
pointerOwner: pointerOwner(),
// The viewer's OWN click actions. While a session is open both are
// borrowed (absent here); after it closes both are back. A harness can
// compare the restored functions by identity with what it captured
// before, which is the only way to prove they were given back rather
// than replaced.
stockSingleClick: Boolean(
viewer.screenSpaceEventHandler?.getInputAction?.(
Cesium.ScreenSpaceEventType.LEFT_CLICK,
),
),
stockDoubleClick: Boolean(
viewer.screenSpaceEventHandler?.getInputAction?.(
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
),
),
// The viewer's own select and follow, which the input port runs: off
// while a session is open, back on after it closes.
stockSingleClick: inputFor(viewer).stockEnabled('select'),
stockDoubleClick: inputFor(viewer).stockEnabled('dblclickFollow'),
};
},
/** Resolves once every deferred teardown step has run. */
@@ -649,18 +641,7 @@ export function initDrawTool({
for (const [target, type, listener, options] of domListeners.splice(0)) {
target.removeEventListener(type, listener, options);
}
previewEntities.length = 0;
dataSource.entities.removeAll();
// Wait for the pending add() before removing: a destroy() in the same
// tick as init would otherwise remove nothing and let the attachment land
// behind it.
attaching = attaching.then(() => {
try {
viewer.dataSources.remove(dataSource, true);
} catch {
/* viewer already disposed — nothing to detach from */
}
});
releasePreview();
document.body.classList.remove('gev-drawing');
hint = '';
present();
@@ -672,13 +653,7 @@ export function initDrawTool({
return api;
}
/** How many draw previews are attached — more than one means a leaked tool. */
function countPreviewDataSources(viewer) {
const sources = viewer?.dataSources;
if (!sources) return 0;
let found = 0;
for (let index = 0; index < sources.length; index += 1) {
if (sources.get(index)?.name === PREVIEW_DATA_SOURCE_NAME) found += 1;
}
return found;
/** `color` at `alpha`. */
function withAlpha(color, alpha) {
return [color[0], color[1], color[2], alpha];
}
+2 -5
View File
@@ -205,11 +205,8 @@ test('draped marks classify onto terrain as well as 3D tiles', () => {
// rendered proof is in scripts/qa-draw-tool.mjs, which counts stroke pixels
// against a keyless server; this stops the constant being narrowed again.
const renderer = read('src/annotations/worldAnnotationRenderer.js');
assert.match(renderer, /const CLASSIFY = Cesium\.ClassificationType\.BOTH;/);
assert.doesNotMatch(
renderer,
/classificationType: Cesium\.ClassificationType\.CESIUM_3D_TILE/,
);
assert.match(renderer, /const CLAMP_TO = 'both';/);
assert.doesNotMatch(renderer, /clampTo: '(tiles|terrain)'/);
});
test('the draw modules are registered for formatting and boundary checks', () => {
+436 -115
View File
@@ -13,6 +13,8 @@ import {
releasePointer,
resetPointerOwnership,
} from '../data/inputOwnership.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
/* ── DOM doubles ───────────────────────────────────────────────────────── */
@@ -68,9 +70,17 @@ class FakeElement {
}
closest(selector) {
// Only what the tool asks: "am I inside an activatable control?"
const activatable = ['button', 'a', 'select', '[role="button"]', '[role="radio"]'];
const activatable = [
'button',
'a',
'select',
'[role="button"]',
'[role="radio"]',
];
if (!activatable.some((part) => selector.includes(part))) return null;
return this.tagName === 'BUTTON' || this.tagName === 'A' || this.tagName === 'SELECT'
return this.tagName === 'BUTTON' ||
this.tagName === 'A' ||
this.tagName === 'SELECT'
? this
: null;
}
@@ -143,39 +153,22 @@ function fakeViewer() {
setInputAction: (action, type) => actions.set(type, action),
removeInputAction: (type) => actions.delete(type),
};
const attached = [];
const pendingAdds = [];
const dataSources = {
get length() {
return attached.length;
},
get: (index) => attached[index],
add(source) {
// Cesium resolves this on a later tick — the whole point of finding 7.
const promise = Promise.resolve().then(() => {
attached.push(source);
return source;
});
pendingAdds.push(promise);
return promise;
},
remove(source) {
const at = attached.indexOf(source);
if (at >= 0) attached.splice(at, 1);
return at >= 0;
},
};
return {
scene: { canvas, requestRender() {} },
screenSpaceEventHandler: stockHandler,
dataSources,
_attached: attached,
_actions: actions,
};
}
function fakeAnnotations() {
const calls = { annotate: [], clear: 0, restyle: [], setHidden: [], frame: [], remove: [] };
const calls = {
annotate: [],
clear: 0,
restyle: [],
setHidden: [],
frame: [],
remove: [],
};
const marks = [];
const listeners = new Set();
const changed = () => listeners.forEach((listener) => listener());
@@ -223,10 +216,21 @@ function fakeAnnotations() {
}
/** Stand up a tool against fresh doubles, with globals restored afterwards. */
function harness({ navigation = null, markActions = [] } = {}) {
function harness({
navigation = null,
beforeInput = () => {},
markActions = [],
} = {}) {
resetPointerOwnership();
const { byId, documentDouble } = fakeDom();
const viewer = fakeViewer();
// The viewer's own actions are bound before its input port takes them.
beforeInput(viewer);
const input = fakeInput(viewer);
// The renderer the tool draws its preview with, drawing in the viewer's canvas.
const { draw, unbind: unbindDraw } = bindFakeDraw(viewer, {
canvas: viewer.scene.canvas,
});
const annotations = fakeAnnotations();
const previousDocument = globalThis.document;
const previousWindow = globalThis.window;
@@ -250,6 +254,7 @@ function harness({ navigation = null, markActions = [] } = {}) {
tool,
shown,
viewer,
draw,
annotations,
byId,
documentDouble,
@@ -257,7 +262,10 @@ function harness({ navigation = null, markActions = [] } = {}) {
controls,
/** A control's change, as the view sends it. */
act: (name, ...args) => controls.actions?.[name]?.(...args),
input,
restore() {
input.destroy();
unbindDraw();
resetPointerOwnership();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
@@ -288,23 +296,42 @@ test('turning Draw on takes a lease and turning it off gives it back', async ()
}
});
test('Draw refuses to start when something else holds the pointer', async () => {
test('Draw takes the pointer from another tool, which is told', async () => {
const h = harness();
try {
const other = claimPointer('directions');
let lost = 0;
claimPointer('directions', { onLost: () => (lost += 1) });
h.act('toggleDraw');
assert.equal(h.tool.active, false, 'it must not half-start');
assert.equal(pointerOwner(), 'directions', 'and must not steal the claim');
// Named by its tool, not by the internal owner id.
assert.equal(
h.shown.view.hint,
'Directions is using the pointer — close it first.',
);
assert.equal(h.tool.diagnostics().sceneHandler, false, 'no handler was bound');
assert.equal(h.tool.active, true, 'the newest claim takes over');
assert.equal(pointerOwner(), 'draw');
assert.equal(lost, 1, 'the other tool is told once');
} finally {
h.restore();
}
});
test('Draw turns off, as if toggled off, when a newer tool takes the pointer', async () => {
const h = harness({
beforeInput(viewer) {
viewer.screenSpaceEventHandler.setInputAction(() => {}, LEFT_CLICK);
},
});
try {
h.act('toggleDraw');
assert.equal(h.tool.diagnostics().stockSingleClick, false);
assert.ok(h.tool.addVertex(10, 20), 'a shape is under way');
const other = claimPointer('directions');
assert.equal(h.tool.active, false);
assert.equal(h.tool.session, null, 'the half-drawn shape is dropped');
assert.equal(h.shown.view.active, false, 'the Draw control reads off');
const after = h.tool.diagnostics();
assert.equal(after.sceneHandler, false, 'its subscriptions are gone');
assert.equal(after.stockSingleClick, true, 'the stock clicks are back');
assert.equal(after.previewItems, 0, 'the preview is cleared');
assert.equal(pointerOwner(), 'directions', 'the newer tool keeps it');
releasePointer(other);
h.act('toggleDraw');
assert.equal(h.tool.active, true, 'and it starts once the pointer is free');
assert.equal(h.tool.active, true, 'and it turns on again when asked');
} finally {
h.restore();
}
@@ -336,30 +363,36 @@ test('a destroyed instance cannot free the pointer its replacement holds', async
}
});
test('both stock viewer click actions are borrowed for the session and given back', async () => {
const h = harness();
test('both stock viewer click actions are held off for the session and given back', async () => {
const stockClick = () => 'viewer picks and selects';
const stockDouble = () => 'viewer tracks';
const h = harness({
beforeInput(viewer) {
viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK);
viewer.screenSpaceEventHandler.setInputAction(
stockDouble,
LEFT_DOUBLE_CLICK,
);
},
});
try {
const stockClick = () => 'viewer picks and selects';
const stockDouble = () => 'viewer tracks';
h.viewer.screenSpaceEventHandler.setInputAction(stockClick, LEFT_CLICK);
h.viewer.screenSpaceEventHandler.setInputAction(stockDouble, LEFT_DOUBLE_CLICK);
assert.equal(h.input.stockEnabled('select'), true);
h.act('toggleDraw');
assert.equal(
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK),
undefined,
h.input.stockEnabled('select'),
false,
"the viewer's own selecting click must not run while drawing",
);
assert.equal(
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK),
undefined,
);
assert.equal(h.input.stockEnabled('dblclickFollow'), false);
h.act('toggleDraw');
assert.equal(h.input.stockEnabled('select'), true);
assert.equal(h.input.stockEnabled('dblclickFollow'), true);
h.input.destroy();
assert.equal(
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_CLICK),
stockClick,
'the exact function is restored, not a replacement',
'the exact function goes back to the viewer, not a replacement',
);
assert.equal(
h.viewer.screenSpaceEventHandler.getInputAction(LEFT_DOUBLE_CLICK),
@@ -380,20 +413,55 @@ test('Enter finishes from the canvas and the label field, never from a focused b
h.tool.addVertex(-97.74, 30.27);
// Enter while the Clear button has keyboard focus means "press Clear".
h.documentDouble.emit('keydown', { key: 'Enter', target: h.element('draw-clear') });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.element('draw-clear'),
});
await Promise.resolve();
assert.equal(
h.annotations.calls.annotate.length,
0,
'a focused button keeps its own Enter',
);
assert.equal(h.tool.session.vertices.length, 3, 'and the shape is untouched');
assert.equal(
h.tool.session.vertices.length,
3,
'and the shape is untouched',
);
// Enter from the page body (the canvas has focus in practice) finishes it.
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.documentDouble.body,
});
await Promise.resolve();
await Promise.resolve();
assert.equal(h.annotations.calls.annotate.length, 1, 'Enter on the map finishes');
assert.equal(
h.annotations.calls.annotate.length,
1,
'Enter on the map finishes',
);
assert.equal(h.annotations.calls.annotate[0].specs[0].type, 'area');
} finally {
h.restore();
}
});
test('Enter on the globe canvas finishes, as after the render failure notice hands focus back', async () => {
const h = harness();
try {
h.act('toggleDraw');
h.tool.setShape('area');
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.tool.addVertex(-97.74, 30.27);
// src/ui/views/panels/RenderFailure.vue focuses the canvas when the globe
// draws again and the control that had focus is gone.
h.documentDouble.emit('keydown', { key: 'Enter', target: h.viewer.scene.canvas });
await Promise.resolve();
await Promise.resolve();
assert.equal(h.annotations.calls.annotate.length, 1, 'Enter on the canvas finishes');
assert.equal(h.annotations.calls.annotate[0].specs[0].type, 'area');
} finally {
h.restore();
@@ -408,21 +476,29 @@ test('the live preview hangs at the height the click landed on', async () => {
h.tool.addVertex(-97.75, 30.26, 187.5);
h.tool.addVertex(-97.74, 30.26, 212.25);
await h.tool.whenSettled();
const source = h.viewer._attached[0] ?? null;
assert.ok(source, 'the preview data source is attached');
const points = source.entities.values.filter((entity) => entity.point);
assert.equal(points.length, 2, 'one preview dot per vertex');
const heights = points.map((entity) => {
const position = entity.position.getValue(Cesium.JulianDate.now());
return Cesium.Cartographic.fromCartesian(position).height;
});
const dots = [...h.draw.sets.values()].find(
(set) => !set.disposed && set.kind === 'points',
);
assert.equal(dots.items.size, 2, 'one preview dot per vertex');
const heights = [...dots.items.values()].map((item) => item.pos.height);
const band = [...h.draw.sets.values()]
.find((set) => !set.disposed && set.kind === 'lines')
.items.get('band');
assert.equal(
band.positions.length,
2,
'the rubber band joins the vertices',
);
assert.equal(band.mode, 'geodesic', 'it follows the globe, not draped');
assert.ok(Math.abs(heights[0] - 187.5) < 0.5, `got ${heights[0]}`);
assert.ok(Math.abs(heights[1] - 212.25) < 0.5, `got ${heights[1]}`);
// …and the finished shape is still flattened, deliberately: the renderer
// drapes, so a height carried further would be discarded out of sight.
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.documentDouble.body,
});
await Promise.resolve();
await Promise.resolve();
const spec = h.annotations.calls.annotate[0].specs[0];
@@ -435,17 +511,60 @@ test('the live preview hangs at the height the click landed on', async () => {
}
});
test('destroy in the same tick as init still removes the preview data source', async () => {
test('the rubber band follows the pointer, closes an area and takes the chosen colour', async () => {
const h = harness();
try {
// Nothing has been attached yet — dataSources.add() resolves later.
assert.equal(h.viewer._attached.length, 0, 'the add is still pending');
await h.tool.destroy();
await Promise.resolve();
const sets = () => [...h.draw.sets.values()].filter((set) => !set.disposed);
const band = () =>
sets()
.find((set) => set.kind === 'lines')
.items.get('band');
h.act('toggleDraw');
h.tool.setShape('area');
h.tool.addVertex(-97.75, 30.26);
assert.equal(band(), undefined, 'one vertex and no pointer draw no band');
h.tool.addVertex(-97.74, 30.26);
h.tool.addVertex(-97.74, 30.27);
assert.equal(
h.viewer._attached.length,
band().positions.length,
4,
'an area of three closes back to its first vertex',
);
assert.deepEqual(band().positions[3], band().positions[0]);
h.tool.setColor('red');
assert.deepEqual(
band().style.color,
[1, 107 / 255, 107 / 255, 0.9],
'the band takes the colour',
);
assert.deepEqual(
band().depthFail,
{ kind: 'dash', color: [139 / 255, 233 / 255, 1, 0.35], length: 16 },
'behind the surface it stays the primary colour, dashed, as before',
);
assert.equal(band().style.kind, 'dash');
assert.equal(band().style.length, 16);
assert.equal(band().widthPx, 3);
h.tool.setShape('pin');
assert.equal(band(), undefined, 'a pin has no rubber band');
} finally {
h.restore();
}
});
test('destroy in the same tick as init disposes the preview sets', async () => {
const h = harness();
try {
const live = () => [...h.draw.sets.values()].filter((set) => !set.disposed);
assert.equal(live().length, 2, 'the rubber band and the vertex dots');
await h.tool.destroy();
assert.equal(live().length, 0, 'nothing is left drawn behind the teardown');
assert.equal(
h.tool.diagnostics().previewSets,
0,
'the preview must not be left attached behind the teardown',
'no live tool draws a preview',
);
} finally {
h.restore();
@@ -469,7 +588,11 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
assert.equal(isPointerFree(), true, 'the pointer is free');
const after = h.tool.diagnostics();
assert.equal(after.destroyed, true);
assert.equal(after.sceneHandler, false, 'the Cesium handler is gone');
assert.equal(
after.sceneHandler,
false,
'the pointer subscriptions are gone',
);
assert.equal(after.domListeners, 0, 'every DOM listener came off');
assert.equal(h.documentDouble.listeners.length, 0, 'including the keydown');
assert.equal(h.controls.actions, null, 'and the controls are disconnected');
@@ -478,8 +601,12 @@ test('destroy releases the pointer, the handler, the listeners and the stock act
stockClick,
'the viewer got its selecting click back',
);
assert.equal(h.viewer._attached.length, 0, 'the preview data source is detached');
assert.equal(h.annotations.listeners.size, 0, 'and it no longer follows the board');
assert.equal(after.previewSets, 0, 'the preview sets are disposed');
assert.equal(
h.annotations.listeners.size,
0,
'and it no longer follows the board',
);
// Idempotent: a second destroy is harmless.
await h.tool.destroy();
@@ -498,7 +625,11 @@ test('Clear wipes the board and the shape in progress', async () => {
h.act('clearDraw');
assert.equal(h.annotations.calls.clear, 1, 'placed marks are removed');
assert.equal(h.tool.session.vertices.length, 0, 'and so is the shape in progress');
assert.equal(
h.tool.session.vertices.length,
0,
'and so is the shape in progress',
);
} finally {
h.restore();
}
@@ -512,7 +643,13 @@ test('the controls choose the shape and colour the next shape is drawn with; it
h.act('setDrawColor', 'amber');
assert.deepEqual(
{ ...h.shown.view, hint: undefined },
{ active: true, shape: 'line', color: 'amber', hint: undefined, marks: [] },
{
active: true,
shape: 'line',
color: 'amber',
hint: undefined,
marks: [],
},
'the view shows what the controls chose',
);
h.act('setDrawColor', 'purple');
@@ -524,7 +661,10 @@ test('the controls choose the shape and colour the next shape is drawn with; it
assert.equal(h.tool.session.vertices.length, 0);
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Enter', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Enter',
target: h.documentDouble.body,
});
await Promise.resolve();
await Promise.resolve();
const spec = h.annotations.calls.annotate[0].specs[0];
@@ -549,12 +689,31 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
try {
const board = h.annotations;
board.marks.push(
{ id: 'a1', type: 'route', manual: true, name: null, label: '950 m', color: 'amber', hidden: false },
{ id: 'a2', type: 'pin', manual: false, label: 'Voice pin', color: 'primary', hidden: false },
{
id: 'a1',
type: 'route',
manual: true,
name: null,
label: '950 m',
color: 'amber',
hidden: false,
},
{
id: 'a2',
type: 'pin',
manual: false,
label: 'Voice pin',
color: 'primary',
hidden: false,
},
);
board.changed();
assert.deepEqual(
h.shown.view.marks.map(({ id, placeholder, hidden }) => ({ id, placeholder, hidden })),
h.shown.view.marks.map(({ id, placeholder, hidden }) => ({
id,
placeholder,
hidden,
})),
[{ id: 'a1', placeholder: 'Line · 950 m', hidden: false }],
'only hand-drawn marks are listed, an unnamed line by its length',
);
@@ -569,7 +728,11 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
]);
assert.deepEqual(board.calls.setHidden, [['a1', true]]);
assert.deepEqual(board.calls.frame, ['a1']);
assert.deepEqual(navigations, ['drawing'], 'fly-to goes through the navigation policy');
assert.deepEqual(
navigations,
['drawing'],
'fly-to goes through the navigation policy',
);
assert.deepEqual(board.calls.remove, ['a1']);
assert.deepEqual(h.shown.view.marks, [], 'the row goes with its mark');
} finally {
@@ -577,7 +740,7 @@ test('each drawn shape is a row whose actions reach the board, and fly-to is a n
}
});
test('an application\'s row actions show on the shapes they are for and run with the shape', async () => {
test("row actions given to the tool show on the shapes they are for and run with the shape", async () => {
const ran = [];
const h = harness({
markActions: [
@@ -601,30 +764,102 @@ test('an application\'s row actions show on the shapes they are for and run with
try {
const board = h.annotations;
board.marks.push(
{ id: 'r1', type: 'area', manual: true, name: 'Strait', color: 'primary', hidden: false, ring: [[29, 41], [29.1, 41], [29.1, 41.1]] },
{ id: 'l1', type: 'route', manual: true, name: null, label: '9 km', color: 'amber', hidden: false, path: [{ lon: 29, lat: 41.05, height: 0 }, { lon: 29.1, lat: 41.05, height: 0 }] },
{ id: 'p1', type: 'pin', manual: true, name: 'Camp', color: 'red', hidden: false },
{
id: 'r1',
type: 'area',
manual: true,
name: 'Strait',
color: 'primary',
hidden: false,
ring: [
[29, 41],
[29.1, 41],
[29.1, 41.1],
],
},
{
id: 'l1',
type: 'route',
manual: true,
name: null,
label: '9 km',
color: 'amber',
hidden: false,
path: [
{ lon: 29, lat: 41.05, height: 0 },
{ lon: 29.1, lat: 41.05, height: 0 },
],
},
{
id: 'p1',
type: 'pin',
manual: true,
name: 'Camp',
color: 'red',
hidden: false,
},
);
board.changed();
assert.deepEqual(
h.shown.view.marks.map(({ id, actions }) => [id, actions]),
[
['r1', [
{ id: 'tag', icon: 'sell', label: 'Tag Strait' },
{ id: 'measure', icon: 'straighten', label: 'Measure Strait' },
]],
[
'r1',
[
{ id: 'tag', icon: 'sell', label: 'Tag Strait' },
{ id: 'measure', icon: 'straighten', label: 'Measure Strait' },
],
],
['l1', [{ id: 'tag', icon: 'sell', label: 'Tag Line · 9 km' }]],
['p1', []],
],
);
assert.equal(h.act('runDrawMarkAction', 'l1', 'tag'), true);
assert.equal(h.act('runDrawMarkAction', 'l1', 'measure'), false, 'a line is not offered an area action');
assert.equal(
h.act('runDrawMarkAction', 'l1', 'measure'),
false,
'a line is not offered an area action',
);
assert.equal(h.act('runDrawMarkAction', 'p1', 'tag'), false);
assert.equal(h.act('runDrawMarkAction', 'gone', 'tag'), false);
assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true);
assert.deepEqual(ran, [
['tag', { id: 'l1', shape: 'line', name: '', title: 'Line · 9 km', geometry: { type: 'LineString', coordinates: [[29, 41.05], [29.1, 41.05]] } }],
['measure', { id: 'r1', shape: 'area', name: 'Strait', title: 'Strait', geometry: { type: 'Polygon', coordinates: [[[29, 41], [29.1, 41], [29.1, 41.1], [29, 41]]] } }],
[
'tag',
{
id: 'l1',
shape: 'line',
name: '',
title: 'Line · 9 km',
geometry: {
type: 'LineString',
coordinates: [
[29, 41.05],
[29.1, 41.05],
],
},
},
],
[
'measure',
{
id: 'r1',
shape: 'area',
name: 'Strait',
title: 'Strait',
geometry: {
type: 'Polygon',
coordinates: [
[
[29, 41],
[29.1, 41],
[29.1, 41.1],
[29, 41],
],
],
},
},
],
]);
} finally {
h.restore();
@@ -634,16 +869,40 @@ test('an application\'s row actions show on the shapes they are for and run with
test('an action that throws is reported and leaves the row alone', async () => {
const h = harness({
markActions: [
{ id: 'boom', icon: 'bolt', label: () => { throw new Error('label'); }, shapes: ['area'], run: () => { throw new Error('run'); } },
{
id: 'boom',
icon: 'bolt',
label: () => {
throw new Error('label');
},
shapes: ['area'],
run: () => {
throw new Error('run');
},
},
],
});
const warn = console.warn;
const warned = [];
console.warn = (...args) => warned.push(args[0]);
try {
h.annotations.marks.push({ id: 'r1', type: 'area', manual: true, name: null, color: 'primary', hidden: false, ring: [[0, 0], [1, 0], [1, 1]] });
h.annotations.marks.push({
id: 'r1',
type: 'area',
manual: true,
name: null,
color: 'primary',
hidden: false,
ring: [
[0, 0],
[1, 0],
[1, 1],
],
});
h.annotations.changed();
assert.deepEqual(h.shown.view.marks[0].actions, [{ id: 'boom', icon: 'bolt', label: 'boom' }]);
assert.deepEqual(h.shown.view.marks[0].actions, [
{ id: 'boom', icon: 'bolt', label: 'boom' },
]);
assert.equal(h.act('runDrawMarkAction', 'r1', 'boom'), false);
assert.deepEqual(warned, ['[draw] boom failed']);
} finally {
@@ -652,7 +911,7 @@ test('an action that throws is reported and leaves the row alone', async () => {
}
});
test('what a row action answers is its row\'s note; the row is busy until then, and a removed shape drops it', async () => {
test("what a row action answers is its row's note; the row is busy until then, and a removed shape drops it", async () => {
const pending = [];
const h = harness({
markActions: [
@@ -661,34 +920,73 @@ test('what a row action answers is its row\'s note; the row is busy until then,
icon: 'straighten',
label: (name) => `Measure ${name}`,
shapes: ['area'],
run: () => new Promise((resolve, reject) => pending.push({ resolve, reject })),
run: () =>
new Promise((resolve, reject) => pending.push({ resolve, reject })),
},
{
id: 'now',
icon: 'bolt',
label: () => 'Now',
shapes: ['area'],
run: () => ' 12 km² ',
},
{
id: 'long',
icon: 'notes',
label: () => 'Long',
shapes: ['area'],
run: () => `${'word '.repeat(60)}end`,
},
{ id: 'now', icon: 'bolt', label: () => 'Now', shapes: ['area'], run: () => ' 12 km² ' },
{ id: 'long', icon: 'notes', label: () => 'Long', shapes: ['area'], run: () => `${'word '.repeat(60)}end` },
],
});
const warn = console.warn;
console.warn = () => {};
try {
const board = h.annotations;
const area = (id) => ({ id, type: 'area', manual: true, name: null, color: 'primary', hidden: false, ring: [[0, 0], [1, 0], [1, 1]] });
const area = (id) => ({
id,
type: 'area',
manual: true,
name: null,
color: 'primary',
hidden: false,
ring: [
[0, 0],
[1, 0],
[1, 1],
],
});
board.marks.push(area('r1'), area('r2'));
board.changed();
const row = (id) => h.shown.view.marks.find((entry) => entry.id === id);
assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), true);
assert.deepEqual([row('r1').busy, row('r1').note], [false, '12 km²']);
h.act('runDrawMarkAction', 'r1', 'long');
assert.ok(row('r1').note.length <= 200 && row('r1').note.endsWith('word…'), 'a long note is cut at a word');
assert.ok(
row('r1').note.length <= 200 && row('r1').note.endsWith('word…'),
'a long note is cut at a word',
);
assert.equal(h.act('runDrawMarkAction', 'r1', 'measure'), true);
assert.deepEqual([row('r1').busy, row('r1').note], [true, '']);
assert.equal(h.act('runDrawMarkAction', 'r1', 'now'), false, 'a busy row takes no second press');
assert.equal(
h.act('runDrawMarkAction', 'r1', 'now'),
false,
'a busy row takes no second press',
);
pending[0].resolve('412 km², 38 km of edge');
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual([row('r1').busy, row('r1').note], [false, '412 km², 38 km of edge']);
assert.deepEqual(
[row('r1').busy, row('r1').note],
[false, '412 km², 38 km of edge'],
);
h.act('runDrawMarkAction', 'r1', 'measure');
pending[1].reject(new Error('refused'));
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual([row('r1').busy, row('r1').note], [false, ''], 'a failure clears the note');
assert.deepEqual(
[row('r1').busy, row('r1').note],
[false, ''],
'a failure clears the note',
);
h.act('runDrawMarkAction', 'r2', 'measure');
board.marks.splice(1, 1);
board.changed();
@@ -697,7 +995,11 @@ test('what a row action answers is its row\'s note; the row is busy until then,
assert.equal(row('r2'), undefined);
board.marks.push(area('r2'));
board.changed();
assert.deepEqual([row('r2').busy, row('r2').note], [false, ''], 'a late answer never reaches a shape that went');
assert.deepEqual(
[row('r2').busy, row('r2').note],
[false, ''],
'a late answer never reaches a shape that went',
);
} finally {
console.warn = warn;
h.restore();
@@ -710,30 +1012,49 @@ test('Backspace on the page removes the last vertex', () => {
h.act('toggleDraw');
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Backspace', target: h.documentDouble.body });
h.documentDouble.emit('keydown', {
key: 'Backspace',
target: h.documentDouble.body,
});
assert.equal(h.tool.session.vertices.length, 1);
} finally {
h.restore();
}
});
test('keys on the shape list are the list\'s, not the drawing\'s', async () => {
test("keys on the shape list are the list's, not the drawing's", async () => {
const h = harness();
try {
const listButton = new FakeElement('BUTTON');
listButton.closest = (selector) => (selector === '#draw-mark-list' ? {} : null);
listButton.closest = (selector) =>
selector === '#draw-mark-list' ? {} : null;
const elsewhere = new FakeElement('INPUT', 'location-search');
h.act('toggleDraw');
h.tool.addVertex(-97.75, 30.26);
h.tool.addVertex(-97.74, 30.26);
h.documentDouble.emit('keydown', { key: 'Escape', target: listButton });
assert.equal(h.tool.session.vertices.length, 2, 'Escape in the list keeps the shape');
assert.equal(
h.tool.session.vertices.length,
2,
'Escape in the list keeps the shape',
);
assert.equal(h.tool.active, true, 'and keeps Draw on');
h.documentDouble.emit('keydown', { key: 'Enter', target: elsewhere });
await Promise.resolve();
assert.equal(h.annotations.calls.annotate.length, 0, 'another field keeps its Enter');
h.documentDouble.emit('keydown', { key: 'Escape', target: h.documentDouble.body });
assert.equal(h.tool.session.vertices.length, 0, 'Escape on the page drops the open shape');
assert.equal(
h.annotations.calls.annotate.length,
0,
'another field keeps its Enter',
);
h.documentDouble.emit('keydown', {
key: 'Escape',
target: h.documentDouble.body,
});
assert.equal(
h.tool.session.vertices.length,
0,
'Escape on the page drops the open shape',
);
} finally {
h.restore();
}
+106 -104
View File
@@ -5,6 +5,9 @@ import { createPinia } from 'pinia';
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
import { createHybridAnnotationRenderer } from './hybridAnnotationRenderer.js';
import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
import { bindFakeCesiumCredits, fakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
/** A hybrid renderer whose screen board is presented to its own store. */
function hybridWithBoard(viewer) {
@@ -89,11 +92,41 @@ function installBrowserGlobals(t) {
});
}
/**
* `viewer` with the fake scene's camera, query, frame and draw ports and the
* fake credits bound over it as one renderer.
*/
function withScenePorts(viewer) {
const { unbind, ...ports } = bindFakeCesiumScene(viewer);
unbind();
bindRenderer(viewer, { ...ports, credits: fakeCesiumCredits(viewer) });
return ports.draw;
}
/** What the world renderer draws, each item of its live sets (of `kind`). */
function worldItems(draw, kind) {
const items = [];
for (const record of draw.sets.values())
if (
!record.disposed &&
record.spec.id.startsWith('annotations:') &&
(!kind || record.kind === kind)
)
items.push(...record.items.values());
return items;
}
/** Surface heights the scene samples: `height(lon, lat)` in degrees. */
function sampleHeights(scene, height) {
scene.sampleHeightSupported = true;
scene.sampleHeight = (carto) =>
height(Cesium.Math.toDegrees(carto.longitude), Cesium.Math.toDegrees(carto.latitude));
}
/** A viewer whose scene/camera is just enough for both sub-renderers. */
function fakeViewer(lon, lat) {
const credits = new Set();
const camera = cameraLookingAt(lon, lat);
const dataSources = [];
const frames = controlledFrames();
const scene = {
camera,
@@ -107,31 +140,19 @@ function fakeViewer(lon, lat) {
scene.renderRequests += 1;
},
};
return {
dataSources,
frames,
viewer: {
credits,
creditDisplay: {
addStaticCredit: (credit) => credits.add(credit),
removeStaticCredit: (credit) => credits.delete(credit),
},
scene,
camera,
trackedEntity: null,
dataSources: {
add(dataSource) {
dataSources.push(dataSource);
return dataSource;
},
remove(dataSource) {
const index = dataSources.indexOf(dataSource);
if (index >= 0) dataSources.splice(index, 1);
return index >= 0;
},
},
const viewer = {
credits,
creditDisplay: {
addStaticCredit: (credit) => credits.add(credit),
removeStaticCredit: (credit) => credits.delete(credit),
},
scene,
camera,
canvas: scene.canvas,
trackedEntity: null,
};
const draw = withScenePorts(viewer);
return { draw, frames, viewer };
}
function controlledFrames() {
@@ -192,7 +213,6 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
});
const camera = cameraLookingAt(-99, 31);
const dataSources = [];
const frames = controlledFrames();
const scene = {
camera,
@@ -206,19 +226,12 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
const viewer = {
scene,
camera,
canvas: scene.canvas,
trackedEntity: null,
dataSources: {
add(dataSource) {
dataSources.push(dataSource);
return dataSource;
},
remove(dataSource) {
const index = dataSources.indexOf(dataSource);
if (index >= 0) dataSources.splice(index, 1);
return index >= 0;
},
},
};
// The screen board projects through the renderer's camera and query; the
// world renderer draws through its draw port.
const { draw } = bindFakeCesiumScene(viewer);
const { store, renderer } = hybridWithBoard(viewer);
const anno = {
id: 'anno-hybrid-fb3',
@@ -235,8 +248,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
renderer.add(anno);
const [before] = annotationGroups(store);
assert.equal(childrenWithClass(before, 'gev-anno-ring').length, 2);
assert.equal(dataSources.length, 1);
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
const ring = [
[-106, 25],
@@ -268,10 +280,10 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
assert.equal(dot.attrs.cx, expectedWindow.x.toFixed(1));
assert.equal(dot.attrs.cy, expectedWindow.y.toFixed(1));
assert.deepEqual(centroid, { lon: -100.8, lat: 29.4, height: 0 }, 'closed-ring vertex mean stays pinned');
assert.equal(dataSources[0].entities.values.length, 2, 'world area adds one fill and one outline');
assert.equal(dataSources[0].entities.values.filter((entity) => entity.polygon).length, 1);
assert.equal(dataSources[0].entities.values.filter((entity) => entity.polyline).length, 1);
assert.equal(Object.hasOwn(anno, '_entities'), false, 'world entity state stays on the inherited proxy');
assert.equal(worldItems(draw).length, 2, 'world area adds one fill and one outline');
assert.equal(worldItems(draw, 'shapes').length, 1);
assert.equal(worldItems(draw, 'lines').length, 1);
assert.equal(Object.hasOwn(anno, '_draw'), false, 'world draw state stays on the inherited proxy');
const outer = [
[-99, 31],
[-98.999, 31],
@@ -298,33 +310,26 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
buildingHeight: 20,
};
const completion = renderer.add(building);
assert.equal(dataSources[0].entities.values.length, 2, 'building geometry waits for all probes');
assert.equal(worldItems(draw).length, 2, 'building geometry waits for all probes');
for (let frame = 0; frame < 8; frame += 1) frames.emit();
assert.equal((await completion).status, 'installed');
const added = dataSources[0].entities.values.slice(2);
const fills = added.filter(
(entity) => entity.polygon && entity.polygon.fill?.getValue() !== false,
);
const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:'));
assert.equal(
fills.length,
2,
'every building part gets a classification volume',
'every building part gets a volume',
);
assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1);
assert.equal(fills[1].polygon.hierarchy.getValue().holes.length, 0);
assert.equal(fills[0].geometry.rings.length, 2, 'the first with its hole');
assert.equal(fills[1].geometry.rings.length, 1);
assert.deepEqual(fills[0].fill, fills[1].fill, 'parts share the fill colour');
assert.equal(
fills[0].polygon.material,
fills[1].polygon.material,
'parts share the fill material',
);
assert.equal(
added.filter((entity) => entity.polyline).length,
worldItems(draw, 'lines').filter((item) => item.id.startsWith('base:')).length,
3,
'all outer and hole outlines are retained',
);
renderer.remove(building);
assert.equal(
dataSources[0].entities.values.length,
worldItems(draw).length,
2,
'multipart removal leaves only the earlier area',
);
@@ -341,7 +346,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry'
test('a sub-renderer throw mid-add leaves state the rollback can still remove', (t) => {
installBrowserGlobals(t);
const { viewer, dataSources } = fakeViewer(-99, 31);
const { viewer, draw } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
const anno = {
@@ -369,26 +374,26 @@ test('a sub-renderer throw mid-add leaves state the rollback can still remove',
};
assert.throws(() => renderer.add(anno), /screen insert failed/);
assert.equal(dataSources[0].entities.values.length, 2, 'the world drape is already live');
assert.equal(worldItems(draw).length, 2, 'the world drape is already live');
assert.equal(annotationGroups(store).length, 0, 'the half-built screen group detached itself');
// The engine's rollback path — it must reach the partial state by id.
renderer.remove(anno);
assert.equal(dataSources[0].entities.values.length, 0, 'partial world state must be released');
assert.equal(worldItems(draw).length, 0, 'partial world state must be released');
// …and the id is free again: a retry draws ONE mark, not a second one over
// an orphan nothing owns.
renderer.add(anno);
assert.equal(dataSources[0].entities.values.length, 2, 'the retry draws exactly one world drape');
assert.equal(worldItems(draw).length, 2, 'the retry draws exactly one world drape');
assert.equal(annotationGroups(store).length, 1, 'and exactly one screen caption');
renderer.remove(anno);
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
renderer.destroy();
});
test('a release that throws keeps the mark addressable for a retry cleanup', (t) => {
installBrowserGlobals(t);
const { viewer, dataSources } = fakeViewer(-99, 31);
const { viewer, draw } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
const anno = {
@@ -404,7 +409,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
};
renderer.add(anno);
assert.equal(dataSources[0].entities.values.length, 2);
assert.equal(worldItems(draw).length, 2);
assert.equal(annotationGroups(store).length, 1);
// The world route releases fine, then the screen release fails part-way
@@ -412,7 +417,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
const workingSetTimeout = globalThis.window.setTimeout;
globalThis.window.setTimeout = () => { throw new Error('teardown scheduling failed'); };
assert.throws(() => renderer.remove(anno), /teardown scheduling failed/);
assert.equal(dataSources[0].entities.values.length, 0, 'the world route did release');
assert.equal(worldItems(draw).length, 0, 'the world route did release');
assert.equal(annotationGroups(store).length, 1, 'the screen route did NOT — that is the orphan');
// Dropping the routing entry here would make that orphan permanently
@@ -420,7 +425,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
globalThis.window.setTimeout = workingSetTimeout;
renderer.remove(anno);
assert.equal(annotationGroups(store).length, 0, 'the retry cleanup must reach the orphan');
assert.equal(dataSources[0].entities.values.length, 0, 'without double-releasing the world route');
assert.equal(worldItems(draw).length, 0, 'without double-releasing the world route');
// Fully released now — a third call is inert.
renderer.remove(anno);
@@ -430,7 +435,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t)
test('a world add that fails mid-way leaves its landed entities removable', (t) => {
installBrowserGlobals(t);
const { viewer, dataSources } = fakeViewer(-99, 31);
const { viewer, draw } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
const anno = {
@@ -446,25 +451,23 @@ test('a world add that fails mid-way leaves its landed entities removable', (t)
};
// The draped fill lands; the outline throws (bad geometry / lost context).
const entities = dataSources[0].entities;
const realAdd = entities.add.bind(entities);
let addsLeft = 1;
entities.add = (options) => {
if (addsLeft <= 0) throw new Error('entity add failed');
addsLeft -= 1;
return realAdd(options);
const realLines = draw.lines;
draw.lines = (spec) => {
const set = realLines(spec);
set.set = () => { throw new Error('draw failed'); };
return set;
};
assert.throws(() => renderer.add(anno), /entity add failed/);
assert.equal(entities.values.length, 1, 'one entity landed before the failure');
assert.throws(() => renderer.add(anno), /draw failed/);
assert.equal(worldItems(draw).length, 1, 'one item landed before the failure');
entities.add = realAdd;
draw.lines = realLines;
renderer.remove(anno);
assert.equal(entities.values.length, 0,
'the rollback must see the entities that landed before the throw');
assert.equal(worldItems(draw).length, 0,
'the rollback must see the items that landed before the throw');
renderer.add(anno);
assert.equal(entities.values.length, 2, 'the retry draws a complete mark');
assert.equal(worldItems(draw).length, 2, 'the retry draws a complete mark');
assert.equal(annotationGroups(store).length, 1);
renderer.destroy();
});
@@ -475,7 +478,7 @@ function workTrace() {
test('buildings share one probe per frame and preserve probe geometry, filtering and fallback', async (t) => {
installBrowserGlobals(t);
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
const { viewer, draw, frames } = fakeViewer(-99, 31);
const renderer = createHybridAnnotationRenderer(viewer);
t.after(() => renderer.destroy());
const first = buildingAnnotation('sampled-building');
@@ -485,15 +488,12 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
showOsmCredit(viewer, otherOwner);
const probes = [];
const outcomes = [-500, 120, 30, null, new Error('tile unavailable'), 60, 9001, 90];
viewer.scene.clampToHeight = (position) => {
const cartographic = Cesium.Cartographic.fromCartesian(position);
const lon = Cesium.Math.toDegrees(cartographic.longitude);
const lat = Cesium.Math.toDegrees(cartographic.latitude);
sampleHeights(viewer.scene, (lon, lat) => {
probes.push([lon, lat]);
const outcome = outcomes[probes.length - 1];
if (outcome instanceof Error) throw outcome;
return outcome == null ? undefined : Cesium.Cartesian3.fromDegrees(lon, lat, outcome);
};
return outcome == null ? undefined : outcome;
});
// Suppress screen points: these counts concern the eight outside-building
// probes, not the screen renderer's separate anchor-height sampling.
const firstTrace = workTrace();
@@ -510,14 +510,14 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
const firstCompletion = renderer.add(first, { pendingVisible: false, workTrace: firstTrace });
const secondCompletion = renderer.add(second, { pendingVisible: false, workTrace: secondTrace });
assert.equal(probes.length, 0, 'enqueue must not probe synchronously');
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1,
'pending outlines add no tile credit to the other owner');
for (let frame = 0; frame < 16; frame += 1) {
const before = probes.length;
frames.emit();
assert.equal(probes.length, before + 1, 'the two buildings share one total probe budget');
if (frame < 7) assert.equal(dataSources[0].entities.values.length, 0, 'no partial world parts');
if (frame < 7) assert.equal(worldItems(draw).length, 0, 'no partial world parts');
}
const [installed, fallback] = await Promise.all([firstCompletion, secondCompletion]);
assert.equal(installed.status, 'installed');
@@ -540,8 +540,9 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
const detail = parent.detail;
assert.equal(detail.index, index);
assert.equal(detail.status, trace === firstTrace ? 'recorded' : 'missing');
// The fourth probe finds nothing and the fifth throws: both are misses.
assert.equal(detail.clampResult,
trace === firstTrace && index === 4 ? 'threw' : 'returned');
trace === firstTrace && index !== 3 && index !== 4 ? 'hit' : 'missed');
assert.ok(Number.isFinite(detail.clampStart) && Number.isFinite(detail.clampEnd));
assert.ok(parent.start <= detail.clampStart && detail.clampStart <= detail.clampEnd && detail.clampEnd <= parent.end);
if (index === 7) {
@@ -571,10 +572,10 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
assert.ok(Math.abs(probes[index + 8][1] - probes[index][1]) < 1e-10);
}
assert.equal(new Set(probes.slice(0, 8).map((point) => point.join(','))).size, 8);
const fills = dataSources[0].entities.values.filter((entity) => entity.polygon?.fill?.getValue() !== false && entity.polygon);
const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:'));
assert.equal(fills.length, 2);
assert.ok(Math.abs(fills[0].polygon.height.getValue() - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3');
assert.ok(Math.abs(fills[1].polygon.height.getValue() - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback');
assert.ok(Math.abs(fills[0].geometry.rings[0][0].height - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3');
assert.ok(Math.abs(fills[1].geometry.rings[0][0].height - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback');
const afterCompletion = probes.length;
frames.emit();
assert.equal(probes.length, afterCompletion, 'completion releases the sampler');
@@ -597,7 +598,7 @@ test('a building queued behind others gets its full budget on a slow device', as
t.mock.method(globalThis.performance, 'now', () => now);
const { viewer, frames } = fakeViewer(-99, 31);
const renderer = createHybridAnnotationRenderer(viewer);
viewer.scene.clampToHeight = (position) => position;
sampleHeights(viewer.scene, () => 0);
const traces = [workTrace(), workTrace(), workTrace()];
const completions = [0, 0.01, 0.02].map((offset, index) =>
renderer.add(buildingAnnotation(`queued-${index}`, offset), {
@@ -626,10 +627,10 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks
installBrowserGlobals(t);
t.mock.timers.enable({ apis: ['setTimeout'] });
t.after(() => t.mock.timers.reset());
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
const { viewer, draw, frames } = fakeViewer(-99, 31);
const renderer = createHybridAnnotationRenderer(viewer);
let probeCount = 0;
viewer.scene.clampToHeight = (position) => { probeCount += 1; return position; };
sampleHeights(viewer.scene, () => { probeCount += 1; return 0; });
const cancelled = buildingAnnotation('cancelled-building');
const cancelledTrace = workTrace();
const cancelledCompletion = renderer.add(cancelled, { pendingVisible: false, workTrace: cancelledTrace });
@@ -671,7 +672,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks
assert.equal(viewer.credits.size, 0);
for (const listener of savedTimeout) listener();
assert.equal(probeCount, 1, 'saved callbacks cannot revive timed-out tasks');
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
const pending = buildingAnnotation('destroyed-building');
const destruction = renderer.add(pending, { pendingVisible: false });
@@ -681,7 +682,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks
for (const listener of savedDestroy) listener();
t.mock.timers.tick(2000);
assert.equal(probeCount, 1);
assert.equal(dataSources.length, 0, 'destroy removes the owned data source');
assert.ok([...draw.sets.values()].every((record) => record.disposed), 'destroy lets every set go');
assert.equal(frames.size, 0, 'destroy removes frame listeners');
assert.equal(viewer.credits.size, 0);
});
@@ -690,7 +691,7 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy
installBrowserGlobals(t);
t.mock.timers.enable({ apis: ['setTimeout'] });
t.after(() => t.mock.timers.reset());
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
const { viewer, draw, frames } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const anno = { ...buildingAnnotation('pending-upgrade'), ring: null, label: 'Building' };
renderer.add(anno);
@@ -703,15 +704,15 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy
assert.equal(after.key, before.key);
assert.equal(others.length, 0);
assert.ok(childrenWithClass(after, 'gev-anno-ring').length > 0, 'the honest pending point is not converted');
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
frames.emit();
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(worldItems(draw).length, 0);
renderer.destroy();
});
test('an asynchronous caption-conversion throw rolls back multipart world geometry and remains removable', async (t) => {
installBrowserGlobals(t);
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
const { viewer, draw, frames } = fakeViewer(-99, 31);
const { store, renderer } = hybridWithBoard(viewer);
const anno = { ...buildingAnnotation('caption-failure'), ring: null, label: 'Building' };
renderer.add(anno);
@@ -724,7 +725,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet
// Frame projection is still ordinary pending-point work. Arm the failure
// only after sampling completes, before its promise converts the caption.
for (let frame = 0; frame < 8; frame += 1) frames.emit();
assert.ok(dataSources[0].entities.values.length > 0, 'multipart world geometry landed before caption conversion');
assert.ok(worldItems(draw).length > 0, 'multipart world geometry landed before caption conversion');
assert.equal(viewer.credits.size, 2, 'credit belongs to the committed world proxy');
// The caption conversion fails when it presents the converted mark.
const publish = store.publish;
@@ -747,7 +748,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet
assert.equal(captionTrace.slices.filter(s => s.phase === 'ground-step').length, 8);
assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-complete').length, 1);
assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-rollback').length, 1);
assert.equal(dataSources[0].entities.values.length, 0, 'all classification, cage and outline parts roll back');
assert.equal(worldItems(draw).length, 0, 'all classification, cage and outline parts roll back');
assert.equal(viewer.credits.size, 0, 'caption rollback releases that same proxy');
assert.equal(annotationGroups(store).length, 1, 'failed screen cleanup remains addressable');
globalThis.window.setTimeout = workingSetTimeout;
@@ -781,6 +782,7 @@ test('a deadline passed during caption conversion leaves a drawn pending point',
const live = annotationGroups(store).filter((mark) => !mark.className?.includes('gev-out'));
assert.equal(live.length, 1);
assert.ok(childrenWithClass(live[0], 'gev-anno-ring').length > 0, 'the pending point still draws');
assert.notEqual(live[0].display, 'none', 'and is on screen');
renderer.remove(anno);
renderer.destroy();
});
+11 -8
View File
@@ -18,6 +18,7 @@ import {
outlineQueryText,
} from './outlineRungs.js';
import { createAnnotationResolver } from './resolver.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { decodeOpenFreeMapOutlineTile } from '../sources/openFreeMapOutlines.js';
import { createNominatimOutlineClient } from '../sources/nominatimOutlines.js';
import { createApplicationRequestServices } from '../services/requests.js';
@@ -924,15 +925,17 @@ const PLACES = {
},
};
const viewerAt = (lat, lon, height = 4000) => ({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
longitude: (lon * Math.PI) / 180,
height,
// The resolver reads the camera through the renderer's camera port.
const viewerAt = (lat, lon, height = 4000) =>
bindFakeCesiumCamera({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
longitude: (lon * Math.PI) / 180,
height,
},
},
},
});
});
test('default settings: outline, street and building asks send nothing to Overpass', async (t) => {
const prior = process.env.OVERPASS_UPSTREAMS;
+7 -4
View File
@@ -5,11 +5,14 @@ import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
import { createAnnotationResolver } from './resolver.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { polygonsContain } from '../data/adminBoundaries.js';
import { streetFootprint } from './outlineRungs.js';
import { bindFakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs';
function viewerAt(lat, lon, height = 20_000) {
return {
// The resolver reads the camera through the renderer's camera port.
return bindFakeCesiumCamera({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
@@ -17,7 +20,7 @@ function viewerAt(lat, lon, height = 20_000) {
height,
},
},
};
});
}
/** A resolver whose boundary lookups and geocoder record every call. */
@@ -180,10 +183,10 @@ test('a geocoded city or neighborhood upgrades to the bundled outline', async ()
const credits = [];
const cancelled = await city.resolve(
'Austin',
{
bindFakeCesiumCredits({
...viewerAt(39, -100, 5_000_000),
creditDisplay: { addStaticCredit: (credit) => credits.push(credit) },
},
}),
{ signal: controller.signal },
);
const pending = cancelled.resolveOutline();
+43 -71
View File
@@ -14,7 +14,6 @@ import {
nearestPointOnLines,
} from '../sources/featureGeometry.js';
import { defaultGeospatial } from '../search/defaults.js';
import * as Cesium from 'cesium';
import { lookupNeighborhoodRing } from '../data/neighborhoodPolygons.js';
import {
lookupNaturalRegionOutline,
@@ -45,6 +44,9 @@ import {
import { createOutlineRungs } from './outlineRungs.js';
import { unavailablePlaceSearch } from '../search/placeSearch.js';
import { isPickedWorldPosition } from '../data/scenePick.js';
import { heightsOf } from '../queries/heights.js';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
import { canvasOf, findCamera, findQuery } from '../render/rendererOf.js';
/** Prepare only local dateline outlines for planar admission and centering. */
function localOutlineFrame(fp) {
@@ -178,7 +180,7 @@ export function createAnnotationResolver({
* Resolve a single annotation target to a normalized world anchor.
*
* @param {object} opts
* @param {Cesium.Viewer} opts.viewer
* @param {object} opts.viewer The viewer the renderer is bound to.
* @param {string} [opts.target] Place name to geocode.
* @param {number} [opts.latitude] Explicit latitude (wins over target).
* @param {number} [opts.longitude] Explicit longitude.
@@ -2216,11 +2218,10 @@ export function createAnnotationResolver({
*/
function viewportProximity(viewer) {
try {
const carto = viewer?.camera?.positionCartographic;
if (!carto) return null;
const lat = Cesium.Math.toDegrees(carto.latitude);
const lon = Cesium.Math.toDegrees(carto.longitude);
const radiusKm = Math.max((carto.height / 1000) * 3, 5);
const pose = viewer ? findCamera(viewer)?.pose() : null;
if (!pose) return null;
const { lat, lon } = pose;
const radiusKm = Math.max((pose.height / 1000) * 3, 5);
if (![lat, lon, radiusKm].every(Number.isFinite)) return null;
return { lat, lon, radiusKm };
} catch {
@@ -2231,12 +2232,12 @@ export function createAnnotationResolver({
/** Exported for searchAndFlyTo (src/locations.js), which shares this bias. */
function viewportBias(viewer) {
try {
const rect = viewer?.camera?.computeViewRectangle?.();
const rect = viewer ? findCamera(viewer)?.viewRectangle() : null;
if (!rect) return null;
const swLat = Cesium.Math.toDegrees(rect.south).toFixed(4);
const swLng = Cesium.Math.toDegrees(rect.west).toFixed(4);
const neLat = Cesium.Math.toDegrees(rect.north).toFixed(4);
const neLng = Cesium.Math.toDegrees(rect.east).toFixed(4);
const swLat = rect.south.toFixed(4);
const swLng = rect.west.toFixed(4);
const neLat = rect.north.toFixed(4);
const neLng = rect.east.toFixed(4);
if ([swLat, swLng, neLat, neLng].some((v) => v === 'NaN')) return null;
return `${swLat},${swLng}|${neLat},${neLng}`;
} catch {
@@ -2289,58 +2290,39 @@ export function createAnnotationResolver({
* name the place, and we anchor the mark to the actual world point under it.
*/
function pickWorldFromScreen(viewer, nx, ny) {
const scene = viewer?.scene;
if (!scene) return null;
const canvas = scene.canvas;
const query = viewer ? findQuery(viewer) : null;
// The renderer's canvas; a viewer with no renderer bound, its own.
const canvas = canvasOf(viewer);
if (!query || !canvas) return null;
const w = canvas.clientWidth || canvas.width || 0;
const h = canvas.clientHeight || canvas.height || 0;
if (!w || !h) return null;
const px = Math.max(0, Math.min(1, nx)) * w;
const py = Math.max(0, Math.min(1, ny)) * h;
const pos = new Cesium.Cartesian2(px, py);
// Each stage is validated before it is accepted: a depth pick over empty sky
// can return a NaN or centre-of-the-earth Cartesian, and converting one of
// those throws inside Cesium. A degenerate pick IS a missed pick, so it falls
// through to the next stage and ultimately to the caller's null.
let cart = null;
if (
scene.pickPositionSupported &&
typeof scene.pickPosition === 'function'
) {
// can return a NaN or centre-of-the-earth position, and converting one of
// those throws inside the renderer. A degenerate pick IS a missed pick, so it
// falls through to the next stage and ultimately to the caller's null.
const attempt = (pick) => {
try {
cart = scene.pickPosition(pos);
return pick();
} catch {
cart = null;
return null;
}
}
if (
!isPickedWorldPosition(cart) &&
typeof viewer.camera.pickEllipsoid === 'function'
) {
try {
cart = viewer.camera.pickEllipsoid(pos, Cesium.Ellipsoid.WGS84);
} catch {
cart = null;
}
}
if (
!isPickedWorldPosition(cart) &&
typeof viewer.camera.getPickRay === 'function'
) {
try {
const ray = viewer.camera.getPickRay(pos);
cart = ray ? scene.globe?.pick(ray, scene) || null : null;
} catch {
cart = null;
}
}
};
// The depth pick answers null where the renderer has no depth support.
let cart = attempt(() => query.pickPosition(px, py));
if (!isPickedWorldPosition(cart))
cart = attempt(() => query.pickEllipsoid(px, py));
if (!isPickedWorldPosition(cart))
cart = attempt(() => query.pickGlobe(query.pickRay(px, py)));
if (!isPickedWorldPosition(cart)) return null;
const carto = Cesium.Cartographic.fromCartesian(cart);
const carto = toLonLatH(cart);
if (!carto) return null;
return {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
lat: carto.lat,
lon: carto.lon,
// The height the pick actually landed on — a roof, a hillside, or 0 on
// the ellipsoid. Callers that only want a coordinate ignore it; the draw
// tool's live preview needs it, or the rubber band sinks to sea level
@@ -2355,28 +2337,18 @@ export function createAnnotationResolver({
* the tiles for that spot aren't loaded we fall back to the ellipsoid (0).
*/
function sampleGroundHeight(viewer, lon, lat) {
const scene = viewer?.scene;
if (!scene) return 0;
try {
if (
scene.clampToHeightSupported &&
typeof scene.clampToHeight === 'function'
) {
const carto = Cesium.Cartographic.fromDegrees(lon, lat);
const surface = Cesium.Cartographic.toCartesian(carto);
const clamped = scene.clampToHeight(surface);
if (clamped) {
const h = Cesium.Cartographic.fromCartesian(clamped).height;
if (Number.isFinite(h)) return h;
}
if (!viewer) return 0;
const heights = heightsOf(viewer);
// A miss is tiles not ready: fall through to the terrain, then 0.
if (heights.supported().clamp) {
const clamped = heights.clampNow(fromDegrees(lon, lat, 0));
if (clamped) {
const h = toLonLatH(clamped)?.height;
if (Number.isFinite(h)) return h;
}
} catch {
/* tiles not ready — fall through */
}
const globeHeight = scene.globe?.getHeight?.(
Cesium.Cartographic.fromDegrees(lon, lat),
);
return Number.isFinite(globeHeight) && globeHeight > 0 ? globeHeight : 0;
const globeHeight = heights.now({ lon, lat }, { against: 'terrain' });
return globeHeight !== null && globeHeight > 0 ? globeHeight : 0;
}
function shortLabel(formattedAddress) {
+78 -65
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { followedOf } from '../data/followed.js';
import { getOverlayPaintRect } from '../overlays/worldOverlay.js';
import {
getActiveTrackedReadoutId,
@@ -8,6 +8,15 @@ import { t } from '../i18n/index.js';
import { nextTick } from 'vue';
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { heightsOf } from '../queries/heights.js';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
import { distance } from '../geo/vector.js';
import {
canvasOf as sceneCanvasOf,
findCamera,
findFrame,
findQuery,
} from '../render/rendererOf.js';
/** A label whose detailed outline could not be resolved. */
function outlineUnavailableLabel(label) {
@@ -78,11 +87,13 @@ export function createScreenAnnotationRenderer(
const arrowMarkers = new Map();
let viewBox = null;
const scene = viewer.scene;
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
scene.camera.positionWC,
);
// The eye this frame is projected from (the camera port's pose), and the
// query port and canvas it is projected through, read once per pass.
let pose = null;
let passQuery = null;
let passCanvas = null;
// The renderer's canvas; a viewer with no renderer bound, its own.
const canvasOf = () => sceneCanvasOf(viewer);
const records = new Map(); // anno.id -> { key, anno, group, parts }
const leaving = new Map(); // key -> a removed mark's record while it fades out
const byKey = new Map(); // key -> record, live or fading
@@ -91,8 +102,6 @@ export function createScreenAnnotationRenderer(
let published = '';
// Only the renderer whose board the store shows may change or remove it.
const shown = () => store.board?.owner === owner;
const scratch = new Cesium.Cartesian2();
const scratchDir = new Cesium.Cartesian3();
// Per-point ground height cache. Marks must sit on the real surface, not at
// sea level — otherwise in elevated cities (Austin ~150 m) they project
// underground and parallax sinks them at oblique angles. Sampled once the
@@ -121,7 +130,7 @@ export function createScreenAnnotationRenderer(
// Re-project every annotation each rendered frame so marks stay glued to the
// world. postRender runs after the camera/tiles update, so positions are exact.
const onPostRender = () => projectAll();
scene.postRender.addEventListener(onPostRender);
const removePostRender = findFrame(viewer)?.on('postRender', onPostRender);
function color(anno) {
return PALETTE[anno.color] || PALETTE.primary;
@@ -141,15 +150,12 @@ export function createScreenAnnotationRenderer(
return cached.h;
}
try {
if (
scene.clampToHeightSupported &&
typeof scene.clampToHeight === 'function'
) {
const c = scene.clampToHeight(
Cesium.Cartesian3.fromDegrees(lon, lat, 0),
);
const heights = heightsOf(viewer);
if (heights.supported().clamp) {
// A miss is tiles not ready.
const c = heights.clampNow(fromDegrees(lon, lat, 0));
if (c) {
const h = Cesium.Cartographic.fromCartesian(c).height;
const h = toLonLatH(c)?.height;
if (Number.isFinite(h) && h > -430 && h < 9000) {
heightCache.set(key, { h, settled: true, gen: projGen });
trimHeightCache();
@@ -278,7 +284,7 @@ export function createScreenAnnotationRenderer(
}
// Record the mark BEFORE it reaches the board, then unwind on any throw
// from here down (projectAll reaches into Cesium and can fail on a lost
// from here down (projectAll reaches into the renderer and can fail on a lost
// context). Previously a throw past the insert left an ORPHANED mark: the
// engine's rollback only deletes its own map entry, so the next annotate
// of the same geometry stacked a fresh mark on top of the corpse.
@@ -363,26 +369,27 @@ export function createScreenAnnotationRenderer(
// Anchor at the real surface height (cached + validated), so marks sit on
// the ground/building instead of at sea level. The settle-once cache keeps
// it stable (no per-frame jitter that earlier broke nearby projections).
const world = Cesium.Cartesian3.fromDegrees(
lon,
lat,
groundHeight(lon, lat),
);
const world = fromDegrees(lon, lat, groundHeight(lon, lat));
if (!pose) return null;
// Reject points behind the camera (they produce wrapped/extreme coords).
Cesium.Cartesian3.subtract(world, scene.camera.positionWC, scratchDir);
if (Cesium.Cartesian3.dot(scratchDir, scene.camera.directionWC) <= 0)
const eye = pose.position;
const look = pose.direction;
if (
(world.x - eye.x) * look.x +
(world.y - eye.y) * look.y +
(world.z - eye.z) * look.z <=
0
)
return null;
// Reject points beyond the globe horizon.
if (!occluder.isPointVisible(world)) return null;
const win = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
world,
scratch,
);
const query = passQuery;
if (!query || query.isOccluded(world)) return null;
const win = query.project(world);
if (!win || !Number.isFinite(win.x) || !Number.isFinite(win.y)) return null;
// Reject absurd off-screen projections (anchor not in view).
const w = scene.canvas.clientWidth || scene.canvas.width;
const h = scene.canvas.clientHeight || scene.canvas.height;
const canvas = passCanvas;
const w = canvas.clientWidth || canvas.width;
const h = canvas.clientHeight || canvas.height;
if (
!allowOffscreen &&
(win.x < -w || win.x > 2 * w || win.y < -h || win.y > 2 * h)
@@ -399,9 +406,13 @@ export function createScreenAnnotationRenderer(
// from the host's ACTUAL painted rectangle after final layout; the billboard extent
// is unioned for aircraft/satellites that also own a native tracked graphic.
const TRACKED_BBOX_MARGIN = 8; // px buffer added around the footprint
const TRACKED_FADE_EASE = 0.22; // per-frame ease toward hidden(0) / visible(1)
// Ease toward hidden(0) / visible(1): this share of the gap closes in one
// 60 Hz frame (about 200 ms to settle), scaled by elapsed time so the fade
// takes as long at any refresh rate.
const TRACKED_FADE_EASE = 0.22;
const TRACKED_FADE_FRAME_MS = 1000 / 60;
let trackedFadeAtMs = -Infinity;
const TRACKED_HYSTERESIS_PX = 18; // dead-band so the overlap test can't flip-flop
const _scratchTrackedWin = new Cesium.Cartesian2();
// Evaluate a NearFarScalar (billboard scaleByDistance) at a camera distance.
function nearFarValue(nfs, dist) {
@@ -422,32 +433,23 @@ export function createScreenAnnotationRenderer(
let top = painted?.y;
let bottom = painted ? painted.y + painted.h : undefined;
const ent = viewer.trackedEntity;
const now = Cesium.JulianDate.now();
const followed = followedOf(viewer);
const displayPosition = followed?.displayPosition;
const world =
typeof ent?.gevDisplayPosition === 'function'
? ent.gevDisplayPosition()
: null;
const win = world
? Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
world,
_scratchTrackedWin,
)
: null;
typeof displayPosition === 'function' ? displayPosition() : null;
const win = world ? (passQuery?.project(world) ?? null) : null;
// Billboard box — centered on the anchor, magnified by scaleByDistance.
const bb = ent?.billboard;
if (bb && win && Number.isFinite(win.x) && Number.isFinite(win.y)) {
const baseW = bb.width?.getValue?.(now) ?? 28;
const baseH = bb.height?.getValue?.(now) ?? 28;
// Billboard box — centered on the anchor, magnified by scaleByDistance, from
// the size the tracking layer recorded for its sprite.
const sprite = followed?.sprite;
if (sprite && win && Number.isFinite(win.x) && Number.isFinite(win.y)) {
const baseW = sprite.width ?? 28;
const baseH = sprite.height ?? 28;
let scale = 1;
const sbd = bb.scaleByDistance?.getValue?.(now);
if (sbd)
scale = nearFarValue(
sbd,
Cesium.Cartesian3.distance(scene.camera.positionWC, world),
);
const sbd = sprite.scaleByDistance;
// No eye to measure from: the sprite's own size.
if (sbd && pose)
scale = nearFarValue(sbd, distance(pose.position, world));
const hw = (baseW * scale) / 2;
const hh = (baseH * scale) / 2;
const bbLeft = win.x - hw;
@@ -476,14 +478,17 @@ export function createScreenAnnotationRenderer(
return;
}
projGen += 1; // new frame: entries touched below are "hot" and survive trimming
pose = findCamera(viewer)?.pose() ?? null;
passQuery = findQuery(viewer);
passCanvas = canvasOf();
const trackedRect = trackedEntityRect();
occluder.cameraPosition = scene.camera.positionWC;
const h = scene.canvas.clientHeight || scene.canvas.height;
const w = scene.canvas.clientWidth || scene.canvas.width;
const canvas = passCanvas;
const h = canvas.clientHeight || canvas.height;
const w = canvas.clientWidth || canvas.width;
viewBox = `0 0 ${w} ${h}`;
// Shrink point-marker geometry as the camera pulls back (declutter the blob).
const mScale = markScale(
viewer.camera.positionCartographic?.height ?? 1000,
Number.isFinite(pose?.height) ? pose.height : 1000,
);
for (const rec of records.values()) {
@@ -677,6 +682,14 @@ export function createScreenAnnotationRenderer(
// safe and not jarring.
function fadeTracked(trackedRect) {
if (!shown()) return;
const nowMs = performance.now();
// A gap longer than a slow frame means the fade was not running (nothing
// followed): it starts again as from one 60 Hz frame.
const gapMs = nowMs - trackedFadeAtMs;
const stepMs = gapMs >= 0 && gapMs <= 100 ? gapMs : TRACKED_FADE_FRAME_MS;
trackedFadeAtMs = nowMs;
const ease =
1 - Math.pow(1 - TRACKED_FADE_EASE, stepMs / TRACKED_FADE_FRAME_MS);
let changed = false;
for (const rec of records.values()) {
const { anno, group } = rec;
@@ -705,10 +718,10 @@ export function createScreenAnnotationRenderer(
}
}
const target = overlapping ? 0 : 1;
const next = cur + (target - cur) * TRACKED_FADE_EASE;
const next = cur + (target - cur) * ease;
rec._trackedFade = Math.abs(next - target) < 0.02 ? target : next;
// The base alpha applies unless faded. (The CSS `transition: opacity` was
// removed from .gev-anno so this per-frame JS ease is the ONLY easing —
// removed from .gev-anno so this JS ease is the ONLY easing —
// previously the two fought and produced an opacity oscillation.)
const opacity = String(
(anno.alpha ?? 1) * (rec._trackedFade !== 1 ? rec._trackedFade : 1),
@@ -821,7 +834,7 @@ export function createScreenAnnotationRenderer(
function destroy() {
try {
scene.postRender.removeEventListener(onPostRender);
removePostRender?.();
} catch {
/* torn down */
}
@@ -6,7 +6,19 @@ import { createApp, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
import ScreenAnnotations from '../ui/views/panels/ScreenAnnotations.vue';
import { createScreenAnnotationRenderer } from './screenAnnotationRenderer.js';
import { createScreenAnnotationRenderer as createRenderer } from './screenAnnotationRenderer.js';
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
import { rendererOf } from '../render/rendererOf.js';
/**
* The renderer over a viewer double with the camera, query and frame ports
* bound over it (once per double), and the scene's canvas as the viewer's.
*/
function createScreenAnnotationRenderer(viewer, options) {
if (!rendererOf(viewer)) bindFakeCesiumScene(viewer);
viewer.canvas ??= viewer.scene?.canvas;
return createRenderer(viewer, options);
}
// happy-dom does not lay out SVG; every element measures as a 40 x 16 box.
for (const type of [globalThis.SVGElement, globalThis.SVGGraphicsElement]) {
@@ -53,7 +65,7 @@ function sceneFor(camera, extra = {}) {
return {
camera,
canvas: { clientWidth: 800, clientHeight: 600, width: 800, height: 600 },
clampToHeightSupported: false,
sampleHeightSupported: false,
postRender: { addEventListener() {}, removeEventListener() {} },
...extra,
};
@@ -173,14 +185,13 @@ test('outline upgrade preserves the existing SVG group identity', async (t) => {
const sampledAnchors = [];
const scene = sceneFor(camera, {
canvas: { clientWidth: 1280, clientHeight: 720, width: 1280, height: 720 },
clampToHeightSupported: true,
clampToHeight(world) {
const cartographic = Cesium.Cartographic.fromCartesian(world);
sampleHeightSupported: true,
sampleHeight(cartographic) {
sampledAnchors.push([
Number(Cesium.Math.toDegrees(cartographic.longitude).toFixed(4)),
Number(Cesium.Math.toDegrees(cartographic.latitude).toFixed(4)),
]);
return world;
return 0;
},
});
const renderer = createScreenAnnotationRenderer(
@@ -216,7 +227,7 @@ test('outline upgrade preserves the existing SVG group identity', async (t) => {
assert.ok(after === before, 'the rendered group is mutated, not replaced');
assert.deepEqual(sampledAnchors.at(-1), [-97.5, 31.2], 'the existing group projects from the re-seated anchor');
assert.equal(groups().length, 1);
assert.equal(after.querySelector('.gev-anno-ring'), null, 'reticle rings are removed in place');
assert.equal(after.querySelector('.gev-anno-ring') === null, true, 'reticle rings are removed in place');
assert.ok(after.querySelector('.gev-anno-callout') === callout, 'the original callout remains in the group');
assert.ok(after.querySelector('.gev-anno-dot') === dot, 'the anchor dot remains in the group');
assert.ok(svg());
@@ -330,7 +341,7 @@ test('a removed mark fades out, then leaves the board', async (t) => {
assert.equal(group.isConnected, false);
renderer.destroy();
await settle();
assert.equal(document.querySelector('.gev-screen-whiteboard'), null);
assert.equal(document.querySelector('.gev-screen-whiteboard') === null, true);
});
// ── Partial-add unwind (review round 2) ───────────────────────────────────────
File diff suppressed because it is too large. Load diff
+423 -45
View File
@@ -1,70 +1,448 @@
// A mark hidden from Draw's list leaves the globe whole: every entity it put
// there is taken out on sync and comes back when shown, and the line's
// flowing stroke, which keeps its own colour, follows the mark's alpha.
// The world renderer draws each mark through the draw port, in sets of its
// own: a hidden mark has its sets hidden on sync and shown again; a fading
// mark takes its new colours in place; every kind draws what it drew as
// entities, draped and clamped to terrain and tiles alike.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as C from 'cesium';
import {
FlowMaterialProperty,
createWorldAnnotationRenderer,
} from './worldAnnotationRenderer.js';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { createWorldAnnotationRenderer } from './worldAnnotationRenderer.js';
const noop = () => {};
function viewer(t) {
for (const name of ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']) {
const original = globalThis[name];
globalThis[name] = class {};
t.after(() => { if (original === undefined) delete globalThis[name]; else globalThis[name] = original; });
}
const before = globalThis.document;
globalThis.document = { addEventListener: noop, removeEventListener: noop };
t.after(() => { if (before === undefined) delete globalThis.document; else globalThis.document = before; });
/**
* A viewer with a fake draw port, frame, camera and query bound. The camera
* stands at `camera.height`; `preRender()` runs the frame's preRender
* listeners, `emit()` its postRender ones.
*/
function viewer(t, { heights = () => null } = {}) {
const draw = fakeDrawPort();
const frames = new Set();
const before = new Set();
const v = { requests: 0 };
const frame = {
on(phase, cb) {
const listeners =
phase === 'postRender' ? frames : phase === 'preRender' ? before : null;
if (!listeners) return () => {};
listeners.add(cb);
return () => listeners.delete(cb);
},
requestRender() {
v.requests += 1;
},
};
const camera = { height: 2000, pose: () => ({ height: camera.height }) };
const query = { sampleHeightNow: (point) => heights(point) };
const unbind = bindRenderer(v, { draw, frame, query, camera });
t.after(unbind);
return {
creditDisplay: { addStaticCredit: noop, removeStaticCredit: noop },
entities: new C.EntityCollection(),
dataSources: new C.DataSourceCollection(),
camera: { moveEnd: new C.Event(), positionCartographic: { height: 1000 } },
scene: { requestRender: noop, canvas: { addEventListener: noop, removeEventListener: noop }, preRender: new C.Event(),
primitives: { add: (p) => p, remove: noop }, screenSpaceCameraController: { enableInputs: true } },
v,
draw,
frames,
before,
camera,
emit: () => [...frames].forEach((cb) => cb()),
preRender: () => [...before].forEach((cb) => cb()),
};
}
const marks = () => [
{ id: 'route', type: 'route', color: 'amber', alpha: 1, anchor: { lat: 0, lon: 0 }, path: [{ lat: 0, lon: 0 }, { lat: 0.01, lon: 0.01 }] },
{ id: 'area', type: 'area', color: 'green', alpha: 1, anchor: { lat: 0.005, lon: 0.005 }, ring: [[0, 0], [0.01, 0], [0.01, 0.01], [0, 0]] },
{ id: 'pin', type: 'pin', color: 'primary', alpha: 1, anchor: { lat: 0.02, lon: 0.02 } },
{
id: 'route',
type: 'route',
color: 'amber',
alpha: 1,
anchor: { lat: 0, lon: 0 },
path: [
{ lat: 0, lon: 0 },
{ lat: 0.01, lon: 0.01 },
],
},
{
id: 'area',
type: 'area',
color: 'green',
alpha: 1,
anchor: { lat: 0.005, lon: 0.005 },
ring: [
[0, 0],
[0.01, 0],
[0.01, 0.01],
[0, 0],
],
},
{
id: 'pin',
type: 'pin',
color: 'primary',
alpha: 1,
anchor: { lat: 0.02, lon: 0.02 },
},
];
test('a hidden mark has every entity taken off on sync, and back when shown', (t) => {
const renderer = createWorldAnnotationRenderer(viewer(t));
/** The live sets a mark draws into. */
const setsOf = (draw, anno) =>
[...draw.sets.values()].filter(
(record) =>
!record.disposed && record.spec.id.startsWith(`${anno._draw.prefix}:`),
);
test('each mark draws in sets of its own; a hidden one has them hidden on sync, and back when shown', (t) => {
const { v, draw } = viewer(t);
const renderer = createWorldAnnotationRenderer(v);
const [route, area, pin] = marks();
for (const anno of [route, area, pin]) renderer.add(anno);
const shown = (anno) => anno._entities.map((entity) => entity.show);
for (const anno of [route, area, pin]) assert.ok(anno._entities.length > 0, anno.id);
for (const anno of [route, area, pin])
assert.ok(setsOf(draw, anno).length > 0, anno.id);
const shown = (anno) => setsOf(draw, anno).map((record) => record.show);
route.hidden = true;
area.hidden = true;
renderer.sync();
assert.ok(shown(route).every((show) => show === false), 'the line is off');
assert.ok(shown(area).every((show) => show === false), 'the area is off');
assert.ok(shown(pin).every((show) => show === true), 'a visible mark stays');
assert.ok(
shown(route).every((show) => show === false),
'the line is off',
);
assert.ok(
shown(area).every((show) => show === false),
'the area is off',
);
assert.ok(
shown(pin).every((show) => show === true),
'a visible mark stays',
);
route.hidden = false;
renderer.sync();
assert.ok(shown(route).every((show) => show === true), 'the line is back');
assert.ok(
shown(route).every((show) => show === true),
'the line is back',
);
const areaSets = setsOf(draw, area);
renderer.remove(area);
assert.ok(
areaSets.every((record) => record.disposed),
'a removed mark lets its sets go',
);
renderer.sync();
assert.equal(area._entities, null, 'a removed mark is no longer synced');
renderer.destroy();
assert.equal(
[...draw.sets.values()].filter((record) => !record.disposed).length,
0,
);
});
test('a fading mark takes its new colours in place, its pulses with them', (t) => {
const { v, draw } = viewer(t);
const renderer = createWorldAnnotationRenderer(v);
const [route, area] = marks();
renderer.add(route);
renderer.add(area);
const line = () => [...setsOf(draw, route)[0].items.values()][0];
const fill = () =>
setsOf(draw, area)
.find((r) => r.kind === 'shapes')
.items.get('fill:0');
assert.ok(Math.abs(line().style.color[3] - 0.95) < 1e-9);
assert.ok(Math.abs(fill().fill[3] - 0.2) < 1e-9);
route.alpha = 0.5;
area.alpha = 0.5;
renderer.sync();
assert.ok(Math.abs(line().style.color[3] - 0.475) < 1e-9, 'fading');
assert.ok(Math.abs(fill().fill[3] - 0.1) < 1e-9);
assert.deepEqual(
[fill().animate.from, fill().animate.to].map((a) => Math.round(a * 1000)),
[60, 100],
'its pulse swings between 60% and all of its alpha',
);
route.alpha = 0;
renderer.sync();
assert.equal(line().style.color[3], 0, 'faded out: nothing painted');
renderer.destroy();
});
test('the line\'s flowing stroke follows its mark\'s alpha', () => {
let alpha = 1;
const material = new FlowMaterialProperty('#ffb547', () => alpha);
assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.95) < 1e-9);
alpha = 0;
assert.equal(material.getValue(null, {}).color.alpha, 0, 'hidden: nothing painted');
alpha = 0.5;
assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.475) < 1e-9, 'fading');
assert.equal(new FlowMaterialProperty('#fff').getValue(null, {}).color.alpha, 0.95, 'no alpha source: opaque as before');
test('every kind draws as it did: draped on terrain and tiles alike, rings by camera height, pulses', (t) => {
const { v, draw } = viewer(t);
const renderer = createWorldAnnotationRenderer(v);
const [route, area, pin] = marks();
const synth = { ...area, id: 'synth', synthesized: true };
const arrow = {
id: 'arrow',
type: 'arrow',
color: 'red',
alpha: 1,
anchor: { lon: 0, lat: 0 },
to: { lon: 0.01, lat: 0 },
};
const label = {
id: 'label',
type: 'label',
color: 'amber',
alpha: 1,
anchor: { lon: 0.03, lat: 0 },
};
for (const anno of [route, area, pin, synth, arrow, label])
renderer.add(anno);
const items = (anno, kind) => [
...(setsOf(draw, anno)
.find((r) => r.kind === kind)
?.items.values() ?? []),
];
for (const record of [...draw.sets.values()])
assert.equal(record.spec.clampTo, 'both');
const [flow] = items(route, 'lines');
assert.equal(flow.mode, 'draped');
assert.equal(flow.widthPx, 9);
assert.deepEqual(
{ ...flow.style, color: undefined },
{ kind: 'flow', color: undefined, repeat: 64, duty: 0.46, speed: 0.55 },
);
const [areaFill] = items(area, 'shapes');
assert.equal(areaFill.height, 'clampGround');
assert.equal(areaFill.animate.property, 'alpha');
assert.ok(Math.abs(areaFill.animate.periodMs - (2 * Math.PI) / 0.005) < 1e-9);
const [areaLine] = items(area, 'lines');
assert.deepEqual(
[areaLine.widthPx, areaLine.style.kind, areaLine.style.power],
[6, 'glow', 0.35],
);
const [synthLine] = items(synth, 'lines');
assert.deepEqual(
[synthLine.style.kind, synthLine.style.length],
['dash', 24],
);
assert.ok(
Math.abs(items(synth, 'shapes')[0].fill[3] - 0.1) < 1e-9,
'an approximate area is fainter',
);
const [arrowLine] = items(arrow, 'lines');
assert.deepEqual(
[arrowLine.mode, arrowLine.widthPx, arrowLine.style.kind],
['draped', 16, 'arrow'],
);
const [ring] = items(pin, 'shapes');
assert.equal(ring.geometry.semiMajor, 60, '3% of the camera height');
assert.equal(ring.geometry.semiMinor, ring.geometry.semiMajor);
const [marker] = items(pin, 'points');
assert.deepEqual(
[
marker.pixelSize,
marker.height,
marker.outlineWidth,
marker.disableDepthTest,
],
[14, 'clampGround', 3, Infinity],
);
assert.equal(items(label, 'shapes').length, 0, 'a label has no ring');
assert.equal(items(label, 'points')[0].pixelSize, 8);
renderer.destroy();
});
test('target rings follow the camera height, sent again only when the radius changes, and catch up once shown', (t) => {
const { v, draw, camera, preRender, before } = viewer(t);
const renderer = createWorldAnnotationRenderer(v);
const [, , pin] = marks();
const other = { ...pin, id: 'pin2', anchor: { lat: 0.03, lon: 0.03 } };
renderer.add(pin);
renderer.add(other);
const ringOf = (anno) =>
setsOf(draw, anno)
.find((r) => r.kind === 'shapes')
.items.get('ring');
// Writes to the rings' sets since they were drawn.
const shapeSets = [pin, other].map((anno) =>
setsOf(draw, anno).find((r) => r.kind === 'shapes'),
);
const upserts = {
get length() {
return shapeSets.reduce((n, record) => n + record.writes - 1, 0);
},
};
assert.equal(ringOf(pin).geometry.semiMajor, 60);
assert.equal(before.size, 1, 'one listener for every ring');
// The camera has not moved: nothing is sent.
preRender();
assert.equal(upserts.length, 0);
// It climbs: both rings are sent at the new radius, once.
camera.height = 4000;
preRender();
preRender();
assert.equal(upserts.length, 2);
assert.equal(ringOf(pin).geometry.semiMajor, 120);
assert.equal(ringOf(pin).geometry.semiMinor, 120);
assert.equal(ringOf(other).geometry.semiMajor, 120);
// A change under 0.1% sends nothing.
camera.height = 4002;
preRender();
assert.equal(upserts.length, 2);
// Held within 14 m and 170 m.
camera.height = 1e6;
preRender();
assert.equal(ringOf(pin).geometry.semiMajor, 170);
camera.height = 10;
preRender();
assert.equal(ringOf(pin).geometry.semiMajor, 14);
// A hidden mark waits, and catches up when shown.
other.hidden = true;
renderer.sync();
camera.height = 3000;
preRender();
assert.equal(ringOf(pin).geometry.semiMajor, 90);
assert.equal(ringOf(other).geometry.semiMajor, 14, 'hidden: not sent');
other.hidden = false;
renderer.sync();
assert.equal(ringOf(other).geometry.semiMajor, 90, 'shown: caught up');
// The last ring gone, the listener goes with it.
renderer.remove(pin);
renderer.remove(other);
assert.equal(before.size, 0);
renderer.destroy();
});
test('a building waits for its ground probes, then draws a pulsing column, a cage and a draped base', async (t) => {
const { v, draw, emit, frames } = viewer(t, { heights: () => 150 });
const renderer = createWorldAnnotationRenderer(v);
const ring = [
[0, 0],
[0.001, 0],
[0.001, 0.001],
[0, 0.001],
[0, 0],
];
const anno = {
id: 'b',
type: 'area',
color: 'amber',
alpha: 1,
footprintKind: 'building',
buildingHeight: 40,
anchor: { lon: 0.0005, lat: 0.0005, height: 200 },
ring,
};
const done = renderer.add(anno);
assert.equal(frames.size, 1, 'probing on the frames');
assert.equal(
setsOf(draw, anno).length,
0,
'nothing until its ground is known',
);
for (let i = 0; i < 8; i++) emit();
assert.equal((await done).status, 'installed');
assert.equal(frames.size, 0, 'done probing');
const shapes = [
...setsOf(draw, anno)
.find((r) => r.kind === 'shapes')
.items.values(),
];
const volume = shapes.find((s) => s.id === 'volume:0');
assert.equal(volume.extrudeHeight, 150 + 40 + 24);
assert.equal(volume.geometry.rings[0][0].height, 147);
assert.equal(volume.height, 'absolute');
const cage = shapes.find((s) => s.id === 'cage:0');
assert.equal(cage.outlineOnly, true);
assert.ok(cage.geometry.rings[0].length <= 14);
const [base] = setsOf(draw, anno)
.find((r) => r.kind === 'lines')
.items.values();
assert.deepEqual(
[base.mode, base.widthPx, base.style.kind, base.style.power],
['draped', 3, 'glow', 0.25],
);
renderer.destroy();
});
test('each kind paints the alphas it painted as entities, at full alpha', (t) => {
const { v, draw } = viewer(t, { heights: () => 150 });
const renderer = createWorldAnnotationRenderer(v);
const [route, area, pin] = marks();
const synth = { ...area, id: 'synth', synthesized: true };
const arrow = {
id: 'arrow',
type: 'arrow',
color: 'red',
alpha: 1,
anchor: { lon: 0, lat: 0 },
to: { lon: 0.01, lat: 0 },
};
const ring = Array.from({ length: 40 }, (_, i) => [
0.0005 + 0.0004 * Math.cos((i / 40) * 2 * Math.PI),
0.0005 + 0.0004 * Math.sin((i / 40) * 2 * Math.PI),
]);
const building = {
id: 'b',
type: 'area',
color: 'amber',
alpha: 1,
footprintKind: 'building',
buildingHeight: 40,
anchor: { lon: 0.0005, lat: 0.0005, height: 200 },
ring,
};
for (const anno of [route, area, pin, synth, arrow]) renderer.add(anno);
renderer.add(building, { sampledGroundHeight: 150 });
const items = (anno, kind) => [
...(setsOf(draw, anno)
.find((r) => r.kind === kind)
?.items.values() ?? []),
];
const alpha = (c) => Math.round(c[3] * 1000) / 1000;
assert.equal(alpha(items(route, 'lines')[0].style.color), 0.95);
assert.equal(alpha(items(area, 'lines')[0].style.color), 1);
assert.equal(alpha(items(synth, 'lines')[0].style.color), 0.95);
assert.equal(alpha(items(arrow, 'lines')[0].style.color), 0.95);
assert.equal(alpha(items(pin, 'shapes')[0].fill), 0.38);
const marker = items(pin, 'points')[0];
assert.deepEqual(
[alpha(marker.color), alpha(marker.outlineColor)],
[1, 0.95],
);
assert.deepEqual(marker.outlineColor.slice(0, 3), [1, 1, 1]);
const [volume, cage] = items(building, 'shapes');
assert.equal(alpha(volume.fill), 0.45);
assert.equal(alpha(cage.outline), 0.32);
assert.equal(
Math.round(cage.animate.from * 1000) / 1000,
0.192,
'the cage pulses too',
);
assert.equal(cage.geometry.rings[0].length, 14, 'decimated to 14');
assert.equal(alpha(items(building, 'lines')[0].style.color), 0.7);
renderer.destroy();
});
test('a mark removed and added again draws afresh; two renderers on one viewer keep apart', (t) => {
const { v, draw } = viewer(t);
const first = createWorldAnnotationRenderer(v);
const second = createWorldAnnotationRenderer(v);
const [route, area] = marks();
first.add(route);
const prefix = route._draw.prefix;
first.remove(route);
assert.doesNotThrow(() => first.add(route));
assert.notEqual(route._draw.prefix, prefix, 'fresh sets');
assert.doesNotThrow(() => second.add(area));
assert.ok(
!area._draw.prefix.startsWith(
route._draw.prefix.split(':').slice(0, 2).join(':') + ':',
),
);
// Added again as another kind, its old sets go.
const kinds = () =>
setsOf(draw, route)
.map((r) => r.kind)
.sort();
assert.deepEqual(kinds(), ['lines']);
Object.assign(route, { type: 'pin', path: undefined });
first.add(route);
assert.deepEqual(kinds(), ['points', 'shapes']);
assert.doesNotThrow(() => first.remove(null));
first.destroy();
second.destroy();
assert.equal(route._draw, null);
first.add(route);
assert.equal(route._draw, null, 'a destroyed renderer draws nothing more');
assert.equal([...draw.sets.values()].filter((r) => !r.disposed).length, 0);
});
+109 -38
View File
@@ -2,20 +2,74 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { createApplication } from './application.js';
import { installTrackpadPinchRelay } from '../render/cesium/ctrlWheelZoom.js';
import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js';
import * as Cesium from 'cesium';
import {
installFreeLookHeightLimit,
installGlobeInViewRecovery,
installTrackpadPinchZoom,
} from './viewer.js';
import {
FREE_LOOK_MAX_HEIGHT_METERS,
globeFrameShare,
globeOutOfFrame,
lookAngleWithinFrame,
lookStepLosesGlobe,
} from '../globeInView.js';
import { installFreeLookHeightLimit } from '../render/cesium/freeLookLimit.js';
import { installGlobeInViewRecovery } from './globeInViewRecovery.js';
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../globeInView.js';
import * as globeInView from '../globeInView.js';
import { createCesiumCamera } from '../render/cesium/camera.js';
import { bindRenderer } from '../render/rendererOf.js';
import { entityFollowTarget } from '../data/followed.js';
/** The camera port bound over each real Cesium camera a test makes. */
const cameraPorts = new WeakMap();
/**
* Bind `viewer` the Cesium renderer's own camera port over its real camera,
* with the camera's own `moveStart` and `moveEnd` so a test raises them, and
* a frame port that counts render requests on the scene.
*/
function bindCameraPorts(viewer) {
const { camera, scene } = viewer;
const noEvent = { addEventListener: () => () => {} };
const real = createCesiumCamera({
scene: {
postUpdate: noEvent,
preUpdate: noEvent,
get screenSpaceCameraController() {
return scene.screenSpaceCameraController;
},
requestRender: () => scene.requestRender?.(),
},
camera,
report: (error) => {
throw error;
},
}).port;
const port = Object.create(real, {
on: { value: (event, cb) => camera[event].addEventListener(cb) },
});
cameraPorts.set(camera, port);
bindRenderer(viewer, {
camera: port,
get canvas() {
return scene.canvas;
},
frame: {
on: () => () => {},
requestRender: () => scene.requestRender?.(),
},
});
}
// The frame measures take a camera pose; these take the test's camera.
const poseOf = (camera) => cameraPorts.get(camera).pose();
const LOOKS = {
lookUp: 'up',
lookDown: 'down',
lookLeft: 'left',
lookRight: 'right',
};
const globeFrameShare = (camera, options) =>
globeInView.globeFrameShare(poseOf(camera), options);
const globeOutOfFrame = (camera, options) =>
globeInView.globeOutOfFrame(poseOf(camera), options);
const lookAngleWithinFrame = (camera, look, angle, options) =>
globeInView.lookAngleWithinFrame(poseOf(camera), LOOKS[look], angle, options);
const lookStepLosesGlobe = (camera, look, angle, options) =>
globeInView.lookStepLosesGlobe(poseOf(camera), LOOKS[look], angle, options);
const phases = ['Scene', 'Controls', 'Data', 'Tools'];
function fixture(overrides = {}) {
@@ -235,8 +289,9 @@ test('the separate viewer export imports without constructing a browser viewer',
});
test('the viewer gets the starry sky as an option, which keeps the Sun and Moon', async () => {
const { applicationViewerOptions } = await import('./viewer.js');
const { StarrySky } = await import('../sky/starrySky.js');
const { applicationViewerOptions } =
await import('../render/cesium/applicationViewer.js');
const { StarrySky } = await import('../render/cesium/starrySky.js');
const creditContainer = {};
const options = applicationViewerOptions(creditContainer);
// CesiumWidget skips scene.sun and scene.moon when skyBox is false.
@@ -300,14 +355,13 @@ function pinchFixture({ zoomEventTypes } = {}) {
return { viewer, controller, container, handlers, relayed, createEvent };
}
test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs', () => {
test('the trackpad pinch relay leaves the zoom bindings and plain or line-mode wheels alone', () => {
const original = [1, 2, 3];
const f = pinchFixture({ zoomEventTypes: original });
const dispose = installTrackpadPinchZoom(f.viewer, {
const dispose = installTrackpadPinchRelay(f.viewer, {
createWheelEvent: (_type, init) => f.createEvent(init),
});
assert.deepEqual(f.controller.zoomEventTypes.slice(0, 3), original);
assert.equal(f.controller.zoomEventTypes.length, 4);
assert.equal(f.controller.zoomEventTypes, original);
const plain = f.createEvent({ deltaY: 2 });
f.container.emit(plain);
@@ -325,7 +379,7 @@ test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs
test('trackpad pinch relays pixel deltas once with bounded amplification', () => {
const f = pinchFixture({ zoomEventTypes: [1, 2, 3] });
installTrackpadPinchZoom(f.viewer, {
installTrackpadPinchRelay(f.viewer, {
createWheelEvent: (_type, init) => f.createEvent(init),
});
@@ -345,7 +399,7 @@ test('trackpad pinch relays pixel deltas once with bounded amplification', () =>
test('trackpad pinch falls back to the original event when relay construction fails', () => {
const f = pinchFixture({ zoomEventTypes: [1, 2, 3] });
installTrackpadPinchZoom(f.viewer, {
installTrackpadPinchRelay(f.viewer, {
createWheelEvent() {
throw new Error('unsupported');
},
@@ -382,7 +436,10 @@ function freeLookFixture({ enableLook = true, height = 0 } = {}) {
test('free look follows camera height and is restored on dispose', () => {
const f = freeLookFixture({ height: 500 });
const dispose = installFreeLookHeightLimit(f.viewer);
const dispose = installFreeLookHeightLimit(
f.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
assert.equal(f.controller.enableLook, true);
f.frame(FREE_LOOK_MAX_HEIGHT_METERS + 1);
@@ -402,7 +459,10 @@ test('free look follows camera height and is restored on dispose', () => {
test('drags that start on the stars orbit above the free-look height', () => {
// Below Cesium's trackball height such a drag turns the camera in place.
const f = freeLookFixture({ height: 500 });
const dispose = installFreeLookHeightLimit(f.viewer);
const dispose = installFreeLookHeightLimit(
f.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
assert.equal(
f.controller.minimumTrackBallHeight,
FREE_LOOK_MAX_HEIGHT_METERS,
@@ -412,7 +472,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
const lower = freeLookFixture({ height: 500 });
lower.controller.minimumTrackBallHeight = 500_000;
const disposeLower = installFreeLookHeightLimit(lower.viewer);
const disposeLower = installFreeLookHeightLimit(
lower.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
assert.equal(
lower.controller.minimumTrackBallHeight,
500_000,
@@ -422,7 +485,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
assert.equal(lower.controller.minimumTrackBallHeight, 500_000);
const later = freeLookFixture({ height: 500 });
const disposeLater = installFreeLookHeightLimit(later.viewer);
const disposeLater = installFreeLookHeightLimit(
later.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
later.controller.minimumTrackBallHeight = 2_000_000;
disposeLater();
assert.equal(
@@ -434,7 +500,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
test('free look keeps a setting other code makes after it is installed', () => {
const f = freeLookFixture({ height: 500 });
const dispose = installFreeLookHeightLimit(f.viewer);
const dispose = installFreeLookHeightLimit(
f.viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
f.controller.enableLook = false;
f.frame(10);
assert.equal(f.controller.enableLook, false, 'turned off stays off');
@@ -454,7 +523,7 @@ test('free look keeps a setting other code makes after it is installed', () => {
test('free look stays off when the viewer had it disabled', () => {
const f = freeLookFixture({ enableLook: false, height: 500 });
installFreeLookHeightLimit(f.viewer);
installFreeLookHeightLimit(f.viewer, FREE_LOOK_MAX_HEIGHT_METERS);
f.frame(10);
assert.equal(f.controller.enableLook, false);
});
@@ -479,7 +548,9 @@ function realCamera({ width = 1600, height = 900, mode } = {}) {
};
const camera = new Cesium.Camera(scene);
camera.frustum.aspectRatio = width / height;
return { camera, scene, viewer: { camera, scene } };
const viewer = { camera, scene };
bindCameraPorts(viewer);
return { camera, scene, viewer };
}
function aim(
@@ -573,7 +644,8 @@ test('a move that ends with the globe out of frame turns back to nadir', () => {
Cesium.Cartesian3.equalsEpsilon(camera.positionWC, position, 0, 1e-3),
);
assert.equal(globeOutOfFrame(camera), false);
assert.equal(scene.renders, 1);
// One render for the new view, one the recovery asks for itself.
assert.equal(scene.renders, 2, 'the turned view is drawn');
// Looking up near the ground, then zoomed out past the limit.
aim(camera, { alt: 3_834_000, pitch: 10 });
@@ -602,7 +674,7 @@ function moveEndKeepsView(camera) {
return Cesium.Cartesian3.equalsEpsilon(camera.directionWC, direction, 1e-9);
}
test('globe recovery leaves partial, low, locked and 2D views alone', () => {
test('globe recovery leaves partial, low, locked and following views alone', () => {
for (const view of partialGlobeViews) {
const { camera, viewer } = realCamera();
installGlobeInViewRecovery(viewer);
@@ -626,19 +698,18 @@ test('globe recovery leaves partial, low, locked and 2D views alone', () => {
assert.equal(globeOutOfFrame(locked.camera), true);
assert.ok(moveEndKeepsView(locked.camera), 'locked camera');
// Tracking an entity that has no position yet keeps an identity transform.
// Following an entity that has no position yet keeps an identity transform.
const tracked = realCamera();
tracked.viewer.trackedEntity = { id: 'pending-fix' };
const pending = entityFollowTarget(
{ id: 'pending-fix' },
{ position: () => null },
);
Object.defineProperty(cameraPorts.get(tracked.camera), 'followed', {
get: () => pending,
});
installGlobeInViewRecovery(tracked.viewer);
aim(tracked.camera, reportedStuckView);
assert.ok(moveEndKeepsView(tracked.camera), 'tracked camera');
const flat = realCamera({ mode: Cesium.SceneMode.COLUMBUS_VIEW });
installGlobeInViewRecovery(flat.viewer);
flat.scene.mode = Cesium.SceneMode.SCENE3D;
aim(flat.camera, reportedStuckView);
flat.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW;
assert.ok(moveEndKeepsView(flat.camera), 'Columbus view');
});
test('the look limit from orbit tolerates grid noise and never reaches zero', () => {
+24 -2
View File
@@ -6,6 +6,7 @@ import { createWeatherLayer } from '../layers/weather/index.js';
import { createApplicationCyclones } from './layers/cyclones.js';
import { createWindLayer } from '../layers/wind/index.js';
import { createLayerCatalog } from './catalog.js';
import { layerPlacement } from '../data/placementProvider.js';
import { LAYER_STATE_REGISTRY } from '../data/layerState.js';
import { createMilitaryRegistry } from '../layers/aircraft/classification.js';
import { createApplicationFlights } from './layers/flights.js';
@@ -63,6 +64,9 @@ export const APPLICATION_LAYER_METADATA = Object.freeze([
/** Construct the current catalog without choosing any source provider.
* Scene engines remain page-owned; layers and classification have this app's lifetime.
* The manager owns layer destruction, while abort releases classification even if startup fails.
* `placement`, a host-supplied placement provider (../data/placementProvider.js),
* places live aircraft, vessels, transit and trains; without one each layer
* uses its own motion.
*/
export function createApplicationCatalog({
surface,
@@ -74,6 +78,7 @@ export function createApplicationCatalog({
resolveAsset,
nepalBoundaryResolver,
streetLevelProviders,
placement = null,
}) {
if (!signal?.addEventListener)
throw new TypeError('An application lifetime signal is required');
@@ -97,18 +102,23 @@ export function createApplicationCatalog({
const flights = createApplicationFlights({
surface,
source: sources.flights,
placement: layerPlacement(placement, 'aircraft'),
militaryRegistry,
resolveAsset,
});
const military = createApplicationMilitary({
surface,
source: sources.military,
placement: layerPlacement(placement, 'military'),
militaryRegistry,
resolveAsset,
});
const vessels = createApplicationVessels({
source: sources.vessels,
placement: layerPlacement(placement, 'vessels'),
options: vesselOptions,
displayParams: () => flights.getParams(),
...(resolveAsset ? { resolveAsset } : {}),
});
const installations = createApplicationInstallations({
surface,
@@ -167,7 +177,13 @@ export function createApplicationCatalog({
createApplicationTraffic({ source: sources.traffic, surface }),
createApplicationCctv({ surface, source: sources.cctv }),
createApplicationRadio({ surface, source: sources.radio }),
createApplicationTransit({ surface, source: sources.transit }),
createApplicationTransit({
surface,
source: sources.transit,
placement: layerPlacement(placement, 'transit'),
displayParams: () => flights.getParams(),
...(resolveAsset ? { resolveAsset } : {}),
}),
createApplicationBikeshare({ source: sources.bikeshare }),
createApplicationDirections({ source: sources.directions }),
createApplicationRecentImagery({ source: sources['recent-imagery'] }),
@@ -200,7 +216,13 @@ export function createApplicationCatalog({
...createOsmOverlayLayers(),
...createInfrastructureLayers(localGeoJsonServices),
createApplicationCables({ source: sources.cables }),
createApplicationRail({ surface, source: sources.rail }),
createApplicationRail({
surface,
source: sources.rail,
placement: layerPlacement(placement, 'rail'),
displayParams: () => flights.getParams(),
...(resolveAsset ? { resolveAsset } : {}),
}),
createApplicationFirms({
surface,
id: 'local-firms',
+20 -5
View File
@@ -6,6 +6,11 @@ import { createStandaloneLayerSources } from '../standalone/layerSources.js';
import { catalogControlServices } from './catalog.js';
import { LayerLifecycle } from '../data/lifecycle.js';
import { fakeStreetLevelProvider } from '../testSupport/streetLevelFakes.mjs';
import { worldClock } from '../time/worldClock.js';
const flush = async () => {
for (let i = 0; i < 20; i++) await Promise.resolve();
};
function fixtureSources(ids, calls) {
const sources = createStandaloneLayerSources();
@@ -27,6 +32,7 @@ test('catalogs construct distinct layers and classification from their supplied
t.after(() => {
a.abort();
b.abort();
worldClock.goLive();
});
const callsA = [];
const callsB = [];
@@ -53,7 +59,10 @@ test('catalogs construct distinct layers and classification from their supplied
'the hardware-local layer is never serialized into links',
);
assert.notEqual(first.weatherClock, second.weatherClock);
await first.weatherClock.setTarget('2026-09-21T12:00:00.000Z');
// Time moves on the world clock, which the catalog's weather clock follows.
assert.equal(first.weatherClock.world, worldClock);
worldClock.seek(Date.parse('2026-09-21T12:00:00.000Z'));
await flush();
assert.match(
first.get('wind').getRowControls().info,
/Forecast · does not follow history/,
@@ -111,9 +120,16 @@ test('catalogs construct distinct layers and classification from their supplied
assert.equal(first.militaryRegistry.isMilitaryIcao('def456'), false);
assert.equal(second.militaryRegistry.isMilitaryIcao('def456'), true);
a.abort();
worldClock.seek(Date.parse('2026-09-21T13:00:00.000Z'));
await flush();
assert.equal(
await first.weatherClock.setTarget('2026-09-21T13:00:00.000Z'),
false,
first.weatherClock.getState().target,
'2026-09-21T12:00:00.000Z',
'an aborted catalog no longer follows the world clock',
);
assert.equal(
second.weatherClock.getState().target,
'2026-09-21T13:00:00.000Z',
);
assert.equal(callsA[0].aborted, true);
assert.equal(first.militaryRegistry.isMilitaryIcao('abc123'), false);
@@ -218,9 +234,8 @@ test('a GNSS integrity source can set the layer evidence window', (t) => {
};
const shows = (layer, minutes) => {
assert.equal(layer.provenance.window.minutes, minutes);
const { info, legend } = layer.getRowControls();
const { info } = layer.getRowControls();
assert.match(info, new RegExp(`visited views over ${minutes} min`));
assert.match(legend[0].blurb, new RegExp(`over ${minutes} minutes`));
};
shows(gnssLayer({ windowMs: 65 * 60_000 }), 65);
shows(gnssLayer({}), 30);
+30 -20
View File
@@ -1,8 +1,11 @@
import { catalogControlServices } from './catalog.js';
import { StyleManager } from '../ui/composition.js';
import { flyToAustin } from '../camera.js';
import { installZoomOutGuard } from './zoomOutGuard.js';
import { applyStartView, START_VIEW } from '../camera.js';
import { initCockpitCloudEffects } from '../cockpitCloudEffects.js';
import { createViewSky } from '../viewSky.js';
import { findGlobe } from '../render/rendererOf.js';
import { useDisplayStore } from '../ui/stores/display.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { t } from '../i18n/index.js';
/**
@@ -10,10 +13,13 @@ import { t } from '../i18n/index.js';
* opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host
* whose address does not carry one. `localePicker: false` removes the language
* picker, for a host that offers its own language choice (`switchLocale` from
* the `./i18n` entry).
* the `./i18n` entry). `startView` is where the camera starts (the whole
* planet by default; a host may pass a city); a shared view flies from there.
* `services.cockpitSubjects` adds the application's own first-person subjects
* to the Cockpit (src/cockpitSubjectProviders.js).
*/
export function createApplicationControls({
scene: { viewer, mapStackController, operations },
scene: { viewer, mapStackController, operations, viewerDrawsEntity },
loaderStatus,
Controls = StyleManager,
services,
@@ -22,7 +28,10 @@ export function createApplicationControls({
defer,
initialShareCode = null,
localePicker = true,
startView = START_VIEW,
}) {
// Every boot starts from the same view, before share restoration flies on.
applyStartView(viewer, startView);
// Initialize the style manager (post-processing, HUD, locations, share links)
const styleManager = new Controls(viewer, {
services: {
@@ -32,6 +41,8 @@ export function createApplicationControls({
fetchRegionalBrief: (...args) =>
operations.requests.regional.getBrief(...args),
...catalogControlServices(catalog),
// Whether an entity is one of the viewer's own; the scene answers it.
viewerDrawsEntity: viewerDrawsEntity ?? services?.viewerDrawsEntity,
},
requestServices: operations.requests,
mapStackController,
@@ -43,28 +54,27 @@ export function createApplicationControls({
defer(() => styleManager.orbitController.stop());
defer(() => styleManager.hud.destroy());
defer(() => styleManager.dispose());
defer(
installZoomOutGuard(viewer, {
subscribeCameraHandoff: (listener) =>
styleManager.subscribeCameraHandoff?.(listener),
}),
);
// The previous multi-canvas weather compositor remains disabled. Cockpit
// clouds use a separate, capped low-resolution GPU pass that never attaches
// Cesium fog or post-process stages and is fully stopped in map mode.
const weatherEffects = null;
const cockpitCloudEffects = initCockpitCloudEffects(viewer, {
weatherService: operations.requests.weather,
});
// Where the renderer draws weather, it draws the cockpit's clouds too.
const cockpitCloudEffects = findGlobe(viewer)?.weather
? null
: initCockpitCloudEffects(viewer, {
weatherService: operations.requests.weather,
});
defer(() => cockpitCloudEffects?.destroy());
// The atmosphere, sun lighting, sun, moon, stars and Milky Way the user
// chooses in the Display panel.
const viewSky = createViewSky(viewer, {
store: useDisplayStore(applicationPinia()),
});
defer(() => viewSky.destroy());
// If no share link state, do default fly-to Austin
if (!styleManager.hasShareState) {
loaderStatus.textContent = t('Flying to Austin, TX...');
defer(flyToAustin(viewer));
} else {
loaderStatus.textContent = t('Restoring shared view...');
}
loaderStatus.textContent = styleManager.hasShareState
? t('Restoring shared view...')
: t('Loading');
return { styleManager, weatherEffects, cockpitCloudEffects };
}
+6 -32
View File
@@ -1,9 +1,8 @@
import test, { after, before } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import '../testSupport/stubMgrs.mjs';
import { installVueDom } from '../testSupport/vueDom.mjs';
import { MAXIMUM_ZOOM_DISTANCE_M } from './zoomOutGuard.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
const { createApplicationControls } = await import('./controls.js');
@@ -13,35 +12,20 @@ before(() => {
});
after(() => uninstallDom());
test('application controls install the zoom-out guard and remove it on teardown', () => {
const canvas = document.createElement('canvas');
const controller = { maximumZoomDistance: Infinity };
const scene = {
mode: Cesium.SceneMode.SCENE3D,
screenSpaceCameraController: controller,
preRender: new Cesium.Event(),
postUpdate: new Cesium.Event(),
};
const camera = {
position: Cesium.Cartesian3.fromDegrees(0, 0, 1_000_000),
positionCartographic: { height: 1_000_000 },
};
const viewer = { scene, camera, canvas };
const handoffs = new Set();
test('the application controls start and stop', () => {
class Controls {
hasShareState = true;
orbitController = { stop() {} };
hud = { destroy() {} };
dispose() {}
subscribeCameraHandoff(listener) {
handoffs.add(listener);
return () => handoffs.delete(listener);
}
}
const cleanups = [];
createApplicationControls({
scene: {
viewer,
viewer: bindFakeCesiumCamera({
isDestroyed: () => false,
camera: { setView() {} },
}),
mapStackController: {},
operations: {
surface: { controlServices: {} },
@@ -54,15 +38,5 @@ test('application controls install the zoom-out guard and remove it on teardown'
catalog: { get: (id) => ({ id }) },
defer: (cleanup) => cleanups.push(cleanup),
});
assert.equal(controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
assert.equal(scene.preRender.numberOfListeners, 1);
assert.equal(scene.postUpdate.numberOfListeners, 1);
assert.equal(handoffs.size, 1);
for (const cleanup of cleanups.reverse()) cleanup();
assert.equal(controller.maximumZoomDistance, Infinity);
assert.equal(scene.preRender.numberOfListeners, 0);
assert.equal(scene.postUpdate.numberOfListeners, 0);
assert.equal(handoffs.size, 0);
});
+1 -1
View File
@@ -15,7 +15,7 @@ export function createApplicationData({
const dataManager = new LayerLifecycle(viewer, {
allowQaRegistration,
// A panel's host may report it hidden while it is on screen; its layers
// keep polling (see keepPanelRendering in embed.js).
// keep polling (see keepPanelRendering in app/panelRendering.js).
visibilityTarget: panelAwareVisibility(document),
getSourceAvailability: catalog?.getSourceAvailability,
});
+24 -82
View File
@@ -11,13 +11,14 @@
* embedded or not.
*/
import * as Cesium from 'cesium';
import {
announceNavigationAuthority,
watchCameraOwner,
} from '../navigationPolicy.js';
import { toRadians } from '../geo/index.js';
import { t, translateKnown } from '../i18n/index.js';
import { GOOGLE_LABEL } from '../layers/streetLevel/providers/google/policy.js';
import { cameraOf } from '../render/rendererOf.js';
import {
annotationsFromParams,
createView,
@@ -69,7 +70,8 @@ function isFreshPanelResult() {
/**
* `doc`'s visibility for work that pauses in a hidden page. A panel's host
* may report it hidden while it is on screen (see keepPanelRendering), so an
* may report it hidden while it is on screen (see keepPanelRendering in
* render/cesium/panelRendering.js), so an
* inline panel always reads as visible.
*/
export function panelAwareVisibility(doc = globalThis.document) {
@@ -89,69 +91,6 @@ export function panelAwareVisibility(doc = globalThis.document) {
};
}
// A panel keeps drawing at about this rate when its host stops animation
// frames; see keepPanelRendering.
const PANEL_FRAME_MS = 33;
const MISSED_FRAMES_MS = 250;
/** A render error's details, including the plain objects workers report. */
function describeError(error) {
if (error instanceof Error)
return `${error.name}: ${error.message}\n${error.stack}`;
try {
return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {}));
} catch {
return String(error);
}
}
/**
* Keep the globe drawing in an inline panel. Some hosts report a panel on
* screen as hidden, which stops the browser's animation frames and with them
* Cesium's render loop; while frames stop arriving, draw from a timer.
* Returns a function that stops it.
*/
export function keepPanelRendering(
viewer,
{ windowRef = globalThis.window, now = () => performance.now() } = {},
) {
let lastFrame = now();
let frameRequest = null;
const onFrame = () => {
lastFrame = now();
frameRequest = windowRef.requestAnimationFrame(onFrame);
};
frameRequest = windowRef.requestAnimationFrame(onFrame);
// Cesium stops drawing after a render error, and so does the timer.
// Report the error in full: workers report plain objects, which Cesium
// prints as [object Object].
let failed = false;
const removeErrorListener = viewer.scene?.renderError?.addEventListener(
(_scene, error) => {
failed = true;
console.error(
"[God's Eye View panel] render error:",
describeError(error),
);
},
);
const timer = windowRef.setInterval(() => {
if (
failed ||
now() - lastFrame < MISSED_FRAMES_MS ||
viewer.isDestroyed?.()
)
return;
viewer.resize();
viewer.render();
}, PANEL_FRAME_MS);
return () => {
windowRef.clearInterval(timer);
windowRef.cancelAnimationFrame(frameRequest);
removeErrorListener?.();
};
}
const delay = (ms, signal) =>
new Promise((resolve) => {
const timer = setTimeout(resolve, ms);
@@ -169,21 +108,19 @@ const delay = (ms, signal) =>
function flyTo(viewer, camera) {
announceNavigationAuthority('embed-view');
return new Promise((resolve) => {
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
camera.lon,
camera.lat,
camera.altitude_m,
),
orientation: {
heading: Cesium.Math.toRadians(camera.heading_deg),
pitch: Cesium.Math.toRadians(camera.pitch_deg),
roll: 0,
cameraOf(viewer).flyTo(
{ lon: camera.lon, lat: camera.lat, height: camera.altitude_m },
{
orientation: {
heading: toRadians(camera.heading_deg),
pitch: toRadians(camera.pitch_deg),
roll: 0,
},
durationS: FLIGHT_SECONDS,
onComplete: () => resolve(true),
onCancel: () => resolve(false),
},
duration: FLIGHT_SECONDS,
complete: () => resolve(true),
cancel: () => resolve(false),
});
);
});
}
@@ -331,6 +268,9 @@ export async function applyView(
/**
* Install embed mode when the page asks for it, and draw any annotations the
* opening link carries. Returns a function that removes the message handler.
* `keepRendering({windowRef})` keeps the globe drawing in an inline panel
* whose host stops animation frames, and returns a function that stops it;
* the application scene gives it (`keepPanelRendering`).
*/
export function installViews({
shell,
@@ -338,6 +278,7 @@ export function installViews({
dataManager,
run,
signal,
keepRendering = null,
terrain = null,
location = globalThis.location,
windowRef = globalThis.window,
@@ -450,9 +391,10 @@ export function installViews({
windowRef.document.body.classList.add('ui-embed');
shell.setCleanView?.(true);
const stopRendering = isEmbeddedInline()
? keepPanelRendering(viewer, { windowRef })
: () => {};
const stopRendering =
isEmbeddedInline() && keepRendering
? keepRendering({ windowRef })
: () => {};
// A framing page talks to the app across frames; an inline panel shares
// the page with it and talks through the page's own window.
const peer = isEmbeddedInline() ? windowRef : windowRef.parent;
+11 -70
View File
@@ -1,10 +1,10 @@
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import assert from 'node:assert/strict';
import test from 'node:test';
import {
applyView,
installViews,
isEmbedded,
keepPanelRendering,
panelAwareVisibility,
} from './embed.js';
import { LayerLifecycle } from '../data/lifecycle.js';
@@ -12,7 +12,7 @@ import { createView, viewToParams } from '../view/index.js';
const fakeViewer = () => {
const flights = [];
return {
return bindFakeCesiumCamera({
flights,
camera: {
flyTo(options) {
@@ -20,7 +20,7 @@ const fakeViewer = () => {
options.complete();
},
},
};
});
};
const fakeLayers = (enabled) => ({
getAll: () =>
@@ -329,6 +329,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn
globalThis.GEV_EMBED_INLINE = true;
try {
assert.equal(isEmbedded({ search: '' }), true);
const kept = [];
const remove = installViews({
shell: { initialRestorePromise: Promise.resolve() },
viewer: fakeViewer(),
@@ -336,7 +337,13 @@ test('an app loaded inline into a panel page talks through its own window', asyn
run: recorder().run,
location: { search: '', hash: '' },
windowRef,
// The scene's panel rendering, kept on while the views are installed.
keepRendering: (options) => {
kept.push(options.windowRef === windowRef);
return () => kept.push('stopped');
},
});
assert.deepEqual(kept, [true]);
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(posted, [{ type: 'gev:ready' }]);
const event = new Event('message');
@@ -349,6 +356,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn
assert.equal(posted[1].id, 7);
assert.equal(posted[1].ok, true);
remove();
assert.deepEqual(kept, [true, 'stopped']);
} finally {
delete globalThis.GEV_EMBED_INLINE;
}
@@ -427,73 +435,6 @@ test('annotations in a link are drawn after it restores, embedded or not', async
]);
});
test('a panel keeps drawing from a timer while animation frames stop', () => {
let clock = 0;
let tick = null;
let frame = null;
const windowRef = {
requestAnimationFrame: (fn) => ((frame = fn), 1),
cancelAnimationFrame: () => (frame = null),
setInterval: (fn) => ((tick = fn), 1),
clearInterval: () => (tick = null),
};
const drawn = [];
const viewer = {
resize: () => drawn.push('resize'),
render: () => drawn.push('render'),
};
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
// Frames arrive: the render loop draws, so the timer does nothing.
clock = 100;
frame();
tick();
assert.deepEqual(drawn, []);
// Frames stop, as in a panel its host reports hidden: the timer draws.
clock = 400;
tick();
assert.deepEqual(drawn, ['resize', 'render']);
stop();
assert.equal(tick, null);
assert.equal(frame, null);
});
test('a panel reports a render error in full and stops drawing', () => {
let listener = null;
let tick = null;
const windowRef = {
requestAnimationFrame: () => 1,
cancelAnimationFrame() {},
setInterval: (fn) => ((tick = fn), 1),
clearInterval() {},
};
const drawn = [];
const viewer = {
resize() {},
render: () => drawn.push('render'),
scene: {
renderError: {
addEventListener: (fn) => ((listener = fn), () => (listener = null)),
},
},
};
const logged = [];
const original = console.error;
console.error = (...args) => logged.push(args.join(' '));
try {
let clock = 0;
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
listener(viewer.scene, { name: 'RuntimeError', message: 'worker failed' });
assert.match(logged[0], /render error: .*"message":"worker failed"/);
clock = 1000;
tick();
assert.deepEqual(drawn, []);
stop();
assert.equal(listener, null);
} finally {
console.error = original;
}
});
test('a followed aircraft owns the camera, and cockpit view is entered after it', async () => {
const viewer = fakeViewer();
const { calls, run } = recorder();
+181
View File
@@ -0,0 +1,181 @@
/**
* @module app/globeInViewRecovery
* @description Turns the camera back to the planet when a move ends looking
* away from it, through the renderer's camera and frame ports.
*/
import { PI_OVER_TWO } from '../geo/vector.js';
import {
FREE_LOOK_MAX_HEIGHT_METERS,
globeOutOfFrame,
isFreeGlobeCamera,
} from '../globeInView.js';
import { canvasOf, findCamera, findFrame } from '../render/rendererOf.js';
/** Whether two vectors agree to `tolerance` in every component. */
const within = (a, b, tolerance) =>
Math.abs(a.x - b.x) <= tolerance &&
Math.abs(a.y - b.y) <= tolerance &&
Math.abs(a.z - b.z) <= tolerance;
// How often a moving camera is sampled to see whether it has come to rest, how
// far a pose may drift between samples and still count as at rest, and how
// long after the camera last moved the check gives up if the camera never
// raises moveEnd.
const SETTLE_SAMPLE_MS = 250;
const SETTLE_POSITION_TOLERANCE_M = 1e-3;
const SETTLE_DIRECTION_TOLERANCE = 1e-9;
const SETTLE_GIVE_UP_MS = 5 * 60_000;
/**
* Turn the camera back to the planet when a move ends above `minHeight` with
* no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about
* one sample cell thick can count as none), and return the disposer. Views with
* more surface, such as an oblique orbital shot, are left as they are. This
* catches a saved or shared view that looked away, or any other move that ends
* looking away from the planet.
* Heading and position are kept. Following cameras, locked ones (a target's
* frame), a camera flight in progress, a pointer held down on the canvas
* (a drag held still), and any time `paused`
* returns true (an authored scene playing) are left alone; a check they defer
* runs once they end, however long they last.
* `keyholeRadius`
* returns the radius of the visible circle when a scope mask hides the rest of
* the frame (see `globeFrameShare`), or 0; it is read at every check.
*
* The camera's `moveEnd` alone is not enough: the default renderer compares
* the camera with the last frame's to the last rounding error, and at some of
* these poses the camera drifts by a rounding error every frame, so it never
* sees it stop.
* So each `moveStart` also starts a check of its own that samples the pose
* every 250 ms, with a tolerance for that drift, and once the pose has held
* for half a second after moving runs the same recovery. It keeps watching
* until the camera raises `moveEnd`, since under that drift it raises no new
* `moveStart` for a later move, and gives up five minutes after the camera
* last moved.
* `setTimeout` and `clearTimeout` can be injected for tests.
*/
export function installGlobeInViewRecovery(
viewer,
{
minHeight = FREE_LOOK_MAX_HEIGHT_METERS,
keyholeRadius = () => 0,
paused = () => false,
setTimeout: schedule = globalThis.setTimeout,
clearTimeout: unschedule = globalThis.clearTimeout,
} = {},
) {
const camera = findCamera(viewer);
if (!camera) throw new TypeError('A viewer with a camera is required');
// A pointer held on the globe is a gesture in progress, even when it holds
// still for half a second: the check waits until every pointer pressed on
// it (each finger of a pinch) is released. A release the page never sees,
// outside the window, is taken as given when the window loses focus, the
// page is hidden, the canvas loses the pointer's capture, or the pointer
// moves with no button down.
const canvas = canvasOf(viewer);
const releaseTarget = canvas?.ownerDocument ?? canvas;
const releaseWindow = canvas?.ownerDocument?.defaultView;
const heldPointers = new Set();
const onPointerDown = (event) => heldPointers.add(event?.pointerId);
const onPointerUp = (event) => heldPointers.delete(event?.pointerId);
const onPointerMove = (event) => {
if (event?.buttons === 0) heldPointers.delete(event.pointerId);
};
const releaseAll = () => heldPointers.clear();
const onVisibilityChange = () => {
if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll();
};
const listeners = [
[canvas, 'pointerdown', onPointerDown],
[canvas, 'lostpointercapture', onPointerUp],
[releaseTarget, 'pointerup', onPointerUp],
[releaseTarget, 'pointercancel', onPointerUp],
[releaseTarget, 'pointermove', onPointerMove],
[canvas?.ownerDocument, 'visibilitychange', onVisibilityChange],
[releaseWindow, 'blur', releaseAll],
];
for (const [target, type, listener] of listeners)
target?.addEventListener?.(type, listener);
// Returns false while a flight, a paused scene or a held pointer defers the
// check, so the caller can try again once it ends.
const recover = () => {
if (!isFreeGlobeCamera(viewer)) return true;
if (camera.flying || paused() || heldPointers.size > 0) return false;
const pose = camera.pose();
if (
!(pose.height > minHeight) ||
!globeOutOfFrame(pose, { keyholeRadius: keyholeRadius() })
)
return true;
camera.setView({
orientation: { heading: pose.heading, pitch: -PI_OVER_TWO, roll: 0 },
});
findFrame(viewer)?.requestRender?.('globe-in-view');
return true;
};
let lastPosition = null;
let lastDirection = null;
const remember = () => {
({ position: lastPosition, direction: lastDirection } = camera.pose());
};
let settleTimer = null;
let settleElapsed = 0;
let restingSamples = 0;
let movedSinceCheck = false;
const stopSettling = () => {
if (settleTimer !== null) unschedule(settleTimer);
settleTimer = null;
};
const sample = () => {
settleTimer = null;
settleElapsed += SETTLE_SAMPLE_MS;
const now = camera.pose();
const atRest =
within(now.position, lastPosition, SETTLE_POSITION_TOLERANCE_M) &&
within(now.direction, lastDirection, SETTLE_DIRECTION_TOLERANCE);
restingSamples = atRest ? restingSamples + 1 : 0;
if (!atRest) {
movedSinceCheck = true;
settleElapsed = 0;
}
// Two quiet samples in a row after a move: at rest for half a second, as
// for moveEnd.
if (restingSamples >= 2 && movedSinceCheck) {
if (recover()) movedSinceCheck = false;
// A flight or a playing scene bounds its own deferral.
else settleElapsed = 0;
}
if (settleElapsed >= SETTLE_GIVE_UP_MS) return;
remember();
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const startSettling = () => {
stopSettling();
settleElapsed = 0;
restingSamples = 0;
movedSinceCheck = true;
remember();
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const removeMoveEnd = camera.on('moveEnd', () => {
if (recover()) stopSettling();
// Deferred: keep sampling so the check runs once the flight or scene ends.
else if (settleTimer === null) startSettling();
});
const removeMoveStart = camera.on('moveStart', startSettling);
let active = true;
return () => {
if (!active) return;
active = false;
stopSettling();
removeMoveEnd();
removeMoveStart();
for (const [target, type, listener] of listeners)
target?.removeEventListener?.(type, listener);
heldPointers.clear();
};
}
+19 -2
View File
@@ -10,9 +10,21 @@ import * as focus from '../../data/focusDeemphasis.js';
import * as worldFocus from '../../worldFocus.js';
import * as render from '../../renderGovernor.js';
import * as readouts from '../../hudReadouts.js';
import { fleetModelServices } from './fleetModels.js';
/** Construct one layer using the application scene owners and a supplied source. */
export function createApplicationVessels({ source, options = {} }) {
/**
* Construct one layer using the application scene owners and a supplied
* source. `displayParams` reads the Flights layer's DISPLAY-rail 3D
* preference, under which nearby vessels are drawn as fleet models.
* `placement`: a host-supplied placement for its live vessels, or null.
*/
export function createApplicationVessels({
source,
placement = null,
options = {},
displayParams = null,
resolveAsset,
}) {
return createVesselLayer({
source,
options,
@@ -28,6 +40,11 @@ export function createApplicationVessels({ source, options = {} }) {
worldFocus,
render,
readouts,
placement,
fleet: fleetModelServices({
display: displayParams,
...(resolveAsset ? { resolveAsset } : {}),
}),
},
});
}
-5
View File
@@ -1,8 +1,6 @@
import * as Cesium from 'cesium';
import { createDroneAirspaceLayer } from '../../layers/droneAirspace/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { isPointerFree } from '../../data/inputOwnership.js';
/** Wire FAA special-use airspace into the application catalog. */
export function createApplicationDroneAirspace(options) {
@@ -13,10 +11,7 @@ export function createApplicationDroneAirspace(options) {
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
...options,
});
}
-4
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { createFirmsHeatmapLayer as createLayer } from '../../layers/firms/index.js';
import * as render from '../../renderGovernor.js';
import * as sprites from '../../data/spriteOrder.js';
@@ -29,8 +28,5 @@ export function createApplicationFirms({ surface, ...options }) {
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
screenSpaceEventHandlerFactory:
options.screenSpaceEventHandlerFactory ??
((viewer) => new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)),
});
}
+19
View File
@@ -0,0 +1,19 @@
import { FLEET_MODEL_POLICY } from '../../layers/flights/policy.js';
/**
* The fleet-model service the Vessels, Transit and Rail layers draw their 3D
* models with: the Flights layer's DISPLAY-rail 3D preference
* (`{ models3d, models3dMode }`), the aircraft layers' icon-to-model rules,
* and the resolver the fleet set's files are fetched through.
* @param {{display?: (() => object|null)|null,
* resolveAsset?: (url: string) => string}} [options]
* @returns {object|null} Null without a display preference (no models).
*/
export function fleetModelServices({
display = null,
resolveAsset = (url) =>
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
} = {}) {
if (!display) return null;
return Object.freeze({ display, policy: FLEET_MODEL_POLICY, resolveAsset });
}
+4 -1
View File
@@ -12,11 +12,13 @@ import * as context from '../../data/contextStore.js';
import * as render from '../../renderGovernor.js';
import * as recession from '../../data/aircraftRecession.js';
/** Construct one layer using the application scene owners and a supplied source. */
/** Construct one layer using the application scene owners and a supplied source.
* `placement`: a host-supplied placement for its live aircraft, or null. */
export function createApplicationFlights({
surface,
source,
militaryRegistry,
placement = null,
resolveAsset = (url) =>
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
}) {
@@ -41,6 +43,7 @@ export function createApplicationFlights({
render,
groundSnap,
recession,
placement,
},
});
}
-5
View File
@@ -1,8 +1,6 @@
import * as Cesium from 'cesium';
import { createGhostMapsLayer } from '../../layers/ghostMaps/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { isPointerFree } from '../../data/inputOwnership.js';
/** Wire the S2 Underground GhostMaps layer into the application catalog. */
export function createApplicationGhostMaps(options) {
@@ -14,10 +12,7 @@ export function createApplicationGhostMaps(options) {
hitTest: overlays.hitTestWorldOverlay,
},
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
...options,
});
}
+4 -1
View File
@@ -12,11 +12,13 @@ import * as context from '../../data/contextStore.js';
import * as render from '../../renderGovernor.js';
import * as recession from '../../data/aircraftRecession.js';
/** Construct one layer using the application scene owners and a supplied source. */
/** Construct one layer using the application scene owners and a supplied source.
* `placement`: a host-supplied placement for its live aircraft, or null. */
export function createApplicationMilitary({
surface,
source,
militaryRegistry,
placement = null,
resolveAsset = (url) =>
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
}) {
@@ -41,6 +43,7 @@ export function createApplicationMilitary({
render,
groundSnap,
recession,
placement,
},
});
}
-5
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import {
createFirePerimetersLayer,
createInciwebIndexSource,
@@ -6,7 +5,6 @@ import {
} from '../../layers/perimeters/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { isPointerFree } from '../../data/inputOwnership.js';
/** Wire WFIGS fire perimeters into the application catalog. */
export function createApplicationFirePerimeters(options) {
@@ -20,10 +18,7 @@ export function createApplicationFirePerimeters(options) {
inciwebSource: createInciwebIndexSource(),
inciwebPublications: createInciwebPublicationSource(),
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
...options,
});
}
+18 -4
View File
@@ -1,9 +1,9 @@
import { createRailLayer } from '../../layers/rail/index.js';
import * as render from '../../renderGovernor.js';
import { fleetModelServices } from './fleetModels.js';
import * as sprites from '../../data/spriteOrder.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { applyTrackedCameraFrame } from '../../data/trackedCamera.js';
import { WORLD_FOCUS_FRAMING, requestWorldFocus } from '../../worldFocus.js';
import {
railFeedCredit,
@@ -13,10 +13,20 @@ import {
/**
* Construct the Rail layer on the application's scene owners and its shared
* ground floor, the same floor Transit and the aircraft stand on.
* @param {{surface: object, source?: object}} options
* `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under
* which nearby trains are drawn as fleet models.
* `placement` is a host-supplied placement for its live trains, or null.
* @param {{surface: object, source?: object, placement?: object|null,
* displayParams?: () => object|null, resolveAsset?: (url: string) => string}} options
* @returns {object}
*/
export function createApplicationRail({ surface, source }) {
export function createApplicationRail({
surface,
source,
placement = null,
displayParams = null,
resolveAsset,
}) {
if (!surface?.groundFloor)
throw new TypeError('Rail needs the application surface services');
const { groundFloor } = surface;
@@ -27,6 +37,7 @@ export function createApplicationRail({ surface, source }) {
sprites,
picking,
overlays,
placement,
credits: { registerDynamicCredit, railFeedCredit },
ground: {
GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M,
@@ -40,11 +51,14 @@ export function createApplicationRail({ surface, source }) {
camera: {
framing: WORLD_FOCUS_FRAMING.train,
requestWorldFocus,
applyTrackedCameraFrame,
isCockpitActive: () =>
globalThis.document?.body?.classList?.contains('cockpit-mode') ===
true,
},
fleet: fleetModelServices({
display: displayParams,
...(resolveAsset ? { resolveAsset } : {}),
}),
},
});
}
-3
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { createShipwrecksLayer } from '../../layers/shipwrecks/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
@@ -14,8 +13,6 @@ export function createApplicationShipwrecks(options) {
hitTest: overlays.hitTestWorldOverlay,
},
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
...options,
+1 -3
View File
@@ -3,9 +3,7 @@ import { createMapillaryProvider } from '../../layers/streetLevel/providers/mapi
import { createGoogleProvider } from '../../layers/streetLevel/providers/google/index.js';
import { createKartaViewProvider } from '../../layers/streetLevel/providers/kartaview/index.js';
import { createPanoramaxProvider } from '../../layers/streetLevel/providers/panoramax/index.js';
import * as sprites from '../../data/spriteOrder.js';
import * as picking from '../../data/pickRegistry.js';
import * as input from '../../data/inputOwnership.js';
import * as scenePick from '../../data/scenePick.js';
import * as render from '../../renderGovernor.js';
@@ -37,6 +35,6 @@ export function createApplicationStreetLevel({
}) {
return createStreetLevelLayer({
providers,
services: { sprites, picking, input, scenePick, render },
services: { picking, scenePick, render },
});
}
-3
View File
@@ -1,12 +1,9 @@
import * as Cesium from 'cesium';
import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js';
import { overlayHost } from './overlayHost.js';
/** Wire cable source geometry to the application overlay host. */
export function createApplicationCables(options) {
return createSubmarineCableLayer({
overlayHost,
screenSpaceEventHandlerFactory: (canvas) =>
new Cesium.ScreenSpaceEventHandler(canvas),
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
...options,
});
+19 -2
View File
@@ -1,5 +1,6 @@
import { createTransitLayer } from '../../layers/transit/index.js';
import * as render from '../../renderGovernor.js';
import { fleetModelServices } from './fleetModels.js';
import * as sprites from '../../data/spriteOrder.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
@@ -19,10 +20,21 @@ import {
* own mesh floors. An earlier cut imported the legacy module-level singleton
* instead and could not see either.
*
* @param {{surface: object}} options
* `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under
* which nearby vehicles are drawn as fleet models.
*
* `placement` is a host-supplied placement for its live vehicles, or null.
* @param {{surface: object, source?: object, placement?: object|null,
* displayParams?: () => object|null, resolveAsset?: (url: string) => string}} options
* @returns {object}
*/
export function createApplicationTransit({ surface, source }) {
export function createApplicationTransit({
surface,
source,
placement = null,
displayParams = null,
resolveAsset,
}) {
if (!surface?.groundFloor || !surface?.meshFloor)
throw new TypeError('Transit needs the application surface services');
const { groundFloor, meshFloor } = surface;
@@ -33,6 +45,7 @@ export function createApplicationTransit({ surface, source }) {
sprites,
picking,
overlays,
placement,
credits: { registerDynamicCredit, transitFeedCredit },
ground: {
GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M,
@@ -44,6 +57,10 @@ export function createApplicationTransit({ surface, source }) {
allocateCorridorCells: groundFloor.allocateCorridorCells,
},
mesh: { sampleMeshFloorCells: meshFloor.sampleMeshFloorCells },
fleet: fleetModelServices({
display: displayParams,
...(resolveAsset ? { resolveAsset } : {}),
}),
},
});
}
-3
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { createWildlifeSightingsLayer } from '../../layers/wildlifeSightings/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
@@ -17,8 +16,6 @@ export function createApplicationWildlifeSightings(options) {
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
sprites,
+2
View File
@@ -2,6 +2,7 @@ import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
import { governorRequestRender } from '../renderGovernor.js';
import {
clearSelectedEntityContextForLayer,
getSelectedEntityContext,
registerEntityContext,
removeEntityContextsForLayer,
selectEntityContext,
@@ -19,6 +20,7 @@ export const localGeoJsonServices = Object.freeze({
setVisible: setOverlaySourceVisible,
}),
clearSelectedEntityContextForLayer,
getSelectedEntityContext,
registerEntityContext,
removeEntityContextsForLayer,
selectEntityContext,
+5 -3
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { MapStackController } from '../mapStackController.js';
import '../render/cesium/mapEngine.js';
import {
installRenderGovernor,
uninstallRenderGovernor,
@@ -8,6 +9,7 @@ import {
governorRequestRender,
getRenderGovernorDiagnostics,
} from '../renderGovernor.js';
import { framePortFor } from '../testSupport/fakeFramePort.mjs';
test('destroy invalidates a pending imagery provider before it can touch the viewer', async () => {
let resolveProvider;
@@ -44,11 +46,11 @@ test('uninstall only releases the current viewer and makes later render requests
},
},
};
installRenderGovernor(viewer);
installRenderGovernor(framePortFor(viewer.scene));
holdContinuousRender('fixture');
uninstallRenderGovernor({});
uninstallRenderGovernor(framePortFor({}));
assert.equal(getRenderGovernorDiagnostics().installed, true);
uninstallRenderGovernor(viewer);
uninstallRenderGovernor(framePortFor(viewer.scene));
const before = renders;
governorRequestRender('late');
assert.equal(renders, before);
+74
View File
@@ -0,0 +1,74 @@
/**
* @module app/panelRendering
* @description Keeping the globe drawing in an inline panel whose host stops
* animation frames (`src/app/embed.js`, embed mode), through the ports alone: the
* application scene hands it to the embed views (`src/app/scene.js`).
*/
// A panel keeps drawing at about this rate when its host stops animation
// frames; see keepPanelRendering.
const PANEL_FRAME_MS = 33;
const MISSED_FRAMES_MS = 250;
/** A render error's details, including the plain objects workers report. */
function describeError(error) {
if (error instanceof Error)
return `${error.name}: ${error.message}\n${error.stack}`;
try {
return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {}));
} catch {
return String(error);
}
}
/**
* Keep `renderer` drawing in an inline panel. Some hosts report a panel on
* screen as hidden, which stops the browser's animation frames and with them
* the renderer's own loop; while frames stop arriving, draw from a timer
* (`resize`, then a frame of the loop, `frame.renderNow({ifDue: true})`: the
* camera moves, input and the clock run, and it draws when due). While the
* renderer's loop is stopped after a failed frame (`stopped` in its frame
* diagnostics) the timer waits, and goes on once a retry starts the loop
* again; the render failure notice reports the error
* (src/render/cesium/renderFailure.js). Where the renderer never says so, a frame
* that fails stops the timer, its error reported in full. Returns a
* function that stops it.
* @param {import('../render/contract/renderer').Renderer} renderer
* @param {{windowRef?: Window, now?: () => number}} [options]
* @returns {() => void}
*/
export function keepPanelRendering(
renderer,
{ windowRef = globalThis.window, now = () => performance.now() } = {},
) {
let lastFrame = now();
let frameRequest = null;
const onFrame = () => {
lastFrame = now();
frameRequest = windowRef.requestAnimationFrame(onFrame);
};
frameRequest = windowRef.requestAnimationFrame(onFrame);
let failed = false;
const stopped = () => renderer.frame.diagnostics?.().stopped;
const timer = windowRef.setInterval(() => {
if (failed || now() - lastFrame < MISSED_FRAMES_MS || stopped()) return;
try {
renderer.resize();
renderer.frame.renderNow({ ifDue: true });
} catch (error) {
// Stopped by now: the render failure notice has the error.
if (stopped() !== undefined) return;
// Report the error in full: workers report plain objects, which
// would print as [object Object].
failed = true;
console.error(
"[God's Eye View panel] render error:",
describeError(error),
);
}
}, PANEL_FRAME_MS);
return () => {
windowRef.clearInterval(timer);
windowRef.cancelAnimationFrame(frameRequest);
};
}
+125
View File
@@ -0,0 +1,125 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { keepPanelRendering } from './panelRendering.js';
const windowWith = () => {
const handles = { tick: null, frame: null };
handles.windowRef = {
requestAnimationFrame: (fn) => ((handles.frame = fn), 1),
cancelAnimationFrame: () => (handles.frame = null),
setInterval: (fn) => ((handles.tick = fn), 1),
clearInterval: () => (handles.tick = null),
};
return handles;
};
test('a panel keeps drawing from a timer while animation frames stop', () => {
let clock = 0;
const handles = windowWith();
const drawn = [];
const renderer = {
resize: () => drawn.push('resize'),
frame: {
renderNow: (options) =>
drawn.push(options?.ifDue ? 'loop frame' : 'forced frame'),
},
};
const stop = keepPanelRendering(renderer, {
windowRef: handles.windowRef,
now: () => clock,
});
// Frames arrive: the render loop draws, so the timer does nothing.
clock = 100;
handles.frame();
handles.tick();
assert.deepEqual(drawn, []);
// Frames stop, as in a panel its host reports hidden: the timer draws.
clock = 400;
handles.tick();
// A frame of the loop, as the loop's own: the camera moves, input and
// the clock run, and it draws when due.
assert.deepEqual(drawn, ['resize', 'loop frame']);
stop();
assert.equal(handles.tick, null);
assert.equal(handles.frame, null);
});
test('a panel reports a failed frame in full and stops drawing', () => {
const handles = windowWith();
let renders = 0;
const renderer = {
resize() {},
frame: {
renderNow() {
renders += 1;
// Workers report plain objects.
throw { name: 'RuntimeError', message: 'worker failed' };
},
},
};
const logged = [];
const original = console.error;
console.error = (...args) => logged.push(args.join(' '));
try {
let clock = 0;
const stop = keepPanelRendering(renderer, {
windowRef: handles.windowRef,
now: () => clock,
});
clock = 1000;
handles.tick();
assert.match(logged[0], /render error: .*"message":"worker failed"/);
handles.tick();
assert.equal(renders, 1, 'no frame after the one that failed');
stop();
} finally {
console.error = original;
}
});
test('a panel waits while its renderer’s loop is stopped after a failed frame, and draws again once it restarts', () => {
let clock = 0;
const handles = windowWith();
let stopped = false;
let fail = false;
let renders = 0;
const renderer = {
resize() {},
frame: {
diagnostics: () => ({ stopped }),
renderNow() {
renders += 1;
if (fail) {
// The renderer stops its loop as the frame fails.
stopped = true;
throw new Error('frame failed');
}
},
},
};
const errors = [];
const error = console.error;
console.error = (...args) => errors.push(args);
try {
const stop = keepPanelRendering(renderer, {
windowRef: handles.windowRef,
now: () => clock,
});
clock = 1000;
fail = true;
handles.tick();
assert.equal(renders, 1);
// Stopped: the timer waits, and leaves the error to the notice.
handles.tick();
assert.equal(renders, 1);
assert.deepEqual(errors, []);
// A retry starts the loop again: the timer draws again.
stopped = false;
fail = false;
handles.tick();
assert.equal(renders, 2);
stop();
} finally {
console.error = error;
}
});
+132
View File
@@ -0,0 +1,132 @@
// Retry in an inline panel whose host stops animation frames, so the panel
// draws from keepPanelRendering's timer. Drives Cesium's real startRenderLoop
// and useDefaultRenderLoop setter (CesiumWidget.prototype), through the
// Cesium frame port.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { keepPanelRendering } from './panelRendering.js';
import { renderLoopFixture } from '../render/cesium/renderLoopFixture.mjs';
import { createSceneFrame } from '../render/cesium/frame.js';
function setup() {
let tick = null;
let clock = 0;
// The host reports the panel hidden: its own animation frames never arrive.
const windowRef = {
requestAnimationFrame: () => 1,
cancelAnimationFrame() {},
setInterval: (fn) => ((tick = fn), 1),
clearInterval() {},
};
const previousError = console.error;
console.error = () => {};
const state = { failure: null, drawn: 0 };
const scene = {
renderError: new Cesium.Event(),
preUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
requestRender() {},
initializeFrame() {},
// Scene.render: a failing primitive update raises renderError
// (tryAndCatchError) and returns; a failing listener throws.
render() {
state.drawn += 1;
this.preUpdate.raiseEvent(this);
if (state.failure === 'caught')
this.renderError.raiseEvent(this, new Error('boom'));
if (state.failure === 'thrown') throw new Error('boom');
this.postRender.raiseEvent(this);
},
};
const { frames, widget, viewer, store, runFrames, restore } =
renderLoopFixture(scene, {
viewer: {
isDestroyed: () => false,
render: () => widget.render(),
resize: () => widget.resize(),
},
notice: { allowReload: false },
});
const frame = createSceneFrame(viewer);
const renderer = { resize: () => viewer.resize(), frame: frame.port };
const stopPanel = keepPanelRendering(renderer, {
windowRef,
now: () => clock,
});
const stop = () => {
stopPanel();
frame.dispose();
};
viewer.useDefaultRenderLoop = true;
const timerFrame = () => {
clock += 400;
tick();
};
return {
frames,
state,
store,
timerFrame,
animationFrames: runFrames,
restore: () => {
stop();
restore();
console.error = previousError;
},
};
}
for (const failure of ['caught', 'thrown']) {
test(`an error ${failure} in a frame the timer draws: Retry draws again with one render loop`, () => {
const { frames, state, store, timerFrame, animationFrames, restore } =
setup();
try {
// The host stops animation frames with the loop's next one queued.
assert.equal(frames.length, 1);
state.failure = failure;
timerFrame(); // an error thrown here does not reach the host page
assert.equal(store.renderFailure?.reason, 'render-error');
assert.equal(typeof store.renderFailure.retry, 'function');
state.failure = null;
store.renderFailure.retry();
const before = state.drawn;
timerFrame();
assert.ok(state.drawn > before, 'the panel draws again after Retry');
assert.equal(
store.renderFailure,
null,
'a clean frame clears the notice',
);
assert.equal(frames.length, 1, 'Retry starts no second loop');
// The host resumes frames: the globe draws once a frame.
state.drawn = 0;
animationFrames(3);
assert.equal(state.drawn, 3);
} finally {
restore();
}
});
}
test('an error Scene caught in an animation frame right before the host stopped frames: Retry keeps one render loop', () => {
const { frames, state, store, timerFrame, animationFrames, restore } =
setup();
try {
state.failure = 'caught';
animationFrames(1);
assert.equal(store.renderFailure?.reason, 'render-error');
assert.equal(frames.length, 1);
state.failure = null;
store.renderFailure.retry();
timerFrame();
assert.equal(store.renderFailure, null);
assert.equal(frames.length, 1, 'Retry starts no second loop');
state.drawn = 0;
animationFrames(3);
assert.equal(state.drawn, 3);
} finally {
restore();
}
});
+156 -33
View File
@@ -1,26 +1,66 @@
import { createApplicationOperations } from './operations.js';
import * as Cesium from 'cesium';
import {
createApplicationViewer,
installFreeLookHeightLimit,
installTrackpadPinchZoom,
} from '../app/viewer.js';
import { registerDataCredits } from '../data/dataCredits.js';
import { configureCreditKeyboardAccess } from '../creditKeyboard.js';
import { mountCreditsView } from '../ui/creditsView.js';
import { MapStackController } from '../mapStackController.js';
import { loadPhotorealisticTileset } from '../mapStartup.js';
import { mapEngineFor } from '../maps/engine.js';
import { initLogoGaze } from '../logoGaze.js';
import { inputFor } from '../input/dispatcher.js';
import {
holdContinuousRender,
installRenderGovernor,
uninstallRenderGovernor,
governorRequestRender,
releaseContinuousRender,
} from '../renderGovernor.js';
import { describeError } from './errors.js';
import { isEmbeddedInline } from './embed.js';
import { worldClock, worldTimeFor } from '../time/worldClock.js';
import { followWorldTime } from '../time/viewerClock.js';
import { onLocaleChange, t } from '../i18n/index.js';
import { t } from '../i18n/index.js';
import {
applicationHooksOf,
provideApplicationHooks,
} from '../render/applicationHooks.js';
import { keepPanelRendering } from './panelRendering.js';
import { useStatusStore } from '../ui/stores/status.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { createSceneHost } from '../render/rendererOf.js';
/** Construct the application globe using the caller's local configuration. */
let defaultLoad = null;
/**
* The application's composition root picks the renderer: the one given, else
* the default (Cesium), loaded only then, so a page on the stub never
* loads it. This is the only part of an adapter the application imports. A
* page that starts on the default calls this as it starts, so the renderer
* loads beside the rest of the page rather than after it.
* @returns {Promise<object>} The default `RendererPlugin`.
*/
export function loadDefaultRenderer() {
if (defaultLoad) return defaultLoad;
const load = (async () => {
const { cesiumRenderer } = await import('../render/cesium/application.js');
return cesiumRenderer;
})();
defaultLoad = load;
// A load that failed is tried again by the next call.
load.catch(() => {
if (defaultLoad === load) defaultLoad = null;
});
return load;
}
/**
* Construct the application globe using the caller's local configuration.
* `renderer` is the `RendererPlugin` that draws it, or a promise of one
* (default: Cesium, `loadDefaultRenderer`). The
* application runs on a renderer with only the contract's required members:
* what a renderer's plugin hands it beside the contract
* (`src/render/applicationHooks.js`) it uses where given, and does without
* where not.
*/
export async function createApplicationScene({
renderer: givenPlugin,
requestServices,
googleApiKey,
googleTokens = null,
@@ -47,52 +87,117 @@ export async function createApplicationScene({
});
}
loaderStatus.textContent = t('Configuring viewer...');
// Provider attribution stays visible, including clean-view and recording.
const creditContainer = document.createElement('div');
creditContainer.id = 'cesium-credits';
document.body.appendChild(creditContainer);
defer(() => creditContainer.remove());
const viewer = createApplicationViewer({
container: 'cesiumContainer',
creditContainer,
const rendererPlugin = (await givenPlugin) ?? (await loadDefaultRenderer());
signal.throwIfAborted();
const container = document.getElementById('cesiumContainer');
const renderer = await rendererPlugin.create({
container,
googleApiKey: googleApiKey || undefined,
googleTokens: googleTokens
? (options) => googleTokens.token(options)
: undefined,
worldDataToken: cesiumToken || undefined,
signal,
});
// The scene object every layer and tool is handed: the application's own,
// bound to the renderer.
const scene = createSceneHost(renderer, { container });
const viewer = scene.host;
// The governor keeps its holds on the renderer's frame port. The loop
// draws every frame until the application's tools are up (they release
// 'boot'), as it did before anything could hold it. A camera move holds
// it drawing every frame too.
installRenderGovernor(renderer.frame, { camera: renderer.camera });
holdContinuousRender('boot');
defer(() => {
uninstallRenderGovernor(viewer);
if (!viewer.isDestroyed()) viewer.destroy();
try {
uninstallRenderGovernor(renderer.frame);
} finally {
try {
renderer.destroy();
} finally {
scene.release();
}
}
});
defer(installTrackpadPinchZoom(viewer));
// What the plugin hands the application beside the contract, each hook
// optional (render/applicationHooks.js).
if (typeof rendererPlugin.applicationHooks === 'function')
provideApplicationHooks(
renderer,
rendererPlugin.applicationHooks(renderer),
);
const hooks = applicationHooksOf(renderer);
// The renderer follows its container's size (`Renderer.resize`).
if (typeof ResizeObserver === 'function' && container) {
const resizes = new ResizeObserver(() => renderer.resize());
resizes.observe(container);
defer(() => resizes.disconnect());
}
// Before any layer binds a click: every layer and tool shares this one.
// Deferred after the renderer, so it is released before the renderer goes.
const input = inputFor(viewer);
defer(() => input.destroy());
// Ctrl+wheel and trackpad pinches zoom the globe, not the page.
const { controls } = renderer.camera;
if (!controls.zoomInputs.includes('ctrlWheel'))
controls.zoomInputs = [...controls.zoomInputs, 'ctrlWheel'];
// The user's outward zooms stop at a whole-Earth view, which stays framed.
if (renderer.capabilities.has('keepEarthFramed')) {
controls.keepEarthFramed = true;
defer(() => {
controls.keepEarthFramed = false;
});
}
// The renderer's own notice when the globe stops drawing, in place of a
// dead-end panel; an inline panel must not reload or navigate its host's
// page.
const offRenderFailure = hooks.renderFailureNotice?.({
allowReload: !isEmbeddedInline(),
store: useStatusStore(applicationPinia()),
});
if (offRenderFailure) defer(offRenderFailure);
defer(
followWorldTime(viewer, worldTimeFor('sky'), {
subscribe: worldClock.subscribe,
requestRender: () => governorRequestRender('world-time'),
// A playing world time moves something every frame: draw at the
// display's rate meanwhile, not the parked scene's cap.
onPlaying: (playing) =>
playing
? holdContinuousRender('world-time')
: releaseContinuousRender('world-time'),
}),
);
defer(installFreeLookHeightLimit(viewer));
registerDataCredits(viewer, credits);
configureCreditKeyboardAccess(document);
defer(onLocaleChange(() => configureCreditKeyboardAccess(document)));
// The credits, in the application's own line, unless the renderer shows
// them in a display of its own.
if (!hooks.ownCreditDisplay) defer(mountCreditsView(viewer));
loaderStatus.textContent =
googleApiKey || googleTokens || cesiumToken
? t('Loading Google 3D Tiles...')
: t('Loading the keyless globe...');
const photoreal = await loadPhotorealisticTileset(Cesium, {
// The map stacks, and the photoreal base among them, switch through the
// scene's map engine: the renderer's own, or its globe port.
const engine = mapOptions.engine ?? mapEngineFor(viewer);
const photoreal = (await engine.loadPhotoreal?.(viewer, {
googleApiKey,
googleTokens,
cesiumToken,
});
})) ?? { tileset: null, route: 'none', errors: [] };
const tileset = photoreal.tileset;
// A provider can finish after cancellation; retain ownership of its result.
defer(() => {
if (tileset && !tileset.isDestroyed()) {
if (!viewer.scene.primitives.remove(tileset)) tileset.destroy();
}
if (!tileset || engine.isDestroyed(tileset)) return;
engine.removeTileset(viewer, tileset);
engine.release(tileset);
});
signal.throwIfAborted();
if (tileset) {
viewer.scene.primitives.add(tileset);
engine.addTileset(viewer, tileset);
// NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom.
// Google Photorealistic 3D Tiles provide their own terrain/elevation.
viewer.scene.globe.show = false;
renderer.globe.setGlobeVisible(false);
console.info(`[Init] Google 3D Tiles loaded via ${photoreal.route}.`);
} else {
if (photoreal.errors.length) {
@@ -109,7 +214,7 @@ export async function createApplicationScene({
},
);
}
viewer.scene.globe.show = true;
renderer.globe.setGlobeVisible(true);
}
loaderStatus.textContent = t('Initializing systems...');
@@ -117,6 +222,7 @@ export async function createApplicationScene({
const mapStackController = new MapController(viewer, {
requestRender: governorRequestRender,
...mapOptions,
engine,
googleTileset: tileset,
cesiumToken,
initialStack: tileset ? 'photoreal' : 'esri-imagery',
@@ -138,5 +244,22 @@ export async function createApplicationScene({
});
signal.throwIfAborted();
return { viewer, tileset, mapStackController, operations };
return {
renderer,
viewer,
tileset,
mapStackController,
operations,
input,
// Keeps the globe drawing in an inline panel whose host stops animation
// frames (embed mode, src/app/embed.js); returns its disposer.
keepPanelRendering: (options) => keepPanelRendering(renderer, options),
// What the renderer's plugin hands the application beside the contract,
// each optional: trims stale draw commands, says whether an entity is
// the renderer's own, and what QA scripts read
// (render/applicationHooks.js).
trimStaleCommands: hooks.trimStaleCommands,
viewerDrawsEntity: hooks.viewerDrawsEntity,
qaHandles: hooks.qaHandles,
};
}
+152
View File
@@ -0,0 +1,152 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApplicationScene } from './scene.js';
import { createApplicationRequestServices } from '../services/requests.js';
import { createStubRendererPlugin } from '../render/stub/index.js';
import { rendererOf } from '../render/rendererOf.js';
/** Start the scene on a stub renderer with `capabilities`. */
async function startOnStub(t, { capabilities = [], ...rest } = {}) {
document.body.innerHTML = '<div id="cesiumContainer"></div>';
const made = [];
const deferred = [];
t.after(async () => {
for (const fn of deferred.reverse()) await fn();
});
const scene = await createApplicationScene({
renderer: createStubRendererPlugin({ capabilities }, (renderer) =>
made.push(renderer),
),
requestServices: createApplicationRequestServices(),
loaderStatus: { textContent: '' },
signal: new AbortController().signal,
defer: (fn) => deferred.push(fn),
...rest,
});
return { scene, renderer: made[0], deferred };
}
test('the scene runs on a renderer with only the required members', async (t) => {
const { scene, renderer, deferred } = await startOnStub(t);
assert.equal(scene.renderer, renderer);
assert.equal(rendererOf(scene.viewer), renderer, 'the scene object is bound');
assert.equal(
scene.viewer.container,
document.getElementById('cesiumContainer'),
);
assert.equal(scene.viewer.isDestroyed(), false);
assert.ok(
scene.viewer.container.contains(renderer.canvas),
'the renderer fills the container',
);
// Nothing of the engine on the scene object.
assert.deepEqual(Object.keys(scene.viewer).sort(), [
'container',
'isDestroyed',
]);
// No hooks: each is left out, not faked.
for (const name of ['trimStaleCommands', 'viewerDrawsEntity', 'qaHandles'])
assert.equal(scene[name], undefined, name);
// What the renderer does through its ports.
assert.equal(typeof scene.keepPanelRendering, 'function');
assert.equal(
renderer.camera.controls.keepEarthFramed,
undefined,
'no framing on a renderer without it',
);
// Keyless, the map stack shows Esri on the globe through the globe port.
assert.equal(scene.tileset, null);
assert.equal(scene.mapStackController.getActiveId(), 'esri-imagery');
const layers = renderer.globe.imagery.list();
assert.equal(layers.length, 1, 'one base imagery layer');
assert.ok(
renderer.testing.calls.some(
(call) =>
call.port === 'globe' &&
call.member === 'imagery.add' &&
call.args[0]?.url?.includes('World_Imagery'),
),
'Esri imagery through the port',
);
assert.equal(scene.mapStackController.getDrapeSurface(), 'globe');
// The credits show in the application's own line: the Esri base's on it,
// the data credits in the list it opens.
const line = document.getElementById('gev-credits');
assert.ok(line, 'a credits line');
assert.match(line.textContent, /Esri/);
assert.ok(
document.querySelectorAll('#gev-credits-panel li').length > 10,
'the data credits',
);
// Switching stacks goes through the port too.
await scene.mapStackController.setStack('osm');
assert.equal(scene.mapStackController.getActiveId(), 'osm');
assert.equal(renderer.globe.imagery.list().length, 1, 'Esri gave way');
for (const fn of deferred.splice(0).reverse()) await fn();
assert.equal(scene.viewer.isDestroyed(), true);
assert.equal(rendererOf(scene.viewer), null, 'and lets go of the renderer');
assert.equal(renderer.globe.imagery.list().length, 0, 'imagery released');
assert.equal(document.getElementById('gev-credits'), null, 'credits gone');
});
test('the scene keeps the Earth framed where the renderer can', async (t) => {
const { renderer, deferred } = await startOnStub(t, {
capabilities: ['keepEarthFramed'],
});
assert.equal(renderer.camera.controls.keepEarthFramed, true);
const controls = renderer.camera.controls;
for (const fn of deferred.splice(0).reverse()) await fn();
assert.equal(controls.keepEarthFramed, false, 'and lets go on teardown');
});
test("the scene takes a plugin's application hooks", async (t) => {
const stub = createStubRendererPlugin({ capabilities: [] });
const given = [];
const handles = Object.freeze({ probe: 'qa' });
const { scene } = await startOnStub(t, {
renderer: {
id: 'stub-with-hooks',
create: (options) => stub.create(options),
applicationHooks(made) {
given.push(made);
return { qaHandles: handles, ownCreditDisplay: true };
},
},
});
assert.deepEqual(given, [scene.renderer], 'asked once, for the renderer');
assert.equal(scene.qaHandles, handles, 'QA scripts read its handles');
assert.equal(
document.getElementById('gev-credits'),
null,
'its own display shows the credits',
);
});
test('with credentials, the photoreal base loads through the globe port', async (t) => {
const { scene, renderer } = await startOnStub(t, {
capabilities: ['photoreal', 'globeVisibility'],
googleApiKey: 'stub-key',
});
assert.ok(scene.tileset, 'a photoreal base');
assert.equal(scene.mapStackController.getActiveId(), 'photoreal');
assert.equal(renderer.globe.isGlobeVisible(), false, 'the globe is hidden');
const photoreal = renderer.testing.calls.filter(
(call) => call.port === 'globe' && call.member === 'setPhotoreal',
);
assert.equal(photoreal[0]?.args[0]?.key, 'stub-key');
// A globe stack hides photoreal through the port, and shows the globe.
await scene.mapStackController.setStack('esri-imagery');
assert.equal(renderer.globe.isGlobeVisible(), true);
assert.equal(
renderer.testing.calls
.filter((call) => call.port === 'globe' && call.member === 'setPhotoreal')
.at(-1).args[0],
null,
);
await scene.mapStackController.setStack('photoreal');
assert.equal(renderer.globe.isGlobeVisible(), false);
});
+2
View File
@@ -1,3 +1,5 @@
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
import '../render/cesium/input.js';
import assert from 'node:assert/strict';
import test from 'node:test';
import {
+31 -15
View File
@@ -1,25 +1,41 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { flyToAustin } from '../camera.js';
import { applyStartView, START_VIEW } from '../camera.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
test('teardown before the initial camera delay prevents a late flight', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let flights = 0;
let cancelled = 0;
const stop = flyToAustin({
function viewerRecording(views) {
return bindFakeCesiumCamera({
isDestroyed: () => false,
camera: {
setView() {},
flyTo() {
flights++;
setView(view) {
views.push(view);
},
cancelFlight() {
cancelled++;
flyTo() {
assert.fail('a start view is set, not flown to');
},
},
});
stop();
t.mock.timers.tick(1000);
assert.equal(flights, 0);
assert.equal(cancelled, 1);
}
test('the camera starts over the whole planet, looking straight down', () => {
const views = [];
applyStartView(viewerRecording(views));
assert.equal(views.length, 1);
assert.ok(START_VIEW.height >= 20000000, 'the whole planet is in view');
assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 2) < 1e-9);
assert.equal(views[0].orientation.heading, 0);
});
test('a host can start the camera at a city instead', () => {
const views = [];
applyStartView(viewerRecording(views), {
lon: 2.35,
lat: 48.86,
height: 5000,
heading: 90,
pitch: -30,
});
assert.equal(views.length, 1);
assert.ok(Math.abs(views[0].orientation.heading - Math.PI / 2) < 1e-9);
assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 6) < 1e-9);
});
+40 -28
View File
@@ -1,3 +1,4 @@
import { onFollowChanged } from '../data/followed.js';
import { SceneDirector } from '../scenes/director.js';
import { initAnnotations } from '../annotations/index.js';
import { initDrawTool } from '../annotations/drawTool.js';
@@ -24,17 +25,22 @@ import {
isScopeMaskEnabled,
} from '../scopeMask.js';
import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js';
import { installGlobeInViewRecovery } from './viewer.js';
import { installGlobeInViewRecovery } from './globeInViewRecovery.js';
import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
import {
installRenderGovernor,
getRenderGovernorDiagnostics,
governorRequestRender,
holdContinuousRender,
releaseContinuousRender,
} from '../renderGovernor.js';
import { entityRecord, readEntityRecord } from '../data/entityRecords.js';
import { overlayHost } from './layers/overlayHost.js';
/** Attach scene tools, rendering listeners and the application debug handle. */
/**
* Attach scene tools, rendering listeners and the application debug handle.
* `scene` is what `createApplicationScene` returns; its `trimStaleCommands`
* runs after each layer disable (a scene without one keeps that memory).
*/
export function createApplicationTools({
scene,
controls,
@@ -49,11 +55,11 @@ export function createApplicationTools({
signal,
defer,
}) {
const { viewer, tileset, mapStackController, operations } = scene;
const { viewer, renderer, tileset, mapStackController, operations } = scene;
const { styleManager, weatherEffects, cockpitCloudEffects } = controls;
const { dataManager } = data;
const sceneDirector = new SceneDirector(viewer, styleManager, dataManager, {
dataPacks: sceneDataPacks,
dataPacks: { overlayHost, ...sceneDataPacks },
isMapStackAvailable: (id) =>
mapStackController?.isStackAvailable(id) === true,
});
@@ -198,19 +204,21 @@ export function createApplicationTools({
}
if (startChrome)
defer(startChrome({ loadingScreen, styleManager, dataManager, signal }));
// Idle render governor: flips the scene into requestRenderMode whenever
// nothing animates per frame. Installed AFTER every module above has had
// its chance to register pre-install holds. (perf wave 2)
installRenderGovernor(viewer);
// Cesium keeps a turned-off layer's draw commands (and so all its entities)
// alive in reused per-pass arrays; trim them after each disable.
defer(
installLayerReleaseTrim({
scene: viewer.scene,
dataManager,
requestRender: governorRequestRender,
}),
);
// Idle render governor: the loop draws on demand whenever nothing animates
// per frame. It goes idle only now, after every module above has had its
// chance to hold. (perf wave 2)
releaseContinuousRender('boot');
// The renderer may keep a turned-off layer's draw commands (and so all its
// entities) alive; trim them after each disable.
if (scene.trimStaleCommands)
defer(
installLayerReleaseTrim({
frame: renderer.frame,
dataManager,
requestRender: governorRequestRender,
trim: scene.trimStaleCommands,
}),
);
// Install the explicit scope mask used by the DISPLAY controls.
installScopeMask(viewer);
@@ -218,12 +226,10 @@ export function createApplicationTools({
// The follow camera recomputes the tracked target's dead-reckon position
// every frame — tracking anything is a per-frame animation. (perf wave 2)
const removeTrackingListener = viewer.trackedEntityChanged.addEventListener(
() => {
if (viewer.trackedEntity) holdContinuousRender('tracked-entity');
else releaseContinuousRender('tracked-entity');
},
);
const removeTrackingListener = onFollowChanged(viewer, (followed) => {
if (followed) holdContinuousRender('tracked-entity');
else releaseContinuousRender('tracked-entity');
});
// Hidden-state suspension (perf wave 2): when the window/tab is hidden,
// stop the default render loop outright — a hidden canvas repaints for
@@ -232,9 +238,9 @@ export function createApplicationTools({
// the loop, refresh the one DOM surface we gated, render a frame.
const syncVisibilitySuspension = () => {
// A panel's host may report it hidden while it is on screen; the panel
// keeps drawing itself (see keepPanelRendering in embed.js).
// keeps drawing itself (see keepPanelRendering in app/panelRendering.js).
const hidden = document.hidden && !isEmbeddedInline();
viewer.useDefaultRenderLoop = !hidden;
renderer.frame.suspend(hidden);
cockpitCloudEffects?.setSuspended?.(hidden);
if (!hidden) {
data.presentation.flushVisible();
@@ -267,6 +273,10 @@ export function createApplicationTools({
getRenderGovernorDiagnostics,
surfaceServices: operations.surface,
requestRender: governorRequestRender,
entityRecords: { read: readEntityRecord, write: entityRecord },
// What the renderer's plugin lets QA scripts read (the Cesium viewer,
// for the default renderer), in place of the scene object above.
...scene.qaHandles,
};
const debug = window.__godsEyeView;
defer(() => {
@@ -299,11 +309,13 @@ export function createApplicationTools({
run: (name, args, options = {}) =>
voiceCommands.runner(name, args, { ...options, signal }),
signal,
keepRendering: scene.keepPanelRendering,
terrain: operations.requests.terrain,
}),
);
// An application's own tool takes the pointer as Draw does, and its own
// click handlers yield while a tool holds it, as the layers' do
// Any other tool takes the pointer as Draw does (the newest
// claim takes over; `claim(owner, {onLost})` tells the tool it replaces),
// and its own click handlers yield while a tool holds it, as the layers' do
// (data/inputOwnership.js).
return {
sceneDirector,
-432
View File
@@ -1,432 +0,0 @@
import * as Cesium from 'cesium';
import { applyModelAtmosphereWorkaround } from './atmosphereCompat.js';
import { StarrySky } from '../sky/starrySky.js';
import {
FREE_LOOK_MAX_HEIGHT_METERS,
globeOutOfFrame,
isFreeGlobeCamera,
} from '../globeInView.js';
/**
* At the farthest a hand can zoom out, the globe is this share of the
* screen's height across. Cesium sets no limit, so zooming on left the globe
* a speck among the stars.
*/
const MIN_GLOBE_SHARE = 0.3;
/**
* The farthest a hand can zoom out, in metres above the ellipsoid, for a
* vertical field of view. It follows the screen's shape, as the app's own
* whole-globe view does, so that view always lies within it.
* @param {number} fovy Vertical field of view, radians.
*/
export function zoomOutLimit(fovy) {
const radius = Cesium.Ellipsoid.WGS84.maximumRadius;
const angular = Math.atan(MIN_GLOBE_SHARE * Math.tan(fovy / 2));
return radius / Math.sin(angular) - radius;
}
/**
* Hold a hand's zoom out to `zoomOutLimit` on the globe, each frame, since the
* field of view follows the screen's shape. The limit never sits below the
* camera: one already past it (a flight, a screen turned) stops there rather
* than jumping in at the next zoom. Flat maps keep Cesium's own, unlimited.
* @returns {() => void} Stop limiting.
*/
export function limitZoomOut(viewer) {
const { scene, camera } = viewer;
return scene.preRender.addEventListener(() => {
const controller = scene.screenSpaceCameraController;
const fovy = camera.frustum.fovy;
if (scene.mode !== Cesium.SceneMode.SCENE3D || !Number.isFinite(fovy)) {
controller.maximumZoomDistance = Number.POSITIVE_INFINITY;
return;
}
controller.maximumZoomDistance = Math.max(
zoomOutLimit(fovy),
camera.positionCartographic?.height ?? 0,
);
});
}
const PINCH_ZOOM_MULTIPLIER = 8;
const MAX_PINCH_PIXEL_DELTA = 120;
function boundedPinchDelta(delta) {
if (!Number.isFinite(delta) || delta === 0) return delta;
return (
Math.sign(delta) *
Math.min(Math.abs(delta) * PINCH_ZOOM_MULTIPLIER, MAX_PINCH_PIXEL_DELTA)
);
}
/**
* Add browser trackpad pinch to Cesium's zoom inputs and return its disposer.
* Browsers expose this gesture as a small pixel-mode Ctrl+wheel event.
*/
export function installTrackpadPinchZoom(
viewer,
{ createWheelEvent = (type, init) => new WheelEvent(type, init) } = {},
) {
const controller = viewer?.scene?.screenSpaceCameraController;
const container = viewer?.container;
const canvas = viewer?.canvas;
if (!controller || !container || !canvas)
throw new TypeError('A complete Cesium viewer is required');
const originalZoomEventTypes = controller.zoomEventTypes;
const zoomEventTypes = Array.isArray(originalZoomEventTypes)
? originalZoomEventTypes
: originalZoomEventTypes === undefined
? []
: [originalZoomEventTypes];
const alreadyHandlesControlWheel = zoomEventTypes.some(
(binding) =>
binding?.eventType === Cesium.CameraEventType.WHEEL &&
binding?.modifier === Cesium.KeyboardEventModifier.CTRL,
);
const configuredZoomEventTypes = alreadyHandlesControlWheel
? originalZoomEventTypes
: [
...zoomEventTypes,
{
eventType: Cesium.CameraEventType.WHEEL,
modifier: Cesium.KeyboardEventModifier.CTRL,
},
];
if (!alreadyHandlesControlWheel)
controller.zoomEventTypes = configuredZoomEventTypes;
const relayedEvents = new WeakSet();
const relayPinch = (event) => {
if (
!event.ctrlKey ||
relayedEvents.has(event) ||
event.deltaMode !== 0 ||
!Number.isFinite(event.deltaY) ||
event.deltaY === 0
)
return;
let relayed;
try {
relayed = createWheelEvent('wheel', {
deltaX: event.deltaX,
deltaY: boundedPinchDelta(event.deltaY),
deltaZ: event.deltaZ,
deltaMode: event.deltaMode,
screenX: event.screenX,
screenY: event.screenY,
clientX: event.clientX,
clientY: event.clientY,
ctrlKey: true,
bubbles: true,
cancelable: true,
view: globalThis.window,
});
} catch {
// The registered Ctrl+wheel binding can still consume the original.
return;
}
relayedEvents.add(relayed);
event.preventDefault();
event.stopPropagation();
canvas.dispatchEvent(relayed);
};
container.addEventListener('wheel', relayPinch, {
capture: true,
passive: false,
});
let active = true;
return () => {
if (!active) return;
active = false;
container.removeEventListener('wheel', relayPinch, true);
if (
!alreadyHandlesControlWheel &&
controller.zoomEventTypes === configuredZoomEventTypes
)
controller.zoomEventTypes = originalZoomEventTypes;
};
}
/**
* Allow Cesium's free look only below `maxHeight` and return its disposer.
* Orbit, tilt and zoom stay available at every height. A value other code
* sets later is kept as the one to allow below that height, and restored on
* dispose; a `false` written while the camera is above `maxHeight` cannot be
* told apart from this limit's own write, so dispose restores the earlier
* value then. `enableLook` gates the Shift+drag binding only: below its trackball
* height Cesium also turns the camera in place for a drag that starts on the
* stars. That height is lowered to `maxHeight` too, so above it such a drag
* orbits the globe, as it does above Cesium's own 7,500 km.
*/
export function installFreeLookHeightLimit(
viewer,
maxHeight = FREE_LOOK_MAX_HEIGHT_METERS,
) {
const scene = viewer?.scene;
const controller = scene?.screenSpaceCameraController;
const camera = viewer?.camera;
if (!controller || !camera || !scene?.preUpdate)
throw new TypeError('A complete Cesium viewer is required');
const originalTrackBallHeight = controller.minimumTrackBallHeight;
const trackBallHeight = Math.min(originalTrackBallHeight, maxHeight);
controller.minimumTrackBallHeight = trackBallHeight;
let wanted = controller.enableLook;
let written;
const sync = () => {
if (written !== undefined && controller.enableLook !== written)
wanted = controller.enableLook;
const height = camera.positionCartographic?.height;
written = wanted && !(Number.isFinite(height) && height > maxHeight);
controller.enableLook = written;
};
sync();
const removeListener = scene.preUpdate.addEventListener(sync);
let active = true;
return () => {
if (!active) return;
active = false;
removeListener();
if (controller.enableLook === written) controller.enableLook = wanted;
if (controller.minimumTrackBallHeight === trackBallHeight)
controller.minimumTrackBallHeight = originalTrackBallHeight;
};
}
// How often a moving camera is sampled to see whether it has come to rest, how
// far a pose may drift between samples and still count as at rest, and how
// long after the camera last moved the check gives up if Cesium never raises
// moveEnd.
const SETTLE_SAMPLE_MS = 250;
const SETTLE_POSITION_TOLERANCE_M = 1e-3;
const SETTLE_DIRECTION_TOLERANCE = 1e-9;
const SETTLE_GIVE_UP_MS = 5 * 60_000;
/**
* Turn the camera back to the planet when a move ends above `minHeight` with
* no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about
* one sample cell thick can count as none), and return the disposer. Views with
* more surface, such as an oblique orbital shot, are left as they are. This
* catches a saved or shared view that looked away, or any other move that ends
* looking away from the planet.
* Heading and position are kept. Tracked cameras, locked ones (non-identity
* transform), a camera flight in progress, a pointer held down on the canvas
* (a drag held still), the 2D and Columbus modes, and any time `paused`
* returns true (an authored scene playing) are left alone; a check they defer
* runs once they end, however long they last.
* `keyholeRadius`
* returns the radius of the visible circle when a scope mask hides the rest of
* the frame (see `globeFrameShare`), or 0; it is read at every check.
*
* Cesium's `moveEnd` alone is not enough: Cesium compares the camera with the
* last frame's to the last rounding error, and at some of these poses the
* camera drifts by a rounding error every frame, so Cesium never sees it stop.
* So each `moveStart` also starts a check of its own that samples the pose
* every 250 ms, with a tolerance for that drift, and once the pose has held
* for half a second after moving runs the same recovery. It keeps watching
* until Cesium raises `moveEnd`, since under that drift Cesium raises no new
* `moveStart` for a later move, and gives up five minutes after the camera
* last moved.
* `setTimeout` and `clearTimeout` can be injected for tests.
*/
export function installGlobeInViewRecovery(
viewer,
{
minHeight = FREE_LOOK_MAX_HEIGHT_METERS,
keyholeRadius = () => 0,
paused = () => false,
setTimeout: schedule = globalThis.setTimeout,
clearTimeout: unschedule = globalThis.clearTimeout,
} = {},
) {
const scene = viewer?.scene;
const camera = viewer?.camera;
if (!scene || !camera?.moveEnd || !camera?.moveStart)
throw new TypeError('A complete Cesium viewer is required');
// A pointer held on the globe is a gesture in progress, even when it holds
// still for half a second: the check waits until every pointer pressed on
// it (each finger of a pinch) is released. A release the page never sees,
// outside the window, is taken as given when the window loses focus, the
// page is hidden, the canvas loses the pointer's capture, or the pointer
// moves with no button down.
const canvas = scene.canvas;
const releaseTarget = canvas?.ownerDocument ?? canvas;
const releaseWindow = canvas?.ownerDocument?.defaultView;
const heldPointers = new Set();
const onPointerDown = (event) => heldPointers.add(event?.pointerId);
const onPointerUp = (event) => heldPointers.delete(event?.pointerId);
const onPointerMove = (event) => {
if (event?.buttons === 0) heldPointers.delete(event.pointerId);
};
const releaseAll = () => heldPointers.clear();
const onVisibilityChange = () => {
if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll();
};
const listeners = [
[canvas, 'pointerdown', onPointerDown],
[canvas, 'lostpointercapture', onPointerUp],
[releaseTarget, 'pointerup', onPointerUp],
[releaseTarget, 'pointercancel', onPointerUp],
[releaseTarget, 'pointermove', onPointerMove],
[canvas?.ownerDocument, 'visibilitychange', onVisibilityChange],
[releaseWindow, 'blur', releaseAll],
];
for (const [target, type, listener] of listeners)
target?.addEventListener?.(type, listener);
// Returns false while a flight, a paused scene or a held pointer defers the
// check, so the caller can try again once it ends.
const recover = () => {
if (!isFreeGlobeCamera(viewer)) return true;
// Cesium has no public running-flight flag.
if (camera._currentFlight || paused() || heldPointers.size > 0)
return false;
const height = camera.positionCartographic?.height;
if (
!(height > minHeight) ||
!globeOutOfFrame(camera, { keyholeRadius: keyholeRadius() })
)
return true;
camera.setView({
orientation: {
heading: camera.heading,
pitch: -Cesium.Math.PI_OVER_TWO,
roll: 0,
},
});
scene.requestRender?.();
return true;
};
const lastPosition = new Cesium.Cartesian3();
const lastDirection = new Cesium.Cartesian3();
let settleTimer = null;
let settleElapsed = 0;
let restingSamples = 0;
let movedSinceCheck = false;
const stopSettling = () => {
if (settleTimer !== null) unschedule(settleTimer);
settleTimer = null;
};
const sample = () => {
settleTimer = null;
settleElapsed += SETTLE_SAMPLE_MS;
const atRest =
Cesium.Cartesian3.equalsEpsilon(
camera.positionWC,
lastPosition,
0,
SETTLE_POSITION_TOLERANCE_M,
) &&
Cesium.Cartesian3.equalsEpsilon(
camera.directionWC,
lastDirection,
0,
SETTLE_DIRECTION_TOLERANCE,
);
restingSamples = atRest ? restingSamples + 1 : 0;
if (!atRest) {
movedSinceCheck = true;
settleElapsed = 0;
}
// Two quiet samples in a row after a move: at rest for half a second, as
// for moveEnd.
if (restingSamples >= 2 && movedSinceCheck) {
if (recover()) movedSinceCheck = false;
// A flight or a playing scene bounds its own deferral.
else settleElapsed = 0;
}
if (settleElapsed >= SETTLE_GIVE_UP_MS) return;
Cesium.Cartesian3.clone(camera.positionWC, lastPosition);
Cesium.Cartesian3.clone(camera.directionWC, lastDirection);
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const startSettling = () => {
stopSettling();
settleElapsed = 0;
restingSamples = 0;
movedSinceCheck = true;
Cesium.Cartesian3.clone(camera.positionWC, lastPosition);
Cesium.Cartesian3.clone(camera.directionWC, lastDirection);
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const removeMoveEnd = camera.moveEnd.addEventListener(() => {
if (recover()) stopSettling();
// Deferred: keep sampling so the check runs once the flight or scene ends.
else if (settleTimer === null) startSettling();
});
const removeMoveStart = camera.moveStart.addEventListener(startSettling);
let active = true;
return () => {
if (!active) return;
active = false;
stopSettling();
removeMoveEnd();
removeMoveStart();
for (const [target, type, listener] of listeners)
target?.removeEventListener?.(type, listener);
heldPointers.clear();
};
}
/** Cesium.Viewer options of the standard globe viewer. */
export function applicationViewerOptions(creditContainer) {
return {
timeline: false,
animation: false,
baseLayerPicker: false,
geocoder: false,
homeButton: false,
sceneModePicker: false,
navigationHelpButton: false,
fullscreenButton: false,
vrButton: false,
selectionIndicator: false,
infoBox: false,
baseLayer: false,
// Replaces the blocky Tycho-2 default. An option, not `skyBox: false`,
// which would also stop CesiumWidget from creating the Sun and Moon.
skyBox: new StarrySky(),
creditContainer,
msaaSamples: 4,
contextOptions: { webgl: { preserveDrawingBuffer: true } },
};
}
/** Create the standard globe viewer in caller-owned, visible containers. */
export function createApplicationViewer({ container, creditContainer }) {
if (!container || !creditContainer)
throw new TypeError('Viewer and credit containers are required');
const viewer = new Cesium.Viewer(
container,
applicationViewerOptions(creditContainer),
);
try {
viewer.targetFrameRate = 60;
// A phone pinch spans fewer screen pixels than desktop zoom gestures.
// Keep Cesium's distance-aware zoom and collision limits, with less travel
// required on touch-first screens. Mouse/trackpad sensitivity stays native.
if (globalThis.matchMedia?.('(pointer: coarse)').matches)
viewer.scene.screenSpaceCameraController.zoomFactor *= 3;
limitZoomOut(viewer);
// Before any tile builds a draw command: Cesium's per-vertex model
// atmosphere fails to LINK on Apple's Metal backend and kills the
// render loop. See app/atmosphereCompat.js.
applyModelAtmosphereWorkaround(viewer.scene);
viewer.scene.globe.show = false;
viewer.scene.skyAtmosphere.show = true;
viewer.scene.skyAtmosphere.atmosphereLightIntensity = 18;
viewer.scene.skyAtmosphere.saturationShift = -0.12;
viewer.scene.skyAtmosphere.brightnessShift = -0.08;
return viewer;
} catch (error) {
viewer.destroy();
throw error;
}
}
+7 -10
View File
@@ -6,11 +6,12 @@
* awareness policy of its own: the publisher passes radius, pulse timing and
* echo styling in, so the overlay never imports awareness internals.
*/
import * as Cesium from 'cesium';
import { scaleToGeodeticSurface } from './geo/ellipsoid.js';
import { distance } from './geo/vector.js';
/**
* @typedef {object} AwarenessEchoField
* @property {Cesium.Cartesian3} center Subject's ground point. The publisher
* @property {{x: number, y: number, z: number}} center Subject's ground point. The publisher
* may move it in place; it is read on every query.
* @property {number} radiusM Range the pulses grow to.
* @property {{count: number, periodMs: number, startFraction: number, fadeInFraction?: number}} pulse
@@ -22,7 +23,6 @@ import * as Cesium from 'cesium';
/** @type {AwarenessEchoField|null} */
let field = null;
let layerIds = new Set();
const groundScratch = new Cesium.Cartesian3();
/**
* Start (or replace) the echo field.
@@ -104,7 +104,7 @@ export function awarenessEchoStrength(nowMs, distanceM, radiusM, pulse, echo) {
* field is set or the layer does not echo. Distance is measured between
* ground points, so an aircraft's altitude does not shift its echo.
* @param {string} layerId Owning layer of the contact.
* @param {Cesium.Cartesian3} position Contact's world position.
* @param {{x: number, y: number, z: number}} position Contact's world position.
* @param {number} nowMs Monotonic clock in milliseconds.
* @returns {number} 0 to 1.
*/
@@ -112,16 +112,13 @@ export function awarenessEchoAt(layerId, position, nowMs) {
if (!field || !position || !layerIds.has(layerId)) return 0;
const level = field.level?.(nowMs) ?? 1;
if (!(level > 0)) return 0;
const ground = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(
position,
groundScratch,
);
const ground = scaleToGeodeticSurface(position);
if (!ground) return 0;
return (
level *
awarenessEchoStrength(
nowMs,
Cesium.Cartesian3.distance(field.center, ground),
distance(field.center, ground),
field.radiusM,
field.pulse,
field.echo,
@@ -138,7 +135,7 @@ export function awarenessEchoAt(layerId, position, nowMs) {
* outside the contact's bracket, 0 as the front arrives, growing to the
* field's `spreadPx` as it fades.
* @param {string} layerId Owning layer of the contact.
* @param {Cesium.Cartesian3} position Contact's world position.
* @param {{x: number, y: number, z: number}} position Contact's world position.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {number} bracketAlpha The contact bracket's drawn alpha, 0 to 1.
* @param {number} steps Alpha bands the overlay batches by.
+22 -29
View File
@@ -1,36 +1,29 @@
import * as Cesium from 'cesium';
import { toRadians } from './geo/index.js';
import { cameraOf } from './render/rendererOf.js';
/**
* Set camera to Austin on load with a cinematic fly-in.
* @returns {Function} Cancels the pending or active startup flight.
* The view the renderer starts from: the whole planet, looking straight
* down, centred where Cesium's default view rectangle is.
*/
export function flyToAustin(viewer) {
// Start from a high altitude, then fly down
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 25000),
export const START_VIEW = Object.freeze({
lon: -82.5,
lat: 35,
height: 23000000,
});
/**
* Put the camera at a start view without a flight. A host may pass a city
* (`{ lon, lat, height, heading?, pitch? }`, angles in degrees) instead of
* the planet.
*/
export function applyStartView(viewer, view = START_VIEW) {
const { lon, lat, height, heading = 0, pitch = -90 } = view;
cameraOf(viewer).setView({
destination: { lon, lat, height },
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-90),
roll: 0.0,
heading: toRadians(heading),
pitch: toRadians(pitch),
roll: 0,
},
});
// Cinematic fly-in after a brief pause
const timer = setTimeout(() => {
if (viewer.isDestroyed()) return;
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 600),
orientation: {
heading: Cesium.Math.toRadians(15),
pitch: Cesium.Math.toRadians(-30),
roll: 0.0,
},
duration: 4.0,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
});
}, 500);
return () => {
clearTimeout(timer);
if (!viewer.isDestroyed()) viewer.camera.cancelFlight();
};
}
+103 -161
View File
@@ -1,3 +1,14 @@
import {
bindFakeCesiumCamera,
followEntity,
followedEntity,
} from './testSupport/fakeCameraPort.mjs';
import { rendererOf } from './render/rendererOf.js';
import { followedOf } from './data/followed.js';
import {
fakeSceneFrame,
fakeSceneQuery,
} from './testSupport/fakeCesiumScene.mjs';
import { GLOBE_VIEW } from './locations.js';
import { projectEarthDiscToViewport } from './celestialRing.js';
import assert from 'node:assert/strict';
@@ -13,11 +24,24 @@ import {
moveCamera,
} from './cameraVerbs.js';
import { getRenderGovernorDiagnostics } from './renderGovernor.js';
import {
MIN_GLOBE_FRAME_SHARE,
globeFrameShare,
globeOutOfFrame,
} from './globeInView.js';
import { MIN_GLOBE_FRAME_SHARE } from './globeInView.js';
import * as globeInView from './globeInView.js';
// The frame measures take a camera pose; these read it off the real camera.
const framePose = (camera) => ({
position: camera.positionWC,
direction: camera.directionWC,
up: camera.upWC,
right: camera.rightWC,
fovy: camera.frustum.fovy,
aspectRatio: camera.frustum.aspectRatio,
height: camera.positionCartographic.height,
pitch: camera.pitch,
});
const globeFrameShare = (camera, options) =>
globeInView.globeFrameShare(framePose(camera), options);
const globeOutOfFrame = (camera, options) =>
globeInView.globeOutOfFrame(framePose(camera), options);
import { KEYHOLE_OUTER_RADIUS } from './celestialRing.js';
import { setScopeMaskEnabled } from './scopeMask.js';
@@ -136,7 +160,7 @@ function harness(
mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL,
mode: Cesium.SceneMode.SCENE3D,
pixelRatio: 1,
tweens: [],
preUpdate: new Cesium.Event(),
requestRender() {},
};
const camera = new Cesium.Camera(scene);
@@ -154,13 +178,37 @@ function harness(
roll: radians(roll),
},
});
const viewer = {
const double = {
camera,
scene,
trackedEntity: undefined,
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
clock: { onTick: new Cesium.Event() },
entities: {},
};
const viewer = bindFakeCesiumCamera(double, {
query: fakeSceneQuery(double),
frame: fakeSceneFrame(double),
});
// Count who listens for the port's follow changes.
const renderer = rendererOf(viewer);
const port = renderer.camera;
let followListeners = 0;
renderer.camera = Object.create(port, {
on: {
value(event, cb, options) {
const off = port.on(event, cb, options);
if (event !== 'followChanged') return off;
followListeners += 1;
let live = true;
return () => {
if (live) followListeners -= 1;
live = false;
off();
};
},
},
});
const target = Cesium.Cartesian3.fromDegrees(
longitudeDeg,
latitude,
@@ -174,73 +222,21 @@ function harness(
});
const tick = (seconds = 0.1) => {
nowMs += seconds * 1000;
viewer.clock.onTick.raiseEvent(viewer.clock);
viewer.scene.preUpdate.raiseEvent(viewer.scene);
};
const finishOnce = () => {
for (let i = 0; i < 20 && getActiveCameraMotion(); i += 1) tick();
assert.equal(getActiveCameraMotion(), null, 'once motion must finish');
};
return { viewer, camera, canvas, target, tick, finishOnce };
}
for (const [name, sceneMode] of [
['2D', Cesium.SceneMode.SCENE2D],
['Columbus', Cesium.SceneMode.COLUMBUS_VIEW],
['morphing', Cesium.SceneMode.MORPHING],
]) {
test(`globe rotation refuses ${name} before changing the prior owner`, (t) => {
const { viewer, camera } = harness(t);
assert.equal(
moveCamera({ motion: 'rotate', direction: 'right', mode: 'continuous' })
.ok,
true,
);
const priorId = activeCameraMotionId();
const before = pose(camera);
const transform = Cesium.Matrix4.clone(camera.transform);
viewer.scene.mode = sceneMode;
let handoffs = 0;
let cancellations = 0;
camera.cancelFlight = () => {
cancellations += 1;
};
for (const mode of ['once', 'continuous']) {
const result = moveCamera(
{ motion: 'rotate_globe', direction: 'left', mode },
() => {
handoffs += 1;
return { ok: true };
},
);
assert.equal(result.ok, false);
assert.match(result.error, /3D/);
}
assert.equal(handoffs, 0);
assert.equal(cancellations, 0);
assert.equal(activeCameraMotionId(), priorId);
assert.equal(hasRenderHold(), true);
assert.ok(Cesium.Matrix4.equals(camera.transform, transform));
samePose(camera, before);
});
test(`active globe rotation yields to ${name} without changing the camera`, (t) => {
const { viewer, camera, tick } = harness(t);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
true,
);
viewer.scene.mode = sceneMode;
const before = pose(camera);
let rotations = 0;
camera.rotate = () => {
rotations += 1;
};
tick();
assert.equal(rotations, 0);
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
samePose(camera, before);
});
return {
viewer,
camera,
canvas,
target,
tick,
finishOnce,
followListeners: () => followListeners,
};
}
test('globe rotation yields to tracking acquired and cleared before the next tick', (t) => {
@@ -251,15 +247,13 @@ test('globe rotation yields to tracking acquired and cleared before the next tic
);
const before = pose(camera);
const entity = { id: 'cockpit-aircraft', position: {} };
viewer.trackedEntity = entity;
viewer.trackedEntityChanged.raiseEvent(entity);
followEntity(viewer, entity);
assert.equal(
getActiveCameraMotion(),
null,
'tracking acquisition must synchronously yield',
);
viewer.trackedEntity = undefined;
viewer.trackedEntityChanged.raiseEvent(undefined);
followEntity(viewer, null);
tick();
samePose(camera, before);
assert.equal(hasRenderHold(), false);
@@ -272,33 +266,34 @@ test('tracking event keeps legacy yaw and an untracked globe rotation active', (
true,
);
const yawId = activeCameraMotionId();
viewer.trackedEntityChanged.raiseEvent({ id: 'aircraft' });
followEntity(viewer, { id: 'aircraft' });
assert.equal(activeCameraMotionId(), yawId);
followEntity(viewer, null);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
true,
);
const globeId = activeCameraMotionId();
viewer.trackedEntityChanged.raiseEvent(undefined);
followEntity(viewer, null);
assert.equal(activeCameraMotionId(), globeId);
});
test('replaced viewer releases the old tracking listener without duplicate subscriptions', (t) => {
const first = harness(t);
assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1);
assert.equal(first.followListeners(), 1);
initCameraVerbs(first.viewer);
assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1);
assert.equal(first.followListeners(), 1);
const next = harness(t);
assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 0);
assert.equal(next.viewer.trackedEntityChanged.numberOfListeners, 1);
assert.equal(first.followListeners(), 0);
assert.equal(next.followListeners(), 1);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
true,
);
const id = activeCameraMotionId();
first.viewer.trackedEntityChanged.raiseEvent({ id: 'stale-aircraft' });
followEntity(first.viewer, { id: 'stale-aircraft' });
assert.equal(activeCameraMotionId(), id);
next.viewer.trackedEntityChanged.raiseEvent({ id: 'new-aircraft' });
followEntity(next.viewer, { id: 'new-aircraft' });
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
});
@@ -534,7 +529,7 @@ test('replacement motion rejects a stale globe owner cancellation', (t) => {
assert.equal(hasRenderHold(), false);
});
test('replacing the viewer retires globe motion and its old clock listener', (t) => {
test('replacing the viewer retires globe motion and its old frame listener', (t) => {
const { viewer, camera, tick } = harness(t);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
@@ -542,15 +537,16 @@ test('replacing the viewer retires globe motion and its old clock listener', (t)
);
tick();
const before = pose(camera);
const nextViewer = {
...viewer,
clock: { onTick: new Cesium.Event() },
};
const nextScene = { ...viewer.scene, preUpdate: new Cesium.Event() };
const nextViewer = bindFakeCesiumCamera(
{ ...viewer, scene: nextScene },
{ frame: fakeSceneFrame({ scene: nextScene }) },
);
initCameraVerbs(nextViewer);
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
tick();
nextViewer.clock.onTick.raiseEvent(nextViewer.clock);
nextScene.preUpdate.raiseEvent(nextScene);
samePose(camera, before);
});
@@ -580,7 +576,7 @@ for (const mode of ['once', 'continuous']) {
tick();
assert.equal(hasRenderHold(), true);
const tracked = { id: 'new-tracked-aircraft' };
if (acquisition === 'tracking') viewer.trackedEntity = tracked;
if (acquisition === 'tracking') followEntity(viewer, tracked);
else
camera.lookAt(
target,
@@ -591,10 +587,9 @@ for (const mode of ['once', 'continuous']) {
tick();
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
assert.equal(
viewer.trackedEntity,
acquisition === 'tracking' ? tracked : undefined,
);
if (acquisition === 'tracking')
assert.equal(followedEntity(viewer), tracked);
else assert.equal(followedOf(viewer), null);
assert.equal(Cesium.Matrix4.equals(camera.transform, transform), true);
samePose(camera, before);
tick();
@@ -605,7 +600,7 @@ for (const mode of ['once', 'continuous']) {
test('direct globe rotation refuses a tracked camera without disturbing its reference frame', (t) => {
const { viewer, camera, target } = harness(t);
viewer.trackedEntity = { id: 'tracked-aircraft' };
followEntity(viewer, { id: 'tracked-aircraft', name: 'tracked-aircraft' });
camera.lookAt(target, new Cesium.HeadingPitchRange(0, radians(-40), 1_000));
const before = pose(camera);
const transform = Cesium.Matrix4.clone(camera.transform);
@@ -676,18 +671,19 @@ test('close-up refusal preserves an inherited target frame', (t) => {
});
test('navigation callback never releases tracking for globe rotation', (t) => {
const { viewer, camera } = harness(t);
const tracked = (viewer.trackedEntity = { id: 'tracked-aircraft' });
const tracked = { id: 'tracked-aircraft' };
followEntity(viewer, tracked);
const before = pose(camera);
let calls = 0;
assert.equal(
moveCamera({ motion: 'rotate_globe' }, () => {
calls++;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
}).ok,
false,
);
assert.equal(calls, 0);
assert.equal(viewer.trackedEntity, tracked);
assert.equal(followedEntity(viewer), tracked);
samePose(camera, before);
});
test('direct globe request refuses Cockpit before navigation mutation', (t) => {
@@ -878,8 +874,8 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
height: owner === 'close-up' ? 5000 : GLOBE_VIEW.heightM,
});
const before = pose(camera);
if (owner === 'tracking') viewer.trackedEntity = { id: 'tracked-aircraft' };
const tracked = viewer.trackedEntity;
if (owner === 'tracking') followEntity(viewer, { id: 'tracked-aircraft' });
const tracked = followedEntity(viewer);
let releases = 0,
stamps = 0;
const styleManager = {
@@ -893,7 +889,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
},
release() {
releases++;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
},
navigate,
});
@@ -915,7 +911,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
assert.equal(result.ok, false);
assert.equal(releases, 0);
assert.equal(stamps, 0);
assert.equal(viewer.trackedEntity, tracked);
assert.equal(followedEntity(viewer), tracked);
samePose(camera, before);
if (owner === 'close-up') {
assert.equal(result.reason, 'globe-view-required');
@@ -926,29 +922,6 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
}
});
for (const [label, ellipsoid] of [
['nonfinite radii', { minimumRadius: 1, maximumRadius: Infinity }],
['nonpositive radii', { minimumRadius: 0, maximumRadius: 1 }],
['non-WGS84 radii', new Cesium.Ellipsoid(30_000_000, 30_000_000, 1_000_000)],
])
test(`globe rotation refuses ${label} before handoff`, (t) => {
const { viewer, camera } = harness(t, { height: 100_000_000 });
const before = pose(camera);
viewer.scene.globe.ellipsoid = ellipsoid;
let handedOff = false;
const result = moveCamera({ motion: 'rotate_globe' }, () => {
handedOff = true;
});
assert.equal(result.ok, false);
assert.equal(
result.reason,
label === 'non-WGS84 radii' ? 'unsupported-view' : 'unsafe-ellipsoid',
);
assert.equal(handedOff, false);
assert.equal(hasRenderHold(), false);
samePose(camera, before);
});
test('an external radius change retires globe rotation without another write', (t) => {
const { camera, tick } = harness(t);
moveCamera({ motion: 'rotate_globe', mode: 'continuous' });
@@ -960,16 +933,6 @@ test('an external radius change retires globe rotation without another write', (
samePose(camera, changed);
});
test('a non-WGS84 ellipsoid fails closed rather than borrowing the WGS84 silhouette', (t) => {
const ellipsoid = new Cesium.Ellipsoid(10_000_000, 10_000_000, 8_000_000);
const { camera } = harness(t, { ellipsoid, latitude: 60 });
const before = pose(camera);
const result = moveCamera({ motion: 'rotate_globe' });
assert.equal(result.ok, false);
assert.equal(result.reason, 'unsupported-view');
samePose(camera, before);
});
test('untouched polar framing permits repeated direction and speed changes below preset altitude', (t) => {
const { camera, finishOnce, tick } = harness(t, { latitude: 90 });
const radius = Cesium.Cartesian3.magnitude(camera.positionWC);
@@ -1874,7 +1837,7 @@ test('a voice turn reported as done turns at least the half degree its check pro
/** Track an entity below `camera`, locking it into that entity's frame. */
function trackFrom(viewer, camera) {
viewer.trackedEntity = { id: 'high-satellite' };
followEntity(viewer, { id: 'high-satellite' });
const below = Cesium.Cartesian3.fromDegrees(10, 20, 400_000);
camera.lookAtTransform(Cesium.Transforms.eastNorthUpToFixedFrame(below));
}
@@ -1900,7 +1863,7 @@ test('a voice turn that releases a tracked camera is checked as released', (t) =
});
trackFrom(viewer, camera);
const releaseThenRun = (start) => {
viewer.trackedEntity = undefined;
followEntity(viewer, null);
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
return start();
};
@@ -1941,14 +1904,14 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => {
for (let j = 0; j < 600 && getActiveCameraMotion(); j += 1) tick(1 / 60);
}
trackFrom(viewer, camera);
const tracked = viewer.trackedEntity;
const tracked = followedEntity(viewer);
const transform = Cesium.Matrix4.clone(camera.transform);
let released = false;
const result = moveCamera(
{ motion: 'tilt', direction: 'up', mode: 'once' },
(start) => {
released = true;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
return start();
},
@@ -1957,7 +1920,7 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => {
assert.equal(result.ok, false, label);
assert.match(result.error, /globe out of view/, label);
assert.equal(released, false, label);
assert.equal(viewer.trackedEntity, tracked, label);
assert.equal(followedEntity(viewer), tracked, label);
assert.ok(Cesium.Matrix4.equals(camera.transform, transform), label);
}
});
@@ -1988,27 +1951,6 @@ test('a turn proven at one position is checked again after a release moves the c
assert.match(result.error, /globe out of view/);
});
test('the voice frame limit leaves Columbus view alone', (t) => {
// At its limit in 3D a further tilt up is refused; the same tilt in Columbus
// view is not limited by the frame.
withScope(t, false);
const { viewer, finishOnce } = harness(t, {
pitch: -80,
viewportWidth: 1600,
viewportHeight: 900,
});
assert.equal(
moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }).ok,
true,
);
finishOnce();
const refused = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' });
assert.match(refused.error || '', /globe out of view/);
viewer.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW;
const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' });
assert.doesNotMatch(result.error || '', /globe out of view/);
});
test('voice tilt below the free-look height is not limited by the frame', (t) => {
const { camera, finishOnce } = harness(t, { height: 500_000, pitch: -60 });
const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' });
+96 -75
View File
@@ -14,8 +14,11 @@
* lifts the eye if it sits below a usable clearance. Heading and pitch are
* held, so the correction reads as the shot settling.
*/
import * as Cesium from 'cesium';
import { onFollowChanged } from './data/followed.js';
import { ownCameraArrival } from './data/cameraArrival.js';
import { distance, dot, fromDegrees, toLonLatH } from './geo/index.js';
import { heightsOf } from './queries/heights.js';
import { canvasOf, findCamera } from './render/rendererOf.js';
/** Minimum eye height above the rendered surface for a usable view. */
export const MIN_EYE_CLEARANCE_M = 120;
@@ -24,35 +27,79 @@ const GUARD_ATTEMPTS = 8;
const GUARD_INTERVAL_MS = 600;
/** Ignore sub-metre noise rather than nudging the camera forever. */
const GUARD_EPSILON_M = 2;
const probeScratch = new Cesium.Cartographic();
/** Eye travel (m) and turn (cosine) that mean another owner moved the camera. */
const MOVED_M = 0.01;
const TURNED_COS = 1 - 1e-9;
/**
* Highest rendered surface across a few cells, with how many cells answered.
* A cell whose tiles are not streamed yet contributes nothing.
* @param {Cesium.Scene} scene Live scene.
* @param {import('./queries/heights.js').HeightService|null} heights The
* scene's height service.
* @param {Array<{lat: number, lon: number}>} cells Cells to probe.
* @returns {{heightM: number, sampled: number}} Reading.
*/
function sampleSurfaceM(scene, cells) {
function sampleSurfaceM(heights, cells) {
let heightM = Number.NaN;
let sampled = 0;
if (typeof scene?.sampleHeight !== 'function') return { heightM, sampled };
if (!heights) return { heightM, sampled };
for (const cell of cells) {
try {
const height = scene.sampleHeight(
Cesium.Cartographic.fromDegrees(cell.lon, cell.lat, 0, probeScratch),
);
if (!Number.isFinite(height)) continue;
sampled += 1;
heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height;
} catch {
/* tiles not ready for this cell */
}
// A miss is a cell whose tiles are not ready.
const height = heights.now(cell);
if (!Number.isFinite(height)) continue;
sampled += 1;
heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height;
}
return { heightM, sampled };
}
/**
* The eye as the camera port poses it: where it is (from its position) and
* which way it looks; null when the pose cannot be read.
*/
function eyeOf(camera) {
try {
const pose = camera?.pose();
const at = pose?.position && toLonLatH(pose.position);
if (!at || !pose.direction || !pose.up) return null;
return { ...pose, lon: at.lon, lat: at.lat, height: at.height };
} catch {
return null;
}
}
/** The eye's ground point (height 0), its height, and which way it looks. */
function poseOf(eye) {
if (!eye) return null;
return {
ground: fromDegrees(eye.lon, eye.lat),
height: eye.height,
direction: { ...eye.direction },
up: { ...eye.up },
};
}
/**
* Whether another owner has moved the camera off `pose`: across the ground,
* down, or around. A pure rise is not one: the renderer's terrain collision
* lifts a buried eye straight up as tiles load, which is the case the guard
* exists for, so `pose` follows the highest eye seen and the guard keeps
* measuring.
*/
function moved(now, pose) {
if (!now) return true;
const ground = fromDegrees(now.lon, now.lat);
if (
distance(ground, pose.ground) > MOVED_M ||
now.height < pose.height - MOVED_M ||
dot(now.direction, pose.direction) < TURNED_COS ||
dot(now.up, pose.up) < TURNED_COS
)
return true;
pose.height = Math.max(pose.height, now.height);
return false;
}
/**
* How far the camera must rise to clear the ground, given a measured surface.
* Pure so the policy is testable without a scene.
@@ -76,9 +123,11 @@ export function groundClearanceDeficitM(
* Watch an arrival and lift the camera once the real surface can be measured.
*
* Stops quietly on a clear view, exhausted attempts, the user taking the
* controls (pointer or wheel on the canvas), or `isStale()` reporting that a
* newer arrival owns the camera.
* @param {Cesium.Viewer} viewer Live viewer.
* controls (pointer or wheel on the canvas), `isStale()` reporting that a
* newer arrival owns the camera, or any other caller moving the camera or
* starting a flight in the meantime: the guard only ever corrects the pose it
* was started on.
* @param {object} viewer Live viewer.
* @param {{lat: number, lon: number}} at Destination being framed.
* @param {{clearanceM?: number, attempts?: number, intervalMs?: number,
* isStale?: () => boolean, onLift?: (liftM: number) => void}} [options]
@@ -92,12 +141,16 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
isStale = () => false,
onLift = null,
} = options;
if (!viewer?.scene || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon))
if (!viewer || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon))
return () => {};
// Without a readable pose the guard could not tell a later owner's move.
const arrival = poseOf(eyeOf(findCamera(viewer)));
if (!arrival) return () => {};
let timer = null;
let done = false;
const canvas = viewer.scene.canvas;
const canvas = canvasOf(viewer);
const documentRef = canvas?.ownerDocument;
const removers = [];
let release = () => {};
@@ -112,32 +165,7 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
release();
};
release = ownCameraArrival(viewer, stop);
// Direct camera API callers (including duration-zero flights) must yield
// before moving the eye. Restore the exact method ownership on completion.
for (const name of [
'flyTo',
'flyToBoundingSphere',
'setView',
'lookAt',
'cancelFlight',
]) {
const camera = viewer.camera;
const original = camera[name];
if (typeof original !== 'function') continue;
const descriptor = Object.getOwnPropertyDescriptor(camera, name);
const wrapped = function (...args) {
stop();
return original.apply(this, args);
};
camera[name] = wrapped;
removers.push(() => {
if (camera[name] !== wrapped) return;
if (descriptor) Object.defineProperty(camera, name, descriptor);
else delete camera[name];
});
}
const removeTracking = viewer.trackedEntityChanged?.addEventListener(stop);
if (removeTracking) removers.push(removeTracking);
removers.push(onFollowChanged(viewer, stop));
documentRef?.addEventListener?.('keydown', stop, true);
// A manual gesture ends the guard, as it interrupts camera motion elsewhere.
for (const type of ['pointerdown', 'wheel'])
@@ -147,40 +175,33 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
const attempt = () => {
if (done) return;
if (isStale() || viewer.isDestroyed?.()) return stop();
const camera = findCamera(viewer);
const now = eyeOf(camera);
// Another caller owns the camera now; lifting would undo its move.
if (!camera || camera.flying || moved(now, arrival)) return stop();
remaining -= 1;
const camera = viewer.camera;
const carto = camera.positionCartographic;
// The eye must clear both the framed target and the ground beneath it.
const below = {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
};
const { heightM, sampled } = sampleSurfaceM(viewer.scene, [
{ lat: at.lat, lon: at.lon },
below,
]);
const below = { lat: now.lat, lon: now.lon };
const { heightM, sampled } = sampleSurfaceM(
viewer ? heightsOf(viewer) : null,
[{ lat: at.lat, lon: at.lon }, below],
);
if (sampled > 0 && Number.isFinite(heightM)) {
const deficit = groundClearanceDeficitM(
carto.height,
heightM,
clearanceM,
);
const deficit = groundClearanceDeficitM(now.height, heightM, clearanceM);
if (deficit > 0) {
stop();
camera.flyTo({
destination: Cesium.Cartesian3.fromRadians(
carto.longitude,
carto.latitude,
carto.height + deficit,
),
orientation: {
heading: camera.heading,
pitch: camera.pitch,
roll: camera.roll,
camera.flyTo(
{ lon: now.lon, lat: now.lat, height: now.height + deficit },
{
orientation: {
heading: now.heading,
pitch: now.pitch,
roll: now.roll,
},
durationS: 0.9,
easing: 'cubicInOut',
},
duration: 0.9,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
});
);
try {
onLift?.(deficit);
} catch {
+195 -27
View File
@@ -3,6 +3,12 @@
// Arrival framing is computed before the destination's tiles exist, so it
// works from a predicted ground height. The guard measures the real surface
// after arrival and lifts the eye; these tests pin when it acts.
import {
bindFakeCesiumCamera,
followEntity,
} from './testSupport/fakeCameraPort.mjs';
import { rendererOf } from './render/rendererOf.js';
import { fakeSceneQuery } from './testSupport/fakeCesiumScene.mjs';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
@@ -47,24 +53,71 @@ test('the clearance frames a subject without turning into an overflight', () =>
assert.ok(MIN_EYE_CLEARANCE_M <= 250);
});
function fakeViewer({ cameraHeightM, surfaceM }) {
/**
* Count the listeners for `viewer`'s camera port follow changes, from now on.
* @returns {() => number}
*/
function countFollowListeners(viewer) {
const renderer = rendererOf(viewer);
const port = renderer.camera;
let listeners = 0;
renderer.camera = Object.create(port, {
on: {
value(event, cb, options) {
const off = port.on(event, cb, options);
if (event !== 'followChanged') return off;
listeners += 1;
let live = true;
return () => {
if (live) listeners -= 1;
live = false;
off();
};
},
},
});
return () => listeners;
}
function fakeViewer({ cameraHeightM, surfaceM, tracks = false }) {
const flights = [];
const position = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, cameraHeightM);
return {
const position = Cesium.Cartographic.fromDegrees(
-97.7603,
30.3141,
cameraHeightM,
);
const viewer = {
flights,
scene: {
canvas: null,
sampleHeightSupported: true,
sampleHeight: (carto) =>
typeof surfaceM === 'function' ? surfaceM(carto) : surfaceM,
},
camera: {
positionCartographic: position,
positionWC: Cesium.Cartographic.toCartesian(position),
directionWC: new Cesium.Cartesian3(0, 0, -1),
upWC: new Cesium.Cartesian3(0, 1, 0),
heading: 0.5,
pitch: -0.55,
roll: 0,
flyTo: (options) => flights.push(options),
// As Cesium does: a flight is under way until it completes.
_currentFlight: undefined,
flyTo(options) {
flights.push(options);
this._currentFlight = {};
},
},
};
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
if (tracks)
Object.assign(viewer, {
trackedEntityChanged: new Cesium.Event(),
entities: {},
});
return bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) });
}
test('the guard lifts a buried arrival once the surface answers', async () => {
@@ -104,7 +157,11 @@ test('the guard waits for streaming tiles and yields to a newer arrival', async
test('the guard leaves a clear view untouched', async () => {
const viewer = fakeViewer({ cameraHeightM: 400, surfaceM: 171 });
guardCameraAboveGround(viewer, { lat: 30.3125, lon: -97.765 }, { intervalMs: 1 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 1 },
);
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(viewer.flights.length, 0);
});
@@ -116,39 +173,85 @@ import { LayerLifecycle } from './data/lifecycle.js';
function handoffFixture(t) {
t.mock.timers.enable({ apis: ['setTimeout'] });
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
const viewer = fakeViewer({
cameraHeightM: 172,
surfaceM: 171,
tracks: true,
});
const followListeners = countFollowListeners(viewer);
viewer.scene.canvas = new EventTarget();
viewer.scene.canvas.ownerDocument = new EventTarget();
viewer.trackedEntityChanged = new Cesium.Event();
viewer.camera.cancelFlight = () => {};
viewer.camera.lookAtTransform = () => {};
viewer.camera.flyToBoundingSphere = () => {};
viewer.camera.setView = () => {};
viewer.camera.flyToBoundingSphere = function () {
this._currentFlight = {};
};
viewer.camera.setView = function () {
this.positionWC = Cesium.Cartesian3.add(
this.positionWC,
new Cesium.Cartesian3(0, 0, 50),
new Cesium.Cartesian3(),
);
};
const originalFly = viewer.camera.flyTo;
const navigation = new NavigationController({
viewer,
tracking: Object.fromEntries(['flightsLayer', 'militaryFlightsLayer',
'satellitesLayer', 'aisLiveVesselsLayer', 'militaryAwarenessLayer',
'rocketLaunchesLayer'].map((key) => [key, {}])),
cancelOrientation() {}, clearLocation() {}, cancelShareSelection() {},
getDataManager() {}, interruptCameraMotion() {}, stopOrbit() {},
isCockpitActive: () => false, showToast() {},
tracking: Object.fromEntries(
[
'flightsLayer',
'militaryFlightsLayer',
'satellitesLayer',
'aisLiveVesselsLayer',
'militaryAwarenessLayer',
'rocketLaunchesLayer',
].map((key) => [key, {}]),
),
cancelOrientation() {},
clearLocation() {},
cancelShareSelection() {},
getDataManager() {},
interruptCameraMotion() {},
stopOrbit() {},
isCockpitActive: () => false,
showToast() {},
});
guardCameraAboveGround(viewer, { lat: 30.3, lon: -97.7 });
return { viewer, navigation, originalFly };
return { viewer, navigation, originalFly, followListeners };
}
for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI',
'flyTo', 'flyToBoundingSphere', 'setView', 'layer-disable', 'layer-destroy', 'app-stop']) {
for (const handoff of [
'Director',
'tracking',
'follow',
'keyboard',
'UI',
'flyTo',
'flyToBoundingSphere',
'setView',
'layer-disable',
'layer-destroy',
'app-stop',
]) {
test(`arrival guard relinquishes and removes hooks on ${handoff}`, async (t) => {
const { viewer, navigation, originalFly } = handoffFixture(t);
const { viewer, navigation, originalFly, followListeners } =
handoffFixture(t);
const methods = [
'flyTo',
'flyToBoundingSphere',
'setView',
'lookAt',
'cancelFlight',
].map((name) => viewer.camera[name]);
if (handoff === 'Director') {
SceneDirector.prototype._claimCameraOwnership.call({
viewer, styleManager: { runImmediateNavigation: (noun, fn) =>
navigation._runExplicitNavigation(noun, fn) },
viewer,
styleManager: {
runImmediateNavigation: (noun, fn) =>
navigation._runExplicitNavigation(noun, fn),
},
});
} else if (handoff === 'tracking') {
viewer.trackedEntityChanged.raiseEvent({ id: 'contact' });
followEntity(viewer, { id: 'contact' });
} else if (handoff === 'follow' || handoff === 'UI') {
navigation._stampNavigation({ cancelPendingSelection: false });
} else if (handoff === 'keyboard') {
@@ -156,16 +259,81 @@ for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI',
} else if (handoff === 'app-stop') navigation.stop();
else if (handoff.startsWith('layer-')) {
const lifecycle = new LayerLifecycle(viewer);
lifecycle.register({ id: 'test', init() {}, enable() {}, disable() {}, destroy() {} });
lifecycle.register({
id: 'test',
init() {},
enable() {},
disable() {},
destroy() {},
});
await lifecycle.setEnabled('test', true);
if (handoff === 'layer-disable') await lifecycle.setEnabled('test', false);
if (handoff === 'layer-disable')
await lifecycle.setEnabled('test', false);
else await lifecycle.destroyLayer('test');
} else viewer.camera[handoff]({});
// A direct flyTo is itself one recorded flight; the guard adds none.
const priorFlights = viewer.flights.length;
t.mock.timers.tick(10000);
assert.equal(viewer.flights.length, priorFlights, 'the old probe cannot fly');
assert.equal(viewer.camera.flyTo, originalFly, 'direct-call hook is removed');
assert.equal(viewer.trackedEntityChanged.numberOfListeners, 0);
assert.equal(
viewer.flights.length,
priorFlights,
'the old probe cannot fly',
);
assert.equal(viewer.camera.flyTo, originalFly);
assert.deepEqual(
['flyTo', 'flyToBoundingSphere', 'setView', 'lookAt', 'cancelFlight'].map(
(name) => viewer.camera[name],
),
methods,
'the guard never replaces camera methods',
);
assert.equal(followListeners(), 0);
navigation.destroy();
});
}
test('the guard yields to a camera moved without any camera method', async () => {
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 5 },
);
// A cockpit or follow frame writes the pose directly.
viewer.camera.directionWC = new Cesium.Cartesian3(1, 0, 0);
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(viewer.flights.length, 0, 'the moved view is not corrected');
});
test('Cesium lifting a buried eye straight up is not another owner', async () => {
const viewer = fakeViewer({ cameraHeightM: 104, surfaceM: 171 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 5 },
);
// Terrain collision raises the eye to just above the loaded ground.
const raised = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 172);
viewer.camera.positionCartographic = raised;
viewer.camera.positionWC = Cesium.Cartographic.toCartesian(raised);
await new Promise((resolve) => setTimeout(resolve, 30));
assert.equal(viewer.flights.length, 1, 'the guard still lifts the eye');
const lifted = Cesium.Cartographic.fromCartesian(
viewer.flights[0].destination,
);
assert.ok(Math.abs(lifted.height - (171 + MIN_EYE_CLEARANCE_M)) < 0.5);
});
test('another owner lowering the eye is not corrected', async () => {
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 5 },
);
const lowered = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 150);
viewer.camera.positionCartographic = lowered;
viewer.camera.positionWC = Cesium.Cartographic.toCartesian(lowered);
await new Promise((resolve) => setTimeout(resolve, 30));
assert.equal(viewer.flights.length, 0);
});
+11 -11
View File
@@ -44,8 +44,8 @@ test('Cockpit takeover invalidates deferred work before camera cancellation', ()
ordered(enter, [
'if (!info || (!vessel && !satellite && !entity?.position)) return false;',
'this.onCameraTakeover?.();',
'this.viewer.camera.cancelFlight();',
'this.viewer.trackedEntity = undefined;',
'cameraOf(this.viewer).cancelFlight();',
'stopFollowing(this.viewer);',
], 'Cockpit takeover');
assert.match(
ui,
@@ -97,7 +97,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () =>
// The transaction has exactly two camera-owner mutations, and each one
// stamps:
// 1. selectedLayer.trackById(id) -> viewer.trackedEntity
// -> viewer.trackedEntityChanged -> _stampNavigation()
// -> onFollowChanged(viewer) -> _stampNavigation()
// 2. cockpitView.enter() -> onCameraTakeover() -> _stampNavigation()
const transaction = body(
cockpitTracking,
@@ -118,7 +118,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () =>
// Seam 1: any tracker handoff stamps, so the adoption step is covered.
assert.match(
ui,
/viewer\.trackedEntityChanged\.addEventListener\(\s*\(entity\) => \{\s*if \(entity && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/,
/onFollowChanged\(\s*this\.viewer,\s*\(followed\) => \{\s*if \(followed && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/,
'tracker handoff must stamp',
);
// Seam 2 is pinned by "Cockpit takeover invalidates deferred work" above.
@@ -191,10 +191,10 @@ test('accepted navigation releases through PR15-aware ownership before flight',
'origin: trackingOrigin',
'satellitesLayer.stopTracking?.({ origin: trackingOrigin })',
'rocketLaunchesLayer.releaseCameraOwnership?.()',
'this.viewer.trackedEntity = undefined;',
'stopFollowing(this.viewer);',
"interruptCameraMotion('explicit-navigation')",
'this.viewer.camera.cancelFlight();',
'this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);',
'camera?.cancelFlight();',
'camera?.release();',
], 'follow release');
assert.match(release, /flightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/);
assert.match(release, /militaryFlightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/);
@@ -282,11 +282,11 @@ test('a direct globe gesture retires delayed camera and selection restore only',
);
assert.match(
ui,
/viewer\?\.canvas\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/,
/canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/,
);
assert.match(
ui,
/viewer\?\.canvas\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/,
/canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/,
);
assert.match(
ui,
@@ -399,7 +399,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
}
const vesselClick = body(
vessels,
/handler\.setInputAction\(\s*\(click\) => \{([\s\S]*?)\n\s*\},\s*Cesium\.ScreenSpaceEventType\.LEFT_CLICK,?\s*\);/,
/inputFor\(viewer\)\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/,
'vessel click',
);
ordered(vesselClick, [
@@ -415,7 +415,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
assert.match(vesselFocus, /requestWorldFocus\(\{/);
const fireClick = body(
firms,
/_clickHandler\.setInputAction\(\(click\) => \{([\s\S]*?)\n \}, Cesium\.ScreenSpaceEventType\.LEFT_CLICK\);/,
/input\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/,
'fire click',
);
ordered(fireClick, [
+23 -8
View File
@@ -9,6 +9,14 @@ import {
moveCamera,
} from './cameraVerbs.js';
import { createGevActionRunner } from './voice/gevActions.js';
import {
bindFakeCesiumCamera,
followEntity,
} from './testSupport/fakeCameraPort.mjs';
import {
fakeSceneFrame,
fakeSceneQuery,
} from './testSupport/fakeCesiumScene.mjs';
const radians = Cesium.Math.toRadians;
const degrees = Cesium.Math.toDegrees;
@@ -39,6 +47,7 @@ function harness(
mode: Cesium.SceneMode.SCENE3D,
pixelRatio: 1,
tweens: [],
preUpdate: new Cesium.Event(),
requestRender() {},
};
const camera = new Cesium.Camera(scene);
@@ -47,13 +56,21 @@ function harness(
destination: Cesium.Cartesian3.fromDegrees(-0.1276, 51.5072, height),
orientation: { heading: radians(heading), pitch: radians(pitch), roll: 0 },
});
const viewer = {
const double = {
camera,
scene,
trackedEntity: undefined,
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
entities: {},
clock: { onTick: new Cesium.Event() },
};
// The Cesium renderer's own camera port over the real camera; frames from
// the scene's preUpdate.
const viewer = bindFakeCesiumCamera(double, {
query: fakeSceneQuery(double),
frame: fakeSceneFrame(double),
});
// The app's view target: the ground point under the screen centre.
const viewTarget = () => {
const ray = new Cesium.Ray(camera.positionWC, camera.directionWC);
@@ -68,7 +85,7 @@ function harness(
});
const tick = (seconds = 1 / 30) => {
nowMs += seconds * 1000;
viewer.clock.onTick.raiseEvent(viewer.clock);
viewer.scene.preUpdate.raiseEvent(viewer.scene);
};
const finish = () => {
for (let i = 0; i < 600 && getActiveCameraMotion(); i += 1) tick();
@@ -239,9 +256,7 @@ test('a pivoting tilt yields when tracking takes the camera', (t) => {
const h = harness(t);
assert.equal(moveCamera({ motion: 'tilt', pitchDeg: -45 }).ok, true);
h.tick();
const entity = { id: 'tracked' };
h.viewer.trackedEntity = entity;
h.viewer.trackedEntityChanged.raiseEvent(entity);
followEntity(h.viewer, { id: 'tracked' });
assert.equal(getActiveCameraMotion(), null);
});
@@ -548,10 +563,10 @@ test('a regional tilt-up nudge goes to the camera horizon limit', (t) => {
test('a voice tilt from a tracked view judges its limit from the camera pitch', (t) => {
const h = harness(t, { height: 20000, pitch: -5.2 });
h.viewer.trackedEntity = { id: 'tracked' };
followEntity(h.viewer, { id: 'tracked' });
// Voice releases the follow camera before the motion starts.
const release = (start) => {
h.viewer.trackedEntity = undefined;
followEntity(h.viewer, null);
return start();
};
const result = moveCamera({ motion: 'tilt', direction: 'up' }, release);
+437 -514
View File
File diff suppressed because it is too large. Load diff
+9 -8
View File
@@ -1,22 +1,23 @@
/**
* Activates the nearest CCTV record on layer enable and flies only when no
* aircraft tracker or cockpit camera owns the view.
* followed target or cockpit camera owns the view.
* @param {Object} options Layer-enable focus inputs.
* @param {*} options.trackedEntity Current Cesium tracked entity, if any.
* @param {*} options.followed What the camera follows, if anything
* (`followedOf`).
* @param {boolean} options.cockpitActive Whether cockpit mode owns the camera.
* @param {() => (string|null)} options.activate Nearest-camera activation.
* @param {(cameraId: string) => *} options.fly Optional camera flight.
* @returns {*} Activated camera ID for a held view, or the flight result.
*/
export function runCctvLayerEnableFocus({
trackedEntity = null,
followed = null,
cockpitActive = false,
activate,
fly,
} = {}) {
const cameraId = activate?.();
if (!cameraId) return false;
if (trackedEntity || cockpitActive) return cameraId;
if (followed || cockpitActive) return cameraId;
return fly?.(cameraId);
}
@@ -25,11 +26,11 @@ export function runCctvLayerEnableFocus({
* chain. Either observation suppresses the optional CCTV focus flight.
* @param {Object} [before={}] Ownership immediately before the await.
* @param {Object} [after={}] Ownership immediately after the await.
* @returns {{ trackedEntity: *, cockpitActive: boolean }} Conservative ownership.
* @returns {{ followed: *, cockpitActive: boolean }} Conservative ownership.
*/
function mergeCctvEnableOwnership(before = {}, after = {}) {
return {
trackedEntity: before.trackedEntity || after.trackedEntity || null,
followed: before.followed || after.followed || null,
cockpitActive: !!(before.cockpitActive || after.cockpitActive),
};
}
@@ -60,7 +61,7 @@ export async function runCctvLayerEnableTransition({
const ownershipBefore = readOwnership?.() || {};
if (target === true) {
debug?.('[UI:CCTV] ownership before setEnabled await', {
trackedId: ownershipBefore.trackedEntity?.id ?? null,
trackedId: ownershipBefore.followed?.key ?? null,
cockpitActive: !!ownershipBefore.cockpitActive,
});
}
@@ -68,7 +69,7 @@ export async function runCctvLayerEnableTransition({
const ownershipAfter = readOwnership?.() || {};
if (target === true) {
debug?.('[UI:CCTV] ownership after setEnabled await', {
trackedId: ownershipAfter.trackedEntity?.id ?? null,
trackedId: ownershipAfter.followed?.key ?? null,
cockpitActive: !!ownershipAfter.cockpitActive,
});
}
+6 -6
View File
@@ -8,8 +8,8 @@ import {
test('CCTV layer enable activates nearest without stealing a tracked or cockpit view', () => {
for (const ownership of [
{ trackedEntity: { id: 'tracked-plane' }, cockpitActive: false },
{ trackedEntity: null, cockpitActive: true },
{ followed: { key: 'tracked-plane' }, cockpitActive: false },
{ followed: null, cockpitActive: true },
]) {
const calls = [];
const result = runCctvLayerEnableFocus({
@@ -48,15 +48,15 @@ test('CCTV layer enable activates nearest without stealing a tracked or cockpit
});
test('CCTV enable retains a pre-await tracking snapshot when tracking clears during enable', async () => {
let trackedEntity = { id: 'tracked-plane' };
let followed = { key: 'tracked-plane' };
let flyCalls = 0;
const diagnostics = [];
const result = await runCctvLayerEnableTransition({
target: true,
readOwnership: () => ({ trackedEntity, cockpitActive: false }),
readOwnership: () => ({ followed, cockpitActive: false }),
setEnabled: async () => {
await Promise.resolve();
trackedEntity = null;
followed = null;
},
shouldFocus: () => true,
activate: () => 'cam-near',
@@ -83,7 +83,7 @@ test('CCTV disable transition does not emit enable-ownership diagnostics', async
const result = await runCctvLayerEnableTransition({
target: false,
readOwnership: () => ({ trackedEntity: { id: 'tracked-plane' }, cockpitActive: false }),
readOwnership: () => ({ followed: { key: 'tracked-plane' }, cockpitActive: false }),
setEnabled: async (target) => transitions.push(target),
shouldFocus: () => true,
activate: () => 'cam-near',
+121 -104
View File
@@ -1,5 +1,25 @@
import * as Cesium from 'cesium';
import { governorRequestRender } from './renderGovernor.js';
import {
cameraOf,
canvasOf,
findCamera,
findFrame,
findQuery,
} from './render/rendererOf.js';
import {
moonPositionInertial,
sunPositionInertial,
temeToPseudoFixed,
} from './geo/celestial.js';
import { WGS84 } from './geo/ellipsoid.js';
import { frameVector } from './geo/frames.js';
import {
dot,
magnitude,
normalize,
PI_OVER_TWO,
toRadians,
} from './geo/vector.js';
import { worldClock, worldTimeFor } from './time/worldClock.js';
// The ring shows the sun and moon at the time the sky is drawn.
@@ -38,7 +58,13 @@ const EPHEMERIS_WORLD_STEP_MS = 60_000;
const RING_INSET_PX = 11;
const MARKER_INSET_PX = 36;
const COLLIDING_MARKER_EXTRA_INSET_PX = 32;
const MARKER_COLLISION_ANGLE = Cesium.Math.toRadians(6);
const MARKER_COLLISION_ANGLE = toRadians(6);
/** The ellipsoid's largest radius, metres. */
const EARTH_MAX_RADIUS_M = Math.max(
WGS84.radii.x,
WGS84.radii.y,
WGS84.radii.z,
);
const FULL_GLOBE_RADIUS_RATIO = 0.61;
const TAU = Math.PI * 2;
// This overlay is a secondary HUD treatment. Keep it smooth while reserving
@@ -218,7 +244,7 @@ export function isFullGlobeInsideKeyhole(geometry, wasVisible = false) {
/** Return the Earth-disc radius in CSS pixels for a perspective camera. */
export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) {
const earthRadiusM = Cesium.Ellipsoid.WGS84.maximumRadius;
const earthRadiusM = EARTH_MAX_RADIUS_M;
if (
!Number.isFinite(cameraDistance) ||
cameraDistance <= earthRadiusM ||
@@ -234,15 +260,19 @@ export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) {
return Number.isFinite(radius) && radius > 0 ? radius : null;
}
const EARTH_CENTRE = Object.freeze({ x: 0, y: 0, z: 0 });
/**
* Project the visible Earth disc into viewport coordinates.
* Project the visible Earth disc into viewport coordinates, through the
* renderer's camera pose and its query port's projection.
* Shared by full-globe UI treatments that must agree on visual containment.
*
* @param {object} viewer - Cesium Viewer-like object.
* @param {object} viewer - The scene object the renderer is found from.
* @param {number} width - Viewport width in CSS pixels.
* @param {number} height - Viewport height in CSS pixels.
* @param {object} [scratchCenter] - Reusable Cesium Cartesian2 result.
* @param {object} [scratchToCenter] - Reusable Cesium Cartesian3 result.
* @param {{x:number,y:number}} [scratchCenter] - Takes the projected centre.
* @param {{x:number,y:number,z:number}} [scratchToCenter] - Takes the
* vector from the eye to the Earth's centre.
* @returns {object|null}
*/
export function projectEarthDiscToViewport(
@@ -252,36 +282,32 @@ export function projectEarthDiscToViewport(
scratchCenter = undefined,
scratchToCenter = undefined,
) {
const camera = viewer?.camera;
const scene = viewer?.scene;
if (!camera || !scene || !(width > 0) || !(height > 0)) return null;
const camera = findCamera(viewer);
if (!camera || !(width > 0) || !(height > 0)) return null;
const pose = camera.pose();
const eye = pose.position;
const distance = Cesium.Cartesian3.magnitude(camera.positionWC);
const distance = magnitude(eye);
if (!Number.isFinite(distance) || distance <= EARTH_MAX_RADIUS_M) return null;
const toCenter = scratchToCenter || { x: 0, y: 0, z: 0 };
toCenter.x = -eye.x;
toCenter.y = -eye.y;
toCenter.z = -eye.z;
if (dot(pose.direction, toCenter) <= 0) return null;
const projected = findQuery(viewer)?.project(EARTH_CENTRE);
if (
!Number.isFinite(distance) ||
distance <= Cesium.Ellipsoid.WGS84.maximumRadius
!projected ||
!Number.isFinite(projected.x) ||
!Number.isFinite(projected.y)
)
return null;
const center = scratchCenter || { x: 0, y: 0 };
center.x = projected.x;
center.y = projected.y;
const toCenter = Cesium.Cartesian3.negate(
camera.positionWC,
scratchToCenter || new Cesium.Cartesian3(),
);
if (Cesium.Cartesian3.dot(camera.directionWC, toCenter) <= 0) return null;
const center = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
Cesium.Cartesian3.ZERO,
scratchCenter,
);
if (!center || !Number.isFinite(center.x) || !Number.isFinite(center.y))
return null;
const earthRadius = earthDiscScreenRadius(
distance,
height,
camera.frustum?.fovy,
);
const earthRadius = earthDiscScreenRadius(distance, height, pose.fovy);
if (!earthRadius) return null;
const keyhole = getKeyholeGeometry(width, height);
@@ -396,14 +422,23 @@ let rings = 0;
*/
export class CelestialRing {
/**
* @param {Cesium.Viewer} viewer
* @param {{enabled?:boolean,onAutoDisable?:Function,store:object}} options
* @param {object} viewer - The scene object the renderer is found from;
* the ring reads its canvas and container (DOM) and reaches the rest
* through the renderer's camera, frame and query ports.
* @param {{enabled?:boolean,onAutoDisable?:Function,store:object,preciseFrameAt?:Function}} options
* `store` is the celestial ring store (src/ui/stores/celestialRing.js);
* the keyhole helpers here stay free of Vue for the packages that use
* them.
* them. `preciseFrameAt(ms)` gives the ICRF-to-fixed rotation as axes,
* or null while its tables have not loaded; without it, or while it has
* no answer, the ring uses the pseudo-fixed frame.
*/
constructor(viewer, { enabled = true, onAutoDisable = null, store }) {
constructor(
viewer,
{ enabled = true, onAutoDisable = null, store, preciseFrameAt = null },
) {
this.viewer = viewer;
this._preciseFrameAt =
typeof preciseFrameAt === 'function' ? preciseFrameAt : null;
this.enabled = !!enabled;
this.visible = false;
this._onAutoDisable =
@@ -426,18 +461,14 @@ export class CelestialRing {
this._moonCanvas = null;
this._moonCtx = null;
this._sunInertial = new Cesium.Cartesian3();
this._moonInertial = new Cesium.Cartesian3();
this._sunFixed = new Cesium.Cartesian3();
this._moonFixed = new Cesium.Cartesian3();
this._toCenter = new Cesium.Cartesian3();
this._screenCenter = new Cesium.Cartesian2();
this._fixedMatrix = new Cesium.Matrix3();
this._sunFixed = { x: 0, y: 0, z: 0 };
this._moonFixed = { x: 0, y: 0, z: 0 };
this._toCenter = { x: 0, y: 0, z: 0 };
this._screenCenter = { x: 0, y: 0 };
this._initView(store);
this._removePostRender = viewer.scene.postRender.addEventListener(() =>
this._draw(),
);
this._removePostRender =
findFrame(viewer)?.on('postRender', () => this._draw()) ?? null;
// Pre-existing staleness fix (perf wave 2 review): the ephemeris was
// sampled once per visible-enable from the FROZEN app clock, so the
// sun/moon markers aged with the app. Resample real wall time each
@@ -453,8 +484,6 @@ export class CelestialRing {
governorRequestRender('celestial-ephemeris');
}, 60_000);
// A jump in the world time moves the sun and moon at once.
this._skyDate = new Date();
this._skyTime = new Cesium.JulianDate();
// Played through, the sky moves on each minute of world time it passes.
this._ephemerisWorldMs = null;
this._unsubscribeWorldTime = worldClock.subscribe(({ timeMs }) => {
@@ -554,9 +583,14 @@ export class CelestialRing {
});
}
/** The renderer's canvas; a viewer with no renderer bound, its own. */
_canvas() {
return canvasOf(this.viewer);
}
/** Whether the current camera already frames the complete globe inside the keyhole. */
isGlobeFullyVisible() {
const canvas = this.viewer.scene.canvas;
const canvas = this._canvas();
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
if (!(width > 0 && height > 0)) return false;
@@ -571,13 +605,15 @@ export class CelestialRing {
* @returns {boolean} Whether a valid camera flight was started.
*/
focusFullGlobe({ duration = 2.4 } = {}) {
const canvas = this.viewer.scene.canvas;
const canvas = this._canvas();
const height = canvas.clientHeight || canvas.height;
const cartographic = this.viewer.camera.positionCartographic;
const fovy = this.viewer.camera.frustum?.fovy;
const camera = cameraOf(this.viewer);
const pose = camera.pose();
const fovy = pose.fovy;
if (
!(height > 0) ||
!cartographic ||
!Number.isFinite(pose.lon) ||
!Number.isFinite(pose.lat) ||
!Number.isFinite(fovy) ||
fovy <= 0 ||
fovy >= Math.PI
@@ -585,7 +621,7 @@ export class CelestialRing {
return false;
}
const earthRadius = Cesium.Ellipsoid.WGS84.maximumRadius;
const earthRadius = EARTH_MAX_RADIUS_M;
const keyholeRadius = getKeyholeGeometry(
canvas.clientWidth || canvas.width,
height,
@@ -600,27 +636,25 @@ export class CelestialRing {
this._focusInProgress = true;
const finishFocus = () => {
this._focusInProgress = false;
this.viewer.scene.requestRender?.();
findFrame(this.viewer)?.requestRender('celestial-focus');
};
this.viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromRadians(
cartographic.longitude,
cartographic.latitude,
altitude,
),
orientation: {
heading: this.viewer.camera.heading,
pitch: -Cesium.Math.PI_OVER_TWO,
roll: 0,
camera.flyTo(
{ lon: pose.lon, lat: pose.lat, height: altitude },
{
orientation: {
heading: pose.heading,
pitch: -PI_OVER_TWO,
roll: 0,
},
durationS: duration,
easing: 'cubicInOut',
onComplete: finishFocus,
onCancel: () => {
finishFocus();
if (!this.isGlobeFullyVisible()) this._autoDisable();
},
},
duration,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
complete: finishFocus,
cancel: () => {
finishFocus();
if (!this.isGlobeFullyVisible()) this._autoDisable();
},
});
);
return true;
}
@@ -671,31 +705,16 @@ export class CelestialRing {
/**
* Sample Earth-fixed directions once per enable. Camera movement only
* re-projects these cached vectors; it never re-runs the planetary model.
* The precise ICRF frame serves once its tables have loaded, the
* pseudo-fixed one before.
* @param {number} ms Epoch milliseconds.
*/
_updateEphemeris(time) {
_updateEphemeris(ms) {
if (!this._ephemerisDirty) return true;
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
time,
this._sunInertial,
);
Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(
time,
this._moonInertial,
);
const matrix =
Cesium.Transforms.computeIcrfToFixedMatrix(time, this._fixedMatrix) ||
Cesium.Transforms.computeTemeToPseudoFixedMatrix(time, this._fixedMatrix);
if (!matrix) return false;
Cesium.Matrix3.multiplyByVector(matrix, this._sunInertial, this._sunFixed);
Cesium.Matrix3.multiplyByVector(
matrix,
this._moonInertial,
this._moonFixed,
);
Cesium.Cartesian3.normalize(this._sunFixed, this._sunFixed);
Cesium.Cartesian3.normalize(this._moonFixed, this._moonFixed);
const frame = this._preciseFrameAt?.(ms) ?? temeToPseudoFixed(ms);
this._sunFixed = normalize(frameVector(frame, sunPositionInertial(ms)));
this._moonFixed = normalize(frameVector(frame, moonPositionInertial(ms)));
this._ephemerisDirty = false;
this._ephemerisUpdateCount += 1;
return true;
@@ -792,7 +811,7 @@ export class CelestialRing {
const now = performance.now();
if (now < this._nextDrawAt) return;
this._nextDrawAt = now + 1000 / CELESTIAL_MAX_FRAME_RATE;
const canvas = this.viewer.scene.canvas;
const canvas = this._canvas();
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
if (!(width > 0 && height > 0)) return;
@@ -822,19 +841,17 @@ export class CelestialRing {
return;
}
this._skyDate.setTime(skyTime());
const time = Cesium.JulianDate.fromDate(this._skyDate, this._skyTime);
if (!this._updateEphemeris(time)) return;
if (!this._updateEphemeris(skyTime())) return;
this._present({ ephemerisUpdates: String(this._ephemerisUpdateCount) });
const camera = this.viewer.camera;
const pose = cameraOf(this.viewer).pose();
const sunProjection = celestialScreenAngle(
Cesium.Cartesian3.dot(this._sunFixed, camera.rightWC),
Cesium.Cartesian3.dot(this._sunFixed, camera.upWC),
dot(this._sunFixed, pose.right),
dot(this._sunFixed, pose.up),
this._sunAngle,
);
const moonProjection = celestialScreenAngle(
Cesium.Cartesian3.dot(this._moonFixed, camera.rightWC),
Cesium.Cartesian3.dot(this._moonFixed, camera.upWC),
dot(this._moonFixed, pose.right),
dot(this._moonFixed, pose.up),
this._moonAngle,
);
if (sunProjection.stable) this._sunAngle = sunProjection.angle;
+135 -5
View File
@@ -9,7 +9,14 @@ import { createPinia } from 'pinia';
import { useCelestialRingStore } from './ui/stores/celestialRing.js';
import CelestialRingView from './ui/views/panels/CelestialRing.vue';
import * as Cesium from 'cesium';
import { CelestialRing } from './celestialRing.js';
import {
CelestialRing,
earthDiscScreenRadius,
projectEarthDiscToViewport,
} from './celestialRing.js';
import { bindRenderer } from './render/rendererOf.js';
import { bindFakeCesiumCamera } from './testSupport/fakeCameraPort.mjs';
import { fakeSceneFrame } from './testSupport/fakeCesiumScene.mjs';
// happy-dom has no 2D context; a stand-in takes every drawing call.
const context = new Proxy(
@@ -19,18 +26,26 @@ const context = new Proxy(
globalThis.HTMLCanvasElement.prototype.getContext = () => context;
function fakeViewer(container) {
return {
const canvas = {
clientWidth: 400,
clientHeight: 300,
width: 400,
height: 300,
};
const viewer = {
container,
canvas,
camera: {
rightWC: new Cesium.Cartesian3(1, 0, 0),
upWC: new Cesium.Cartesian3(0, 1, 0),
},
scene: {
canvas: { clientWidth: 400, clientHeight: 300, width: 400, height: 300 },
canvas,
postRender: { addEventListener: () => () => {} },
requestRender() {},
},
};
return bindFakeCesiumCamera(viewer, { frame: fakeSceneFrame(viewer) });
}
function fixture(t) {
@@ -157,8 +172,7 @@ const FRAMED = {
/** Run one rendered frame, past the frame-rate throttle. */
function frame(ring, disc) {
ring._projectedEarthDisc = () => disc;
// Fixed sun and moon directions; Cesium's own model would fetch its
// orientation data.
// Fixed sun and moon directions, so markers do not move with the clock.
ring._updateEphemeris = () => {
if (ring._ephemerisDirty) {
Cesium.Cartesian3.clone(new Cesium.Cartesian3(1, 0, 0), ring._sunFixed);
@@ -249,3 +263,119 @@ test('a ring the store no longer shows stops drawing', async (t) => {
assert.equal(earlier.enabled, true);
assert.equal(disabled, 0);
});
test('the sun and moon directions are the planetary model in the pseudo-fixed frame', () => {
const pinia = createPinia();
const ring = new CelestialRing(fakeViewer({}), {
enabled: false,
store: useCelestialRingStore(pinia),
// The precise frame's tables have not loaded.
preciseFrameAt: () => null,
});
const ms = Date.UTC(2026, 10, 7, 12, 30);
ring._ephemerisDirty = true;
assert.equal(ring._updateEphemeris(ms), true);
// Cesium's own, before the sky has loaded the precise frame's tables.
const time = Cesium.JulianDate.fromDate(new Date(ms));
const matrix = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);
const expected = (inertial) =>
Cesium.Cartesian3.normalize(
Cesium.Matrix3.multiplyByVector(
matrix,
inertial,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const sun = expected(
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
time,
),
);
const moon = expected(
Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(
time,
),
);
for (const [got, want] of [
[ring._sunFixed, sun],
[ring._moonFixed, moon],
])
for (const axis of ['x', 'y', 'z'])
assert.ok(Object.is(got[axis], want[axis]), axis);
assert.equal(ring._ephemerisUpdateCount, 1);
ring.destroy();
});
test('the projected disc reads the camera and query ports', () => {
const canvas = { clientWidth: 800, clientHeight: 600 };
const viewer = { canvas };
const distance = 3 * 6378137;
const pose = {
position: { x: distance, y: 0, z: 0 },
direction: { x: -1, y: 0, z: 0 },
fovy: Math.PI / 3,
};
const unbind = bindRenderer(viewer, {
canvas,
camera: { pose: () => pose },
query: { project: () => ({ x: 410, y: 290 }) },
});
const toCenter = { x: 0, y: 0, z: 0 };
const centre = { x: 0, y: 0 };
const disc = projectEarthDiscToViewport(viewer, 800, 600, centre, toCenter);
assert.equal(disc.earthCenterX, 410);
assert.equal(disc.earthCenterY, 290);
assert.deepEqual(centre, { x: 410, y: 290 });
// The scratch takes the eye-to-centre vector, as callers read it after.
assert.deepEqual(toCenter, { x: -distance, y: -0, z: -0 });
assert.ok(
Math.abs(
disc.earthRadius - earthDiscScreenRadius(distance, 600, pose.fovy),
) < 1e-9,
);
// Facing away: null, with the eye-to-centre vector still written, as
// radio navigation reads it after.
pose.direction = { x: 1, y: 0, z: 0 };
const away = { x: 0, y: 0, z: 0 };
assert.equal(projectEarthDiscToViewport(viewer, 800, 600, null, away), null);
assert.deepEqual(away, { x: -distance, y: -0, z: -0 });
// Inside the ellipsoid's largest radius: null, the scratch untouched.
pose.position = { x: 6378137, y: 0, z: 0 };
const inside = { x: 1, y: 2, z: 3 };
assert.equal(
projectEarthDiscToViewport(viewer, 800, 600, null, inside),
null,
);
assert.deepEqual(inside, { x: 1, y: 2, z: 3 });
unbind();
});
test('the precise frame serves once it answers', () => {
const pinia = createPinia();
// A quarter turn about z: x goes to y.
const quarter = {
x: { x: 0, y: 1, z: 0 },
y: { x: -1, y: 0, z: 0 },
z: { x: 0, y: 0, z: 1 },
};
const ring = new CelestialRing(fakeViewer({}), {
enabled: false,
store: useCelestialRingStore(pinia),
preciseFrameAt: () => quarter,
});
const ms = Date.UTC(2026, 10, 7, 12, 30);
ring._ephemerisDirty = true;
ring._updateEphemeris(ms);
const time = Cesium.JulianDate.fromDate(new Date(ms));
const sun = Cesium.Cartesian3.normalize(
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
time,
),
new Cesium.Cartesian3(),
);
assert.ok(Math.abs(ring._sunFixed.x + sun.y) < 1e-12);
assert.ok(Math.abs(ring._sunFixed.y - sun.x) < 1e-12);
assert.ok(Math.abs(ring._sunFixed.z - sun.z) < 1e-12);
ring.destroy();
});
+7 -7
View File
@@ -1,5 +1,6 @@
import { applicationServices } from './services/application.js';
import * as Cesium from 'cesium';
import { toRadians } from './geo/vector.js';
import { findCamera } from './render/rendererOf.js';
import { greatCircleMeters } from './geoDistance.js';
import {
deriveWeatherEffectProfile,
@@ -341,15 +342,14 @@ class CockpitCloudEffectsController {
}
cameraPoint() {
const cartographic = this.viewer?.camera?.positionCartographic;
if (!cartographic) return null;
const latitude = Cesium.Math.toDegrees(cartographic.latitude);
const longitude = Cesium.Math.toDegrees(cartographic.longitude);
const pose = this.viewer ? findCamera(this.viewer)?.pose() : null;
if (!pose) return null;
const { lat: latitude, lon: longitude } = pose;
if (![latitude, longitude].every(Number.isFinite)) return null;
return {
latitude,
longitude,
altitudeM: Math.max(0, Number(cartographic.height) || 0),
altitudeM: Math.max(0, Number(pose.height) || 0),
};
}
@@ -543,7 +543,7 @@ class CockpitCloudEffectsController {
render(timeSec) {
const gl = this.gl;
if (!gl || !this.program || !this.locations) return;
const windRadians = Cesium.Math.toRadians(this.windDirectionDeg);
const windRadians = toRadians(this.windDirectionDeg);
const windScale = 0.008 + this.windStrength * 0.022;
gl.useProgram(this.program);
gl.uniform2f(
+48 -27
View File
@@ -26,10 +26,7 @@ import {
setSignalCollapsed,
} from './ui/cockpitLayout.js';
import { createBriefState } from './ui/cockpitBriefPages.js';
import {
publishBriefView,
setBriefAutoRotate,
} from './ui/cockpitBriefing.js';
import { publishBriefView, setBriefAutoRotate } from './ui/cockpitBriefing.js';
import { CockpitDisplayPortal } from './ui/cockpitDisplayPortal.js';
import { _handleContextLayerChange } from './ui/contextLayerChanges.js';
import { clearSelectedLayers } from './ui/contextActions.js';
@@ -228,7 +225,7 @@ test('Cockpit Escape handling precedes form-control shortcut suppression and foc
assert.doesNotMatch(exit, /applyTrackedCameraFrame/);
assert.match(
ui,
/restoreTrackingFrame: \(entity\) => \{[\s\S]*?gevTrackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/,
/restoreTrackingFrame: \(entity\) => \{[\s\S]*?readEntityRecord\(entity\)\?\.trackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/,
'Cockpit exit must return camera-frame ownership through the source layer so Contact Focus cannot accumulate a second owner',
);
});
@@ -294,14 +291,14 @@ test('the Contact panel never hides itself out from under its own NEXT button',
);
});
test('the cockpit reads its aircraft from the layer that owns Cesium tracking', () => {
test('the cockpit reads its aircraft from the layer the camera follows', () => {
const read = readAircraftInfo.toString();
assert.ok(read, 'readAircraftInfo is missing');
assert.match(read, /resolveTrackedAircraftInfo\(\{/);
assert.match(read, /gevTrackedId/);
// In cockpit mode the controller moves the entity off viewer.trackedEntity,
// so its own handle is the tracked identity there.
assert.match(read, /this\.viewer\?\.trackedEntity \|\| this\.trackedEntity/);
assert.match(read, /trackedId: followed\?\.key/);
// In cockpit mode the controller stops the camera following, so its own
// handle is the tracked identity there.
assert.match(read, /followedOf\(this\.viewer\) \|\| this\.trackedFollow/);
});
test('programmatic Context layer changes cannot bypass explicit expansion policy', () => {
@@ -438,13 +435,10 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls',
/data-cockpit-launcher="radio"[\s\S]*?id="cockpit-radio-toggle-btn"/,
);
const cockpitRadio = html.match(
/id="cockpit-radio-panel"[\s\S]*?<\/div>\s*<\/div>\s*<\/aside>/,
/id="cockpit-radio-panel"[\s\S]*?<\/div>\s*<\/div>\s*<div class="cockpit-utility-rail/,
);
assert.ok(cockpitRadio, 'Cockpit compact Radio controls are missing');
assert.doesNotMatch(
cockpitRadio[0],
/radio-filter|radio-tuner/,
);
assert.doesNotMatch(cockpitRadio[0], /radio-filter|radio-tuner/);
assert.match(
css,
/\.cockpit-utility-controls[\s\S]*?top:\s*var\(\s*--cockpit-utility-top/,
@@ -530,12 +524,12 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls',
);
});
test('Display orders 3D above Celestial, Clean UI below it, and Parameters below Detection', () => {
test('Visual orders Parameters below Detection, 3D below them, and Clean UI above the Effects', () => {
const display = html.match(/id="pp-toggles"[\s\S]*?id="clean-view-exit"/);
assert.ok(display, 'Display markup is missing');
assert.match(
display[0],
/id="detection-toggle"[\s\S]*?id="param-slider-panel"[\s\S]*?id="models3d-toggle"[\s\S]*?id="celestial-toggle"[\s\S]*?id="clean-view-toggle"/,
/id="detection-toggle"[\s\S]*?id="param-slider-panel"[\s\S]*?id="models3d-toggle"[\s\S]*?id="scope-toggle"[\s\S]*?id="clean-view-toggle"[\s\S]*?class="pp-section-heading">Effects<[\s\S]*?id="celestial-toggle"/,
);
assert.equal(
(html.match(/id="param-slider-panel"/g) || []).length,
@@ -811,18 +805,27 @@ test('Reset releases Contact camera ownership through its selection-preserving r
);
assert.match(ui, /onReset: \(\) => this\.resetToGlobeView\(\)/);
assert.match(ui, /this\._connectGlobeReset\?\.\(this\._locationControls\)/);
assert.match(controls, /reset\(\) \{\s*if \(!this\.destroyed\) return this\.onReset\(\);/);
assert.match(
controls,
/reset\(\) \{\s*if \(!this\.destroyed\) return this\.onReset\(\);/,
);
// Both reset buttons ask the one reset owner.
const globeActions = fs.readFileSync(
path.join(ROOT, 'src', 'ui', 'views', 'panels', 'GlobeActions.vue'),
'utf8',
);
assert.match(globeActions, /id="reset-globe-view"[^>]*@click="act\('reset'\)"/);
assert.match(
globeActions,
/id="reset-globe-view"[^>]*@click="act\('reset'\)"/,
);
const cockpitView = readRadioSource(
new URL('./ui/views/CockpitView.vue', import.meta.url),
'utf8',
);
assert.match(cockpitView, /id="cockpit-reset-globe"[^>]*@click="globe\.act\('reset'\)"/);
assert.match(
cockpitView,
/id="cockpit-reset-globe"[^>]*@click="globe\.act\('reset'\)"/,
);
assert.match(
cockpitEnter.toString(),
/Object\.assign\(this\.presence, \{\s*active: true,/,
@@ -1170,7 +1173,7 @@ test('cockpit route direction uses self-contained vector artwork, not a font lig
test('cockpit aircraft handoff invalidates the prior world-position anchor', () => {
const match = _adoptTrackedEntity.toString();
assert.ok(match, 'cockpit tracked-entity handoff block is missing');
assert.match(match, /this\.viewer\.trackedEntity = undefined;/);
assert.match(match, /stopFollowing\(this\.viewer\);/);
assert.match(match, /this\.cockpitAnchorValid = false;/);
assert.match(
match,
@@ -1193,7 +1196,10 @@ test('cockpit summary presents the focused item as Contact', () => {
const match = html.match(/<aside id="cockpit-context"[\s\S]*?<\/aside>/);
assert.ok(match, 'cockpit Contact summary is missing');
assert.match(match[0], /aria-label="Contact cockpit summary"/);
assert.match(match[0], /class="cockpit-card-kicker cockpit-context-kicker">CONTACT</);
assert.match(
match[0],
/class="cockpit-card-kicker cockpit-context-kicker">CONTACT</,
);
assert.match(match[0], /aria-label="Contact navigation"/);
assert.match(
match[0],
@@ -1408,15 +1414,30 @@ test('Contact folded for one Cockpit left panel comes back only once neither is
const previous = globalThis.document;
const panels = {};
globalThis.document = { getElementById: (id) => panels[id] ?? null };
const panel = (...classes) => ({ classList: { contains: (name) => classes.includes(name) } });
const panel = (...classes) => ({
classList: { contains: (name) => classes.includes(name) },
});
try {
const otherOpen = (id) => PanelChrome.prototype._otherCockpitLeftPanelOpen(id);
const otherOpen = (id) =>
PanelChrome.prototype._otherCockpitLeftPanelOpen(id);
panels['data-panel'] = panel('collapsed');
assert.equal(otherOpen('utilities-panel'), false, 'Data Layers closed: restore');
assert.equal(
otherOpen('utilities-panel'),
false,
'Data Layers closed: restore',
);
panels['data-panel'] = panel('collapsed', 'layout-auto-collapsed');
assert.equal(otherOpen('utilities-panel'), true, 'Data Layers comes back: keep Contact folded');
assert.equal(
otherOpen('utilities-panel'),
true,
'Data Layers comes back: keep Contact folded',
);
panels['data-panel'] = panel();
assert.equal(otherOpen('utilities-panel'), true, 'Data Layers open: keep it folded');
assert.equal(
otherOpen('utilities-panel'),
true,
'Data Layers open: keep it folded',
);
} finally {
globalThis.document = previous;
}
+69 -3
View File
@@ -32,8 +32,15 @@ export function slewHeading(current, target, maxStepDeg) {
* then uses this amount to converge on the layer's delayed display position.
* Capping correction below forward speed prevents a late feed fix from
* becoming a first-person surge or reversal while still removing drift.
* @param {number} [maxDtSec] The longest step corrected for: 0.1 s, or an
* application subject's own (cockpitSubjectStepSec).
*/
export function cockpitAnchorCorrectionStep(distanceM, speedMps, dtSec) {
export function cockpitAnchorCorrectionStep(
distanceM,
speedMps,
dtSec,
maxDtSec = 0.1,
) {
if (
!Number.isFinite(distanceM) ||
distanceM <= 0 ||
@@ -41,13 +48,36 @@ export function cockpitAnchorCorrectionStep(distanceM, speedMps, dtSec) {
dtSec <= 0
)
return 0;
const dt = Math.min(0.1, dtSec);
const dt = Math.min(
Number.isFinite(maxDtSec) && maxDtSec > 0 ? maxDtSec : 0.1,
dtSec,
);
const speed = Number.isFinite(speedMps) ? Math.max(0, speedMps) : 0;
const eased = distanceM * (1 - Math.exp(-1.25 * dt));
const correctionRateMps = Math.max(0.75, speed * 0.22);
return Math.min(distanceM, eased, correctionRateMps * dt);
}
/**
* The seconds an application subject's camera update advances its heading
* slew, ground lift and anchor by: the time since the last update, at most
* its update interval plus 0.1 s. A subject updated every 500 ms then turns
* and eases at its configured rates, while a long stall (a hidden tab) still
* moves it no further than one late update would.
* @param {number} elapsedMs Time since the last camera update.
* @param {number} intervalMs The subject's update interval (0: every frame).
* @returns {number}
*/
export function cockpitSubjectStepSec(elapsedMs, intervalMs) {
const elapsedSec = Number.isFinite(elapsedMs)
? Math.max(0, elapsedMs) / 1000
: 0;
const intervalSec = Number.isFinite(intervalMs)
? Math.max(0, intervalMs) / 1000
: 0;
return Math.min(intervalSec + 0.1, elapsedSec);
}
/** Return whether a throttled cockpit presentation update is due. */
export function cockpitUiUpdateDue(nowMs, lastUpdateMs, intervalMs) {
if (!Number.isFinite(nowMs) || !Number.isFinite(intervalMs) || intervalMs < 0)
@@ -68,6 +98,42 @@ export function cockpitSurfaceWaitExpired(nowMs, startedMs, timeoutMs = 5000) {
return nowMs - startedMs >= timeoutMs;
}
/**
* How fast the clearance a ground clamp adds under an application subject's
* eye comes and goes (m/s).
*/
export const COCKPIT_SUBJECT_LIFT_MPS = 1.5;
/**
* The lift the ground clamp gives an application subject's eye this update.
* The floor is read from coarse cells that refine as tiles load, so the lift
* it asks for jumps; a ridden eye takes the clearance part of it at
* `rateMps`, while what it needs to stay out of the floor itself (`hardM`)
* applies at once.
* @param {number|null} previousM The lift given last update; null on entry.
* @param {number} targetM The lift the floor and clearance ask for (m).
* @param {number} hardM The lift that keeps the eye out of the floor (m).
* @param {number} dtSec Seconds since the last update.
* @param {number} [rateMps]
* @returns {number} At least 0, at least `hardM`.
*/
export function easeCockpitLift(
previousM,
targetM,
hardM,
dtSec,
rateMps = COCKPIT_SUBJECT_LIFT_MPS,
) {
const target = Number.isFinite(targetM) ? Math.max(0, targetM) : 0;
const hard = Number.isFinite(hardM) ? Math.max(0, hardM) : 0;
if (!Number.isFinite(previousM)) return Math.max(target, hard);
const step =
Math.max(0, Number.isFinite(rateMps) ? rateMps : 0) *
Math.max(0, Number.isFinite(dtSec) ? dtSec : 0);
const eased = previousM + Math.max(-step, Math.min(step, target - previousM));
return Math.max(0, hard, eased);
}
/**
* Keep the cockpit camera above the shared rendered-surface floor.
* Unknown floors preserve the proposed camera height.
@@ -346,7 +412,7 @@ export function relativeBearing(bearing, heading) {
* Resolve which flight layer owns the cockpit's tracked aircraft.
*
* Both layers can briefly describe a tracked aircraft during a cross-layer
* handoff, so the viewer's normalized tracked identity (`gevTrackedId`) is the
* handoff, so the viewer's normalized tracked identity (the entity record's `trackedId`) is the
* tie-breaker — the same rule `militaryAwareness.currentTrackedFlightSubject`
* uses. Layer precedence remains the fallback when no normalized identity is
* available, so tracking paths that never stamp one keep working.
+53 -1
View File
@@ -8,8 +8,11 @@ import {
cockpitAnchorCorrectionStep,
cockpitAltitudeDisplayFt,
cockpitGroundSafeHeight,
cockpitSubjectStepSec,
cockpitSurfaceWaitExpired,
cockpitUiUpdateDue,
COCKPIT_SUBJECT_LIFT_MPS,
easeCockpitLift,
compassDivisions,
compassMarkerSlot,
scrollingCompassDivisions,
@@ -56,6 +59,28 @@ test('cockpit anchor correction bounds late-fix catch-up and render stalls', ()
assert.equal(cockpitAnchorCorrectionStep(Number.NaN, 250, 0.1), 0);
});
test('an application subject on a slow cadence is corrected for its whole step', () => {
// The built-in views' step stays capped at 0.1 s...
const capped = cockpitAnchorCorrectionStep(100, 0, 0.5);
assert.equal(capped, cockpitAnchorCorrectionStep(100, 0, 0.1));
// ...while a subject updated every 500 ms is corrected for all of it.
const whole = cockpitAnchorCorrectionStep(100, 0, 0.5, 0.5);
assert.ok(Math.abs(whole / capped - 5) < 1e-9);
assert.equal(cockpitAnchorCorrectionStep(100, 0, 0.5, Number.NaN), capped);
});
test('an application subject steps by its interval, never by a long stall', () => {
assert.equal(cockpitSubjectStepSec(16, 0), 0.016);
assert.equal(cockpitSubjectStepSec(500, 500), 0.5);
assert.equal(cockpitSubjectStepSec(520, 500), 0.52);
// A hidden tab's minutes count as one late update.
assert.equal(cockpitSubjectStepSec(60_000, 500), 0.6);
assert.equal(cockpitSubjectStepSec(60_000, 0), 0.1);
assert.equal(cockpitSubjectStepSec(-5, 500), 0);
assert.equal(cockpitSubjectStepSec(Number.NaN, 500), 0);
assert.equal(cockpitSubjectStepSec(1000, Number.NaN), 0.1);
});
test('cockpit camera clearance never falls below the rendered ground floor', () => {
assert.equal(cockpitGroundSafeHeight(47, 57, 12), 69);
assert.equal(cockpitGroundSafeHeight(1200, 57, 12), 1200);
@@ -407,7 +432,7 @@ test('tracked-identity resolution falls back to layer precedence', () => {
const civilian = { icao24: 'aaa077' };
const military = { icao24: 'ae01ce' };
// No stamped identity (or one that matches neither layer) keeps the historic
// civilian-first order so tracking paths without gevTrackedId still work.
// civilian-first order so tracking paths without an entity record trackedId still work.
assert.equal(resolveTrackedAircraftInfo({ civilian, military }).layerId, 'flights');
assert.equal(
resolveTrackedAircraftInfo({ civilian, military, trackedId: 'satellites:25544' }).layerId,
@@ -435,3 +460,30 @@ test('cockpit emergency wording states the broadcast code, not a conclusion', ()
assert.equal(formatCockpitEmergency(null), null);
assert.equal(formatCockpitEmergency({ label: '' }), null);
});
test('an application subject’s ground lift eases its clearance, never the floor', () => {
// On entry the lift asked for applies at once.
assert.equal(easeCockpitLift(null, 1.5, 0, 0.016), 1.5);
// A floor cell that rises by a metre is met at the lift rate...
let lift = 0;
const frames = [];
for (let i = 0; i < 60; i += 1) {
lift = easeCockpitLift(lift, 1, 0, 0.016);
frames.push(lift);
}
assert.ok(frames[0] <= COCKPIT_SUBJECT_LIFT_MPS * 0.016 + 1e-9);
for (let i = 1; i < frames.length; i += 1)
assert.ok(
frames[i] - frames[i - 1] <= COCKPIT_SUBJECT_LIFT_MPS * 0.016 + 1e-9,
);
assert.ok(Math.abs(frames.at(-1) - 1) < 1e-9, 'reached in under a second');
// ...and given back the same way.
assert.ok(Math.abs(easeCockpitLift(1, 0, 0, 0.1) - 0.85) < 1e-9);
// What keeps the eye out of the floor itself is never eased.
assert.equal(easeCockpitLift(0, 201.5, 200, 0.016), 200);
assert.equal(
easeCockpitLift(0.2, -3, -3, 0.016),
0.2 - COCKPIT_SUBJECT_LIFT_MPS * 0.016,
);
assert.equal(easeCockpitLift(0, Number.NaN, Number.NaN, 0.016), 0);
});
+182
View File
@@ -0,0 +1,182 @@
/**
* @module cockpitProgress
* @description Lay out a subject's progress line (cockpitSubjectProviders.js)
* at a width in pixels: where each tick, label and the marker go.
*
* Ticks sit at fractions of the line, 0 at the left. Ticks closer than
* `minTickPx` merge, so a long run still reads as a line: a labelled tick
* keeps its place and takes in the bare ticks beside it, and bare ticks merge
* with each other at their mean place. A merged tick takes the strongest tone
* of those it holds. Labels never overlap: where two would, the one of lower
* priority is left out (on a tie, the later one).
*
* Pure: no DOM.
*/
/** Bare ticks closer than this merge (px). */
export const COCKPIT_PROGRESS_MIN_TICK_PX = 6;
/** Room kept between two labels (px). */
export const COCKPIT_PROGRESS_LABEL_GAP_PX = 8;
/** Tones from weakest to strongest, for a merged tick. */
const TONE_RANK = Object.freeze([
'muted',
'normal',
'live',
'estimate',
'warning',
'alert',
]);
const stronger = (a, b) =>
TONE_RANK.indexOf(b) > TONE_RANK.indexOf(a) ? b : a;
/** A label's width estimate (px): its longer line in small capitals. */
export function estimateProgressLabelPx(label) {
const longest = Math.max(
String(label?.text ?? '').length,
String(label?.detail ?? '').length,
);
return longest * 6.4 + 8;
}
/**
* The progress line at `widthPx`, or null when there is nothing to draw.
* @param {{ticks: Array<{at: number, tone: string, label: object|null}>,
* marker: {at: number, dwell: boolean}|null, tag: string}|null} progress
* As cockpitSubjectHudView gives it: ticks sorted by `at`.
* @param {number} widthPx
* @param {{minTickPx?: number, gapPx?: number,
* measure?: (label: object) => number}} [options]
* @returns {{ticks: Array<{x: number, tone: string, count: number,
* labelled: boolean}>, labels: Array<{x: number, left: number,
* width: number, align: string, text: string, detail: string,
* tone: string}>, marker: {x: number, dwell: boolean}|null,
* travelledX: number, tag: string}|null}
*/
export function cockpitProgressLayout(
progress,
widthPx,
{
minTickPx = COCKPIT_PROGRESS_MIN_TICK_PX,
gapPx = COCKPIT_PROGRESS_LABEL_GAP_PX,
measure = estimateProgressLabelPx,
} = {},
) {
const ticks = progress?.ticks;
if (!Array.isArray(ticks) || ticks.length < 2) return null;
if (!Number.isFinite(widthPx) || widthPx <= 0) return null;
const placed = ticks.map((tick, order) => ({
x: tick.at * widthPx,
tone: tick.tone,
label: tick.label,
order,
}));
const labelled = placed.filter((tick) => tick.label);
// Bare ticks beside a labelled one go into it.
const kept = labelled.map((tick) => ({
x: tick.x,
tone: tick.tone,
count: 1,
labelled: true,
label: tick.label,
order: tick.order,
}));
const bare = [];
for (const tick of placed) {
if (tick.label) continue;
const host = kept.find((entry) => Math.abs(entry.x - tick.x) < minTickPx);
if (host) {
host.tone = stronger(host.tone, tick.tone);
host.count += 1;
} else bare.push(tick);
}
// Bare ticks in a chain closer than minTickPx merge at their mean place.
let cluster = null;
const flush = () => {
if (!cluster) return;
kept.push({
x: cluster.sum / cluster.count,
tone: cluster.tone,
count: cluster.count,
labelled: false,
label: null,
order: cluster.order,
});
cluster = null;
};
for (const tick of bare) {
if (cluster && tick.x - cluster.last < minTickPx) {
cluster.sum += tick.x;
cluster.count += 1;
cluster.last = tick.x;
cluster.tone = stronger(cluster.tone, tick.tone);
} else {
flush();
cluster = {
sum: tick.x,
count: 1,
last: tick.x,
tone: tick.tone,
order: tick.order,
};
}
}
flush();
kept.sort((a, b) => a.x - b.x || a.order - b.order);
// Labels by priority; one that would overlap a placed label is left out.
const boxes = [];
const candidates = kept
.filter((tick) => tick.labelled)
.sort((a, b) => b.label.priority - a.label.priority || a.order - b.order);
for (const tick of candidates) {
const width = Math.min(widthPx, Math.max(0, measure(tick.label)));
let left =
tick.label.align === 'start'
? tick.x
: tick.label.align === 'end'
? tick.x - width
: tick.x - width / 2;
left = Math.min(Math.max(0, left), widthPx - width);
const right = left + width;
if (
boxes.some((box) => left < box.right + gapPx && right > box.left - gapPx)
)
continue;
boxes.push({
x: tick.x,
left,
right,
width,
align: tick.label.align,
text: tick.label.text,
detail: tick.label.detail,
tone: tick.tone,
order: tick.order,
});
}
boxes.sort((a, b) => a.left - b.left);
const marker = progress.marker
? { x: progress.marker.at * widthPx, dwell: progress.marker.dwell }
: null;
return {
ticks: kept.map(({ x, tone, count, labelled: isLabelled }) => ({
x,
tone,
count,
labelled: isLabelled,
})),
labels: boxes.map(({ x, left, width, align, text, detail, tone }) => ({
x,
left,
width,
align,
text,
detail,
tone,
})),
marker,
travelledX: marker ? marker.x : 0,
tag: progress.tag || '',
};
}
+144
View File
@@ -0,0 +1,144 @@
// src/cockpitProgress.test.mjs — a subject's progress line laid out at a
// width: close bare ticks merge, labelled ticks keep their place, labels never
// overlap (the lower priority gives way) and the part before the marker is
// the travelled part.
import test from 'node:test';
import assert from 'node:assert/strict';
import { cockpitProgressLayout } from './cockpitProgress.js';
const tick = (at, label = null, tone = 'normal') => ({ at, tone, label });
const label = (text, priority, align = 'center', detail = '') => ({
text,
detail,
priority,
align,
});
/** Every label is 50 px wide. */
const measure = () => 50;
test('nothing is drawn without two ticks or a width', () => {
assert.equal(cockpitProgressLayout(null, 500), null);
assert.equal(cockpitProgressLayout({ ticks: [tick(0)] }, 500), null);
assert.equal(
cockpitProgressLayout({ ticks: [tick(0), tick(1)], marker: null }, 0),
null,
);
});
test('ticks closer than the minimum spacing merge, keeping the strongest tone', () => {
const layout = cockpitProgressLayout(
{
ticks: [
tick(0, label('A', 1, 'start')),
tick(0.1),
tick(0.101, null, 'warning'),
tick(0.102),
tick(0.5),
tick(1, label('Z', 1, 'end')),
],
marker: { at: 0.3, dwell: false },
tag: 'TIMETABLE',
},
1000,
{ measure },
);
assert.deepEqual(
layout.ticks.map(({ x, count, tone, labelled }) => [
Math.round(x),
count,
tone,
labelled,
]),
[
[0, 1, 'normal', true],
[101, 3, 'warning', false],
[500, 1, 'normal', false],
[1000, 1, 'normal', true],
],
);
assert.deepEqual(layout.marker, { x: 300, dwell: false });
assert.equal(layout.travelledX, 300);
assert.equal(layout.tag, 'TIMETABLE');
});
test('a labelled tick keeps its place and takes in the bare ticks beside it', () => {
const layout = cockpitProgressLayout(
{
ticks: [
tick(0, label('A', 1, 'start')),
tick(0.498),
tick(0.5, label('Next', 3), 'alert'),
tick(0.503, null, 'warning'),
tick(1, label('Z', 1, 'end')),
],
marker: null,
},
1000,
{ measure },
);
const next = layout.ticks.find(({ x }) => Math.round(x) === 500);
assert.equal(next.count, 3);
assert.equal(next.labelled, true);
assert.equal(next.tone, 'alert');
assert.equal(layout.ticks.length, 3);
assert.equal(layout.marker, null);
assert.equal(layout.travelledX, 0);
});
test('labels hang from their ticks inside the line, and overlaps give way by priority', () => {
const layout = cockpitProgressLayout(
{
ticks: [
tick(0, label('First', 1, 'start')),
tick(0.04, label('Previous', 2)),
tick(0.5, label('Next', 3)),
tick(0.52, label('Close', 0)),
tick(1, label('Last', 1, 'end')),
],
marker: { at: 0.2, dwell: true },
},
1000,
{ measure },
);
assert.deepEqual(
layout.labels.map(({ text, left }) => [text, Math.round(left)]),
[
['Previous', 15],
['Next', 475],
['Last', 950],
],
);
// The first stop's label would cover the previous stop's: it gives way.
assert.ok(!layout.labels.some(({ text }) => text === 'First'));
assert.ok(!layout.labels.some(({ text }) => text === 'Close'));
assert.deepEqual(layout.marker, { x: 200, dwell: true });
});
test('a centred label at an edge is clamped inside the line', () => {
const layout = cockpitProgressLayout(
{ ticks: [tick(0, label('Edge', 1)), tick(1)], marker: null },
300,
{ measure },
);
assert.equal(layout.labels[0].left, 0);
const right = cockpitProgressLayout(
{ ticks: [tick(0), tick(1, label('Edge', 1))], marker: null },
300,
{ measure },
);
assert.equal(right.labels[0].left, 250);
});
test('a long run of calls still lays out, every one a tick or part of one', () => {
const ticks = Array.from({ length: 60 }, (_, i) => tick(i / 59));
ticks[0].label = label('First', 1, 'start');
ticks[59].label = label('Last', 1, 'end');
const narrow = cockpitProgressLayout({ ticks, marker: null }, 200);
const wide = cockpitProgressLayout({ ticks, marker: null }, 2000);
const count = (layout) =>
layout.ticks.reduce((sum, entry) => sum + entry.count, 0);
assert.equal(count(narrow), 60);
assert.equal(count(wide), 60);
assert.ok(narrow.ticks.length < wide.ticks.length);
assert.equal(wide.ticks.length, 60);
});
+2 -2
View File
@@ -209,7 +209,7 @@ test('rows render the signals the controller presents', async (t) => {
);
assert.equal(status.className, 'warning');
assert.equal(status.querySelector('div > strong').textContent, 'UNKNOWN');
assert.equal(status.querySelector('button'), null);
assert.equal(status.querySelector('button') === null, true);
});
test('actual Context refresh retains the focused signal button across unchanged and changed details', async (t) => {
@@ -315,7 +315,7 @@ test('removing the focused identity uses the shown briefing tab once and permits
assert.equal(document.activeElement === f.signalTab(), true);
assert.equal(f.focusCalls(), calls + 1);
assert.equal(f.losses(), 0);
assert.equal(f.signalTab().closest('[hidden]'), null);
assert.equal(f.signalTab().closest('[hidden]') === null, true);
// Traversal carries on forward from the footer tab.
f.tab();
assert.equal(document.activeElement === f.pageTab(1), true);
+644
View File
@@ -0,0 +1,644 @@
/**
* @module cockpitSubjectProviders
* @description Subject providers: kinds of subject an application adds to the
* Cockpit beside its own aircraft, satellite and vessel. A provider names the
* subject entry would take, holds it while the view rides it, hands the camera
* a frame each update and the HUD a view model, and releases it on exit. Core
* knows nothing else about it.
*
* Everything a provider returns is normalized here before the Cockpit uses
* it: a malformed provider is left out, a malformed frame ends the view, and a
* malformed HUD view is read field by field, never thrown on.
*
* Pure: no Cesium, no DOM.
*/
/** The kinds the Cockpit rides itself; no provider may take one. */
export const COCKPIT_BUILT_IN_KINDS = Object.freeze([
'aircraft',
'satellite',
'vessel',
]);
/** The tones a provider's HUD texts may take. */
export const COCKPIT_SUBJECT_TONES = Object.freeze([
'normal',
'muted',
'live',
'estimate',
'warning',
'alert',
]);
/**
* The heights a frame may give (m, ellipsoidal): below the deepest dry
* ground, above anything ridden near it; outside, the frame stands on the
* floor.
*/
export const COCKPIT_SUBJECT_MIN_HEIGHT_M = -1_000;
export const COCKPIT_SUBJECT_MAX_HEIGHT_M = 50_000;
/** The most readouts, sources and signals a HUD view shows. */
export const COCKPIT_SUBJECT_MAX_READOUTS = 4;
export const COCKPIT_SUBJECT_MAX_SOURCES = 4;
export const COCKPIT_SUBJECT_MAX_SIGNALS = 4;
/** The most ticks a progress line takes. */
export const COCKPIT_SUBJECT_MAX_TICKS = 512;
const KIND_PATTERN = /^[a-z][a-z0-9-]{1,31}$/;
const LAYER_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
const ICON_PATTERN = /^[a-z0-9_]{1,40}$/;
const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/;
const REQUIRED_METHODS = Object.freeze([
'candidate',
'hold',
'read',
'hud',
'release',
]);
const RESERVED = new Set(COCKPIT_BUILT_IN_KINDS);
const TONES = new Set(COCKPIT_SUBJECT_TONES);
const isObject = (value) =>
value !== null && typeof value === 'object' && !Array.isArray(value);
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
/**
* `value` as display text: trimmed, at most `max` characters (the last one
* an ellipsis when cut, the cut never inside a surrogate pair, so an emoji is
* kept whole or left out); '' for anything that is not a string or a number.
*/
export function cockpitSubjectText(value, max) {
if (typeof value !== 'string' && !finite(value)) return '';
const text = String(value).replace(/\s+/g, ' ').trim();
if (text.length <= max) return text;
let end = max - 1;
const last = text.charCodeAt(end - 1);
if (last >= 0xd800 && last <= 0xdbff) end -= 1;
return `${text.slice(0, end)}…`;
}
const tone = (value) => (TONES.has(value) ? value : 'normal');
/** A Material Symbols entry face, or null. */
function faceOf(raw) {
if (!isObject(raw)) return null;
const label = cockpitSubjectText(raw.label, 16);
if (typeof raw.icon !== 'string' || !ICON_PATTERN.test(raw.icon) || !label)
return null;
return Object.freeze({ icon: raw.icon, label });
}
/** The labels a provider gives, normalized, or null without the required. */
function labelsOf(raw) {
if (!isObject(raw)) return null;
const labels = {
view: cockpitSubjectText(raw.view, 48),
exit: cockpitSubjectText(raw.exit, 48),
exitText: cockpitSubjectText(raw.exitText, 24),
kicker: cockpitSubjectText(raw.kicker, 48),
};
return labels.view && labels.exit && labels.exitText
? Object.freeze(labels)
: null;
}
/** A provider's look, normalized, or null without an aheadLabel. */
function lookOf(raw) {
if (!isObject(raw)) return null;
const aheadLabel = cockpitSubjectText(raw.aheadLabel, 64);
if (!aheadLabel) return null;
return Object.freeze({
restPitchDeg: finite(raw.restPitchDeg)
? clamp(raw.restPitchDeg, -90, 90)
: 0,
aheadLabel,
});
}
/**
* A provider's worded member `key` as it reads now, normalized: the value,
* or what the function it is returns when called on `provider` (so it can
* follow the page's language); null when it is malformed or a read throws.
* Reading the member, and reading what it gives, runs provider code too (a
* getter), so both are guarded as the call is.
*/
function wordedNow(provider, key, normalize) {
try {
const value = provider[key];
return (
normalize(typeof value === 'function' ? value.call(provider) : value) ??
null
);
} catch {
return null;
}
}
/** A provider's name in a warning: its kind, cut, or its place in the list. */
function providerName(provider, order) {
try {
if (typeof provider?.kind === 'string') return provider.kind.slice(0, 32);
} catch {
// A kind getter that throws gives no name.
}
return `#${order}`;
}
/** Why `provider` cannot be kept, or null. */
function refusal(provider, kinds) {
if (!isObject(provider)) return 'not an object';
if (typeof provider.kind !== 'string' || !KIND_PATTERN.test(provider.kind))
return 'malformed kind';
if (RESERVED.has(provider.kind)) return 'reserved kind';
if (kinds.has(provider.kind)) return 'repeated kind';
if (
typeof provider.layerId !== 'string' ||
!LAYER_ID_PATTERN.test(provider.layerId)
)
return 'malformed layer id';
for (const method of REQUIRED_METHODS)
if (typeof provider[method] !== 'function') return `no ${method}()`;
if (
provider.isEntryAllowed !== undefined &&
typeof provider.isEntryAllowed !== 'function'
)
return 'isEntryAllowed is not a function';
if (!wordedNow(provider, 'entryFace', faceOf)) return 'malformed entry face';
if (!wordedNow(provider, 'labels', labelsOf))
return 'labels need view, exit and exitText';
if (provider.look != null && !wordedNow(provider, 'look', lookOf))
return 'look needs an aheadLabel';
return null;
}
/**
* The application's subject providers, checked once and frozen, in the order
* entry asks them: ascending `priority`, ties in list order. Each has
* - `kind`: /^[a-z][a-z0-9-]{1,31}$/, not a built-in kind, unique;
* - `layerId`: the catalog layer the subject belongs to (entry needs it on);
* - `priority`: a finite number (default 0);
* - `entryFace`: `{icon, label}`, a Material Symbols name and a label of at
* most 16 characters, in the page's language;
* - `labels`: `{view, exit, exitText, kicker?}`, the HUD's and the exit
* button's accessible names, the exit button's text and the default kicker,
* in the page's language;
* - `look` (optional): `{restPitchDeg?, aheadLabel}`, arrow-key look-around as
* on a bridge, resting at `restPitchDeg` (default 0, -90..90), its Look
* ahead button named `aheadLabel`;
* `entryFace`, `labels` and `look` may each be a function returning the
* object: it is called on the provider again whenever they are shown and
* when the page's language changes, so its words can follow it
* (`./i18n`). A read that throws or is malformed keeps the last
* good one; `look` is on or off and `restPitchDeg` fixed as first read;
* - `cameraIntervalMs` (optional): 0..1000, null for the Cockpit's default; 0
* updates the camera every rendered frame;
* - `headingSlewDps` (optional): how fast the view turns to a new heading,
* positive or Infinity, null for the Cockpit's default;
* - `candidate()`, `isEntryAllowed(candidate)` (optional), `hold(id)`,
* `read(nowMs, ctx)`, `hud(frame, ctx)` and `release(id, {restore})`, all
* synchronous (createCockpitSubjectCaller) and called on the provider, so
* a class instance's methods keep their `this`. `isEntryAllowed` allows
* entry only by returning `true`. `hold` returns `true` once it holds the
* subject, or `false` to refuse entry; any other answer refuses it too,
* with one warning. A refused hold, and one that throws or returns a
* promise, is followed by `release(id, {restore: false})`, and by another
* once that promise settles; `release` must therefore be harmless for a
* subject it does not hold or already gave back.
*
* A provider that is not so, or whose members throw when read (a getter), is
* left out with one warning naming it; the providers after it are kept.
* @param {unknown} list
* @param {{warn?: (message: string) => void}} [options]
* @returns {ReadonlyArray<object>}
*/
export function cockpitSubjectProviders(
list = [],
{ warn = (message) => console.warn(message) } = {},
) {
const kept = [];
const kinds = new Set();
(Array.isArray(list) ? list : []).forEach((provider, order) => {
let reason;
let copy = null;
try {
reason = refusal(provider, kinds);
if (!reason) copy = keptProvider(provider, order);
} catch {
reason = 'a member threw when read';
}
if (reason) {
warn(
`[Cockpit] subject provider ${providerName(provider, order)} left out: ${reason}`,
);
return;
}
kinds.add(copy.kind);
kept.push(copy);
});
kept.sort((a, b) => a.priority - b.priority || a.order - b.order);
return Object.freeze(kept);
}
/** The frozen copy the Cockpit keeps of a provider `refusal` passed. */
function keptProvider(provider, order) {
// Worded members are read again on each use (see above); the last good
// read stands in for one that is malformed or throws.
let face = wordedNow(provider, 'entryFace', faceOf);
let labels = wordedNow(provider, 'labels', labelsOf);
// On or off, and its rest pitch, as first read.
let look = wordedNow(provider, 'look', lookOf);
const restPitchDeg = look?.restPitchDeg ?? 0;
return Object.freeze({
kind: provider.kind,
layerId: provider.layerId,
priority: finite(provider.priority) ? provider.priority : 0,
order,
get entryFace() {
face = wordedNow(provider, 'entryFace', faceOf) ?? face;
return face;
},
get labels() {
labels = wordedNow(provider, 'labels', labelsOf) ?? labels;
return labels;
},
get look() {
if (!look) return null;
const now = wordedNow(provider, 'look', lookOf);
if (now)
look = Object.freeze({ restPitchDeg, aheadLabel: now.aheadLabel });
return look;
},
cameraIntervalMs:
finite(provider.cameraIntervalMs) &&
provider.cameraIntervalMs >= 0 &&
provider.cameraIntervalMs <= 1000
? provider.cameraIntervalMs
: null,
headingSlewDps:
provider.headingSlewDps === Infinity ||
(finite(provider.headingSlewDps) && provider.headingSlewDps > 0)
? provider.headingSlewDps
: null,
// Bound, so a method that uses `this` (a class instance's, say) still
// reads its own provider when called on this copy.
candidate: provider.candidate.bind(provider),
isEntryAllowed: provider.isEntryAllowed
? provider.isEntryAllowed.bind(provider)
: () => true,
hold: provider.hold.bind(provider),
read: provider.read.bind(provider),
hud: provider.hud.bind(provider),
release: provider.release.bind(provider),
});
}
/**
* A provider's candidate: `{id, name, face, selectedAt}`, or null without a
* usable id. `name` falls back to the id; `face` is null unless well formed;
* `selectedAt` (a number or a short string, else null) is a token the
* provider changes each time its subject is selected, even again: a
* subject selected after the built-in ones takes entry (entryCandidates).
* Null too when reading `raw` throws (a getter runs provider code).
* @param {unknown} raw What `candidate()` returned.
*/
export function cockpitSubjectCandidate(raw) {
try {
return candidateOf(raw);
} catch {
// A getter on what candidate() returned threw: no candidate.
return null;
}
}
function candidateOf(raw) {
if (!isObject(raw) || typeof raw.id !== 'string') return null;
const id = raw.id.trim();
if (!id || id.length > 128) return null;
const selectedAt =
finite(raw.selectedAt) ||
(typeof raw.selectedAt === 'string' && raw.selectedAt.length <= 64)
? raw.selectedAt
: null;
return Object.freeze({
id,
name: cockpitSubjectText(raw.name, 64) || cockpitSubjectText(id, 64),
face: faceOf(raw.face),
selectedAt,
});
}
/**
* One camera frame from a provider, normalized, or null when it cannot place
* the camera (the view then ends): not an object, an id other than `heldId`,
* a position that is not finite, an eye with no valid `upM` (0..1000), or a
* read of it that throws (a getter runs provider code).
* A `heightM` that is not finite or lies outside
* COCKPIT_SUBJECT_MIN_HEIGHT_M..COCKPIT_SUBJECT_MAX_HEIGHT_M reads as null:
* the eye then stands on the shared floor, or where it last stood while that
* is cold. The anchor is `'inertial'` only when asked for and the frame
* gives a speed; otherwise it is `'exact'`. An id is compared with `heldId`
* trimmed, as `cockpitSubjectCandidate` trims it.
* @param {unknown} raw What `read()` returned.
* @param {string} heldId The subject the view holds.
* @returns {object|null} `{id, name, latitude, longitude, heightM, headingDeg,
* courseDeg, speedMps, stale, groundClamp, anchor, eye: {upM, forwardM,
* pitchDeg, minClearanceM}}`.
*/
export function cockpitSubjectFrame(raw, heldId) {
try {
return frameOf(raw, heldId);
} catch {
// A getter on what read() returned threw: as a malformed frame.
return null;
}
}
function frameOf(raw, heldId) {
if (!isObject(raw) || typeof raw.id !== 'string' || raw.id.trim() !== heldId)
return null;
const latitude = raw.latitude;
const longitude = raw.longitude;
if (!finite(latitude) || !finite(longitude) || Math.abs(latitude) > 90)
return null;
const eye = isObject(raw.eye) ? raw.eye : null;
if (!eye || !finite(eye.upM) || eye.upM < 0 || eye.upM > 1000) return null;
const heading = (value) =>
finite(value) ? ((value % 360) + 360) % 360 : null;
const headingDeg = heading(raw.headingDeg);
const speedMps =
finite(raw.speedMps) && raw.speedMps >= 0 ? raw.speedMps : null;
return {
id: heldId,
name: cockpitSubjectText(raw.name, 64) || cockpitSubjectText(heldId, 64),
latitude,
longitude: ((((longitude + 180) % 360) + 360) % 360) - 180,
heightM:
finite(raw.heightM) &&
raw.heightM >= COCKPIT_SUBJECT_MIN_HEIGHT_M &&
raw.heightM <= COCKPIT_SUBJECT_MAX_HEIGHT_M
? raw.heightM
: null,
headingDeg,
courseDeg: heading(raw.courseDeg) ?? headingDeg,
speedMps,
stale: raw.stale === true,
groundClamp: raw.groundClamp !== false,
// An inertial anchor runs on at the frame's speed; with none it would
// close on a moving subject at the correction's floor and fall behind.
anchor: raw.anchor === 'exact' || speedMps === null ? 'exact' : 'inertial',
eye: {
upM: eye.upM,
forwardM:
finite(eye.forwardM) && Math.abs(eye.forwardM) <= 500
? eye.forwardM
: 0,
pitchDeg: finite(eye.pitchDeg) ? clamp(eye.pitchDeg, -90, 90) : 0,
minClearanceM:
finite(eye.minClearanceM) && eye.minClearanceM >= 0
? eye.minClearanceM
: 0,
},
};
}
/** A list of `{id, ...}` rows, each read by `row`, at most `max` kept. */
function rowsOf(raw, max, row) {
if (!Array.isArray(raw)) return [];
const rows = [];
const ids = new Set();
for (const entry of raw) {
if (rows.length >= max) break;
if (!isObject(entry)) continue;
const id = typeof entry.id === 'string' ? entry.id : '';
if (!ID_PATTERN.test(id) || ids.has(id)) continue;
const read = row(entry);
if (!read) continue;
ids.add(id);
rows.push({ id, ...read });
}
return rows;
}
/** A progress line, or null without at least two ticks. */
function progressOf(raw) {
if (!isObject(raw) || !Array.isArray(raw.ticks)) return null;
const ticks = [];
for (const tick of raw.ticks) {
if (ticks.length >= COCKPIT_SUBJECT_MAX_TICKS) break;
if (!isObject(tick) || !finite(tick.at) || tick.at < 0 || tick.at > 1)
continue;
let label = null;
if (isObject(tick.label)) {
const text = cockpitSubjectText(tick.label.text, 40);
if (text)
label = {
text,
detail: cockpitSubjectText(tick.label.detail, 64),
priority: finite(tick.label.priority)
? clamp(Math.round(tick.label.priority), 0, 9)
: 0,
align: ['start', 'center', 'end'].includes(tick.label.align)
? tick.label.align
: 'center',
};
}
ticks.push({ at: tick.at, tone: tone(tick.tone), label });
}
if (ticks.length < 2) return null;
ticks.sort((a, b) => a.at - b.at);
const marker =
isObject(raw.marker) && finite(raw.marker.at)
? { at: clamp(raw.marker.at, 0, 1), dwell: raw.marker.dwell === true }
: null;
return {
ticks,
marker,
tag: cockpitSubjectText(raw.tag, 16),
summary: cockpitSubjectText(raw.summary, 160),
};
}
/**
* A provider's HUD view model, normalized; never throws. Texts are coerced
* and cut to their caps, lists to their lengths, tones to
* COCKPIT_SUBJECT_TONES, numbers clamped; a malformed member reads as absent.
* Null when reading `raw` throws (a getter runs provider code), so the caller
* keeps the view it has, as when `hud()` itself throws.
* All text is shown as given: the provider words it in the page's language.
* @param {unknown} raw What `hud()` returned.
* @returns {object|null} `{kicker, title, meta: {text, tone}, speed: {value,
* unit, tag, tone}|null, readouts: [{id, label, value, detail, tone}],
* sources: [{id, label, text, tone}],
* route: {title, from, to, status}|null,
* progress: {ticks: [{at, tone, label: {text, detail, priority,
* align}|null}], marker: {at, dwell}|null, tag, summary}|null,
* banner: {title, detail, tone}|null, veil: {level, streaks}|null,
* lookReadout, signals: [{id, tone, title, detail}]}`.
*/
export function cockpitSubjectHudView(raw) {
try {
return hudViewOf(raw);
} catch {
// A getter on what hud() returned threw: the caller keeps its last view.
return null;
}
}
function hudViewOf(raw) {
const view = isObject(raw) ? raw : {};
const meta = isObject(view.meta) ? view.meta : {};
const speed =
isObject(view.speed) &&
(view.speed.value === null ||
(finite(view.speed.value) && view.speed.value >= 0))
? {
value:
view.speed.value === null
? null
: Math.min(view.speed.value, 99_999),
unit: cockpitSubjectText(view.speed.unit, 12),
tag: cockpitSubjectText(view.speed.tag, 8),
tone: tone(view.speed.tone),
}
: null;
const route = isObject(view.route)
? {
title: cockpitSubjectText(view.route.title, 32),
from: cockpitSubjectText(view.route.from, 48),
to: cockpitSubjectText(view.route.to, 48),
status: cockpitSubjectText(view.route.status, 64),
}
: null;
const bannerTitle = isObject(view.banner)
? cockpitSubjectText(view.banner.title, 48)
: '';
const veil =
isObject(view.veil) && finite(view.veil.level)
? {
level: clamp(view.veil.level, 0, 1),
streaks: view.veil.streaks === true,
}
: null;
return {
kicker: cockpitSubjectText(view.kicker, 48),
title: cockpitSubjectText(view.title, 64),
meta: { text: cockpitSubjectText(meta.text, 96), tone: tone(meta.tone) },
speed,
readouts: rowsOf(view.readouts, COCKPIT_SUBJECT_MAX_READOUTS, (row) => {
const label = cockpitSubjectText(row.label, 24);
const value = cockpitSubjectText(row.value, 48);
return label || value
? {
label,
value,
detail: cockpitSubjectText(row.detail, 80),
tone: tone(row.tone),
}
: null;
}),
sources: rowsOf(view.sources, COCKPIT_SUBJECT_MAX_SOURCES, (row) => {
const text = cockpitSubjectText(row.text, 120);
return text
? {
label: cockpitSubjectText(row.label, 16),
text,
tone: tone(row.tone),
}
: null;
}),
route: route && (route.from || route.to) ? route : null,
progress: progressOf(view.progress),
banner: bannerTitle
? {
title: bannerTitle,
detail: cockpitSubjectText(view.banner.detail, 96),
tone: tone(view.banner.tone),
}
: null,
veil: veil && veil.level > 0 ? veil : null,
lookReadout: cockpitSubjectText(view.lookReadout, 48),
signals: rowsOf(view.signals, COCKPIT_SUBJECT_MAX_SIGNALS, (row) => {
const title = cockpitSubjectText(row.title, 48);
return title
? {
title,
detail: cockpitSubjectText(row.detail, 96),
tone: tone(row.tone),
}
: null;
}),
};
}
/**
* A guarded caller for provider methods: `call(provider, method, args,
* fallback)` returns what the method returns, or `fallback` when it throws,
* warning once per provider and method.
*
* Provider methods are synchronous: the Cockpit calls them on its render
* cadence and uses the answer at once. One that returns a promise (an async
* function, say) breaks that contract: the promise is refused as a throw
* would be (its rejection, if any, is swallowed), with one warning, and
* `onSettled`, when given, runs once the promise has settled, so a caller
* can undo work that lands late.
*
* `call.warnOnce(provider, method, message, error)` warns on the same
* once-per-provider-and-method footing, for an answer the caller finds
* malformed.
* @param {{warn?: (message: string, error: unknown) => void}} [options]
*/
export function createCockpitSubjectCaller({
warn = (message, error) => console.warn(message, error),
} = {}) {
const warned = new Set();
const warnOnce = (provider, method, message, error) => {
const key = `${provider.kind}:${method}`;
if (warned.has(key)) return;
warned.add(key);
warn(
`[Cockpit] subject provider ${provider.kind} ${method}() ${message}`,
error,
);
};
function call(
provider,
method,
args = [],
fallback = null,
onSettled = null,
) {
let result;
let thenable;
try {
result = provider[method](...args);
// Reading `then` runs provider code too (a getter may throw), so it is
// guarded as the call is.
thenable =
result !== null &&
(typeof result === 'object' || typeof result === 'function') &&
typeof result.then === 'function';
} catch (error) {
warnOnce(provider, method, 'failed', error);
return fallback;
}
if (thenable) {
// Its work may still land: `onSettled` runs once it has, either way.
const settled = () => {
if (typeof onSettled === 'function') onSettled();
};
Promise.resolve(result).then(settled, settled);
warnOnce(
provider,
method,
'returned a promise; provider methods are synchronous',
null,
);
return fallback;
}
return result;
}
call.warnOnce = warnOnce;
return call;
}
+698
View File
@@ -0,0 +1,698 @@
// src/cockpitSubjectProviders.test.mjs — an application's subject providers
// are checked once and what they return is normalized before the Cockpit
// uses it: a malformed provider is left out, a malformed frame ends the view,
// and a malformed HUD view is read field by field and never thrown on.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
COCKPIT_BUILT_IN_KINDS,
COCKPIT_SUBJECT_MAX_READOUTS,
COCKPIT_SUBJECT_MAX_TICKS,
cockpitSubjectCandidate,
cockpitSubjectFrame,
cockpitSubjectHudView,
cockpitSubjectProviders,
cockpitSubjectText,
createCockpitSubjectCaller,
} from './cockpitSubjectProviders.js';
const noop = () => null;
/** A well-formed provider, with `overrides`. */
const provider = (overrides = {}) => ({
kind: 'example-kind',
layerId: 'example-layer',
entryFace: { icon: 'commute', label: 'RIDE' },
labels: {
view: 'First-person view',
exit: 'Exit first-person view',
exitText: 'EXIT VIEW',
},
candidate: noop,
hold: () => true,
read: noop,
hud: noop,
release: noop,
...overrides,
});
const keep = (list) => {
const warnings = [];
const kept = cockpitSubjectProviders(list, {
warn: (message) => warnings.push(message),
});
return { kept, warnings };
};
test('well-formed providers are kept, frozen, in priority then list order', () => {
const { kept, warnings } = keep([
provider({ kind: 'late', priority: 5 }),
provider({ kind: 'first-of-two', priority: 1 }),
provider({ kind: 'second-of-two', priority: 1 }),
provider({ kind: 'default-priority' }),
]);
assert.deepEqual(warnings, []);
assert.deepEqual(
kept.map(({ kind }) => kind),
['default-priority', 'first-of-two', 'second-of-two', 'late'],
);
assert.ok(Object.isFrozen(kept));
assert.ok(Object.isFrozen(kept[0]));
const [first] = kept;
assert.equal(first.priority, 0);
assert.equal(first.look, null);
assert.equal(first.cameraIntervalMs, null);
assert.equal(first.headingSlewDps, null);
assert.equal(first.isEntryAllowed(), true, 'no rule of its own allows');
assert.deepEqual(first.labels, {
view: 'First-person view',
exit: 'Exit first-person view',
exitText: 'EXIT VIEW',
kicker: '',
});
});
test('malformed, reserved and repeated providers are left out with one warning each', () => {
const cases = [
[null, /not an object/],
[provider({ kind: 'X' }), /malformed kind/],
[provider({ kind: 'a' }), /malformed kind/],
[provider({ layerId: 'Bad Layer' }), /malformed layer id/],
[provider({ hold: undefined }), /no hold\(\)/],
[provider({ read: 'read' }), /no read\(\)/],
[provider({ isEntryAllowed: true }), /isEntryAllowed/],
[provider({ entryFace: { icon: 'Bad Icon', label: 'X' } }), /entry face/],
[provider({ entryFace: { icon: 'commute', label: '' } }), /entry face/],
[provider({ labels: { view: 'v', exit: 'e' } }), /labels/],
[provider({ look: { restPitchDeg: -3 } }), /aheadLabel/],
];
for (const [entry, reason] of cases) {
const { kept, warnings } = keep([entry]);
assert.equal(kept.length, 0, String(reason));
assert.equal(warnings.length, 1, String(reason));
assert.match(warnings[0], reason);
}
for (const kind of COCKPIT_BUILT_IN_KINDS) {
const { kept, warnings } = keep([provider({ kind })]);
assert.equal(kept.length, 0, kind);
assert.match(warnings[0], /reserved kind/);
}
const { kept, warnings } = keep([provider(), provider()]);
assert.equal(kept.length, 1);
assert.match(warnings[0], /repeated kind/);
assert.deepEqual(keep('not a list').kept, []);
});
test('optional settings are kept when in range and defaulted otherwise', () => {
const [ranged] = keep([
provider({
priority: -2,
look: { restPitchDeg: -120, aheadLabel: 'Look ahead' },
cameraIntervalMs: 0,
headingSlewDps: Infinity,
labels: {
view: 'v',
exit: 'e',
exitText: 'x',
kicker: 'K'.repeat(80),
},
}),
]).kept;
assert.equal(ranged.priority, -2);
assert.deepEqual(ranged.look, {
restPitchDeg: -90,
aheadLabel: 'Look ahead',
});
assert.equal(ranged.cameraIntervalMs, 0);
assert.equal(ranged.headingSlewDps, Infinity);
assert.equal(ranged.labels.kicker.length, 48);
assert.ok(ranged.labels.kicker.endsWith('…'));
const [defaulted] = keep([
provider({
priority: NaN,
cameraIntervalMs: 5000,
headingSlewDps: -1,
}),
]).kept;
assert.equal(defaulted.priority, 0);
assert.equal(defaulted.cameraIntervalMs, null);
assert.equal(defaulted.headingSlewDps, null);
});
test('a candidate needs an id; its name and face are read with care', () => {
assert.equal(cockpitSubjectCandidate(null), null);
assert.equal(cockpitSubjectCandidate({ id: 7 }), null);
assert.equal(cockpitSubjectCandidate({ id: ' ' }), null);
assert.equal(cockpitSubjectCandidate({ id: 'x'.repeat(129) }), null);
assert.deepEqual(cockpitSubjectCandidate({ id: ' a1 ' }), {
id: 'a1',
name: 'a1',
face: null,
selectedAt: null,
});
// A selection token is a number or a short string.
assert.equal(
cockpitSubjectCandidate({ id: 'a1', selectedAt: 5 }).selectedAt,
5,
);
assert.equal(
cockpitSubjectCandidate({ id: 'a1', selectedAt: 'click-2' }).selectedAt,
'click-2',
);
for (const selectedAt of [Number.NaN, {}, 'x'.repeat(65)])
assert.equal(
cockpitSubjectCandidate({ id: 'a1', selectedAt }).selectedAt,
null,
);
const read = cockpitSubjectCandidate({
id: 'a1',
name: ' Example 12 ',
face: { icon: 'tram', label: 'RIDE' },
});
assert.equal(read.name, 'Example 12');
assert.deepEqual(read.face, { icon: 'tram', label: 'RIDE' });
assert.equal(
cockpitSubjectCandidate({ id: 'a1', face: { icon: 'BAD' } }).face,
null,
);
});
test('a frame is the held subject at a finite place with an eye height, else null', () => {
const frame = (overrides = {}) => ({
id: 'a1',
latitude: 47,
longitude: 8,
eye: { upM: 3.5 },
...overrides,
});
const read = cockpitSubjectFrame(frame(), 'a1');
assert.deepEqual(read, {
id: 'a1',
name: 'a1',
latitude: 47,
longitude: 8,
heightM: null,
headingDeg: null,
courseDeg: null,
speedMps: null,
stale: false,
groundClamp: true,
// No speed to run an inertial anchor on: it sits on the subject.
anchor: 'exact',
eye: { upM: 3.5, forwardM: 0, pitchDeg: 0, minClearanceM: 0 },
});
assert.equal(
cockpitSubjectFrame(frame({ speedMps: 30 }), 'a1').anchor,
'inertial',
'with a speed it runs on',
);
// A held id is trimmed (cockpitSubjectCandidate), and so is a frame's.
assert.equal(cockpitSubjectFrame(frame({ id: ' a1 ' }), 'a1')?.id, 'a1');
for (const bad of [
null,
frame({ id: 'other' }),
frame({ latitude: 91 }),
frame({ latitude: NaN }),
frame({ longitude: Infinity }),
frame({ eye: null }),
frame({ eye: { upM: -1 } }),
frame({ eye: { upM: 2000 } }),
frame({ eye: { upM: '3' } }),
])
assert.equal(cockpitSubjectFrame(bad, 'a1'), null, JSON.stringify(bad));
const full = cockpitSubjectFrame(
frame({
name: 'Example',
longitude: 190,
heightM: 412.5,
headingDeg: -10,
courseDeg: 725,
speedMps: 22,
stale: true,
groundClamp: false,
anchor: 'exact',
eye: { upM: 2, forwardM: 600, pitchDeg: -100, minClearanceM: 1.5 },
}),
'a1',
);
assert.equal(full.longitude, -170);
assert.equal(full.heightM, 412.5);
// A height outside any plausible ground reads as none.
for (const heightM of [-6_400_000, 1e9, Infinity])
assert.equal(cockpitSubjectFrame(frame({ heightM }), 'a1').heightM, null);
assert.equal(
cockpitSubjectFrame(frame({ heightM: -400 }), 'a1').heightM,
-400,
);
assert.equal(full.headingDeg, 350);
assert.equal(full.courseDeg, 5);
assert.equal(full.speedMps, 22);
assert.equal(full.stale, true);
assert.equal(full.groundClamp, false);
assert.equal(full.anchor, 'exact');
assert.deepEqual(full.eye, {
upM: 2,
forwardM: 0,
pitchDeg: -90,
minClearanceM: 1.5,
});
// Only exactly false turns the ground clamp off; course falls back to heading.
const loose = cockpitSubjectFrame(
frame({ groundClamp: 0, anchor: 'EXACT', headingDeg: 90, speedMps: -1 }),
'a1',
);
assert.equal(loose.groundClamp, true);
assert.equal(
cockpitSubjectFrame(frame({ anchor: 'EXACT', speedMps: 5 }), 'a1').anchor,
'inertial',
);
assert.equal(loose.courseDeg, 90);
assert.equal(loose.speedMps, null);
});
test('a HUD view is read field by field: caps, tones, clamps, never a throw', () => {
const empty = cockpitSubjectHudView(null);
assert.deepEqual(empty, {
kicker: '',
title: '',
meta: { text: '', tone: 'normal' },
speed: null,
readouts: [],
sources: [],
route: null,
progress: null,
banner: null,
veil: null,
lookReadout: '',
signals: [],
});
for (const odd of [42, 'text', [], { readouts: 'x', progress: { ticks: 3 } }])
assert.doesNotThrow(() => cockpitSubjectHudView(odd));
const view = cockpitSubjectHudView({
kicker: 'LINE · OPERATOR',
title: 'Name → Destination',
meta: { text: 'LIVE', tone: 'bogus' },
speed: { value: 84.4, unit: 'km/h', tag: 'LIVE', tone: 'live' },
readouts: [
...Array.from({ length: 6 }, (_, i) => ({
id: `r${i}`,
label: 'NEXT',
value: `Stop ${i}`,
tone: 'warning',
})),
],
sources: [
{ id: 'track', label: 'TRACK', text: 'operator shape' },
{ id: 'track', label: 'TRACK', text: 'repeated id' },
{ id: 'Bad Id', text: 'refused' },
{ id: 'empty', label: 'X', text: '' },
],
route: { title: 'ROUTE', from: 'A', to: 'B', status: '3 stops' },
banner: { title: 'BANNER', detail: 'detail', tone: 'alert' },
veil: { level: 4, streaks: 1 },
lookReadout: 'LOOK RIGHT',
signals: [{ id: 's1', title: 'T', detail: 'D', tone: 'warning' }],
});
assert.equal(view.meta.tone, 'normal');
assert.deepEqual(view.speed, {
value: 84.4,
unit: 'km/h',
tag: 'LIVE',
tone: 'live',
});
assert.equal(view.readouts.length, COCKPIT_SUBJECT_MAX_READOUTS);
assert.equal(view.readouts[0].tone, 'warning');
assert.deepEqual(
view.sources.map(({ id }) => id),
['track'],
);
assert.deepEqual(view.route, {
title: 'ROUTE',
from: 'A',
to: 'B',
status: '3 stops',
});
assert.equal(view.banner.tone, 'alert');
assert.deepEqual(view.veil, { level: 1, streaks: false });
assert.equal(view.lookReadout, 'LOOK RIGHT');
assert.equal(view.signals[0].tone, 'warning');
// A veil at 0, a speed below 0 and a route with no ends are absent.
const absent = cockpitSubjectHudView({
veil: { level: 0 },
speed: { value: -3 },
route: { from: '', to: '' },
});
assert.equal(absent.veil, null);
assert.equal(absent.speed, null);
assert.equal(absent.route, null);
// A speed of null is a speed not yet known.
assert.equal(
cockpitSubjectHudView({ speed: { value: null } }).speed.value,
null,
);
});
test('a progress line keeps ticks in 0..1, sorted and capped, and needs two', () => {
const read = cockpitSubjectHudView({
progress: {
ticks: [
{ at: 1, label: { text: 'End', align: 'end', priority: 1 } },
{ at: 0.5, tone: 'warning' },
{ at: 2 },
{ at: -0.1 },
{ at: 0, label: { text: 'Start', align: 'start', priority: 12 } },
{ at: 0.25, label: { text: '', detail: 'no text, no label' } },
],
marker: { at: 1.4, dwell: true },
tag: 'TIMETABLE',
summary: 'From Start to End',
},
}).progress;
assert.deepEqual(
read.ticks.map(({ at }) => at),
[0, 0.25, 0.5, 1],
);
assert.equal(read.ticks[0].label.priority, 9);
assert.equal(read.ticks[0].label.align, 'start');
assert.equal(read.ticks[1].label, null);
assert.equal(read.ticks[2].tone, 'warning');
assert.deepEqual(read.marker, { at: 1, dwell: true });
assert.equal(read.tag, 'TIMETABLE');
assert.equal(read.summary, 'From Start to End');
assert.equal(
cockpitSubjectHudView({ progress: { ticks: [{ at: 0.5 }] } }).progress,
null,
);
const many = cockpitSubjectHudView({
progress: {
ticks: Array.from({ length: COCKPIT_SUBJECT_MAX_TICKS + 40 }, (_, i) => ({
at: i / (COCKPIT_SUBJECT_MAX_TICKS + 40),
})),
},
}).progress;
assert.equal(many.ticks.length, COCKPIT_SUBJECT_MAX_TICKS);
});
test('texts are trimmed, collapsed and cut with an ellipsis', () => {
assert.equal(cockpitSubjectText(' a \n b ', 10), 'a b');
assert.equal(cockpitSubjectText('abcdef', 4), 'abc…');
assert.equal(cockpitSubjectText(12.5, 10), '12.5');
assert.equal(cockpitSubjectText({}, 10), '');
assert.equal(cockpitSubjectText(NaN, 10), '');
});
test('a cut never splits a surrogate pair', () => {
// The cut would fall between the emoji's halves: it is left out whole.
assert.equal(cockpitSubjectText('abcd😀efgh', 6), 'abcd…');
// One that fits before the cut is kept whole.
assert.equal(cockpitSubjectText('abc😀efgh', 6), 'abc😀…');
const lone =
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
for (let max = 2; max <= 24; max += 1)
assert.equal(
lone.test(cockpitSubjectText('🚆 Example 12 🚉 Central', max)),
false,
`cut at ${max}`,
);
});
test('a provider method that throws returns the fallback and warns once', () => {
const warnings = [];
const call = createCockpitSubjectCaller({
warn: (message) => warnings.push(message),
});
const failing = {
kind: 'example-kind',
read() {
throw new Error('boom');
},
hud: (value) => value * 2,
};
assert.equal(call(failing, 'read', [], 'fallback'), 'fallback');
assert.equal(call(failing, 'read', [], 'fallback'), 'fallback');
assert.equal(call(failing, 'hud', [21]), 42);
assert.equal(warnings.length, 1);
assert.match(warnings[0], /example-kind read\(\) failed/);
});
test('a provider method that returns a promise is refused as a throw is, warning once', async () => {
const warnings = [];
const call = createCockpitSubjectCaller({
warn: (message) => warnings.push(message),
});
const asynchronous = {
kind: 'example-kind',
hold: async () => true,
read: () => Promise.reject(new Error('late')),
};
assert.equal(call(asynchronous, 'hold', ['a1'], 'refused'), 'refused');
assert.equal(call(asynchronous, 'hold', ['a1'], 'refused'), 'refused');
assert.equal(call(asynchronous, 'read', [], null), null);
assert.equal(warnings.length, 2, 'once per method');
assert.match(warnings[0], /hold\(\) returned a promise/);
// The rejected promise is not left unhandled.
await new Promise((resolve) => setTimeout(resolve, 0));
});
test('an answer whose `then` throws when read is handled as a throw', () => {
const warnings = [];
const call = createCockpitSubjectCaller({
warn: (message) => warnings.push(message),
});
const tricky = {
kind: 'example-kind',
hold: () => ({
get then() {
throw new Error('no then');
},
}),
};
assert.equal(call(tricky, 'hold', ['a1'], 'refused'), 'refused');
assert.equal(warnings.length, 1);
assert.match(warnings[0], /example-kind hold\(\) failed/);
});
test('the caller’s warnOnce shares its once-per-provider-and-method record', () => {
const warnings = [];
const call = createCockpitSubjectCaller({
warn: (message) => warnings.push(message),
});
const ride = {
kind: 'example-kind',
hold() {
throw new Error('boom');
},
};
call.warnOnce(ride, 'read', 'is odd');
call.warnOnce(ride, 'read', 'is odd again');
call(ride, 'hold', ['a1']);
call.warnOnce(ride, 'hold', 'is odd');
assert.deepEqual(warnings, [
'[Cockpit] subject provider example-kind read() is odd',
'[Cockpit] subject provider example-kind hold() failed',
]);
});
test('a class-based provider keeps its `this`, in its methods and its worded members', () => {
class Ride {
#word = 'RIDE';
#held = null;
kind = 'example-kind';
layerId = 'example-layer';
speak(word) {
this.#word = word;
}
entryFace() {
return { icon: 'commute', label: this.#word };
}
get labels() {
return {
view: `${this.#word} view`,
exit: 'Exit ride view',
exitText: 'EXIT RIDE',
};
}
look() {
return { aheadLabel: `Look ahead, ${this.#word}` };
}
candidate() {
return { id: 'a1', name: this.#word };
}
isEntryAllowed(candidate) {
return candidate.id === 'a1' && this.#held === null;
}
hold(id) {
this.#held = id;
return true;
}
read() {
return this.#held;
}
hud(frame) {
return { title: `${this.#word} ${frame}` };
}
release() {
this.#held = null;
return 'released';
}
}
const instance = new Ride();
const { kept, warnings } = keep([instance]);
assert.deepEqual(warnings, []);
const [ride] = kept;
assert.equal(ride.entryFace.label, 'RIDE');
assert.equal(ride.labels.view, 'RIDE view');
assert.equal(ride.look.aheadLabel, 'Look ahead, RIDE');
instance.speak('FAHRT');
assert.equal(ride.entryFace.label, 'FAHRT', 'read again, on the instance');
assert.equal(ride.look.aheadLabel, 'Look ahead, FAHRT');
// Called on the kept copy, as the Cockpit calls them.
const failures = [];
const call = createCockpitSubjectCaller({
warn: (message) => failures.push(message),
});
assert.deepEqual(call(ride, 'candidate'), { id: 'a1', name: 'FAHRT' });
assert.equal(ride.isEntryAllowed({ id: 'a1' }), true);
assert.equal(call(ride, 'hold', ['a1']), true);
assert.equal(ride.isEntryAllowed({ id: 'a1' }), false);
assert.equal(call(ride, 'read', [0, {}]), 'a1');
assert.deepEqual(call(ride, 'hud', ['a1', {}]), { title: 'FAHRT a1' });
assert.equal(call(ride, 'release', ['a1', { restore: true }]), 'released');
assert.equal(call(ride, 'read', [0, {}]), null);
assert.deepEqual(failures, []);
});
test('labels, entry face and look given as functions are read again on each use', () => {
let lang = 'en';
const words = {
en: { view: 'Ride view', exit: 'Exit ride view', exitText: 'EXIT RIDE' },
de: { view: 'Fahrtansicht', exit: 'Verlassen', exitText: 'VERLASSEN' },
};
const { kept, warnings } = keep([
provider({
labels: () => words[lang],
entryFace: () => ({
icon: 'commute',
label: { en: 'RIDE', de: 'FAHRT' }[lang],
}),
look: () => ({
restPitchDeg: lang === 'de' ? 40 : -3,
aheadLabel: lang === 'de' ? 'Nach vorn' : 'Look ahead',
}),
}),
]);
assert.deepEqual(warnings, []);
const [ride] = kept;
assert.equal(ride.labels.exitText, 'EXIT RIDE');
assert.equal(ride.entryFace.label, 'RIDE');
assert.equal(ride.look.aheadLabel, 'Look ahead');
lang = 'de';
assert.equal(ride.labels.exitText, 'VERLASSEN');
assert.equal(ride.entryFace.label, 'FAHRT');
assert.equal(ride.look.aheadLabel, 'Nach vorn');
assert.equal(ride.look.restPitchDeg, -3, 'the rest pitch is as first read');
// A read that fails or is malformed keeps the last good one.
lang = 'xx';
assert.equal(ride.labels.exitText, 'VERLASSEN');
assert.equal(ride.entryFace.label, 'FAHRT');
// Functions that are malformed from the start leave the provider out.
const bad = keep([
provider({ kind: 'bad-labels', labels: () => null }),
provider({
kind: 'thrown-face',
entryFace: () => {
throw new Error('no face');
},
}),
]);
assert.deepEqual(bad.kept, []);
assert.equal(bad.warnings.length, 2);
});
/** `target` with a getter for `key` that throws (provider code runs on a read). */
const throwingGetter = (target, key) =>
Object.defineProperty(target, key, {
enumerable: true,
get() {
throw new Error(`${key} unavailable`);
},
});
test('a provider whose getter throws is left out with one warning; the next is kept', () => {
const { kept, warnings } = keep([
throwingGetter(provider({ kind: 'thrown-face' }), 'entryFace'),
throwingGetter(provider({ kind: 'thrown-labels' }), 'labels'),
throwingGetter(provider({ kind: 'thrown-look' }), 'look'),
throwingGetter(provider(), 'kind'),
throwingGetter(provider({ kind: 'thrown-method' }), 'read'),
// Read only once the provider is accepted, so its kind must stay free.
throwingGetter(provider({ kind: 'example-kind' }), 'priority'),
provider({ kind: 'example-kind' }),
]);
assert.deepEqual(
kept.map(({ kind }) => kind),
['example-kind'],
);
assert.deepEqual(warnings, [
'[Cockpit] subject provider thrown-face left out: malformed entry face',
'[Cockpit] subject provider thrown-labels left out: labels need view, exit and exitText',
'[Cockpit] subject provider thrown-look left out: a member threw when read',
'[Cockpit] subject provider #3 left out: a member threw when read',
'[Cockpit] subject provider thrown-method left out: a member threw when read',
'[Cockpit] subject provider example-kind left out: a member threw when read',
]);
});
test('a worded getter that starts throwing keeps the last good words', () => {
let failing = false;
const words = (value) => () => {
if (failing) throw new Error('translations unavailable');
return value;
};
const definition = provider();
for (const [key, value] of Object.entries({
labels: { view: 'Ride view', exit: 'Exit ride view', exitText: 'EXIT' },
entryFace: { icon: 'commute', label: 'RIDE' },
look: { restPitchDeg: 10, aheadLabel: 'Look ahead' },
}))
Object.defineProperty(definition, key, { get: words(value) });
const { kept, warnings } = keep([definition]);
assert.deepEqual(warnings, []);
const [ride] = kept;
failing = true;
assert.equal(ride.labels.view, 'Ride view');
assert.equal(ride.entryFace.label, 'RIDE');
assert.deepEqual(ride.look, { restPitchDeg: 10, aheadLabel: 'Look ahead' });
// So does a worded object whose own member throws when read.
failing = false;
Object.defineProperty(definition, 'labels', {
get: () => throwingGetter({ view: 'v', exit: 'e', exitText: 'x' }, 'view'),
});
assert.equal(ride.labels.view, 'Ride view');
});
test('a candidate, frame or HUD view whose getter throws reads as null', () => {
assert.equal(
cockpitSubjectCandidate(throwingGetter({ name: 'Example' }, 'id')),
null,
);
const frame = { id: 'a1', latitude: 1, longitude: 2, eye: { upM: 3 } };
assert.ok(cockpitSubjectFrame(frame, 'a1'), 'well formed');
assert.equal(
cockpitSubjectFrame(throwingGetter({ ...frame }, 'latitude'), 'a1'),
null,
);
assert.equal(
cockpitSubjectFrame({ ...frame, eye: throwingGetter({}, 'upM') }, 'a1'),
null,
);
assert.equal(
cockpitSubjectHudView(throwingGetter({ title: 'T' }, 'meta')),
null,
);
assert.equal(
cockpitSubjectHudView({ title: 'T', readouts: [throwingGetter({}, 'id')] }),
null,
);
// Nothing to read is still the empty view, never null.
assert.equal(cockpitSubjectHudView(null).title, '');
});
+1 -1
View File
@@ -1,7 +1,7 @@
/*
* Cockpit aircraft metadata itself is resolved by `resolveTrackedAircraftInfo`
* in `cockpitMath.js` — the landed owner of that rule. It keeps layer
* precedence as the fallback when no normalized `gevTrackedId` is available,
* precedence as the fallback when the entity record has no normalized `trackedId`,
* so tracking paths that never stamp one keep working; `readAircraftInfo` is
* pinned to it by `cockpitMarkup.test.mjs`. This module owns only the
* multi-step ENTRY TRANSACTION (adopt → enter → roll back).
+3 -2
View File
@@ -5,6 +5,7 @@ import {
enterCockpitWithTracking,
restoreAircraftTrackingOwner,
} from './cockpitTracking.js';
import { readEntityRecord, withEntityRecord } from './data/entityRecords.js';
/**
* Model the two production stamping seams that sit under this transaction:
@@ -22,7 +23,7 @@ function stampingWorld({ entryAllowed = true } = {}) {
layerId,
trackById(id) {
if (!trackable) return false;
world.trackedEntity = { gevTrackedId: `${layerId}:${id}` };
world.trackedEntity = withEntityRecord({}, { trackedId: `${layerId}:${id}` });
stamp('trackedEntityChanged'); // the ui.js listener
return true;
},
@@ -80,7 +81,7 @@ test('a refused Cockpit entry still stamps for the tracker it already moved', ()
// Adoption stamped, and the rollback re-track stamped again.
assert.deepEqual(world.stamps, ['trackedEntityChanged', 'trackedEntityChanged']);
assert.equal(world.generation, 2);
assert.equal(world.trackedEntity.gevTrackedId, 'military:ae01ce');
assert.equal(readEntityRecord(world.trackedEntity)?.trackedId, 'military:ae01ce');
});
test('a Cockpit entry that mutates nothing takes no camera authority', () => {
+18
View File
@@ -481,6 +481,24 @@ export function orbitEntryAllowed({
);
}
/**
* Whether an application subject provider's candidate can be ridden. Like the
* bridge and orbit it needs only its own layer on, and waits out a Context
* change in flight; the provider then has its own say (`isEntryAllowed`).
* @param {{layerEnabled: boolean, contextModeChanging: boolean,
* providerAllows: boolean}} state
* @returns {boolean}
*/
export function subjectEntryAllowed({
layerEnabled,
contextModeChanging,
providerAllows,
}) {
return (
Boolean(layerEnabled) && !contextModeChanging && providerAllows === true
);
}
/**
* Internal context-mode id → the word the voice tools accept for it.
*
+127 -36
View File
@@ -4,18 +4,31 @@ import { _selectContextMode } from './ui/contextTransactions.js';
import { _initGlobalContextPanel } from './ui/contextBindings.js';
import { clearSelectedLayers } from './ui/contextActions.js';
import { readFileSync as readRadioSource } from 'node:fs';
const radioBindings = readRadioSource(new URL('./ui/radioBindings.js', import.meta.url), 'utf8');
const contextView = readRadioSource(new URL('./ui/views/ContextView.vue', import.meta.url), 'utf8');
const radioBindings = readRadioSource(
new URL('./ui/radioBindings.js', import.meta.url),
'utf8',
);
const contextView = readRadioSource(
new URL('./ui/views/ContextView.vue', import.meta.url),
'utf8',
);
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import assert from 'node:assert/strict';
const html = await renderApplicationHtml(readFileSync(new URL('../index.html', import.meta.url), 'utf8'));
const html = await renderApplicationHtml(
readFileSync(new URL('../index.html', import.meta.url), 'utf8'),
);
const css = readStylesheet(new URL('../style.css', import.meta.url));
test('Contacts and Space Missions both participate in the ordinary Tab sequence', () => {
for (const id of ['global-context-flights-btn', 'global-context-missions-btn']) {
const button = html.match(new RegExp(`<button id="${id}"[\\s\\S]*?</button>`));
for (const id of [
'global-context-flights-btn',
'global-context-missions-btn',
]) {
const button = html.match(
new RegExp(`<button id="${id}"[\\s\\S]*?</button>`),
);
assert.ok(button, `${id} is missing`);
assert.match(button[0], /role="tab"/);
assert.match(button[0], /tabindex="0"/);
@@ -23,7 +36,10 @@ test('Contacts and Space Missions both participate in the ordinary Tab sequence'
// The view keeps both tabs' tabindex static and never disables them; the
// transition itself is covered over happy-dom in ui/contextPanel.test.mjs.
for (const id of ['global-context-flights-btn', 'global-context-missions-btn']) {
for (const id of [
'global-context-flights-btn',
'global-context-missions-btn',
]) {
const tag = contextView.match(new RegExp(`<button id="${id}"[^>]*>`))?.[0];
assert.ok(tag, `${id} is missing from the view`);
assert.doesNotMatch(tag, /:tabindex|:disabled|\sdisabled/);
@@ -34,9 +50,22 @@ test('Context activation and Clear All never native-disable tabs and guard repea
const init = _initGlobalContextPanel.toString();
const select = _selectContextMode.toString();
const clear = clearSelectedLayers.toString();
assert.equal((init.match(/if \(\s*this\.destroyed\s*\|\|\s*this\._contextModeChanging\s*\|\|\s*this\._clearSelectedLayersPromise\s*\)\s*return;/g) || []).length, 2);
assert.doesNotMatch(select, /_globalContext(?:Flights|Missions)Btn\.disabled\s*=\s*true/);
assert.doesNotMatch(clear, /_globalContext(?:Flights|Missions)Btn\.disabled\s*=\s*true/);
assert.equal(
(
init.match(
/if \(\s*this\.destroyed\s*\|\|\s*this\._contextModeChanging\s*\|\|\s*this\._clearSelectedLayersPromise\s*\)\s*return;/g,
) || []
).length,
2,
);
assert.doesNotMatch(
select,
/_globalContext(?:Flights|Missions)Btn\.disabled\s*=\s*true/,
);
assert.doesNotMatch(
clear,
/_globalContext(?:Flights|Missions)Btn\.disabled\s*=\s*true/,
);
});
test('Context tablist retains Left, Right, Home, and End keyboard navigation', () => {
@@ -45,40 +74,62 @@ test('Context tablist retains Left, Right, Home, and End keyboard navigation', (
assert.match(initSource, /event\.key === 'ArrowLeft'/);
assert.match(initSource, /event\.key === 'Home'/);
assert.match(initSource, /event\.key === 'End'/);
assert.match(initSource, /contextTabs\[nextIndex\]\.focus\(\{ preventScroll: true \}\)/);
assert.match(
initSource,
/contextTabs\[nextIndex\]\.focus\(\{ preventScroll: true \}\)/,
);
assert.match(initSource, /contextTabs\[nextIndex\]\.click\(\)/);
});
test('Context tabs draw a visible keyboard-focus outline including active tabs', () => {
const rules = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)];
const focusRule = rules.find(([, selector, body]) => (
selector.trim().endsWith('.context-mode-button:focus-visible')
&& /outline:\s*2px solid var\(--text-primary\)/.test(body)
));
assert.ok(focusRule, 'Context focus-visible rule must draw a two-pixel outline');
const focusRule = rules.find(
([, selector, body]) =>
selector.trim().endsWith('.context-mode-button:focus-visible') &&
/outline:\s*2px solid var\(--text-primary\)/.test(body),
);
assert.ok(
focusRule,
'Context focus-visible rule must draw a two-pixel outline',
);
assert.match(focusRule[2], /outline-offset:\s*-3px/);
const activeRule = rules.find(([, selector]) => selector.trim().endsWith('.context-mode-button.active'));
const activeRule = rules.find(([, selector]) =>
selector.trim().endsWith('.context-mode-button.active'),
);
assert.ok(activeRule, 'Context active-state rule is missing');
assert.doesNotMatch(activeRule[2], /outline:\s*none/);
});
test('Context async action buttons remain focused while busy', () => {
const init = _initGlobalContextPanel.toString();
const radio = radioBindings.slice(radioBindings.indexOf('const toggleRadio = async (trigger) => {'), radioBindings.indexOf('this._storeToken = this.store?.connect?.('));
const radioPanel = readFileSync(new URL('./ui/views/panels/RadioPanel.vue', import.meta.url), 'utf8');
const radio = radioBindings.slice(
radioBindings.indexOf('const toggleRadio = async (trigger) => {'),
radioBindings.indexOf('this._storeToken = this.store?.connect?.('),
);
const radioPanel = readFileSync(
new URL('./ui/views/panels/RadioPanel.vue', import.meta.url),
'utf8',
);
const clear = clearSelectedLayers.toString();
assert.match(init, /if \(this\._installationsSearchBusy\) return;/);
assert.doesNotMatch(init, /\.disabled\s*=\s*true/);
const search = contextView.match(/<button id="installations-search-btn"[^>]*>/)?.[0];
const search = contextView.match(
/<button id="installations-search-btn"[^>]*>/,
)?.[0];
assert.ok(search, 'nearby sites search is missing');
assert.doesNotMatch(search, /:disabled|\sdisabled/);
assert.match(search, /:aria-busy=/);
assert.match(radio, /trigger\.getAttribute\('aria-busy'\) === 'true'/);
assert.doesNotMatch(radio, /trigger\.disabled\s*=\s*true/);
const cockpitRadio = readFileSync(new URL('./ui/views/panels/CockpitUtilityControls.vue', import.meta.url), 'utf8');
const cockpitEnable = cockpitRadio.match(/<UiButton id="cockpit-radio-enable-btn"[^>]*>/)?.[0];
const cockpitRadio = readFileSync(
new URL('./ui/views/panels/CockpitUtilityControls.vue', import.meta.url),
'utf8',
);
const cockpitEnable = cockpitRadio.match(
/<UiButton id="cockpit-radio-enable-btn"[^>]*>/,
)?.[0];
assert.ok(cockpitEnable, 'Cockpit Radio Enable button is missing');
assert.doesNotMatch(cockpitEnable, /disabled(?!=")|:disabled/);
assert.match(cockpitEnable, /:aria-busy=/);
@@ -89,44 +140,84 @@ test('Context async action buttons remain focused while busy', () => {
assert.match(enable, /:aria-busy=/);
assert.match(clear, /this\.setClearBusy\(true\)/);
// The globe actions view marks the clear button busy, never disabled.
const globeActions = readFileSync(new URL('./ui/views/panels/GlobeActions.vue', import.meta.url), 'utf8');
const clearButton = globeActions.match(/<button id="clear-selected-layers"[^>]*>/)?.[0];
const globeActions = readFileSync(
new URL('./ui/views/panels/GlobeActions.vue', import.meta.url),
'utf8',
);
const clearButton = globeActions.match(
/<button id="clear-selected-layers"[^>]*>/,
)?.[0];
assert.ok(clearButton, 'Clear selected layers button is missing');
assert.doesNotMatch(clearButton, /disabled(?!=")|:disabled=/);
assert.match(clearButton, /:aria-busy=/);
});
test('Context header holds only its title and collapse control', () => {
const panel = html.match(/<div id="global-context-panel"[\s\S]*?<div class="cyber-panel-body[ "]/);
test('Context header holds only its title, edge switch and collapse control', () => {
const panel = html.match(
/<div id="global-context-panel"[\s\S]*?<div class="cyber-panel-body[ "]/,
);
assert.ok(panel, 'Global Context panel is missing');
const header = panel[0].match(/<div class="ui-panel__head panel-header">([\s\S]*?)<\/div>\s*<div class="cyber-panel-body[ "]/);
const header = panel[0].match(
/<div class="ui-panel__head panel-header">([\s\S]*?)<\/div>\s*<div class="cyber-panel-body[ "]/,
);
assert.ok(header, 'Global Context header is missing');
// The kit's own ui-* classes carry no Core styles.
const tags = [...header[1].matchAll(/<(\w+)\s+(?:type="button"\s+)?class="([^"]+)"/g)].map(([, tag, cls]) =>
`${tag}.${cls.split(' ').filter((name) => !/^ui-/.test(name)).join(' ')}`);
assert.deepEqual(tags, ['span.panel-title', 'span.panel-divider', 'button.panel-collapse-btn']);
const tags = [
...header[1].matchAll(/<(\w+)\s+(?:type="button"\s+)?class="([^"]+)"/g),
].map(
([, tag, cls]) =>
`${tag}.${cls
.split(' ')
.filter((name) => !/^ui-/.test(name))
.join(' ')}`,
);
assert.deepEqual(tags, [
'span.panel-title',
'span.panel-divider',
'button.panel-edge-btn',
'span.material-symbols-outlined',
'button.panel-collapse-btn',
]);
});
test('Context reads as one segmented control with legible type and no halo', () => {
const rules = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)];
const clean = (selector) => selector.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s+/g, ' ').trim();
const rule = (selector) => rules.find(([, s]) => clean(s) === selector)?.[2] || '';
const px = (body, prop) => Number(body.match(new RegExp(`${prop}:[^;]*?(\\d+(?:\\.\\d+)?)px`))?.[1] || 0);
const clean = (selector) =>
selector
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/\s+/g, ' ')
.trim();
const rule = (selector) =>
rules.find(([, s]) => clean(s) === selector)?.[2] || '';
const px = (body, prop) =>
Number(
body.match(new RegExp(`${prop}:[^;]*?(\\d+(?:\\.\\d+)?)px`))?.[1] || 0,
);
assert.match(rule('#global-context-panel .panel-glow'), /display:\s*none/);
const modes = rule('.global-context-modes');
assert.match(modes, /border:\s*1px solid/);
assert.match(modes, /padding:\s*2px/);
assert.ok(px(rule('.context-mode-button'), 'font') >= 10, 'mode labels must stay at least 10px');
assert.ok(
px(rule('.context-mode-button'), 'font') >= 10,
'mode labels must stay at least 10px',
);
assert.doesNotMatch(rule('.context-mode-button.active'), /box-shadow/);
const standby = rule('.context-mode-standby');
assert.ok(px(standby, 'font') >= 10, 'standby guidance must stay at least 10px');
assert.ok(
px(standby, 'font') >= 10,
'standby guidance must stay at least 10px',
);
assert.doesNotMatch(standby, /dashed/);
assert.ok(px(rule('.global-context-actions .panel-layer-toggle'), 'font-size') >= 10);
assert.ok(
px(rule('.global-context-actions .panel-layer-toggle'), 'font-size') >= 10,
);
// The shared rail title colour (brighter than --text-secondary) keeps the
// open Context title legible; no Context-only rule dims it again.
assert.equal(
rule(":root:not([data-ui-theme='cyber']) #global-context-panel:not(.collapsed) .panel-title"),
rule(
":root:not([data-ui-theme='cyber']) #global-context-panel:not(.collapsed) .panel-title",
),
'',
);
});
+65
View File
@@ -206,6 +206,71 @@ export function createCyberSonarSampler(
};
}
// The contact tint: a cool grey outside the sector, warm inside it, each
// mixed in at this strength over the contact's own colour.
const CYBER_SONAR_DIM_RGB = [0.62, 0.68, 0.72];
const CYBER_SONAR_LIT_RGB = [1, 0.84, 0.84];
const CYBER_SONAR_TINT_STRENGTH = 0.72;
/** How far toward the warm tint contacts sit while the sweep is off. */
const CYBER_SONAR_NEUTRAL_COVERAGE = 0.46;
const hexOf = (rgb) =>
`#${rgb
.map((c) =>
Math.round(clamp01(c) * 255)
.toString(16)
.padStart(2, '0'),
)
.join('')}`;
/**
* The renderer's screen modulation sector for the Cyber contact sweep over
* a `width` x `height` CSS-pixel map: the same band `createCyberSonarSampler`
* samples. Not sweeping (Sonar OFF, reduced motion), a radius of 0 holds
* every contact at the neutral level the sweep rests at.
* @param {number} width
* @param {number} height
* @param {number} nowMs
* @param {{sweeping?: boolean, root?: object}} [options]
* @returns {import('./render/contract/effects').ModulationSector}
*/
export function cyberSonarSector(
width,
height,
nowMs,
{ sweeping = true, root = globalThis.document?.documentElement } = {},
) {
const settings = readCyberSonarSettings(root);
const floor = settings.opacity / 100;
const center = { x: width / 2, y: height / 2 };
const widthRad = (settings.sector * Math.PI) / 180;
if (!sweeping) {
const coverage = floor >= 0.9999 ? 1 : CYBER_SONAR_NEUTRAL_COVERAGE;
return {
center,
angle: 0,
width: widthRad,
radius: 0,
floor: floor + (1 - floor) * CYBER_SONAR_NEUTRAL_COVERAGE,
strength: CYBER_SONAR_TINT_STRENGTH,
color: hexOf(
CYBER_SONAR_DIM_RGB.map(
(c, i) => c + (CYBER_SONAR_LIT_RGB[i] - c) * coverage,
),
),
};
}
return {
center,
angle: (cyberSonarAngleDeg(nowMs) * Math.PI) / 180,
width: widthRad,
radius: (Math.min(width * 0.4, height * 0.52) * settings.range) / 100,
floor,
strength: CYBER_SONAR_TINT_STRENGTH,
color: hexOf(CYBER_SONAR_LIT_RGB),
};
}
/** Remaining delay before the next contact-projection refresh is due. */
export function cyberSonarFrameDelay(
lastPaintAt,
-295
View File
@@ -1,295 +0,0 @@
import * as Cesium from 'cesium';
// Narrow, version-tested engine adapter. Cesium has no public custom shader
// option for native point/billboard collections. Do not patch its prototypes or
// access EntityCluster's private collections. An engine upgrade must revalidate
// this adapter; unsupported versions keep the original commands unchanged.
export const CYBER_SONAR_CESIUM_VERSION = '1.138.0';
// Follow every public DrawCommand setter, including pick/shadow/culling flags.
// Copying native.dirty would keep derived pipelines dirty forever: the scene
// consumes our command, so it never clears that flag on the native command.
const commandProperties = Object.entries(
Object.getOwnPropertyDescriptors(Cesium.DrawCommand.prototype),
)
.filter(
([key, descriptor]) =>
descriptor.set && key !== 'shaderProgram' && key !== 'uniformMap',
)
.map(([key]) => key);
export function syncCyberSonarCommand(
native,
record,
program,
uniforms,
labelBackground,
) {
if (!record.command) {
record.command = new Cesium.DrawCommand();
record.uniformMap = {
...uniforms,
u_gevSonarLabelBackground: () => record.labelBackground,
};
}
const command = record.command;
record.labelBackground = labelBackground;
// Uniform values (angle/viewport/etc.) change through stable callbacks, not
// new maps/functions. Owner callback replacement and removal still propagate.
for (const key in record.uniformMap) {
if (
!(key in uniforms) &&
key !== 'u_gevSonarLabelBackground' &&
!(key in native.uniformMap)
) {
delete record.uniformMap[key];
command.dirty = true;
}
}
for (const key in native.uniformMap) {
if (record.uniformMap[key] !== native.uniformMap[key]) {
record.uniformMap[key] = native.uniformMap[key];
command.dirty = true;
}
}
for (const key of commandProperties) command[key] = native[key];
command.shaderProgram = program;
command.uniformMap = record.uniformMap;
return command;
}
export function sonarVertexSource(source, kind) {
const text = source.sources.join('\n');
const attribute =
kind === 'point' ? 'positionHighAndSize' : 'positionHighAndScale';
const lowAttribute =
kind === 'point' ? 'positionLowAndOutline' : 'positionLowAndRotation';
if (
!text.includes(attribute) ||
!text.includes(lowAttribute) ||
!text.includes('v_color') ||
!/void\s+main\s*\(\s*\)/.test(text)
)
return null;
const next = source.clone();
next.sources = [
text.replace(/void\s+main\s*\(\s*\)/, 'void gev_sonar_main()'),
`
uniform vec4 u_gevSonar; // angle, radius, opacity floor, sweep enabled
uniform vec2 u_gevSonarViewport;
uniform float u_gevSonarSector;
uniform float u_gevSonarLabelBackground;
void main() {
gev_sonar_main();
// All corners/glyphs share the contact anchor, before native screen offsets.
// Leave gl_Position untouched so appearance never changes geometry or picks.
vec4 anchor = czm_modelViewProjectionRelativeToEye * czm_translateRelativeToEye(${attribute}.xyz, ${lowAttribute}.xyz);
if (anchor.w <= 0.0) return;
vec2 pixel = anchor.xy / anchor.w * u_gevSonarViewport * 0.5;
float floorValue = u_gevSonar.z;
float factor = floorValue + (1.0 - floorValue) * 0.46;
if (u_gevSonar.w > 0.5) {
float distanceSquared = dot(pixel, pixel);
float radiusSquared = u_gevSonar.y * u_gevSonar.y;
float delta = mod(degrees(atan(pixel.x, pixel.y)) - u_gevSonar.x + 360.0, 360.0);
if (delta > 359.9999) delta = 0.0;
factor = floorValue;
if (distanceSquared < radiusSquared * 0.000625) factor = 1.0;
else if (distanceSquared <= radiusSquared && delta <= u_gevSonarSector)
factor += (1.0 - floorValue) * min(1.0, (u_gevSonarSector - delta) / min(10.0, u_gevSonarSector * 0.42));
}
#ifdef SDF
factor = (1.0 + factor) * 0.5;
#else
if (u_gevSonarLabelBackground > 0.5) factor = (1.0 + factor) * 0.5;
#endif
float coverage = floorValue >= 0.9999 ? 1.0 : clamp((factor - floorValue) / (1.0 - floorValue), 0.0, 1.0);
if (u_gevSonarLabelBackground < 0.5)
v_color.rgb = v_color.rgb * 0.28 + (vec3(0.62, 0.68, 0.72) + vec3(0.38, 0.16, 0.12) * coverage) * 0.72;
// Apply before native fragment pass classification, never after main().
v_color.a *= factor;
${kind === 'point' ? 'v_outlineColor.a *= factor;' : '#ifdef SDF\n v_outlineColor.a *= factor;\n #endif'}
}
`,
];
return next;
}
// Use native batch bounds, never individual contacts, for idle render demand.
// Like Cesium's frustum builder, exclude the far plane (it fits multiple frusta).
export function isCyberSonarCommandVisible(command, frameState, culling) {
const bounds = command.boundingVolume;
if (!bounds || !command.cull) return true;
culling ??= new Cesium.CullingVolume(
frameState.cullingVolume.planes.slice(0, 5),
);
if (culling.computeVisibility(bounds) === Cesium.Intersect.OUTSIDE)
return false;
return !(
frameState.mode === Cesium.SceneMode.SCENE3D &&
frameState.occluder &&
command.occlude &&
bounds.isOccluded(frameState.occluder)
);
}
/** Work scales with draw commands, not the number of contacts in a collection.
* Source programs, colors, pick IDs, render states and other scenes stay owned
* by Cesium. Only this scene's rendered command slice receives derived shaders.
*/
export function createCyberSonarGpu(scene, readFrame) {
const root = scene.primitives;
const original = root.update;
const programs = new Map();
let commands = new WeakMap();
let disposed = false;
const stats = {
commands: 0,
visibleCommands: 0,
programs: 0,
supported: Cesium.VERSION === CYBER_SONAR_CESIUM_VERSION,
error: null,
};
const uniforms = new Cesium.Cartesian4();
const viewport = new Cesium.Cartesian2();
let sector = 24;
const sonarUniforms = {
u_gevSonar: () => uniforms,
u_gevSonarViewport: () => viewport,
u_gevSonarSector: () => sector,
};
const culling = new Cesium.CullingVolume();
const used = new Set();
const replaced = [];
const release = () => {
for (const { program } of programs.values())
if (!program.isDestroyed()) program.destroy();
programs.clear();
commands = new WeakMap();
used.clear();
replaced.length = 0;
stats.programs = 0;
};
const wrapped = function (frameState) {
const start = frameState.commandList.length;
original.call(this, frameState);
stats.commands = 0;
stats.visibleCommands = 0;
if (
disposed ||
!stats.supported ||
!frameState.passes.render ||
frameState.passes.pick
)
return;
const frame = readFrame();
if (!frame.enabled) {
if (programs.size) release();
return;
}
viewport.x = scene.drawingBufferWidth;
viewport.y = scene.drawingBufferHeight;
uniforms.x = frame.angle;
uniforms.y =
(Math.min(viewport.x * 0.4, viewport.y * 0.52) * frame.range) / 100;
uniforms.z = frame.opacity / 100;
uniforms.w = frame.active ? 1 : 0;
sector = frame.sector;
used.clear();
replaced.length = 0;
if (frameState.cullingVolume)
for (let i = 0; i < 5; i++)
culling.planes[i] = frameState.cullingVolume.planes[i];
try {
for (let i = start; i < frameState.commandList.length; i++) {
const native = frameState.commandList[i];
const kind =
native.owner instanceof Cesium.PointPrimitiveCollection
? 'point'
: native.owner instanceof Cesium.BillboardCollection
? 'billboard'
: null;
if (!kind || !native.shaderProgram || !native.uniformMap) continue;
const source = native.shaderProgram;
// Label backgrounds are non-SDF billboard batches. The version-tested
// engine pick association distinguishes them without enumerating labels
// or reaching into EntityCluster. One representative per draw batch;
// Cesium's label glyph/background collections are homogeneous.
const labelBackground =
kind === 'billboard' &&
!source.vertexShaderSource.defines.includes('SDF') &&
native.owner.length > 0 &&
native.owner.get(0).pickPrimitive instanceof Cesium.Label
? 1
: 0;
let entry = programs.get(source);
if (!entry) {
const vertex = sonarVertexSource(source.vertexShaderSource, kind);
if (!vertex) throw new Error('Unsupported native contact shader');
const attributes = Object.fromEntries(
Object.entries(source.vertexAttributes).map(([name, value]) => [
name,
value.index,
]),
);
const program = Cesium.ShaderProgram.fromCache({
context: frameState.context,
vertexShaderSource: vertex,
fragmentShaderSource: source.fragmentShaderSource,
attributeLocations: attributes,
});
// Compile while errors can still leave the whole native command slice
// intact, rather than stopping the viewer's render loop at draw time.
try {
void program.allUniforms;
} catch (error) {
program.destroy();
throw error;
}
programs.set(source, (entry = { program }));
}
used.add(source);
let record = commands.get(native);
if (!record) commands.set(native, (record = {}));
const derived = syncCyberSonarCommand(
native,
record,
entry.program,
sonarUniforms,
labelBackground,
);
replaced.push(i, native);
frameState.commandList[i] = derived;
stats.commands++;
if (isCyberSonarCommandVisible(native, frameState, culling))
stats.visibleCommands++;
}
for (const [source, entry] of programs)
if (!used.has(source)) {
if (!entry.program.isDestroyed()) entry.program.destroy();
programs.delete(source);
}
stats.programs = programs.size;
} catch (error) {
// Recover the original commands already replaced in this slice.
for (let i = 0; i < replaced.length; i += 2)
frameState.commandList[replaced[i]] = replaced[i + 1];
stats.supported = false;
stats.commands = 0;
stats.visibleCommands = 0;
stats.error = String(error?.message || error);
release();
}
};
root.update = wrapped;
return {
stats,
destroy() {
if (disposed) return;
disposed = true;
if (root.update === wrapped && !root.isDestroyed?.())
root.update = original;
release();
},
};
}
-354
View File
@@ -1,354 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
createCyberSonarGpu,
sonarVertexSource,
CYBER_SONAR_CESIUM_VERSION,
isCyberSonarCommandVisible,
syncCyberSonarCommand,
} from './cyberSonarGpu.js';
test('stable commands reuse uniforms and derived pipelines while all native fields remain live', () => {
const native = new Cesium.DrawCommand({
count: 6,
uniformMap: { value: () => 1 },
});
const record = {},
program = {},
uniforms = { u_gevSonar: () => 42 };
const derived = syncCyberSonarCommand(native, record, program, uniforms, 0);
const map = derived.uniformMap;
derived.dirty = false;
derived.lastDirtyTime = 7;
assert.equal(native.dirty, true);
assert.equal(
syncCyberSonarCommand(native, record, program, uniforms, 1),
derived,
);
assert.equal(
derived.dirty,
false,
'stale native dirty flag must not rebuild pipelines',
);
assert.equal(derived.lastDirtyTime, 7);
assert.equal(derived.uniformMap, map);
assert.equal(map.u_gevSonarLabelBackground(), 1);
for (const [key, value] of Object.entries({
count: 12,
offset: 2,
instanceCount: 3,
pickId: 'pick',
pass: Cesium.Pass.TRANSLUCENT,
cull: false,
occlude: false,
castShadows: true,
receiveShadows: true,
pickOnly: true,
renderState: {},
vertexArray: {},
modelMatrix: Cesium.Matrix4.IDENTITY,
framebuffer: {},
})) {
derived.dirty = false;
native[key] = value;
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(derived[key], value, key);
assert.equal(derived.dirty, true, key);
}
native.uniformMap.value = () => 2;
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(map.value(), 2);
native.uniformMap = { replacement: () => 3 };
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(map.value, undefined);
assert.equal(map.replacement(), 3);
assert.equal(map.u_gevSonar(), 42);
const nextProgram = {};
syncCyberSonarCommand(native, record, nextProgram, uniforms, 0);
assert.equal(derived.shaderProgram, nextProgram);
assert.equal(native.shaderProgram, undefined);
});
test('GPU shader transform is isolated, settings-driven, and precedes native fragment classification', () => {
assert.equal(
Cesium.VERSION,
CYBER_SONAR_CESIUM_VERSION,
'engine upgrades require GPU revalidation',
);
for (const [kind, attr, low] of [
['point', 'positionHighAndSize', 'positionLowAndOutline'],
['billboard', 'positionHighAndScale', 'positionLowAndRotation'],
]) {
const source = new Cesium.ShaderSource({
defines: ['SDF'],
sources: [
`in vec4 ${attr}; in vec4 ${low}; out vec4 v_color; void main() { v_color=vec4(1.); }`,
],
});
const original = source.sources[0];
const next = sonarVertexSource(source, kind);
assert.equal(source.sources[0], original);
assert.notEqual(next, source);
assert.deepEqual(next.defines, ['SDF']);
assert.match(next.sources[0], /void gev_sonar_main/);
assert.match(next.sources[1], /v_color.a \*= factor/);
assert.match(next.sources[1], /u_gevSonarSector/);
assert.match(next.sources[1], /floorValue \+ \(1.0 - floorValue\) \* 0.46/);
assert.ok(
next.sources[1].includes(
`czm_translateRelativeToEye(${attr}.xyz, ${low}.xyz)`,
),
);
assert.match(next.sources[1], /anchor.xy \/ anchor.w/);
assert.doesNotMatch(next.sources[1], /gl_Position\s*[=\/]/);
}
assert.equal(
sonarVertexSource(
new Cesium.ShaderSource({ sources: ['void main() {}'] }),
'point',
),
null,
);
});
test('render demand follows batch bounds, including horizon culling, without far-plane rejection', () => {
const planes = Array.from(
{ length: 6 },
(_, i) => new Cesium.Cartesian4(1, 0, 0, i),
);
const frame = {
cullingVolume: { planes },
mode: Cesium.SceneMode.SCENE3D,
occluder: {},
};
let intersections = 0;
let occluded = false;
const command = {
cull: true,
occlude: true,
boundingVolume: {
intersectPlane(plane) {
intersections++;
return plane.distance === 5
? Cesium.Intersect.OUTSIDE
: Cesium.Intersect.INSIDE;
},
isOccluded() {
return occluded;
},
},
};
assert.equal(isCyberSonarCommandVisible(command, frame), true);
assert.equal(intersections, 5);
occluded = true;
assert.equal(isCyberSonarCommandVisible(command, frame), false);
frame.mode = Cesium.SceneMode.SCENE2D;
assert.equal(isCyberSonarCommandVisible(command, frame), true);
command.boundingVolume.intersectPlane = () => Cesium.Intersect.OUTSIDE;
assert.equal(isCyberSonarCommandVisible(command, frame), false);
command.cull = false;
assert.equal(isCyberSonarCommandVisible(command, frame), true);
assert.equal(isCyberSonarCommandVisible({}, frame), true);
});
test('adapter never walks contacts, touches other scenes, or transforms pick-only passes', () => {
let calls = 0;
const original = function (fs) {
assert.equal(this, root);
calls++;
fs.commandList.push({ owner: {}, id: 'terrain' });
};
const root = { update: original };
const other = { update: original };
const adapter = createCyberSonarGpu({ primitives: root }, () => ({
enabled: false,
}));
const frame = { commandList: [], passes: { render: true, pick: false } };
root.update(frame);
assert.equal(calls, 1);
assert.equal(frame.commandList[0].id, 'terrain');
assert.equal(other.update, original);
root.update({ commandList: [], passes: { render: false, pick: true } });
assert.equal(calls, 2);
adapter.destroy();
adapter.destroy();
assert.equal(root.update, original);
});
test('unknown native shaders fail closed without losing native commands', () => {
const points = new Cesium.PointPrimitiveCollection();
const command = {
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
};
const root = {
update(fs) {
fs.commandList.push(command);
},
};
const adapter = createCyberSonarGpu(
{ primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 },
() => ({
enabled: true,
active: true,
angle: 0,
range: 100,
opacity: 84,
sector: 24,
}),
);
const frame = { commandList: [], passes: { render: true } };
root.update(frame);
assert.equal(frame.commandList[0], command);
assert.equal(adapter.stats.supported, false);
assert.match(adapter.stats.error, /Unsupported native contact shader/);
assert.equal(adapter.stats.programs, 0);
adapter.destroy();
points.destroy();
});
test('program swaps, layer removal and late shader failure release only adapter resources', () => {
const points = new Cesium.PointPrimitiveCollection();
const source = () => ({
vertexShaderSource: new Cesium.ShaderSource({
sources: [
'in vec4 positionHighAndSize; in vec4 positionLowAndOutline; out vec4 v_color; void main() {}',
],
}),
vertexAttributes: {},
fragmentShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
});
const native = new Cesium.DrawCommand({
owner: points,
uniformMap: {},
shaderProgram: source(),
cull: false,
vertexArray: { generation: 1 },
pickId: 'native-pick',
});
const unknown = new Cesium.DrawCommand({
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
});
let nativeCommands = [native];
let enabled = true;
const root = {
update(frame) {
frame.commandList.push(...nativeCommands);
},
};
const fromCache = Cesium.ShaderProgram.fromCache;
const created = [];
Cesium.ShaderProgram.fromCache = () => {
const program = {
allUniforms: {},
destroyed: false,
isDestroyed() {
return this.destroyed;
},
destroy() {
assert.equal(this.destroyed, false);
this.destroyed = true;
},
};
created.push(program);
return program;
};
const adapter = createCyberSonarGpu(
{ primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 },
() => ({
enabled,
active: true,
angle: 0,
range: 100,
opacity: 84,
sector: 24,
}),
);
const draw = () => {
const frame = { commandList: [], passes: { render: true } };
root.update(frame);
return frame.commandList;
};
try {
const first = draw()[0];
assert.notEqual(first, native);
first.dirty = false;
assert.equal(draw()[0], first);
assert.equal(first.dirty, false);
assert.equal(created.length, 1, 'stable draws reuse the program');
const buffer = { generation: 2 };
native.vertexArray = buffer;
native.shaderProgram = source();
const swapped = draw()[0];
assert.equal(swapped, first);
assert.equal(swapped.vertexArray, buffer);
assert.equal(swapped.pickId, 'native-pick');
assert.equal(swapped.shaderProgram, created[1]);
assert.equal(created[0].destroyed, true);
assert.equal(adapter.stats.programs, 1);
nativeCommands = [];
draw();
assert.equal(created[1].destroyed, true);
assert.equal(
adapter.stats.programs,
0,
'disabled layers retain no adapter program',
);
nativeCommands = [native];
draw();
enabled = false;
assert.equal(draw()[0], native);
assert.equal(
created[2].destroyed,
true,
'theme/cockpit exit releases the derived program',
);
enabled = true;
nativeCommands = [native, unknown];
assert.deepEqual(
draw(),
nativeCommands,
'a later failure rolls back earlier replacements in the same slice',
);
assert.equal(created[3].destroyed, true);
assert.equal(adapter.stats.supported, false);
assert.equal(adapter.stats.programs, 0);
assert.equal(adapter.stats.commands, 0);
assert.equal(adapter.stats.visibleCommands, 0);
assert.deepEqual(draw(), nativeCommands);
assert.equal(
created.length,
4,
'unsupported draws do not retry compilation',
);
} finally {
adapter.destroy();
Cesium.ShaderProgram.fromCache = fromCache;
points.destroy();
}
});
test('disposal does not overwrite a successor update owner', () => {
const root = { update() {} };
const adapter = createCyberSonarGpu({ primitives: root }, () => ({
enabled: false,
}));
const successor = () => {};
root.update = successor;
adapter.destroy();
assert.equal(root.update, successor);
});
+120 -190
View File
@@ -1,211 +1,141 @@
import * as Cesium from 'cesium';
import { createCyberSonarGpu } from './cyberSonarGpu.js';
/**
* The Cyber contact sweep on the map's markers, through the renderer's
* `effects.screenModulation` (`src/render/contract/effects.d.ts`). This
* keeps the sweep's clock and settings; the renderer shades the markers.
*
* Each tick, before the renderer decides whether to draw: a change of the
* theme, the sweep, its settings or the map's size sets the sector at once;
* while sweeping, the sector moves to the current angle on every tick that
* draws anyway, and at least every `CYBER_SONAR_RENDER_INTERVAL_MS` (which
* then asks for a frame). Out of the theme the sector is cleared.
*
* A renderer without the capability, or one that does not list the pass
* once a sector is set, leaves markers as they are: the document's
* `cyberSonarGpu` says `unsupported`, so the HUD overlays skip their own
* sweep too, and the sonar status says so.
*
* The frame and effects ports are looked up once, when the scene is made:
* bind the renderer to the viewer before creating it.
*/
import {
applyCyberSonarPrimitive,
createCyberSonarSampler,
isCyberContactThemeActive,
isCyberContactSonarActive,
CYBER_SONAR_RENDER_INTERVAL_MS,
cyberSonarSector,
isCyberMapThemeActive,
isCyberSonarActive,
readCyberSonarSettings,
cyberSonarAngleDeg,
syncCyberSonarAnimation,
CYBER_SONAR_RENDER_INTERVAL_MS,
} from './cyberSonar.js';
import { canvasOf, findEffects, findFrame } from './render/rendererOf.js';
const alive = (value) => value && !value.isDestroyed?.();
const diagnostics = new WeakMap();
export const getCyberSonarSceneDiagnostics = (viewer) => ({
...diagnostics.get(viewer),
});
const UNSUPPORTED_MESSAGE =
'Contact GPU unavailable. Native contacts remain visible.';
export function visitCyberSonarModels(primitive, visit, visible = true) {
if (!alive(primitive)) return;
visible = visible && primitive.show !== false;
if (primitive instanceof Cesium.PrimitiveCollection) {
for (let i = 0; i < primitive.length; i++)
visitCyberSonarModels(primitive.get(i), visit, visible);
} else if (primitive instanceof Cesium.Model) {
visit(primitive, primitive, 'model', visible && primitive.ready);
}
}
/** Native dots, icons and glyphs use GPU draw-command treatment. Models retain
* their existing reversible CPU color treatment without walking native records.
/**
* @param {object} viewer The scene object the renderer is bound to.
* @param {{subscribe?: Function}} [manager] Layer visibility changes ask
* for a frame, so markers shown or hidden draw with the sweep.
* @returns {() => void} Clears the sector and lets go.
*/
export function createCyberSonarScene(viewer, manager) {
const scene = viewer?.scene;
if (
!scene?.postUpdate?.addEventListener ||
!scene?.preRender?.addEventListener
)
return () => {};
const tracked = new Map();
const matrix = new Cesium.Matrix4();
const position = new Cesium.Cartesian3();
let epoch = 0,
timer = null,
disposed = false;
let sampler, width, height, active, count;
const stats = { contacts: 0, updateMs: 0, frames: 0 };
const root = globalThis.document?.documentElement;
const gpu = createCyberSonarGpu(scene, () => ({
...readCyberSonarSettings(),
enabled: isCyberContactThemeActive(),
active: isCyberContactSonarActive(),
angle: cyberSonarAngleDeg(performance.now()),
}));
stats.gpu = gpu.stats;
let gpuSupported = gpu.stats.supported;
diagnostics.set(viewer, stats);
const restore = (visual, state) => {
if (!alive(state.owner)) return;
for (const key of state.keys)
applyCyberSonarPrimitive(visual, 1, false, undefined, key);
};
const visit = (visual, owner, kind, visible) => {
let state = tracked.get(visual);
if (!visible) {
if (state) {
restore(visual, state);
tracked.delete(visual);
}
return;
}
let p = visual.position;
if (kind === 'model')
p = Cesium.Matrix4.getTranslation(visual.modelMatrix, position);
else if (
p &&
owner.modelMatrix &&
!Cesium.Matrix4.equals(owner.modelMatrix, Cesium.Matrix4.IDENTITY)
)
p = Cesium.Matrix4.multiplyByPoint(owner.modelMatrix, p, position);
if (!p) return;
const w = matrix[3] * p.x + matrix[7] * p.y + matrix[11] * p.z + matrix[15];
const x =
(matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12]) / w;
const y =
(matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13]) / w;
if (w <= 0 || Math.abs(x) > 1.1 || Math.abs(y) > 1.1) return;
if (!state) {
state = {
owner,
keys:
kind === 'label'
? ['fillColor', 'outlineColor', 'backgroundColor']
: kind === 'marker' && visual.outlineColor
? ['color', 'outlineColor']
: ['color'],
epoch,
};
tracked.set(visual, state);
}
state.epoch = epoch;
const factor = active
? sampler.at((x + 1) * width * 0.5, (1 - y) * height * 0.5)
: sampler.neutral;
for (const key of state.keys) {
if (key === 'outlineColor' && visual.outlineWidth === 0) continue;
if (key === 'backgroundColor' && !visual.showBackground) continue;
applyCyberSonarPrimitive(
visual,
kind === 'label' ? sampler.label(factor) : factor,
true,
sampler,
key,
kind === 'model',
);
}
count++;
};
const update = () => {
if (disposed) return;
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
if (!isCyberContactThemeActive()) {
for (const [visual, state] of tracked) restore(visual, state);
tracked.clear();
stats.contacts = 0;
stats.updateMs = 0;
return;
}
const started = performance.now();
width = scene.canvas.clientWidth;
height = scene.canvas.clientHeight;
sampler = createCyberSonarSampler(width, height, started);
active = isCyberContactSonarActive();
Cesium.Matrix4.multiply(
scene.camera.frustum.projectionMatrix,
scene.camera.viewMatrix,
matrix,
);
epoch++;
count = 0;
visitCyberSonarModels(scene.primitives, visit);
for (const [visual, state] of tracked)
if (state.epoch !== epoch) {
restore(visual, state);
tracked.delete(visual);
}
stats.contacts = count;
stats.updateMs = performance.now() - started;
stats.frames++;
// No contacts, no scanner-owned render demand. In continuous scenes the
// next rendered frame cancels this timer; parked scenes refresh at fleet
// cadence. Idle update-only ticks must not continually postpone the timer.
};
let removeRender;
// Aircraft fleet writers run in preRender, while tracked models and entity
// visualizers update earlier. Compose AFTER all those owners and BEFORE
// Cesium uploads primitive attributes for this draw. Requeue at postUpdate
// so writers installed later (enable/re-enable/track) cannot overwrite sonar.
// This only reorders one callback; the contact walk runs once per actual draw.
const removeUpdate = scene.postUpdate.addEventListener(() => {
if (isCyberSonarActive()) syncCyberSonarAnimation();
const supportChanged = gpuSupported !== gpu.stats.supported;
gpuSupported = gpu.stats.supported;
const support = gpu.stats.supported ? 'supported' : 'unsupported';
const frame = findFrame(viewer);
if (!frame) return () => {};
const effects = findEffects(viewer);
const doc = globalThis.document;
const root = doc?.documentElement;
let failed = typeof effects?.screenModulation !== 'function';
let current = null;
let key = null;
let lastSetAt = Number.NEGATIVE_INFINITY;
let disposed = false;
const publish = () => {
const support = failed ? 'unsupported' : 'supported';
if (root?.dataset && root.dataset.cyberSonarGpu !== support)
root.dataset.cyberSonarGpu = support;
// Shader setup runs after preRender's model tint. If it fails while the
// scene is parked (including Sonar OFF/reduced motion), draw once more so
// the now-unsupported contact path restores models before becoming idle.
if (supportChanged) scene.requestRender();
const status = globalThis.document?.getElementById?.('cyber-sonar-status');
const message = gpu.stats.supported
? ''
: 'Contact GPU unavailable. Native contacts remain visible.';
const status = doc?.getElementById?.('cyber-sonar-status');
const message = failed ? UNSUPPORTED_MESSAGE : '';
if (status && status.textContent !== message) status.textContent = message;
removeRender?.();
removeRender = scene.preRender.addEventListener(update);
});
const removePostRender = scene.postRender?.addEventListener(() => {
if (timer !== null) clearTimeout(timer);
timer = null;
if (isCyberContactSonarActive() && (count || gpu.stats.visibleCommands))
timer = setTimeout(() => {
timer = null;
if (!disposed && isCyberContactSonarActive()) scene.requestRender();
}, CYBER_SONAR_RENDER_INTERVAL_MS);
};
/** The renderer cannot draw the pass: markers stay as they are. */
const fail = () => {
if (failed) return;
failed = true;
const had = current;
current = null;
key = null;
if (had) effects.screenModulation(null);
publish();
};
const set = (sector, at) => {
const had = current;
// Before the call: its change listeners read `current`.
current = sector;
lastSetAt = at;
effects.screenModulation(sector);
// A first sector set but not listed is unsupported; a pass that stops
// later is caught by the change listener.
if (
sector &&
!had &&
!effects.diagnostics().passes.includes('screenModulation')
)
fail();
};
const offTick = frame.on('preUpdate', (t) => {
if (disposed) return;
// The HUD's own sweep keeps its clock whether or not markers are shaded.
const active = isCyberSonarActive();
if (active) syncCyberSonarAnimation();
if (failed) return;
const theme = isCyberMapThemeActive();
const sweeping = theme && active;
if (!theme) {
if (current) set(null, lastSetAt);
key = null;
return;
}
const canvas = canvasOf(viewer);
// The sector is in CSS pixels.
const width = canvas?.clientWidth ?? 0;
const height = canvas?.clientHeight ?? 0;
const settings = readCyberSonarSettings(root);
const next = `${sweeping}|${settings.range}|${settings.opacity}|${settings.sector}|${width}|${height}`;
const now = performance.now();
if (
next === key &&
!(
sweeping &&
(now - lastSetAt >= CYBER_SONAR_RENDER_INTERVAL_MS || t.rendering)
)
)
return;
key = next;
set(cyberSonarSector(width, height, now, { sweeping, root }), now);
});
const offChange = failed
? null
: effects.on('change', (diagnostics) => {
if (current && !diagnostics.passes.includes('screenModulation')) fail();
});
const unsubscribe = manager?.subscribe?.((change) => {
if (change.type !== 'visibility') return;
scene.requestRender();
if (change.type === 'visibility') frame.requestRender('cyber-sonar');
});
publish();
return () => {
if (disposed) return;
disposed = true;
removeUpdate();
removeRender?.();
removePostRender?.();
gpu.destroy();
if (root?.dataset) delete root.dataset.cyberSonarGpu;
offTick();
offChange?.();
unsubscribe?.();
if (timer !== null) clearTimeout(timer);
for (const [visual, state] of tracked) restore(visual, state);
tracked.clear();
diagnostics.delete(viewer);
const had = current;
current = null;
if (had) effects.screenModulation(null);
if (root?.dataset) delete root.dataset.cyberSonarGpu;
};
}
+260 -240
View File
@@ -1,19 +1,16 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
CYBER_SONAR_RENDER_INTERVAL_MS,
applyCyberSonarSettings,
createCyberSonarSampler,
cyberSonarIntensityAtScreenPoint,
applyCyberSonarPrimitive,
applyCyberSonarSettings,
cyberSonarSector,
isCyberContactSonarActive,
isCyberSonarActive,
} from './cyberSonar.js';
import {
createCyberSonarScene,
visitCyberSonarModels,
getCyberSonarSceneDiagnostics,
} from './cyberSonarScene.js';
import { createCyberSonarScene } from './cyberSonarScene.js';
import { bindRenderer } from './render/rendererOf.js';
test('frame sampler matches reference without per-contact settings access', () => {
let reads = 0;
@@ -47,44 +44,7 @@ test('frame sampler matches reference without per-contact settings access', () =
);
});
test('model walk never enumerates native contact or EntityCluster records', () => {
const root = new Cesium.PrimitiveCollection();
const points = root.add(new Cesium.PointPrimitiveCollection());
points.add();
points.get = () => {
throw new Error('must not enumerate contacts');
};
const cluster = root.add(new Cesium.EntityCluster());
Object.defineProperty(cluster, '_billboardCollection', {
get() {
throw new Error('must not access cluster internals');
},
configurable: true,
});
const seen = [];
visitCyberSonarModels(root, (...v) => seen.push(v));
assert.equal(seen.length, 0);
delete cluster._billboardCollection;
root.destroy();
});
test('models retain render-pass alpha and owner refresh survives teardown', () => {
const frame = createCyberSonarSampler(1000, 800, 0);
const model = { color: new Cesium.Color(1, 0.5, 0.2, 1) };
applyCyberSonarPrimitive(model, 0.5, true, frame, 'color', true);
assert.equal(model.color.alpha, 1);
assert.ok(model.color.red < 1);
const owner = new Cesium.Color(0.2, 0.3, 0.4, 0.7);
model.color = owner;
applyCyberSonarPrimitive(model, 1, false);
assert.equal(model.color, owner);
const unset = {};
applyCyberSonarPrimitive(unset, 0.5, true, frame, 'color', true);
applyCyberSonarPrimitive(unset, 1, false);
assert.equal(unset.color, undefined);
});
test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail closed', () => {
test('removed CSS mode cannot disable GPU contacts; unsupported renderers fail closed', () => {
const root = { dataset: { uiTheme: 'cyber' }, style: { setProperty() {} } };
const options = {
root,
@@ -106,209 +66,269 @@ test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail cl
assert.equal(isCyberContactSonarActive(options), false);
});
test('native owner colors remain untouched and scene teardown releases listeners', () => {
const previous = globalThis.document;
test('the sector is the sweep the HUD shows, in CSS pixels and radians', () => {
const root = {
dataset: {
cyberSonarOpacity: '62',
cyberSonarSector: '40',
cyberSonarRange: '110',
},
};
const s = cyberSonarSector(1000, 800, 1300, { root });
assert.deepEqual(s.center, { x: 500, y: 400 });
assert.ok(Math.abs(s.angle - Math.PI / 2) < 1e-9, 'a quarter period');
assert.ok(Math.abs(s.width - (40 * Math.PI) / 180) < 1e-12);
assert.ok(Math.abs(s.radius - 440) < 1e-9);
assert.equal(s.floor, 0.62);
assert.equal(s.strength, 0.72);
assert.equal(s.color, '#ffd6d6');
const rest = cyberSonarSector(1000, 800, 1300, { root, sweeping: false });
assert.equal(rest.radius, 0);
assert.ok(Math.abs(rest.floor - (0.62 + 0.38 * 0.46)) < 1e-12);
});
/**
* A document with the Cyber HUD shown, and a renderer fake bound to a
* viewer: its frame's preUpdate is ticked by hand and its effects record
* each sector.
*/
function fixture({ modulation = true, lists = true } = {}) {
const previous = {
document: globalThis.document,
matchMedia: globalThis.matchMedia,
};
const root = { dataset: { uiTheme: 'cyber', cyberSonar: 'on' } };
let cockpit = false;
const status = { textContent: '' };
const state = { cockpit: false, reducedMotion: false };
globalThis.document = {
documentElement: root,
body: { classList: { contains: () => cockpit } },
getElementById: () => ({ classList: { contains: () => true } }),
body: { classList: { contains: () => state.cockpit } },
getElementById: (id) =>
id === 'cyber-sonar-status'
? status
: { classList: { contains: () => true } },
};
const primitives = new Cesium.PrimitiveCollection();
const points = primitives.add(new Cesium.PointPrimitiveCollection());
const point = points.add({ color: new Cesium.Color(0.3, 0.7, 0.5, 0.8) });
const original = primitives.update;
const scene = {
primitives,
postUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
canvas: { clientWidth: 1000, clientHeight: 800 },
camera: {
frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY },
viewMatrix: Cesium.Matrix4.IDENTITY,
globalThis.matchMedia = () => ({ matches: state.reducedMotion });
const ticks = new Set();
const changes = new Set();
const sets = [];
const requests = [];
let drawing = null;
const effects = {
diagnostics: () => ({
style: null,
passes: drawing && lists ? ['screenModulation'] : [],
}),
on(event, cb) {
changes.add(cb);
return () => changes.delete(cb);
},
requestRender() {},
};
const viewer = { scene };
const dispose = createCyberSonarScene(viewer);
try {
for (const enabled of ['on', 'off', 'on']) {
root.dataset.cyberSonar = enabled;
for (const opacity of [35, 84, 100]) {
root.dataset.cyberSonarOpacity = String(opacity);
point.color = new Cesium.Color(0.6, 0.4, 0.2, 0.7);
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
assert.equal(point.color.alpha, 0.7);
assert.equal(point.color.red, 0.6);
}
}
const previousTimeout = globalThis.setTimeout;
const previousClear = globalThis.clearTimeout;
let timers = 0;
globalThis.setTimeout = () => {
timers++;
return 1;
if (modulation)
effects.screenModulation = (sector) => {
const was = effects.diagnostics().passes.length;
drawing = sector;
sets.push(sector);
if (effects.diagnostics().passes.length !== was)
for (const cb of [...changes]) cb(effects.diagnostics());
};
globalThis.clearTimeout = () => {};
try {
const gpu = getCyberSonarSceneDiagnostics(viewer).gpu;
gpu.commands = 6;
gpu.visibleCommands = 0;
scene.postRender.raiseEvent();
assert.equal(timers, 0, 'culled batches must not schedule a sonar draw');
gpu.visibleCommands = 1;
scene.postRender.raiseEvent();
assert.equal(timers, 1, 'a visible batch keeps the sweep moving');
root.dataset.cyberSonar = 'off';
scene.postRender.raiseEvent();
assert.equal(timers, 1, 'OFF does not schedule contact draws');
} finally {
globalThis.setTimeout = previousTimeout;
globalThis.clearTimeout = previousClear;
}
cockpit = true;
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
root.dataset.uiTheme = 'tactical';
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
const canvas = { clientWidth: 1000, clientHeight: 800 };
const viewer = {};
const unbind = bindRenderer(viewer, {
canvas,
effects,
frame: {
on(phase, cb) {
assert.equal(phase, 'preUpdate');
ticks.add(cb);
return () => ticks.delete(cb);
},
requestRender: (reason) => requests.push(reason),
},
});
return {
root,
status,
state,
sets,
requests,
canvas,
viewer,
ticks,
changes,
effects,
tick(rendering = false) {
for (const cb of [...ticks]) cb({ rendering });
},
restore() {
unbind();
globalThis.document = previous.document;
globalThis.matchMedia = previous.matchMedia;
},
};
}
test('a renderer without the capability leaves markers alone and says so', () => {
const f = fixture({ modulation: false });
try {
const dispose = createCyberSonarScene(f.viewer);
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
assert.match(f.status.textContent, /Native contacts remain visible/);
f.tick(true);
assert.equal(f.changes.size, 0);
dispose();
dispose();
assert.equal(primitives.update, original);
assert.equal(scene.postUpdate.numberOfListeners, 0);
assert.equal(scene.preRender.numberOfListeners, 0);
assert.equal(scene.postRender.numberOfListeners, 0);
assert.equal(root.dataset.cyberSonarGpu, undefined);
assert.equal(f.ticks.size, 0);
assert.equal(f.root.dataset.cyberSonarGpu, undefined);
} finally {
dispose();
primitives.destroy();
globalThis.document = previous;
f.restore();
}
});
for (const reducedMotion of [false, true]) {
test(`shader failure requests one parked restoration draw with ${reducedMotion ? 'reduced motion' : 'Sonar OFF'}`, () => {
const previousDocument = globalThis.document;
const previousMatchMedia = globalThis.matchMedia;
const previousTimeout = globalThis.setTimeout;
const previousClear = globalThis.clearTimeout;
const root = {
dataset: { uiTheme: 'cyber', cyberSonar: reducedMotion ? 'on' : 'off' },
};
const status = { textContent: '' };
globalThis.document = {
documentElement: root,
body: { classList: { contains: () => false } },
getElementById: (id) =>
id === 'cyber-sonar-status'
? status
: { classList: { contains: () => true } },
};
globalThis.matchMedia = () => ({ matches: reducedMotion });
let scheduled = 0;
globalThis.setTimeout = () => {
scheduled++;
return 1;
};
globalThis.clearTimeout = () => {};
// A model-shaped fixture exercises the actual scene walk without loading a
// glTF or allocating a WebGL context. Rendering remains the browser gate.
const nativeColor = new Cesium.Color(0.2, 0.4, 0.8, 1);
const model = Object.create(Cesium.Model.prototype, {
ready: { value: true },
show: { value: true },
color: { value: nativeColor.clone(), writable: true },
modelMatrix: { value: Cesium.Matrix4.IDENTITY },
});
const primitives = new Cesium.PrimitiveCollection({
destroyPrimitives: false,
});
primitives.add(model);
const points = new Cesium.PointPrimitiveCollection();
const nativeCommand = {
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
};
primitives.update = (frame) => frame.commandList.push(nativeCommand);
let requests = 0;
const scene = {
primitives,
postUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
canvas: { clientWidth: 1000, clientHeight: 800 },
drawingBufferWidth: 1000,
drawingBufferHeight: 800,
camera: {
frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY },
viewMatrix: Cesium.Matrix4.IDENTITY,
},
requestRender() {
requests++;
},
};
const viewer = { scene };
const dispose = createCyberSonarScene(viewer);
try {
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
assert.notDeepEqual(
model.color,
nativeColor,
'Cyber neutral treatment precedes shader compilation',
);
const frame = { commandList: [], passes: { render: true } };
primitives.update(frame);
assert.equal(getCyberSonarSceneDiagnostics(viewer).gpu.supported, false);
assert.equal(frame.commandList[0], nativeCommand);
scene.postRender.raiseEvent();
assert.equal(
scheduled,
0,
'inactive sweep has no timer to perform recovery',
);
scene.postUpdate.raiseEvent();
assert.equal(root.dataset.cyberSonarGpu, 'unsupported');
assert.match(status.textContent, /Native contacts remain visible/);
assert.equal(
requests,
1,
'support loss explicitly wakes the parked scene',
);
scene.preRender.raiseEvent();
assert.deepEqual(
model.color,
nativeColor,
'the requested draw restores native model color',
);
assert.equal(getCyberSonarSceneDiagnostics(viewer).contacts, 0);
scene.postRender.raiseEvent();
for (let i = 0; i < 3; i++) scene.postUpdate.raiseEvent();
assert.equal(
requests,
1,
'unsupported idle ticks do not create a render loop',
);
assert.equal(scheduled, 0);
dispose();
scene.postUpdate.raiseEvent();
assert.equal(requests, 1, 'disposed callbacks cannot wake the scene');
} finally {
dispose();
points.destroy();
primitives.destroy();
globalThis.document = previousDocument;
globalThis.matchMedia = previousMatchMedia;
globalThis.setTimeout = previousTimeout;
globalThis.clearTimeout = previousClear;
}
});
}
test('the HUD sweep keeps its clock while markers cannot be shaded', () => {
const f = fixture({ modulation: false });
const animation = {
animationName: 'cyber-sonar-sweep',
playState: 'running',
startTime: 500,
effect: { updateTiming() {} },
};
f.root.querySelector = (selector) =>
selector === '.hud-sonar'
? { isConnected: true, getAnimations: () => [animation] }
: null;
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick(false);
assert.equal(animation.startTime, 0);
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
dispose();
} finally {
f.restore();
}
});
test('the sweep sets its sector on drawing ticks and at the cadence, and changes at once', () => {
const f = fixture();
const now = performance.now;
let clock = 1000;
performance.now = () => clock;
try {
const dispose = createCyberSonarScene(f.viewer);
assert.equal(f.root.dataset.cyberSonarGpu, 'supported');
assert.equal(f.status.textContent, '');
f.tick();
assert.equal(f.sets.length, 1, 'the theme sets a sector');
assert.deepEqual(f.sets[0], cyberSonarSector(1000, 800, 1000));
clock += 10;
f.tick(false);
assert.equal(f.sets.length, 1, 'an idle tick before the cadence sets none');
f.tick(true);
assert.equal(f.sets.length, 2, 'a tick that draws moves the angle');
assert.deepEqual(f.sets[1], cyberSonarSector(1000, 800, 1010));
clock += CYBER_SONAR_RENDER_INTERVAL_MS;
f.tick(false);
assert.equal(f.sets.length, 3, 'the cadence moves it on an idle tick');
f.canvas.clientWidth = 600;
f.tick(false);
assert.equal(f.sets.length, 4, 'a resize sets it at once');
assert.deepEqual(f.sets[3].center, { x: 300, y: 400 });
f.root.dataset.cyberSonar = 'off';
f.tick(false);
assert.equal(f.sets[4].radius, 0, 'Sonar OFF rests every contact');
clock += 1000;
f.tick(true);
f.tick(false);
assert.equal(f.sets.length, 5, 'at rest only changes set it');
f.root.dataset.cyberSonarOpacity = '50';
f.tick(false);
assert.equal(f.sets.length, 6);
assert.equal(f.sets[5].floor, 0.5 + 0.5 * 0.46);
f.state.cockpit = true;
f.tick(false);
assert.equal(f.sets[6], null, 'out of the map theme it clears');
f.tick(true);
assert.equal(f.sets.length, 7, 'cleared once');
f.state.cockpit = false;
f.root.dataset.cyberSonar = 'on';
f.state.reducedMotion = true;
f.tick(false);
assert.equal(f.sets[7].radius, 0, 'reduced motion rests the sweep');
f.state.reducedMotion = false;
f.root.dataset.uiTheme = 'tactical';
f.tick(false);
assert.equal(f.sets[8], null, 'another HUD style clears it');
f.tick(true);
assert.equal(f.sets.length, 9);
f.root.dataset.uiTheme = 'cyber';
f.tick(false);
assert.ok(f.sets[9]?.radius > 0, 'back in Cyber it sweeps at once');
assert.deepEqual(f.requests, [], 'the scene itself never asks for frames');
dispose();
assert.equal(f.sets[10], null, 'disposal clears it');
assert.equal(f.ticks.size, 0);
assert.equal(f.changes.size, 0);
assert.equal(f.root.dataset.cyberSonarGpu, undefined);
dispose();
assert.equal(f.sets.length, 11);
} finally {
performance.now = now;
f.restore();
}
});
test('a sector the renderer does not list is unsupported: cleared, and the sweep stops', () => {
const f = fixture({ lists: false });
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick(true);
assert.equal(f.sets.length, 2);
assert.equal(f.sets[1], null, 'cleared again');
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
assert.match(f.status.textContent, /Native contacts remain visible/);
f.tick(true);
assert.equal(f.sets.length, 2, 'never set again');
dispose();
assert.equal(f.sets.length, 2);
} finally {
f.restore();
}
});
test('a pass the renderer stops drawing on its own stops the sweep', () => {
const f = fixture();
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick(true);
assert.equal(f.sets.length, 1);
for (const cb of [...f.changes]) cb({ style: null, passes: [] });
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
assert.equal(f.sets.at(-1), null);
const count = f.sets.length;
f.tick(true);
assert.equal(f.sets.length, count);
dispose();
} finally {
f.restore();
}
});
test('layer visibility changes ask for a frame', () => {
const f = fixture();
let listener = null;
const manager = {
subscribe(cb) {
listener = cb;
return () => (listener = null);
},
};
try {
const dispose = createCyberSonarScene(f.viewer, manager);
listener({ type: 'visibility' });
listener({ type: 'data' });
assert.deepEqual(f.requests, ['cyber-sonar']);
dispose();
assert.equal(listener, null);
} finally {
f.restore();
}
});
+5 -1
View File
@@ -64,7 +64,11 @@ export function normalizeAdsbLolAircraftState(aircraft, nowSeconds) {
const geometricFeet = finiteNumber(aircraft?.alt_geom);
const groundSpeedKnots = finiteNumber(aircraft?.gs);
const verticalRateFpm = readAdsbVerticalRateFpm(aircraft);
const track = finiteNumber(aircraft?.track);
// A parked or slow aircraft reports no ground track, but often its true
// heading (surface messages): the way its nose points, which is what an
// aircraft standing still is drawn by. Magnetic heading is not true north.
const track =
finiteNumber(aircraft?.track) ?? finiteNumber(aircraft?.true_heading);
return [
hex,
+12
View File
@@ -49,3 +49,15 @@ test('keeps grounded fallback contacts and rejects rows without positions', () =
assert.equal(normalized.states[0][7], null);
assert.equal(normalized.states[0][8], true);
});
test('an aircraft with no track takes its true heading, never its magnetic one', () => {
const at = (extra) =>
normalizeAdsbLolAircraftState(
{ hex: 'abc123', lat: 37.7, lon: -122.2, alt_baro: 'ground', ...extra },
1000,
)[10];
assert.equal(at({ track: 56.25, true_heading: 40 }), 56.25, 'track first');
assert.equal(at({ true_heading: 244.69 }), 244.69, 'true heading');
assert.equal(at({ mag_heading: 278.44 }), null, 'not magnetic');
assert.equal(at({}), null, 'none');
});
-51
View File
@@ -467,54 +467,3 @@ export const CLASS_SCALE_2D = {
bizjet: 0.72,
uav: 0.75,
};
/** 3D model scale multipliers — clamped [0.75, 1.45] while every class shares
* the single airplane.glb (a jet mesh at C172 scale reads wrong). Widen when
* real per-class models land in CLASS_MODEL_URL. */
export const CLASS_SCALE_3D = {
light: 0.75,
glider: 0.75,
turboprop: 0.85,
airliner: 1.0,
widebody: 1.3,
quadjet: 1.45,
helicopter: 0.8,
fastjet: 0.8,
bizjet: 0.8,
uav: 0.8,
};
/** Per-class glTF — all the shared airplane today; drop real assets in here.
* NOTE for future models: each asset may need its own heading offset (the
* shared GLB uses MODEL_HEADING_OFFSET_DEG = 180 in both layers). */
export const CLASS_MODEL_URL = {
light: '/models/airplane.glb',
glider: '/models/airplane.glb',
turboprop: '/models/airplane.glb',
airliner: '/models/airplane.glb',
widebody: '/models/airplane.glb',
quadjet: '/models/airplane.glb',
helicopter: '/models/airplane.glb',
fastjet: '/models/airplane.glb',
bizjet: '/models/airplane.glb',
uav: '/models/airplane.glb',
};
/** Real per-class GLBs (2026-08-15 Hangar fleet, owner picks; CC-BY 4.0 —
* provenance in public/models/README.md). Every asset is vertex-baked to the
* airplane.glb convention: Y-up, X = length, Z = span, nose −X (so the layers'
* MODEL_HEADING_OFFSET_DEG = 180 applies unchanged), origin at bbox centre,
* REAL-WORLD METERS (render at scale 1 — no MODEL_SCALE, no CLASS_SCALE_3D).
* bellyM = origin→lowest-vertex distance (grounded-model lift, replaces the
* airplane.glb MODEL_BELLY_OFFSET_NATIVE formula); radiusM = bounding-sphere
* radius in meters (pixel-size math). Values measured from the shipped GLBs —
* pinned by modelScale.test.mjs. Classes NOT listed (airliner, quadjet,
* glider, fastjet) still render the shared airplane.glb via CLASS_MODEL_URL. */
export const CLASS_MODEL_REAL = {
helicopter: { url: '/models/bell206.glb', bellyM: 1.66, radiusM: 8.24 },
light: { url: '/models/c172.glb', bellyM: 1.36, radiusM: 7.0 },
bizjet: { url: '/models/citation2.glb', bellyM: 2.86, radiusM: 11.24 },
uav: { url: '/models/mq9.glb', bellyM: 2.02, radiusM: 12.0 },
widebody: { url: '/models/b789.glb', bellyM: 7.81, radiusM: 44.08 },
turboprop: { url: '/models/atr72.glb', bellyM: 3.81, radiusM: 19.49 },
};
+2 -13
View File
@@ -1,7 +1,7 @@
// src/data/aircraftClass.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { classifyAircraft, CLASS_SCALE_2D, CLASS_SCALE_3D, CLASS_MODEL_URL, CLASS_MODEL_REAL } from './aircraftClass.js';
import { classifyAircraft, CLASS_SCALE_2D } from './aircraftClass.js';
test('type-code classification (military layer path)', () => {
assert.equal(classifyAircraft({ typeCode: 'F16' }), 'fastjet');
@@ -48,19 +48,8 @@ test('typeCode outranks category; unknown → airliner', () => {
assert.equal(classifyAircraft({ typeCode: null, category: 0 }), 'airliner');
});
test('scale/url tables cover every class', () => {
test('the icon scale table covers every class', () => {
for (const kind of ['light','glider','turboprop','airliner','widebody','quadjet','helicopter','fastjet','bizjet','uav']) {
assert.ok(Number.isFinite(CLASS_SCALE_2D[kind]), kind);
assert.ok(CLASS_SCALE_3D[kind] >= 0.75 && CLASS_SCALE_3D[kind] <= 1.45, kind);
assert.ok(typeof CLASS_MODEL_URL[kind] === 'string', kind);
}
});
test('CLASS_MODEL_REAL entries carry the fields the layers consume', () => {
for (const [kind, spec] of Object.entries(CLASS_MODEL_REAL)) {
assert.ok(spec.url.startsWith('/models/') && spec.url.endsWith('.glb'), kind);
assert.ok(spec.radiusM > 0 && spec.bellyM > 0, kind);
// every real-model class must also exist in the classifier tables
assert.ok(Number.isFinite(CLASS_SCALE_2D[kind]), kind);
}
});
+64 -20
View File
@@ -1,8 +1,19 @@
import * as Cesium from 'cesium';
import { TRACKED_ICON_COLOR } from '../layers/military/policy.js';
import { TRACKED_CYAN } from '../layers/flights/policy.js';
import { createRendering as civilRendering } from '../layers/flights/rendering.js';
import { createRendering as militaryRendering } from '../layers/military/rendering.js';
import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js';
import { createIcons as createMilitaryIcons } from '../layers/military/icons.js';
import { createContactIcons } from './aircraftIconLayer.js';
import {
aircraftMotionRegime,
createMotionRegime,
fixEpochMs,
fixPosition,
copyPosition,
historyFix,
julianAt,
} from './aircraftMotionRegime.js';
import { aircraftEmergency } from './aircraftEmergency.js';
// Source-to-voice provenance, status retention/clearing, contact-time contracts,
// and civil/military billboard, Cockpit and model tint regressions.
@@ -138,6 +149,7 @@ test('changed status without contact time retains general contact, including voi
const runner = createGevActionRunner({
viewer: {
clock: { onTick: { addEventListener: () => () => {} } },
canvas: { addEventListener() {}, removeEventListener() {} },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: {
moveEnd: { addEventListener() {} },
@@ -444,7 +456,7 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
const red = rendering._fleetBillboardColor('civil', {
emergency: aircraftEmergency({ squawk: '7700' }),
});
assert.ok(red.red > 0.9 && red.green < 0.5);
assert.ok(red[0] > 0.9 && red[1] < 0.5);
flightState.records.data.set('civil', {
emergency: aircraftEmergency({ squawk: '7700' }),
});
@@ -454,26 +466,25 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
flightState._trackedIcao = 'civil';
assert.equal(
rendering._modelColor('civil'),
factory === civilRendering ? Cesium.Color.CYAN : TRACKED_ICON_COLOR,
factory === civilRendering ? TRACKED_CYAN : TRACKED_ICON_COLOR,
);
flightState._trackedIcao = null;
flightState.records.data.set('civil', { emergency: null });
assert.equal(rendering._modelColor('civil'), normal);
// An ordinary model draws its mesh's own colours, whatever the billboard's.
assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]);
}
});
test('GERMAN: an existing untracked military billboard repaints each poll without alpha loss', () => {
test('GERMAN: an existing untracked military icon repaints each poll without losing its fade', () => {
const { flightState, rendering } = renderHarness(militaryRendering);
const bb = {
color: rendering._fleetBillboardColor('abc123').withAlpha(0.65),
};
Object.assign(flightState, {
_billboards: new Map([['abc123', bb]]),
_icons: createContactIcons(),
_models: new Map(),
_positionHistory: new Map(),
_cullPositions: new Map(),
_displayCourse: new Map(),
_groundSnap: { forget() {} },
_cockpitContactMode: false,
_cockpitNearContacts: new Set(),
});
const records = new MilitaryFlightRecords({
geoidHeight: () => 0,
@@ -481,18 +492,51 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou
floorAltitudeM: (value) => value,
});
flightState.records = records;
const parts = {
rendering: {
...rendering,
_iconKind: () => 'jet',
_syncModelToClass() {},
},
motion: {
_motionRegime: (history, info, renderTime) =>
aircraftMotionRegime(
history,
info,
renderTime,
{ speed: 'speedMps', track: 'track' },
createMotionRegime(),
),
_displayTimeAt: julianAt,
_fixEpochMs: fixEpochMs,
_fixPosition: fixPosition,
_copyPosition: copyPosition,
_historyFix: historyFix,
_refloorStaleGroundedContacts() {},
_sampleMeshFloor() {},
},
};
const icons = createMilitaryIcons({
flightState,
services: { focus: { focusPassIsNeeded: () => false } },
parts,
});
const row = 'abc123';
flightState._icons.put({
id: row,
pos: { x: 0, y: 0, z: 0 },
meta: { layer: 'military', id: row },
});
// The focus fade the fleet tick composes lives in its own field.
flightState._icons.setFocus(row, 0.65);
const apply = createMilitarySnapshotRenderer({
flightState,
records,
groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null },
meshFloor: { sampleMeshFloorCells() {} },
groundFloor: { warmGroundFloor() {} },
militaryRegistry: { registerMilitaryIcaos() {} },
rendering: {
...rendering,
_syncModelToClass() {},
_applyFleetBillboardPresentation() {},
},
motion: {},
rendering: parts.rendering,
motion: parts.motion,
icons,
tracking: {},
queries: {},
});
@@ -518,7 +562,7 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou
{ observedAtMs: NOW_MS },
);
apply(snapshot, {});
assert.equal(bb.color.green < 0.5, red);
assert.equal(bb.color.alpha, 0.65);
assert.equal(flightState._icons.item(row).color[1] < 0.5, red);
assert.ok(Math.abs(flightState._icons.focus(row) - 0.65) < 1e-6);
}
});
File diff suppressed because it is too large. Load diff
+201
View File
@@ -0,0 +1,201 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
COAST_FLOOR_LOOKAHEAD_MS,
createAircraftIcons,
createContactIcons,
floorCoastArc,
} from './aircraftIconLayer.js';
import { COAST_FLOOR_LIFT_M } from './motionModel.js';
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { createDisplayDelay } from './displayDelay.js';
const WORLD_MS = Date.UTC(2026, 10, 1, 12, 0);
test('following the world clock, contacts draw at the world’s time on the scene clock', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS + 86_400_000 });
const viewer = {};
const { draw } = bindFakeDraw(viewer);
let following = false;
const state = {
_viewer: viewer,
now: () => (following ? WORLD_MS : Date.now()),
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {},
layerId: 'flights',
renderDelaySec: 30,
followsClock: () => following,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
// Live: a poll interval behind real time, on the delayed live clock.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
assert.equal(icons._displayMs(), Date.now() - 30_000);
following = true;
assert.equal(icons._displayMs(), WORLD_MS, 'the world’s time, no delay');
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
icons._disposeIcons();
});
test('as the display delay moves, the renderer’s live clock and the layer’s display time move with it; the world clock ignores it', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const viewer = {};
const { draw } = bindFakeDraw(viewer);
let following = false;
const state = { _viewer: viewer, now: () => Date.now() };
const delay = createDisplayDelay({ floorMs: 30_000, pollMs: 30_000 });
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {},
layerId: 'flights',
displayDelay: delay,
followsClock: () => following,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
// Reports 90 s old every 30 s: the delay heads for about two minutes.
for (let i = 0; i < 20; i++)
delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000);
delay.settle(WORLD_MS);
t.mock.timers.setTime(WORLD_MS + 10_000);
icons._syncMotionClock();
// 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 });
assert.equal(icons._displayMs(), Date.now() - 32_000);
// Following the world clock: no delay, and it is not moved on meanwhile.
following = true;
t.mock.timers.setTime(WORLD_MS + 20_000);
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
assert.equal(icons._displayMs(), Date.now());
assert.equal(delay.currentMs, 32_000);
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 });
icons._disposeIcons();
});
test('a coasting icon is kept above rising ground, as the CPU coast is', () => {
const T0 = WORLD_MS;
let now = T0;
const cosLat = Math.cos((30 * Math.PI) / 180);
const metresEast = (lonDeg) => lonDeg * 111_320 * cosLat;
// A slope rising east from 100 m out, half a metre per metre.
const ground = (_lat, lon) => Math.max(0, (metresEast(lon) - 100) * 0.5);
const fix = { epochMs: T0, position: fromDegrees(0, 30, 100) };
const state = {
now: () => now,
_icons: createContactIcons(),
_positionHistory: new Map([['c', [fix]]]),
records: { data: new Map([['c', {}]]) },
};
const icons = createAircraftIcons({
state,
services: {
focus: { focusPassIsNeeded: () => false },
groundFloor: { cachedGroundFloor: ground },
},
parts: {
motion: {
_displayTimeAt: (ms) => ms,
_fixEpochMs: (f) => f.epochMs,
// Coasting east past its only fix at 100 m/s, for five minutes.
_motionRegime: () => ({
kind: 'fix',
fix,
speed: 100,
heading: 90,
turnRateDps: 0,
minDt: -60,
maxDt: 300,
}),
},
},
layerId: 'flights',
renderDelaySec: 30,
followsClock: () => true,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
state._icons.put(
{
id: 'c',
pos: fix.position,
motion: { kind: 'hold', courseDeg: 90 },
course: 90,
size: [20, 20],
},
{ expiresAt: -Infinity },
);
icons._planIcon('c');
// The fleet pass, every 80 ms for 12 s: the icon never sinks into the
// slope, and over open ground it coasts level.
let lowest = Infinity;
for (now = T0; now <= T0 + 12_000; now += 80) {
icons._replanExpired(now);
const p = icons._iconPosition('c');
const carto = toCartographicRadians(p);
const floor = ground(0, (carto.lon * 180) / Math.PI) + COAST_FLOOR_LIFT_M;
lowest = Math.min(lowest, carto.height - floor);
if (now - T0 <= 2_000)
assert.ok(Math.abs(carto.height - 100) < 0.1, 'level over open ground');
assert.ok(Math.abs(icons._iconCourse('c') - 90) < 1e-6, 'nose east');
}
assert.ok(lowest > -0.05, `at most 5 cm under the floor (${lowest} m)`);
// 1.2 km east, the slope is at 550 m: it rode up the slope.
now = T0 + 12_000;
icons._replanExpired(now);
const end = toCartographicRadians(icons._iconPosition('c'));
const east = metresEast((end.lon * 180) / Math.PI);
assert.ok(Math.abs(east - 1_200) < 5, `1.2 km east (${east} m)`);
assert.ok(end.height > 550, `on the slope (${end.height} m)`);
});
test('a coast over known ground that never rises is planned once', () => {
const fix = { position: fromDegrees(0, 30, 100) };
const arc = {
kind: 'arc',
fix: fix.position,
t0: 0,
minDtS: -60,
maxDtS: 5,
speedMps: 100,
trackDeg: 90,
turnRateDps: 0,
};
assert.deepEqual(
floorCoastArc(arc, 0, () => 0),
{ expiresAt: Infinity },
);
assert.deepEqual(
floorCoastArc(arc, 0, () => null),
{ expiresAt: COAST_FLOOR_LOOKAHEAD_MS },
'unknown ground is read again',
);
assert.equal(
floorCoastArc({ ...arc, fix: fromDegrees(0, 30, 10_000) }, 0, () => 0),
null,
'a cruise above any terrain never reads it',
);
// Stopped at the end of its coast, under ground that rose since.
const held = floorCoastArc(arc, 6_000, () => 200);
assert.equal(held.motion.kind, 'hold');
assert.ok(
Math.abs(toCartographicRadians(held.pos).height - 201.5) < 1e-6,
'held on the ground where the coast stopped',
);
});
+4 -2
View File
@@ -160,8 +160,8 @@ const BODIES = {
L -3,31 L -8,34 L -8,30 L -6,16
L -27,26 L -27,20 L -5,-8
C -4.6,-16 -4,-24 -3.5,-30 Z" fill="white" ${STROKE}/>`,
// 2026-08-15 Hangar additions: two NEW classes shipped with the real-model
// fleet (CLASS_MODEL_REAL). Same contract as the set above: 96×96 nose-up,
// 2026-08-15 additions: two NEW classes (bizjet, uav). Same contract as
// the set above: 96×96 nose-up,
// white fill, hairline stroke, tint-safe.
// Business jet — slender fuselage, modest swept wing, aft engines, T-tail.
bizjet: `
@@ -252,6 +252,8 @@ const _b64 = (s) =>
* NEAR the display size lets the browser's SVG AA do the work: crisp AND
* smooth. 64 covers the 40–58 px fleet band with ≤1.6× minification. */
const FLEET_RASTER_PX = 64;
/** Raster size of the default fleet glyph. */
export const FLEET_ICON_PX = FLEET_RASTER_PX;
/** Tracked raster: the tracked billboard is the one SUSTAINED large 2D glyph
* (close-zoom fleet flybys hand off to 3D models). Keep the 192 px texture so
* it stays crisp at its biggest on-screen sizes. */
File diff suppressed because it is too large. Load diff
+391
View File
@@ -0,0 +1,391 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAircraftModels } from './aircraftModelLayer.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { fromDegrees } from '../geo/ellipsoid.js';
const POLICY = {
MODEL_ALT_CEIL_M: 800_000,
MODEL_MAX: 40,
MODEL_MAX_ALL: 350,
COCKPIT_MODEL_MAX: 60,
MODEL_PROX_ADD_M: 150_000,
MODEL_PROX_KEEP_M: 185_000,
MODEL_ALL_ADD_M: 400_000,
MODEL_ALL_KEEP_M: 450_000,
MODEL_MIN_PX: 24,
TRACKED_MODEL_MIN_PX: 48,
TRACKED_MODEL_MAX_PX: 600,
MODEL_HEADING_OFFSET_DEG: 0,
FLEET_DR_INTERVAL_MS: 80,
TRACKED_MODEL_MAX_LOAD_FAILS: 3,
TRACKED_MODEL_RETRY_BACKOFF_MS: 1500,
};
const SPEC = {
url: 'plane.glb',
scale: 1,
bellyM: 3,
nativeRadiusM: 20,
blendAmount: 0.9,
};
/**
* A fleet of airborne contacts at `positions` (icao → ECEF), drawn by a
* models layer over a fake draw port whose fleet set can be told to fail a
* write. The eye sits above them at 30 km.
*/
function fleetFixture(positions) {
const base = fakeDrawPort();
const removes = [];
let failNextUpsert = false;
const draw = {
...base,
models(spec) {
const set = base.models(spec);
return {
...set,
get show() {
return set.show;
},
set show(value) {
set.show = value;
},
id: set.id,
upsert(items) {
if (failNextUpsert && spec.id.includes('-models:')) {
failNextUpsert = false;
throw new Error('simulated write failure');
}
return set.upsert(items);
},
remove(ids) {
removes.push([...ids]);
return set.remove(ids);
},
};
},
};
const eye = fromDegrees(-97.71, 30.21, 30_000);
const viewer = {};
bindRenderer(viewer, {
draw,
camera: {
pose: () => ({
position: eye,
direction: { x: 0, y: 0, z: -1 },
up: { x: 0, y: 1, z: 0 },
right: { x: 1, y: 0, z: 0 },
fovy: Math.PI / 3,
aspectRatio: 1,
height: 30_000,
}),
},
});
const shown = new Map([...positions.keys()].map((id) => [id, true]));
let alphaOf = 1;
let focusOf = 1;
const unseenIds = new Set();
const icons = {
show: true,
setId: 'flights-icons:1',
ids: () => [...positions.keys()],
has: (id) => positions.has(id),
position: (id) => positions.get(id),
course: () => 90,
alpha: () => alphaOf,
focus: () => focusOf,
setShown: (id, value) => shown.set(id, value),
unseen: (id) => unseenIds.has(id),
flush() {},
};
const state = {
_viewer: viewer,
_icons: icons,
_models: new Map(),
_modelSets: null,
_trackedIcao: null,
_trackedModel: null,
_models3dEnabled: true,
_models3dMode: 'proximity',
_cockpitContactMode: false,
_irBoost: false,
_lastFleetTickMs: 0,
_lastModelCapWarnMs: 0,
records: {
data: new Map(
[...positions.keys()].map((id) => [id, { klass: 'airliner' }]),
),
},
};
let now = 1_000_000;
let iconRecedeSyncs = 0;
const parts = {
icons: {
_displayMs: () => now,
_syncImageSwitch() {},
_replanExpired() {},
_focusIcons() {},
_occluder: () => null,
_aboveHorizon: () => true,
_syncRecede() {
iconRecedeSyncs += 1;
},
},
motion: { _displayTimeAt: () => null },
tracking: {
_refreshCockpitNearContacts() {},
_trackedModelRegimeActive: () => false,
},
};
const models = createAircraftModels({
state,
services: {
aircraftPresentation: { isTr3b: () => false },
camera: { trackedModelScaleForPixelCap: ({ baseScale }) => baseScale },
focus: { focusNowMs: () => now, getFocusTarget: () => null },
},
parts,
resolveAsset: (url) => url,
logLabel: 'Test',
setPrefix: 'flights',
policy: POLICY,
modelSpec: () => SPEC,
modelColor: () => ({ red: 1, green: 1, blue: 1, alpha: 1 }),
});
models._createModelSets(viewer);
const fleetId = models._modelSetIds()[0];
return {
models,
state,
draw: base,
fleet: () => base.set(fleetId),
fleetId,
removes,
shown,
failNextUpsert: () => (failNextUpsert = true),
/** How often the icons were told to recede by the tuning as it is now. */
iconRecedeSyncs: () => iconRecedeSyncs,
/** Mark a contact as not there yet at the time drawn, or there again. */
setUnseen(id, value) {
if (value) unseenIds.add(id);
else unseenIds.delete(id);
},
/** The icons' alpha and focus the fleet models take. */
look(alpha, focus) {
alphaOf = alpha;
focusOf = focus;
},
/** One fleet tick, past the tick interval. */
tick() {
now += 1000;
models._fleetTick();
},
};
}
const near = (k) => fromDegrees(-97.71 + k * 0.01, 30.21, 10_000);
const far = (k) => fromDegrees(-90 + k * 0.01, 30.21, 10_000);
test('the fleet tick hands contacts to ready models and back without a gap', () => {
const positions = new Map([
['a1', near(1)],
['a2', near(2)],
]);
const f = fleetFixture(positions);
f.tick();
assert.deepEqual([...f.fleet().items.keys()].sort(), ['a1', 'a2']);
assert.equal(
f.shown.get('a1'),
true,
'icons carry contacts until models load',
);
f.draw.ready(f.fleetId, 'a1');
f.tick();
assert.equal(f.shown.get('a1'), false, 'a ready, placed model takes over');
assert.equal(f.fleet().items.get('a1').show, true);
assert.equal(
f.shown.get('a2'),
true,
'a model still loading leaves its icon',
);
});
test('contacts leaving the model band are released in one write', () => {
const positions = new Map([
['a1', near(1)],
['a2', near(2)],
['a3', near(3)],
]);
const f = fleetFixture(positions);
f.tick();
for (const id of ['a1', 'a2', 'a3']) f.draw.ready(f.fleetId, id);
f.tick();
positions.set('a2', far(2));
positions.set('a3', far(3));
f.removes.length = 0;
f.tick();
assert.deepEqual(
f.removes,
[['a2', 'a3']],
'one remove for every evicted model',
);
assert.deepEqual([...f.fleet().items.keys()], ['a1']);
assert.equal(
f.shown.get('a2'),
true,
'a released model hands back to its icon',
);
assert.equal(f.shown.get('a3'), true);
});
test('a failed fleet write leaves the icons in charge and is sent again', () => {
const positions = new Map([['a1', near(1)]]);
const f = fleetFixture(positions);
f.tick();
f.draw.ready(f.fleetId, 'a1');
const realWarn = console.warn;
console.warn = () => {};
try {
f.failNextUpsert();
f.tick();
} finally {
console.warn = realWarn;
}
assert.equal(f.shown.get('a1'), true, 'the contact keeps its icon');
assert.equal(
f.fleet().items.get('a1').show,
false,
'the set still has the hidden model',
);
assert.equal(f.models._modelOwnsVisual('a1'), false);
f.tick();
assert.equal(
f.fleet().items.get('a1').show,
true,
'the next tick sends it again',
);
assert.equal(f.shown.get('a1'), false);
});
test('a fleet model whose load failed is loaded again after a wait, not before', () => {
const positions = new Map([['a1', near(1)]]);
const f = fleetFixture(positions);
const realNow = Date.now;
let clock = 50_000_000;
Date.now = () => clock;
try {
f.tick();
const writes = f.fleet().writes;
clock += 60_000;
f.tick();
assert.equal(
f.fleet().writes,
writes,
'a model still loading is not rewritten, however long it takes',
);
f.draw.loadFailed(f.fleetId, 'a1');
f.removes.length = 0;
clock += 4_999;
f.tick();
assert.deepEqual(f.removes, [], 'not before the wait');
assert.equal(f.shown.get('a1'), true, 'the icon carries the contact');
clock += 1;
f.tick();
assert.deepEqual(f.removes, [['a1']], 'removed once the wait is over');
assert.ok(f.fleet().items.has('a1'), 'and added again in the same tick');
assert.equal(f.state._models.get('a1').failedAt, 0);
assert.equal(f.state._models.get('a1').ready, false, 'a fresh load');
f.removes.length = 0;
clock += 60_000;
f.tick();
assert.deepEqual(f.removes, [], 'tried again only after another failure');
// A renderer's own retry that loads before the layer's: nothing is due.
f.draw.loadFailed(f.fleetId, 'a1');
f.draw.ready(f.fleetId, 'a1');
clock += 60_000;
f.tick();
assert.deepEqual(f.removes, [], 'a model that loaded is not tried again');
assert.equal(
f.shown.get('a1'),
false,
'the model takes over once it loads',
);
} finally {
Date.now = realNow;
}
});
test('fleet model alpha is worked out once a fleet tick from the camera then, as base × max(floor, focus × haze); the IR boost draws full strength', async () => {
const {
aircraftTreatmentAlpha,
setAircraftRecessionParams,
resetAircraftRecessionParams,
} = await import('./aircraftRecession.js');
const position = near(1);
const f = fleetFixture(new Map([['a1', position]]));
assert.equal(f.fleet().spec.recede ?? null, null, 'the set does not recede');
const eye = fromDegrees(-97.71, 30.21, 30_000);
const expected = (focusFactor) =>
aircraftTreatmentAlpha({
baseAlpha: 0.8,
focusFactor,
cameraDistanceM: Math.hypot(
eye.x - position.x,
eye.y - position.y,
eye.z - position.z,
),
cameraHeightM: 30_000,
});
try {
// Recede from the eye on, so the haze is not 1 here.
setAircraftRecessionParams({ startLimbRatio: 0, alphaFloor: 0.05 });
f.look(0.8, 0.5);
f.tick();
f.draw.ready(f.fleetId, 'a1');
f.tick();
const item = f.fleet().items.get('a1');
assert.equal(item.tint[3], expected(0.5), 'the tint carries it all');
assert.equal(item.focus ?? 1, 1, 'with no focus for the set to compose');
// A frame inside the fleet interval writes nothing, whatever changed.
f.look(0.8, 0.25);
f.models._fleetTick();
assert.equal(f.fleet().items.get('a1').tint[3], item.tint[3]);
f.tick();
assert.equal(
f.fleet().items.get('a1').tint[3],
expected(0.25),
'the next tick takes it',
);
} finally {
resetAircraftRecessionParams();
}
f.state._irBoost = true;
f.models._reloadModelsForIrBoost();
f.tick();
assert.equal(f.fleet().items.get('a1').tint[3], 1, 'boosted: full strength');
});
test('a tuning change reaches the icons on the next frame, icons shown or not', async () => {
const f = fleetFixture(new Map([['a1', near(1)]]));
f.state._icons.show = false;
const before = f.iconRecedeSyncs();
f.models._fleetTick();
assert.ok(f.iconRecedeSyncs() > before, 'the icons are told');
});
test('a contact not there yet at the time drawn has its fleet model hidden, as one beyond the horizon', () => {
const f = fleetFixture(new Map([['a1', near(1)]]));
f.tick();
f.draw.ready(f.fleetId, 'a1');
f.tick();
assert.equal(f.fleet().items.get('a1').show, true, 'drawn while there');
f.setUnseen('a1', true);
f.tick();
assert.equal(f.fleet().items.get('a1').show, false, 'hidden while unseen');
f.setUnseen('a1', false);
f.tick();
f.tick();
assert.equal(f.fleet().items.get('a1').show, true, 'drawn again');
});
+19 -5
View File
@@ -6,12 +6,26 @@
* the model and reads the result back from the GPU (`readPixels`) to light it,
* when the model is first placed and again when it moves more than 1 km, when
* the scene's atmosphere settings change, or every scene hour under sunlight
* lighting. Aircraft models take 94% of their surface from the class colour
* (`colorBlendAmount`), so that lighting contributes little; without it they
* are lit from Cesium's default spherical harmonics. Measured 2026-10-24
* (Intel Arc, Google 3D, ~150 models in the scene): GPU per frame at rest
* 14.3-14.8 -> 12.1-12.5 ms.
* lighting. Without it they are lit from Cesium's default spherical
* harmonics. Measured 2026-10-24 (Intel Arc, Google 3D, ~150 models in the
* scene): GPU per frame at rest 14.3-14.8 -> 12.1-12.5 ms.
*/
export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({
enabled: false,
});
const HIGHLIGHT = Object.freeze({ mode: 'highlight' });
const FLAT = Object.freeze({ mode: 'mix', amount: 1 });
/**
* How an aircraft model's colour meets its mesh, as a draw item's
* `colorBlend`. `highlight` multiplies, so white draws the mesh's own
* colours as built, and the tracked or emergency colour tints the mesh
* without hiding its paint. The IR boost draws the model flat white instead
* (`mix` at 1, unlit).
* @param {boolean} irBoost
* @returns {{mode: 'highlight'|'mix', amount?: number}}
*/
export function aircraftModelBlend(irBoost) {
return irBoost ? FLAT : HIGHLIGHT;
}
+22 -23
View File
@@ -5,10 +5,8 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
/**
* Every aircraft model drawn in the scene skips Cesium's dynamic environment
* map (a sky render and GPU readback per model). The preload calls only warm
* the glTF cache and are never added to the scene, so they are left out:
* drawn models are the calls that set a minimum pixel size.
* Every aircraft model drawn in the scene skips the renderer's dynamic
* environment map (a sky render and GPU readback per model).
*/
const SOURCES = [
{
@@ -19,13 +17,6 @@ const SOURCES = [
name: 'militaryFlights',
source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)),
},
{
name: 'localAdsb',
source: readFileSync(
new URL('../layers/localAdsb/models.js', import.meta.url),
'utf8',
),
},
];
test('the shared option turns the dynamic environment map off', () => {
@@ -35,17 +26,25 @@ test('the shared option turns the dynamic environment map off', () => {
for (const { name, source } of SOURCES) {
test(`${name}: every drawn aircraft model skips the dynamic environment map`, () => {
const calls = [
...source.matchAll(/(?:fromGltfAsync|loadModel)\(\{([\s\S]*?)\}\)/g),
]
.map((match) => match[1])
.filter((options) => /\bminimumPixelSize:/.test(options));
assert.ok(calls.length >= 1, `expected drawn model calls in ${name}`);
for (const [index, options] of calls.entries())
assert.match(
options,
/\benvironmentMapOptions:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\b/,
`${name} model call ${index + 1} must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`,
);
// Its models are draw-port items; every item it builds (fleet and
// tracked) carries the shared option.
assert.doesNotMatch(source, /fromGltfAsync|loadModel\(/);
const items = [...source.matchAll(/\burl: record\.url,/g)];
assert.ok(items.length >= 1, `expected model items in ${name}`);
const flags = [
...source.matchAll(/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/g),
];
assert.equal(flags.length, items.length, `${name} model items must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`);
});
}
test('localAdsb: its draw-port models skip the dynamic environment map', () => {
const source = readFileSync(
new URL('../layers/localAdsb/models.js', import.meta.url),
'utf8',
);
assert.match(
source,
/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/,
);
});
+336
View File
@@ -0,0 +1,336 @@
import { fromDegrees } from '../geo/ellipsoid.js';
import {
julianFromEpochMs,
julianLessThan,
julianLessThanOrEquals,
julianToEpochMs,
secondsDifference,
} from '../geo/julian.js';
import { clone, distance } from '../geo/vector.js';
import { curvePieceAt, fixCurveCached } from './fixCurve.js';
import { historyBracketIndex, historyUnseenAt } from './timelineHistory.js';
import {
COAST_MAX_SPEED_MPS,
courseBetweenCartesians,
speedRamp,
STALE_COAST_MAX_SEC,
staleCoastLimitSeconds,
staleHoldsForFix,
} from './motionModel.js';
/**
* Which record fields carry an aircraft layer's reported ground speed (m/s)
* and track (degrees clockwise from north).
* @typedef {{speed: string, track: string}} AircraftRecordFields
*/
/** A fix's own ground speed, else the record's; never over COAST_MAX_SPEED_MPS. */
export function fixSpeedMps(fix, info, fields) {
return Math.min(
Number.isFinite(fix.velocity)
? fix.velocity
: (info && info[fields.speed]) || 0,
COAST_MAX_SPEED_MPS,
);
}
/** A fix's own track, else the record's. */
export function fixTrackDeg(fix, info, fields) {
return Number.isFinite(fix.track)
? fix.track
: (info && info[fields.track]) || 0;
}
/**
* The instant `epochMs` as a Julian date (into `result` when given), for
* `aircraftMotionRegime`'s `renderTime`.
*/
export function julianAt(epochMs, result) {
return julianFromEpochMs(epochMs, result);
}
/** A history fix's time in epoch ms: its `epochMs`, else its `time`'s. */
export function fixEpochMs(fix) {
return Number.isFinite(fix.epochMs) ? fix.epochMs : julianToEpochMs(fix.time);
}
/** A feed fix's ECEF position, from its degrees and render altitude. */
export function fixPosition(lonDeg, latDeg, heightM) {
return fromDegrees(lonDeg, latDeg, heightM);
}
/** A copy of a fix position, for a trail that keeps it. */
export function copyPosition(position) {
return clone(position);
}
/**
* A position-history entry for a feed fix at `epochMs`, carrying the fix's
* own speed and track; it keeps a copy of `position`.
*/
export function historyFix(epochMs, position, velocity, track) {
return {
time: julianAt(epochMs),
epochMs,
position: clone(position),
velocity,
track,
};
}
/**
* Whether a history fix is a forward synthetic fix (a motion aid built from
* a repeated report's new speed or course, `synthesizeForwardKinematicsFix`)
* rather than a report.
*/
export const isSyntheticFix = (fix) => Number.isFinite(fix?.reportEpochMs);
/**
* Put a new report at the end of a contact's history: forward synthetic
* fixes after the previous report go (the report supersedes them), and past
* `limit` the oldest fixes go.
* @param {Array<object>} history Oldest first; mutated.
* @param {object} fix The report's history fix.
* @param {number} limit
*/
export function pushReport(history, fix, limit) {
while (history.length && isSyntheticFix(history[history.length - 1]))
history.pop();
history.push(fix);
while (history.length > limit) history.shift();
}
/** The newest report in a history (not a synthetic fix), or undefined. */
export function newestReport(history) {
for (let i = history.length - 1; i >= 0; i--)
if (!isSyntheticFix(history[i])) return history[i];
return undefined;
}
/** The curve a contact is drawn along between two history fixes, or null. */
export function historyCurve(a, b) {
return fixCurveCached(
a.position,
fixEpochMs(a),
a.track,
b.position,
fixEpochMs(b),
b.track,
);
}
/** A reusable result for `aircraftMotionRegime`. */
export function createMotionRegime() {
return {
kind: 'fix',
a: null,
b: null,
piece: null,
span: 0,
speed: 0,
trackFrom: 0,
trackTo: 0,
chordCourse: null,
blend: 0,
fix: null,
heading: 0,
turnRateDps: 0,
minDt: 0,
maxDt: 0,
unseen: false,
};
}
/**
* Which motion an aircraft's history gives at `renderTime` — the one choice
* the CPU dead reckoning and the icon planner (GPU segment) both draw from.
*
* - `between`: between the bracketing pair `a`→`b`, no extrapolation
* error and no snap-back. Along their curve (`data/fixCurve`) when the
* pair describes one: `piece` is the curve's piece at `renderTime`, a
* contract `arc` segment with its times. Otherwise straight from `a` to
* `b` (`piece` null), and the course of the DISPLAYED motion blends the
* time-interpolated reported track toward the chord by `blend`: the chord
* is only trustworthy when the segment covers real ground (at hover its
* direction is GPS jitter; on a slow tight turn it STEPS the whole
* per-segment turn at each boundary), and helicopters never use it
* (rotorcraft chords are noise-dominated at their typical speeds).
* - `fix`: extrapolate `fix` by the elapsed time clamped to [minDt, maxDt].
* Warm-up (renderTime predates ALL history: freshly seen or just tracked,
* before a poll interval of history exists) runs the OLDEST fix BACKWARD,
* preserving the behind-real-time invariant, so as history fills the icon
* glides FORWARD into interpolation with no freeze and no backward snap
* (holding the oldest fix froze the icon; extrapolating the newest to
* wall-clock made it jump back a poll interval when interpolation took
* over). Otherwise the newest fix coasts on its last speed and heading for
* five minutes past it, then stops (SIGNAL LOST). A contact last heard on
* or near the ground holds there instead (`staleHoldsForFix`, decided once
* per report), and a chain of synthetic fixes never coasts further than
* the real report they were built from would. Following the clock, a
* warm-up well before a contact's own first fix is `unseen`: it was not
* there yet, and is not drawn (`historyUnseenAt`).
*
* @param {Array<object>} history Non-empty, oldest first.
* @param {object|undefined} info The contact's record.
* @param {{dayNumber: number, secondsOfDay: number}} renderTime A Julian date (geo/julian).
* @param {AircraftRecordFields} fields
* @param {object} result From `createMotionRegime`; returned filled in.
* @param {{cachedGroundFloor?: (latDeg: number, lonDeg: number) => number|null}} [options]
* The ground under a report, where known, for the hold decision.
*/
export function aircraftMotionRegime(
history,
info,
renderTime,
fields,
result,
{ cachedGroundFloor } = {},
) {
// A synthetic fix a later report superseded is not on the path: the
// contact is drawn report to report, as its trail is.
let report = history.length - 1;
while (report >= 0 && isSyntheticFix(history[report])) report--;
// The pairs are read back from the fix after the first one at or after
// the render time (so a fix at exactly that time takes the later pair, as
// it always did; past any superseded synthetic fix there), found by
// halving, and stop at the first pair wholly before it: a contact
// following the clock keeps a long history.
let start = Math.min(
historyBracketIndex(history, renderTime) + 1,
history.length - 1,
);
while (start < report && isSyntheticFix(history[start])) start++;
let b = null;
for (let i = start; i >= 0; i--) {
const a = history[i];
if (i < report && isSyntheticFix(a)) continue;
const pairB = b;
b = a;
if (!pairB) continue;
if (julianLessThan(pairB.time, renderTime)) break;
if (
!julianLessThanOrEquals(a.time, renderTime) ||
!julianLessThanOrEquals(renderTime, pairB.time)
)
continue;
const span = secondsDifference(pairB.time, a.time);
const chordLenM = distance(a.position, pairB.position);
const speed =
span > 0 ? chordLenM / span : (info && info[fields.speed]) || 0;
const fallbackTrack = (info && info[fields.track]) || 0;
const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack;
const blend = info && info.klass === 'helicopter' ? 0 : speedRamp(speed);
const curve = span > 0 ? historyCurve(a, pairB) : null;
result.kind = 'between';
result.a = a;
result.b = pairB;
result.piece = curve
? curvePieceAt(curve, julianToEpochMs(renderTime))
: null;
result.span = span;
result.speed = speed;
result.trackFrom = trackFrom;
result.trackTo = Number.isFinite(pairB.track) ? pairB.track : trackFrom;
result.chordCourse =
blend > 0 ? courseBetweenCartesians(a.position, pairB.position) : null;
result.blend = blend;
result.unseen = false;
return result;
}
const newest = history[history.length - 1];
const warming = julianLessThan(renderTime, history[0].time);
result.kind = 'fix';
result.piece = null;
result.fix = warming ? history[0] : newest;
result.unseen = warming && historyUnseenAt(history, renderTime);
result.speed = fixSpeedMps(result.fix, info, fields);
result.heading = fixTrackDeg(result.fix, info, fields);
// Past the newest report it flies straight on along its course: a turn
// rate averaged over earlier reports outlives the turn it measured, and
// coasting on it put contacts kilometres off a straight path.
result.turnRateDps = 0;
result.minDt = -60;
// A warm-up ends when real time reaches the oldest fix; a single fix keeps
// coasting forward on the same line.
result.maxDt =
warming && history.length > 1
? 0
: staleCoastSeconds(newest, info, cachedGroundFloor);
return result;
}
/**
* How long `newest` coasts at most: five minutes, less what a synthetic
* fix's chain already coasted since its real report (`reportEpochMs`); none
* for a report that holds (judged once per report, from its ground flag and
* the ground under it where `cachedGroundFloor` knows it).
* @param {object} newest
* @param {object|undefined} info
* @param {Function} [cachedGroundFloor]
* @returns {number}
*/
export function staleCoastSeconds(newest, info, cachedGroundFloor) {
const newestMs = fixEpochMs(newest);
const limitSec = staleCoastLimitSeconds({
fixEpochMs: newestMs,
lastContactEpochMs: info?.lastContactEpochMs,
// A plane that stops reporting keeps flying for five minutes, whatever
// its contact time, then stops dimmed as SIGNAL LOST. A missed update
// shows STALE throughout.
minimumSec: 300,
maximumSec: 300,
});
if (staleHoldsForFix(newest, { onGround: info?.onGround, cachedGroundFloor }))
return 0;
const alreadySec = Number.isFinite(newest.reportEpochMs)
? Math.max(0, (newestMs - newest.reportEpochMs) / 1000)
: 0;
return Math.max(0, Math.min(limitSec, STALE_COAST_MAX_SEC - alreadySec));
}
/** A raw position this far (m) off its own path, plus half its step, is a jump. */
const RAW_JUMP_SLACK_M = 5;
/**
* Whether a tracked aircraft's raw position jumped this frame: a new report
* moved its path. Judged against the path itself, where its last frame's
* step carries it, not against a reported speed (which can be stale or 0
* while the drawn motion, minutes behind the newest report, is fast). A
* frame with no step to go by (the first on a track, or the one after a
* jump) is never a jump.
* @param {{x: number, y: number, z: number}} raw This frame's raw position.
* @param {{x: number, y: number, z: number}} prevRaw Last frame's.
* @param {{x: number, y: number, z: number}} prevRawStep Last frame's step.
* @param {number} prevRawStepSec Last frame's length, s (0: no step).
* @param {number} dtSec This frame's length, s.
* @returns {boolean}
*/
export function rawPositionJumped(
raw,
prevRaw,
prevRawStep,
prevRawStepSec,
dtSec,
) {
if (!(prevRawStepSec > 0)) return false;
const k = dtSec / prevRawStepSec;
const dx = raw.x - (prevRaw.x + prevRawStep.x * k);
const dy = raw.y - (prevRaw.y + prevRawStep.y * k);
const dz = raw.z - (prevRaw.z + prevRawStep.z * k);
const stepM =
Math.hypot(prevRawStep.x, prevRawStep.y, prevRawStep.z) * Math.abs(k);
return Math.hypot(dx, dy, dz) > RAW_JUMP_SLACK_M + 0.5 * stepM;
}
/**
* How fast the drawn path moves (m/s), from its last raw step; `fallback`
* (a reported speed) with no step to go by.
* @param {{x: number, y: number, z: number}} step
* @param {number} stepSec
* @param {number} fallback
* @returns {number}
*/
export function rawStepSpeedMps(step, stepSec, fallback) {
if (!(stepSec > 0)) return fallback;
return Math.hypot(step.x, step.y, step.z) / stepSec;
}
+53 -143
View File
@@ -1,35 +1,33 @@
/**
* Limb-relative recession for distant aircraft billboards.
* Limb-relative recession for distant aircraft: the tuning the aircraft icon
* and model sets recede by (`aircraftRecedeSpec`), and the factors and alpha
* those sets draw with, for evidence and checks.
*
* This multiplies the billboard's ordinary scale, which Cesium then composes
* with the locked NearFarScalar. It never edits that scalar, culls a contact,
* or allows alpha to reach zero.
* It multiplies an icon's ordinary scale, which composes with its locked
* NearFarScalar. It never edits that scalar, culls a contact, or allows alpha
* to reach zero. The maths is the Cesium-free `render/recession.js`,
* which the sets drawing aircraft recede by (`SetSpec.recede`).
*/
import {
RECEDE_DEFAULTS,
limbDistanceM,
recedeFactors,
recedeFrame,
recedeParams,
recededAlpha,
} from '../render/recession.js';
export const DEFAULT_AIRCRAFT_RECESSION_PARAMS = Object.freeze({
startLimbRatio: 0.5,
scaleFloor: 0.45,
alphaFloor: 0.35,
combinedAlphaFloor: 0.2,
globeViewBlendStartM: 3_500_000,
globeViewBlendEndM: 4_500_000,
earthRadiusM: 6_378_137,
...RECEDE_DEFAULTS,
writeEpsilon: 0.005,
});
let _params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS };
const _scratchFactors = { scale: 1, alpha: 1, limbRatio: null };
const _treatmentResult = {
scale: 1,
alpha: 1,
scaleWrites: 0,
alphaWrites: 0,
factors: _scratchFactors,
};
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
const _scratchFrame = { active: false, limbM: 1, strength: 0 };
// The tuning `_recede` was made from, and the set option made from it.
let _recedeFor = null;
let _recede = null;
function resolvedParams(overrides) {
if (!overrides || overrides === _params) return _params;
@@ -42,47 +40,12 @@ function aircraftRecessionFactorsResolved(
tuning,
result,
) {
if (
!Number.isFinite(cameraDistanceM) ||
cameraDistanceM < 0 ||
!Number.isFinite(cameraHeightM) ||
cameraHeightM <= 0 ||
cameraHeightM >= tuning.globeViewBlendEndM
) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = null;
return result;
}
const limbDistance = cameraLimbDistanceM(cameraHeightM, tuning.earthRadiusM);
if (!Number.isFinite(limbDistance) || limbDistance <= 0) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = null;
return result;
}
const limbRatio = cameraDistanceM / limbDistance;
if (limbRatio <= tuning.startLimbRatio) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = limbRatio;
return result;
}
const rawT =
(limbRatio - tuning.startLimbRatio) / (1 - tuning.startLimbRatio);
const t = clamp(rawT, 0, 1);
const limbEase = t * t * (3 - 2 * t); // smoothstep: zero slope at both band edges
const globeRawT =
(cameraHeightM - tuning.globeViewBlendStartM) /
(tuning.globeViewBlendEndM - tuning.globeViewBlendStartM);
const globeT = clamp(globeRawT, 0, 1);
const globeEase = globeT * globeT * (3 - 2 * globeT);
const strength = 1 - globeEase;
result.scale = 1 + (tuning.scaleFloor - 1) * limbEase * strength;
result.alpha = 1 + (tuning.alphaFloor - 1) * limbEase * strength;
result.limbRatio = limbRatio;
return result;
return recedeFactors(
cameraDistanceM,
recedeFrame(cameraHeightM, tuning, _scratchFrame),
tuning,
result,
);
}
/**
@@ -91,45 +54,34 @@ function aircraftRecessionFactorsResolved(
* @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS}
*/
export function setAircraftRecessionParams(patch = {}) {
const next = { ..._params };
if (Number.isFinite(patch.startLimbRatio)) {
next.startLimbRatio = clamp(patch.startLimbRatio, 0, 0.99);
}
if (Number.isFinite(patch.scaleFloor))
next.scaleFloor = clamp(patch.scaleFloor, 0.05, 1);
if (Number.isFinite(patch.alphaFloor))
next.alphaFloor = clamp(patch.alphaFloor, 0.05, 1);
if (Number.isFinite(patch.combinedAlphaFloor)) {
next.combinedAlphaFloor = clamp(patch.combinedAlphaFloor, 0.05, 1);
}
if (Number.isFinite(patch.globeViewBlendStartM)) {
next.globeViewBlendStartM = Math.max(1, patch.globeViewBlendStartM);
}
if (Number.isFinite(patch.globeViewBlendEndM)) {
next.globeViewBlendEndM = Math.max(
next.globeViewBlendStartM + 1,
patch.globeViewBlendEndM,
);
}
// Backward-compatible evidence override: the former hard threshold now
// names the identity end of the blend band.
if (Number.isFinite(patch.globeViewHeightM)) {
next.globeViewBlendEndM = Math.max(
next.globeViewBlendStartM + 1,
patch.globeViewHeightM,
);
}
if (next.globeViewBlendStartM >= next.globeViewBlendEndM) {
next.globeViewBlendStartM = Math.max(1, next.globeViewBlendEndM - 1);
}
if (Number.isFinite(patch.earthRadiusM))
next.earthRadiusM = Math.max(1, patch.earthRadiusM);
const given = Number.isFinite(patch.globeViewHeightM)
? { ...patch, globeViewBlendEndM: patch.globeViewHeightM }
: patch;
const next = {
...recedeParams(given, _params),
writeEpsilon: _params.writeEpsilon,
};
if (Number.isFinite(patch.writeEpsilon))
next.writeEpsilon = Math.max(0, patch.writeEpsilon);
_params = next;
return { ..._params };
}
/**
* The tuning as the `recede` of the sets that draw aircraft: the same
* object until the tuning changes.
* @returns {import('../render/contract/index').RecedeSpec}
*/
export function aircraftRecedeSpec() {
if (_recedeFor !== _params) {
_recedeFor = _params;
_recede = Object.freeze(recedeParams(_params));
}
return _recede;
}
/** @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS} Current tuning. */
export function getAircraftRecessionParams() {
return _params;
@@ -148,13 +100,7 @@ export function resetAircraftRecessionParams() {
* @param {number} [earthRadiusM]
* @returns {number}
*/
export function cameraLimbDistanceM(
cameraHeightM,
earthRadiusM = DEFAULT_AIRCRAFT_RECESSION_PARAMS.earthRadiusM,
) {
if (!Number.isFinite(cameraHeightM) || cameraHeightM <= 0) return Number.NaN;
return Math.sqrt(cameraHeightM * (2 * earthRadiusM + cameraHeightM));
}
export const cameraLimbDistanceM = limbDistanceM;
/**
* Pure recession factors for one aircraft.
@@ -178,28 +124,18 @@ export function aircraftRecessionFactors(
}
/**
* Production wire helper: compose base scale/alpha, focus emphasis, and limb
* recession into one deadband-gated billboard write site.
* The alpha an aircraft draws with: base × max(combined floor, focus × limb
* haze). Icon sets compose the same thing in their shader; models need it here.
* @param {object} input
* @param {object} input.billboard
* @param {number} input.baseScale
* @param {number} input.baseAlpha
* @param {{withAlpha:(alpha:number)=>object}} input.baseColor
* @param {number} input.focusFactor
* @param {number} input.cameraDistanceM
* @param {number} input.cameraHeightM
* @param {Partial<typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS>} [input.params]
*
* IMPORTANT: the returned object (including `factors`) is a module-owned
* mutable singleton. Consume every needed property before the next call;
* never retain it as a snapshot.
* @returns {{scale:number,alpha:number,scaleWrites:number,alphaWrites:number,factors:object}}
* @returns {number}
*/
export function applyAircraftBillboardTreatment({
billboard,
baseScale,
export function aircraftTreatmentAlpha({
baseAlpha,
baseColor,
focusFactor,
cameraDistanceM,
cameraHeightM,
@@ -212,38 +148,12 @@ export function applyAircraftBillboardTreatment({
tuning,
_scratchFactors,
);
const scale = baseScale * factors.scale;
const composedTreatment = Math.max(
tuning.combinedAlphaFloor,
clamp(focusFactor, 0, 1) * factors.alpha,
);
const alpha = baseAlpha * composedTreatment;
let scaleWrites = 0;
let alphaWrites = 0;
if (
!Number.isFinite(billboard.scale) ||
Math.abs(billboard.scale - scale) > tuning.writeEpsilon
) {
billboard.scale = scale;
scaleWrites = 1;
}
if (
!Number.isFinite(billboard.color?.alpha) ||
Math.abs(billboard.color.alpha - alpha) > tuning.writeEpsilon
) {
billboard.color = baseColor.withAlpha(alpha);
alphaWrites = 1;
}
_treatmentResult.scale = scale;
_treatmentResult.alpha = alpha;
_treatmentResult.scaleWrites = scaleWrites;
_treatmentResult.alphaWrites = alphaWrites;
return _treatmentResult;
return baseAlpha * recededAlpha(focusFactor, factors.alpha, tuning);
}
/**
* Apply layer-owned hue and composed aircraft alpha to an ambient glTF model without
* disturbing Cesium's existing MIX/colorBlendAmount presentation semantics.
* changing the model's colour blend mode or amount.
* @param {object} input
* @param {object} input.model
* @param {{withAlpha:(alpha:number)=>object}} input.baseColor
+24 -60
View File
@@ -3,9 +3,9 @@ import assert from 'node:assert/strict';
import {
DEFAULT_AIRCRAFT_RECESSION_PARAMS,
aircraftRecessionFactors,
applyAircraftBillboardTreatment,
applyAircraftModelTreatment,
cameraLimbDistanceM,
aircraftTreatmentAlpha,
} from './aircraftRecession.js';
const params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS };
@@ -66,72 +66,15 @@ test('globe-view transition eases to identity without a threshold pop', () => {
assert.deepEqual(end, { scale: 1, alpha: 1, limbRatio: null });
});
test('aircraft billboard wire writes scale and alpha only for the far treatment', () => {
const color = { withAlpha: (alpha) => ({ alpha }) };
const near = { scale: 1.2, color: { alpha: 0.8 } };
const nearResult = applyAircraftBillboardTreatment({
billboard: near,
baseScale: 1.2,
baseAlpha: 0.8,
baseColor: color,
focusFactor: 1,
cameraDistanceM: limb * 0.4,
cameraHeightM,
params,
});
assert.equal(nearResult.scaleWrites, 0);
assert.equal(nearResult.alphaWrites, 0);
const far = { scale: 1.2, color: { alpha: 0.8 } };
const farResult = applyAircraftBillboardTreatment({
billboard: far,
baseScale: 1.2,
baseAlpha: 0.8,
baseColor: color,
focusFactor: 0.5,
cameraDistanceM: limb,
cameraHeightM,
params,
});
assert.equal(farResult.scaleWrites, 1);
assert.equal(farResult.alphaWrites, 1);
assert.ok(Math.abs(far.scale - (1.2 * 0.45)) < 1e-12);
assert.ok(Math.abs(far.color.alpha - (0.8 * 0.20)) < 1e-12);
});
test('combined focus and haze product is clamped at the composed alpha floor', () => {
const color = { withAlpha: (alpha) => ({ alpha }) };
const billboard = { scale: 0.45, color: { alpha: 1 } };
const result = applyAircraftBillboardTreatment({
billboard,
baseScale: 1,
const alpha = aircraftTreatmentAlpha({
baseAlpha: 1,
baseColor: color,
focusFactor: 0.25,
cameraDistanceM: limb,
cameraHeightM,
params,
});
assert.equal(result.alpha, 0.20);
assert.equal(billboard.color.alpha, 0.20);
});
test('applyAircraftBillboardTreatment returns its documented module singleton', () => {
const color = { withAlpha: (alpha) => ({ alpha }) };
const billboard = { scale: 1, color: { alpha: 1 } };
const input = {
billboard,
baseAlpha: 1,
baseColor: color,
focusFactor: 1,
cameraDistanceM: 0,
cameraHeightM,
params,
};
const first = applyAircraftBillboardTreatment({ ...input, baseScale: 1 });
const second = applyAircraftBillboardTreatment({ ...input, baseScale: 0.5 });
assert.strictEqual(first, second);
assert.equal(first.scale, 0.5, 'the prior reference reflects the next call');
assert.equal(alpha, 0.2);
});
test('ambient model presentation receives composed alpha without changing blend semantics', () => {
@@ -154,3 +97,24 @@ test('model hue changes at constant alpha, then clears without redundant writes'
assert.equal(applyAircraftModelTreatment({model,baseColor:color(1,1,1),alpha:0.65}),1);
assert.equal(model.color.green,1);
});
test('the aircraft sets recede by the tuning: one object until it changes', async () => {
const {
aircraftRecedeSpec,
setAircraftRecessionParams,
resetAircraftRecessionParams,
} = await import('./aircraftRecession.js');
const { RECEDE_DEFAULTS } = await import('../render/recession.js');
resetAircraftRecessionParams();
const first = aircraftRecedeSpec();
assert.deepEqual(first, { ...RECEDE_DEFAULTS });
assert.equal(aircraftRecedeSpec(), first);
setAircraftRecessionParams({ scaleFloor: 0.6, globeViewHeightM: 4_000_000 });
const tuned = aircraftRecedeSpec();
assert.notEqual(tuned, first);
assert.equal(tuned.scaleFloor, 0.6);
assert.equal(tuned.globeViewBlendEndM, 4_000_000);
assert.equal('writeEpsilon' in tuned, false);
resetAircraftRecessionParams();
assert.deepEqual(aircraftRecedeSpec(), first);
});
File diff suppressed because it is too large. Load diff
+152
View File
@@ -258,3 +258,155 @@ test('partial static data keeps newer live metadata ahead of the old static cach
assert.equal(rowFor(mmsi).type, '80');
assert.equal(rowFor(mmsi).destination, 'HAMBURG');
});
// A static report's dimensions are the antenna's distances to bow (A), stern
// (B), port (C) and starboard (D): length A+B, beam C+D. Zero is AIS's "not
// available", so a vessel reporting none has no size, not a size of zero.
test('a static report gives a vessel its hull length and beam', () => {
ingestAisStreamEnvelope(positionReport('636019825', { Sog: 14 }));
ingestAisStreamEnvelope({
MessageType: 'ShipStaticData',
Message: {
ShipStaticData: {
UserID: 636019825,
Name: 'EVER GIVEN',
Type: 70,
Dimension: { A: 330, B: 70, C: 30, D: 29 },
},
},
MetaData: { MMSI: '636019825' },
});
const row = rowFor('636019825');
assert.equal(row.length, 400);
assert.equal(row.beam, 59);
ingestAisStreamEnvelope(positionReport('636019826', { Sog: 3 }));
ingestAisStreamEnvelope({
MessageType: 'ShipStaticData',
Message: {
ShipStaticData: {
UserID: 636019826,
Type: 52,
Dimension: { A: 0, B: 0, C: 0, D: 0 },
},
},
MetaData: { MMSI: '636019826' },
});
assert.equal(rowFor('636019826').length, null);
assert.equal(rowFor('636019826').beam, null);
});
test('a Class B report carries its dimensions in part B', () => {
ingestAisStreamEnvelope(positionReport('244000777', { Sog: 6 }));
ingestAisStreamEnvelope({
MessageType: 'StaticDataReport',
Message: {
StaticDataReport: {
UserID: 244000777,
ReportB: {
Valid: true,
ShipType: 37,
Dimension: { A: 8, B: 4, C: 2, D: 2 },
},
},
},
MetaData: { MMSI: '244000777' },
});
const row = rowFor('244000777');
assert.equal(row.length, 12);
assert.equal(row.beam, 4);
});
test('an aid-to-navigation report is a row named by its kind of aid, not a ship type', () => {
assert.equal(
ingestAisStreamEnvelope({
MessageType: 'AidsToNavigationReport',
Message: {
AidsToNavigationReport: {
UserID: 993672001,
Type: 20,
Name: 'SF APPROACH N',
},
},
MetaData: {
MMSI: '993672001',
latitude: 37.79,
longitude: -122.52,
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
},
}),
true,
);
const row = rowFor('993672001');
assert.equal(row.type, 'Cardinal Mark N');
assert.equal(row.name, 'SF APPROACH N');
assert.equal(row.speed, null);
});
test("an aid's name runs on into its name extension", () => {
ingestAisStreamEnvelope({
MessageType: 'AidsToNavigationReport',
Message: {
AidsToNavigationReport: {
UserID: 993672002,
Type: 13,
Name: 'SAN FRANCISCO MAIN S',
NameExtension: 'HIP CHANNEL 2',
},
},
MetaData: {
MMSI: '993672002',
ShipName: 'SAN FRANCISCO MAIN S',
latitude: 37.79,
longitude: -122.52,
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
},
});
assert.equal(rowFor('993672002').name, 'SAN FRANCISCO MAIN SHIP CHANNEL 2');
});
test('a capped row request keeps every vessel ahead of aids to navigation', () => {
// The aid reports last, so it is the newest row.
ingestAisStreamEnvelope(positionReport('244060901', { Sog: 3 }));
ingestAisStreamEnvelope({
MessageType: 'AidsToNavigationReport',
Message: { AidsToNavigationReport: { UserID: 993672003, Type: 24 } },
MetaData: {
MMSI: '993672003',
latitude: 37.79,
longitude: -122.52,
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
},
});
const rows = aisStreamRows(50000);
const firstAid = rows.findIndex((row) => row.mmsi.startsWith('99'));
const lastVessel = rows.findLastIndex((row) => !row.mmsi.startsWith('99'));
assert.ok(firstAid > lastVessel, `${firstAid} > ${lastVessel}`);
const vesselCount =
rows.length - rows.filter((row) => row.mmsi.startsWith('99')).length;
assert.ok(
aisStreamRows(vesselCount).every((row) => !row.mmsi.startsWith('99')),
);
});
test('a virtual aid to navigation is marked virtual; a real one carries no flag', () => {
const aidReport = (mmsi, VirtualAtoN) => ({
MessageType: 'AidsToNavigationReport',
Message: {
AidsToNavigationReport: { UserID: Number(mmsi), Type: 28, VirtualAtoN },
},
MetaData: {
MMSI: mmsi,
latitude: 37.79,
longitude: -122.52,
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
},
});
ingestAisStreamEnvelope(aidReport('993672004', true));
ingestAisStreamEnvelope(aidReport('993672005', false));
assert.equal(rowFor('993672004').virtual, true);
assert.equal('virtual' in rowFor('993672005'), false);
// A later real report of the same aid drops the flag.
ingestAisStreamEnvelope(aidReport('993672004', false));
assert.equal('virtual' in rowFor('993672004'), false);
});
+131 -123
View File
@@ -3,6 +3,11 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
bindFakeCesiumCamera,
followEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
import alprCamerasLayer, {
createAlprCamerasLayer,
configureAlprSource,
@@ -31,6 +36,8 @@ import {
isAlprSurveillanceType,
normalizeAlprNode,
} from './alprCameras.js';
import { readEntityRecord } from './entityRecords.js';
import { alprMarkers } from '../layers/alpr/markerState.js';
test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
const record = normalizeAlprNode({
@@ -308,7 +315,7 @@ function cameraHarness(layer = alprCamerasLayer) {
},
});
let box = { south: 30.26, west: -97.75, north: 30.28, east: -97.73 };
let source, click, picked;
let click, picked;
const credits = new Set();
const viewer = {
creditDisplay: {
@@ -333,20 +340,27 @@ function cameraHarness(layer = alprCamerasLayer) {
postRender: new Cesium.Event(),
pick: () => picked,
},
dataSources: {
add: (value) => {
source = value;
},
remove() {},
},
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
entities: {},
};
const ports = fakeScenePorts(viewer);
bindFakeCesiumCamera(viewer, ports);
// The renderer's camera port relays moveEnd; the layer's own come on top.
const portMoveEndListeners = viewer.camera.moveEnd.numberOfListeners;
const setInput = Cesium.ScreenSpaceEventHandler.prototype.setInputAction;
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = function (
fn,
type,
modifier,
) {
if (type === Cesium.ScreenSpaceEventType.LEFT_CLICK) click = fn;
// The unmodified click: the input port binds one per modifier.
if (
type === Cesium.ScreenSpaceEventType.LEFT_CLICK &&
modifier === undefined
)
click = fn;
return setInput.call(this, fn, type, modifier);
};
try {
@@ -355,13 +369,22 @@ function cameraHarness(layer = alprCamerasLayer) {
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = setInput;
}
layer.enable();
const icons = () => {
const set = [...ports.draw.sets.values()].find(
(candidate) => candidate.kind === 'icons' && !candidate.disposed,
);
return set && { ...set, id: set.spec.id };
};
const marker = (id) =>
icons()?.items.has(id)
? getContextStore().entities.get(id)?.entity
: undefined;
return {
viewer,
ports,
portMoveEndListeners,
requests,
credits,
get source() {
return source;
},
setFetch(fn) {
response = fn;
},
@@ -374,9 +397,16 @@ function cameraHarness(layer = alprCamerasLayer) {
advance(ms) {
now += ms;
},
/** The layer's icon set, as the fake draw port holds it. */
icons,
/** The icon drawn for a camera, or undefined. */
icon: (id) => icons()?.items.get(id),
/** The drawn markers' carriers (their context entities), in draw order. */
markers: () => [...(icons()?.items.keys() ?? [])].map((id) => marker(id)),
marker,
click(id) {
const entity = typeof id === 'string' ? source.entities.getById(id) : id;
picked = entity ? { id: entity } : undefined;
const item = typeof id === 'string' ? icons()?.items.get(id) : null;
picked = item ? { id: { set: icons().id, id: item.id } } : undefined;
click({ position: new Cesium.Cartesian2() });
},
restore() {
@@ -440,28 +470,28 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a
]),
);
await alprCamerasLayer.update();
const entities = h.source.entities.values;
const entities = h.markers();
assert.equal(alprCamerasLayer.name, 'ALPR Cameras');
assert.deepEqual(
entities.map((entity) => entity.gevLabelModel.title),
entities.map((entity) => readEntityRecord(entity)?.labelModel.title),
['ALPR-0042', 'ALPR-0043', 'ALPR-0044'],
);
assert.equal(
new Set(entities.map((entity) => entity.billboard.image.getValue())).size,
new Set(entities.map((entity) => h.icon(entity.id).image)).size,
1,
);
assert.deepEqual(entities[0].gevLabelModel.details, [
assert.deepEqual(readEntityRecord(entities[0])?.labelModel.details, [
'OSM MAPPED',
'FLOCK SAFETY · CITY POLICE · FIXED',
'PUBLIC MAP DATA',
]);
assert.deepEqual(entities[1].gevLabelModel.details, [
assert.deepEqual(readEntityRecord(entities[1])?.labelModel.details, [
'OSM MAPPED',
'MOTOROLA SOLUTIONS',
'PUBLIC MAP DATA',
]);
assert.deepEqual(
entities[2].gevLabelModel.details,
readEntityRecord(entities[2])?.labelModel.details,
['OSM MAPPED', 'PUBLIC MAP DATA'],
'unknown metadata is not guessed, but the source is always named',
);
@@ -486,7 +516,7 @@ test('the camera label stays English data in a translated interface', async () =
]),
);
await alprCamerasLayer.update();
h.click(h.source.entities.values[0].id);
h.click(h.markers()[0].id);
assert.equal(getSelectedEntityContext().label, 'ALPR camera');
assert.equal(
shownEntityLabel(getSelectedEntityContext().label),
@@ -523,10 +553,7 @@ test('clicking the selected camera or empty map deselects, including after refre
h.expire();
await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null);
assert.equal(
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
assert.equal(h.icon('alpr:42').size[0], 38);
}
} finally {
h.restore();
@@ -582,10 +609,7 @@ test('disable removes contexts and highlight; cache reuse after re-enable does n
alprCamerasLayer.enable();
await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null);
assert.equal(
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
assert.equal(h.icon('alpr:42').size[0], 38);
} finally {
h.restore();
}
@@ -674,7 +698,7 @@ test('duplicate nodes render once with a count that agrees with the entity set',
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'ready');
assert.equal(alprCamerasLayer.getStats().count, 1);
assert.equal(h.source.entities.values.length, 1);
assert.equal(h.icons().items.size, 1);
} finally {
h.restore();
}
@@ -690,7 +714,7 @@ test('zooming out hides local markers, releases selection and makes no unbounded
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(alprCamerasLayer.getStats().count, 0);
assert.equal(getSelectedEntityContext(), null);
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.icons().items.size, 0);
assert.equal(h.requests.length, 1);
} finally {
h.restore();
@@ -750,7 +774,7 @@ test('nearby camera moves reuse the snapped query but count and register only in
await alprCamerasLayer.update();
assert.equal(h.requests.length, 1);
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
h.markers().map((e) => e.id),
['alpr:43'],
);
assert.deepEqual([...getContextStore().entities.keys()], ['alpr:43']);
@@ -797,9 +821,8 @@ test('selected readout samples the rendered ground, not zero elevation or the di
try {
let samples = 0;
h.viewer.scene.sampleHeightSupported = true;
h.viewer.scene.sampleHeight = (point, excluded) => {
h.viewer.scene.sampleHeight = () => {
samples += 1;
assert.equal(excluded[0].id, 'alpr:42');
return 187;
};
h.setFetch(async () =>
@@ -811,9 +834,9 @@ test('selected readout samples the rendered ground, not zero elevation or the di
);
await alprCamerasLayer.update();
h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42');
const entity = h.marker('alpr:42');
const anchor = Cesium.Cartographic.fromCartesian(
entity.gevDisplayPosition(),
readEntityRecord(entity)?.displayPosition(),
);
assert.ok(Math.abs(anchor.height - 187) < 0.001);
assert.ok(
@@ -821,7 +844,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di
);
for (let i = 0; i < 60; i++) {
h.viewer.scene.postRender.raiseEvent();
entity.gevDisplayPosition();
readEntityRecord(entity)?.displayPosition();
}
assert.equal(samples, 1, 'no per-frame raycasts');
h.advance(1000);
@@ -859,6 +882,7 @@ test('a late network failure after disable cannot resurrect retries or an error
});
test('two factories keep their requests, records and destruction independent', async () => {
const carriers = new Map();
const services = {
render: { governorRequestRender() {} },
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
@@ -872,7 +896,9 @@ test('two factories keep their requests, records and destruction independent', a
getSelectedEntityContext() {
return null;
},
registerEntityContext() {},
registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
@@ -918,14 +944,17 @@ test('two factories keep their requests, records and destruction independent', a
await pending;
assert.equal(first.getStats().count, 0);
assert.equal(second.getStats().count, 1);
assert.equal(b.source.entities.values[0].id, 'directory:99');
assert.deepEqual([...b.icons().items.keys()], ['directory:99']);
assert.equal(second.source, 'Test camera directory');
assert.ok(
b.source.entities.values[0].gevLabelModel.details.includes(
'Source: Test directory',
),
readEntityRecord(
carriers.get('directory:99'),
)?.labelModel.details.includes('Source: Test directory'),
);
assert.equal(
a.viewer.camera.moveEnd.numberOfListeners,
a.portMoveEndListeners,
);
assert.equal(a.viewer.camera.moveEnd.numberOfListeners, 0);
assert.equal(a.viewer.scene.postRender.numberOfListeners, 0);
} finally {
b.restore();
@@ -937,6 +966,7 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
// Ground clamping re-samples every marker whenever a photoreal tile streams
// in; a whole-city view (about 1,000 cameras) stuttered while zooming.
const floors = new Map([['30.2672', 150]]);
const carriers = new Map();
let resolveCalls = 0;
let releaseResolve;
const services = {
@@ -957,7 +987,9 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
getSelectedEntityContext() {
return null;
},
registerEntityContext() {},
registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
@@ -978,38 +1010,29 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
const h = cameraHarness(layer);
try {
await layer.update();
const known = h.source.entities.getById('directory:1');
const unknown = h.source.entities.getById('directory:2');
assert.equal(
known.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
const known = h.icon('directory:1');
const unknown = () => h.icon('directory:2');
const unknownCarrier = carriers.get('directory:2');
assert.equal(known.height, 'absolute');
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(known.position.getValue()).height -
151.5,
) < 0.01,
);
assert.equal(
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND,
Math.abs(Cesium.Cartographic.fromCartesian(known.pos).height - 151.5) <
0.01,
);
assert.equal(unknown().height, 'clampGround');
assert.equal(resolveCalls, 1);
const writes = h.icons().writes;
releaseResolve();
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
assert.equal(unknown().height, 'absolute');
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(unknown.position.getValue()).height -
161.5,
Cesium.Cartographic.fromCartesian(unknown().pos).height - 161.5,
) < 0.01,
);
assert.equal(h.icons().writes, writes + 1, 'one write for the move');
assert.equal(
h.source.entities.getById('directory:2'),
unknown,
carriers.get('directory:2'),
unknownCarrier,
'placed in place, not rebuilt',
);
} finally {
@@ -1061,23 +1084,16 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
);
await alprCamerasLayer.update();
h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42');
const position = entity.position,
line = entity.polyline;
const entity = h.marker('alpr:42');
const icon = h.icon('alpr:42');
// Ground-clamped native wedges cost ~40 ms per frame for a downtown view;
// bearings are painted by the overlay for the nearest cameras instead.
assert.equal(line, undefined);
assert.equal(entity.polygon, undefined);
assert.equal(h.ports.draw.sets.size, 1, 'icons only, no wedge geometry');
let selections = 0,
clears = 0,
collectionChanges = 0;
clears = 0;
window.addEventListener('gev:entity-selected', () => selections++);
window.addEventListener('gev:entity-selection-cleared', () => clears++);
h.source.entities.collectionChanged.addEventListener(
(_collection, added, removed) => {
collectionChanges += added.length + removed.length;
},
);
const writes = h.icons().writes;
h.setBox({ south: 30.261, west: -97.749, north: 30.279, east: -97.731 });
await alprCamerasLayer.update();
h.expire();
@@ -1093,30 +1109,26 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
]),
);
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(entity.position, position);
assert.equal(entity.polyline, line);
assert.equal(h.marker('alpr:42'), entity);
assert.equal(h.icon('alpr:42'), icon, 'the icon is not sent again');
assert.equal(
getSelectedEntityContext().properties.operator,
'Updated directory',
);
assert.equal(selections, 0);
assert.equal(clears, 0);
assert.equal(collectionChanges, 0);
assert.equal(h.icons().writes, writes, 'no icon added or removed');
assert.equal(h.requests.length, 2, 'only expiry needs another request');
h.expire();
h.setFetch(async () => cameraResponse([cameraNode(42, { lon: -97.742 })]));
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(
entity.polyline,
undefined,
'removed direction must not persist',
);
assert.equal(h.marker('alpr:42'), entity);
assert.ok(
Cesium.Cartesian3.equals(
entity.position.getValue(),
Cesium.Cartesian3.equalsEpsilon(
h.icon('alpr:42').pos,
Cesium.Cartesian3.fromDegrees(-97.742, 30.2672),
0,
1e-6,
),
);
} finally {
@@ -1156,7 +1168,7 @@ test('moves inside a pending query do not restart it; moving to another city can
resolve(cameraResponse([cameraNode(43, { lat: 51.495, lon: -0.13 })]));
await second;
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
h.markers().map((e) => e.id),
['alpr:43'],
);
} finally {
@@ -1174,12 +1186,12 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da
camera.positionWC = Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 1200);
try {
await alprCamerasLayer.update();
const entity = h.source.entities.getById('alpr:42');
const entity = h.marker('alpr:42');
h.click('alpr:42');
for (const box of [null, { south: 31, west: -99, north: 36, east: -95 }]) {
h.setBox(box);
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(h.marker('alpr:42'), entity);
assert.equal(getSelectedEntityContext().id, 'alpr:42');
assert.equal(h.requests.length, 1);
}
@@ -1190,7 +1202,7 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da
);
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.icons().items.size, 0);
camera.pickEllipsoid = () => undefined;
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
@@ -1235,14 +1247,14 @@ test('nearby count and discovery control frame a real loaded camera without fetc
);
assert.equal(flights[0].options.offset.range, 800);
assert.equal(h.requests.length, 1);
h.viewer.trackedEntity = {};
followEntity(h.viewer, {});
assert.equal(alprCamerasLayer.getRowControls().chips[0].disabled, true);
assert.equal(
controls.chips[0].onClick(),
false,
'a stale button cannot steal the follow camera',
);
h.viewer.trackedEntity = undefined;
followEntity(h.viewer, null);
alprCamerasLayer.disable();
assert.equal(alprCamerasLayer.getStats().countLabel, '');
assert.equal(controls.chips[0].onClick(), false);
@@ -1385,7 +1397,7 @@ test('slow ALPR floors share real terrain requests across preparation, render an
requests[1].release();
await new Promise((done) => setTimeout(done, 0));
assert.equal(requests.length, 2, 'queued final cells are discarded');
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.icons().items.size, 0);
layer.enable();
await layer.update();
assert.equal(
@@ -1404,10 +1416,11 @@ test('slow ALPR floors share real terrain requests across preparation, render an
}
});
test('map-source changes reposition all ALPR entities and saved native appearances in place', async () => {
test('map-source changes reposition all ALPR markers, those under canvas badges too, in place', async () => {
let floor = 180;
let listener;
let removed = 0;
const carriers = new Map();
const records = Array.from({ length: 70 }, (_, i) => ({
id: `surface:${i}`,
latitude: 30.2672 + i * 0.00001,
@@ -1433,7 +1446,9 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
context: {
clearSelectedEntityContextForLayer() {},
getSelectedEntityContext() {},
registerEntityContext() {},
registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
@@ -1442,40 +1457,33 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
const h = cameraHarness(layer);
try {
await layer.update();
const entities = [...h.source.entities.values];
const entities = [...carriers.values()];
// One marker under a canvas badge: its icon is the faint pick target.
const saved = entities[1];
saved.gevAlprNativeAppearance = {
position: saved.position,
heightReference: saved.billboard.heightReference,
};
saved.position = Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190);
saved.gevAlprPickPosition = saved.position;
Object.assign(alprMarkers.write(saved), {
canvasOwned: true,
canvasPosition: Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190),
});
for (const next of [150, 120, null, 180]) {
floor = next;
// Includes a provider switch with the same globe.show value.
h.viewer.scene.globe.show = next !== 180;
listener({ detail: { status: 'ready' } });
for (const entity of entities) {
assert.equal(h.source.entities.getById(entity.id), entity);
const icon = h.icon(entity.id);
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(entity.position.getValue())
.height - (next == null ? 0 : next + 1.5),
Cesium.Cartographic.fromCartesian(icon.pos).height -
(next == null ? 0 : next + 1.5),
) < 0.01,
`${entity.id} refreshes at ${next}`,
);
assert.equal(
entity.billboard.heightReference.getValue(),
next == null
? Cesium.HeightReference.CLAMP_TO_GROUND
: Cesium.HeightReference.NONE,
);
assert.equal(entity.gevAlprCanvasPosition, null);
assert.equal(icon.height, next == null ? 'clampGround' : 'absolute');
assert.equal(icon.color, undefined, 'drawn as a badge');
assert.equal(alprMarkers.read(entity)?.canvasPosition, null);
}
assert.equal(
saved.gevAlprNativeAppearance,
null,
'saved appearance restores at the new floor',
alprMarkers.read(saved)?.canvasOwned,
false,
'the badge comes back at the new floor',
);
}
} finally {
@@ -1488,7 +1496,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const h = cameraHarness();
try {
await alprCamerasLayer.update();
const previous = h.source.entities.getById('alpr:42');
const previous = h.marker('alpr:42');
const revision = alprCamerasLayer.getStats().renderRevision;
let release;
h.setFetch(
@@ -1501,7 +1509,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const pending = alprCamerasLayer.update();
await alprCamerasLayer.update();
assert.equal(
h.source.entities.getById('alpr:42'),
h.marker('alpr:42'),
previous,
'do not show an intermediate filtered snapshot while the new query prepares',
);
@@ -1511,7 +1519,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
await pending;
assert.equal(alprCamerasLayer.getStats().renderRevision, revision + 1);
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
h.markers().map((e) => e.id),
['alpr:43'],
);
} finally {
+22 -17
View File
@@ -1,4 +1,10 @@
import * as Cesium from 'cesium';
import {
canvasOf,
findCamera,
findFrame,
findQuery,
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
const YOUTUBE_HOSTS = new Set([
@@ -538,23 +544,22 @@ function ensureProviderConnections(documentRef, provider) {
}
}
/**
* Where an anchor (ECEF) is in the card root, through the renderer's camera
* and query ports; null behind the eye, off the root, or with no renderer.
*/
function anchorOnScreen(viewer, anchor, root) {
if (!viewer?.scene || !anchor || !root) return null;
const camera = viewer.camera;
if (camera?.positionWC && camera?.directionWC) {
const delta = Cesium.Cartesian3.subtract(
anchor,
camera.positionWC,
new Cesium.Cartesian3(),
);
if (Cesium.Cartesian3.dot(delta, camera.directionWC) <= 0) return null;
}
const pixel = Cesium.SceneTransforms.worldToWindowCoordinates(
viewer.scene,
anchor,
);
if (!anchor || !root) return null;
const camera = findCamera(viewer);
const query = findQuery(viewer);
if (!camera || !query) return null;
const pose = camera.pose();
if (dot(sub(anchor, pose.position), pose.direction) <= 0) return null;
const pixel = query.project(anchor);
if (!pixel) return null;
const canvasBounds = viewer.canvas?.getBoundingClientRect?.();
// The renderer's canvas; a viewer with no renderer bound, its own.
const canvas = canvasOf(viewer);
const canvasBounds = canvas?.getBoundingClientRect?.();
const rootBounds = root.getBoundingClientRect?.();
if (!canvasBounds || !rootBounds) return null;
const x = pixel.x + canvasBounds.left - rootBounds.left;
@@ -865,7 +870,7 @@ export function createBhoteKoshiEmbeddedMedia({
}
};
const removePostRender =
viewer.scene?.postRender?.addEventListener?.(position);
findFrame(viewer)?.on('postRender', () => position()) ?? null;
function hide({ immediate = false, preserveWarm = false } = {}) {
if (!preserveWarm) clearWarm();
Loaded 100 of 1502 files, more files were not shown because too many files have changed in this diff. Show more