Merge remote-tracking branch 'origin/main' into feat/alpr-model-specs

This commit is contained in:
German Khokhlov committed 2026-11-19 18:24:38 +04:00
commit 4eacbe67c7
2602 files changed
+251040 -57704

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', () => {
+415 -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,34 @@ 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();
@@ -429,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];
@@ -456,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();
@@ -490,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');
@@ -499,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();
@@ -519,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();
}
@@ -533,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');
@@ -545,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];
@@ -570,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',
);
@@ -590,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 {
@@ -598,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: [
@@ -622,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();
@@ -655,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 {
@@ -673,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: [
@@ -682,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();
@@ -718,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();
@@ -731,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', () => {
+10
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,17 +102,20 @@ 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 } : {}),
@@ -172,6 +180,7 @@ export function createApplicationCatalog({
createApplicationTransit({
surface,
source: sources.transit,
placement: layerPlacement(placement, 'transit'),
displayParams: () => flights.getParams(),
...(resolveAsset ? { resolveAsset } : {}),
}),
@@ -210,6 +219,7 @@ export function createApplicationCatalog({
createApplicationRail({
surface,
source: sources.rail,
placement: layerPlacement(placement, 'rail'),
displayParams: () => flights.getParams(),
...(resolveAsset ? { resolveAsset } : {}),
}),
+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);
+37 -20
View File
@@ -1,21 +1,31 @@
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';
/** Where the camera starts unless a host gives a `startView`. */
export { START_VIEW };
/**
* Construct the existing controls and camera presentation. `initialShareCode`
* 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.
* `homeView` is where the title's logo goes back to (with the clock live): the
* start view unless given, for a host whose `startView` only carries a view
* across a rebuild.
* `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,
@@ -24,16 +34,23 @@ export function createApplicationControls({
defer,
initialShareCode = null,
localePicker = true,
startView = START_VIEW,
homeView = startView,
}) {
// 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: {
...services,
...operations.surface.controlServices,
searchAndFlyTo: operations.searchAndFlyTo,
pickWorldFromScreen: operations.annotationResolver?.pickWorldFromScreen,
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,
@@ -41,32 +58,32 @@ export function createApplicationControls({
// A share code to open at start-up instead of the page's address.
initialShareCode,
localePicker,
homeView,
});
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 -65
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,52 +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;
/**
* 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 its render loop after a render error, and the timer stops
// with it; Retry restarts both. The render failure notice logs the error
// (src/ui/renderFailure.js).
const timer = windowRef.setInterval(() => {
if (
viewer.useDefaultRenderLoop === false ||
now() - lastFrame < MISSED_FRAMES_MS ||
viewer.isDestroyed?.()
)
return;
try {
viewer.resize();
viewer.render();
} catch {
// Raised as a render error by now (src/ui/renderFailure.js), which
// stops this timer; thrown on, it would only reach the host page.
}
}, PANEL_FRAME_MS);
return () => {
windowRef.clearInterval(timer);
windowRef.cancelAnimationFrame(frameRequest);
};
}
const delay = (ms, signal) =>
new Promise((resolve) => {
const timer = setTimeout(resolve, ms);
@@ -152,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),
});
);
});
}
@@ -314,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,
@@ -321,6 +278,7 @@ export function installViews({
dataManager,
run,
signal,
keepRendering = null,
terrain = null,
location = globalThis.location,
windowRef = globalThis.window,
@@ -433,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 -57
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,60 +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 stops drawing while its render loop is stopped', () => {
let tick = null;
const windowRef = {
requestAnimationFrame: () => 1,
cancelAnimationFrame() {},
setInterval: (fn) => ((tick = fn), 1),
clearInterval() {},
};
const drawn = [];
const viewer = { resize() {}, render: () => drawn.push('render') };
let clock = 0;
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
// Cesium stops its render loop after a render error.
viewer.useDefaultRenderLoop = false;
clock = 1000;
tick();
assert.deepEqual(drawn, []);
// Retry restarts it, and the timer draws again.
viewer.useDefaultRenderLoop = true;
tick();
assert.deepEqual(drawn, ['render']);
stop();
});
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();
};
}
+3
View File
@@ -16,9 +16,11 @@ import { fleetModelServices } from './fleetModels.js';
* 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,
@@ -38,6 +40,7 @@ export function createApplicationVessels({
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,
});
}
+428
View File
@@ -0,0 +1,428 @@
import { registerWorldOverlayPaintLane } from '../../overlays/worldOverlay.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import {
earthquakeContourRings,
earthquakeContourScale,
earthquakeContourShape,
earthquakeRippleRings,
EARTHQUAKE_RIPPLE_PERIOD_MS,
} from '../../layers/earthquakes/model.js';
/** Points around each contour line: smooth at the largest disc on screen. */
export const RIPPLE_RING_SEGMENTS = 96;
/** An index contour's width, and every other line's. */
const INDEX_WIDTH_PX = 2;
const LINE_WIDTH_PX = 1.1;
/**
* The overlay lane the lines paint in: the magnitude labels' own. A lane's
* custom painters run before its entries, so the lines sit under the labels
* and under the selected quake's card.
*/
export const RIPPLE_PAINT_LANE = 'ambient-label';
/**
* The selected disc's fill, [offset, alpha] from the epicentre (0) to its
* outer circle (1): strongest in the middle, fading out to nothing at the
* edge.
*/
export const DISC_FADE = Object.freeze([
[0, 0.42],
[0.35, 0.26],
[0.75, 0.1],
[1, 0],
]);
/**
* Each contour wave's fill, out to its own line: clear inside, tinting
* toward the line; times the wave's own fade.
*/
export const WAVE_FADE = Object.freeze([
[0, 0],
[0.55, 0],
[1, 0.2],
]);
/**
* `rgb(r,g,b)` (or `rgba`) as a function of alpha, for gradient stops; any
* other colour keeps its own alpha.
*/
export function cssWithAlpha(color) {
const m = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(String(color));
if (!m) return () => color;
const rgb = `${m[1]},${m[2]},${m[3]}`;
return (alpha) => `rgba(${rgb},${Math.max(0, Math.min(1, alpha))})`;
}
/**
* How many times the lines run out to the edge after a quake is selected
* before they rest as still contours and stop asking for frames: earthquakes
* otherwise hold no render (docs/CURRENT-STATE.md, "Earthquake discs are
* STATIC geometry"), and a quake can stay selected for hours.
*/
export const RIPPLE_ACTIVE_CYCLES = 3;
let reducedMotionQuery;
/**
* The viewer's reduced-motion setting, live: the media query is kept, so a
* change mid-session is read at the next paint and tick.
*/
const reducedMotion = () => {
try {
reducedMotionQuery ??=
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)') ?? null;
return reducedMotionQuery?.matches === true;
} catch {
return false;
}
};
/** How often the rings re-read the ground height under the quake. */
const HEIGHT_READ_INTERVAL_MS = 500;
/**
* A ground height the rings accept, in metres: the Dead Sea shore to above
* Everest. Anything else is a bad sample (a hit on something drawn above
* the ground, or a broken tile), and the rings stay where they are.
*/
const groundHeightOk = (h) => Number.isFinite(h) && h >= -500 && h <= 9000;
/**
* The selected earthquake's contour lines, painted on the world overlay:
* wavy closed lines, shaped by the quake's id (earthquakeContourShape), run
* from the marker out to the disc's edge and fade there, one after another,
* for RIPPLE_ACTIVE_CYCLES runs after a quake is selected and only while it
* is on screen, then rest as still contours. They never cross, and every third is
* a heavier index contour, as on a topographic map. Nothing is drawn, and no
* frame is asked for, while no quake is selected. With reduced motion the
* lines hold still.
*
* A line is drawn in the tangent plane at the epicentre: at the largest
* disc (M6, 64 km) it sits about 320 m above the curved ground at its edge
* (64² / 2R), about 1.5 px off the drawn disc at the 220 km, -45° framing a
* label click flies to (900 px tall, 35° field of view); less for smaller
* quakes, as the offset grows with the square of the radius.
* @param {object} [deps]
* @param {Function} [deps.registerLane] `registerWorldOverlayPaintLane`.
* @param {() => number} [deps.now] Steady clock, ms.
* @param {(cb: Function) => number} [deps.requestFrame]
* @param {(handle: number) => void} [deps.cancelFrame]
* @param {() => boolean} [deps.prefersReducedMotion]
* @returns {{show: Function, hide: Function, dispose: Function}}
*/
export function createEarthquakeRipples({
registerLane = registerWorldOverlayPaintLane,
now = () => globalThis.performance?.now?.() ?? Date.now(),
requestFrame = (cb) => globalThis.requestAnimationFrame?.(cb) ?? null,
cancelFrame = (handle) => globalThis.cancelAnimationFrame?.(handle),
prefersReducedMotion = reducedMotion,
} = {}) {
let lane = null;
let target = null;
let frameHandle = null;
// When the running lines settle into still contours (the selection's
// bound), and whether the last paint found the quake on screen.
let startedAt = 0;
let settlesAt = 0;
let onScreen = false;
/** Whether the lines run now: in the window, and motion allowed. */
const running = () => now() < settlesAt && !prefersReducedMotion();
// Unit offsets around the line in the epicentre's tangent plane, packed
// x, y, z per point: north·cos + east·sin.
const offsets = new Float64Array((RIPPLE_RING_SEGMENTS + 1) * 3);
const angles = new Float64Array(RIPPLE_RING_SEGMENTS + 1);
for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++)
angles[i] = (2 * Math.PI * i) / RIPPLE_RING_SEGMENTS;
// Screen points, reused every frame.
const at = { x: 0, y: 0 };
const centerAt = { x: 0, y: 0 };
const eastAt = { x: 0, y: 0 };
const northAt = { x: 0, y: 0 };
/** Project an ECEF point to CSS pixels; false when it is behind the eye. */
function project(frame, px, py, pz, out) {
const m = frame.viewProjectionMatrix;
const w = m[3] * px + m[7] * py + m[11] * pz + m[15];
if (w <= 0) return false;
out.x =
((m[0] * px + m[4] * py + m[8] * pz + m[12]) / w / 2 + 0.5) * frame.width;
out.y =
(0.5 - (m[1] * px + m[5] * py + m[9] * pz + m[13]) / w / 2) *
frame.height;
return true;
}
/**
* Trace one closed line at `fraction` of the disc's radius (`shaped`:
* as a contour, else the disc's own circle). True when all of it is in
* front of the eye, so it can be filled.
*/
function trace(frame, fraction, shaped) {
const { ctx } = frame;
const center = target.center;
const reach = fraction * target.radiusM;
ctx.beginPath();
let pen = false;
let whole = true;
for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) {
// The last point repeats the first angle, so the line closes.
const r = shaped
? reach * earthquakeContourScale(target.shape, angles[i], fraction)
: reach;
const visible = project(
frame,
center.x + offsets[i * 3] * r,
center.y + offsets[i * 3 + 1] * r,
center.z + offsets[i * 3 + 2] * r,
at,
);
if (!visible) {
pen = false;
whole = false;
continue;
}
if (pen) ctx.lineTo(at.x, at.y);
else ctx.moveTo(at.x, at.y);
pen = true;
}
return whole;
}
/**
* Fill the traced path with a radial gradient laid on the ground: the
* canvas places a path when it is traced and a gradient when it fills, so
* under the disc's ground-to-screen transform the gradient's circle
* becomes the disc's ellipse on screen while the path stays exact.
* @param {Array<[number, number]>} stops [offset, alpha], out to `reach`.
*/
function fillGround(ctx, reach, stops) {
ctx.save();
ctx.transform(
eastAt.x - centerAt.x,
eastAt.y - centerAt.y,
northAt.x - centerAt.x,
northAt.y - centerAt.y,
centerAt.x,
centerAt.y,
);
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, reach);
for (const [offset, alpha] of stops)
gradient.addColorStop(offset, target.rgba(alpha));
ctx.fillStyle = gradient;
ctx.globalAlpha = 1;
ctx.fill();
ctx.restore();
}
/**
* Whether any of the disc is in the viewport: its centre's screen point,
* padded by its larger screen radius (or, seen edge-on, the centre alone).
*/
function discOnScreen(frame, c, e, n) {
if (!Number.isFinite(c.x) || !Number.isFinite(c.y)) return false;
const pad = Math.max(
Math.hypot(e.x - c.x, e.y - c.y) || 0,
Math.hypot(n.x - c.x, n.y - c.y) || 0,
);
return (
c.x + pad >= 0 &&
c.x - pad <= frame.width &&
c.y + pad >= 0 &&
c.y - pad <= frame.height
);
}
/**
* Re-read the ground height under the quake, at most twice a second while
* painting: the ground loads and refines as the camera comes in, and the
* rings move onto it once it differs by more than a metre.
*/
function settleHeight() {
if (!target.heightAt) return;
const at = now();
if (at - target.heightReadAt < HEIGHT_READ_INTERVAL_MS) return;
target.heightReadAt = at;
let height = null;
try {
height = target.heightAt();
} catch {
height = null;
}
if (!groundHeightOk(height) || Math.abs(height - target.heightM) <= 1)
return;
target.heightM = height;
target.center = fromDegrees(target.lon, target.lat, height);
}
function paint(frame) {
if (!target) return;
const { ctx } = frame;
settleHeight();
const center = target.center;
onScreen = false;
if (frame.occluder?.isPointVisible?.(center) === false) return;
const R = target.radiusM;
// The disc's ground frame on screen: its centre, and a radius east and
// north. Seen edge-on (or partly behind the eye) it is not filled.
const centerOk = project(frame, center.x, center.y, center.z, centerAt);
const eastOk = project(
frame,
center.x + target.east.x * R,
center.y + target.east.y * R,
center.z + target.east.z * R,
eastAt,
);
const northOk = project(
frame,
center.x + target.north.x * R,
center.y + target.north.y * R,
center.z + target.north.z * R,
northAt,
);
let fills = centerOk && eastOk && northOk;
if (fills) {
const area =
(eastAt.x - centerAt.x) * (northAt.y - centerAt.y) -
(eastAt.y - centerAt.y) * (northAt.x - centerAt.x);
fills = Math.abs(area) > 1;
}
onScreen =
centerOk &&
discOnScreen(
frame,
centerAt,
eastOk ? eastAt : centerAt,
northOk ? northAt : centerAt,
);
// The disc: strongest at the epicentre, fading out to its outer circle.
if (fills && trace(frame, 1, false)) fillGround(ctx, 1, DISC_FADE);
const animate = running();
const rings = animate
? earthquakeRippleRings(now() - startedAt)
: earthquakeContourRings();
// Brought back into view while the window lasts: run again.
if (animate && onScreen && frameHandle === null && lane)
frameHandle = requestFrame(tick);
ctx.strokeStyle = target.color;
ctx.lineJoin = 'round';
for (const { fraction, alpha, index } of rings) {
if (!(alpha > 0.01)) continue;
const whole = trace(frame, fraction, true);
// Each wave: clear inside, tinting toward its own line, as it fades.
if (fills && whole)
fillGround(
ctx,
fraction,
WAVE_FADE.map(([offset, a]) => [offset, a * alpha]),
);
ctx.lineWidth = index ? INDEX_WIDTH_PX : LINE_WIDTH_PX;
ctx.globalAlpha = alpha;
ctx.stroke();
}
ctx.globalAlpha = 1;
}
/** Ask for one more frame while the lines run (one request at a time). */
function tick() {
frameHandle = null;
if (!target || !lane) return;
// Settled, or out of sight: one last paint draws the still contours
// (or nothing), and no more frames are asked for. A paint that finds it
// on screen again inside the window starts the frames again.
if (!running() || !onScreen) {
lane.requestPaint();
return;
}
lane.requestPaint();
frameHandle = requestFrame(tick);
}
function stopFrames() {
if (frameHandle !== null) cancelFrame(frameHandle);
frameHandle = null;
}
/**
* Run the contour lines around one quake, replacing any other.
* @param {{id: string, lon: number, lat: number, heightM?: number, heightAt?: () => number|null, radiusM: number, color: string}} next
* @param {{restart?: boolean}} [options] `restart: false` updates the
* same quake in place (a feed refresh) without running it again.
*/
function show(next, { restart = true } = {}) {
if (
!next ||
!Number.isFinite(next.lon) ||
!Number.isFinite(next.lat) ||
!(next.radiusM > 0)
) {
hide();
return;
}
const sameQuake = target?.id === next.id;
const lon = (next.lon * Math.PI) / 180;
const lat = (next.lat * Math.PI) / 180;
const [sinLon, cosLon] = [Math.sin(lon), Math.cos(lon)];
const [sinLat, cosLat] = [Math.sin(lat), Math.cos(lat)];
for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) {
const [c, s] = [Math.cos(angles[i]), Math.sin(angles[i])];
offsets[i * 3] = c * -sinLat * cosLon + s * -sinLon;
offsets[i * 3 + 1] = c * -sinLat * sinLon + s * cosLon;
offsets[i * 3 + 2] = c * cosLat;
}
target = {
id: next.id,
// On the ground the disc is draped on: the height known now, then
// re-read while painting (see `settleHeight`), since a label's fly-to
// starts from far away, before that ground has loaded.
lon: next.lon,
lat: next.lat,
heightM: groundHeightOk(next.heightM) ? next.heightM : 0,
heightAt: typeof next.heightAt === 'function' ? next.heightAt : null,
heightReadAt: -Infinity,
center: fromDegrees(
next.lon,
next.lat,
groundHeightOk(next.heightM) ? next.heightM : 0,
),
radiusM: next.radiusM,
color: next.color || 'rgb(255,165,0)',
shape: earthquakeContourShape(next.id),
rgba: cssWithAlpha(next.color || 'rgb(255,165,0)'),
// Angle 0 is north and a quarter turn is east (see `offsets`).
north: { x: offsets[0], y: offsets[1], z: offsets[2] },
east: {
x: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3],
y: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3 + 1],
z: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3 + 2],
},
};
if (restart || !sameQuake) {
startedAt = now();
settlesAt =
startedAt + RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS;
// Assume it is in view until a paint says otherwise.
onScreen = true;
}
lane ??= registerLane(RIPPLE_PAINT_LANE, paint, {
id: 'earthquake-ripples',
});
lane.setActive(true);
lane.requestPaint();
// A refresh while the disc is out of sight asks for no frame; a paint
// that finds it on screen again starts them (a restart sets onScreen).
if (running() && onScreen && frameHandle === null)
frameHandle = requestFrame(tick);
}
function hide() {
stopFrames();
if (!target) return;
target = null;
lane?.setActive(false);
}
function dispose() {
hide();
lane?.unregister();
lane = null;
}
return { show, hide, dispose };
}
+452
View File
@@ -0,0 +1,452 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
DISC_FADE,
cssWithAlpha,
RIPPLE_ACTIVE_CYCLES,
RIPPLE_PAINT_LANE,
RIPPLE_RING_SEGMENTS,
createEarthquakeRipples,
} from './earthquakeRipples.js';
import {
EARTHQUAKE_RIPPLE_PERIOD_MS,
EARTHQUAKE_RIPPLE_RINGS,
} from '../../layers/earthquakes/model.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
/** A paint lane, frame clock and canvas the test steps by hand. */
function harness({ reducedMotion = false } = {}) {
let motionReduced = reducedMotion;
const lanes = [];
const frames = new Map();
let nextFrame = 1;
let clock = 0;
const ripples = createEarthquakeRipples({
registerLane(laneId, painter, options) {
const lane = {
laneId,
painter,
options,
active: false,
paints: 0,
unregistered: false,
setActive(next) {
lane.active = next;
},
requestPaint() {
lane.paints++;
},
unregister() {
lane.unregistered = true;
},
};
lanes.push(lane);
return lane;
},
now: () => clock,
requestFrame(cb) {
const handle = nextFrame++;
frames.set(handle, cb);
return handle;
},
cancelFrame: (handle) => frames.delete(handle),
prefersReducedMotion: () => motionReduced,
});
const strokes = [];
const fills = [];
let path = null;
const ctx = {
globalAlpha: 1,
beginPath() {
path = { moves: 0, lines: 0 };
},
moveTo() {
path.moves++;
},
lineTo() {
path.lines++;
},
stroke() {
strokes.push({
...path,
alpha: ctx.globalAlpha,
color: ctx.strokeStyle,
width: ctx.lineWidth,
});
},
// Fills record their path, gradient and the transform they fill under.
saved: 0,
transformed: null,
save() {
ctx.saved++;
},
restore() {
ctx.saved--;
ctx.transformed = null;
},
transform(...args) {
ctx.transformed = args;
},
createRadialGradient(...circles) {
const gradient = { circles, stops: [] };
gradient.addColorStop = (offset, color) =>
gradient.stops.push([offset, color]);
return gradient;
},
fill() {
fills.push({
...path,
gradient: ctx.fillStyle,
transform: ctx.transformed,
});
},
};
// w = 1 everywhere: every point is in front of the eye.
const matrix = new Float64Array(16);
matrix[0] = 1e-7;
matrix[5] = 1e-7;
matrix[15] = 1;
const frame = (visible = true) => ({
ctx,
width: 800,
height: 600,
viewProjectionMatrix: matrix,
occluder: { isPointVisible: () => visible },
});
return {
ripples,
lanes,
frames,
strokes,
fills,
frame,
matrix,
setReducedMotion(next) {
motionReduced = next;
},
advance(ms) {
clock += ms;
},
/** Run the pending animation frames once. */
step() {
const pending = [...frames.entries()];
frames.clear();
for (const [, cb] of pending) cb();
},
};
}
const target = {
id: 'ak1',
lon: -153.3,
lat: 60,
radiusM: 32000,
color: 'rgb(255,0,0)',
};
test('nothing is registered or animated until a quake is selected', () => {
const h = harness();
assert.equal(h.lanes.length, 0);
assert.equal(h.frames.size, 0);
h.ripples.hide();
assert.equal(h.frames.size, 0);
});
test('a selected quake animates one ring set, one frame request at a time', () => {
const h = harness();
h.ripples.show(target);
const [lane] = h.lanes;
assert.equal(lane.laneId, RIPPLE_PAINT_LANE);
assert.equal(RIPPLE_PAINT_LANE, 'ambient-label', 'under the labels');
assert.equal(lane.active, true);
assert.equal(h.frames.size, 1);
h.ripples.show({ ...target, id: 'ak2' });
assert.equal(h.lanes.length, 1, 'the lane is reused');
assert.equal(h.frames.size, 1, 'still one frame loop');
const before = lane.paints;
h.step();
h.step();
assert.equal(lane.paints, before + 2, 'one repaint per frame');
assert.equal(h.frames.size, 1);
h.advance(600);
lane.painter(h.frame());
// At 600 ms every line is between the marker and the edge, so all draw.
assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS);
assert.deepEqual(
h.strokes.map((stroke) => stroke.width),
[2, 1.1, 1.1, 2, 1.1, 1.1],
'every third line is an index contour',
);
for (const stroke of h.strokes) {
assert.equal(stroke.moves, 1, 'one unbroken ring');
assert.equal(stroke.lines, RIPPLE_RING_SEGMENTS);
assert.equal(stroke.color, 'rgb(255,0,0)');
assert.ok(stroke.alpha > 0 && stroke.alpha <= 1);
}
h.ripples.hide();
assert.equal(lane.active, false);
assert.equal(h.frames.size, 0, 'no frames asked for once hidden');
h.strokes.length = 0;
lane.painter(h.frame());
assert.equal(h.strokes.length, 0);
});
test('rings are skipped behind the globe and broken behind the eye', () => {
const h = harness();
h.ripples.show(target);
h.advance(600);
const [lane] = h.lanes;
lane.painter(h.frame(false));
assert.equal(h.strokes.length, 0, 'epicentre over the horizon');
// Points with negative x fall behind the eye: each ring breaks there.
const frame = h.frame();
frame.viewProjectionMatrix[3] = 1e-6;
const center = fromDegrees(target.lon, target.lat);
frame.viewProjectionMatrix[15] = -1e-6 * center.x;
lane.painter(frame);
assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS);
for (const stroke of h.strokes)
assert.ok(stroke.lines < RIPPLE_RING_SEGMENTS, 'part of each ring hidden');
});
test('reduced motion draws still contour rings and asks for no frames', () => {
const h = harness({ reducedMotion: true });
h.ripples.show(target);
assert.equal(h.frames.size, 0);
assert.equal(h.lanes[0].paints, 1, 'painted once');
h.lanes[0].painter(h.frame());
assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS);
assert.ok(h.strokes.every((stroke) => stroke.alpha === 0.7));
});
test('an unusable target hides the rings; dispose releases the lane', () => {
const h = harness();
h.ripples.show(target);
h.ripples.show({ ...target, radiusM: 0 });
assert.equal(h.lanes[0].active, false);
assert.equal(h.frames.size, 0);
h.ripples.dispose();
assert.equal(h.lanes[0].unregistered, true);
// Shown again after dispose, it registers a fresh lane.
h.ripples.show(target);
assert.equal(h.lanes.length, 2);
h.ripples.dispose();
});
test('contour lines are wavy, the same for a quake every time, and inside the disc', () => {
const h = harness();
h.ripples.show(target);
h.advance(600);
// An identity-like projection: screen x, y follow ECEF y, z, so the
// distance from the projected epicentre measures each point's radius.
const frame = h.frame();
const m = frame.viewProjectionMatrix;
m[0] = 0;
m[5] = 0;
m[4] = 1e-6;
m[9] = 1e-6;
const points = [];
const ctx = frame.ctx;
const record = (x, y) => points.at(-1).push([x, y]);
ctx.beginPath = () => points.push([]);
ctx.moveTo = record;
ctx.lineTo = record;
ctx.stroke = () => {};
h.lanes[0].painter(frame);
const center = fromDegrees(target.lon, target.lat);
const cx = (center.y * 1e-6 * 0.5 + 0.5) * 800;
const cy = (0.5 - center.z * 1e-6 * 0.5) * 600;
const spread = (line) => {
const radii = line.map(([x, y]) => Math.hypot(x - cx, y - cy));
return Math.max(...radii) / Math.min(...radii);
};
// The disc's outer circle first (filled, not stroked), then each line.
assert.equal(points.length, EARTHQUAKE_RIPPLE_RINGS + 1);
points.shift();
assert.ok(
points.every((line) => spread(line) > 1.05),
'not circles: each line dents in and out',
);
for (const line of points) {
const [first, last] = [line[0], line.at(-1)];
assert.ok(
Math.hypot(first[0] - last[0], first[1] - last[1]) < 1e-6,
'closed',
);
}
});
test('the disc fades out to its outer circle; each wave fills with a fade', () => {
const h = harness();
h.ripples.show(target);
h.advance(600);
// A projection where east and north span the screen: the disc is seen
// from above, so its ground frame can be filled.
const frame = h.frame();
const m = frame.viewProjectionMatrix;
m[0] = 0;
m[5] = 0;
m[4] = 1e-6;
m[9] = 1e-6;
h.lanes[0].painter(frame);
assert.equal(h.fills.length, 1 + EARTHQUAKE_RIPPLE_RINGS);
const [disc, ...waves] = h.fills;
assert.equal(disc.lines, RIPPLE_RING_SEGMENTS, 'the whole outer circle');
assert.deepEqual(disc.gradient.circles, [0, 0, 0, 0, 0, 1]);
assert.deepEqual(
disc.gradient.stops,
DISC_FADE.map(([offset, alpha]) => [offset, `rgba(255,0,0,${alpha})`]),
);
assert.equal(disc.gradient.stops.at(-1)[1], 'rgba(255,0,0,0)', 'fades out');
assert.ok(disc.transform, 'filled under the ground-to-screen transform');
assert.equal(h.fills.length, waves.length + 1);
for (const wave of waves) {
const reach = wave.gradient.circles[5];
assert.ok(reach > 0 && reach < 1, 'out to its own line');
assert.equal(wave.gradient.stops[0][1], 'rgba(255,0,0,0)', 'clear inside');
}
// The transforms were undone: nothing leaks into the labels' painting.
assert.equal(frame.ctx.saved, 0);
// Seen edge-on, the ground frame has no area: lines only, no fills.
h.fills.length = 0;
m[9] = 0;
m[5] = 0;
h.lanes[0].painter(frame);
assert.equal(h.fills.length, 0);
});
test('cssWithAlpha turns rgb into rgba stops', () => {
assert.equal(cssWithAlpha('rgb(255,165,0)')(0.25), 'rgba(255,165,0,0.25)');
assert.equal(cssWithAlpha('rgba(1, 2, 3, 0.5)')(2), 'rgba(1,2,3,1)');
assert.equal(cssWithAlpha('red')(0.3), 'red');
});
test('the lines run a bounded time after a selection, then rest without frames', () => {
const h = harness();
h.ripples.show(target);
const [lane] = h.lanes;
const window = RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS;
assert.ok(window <= 15_000, 'about a quarter of a minute at most');
let frames = 0;
for (let t = 0; t < window * 3; t += 16) {
if (!h.frames.size) break;
lane.painter(h.frame());
h.advance(16);
h.step();
frames++;
}
assert.equal(h.frames.size, 0, 'no frame asked for once settled');
assert.ok(frames <= Math.ceil(window / 16) + 2, `bounded: ${frames} frames`);
// At rest the lines hold still as readable contours.
h.strokes.length = 0;
lane.painter(h.frame());
assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS);
assert.ok(h.strokes.every((stroke) => stroke.alpha === 0.7));
// A parked camera repainting the overlay does not start them again.
lane.painter(h.frame());
assert.equal(h.frames.size, 0);
// A new selection runs again.
h.ripples.show({ ...target, id: 'ak2' });
assert.equal(h.frames.size, 1);
h.ripples.dispose();
});
test('off screen the frames stop; back in view inside the window they resume', () => {
const h = harness();
h.ripples.show(target);
const [lane] = h.lanes;
// Behind the globe.
lane.painter(h.frame(false));
const paints = lane.paints;
h.step();
assert.equal(h.frames.size, 0, 'stopped while out of sight');
assert.equal(lane.paints, paints + 1, 'one last paint, then none');
h.step();
assert.equal(lane.paints, paints + 1);
// Panned away: the disc is far off the viewport.
h.ripples.show(target);
const away = h.frame();
away.viewProjectionMatrix[12] = 50;
lane.painter(away);
h.step();
assert.equal(h.frames.size, 0);
// The camera brings it back while the window lasts.
away.viewProjectionMatrix[12] = 0;
lane.painter(h.frame());
assert.equal(h.frames.size, 1, 'resumed');
h.ripples.dispose();
});
test('turning reduced motion on mid-run stills the lines and stops the frames', () => {
const h = harness();
h.ripples.show(target);
const [lane] = h.lanes;
lane.painter(h.frame());
h.setReducedMotion(true);
h.step();
assert.equal(h.frames.size, 0);
h.strokes.length = 0;
lane.painter(h.frame());
assert.ok(
h.strokes.every((stroke) => stroke.alpha === 0.7),
'still',
);
// Turned off again within the window: the next paint runs them again.
h.setReducedMotion(false);
lane.painter(h.frame());
assert.equal(h.frames.size, 1);
h.ripples.dispose();
});
test('a refresh of the same quake does not run a settled selection again', () => {
const h = harness();
h.ripples.show(target);
const [lane] = h.lanes;
h.advance(RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS + 1);
lane.painter(h.frame());
h.step();
assert.equal(h.frames.size, 0, 'settled');
h.ripples.show({ ...target, radiusM: 40000 }, { restart: false });
assert.equal(h.frames.size, 0, 'a refresh keeps it at rest');
lane.painter(h.frame());
assert.equal(h.frames.size, 0);
// A different quake, or a user's restart, runs again.
h.ripples.show({ ...target, id: 'other' }, { restart: false });
assert.equal(h.frames.size, 1);
h.ripples.dispose();
});
// The rings sit on the ground the disc is draped on. A label's fly-to starts
// far away, before that ground loads, so the painter reads the height again
// while it paints and moves the rings onto it.
test('the rings move onto the ground height once it loads', () => {
const h = harness();
let ground = null;
h.ripples.show({ ...target, heightM: 0, heightAt: () => ground });
h.advance(600);
const [lane] = h.lanes;
lane.painter(h.frame());
const atSea = h.fills.at(-1).transform;
h.fills.length = 0;
ground = 4000;
h.advance(600);
lane.painter(h.frame());
const onGround = h.fills.at(-1).transform;
assert.notDeepEqual(onGround, atSea, 'the centre moved up onto the ground');
// A change of a metre or less, or an impossible height, leaves them put.
for (const next of [4000.5, 25000, -2000]) {
ground = next;
h.advance(600);
lane.painter(h.frame());
assert.deepEqual(h.fills.at(-1).transform, onGround, String(next));
}
// Reads are bounded: a second paint within the interval does not ask again.
let reads = 0;
h.ripples.show({ ...target, id: 'ak2', heightAt: () => (reads++, 4000) });
lane.painter(h.frame());
lane.painter(h.frame());
assert.equal(reads, 1);
});
+45 -2
View File
@@ -1,6 +1,49 @@
import { createEarthquakesLayer } from '../../layers/earthquakes/index.js';
import { overlayHost } from './overlayHost.js';
/** Wire earthquake observations to the application overlay host. */
import { inputFor } from '../../input/dispatcher.js';
import * as picking from '../../data/pickRegistry.js';
import * as context from '../../data/contextStore.js';
import { isPointerFree } from '../../data/inputOwnership.js';
import { requestWorldFocus } from '../../worldFocus.js';
import { createEarthquakeRipples } from './earthquakeRipples.js';
import { heightsOf } from '../../queries/heights.js';
import { formatDate, formatNumber, t } from '../../i18n/index.js';
const EVENT_TIME = Object.freeze({
day: 'numeric',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
timeZone: 'UTC',
timeZoneName: 'short',
});
/** The clicked quake's card text, in the page's language. */
export const earthquakeCardText = Object.freeze({
t,
formatTime: (time) => formatDate(time, EVENT_TIME),
formatDepth: (km) => formatNumber(km, { maximumFractionDigits: 1 }),
});
/**
* Wire earthquake observations to the application overlay host, and its
* discs to the globe's clicks: a clicked quake shows its detail card.
*/
export function createApplicationEarthquakes(options) {
return createEarthquakesLayer({ overlayHost, ...options });
return createEarthquakesLayer({
overlayHost,
input: (viewer) => inputFor(viewer),
picking,
context,
pointer: { isPointerFree },
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
focus: { requestWorldFocus },
ripples: createEarthquakeRipples(),
// The loaded ground (terrain or tiles) the clamped disc is draped on.
groundHeight: (viewer, lon, lat) =>
viewer ? heightsOf(viewer).now({ lon, lat }) : null,
text: earthquakeCardText,
...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)),
});
}
+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,
});
}
+4 -3
View File
@@ -4,7 +4,6 @@ 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,
@@ -16,13 +15,15 @@ import {
* ground floor, the same floor Transit and the aircraft stand on.
* `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under
* which nearby trains are drawn as fleet models.
* @param {{surface: object, source?: object,
* `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,
placement = null,
displayParams = null,
resolveAsset,
}) {
@@ -36,6 +37,7 @@ export function createApplicationRail({
sprites,
picking,
overlays,
placement,
credits: { registerDynamicCredit, railFeedCredit },
ground: {
GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M,
@@ -49,7 +51,6 @@ export function createApplicationRail({
camera: {
framing: WORLD_FOCUS_FRAMING.train,
requestWorldFocus,
applyTrackedCameraFrame,
isCockpitActive: () =>
globalThis.document?.body?.classList?.contains('cockpit-mode') ===
true,
+2 -1
View File
@@ -2,11 +2,12 @@ import { createRocketLaunchesLayer } from '../../layers/launches/index.js';
import * as geometry from '../../celestialRing.js';
import * as overlays from '../../overlays/worldOverlay.js';
import * as render from '../../renderGovernor.js';
import * as picking from '../../data/pickRegistry.js';
/** Construct one layer using the application scene owners and a supplied source. */
export function createApplicationLaunches({ source, satellites }) {
return createRocketLaunchesLayer({
source,
services: { satellites, geometry, overlays, render },
services: { satellites, geometry, overlays, render, picking },
});
}
-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 },
});
}
+2 -3
View File
@@ -1,12 +1,11 @@
import * as Cesium from 'cesium';
import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js';
import { overlayHost } from './overlayHost.js';
import * as picking from '../../data/pickRegistry.js';
/** Wire cable source geometry to the application overlay host. */
export function createApplicationCables(options) {
return createSubmarineCableLayer({
overlayHost,
screenSpaceEventHandlerFactory: (canvas) =>
new Cesium.ScreenSpaceEventHandler(canvas),
picking,
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
...options,
});
+4 -1
View File
@@ -23,13 +23,15 @@ import {
* `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under
* which nearby vehicles are drawn as fleet models.
*
* @param {{surface: object, source?: object,
* `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,
placement = null,
displayParams = null,
resolveAsset,
}) {
@@ -43,6 +45,7 @@ export function createApplicationTransit({
sprites,
picking,
overlays,
placement,
credits: { registerDynamicCredit, transitFeedCredit },
ground: {
GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M,
-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;
}
});
+16 -4
View File
@@ -1,11 +1,13 @@
// 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).
// 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 './embed.js';
import { renderLoopFixture } from '../ui/renderLoopFixture.mjs';
import { keepPanelRendering } from './panelRendering.js';
import { renderLoopFixture } from '../render/cesium/renderLoopFixture.mjs';
import { createSceneFrame } from '../render/cesium/frame.js';
function setup() {
let tick = null;
@@ -23,6 +25,7 @@ function setup() {
const scene = {
renderError: new Cesium.Event(),
preUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
requestRender() {},
initializeFrame() {},
@@ -46,7 +49,16 @@ function setup() {
},
notice: { allowReload: false },
});
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
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;
+158 -40
View File
@@ -1,28 +1,67 @@
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 { trackCreditLineHeight } from '../ui/creditLineHeight.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 { installRenderFailureNotice } from '../ui/renderFailure.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,
@@ -49,58 +88,119 @@ 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,
// The render failure notice below replaces Cesium's dead-end panel.
showRenderLoopErrors: false,
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();
}
}
});
// An inline panel must not reload or navigate its host's page.
defer(
installRenderFailureNotice(viewer, { allowReload: !isEmbeddedInline() }),
);
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));
// The HUD corners above the line clear it when it wraps.
defer(trackCreditLineHeight(document));
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) {
@@ -117,7 +217,7 @@ export async function createApplicationScene({
},
);
}
viewer.scene.globe.show = true;
renderer.globe.setGlobeVisible(true);
}
loaderStatus.textContent = t('Initializing systems...');
@@ -125,6 +225,7 @@ export async function createApplicationScene({
const mapStackController = new MapController(viewer, {
requestRender: governorRequestRender,
...mapOptions,
engine,
googleTileset: tileset,
cesiumToken,
initialStack: tileset ? 'photoreal' : 'esri-imagery',
@@ -146,5 +247,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);
});
+155 -88
View File
@@ -1,3 +1,11 @@
import { onFollowChanged } from '../data/followed.js';
import {
bootStories,
stopVoiceForStories,
storiesOpener,
} from '../stories/boot.js';
import { t } from '../i18n/index.js';
import { useStoriesStore } from '../ui/stores/stories.js';
import { SceneDirector } from '../scenes/director.js';
import { initAnnotations } from '../annotations/index.js';
import { initDrawTool } from '../annotations/drawTool.js';
@@ -17,6 +25,7 @@ import { createLibraryBrowser } from '../ui/libraryBrowser.js';
import { useDataLibraryStore } from '../ui/stores/dataLibrary.js';
import { localGeoJsonServices } from './localGeojsonServices.js';
import { initGevVoiceCommands } from '../voice/gevRealtime.js';
import { isStoriesOpen } from '../voice/realtimeInputPolicy.js';
import { installViews, isEmbeddedInline } from './embed.js';
import {
installScopeMask,
@@ -24,17 +33,29 @@ 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).
* `library.fetchTile` and `library.fetchData` fetch the Data Library's tiles
* and proxied datasets in place of the defaults (`createLibrarySource`).
* `library.fetchImpl` asks the library server (its catalog) in place of the
* page's fetch, for a server that wants the application's own credentials.
* `library.requireCatalog` offers only what the server's library catalog
* names, and nothing while it does not answer. `library: false` leaves the
* Data Library out: no catalog is asked, and no Browse button is drawn.
*/
export function createApplicationTools({
scene,
controls,
@@ -46,14 +67,15 @@ export function createApplicationTools({
onSceneDirector,
sceneDataPacks,
drawMarkActions = [],
library = {},
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,
});
@@ -70,6 +92,26 @@ export function createApplicationTools({
}),
);
onSceneDirector?.(sceneDirector);
// Stories: GEV scenes on this globe, from a Stories button. Its screens,
// styles, story data and controller load on first use.
const storiesStore = useStoriesStore(applicationPinia());
let voiceCommands;
const stories = bootStories({
// Inline in a host page, the URL and history are the host's.
available: !isEmbeddedInline(),
viewer,
director: sceneDirector,
store: storiesStore,
onEnter: () => {
if (stopVoiceForStories(voiceCommands?.session))
storiesStore.flashToast(t('Voice is disabled in Stories.'), 4000);
},
onLoadFailed: () =>
styleManager._showToast?.(
t('Stories could not load. Check the connection and try again.'),
),
});
defer(() => stories.destroy());
const annotations = initAnnotations({
viewer,
tileset,
@@ -114,51 +156,60 @@ export function createApplicationTools({
connect: connectDisplay,
});
defer(() => geoFileImport?.destroy());
// DATA ▸ Library: entries register their layers only when a viewer adds
// them, after the core catalog is sealed. The browser dialog and the
// controller share the application lifetime.
const dataLibrary = createDataLibrary({
dataManager,
services: localGeoJsonServices,
getTileset: () => tileset,
mapStackController,
shareLink: styleManager.shareLinkManager,
requestRender: governorRequestRender,
// Zoom to layer: an immediate navigation, so Cockpit can refuse it and
// the current follow owner is released first (as for imported files).
zoomTo: (extent) =>
styleManager.runImmediateNavigation('layer', () =>
flyToLibraryExtent(viewer, extent),
) !== false,
});
defer(() => dataLibrary.destroy());
// Browse: the owner presents the dialog through the store; LayerPanelsView
// draws the Browse button and the dialog from it.
const libraryStore = useDataLibraryStore(applicationPinia());
const libraryBrowser = createLibraryBrowser({
library: dataLibrary,
publish: (view) => libraryStore.publish(view),
});
libraryStore.connect(libraryBrowser.controls);
defer(() => {
libraryBrowser.destroy();
libraryStore.connect(null);
});
dataLibrary.start({ signal }).catch((error) => {
if (!signal?.aborted) console.warn('[Library] start failed:', error);
});
// The live gate's handle (scripts/qa-data-library.mjs).
const libraryHandle = {
library: dataLibrary,
browser: libraryBrowser,
// What Copy Link would copy.
buildShareLink: () => styleManager.shareLinkManager?.buildLink?.() ?? null,
};
window.__gevDataLibrary = libraryHandle;
defer(() => {
if (window.__gevDataLibrary === libraryHandle)
delete window.__gevDataLibrary;
});
if (library !== false) {
// DATA ▸ Library: entries register their layers only when a viewer adds
// them, after the core catalog is sealed. The browser dialog and the
// controller share the application lifetime.
const dataLibrary = createDataLibrary({
dataManager,
services: localGeoJsonServices,
getTileset: () => tileset,
mapStackController,
shareLink: styleManager.shareLinkManager,
requestRender: governorRequestRender,
// An application's own tile and dataset fetches, when it keeps them in
// its own cache.
fetchImpl: library.fetchImpl ?? undefined,
fetchTile: library.fetchTile ?? null,
fetchData: library.fetchData ?? null,
requireCatalog: library.requireCatalog === true,
// Zoom to layer: an immediate navigation, so Cockpit can refuse it and
// the current follow owner is released first (as for imported files).
zoomTo: (extent) =>
styleManager.runImmediateNavigation('layer', () =>
flyToLibraryExtent(viewer, extent),
) !== false,
});
defer(() => dataLibrary.destroy());
// Browse: the owner presents the dialog through the store; LayerPanelsView
// draws the Browse button and the dialog from it.
const libraryStore = useDataLibraryStore(applicationPinia());
const libraryBrowser = createLibraryBrowser({
library: dataLibrary,
publish: (view) => libraryStore.publish(view),
});
libraryStore.connect(libraryBrowser.controls);
defer(() => {
libraryBrowser.destroy();
libraryStore.connect(null);
});
dataLibrary.start({ signal }).catch((error) => {
if (!signal?.aborted) console.warn('[Library] start failed:', error);
});
// The live gate's handle (scripts/qa-data-library.mjs).
const libraryHandle = {
library: dataLibrary,
browser: libraryBrowser,
// What Copy Link would copy.
buildShareLink: () =>
styleManager.shareLinkManager?.buildLink?.() ?? null,
};
window.__gevDataLibrary = libraryHandle;
defer(() => {
if (window.__gevDataLibrary === libraryHandle)
delete window.__gevDataLibrary;
});
}
// DATA ▸ Recent Imagery: the box tool claims the pointer like Draw and the
// panel lives on the right rail, so both belong to the application
// lifetime. The tileset lets the layer drape while the globe is hidden.
@@ -198,19 +249,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 +271,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 +283,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();
@@ -254,26 +305,40 @@ export function createApplicationTools({
// loop burning behind a hidden tab. (perf wave 2 fix)
syncVisibilitySuspension();
window.__godsEyeView = {
viewer,
styleManager,
tileset,
dataManager,
sceneDirector,
mapStackController,
annotations,
weatherEffects,
cockpitCloudEffects,
getRenderGovernorDiagnostics,
surfaceServices: operations.surface,
requestRender: governorRequestRender,
};
window.__godsEyeView = Object.defineProperties(
{
viewer,
styleManager,
tileset,
dataManager,
sceneDirector,
mapStackController,
annotations,
weatherEffects,
cockpitCloudEffects,
getRenderGovernorDiagnostics,
surfaceServices: operations.surface,
requestRender: governorRequestRender,
entityRecords: { read: readEntityRecord, write: entityRecord },
},
// What the renderer's plugin lets QA scripts read (the Cesium viewer and
// its photoreal tileset, for the default renderer), in place of the
// scene's objects above; read as they are when asked.
Object.getOwnPropertyDescriptors(scene.qaHandles ?? {}),
);
const debug = window.__godsEyeView;
defer(() => {
if (window.__godsEyeView === debug) delete window.__godsEyeView;
});
const voiceCommands = initGevVoiceCommands({
voiceCommands = initGevVoiceCommands({
...voice,
canStartVoice: () => !isStoriesOpen(),
// An app may supply what open_stories does; the Stories page by default.
openStories: storiesOpener({
openStories: voice?.openStories,
store: storiesStore,
stories,
}),
floorServices: operations.surface.groundFloor,
annotationResolver: operations.annotationResolver,
searchNavigation: operations.searchAndFlyTo,
@@ -299,11 +364,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,
-444
View File
@@ -1,444 +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. `showRenderLoopErrors`
* false leaves render errors to the caller's own notice instead of Cesium's
* panel.
*/
export function applicationViewerOptions(
creditContainer,
{ showRenderLoopErrors = true } = {},
) {
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 } },
showRenderLoopErrors,
};
}
/** Create the standard globe viewer in caller-owned, visible containers. */
export function createApplicationViewer({
container,
creditContainer,
showRenderLoopErrors,
}) {
if (!container || !creditContainer)
throw new TypeError('Viewer and credit containers are required');
const viewer = new Cesium.Viewer(
container,
applicationViewerOptions(creditContainer, { showRenderLoopErrors }),
);
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);
});
+18 -16
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,14 +399,15 @@ 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, [
'clickCard?.(event)',
'selectAndFocusVessel(carded)',
"isOwnedByOtherLayer('ais-live-vessels', pickedId)",
'_vesselOverlayHost.hitTest?.(',
'selectAndFocusVessel(record)',
], 'vessel sibling ownership');
], 'vessel card on top, then sibling ownership');
const vesselFocus = body(
vessels,
/function selectAndFocusVessel\(record\) \{([\s\S]*?)\n \}/,
@@ -415,12 +416,13 @@ 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, [
'isOwnedByOtherLayer(id, pickedId)',
'overlayHost.hitTest?.(',
'clickCard?.(event)',
'selectAndFocusFire(carded)',
], 'fire sibling ownership');
'isOwnedByOtherLayer(id, pickedId)',
'clearFireSelection()',
], 'fire card on top, then sibling ownership');
});
+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(
+56 -33
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,
@@ -601,7 +595,7 @@ test('Cockpit Display portal retains both scroll owners across round trips', ()
const portal = CockpitDisplayPortal.toString();
assert.match(
portal,
/this\.standardScrollTop =\s*displayPanelScroller\(standardPanel\)\?\.scrollTop \|\| 0/,
/this\.standardScrollTop = standardPanel\?\.scrollTop \|\| 0/,
);
assert.match(
portal,
@@ -609,7 +603,7 @@ test('Cockpit Display portal retains both scroll owners across round trips', ()
);
assert.match(
portal,
/if \(!this\.active\)[\s\S]*?this\.standardScrollTop =\s*displayPanelScroller\(standardPanel\)\.scrollTop/,
/if \(!this\.active\)[\s\S]*?this\.standardScrollTop = standardPanel\.scrollTop/,
);
assert.match(
portal,
@@ -617,7 +611,7 @@ test('Cockpit Display portal retains both scroll owners across round trips', ()
);
assert.match(
portal,
/this\.cockpitPanel\.scrollTop = this\.cockpitScrollTop[\s\S]*?displayPanelScroller\(this\.standardPanel\)\.scrollTop =\s*this\.standardScrollTop/,
/this\.cockpitPanel\.scrollTop = this\.cockpitScrollTop[\s\S]*?this\.standardPanel\.scrollTop = this\.standardScrollTop/,
);
});
@@ -686,6 +680,7 @@ test('fresh Cockpit entry temporarily collapses map panels and exit restores the
'scene-panel',
'pp-toggles',
'global-context-panel',
'space-missions-panel',
'radio-panel',
]) {
assert.match(
@@ -811,18 +806,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 +1174,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 +1197,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],
@@ -1255,14 +1262,15 @@ test('Global Context uses its dedicated right rail without a duplicate Data Laye
);
assert.match(html, /id="global-context-panel"/);
assert.match(html, /id="global-context-flights-btn"/);
assert.match(html, /id="global-context-missions-btn"/);
assert.doesNotMatch(html, /id="global-context-missions-btn"/);
assert.match(html, /id="space-missions-panel"/);
});
test('Global Context standby describes both chooser modes', () => {
test('Global Context standby describes Contacts', () => {
const match = html.match(/<div id="context-mode-standby"[\s\S]*?<\/div>/);
assert.ok(match, 'Global Context standby is missing');
assert.match(match[0], /CONTACTS — nearest planes · vessels · sites/);
assert.match(match[0], /SPACE MISSIONS — launches &amp; orbital assets/);
assert.doesNotMatch(match[0], /SPACE MISSIONS/);
});
test('cockpit briefing cycle control keeps its state as the accessible name', () => {
@@ -1408,15 +1416,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;
}
+8 -5
View File
@@ -58,12 +58,15 @@ export function cockpitAnchorCorrectionStep(
return Math.min(distanceM, eased, correctionRateMps * dt);
}
/** How late past its interval an update may come and still count in full. */
const COCKPIT_SUBJECT_LATE_SEC = 1;
/**
* 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.
* its interval plus COCKPIT_SUBJECT_LATE_SEC. A subject updated every 500 ms,
* or a browser drawing 5 frames a second, then keeps up, while a long stall
* (a hidden tab) counts as one late update.
* @param {number} elapsedMs Time since the last camera update.
* @param {number} intervalMs The subject's update interval (0: every frame).
* @returns {number}
@@ -75,7 +78,7 @@ export function cockpitSubjectStepSec(elapsedMs, intervalMs) {
const intervalSec = Number.isFinite(intervalMs)
? Math.max(0, intervalMs) / 1000
: 0;
return Math.min(intervalSec + 0.1, elapsedSec);
return Math.min(intervalSec + COCKPIT_SUBJECT_LATE_SEC, elapsedSec);
}
/** Return whether a throttled cockpit presentation update is due. */
@@ -412,7 +415,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.
+146 -5
View File
@@ -31,6 +31,7 @@ import {
speedRulerStep,
speedRulerTicks,
} from './cockpitMath.js';
import { bandBesideMidpointObstacles } from './ui/panelRailGeometry.js';
test('cockpit presentation updates are throttled independently of camera frames', () => {
assert.equal(cockpitUiUpdateDue(1000, 0, 100), true);
@@ -73,12 +74,15 @@ 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);
// Slow frames (5 a second) count in full...
assert.equal(cockpitSubjectStepSec(200, 50), 0.2);
assert.equal(cockpitSubjectStepSec(1000, 0), 1);
// ...and a hidden tab's minutes as one late update.
assert.equal(cockpitSubjectStepSec(60_000, 500), 1.5);
assert.equal(cockpitSubjectStepSec(60_000, 0), 1);
assert.equal(cockpitSubjectStepSec(-5, 500), 0);
assert.equal(cockpitSubjectStepSec(Number.NaN, 500), 0);
assert.equal(cockpitSubjectStepSec(1000, Number.NaN), 0.1);
assert.equal(cockpitSubjectStepSec(1000, Number.NaN), 1);
});
test('cockpit camera clearance never falls below the rendered ground floor', () => {
@@ -283,6 +287,143 @@ test('HUD rail layout constrains an oversized panel to the safe corridor', () =>
assert.equal(layout.constrained, true);
});
test('HUD rail layout keeps a short window clear of an obstacle across its midpoint', () => {
// 480px window: midpoint 240. Each obstacle is neither wholly above nor
// wholly below the midpoint, and must still limit the band.
const above = resolveHudRailLayout({
viewportHeight: 480,
panelHeight: 120,
laneLeft: 20,
laneRight: 340,
baseTop: 40,
baseBottom: 460,
gap: 10,
obstacles: [{ left: 0, right: 400, top: 200, bottom: 300 }],
});
// Room above: 200 - 10 - 40 = 150; below: 460 - 310 = 150. A tie keeps the
// band above the obstacle.
assert.equal(above.safeTop, 40);
assert.equal(above.safeBottom, 190);
assert(above.top + Math.min(120, above.maxHeight) <= 190);
const below = resolveHudRailLayout({
viewportHeight: 480,
panelHeight: 120,
laneLeft: 20,
laneRight: 340,
baseTop: 40,
baseBottom: 460,
gap: 10,
obstacles: [{ left: 0, right: 400, top: 120, bottom: 260 }],
});
// Room above: 70; below: 190. The band goes under the obstacle.
assert.equal(below.safeTop, 270);
assert.equal(below.safeBottom, 460);
assert(below.top >= 270);
});
test('HUD rail layout leaves the band as it is when an obstacle across the midpoint leaves no room', () => {
const layout = resolveHudRailLayout({
viewportHeight: 480,
panelHeight: 120,
laneLeft: 20,
laneRight: 340,
baseTop: 100,
baseBottom: 400,
gap: 10,
obstacles: [{ left: 0, right: 400, top: 80, bottom: 420 }],
});
assert.equal(layout.safeTop, 100);
assert.equal(layout.safeBottom, 400);
});
test('HUD rail layout reads several obstacles across the midpoint the same in any order', () => {
const a = { left: 0, right: 400, top: 100, bottom: 260 };
const b = { left: 0, right: 400, top: 200, bottom: 470 };
const layoutWith = (obstacles) =>
resolveHudRailLayout({
viewportHeight: 480,
panelHeight: 120,
laneLeft: 20,
laneRight: 340,
baseTop: 40,
baseBottom: 460,
gap: 10,
obstacles,
});
// Together they cover 100 to 470: the only room is above, 40 to 90.
for (const layout of [layoutWith([a, b]), layoutWith([b, a])]) {
assert.equal(layout.safeTop, 40);
assert.equal(layout.safeBottom, 90);
assert.equal(layout.maxHeight, 50);
}
});
test('HUD rail layout counts obstacles beside those across the midpoint', () => {
const band = (obstacles) => {
const layout = resolveHudRailLayout({
viewportHeight: 480,
panelHeight: 120,
laneLeft: 20,
laneRight: 340,
baseTop: 40,
baseBottom: 460,
gap: 10,
obstacles: obstacles.map(([top, bottom]) => ({
left: 0,
right: 400,
top,
bottom,
})),
});
return [layout.safeTop, layout.safeBottom];
};
// One inside the span below the midpoint: 150px below the span, 50 above.
assert.deepEqual(band([[100, 300], [250, 280]]), [310, 460]);
// One touching the midpoint from below: 190px below, 100 above.
assert.deepEqual(band([[150, 260], [240, 250]]), [270, 460]);
// One inside the span above the midpoint: 150px above, 50 below.
assert.deepEqual(band([[200, 400], [210, 230]]), [40, 190]);
// A lower obstacle past the span limits the room below it: 100px between
// them against 70 above, and with a taller one only 60, so above.
assert.deepEqual(band([[120, 260], [380, 420]]), [270, 370]);
assert.deepEqual(band([[120, 260], [340, 420]]), [40, 110]);
// Neighbours exactly two gaps away leave no room between: one block, 100
// to 400, and a tie (50px a side) goes above.
assert.deepEqual(band([[100, 180], [200, 300], [320, 400]]), [40, 90]);
// A neighbour exactly two gaps below joins it too: 150 to 300, 100px
// above against 150 below.
assert.deepEqual(band([[150, 250], [270, 300]]), [310, 460]);
// A side under 8% of the window (38.4px) is no room: 30px above, none
// below, so the band stays as it is.
assert.deepEqual(band([[80, 455]]), [40, 460]);
// Exactly the minimum is enough.
const exact = bandBesideMidpointObstacles({
midpoint: 240,
top: 40,
bottom: 460,
obstacles: [{ top: 90, bottom: 465 }],
gap: 10,
minimum: 40,
});
assert.deepEqual([exact?.top, exact?.bottom], [40, 80]);
});
test('HUD rail layout keeps a band beside a midpoint obstacle inside its own edges', () => {
const layout = resolveHudRailLayout({
viewportHeight: 480,
panelHeight: 80,
laneLeft: 20,
laneRight: 340,
baseTop: 350,
baseBottom: 460,
gap: 10,
obstacles: [{ left: 0, right: 400, top: 100, bottom: 260 }],
});
assert.equal(layout.safeTop, 350);
assert.equal(layout.safeBottom, 460);
});
test('HUD rail layout can anchor controls to the start of the safe corridor', () => {
const layout = resolveHudRailLayout({
viewportHeight: 1000,
@@ -432,7 +573,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,
+19 -6
View File
@@ -30,13 +30,26 @@ const TONE_RANK = Object.freeze([
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. */
/** Full-width glyphs in the BMP: CJK, kana, Hangul, full-width forms. */
const WIDE_GLYPHS =
/[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/g;
/**
* One line's width (px) in `.cockpit-progress-label` type (cockpitSubject.css:
* 10 px, 0.06 em spacing): 10.6 px a full-width glyph and 6.4 px each UTF-16
* unit of any other, so an astral glyph (an emoji, a CJK extension) counts as
* two and an emoji in the BMP (☕) as one, narrower than it is drawn. The
* detail line's `<small>` draws smaller, so these widths only overestimate it.
*/
function lineWidthPx(line) {
const text = String(line ?? '');
const wide = text.match(WIDE_GLYPHS)?.length ?? 0;
return wide * 10.6 + (text.length - wide) * 6.4;
}
/** A label's width estimate (px): its wider line and 8 px of padding. */
export function estimateProgressLabelPx(label) {
const longest = Math.max(
String(label?.text ?? '').length,
String(label?.detail ?? '').length,
);
return longest * 6.4 + 8;
return Math.max(lineWidthPx(label?.text), lineWidthPx(label?.detail)) + 8;
}
/**
+60 -1
View File
@@ -4,7 +4,10 @@
// the travelled part.
import test from 'node:test';
import assert from 'node:assert/strict';
import { cockpitProgressLayout } from './cockpitProgress.js';
import {
cockpitProgressLayout,
estimateProgressLabelPx,
} from './cockpitProgress.js';
const tick = (at, label = null, tone = 'normal') => ({ at, tone, label });
const label = (text, priority, align = 'center', detail = '') => ({
@@ -142,3 +145,59 @@ test('a long run of calls still lays out, every one a tick or part of one', () =
assert.ok(narrow.ticks.length < wide.ticks.length);
assert.equal(wide.ticks.length, 60);
});
test('a CJK stop name gets the width its full-width glyphs need', () => {
const text = '中央駅前広場東口'; // 8 full-width glyphs
// 10 px type, 0.06 em apart.
const needPx = text.length * (10 + 0.6);
const givenPx = estimateProgressLabelPx({ text, detail: '' });
assert.ok(
givenPx >= needPx,
`${givenPx} px given, about ${needPx} px needed`,
);
// As many Latin letters are narrower; half-width katakana are as narrow.
assert.ok(givenPx > estimateProgressLabelPx({ text: 'CENTRALS' }));
assert.equal(
estimateProgressLabelPx({ text: 'カタカナ' }),
estimateProgressLabelPx({ text: 'KANA' }),
);
});
test('astral glyphs (emoji outside the BMP, supplementary kana) in a progress label get at least 1 em each', () => {
// About 1 em in 10 px type, 0.06 em apart.
const emPx = 10 + 0.6;
for (const [text, needPx] of [
['🚉🚆🚇🚋', 4 * emPx],
['🚆'.repeat(8), 8 * emPx],
// Supplementary kana, outside the full-width ranges.
['𛀁𛀂', 2 * emPx],
// Mixed: four emoji, a space and two full-width glyphs.
['🚆🚇🚌🚕 乗換', 4 * emPx + 6.4 + 2 * emPx],
]) {
const givenPx = estimateProgressLabelPx({ text, detail: '' });
assert.ok(
givenPx >= needPx + 8,
`${text}: ${givenPx} px given, about ${needPx} px needed`,
);
}
});
test('a label is as wide as its wider line, its smaller detail line included', () => {
assert.ok(
estimateProgressLabelPx({ text: 'GATE', detail: '中央駅前' }) >
estimateProgressLabelPx({ text: 'GATE', detail: '' }),
'the wider detail line widens the label',
);
// As headless Chrome draws the detail's <small> (8.333 px JetBrains Mono,
// 0.6 px apart): 'WWWWMMMMWWWW' at 67.2 px, '中央駅前広場東口' at 72.9 px.
for (const [detail, needPx] of [
['W'.repeat(64), 64 * (67.2 / 12)],
['駅'.repeat(45), 45 * (72.9 / 8)],
]) {
const givenPx = estimateProgressLabelPx({ text: 'A', detail });
assert.ok(
givenPx >= needPx,
`${detail.length} × ${detail[0]}: ${givenPx} px given, ${needPx} px needed`,
);
}
});
+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);
+91 -62
View File
@@ -117,20 +117,27 @@ function lookOf(raw) {
});
}
/** Promises already given a catch: a pending one is read again on every use. */
const caughtWords = new WeakSet();
/**
* 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.
* A worded member as `read()` gives it, normalized: called on `provider`
* when it is a function (so it can follow the page's language); null when it
* is malformed (a promise too) or provider code throws, its getter included
* (hence `read`).
*/
function wordedNow(provider, key, normalize) {
function worded(provider, read, normalize) {
try {
const value = provider[key];
return (
normalize(typeof value === 'function' ? value.call(provider) : value) ??
null
);
const value = read();
const words = typeof value === 'function' ? value.call(provider) : value;
if (typeof words?.then === 'function') {
if (!caughtWords.has(words)) {
caughtWords.add(words);
Promise.resolve(words).catch(() => {});
}
return null;
}
return normalize(words) ?? null;
} catch {
return null;
}
@@ -146,7 +153,7 @@ function providerName(provider, order) {
return `#${order}`;
}
/** Why `provider` cannot be kept, or null. */
/** Why `provider` cannot be kept, its worded members aside, or null. */
function refusal(provider, kinds) {
if (!isObject(provider)) return 'not an object';
if (typeof provider.kind !== 'string' || !KIND_PATTERN.test(provider.kind))
@@ -165,14 +172,25 @@ function refusal(provider, kinds) {
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;
}
/**
* A provider's worded members, each read once, to seed its copy (so one that
* fails when read again cannot undo this check), or why one is malformed.
* @returns {{face: object, labels: object, look: ?object}|string}
*/
function checkedWords(provider) {
const face = worded(provider, () => provider.entryFace, faceOf);
if (!face) return 'malformed entry face';
const labels = worded(provider, () => provider.labels, labelsOf);
if (!labels) return 'labels need view, exit and exitText';
const lookValue = provider.look;
if (lookValue == null) return { face, labels, look: null };
const look = worded(provider, () => lookValue, lookOf);
return look ? { face, labels, look } : 'look needs an aheadLabel';
}
/**
* The application's subject providers, checked once and frozen, in the order
* entry asks them: ascending `priority`, ties in list order. Each has
@@ -191,7 +209,8 @@ function refusal(provider, kinds) {
* 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;
* good one; `look` is on or off and `restPitchDeg` fixed as read at
* registration;
* - `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,
@@ -224,7 +243,11 @@ export function cockpitSubjectProviders(
let copy = null;
try {
reason = refusal(provider, kinds);
if (!reason) copy = keptProvider(provider, order);
if (!reason) {
const words = checkedWords(provider);
if (typeof words === 'string') reason = words;
else copy = keptProvider(provider, order, words);
}
} catch {
reason = 'a member threw when read';
}
@@ -241,14 +264,12 @@ export function cockpitSubjectProviders(
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);
/**
* The frozen copy the Cockpit keeps of a provider that passed `refusal`,
* seeded with the worded members `checkedWords` read.
*/
function keptProvider(provider, order, words) {
let { face, labels, look } = words;
const restPitchDeg = look?.restPitchDeg ?? 0;
return Object.freeze({
kind: provider.kind,
@@ -256,16 +277,16 @@ function keptProvider(provider, order) {
priority: finite(provider.priority) ? provider.priority : 0,
order,
get entryFace() {
face = wordedNow(provider, 'entryFace', faceOf) ?? face;
face = worded(provider, () => provider.entryFace, faceOf) ?? face;
return face;
},
get labels() {
labels = wordedNow(provider, 'labels', labelsOf) ?? labels;
labels = worded(provider, () => provider.labels, labelsOf) ?? labels;
return labels;
},
get look() {
if (!look) return null;
const now = wordedNow(provider, 'look', lookOf);
const now = worded(provider, () => provider.look, lookOf);
if (now)
look = Object.freeze({ restPitchDeg, aheadLabel: now.aheadLabel });
return look;
@@ -335,11 +356,11 @@ function candidateOf(raw) {
* 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.
* COCKPIT_SUBJECT_MIN_HEIGHT_M..COCKPIT_SUBJECT_MAX_HEIGHT_M reads as null,
* for the eye to stand on the shared floor (ui/cockpitCamera.js). The anchor
* is `'inertial'` by default for a frame with a valid speed, and `'exact'`
* when asked for or with no speed. 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,
@@ -356,49 +377,57 @@ export function cockpitSubjectFrame(raw, heldId) {
}
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 (!isObject(raw)) return null;
// Each field read once: a getter on the frame runs provider code.
const {
id,
name,
latitude,
longitude,
heightM,
headingDeg: rawHeadingDeg,
courseDeg,
speedMps: rawSpeedMps,
stale,
groundClamp,
anchor,
eye: rawEye,
} = raw;
if (typeof id !== 'string' || id.trim() !== heldId) return null;
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;
if (!isObject(rawEye)) return null;
const { upM, forwardM, pitchDeg, minClearanceM } = rawEye;
if (!finite(upM) || upM < 0 || 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;
const headingDeg = heading(rawHeadingDeg);
const speedMps = finite(rawSpeedMps) && rawSpeedMps >= 0 ? rawSpeedMps : null;
return {
id: heldId,
name: cockpitSubjectText(raw.name, 64) || cockpitSubjectText(heldId, 64),
name: cockpitSubjectText(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
finite(heightM) &&
heightM >= COCKPIT_SUBJECT_MIN_HEIGHT_M &&
heightM <= COCKPIT_SUBJECT_MAX_HEIGHT_M
? heightM
: null,
headingDeg,
courseDeg: heading(raw.courseDeg) ?? headingDeg,
courseDeg: heading(courseDeg) ?? headingDeg,
speedMps,
stale: raw.stale === true,
groundClamp: raw.groundClamp !== false,
stale: stale === true,
groundClamp: 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',
anchor: 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,
upM,
forwardM: finite(forwardM) && Math.abs(forwardM) <= 500 ? forwardM : 0,
pitchDeg: finite(pitchDeg) ? clamp(pitchDeg, -90, 90) : 0,
minClearanceM:
finite(eye.minClearanceM) && eye.minClearanceM >= 0
? eye.minClearanceM
: 0,
finite(minClearanceM) && minClearanceM >= 0 ? minClearanceM : 0,
},
};
}
+42 -8
View File
@@ -642,11 +642,15 @@ test('a provider whose getter throws is left out with one warning; the next is k
]);
});
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;
test('a worded getter that throws from its second read keeps the last good words', () => {
// Registration reads each once: the second read is the first use.
const once = (value) => {
let read = false;
return () => {
if (read) throw new Error('translations unavailable');
read = true;
return value;
};
};
const definition = provider();
for (const [key, value] of Object.entries({
@@ -654,22 +658,52 @@ test('a worded getter that starts throwing keeps the last good words', () => {
entryFace: { icon: 'commute', label: 'RIDE' },
look: { restPitchDeg: 10, aheadLabel: 'Look ahead' },
}))
Object.defineProperty(definition, key, { get: words(value) });
Object.defineProperty(definition, key, { get: once(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 worded member that returns a rejected promise keeps the last good words, the rejection caught', async () => {
const definition = provider();
const words = definition.labels;
let reads = 0;
definition.labels = () => {
reads += 1;
return reads === 1 ? words : Promise.reject(new Error('late words'));
};
const { kept, warnings } = keep([definition]);
assert.deepEqual(warnings, []);
assert.equal(kept[0].labels.view, words.view);
// An unhandled rejection would fail this test once it surfaces.
await new Promise((resolve) => setTimeout(resolve, 10));
});
test('a frame field read through a getter is read once', () => {
const frame = { id: 'a1', latitude: 1, longitude: 2, eye: { upM: 3 } };
const once = (value) => {
let read = false;
return () => {
const answer = read ? undefined : value;
read = true;
return answer;
};
};
Object.defineProperty(frame, 'heightM', { get: once(420) });
Object.defineProperty(frame, 'speedMps', { get: once(12) });
const normalized = cockpitSubjectFrame(frame, 'a1');
assert.equal(normalized.heightM, 420);
assert.equal(normalized.speedMps, 12);
});
test('a candidate, frame or HUD view whose getter throws reads as null', () => {
assert.equal(
cockpitSubjectCandidate(throwingGetter({ name: 'Example' }, 'id')),
+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', () => {
+1 -44
View File
@@ -17,11 +17,6 @@
* @param {number} [input.signalGap] Clearance above the briefing card.
* @param {number} [input.minTopFloor] Absolute ceiling for the strip, in px.
* @param {number} [input.minTopRatio] Viewport-relative ceiling, 0..1.
* @param {boolean} [input.signalCollapsed] Whether the briefing card is collapsed.
* @param {boolean} [input.utilityExpanded] Whether Display or Radio is expanded.
* @param {number} [input.bottomInset] Reserved viewport space below an expanded panel.
* @param {number} [input.signalHeight] Collapsed briefing header reserved below the utility.
* @param {boolean} [input.reserveViewportLane] Theme relocates the briefing below the expanded utility.
* @returns {{ top: number, maxHeight: number }}
*/
export function resolveCockpitUtilityAnchor({
@@ -34,29 +29,13 @@ export function resolveCockpitUtilityAnchor({
signalGap = 8,
minTopFloor = 96,
minTopRatio = 0.12,
signalCollapsed = false,
utilityExpanded = false,
bottomInset = 80,
signalHeight = 0,
reserveViewportLane = false,
}) {
const viewport = Math.max(0, Number(viewportHeight) || 0);
const minTop = Math.max(minTopFloor, viewport * minTopRatio);
const anchoredTop = Math.max(minTop, (Number(recBottom) || 0) + recGap);
const strip = Math.max(0, Number(stripHeight) || 0);
const signal = Number(signalTop);
const expandedLaneBottom = Math.max(
0,
viewport -
Math.max(0, Number(bottomInset) || 0) -
Math.max(0, Number(signalHeight) || 0),
);
const lowerBound =
reserveViewportLane && signalCollapsed && utilityExpanded
? expandedLaneBottom
: Number.isFinite(signal)
? signal
: viewport;
const lowerBound = Number.isFinite(signal) ? signal : viewport;
const clearedTop = lowerBound - signalGap - strip;
const top = Math.max(minTop, Math.min(anchoredTop, clearedTop));
const floor = Math.max(0, Number(collapsedHeight) || 0) || 50;
@@ -100,25 +79,3 @@ export function resolveCockpitUtilityLayout({
),
};
}
/** Shared Cyber panel slot, with footer controls above the lower frame (83vh). */
export function resolveCyberCockpitPanelLane({
viewportHeight,
top,
launcherHeight = 60,
signalHeight = 44,
contactHeight = 64,
}) {
const gap = 8;
const footerHeight = Math.max(
contactHeight + gap,
launcherHeight + signalHeight + gap * 2,
);
const bottom = viewportHeight * 0.82;
const panelHeight = Math.max(120, bottom - top - footerHeight);
return {
panelHeight,
utilityHeight: panelHeight + gap + launcherHeight,
signalTop: top + panelHeight + launcherHeight + gap * 2,
};
}
+1 -71
View File
@@ -4,58 +4,11 @@ import assert from 'node:assert/strict';
import {
resolveCockpitUtilityAnchor,
resolveCockpitUtilityLayout,
resolveCyberCockpitPanelLane,
} from './cockpitUtilityLayout.js';
// 1512x790, the height the strip used to collide with the briefing card at.
const desktop = { viewportHeight: 790, stripHeight: 107, collapsedHeight: 50 };
test('Cyber shared panel slot reserves both footer lanes above the decorative frame', () => {
for (const viewportHeight of [600, 673, 713, 986, 1376]) {
for (const signalHeight of [44, 76]) {
for (const contactHeight of [44, 84, 120]) {
const top = Math.max(164, Math.min(204, viewportHeight * 0.19));
const lane = resolveCyberCockpitPanelLane({ viewportHeight, top, signalHeight, contactHeight });
assert.ok(lane.panelHeight >= 120);
assert.ok(top + lane.panelHeight + 8 + contactHeight <= viewportHeight * 0.82 + .01);
assert.ok(lane.signalTop + signalHeight <= viewportHeight * 0.82 + .01);
assert.equal(lane.signalTop, top + lane.utilityHeight + 8);
}
}
}
});
test('Cyber keeps the Data Layers top while reserving briefing clearance', () => {
for (const viewportHeight of [673, 713, 986, 1376]) {
const leftTop = Math.max(164, Math.min(204, viewportHeight * 0.19));
const collapsed = resolveCockpitUtilityAnchor({
viewportHeight, stripHeight: 128, collapsedHeight: 60, recBottom: 0,
signalTop: leftTop + 128 + 28, minTopFloor: leftTop, minTopRatio: 0,
});
assert.equal(collapsed.top, leftTop);
assert.ok(collapsed.maxHeight >= 128);
const expanded = resolveCockpitUtilityAnchor({
viewportHeight, stripHeight: 700, collapsedHeight: 60, recBottom: 0,
signalTop: 255, minTopFloor: leftTop, minTopRatio: 0,
signalCollapsed: true, utilityExpanded: true, reserveViewportLane: true, signalHeight: 44,
});
assert.equal(expanded.top, leftTop);
assert.equal(expanded.top + expanded.maxHeight + 8 + 44 + 80, viewportHeight);
}
});
test('expanded utilities reserve the visible collapsed briefing header at every desktop height', () => {
for (const viewportHeight of [640, 720, 987, 1376]) {
for (const signalHeight of [48, 76, 100]) {
const { top, maxHeight } = resolveCockpitUtilityAnchor({
...desktop, viewportHeight, recBottom: 0, signalTop: 255,
signalCollapsed: true, utilityExpanded: true, signalHeight, reserveViewportLane: true,
});
assert.equal(top + maxHeight + 8, viewportHeight - 80 - signalHeight);
}
}
});
test('the strip hangs 12px under the REC readout when the briefing card leaves room', () => {
const { top } = resolveCockpitUtilityAnchor({ ...desktop, recBottom: 148.1, signalTop: 420 });
assert.equal(Number(top.toFixed(1)), 160.1);
@@ -101,34 +54,11 @@ test('a missing REC readout leaves the strip on the viewport ceiling', () => {
assert.equal(top, 96);
});
test('an expanded utility claims the vertical lane released by a collapsed briefing', () => {
const { top, maxHeight } = resolveCockpitUtilityAnchor({
...desktop,
recBottom: 148.1,
signalTop: 265.4,
signalCollapsed: true,
utilityExpanded: true,
reserveViewportLane: true,
});
assert.equal(Number(top.toFixed(1)), 160.1);
assert.equal(Number(maxHeight.toFixed(1)), 541.9);
});
test('non-relocating themes preserve the visible briefing boundary even when collapsed', () => {
test('the visible briefing card bounds the utility strip, collapsed or not', () => {
const { top, maxHeight } = resolveCockpitUtilityAnchor({
...desktop, recBottom: 148.1, signalTop: 265.4,
signalCollapsed: true, utilityExpanded: true,
});
assert.equal(Number((top + maxHeight).toFixed(1)), 257.4);
});
test('a collapsed briefing still bounds the utility strip until a panel expands', () => {
const { maxHeight } = resolveCockpitUtilityAnchor({
...desktop,
recBottom: 148.1,
signalTop: 265.4,
signalCollapsed: true,
});
assert.equal(Number(maxHeight.toFixed(1)), 107);
});
+19 -106
View File
@@ -1,5 +1,3 @@
import { msg } from './i18n/marker.js';
const CONTEXT_DEPENDENCIES = Object.freeze({
flights: new Set([
'military-awareness',
@@ -8,15 +6,18 @@ const CONTEXT_DEPENDENCIES = Object.freeze({
'ais-live-vessels',
'military-installations',
]),
'space-missions': new Set(['rocket-launches', 'satellites']),
});
const CONTEXT_COMPANIONS = new Set(['radio']);
/** The Space Missions refusal, with the blocked layer's name as {layer}. */
export const SPACE_MISSIONS_LAYER_BLOCK_REASON = msg(
'Space Missions isolates replay data. Exit the mode to enable {layer}.',
);
const [BLOCK_REASON_PREFIX, BLOCK_REASON_SUFFIX] =
SPACE_MISSIONS_LAYER_BLOCK_REASON.split('{layer}');
/**
* Layers Context never touches: Space Missions and the Satellites layer it
* depends on. Contacts neither switches them off on entry nor restores them
* on exit, so they run beside it in either order and keep their own state
* (the mission controller owns the Satellites dependency).
*/
export const CONTEXT_INDEPENDENT_LAYER_IDS = Object.freeze([
'rocket-launches',
'satellites',
]);
/** Return whether an origin represents a direct user choice on this route. */
export function isExplicitUserIntentOrigin(origin, layerId = null) {
return origin === 'user' || origin === 'voice';
@@ -27,7 +28,8 @@ export function recordContextRestoreExplicitChange({ restoreState, change }) {
if (
!restoreState?.enabledLayerIds ||
change?.type !== 'visibility' ||
!isExplicitUserIntentOrigin(change.origin, change.layerId)
!isExplicitUserIntentOrigin(change.origin, change.layerId) ||
CONTEXT_INDEPENDENT_LAYER_IDS.includes(change.layerId)
)
return false;
if (!restoreState.explicitLayerStates)
@@ -121,10 +123,7 @@ export async function settleUserFacingContextAction({
* one into `userAdded` makes exit restoration re-enable the mode layer the
* user just turned off.
*/
export const CONTEXT_ENTRY_LAYER_IDS = Object.freeze([
'military-awareness',
'rocket-launches',
]);
export const CONTEXT_ENTRY_LAYER_IDS = Object.freeze(['military-awareness']);
/**
* Leave a Context transaction: publish the settled coordination flag, then
@@ -193,7 +192,8 @@ export function shouldExitContextForLayerChange({
change?.type !== 'visibility' ||
!isExplicitUserIntentOrigin(change.origin, change.layerId) ||
change.layerId === 'military-awareness' ||
CONTEXT_COMPANIONS.has(change.layerId)
CONTEXT_COMPANIONS.has(change.layerId) ||
CONTEXT_INDEPENDENT_LAYER_IDS.includes(change.layerId)
) {
return false;
}
@@ -215,6 +215,7 @@ export function contextAllowedLayerIds(contextMode) {
return new Set([
...(CONTEXT_DEPENDENCIES[contextMode] || ['military-awareness']),
...CONTEXT_COMPANIONS,
...CONTEXT_INDEPENDENT_LAYER_IDS,
]);
}
@@ -235,21 +236,6 @@ export function shouldCaptureContextSession(change) {
);
}
/**
* Return whether one explicit mission intent superseded an in-flight Clear All
* reservation and therefore needs deferred Context adoption.
*/
export function shouldDeferContextEntryDuringClear({ change, clearInFlight }) {
return Boolean(
clearInFlight &&
change?.type === 'visibility-requested' &&
change.layerId === 'rocket-launches' &&
change.enabled === true &&
isExplicitUserIntentOrigin(change.origin, change.layerId) &&
Number.isInteger(change.intentEpoch),
);
}
/**
* Bookkeep a user-owned layer change against the active Context session so
* exit restoration can honor layers the user added mid-session. Two rules
@@ -273,7 +259,8 @@ export function recordContextSessionUserChange({
if (
!snapshot?.userAdded ||
change?.type !== 'visibility' ||
!isExplicitUserIntentOrigin(change.origin, change.layerId)
!isExplicitUserIntentOrigin(change.origin, change.layerId) ||
CONTEXT_INDEPENDENT_LAYER_IDS.includes(change.layerId)
) {
return false;
}
@@ -319,83 +306,10 @@ export function contextSnapshotLayerIds(
) {
const snapshot = new Set(restoringLayerIds || currentEnabledLayerIds || []);
for (const layerId of excludeLayerIds || []) snapshot.delete(layerId);
for (const layerId of CONTEXT_INDEPENDENT_LAYER_IDS) snapshot.delete(layerId);
return snapshot;
}
/**
* Block layers that would mix unrelated live/current data into Space Missions.
* The manager calls this before lifecycle work so a refused layer never starts.
* @param {object} input Current mode and requested visibility transition.
* @param {string|null} input.contextMode Active Context mode.
* @param {object|null} input.change Requested visibility transition.
* @param {string|null} [input.layerName] User-facing layer name.
* @returns {string|null} Honest user-facing refusal reason, or null when allowed.
*/
export function contextLayerEnableBlockReason({
contextMode,
change,
layerName = null,
}) {
if (
contextMode !== 'space-missions' ||
change?.enabled !== true ||
contextAllowedLayerIds('space-missions').has(change.layerId)
) {
return null;
}
const label = String(layerName || change.layerId || 'that layer');
return SPACE_MISSIONS_LAYER_BLOCK_REASON.replace('{layer}', label);
}
/**
* The layer name from a Space Missions refusal, so the UI can rebuild the
* sentence in its language.
* @param {string} reason
* @returns {{layer: string}|null} The blocked layer's name, or null when the
* reason is not a Space Missions refusal.
*/
export function parseContextLayerBlockReason(reason) {
if (
typeof reason !== 'string' ||
!reason.startsWith(BLOCK_REASON_PREFIX) ||
!reason.endsWith(BLOCK_REASON_SUFFIX) ||
reason.length <= BLOCK_REASON_PREFIX.length + BLOCK_REASON_SUFFIX.length
)
return null;
return {
layer: reason.slice(
BLOCK_REASON_PREFIX.length,
reason.length - BLOCK_REASON_SUFFIX.length,
),
};
}
/**
* Resolve who owns a cancelled direct Space Missions entry. A newer ON keeps
* the entry shell reserved for its replacement transaction; every other
* cancellation must roll back the isolated pre-entry session.
*
* @param {object} input Cancellation and current manager intent state.
* @param {object|null} input.change Manager visibility notification.
* @returns {'ignore'|'replacement'|'restore'} Cancellation disposition.
*/
export function spaceMissionEntryCancellationDisposition({ change }) {
if (
change?.type !== 'visibility-cancelled' ||
change.layerId !== 'rocket-launches' ||
change.enabled !== true
)
return 'ignore';
if (
change.cancellationReason === 'superseded' &&
Number.isInteger(change.successorIntentEpoch) &&
change.successorIntentEpoch > change.intentEpoch &&
change.successorEnabled === true
)
return 'replacement';
return 'restore';
}
/**
* Merge the pre-entry layer snapshot with layers the user enabled during the
* Context session so both survive restoration.
@@ -510,7 +424,6 @@ export function subjectEntryAllowed({
*/
export const CONTEXT_MODE_VOICE_NAMES = Object.freeze({
flights: 'contacts',
'space-missions': 'space-missions',
});
/**
+63 -111
View File
@@ -5,7 +5,6 @@ import {
orbitEntryAllowed,
cockpitEntryAllowed,
contextAllowedLayerIds,
contextLayerEnableBlockReason,
contextRestoreLayerIds,
isExplicitUserIntentOrigin,
mergeContextTransitionErrors,
@@ -17,9 +16,7 @@ import {
settleContextIntentReplay,
settleUserFacingContextAction,
shouldCaptureContextSession,
shouldDeferContextEntryDuringClear,
shouldExitContextForLayerChange,
spaceMissionEntryCancellationDisposition,
} from './contextModePolicy.js';
test('Context transition errors preserve primary identity and aggregate failed layers', () => {
@@ -119,11 +116,6 @@ test('user-enabled layers are additive and do not exit Context', () => {
globalContextEnabled: true,
change: userEnable('earthquakes'),
}), false);
assert.equal(shouldExitContextForLayerChange({
contextMode: 'space-missions',
globalContextEnabled: false,
change: userEnable('traffic'),
}), false);
assert.equal(shouldExitContextForLayerChange({
contextMode: null,
globalContextEnabled: true,
@@ -133,48 +125,16 @@ test('user-enabled layers are additive and do not exit Context', () => {
test('programmatic Context dependencies and direct mode setup remain allowed', () => {
assert.equal(shouldExitContextForLayerChange({
contextMode: 'space-missions',
contextMode: 'flights',
globalContextEnabled: true,
change: { ...userEnable('satellites'), origin: 'programmatic' },
change: { ...userEnable('military'), enabled: false, origin: 'programmatic' },
}), false);
});
test('Space Missions cancellation retains only a newer authoritative ON entry', () => {
const cancelledEntry = {
type: 'visibility-cancelled',
layerId: 'rocket-launches',
enabled: true,
intentEpoch: 8,
cancellationReason: 'superseded',
successorIntentEpoch: 9,
successorEnabled: true,
successorOrigin: 'programmatic',
};
assert.equal(spaceMissionEntryCancellationDisposition({
change: cancelledEntry,
}), 'replacement');
assert.equal(spaceMissionEntryCancellationDisposition({
change: { ...cancelledEntry, successorEnabled: false },
}), 'restore', 'a newer OFF releases the entry shell');
assert.equal(spaceMissionEntryCancellationDisposition({
change: {
...cancelledEntry,
cancellationReason: 'caller-abort',
successorIntentEpoch: undefined,
successorEnabled: undefined,
},
}), 'restore', 'caller abort at the same epoch restores the isolated session');
assert.equal(spaceMissionEntryCancellationDisposition({
change: { ...cancelledEntry, enabled: false },
currentIntentEpoch: 9,
effectivelyEnabled: true,
}), 'ignore');
});
test('only explicit user-owned shell enables capture a Context restoration snapshot', () => {
const userMissionEnable = {
type: 'visibility-requested',
layerId: 'rocket-launches',
layerId: 'military-awareness',
enabled: true,
origin: 'user',
};
@@ -186,40 +146,25 @@ test('only explicit user-owned shell enables capture a Context restoration snaps
assert.equal(shouldCaptureContextSession({ ...userMissionEnable, origin: 'context-restore' }), false);
assert.equal(shouldCaptureContextSession({ ...userMissionEnable, enabled: false }), false);
assert.equal(shouldCaptureContextSession({ ...userMissionEnable, layerId: 'satellites' }), false);
assert.equal(
shouldCaptureContextSession({ ...userMissionEnable, layerId: 'rocket-launches' }),
false,
'Space Missions is an ordinary layer, not a Context entry',
);
});
test('voice dependency OFF exits Space Missions like the equivalent UI action', () => {
test('voice dependency OFF exits Contacts like the equivalent UI action', () => {
assert.equal(shouldExitContextForLayerChange({
contextMode: 'space-missions',
contextMode: 'flights',
globalContextEnabled: false,
change: { type: 'visibility', layerId: 'satellites', enabled: false, origin: 'voice' },
change: { type: 'visibility', layerId: 'flights', enabled: false, origin: 'voice' },
}), true);
});
test('only a newer explicit mission request is deferred during Clear All', () => {
const change = {
type: 'visibility-requested',
layerId: 'rocket-launches',
enabled: true,
origin: 'voice',
intentEpoch: 12,
};
assert.equal(shouldDeferContextEntryDuringClear({ change, clearInFlight: true }), true);
assert.equal(shouldDeferContextEntryDuringClear({ change, clearInFlight: false }), false);
assert.equal(shouldDeferContextEntryDuringClear({
change: { ...change, origin: 'programmatic' },
clearInFlight: true,
}), false);
assert.equal(shouldDeferContextEntryDuringClear({
change: { ...change, enabled: false },
clearInFlight: true,
}), false);
});
test('a rapid re-entry snapshots the settled restore target, not partial manager state', () => {
assert.deepEqual(
[...contextSnapshotLayerIds(
new Set(['rocket-launches', 'earthquakes']),
new Set(['cctv', 'earthquakes']),
new Set(['flights', 'traffic']),
)],
['flights', 'traffic'],
@@ -230,31 +175,15 @@ test('a rapid re-entry snapshots the settled restore target, not partial manager
);
assert.deepEqual(
[...contextSnapshotLayerIds(
new Set(['rocket-launches', 'satellites']),
new Set(['military-awareness', 'cctv']),
null,
['rocket-launches'],
['military-awareness'],
)],
['satellites'],
['cctv'],
'the synchronous entry intent is not part of the pre-entry snapshot',
);
});
test('Space Missions blocks unrelated layer enables before replay data can mix', () => {
const change = { layerId: 'flights', enabled: true, origin: 'user' };
assert.match(
contextLayerEnableBlockReason({ contextMode: 'space-missions', change, layerName: 'Live Flights' }),
/Exit the mode to enable Live Flights/,
);
assert.equal(contextLayerEnableBlockReason({
contextMode: 'space-missions',
change: { ...change, layerId: 'satellites' },
}), null);
assert.equal(contextLayerEnableBlockReason({
contextMode: 'flights',
change,
}), null, 'live cockpit keeps additive user layers');
});
test('the Global Context shell and layers selected while Context is off remain allowed', () => {
assert.equal(shouldExitContextForLayerChange({
contextMode: null,
@@ -275,14 +204,38 @@ test('manually disabling a mode dependency exits that Context bundle', () => {
change: { ...userEnable('military'), enabled: false },
}), true);
assert.equal(shouldExitContextForLayerChange({
contextMode: 'space-missions',
contextMode: 'flights',
globalContextEnabled: false,
change: { ...userEnable('satellites'), enabled: false },
}), true);
}), false, 'Satellites is not a Contacts dependency');
});
test('Context never isolates, snapshots, restores or bookkeeps Space Missions and Satellites', () => {
for (const layerId of ['rocket-launches', 'satellites']) {
assert.equal(contextAllowedLayerIds('flights').has(layerId), true);
const snapshot = { userAdded: new Set(), userRemoved: new Set() };
for (const enabled of [true, false]) {
assert.equal(recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', origin: 'user', layerId, enabled },
effectiveContextMode: 'flights',
}), false);
const restoreState = { enabledLayerIds: new Set() };
assert.equal(recordContextRestoreExplicitChange({
restoreState,
change: { type: 'visibility', origin: 'user', layerId, enabled },
}), false);
}
assert.equal(snapshot.userAdded.size + snapshot.userRemoved.size, 0);
}
assert.deepEqual(
[...contextSnapshotLayerIds(new Set(['rocket-launches', 'satellites', 'cctv']))],
['cctv'],
);
});
test('Radio remains an independent companion across Context transitions', () => {
for (const contextMode of ['flights', 'space-missions']) {
for (const contextMode of ['flights', null]) {
for (const enabled of [true, false]) {
assert.equal(shouldExitContextForLayerChange({
contextMode,
@@ -292,21 +245,17 @@ test('Radio remains an independent companion across Context transitions', () =>
}
assert.equal(contextAllowedLayerIds(contextMode).has('radio'), true);
}
assert.equal(contextLayerEnableBlockReason({
contextMode: 'space-missions',
change: { type: 'visibility', origin: 'user', layerId: 'radio', enabled: true },
layerName: 'Radio',
}), null);
});
test('each Context mode exposes only its shell and dependencies', () => {
assert.deepEqual(
[...contextAllowedLayerIds(null)],
['military-awareness', 'radio'],
['military-awareness', 'radio', 'rocket-launches', 'satellites'],
);
assert.deepEqual(
[...contextAllowedLayerIds('space-missions')],
['rocket-launches', 'satellites', 'radio'],
['military-awareness', 'radio', 'rocket-launches', 'satellites'],
'Space Missions is not a Context mode',
);
});
@@ -332,7 +281,7 @@ test('Context restoration honors an explicit companion disable', () => {
});
test('the latest explicit Radio state wins across a Context session', () => {
for (const effectiveContextMode of [null, 'flights', 'space-missions']) {
for (const effectiveContextMode of [null, 'flights']) {
for (const origin of ['user', 'voice']) {
const snapshot = { userAdded: new Set(), userRemoved: new Set() };
const record = (enabled) => recordContextSessionUserChange({
@@ -368,7 +317,7 @@ test('only direct UI and voice origins count as explicit Context intent', () =>
assert.equal(recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', origin, layerId: 'radio', enabled: true },
effectiveContextMode: 'space-missions',
effectiveContextMode: 'flights',
}), false);
assert.equal(snapshot.userAdded.size, 0);
}
@@ -526,16 +475,8 @@ test('the teardown guard re-publishes on the way out, so a mid-flight exit is no
test('the session-starting entry layer is never bookkept as user-added (chip ON→OFF restores exactly)', () => {
const snapshot = { enabledLayerIds: new Set(['flights', 'ais-live-vessels']), userAdded: new Set() };
// The exact left-panel regression: the rockets enable event lands while the
// mode is still being entered (or even null); it must not survive its own exit.
for (const effectiveContextMode of ['space-missions', null]) {
recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', layerId: 'rocket-launches', enabled: true, origin: 'user' },
effectiveContextMode,
});
assert.equal(snapshot.userAdded.has('rocket-launches'), false);
}
// The entry layer's enable event lands while the mode is still being
// entered; it must not survive its own exit.
recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', layerId: 'military-awareness', enabled: true, origin: 'user' },
@@ -559,10 +500,21 @@ test('mid-session user additions are recorded, removed on disable, and judged ag
// A dependency of the mode being ENTERED is not a user addition.
recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', layerId: 'satellites', enabled: true, origin: 'user' },
effectiveContextMode: 'space-missions',
change: { type: 'visibility', layerId: 'military', enabled: true, origin: 'user' },
effectiveContextMode: 'flights',
});
assert.equal(snapshot.userAdded.has('satellites'), false);
assert.equal(snapshot.userAdded.has('military'), false);
// Space Missions is not Context's: it is never bookkept.
recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', layerId: 'rocket-launches', enabled: true, origin: 'user' },
effectiveContextMode: 'flights',
});
assert.equal(
snapshot.userAdded.has('rocket-launches'),
false,
'Space Missions is not Context state',
);
// Disabling a recorded addition removes it before any exit restore reads it.
recordContextSessionUserChange({
snapshot,
+38 -36
View File
@@ -13,10 +13,7 @@ const radioControlsSource = readRadioSource(new URL('./ui/radioControls.js', imp
// - session bookkeeping ran AFTER the exit early-return, so the compensating
// userAdded.delete never ran on the left-panel chip exit and restoration
// resurrected the mission layer the user just disabled;
// - the effective mode was read AFTER the entering flag was cleared, so the
// entry layer's own enable event was judged against a null mode;
// - a failed Space Missions START from the chip route cleared siblings with
// no rollback;
// - a failed direct Contacts START cleared siblings with no rollback;
// - the right-rail entry ignored the activation result entirely.
import { test } from 'node:test';
import assert from 'node:assert/strict';
@@ -33,25 +30,20 @@ test('context handler: session bookkeeping runs before the exit early-return', (
assert.ok(record < exit, 'bookkeeping must precede the exit check');
});
test('context handler: effective mode is read before the entering flag is cleared', () => {
const effective = handler.indexOf('this._contextModeEntering || this._contextMode');
const clear = handler.indexOf('this._contextModeEntering = null');
assert.ok(effective > 0, 'effective-mode read present');
assert.ok(clear > 0, 'entering-flag clear present');
assert.ok(effective < clear, 'effective mode must be captured first');
test('Space Missions is an ordinary layer the Context handler never enters', () => {
assert.doesNotMatch(handler, /'space-missions'/);
assert.doesNotMatch(handler, /_contextModeEntering = /);
const attach = connectContextManager.toString();
assert.doesNotMatch(attach, /rocket-launches|space-missions/);
});
test('cancelled Space Missions entry resolves ownership before settled bookkeeping', () => {
test('a cancelled visibility request returns before settled bookkeeping', () => {
const cancelled = handler.indexOf("change?.type === 'visibility-cancelled'");
const bookkeeping = handler.indexOf('recordContextSessionUserChange(');
assert.ok(cancelled > 0, 'cancellation branch present');
assert.ok(cancelled < bookkeeping, 'cancellation returns before settled session bookkeeping');
const branch = handler.slice(cancelled, handler.indexOf("change?.type === 'visibility-blocked'"));
assert.match(branch, /spaceMissionEntryCancellationDisposition\(\{/);
assert.match(branch, /cancellationDisposition === 'replacement'[\s\S]*?_contextModeEntering = 'space-missions'[\s\S]*?entryIntent\.intentEpoch === change\.intentEpoch[\s\S]*?_contextModeReplacementIntent = \{[\s\S]*?intentEpoch: change\.successorIntentEpoch/);
assert.match(branch, /cancellationDisposition === 'restore'[\s\S]*?_contextModeEntering = null/);
assert.match(branch, /_restoreContextSessionAfterLayerSettles\(/);
assert.match(branch, /return;/);
assert.match(branch, /this\._syncContextModeButtons\(\);\s*return;/);
});
test('direct Context entry captures on the synchronous request boundary', () => {
@@ -60,18 +52,29 @@ test('direct Context entry captures on the synchronous request boundary', () =>
attach,
/subscribeVisibilityRequests\(\(change\) => \{[\s\S]*?shouldCaptureContextSession\(change\)/,
);
assert.match(
attach,
/_captureContextSessionSnapshot\(\{\s*excludeLayerIds:\s*\[change\.layerId\],?\s*\}\)/,
);
});
test('Clear All defers a newer explicit mission guard until its batch settles', () => {
const attach = connectContextManager.toString();
assert.match(attach, /shouldDeferContextEntryDuringClear\(\{/);
assert.match(attach, /_contextModeDeferredEntryIntent = \{/);
assert.match(attach, /await this\._clearSelectedLayersManagerPromise/);
assert.match(attach, /await this\._clearLayersOutsideContextMode\(entryMode/);
test('only a direct Contacts entry request snapshots the layers', () => {
let request;
const controls = new ContextControls({
elements: {},
installations: {},
actions: { getCockpit: () => null },
});
const captures = [];
controls._captureContextSessionSnapshot = (options) => captures.push(options);
controls._syncContextModeButtons = () => {};
controls.connect({
subscribe: () => () => {},
subscribeVisibilityRequests(listener) {
request = listener;
return () => {};
},
});
for (const layerId of ['rocket-launches', 'military-awareness'])
request({ type: 'visibility-requested', layerId, enabled: true, origin: 'user', intentEpoch: 1 });
controls.stop();
assert.deepEqual(captures, [{ excludeLayerIds: ['military-awareness'] }]);
});
test('context restore replays explicit companion intent after the stale restore queue drains', () => {
@@ -91,7 +94,7 @@ test('context restore settles the Contacts coordinator before dependency fanout'
assert.ok(settle > 0, 'Contacts coordinator settlement is present');
assert.ok(coordinatorOff > settle, 'Contacts OFF is awaited');
assert.ok(fanout > coordinatorOff, 'snapshot fanout starts after Contacts settles');
assert.match(restore, /excludeLayerIds: settleContactsCoordinator[\s\S]*?contactsCoordinatorId/);
assert.match(restore, /excludeLayerIds: \[[\s\S]*?CONTEXT_INDEPENDENT_LAYER_IDS[\s\S]*?settleContactsCoordinator \? \[contactsCoordinatorId\]/);
});
test('Clear All during the Contacts settle stops the snapshot coming back', () => {
@@ -116,7 +119,7 @@ test('context handler: either failed direct Context-shell start rolls the sessio
handler.indexOf("change?.type === 'visibility-failed'"),
handler.indexOf("change?.type === 'visibility-will-change'"),
);
assert.match(failedBranch, /\['military-awareness', 'rocket-launches'\]\.includes\(change\.layerId\)/);
assert.match(failedBranch, /change\.layerId === 'military-awareness' &&/);
assert.match(
failedBranch,
/_restoreContextSessionAfterLayerSettles\(\s*change\.layerId,\s*\{\s*notificationToken,?\s*\},?\s*\)/,
@@ -154,14 +157,14 @@ test('wrapped visibility blocks leave the accessible toast to the wrapper token
test('every user-facing Context exit route settles through the failure surface', () => {
const initPanel = _initGlobalContextPanel.toString();
assert.equal((initPanel.match(/void this\._runUserFacingContextAction/g) || []).length, 3);
assert.equal((initPanel.match(/void this\._runUserFacingContextAction/g) || []).length, 2);
assert.doesNotMatch(initPanel, /falseIsFailure:\s*false/);
assert.doesNotMatch(initPanel, /void this\._selectContextMode/);
const deactivationCalls = [...handler.matchAll(
/void this\._trackContextLayerReaction\(\s*this\._runUserFacingContextAction\(\(notificationToken\) =>\s*this\._deactivateContextForLayerChange\(\{ notificationToken \}\),?\s*\),?\s*\)/g,
)];
assert.equal(deactivationCalls.length, 4, 'dependency and primary layer exits share the caught restore path');
assert.equal(deactivationCalls.length, 3, 'dependency and primary layer exits share the caught restore path');
assert.doesNotMatch(handler, /void this\._deactivateContextForLayerChange\(\)/);
});
@@ -193,10 +196,7 @@ test('right-rail context entry is transactional: activation result gates the mod
const failureBlock = select.slice(activation);
assert.match(failureBlock, /activated = await activationIntent\.promise/);
assert.match(failureBlock, /catch \(error\) \{\s*activationError = error;/);
assert.match(failureBlock, /_contextModeReplacementIntent\?\.generation === generation/);
assert.match(failureBlock, /await this\._dataManager\._waitForVisibilityIntent\?\.\(/);
assert.match(failureBlock, /outcome\?\.intentEpoch === replacementIntent\.intentEpoch[\s\S]*?outcome\.succeeded === true/);
assert.match(failureBlock, /outcome\?\.cancellationReason === 'superseded'[\s\S]*?outcome\.successorEnabled === true[\s\S]*?outcome\.successorIntentEpoch > replacementIntent\.intentEpoch/);
assert.match(failureBlock, /activationError\s*\|\|\s*activated === false\s*\|\|\s*!this\._dataManager\.isEnabled\(entryLayerId\)/);
assert.match(failureBlock, /cancelledAndSettled\s*=\s*terminalIntentOutcome\?\.succeeded === false/);
assert.match(failureBlock, /\['caller-abort', 'resource-abort', 'superseded'\]/);
@@ -216,9 +216,11 @@ test('Context entry awaits isolation and direct shell routes isolate in the visi
// rests on Context OFF; the honesty lives in the REPORT, not in a racy
// attempt to put the prior mode back (see the note above
// _restoreContextSessionAfterLayerSettles).
const capture = select.indexOf('this._captureContextSessionSnapshot(');
assert.ok(capture > 0, 'Context snapshot capture is missing');
const crossMode = select.slice(
select.indexOf('const crossModeSwitch = Boolean('),
select.indexOf('this._captureContextSessionSnapshot();'),
capture,
);
assert.ok(crossMode, 'cross-mode teardown block is missing');
assert.doesNotMatch(crossMode, /if \(signal\?\.aborted\)[\s\S]*?await this\._restoreContextSession/);
@@ -242,10 +244,10 @@ test('Context entry awaits isolation and direct shell routes isolate in the visi
assert.match(ContextControls.prototype.stop.toString(), /this\._contextModeGeneration\+\+/);
const guard = connectContextManager.toString();
assert.match(guard, /\['military-awareness', 'rocket-launches'\]\.includes\(change\.layerId\)/);
assert.match(guard, /change\.layerId !== 'military-awareness'/);
assert.match(guard, /const notificationToken\s*=\s*change\.notificationToken\s*\|\|\s*Symbol\('direct-context-shell-entry'\)/);
assert.match(guard, /this\._userFacingContextNotificationTokens\.add\(notificationToken\)/);
assert.match(guard, /await this\._clearLayersOutsideContextMode\(entryMode,\s*\{\s*notificationToken,?\s*\}\)/);
assert.match(guard, /await this\._clearLayersOutsideContextMode\(null,\s*\{\s*notificationToken,?\s*\}\)/);
assert.match(
guard,
/await this\._restoreContextSession\(\{\s*excludeLayerIds: \[change\.layerId\],\s*notificationToken,\s*\}\)/,
+147 -57
View File
@@ -2,83 +2,129 @@ import { renderApplicationHtml } from './testSupport/applicationHtml.mjs';
import { readStylesheet } from './testSupport/readStylesheet.mjs';
import { _selectContextMode } from './ui/contextTransactions.js';
import { _initGlobalContextPanel } from './ui/contextBindings.js';
import { ContextControls } from './ui/contextControls.js';
import { clearSelectedLayers } from './ui/contextActions.js';
import { PANEL_RAIL_ITEMS } from './ui/panelRailCatalog.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>`));
assert.ok(button, `${id} is missing`);
assert.match(button[0], /role="tab"/);
assert.match(button[0], /tabindex="0"/);
}
// 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']) {
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/);
}
test('Contacts stays in the keyboard sequence and Space Missions owns its rail item', () => {
const button = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
)?.[0];
assert.ok(button, 'Contacts control is missing');
assert.match(button, /role="tab"/);
assert.match(button, /tabindex="0"/);
const tag = contextView.match(/<button id="global-context-flights-btn"[^>]*>/)?.[0];
assert.ok(tag, 'Contacts control is missing from the view');
assert.doesNotMatch(tag, /:tabindex|:disabled|\sdisabled/);
assert.doesNotMatch(html, /id="global-context-missions-btn"/);
assert.match(html, /id="space-missions-panel"[^>]*data-panel-id="space-missions-panel"/);
assert.equal(PANEL_RAIL_ITEMS['space-missions-panel'].icon, 'rocket_launch');
});
test('Context activation and Clear All never native-disable tabs and guard repeated clicks', () => {
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.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', () => {
const initSource = _initGlobalContextPanel.toString();
assert.match(initSource, /event\.key === 'ArrowRight'/);
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\]\.click\(\)/);
test('a Contacts click while Context is busy is ignored', () => {
const button = new EventTarget();
const controls = new ContextControls({
elements: { _globalContextFlightsBtn: button },
installations: {},
actions: { getCockpit: () => null, claimVisualAuthority() {} },
});
const runs = [];
controls._runUserFacingContextAction = (operation) => {
runs.push(operation);
return Promise.resolve(false);
};
const click = () => button.dispatchEvent(new Event('click'));
controls._contextModeChanging = true;
click();
controls._contextModeChanging = false;
controls._clearSelectedLayersPromise = Promise.resolve();
click();
assert.equal(runs.length, 0, 'a transition or Clear All in flight drops it');
controls._clearSelectedLayersPromise = null;
click();
assert.equal(runs.length, 1, 'an idle panel takes the click');
controls.stop();
});
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();
const init = _initGlobalContextPanel.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 +135,88 @@ 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 its title, search, expand, 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.context-dock-btn',
'span.material-symbols-outlined',
'button.context-dock-btn',
'span.material-symbols-outlined',
'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 #global-context-panel:not(.collapsed) .panel-title",
),
'',
);
});
File diff suppressed because it is too large. Load diff
+73 -6
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,
@@ -462,10 +527,15 @@ export function cyberSonarLabelIntensity(
return labelDimFactor + (1 - labelDimFactor) * normalized;
}
/**
* Sonar is an opt-in visual style over any HUD layout: it is on only after
* the Display panel's Sonar toggle, a voice request or a legacy Cyber link
* turns it on.
*/
export function isCyberSonarEnabled(
root = globalThis.document?.documentElement,
) {
return root?.dataset?.cyberSonar !== 'off';
return root?.dataset?.cyberSonar === 'on';
}
export function setCyberSonarEnabled(
@@ -474,9 +544,7 @@ export function setCyberSonarEnabled(
) {
if (!root?.dataset) return false;
root.dataset.cyberSonar = enabled ? 'on' : 'off';
if (root.dataset.uiTheme === 'cyber') {
applyCyberSonarThemePhase(root, enabled);
}
applyCyberSonarThemePhase(root, enabled);
return enabled;
}
@@ -501,7 +569,6 @@ export function isCyberSonarActive({
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ??
false;
return !!(
root?.dataset?.uiTheme === 'cyber' &&
isCyberSonarEnabled(root) &&
(hudActive ?? hud?.classList?.contains?.('active')) &&
!body?.classList?.contains?.('cockpit-mode') &&
@@ -518,7 +585,7 @@ export function isCyberMapThemeActive({
if (hud === undefined)
hud = globalThis.document?.getElementById?.('intel-hud');
return !!(
root?.dataset?.uiTheme === 'cyber' &&
isCyberSonarEnabled(root) &&
(hudActive ?? hud?.classList?.contains?.('active')) &&
!body?.classList?.contains?.('cockpit-mode')
);
+13 -9
View File
@@ -39,7 +39,7 @@ test('production-transformed sonar defaults retain the document method receiver'
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
const hud = { classList: { contains: (name) => name === 'active' } };
const document = {
documentElement: { dataset: { uiTheme: 'cyber' } },
documentElement: { dataset: { cyberSonar: 'on' } },
body: { classList: { contains: () => false } },
getElementById(id) {
assert.equal(this, document);
@@ -57,7 +57,7 @@ test('production-transformed sonar defaults retain the document method receiver'
assert.ok(
Number.isFinite(compiled.createCyberSonarSampler(800, 600).at(400, 300)),
);
document.documentElement.dataset.uiTheme = 'tactical';
document.documentElement.dataset.cyberSonar = 'off';
assert.equal(compiled.isCyberSonarActive(), false);
assert.equal(compiled.isCyberMapThemeActive(), false);
} finally {
@@ -139,8 +139,8 @@ test('the sweep brightens contacts inside its sector and dims the remainder', ()
);
});
test('the sonar activates only for a visible Cyber map HUD with motion enabled', () => {
const root = { dataset: { uiTheme: 'cyber' } };
test('the sonar activates only while on, over a visible map HUD with motion enabled', () => {
const root = { dataset: { cyberSonar: 'on' } };
const classes = (...values) => ({
contains: (value) => values.includes(value),
});
@@ -220,14 +220,18 @@ test('the opacity setting controls every contact floor and preserves brighter la
);
});
test('the sonar control defaults on and records explicit operator state', () => {
test('the sonar control defaults off and records explicit operator state', () => {
const root = { dataset: {} };
assert.equal(isCyberSonarEnabled(root), false);
// The removed Cyber theme no longer turns it on.
root.dataset.uiTheme = 'cyber';
assert.equal(isCyberSonarEnabled(root), false);
assert.equal(setCyberSonarEnabled(true, root), true);
assert.equal(root.dataset.cyberSonar, 'on');
assert.equal(isCyberSonarEnabled(root), true);
assert.equal(setCyberSonarEnabled(false, root), false);
assert.equal(root.dataset.cyberSonar, 'off');
assert.equal(isCyberSonarEnabled(root), false);
assert.equal(setCyberSonarEnabled(true, root), true);
assert.equal(root.dataset.cyberSonar, 'on');
});
test('real Cesium points and billboards recover after repeated low/high opacity cycles', () => {
@@ -349,10 +353,10 @@ test('the sweep corrects delayed starts and reacquires restarted animations with
assert.doesNotThrow(() => syncCyberSonarAnimation({}));
});
test('the selected Cyber theme seeds and releases the compositor sweep phase', () => {
test('turning Sonar on seeds and releases the compositor sweep phase', () => {
const values = new Map();
const root = {
dataset: {},
dataset: { cyberSonar: 'on' },
style: {
setProperty: (name, value) => values.set(name, value),
removeProperty: (name) => values.delete(name),
-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;
};
}
+273 -242
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,45 +44,8 @@ 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', () => {
const root = { dataset: { uiTheme: 'cyber' }, style: { setProperty() {} } };
test('removed CSS mode cannot disable GPU contacts; unsupported renderers fail closed', () => {
const root = { dataset: { cyberSonar: 'on' }, style: { setProperty() {} } };
const options = {
root,
body: { classList: { contains: () => false } },
@@ -106,209 +66,280 @@ 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;
const root = { dataset: { uiTheme: 'cyber', cyberSonar: 'on' } };
let cockpit = false;
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: { cyberSonar: 'on' } };
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.cyberSonarOpacity = '50';
f.tick(false);
assert.equal(f.sets.length, 5, 'a setting change sets it at once');
assert.equal(
f.sets[4].floor,
0.5,
'while sweeping the floor is the opacity',
);
f.state.reducedMotion = true;
f.tick(false);
assert.equal(f.sets[5].radius, 0, 'reduced motion rests the sweep');
assert.equal(f.sets[5].floor, 0.5 + 0.5 * 0.46, 'at rest it lifts');
clock += 1000;
f.tick(true);
f.tick(false);
assert.equal(f.sets.length, 6, 'at rest only changes set it');
f.state.reducedMotion = false;
f.state.cockpit = true;
f.tick(false);
assert.equal(f.sets[6], null, 'out of the map it clears');
f.tick(true);
assert.equal(f.sets.length, 7, 'cleared once');
f.state.cockpit = false;
f.root.dataset.cyberSonar = 'off';
f.tick(false);
assert.equal(f.sets.length, 7, 'Sonar OFF leaves contacts untreated');
f.root.dataset.cyberSonar = 'on';
f.tick(false);
assert.ok(f.sets[7]?.radius > 0, 'Sonar ON sweeps at once');
f.root.dataset.cyberSonar = 'off';
f.tick(false);
assert.equal(f.sets[8], null, 'Sonar OFF clears it');
f.tick(true);
assert.equal(f.sets.length, 9);
// The removed Cyber theme attribute alone does nothing.
f.root.dataset.uiTheme = 'cyber';
f.tick(false);
assert.equal(f.sets.length, 9);
f.root.dataset.cyberSonar = 'on';
f.tick(false);
assert.ok(f.sets[9]?.radius > 0, 'back on, 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();
}
});
+14 -3
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,
@@ -94,7 +98,7 @@ export function normalizeAdsbLolAircraftState(aircraft, nowSeconds) {
* Normalize an adsb.lol point response to an OpenSky-compatible response.
* Invalid rows and positionless contacts are intentionally excluded.
* @param {object} payload adsb.lol v2 response.
* @returns {{time:number,states:Array[]}}
* @returns {{time:number,states:Array[],emergencyByIcao?:object,typeByIcao?:object}}
*/
export function normalizeAdsbLolPointResponse(payload) {
const responseNow = finiteNumber(payload?.now);
@@ -107,9 +111,10 @@ export function normalizeAdsbLolPointResponse(payload) {
const aircraft = Array.isArray(payload?.ac) ? payload.ac : [];
const states = [];
// Keep the OpenSky vectors unchanged. The regional fallback's extra readsb
// status travels alongside them, keyed only to admitted aircraft.
// status and type travel alongside them, keyed only to admitted aircraft.
const admitted = new Set();
const statuses = [];
const types = [];
for (const row of aircraft) {
const state = normalizeAdsbLolAircraftState(row, nowSeconds);
if (!state) continue;
@@ -121,11 +126,17 @@ export function normalizeAdsbLolPointResponse(payload) {
admitted.add(id);
if (typeof row.emergency === 'string')
statuses.push([id, row.emergency.trim().toLowerCase()]);
const type = typeof row.t === 'string' ? row.t.trim().toUpperCase() : '';
if (type) types.push([id, type]);
}
const emergencyByIcao = Object.fromEntries(statuses);
const typeByIcao = Object.fromEntries(types);
return {
time: nowSeconds,
states,
...(Object.keys(emergencyByIcao).length ? { emergencyByIcao } : {}),
// The ICAO type designator (readsb `t`), so the aircraft is classed from
// its first fix instead of after a lookup.
...(types.length ? { typeByIcao } : {}),
};
}
+31
View File
@@ -49,3 +49,34 @@ 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');
});
test('the point response sends each admitted aircraft type alongside the vectors', () => {
const response = normalizeAdsbLolPointResponse({
now: 1000,
ac: [
{ hex: 'A1B2C3', lat: 30, lon: -97, t: 'ec45' },
{ hex: 'A1B2C3', lat: 31, lon: -97, t: 'B738' },
{ hex: 'D4E5F6', lat: 30, lon: -98 },
{ hex: 'BAD000', t: 'A320' },
],
});
assert.equal(response.states.length, 3);
assert.deepEqual(response.typeByIcao, { a1b2c3: 'EC45' });
const untyped = normalizeAdsbLolPointResponse({
now: 1000,
ac: [{ hex: 'D4E5F6', lat: 30, lon: -98 }],
});
assert.equal(Object.hasOwn(untyped, 'typeByIcao'), false);
});
+35 -13
View File
@@ -401,6 +401,11 @@ const OPENSKY_CATEGORY = {
7: 'fastjet', // High performance (>5g, >400 kt)
8: 'helicopter', // Rotorcraft
9: 'glider',
16: 'vehicle', // Surface vehicle, emergency
17: 'vehicle', // Surface vehicle, service
18: 'station', // Point obstacle
19: 'station', // Cluster obstacle
20: 'station', // Line obstacle
};
/** ADS-B emitter-category string → class. */
@@ -413,13 +418,35 @@ const EMITTER_CATEGORY = {
A6: 'fastjet',
A7: 'helicopter',
B1: 'glider',
C1: 'vehicle', // Surface vehicle, emergency
C2: 'vehicle', // Surface vehicle, service
C3: 'station', // Point obstacle
C4: 'station', // Cluster obstacle
C5: 'station', // Line obstacle
};
/**
* The type codes feeds give what is not an aircraft: an airport vehicle
* (ZVEH) and a ground station (GRND).
*/
const GROUND_TYPE_CLASS = { ZVEH: 'vehicle', GRND: 'station' };
/**
* The class an aircraft draws and reads as, from its ICAO type code (which
* outranks the category), else its OpenSky integer or ADS-B emitter category.
* Besides the aircraft classes, `vehicle` is an airport vehicle (type ZVEH,
* emitter C1 or C2) and `station` a ground station or obstacle (type GRND,
* emitter C3 to C5). A known type code outside every set is an airliner, and
* so is a contact with nothing to go on.
* @param {{typeCode?: string|null, category?: string|number|null}} [record]
* @returns {string}
*/
export function classifyAircraft({ typeCode, category } = {}) {
const code = String(typeCode || '')
.trim()
.toUpperCase();
if (code) {
if (GROUND_TYPE_CLASS[code]) return GROUND_TYPE_CLASS[code];
if (FASTJET.has(code)) return 'fastjet';
if (UAV.has(code)) return 'uav';
if (HELI.has(code)) return 'helicopter';
@@ -452,18 +479,13 @@ export const AIRCRAFT_CLASS_LABELS = Object.freeze({
fastjet: msg('Fast jet'),
bizjet: msg('Business jet'),
uav: msg('Drone'),
vehicle: msg('Airport vehicle'),
station: msg('Ground station / obstacle'),
});
/** Billboard scale multipliers (skylight GLYPH_SCALE, + fastjet). */
export const CLASS_SCALE_2D = {
light: 0.62,
glider: 0.58,
turboprop: 0.86,
airliner: 1.0,
widebody: 1.3,
quadjet: 1.45,
helicopter: 0.82,
fastjet: 0.8,
bizjet: 0.72,
uav: 0.75,
};
/**
* The tint an airport vehicle's sprite draws with in Flights and Local
* ADS-B: an orange amber, apart from aircraft white and the military layer's
* yellow amber (#FFB800).
*/
export const VEHICLE_TINT_CSS = '#FF8F1F';
+49 -4
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 } from './aircraftClass.js';
import { AIRCRAFT_CLASS_LABELS, classifyAircraft } from './aircraftClass.js';
test('type-code classification (military layer path)', () => {
assert.equal(classifyAircraft({ typeCode: 'F16' }), 'fastjet');
@@ -48,8 +48,53 @@ test('typeCode outranks category; unknown → airliner', () => {
assert.equal(classifyAircraft({ typeCode: null, category: 0 }), 'airliner');
});
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);
test('every class has a label', () => {
for (const kind of [
'light',
'glider',
'turboprop',
'airliner',
'widebody',
'quadjet',
'helicopter',
'fastjet',
'bizjet',
'uav',
'vehicle',
'station',
]) {
assert.ok(AIRCRAFT_CLASS_LABELS[kind], kind);
}
});
test('airport vehicles and ground stations class apart from aircraft', () => {
// A feed's own types, in any case.
assert.equal(classifyAircraft({ typeCode: 'ZVEH' }), 'vehicle');
assert.equal(classifyAircraft({ typeCode: ' zveh ' }), 'vehicle');
assert.equal(classifyAircraft({ typeCode: 'GRND' }), 'station');
// Emitter categories: surface vehicles, then obstacles.
assert.equal(classifyAircraft({ category: 'C1' }), 'vehicle');
assert.equal(classifyAircraft({ category: 'C2' }), 'vehicle');
for (const category of ['C3', 'C4', 'C5'])
assert.equal(classifyAircraft({ category }), 'station', category);
// OpenSky's integer categories for the same.
assert.equal(classifyAircraft({ category: 16 }), 'vehicle');
assert.equal(classifyAircraft({ category: 17 }), 'vehicle');
assert.equal(classifyAircraft({ category: 18 }), 'station');
// A type code still outranks the category.
assert.equal(
classifyAircraft({ typeCode: 'ZVEH', category: 'A3' }),
'vehicle',
);
assert.equal(
classifyAircraft({ typeCode: 'A320', category: 'C1' }),
'airliner',
);
});
test('helicopter types and categories', () => {
for (const typeCode of ['EC35', 'R44', 'S76', 'H60', 'AS50', 'B407'])
assert.equal(classifyAircraft({ typeCode }), 'helicopter', typeCode);
assert.equal(classifyAircraft({ category: 'A7' }), 'helicopter');
assert.equal(classifyAircraft({ category: 8 }), 'helicopter');
});
+67 -24
View File
@@ -1,8 +1,17 @@
import * as Cesium from 'cesium';
import { TRACKED_ICON_COLOR } from '../layers/military/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 +147,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,36 +454,36 @@ 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' }),
});
assert.equal(rendering._modelColor('civil'), red);
if (rendering._cockpitContactColor)
assert.equal(rendering._cockpitContactColor('civil'), red);
// Tracking never recolours: a tracked emergency stays red.
flightState._trackedIcao = 'civil';
assert.equal(
rendering._modelColor('civil'),
factory === civilRendering ? Cesium.Color.CYAN : TRACKED_ICON_COLOR,
);
assert.equal(rendering._modelColor('civil'), red);
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]);
flightState._trackedIcao = 'civil';
assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]);
flightState._trackedIcao = null;
}
});
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 +491,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 +561,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
+483
View File
@@ -0,0 +1,483 @@
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, recoveryMs } from './motionModel.js';
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { createDisplayDelay } from './displayDelay.js';
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
import { ROTOR_STILL_FRAME } from './rotorFrames.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',
);
});
test('only airborne helicopters in view turn their rotor, written when the frame steps', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const here = fromDegrees(0, 30, 300);
const away = fromDegrees(90, 30, 300);
const records = new Map([
['h1', { klass: 'helicopter', onGround: false }],
['h2', { klass: 'helicopter', onGround: true }],
['p1', { klass: 'airliner', onGround: false }],
['h3', { klass: 'helicopter', onGround: false }],
]);
const state = {
now: () => Date.now(),
_icons: createContactIcons(),
_positionHistory: new Map(),
_cockpitNearContacts: new Set(),
records: { data: records, missingPolls: new Map() },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
rendering: {
_iconKind: (_id, klass) => klass,
_fleetBillboardColor: () => [1, 1, 1, 1],
_fleetBillboardScale: () => 1,
},
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
for (const id of records.keys()) {
state._icons.put(
{
id,
pos: id === 'h3' ? away : here,
motion: { kind: 'hold', courseDeg: 0 },
size: [20, 20],
},
{ expiresAt: Infinity },
);
icons._applyIconPresentation(id);
}
const image = (id) => state._icons.item(id).image;
// The grounded helicopter holds the still frame.
assert.equal(
image('h2'),
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
const h3Before = image('h3');
const writes = new Map();
const update = state._icons.update;
state._icons.update = (id, patch, options) => {
writes.set(id, (writes.get(id) ?? 0) + 1);
return update(id, patch, options);
};
// The fleet pass, every 80 ms for a second; h3 is out of view.
const inView = (p) => Math.abs(p.x - here.x) < 1;
const seen = new Set();
for (let step = 0; step <= 12; step++) {
if (step) t.mock.timers.tick(80);
icons._turnRotors(Date.now(), Date.now(), inView);
seen.add(image('h1'));
}
// Through every frame, written only on the steps its frame changed.
assert.equal(seen.size, 3);
for (const frame of [0, 1, 2])
assert.ok(seen.has(aircraftIcon('helicopter', FLEET_ICON_PX, frame)));
assert.ok(
writes.get('h1') >= 8 && writes.get('h1') <= 11,
`${writes.get('h1')} writes`,
);
assert.equal(writes.get('h2') ?? 0, 0, 'grounded: frozen');
assert.equal(writes.get('p1') ?? 0, 0, 'not a helicopter');
assert.equal(writes.get('h3') ?? 0, 0, 'out of view');
assert.equal(image('h3'), h3Before);
// Landing freezes it on the still frame.
records.get('h1').onGround = true;
icons._applyIconPresentation('h1');
const landed = writes.get('h1');
t.mock.timers.tick(400);
icons._turnRotors(Date.now(), Date.now(), inView);
assert.equal(writes.get('h1'), landed);
assert.equal(
image('h1'),
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
});
/** An icon layer over helicopters `ids`, all at `here`, for the rotor tests. */
function rotorFixture(records, positions, tracking = {}) {
const state = {
now: () => Date.now(),
_icons: createContactIcons(),
_positionHistory: new Map(),
_cockpitNearContacts: new Set(),
records: { data: records, missingPolls: new Map() },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
rendering: {
_iconKind: (_id, klass) => klass,
_fleetBillboardColor: () => [1, 1, 1, 1],
_fleetBillboardScale: () => 1,
},
tracking,
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
for (const id of records.keys()) {
state._icons.put(
{
id,
pos: positions[id],
motion: { kind: 'hold', courseDeg: 0 },
size: [20, 20],
},
{ expiresAt: Infinity },
);
icons._applyIconPresentation(id);
}
return { state, icons };
}
test('a tracked helicopter that lands shows the still frame at once', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]);
let synced = 0;
const { state, icons } = rotorFixture(
records,
{ h1: fromDegrees(0, 30, 300) },
{ _syncTrackedBillboardImage: () => synced++ },
);
state._trackedIcao = 'h1';
assert.equal(icons._rotorsTurning(), true);
records.get('h1').onGround = true;
icons._applyIconPresentation('h1');
assert.equal(synced, 1, 'the tracked billboard is given its images again');
assert.equal(icons._rotorsTurning(), false);
assert.equal(
icons._fleetLook('h1').image,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
// Taxiing faster than 1 m/s, its rotor turns again, as the model's does.
records.get('h1').velocity = 5;
icons._applyIconPresentation('h1');
assert.equal(icons._rotorsTurning(), true);
records.get('h1').velocity = 0;
icons._applyIconPresentation('h1');
assert.equal(synced, 2);
assert.equal(icons._rotorsTurning(), false);
// An untracked one landing does not touch the tracked billboard.
records.get('h1').onGround = false;
icons._applyIconPresentation('h1');
state._trackedIcao = null;
records.get('h1').onGround = true;
icons._applyIconPresentation('h1');
assert.equal(synced, 2);
});
test('a helicopter out of view is judged once per rotor frame, not every pass', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map();
const positions = {};
for (let i = 0; i < 300; i++) {
const id = `h${i}`;
records.set(id, { klass: 'helicopter', onGround: false });
positions[id] = fromDegrees(90, 30, 300);
}
const { state, icons } = rotorFixture(records, positions);
let judged = 0;
const inView = () => {
judged++;
return false;
};
const writes = [];
const update = state._icons.update;
state._icons.update = (id, ...rest) => {
writes.push(id);
return update(id, ...rest);
};
// Passes 10 ms apart for 2 s: 200 passes over 300 helicopters, all out of
// view. Each is judged at most once per frame step (20 steps), and not on
// a step back onto the frame it is drawn at.
for (let pass = 0; pass < 200; pass++) {
t.mock.timers.tick(10);
icons._turnRotors(Date.now(), Date.now(), inView);
}
assert.ok(judged <= 300 * 21, `${judged} judgements`);
assert.ok(judged >= 300 * 10, `${judged} judgements`);
assert.equal(writes.length, 0, 'none in view: no image written');
});
test('back at live, a placed contact eases from where it is drawn over a recovery, nose along the way', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const drawnAt = fromDegrees(0, 30, 3_000);
const SPEED = 200;
// The placement has it 2 km east of where it is drawn, flying east.
const placedAt = (wallMs) => {
const east = 2_000 + (SPEED * (wallMs - WORLD_MS)) / 1000;
return fromDegrees(east / (111_320 * Math.cos(Math.PI / 6)), 30, 3_000);
};
const plan = (handover, keep = {}) => {
const state = {
now: () => Date.now(),
_icons: createContactIcons(),
_positionHistory: new Map([['c', [{ epochMs: WORLD_MS }]]]),
records: { data: new Map([['c', {}]]) },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs },
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
placeAt: (_id, wallMs, _info, _history, out) => {
Object.assign(out, placedAt(wallMs));
return { courseDeg: 90, speedMps: SPEED };
},
});
state._icons.put(
{
id: 'c',
pos: drawnAt,
motion: { kind: 'hold', courseDeg: 0 },
course: 0,
size: [20, 20],
},
{ expiresAt: -Infinity },
);
icons._planIcon('c', handover ? { handover: true } : undefined);
keep.icons = icons;
return state._icons;
};
const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
const eased = plan(true);
const end = eased.expires('c');
assert.equal(end, WORLD_MS + recoveryMs(2_000, SPEED));
assert.ok(end - WORLD_MS > 1_000, 'longer than a placed plan');
assert.ok(metres(eased.position('c', WORLD_MS, {}), drawnAt) < 1);
assert.ok(metres(eased.position('c', end, {}), placedAt(end)) < 1);
// The nose points along the way from where it is drawn to where it goes.
assert.ok(Math.abs(eased.course('c', WORLD_MS) - 90) < 1);
const plain = plan(false);
assert.ok(
metres(plain.position('c', WORLD_MS, {}), placedAt(WORLD_MS)) < 1,
'without the handover it is drawn where it is placed',
);
// The next answer comes 15 s in, the ease still running: it eases on from
// where it is drawn then, not cut to where it is placed.
const keep = {};
const easing = plan(true, keep);
const firstEnd = easing.expires('c');
assert.ok(firstEnd - WORLD_MS > 15_000, 'an ease longer than a poll');
t.mock.timers.tick(15_000);
const at = Date.now();
const drawnThen = easing.position('c', at, {});
keep.icons._planIcon('c');
assert.ok(metres(easing.position('c', at, {}), drawnThen) < 1);
const reEnd = easing.expires('c');
assert.ok(reEnd > at + 1_000, 'eases on');
assert.ok(metres(easing.position('c', reEnd, {}), placedAt(reEnd)) < 1);
// Once it has caught up, the next answer draws it where it is placed.
t.mock.timers.tick(reEnd - at + 1);
keep.icons._planIcon('c');
assert.ok(
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
);
});
+117 -28
View File
@@ -8,9 +8,9 @@
* width/height 20 (24 tracked) in flights.js / militaryFlights.js, so Cesium
* DOWN-samples this larger, higher-precision source to the same on-screen
* footprint — crisp anti-aliased edges instead of an upscaled 32px bitmap. The
* on-screen size is unchanged and CLASS_SCALE_2D is untouched (no scale
* compensation needed: the billboard's explicit width/height, not the SVG's,
* sets the pixel size — the intrinsic SVG size only controls raster fidelity).
* on-screen size is unchanged (the billboard's explicit width/height, not the
* SVG's, sets the pixel size — the intrinsic SVG size only controls raster
* fidelity).
*
* All glyphs are nose-up (nose toward -Y at rotation 0; the screen-projected
* rotation pipeline in iconOrientation.js spins the whole glyph). Fill is white
@@ -23,12 +23,19 @@
* quadjet/glider use the "bold" chart-symbol redraw; light/fastjet keep the
* original drawings. Raster fidelity doubled (192px source, same 96 coords).
*
* The helicopter is a top-down body under a four-blade rotor drawn in three
* frames (`aircraftIcon('helicopter', px, frame)`, turned by
* `rotorFrames.js`). Two kinds are not aircraft: `vehicle`, one sprite for
* every airport vehicle, and `station`, a mast for ground stations, drawn
* upright.
*
* Silhouette language follows skylight's type-aware glyphs (MIT,
* https://github.com/cpaczek/skylight): slender fuselages, swept wings for
* jets, long high-aspect wings for the glider, straight wings + prop discs for
* props, a rotor disc + tail boom + tail-rotor for the helicopter, and a delta
* for the fast jet. Each class has a DISTINCT planform so it reads at ~20px by
* shape, not just by footprint size.
* shape alone: every glyph is fitted to the same extent, so none is bigger
* than another.
*/
const VIEW = 96;
@@ -130,23 +137,6 @@ const BODIES = {
L -3,-25 C -3,-29 -2.4,-33 0,-35 Z" fill="white" ${STROKE_BOLD}/>
<rect x="-10.5" y="32.5" width="21" height="5" rx="1.5" fill="white" ${STROKE_BOLD}/>`,
// ── Helicopter: a SOLID translucent main-rotor disc (survives downscale as an
// obvious circle, unlike a thin ring) with a bold two-blade cross, a
// teardrop cabin, a tail boom, and a tail rotor. Unmistakable "disc on top"
// silhouette that never reads as a fixed-wing.
helicopter: `
<circle cx="0" cy="-6" r="31" fill="white" fill-opacity="0.22"/>
<g transform="rotate(45 0 -6)">
<rect x="-30.5" y="-8.2" width="61" height="4.4" rx="2.2" fill="white" fill-opacity="0.9"/>
<rect x="-30.5" y="-8.2" width="61" height="4.4" rx="2.2" fill="white" fill-opacity="0.9" transform="rotate(90 0 -6)"/>
</g>
<path d="M0,-22 C 8,-20 10.5,-13 10.5,-6 C 10.5,2 7.5,7 0,8.5
C -7.5,7 -10.5,2 -10.5,-6 C -10.5,-13 -8,-20 0,-22 Z" fill="white" ${STROKE}/>
<path d="M-2.6,8 L 2.6,8 L 1.8,32 L -1.8,32 Z" fill="white" ${STROKE}/>
<path d="M-8,27 L 8,27 L 8,30.6 L -8,30.6 Z" fill="white"/>
<circle cx="5.6" cy="35" r="6" fill="white" fill-opacity="0.6"/>
<circle cx="5.6" cy="35" r="2.1" fill="white"/>`,
// ── Fast jet: sharp delta/cropped-delta with a pointed nose, LERX root
// blend, and twin tail fins. Aggressive, all-wing.
fastjet: `
@@ -236,6 +226,87 @@ const BODIES = {
L -1.6,30 L -13,36 L -13,32 L -2.1,24
L -2.3,0 L -43,-2.5 L -43,-7 L -2.4,-12
L -4.4,-30 C -4.6,-35 -3.6,-40 0,-40 Z" fill="white" ${STROKE}/>`,
// ── Airport vehicle (type ZVEH, emitter C1/C2): one service van seen from
// above, front up, for every kind (fire truck, tug, car, de-icer). A
// boxy body, a dark windscreen band and a roof light bar; the layer
// tints it amber so it reads apart from aircraft.
vehicle: `
<path d="M-12,-39 L 12,-39 L 15,-36 L 15,38 L 13,40 L -13,40 L -15,38
L -15,-36 Z" fill="white" ${STROKE}/>
<path d="M-18.5,-25 h4 v3 h-4 Z M14.5,-25 h4 v3 h-4 Z" fill="white" ${STROKE}/>
<path d="M-13,-32 L 13,-32 L 12,-21 L -12,-21 Z" fill="rgba(0,0,0,0.62)"/>
<rect x="-10" y="-13" width="20" height="5" rx="1.5" fill="rgba(0,0,0,0.45)"/>`,
// ── Ground station or obstacle (type GRND, emitter C3–C5): a radio mast
// with two pairs of signal arcs, drawn upright on screen, never turned.
station: `
<path d="M7.1,-38.4 A 11 11 0 0 1 7.1,-21.6 M-7.1,-38.4 A 11 11 0 0 0 -7.1,-21.6
M12.2,-44.6 A 19 19 0 0 1 12.2,-15.4 M-12.2,-44.6 A 19 19 0 0 0 -12.2,-15.4"
fill="none" stroke="rgba(0,0,0,0.32)" stroke-width="5" stroke-linecap="round"/>
<path d="M7.1,-38.4 A 11 11 0 0 1 7.1,-21.6 M-7.1,-38.4 A 11 11 0 0 0 -7.1,-21.6
M12.2,-44.6 A 19 19 0 0 1 12.2,-15.4 M-12.2,-44.6 A 19 19 0 0 0 -12.2,-15.4"
fill="none" stroke="white" stroke-width="3.4" stroke-linecap="round"/>
<circle cx="0" cy="-30" r="4.5" fill="white" ${STROKE}/>
<path d="M-2.5,-25 L 2.5,-25 L 7,34 L 13,34 L 13,38 L -13,38 L -13,34
L -7,34 Z" fill="white" ${STROKE}/>`,
};
/**
* The helicopter, seen from above: a cabin, tail boom and tail plane under a
* four-blade main rotor. The rotor turns in {@link ROTOR_FRAMES} frames 30°
* apart; four blades repeat every 90°, so the third frame steps back onto
* the first and the loop is seamless. The middle frame (blades as an X) is
* the still one.
*/
const HELI_ROTOR_CENTRE_Y = -11.2;
const HELI_DISC = `<circle cx="0" cy="${HELI_ROTOR_CENTRE_Y}" r="32.8" fill="white" fill-opacity="0.22"/>`;
const HELI_BODY = `
<path d="M0,-33.4 L -2.3,-32.1 L -4.2,-28 L -4.3,-30.6 L -6.2,-30.6
L -6.2,0.2 L -4.3,0.2 L -4.2,-3.1 L -1.9,7.9 L -1.7,18.9
L -7.4,19.2 L -7.8,24 L -2.9,24.4 L -3.2,35.6 L -1.2,36
L 0,34.3 L 1.2,36 L 3.2,35.6 L 2.9,24.4 L 7.8,24 L 7.4,19.2
L 1.7,18.9 L 1.9,7.9 L 4.2,-3.1 L 4.3,0.2 L 6.2,0.2 L 6.2,-30.6
L 4.3,-30.6 L 4.2,-28 L 2.3,-32.1 Z" fill="white" ${STROKE}/>
<circle cx="0" cy="${HELI_ROTOR_CENTRE_Y}" r="3.2" fill="white" ${STROKE}/>`;
/** Main-rotor blade angle of each frame, degrees clockwise. */
const ROTOR_ANGLES_DEG = [15, 45, 75];
/** How many rotor frames the helicopter turns through. */
export const ROTOR_FRAMES = ROTOR_ANGLES_DEG.length;
/** The frame a helicopter holds when its rotor does not turn. */
export const ROTOR_STILL_FRAME = 1;
/** One rotor frame: the disc, two crossed blades at `angle`, the body over them. */
function helicopterBody(frame) {
const angle = ROTOR_ANGLES_DEG[frame] ?? ROTOR_ANGLES_DEG[ROTOR_STILL_FRAME];
const blade = (deg) =>
`<rect x="-32.2" y="${HELI_ROTOR_CENTRE_Y - 2.2}" width="64.4" height="4.4" rx="2.2" fill="white" fill-opacity="0.92" stroke="rgba(0,0,0,0.25)" stroke-width="0.8" transform="rotate(${deg} 0 ${HELI_ROTOR_CENTRE_Y})"/>`;
return `${HELI_DISC}${blade(angle)}${blade(angle + 90)}${HELI_BODY}`;
}
/**
* Every sprite draws at one size. The bodies were drawn at different spans
* (a light aircraft's half-extent is 32.8 units, a quadjet's 47), so each is
* scaled until its farthest painted edge, stroke included, sits
* {@link GLYPH_HALF_EXTENT} units from the centre. Values are each body's
* measured half-extent; aircraftIcons.test.mjs re-measures the rasters.
*/
const GLYPH_HALF_EXTENT = 44;
const BODY_HALF_EXTENT = {
airliner: 42.7,
widebody: 45.7,
quadjet: 47.0,
turboprop: 40.7,
light: 32.8,
glider: 46.0,
fastjet: 44.7,
bizjet: 42.7,
uav: 43.7,
helicopter: 44.0,
vehicle: 40.7,
station: 47.1,
tr3b: 40.8,
tr3bHot: 42.3,
};
const _iconCache = new Map();
@@ -252,21 +323,39 @@ 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. */
const TRACKED_RASTER_PX = 192;
/** Data URI for a class silhouette (lazily built, cached per kind+size).
* Default size serves the fleet; pass `aircraftIcon(kind, TRACKED_ICON_PX)`
* (re-exported below) for the tracked billboard. */
/** Raster size of the tracked glyph and every glyph's near image. */
export const TRACKED_ICON_PX = TRACKED_RASTER_PX;
export function aircraftIcon(kind, px = FLEET_RASTER_PX) {
const k = BODIES[kind] ? kind : 'airliner';
const key = `${k}@${px}`;
/**
* Data URI for a class silhouette (lazily built, cached per kind, size and
* frame). The default size serves the fleet; pass
* `aircraftIcon(kind, TRACKED_ICON_PX)` for the near image.
* @param {string} kind A `classifyAircraft()` class, or a TR-3B kind.
* @param {number} [px] Raster size.
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
* (the still frame by default); other kinds have one image.
* @returns {string}
*/
export function aircraftIcon(kind, px = FLEET_RASTER_PX, frame) {
const heli = kind === 'helicopter';
const k = heli || BODIES[kind] ? kind : 'airliner';
const f = heli
? Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
? frame
: ROTOR_STILL_FRAME
: 0;
const key = `${k}@${px}#${f}`;
let uri = _iconCache.get(key);
if (!uri) {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C})">${BODIES[k]}</g></svg>`;
const body = heli ? helicopterBody(f) : BODIES[k];
const fit = +(GLYPH_HALF_EXTENT / BODY_HALF_EXTENT[k]).toFixed(4);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C}) scale(${fit})">${body}</g></svg>`;
uri = 'data:image/svg+xml;base64,' + _b64(svg);
_iconCache.set(key, uri);
}
+57
View File
@@ -0,0 +1,57 @@
// src/data/aircraftIcons.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import sharp from 'sharp';
import { aircraftIcon, ROTOR_FRAMES } from './aircraftIcons.js';
const KINDS = [
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
'helicopter',
'vehicle',
'station',
'tr3b',
'tr3bHot',
];
const PX = 480;
/** Farthest painted pixel from the centre, in the 96-unit glyph space. */
async function halfExtent(uri) {
const svg = Buffer.from(uri.split(',')[1], 'base64');
const { data, info } = await sharp(svg)
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
let half = 0;
const c = info.width / 2;
for (let y = 0; y < info.height; y++) {
for (let x = 0; x < info.width; x++) {
if (data[(y * info.width + x) * 4 + 3] <= 8) continue;
half = Math.max(half, c - x, x + 1 - c, c - y, y + 1 - c);
}
}
return (half * 96) / info.width;
}
test('every sprite fills the same extent, whatever its class', async () => {
const extents = {};
for (const kind of KINDS) {
extents[kind] = await halfExtent(aircraftIcon(kind, PX));
}
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
extents[`helicopter#${frame}`] = await halfExtent(
aircraftIcon('helicopter', PX, frame),
);
}
for (const [kind, half] of Object.entries(extents)) {
assert.ok(Math.abs(half - 44) <= 0.6, `${kind}: ${half.toFixed(2)}`);
}
});
File diff suppressed because it is too large. Load diff
Loaded 100 of 2602 files, more files were not shown because too many files have changed in this diff. Show more