Merge remote-tracking branch 'origin/main' into denis/iss-live-telemetry

# Conflicts:
#	docs/CURRENT-STATE.md
#	scripts/package-boundaries.json
#	src/layers/satellites/interaction.js
#	src/layers/satellites/lifecycle.js
#	src/layers/satellites/tracking.js
This commit is contained in:
Denis Groshev committed 2026-11-16 11:40:19 +01:00
commit fd3ca679ec
1125 files changed
+149994 -45970

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) {
+62 -62
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)
@@ -406,7 +413,6 @@ export function createScreenAnnotationRenderer(
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) {
@@ -427,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;
@@ -481,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()) {
@@ -834,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(
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', () => {
+28 -20
View File
@@ -1,8 +1,11 @@
import { catalogControlServices } from './catalog.js';
import { StyleManager } from '../ui/composition.js';
import { flyToAustin } from '../camera.js';
import { installZoomOutGuard } from './zoomOutGuard.js';
import { applyStartView, START_VIEW } from '../camera.js';
import { initCockpitCloudEffects } from '../cockpitCloudEffects.js';
import { createViewSky } from '../viewSky.js';
import { findGlobe } from '../render/rendererOf.js';
import { useDisplayStore } from '../ui/stores/display.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { t } from '../i18n/index.js';
/**
@@ -10,12 +13,13 @@ import { t } from '../i18n/index.js';
* opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host
* whose address does not carry one. `localePicker: false` removes the language
* picker, for a host that offers its own language choice (`switchLocale` from
* the `./i18n` entry).
* the `./i18n` entry). `startView` is where the camera starts (the whole
* planet by default; a host may pass a city); a shared view flies from there.
* `services.cockpitSubjects` adds the application's own first-person subjects
* to the Cockpit (src/cockpitSubjectProviders.js).
*/
export function createApplicationControls({
scene: { viewer, mapStackController, operations },
scene: { viewer, mapStackController, operations, viewerDrawsEntity },
loaderStatus,
Controls = StyleManager,
services,
@@ -24,7 +28,10 @@ export function createApplicationControls({
defer,
initialShareCode = null,
localePicker = true,
startView = START_VIEW,
}) {
// Every boot starts from the same view, before share restoration flies on.
applyStartView(viewer, startView);
// Initialize the style manager (post-processing, HUD, locations, share links)
const styleManager = new Controls(viewer, {
services: {
@@ -34,6 +41,8 @@ export function createApplicationControls({
fetchRegionalBrief: (...args) =>
operations.requests.regional.getBrief(...args),
...catalogControlServices(catalog),
// Whether an entity is one of the viewer's own; the scene answers it.
viewerDrawsEntity: viewerDrawsEntity ?? services?.viewerDrawsEntity,
},
requestServices: operations.requests,
mapStackController,
@@ -45,28 +54,27 @@ export function createApplicationControls({
defer(() => styleManager.orbitController.stop());
defer(() => styleManager.hud.destroy());
defer(() => styleManager.dispose());
defer(
installZoomOutGuard(viewer, {
subscribeCameraHandoff: (listener) =>
styleManager.subscribeCameraHandoff?.(listener),
}),
);
// The previous multi-canvas weather compositor remains disabled. Cockpit
// clouds use a separate, capped low-resolution GPU pass that never attaches
// Cesium fog or post-process stages and is fully stopped in map mode.
const weatherEffects = null;
const cockpitCloudEffects = initCockpitCloudEffects(viewer, {
weatherService: operations.requests.weather,
});
// Where the renderer draws weather, it draws the cockpit's clouds too.
const cockpitCloudEffects = findGlobe(viewer)?.weather
? null
: initCockpitCloudEffects(viewer, {
weatherService: operations.requests.weather,
});
defer(() => cockpitCloudEffects?.destroy());
// The atmosphere, sun lighting, sun, moon, stars and Milky Way the user
// chooses in the Display panel.
const viewSky = createViewSky(viewer, {
store: useDisplayStore(applicationPinia()),
});
defer(() => viewSky.destroy());
// If no share link state, do default fly-to Austin
if (!styleManager.hasShareState) {
loaderStatus.textContent = t('Flying to Austin, TX...');
defer(flyToAustin(viewer));
} else {
loaderStatus.textContent = t('Restoring shared view...');
}
loaderStatus.textContent = styleManager.hasShareState
? t('Restoring shared view...')
: t('Loading');
return { styleManager, weatherEffects, cockpitCloudEffects };
}
+6 -32
View File
@@ -1,9 +1,8 @@
import test, { after, before } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import '../testSupport/stubMgrs.mjs';
import { installVueDom } from '../testSupport/vueDom.mjs';
import { MAXIMUM_ZOOM_DISTANCE_M } from './zoomOutGuard.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
const { createApplicationControls } = await import('./controls.js');
@@ -13,35 +12,20 @@ before(() => {
});
after(() => uninstallDom());
test('application controls install the zoom-out guard and remove it on teardown', () => {
const canvas = document.createElement('canvas');
const controller = { maximumZoomDistance: Infinity };
const scene = {
mode: Cesium.SceneMode.SCENE3D,
screenSpaceCameraController: controller,
preRender: new Cesium.Event(),
postUpdate: new Cesium.Event(),
};
const camera = {
position: Cesium.Cartesian3.fromDegrees(0, 0, 1_000_000),
positionCartographic: { height: 1_000_000 },
};
const viewer = { scene, camera, canvas };
const handoffs = new Set();
test('the application controls start and stop', () => {
class Controls {
hasShareState = true;
orbitController = { stop() {} };
hud = { destroy() {} };
dispose() {}
subscribeCameraHandoff(listener) {
handoffs.add(listener);
return () => handoffs.delete(listener);
}
}
const cleanups = [];
createApplicationControls({
scene: {
viewer,
viewer: bindFakeCesiumCamera({
isDestroyed: () => false,
camera: { setView() {} },
}),
mapStackController: {},
operations: {
surface: { controlServices: {} },
@@ -54,15 +38,5 @@ test('application controls install the zoom-out guard and remove it on teardown'
catalog: { get: (id) => ({ id }) },
defer: (cleanup) => cleanups.push(cleanup),
});
assert.equal(controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
assert.equal(scene.preRender.numberOfListeners, 1);
assert.equal(scene.postUpdate.numberOfListeners, 1);
assert.equal(handoffs.size, 1);
for (const cleanup of cleanups.reverse()) cleanup();
assert.equal(controller.maximumZoomDistance, Infinity);
assert.equal(scene.preRender.numberOfListeners, 0);
assert.equal(scene.postUpdate.numberOfListeners, 0);
assert.equal(handoffs.size, 0);
});
+1 -1
View File
@@ -15,7 +15,7 @@ export function createApplicationData({
const dataManager = new LayerLifecycle(viewer, {
allowQaRegistration,
// A panel's host may report it hidden while it is on screen; its layers
// keep polling (see keepPanelRendering in embed.js).
// keep polling (see keepPanelRendering in app/panelRendering.js).
visibilityTarget: panelAwareVisibility(document),
getSourceAvailability: catalog?.getSourceAvailability,
});
+24 -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();
};
}
-5
View File
@@ -1,8 +1,6 @@
import * as Cesium from 'cesium';
import { createDroneAirspaceLayer } from '../../layers/droneAirspace/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { isPointerFree } from '../../data/inputOwnership.js';
/** Wire FAA special-use airspace into the application catalog. */
export function createApplicationDroneAirspace(options) {
@@ -13,10 +11,7 @@ export function createApplicationDroneAirspace(options) {
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
...options,
});
}
-4
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { createFirmsHeatmapLayer as createLayer } from '../../layers/firms/index.js';
import * as render from '../../renderGovernor.js';
import * as sprites from '../../data/spriteOrder.js';
@@ -29,8 +28,5 @@ export function createApplicationFirms({ surface, ...options }) {
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
screenSpaceEventHandlerFactory:
options.screenSpaceEventHandlerFactory ??
((viewer) => new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)),
});
}
-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,
});
}
-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,
});
}
-2
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,
@@ -52,7 +51,6 @@ export function createApplicationRail({
camera: {
framing: WORLD_FOCUS_FRAMING.train,
requestWorldFocus,
applyTrackedCameraFrame,
isCockpitActive: () =>
globalThis.document?.body?.classList?.contains('cockpit-mode') ===
true,
-3
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { createShipwrecksLayer } from '../../layers/shipwrecks/index.js';
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
@@ -14,8 +13,6 @@ export function createApplicationShipwrecks(options) {
hitTest: overlays.hitTestWorldOverlay,
},
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
screenSpaceEventHandlerFactory: (viewer) =>
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
picking,
pointer: { isPointerFree },
...options,
+1 -3
View File
@@ -3,9 +3,7 @@ import { createMapillaryProvider } from '../../layers/streetLevel/providers/mapi
import { createGoogleProvider } from '../../layers/streetLevel/providers/google/index.js';
import { createKartaViewProvider } from '../../layers/streetLevel/providers/kartaview/index.js';
import { createPanoramaxProvider } from '../../layers/streetLevel/providers/panoramax/index.js';
import * as sprites from '../../data/spriteOrder.js';
import * as picking from '../../data/pickRegistry.js';
import * as input from '../../data/inputOwnership.js';
import * as scenePick from '../../data/scenePick.js';
import * as render from '../../renderGovernor.js';
@@ -37,6 +35,6 @@ export function createApplicationStreetLevel({
}) {
return createStreetLevelLayer({
providers,
services: { sprites, picking, input, scenePick, render },
services: { picking, scenePick, render },
});
}
-3
View File
@@ -1,12 +1,9 @@
import * as Cesium from 'cesium';
import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js';
import { overlayHost } from './overlayHost.js';
/** Wire cable source geometry to the application overlay host. */
export function createApplicationCables(options) {
return createSubmarineCableLayer({
overlayHost,
screenSpaceEventHandlerFactory: (canvas) =>
new Cesium.ScreenSpaceEventHandler(canvas),
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
...options,
});
-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;
+148 -41
View File
@@ -1,30 +1,66 @@
import { createApplicationOperations } from './operations.js';
import * as Cesium from 'cesium';
import {
createApplicationViewer,
installFreeLookHeightLimit,
installTrackpadPinchZoom,
} from '../app/viewer.js';
import { registerDataCredits } from '../data/dataCredits.js';
import { configureCreditKeyboardAccess } from '../creditKeyboard.js';
import { mountCreditsView } from '../ui/creditsView.js';
import { MapStackController } from '../mapStackController.js';
import { loadPhotorealisticTileset } from '../mapStartup.js';
import { mapEngineFor } from '../maps/engine.js';
import { initLogoGaze } from '../logoGaze.js';
import { inputFor } from '../input/dispatcher.js';
import {
holdContinuousRender,
installRenderGovernor,
uninstallRenderGovernor,
governorRequestRender,
holdContinuousRender,
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,
@@ -51,26 +87,76 @@ 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,
@@ -83,32 +169,35 @@ export async function createApplicationScene({
: releaseContinuousRender('world-time'),
}),
);
defer(installFreeLookHeightLimit(viewer));
registerDataCredits(viewer, credits);
configureCreditKeyboardAccess(document);
defer(onLocaleChange(() => configureCreditKeyboardAccess(document)));
// The credits, in the application's own line, unless the renderer shows
// them in a display of its own.
if (!hooks.ownCreditDisplay) defer(mountCreditsView(viewer));
loaderStatus.textContent =
googleApiKey || googleTokens || cesiumToken
? t('Loading Google 3D Tiles...')
: t('Loading the keyless globe...');
const photoreal = await loadPhotorealisticTileset(Cesium, {
// The map stacks, and the photoreal base among them, switch through the
// scene's map engine: the renderer's own, or its globe port.
const engine = mapOptions.engine ?? mapEngineFor(viewer);
const photoreal = (await engine.loadPhotoreal?.(viewer, {
googleApiKey,
googleTokens,
cesiumToken,
});
})) ?? { tileset: null, route: 'none', errors: [] };
const tileset = photoreal.tileset;
// A provider can finish after cancellation; retain ownership of its result.
defer(() => {
if (tileset && !tileset.isDestroyed()) {
if (!viewer.scene.primitives.remove(tileset)) tileset.destroy();
}
if (!tileset || engine.isDestroyed(tileset)) return;
engine.removeTileset(viewer, tileset);
engine.release(tileset);
});
signal.throwIfAborted();
if (tileset) {
viewer.scene.primitives.add(tileset);
engine.addTileset(viewer, tileset);
// NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom.
// Google Photorealistic 3D Tiles provide their own terrain/elevation.
viewer.scene.globe.show = false;
renderer.globe.setGlobeVisible(false);
console.info(`[Init] Google 3D Tiles loaded via ${photoreal.route}.`);
} else {
if (photoreal.errors.length) {
@@ -125,7 +214,7 @@ export async function createApplicationScene({
},
);
}
viewer.scene.globe.show = true;
renderer.globe.setGlobeVisible(true);
}
loaderStatus.textContent = t('Initializing systems...');
@@ -133,6 +222,7 @@ export async function createApplicationScene({
const mapStackController = new MapController(viewer, {
requestRender: governorRequestRender,
...mapOptions,
engine,
googleTileset: tileset,
cesiumToken,
initialStack: tileset ? 'photoreal' : 'esri-imagery',
@@ -154,5 +244,22 @@ export async function createApplicationScene({
});
signal.throwIfAborted();
return { viewer, tileset, mapStackController, operations };
return {
renderer,
viewer,
tileset,
mapStackController,
operations,
input,
// Keeps the globe drawing in an inline panel whose host stops animation
// frames (embed mode, src/app/embed.js); returns its disposer.
keepPanelRendering: (options) => keepPanelRendering(renderer, options),
// What the renderer's plugin hands the application beside the contract,
// each optional: trims stale draw commands, says whether an entity is
// the renderer's own, and what QA scripts read
// (render/applicationHooks.js).
trimStaleCommands: hooks.trimStaleCommands,
viewerDrawsEntity: hooks.viewerDrawsEntity,
qaHandles: hooks.qaHandles,
};
}
+152
View File
@@ -0,0 +1,152 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApplicationScene } from './scene.js';
import { createApplicationRequestServices } from '../services/requests.js';
import { createStubRendererPlugin } from '../render/stub/index.js';
import { rendererOf } from '../render/rendererOf.js';
/** Start the scene on a stub renderer with `capabilities`. */
async function startOnStub(t, { capabilities = [], ...rest } = {}) {
document.body.innerHTML = '<div id="cesiumContainer"></div>';
const made = [];
const deferred = [];
t.after(async () => {
for (const fn of deferred.reverse()) await fn();
});
const scene = await createApplicationScene({
renderer: createStubRendererPlugin({ capabilities }, (renderer) =>
made.push(renderer),
),
requestServices: createApplicationRequestServices(),
loaderStatus: { textContent: '' },
signal: new AbortController().signal,
defer: (fn) => deferred.push(fn),
...rest,
});
return { scene, renderer: made[0], deferred };
}
test('the scene runs on a renderer with only the required members', async (t) => {
const { scene, renderer, deferred } = await startOnStub(t);
assert.equal(scene.renderer, renderer);
assert.equal(rendererOf(scene.viewer), renderer, 'the scene object is bound');
assert.equal(
scene.viewer.container,
document.getElementById('cesiumContainer'),
);
assert.equal(scene.viewer.isDestroyed(), false);
assert.ok(
scene.viewer.container.contains(renderer.canvas),
'the renderer fills the container',
);
// Nothing of the engine on the scene object.
assert.deepEqual(Object.keys(scene.viewer).sort(), [
'container',
'isDestroyed',
]);
// No hooks: each is left out, not faked.
for (const name of ['trimStaleCommands', 'viewerDrawsEntity', 'qaHandles'])
assert.equal(scene[name], undefined, name);
// What the renderer does through its ports.
assert.equal(typeof scene.keepPanelRendering, 'function');
assert.equal(
renderer.camera.controls.keepEarthFramed,
undefined,
'no framing on a renderer without it',
);
// Keyless, the map stack shows Esri on the globe through the globe port.
assert.equal(scene.tileset, null);
assert.equal(scene.mapStackController.getActiveId(), 'esri-imagery');
const layers = renderer.globe.imagery.list();
assert.equal(layers.length, 1, 'one base imagery layer');
assert.ok(
renderer.testing.calls.some(
(call) =>
call.port === 'globe' &&
call.member === 'imagery.add' &&
call.args[0]?.url?.includes('World_Imagery'),
),
'Esri imagery through the port',
);
assert.equal(scene.mapStackController.getDrapeSurface(), 'globe');
// The credits show in the application's own line: the Esri base's on it,
// the data credits in the list it opens.
const line = document.getElementById('gev-credits');
assert.ok(line, 'a credits line');
assert.match(line.textContent, /Esri/);
assert.ok(
document.querySelectorAll('#gev-credits-panel li').length > 10,
'the data credits',
);
// Switching stacks goes through the port too.
await scene.mapStackController.setStack('osm');
assert.equal(scene.mapStackController.getActiveId(), 'osm');
assert.equal(renderer.globe.imagery.list().length, 1, 'Esri gave way');
for (const fn of deferred.splice(0).reverse()) await fn();
assert.equal(scene.viewer.isDestroyed(), true);
assert.equal(rendererOf(scene.viewer), null, 'and lets go of the renderer');
assert.equal(renderer.globe.imagery.list().length, 0, 'imagery released');
assert.equal(document.getElementById('gev-credits'), null, 'credits gone');
});
test('the scene keeps the Earth framed where the renderer can', async (t) => {
const { renderer, deferred } = await startOnStub(t, {
capabilities: ['keepEarthFramed'],
});
assert.equal(renderer.camera.controls.keepEarthFramed, true);
const controls = renderer.camera.controls;
for (const fn of deferred.splice(0).reverse()) await fn();
assert.equal(controls.keepEarthFramed, false, 'and lets go on teardown');
});
test("the scene takes a plugin's application hooks", async (t) => {
const stub = createStubRendererPlugin({ capabilities: [] });
const given = [];
const handles = Object.freeze({ probe: 'qa' });
const { scene } = await startOnStub(t, {
renderer: {
id: 'stub-with-hooks',
create: (options) => stub.create(options),
applicationHooks(made) {
given.push(made);
return { qaHandles: handles, ownCreditDisplay: true };
},
},
});
assert.deepEqual(given, [scene.renderer], 'asked once, for the renderer');
assert.equal(scene.qaHandles, handles, 'QA scripts read its handles');
assert.equal(
document.getElementById('gev-credits'),
null,
'its own display shows the credits',
);
});
test('with credentials, the photoreal base loads through the globe port', async (t) => {
const { scene, renderer } = await startOnStub(t, {
capabilities: ['photoreal', 'globeVisibility'],
googleApiKey: 'stub-key',
});
assert.ok(scene.tileset, 'a photoreal base');
assert.equal(scene.mapStackController.getActiveId(), 'photoreal');
assert.equal(renderer.globe.isGlobeVisible(), false, 'the globe is hidden');
const photoreal = renderer.testing.calls.filter(
(call) => call.port === 'globe' && call.member === 'setPhotoreal',
);
assert.equal(photoreal[0]?.args[0]?.key, 'stub-key');
// A globe stack hides photoreal through the port, and shows the globe.
await scene.mapStackController.setStack('esri-imagery');
assert.equal(renderer.globe.isGlobeVisible(), true);
assert.equal(
renderer.testing.calls
.filter((call) => call.port === 'globe' && call.member === 'setPhotoreal')
.at(-1).args[0],
null,
);
await scene.mapStackController.setStack('photoreal');
assert.equal(renderer.globe.isGlobeVisible(), false);
});
+2
View File
@@ -1,3 +1,5 @@
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
import '../render/cesium/input.js';
import assert from 'node:assert/strict';
import test from 'node:test';
import {
+31 -15
View File
@@ -1,25 +1,41 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { flyToAustin } from '../camera.js';
import { applyStartView, START_VIEW } from '../camera.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
test('teardown before the initial camera delay prevents a late flight', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let flights = 0;
let cancelled = 0;
const stop = flyToAustin({
function viewerRecording(views) {
return bindFakeCesiumCamera({
isDestroyed: () => false,
camera: {
setView() {},
flyTo() {
flights++;
setView(view) {
views.push(view);
},
cancelFlight() {
cancelled++;
flyTo() {
assert.fail('a start view is set, not flown to');
},
},
});
stop();
t.mock.timers.tick(1000);
assert.equal(flights, 0);
assert.equal(cancelled, 1);
}
test('the camera starts over the whole planet, looking straight down', () => {
const views = [];
applyStartView(viewerRecording(views));
assert.equal(views.length, 1);
assert.ok(START_VIEW.height >= 20000000, 'the whole planet is in view');
assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 2) < 1e-9);
assert.equal(views[0].orientation.heading, 0);
});
test('a host can start the camera at a city instead', () => {
const views = [];
applyStartView(viewerRecording(views), {
lon: 2.35,
lat: 48.86,
height: 5000,
heading: 90,
pitch: -30,
});
assert.equal(views.length, 1);
assert.ok(Math.abs(views[0].orientation.heading - Math.PI / 2) < 1e-9);
assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 6) < 1e-9);
});
+40 -28
View File
@@ -1,3 +1,4 @@
import { onFollowChanged } from '../data/followed.js';
import { SceneDirector } from '../scenes/director.js';
import { initAnnotations } from '../annotations/index.js';
import { initDrawTool } from '../annotations/drawTool.js';
@@ -24,17 +25,22 @@ import {
isScopeMaskEnabled,
} from '../scopeMask.js';
import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js';
import { installGlobeInViewRecovery } from './viewer.js';
import { installGlobeInViewRecovery } from './globeInViewRecovery.js';
import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
import {
installRenderGovernor,
getRenderGovernorDiagnostics,
governorRequestRender,
holdContinuousRender,
releaseContinuousRender,
} from '../renderGovernor.js';
import { entityRecord, readEntityRecord } from '../data/entityRecords.js';
import { overlayHost } from './layers/overlayHost.js';
/** Attach scene tools, rendering listeners and the application debug handle. */
/**
* Attach scene tools, rendering listeners and the application debug handle.
* `scene` is what `createApplicationScene` returns; its `trimStaleCommands`
* runs after each layer disable (a scene without one keeps that memory).
*/
export function createApplicationTools({
scene,
controls,
@@ -49,11 +55,11 @@ export function createApplicationTools({
signal,
defer,
}) {
const { viewer, tileset, mapStackController, operations } = scene;
const { viewer, renderer, tileset, mapStackController, operations } = scene;
const { styleManager, weatherEffects, cockpitCloudEffects } = controls;
const { dataManager } = data;
const sceneDirector = new SceneDirector(viewer, styleManager, dataManager, {
dataPacks: sceneDataPacks,
dataPacks: { overlayHost, ...sceneDataPacks },
isMapStackAvailable: (id) =>
mapStackController?.isStackAvailable(id) === true,
});
@@ -198,19 +204,21 @@ export function createApplicationTools({
}
if (startChrome)
defer(startChrome({ loadingScreen, styleManager, dataManager, signal }));
// Idle render governor: flips the scene into requestRenderMode whenever
// nothing animates per frame. Installed AFTER every module above has had
// its chance to register pre-install holds. (perf wave 2)
installRenderGovernor(viewer);
// Cesium keeps a turned-off layer's draw commands (and so all its entities)
// alive in reused per-pass arrays; trim them after each disable.
defer(
installLayerReleaseTrim({
scene: viewer.scene,
dataManager,
requestRender: governorRequestRender,
}),
);
// Idle render governor: the loop draws on demand whenever nothing animates
// per frame. It goes idle only now, after every module above has had its
// chance to hold. (perf wave 2)
releaseContinuousRender('boot');
// The renderer may keep a turned-off layer's draw commands (and so all its
// entities) alive; trim them after each disable.
if (scene.trimStaleCommands)
defer(
installLayerReleaseTrim({
frame: renderer.frame,
dataManager,
requestRender: governorRequestRender,
trim: scene.trimStaleCommands,
}),
);
// Install the explicit scope mask used by the DISPLAY controls.
installScopeMask(viewer);
@@ -218,12 +226,10 @@ export function createApplicationTools({
// The follow camera recomputes the tracked target's dead-reckon position
// every frame — tracking anything is a per-frame animation. (perf wave 2)
const removeTrackingListener = viewer.trackedEntityChanged.addEventListener(
() => {
if (viewer.trackedEntity) holdContinuousRender('tracked-entity');
else releaseContinuousRender('tracked-entity');
},
);
const removeTrackingListener = onFollowChanged(viewer, (followed) => {
if (followed) holdContinuousRender('tracked-entity');
else releaseContinuousRender('tracked-entity');
});
// Hidden-state suspension (perf wave 2): when the window/tab is hidden,
// stop the default render loop outright — a hidden canvas repaints for
@@ -232,9 +238,9 @@ export function createApplicationTools({
// the loop, refresh the one DOM surface we gated, render a frame.
const syncVisibilitySuspension = () => {
// A panel's host may report it hidden while it is on screen; the panel
// keeps drawing itself (see keepPanelRendering in embed.js).
// keeps drawing itself (see keepPanelRendering in app/panelRendering.js).
const hidden = document.hidden && !isEmbeddedInline();
viewer.useDefaultRenderLoop = !hidden;
renderer.frame.suspend(hidden);
cockpitCloudEffects?.setSuspended?.(hidden);
if (!hidden) {
data.presentation.flushVisible();
@@ -267,6 +273,10 @@ export function createApplicationTools({
getRenderGovernorDiagnostics,
surfaceServices: operations.surface,
requestRender: governorRequestRender,
entityRecords: { read: readEntityRecord, write: entityRecord },
// What the renderer's plugin lets QA scripts read (the Cesium viewer,
// for the default renderer), in place of the scene object above.
...scene.qaHandles,
};
const debug = window.__godsEyeView;
defer(() => {
@@ -299,11 +309,13 @@ export function createApplicationTools({
run: (name, args, options = {}) =>
voiceCommands.runner(name, args, { ...options, signal }),
signal,
keepRendering: scene.keepPanelRendering,
terrain: operations.requests.terrain,
}),
);
// An application's own tool takes the pointer as Draw does, and its own
// click handlers yield while a tool holds it, as the layers' do
// Any other tool takes the pointer as Draw does (the newest
// claim takes over; `claim(owner, {onLost})` tells the tool it replaces),
// and its own click handlers yield while a tool holds it, as the layers' do
// (data/inputOwnership.js).
return {
sceneDirector,
-447
View File
@@ -1,447 +0,0 @@
import * as Cesium from 'cesium';
import { IDLE_FRAME_RATE } from '../renderGovernor.js';
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 {
// Until the render governor takes over (app/tools.js), tick at the idle
// rate so the startup load does not compete with drawing at 240 fps.
viewer.targetFrameRate = IDLE_FRAME_RATE;
// A phone pinch spans fewer screen pixels than desktop zoom gestures.
// Keep Cesium's distance-aware zoom and collision limits, with less travel
// required on touch-first screens. Mouse/trackpad sensitivity stays native.
if (globalThis.matchMedia?.('(pointer: coarse)').matches)
viewer.scene.screenSpaceCameraController.zoomFactor *= 3;
limitZoomOut(viewer);
// Before any tile builds a draw command: Cesium's per-vertex model
// atmosphere fails to LINK on Apple's Metal backend and kills the
// render loop. See app/atmosphereCompat.js.
applyModelAtmosphereWorkaround(viewer.scene);
viewer.scene.globe.show = false;
viewer.scene.skyAtmosphere.show = true;
viewer.scene.skyAtmosphere.atmosphereLightIntensity = 18;
viewer.scene.skyAtmosphere.saturationShift = -0.12;
viewer.scene.skyAtmosphere.brightnessShift = -0.08;
return viewer;
} catch (error) {
viewer.destroy();
throw error;
}
}
+7 -10
View File
@@ -6,11 +6,12 @@
* awareness policy of its own: the publisher passes radius, pulse timing and
* echo styling in, so the overlay never imports awareness internals.
*/
import * as Cesium from 'cesium';
import { scaleToGeodeticSurface } from './geo/ellipsoid.js';
import { distance } from './geo/vector.js';
/**
* @typedef {object} AwarenessEchoField
* @property {Cesium.Cartesian3} center Subject's ground point. The publisher
* @property {{x: number, y: number, z: number}} center Subject's ground point. The publisher
* may move it in place; it is read on every query.
* @property {number} radiusM Range the pulses grow to.
* @property {{count: number, periodMs: number, startFraction: number, fadeInFraction?: number}} pulse
@@ -22,7 +23,6 @@ import * as Cesium from 'cesium';
/** @type {AwarenessEchoField|null} */
let field = null;
let layerIds = new Set();
const groundScratch = new Cesium.Cartesian3();
/**
* Start (or replace) the echo field.
@@ -104,7 +104,7 @@ export function awarenessEchoStrength(nowMs, distanceM, radiusM, pulse, echo) {
* field is set or the layer does not echo. Distance is measured between
* ground points, so an aircraft's altitude does not shift its echo.
* @param {string} layerId Owning layer of the contact.
* @param {Cesium.Cartesian3} position Contact's world position.
* @param {{x: number, y: number, z: number}} position Contact's world position.
* @param {number} nowMs Monotonic clock in milliseconds.
* @returns {number} 0 to 1.
*/
@@ -112,16 +112,13 @@ export function awarenessEchoAt(layerId, position, nowMs) {
if (!field || !position || !layerIds.has(layerId)) return 0;
const level = field.level?.(nowMs) ?? 1;
if (!(level > 0)) return 0;
const ground = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(
position,
groundScratch,
);
const ground = scaleToGeodeticSurface(position);
if (!ground) return 0;
return (
level *
awarenessEchoStrength(
nowMs,
Cesium.Cartesian3.distance(field.center, ground),
distance(field.center, ground),
field.radiusM,
field.pulse,
field.echo,
@@ -138,7 +135,7 @@ export function awarenessEchoAt(layerId, position, nowMs) {
* outside the contact's bracket, 0 as the front arrives, growing to the
* field's `spreadPx` as it fades.
* @param {string} layerId Owning layer of the contact.
* @param {Cesium.Cartesian3} position Contact's world position.
* @param {{x: number, y: number, z: number}} position Contact's world position.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {number} bracketAlpha The contact bracket's drawn alpha, 0 to 1.
* @param {number} steps Alpha bands the overlay batches by.
+22 -29
View File
@@ -1,36 +1,29 @@
import * as Cesium from 'cesium';
import { toRadians } from './geo/index.js';
import { cameraOf } from './render/rendererOf.js';
/**
* Set camera to Austin on load with a cinematic fly-in.
* @returns {Function} Cancels the pending or active startup flight.
* The view the renderer starts from: the whole planet, looking straight
* down, centred where Cesium's default view rectangle is.
*/
export function flyToAustin(viewer) {
// Start from a high altitude, then fly down
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 25000),
export const START_VIEW = Object.freeze({
lon: -82.5,
lat: 35,
height: 23000000,
});
/**
* Put the camera at a start view without a flight. A host may pass a city
* (`{ lon, lat, height, heading?, pitch? }`, angles in degrees) instead of
* the planet.
*/
export function applyStartView(viewer, view = START_VIEW) {
const { lon, lat, height, heading = 0, pitch = -90 } = view;
cameraOf(viewer).setView({
destination: { lon, lat, height },
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-90),
roll: 0.0,
heading: toRadians(heading),
pitch: toRadians(pitch),
roll: 0,
},
});
// Cinematic fly-in after a brief pause
const timer = setTimeout(() => {
if (viewer.isDestroyed()) return;
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 600),
orientation: {
heading: Cesium.Math.toRadians(15),
pitch: Cesium.Math.toRadians(-30),
roll: 0.0,
},
duration: 4.0,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
});
}, 500);
return () => {
clearTimeout(timer);
if (!viewer.isDestroyed()) viewer.camera.cancelFlight();
};
}
+103 -161
View File
@@ -1,3 +1,14 @@
import {
bindFakeCesiumCamera,
followEntity,
followedEntity,
} from './testSupport/fakeCameraPort.mjs';
import { rendererOf } from './render/rendererOf.js';
import { followedOf } from './data/followed.js';
import {
fakeSceneFrame,
fakeSceneQuery,
} from './testSupport/fakeCesiumScene.mjs';
import { GLOBE_VIEW } from './locations.js';
import { projectEarthDiscToViewport } from './celestialRing.js';
import assert from 'node:assert/strict';
@@ -13,11 +24,24 @@ import {
moveCamera,
} from './cameraVerbs.js';
import { getRenderGovernorDiagnostics } from './renderGovernor.js';
import {
MIN_GLOBE_FRAME_SHARE,
globeFrameShare,
globeOutOfFrame,
} from './globeInView.js';
import { MIN_GLOBE_FRAME_SHARE } from './globeInView.js';
import * as globeInView from './globeInView.js';
// The frame measures take a camera pose; these read it off the real camera.
const framePose = (camera) => ({
position: camera.positionWC,
direction: camera.directionWC,
up: camera.upWC,
right: camera.rightWC,
fovy: camera.frustum.fovy,
aspectRatio: camera.frustum.aspectRatio,
height: camera.positionCartographic.height,
pitch: camera.pitch,
});
const globeFrameShare = (camera, options) =>
globeInView.globeFrameShare(framePose(camera), options);
const globeOutOfFrame = (camera, options) =>
globeInView.globeOutOfFrame(framePose(camera), options);
import { KEYHOLE_OUTER_RADIUS } from './celestialRing.js';
import { setScopeMaskEnabled } from './scopeMask.js';
@@ -136,7 +160,7 @@ function harness(
mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL,
mode: Cesium.SceneMode.SCENE3D,
pixelRatio: 1,
tweens: [],
preUpdate: new Cesium.Event(),
requestRender() {},
};
const camera = new Cesium.Camera(scene);
@@ -154,13 +178,37 @@ function harness(
roll: radians(roll),
},
});
const viewer = {
const double = {
camera,
scene,
trackedEntity: undefined,
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
clock: { onTick: new Cesium.Event() },
entities: {},
};
const viewer = bindFakeCesiumCamera(double, {
query: fakeSceneQuery(double),
frame: fakeSceneFrame(double),
});
// Count who listens for the port's follow changes.
const renderer = rendererOf(viewer);
const port = renderer.camera;
let followListeners = 0;
renderer.camera = Object.create(port, {
on: {
value(event, cb, options) {
const off = port.on(event, cb, options);
if (event !== 'followChanged') return off;
followListeners += 1;
let live = true;
return () => {
if (live) followListeners -= 1;
live = false;
off();
};
},
},
});
const target = Cesium.Cartesian3.fromDegrees(
longitudeDeg,
latitude,
@@ -174,73 +222,21 @@ function harness(
});
const tick = (seconds = 0.1) => {
nowMs += seconds * 1000;
viewer.clock.onTick.raiseEvent(viewer.clock);
viewer.scene.preUpdate.raiseEvent(viewer.scene);
};
const finishOnce = () => {
for (let i = 0; i < 20 && getActiveCameraMotion(); i += 1) tick();
assert.equal(getActiveCameraMotion(), null, 'once motion must finish');
};
return { viewer, camera, canvas, target, tick, finishOnce };
}
for (const [name, sceneMode] of [
['2D', Cesium.SceneMode.SCENE2D],
['Columbus', Cesium.SceneMode.COLUMBUS_VIEW],
['morphing', Cesium.SceneMode.MORPHING],
]) {
test(`globe rotation refuses ${name} before changing the prior owner`, (t) => {
const { viewer, camera } = harness(t);
assert.equal(
moveCamera({ motion: 'rotate', direction: 'right', mode: 'continuous' })
.ok,
true,
);
const priorId = activeCameraMotionId();
const before = pose(camera);
const transform = Cesium.Matrix4.clone(camera.transform);
viewer.scene.mode = sceneMode;
let handoffs = 0;
let cancellations = 0;
camera.cancelFlight = () => {
cancellations += 1;
};
for (const mode of ['once', 'continuous']) {
const result = moveCamera(
{ motion: 'rotate_globe', direction: 'left', mode },
() => {
handoffs += 1;
return { ok: true };
},
);
assert.equal(result.ok, false);
assert.match(result.error, /3D/);
}
assert.equal(handoffs, 0);
assert.equal(cancellations, 0);
assert.equal(activeCameraMotionId(), priorId);
assert.equal(hasRenderHold(), true);
assert.ok(Cesium.Matrix4.equals(camera.transform, transform));
samePose(camera, before);
});
test(`active globe rotation yields to ${name} without changing the camera`, (t) => {
const { viewer, camera, tick } = harness(t);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
true,
);
viewer.scene.mode = sceneMode;
const before = pose(camera);
let rotations = 0;
camera.rotate = () => {
rotations += 1;
};
tick();
assert.equal(rotations, 0);
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
samePose(camera, before);
});
return {
viewer,
camera,
canvas,
target,
tick,
finishOnce,
followListeners: () => followListeners,
};
}
test('globe rotation yields to tracking acquired and cleared before the next tick', (t) => {
@@ -251,15 +247,13 @@ test('globe rotation yields to tracking acquired and cleared before the next tic
);
const before = pose(camera);
const entity = { id: 'cockpit-aircraft', position: {} };
viewer.trackedEntity = entity;
viewer.trackedEntityChanged.raiseEvent(entity);
followEntity(viewer, entity);
assert.equal(
getActiveCameraMotion(),
null,
'tracking acquisition must synchronously yield',
);
viewer.trackedEntity = undefined;
viewer.trackedEntityChanged.raiseEvent(undefined);
followEntity(viewer, null);
tick();
samePose(camera, before);
assert.equal(hasRenderHold(), false);
@@ -272,33 +266,34 @@ test('tracking event keeps legacy yaw and an untracked globe rotation active', (
true,
);
const yawId = activeCameraMotionId();
viewer.trackedEntityChanged.raiseEvent({ id: 'aircraft' });
followEntity(viewer, { id: 'aircraft' });
assert.equal(activeCameraMotionId(), yawId);
followEntity(viewer, null);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
true,
);
const globeId = activeCameraMotionId();
viewer.trackedEntityChanged.raiseEvent(undefined);
followEntity(viewer, null);
assert.equal(activeCameraMotionId(), globeId);
});
test('replaced viewer releases the old tracking listener without duplicate subscriptions', (t) => {
const first = harness(t);
assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1);
assert.equal(first.followListeners(), 1);
initCameraVerbs(first.viewer);
assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 1);
assert.equal(first.followListeners(), 1);
const next = harness(t);
assert.equal(first.viewer.trackedEntityChanged.numberOfListeners, 0);
assert.equal(next.viewer.trackedEntityChanged.numberOfListeners, 1);
assert.equal(first.followListeners(), 0);
assert.equal(next.followListeners(), 1);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
true,
);
const id = activeCameraMotionId();
first.viewer.trackedEntityChanged.raiseEvent({ id: 'stale-aircraft' });
followEntity(first.viewer, { id: 'stale-aircraft' });
assert.equal(activeCameraMotionId(), id);
next.viewer.trackedEntityChanged.raiseEvent({ id: 'new-aircraft' });
followEntity(next.viewer, { id: 'new-aircraft' });
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
});
@@ -534,7 +529,7 @@ test('replacement motion rejects a stale globe owner cancellation', (t) => {
assert.equal(hasRenderHold(), false);
});
test('replacing the viewer retires globe motion and its old clock listener', (t) => {
test('replacing the viewer retires globe motion and its old frame listener', (t) => {
const { viewer, camera, tick } = harness(t);
assert.equal(
moveCamera({ motion: 'rotate_globe', mode: 'continuous' }).ok,
@@ -542,15 +537,16 @@ test('replacing the viewer retires globe motion and its old clock listener', (t)
);
tick();
const before = pose(camera);
const nextViewer = {
...viewer,
clock: { onTick: new Cesium.Event() },
};
const nextScene = { ...viewer.scene, preUpdate: new Cesium.Event() };
const nextViewer = bindFakeCesiumCamera(
{ ...viewer, scene: nextScene },
{ frame: fakeSceneFrame({ scene: nextScene }) },
);
initCameraVerbs(nextViewer);
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
tick();
nextViewer.clock.onTick.raiseEvent(nextViewer.clock);
nextScene.preUpdate.raiseEvent(nextScene);
samePose(camera, before);
});
@@ -580,7 +576,7 @@ for (const mode of ['once', 'continuous']) {
tick();
assert.equal(hasRenderHold(), true);
const tracked = { id: 'new-tracked-aircraft' };
if (acquisition === 'tracking') viewer.trackedEntity = tracked;
if (acquisition === 'tracking') followEntity(viewer, tracked);
else
camera.lookAt(
target,
@@ -591,10 +587,9 @@ for (const mode of ['once', 'continuous']) {
tick();
assert.equal(getActiveCameraMotion(), null);
assert.equal(hasRenderHold(), false);
assert.equal(
viewer.trackedEntity,
acquisition === 'tracking' ? tracked : undefined,
);
if (acquisition === 'tracking')
assert.equal(followedEntity(viewer), tracked);
else assert.equal(followedOf(viewer), null);
assert.equal(Cesium.Matrix4.equals(camera.transform, transform), true);
samePose(camera, before);
tick();
@@ -605,7 +600,7 @@ for (const mode of ['once', 'continuous']) {
test('direct globe rotation refuses a tracked camera without disturbing its reference frame', (t) => {
const { viewer, camera, target } = harness(t);
viewer.trackedEntity = { id: 'tracked-aircraft' };
followEntity(viewer, { id: 'tracked-aircraft', name: 'tracked-aircraft' });
camera.lookAt(target, new Cesium.HeadingPitchRange(0, radians(-40), 1_000));
const before = pose(camera);
const transform = Cesium.Matrix4.clone(camera.transform);
@@ -676,18 +671,19 @@ test('close-up refusal preserves an inherited target frame', (t) => {
});
test('navigation callback never releases tracking for globe rotation', (t) => {
const { viewer, camera } = harness(t);
const tracked = (viewer.trackedEntity = { id: 'tracked-aircraft' });
const tracked = { id: 'tracked-aircraft' };
followEntity(viewer, tracked);
const before = pose(camera);
let calls = 0;
assert.equal(
moveCamera({ motion: 'rotate_globe' }, () => {
calls++;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
}).ok,
false,
);
assert.equal(calls, 0);
assert.equal(viewer.trackedEntity, tracked);
assert.equal(followedEntity(viewer), tracked);
samePose(camera, before);
});
test('direct globe request refuses Cockpit before navigation mutation', (t) => {
@@ -878,8 +874,8 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
height: owner === 'close-up' ? 5000 : GLOBE_VIEW.heightM,
});
const before = pose(camera);
if (owner === 'tracking') viewer.trackedEntity = { id: 'tracked-aircraft' };
const tracked = viewer.trackedEntity;
if (owner === 'tracking') followEntity(viewer, { id: 'tracked-aircraft' });
const tracked = followedEntity(viewer);
let releases = 0,
stamps = 0;
const styleManager = {
@@ -893,7 +889,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
},
release() {
releases++;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
},
navigate,
});
@@ -915,7 +911,7 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
assert.equal(result.ok, false);
assert.equal(releases, 0);
assert.equal(stamps, 0);
assert.equal(viewer.trackedEntity, tracked);
assert.equal(followedEntity(viewer), tracked);
samePose(camera, before);
if (owner === 'close-up') {
assert.equal(result.reason, 'globe-view-required');
@@ -926,29 +922,6 @@ for (const owner of ['tracking', 'cockpit', 'close-up'])
}
});
for (const [label, ellipsoid] of [
['nonfinite radii', { minimumRadius: 1, maximumRadius: Infinity }],
['nonpositive radii', { minimumRadius: 0, maximumRadius: 1 }],
['non-WGS84 radii', new Cesium.Ellipsoid(30_000_000, 30_000_000, 1_000_000)],
])
test(`globe rotation refuses ${label} before handoff`, (t) => {
const { viewer, camera } = harness(t, { height: 100_000_000 });
const before = pose(camera);
viewer.scene.globe.ellipsoid = ellipsoid;
let handedOff = false;
const result = moveCamera({ motion: 'rotate_globe' }, () => {
handedOff = true;
});
assert.equal(result.ok, false);
assert.equal(
result.reason,
label === 'non-WGS84 radii' ? 'unsupported-view' : 'unsafe-ellipsoid',
);
assert.equal(handedOff, false);
assert.equal(hasRenderHold(), false);
samePose(camera, before);
});
test('an external radius change retires globe rotation without another write', (t) => {
const { camera, tick } = harness(t);
moveCamera({ motion: 'rotate_globe', mode: 'continuous' });
@@ -960,16 +933,6 @@ test('an external radius change retires globe rotation without another write', (
samePose(camera, changed);
});
test('a non-WGS84 ellipsoid fails closed rather than borrowing the WGS84 silhouette', (t) => {
const ellipsoid = new Cesium.Ellipsoid(10_000_000, 10_000_000, 8_000_000);
const { camera } = harness(t, { ellipsoid, latitude: 60 });
const before = pose(camera);
const result = moveCamera({ motion: 'rotate_globe' });
assert.equal(result.ok, false);
assert.equal(result.reason, 'unsupported-view');
samePose(camera, before);
});
test('untouched polar framing permits repeated direction and speed changes below preset altitude', (t) => {
const { camera, finishOnce, tick } = harness(t, { latitude: 90 });
const radius = Cesium.Cartesian3.magnitude(camera.positionWC);
@@ -1874,7 +1837,7 @@ test('a voice turn reported as done turns at least the half degree its check pro
/** Track an entity below `camera`, locking it into that entity's frame. */
function trackFrom(viewer, camera) {
viewer.trackedEntity = { id: 'high-satellite' };
followEntity(viewer, { id: 'high-satellite' });
const below = Cesium.Cartesian3.fromDegrees(10, 20, 400_000);
camera.lookAtTransform(Cesium.Transforms.eastNorthUpToFixedFrame(below));
}
@@ -1900,7 +1863,7 @@ test('a voice turn that releases a tracked camera is checked as released', (t) =
});
trackFrom(viewer, camera);
const releaseThenRun = (start) => {
viewer.trackedEntity = undefined;
followEntity(viewer, null);
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
return start();
};
@@ -1941,14 +1904,14 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => {
for (let j = 0; j < 600 && getActiveCameraMotion(); j += 1) tick(1 / 60);
}
trackFrom(viewer, camera);
const tracked = viewer.trackedEntity;
const tracked = followedEntity(viewer);
const transform = Cesium.Matrix4.clone(camera.transform);
let released = false;
const result = moveCamera(
{ motion: 'tilt', direction: 'up', mode: 'once' },
(start) => {
released = true;
viewer.trackedEntity = undefined;
followEntity(viewer, null);
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
return start();
},
@@ -1957,7 +1920,7 @@ test('a refused voice turn leaves a tracked camera tracking', (t) => {
assert.equal(result.ok, false, label);
assert.match(result.error, /globe out of view/, label);
assert.equal(released, false, label);
assert.equal(viewer.trackedEntity, tracked, label);
assert.equal(followedEntity(viewer), tracked, label);
assert.ok(Cesium.Matrix4.equals(camera.transform, transform), label);
}
});
@@ -1988,27 +1951,6 @@ test('a turn proven at one position is checked again after a release moves the c
assert.match(result.error, /globe out of view/);
});
test('the voice frame limit leaves Columbus view alone', (t) => {
// At its limit in 3D a further tilt up is refused; the same tilt in Columbus
// view is not limited by the frame.
withScope(t, false);
const { viewer, finishOnce } = harness(t, {
pitch: -80,
viewportWidth: 1600,
viewportHeight: 900,
});
assert.equal(
moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' }).ok,
true,
);
finishOnce();
const refused = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' });
assert.match(refused.error || '', /globe out of view/);
viewer.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW;
const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' });
assert.doesNotMatch(result.error || '', /globe out of view/);
});
test('voice tilt below the free-look height is not limited by the frame', (t) => {
const { camera, finishOnce } = harness(t, { height: 500_000, pitch: -60 });
const result = moveCamera({ motion: 'tilt', direction: 'up', mode: 'once' });
+96 -75
View File
@@ -14,8 +14,11 @@
* lifts the eye if it sits below a usable clearance. Heading and pitch are
* held, so the correction reads as the shot settling.
*/
import * as Cesium from 'cesium';
import { onFollowChanged } from './data/followed.js';
import { ownCameraArrival } from './data/cameraArrival.js';
import { distance, dot, fromDegrees, toLonLatH } from './geo/index.js';
import { heightsOf } from './queries/heights.js';
import { canvasOf, findCamera } from './render/rendererOf.js';
/** Minimum eye height above the rendered surface for a usable view. */
export const MIN_EYE_CLEARANCE_M = 120;
@@ -24,35 +27,79 @@ const GUARD_ATTEMPTS = 8;
const GUARD_INTERVAL_MS = 600;
/** Ignore sub-metre noise rather than nudging the camera forever. */
const GUARD_EPSILON_M = 2;
const probeScratch = new Cesium.Cartographic();
/** Eye travel (m) and turn (cosine) that mean another owner moved the camera. */
const MOVED_M = 0.01;
const TURNED_COS = 1 - 1e-9;
/**
* Highest rendered surface across a few cells, with how many cells answered.
* A cell whose tiles are not streamed yet contributes nothing.
* @param {Cesium.Scene} scene Live scene.
* @param {import('./queries/heights.js').HeightService|null} heights The
* scene's height service.
* @param {Array<{lat: number, lon: number}>} cells Cells to probe.
* @returns {{heightM: number, sampled: number}} Reading.
*/
function sampleSurfaceM(scene, cells) {
function sampleSurfaceM(heights, cells) {
let heightM = Number.NaN;
let sampled = 0;
if (typeof scene?.sampleHeight !== 'function') return { heightM, sampled };
if (!heights) return { heightM, sampled };
for (const cell of cells) {
try {
const height = scene.sampleHeight(
Cesium.Cartographic.fromDegrees(cell.lon, cell.lat, 0, probeScratch),
);
if (!Number.isFinite(height)) continue;
sampled += 1;
heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height;
} catch {
/* tiles not ready for this cell */
}
// A miss is a cell whose tiles are not ready.
const height = heights.now(cell);
if (!Number.isFinite(height)) continue;
sampled += 1;
heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height;
}
return { heightM, sampled };
}
/**
* The eye as the camera port poses it: where it is (from its position) and
* which way it looks; null when the pose cannot be read.
*/
function eyeOf(camera) {
try {
const pose = camera?.pose();
const at = pose?.position && toLonLatH(pose.position);
if (!at || !pose.direction || !pose.up) return null;
return { ...pose, lon: at.lon, lat: at.lat, height: at.height };
} catch {
return null;
}
}
/** The eye's ground point (height 0), its height, and which way it looks. */
function poseOf(eye) {
if (!eye) return null;
return {
ground: fromDegrees(eye.lon, eye.lat),
height: eye.height,
direction: { ...eye.direction },
up: { ...eye.up },
};
}
/**
* Whether another owner has moved the camera off `pose`: across the ground,
* down, or around. A pure rise is not one: the renderer's terrain collision
* lifts a buried eye straight up as tiles load, which is the case the guard
* exists for, so `pose` follows the highest eye seen and the guard keeps
* measuring.
*/
function moved(now, pose) {
if (!now) return true;
const ground = fromDegrees(now.lon, now.lat);
if (
distance(ground, pose.ground) > MOVED_M ||
now.height < pose.height - MOVED_M ||
dot(now.direction, pose.direction) < TURNED_COS ||
dot(now.up, pose.up) < TURNED_COS
)
return true;
pose.height = Math.max(pose.height, now.height);
return false;
}
/**
* How far the camera must rise to clear the ground, given a measured surface.
* Pure so the policy is testable without a scene.
@@ -76,9 +123,11 @@ export function groundClearanceDeficitM(
* Watch an arrival and lift the camera once the real surface can be measured.
*
* Stops quietly on a clear view, exhausted attempts, the user taking the
* controls (pointer or wheel on the canvas), or `isStale()` reporting that a
* newer arrival owns the camera.
* @param {Cesium.Viewer} viewer Live viewer.
* controls (pointer or wheel on the canvas), `isStale()` reporting that a
* newer arrival owns the camera, or any other caller moving the camera or
* starting a flight in the meantime: the guard only ever corrects the pose it
* was started on.
* @param {object} viewer Live viewer.
* @param {{lat: number, lon: number}} at Destination being framed.
* @param {{clearanceM?: number, attempts?: number, intervalMs?: number,
* isStale?: () => boolean, onLift?: (liftM: number) => void}} [options]
@@ -92,12 +141,16 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
isStale = () => false,
onLift = null,
} = options;
if (!viewer?.scene || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon))
if (!viewer || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon))
return () => {};
// Without a readable pose the guard could not tell a later owner's move.
const arrival = poseOf(eyeOf(findCamera(viewer)));
if (!arrival) return () => {};
let timer = null;
let done = false;
const canvas = viewer.scene.canvas;
const canvas = canvasOf(viewer);
const documentRef = canvas?.ownerDocument;
const removers = [];
let release = () => {};
@@ -112,32 +165,7 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
release();
};
release = ownCameraArrival(viewer, stop);
// Direct camera API callers (including duration-zero flights) must yield
// before moving the eye. Restore the exact method ownership on completion.
for (const name of [
'flyTo',
'flyToBoundingSphere',
'setView',
'lookAt',
'cancelFlight',
]) {
const camera = viewer.camera;
const original = camera[name];
if (typeof original !== 'function') continue;
const descriptor = Object.getOwnPropertyDescriptor(camera, name);
const wrapped = function (...args) {
stop();
return original.apply(this, args);
};
camera[name] = wrapped;
removers.push(() => {
if (camera[name] !== wrapped) return;
if (descriptor) Object.defineProperty(camera, name, descriptor);
else delete camera[name];
});
}
const removeTracking = viewer.trackedEntityChanged?.addEventListener(stop);
if (removeTracking) removers.push(removeTracking);
removers.push(onFollowChanged(viewer, stop));
documentRef?.addEventListener?.('keydown', stop, true);
// A manual gesture ends the guard, as it interrupts camera motion elsewhere.
for (const type of ['pointerdown', 'wheel'])
@@ -147,40 +175,33 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
const attempt = () => {
if (done) return;
if (isStale() || viewer.isDestroyed?.()) return stop();
const camera = findCamera(viewer);
const now = eyeOf(camera);
// Another caller owns the camera now; lifting would undo its move.
if (!camera || camera.flying || moved(now, arrival)) return stop();
remaining -= 1;
const camera = viewer.camera;
const carto = camera.positionCartographic;
// The eye must clear both the framed target and the ground beneath it.
const below = {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
};
const { heightM, sampled } = sampleSurfaceM(viewer.scene, [
{ lat: at.lat, lon: at.lon },
below,
]);
const below = { lat: now.lat, lon: now.lon };
const { heightM, sampled } = sampleSurfaceM(
viewer ? heightsOf(viewer) : null,
[{ lat: at.lat, lon: at.lon }, below],
);
if (sampled > 0 && Number.isFinite(heightM)) {
const deficit = groundClearanceDeficitM(
carto.height,
heightM,
clearanceM,
);
const deficit = groundClearanceDeficitM(now.height, heightM, clearanceM);
if (deficit > 0) {
stop();
camera.flyTo({
destination: Cesium.Cartesian3.fromRadians(
carto.longitude,
carto.latitude,
carto.height + deficit,
),
orientation: {
heading: camera.heading,
pitch: camera.pitch,
roll: camera.roll,
camera.flyTo(
{ lon: now.lon, lat: now.lat, height: now.height + deficit },
{
orientation: {
heading: now.heading,
pitch: now.pitch,
roll: now.roll,
},
durationS: 0.9,
easing: 'cubicInOut',
},
duration: 0.9,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
});
);
try {
onLift?.(deficit);
} catch {
+195 -27
View File
@@ -3,6 +3,12 @@
// Arrival framing is computed before the destination's tiles exist, so it
// works from a predicted ground height. The guard measures the real surface
// after arrival and lifts the eye; these tests pin when it acts.
import {
bindFakeCesiumCamera,
followEntity,
} from './testSupport/fakeCameraPort.mjs';
import { rendererOf } from './render/rendererOf.js';
import { fakeSceneQuery } from './testSupport/fakeCesiumScene.mjs';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
@@ -47,24 +53,71 @@ test('the clearance frames a subject without turning into an overflight', () =>
assert.ok(MIN_EYE_CLEARANCE_M <= 250);
});
function fakeViewer({ cameraHeightM, surfaceM }) {
/**
* Count the listeners for `viewer`'s camera port follow changes, from now on.
* @returns {() => number}
*/
function countFollowListeners(viewer) {
const renderer = rendererOf(viewer);
const port = renderer.camera;
let listeners = 0;
renderer.camera = Object.create(port, {
on: {
value(event, cb, options) {
const off = port.on(event, cb, options);
if (event !== 'followChanged') return off;
listeners += 1;
let live = true;
return () => {
if (live) listeners -= 1;
live = false;
off();
};
},
},
});
return () => listeners;
}
function fakeViewer({ cameraHeightM, surfaceM, tracks = false }) {
const flights = [];
const position = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, cameraHeightM);
return {
const position = Cesium.Cartographic.fromDegrees(
-97.7603,
30.3141,
cameraHeightM,
);
const viewer = {
flights,
scene: {
canvas: null,
sampleHeightSupported: true,
sampleHeight: (carto) =>
typeof surfaceM === 'function' ? surfaceM(carto) : surfaceM,
},
camera: {
positionCartographic: position,
positionWC: Cesium.Cartographic.toCartesian(position),
directionWC: new Cesium.Cartesian3(0, 0, -1),
upWC: new Cesium.Cartesian3(0, 1, 0),
heading: 0.5,
pitch: -0.55,
roll: 0,
flyTo: (options) => flights.push(options),
// As Cesium does: a flight is under way until it completes.
_currentFlight: undefined,
flyTo(options) {
flights.push(options);
this._currentFlight = {};
},
},
};
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
if (tracks)
Object.assign(viewer, {
trackedEntityChanged: new Cesium.Event(),
entities: {},
});
return bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) });
}
test('the guard lifts a buried arrival once the surface answers', async () => {
@@ -104,7 +157,11 @@ test('the guard waits for streaming tiles and yields to a newer arrival', async
test('the guard leaves a clear view untouched', async () => {
const viewer = fakeViewer({ cameraHeightM: 400, surfaceM: 171 });
guardCameraAboveGround(viewer, { lat: 30.3125, lon: -97.765 }, { intervalMs: 1 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 1 },
);
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(viewer.flights.length, 0);
});
@@ -116,39 +173,85 @@ import { LayerLifecycle } from './data/lifecycle.js';
function handoffFixture(t) {
t.mock.timers.enable({ apis: ['setTimeout'] });
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
const viewer = fakeViewer({
cameraHeightM: 172,
surfaceM: 171,
tracks: true,
});
const followListeners = countFollowListeners(viewer);
viewer.scene.canvas = new EventTarget();
viewer.scene.canvas.ownerDocument = new EventTarget();
viewer.trackedEntityChanged = new Cesium.Event();
viewer.camera.cancelFlight = () => {};
viewer.camera.lookAtTransform = () => {};
viewer.camera.flyToBoundingSphere = () => {};
viewer.camera.setView = () => {};
viewer.camera.flyToBoundingSphere = function () {
this._currentFlight = {};
};
viewer.camera.setView = function () {
this.positionWC = Cesium.Cartesian3.add(
this.positionWC,
new Cesium.Cartesian3(0, 0, 50),
new Cesium.Cartesian3(),
);
};
const originalFly = viewer.camera.flyTo;
const navigation = new NavigationController({
viewer,
tracking: Object.fromEntries(['flightsLayer', 'militaryFlightsLayer',
'satellitesLayer', 'aisLiveVesselsLayer', 'militaryAwarenessLayer',
'rocketLaunchesLayer'].map((key) => [key, {}])),
cancelOrientation() {}, clearLocation() {}, cancelShareSelection() {},
getDataManager() {}, interruptCameraMotion() {}, stopOrbit() {},
isCockpitActive: () => false, showToast() {},
tracking: Object.fromEntries(
[
'flightsLayer',
'militaryFlightsLayer',
'satellitesLayer',
'aisLiveVesselsLayer',
'militaryAwarenessLayer',
'rocketLaunchesLayer',
].map((key) => [key, {}]),
),
cancelOrientation() {},
clearLocation() {},
cancelShareSelection() {},
getDataManager() {},
interruptCameraMotion() {},
stopOrbit() {},
isCockpitActive: () => false,
showToast() {},
});
guardCameraAboveGround(viewer, { lat: 30.3, lon: -97.7 });
return { viewer, navigation, originalFly };
return { viewer, navigation, originalFly, followListeners };
}
for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI',
'flyTo', 'flyToBoundingSphere', 'setView', 'layer-disable', 'layer-destroy', 'app-stop']) {
for (const handoff of [
'Director',
'tracking',
'follow',
'keyboard',
'UI',
'flyTo',
'flyToBoundingSphere',
'setView',
'layer-disable',
'layer-destroy',
'app-stop',
]) {
test(`arrival guard relinquishes and removes hooks on ${handoff}`, async (t) => {
const { viewer, navigation, originalFly } = handoffFixture(t);
const { viewer, navigation, originalFly, followListeners } =
handoffFixture(t);
const methods = [
'flyTo',
'flyToBoundingSphere',
'setView',
'lookAt',
'cancelFlight',
].map((name) => viewer.camera[name]);
if (handoff === 'Director') {
SceneDirector.prototype._claimCameraOwnership.call({
viewer, styleManager: { runImmediateNavigation: (noun, fn) =>
navigation._runExplicitNavigation(noun, fn) },
viewer,
styleManager: {
runImmediateNavigation: (noun, fn) =>
navigation._runExplicitNavigation(noun, fn),
},
});
} else if (handoff === 'tracking') {
viewer.trackedEntityChanged.raiseEvent({ id: 'contact' });
followEntity(viewer, { id: 'contact' });
} else if (handoff === 'follow' || handoff === 'UI') {
navigation._stampNavigation({ cancelPendingSelection: false });
} else if (handoff === 'keyboard') {
@@ -156,16 +259,81 @@ for (const handoff of ['Director', 'tracking', 'follow', 'keyboard', 'UI',
} else if (handoff === 'app-stop') navigation.stop();
else if (handoff.startsWith('layer-')) {
const lifecycle = new LayerLifecycle(viewer);
lifecycle.register({ id: 'test', init() {}, enable() {}, disable() {}, destroy() {} });
lifecycle.register({
id: 'test',
init() {},
enable() {},
disable() {},
destroy() {},
});
await lifecycle.setEnabled('test', true);
if (handoff === 'layer-disable') await lifecycle.setEnabled('test', false);
if (handoff === 'layer-disable')
await lifecycle.setEnabled('test', false);
else await lifecycle.destroyLayer('test');
} else viewer.camera[handoff]({});
// A direct flyTo is itself one recorded flight; the guard adds none.
const priorFlights = viewer.flights.length;
t.mock.timers.tick(10000);
assert.equal(viewer.flights.length, priorFlights, 'the old probe cannot fly');
assert.equal(viewer.camera.flyTo, originalFly, 'direct-call hook is removed');
assert.equal(viewer.trackedEntityChanged.numberOfListeners, 0);
assert.equal(
viewer.flights.length,
priorFlights,
'the old probe cannot fly',
);
assert.equal(viewer.camera.flyTo, originalFly);
assert.deepEqual(
['flyTo', 'flyToBoundingSphere', 'setView', 'lookAt', 'cancelFlight'].map(
(name) => viewer.camera[name],
),
methods,
'the guard never replaces camera methods',
);
assert.equal(followListeners(), 0);
navigation.destroy();
});
}
test('the guard yields to a camera moved without any camera method', async () => {
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 5 },
);
// A cockpit or follow frame writes the pose directly.
viewer.camera.directionWC = new Cesium.Cartesian3(1, 0, 0);
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(viewer.flights.length, 0, 'the moved view is not corrected');
});
test('Cesium lifting a buried eye straight up is not another owner', async () => {
const viewer = fakeViewer({ cameraHeightM: 104, surfaceM: 171 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 5 },
);
// Terrain collision raises the eye to just above the loaded ground.
const raised = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 172);
viewer.camera.positionCartographic = raised;
viewer.camera.positionWC = Cesium.Cartographic.toCartesian(raised);
await new Promise((resolve) => setTimeout(resolve, 30));
assert.equal(viewer.flights.length, 1, 'the guard still lifts the eye');
const lifted = Cesium.Cartographic.fromCartesian(
viewer.flights[0].destination,
);
assert.ok(Math.abs(lifted.height - (171 + MIN_EYE_CLEARANCE_M)) < 0.5);
});
test('another owner lowering the eye is not corrected', async () => {
const viewer = fakeViewer({ cameraHeightM: 172, surfaceM: 171 });
guardCameraAboveGround(
viewer,
{ lat: 30.3125, lon: -97.765 },
{ intervalMs: 5 },
);
const lowered = Cesium.Cartographic.fromDegrees(-97.7603, 30.3141, 150);
viewer.camera.positionCartographic = lowered;
viewer.camera.positionWC = Cesium.Cartographic.toCartesian(lowered);
await new Promise((resolve) => setTimeout(resolve, 30));
assert.equal(viewer.flights.length, 0);
});
+11 -11
View File
@@ -44,8 +44,8 @@ test('Cockpit takeover invalidates deferred work before camera cancellation', ()
ordered(enter, [
'if (!info || (!vessel && !satellite && !entity?.position)) return false;',
'this.onCameraTakeover?.();',
'this.viewer.camera.cancelFlight();',
'this.viewer.trackedEntity = undefined;',
'cameraOf(this.viewer).cancelFlight();',
'stopFollowing(this.viewer);',
], 'Cockpit takeover');
assert.match(
ui,
@@ -97,7 +97,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () =>
// The transaction has exactly two camera-owner mutations, and each one
// stamps:
// 1. selectedLayer.trackById(id) -> viewer.trackedEntity
// -> viewer.trackedEntityChanged -> _stampNavigation()
// -> onFollowChanged(viewer) -> _stampNavigation()
// 2. cockpitView.enter() -> onCameraTakeover() -> _stampNavigation()
const transaction = body(
cockpitTracking,
@@ -118,7 +118,7 @@ test('voice Cockpit entry reaches the camera only through stamping seams', () =>
// Seam 1: any tracker handoff stamps, so the adoption step is covered.
assert.match(
ui,
/viewer\.trackedEntityChanged\.addEventListener\(\s*\(entity\) => \{\s*if \(entity && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/,
/onFollowChanged\(\s*this\.viewer,\s*\(followed\) => \{\s*if \(followed && !this\._disposed\)\s*this\._stampNavigation\(\{\s*cancelPendingSelection: false,?\s*\}\);/,
'tracker handoff must stamp',
);
// Seam 2 is pinned by "Cockpit takeover invalidates deferred work" above.
@@ -191,10 +191,10 @@ test('accepted navigation releases through PR15-aware ownership before flight',
'origin: trackingOrigin',
'satellitesLayer.stopTracking?.({ origin: trackingOrigin })',
'rocketLaunchesLayer.releaseCameraOwnership?.()',
'this.viewer.trackedEntity = undefined;',
'stopFollowing(this.viewer);',
"interruptCameraMotion('explicit-navigation')",
'this.viewer.camera.cancelFlight();',
'this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);',
'camera?.cancelFlight();',
'camera?.release();',
], 'follow release');
assert.match(release, /flightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/);
assert.match(release, /militaryFlightsLayer\.stopTracking\?\.\(\{ origin: trackingOrigin \}\)/);
@@ -282,11 +282,11 @@ test('a direct globe gesture retires delayed camera and selection restore only',
);
assert.match(
ui,
/viewer\?\.canvas\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/,
/canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'pointerdown',\s*this\._initialShareGestureHandler/,
);
assert.match(
ui,
/viewer\?\.canvas\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/,
/canvasOf\(this\.viewer\)\?\.addEventListener\(\s*'wheel',\s*this\._initialShareGestureHandler/,
);
assert.match(
ui,
@@ -399,7 +399,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
}
const vesselClick = body(
vessels,
/handler\.setInputAction\(\s*\(click\) => \{([\s\S]*?)\n\s*\},\s*Cesium\.ScreenSpaceEventType\.LEFT_CLICK,?\s*\);/,
/inputFor\(viewer\)\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/,
'vessel click',
);
ordered(vesselClick, [
@@ -415,7 +415,7 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
assert.match(vesselFocus, /requestWorldFocus\(\{/);
const fireClick = body(
firms,
/_clickHandler\.setInputAction\(\(click\) => \{([\s\S]*?)\n \}, Cesium\.ScreenSpaceEventType\.LEFT_CLICK\);/,
/input\.onClick\(\(event\) => \{([\s\S]*?)\n \}\);/,
'fire click',
);
ordered(fireClick, [
+23 -8
View File
@@ -9,6 +9,14 @@ import {
moveCamera,
} from './cameraVerbs.js';
import { createGevActionRunner } from './voice/gevActions.js';
import {
bindFakeCesiumCamera,
followEntity,
} from './testSupport/fakeCameraPort.mjs';
import {
fakeSceneFrame,
fakeSceneQuery,
} from './testSupport/fakeCesiumScene.mjs';
const radians = Cesium.Math.toRadians;
const degrees = Cesium.Math.toDegrees;
@@ -39,6 +47,7 @@ function harness(
mode: Cesium.SceneMode.SCENE3D,
pixelRatio: 1,
tweens: [],
preUpdate: new Cesium.Event(),
requestRender() {},
};
const camera = new Cesium.Camera(scene);
@@ -47,13 +56,21 @@ function harness(
destination: Cesium.Cartesian3.fromDegrees(-0.1276, 51.5072, height),
orientation: { heading: radians(heading), pitch: radians(pitch), roll: 0 },
});
const viewer = {
const double = {
camera,
scene,
trackedEntity: undefined,
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
entities: {},
clock: { onTick: new Cesium.Event() },
};
// The Cesium renderer's own camera port over the real camera; frames from
// the scene's preUpdate.
const viewer = bindFakeCesiumCamera(double, {
query: fakeSceneQuery(double),
frame: fakeSceneFrame(double),
});
// The app's view target: the ground point under the screen centre.
const viewTarget = () => {
const ray = new Cesium.Ray(camera.positionWC, camera.directionWC);
@@ -68,7 +85,7 @@ function harness(
});
const tick = (seconds = 1 / 30) => {
nowMs += seconds * 1000;
viewer.clock.onTick.raiseEvent(viewer.clock);
viewer.scene.preUpdate.raiseEvent(viewer.scene);
};
const finish = () => {
for (let i = 0; i < 600 && getActiveCameraMotion(); i += 1) tick();
@@ -239,9 +256,7 @@ test('a pivoting tilt yields when tracking takes the camera', (t) => {
const h = harness(t);
assert.equal(moveCamera({ motion: 'tilt', pitchDeg: -45 }).ok, true);
h.tick();
const entity = { id: 'tracked' };
h.viewer.trackedEntity = entity;
h.viewer.trackedEntityChanged.raiseEvent(entity);
followEntity(h.viewer, { id: 'tracked' });
assert.equal(getActiveCameraMotion(), null);
});
@@ -548,10 +563,10 @@ test('a regional tilt-up nudge goes to the camera horizon limit', (t) => {
test('a voice tilt from a tracked view judges its limit from the camera pitch', (t) => {
const h = harness(t, { height: 20000, pitch: -5.2 });
h.viewer.trackedEntity = { id: 'tracked' };
followEntity(h.viewer, { id: 'tracked' });
// Voice releases the follow camera before the motion starts.
const release = (start) => {
h.viewer.trackedEntity = undefined;
followEntity(h.viewer, null);
return start();
};
const result = moveCamera({ motion: 'tilt', direction: 'up' }, release);
+437 -514
View File
File diff suppressed because it is too large. Load diff
+9 -8
View File
@@ -1,22 +1,23 @@
/**
* Activates the nearest CCTV record on layer enable and flies only when no
* aircraft tracker or cockpit camera owns the view.
* followed target or cockpit camera owns the view.
* @param {Object} options Layer-enable focus inputs.
* @param {*} options.trackedEntity Current Cesium tracked entity, if any.
* @param {*} options.followed What the camera follows, if anything
* (`followedOf`).
* @param {boolean} options.cockpitActive Whether cockpit mode owns the camera.
* @param {() => (string|null)} options.activate Nearest-camera activation.
* @param {(cameraId: string) => *} options.fly Optional camera flight.
* @returns {*} Activated camera ID for a held view, or the flight result.
*/
export function runCctvLayerEnableFocus({
trackedEntity = null,
followed = null,
cockpitActive = false,
activate,
fly,
} = {}) {
const cameraId = activate?.();
if (!cameraId) return false;
if (trackedEntity || cockpitActive) return cameraId;
if (followed || cockpitActive) return cameraId;
return fly?.(cameraId);
}
@@ -25,11 +26,11 @@ export function runCctvLayerEnableFocus({
* chain. Either observation suppresses the optional CCTV focus flight.
* @param {Object} [before={}] Ownership immediately before the await.
* @param {Object} [after={}] Ownership immediately after the await.
* @returns {{ trackedEntity: *, cockpitActive: boolean }} Conservative ownership.
* @returns {{ followed: *, cockpitActive: boolean }} Conservative ownership.
*/
function mergeCctvEnableOwnership(before = {}, after = {}) {
return {
trackedEntity: before.trackedEntity || after.trackedEntity || null,
followed: before.followed || after.followed || null,
cockpitActive: !!(before.cockpitActive || after.cockpitActive),
};
}
@@ -60,7 +61,7 @@ export async function runCctvLayerEnableTransition({
const ownershipBefore = readOwnership?.() || {};
if (target === true) {
debug?.('[UI:CCTV] ownership before setEnabled await', {
trackedId: ownershipBefore.trackedEntity?.id ?? null,
trackedId: ownershipBefore.followed?.key ?? null,
cockpitActive: !!ownershipBefore.cockpitActive,
});
}
@@ -68,7 +69,7 @@ export async function runCctvLayerEnableTransition({
const ownershipAfter = readOwnership?.() || {};
if (target === true) {
debug?.('[UI:CCTV] ownership after setEnabled await', {
trackedId: ownershipAfter.trackedEntity?.id ?? null,
trackedId: ownershipAfter.followed?.key ?? null,
cockpitActive: !!ownershipAfter.cockpitActive,
});
}
+6 -6
View File
@@ -8,8 +8,8 @@ import {
test('CCTV layer enable activates nearest without stealing a tracked or cockpit view', () => {
for (const ownership of [
{ trackedEntity: { id: 'tracked-plane' }, cockpitActive: false },
{ trackedEntity: null, cockpitActive: true },
{ followed: { key: 'tracked-plane' }, cockpitActive: false },
{ followed: null, cockpitActive: true },
]) {
const calls = [];
const result = runCctvLayerEnableFocus({
@@ -48,15 +48,15 @@ test('CCTV layer enable activates nearest without stealing a tracked or cockpit
});
test('CCTV enable retains a pre-await tracking snapshot when tracking clears during enable', async () => {
let trackedEntity = { id: 'tracked-plane' };
let followed = { key: 'tracked-plane' };
let flyCalls = 0;
const diagnostics = [];
const result = await runCctvLayerEnableTransition({
target: true,
readOwnership: () => ({ trackedEntity, cockpitActive: false }),
readOwnership: () => ({ followed, cockpitActive: false }),
setEnabled: async () => {
await Promise.resolve();
trackedEntity = null;
followed = null;
},
shouldFocus: () => true,
activate: () => 'cam-near',
@@ -83,7 +83,7 @@ test('CCTV disable transition does not emit enable-ownership diagnostics', async
const result = await runCctvLayerEnableTransition({
target: false,
readOwnership: () => ({ trackedEntity: { id: 'tracked-plane' }, cockpitActive: false }),
readOwnership: () => ({ followed: { key: 'tracked-plane' }, cockpitActive: false }),
setEnabled: async (target) => transitions.push(target),
shouldFocus: () => true,
activate: () => 'cam-near',
+121 -104
View File
@@ -1,5 +1,25 @@
import * as Cesium from 'cesium';
import { governorRequestRender } from './renderGovernor.js';
import {
cameraOf,
canvasOf,
findCamera,
findFrame,
findQuery,
} from './render/rendererOf.js';
import {
moonPositionInertial,
sunPositionInertial,
temeToPseudoFixed,
} from './geo/celestial.js';
import { WGS84 } from './geo/ellipsoid.js';
import { frameVector } from './geo/frames.js';
import {
dot,
magnitude,
normalize,
PI_OVER_TWO,
toRadians,
} from './geo/vector.js';
import { worldClock, worldTimeFor } from './time/worldClock.js';
// The ring shows the sun and moon at the time the sky is drawn.
@@ -38,7 +58,13 @@ const EPHEMERIS_WORLD_STEP_MS = 60_000;
const RING_INSET_PX = 11;
const MARKER_INSET_PX = 36;
const COLLIDING_MARKER_EXTRA_INSET_PX = 32;
const MARKER_COLLISION_ANGLE = Cesium.Math.toRadians(6);
const MARKER_COLLISION_ANGLE = toRadians(6);
/** The ellipsoid's largest radius, metres. */
const EARTH_MAX_RADIUS_M = Math.max(
WGS84.radii.x,
WGS84.radii.y,
WGS84.radii.z,
);
const FULL_GLOBE_RADIUS_RATIO = 0.61;
const TAU = Math.PI * 2;
// This overlay is a secondary HUD treatment. Keep it smooth while reserving
@@ -218,7 +244,7 @@ export function isFullGlobeInsideKeyhole(geometry, wasVisible = false) {
/** Return the Earth-disc radius in CSS pixels for a perspective camera. */
export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) {
const earthRadiusM = Cesium.Ellipsoid.WGS84.maximumRadius;
const earthRadiusM = EARTH_MAX_RADIUS_M;
if (
!Number.isFinite(cameraDistance) ||
cameraDistance <= earthRadiusM ||
@@ -234,15 +260,19 @@ export function earthDiscScreenRadius(cameraDistance, viewportHeight, fovy) {
return Number.isFinite(radius) && radius > 0 ? radius : null;
}
const EARTH_CENTRE = Object.freeze({ x: 0, y: 0, z: 0 });
/**
* Project the visible Earth disc into viewport coordinates.
* Project the visible Earth disc into viewport coordinates, through the
* renderer's camera pose and its query port's projection.
* Shared by full-globe UI treatments that must agree on visual containment.
*
* @param {object} viewer - Cesium Viewer-like object.
* @param {object} viewer - The scene object the renderer is found from.
* @param {number} width - Viewport width in CSS pixels.
* @param {number} height - Viewport height in CSS pixels.
* @param {object} [scratchCenter] - Reusable Cesium Cartesian2 result.
* @param {object} [scratchToCenter] - Reusable Cesium Cartesian3 result.
* @param {{x:number,y:number}} [scratchCenter] - Takes the projected centre.
* @param {{x:number,y:number,z:number}} [scratchToCenter] - Takes the
* vector from the eye to the Earth's centre.
* @returns {object|null}
*/
export function projectEarthDiscToViewport(
@@ -252,36 +282,32 @@ export function projectEarthDiscToViewport(
scratchCenter = undefined,
scratchToCenter = undefined,
) {
const camera = viewer?.camera;
const scene = viewer?.scene;
if (!camera || !scene || !(width > 0) || !(height > 0)) return null;
const camera = findCamera(viewer);
if (!camera || !(width > 0) || !(height > 0)) return null;
const pose = camera.pose();
const eye = pose.position;
const distance = Cesium.Cartesian3.magnitude(camera.positionWC);
const distance = magnitude(eye);
if (!Number.isFinite(distance) || distance <= EARTH_MAX_RADIUS_M) return null;
const toCenter = scratchToCenter || { x: 0, y: 0, z: 0 };
toCenter.x = -eye.x;
toCenter.y = -eye.y;
toCenter.z = -eye.z;
if (dot(pose.direction, toCenter) <= 0) return null;
const projected = findQuery(viewer)?.project(EARTH_CENTRE);
if (
!Number.isFinite(distance) ||
distance <= Cesium.Ellipsoid.WGS84.maximumRadius
!projected ||
!Number.isFinite(projected.x) ||
!Number.isFinite(projected.y)
)
return null;
const center = scratchCenter || { x: 0, y: 0 };
center.x = projected.x;
center.y = projected.y;
const toCenter = Cesium.Cartesian3.negate(
camera.positionWC,
scratchToCenter || new Cesium.Cartesian3(),
);
if (Cesium.Cartesian3.dot(camera.directionWC, toCenter) <= 0) return null;
const center = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
Cesium.Cartesian3.ZERO,
scratchCenter,
);
if (!center || !Number.isFinite(center.x) || !Number.isFinite(center.y))
return null;
const earthRadius = earthDiscScreenRadius(
distance,
height,
camera.frustum?.fovy,
);
const earthRadius = earthDiscScreenRadius(distance, height, pose.fovy);
if (!earthRadius) return null;
const keyhole = getKeyholeGeometry(width, height);
@@ -396,14 +422,23 @@ let rings = 0;
*/
export class CelestialRing {
/**
* @param {Cesium.Viewer} viewer
* @param {{enabled?:boolean,onAutoDisable?:Function,store:object}} options
* @param {object} viewer - The scene object the renderer is found from;
* the ring reads its canvas and container (DOM) and reaches the rest
* through the renderer's camera, frame and query ports.
* @param {{enabled?:boolean,onAutoDisable?:Function,store:object,preciseFrameAt?:Function}} options
* `store` is the celestial ring store (src/ui/stores/celestialRing.js);
* the keyhole helpers here stay free of Vue for the packages that use
* them.
* them. `preciseFrameAt(ms)` gives the ICRF-to-fixed rotation as axes,
* or null while its tables have not loaded; without it, or while it has
* no answer, the ring uses the pseudo-fixed frame.
*/
constructor(viewer, { enabled = true, onAutoDisable = null, store }) {
constructor(
viewer,
{ enabled = true, onAutoDisable = null, store, preciseFrameAt = null },
) {
this.viewer = viewer;
this._preciseFrameAt =
typeof preciseFrameAt === 'function' ? preciseFrameAt : null;
this.enabled = !!enabled;
this.visible = false;
this._onAutoDisable =
@@ -426,18 +461,14 @@ export class CelestialRing {
this._moonCanvas = null;
this._moonCtx = null;
this._sunInertial = new Cesium.Cartesian3();
this._moonInertial = new Cesium.Cartesian3();
this._sunFixed = new Cesium.Cartesian3();
this._moonFixed = new Cesium.Cartesian3();
this._toCenter = new Cesium.Cartesian3();
this._screenCenter = new Cesium.Cartesian2();
this._fixedMatrix = new Cesium.Matrix3();
this._sunFixed = { x: 0, y: 0, z: 0 };
this._moonFixed = { x: 0, y: 0, z: 0 };
this._toCenter = { x: 0, y: 0, z: 0 };
this._screenCenter = { x: 0, y: 0 };
this._initView(store);
this._removePostRender = viewer.scene.postRender.addEventListener(() =>
this._draw(),
);
this._removePostRender =
findFrame(viewer)?.on('postRender', () => this._draw()) ?? null;
// Pre-existing staleness fix (perf wave 2 review): the ephemeris was
// sampled once per visible-enable from the FROZEN app clock, so the
// sun/moon markers aged with the app. Resample real wall time each
@@ -453,8 +484,6 @@ export class CelestialRing {
governorRequestRender('celestial-ephemeris');
}, 60_000);
// A jump in the world time moves the sun and moon at once.
this._skyDate = new Date();
this._skyTime = new Cesium.JulianDate();
// Played through, the sky moves on each minute of world time it passes.
this._ephemerisWorldMs = null;
this._unsubscribeWorldTime = worldClock.subscribe(({ timeMs }) => {
@@ -554,9 +583,14 @@ export class CelestialRing {
});
}
/** The renderer's canvas; a viewer with no renderer bound, its own. */
_canvas() {
return canvasOf(this.viewer);
}
/** Whether the current camera already frames the complete globe inside the keyhole. */
isGlobeFullyVisible() {
const canvas = this.viewer.scene.canvas;
const canvas = this._canvas();
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
if (!(width > 0 && height > 0)) return false;
@@ -571,13 +605,15 @@ export class CelestialRing {
* @returns {boolean} Whether a valid camera flight was started.
*/
focusFullGlobe({ duration = 2.4 } = {}) {
const canvas = this.viewer.scene.canvas;
const canvas = this._canvas();
const height = canvas.clientHeight || canvas.height;
const cartographic = this.viewer.camera.positionCartographic;
const fovy = this.viewer.camera.frustum?.fovy;
const camera = cameraOf(this.viewer);
const pose = camera.pose();
const fovy = pose.fovy;
if (
!(height > 0) ||
!cartographic ||
!Number.isFinite(pose.lon) ||
!Number.isFinite(pose.lat) ||
!Number.isFinite(fovy) ||
fovy <= 0 ||
fovy >= Math.PI
@@ -585,7 +621,7 @@ export class CelestialRing {
return false;
}
const earthRadius = Cesium.Ellipsoid.WGS84.maximumRadius;
const earthRadius = EARTH_MAX_RADIUS_M;
const keyholeRadius = getKeyholeGeometry(
canvas.clientWidth || canvas.width,
height,
@@ -600,27 +636,25 @@ export class CelestialRing {
this._focusInProgress = true;
const finishFocus = () => {
this._focusInProgress = false;
this.viewer.scene.requestRender?.();
findFrame(this.viewer)?.requestRender('celestial-focus');
};
this.viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromRadians(
cartographic.longitude,
cartographic.latitude,
altitude,
),
orientation: {
heading: this.viewer.camera.heading,
pitch: -Cesium.Math.PI_OVER_TWO,
roll: 0,
camera.flyTo(
{ lon: pose.lon, lat: pose.lat, height: altitude },
{
orientation: {
heading: pose.heading,
pitch: -PI_OVER_TWO,
roll: 0,
},
durationS: duration,
easing: 'cubicInOut',
onComplete: finishFocus,
onCancel: () => {
finishFocus();
if (!this.isGlobeFullyVisible()) this._autoDisable();
},
},
duration,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
complete: finishFocus,
cancel: () => {
finishFocus();
if (!this.isGlobeFullyVisible()) this._autoDisable();
},
});
);
return true;
}
@@ -671,31 +705,16 @@ export class CelestialRing {
/**
* Sample Earth-fixed directions once per enable. Camera movement only
* re-projects these cached vectors; it never re-runs the planetary model.
* The precise ICRF frame serves once its tables have loaded, the
* pseudo-fixed one before.
* @param {number} ms Epoch milliseconds.
*/
_updateEphemeris(time) {
_updateEphemeris(ms) {
if (!this._ephemerisDirty) return true;
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
time,
this._sunInertial,
);
Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(
time,
this._moonInertial,
);
const matrix =
Cesium.Transforms.computeIcrfToFixedMatrix(time, this._fixedMatrix) ||
Cesium.Transforms.computeTemeToPseudoFixedMatrix(time, this._fixedMatrix);
if (!matrix) return false;
Cesium.Matrix3.multiplyByVector(matrix, this._sunInertial, this._sunFixed);
Cesium.Matrix3.multiplyByVector(
matrix,
this._moonInertial,
this._moonFixed,
);
Cesium.Cartesian3.normalize(this._sunFixed, this._sunFixed);
Cesium.Cartesian3.normalize(this._moonFixed, this._moonFixed);
const frame = this._preciseFrameAt?.(ms) ?? temeToPseudoFixed(ms);
this._sunFixed = normalize(frameVector(frame, sunPositionInertial(ms)));
this._moonFixed = normalize(frameVector(frame, moonPositionInertial(ms)));
this._ephemerisDirty = false;
this._ephemerisUpdateCount += 1;
return true;
@@ -792,7 +811,7 @@ export class CelestialRing {
const now = performance.now();
if (now < this._nextDrawAt) return;
this._nextDrawAt = now + 1000 / CELESTIAL_MAX_FRAME_RATE;
const canvas = this.viewer.scene.canvas;
const canvas = this._canvas();
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
if (!(width > 0 && height > 0)) return;
@@ -822,19 +841,17 @@ export class CelestialRing {
return;
}
this._skyDate.setTime(skyTime());
const time = Cesium.JulianDate.fromDate(this._skyDate, this._skyTime);
if (!this._updateEphemeris(time)) return;
if (!this._updateEphemeris(skyTime())) return;
this._present({ ephemerisUpdates: String(this._ephemerisUpdateCount) });
const camera = this.viewer.camera;
const pose = cameraOf(this.viewer).pose();
const sunProjection = celestialScreenAngle(
Cesium.Cartesian3.dot(this._sunFixed, camera.rightWC),
Cesium.Cartesian3.dot(this._sunFixed, camera.upWC),
dot(this._sunFixed, pose.right),
dot(this._sunFixed, pose.up),
this._sunAngle,
);
const moonProjection = celestialScreenAngle(
Cesium.Cartesian3.dot(this._moonFixed, camera.rightWC),
Cesium.Cartesian3.dot(this._moonFixed, camera.upWC),
dot(this._moonFixed, pose.right),
dot(this._moonFixed, pose.up),
this._moonAngle,
);
if (sunProjection.stable) this._sunAngle = sunProjection.angle;
+135 -5
View File
@@ -9,7 +9,14 @@ import { createPinia } from 'pinia';
import { useCelestialRingStore } from './ui/stores/celestialRing.js';
import CelestialRingView from './ui/views/panels/CelestialRing.vue';
import * as Cesium from 'cesium';
import { CelestialRing } from './celestialRing.js';
import {
CelestialRing,
earthDiscScreenRadius,
projectEarthDiscToViewport,
} from './celestialRing.js';
import { bindRenderer } from './render/rendererOf.js';
import { bindFakeCesiumCamera } from './testSupport/fakeCameraPort.mjs';
import { fakeSceneFrame } from './testSupport/fakeCesiumScene.mjs';
// happy-dom has no 2D context; a stand-in takes every drawing call.
const context = new Proxy(
@@ -19,18 +26,26 @@ const context = new Proxy(
globalThis.HTMLCanvasElement.prototype.getContext = () => context;
function fakeViewer(container) {
return {
const canvas = {
clientWidth: 400,
clientHeight: 300,
width: 400,
height: 300,
};
const viewer = {
container,
canvas,
camera: {
rightWC: new Cesium.Cartesian3(1, 0, 0),
upWC: new Cesium.Cartesian3(0, 1, 0),
},
scene: {
canvas: { clientWidth: 400, clientHeight: 300, width: 400, height: 300 },
canvas,
postRender: { addEventListener: () => () => {} },
requestRender() {},
},
};
return bindFakeCesiumCamera(viewer, { frame: fakeSceneFrame(viewer) });
}
function fixture(t) {
@@ -157,8 +172,7 @@ const FRAMED = {
/** Run one rendered frame, past the frame-rate throttle. */
function frame(ring, disc) {
ring._projectedEarthDisc = () => disc;
// Fixed sun and moon directions; Cesium's own model would fetch its
// orientation data.
// Fixed sun and moon directions, so markers do not move with the clock.
ring._updateEphemeris = () => {
if (ring._ephemerisDirty) {
Cesium.Cartesian3.clone(new Cesium.Cartesian3(1, 0, 0), ring._sunFixed);
@@ -249,3 +263,119 @@ test('a ring the store no longer shows stops drawing', async (t) => {
assert.equal(earlier.enabled, true);
assert.equal(disabled, 0);
});
test('the sun and moon directions are the planetary model in the pseudo-fixed frame', () => {
const pinia = createPinia();
const ring = new CelestialRing(fakeViewer({}), {
enabled: false,
store: useCelestialRingStore(pinia),
// The precise frame's tables have not loaded.
preciseFrameAt: () => null,
});
const ms = Date.UTC(2026, 10, 7, 12, 30);
ring._ephemerisDirty = true;
assert.equal(ring._updateEphemeris(ms), true);
// Cesium's own, before the sky has loaded the precise frame's tables.
const time = Cesium.JulianDate.fromDate(new Date(ms));
const matrix = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);
const expected = (inertial) =>
Cesium.Cartesian3.normalize(
Cesium.Matrix3.multiplyByVector(
matrix,
inertial,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const sun = expected(
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
time,
),
);
const moon = expected(
Cesium.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(
time,
),
);
for (const [got, want] of [
[ring._sunFixed, sun],
[ring._moonFixed, moon],
])
for (const axis of ['x', 'y', 'z'])
assert.ok(Object.is(got[axis], want[axis]), axis);
assert.equal(ring._ephemerisUpdateCount, 1);
ring.destroy();
});
test('the projected disc reads the camera and query ports', () => {
const canvas = { clientWidth: 800, clientHeight: 600 };
const viewer = { canvas };
const distance = 3 * 6378137;
const pose = {
position: { x: distance, y: 0, z: 0 },
direction: { x: -1, y: 0, z: 0 },
fovy: Math.PI / 3,
};
const unbind = bindRenderer(viewer, {
canvas,
camera: { pose: () => pose },
query: { project: () => ({ x: 410, y: 290 }) },
});
const toCenter = { x: 0, y: 0, z: 0 };
const centre = { x: 0, y: 0 };
const disc = projectEarthDiscToViewport(viewer, 800, 600, centre, toCenter);
assert.equal(disc.earthCenterX, 410);
assert.equal(disc.earthCenterY, 290);
assert.deepEqual(centre, { x: 410, y: 290 });
// The scratch takes the eye-to-centre vector, as callers read it after.
assert.deepEqual(toCenter, { x: -distance, y: -0, z: -0 });
assert.ok(
Math.abs(
disc.earthRadius - earthDiscScreenRadius(distance, 600, pose.fovy),
) < 1e-9,
);
// Facing away: null, with the eye-to-centre vector still written, as
// radio navigation reads it after.
pose.direction = { x: 1, y: 0, z: 0 };
const away = { x: 0, y: 0, z: 0 };
assert.equal(projectEarthDiscToViewport(viewer, 800, 600, null, away), null);
assert.deepEqual(away, { x: -distance, y: -0, z: -0 });
// Inside the ellipsoid's largest radius: null, the scratch untouched.
pose.position = { x: 6378137, y: 0, z: 0 };
const inside = { x: 1, y: 2, z: 3 };
assert.equal(
projectEarthDiscToViewport(viewer, 800, 600, null, inside),
null,
);
assert.deepEqual(inside, { x: 1, y: 2, z: 3 });
unbind();
});
test('the precise frame serves once it answers', () => {
const pinia = createPinia();
// A quarter turn about z: x goes to y.
const quarter = {
x: { x: 0, y: 1, z: 0 },
y: { x: -1, y: 0, z: 0 },
z: { x: 0, y: 0, z: 1 },
};
const ring = new CelestialRing(fakeViewer({}), {
enabled: false,
store: useCelestialRingStore(pinia),
preciseFrameAt: () => quarter,
});
const ms = Date.UTC(2026, 10, 7, 12, 30);
ring._ephemerisDirty = true;
ring._updateEphemeris(ms);
const time = Cesium.JulianDate.fromDate(new Date(ms));
const sun = Cesium.Cartesian3.normalize(
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
time,
),
new Cesium.Cartesian3(),
);
assert.ok(Math.abs(ring._sunFixed.x + sun.y) < 1e-12);
assert.ok(Math.abs(ring._sunFixed.y - sun.x) < 1e-12);
assert.ok(Math.abs(ring._sunFixed.z - sun.z) < 1e-12);
ring.destroy();
});
+7 -7
View File
@@ -1,5 +1,6 @@
import { applicationServices } from './services/application.js';
import * as Cesium from 'cesium';
import { toRadians } from './geo/vector.js';
import { findCamera } from './render/rendererOf.js';
import { greatCircleMeters } from './geoDistance.js';
import {
deriveWeatherEffectProfile,
@@ -341,15 +342,14 @@ class CockpitCloudEffectsController {
}
cameraPoint() {
const cartographic = this.viewer?.camera?.positionCartographic;
if (!cartographic) return null;
const latitude = Cesium.Math.toDegrees(cartographic.latitude);
const longitude = Cesium.Math.toDegrees(cartographic.longitude);
const pose = this.viewer ? findCamera(this.viewer)?.pose() : null;
if (!pose) return null;
const { lat: latitude, lon: longitude } = pose;
if (![latitude, longitude].every(Number.isFinite)) return null;
return {
latitude,
longitude,
altitudeM: Math.max(0, Number(cartographic.height) || 0),
altitudeM: Math.max(0, Number(pose.height) || 0),
};
}
@@ -543,7 +543,7 @@ class CockpitCloudEffectsController {
render(timeSec) {
const gl = this.gl;
if (!gl || !this.program || !this.locations) return;
const windRadians = Cesium.Math.toRadians(this.windDirectionDeg);
const windRadians = toRadians(this.windDirectionDeg);
const windScale = 0.008 + this.windStrength * 0.022;
gl.useProgram(this.program);
gl.uniform2f(
+7 -7
View File
@@ -225,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',
);
});
@@ -291,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', () => {
@@ -1173,7 +1173,7 @@ test('cockpit route direction uses self-contained vector artwork, not a font lig
test('cockpit aircraft handoff invalidates the prior world-position anchor', () => {
const match = _adoptTrackedEntity.toString();
assert.ok(match, 'cockpit tracked-entity handoff block is missing');
assert.match(match, /this\.viewer\.trackedEntity = undefined;/);
assert.match(match, /stopFollowing\(this\.viewer\);/);
assert.match(match, /this\.cockpitAnchorValid = false;/);
assert.match(
match,
+1 -1
View File
@@ -412,7 +412,7 @@ export function relativeBearing(bearing, heading) {
* Resolve which flight layer owns the cockpit's tracked aircraft.
*
* Both layers can briefly describe a tracked aircraft during a cross-layer
* handoff, so the viewer's normalized tracked identity (`gevTrackedId`) is the
* handoff, so the viewer's normalized tracked identity (the entity record's `trackedId`) is the
* tie-breaker — the same rule `militaryAwareness.currentTrackedFlightSubject`
* uses. Layer precedence remains the fallback when no normalized identity is
* available, so tracking paths that never stamp one keep working.
+1 -1
View File
@@ -432,7 +432,7 @@ test('tracked-identity resolution falls back to layer precedence', () => {
const civilian = { icao24: 'aaa077' };
const military = { icao24: 'ae01ce' };
// No stamped identity (or one that matches neither layer) keeps the historic
// civilian-first order so tracking paths without gevTrackedId still work.
// civilian-first order so tracking paths without an entity record trackedId still work.
assert.equal(resolveTrackedAircraftInfo({ civilian, military }).layerId, 'flights');
assert.equal(
resolveTrackedAircraftInfo({ civilian, military, trackedId: 'satellites:25544' }).layerId,
+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', () => {
+65
View File
@@ -206,6 +206,71 @@ export function createCyberSonarSampler(
};
}
// The contact tint: a cool grey outside the sector, warm inside it, each
// mixed in at this strength over the contact's own colour.
const CYBER_SONAR_DIM_RGB = [0.62, 0.68, 0.72];
const CYBER_SONAR_LIT_RGB = [1, 0.84, 0.84];
const CYBER_SONAR_TINT_STRENGTH = 0.72;
/** How far toward the warm tint contacts sit while the sweep is off. */
const CYBER_SONAR_NEUTRAL_COVERAGE = 0.46;
const hexOf = (rgb) =>
`#${rgb
.map((c) =>
Math.round(clamp01(c) * 255)
.toString(16)
.padStart(2, '0'),
)
.join('')}`;
/**
* The renderer's screen modulation sector for the Cyber contact sweep over
* a `width` x `height` CSS-pixel map: the same band `createCyberSonarSampler`
* samples. Not sweeping (Sonar OFF, reduced motion), a radius of 0 holds
* every contact at the neutral level the sweep rests at.
* @param {number} width
* @param {number} height
* @param {number} nowMs
* @param {{sweeping?: boolean, root?: object}} [options]
* @returns {import('./render/contract/effects').ModulationSector}
*/
export function cyberSonarSector(
width,
height,
nowMs,
{ sweeping = true, root = globalThis.document?.documentElement } = {},
) {
const settings = readCyberSonarSettings(root);
const floor = settings.opacity / 100;
const center = { x: width / 2, y: height / 2 };
const widthRad = (settings.sector * Math.PI) / 180;
if (!sweeping) {
const coverage = floor >= 0.9999 ? 1 : CYBER_SONAR_NEUTRAL_COVERAGE;
return {
center,
angle: 0,
width: widthRad,
radius: 0,
floor: floor + (1 - floor) * CYBER_SONAR_NEUTRAL_COVERAGE,
strength: CYBER_SONAR_TINT_STRENGTH,
color: hexOf(
CYBER_SONAR_DIM_RGB.map(
(c, i) => c + (CYBER_SONAR_LIT_RGB[i] - c) * coverage,
),
),
};
}
return {
center,
angle: (cyberSonarAngleDeg(nowMs) * Math.PI) / 180,
width: widthRad,
radius: (Math.min(width * 0.4, height * 0.52) * settings.range) / 100,
floor,
strength: CYBER_SONAR_TINT_STRENGTH,
color: hexOf(CYBER_SONAR_LIT_RGB),
};
}
/** Remaining delay before the next contact-projection refresh is due. */
export function cyberSonarFrameDelay(
lastPaintAt,
-295
View File
@@ -1,295 +0,0 @@
import * as Cesium from 'cesium';
// Narrow, version-tested engine adapter. Cesium has no public custom shader
// option for native point/billboard collections. Do not patch its prototypes or
// access EntityCluster's private collections. An engine upgrade must revalidate
// this adapter; unsupported versions keep the original commands unchanged.
export const CYBER_SONAR_CESIUM_VERSION = '1.138.0';
// Follow every public DrawCommand setter, including pick/shadow/culling flags.
// Copying native.dirty would keep derived pipelines dirty forever: the scene
// consumes our command, so it never clears that flag on the native command.
const commandProperties = Object.entries(
Object.getOwnPropertyDescriptors(Cesium.DrawCommand.prototype),
)
.filter(
([key, descriptor]) =>
descriptor.set && key !== 'shaderProgram' && key !== 'uniformMap',
)
.map(([key]) => key);
export function syncCyberSonarCommand(
native,
record,
program,
uniforms,
labelBackground,
) {
if (!record.command) {
record.command = new Cesium.DrawCommand();
record.uniformMap = {
...uniforms,
u_gevSonarLabelBackground: () => record.labelBackground,
};
}
const command = record.command;
record.labelBackground = labelBackground;
// Uniform values (angle/viewport/etc.) change through stable callbacks, not
// new maps/functions. Owner callback replacement and removal still propagate.
for (const key in record.uniformMap) {
if (
!(key in uniforms) &&
key !== 'u_gevSonarLabelBackground' &&
!(key in native.uniformMap)
) {
delete record.uniformMap[key];
command.dirty = true;
}
}
for (const key in native.uniformMap) {
if (record.uniformMap[key] !== native.uniformMap[key]) {
record.uniformMap[key] = native.uniformMap[key];
command.dirty = true;
}
}
for (const key of commandProperties) command[key] = native[key];
command.shaderProgram = program;
command.uniformMap = record.uniformMap;
return command;
}
export function sonarVertexSource(source, kind) {
const text = source.sources.join('\n');
const attribute =
kind === 'point' ? 'positionHighAndSize' : 'positionHighAndScale';
const lowAttribute =
kind === 'point' ? 'positionLowAndOutline' : 'positionLowAndRotation';
if (
!text.includes(attribute) ||
!text.includes(lowAttribute) ||
!text.includes('v_color') ||
!/void\s+main\s*\(\s*\)/.test(text)
)
return null;
const next = source.clone();
next.sources = [
text.replace(/void\s+main\s*\(\s*\)/, 'void gev_sonar_main()'),
`
uniform vec4 u_gevSonar; // angle, radius, opacity floor, sweep enabled
uniform vec2 u_gevSonarViewport;
uniform float u_gevSonarSector;
uniform float u_gevSonarLabelBackground;
void main() {
gev_sonar_main();
// All corners/glyphs share the contact anchor, before native screen offsets.
// Leave gl_Position untouched so appearance never changes geometry or picks.
vec4 anchor = czm_modelViewProjectionRelativeToEye * czm_translateRelativeToEye(${attribute}.xyz, ${lowAttribute}.xyz);
if (anchor.w <= 0.0) return;
vec2 pixel = anchor.xy / anchor.w * u_gevSonarViewport * 0.5;
float floorValue = u_gevSonar.z;
float factor = floorValue + (1.0 - floorValue) * 0.46;
if (u_gevSonar.w > 0.5) {
float distanceSquared = dot(pixel, pixel);
float radiusSquared = u_gevSonar.y * u_gevSonar.y;
float delta = mod(degrees(atan(pixel.x, pixel.y)) - u_gevSonar.x + 360.0, 360.0);
if (delta > 359.9999) delta = 0.0;
factor = floorValue;
if (distanceSquared < radiusSquared * 0.000625) factor = 1.0;
else if (distanceSquared <= radiusSquared && delta <= u_gevSonarSector)
factor += (1.0 - floorValue) * min(1.0, (u_gevSonarSector - delta) / min(10.0, u_gevSonarSector * 0.42));
}
#ifdef SDF
factor = (1.0 + factor) * 0.5;
#else
if (u_gevSonarLabelBackground > 0.5) factor = (1.0 + factor) * 0.5;
#endif
float coverage = floorValue >= 0.9999 ? 1.0 : clamp((factor - floorValue) / (1.0 - floorValue), 0.0, 1.0);
if (u_gevSonarLabelBackground < 0.5)
v_color.rgb = v_color.rgb * 0.28 + (vec3(0.62, 0.68, 0.72) + vec3(0.38, 0.16, 0.12) * coverage) * 0.72;
// Apply before native fragment pass classification, never after main().
v_color.a *= factor;
${kind === 'point' ? 'v_outlineColor.a *= factor;' : '#ifdef SDF\n v_outlineColor.a *= factor;\n #endif'}
}
`,
];
return next;
}
// Use native batch bounds, never individual contacts, for idle render demand.
// Like Cesium's frustum builder, exclude the far plane (it fits multiple frusta).
export function isCyberSonarCommandVisible(command, frameState, culling) {
const bounds = command.boundingVolume;
if (!bounds || !command.cull) return true;
culling ??= new Cesium.CullingVolume(
frameState.cullingVolume.planes.slice(0, 5),
);
if (culling.computeVisibility(bounds) === Cesium.Intersect.OUTSIDE)
return false;
return !(
frameState.mode === Cesium.SceneMode.SCENE3D &&
frameState.occluder &&
command.occlude &&
bounds.isOccluded(frameState.occluder)
);
}
/** Work scales with draw commands, not the number of contacts in a collection.
* Source programs, colors, pick IDs, render states and other scenes stay owned
* by Cesium. Only this scene's rendered command slice receives derived shaders.
*/
export function createCyberSonarGpu(scene, readFrame) {
const root = scene.primitives;
const original = root.update;
const programs = new Map();
let commands = new WeakMap();
let disposed = false;
const stats = {
commands: 0,
visibleCommands: 0,
programs: 0,
supported: Cesium.VERSION === CYBER_SONAR_CESIUM_VERSION,
error: null,
};
const uniforms = new Cesium.Cartesian4();
const viewport = new Cesium.Cartesian2();
let sector = 24;
const sonarUniforms = {
u_gevSonar: () => uniforms,
u_gevSonarViewport: () => viewport,
u_gevSonarSector: () => sector,
};
const culling = new Cesium.CullingVolume();
const used = new Set();
const replaced = [];
const release = () => {
for (const { program } of programs.values())
if (!program.isDestroyed()) program.destroy();
programs.clear();
commands = new WeakMap();
used.clear();
replaced.length = 0;
stats.programs = 0;
};
const wrapped = function (frameState) {
const start = frameState.commandList.length;
original.call(this, frameState);
stats.commands = 0;
stats.visibleCommands = 0;
if (
disposed ||
!stats.supported ||
!frameState.passes.render ||
frameState.passes.pick
)
return;
const frame = readFrame();
if (!frame.enabled) {
if (programs.size) release();
return;
}
viewport.x = scene.drawingBufferWidth;
viewport.y = scene.drawingBufferHeight;
uniforms.x = frame.angle;
uniforms.y =
(Math.min(viewport.x * 0.4, viewport.y * 0.52) * frame.range) / 100;
uniforms.z = frame.opacity / 100;
uniforms.w = frame.active ? 1 : 0;
sector = frame.sector;
used.clear();
replaced.length = 0;
if (frameState.cullingVolume)
for (let i = 0; i < 5; i++)
culling.planes[i] = frameState.cullingVolume.planes[i];
try {
for (let i = start; i < frameState.commandList.length; i++) {
const native = frameState.commandList[i];
const kind =
native.owner instanceof Cesium.PointPrimitiveCollection
? 'point'
: native.owner instanceof Cesium.BillboardCollection
? 'billboard'
: null;
if (!kind || !native.shaderProgram || !native.uniformMap) continue;
const source = native.shaderProgram;
// Label backgrounds are non-SDF billboard batches. The version-tested
// engine pick association distinguishes them without enumerating labels
// or reaching into EntityCluster. One representative per draw batch;
// Cesium's label glyph/background collections are homogeneous.
const labelBackground =
kind === 'billboard' &&
!source.vertexShaderSource.defines.includes('SDF') &&
native.owner.length > 0 &&
native.owner.get(0).pickPrimitive instanceof Cesium.Label
? 1
: 0;
let entry = programs.get(source);
if (!entry) {
const vertex = sonarVertexSource(source.vertexShaderSource, kind);
if (!vertex) throw new Error('Unsupported native contact shader');
const attributes = Object.fromEntries(
Object.entries(source.vertexAttributes).map(([name, value]) => [
name,
value.index,
]),
);
const program = Cesium.ShaderProgram.fromCache({
context: frameState.context,
vertexShaderSource: vertex,
fragmentShaderSource: source.fragmentShaderSource,
attributeLocations: attributes,
});
// Compile while errors can still leave the whole native command slice
// intact, rather than stopping the viewer's render loop at draw time.
try {
void program.allUniforms;
} catch (error) {
program.destroy();
throw error;
}
programs.set(source, (entry = { program }));
}
used.add(source);
let record = commands.get(native);
if (!record) commands.set(native, (record = {}));
const derived = syncCyberSonarCommand(
native,
record,
entry.program,
sonarUniforms,
labelBackground,
);
replaced.push(i, native);
frameState.commandList[i] = derived;
stats.commands++;
if (isCyberSonarCommandVisible(native, frameState, culling))
stats.visibleCommands++;
}
for (const [source, entry] of programs)
if (!used.has(source)) {
if (!entry.program.isDestroyed()) entry.program.destroy();
programs.delete(source);
}
stats.programs = programs.size;
} catch (error) {
// Recover the original commands already replaced in this slice.
for (let i = 0; i < replaced.length; i += 2)
frameState.commandList[replaced[i]] = replaced[i + 1];
stats.supported = false;
stats.commands = 0;
stats.visibleCommands = 0;
stats.error = String(error?.message || error);
release();
}
};
root.update = wrapped;
return {
stats,
destroy() {
if (disposed) return;
disposed = true;
if (root.update === wrapped && !root.isDestroyed?.())
root.update = original;
release();
},
};
}
-354
View File
@@ -1,354 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
createCyberSonarGpu,
sonarVertexSource,
CYBER_SONAR_CESIUM_VERSION,
isCyberSonarCommandVisible,
syncCyberSonarCommand,
} from './cyberSonarGpu.js';
test('stable commands reuse uniforms and derived pipelines while all native fields remain live', () => {
const native = new Cesium.DrawCommand({
count: 6,
uniformMap: { value: () => 1 },
});
const record = {},
program = {},
uniforms = { u_gevSonar: () => 42 };
const derived = syncCyberSonarCommand(native, record, program, uniforms, 0);
const map = derived.uniformMap;
derived.dirty = false;
derived.lastDirtyTime = 7;
assert.equal(native.dirty, true);
assert.equal(
syncCyberSonarCommand(native, record, program, uniforms, 1),
derived,
);
assert.equal(
derived.dirty,
false,
'stale native dirty flag must not rebuild pipelines',
);
assert.equal(derived.lastDirtyTime, 7);
assert.equal(derived.uniformMap, map);
assert.equal(map.u_gevSonarLabelBackground(), 1);
for (const [key, value] of Object.entries({
count: 12,
offset: 2,
instanceCount: 3,
pickId: 'pick',
pass: Cesium.Pass.TRANSLUCENT,
cull: false,
occlude: false,
castShadows: true,
receiveShadows: true,
pickOnly: true,
renderState: {},
vertexArray: {},
modelMatrix: Cesium.Matrix4.IDENTITY,
framebuffer: {},
})) {
derived.dirty = false;
native[key] = value;
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(derived[key], value, key);
assert.equal(derived.dirty, true, key);
}
native.uniformMap.value = () => 2;
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(map.value(), 2);
native.uniformMap = { replacement: () => 3 };
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(map.value, undefined);
assert.equal(map.replacement(), 3);
assert.equal(map.u_gevSonar(), 42);
const nextProgram = {};
syncCyberSonarCommand(native, record, nextProgram, uniforms, 0);
assert.equal(derived.shaderProgram, nextProgram);
assert.equal(native.shaderProgram, undefined);
});
test('GPU shader transform is isolated, settings-driven, and precedes native fragment classification', () => {
assert.equal(
Cesium.VERSION,
CYBER_SONAR_CESIUM_VERSION,
'engine upgrades require GPU revalidation',
);
for (const [kind, attr, low] of [
['point', 'positionHighAndSize', 'positionLowAndOutline'],
['billboard', 'positionHighAndScale', 'positionLowAndRotation'],
]) {
const source = new Cesium.ShaderSource({
defines: ['SDF'],
sources: [
`in vec4 ${attr}; in vec4 ${low}; out vec4 v_color; void main() { v_color=vec4(1.); }`,
],
});
const original = source.sources[0];
const next = sonarVertexSource(source, kind);
assert.equal(source.sources[0], original);
assert.notEqual(next, source);
assert.deepEqual(next.defines, ['SDF']);
assert.match(next.sources[0], /void gev_sonar_main/);
assert.match(next.sources[1], /v_color.a \*= factor/);
assert.match(next.sources[1], /u_gevSonarSector/);
assert.match(next.sources[1], /floorValue \+ \(1.0 - floorValue\) \* 0.46/);
assert.ok(
next.sources[1].includes(
`czm_translateRelativeToEye(${attr}.xyz, ${low}.xyz)`,
),
);
assert.match(next.sources[1], /anchor.xy \/ anchor.w/);
assert.doesNotMatch(next.sources[1], /gl_Position\s*[=\/]/);
}
assert.equal(
sonarVertexSource(
new Cesium.ShaderSource({ sources: ['void main() {}'] }),
'point',
),
null,
);
});
test('render demand follows batch bounds, including horizon culling, without far-plane rejection', () => {
const planes = Array.from(
{ length: 6 },
(_, i) => new Cesium.Cartesian4(1, 0, 0, i),
);
const frame = {
cullingVolume: { planes },
mode: Cesium.SceneMode.SCENE3D,
occluder: {},
};
let intersections = 0;
let occluded = false;
const command = {
cull: true,
occlude: true,
boundingVolume: {
intersectPlane(plane) {
intersections++;
return plane.distance === 5
? Cesium.Intersect.OUTSIDE
: Cesium.Intersect.INSIDE;
},
isOccluded() {
return occluded;
},
},
};
assert.equal(isCyberSonarCommandVisible(command, frame), true);
assert.equal(intersections, 5);
occluded = true;
assert.equal(isCyberSonarCommandVisible(command, frame), false);
frame.mode = Cesium.SceneMode.SCENE2D;
assert.equal(isCyberSonarCommandVisible(command, frame), true);
command.boundingVolume.intersectPlane = () => Cesium.Intersect.OUTSIDE;
assert.equal(isCyberSonarCommandVisible(command, frame), false);
command.cull = false;
assert.equal(isCyberSonarCommandVisible(command, frame), true);
assert.equal(isCyberSonarCommandVisible({}, frame), true);
});
test('adapter never walks contacts, touches other scenes, or transforms pick-only passes', () => {
let calls = 0;
const original = function (fs) {
assert.equal(this, root);
calls++;
fs.commandList.push({ owner: {}, id: 'terrain' });
};
const root = { update: original };
const other = { update: original };
const adapter = createCyberSonarGpu({ primitives: root }, () => ({
enabled: false,
}));
const frame = { commandList: [], passes: { render: true, pick: false } };
root.update(frame);
assert.equal(calls, 1);
assert.equal(frame.commandList[0].id, 'terrain');
assert.equal(other.update, original);
root.update({ commandList: [], passes: { render: false, pick: true } });
assert.equal(calls, 2);
adapter.destroy();
adapter.destroy();
assert.equal(root.update, original);
});
test('unknown native shaders fail closed without losing native commands', () => {
const points = new Cesium.PointPrimitiveCollection();
const command = {
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
};
const root = {
update(fs) {
fs.commandList.push(command);
},
};
const adapter = createCyberSonarGpu(
{ primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 },
() => ({
enabled: true,
active: true,
angle: 0,
range: 100,
opacity: 84,
sector: 24,
}),
);
const frame = { commandList: [], passes: { render: true } };
root.update(frame);
assert.equal(frame.commandList[0], command);
assert.equal(adapter.stats.supported, false);
assert.match(adapter.stats.error, /Unsupported native contact shader/);
assert.equal(adapter.stats.programs, 0);
adapter.destroy();
points.destroy();
});
test('program swaps, layer removal and late shader failure release only adapter resources', () => {
const points = new Cesium.PointPrimitiveCollection();
const source = () => ({
vertexShaderSource: new Cesium.ShaderSource({
sources: [
'in vec4 positionHighAndSize; in vec4 positionLowAndOutline; out vec4 v_color; void main() {}',
],
}),
vertexAttributes: {},
fragmentShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
});
const native = new Cesium.DrawCommand({
owner: points,
uniformMap: {},
shaderProgram: source(),
cull: false,
vertexArray: { generation: 1 },
pickId: 'native-pick',
});
const unknown = new Cesium.DrawCommand({
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
});
let nativeCommands = [native];
let enabled = true;
const root = {
update(frame) {
frame.commandList.push(...nativeCommands);
},
};
const fromCache = Cesium.ShaderProgram.fromCache;
const created = [];
Cesium.ShaderProgram.fromCache = () => {
const program = {
allUniforms: {},
destroyed: false,
isDestroyed() {
return this.destroyed;
},
destroy() {
assert.equal(this.destroyed, false);
this.destroyed = true;
},
};
created.push(program);
return program;
};
const adapter = createCyberSonarGpu(
{ primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 },
() => ({
enabled,
active: true,
angle: 0,
range: 100,
opacity: 84,
sector: 24,
}),
);
const draw = () => {
const frame = { commandList: [], passes: { render: true } };
root.update(frame);
return frame.commandList;
};
try {
const first = draw()[0];
assert.notEqual(first, native);
first.dirty = false;
assert.equal(draw()[0], first);
assert.equal(first.dirty, false);
assert.equal(created.length, 1, 'stable draws reuse the program');
const buffer = { generation: 2 };
native.vertexArray = buffer;
native.shaderProgram = source();
const swapped = draw()[0];
assert.equal(swapped, first);
assert.equal(swapped.vertexArray, buffer);
assert.equal(swapped.pickId, 'native-pick');
assert.equal(swapped.shaderProgram, created[1]);
assert.equal(created[0].destroyed, true);
assert.equal(adapter.stats.programs, 1);
nativeCommands = [];
draw();
assert.equal(created[1].destroyed, true);
assert.equal(
adapter.stats.programs,
0,
'disabled layers retain no adapter program',
);
nativeCommands = [native];
draw();
enabled = false;
assert.equal(draw()[0], native);
assert.equal(
created[2].destroyed,
true,
'theme/cockpit exit releases the derived program',
);
enabled = true;
nativeCommands = [native, unknown];
assert.deepEqual(
draw(),
nativeCommands,
'a later failure rolls back earlier replacements in the same slice',
);
assert.equal(created[3].destroyed, true);
assert.equal(adapter.stats.supported, false);
assert.equal(adapter.stats.programs, 0);
assert.equal(adapter.stats.commands, 0);
assert.equal(adapter.stats.visibleCommands, 0);
assert.deepEqual(draw(), nativeCommands);
assert.equal(
created.length,
4,
'unsupported draws do not retry compilation',
);
} finally {
adapter.destroy();
Cesium.ShaderProgram.fromCache = fromCache;
points.destroy();
}
});
test('disposal does not overwrite a successor update owner', () => {
const root = { update() {} };
const adapter = createCyberSonarGpu({ primitives: root }, () => ({
enabled: false,
}));
const successor = () => {};
root.update = successor;
adapter.destroy();
assert.equal(root.update, successor);
});
+120 -190
View File
@@ -1,211 +1,141 @@
import * as Cesium from 'cesium';
import { createCyberSonarGpu } from './cyberSonarGpu.js';
/**
* The Cyber contact sweep on the map's markers, through the renderer's
* `effects.screenModulation` (`src/render/contract/effects.d.ts`). This
* keeps the sweep's clock and settings; the renderer shades the markers.
*
* Each tick, before the renderer decides whether to draw: a change of the
* theme, the sweep, its settings or the map's size sets the sector at once;
* while sweeping, the sector moves to the current angle on every tick that
* draws anyway, and at least every `CYBER_SONAR_RENDER_INTERVAL_MS` (which
* then asks for a frame). Out of the theme the sector is cleared.
*
* A renderer without the capability, or one that does not list the pass
* once a sector is set, leaves markers as they are: the document's
* `cyberSonarGpu` says `unsupported`, so the HUD overlays skip their own
* sweep too, and the sonar status says so.
*
* The frame and effects ports are looked up once, when the scene is made:
* bind the renderer to the viewer before creating it.
*/
import {
applyCyberSonarPrimitive,
createCyberSonarSampler,
isCyberContactThemeActive,
isCyberContactSonarActive,
CYBER_SONAR_RENDER_INTERVAL_MS,
cyberSonarSector,
isCyberMapThemeActive,
isCyberSonarActive,
readCyberSonarSettings,
cyberSonarAngleDeg,
syncCyberSonarAnimation,
CYBER_SONAR_RENDER_INTERVAL_MS,
} from './cyberSonar.js';
import { canvasOf, findEffects, findFrame } from './render/rendererOf.js';
const alive = (value) => value && !value.isDestroyed?.();
const diagnostics = new WeakMap();
export const getCyberSonarSceneDiagnostics = (viewer) => ({
...diagnostics.get(viewer),
});
const UNSUPPORTED_MESSAGE =
'Contact GPU unavailable. Native contacts remain visible.';
export function visitCyberSonarModels(primitive, visit, visible = true) {
if (!alive(primitive)) return;
visible = visible && primitive.show !== false;
if (primitive instanceof Cesium.PrimitiveCollection) {
for (let i = 0; i < primitive.length; i++)
visitCyberSonarModels(primitive.get(i), visit, visible);
} else if (primitive instanceof Cesium.Model) {
visit(primitive, primitive, 'model', visible && primitive.ready);
}
}
/** Native dots, icons and glyphs use GPU draw-command treatment. Models retain
* their existing reversible CPU color treatment without walking native records.
/**
* @param {object} viewer The scene object the renderer is bound to.
* @param {{subscribe?: Function}} [manager] Layer visibility changes ask
* for a frame, so markers shown or hidden draw with the sweep.
* @returns {() => void} Clears the sector and lets go.
*/
export function createCyberSonarScene(viewer, manager) {
const scene = viewer?.scene;
if (
!scene?.postUpdate?.addEventListener ||
!scene?.preRender?.addEventListener
)
return () => {};
const tracked = new Map();
const matrix = new Cesium.Matrix4();
const position = new Cesium.Cartesian3();
let epoch = 0,
timer = null,
disposed = false;
let sampler, width, height, active, count;
const stats = { contacts: 0, updateMs: 0, frames: 0 };
const root = globalThis.document?.documentElement;
const gpu = createCyberSonarGpu(scene, () => ({
...readCyberSonarSettings(),
enabled: isCyberContactThemeActive(),
active: isCyberContactSonarActive(),
angle: cyberSonarAngleDeg(performance.now()),
}));
stats.gpu = gpu.stats;
let gpuSupported = gpu.stats.supported;
diagnostics.set(viewer, stats);
const restore = (visual, state) => {
if (!alive(state.owner)) return;
for (const key of state.keys)
applyCyberSonarPrimitive(visual, 1, false, undefined, key);
};
const visit = (visual, owner, kind, visible) => {
let state = tracked.get(visual);
if (!visible) {
if (state) {
restore(visual, state);
tracked.delete(visual);
}
return;
}
let p = visual.position;
if (kind === 'model')
p = Cesium.Matrix4.getTranslation(visual.modelMatrix, position);
else if (
p &&
owner.modelMatrix &&
!Cesium.Matrix4.equals(owner.modelMatrix, Cesium.Matrix4.IDENTITY)
)
p = Cesium.Matrix4.multiplyByPoint(owner.modelMatrix, p, position);
if (!p) return;
const w = matrix[3] * p.x + matrix[7] * p.y + matrix[11] * p.z + matrix[15];
const x =
(matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12]) / w;
const y =
(matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13]) / w;
if (w <= 0 || Math.abs(x) > 1.1 || Math.abs(y) > 1.1) return;
if (!state) {
state = {
owner,
keys:
kind === 'label'
? ['fillColor', 'outlineColor', 'backgroundColor']
: kind === 'marker' && visual.outlineColor
? ['color', 'outlineColor']
: ['color'],
epoch,
};
tracked.set(visual, state);
}
state.epoch = epoch;
const factor = active
? sampler.at((x + 1) * width * 0.5, (1 - y) * height * 0.5)
: sampler.neutral;
for (const key of state.keys) {
if (key === 'outlineColor' && visual.outlineWidth === 0) continue;
if (key === 'backgroundColor' && !visual.showBackground) continue;
applyCyberSonarPrimitive(
visual,
kind === 'label' ? sampler.label(factor) : factor,
true,
sampler,
key,
kind === 'model',
);
}
count++;
};
const update = () => {
if (disposed) return;
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
if (!isCyberContactThemeActive()) {
for (const [visual, state] of tracked) restore(visual, state);
tracked.clear();
stats.contacts = 0;
stats.updateMs = 0;
return;
}
const started = performance.now();
width = scene.canvas.clientWidth;
height = scene.canvas.clientHeight;
sampler = createCyberSonarSampler(width, height, started);
active = isCyberContactSonarActive();
Cesium.Matrix4.multiply(
scene.camera.frustum.projectionMatrix,
scene.camera.viewMatrix,
matrix,
);
epoch++;
count = 0;
visitCyberSonarModels(scene.primitives, visit);
for (const [visual, state] of tracked)
if (state.epoch !== epoch) {
restore(visual, state);
tracked.delete(visual);
}
stats.contacts = count;
stats.updateMs = performance.now() - started;
stats.frames++;
// No contacts, no scanner-owned render demand. In continuous scenes the
// next rendered frame cancels this timer; parked scenes refresh at fleet
// cadence. Idle update-only ticks must not continually postpone the timer.
};
let removeRender;
// Aircraft fleet writers run in preRender, while tracked models and entity
// visualizers update earlier. Compose AFTER all those owners and BEFORE
// Cesium uploads primitive attributes for this draw. Requeue at postUpdate
// so writers installed later (enable/re-enable/track) cannot overwrite sonar.
// This only reorders one callback; the contact walk runs once per actual draw.
const removeUpdate = scene.postUpdate.addEventListener(() => {
if (isCyberSonarActive()) syncCyberSonarAnimation();
const supportChanged = gpuSupported !== gpu.stats.supported;
gpuSupported = gpu.stats.supported;
const support = gpu.stats.supported ? 'supported' : 'unsupported';
const frame = findFrame(viewer);
if (!frame) return () => {};
const effects = findEffects(viewer);
const doc = globalThis.document;
const root = doc?.documentElement;
let failed = typeof effects?.screenModulation !== 'function';
let current = null;
let key = null;
let lastSetAt = Number.NEGATIVE_INFINITY;
let disposed = false;
const publish = () => {
const support = failed ? 'unsupported' : 'supported';
if (root?.dataset && root.dataset.cyberSonarGpu !== support)
root.dataset.cyberSonarGpu = support;
// Shader setup runs after preRender's model tint. If it fails while the
// scene is parked (including Sonar OFF/reduced motion), draw once more so
// the now-unsupported contact path restores models before becoming idle.
if (supportChanged) scene.requestRender();
const status = globalThis.document?.getElementById?.('cyber-sonar-status');
const message = gpu.stats.supported
? ''
: 'Contact GPU unavailable. Native contacts remain visible.';
const status = doc?.getElementById?.('cyber-sonar-status');
const message = failed ? UNSUPPORTED_MESSAGE : '';
if (status && status.textContent !== message) status.textContent = message;
removeRender?.();
removeRender = scene.preRender.addEventListener(update);
});
const removePostRender = scene.postRender?.addEventListener(() => {
if (timer !== null) clearTimeout(timer);
timer = null;
if (isCyberContactSonarActive() && (count || gpu.stats.visibleCommands))
timer = setTimeout(() => {
timer = null;
if (!disposed && isCyberContactSonarActive()) scene.requestRender();
}, CYBER_SONAR_RENDER_INTERVAL_MS);
};
/** The renderer cannot draw the pass: markers stay as they are. */
const fail = () => {
if (failed) return;
failed = true;
const had = current;
current = null;
key = null;
if (had) effects.screenModulation(null);
publish();
};
const set = (sector, at) => {
const had = current;
// Before the call: its change listeners read `current`.
current = sector;
lastSetAt = at;
effects.screenModulation(sector);
// A first sector set but not listed is unsupported; a pass that stops
// later is caught by the change listener.
if (
sector &&
!had &&
!effects.diagnostics().passes.includes('screenModulation')
)
fail();
};
const offTick = frame.on('preUpdate', (t) => {
if (disposed) return;
// The HUD's own sweep keeps its clock whether or not markers are shaded.
const active = isCyberSonarActive();
if (active) syncCyberSonarAnimation();
if (failed) return;
const theme = isCyberMapThemeActive();
const sweeping = theme && active;
if (!theme) {
if (current) set(null, lastSetAt);
key = null;
return;
}
const canvas = canvasOf(viewer);
// The sector is in CSS pixels.
const width = canvas?.clientWidth ?? 0;
const height = canvas?.clientHeight ?? 0;
const settings = readCyberSonarSettings(root);
const next = `${sweeping}|${settings.range}|${settings.opacity}|${settings.sector}|${width}|${height}`;
const now = performance.now();
if (
next === key &&
!(
sweeping &&
(now - lastSetAt >= CYBER_SONAR_RENDER_INTERVAL_MS || t.rendering)
)
)
return;
key = next;
set(cyberSonarSector(width, height, now, { sweeping, root }), now);
});
const offChange = failed
? null
: effects.on('change', (diagnostics) => {
if (current && !diagnostics.passes.includes('screenModulation')) fail();
});
const unsubscribe = manager?.subscribe?.((change) => {
if (change.type !== 'visibility') return;
scene.requestRender();
if (change.type === 'visibility') frame.requestRender('cyber-sonar');
});
publish();
return () => {
if (disposed) return;
disposed = true;
removeUpdate();
removeRender?.();
removePostRender?.();
gpu.destroy();
if (root?.dataset) delete root.dataset.cyberSonarGpu;
offTick();
offChange?.();
unsubscribe?.();
if (timer !== null) clearTimeout(timer);
for (const [visual, state] of tracked) restore(visual, state);
tracked.clear();
diagnostics.delete(viewer);
const had = current;
current = null;
if (had) effects.screenModulation(null);
if (root?.dataset) delete root.dataset.cyberSonarGpu;
};
}
+260 -240
View File
@@ -1,19 +1,16 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
CYBER_SONAR_RENDER_INTERVAL_MS,
applyCyberSonarSettings,
createCyberSonarSampler,
cyberSonarIntensityAtScreenPoint,
applyCyberSonarPrimitive,
applyCyberSonarSettings,
cyberSonarSector,
isCyberContactSonarActive,
isCyberSonarActive,
} from './cyberSonar.js';
import {
createCyberSonarScene,
visitCyberSonarModels,
getCyberSonarSceneDiagnostics,
} from './cyberSonarScene.js';
import { createCyberSonarScene } from './cyberSonarScene.js';
import { bindRenderer } from './render/rendererOf.js';
test('frame sampler matches reference without per-contact settings access', () => {
let reads = 0;
@@ -47,44 +44,7 @@ test('frame sampler matches reference without per-contact settings access', () =
);
});
test('model walk never enumerates native contact or EntityCluster records', () => {
const root = new Cesium.PrimitiveCollection();
const points = root.add(new Cesium.PointPrimitiveCollection());
points.add();
points.get = () => {
throw new Error('must not enumerate contacts');
};
const cluster = root.add(new Cesium.EntityCluster());
Object.defineProperty(cluster, '_billboardCollection', {
get() {
throw new Error('must not access cluster internals');
},
configurable: true,
});
const seen = [];
visitCyberSonarModels(root, (...v) => seen.push(v));
assert.equal(seen.length, 0);
delete cluster._billboardCollection;
root.destroy();
});
test('models retain render-pass alpha and owner refresh survives teardown', () => {
const frame = createCyberSonarSampler(1000, 800, 0);
const model = { color: new Cesium.Color(1, 0.5, 0.2, 1) };
applyCyberSonarPrimitive(model, 0.5, true, frame, 'color', true);
assert.equal(model.color.alpha, 1);
assert.ok(model.color.red < 1);
const owner = new Cesium.Color(0.2, 0.3, 0.4, 0.7);
model.color = owner;
applyCyberSonarPrimitive(model, 1, false);
assert.equal(model.color, owner);
const unset = {};
applyCyberSonarPrimitive(unset, 0.5, true, frame, 'color', true);
applyCyberSonarPrimitive(unset, 1, false);
assert.equal(unset.color, undefined);
});
test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail closed', () => {
test('removed CSS mode cannot disable GPU contacts; unsupported renderers fail closed', () => {
const root = { dataset: { uiTheme: 'cyber' }, style: { setProperty() {} } };
const options = {
root,
@@ -106,209 +66,269 @@ test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail cl
assert.equal(isCyberContactSonarActive(options), false);
});
test('native owner colors remain untouched and scene teardown releases listeners', () => {
const previous = globalThis.document;
test('the sector is the sweep the HUD shows, in CSS pixels and radians', () => {
const root = {
dataset: {
cyberSonarOpacity: '62',
cyberSonarSector: '40',
cyberSonarRange: '110',
},
};
const s = cyberSonarSector(1000, 800, 1300, { root });
assert.deepEqual(s.center, { x: 500, y: 400 });
assert.ok(Math.abs(s.angle - Math.PI / 2) < 1e-9, 'a quarter period');
assert.ok(Math.abs(s.width - (40 * Math.PI) / 180) < 1e-12);
assert.ok(Math.abs(s.radius - 440) < 1e-9);
assert.equal(s.floor, 0.62);
assert.equal(s.strength, 0.72);
assert.equal(s.color, '#ffd6d6');
const rest = cyberSonarSector(1000, 800, 1300, { root, sweeping: false });
assert.equal(rest.radius, 0);
assert.ok(Math.abs(rest.floor - (0.62 + 0.38 * 0.46)) < 1e-12);
});
/**
* A document with the Cyber HUD shown, and a renderer fake bound to a
* viewer: its frame's preUpdate is ticked by hand and its effects record
* each sector.
*/
function fixture({ modulation = true, lists = true } = {}) {
const previous = {
document: globalThis.document,
matchMedia: globalThis.matchMedia,
};
const root = { dataset: { uiTheme: 'cyber', cyberSonar: 'on' } };
let cockpit = false;
const status = { textContent: '' };
const state = { cockpit: false, reducedMotion: false };
globalThis.document = {
documentElement: root,
body: { classList: { contains: () => cockpit } },
getElementById: () => ({ classList: { contains: () => true } }),
body: { classList: { contains: () => state.cockpit } },
getElementById: (id) =>
id === 'cyber-sonar-status'
? status
: { classList: { contains: () => true } },
};
const primitives = new Cesium.PrimitiveCollection();
const points = primitives.add(new Cesium.PointPrimitiveCollection());
const point = points.add({ color: new Cesium.Color(0.3, 0.7, 0.5, 0.8) });
const original = primitives.update;
const scene = {
primitives,
postUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
canvas: { clientWidth: 1000, clientHeight: 800 },
camera: {
frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY },
viewMatrix: Cesium.Matrix4.IDENTITY,
globalThis.matchMedia = () => ({ matches: state.reducedMotion });
const ticks = new Set();
const changes = new Set();
const sets = [];
const requests = [];
let drawing = null;
const effects = {
diagnostics: () => ({
style: null,
passes: drawing && lists ? ['screenModulation'] : [],
}),
on(event, cb) {
changes.add(cb);
return () => changes.delete(cb);
},
requestRender() {},
};
const viewer = { scene };
const dispose = createCyberSonarScene(viewer);
try {
for (const enabled of ['on', 'off', 'on']) {
root.dataset.cyberSonar = enabled;
for (const opacity of [35, 84, 100]) {
root.dataset.cyberSonarOpacity = String(opacity);
point.color = new Cesium.Color(0.6, 0.4, 0.2, 0.7);
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
assert.equal(point.color.alpha, 0.7);
assert.equal(point.color.red, 0.6);
}
}
const previousTimeout = globalThis.setTimeout;
const previousClear = globalThis.clearTimeout;
let timers = 0;
globalThis.setTimeout = () => {
timers++;
return 1;
if (modulation)
effects.screenModulation = (sector) => {
const was = effects.diagnostics().passes.length;
drawing = sector;
sets.push(sector);
if (effects.diagnostics().passes.length !== was)
for (const cb of [...changes]) cb(effects.diagnostics());
};
globalThis.clearTimeout = () => {};
try {
const gpu = getCyberSonarSceneDiagnostics(viewer).gpu;
gpu.commands = 6;
gpu.visibleCommands = 0;
scene.postRender.raiseEvent();
assert.equal(timers, 0, 'culled batches must not schedule a sonar draw');
gpu.visibleCommands = 1;
scene.postRender.raiseEvent();
assert.equal(timers, 1, 'a visible batch keeps the sweep moving');
root.dataset.cyberSonar = 'off';
scene.postRender.raiseEvent();
assert.equal(timers, 1, 'OFF does not schedule contact draws');
} finally {
globalThis.setTimeout = previousTimeout;
globalThis.clearTimeout = previousClear;
}
cockpit = true;
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
root.dataset.uiTheme = 'tactical';
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
const canvas = { clientWidth: 1000, clientHeight: 800 };
const viewer = {};
const unbind = bindRenderer(viewer, {
canvas,
effects,
frame: {
on(phase, cb) {
assert.equal(phase, 'preUpdate');
ticks.add(cb);
return () => ticks.delete(cb);
},
requestRender: (reason) => requests.push(reason),
},
});
return {
root,
status,
state,
sets,
requests,
canvas,
viewer,
ticks,
changes,
effects,
tick(rendering = false) {
for (const cb of [...ticks]) cb({ rendering });
},
restore() {
unbind();
globalThis.document = previous.document;
globalThis.matchMedia = previous.matchMedia;
},
};
}
test('a renderer without the capability leaves markers alone and says so', () => {
const f = fixture({ modulation: false });
try {
const dispose = createCyberSonarScene(f.viewer);
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
assert.match(f.status.textContent, /Native contacts remain visible/);
f.tick(true);
assert.equal(f.changes.size, 0);
dispose();
dispose();
assert.equal(primitives.update, original);
assert.equal(scene.postUpdate.numberOfListeners, 0);
assert.equal(scene.preRender.numberOfListeners, 0);
assert.equal(scene.postRender.numberOfListeners, 0);
assert.equal(root.dataset.cyberSonarGpu, undefined);
assert.equal(f.ticks.size, 0);
assert.equal(f.root.dataset.cyberSonarGpu, undefined);
} finally {
dispose();
primitives.destroy();
globalThis.document = previous;
f.restore();
}
});
for (const reducedMotion of [false, true]) {
test(`shader failure requests one parked restoration draw with ${reducedMotion ? 'reduced motion' : 'Sonar OFF'}`, () => {
const previousDocument = globalThis.document;
const previousMatchMedia = globalThis.matchMedia;
const previousTimeout = globalThis.setTimeout;
const previousClear = globalThis.clearTimeout;
const root = {
dataset: { uiTheme: 'cyber', cyberSonar: reducedMotion ? 'on' : 'off' },
};
const status = { textContent: '' };
globalThis.document = {
documentElement: root,
body: { classList: { contains: () => false } },
getElementById: (id) =>
id === 'cyber-sonar-status'
? status
: { classList: { contains: () => true } },
};
globalThis.matchMedia = () => ({ matches: reducedMotion });
let scheduled = 0;
globalThis.setTimeout = () => {
scheduled++;
return 1;
};
globalThis.clearTimeout = () => {};
// A model-shaped fixture exercises the actual scene walk without loading a
// glTF or allocating a WebGL context. Rendering remains the browser gate.
const nativeColor = new Cesium.Color(0.2, 0.4, 0.8, 1);
const model = Object.create(Cesium.Model.prototype, {
ready: { value: true },
show: { value: true },
color: { value: nativeColor.clone(), writable: true },
modelMatrix: { value: Cesium.Matrix4.IDENTITY },
});
const primitives = new Cesium.PrimitiveCollection({
destroyPrimitives: false,
});
primitives.add(model);
const points = new Cesium.PointPrimitiveCollection();
const nativeCommand = {
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
};
primitives.update = (frame) => frame.commandList.push(nativeCommand);
let requests = 0;
const scene = {
primitives,
postUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
canvas: { clientWidth: 1000, clientHeight: 800 },
drawingBufferWidth: 1000,
drawingBufferHeight: 800,
camera: {
frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY },
viewMatrix: Cesium.Matrix4.IDENTITY,
},
requestRender() {
requests++;
},
};
const viewer = { scene };
const dispose = createCyberSonarScene(viewer);
try {
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
assert.notDeepEqual(
model.color,
nativeColor,
'Cyber neutral treatment precedes shader compilation',
);
const frame = { commandList: [], passes: { render: true } };
primitives.update(frame);
assert.equal(getCyberSonarSceneDiagnostics(viewer).gpu.supported, false);
assert.equal(frame.commandList[0], nativeCommand);
scene.postRender.raiseEvent();
assert.equal(
scheduled,
0,
'inactive sweep has no timer to perform recovery',
);
scene.postUpdate.raiseEvent();
assert.equal(root.dataset.cyberSonarGpu, 'unsupported');
assert.match(status.textContent, /Native contacts remain visible/);
assert.equal(
requests,
1,
'support loss explicitly wakes the parked scene',
);
scene.preRender.raiseEvent();
assert.deepEqual(
model.color,
nativeColor,
'the requested draw restores native model color',
);
assert.equal(getCyberSonarSceneDiagnostics(viewer).contacts, 0);
scene.postRender.raiseEvent();
for (let i = 0; i < 3; i++) scene.postUpdate.raiseEvent();
assert.equal(
requests,
1,
'unsupported idle ticks do not create a render loop',
);
assert.equal(scheduled, 0);
dispose();
scene.postUpdate.raiseEvent();
assert.equal(requests, 1, 'disposed callbacks cannot wake the scene');
} finally {
dispose();
points.destroy();
primitives.destroy();
globalThis.document = previousDocument;
globalThis.matchMedia = previousMatchMedia;
globalThis.setTimeout = previousTimeout;
globalThis.clearTimeout = previousClear;
}
});
}
test('the HUD sweep keeps its clock while markers cannot be shaded', () => {
const f = fixture({ modulation: false });
const animation = {
animationName: 'cyber-sonar-sweep',
playState: 'running',
startTime: 500,
effect: { updateTiming() {} },
};
f.root.querySelector = (selector) =>
selector === '.hud-sonar'
? { isConnected: true, getAnimations: () => [animation] }
: null;
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick(false);
assert.equal(animation.startTime, 0);
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
dispose();
} finally {
f.restore();
}
});
test('the sweep sets its sector on drawing ticks and at the cadence, and changes at once', () => {
const f = fixture();
const now = performance.now;
let clock = 1000;
performance.now = () => clock;
try {
const dispose = createCyberSonarScene(f.viewer);
assert.equal(f.root.dataset.cyberSonarGpu, 'supported');
assert.equal(f.status.textContent, '');
f.tick();
assert.equal(f.sets.length, 1, 'the theme sets a sector');
assert.deepEqual(f.sets[0], cyberSonarSector(1000, 800, 1000));
clock += 10;
f.tick(false);
assert.equal(f.sets.length, 1, 'an idle tick before the cadence sets none');
f.tick(true);
assert.equal(f.sets.length, 2, 'a tick that draws moves the angle');
assert.deepEqual(f.sets[1], cyberSonarSector(1000, 800, 1010));
clock += CYBER_SONAR_RENDER_INTERVAL_MS;
f.tick(false);
assert.equal(f.sets.length, 3, 'the cadence moves it on an idle tick');
f.canvas.clientWidth = 600;
f.tick(false);
assert.equal(f.sets.length, 4, 'a resize sets it at once');
assert.deepEqual(f.sets[3].center, { x: 300, y: 400 });
f.root.dataset.cyberSonar = 'off';
f.tick(false);
assert.equal(f.sets[4].radius, 0, 'Sonar OFF rests every contact');
clock += 1000;
f.tick(true);
f.tick(false);
assert.equal(f.sets.length, 5, 'at rest only changes set it');
f.root.dataset.cyberSonarOpacity = '50';
f.tick(false);
assert.equal(f.sets.length, 6);
assert.equal(f.sets[5].floor, 0.5 + 0.5 * 0.46);
f.state.cockpit = true;
f.tick(false);
assert.equal(f.sets[6], null, 'out of the map theme it clears');
f.tick(true);
assert.equal(f.sets.length, 7, 'cleared once');
f.state.cockpit = false;
f.root.dataset.cyberSonar = 'on';
f.state.reducedMotion = true;
f.tick(false);
assert.equal(f.sets[7].radius, 0, 'reduced motion rests the sweep');
f.state.reducedMotion = false;
f.root.dataset.uiTheme = 'tactical';
f.tick(false);
assert.equal(f.sets[8], null, 'another HUD style clears it');
f.tick(true);
assert.equal(f.sets.length, 9);
f.root.dataset.uiTheme = 'cyber';
f.tick(false);
assert.ok(f.sets[9]?.radius > 0, 'back in Cyber it sweeps at once');
assert.deepEqual(f.requests, [], 'the scene itself never asks for frames');
dispose();
assert.equal(f.sets[10], null, 'disposal clears it');
assert.equal(f.ticks.size, 0);
assert.equal(f.changes.size, 0);
assert.equal(f.root.dataset.cyberSonarGpu, undefined);
dispose();
assert.equal(f.sets.length, 11);
} finally {
performance.now = now;
f.restore();
}
});
test('a sector the renderer does not list is unsupported: cleared, and the sweep stops', () => {
const f = fixture({ lists: false });
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick(true);
assert.equal(f.sets.length, 2);
assert.equal(f.sets[1], null, 'cleared again');
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
assert.match(f.status.textContent, /Native contacts remain visible/);
f.tick(true);
assert.equal(f.sets.length, 2, 'never set again');
dispose();
assert.equal(f.sets.length, 2);
} finally {
f.restore();
}
});
test('a pass the renderer stops drawing on its own stops the sweep', () => {
const f = fixture();
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick(true);
assert.equal(f.sets.length, 1);
for (const cb of [...f.changes]) cb({ style: null, passes: [] });
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
assert.equal(f.sets.at(-1), null);
const count = f.sets.length;
f.tick(true);
assert.equal(f.sets.length, count);
dispose();
} finally {
f.restore();
}
});
test('layer visibility changes ask for a frame', () => {
const f = fixture();
let listener = null;
const manager = {
subscribe(cb) {
listener = cb;
return () => (listener = null);
},
};
try {
const dispose = createCyberSonarScene(f.viewer, manager);
listener({ type: 'visibility' });
listener({ type: 'data' });
assert.deepEqual(f.requests, ['cyber-sonar']);
dispose();
assert.equal(listener, null);
} finally {
f.restore();
}
});
+63 -20
View File
@@ -1,8 +1,19 @@
import * as Cesium from 'cesium';
import { TRACKED_ICON_COLOR } from '../layers/military/policy.js';
import { TRACKED_CYAN } from '../layers/flights/policy.js';
import { createRendering as civilRendering } from '../layers/flights/rendering.js';
import { createRendering as militaryRendering } from '../layers/military/rendering.js';
import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js';
import { createIcons as createMilitaryIcons } from '../layers/military/icons.js';
import { createContactIcons } from './aircraftIconLayer.js';
import {
aircraftMotionRegime,
createMotionRegime,
fixEpochMs,
fixPosition,
copyPosition,
historyFix,
julianAt,
} from './aircraftMotionRegime.js';
import { aircraftEmergency } from './aircraftEmergency.js';
// Source-to-voice provenance, status retention/clearing, contact-time contracts,
// and civil/military billboard, Cockpit and model tint regressions.
@@ -138,6 +149,7 @@ test('changed status without contact time retains general contact, including voi
const runner = createGevActionRunner({
viewer: {
clock: { onTick: { addEventListener: () => () => {} } },
canvas: { addEventListener() {}, removeEventListener() {} },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: {
moveEnd: { addEventListener() {} },
@@ -444,7 +456,7 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
const red = rendering._fleetBillboardColor('civil', {
emergency: aircraftEmergency({ squawk: '7700' }),
});
assert.ok(red.red > 0.9 && red.green < 0.5);
assert.ok(red[0] > 0.9 && red[1] < 0.5);
flightState.records.data.set('civil', {
emergency: aircraftEmergency({ squawk: '7700' }),
});
@@ -454,27 +466,25 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
flightState._trackedIcao = 'civil';
assert.equal(
rendering._modelColor('civil'),
factory === civilRendering ? Cesium.Color.CYAN : TRACKED_ICON_COLOR,
factory === civilRendering ? TRACKED_CYAN : TRACKED_ICON_COLOR,
);
flightState._trackedIcao = null;
flightState.records.data.set('civil', { emergency: null });
// An ordinary model draws its mesh's own colours, whatever the billboard's.
assert.equal(rendering._modelColor('civil'), Cesium.Color.WHITE);
assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]);
}
});
test('GERMAN: an existing untracked military billboard repaints each poll without alpha loss', () => {
test('GERMAN: an existing untracked military icon repaints each poll without losing its fade', () => {
const { flightState, rendering } = renderHarness(militaryRendering);
const bb = {
color: rendering._fleetBillboardColor('abc123').withAlpha(0.65),
};
Object.assign(flightState, {
_billboards: new Map([['abc123', bb]]),
_icons: createContactIcons(),
_models: new Map(),
_positionHistory: new Map(),
_cullPositions: new Map(),
_displayCourse: new Map(),
_groundSnap: { forget() {} },
_cockpitContactMode: false,
_cockpitNearContacts: new Set(),
});
const records = new MilitaryFlightRecords({
geoidHeight: () => 0,
@@ -482,18 +492,51 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou
floorAltitudeM: (value) => value,
});
flightState.records = records;
const parts = {
rendering: {
...rendering,
_iconKind: () => 'jet',
_syncModelToClass() {},
},
motion: {
_motionRegime: (history, info, renderTime) =>
aircraftMotionRegime(
history,
info,
renderTime,
{ speed: 'speedMps', track: 'track' },
createMotionRegime(),
),
_displayTimeAt: julianAt,
_fixEpochMs: fixEpochMs,
_fixPosition: fixPosition,
_copyPosition: copyPosition,
_historyFix: historyFix,
_refloorStaleGroundedContacts() {},
_sampleMeshFloor() {},
},
};
const icons = createMilitaryIcons({
flightState,
services: { focus: { focusPassIsNeeded: () => false } },
parts,
});
const row = 'abc123';
flightState._icons.put({
id: row,
pos: { x: 0, y: 0, z: 0 },
meta: { layer: 'military', id: row },
});
// The focus fade the fleet tick composes lives in its own field.
flightState._icons.setFocus(row, 0.65);
const apply = createMilitarySnapshotRenderer({
flightState,
records,
groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null },
meshFloor: { sampleMeshFloorCells() {} },
groundFloor: { warmGroundFloor() {} },
militaryRegistry: { registerMilitaryIcaos() {} },
rendering: {
...rendering,
_syncModelToClass() {},
_applyFleetBillboardPresentation() {},
},
motion: {},
rendering: parts.rendering,
motion: parts.motion,
icons,
tracking: {},
queries: {},
});
@@ -519,7 +562,7 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou
{ observedAtMs: NOW_MS },
);
apply(snapshot, {});
assert.equal(bb.color.green < 0.5, red);
assert.equal(bb.color.alpha, 0.65);
assert.equal(flightState._icons.item(row).color[1] < 0.5, red);
assert.ok(Math.abs(flightState._icons.focus(row) - 0.65) < 1e-6);
}
});
File diff suppressed because it is too large. Load diff
+201
View File
@@ -0,0 +1,201 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
COAST_FLOOR_LOOKAHEAD_MS,
createAircraftIcons,
createContactIcons,
floorCoastArc,
} from './aircraftIconLayer.js';
import { COAST_FLOOR_LIFT_M } from './motionModel.js';
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { createDisplayDelay } from './displayDelay.js';
const WORLD_MS = Date.UTC(2026, 10, 1, 12, 0);
test('following the world clock, contacts draw at the world’s time on the scene clock', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS + 86_400_000 });
const viewer = {};
const { draw } = bindFakeDraw(viewer);
let following = false;
const state = {
_viewer: viewer,
now: () => (following ? WORLD_MS : Date.now()),
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {},
layerId: 'flights',
renderDelaySec: 30,
followsClock: () => following,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
// Live: a poll interval behind real time, on the delayed live clock.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
assert.equal(icons._displayMs(), Date.now() - 30_000);
following = true;
assert.equal(icons._displayMs(), WORLD_MS, 'the world’s time, no delay');
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
icons._disposeIcons();
});
test('as the display delay moves, the renderer’s live clock and the layer’s display time move with it; the world clock ignores it', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const viewer = {};
const { draw } = bindFakeDraw(viewer);
let following = false;
const state = { _viewer: viewer, now: () => Date.now() };
const delay = createDisplayDelay({ floorMs: 30_000, pollMs: 30_000 });
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {},
layerId: 'flights',
displayDelay: delay,
followsClock: () => following,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
// Reports 90 s old every 30 s: the delay heads for about two minutes.
for (let i = 0; i < 20; i++)
delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000);
delay.settle(WORLD_MS);
t.mock.timers.setTime(WORLD_MS + 10_000);
icons._syncMotionClock();
// 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 });
assert.equal(icons._displayMs(), Date.now() - 32_000);
// Following the world clock: no delay, and it is not moved on meanwhile.
following = true;
t.mock.timers.setTime(WORLD_MS + 20_000);
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
assert.equal(icons._displayMs(), Date.now());
assert.equal(delay.currentMs, 32_000);
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 });
icons._disposeIcons();
});
test('a coasting icon is kept above rising ground, as the CPU coast is', () => {
const T0 = WORLD_MS;
let now = T0;
const cosLat = Math.cos((30 * Math.PI) / 180);
const metresEast = (lonDeg) => lonDeg * 111_320 * cosLat;
// A slope rising east from 100 m out, half a metre per metre.
const ground = (_lat, lon) => Math.max(0, (metresEast(lon) - 100) * 0.5);
const fix = { epochMs: T0, position: fromDegrees(0, 30, 100) };
const state = {
now: () => now,
_icons: createContactIcons(),
_positionHistory: new Map([['c', [fix]]]),
records: { data: new Map([['c', {}]]) },
};
const icons = createAircraftIcons({
state,
services: {
focus: { focusPassIsNeeded: () => false },
groundFloor: { cachedGroundFloor: ground },
},
parts: {
motion: {
_displayTimeAt: (ms) => ms,
_fixEpochMs: (f) => f.epochMs,
// Coasting east past its only fix at 100 m/s, for five minutes.
_motionRegime: () => ({
kind: 'fix',
fix,
speed: 100,
heading: 90,
turnRateDps: 0,
minDt: -60,
maxDt: 300,
}),
},
},
layerId: 'flights',
renderDelaySec: 30,
followsClock: () => true,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
state._icons.put(
{
id: 'c',
pos: fix.position,
motion: { kind: 'hold', courseDeg: 90 },
course: 90,
size: [20, 20],
},
{ expiresAt: -Infinity },
);
icons._planIcon('c');
// The fleet pass, every 80 ms for 12 s: the icon never sinks into the
// slope, and over open ground it coasts level.
let lowest = Infinity;
for (now = T0; now <= T0 + 12_000; now += 80) {
icons._replanExpired(now);
const p = icons._iconPosition('c');
const carto = toCartographicRadians(p);
const floor = ground(0, (carto.lon * 180) / Math.PI) + COAST_FLOOR_LIFT_M;
lowest = Math.min(lowest, carto.height - floor);
if (now - T0 <= 2_000)
assert.ok(Math.abs(carto.height - 100) < 0.1, 'level over open ground');
assert.ok(Math.abs(icons._iconCourse('c') - 90) < 1e-6, 'nose east');
}
assert.ok(lowest > -0.05, `at most 5 cm under the floor (${lowest} m)`);
// 1.2 km east, the slope is at 550 m: it rode up the slope.
now = T0 + 12_000;
icons._replanExpired(now);
const end = toCartographicRadians(icons._iconPosition('c'));
const east = metresEast((end.lon * 180) / Math.PI);
assert.ok(Math.abs(east - 1_200) < 5, `1.2 km east (${east} m)`);
assert.ok(end.height > 550, `on the slope (${end.height} m)`);
});
test('a coast over known ground that never rises is planned once', () => {
const fix = { position: fromDegrees(0, 30, 100) };
const arc = {
kind: 'arc',
fix: fix.position,
t0: 0,
minDtS: -60,
maxDtS: 5,
speedMps: 100,
trackDeg: 90,
turnRateDps: 0,
};
assert.deepEqual(
floorCoastArc(arc, 0, () => 0),
{ expiresAt: Infinity },
);
assert.deepEqual(
floorCoastArc(arc, 0, () => null),
{ expiresAt: COAST_FLOOR_LOOKAHEAD_MS },
'unknown ground is read again',
);
assert.equal(
floorCoastArc({ ...arc, fix: fromDegrees(0, 30, 10_000) }, 0, () => 0),
null,
'a cruise above any terrain never reads it',
);
// Stopped at the end of its coast, under ground that rose since.
const held = floorCoastArc(arc, 6_000, () => 200);
assert.equal(held.motion.kind, 'hold');
assert.ok(
Math.abs(toCartographicRadians(held.pos).height - 201.5) < 1e-6,
'held on the ground where the coast stopped',
);
});
+2
View File
@@ -252,6 +252,8 @@ const _b64 = (s) =>
* NEAR the display size lets the browser's SVG AA do the work: crisp AND
* smooth. 64 covers the 40–58 px fleet band with ≤1.6× minification. */
const FLEET_RASTER_PX = 64;
/** Raster size of the default fleet glyph. */
export const FLEET_ICON_PX = FLEET_RASTER_PX;
/** Tracked raster: the tracked billboard is the one SUSTAINED large 2D glyph
* (close-zoom fleet flybys hand off to 3D models). Keep the 192 px texture so
* it stays crisp at its biggest on-screen sizes. */
File diff suppressed because it is too large. Load diff
+391
View File
@@ -0,0 +1,391 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAircraftModels } from './aircraftModelLayer.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { fromDegrees } from '../geo/ellipsoid.js';
const POLICY = {
MODEL_ALT_CEIL_M: 800_000,
MODEL_MAX: 40,
MODEL_MAX_ALL: 350,
COCKPIT_MODEL_MAX: 60,
MODEL_PROX_ADD_M: 150_000,
MODEL_PROX_KEEP_M: 185_000,
MODEL_ALL_ADD_M: 400_000,
MODEL_ALL_KEEP_M: 450_000,
MODEL_MIN_PX: 24,
TRACKED_MODEL_MIN_PX: 48,
TRACKED_MODEL_MAX_PX: 600,
MODEL_HEADING_OFFSET_DEG: 0,
FLEET_DR_INTERVAL_MS: 80,
TRACKED_MODEL_MAX_LOAD_FAILS: 3,
TRACKED_MODEL_RETRY_BACKOFF_MS: 1500,
};
const SPEC = {
url: 'plane.glb',
scale: 1,
bellyM: 3,
nativeRadiusM: 20,
blendAmount: 0.9,
};
/**
* A fleet of airborne contacts at `positions` (icao → ECEF), drawn by a
* models layer over a fake draw port whose fleet set can be told to fail a
* write. The eye sits above them at 30 km.
*/
function fleetFixture(positions) {
const base = fakeDrawPort();
const removes = [];
let failNextUpsert = false;
const draw = {
...base,
models(spec) {
const set = base.models(spec);
return {
...set,
get show() {
return set.show;
},
set show(value) {
set.show = value;
},
id: set.id,
upsert(items) {
if (failNextUpsert && spec.id.includes('-models:')) {
failNextUpsert = false;
throw new Error('simulated write failure');
}
return set.upsert(items);
},
remove(ids) {
removes.push([...ids]);
return set.remove(ids);
},
};
},
};
const eye = fromDegrees(-97.71, 30.21, 30_000);
const viewer = {};
bindRenderer(viewer, {
draw,
camera: {
pose: () => ({
position: eye,
direction: { x: 0, y: 0, z: -1 },
up: { x: 0, y: 1, z: 0 },
right: { x: 1, y: 0, z: 0 },
fovy: Math.PI / 3,
aspectRatio: 1,
height: 30_000,
}),
},
});
const shown = new Map([...positions.keys()].map((id) => [id, true]));
let alphaOf = 1;
let focusOf = 1;
const unseenIds = new Set();
const icons = {
show: true,
setId: 'flights-icons:1',
ids: () => [...positions.keys()],
has: (id) => positions.has(id),
position: (id) => positions.get(id),
course: () => 90,
alpha: () => alphaOf,
focus: () => focusOf,
setShown: (id, value) => shown.set(id, value),
unseen: (id) => unseenIds.has(id),
flush() {},
};
const state = {
_viewer: viewer,
_icons: icons,
_models: new Map(),
_modelSets: null,
_trackedIcao: null,
_trackedModel: null,
_models3dEnabled: true,
_models3dMode: 'proximity',
_cockpitContactMode: false,
_irBoost: false,
_lastFleetTickMs: 0,
_lastModelCapWarnMs: 0,
records: {
data: new Map(
[...positions.keys()].map((id) => [id, { klass: 'airliner' }]),
),
},
};
let now = 1_000_000;
let iconRecedeSyncs = 0;
const parts = {
icons: {
_displayMs: () => now,
_syncImageSwitch() {},
_replanExpired() {},
_focusIcons() {},
_occluder: () => null,
_aboveHorizon: () => true,
_syncRecede() {
iconRecedeSyncs += 1;
},
},
motion: { _displayTimeAt: () => null },
tracking: {
_refreshCockpitNearContacts() {},
_trackedModelRegimeActive: () => false,
},
};
const models = createAircraftModels({
state,
services: {
aircraftPresentation: { isTr3b: () => false },
camera: { trackedModelScaleForPixelCap: ({ baseScale }) => baseScale },
focus: { focusNowMs: () => now, getFocusTarget: () => null },
},
parts,
resolveAsset: (url) => url,
logLabel: 'Test',
setPrefix: 'flights',
policy: POLICY,
modelSpec: () => SPEC,
modelColor: () => ({ red: 1, green: 1, blue: 1, alpha: 1 }),
});
models._createModelSets(viewer);
const fleetId = models._modelSetIds()[0];
return {
models,
state,
draw: base,
fleet: () => base.set(fleetId),
fleetId,
removes,
shown,
failNextUpsert: () => (failNextUpsert = true),
/** How often the icons were told to recede by the tuning as it is now. */
iconRecedeSyncs: () => iconRecedeSyncs,
/** Mark a contact as not there yet at the time drawn, or there again. */
setUnseen(id, value) {
if (value) unseenIds.add(id);
else unseenIds.delete(id);
},
/** The icons' alpha and focus the fleet models take. */
look(alpha, focus) {
alphaOf = alpha;
focusOf = focus;
},
/** One fleet tick, past the tick interval. */
tick() {
now += 1000;
models._fleetTick();
},
};
}
const near = (k) => fromDegrees(-97.71 + k * 0.01, 30.21, 10_000);
const far = (k) => fromDegrees(-90 + k * 0.01, 30.21, 10_000);
test('the fleet tick hands contacts to ready models and back without a gap', () => {
const positions = new Map([
['a1', near(1)],
['a2', near(2)],
]);
const f = fleetFixture(positions);
f.tick();
assert.deepEqual([...f.fleet().items.keys()].sort(), ['a1', 'a2']);
assert.equal(
f.shown.get('a1'),
true,
'icons carry contacts until models load',
);
f.draw.ready(f.fleetId, 'a1');
f.tick();
assert.equal(f.shown.get('a1'), false, 'a ready, placed model takes over');
assert.equal(f.fleet().items.get('a1').show, true);
assert.equal(
f.shown.get('a2'),
true,
'a model still loading leaves its icon',
);
});
test('contacts leaving the model band are released in one write', () => {
const positions = new Map([
['a1', near(1)],
['a2', near(2)],
['a3', near(3)],
]);
const f = fleetFixture(positions);
f.tick();
for (const id of ['a1', 'a2', 'a3']) f.draw.ready(f.fleetId, id);
f.tick();
positions.set('a2', far(2));
positions.set('a3', far(3));
f.removes.length = 0;
f.tick();
assert.deepEqual(
f.removes,
[['a2', 'a3']],
'one remove for every evicted model',
);
assert.deepEqual([...f.fleet().items.keys()], ['a1']);
assert.equal(
f.shown.get('a2'),
true,
'a released model hands back to its icon',
);
assert.equal(f.shown.get('a3'), true);
});
test('a failed fleet write leaves the icons in charge and is sent again', () => {
const positions = new Map([['a1', near(1)]]);
const f = fleetFixture(positions);
f.tick();
f.draw.ready(f.fleetId, 'a1');
const realWarn = console.warn;
console.warn = () => {};
try {
f.failNextUpsert();
f.tick();
} finally {
console.warn = realWarn;
}
assert.equal(f.shown.get('a1'), true, 'the contact keeps its icon');
assert.equal(
f.fleet().items.get('a1').show,
false,
'the set still has the hidden model',
);
assert.equal(f.models._modelOwnsVisual('a1'), false);
f.tick();
assert.equal(
f.fleet().items.get('a1').show,
true,
'the next tick sends it again',
);
assert.equal(f.shown.get('a1'), false);
});
test('a fleet model whose load failed is loaded again after a wait, not before', () => {
const positions = new Map([['a1', near(1)]]);
const f = fleetFixture(positions);
const realNow = Date.now;
let clock = 50_000_000;
Date.now = () => clock;
try {
f.tick();
const writes = f.fleet().writes;
clock += 60_000;
f.tick();
assert.equal(
f.fleet().writes,
writes,
'a model still loading is not rewritten, however long it takes',
);
f.draw.loadFailed(f.fleetId, 'a1');
f.removes.length = 0;
clock += 4_999;
f.tick();
assert.deepEqual(f.removes, [], 'not before the wait');
assert.equal(f.shown.get('a1'), true, 'the icon carries the contact');
clock += 1;
f.tick();
assert.deepEqual(f.removes, [['a1']], 'removed once the wait is over');
assert.ok(f.fleet().items.has('a1'), 'and added again in the same tick');
assert.equal(f.state._models.get('a1').failedAt, 0);
assert.equal(f.state._models.get('a1').ready, false, 'a fresh load');
f.removes.length = 0;
clock += 60_000;
f.tick();
assert.deepEqual(f.removes, [], 'tried again only after another failure');
// A renderer's own retry that loads before the layer's: nothing is due.
f.draw.loadFailed(f.fleetId, 'a1');
f.draw.ready(f.fleetId, 'a1');
clock += 60_000;
f.tick();
assert.deepEqual(f.removes, [], 'a model that loaded is not tried again');
assert.equal(
f.shown.get('a1'),
false,
'the model takes over once it loads',
);
} finally {
Date.now = realNow;
}
});
test('fleet model alpha is worked out once a fleet tick from the camera then, as base × max(floor, focus × haze); the IR boost draws full strength', async () => {
const {
aircraftTreatmentAlpha,
setAircraftRecessionParams,
resetAircraftRecessionParams,
} = await import('./aircraftRecession.js');
const position = near(1);
const f = fleetFixture(new Map([['a1', position]]));
assert.equal(f.fleet().spec.recede ?? null, null, 'the set does not recede');
const eye = fromDegrees(-97.71, 30.21, 30_000);
const expected = (focusFactor) =>
aircraftTreatmentAlpha({
baseAlpha: 0.8,
focusFactor,
cameraDistanceM: Math.hypot(
eye.x - position.x,
eye.y - position.y,
eye.z - position.z,
),
cameraHeightM: 30_000,
});
try {
// Recede from the eye on, so the haze is not 1 here.
setAircraftRecessionParams({ startLimbRatio: 0, alphaFloor: 0.05 });
f.look(0.8, 0.5);
f.tick();
f.draw.ready(f.fleetId, 'a1');
f.tick();
const item = f.fleet().items.get('a1');
assert.equal(item.tint[3], expected(0.5), 'the tint carries it all');
assert.equal(item.focus ?? 1, 1, 'with no focus for the set to compose');
// A frame inside the fleet interval writes nothing, whatever changed.
f.look(0.8, 0.25);
f.models._fleetTick();
assert.equal(f.fleet().items.get('a1').tint[3], item.tint[3]);
f.tick();
assert.equal(
f.fleet().items.get('a1').tint[3],
expected(0.25),
'the next tick takes it',
);
} finally {
resetAircraftRecessionParams();
}
f.state._irBoost = true;
f.models._reloadModelsForIrBoost();
f.tick();
assert.equal(f.fleet().items.get('a1').tint[3], 1, 'boosted: full strength');
});
test('a tuning change reaches the icons on the next frame, icons shown or not', async () => {
const f = fleetFixture(new Map([['a1', near(1)]]));
f.state._icons.show = false;
const before = f.iconRecedeSyncs();
f.models._fleetTick();
assert.ok(f.iconRecedeSyncs() > before, 'the icons are told');
});
test('a contact not there yet at the time drawn has its fleet model hidden, as one beyond the horizon', () => {
const f = fleetFixture(new Map([['a1', near(1)]]));
f.tick();
f.draw.ready(f.fleetId, 'a1');
f.tick();
assert.equal(f.fleet().items.get('a1').show, true, 'drawn while there');
f.setUnseen('a1', true);
f.tick();
assert.equal(f.fleet().items.get('a1').show, false, 'hidden while unseen');
f.setUnseen('a1', false);
f.tick();
f.tick();
assert.equal(f.fleet().items.get('a1').show, true, 'drawn again');
});
+10 -10
View File
@@ -1,5 +1,3 @@
import * as Cesium from 'cesium';
/**
* Lighting options shared by every aircraft 3D model (Flights, Military
* Flights, Local ADS-B).
@@ -16,16 +14,18 @@ export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({
enabled: false,
});
const HIGHLIGHT = Object.freeze({ mode: 'highlight' });
const FLAT = Object.freeze({ mode: 'mix', amount: 1 });
/**
* How an aircraft model's colour meets its mesh. HIGHLIGHT multiplies, so
* white draws the mesh's own colours as built, and the tracked or emergency
* colour tints the mesh without hiding its paint. The IR boost draws the
* model flat white instead (MIX at 1, with its unlit shader).
* How an aircraft model's colour meets its mesh, as a draw item's
* `colorBlend`. `highlight` multiplies, so white draws the mesh's own
* colours as built, and the tracked or emergency colour tints the mesh
* without hiding its paint. The IR boost draws the model flat white instead
* (`mix` at 1, unlit).
* @param {boolean} irBoost
* @returns {{colorBlendMode: Cesium.ColorBlendMode, colorBlendAmount: number}}
* @returns {{mode: 'highlight'|'mix', amount?: number}}
*/
export function aircraftModelBlend(irBoost) {
return irBoost
? { colorBlendMode: Cesium.ColorBlendMode.MIX, colorBlendAmount: 1 }
: { colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, colorBlendAmount: 0 };
return irBoost ? FLAT : HIGHLIGHT;
}
+22 -24
View File
@@ -5,9 +5,8 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
/**
* Every aircraft model drawn in the scene skips Cesium's dynamic environment
* map (a sky render and GPU readback per model). Drawn models are the calls
* that set a minimum pixel size.
* Every aircraft model drawn in the scene skips the renderer's dynamic
* environment map (a sky render and GPU readback per model).
*/
const SOURCES = [
{
@@ -18,13 +17,6 @@ const SOURCES = [
name: 'militaryFlights',
source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)),
},
{
name: 'localAdsb',
source: readFileSync(
new URL('../layers/localAdsb/models.js', import.meta.url),
'utf8',
),
},
];
test('the shared option turns the dynamic environment map off', () => {
@@ -34,19 +26,25 @@ test('the shared option turns the dynamic environment map off', () => {
for (const { name, source } of SOURCES) {
test(`${name}: every drawn aircraft model skips the dynamic environment map`, () => {
const calls = [
...source.matchAll(
/(?:fromGltfAsync\(|loadModel\(|(?:_createModel|createFleetModel)\(\s*\w+,\s*)\{([\s\S]*?)\n\s*\}[,)]/g,
),
]
.map((match) => match[1])
.filter((options) => /\bminimumPixelSize:/.test(options));
assert.ok(calls.length >= 1, `expected drawn model calls in ${name}`);
for (const [index, options] of calls.entries())
assert.match(
options,
/\benvironmentMapOptions:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\b/,
`${name} model call ${index + 1} must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`,
);
// Its models are draw-port items; every item it builds (fleet and
// tracked) carries the shared option.
assert.doesNotMatch(source, /fromGltfAsync|loadModel\(/);
const items = [...source.matchAll(/\burl: record\.url,/g)];
assert.ok(items.length >= 1, `expected model items in ${name}`);
const flags = [
...source.matchAll(/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/g),
];
assert.equal(flags.length, items.length, `${name} model items must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`);
});
}
test('localAdsb: its draw-port models skip the dynamic environment map', () => {
const source = readFileSync(
new URL('../layers/localAdsb/models.js', import.meta.url),
'utf8',
);
assert.match(
source,
/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/,
);
});
+336
View File
@@ -0,0 +1,336 @@
import { fromDegrees } from '../geo/ellipsoid.js';
import {
julianFromEpochMs,
julianLessThan,
julianLessThanOrEquals,
julianToEpochMs,
secondsDifference,
} from '../geo/julian.js';
import { clone, distance } from '../geo/vector.js';
import { curvePieceAt, fixCurveCached } from './fixCurve.js';
import { historyBracketIndex, historyUnseenAt } from './timelineHistory.js';
import {
COAST_MAX_SPEED_MPS,
courseBetweenCartesians,
speedRamp,
STALE_COAST_MAX_SEC,
staleCoastLimitSeconds,
staleHoldsForFix,
} from './motionModel.js';
/**
* Which record fields carry an aircraft layer's reported ground speed (m/s)
* and track (degrees clockwise from north).
* @typedef {{speed: string, track: string}} AircraftRecordFields
*/
/** A fix's own ground speed, else the record's; never over COAST_MAX_SPEED_MPS. */
export function fixSpeedMps(fix, info, fields) {
return Math.min(
Number.isFinite(fix.velocity)
? fix.velocity
: (info && info[fields.speed]) || 0,
COAST_MAX_SPEED_MPS,
);
}
/** A fix's own track, else the record's. */
export function fixTrackDeg(fix, info, fields) {
return Number.isFinite(fix.track)
? fix.track
: (info && info[fields.track]) || 0;
}
/**
* The instant `epochMs` as a Julian date (into `result` when given), for
* `aircraftMotionRegime`'s `renderTime`.
*/
export function julianAt(epochMs, result) {
return julianFromEpochMs(epochMs, result);
}
/** A history fix's time in epoch ms: its `epochMs`, else its `time`'s. */
export function fixEpochMs(fix) {
return Number.isFinite(fix.epochMs) ? fix.epochMs : julianToEpochMs(fix.time);
}
/** A feed fix's ECEF position, from its degrees and render altitude. */
export function fixPosition(lonDeg, latDeg, heightM) {
return fromDegrees(lonDeg, latDeg, heightM);
}
/** A copy of a fix position, for a trail that keeps it. */
export function copyPosition(position) {
return clone(position);
}
/**
* A position-history entry for a feed fix at `epochMs`, carrying the fix's
* own speed and track; it keeps a copy of `position`.
*/
export function historyFix(epochMs, position, velocity, track) {
return {
time: julianAt(epochMs),
epochMs,
position: clone(position),
velocity,
track,
};
}
/**
* Whether a history fix is a forward synthetic fix (a motion aid built from
* a repeated report's new speed or course, `synthesizeForwardKinematicsFix`)
* rather than a report.
*/
export const isSyntheticFix = (fix) => Number.isFinite(fix?.reportEpochMs);
/**
* Put a new report at the end of a contact's history: forward synthetic
* fixes after the previous report go (the report supersedes them), and past
* `limit` the oldest fixes go.
* @param {Array<object>} history Oldest first; mutated.
* @param {object} fix The report's history fix.
* @param {number} limit
*/
export function pushReport(history, fix, limit) {
while (history.length && isSyntheticFix(history[history.length - 1]))
history.pop();
history.push(fix);
while (history.length > limit) history.shift();
}
/** The newest report in a history (not a synthetic fix), or undefined. */
export function newestReport(history) {
for (let i = history.length - 1; i >= 0; i--)
if (!isSyntheticFix(history[i])) return history[i];
return undefined;
}
/** The curve a contact is drawn along between two history fixes, or null. */
export function historyCurve(a, b) {
return fixCurveCached(
a.position,
fixEpochMs(a),
a.track,
b.position,
fixEpochMs(b),
b.track,
);
}
/** A reusable result for `aircraftMotionRegime`. */
export function createMotionRegime() {
return {
kind: 'fix',
a: null,
b: null,
piece: null,
span: 0,
speed: 0,
trackFrom: 0,
trackTo: 0,
chordCourse: null,
blend: 0,
fix: null,
heading: 0,
turnRateDps: 0,
minDt: 0,
maxDt: 0,
unseen: false,
};
}
/**
* Which motion an aircraft's history gives at `renderTime` — the one choice
* the CPU dead reckoning and the icon planner (GPU segment) both draw from.
*
* - `between`: between the bracketing pair `a`→`b`, no extrapolation
* error and no snap-back. Along their curve (`data/fixCurve`) when the
* pair describes one: `piece` is the curve's piece at `renderTime`, a
* contract `arc` segment with its times. Otherwise straight from `a` to
* `b` (`piece` null), and the course of the DISPLAYED motion blends the
* time-interpolated reported track toward the chord by `blend`: the chord
* is only trustworthy when the segment covers real ground (at hover its
* direction is GPS jitter; on a slow tight turn it STEPS the whole
* per-segment turn at each boundary), and helicopters never use it
* (rotorcraft chords are noise-dominated at their typical speeds).
* - `fix`: extrapolate `fix` by the elapsed time clamped to [minDt, maxDt].
* Warm-up (renderTime predates ALL history: freshly seen or just tracked,
* before a poll interval of history exists) runs the OLDEST fix BACKWARD,
* preserving the behind-real-time invariant, so as history fills the icon
* glides FORWARD into interpolation with no freeze and no backward snap
* (holding the oldest fix froze the icon; extrapolating the newest to
* wall-clock made it jump back a poll interval when interpolation took
* over). Otherwise the newest fix coasts on its last speed and heading for
* five minutes past it, then stops (SIGNAL LOST). A contact last heard on
* or near the ground holds there instead (`staleHoldsForFix`, decided once
* per report), and a chain of synthetic fixes never coasts further than
* the real report they were built from would. Following the clock, a
* warm-up well before a contact's own first fix is `unseen`: it was not
* there yet, and is not drawn (`historyUnseenAt`).
*
* @param {Array<object>} history Non-empty, oldest first.
* @param {object|undefined} info The contact's record.
* @param {{dayNumber: number, secondsOfDay: number}} renderTime A Julian date (geo/julian).
* @param {AircraftRecordFields} fields
* @param {object} result From `createMotionRegime`; returned filled in.
* @param {{cachedGroundFloor?: (latDeg: number, lonDeg: number) => number|null}} [options]
* The ground under a report, where known, for the hold decision.
*/
export function aircraftMotionRegime(
history,
info,
renderTime,
fields,
result,
{ cachedGroundFloor } = {},
) {
// A synthetic fix a later report superseded is not on the path: the
// contact is drawn report to report, as its trail is.
let report = history.length - 1;
while (report >= 0 && isSyntheticFix(history[report])) report--;
// The pairs are read back from the fix after the first one at or after
// the render time (so a fix at exactly that time takes the later pair, as
// it always did; past any superseded synthetic fix there), found by
// halving, and stop at the first pair wholly before it: a contact
// following the clock keeps a long history.
let start = Math.min(
historyBracketIndex(history, renderTime) + 1,
history.length - 1,
);
while (start < report && isSyntheticFix(history[start])) start++;
let b = null;
for (let i = start; i >= 0; i--) {
const a = history[i];
if (i < report && isSyntheticFix(a)) continue;
const pairB = b;
b = a;
if (!pairB) continue;
if (julianLessThan(pairB.time, renderTime)) break;
if (
!julianLessThanOrEquals(a.time, renderTime) ||
!julianLessThanOrEquals(renderTime, pairB.time)
)
continue;
const span = secondsDifference(pairB.time, a.time);
const chordLenM = distance(a.position, pairB.position);
const speed =
span > 0 ? chordLenM / span : (info && info[fields.speed]) || 0;
const fallbackTrack = (info && info[fields.track]) || 0;
const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack;
const blend = info && info.klass === 'helicopter' ? 0 : speedRamp(speed);
const curve = span > 0 ? historyCurve(a, pairB) : null;
result.kind = 'between';
result.a = a;
result.b = pairB;
result.piece = curve
? curvePieceAt(curve, julianToEpochMs(renderTime))
: null;
result.span = span;
result.speed = speed;
result.trackFrom = trackFrom;
result.trackTo = Number.isFinite(pairB.track) ? pairB.track : trackFrom;
result.chordCourse =
blend > 0 ? courseBetweenCartesians(a.position, pairB.position) : null;
result.blend = blend;
result.unseen = false;
return result;
}
const newest = history[history.length - 1];
const warming = julianLessThan(renderTime, history[0].time);
result.kind = 'fix';
result.piece = null;
result.fix = warming ? history[0] : newest;
result.unseen = warming && historyUnseenAt(history, renderTime);
result.speed = fixSpeedMps(result.fix, info, fields);
result.heading = fixTrackDeg(result.fix, info, fields);
// Past the newest report it flies straight on along its course: a turn
// rate averaged over earlier reports outlives the turn it measured, and
// coasting on it put contacts kilometres off a straight path.
result.turnRateDps = 0;
result.minDt = -60;
// A warm-up ends when real time reaches the oldest fix; a single fix keeps
// coasting forward on the same line.
result.maxDt =
warming && history.length > 1
? 0
: staleCoastSeconds(newest, info, cachedGroundFloor);
return result;
}
/**
* How long `newest` coasts at most: five minutes, less what a synthetic
* fix's chain already coasted since its real report (`reportEpochMs`); none
* for a report that holds (judged once per report, from its ground flag and
* the ground under it where `cachedGroundFloor` knows it).
* @param {object} newest
* @param {object|undefined} info
* @param {Function} [cachedGroundFloor]
* @returns {number}
*/
export function staleCoastSeconds(newest, info, cachedGroundFloor) {
const newestMs = fixEpochMs(newest);
const limitSec = staleCoastLimitSeconds({
fixEpochMs: newestMs,
lastContactEpochMs: info?.lastContactEpochMs,
// A plane that stops reporting keeps flying for five minutes, whatever
// its contact time, then stops dimmed as SIGNAL LOST. A missed update
// shows STALE throughout.
minimumSec: 300,
maximumSec: 300,
});
if (staleHoldsForFix(newest, { onGround: info?.onGround, cachedGroundFloor }))
return 0;
const alreadySec = Number.isFinite(newest.reportEpochMs)
? Math.max(0, (newestMs - newest.reportEpochMs) / 1000)
: 0;
return Math.max(0, Math.min(limitSec, STALE_COAST_MAX_SEC - alreadySec));
}
/** A raw position this far (m) off its own path, plus half its step, is a jump. */
const RAW_JUMP_SLACK_M = 5;
/**
* Whether a tracked aircraft's raw position jumped this frame: a new report
* moved its path. Judged against the path itself, where its last frame's
* step carries it, not against a reported speed (which can be stale or 0
* while the drawn motion, minutes behind the newest report, is fast). A
* frame with no step to go by (the first on a track, or the one after a
* jump) is never a jump.
* @param {{x: number, y: number, z: number}} raw This frame's raw position.
* @param {{x: number, y: number, z: number}} prevRaw Last frame's.
* @param {{x: number, y: number, z: number}} prevRawStep Last frame's step.
* @param {number} prevRawStepSec Last frame's length, s (0: no step).
* @param {number} dtSec This frame's length, s.
* @returns {boolean}
*/
export function rawPositionJumped(
raw,
prevRaw,
prevRawStep,
prevRawStepSec,
dtSec,
) {
if (!(prevRawStepSec > 0)) return false;
const k = dtSec / prevRawStepSec;
const dx = raw.x - (prevRaw.x + prevRawStep.x * k);
const dy = raw.y - (prevRaw.y + prevRawStep.y * k);
const dz = raw.z - (prevRaw.z + prevRawStep.z * k);
const stepM =
Math.hypot(prevRawStep.x, prevRawStep.y, prevRawStep.z) * Math.abs(k);
return Math.hypot(dx, dy, dz) > RAW_JUMP_SLACK_M + 0.5 * stepM;
}
/**
* How fast the drawn path moves (m/s), from its last raw step; `fallback`
* (a reported speed) with no step to go by.
* @param {{x: number, y: number, z: number}} step
* @param {number} stepSec
* @param {number} fallback
* @returns {number}
*/
export function rawStepSpeedMps(step, stepSec, fallback) {
if (!(stepSec > 0)) return fallback;
return Math.hypot(step.x, step.y, step.z) / stepSec;
}
+52 -142
View File
@@ -1,35 +1,33 @@
/**
* Limb-relative recession for distant aircraft billboards.
* Limb-relative recession for distant aircraft: the tuning the aircraft icon
* and model sets recede by (`aircraftRecedeSpec`), and the factors and alpha
* those sets draw with, for evidence and checks.
*
* This multiplies the billboard's ordinary scale, which Cesium then composes
* with the locked NearFarScalar. It never edits that scalar, culls a contact,
* or allows alpha to reach zero.
* It multiplies an icon's ordinary scale, which composes with its locked
* NearFarScalar. It never edits that scalar, culls a contact, or allows alpha
* to reach zero. The maths is the Cesium-free `render/recession.js`,
* which the sets drawing aircraft recede by (`SetSpec.recede`).
*/
import {
RECEDE_DEFAULTS,
limbDistanceM,
recedeFactors,
recedeFrame,
recedeParams,
recededAlpha,
} from '../render/recession.js';
export const DEFAULT_AIRCRAFT_RECESSION_PARAMS = Object.freeze({
startLimbRatio: 0.5,
scaleFloor: 0.45,
alphaFloor: 0.35,
combinedAlphaFloor: 0.2,
globeViewBlendStartM: 3_500_000,
globeViewBlendEndM: 4_500_000,
earthRadiusM: 6_378_137,
...RECEDE_DEFAULTS,
writeEpsilon: 0.005,
});
let _params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS };
const _scratchFactors = { scale: 1, alpha: 1, limbRatio: null };
const _treatmentResult = {
scale: 1,
alpha: 1,
scaleWrites: 0,
alphaWrites: 0,
factors: _scratchFactors,
};
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
const _scratchFrame = { active: false, limbM: 1, strength: 0 };
// The tuning `_recede` was made from, and the set option made from it.
let _recedeFor = null;
let _recede = null;
function resolvedParams(overrides) {
if (!overrides || overrides === _params) return _params;
@@ -42,47 +40,12 @@ function aircraftRecessionFactorsResolved(
tuning,
result,
) {
if (
!Number.isFinite(cameraDistanceM) ||
cameraDistanceM < 0 ||
!Number.isFinite(cameraHeightM) ||
cameraHeightM <= 0 ||
cameraHeightM >= tuning.globeViewBlendEndM
) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = null;
return result;
}
const limbDistance = cameraLimbDistanceM(cameraHeightM, tuning.earthRadiusM);
if (!Number.isFinite(limbDistance) || limbDistance <= 0) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = null;
return result;
}
const limbRatio = cameraDistanceM / limbDistance;
if (limbRatio <= tuning.startLimbRatio) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = limbRatio;
return result;
}
const rawT =
(limbRatio - tuning.startLimbRatio) / (1 - tuning.startLimbRatio);
const t = clamp(rawT, 0, 1);
const limbEase = t * t * (3 - 2 * t); // smoothstep: zero slope at both band edges
const globeRawT =
(cameraHeightM - tuning.globeViewBlendStartM) /
(tuning.globeViewBlendEndM - tuning.globeViewBlendStartM);
const globeT = clamp(globeRawT, 0, 1);
const globeEase = globeT * globeT * (3 - 2 * globeT);
const strength = 1 - globeEase;
result.scale = 1 + (tuning.scaleFloor - 1) * limbEase * strength;
result.alpha = 1 + (tuning.alphaFloor - 1) * limbEase * strength;
result.limbRatio = limbRatio;
return result;
return recedeFactors(
cameraDistanceM,
recedeFrame(cameraHeightM, tuning, _scratchFrame),
tuning,
result,
);
}
/**
@@ -91,45 +54,34 @@ function aircraftRecessionFactorsResolved(
* @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS}
*/
export function setAircraftRecessionParams(patch = {}) {
const next = { ..._params };
if (Number.isFinite(patch.startLimbRatio)) {
next.startLimbRatio = clamp(patch.startLimbRatio, 0, 0.99);
}
if (Number.isFinite(patch.scaleFloor))
next.scaleFloor = clamp(patch.scaleFloor, 0.05, 1);
if (Number.isFinite(patch.alphaFloor))
next.alphaFloor = clamp(patch.alphaFloor, 0.05, 1);
if (Number.isFinite(patch.combinedAlphaFloor)) {
next.combinedAlphaFloor = clamp(patch.combinedAlphaFloor, 0.05, 1);
}
if (Number.isFinite(patch.globeViewBlendStartM)) {
next.globeViewBlendStartM = Math.max(1, patch.globeViewBlendStartM);
}
if (Number.isFinite(patch.globeViewBlendEndM)) {
next.globeViewBlendEndM = Math.max(
next.globeViewBlendStartM + 1,
patch.globeViewBlendEndM,
);
}
// Backward-compatible evidence override: the former hard threshold now
// names the identity end of the blend band.
if (Number.isFinite(patch.globeViewHeightM)) {
next.globeViewBlendEndM = Math.max(
next.globeViewBlendStartM + 1,
patch.globeViewHeightM,
);
}
if (next.globeViewBlendStartM >= next.globeViewBlendEndM) {
next.globeViewBlendStartM = Math.max(1, next.globeViewBlendEndM - 1);
}
if (Number.isFinite(patch.earthRadiusM))
next.earthRadiusM = Math.max(1, patch.earthRadiusM);
const given = Number.isFinite(patch.globeViewHeightM)
? { ...patch, globeViewBlendEndM: patch.globeViewHeightM }
: patch;
const next = {
...recedeParams(given, _params),
writeEpsilon: _params.writeEpsilon,
};
if (Number.isFinite(patch.writeEpsilon))
next.writeEpsilon = Math.max(0, patch.writeEpsilon);
_params = next;
return { ..._params };
}
/**
* The tuning as the `recede` of the sets that draw aircraft: the same
* object until the tuning changes.
* @returns {import('../render/contract/index').RecedeSpec}
*/
export function aircraftRecedeSpec() {
if (_recedeFor !== _params) {
_recedeFor = _params;
_recede = Object.freeze(recedeParams(_params));
}
return _recede;
}
/** @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS} Current tuning. */
export function getAircraftRecessionParams() {
return _params;
@@ -148,13 +100,7 @@ export function resetAircraftRecessionParams() {
* @param {number} [earthRadiusM]
* @returns {number}
*/
export function cameraLimbDistanceM(
cameraHeightM,
earthRadiusM = DEFAULT_AIRCRAFT_RECESSION_PARAMS.earthRadiusM,
) {
if (!Number.isFinite(cameraHeightM) || cameraHeightM <= 0) return Number.NaN;
return Math.sqrt(cameraHeightM * (2 * earthRadiusM + cameraHeightM));
}
export const cameraLimbDistanceM = limbDistanceM;
/**
* Pure recession factors for one aircraft.
@@ -178,28 +124,18 @@ export function aircraftRecessionFactors(
}
/**
* Production wire helper: compose base scale/alpha, focus emphasis, and limb
* recession into one deadband-gated billboard write site.
* The alpha an aircraft draws with: base × max(combined floor, focus × limb
* haze). Icon sets compose the same thing in their shader; models need it here.
* @param {object} input
* @param {object} input.billboard
* @param {number} input.baseScale
* @param {number} input.baseAlpha
* @param {{withAlpha:(alpha:number)=>object}} input.baseColor
* @param {number} input.focusFactor
* @param {number} input.cameraDistanceM
* @param {number} input.cameraHeightM
* @param {Partial<typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS>} [input.params]
*
* IMPORTANT: the returned object (including `factors`) is a module-owned
* mutable singleton. Consume every needed property before the next call;
* never retain it as a snapshot.
* @returns {{scale:number,alpha:number,scaleWrites:number,alphaWrites:number,factors:object}}
* @returns {number}
*/
export function applyAircraftBillboardTreatment({
billboard,
baseScale,
export function aircraftTreatmentAlpha({
baseAlpha,
baseColor,
focusFactor,
cameraDistanceM,
cameraHeightM,
@@ -212,33 +148,7 @@ export function applyAircraftBillboardTreatment({
tuning,
_scratchFactors,
);
const scale = baseScale * factors.scale;
const composedTreatment = Math.max(
tuning.combinedAlphaFloor,
clamp(focusFactor, 0, 1) * factors.alpha,
);
const alpha = baseAlpha * composedTreatment;
let scaleWrites = 0;
let alphaWrites = 0;
if (
!Number.isFinite(billboard.scale) ||
Math.abs(billboard.scale - scale) > tuning.writeEpsilon
) {
billboard.scale = scale;
scaleWrites = 1;
}
if (
!Number.isFinite(billboard.color?.alpha) ||
Math.abs(billboard.color.alpha - alpha) > tuning.writeEpsilon
) {
billboard.color = baseColor.withAlpha(alpha);
alphaWrites = 1;
}
_treatmentResult.scale = scale;
_treatmentResult.alpha = alpha;
_treatmentResult.scaleWrites = scaleWrites;
_treatmentResult.alphaWrites = alphaWrites;
return _treatmentResult;
return baseAlpha * recededAlpha(focusFactor, factors.alpha, tuning);
}
/**
+24 -60
View File
@@ -3,9 +3,9 @@ import assert from 'node:assert/strict';
import {
DEFAULT_AIRCRAFT_RECESSION_PARAMS,
aircraftRecessionFactors,
applyAircraftBillboardTreatment,
applyAircraftModelTreatment,
cameraLimbDistanceM,
aircraftTreatmentAlpha,
} from './aircraftRecession.js';
const params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS };
@@ -66,72 +66,15 @@ test('globe-view transition eases to identity without a threshold pop', () => {
assert.deepEqual(end, { scale: 1, alpha: 1, limbRatio: null });
});
test('aircraft billboard wire writes scale and alpha only for the far treatment', () => {
const color = { withAlpha: (alpha) => ({ alpha }) };
const near = { scale: 1.2, color: { alpha: 0.8 } };
const nearResult = applyAircraftBillboardTreatment({
billboard: near,
baseScale: 1.2,
baseAlpha: 0.8,
baseColor: color,
focusFactor: 1,
cameraDistanceM: limb * 0.4,
cameraHeightM,
params,
});
assert.equal(nearResult.scaleWrites, 0);
assert.equal(nearResult.alphaWrites, 0);
const far = { scale: 1.2, color: { alpha: 0.8 } };
const farResult = applyAircraftBillboardTreatment({
billboard: far,
baseScale: 1.2,
baseAlpha: 0.8,
baseColor: color,
focusFactor: 0.5,
cameraDistanceM: limb,
cameraHeightM,
params,
});
assert.equal(farResult.scaleWrites, 1);
assert.equal(farResult.alphaWrites, 1);
assert.ok(Math.abs(far.scale - (1.2 * 0.45)) < 1e-12);
assert.ok(Math.abs(far.color.alpha - (0.8 * 0.20)) < 1e-12);
});
test('combined focus and haze product is clamped at the composed alpha floor', () => {
const color = { withAlpha: (alpha) => ({ alpha }) };
const billboard = { scale: 0.45, color: { alpha: 1 } };
const result = applyAircraftBillboardTreatment({
billboard,
baseScale: 1,
const alpha = aircraftTreatmentAlpha({
baseAlpha: 1,
baseColor: color,
focusFactor: 0.25,
cameraDistanceM: limb,
cameraHeightM,
params,
});
assert.equal(result.alpha, 0.20);
assert.equal(billboard.color.alpha, 0.20);
});
test('applyAircraftBillboardTreatment returns its documented module singleton', () => {
const color = { withAlpha: (alpha) => ({ alpha }) };
const billboard = { scale: 1, color: { alpha: 1 } };
const input = {
billboard,
baseAlpha: 1,
baseColor: color,
focusFactor: 1,
cameraDistanceM: 0,
cameraHeightM,
params,
};
const first = applyAircraftBillboardTreatment({ ...input, baseScale: 1 });
const second = applyAircraftBillboardTreatment({ ...input, baseScale: 0.5 });
assert.strictEqual(first, second);
assert.equal(first.scale, 0.5, 'the prior reference reflects the next call');
assert.equal(alpha, 0.2);
});
test('ambient model presentation receives composed alpha without changing blend semantics', () => {
@@ -154,3 +97,24 @@ test('model hue changes at constant alpha, then clears without redundant writes'
assert.equal(applyAircraftModelTreatment({model,baseColor:color(1,1,1),alpha:0.65}),1);
assert.equal(model.color.green,1);
});
test('the aircraft sets recede by the tuning: one object until it changes', async () => {
const {
aircraftRecedeSpec,
setAircraftRecessionParams,
resetAircraftRecessionParams,
} = await import('./aircraftRecession.js');
const { RECEDE_DEFAULTS } = await import('../render/recession.js');
resetAircraftRecessionParams();
const first = aircraftRecedeSpec();
assert.deepEqual(first, { ...RECEDE_DEFAULTS });
assert.equal(aircraftRecedeSpec(), first);
setAircraftRecessionParams({ scaleFloor: 0.6, globeViewHeightM: 4_000_000 });
const tuned = aircraftRecedeSpec();
assert.notEqual(tuned, first);
assert.equal(tuned.scaleFloor, 0.6);
assert.equal(tuned.globeViewBlendEndM, 4_000_000);
assert.equal('writeEpsilon' in tuned, false);
resetAircraftRecessionParams();
assert.deepEqual(aircraftRecedeSpec(), first);
});
File diff suppressed because it is too large. Load diff
+131 -123
View File
@@ -3,6 +3,11 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
bindFakeCesiumCamera,
followEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
import alprCamerasLayer, {
createAlprCamerasLayer,
configureAlprSource,
@@ -31,6 +36,8 @@ import {
isAlprSurveillanceType,
normalizeAlprNode,
} from './alprCameras.js';
import { readEntityRecord } from './entityRecords.js';
import { alprMarkers } from '../layers/alpr/markerState.js';
test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
const record = normalizeAlprNode({
@@ -308,7 +315,7 @@ function cameraHarness(layer = alprCamerasLayer) {
},
});
let box = { south: 30.26, west: -97.75, north: 30.28, east: -97.73 };
let source, click, picked;
let click, picked;
const credits = new Set();
const viewer = {
creditDisplay: {
@@ -333,20 +340,27 @@ function cameraHarness(layer = alprCamerasLayer) {
postRender: new Cesium.Event(),
pick: () => picked,
},
dataSources: {
add: (value) => {
source = value;
},
remove() {},
},
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
entities: {},
};
const ports = fakeScenePorts(viewer);
bindFakeCesiumCamera(viewer, ports);
// The renderer's camera port relays moveEnd; the layer's own come on top.
const portMoveEndListeners = viewer.camera.moveEnd.numberOfListeners;
const setInput = Cesium.ScreenSpaceEventHandler.prototype.setInputAction;
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = function (
fn,
type,
modifier,
) {
if (type === Cesium.ScreenSpaceEventType.LEFT_CLICK) click = fn;
// The unmodified click: the input port binds one per modifier.
if (
type === Cesium.ScreenSpaceEventType.LEFT_CLICK &&
modifier === undefined
)
click = fn;
return setInput.call(this, fn, type, modifier);
};
try {
@@ -355,13 +369,22 @@ function cameraHarness(layer = alprCamerasLayer) {
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = setInput;
}
layer.enable();
const icons = () => {
const set = [...ports.draw.sets.values()].find(
(candidate) => candidate.kind === 'icons' && !candidate.disposed,
);
return set && { ...set, id: set.spec.id };
};
const marker = (id) =>
icons()?.items.has(id)
? getContextStore().entities.get(id)?.entity
: undefined;
return {
viewer,
ports,
portMoveEndListeners,
requests,
credits,
get source() {
return source;
},
setFetch(fn) {
response = fn;
},
@@ -374,9 +397,16 @@ function cameraHarness(layer = alprCamerasLayer) {
advance(ms) {
now += ms;
},
/** The layer's icon set, as the fake draw port holds it. */
icons,
/** The icon drawn for a camera, or undefined. */
icon: (id) => icons()?.items.get(id),
/** The drawn markers' carriers (their context entities), in draw order. */
markers: () => [...(icons()?.items.keys() ?? [])].map((id) => marker(id)),
marker,
click(id) {
const entity = typeof id === 'string' ? source.entities.getById(id) : id;
picked = entity ? { id: entity } : undefined;
const item = typeof id === 'string' ? icons()?.items.get(id) : null;
picked = item ? { id: { set: icons().id, id: item.id } } : undefined;
click({ position: new Cesium.Cartesian2() });
},
restore() {
@@ -440,28 +470,28 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a
]),
);
await alprCamerasLayer.update();
const entities = h.source.entities.values;
const entities = h.markers();
assert.equal(alprCamerasLayer.name, 'ALPR Cameras');
assert.deepEqual(
entities.map((entity) => entity.gevLabelModel.title),
entities.map((entity) => readEntityRecord(entity)?.labelModel.title),
['ALPR-0042', 'ALPR-0043', 'ALPR-0044'],
);
assert.equal(
new Set(entities.map((entity) => entity.billboard.image.getValue())).size,
new Set(entities.map((entity) => h.icon(entity.id).image)).size,
1,
);
assert.deepEqual(entities[0].gevLabelModel.details, [
assert.deepEqual(readEntityRecord(entities[0])?.labelModel.details, [
'OSM MAPPED',
'FLOCK SAFETY · CITY POLICE · FIXED',
'PUBLIC MAP DATA',
]);
assert.deepEqual(entities[1].gevLabelModel.details, [
assert.deepEqual(readEntityRecord(entities[1])?.labelModel.details, [
'OSM MAPPED',
'MOTOROLA SOLUTIONS',
'PUBLIC MAP DATA',
]);
assert.deepEqual(
entities[2].gevLabelModel.details,
readEntityRecord(entities[2])?.labelModel.details,
['OSM MAPPED', 'PUBLIC MAP DATA'],
'unknown metadata is not guessed, but the source is always named',
);
@@ -486,7 +516,7 @@ test('the camera label stays English data in a translated interface', async () =
]),
);
await alprCamerasLayer.update();
h.click(h.source.entities.values[0].id);
h.click(h.markers()[0].id);
assert.equal(getSelectedEntityContext().label, 'ALPR camera');
assert.equal(
shownEntityLabel(getSelectedEntityContext().label),
@@ -523,10 +553,7 @@ test('clicking the selected camera or empty map deselects, including after refre
h.expire();
await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null);
assert.equal(
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
assert.equal(h.icon('alpr:42').size[0], 38);
}
} finally {
h.restore();
@@ -582,10 +609,7 @@ test('disable removes contexts and highlight; cache reuse after re-enable does n
alprCamerasLayer.enable();
await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null);
assert.equal(
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
assert.equal(h.icon('alpr:42').size[0], 38);
} finally {
h.restore();
}
@@ -674,7 +698,7 @@ test('duplicate nodes render once with a count that agrees with the entity set',
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'ready');
assert.equal(alprCamerasLayer.getStats().count, 1);
assert.equal(h.source.entities.values.length, 1);
assert.equal(h.icons().items.size, 1);
} finally {
h.restore();
}
@@ -690,7 +714,7 @@ test('zooming out hides local markers, releases selection and makes no unbounded
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(alprCamerasLayer.getStats().count, 0);
assert.equal(getSelectedEntityContext(), null);
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.icons().items.size, 0);
assert.equal(h.requests.length, 1);
} finally {
h.restore();
@@ -750,7 +774,7 @@ test('nearby camera moves reuse the snapped query but count and register only in
await alprCamerasLayer.update();
assert.equal(h.requests.length, 1);
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
h.markers().map((e) => e.id),
['alpr:43'],
);
assert.deepEqual([...getContextStore().entities.keys()], ['alpr:43']);
@@ -797,9 +821,8 @@ test('selected readout samples the rendered ground, not zero elevation or the di
try {
let samples = 0;
h.viewer.scene.sampleHeightSupported = true;
h.viewer.scene.sampleHeight = (point, excluded) => {
h.viewer.scene.sampleHeight = () => {
samples += 1;
assert.equal(excluded[0].id, 'alpr:42');
return 187;
};
h.setFetch(async () =>
@@ -811,9 +834,9 @@ test('selected readout samples the rendered ground, not zero elevation or the di
);
await alprCamerasLayer.update();
h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42');
const entity = h.marker('alpr:42');
const anchor = Cesium.Cartographic.fromCartesian(
entity.gevDisplayPosition(),
readEntityRecord(entity)?.displayPosition(),
);
assert.ok(Math.abs(anchor.height - 187) < 0.001);
assert.ok(
@@ -821,7 +844,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di
);
for (let i = 0; i < 60; i++) {
h.viewer.scene.postRender.raiseEvent();
entity.gevDisplayPosition();
readEntityRecord(entity)?.displayPosition();
}
assert.equal(samples, 1, 'no per-frame raycasts');
h.advance(1000);
@@ -859,6 +882,7 @@ test('a late network failure after disable cannot resurrect retries or an error
});
test('two factories keep their requests, records and destruction independent', async () => {
const carriers = new Map();
const services = {
render: { governorRequestRender() {} },
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
@@ -872,7 +896,9 @@ test('two factories keep their requests, records and destruction independent', a
getSelectedEntityContext() {
return null;
},
registerEntityContext() {},
registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
@@ -918,14 +944,17 @@ test('two factories keep their requests, records and destruction independent', a
await pending;
assert.equal(first.getStats().count, 0);
assert.equal(second.getStats().count, 1);
assert.equal(b.source.entities.values[0].id, 'directory:99');
assert.deepEqual([...b.icons().items.keys()], ['directory:99']);
assert.equal(second.source, 'Test camera directory');
assert.ok(
b.source.entities.values[0].gevLabelModel.details.includes(
'Source: Test directory',
),
readEntityRecord(
carriers.get('directory:99'),
)?.labelModel.details.includes('Source: Test directory'),
);
assert.equal(
a.viewer.camera.moveEnd.numberOfListeners,
a.portMoveEndListeners,
);
assert.equal(a.viewer.camera.moveEnd.numberOfListeners, 0);
assert.equal(a.viewer.scene.postRender.numberOfListeners, 0);
} finally {
b.restore();
@@ -937,6 +966,7 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
// Ground clamping re-samples every marker whenever a photoreal tile streams
// in; a whole-city view (about 1,000 cameras) stuttered while zooming.
const floors = new Map([['30.2672', 150]]);
const carriers = new Map();
let resolveCalls = 0;
let releaseResolve;
const services = {
@@ -957,7 +987,9 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
getSelectedEntityContext() {
return null;
},
registerEntityContext() {},
registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
@@ -978,38 +1010,29 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
const h = cameraHarness(layer);
try {
await layer.update();
const known = h.source.entities.getById('directory:1');
const unknown = h.source.entities.getById('directory:2');
assert.equal(
known.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
const known = h.icon('directory:1');
const unknown = () => h.icon('directory:2');
const unknownCarrier = carriers.get('directory:2');
assert.equal(known.height, 'absolute');
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(known.position.getValue()).height -
151.5,
) < 0.01,
);
assert.equal(
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND,
Math.abs(Cesium.Cartographic.fromCartesian(known.pos).height - 151.5) <
0.01,
);
assert.equal(unknown().height, 'clampGround');
assert.equal(resolveCalls, 1);
const writes = h.icons().writes;
releaseResolve();
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
assert.equal(unknown().height, 'absolute');
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(unknown.position.getValue()).height -
161.5,
Cesium.Cartographic.fromCartesian(unknown().pos).height - 161.5,
) < 0.01,
);
assert.equal(h.icons().writes, writes + 1, 'one write for the move');
assert.equal(
h.source.entities.getById('directory:2'),
unknown,
carriers.get('directory:2'),
unknownCarrier,
'placed in place, not rebuilt',
);
} finally {
@@ -1061,23 +1084,16 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
);
await alprCamerasLayer.update();
h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42');
const position = entity.position,
line = entity.polyline;
const entity = h.marker('alpr:42');
const icon = h.icon('alpr:42');
// Ground-clamped native wedges cost ~40 ms per frame for a downtown view;
// bearings are painted by the overlay for the nearest cameras instead.
assert.equal(line, undefined);
assert.equal(entity.polygon, undefined);
assert.equal(h.ports.draw.sets.size, 1, 'icons only, no wedge geometry');
let selections = 0,
clears = 0,
collectionChanges = 0;
clears = 0;
window.addEventListener('gev:entity-selected', () => selections++);
window.addEventListener('gev:entity-selection-cleared', () => clears++);
h.source.entities.collectionChanged.addEventListener(
(_collection, added, removed) => {
collectionChanges += added.length + removed.length;
},
);
const writes = h.icons().writes;
h.setBox({ south: 30.261, west: -97.749, north: 30.279, east: -97.731 });
await alprCamerasLayer.update();
h.expire();
@@ -1093,30 +1109,26 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
]),
);
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(entity.position, position);
assert.equal(entity.polyline, line);
assert.equal(h.marker('alpr:42'), entity);
assert.equal(h.icon('alpr:42'), icon, 'the icon is not sent again');
assert.equal(
getSelectedEntityContext().properties.operator,
'Updated directory',
);
assert.equal(selections, 0);
assert.equal(clears, 0);
assert.equal(collectionChanges, 0);
assert.equal(h.icons().writes, writes, 'no icon added or removed');
assert.equal(h.requests.length, 2, 'only expiry needs another request');
h.expire();
h.setFetch(async () => cameraResponse([cameraNode(42, { lon: -97.742 })]));
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(
entity.polyline,
undefined,
'removed direction must not persist',
);
assert.equal(h.marker('alpr:42'), entity);
assert.ok(
Cesium.Cartesian3.equals(
entity.position.getValue(),
Cesium.Cartesian3.equalsEpsilon(
h.icon('alpr:42').pos,
Cesium.Cartesian3.fromDegrees(-97.742, 30.2672),
0,
1e-6,
),
);
} finally {
@@ -1156,7 +1168,7 @@ test('moves inside a pending query do not restart it; moving to another city can
resolve(cameraResponse([cameraNode(43, { lat: 51.495, lon: -0.13 })]));
await second;
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
h.markers().map((e) => e.id),
['alpr:43'],
);
} finally {
@@ -1174,12 +1186,12 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da
camera.positionWC = Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 1200);
try {
await alprCamerasLayer.update();
const entity = h.source.entities.getById('alpr:42');
const entity = h.marker('alpr:42');
h.click('alpr:42');
for (const box of [null, { south: 31, west: -99, north: 36, east: -95 }]) {
h.setBox(box);
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(h.marker('alpr:42'), entity);
assert.equal(getSelectedEntityContext().id, 'alpr:42');
assert.equal(h.requests.length, 1);
}
@@ -1190,7 +1202,7 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da
);
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.icons().items.size, 0);
camera.pickEllipsoid = () => undefined;
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
@@ -1235,14 +1247,14 @@ test('nearby count and discovery control frame a real loaded camera without fetc
);
assert.equal(flights[0].options.offset.range, 800);
assert.equal(h.requests.length, 1);
h.viewer.trackedEntity = {};
followEntity(h.viewer, {});
assert.equal(alprCamerasLayer.getRowControls().chips[0].disabled, true);
assert.equal(
controls.chips[0].onClick(),
false,
'a stale button cannot steal the follow camera',
);
h.viewer.trackedEntity = undefined;
followEntity(h.viewer, null);
alprCamerasLayer.disable();
assert.equal(alprCamerasLayer.getStats().countLabel, '');
assert.equal(controls.chips[0].onClick(), false);
@@ -1385,7 +1397,7 @@ test('slow ALPR floors share real terrain requests across preparation, render an
requests[1].release();
await new Promise((done) => setTimeout(done, 0));
assert.equal(requests.length, 2, 'queued final cells are discarded');
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.icons().items.size, 0);
layer.enable();
await layer.update();
assert.equal(
@@ -1404,10 +1416,11 @@ test('slow ALPR floors share real terrain requests across preparation, render an
}
});
test('map-source changes reposition all ALPR entities and saved native appearances in place', async () => {
test('map-source changes reposition all ALPR markers, those under canvas badges too, in place', async () => {
let floor = 180;
let listener;
let removed = 0;
const carriers = new Map();
const records = Array.from({ length: 70 }, (_, i) => ({
id: `surface:${i}`,
latitude: 30.2672 + i * 0.00001,
@@ -1433,7 +1446,9 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
context: {
clearSelectedEntityContextForLayer() {},
getSelectedEntityContext() {},
registerEntityContext() {},
registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
@@ -1442,40 +1457,33 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
const h = cameraHarness(layer);
try {
await layer.update();
const entities = [...h.source.entities.values];
const entities = [...carriers.values()];
// One marker under a canvas badge: its icon is the faint pick target.
const saved = entities[1];
saved.gevAlprNativeAppearance = {
position: saved.position,
heightReference: saved.billboard.heightReference,
};
saved.position = Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190);
saved.gevAlprPickPosition = saved.position;
Object.assign(alprMarkers.write(saved), {
canvasOwned: true,
canvasPosition: Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190),
});
for (const next of [150, 120, null, 180]) {
floor = next;
// Includes a provider switch with the same globe.show value.
h.viewer.scene.globe.show = next !== 180;
listener({ detail: { status: 'ready' } });
for (const entity of entities) {
assert.equal(h.source.entities.getById(entity.id), entity);
const icon = h.icon(entity.id);
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(entity.position.getValue())
.height - (next == null ? 0 : next + 1.5),
Cesium.Cartographic.fromCartesian(icon.pos).height -
(next == null ? 0 : next + 1.5),
) < 0.01,
`${entity.id} refreshes at ${next}`,
);
assert.equal(
entity.billboard.heightReference.getValue(),
next == null
? Cesium.HeightReference.CLAMP_TO_GROUND
: Cesium.HeightReference.NONE,
);
assert.equal(entity.gevAlprCanvasPosition, null);
assert.equal(icon.height, next == null ? 'clampGround' : 'absolute');
assert.equal(icon.color, undefined, 'drawn as a badge');
assert.equal(alprMarkers.read(entity)?.canvasPosition, null);
}
assert.equal(
saved.gevAlprNativeAppearance,
null,
'saved appearance restores at the new floor',
alprMarkers.read(saved)?.canvasOwned,
false,
'the badge comes back at the new floor',
);
}
} finally {
@@ -1488,7 +1496,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const h = cameraHarness();
try {
await alprCamerasLayer.update();
const previous = h.source.entities.getById('alpr:42');
const previous = h.marker('alpr:42');
const revision = alprCamerasLayer.getStats().renderRevision;
let release;
h.setFetch(
@@ -1501,7 +1509,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const pending = alprCamerasLayer.update();
await alprCamerasLayer.update();
assert.equal(
h.source.entities.getById('alpr:42'),
h.marker('alpr:42'),
previous,
'do not show an intermediate filtered snapshot while the new query prepares',
);
@@ -1511,7 +1519,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
await pending;
assert.equal(alprCamerasLayer.getStats().renderRevision, revision + 1);
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
h.markers().map((e) => e.id),
['alpr:43'],
);
} finally {
+22 -17
View File
@@ -1,4 +1,10 @@
import * as Cesium from 'cesium';
import {
canvasOf,
findCamera,
findFrame,
findQuery,
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
const YOUTUBE_HOSTS = new Set([
@@ -538,23 +544,22 @@ function ensureProviderConnections(documentRef, provider) {
}
}
/**
* Where an anchor (ECEF) is in the card root, through the renderer's camera
* and query ports; null behind the eye, off the root, or with no renderer.
*/
function anchorOnScreen(viewer, anchor, root) {
if (!viewer?.scene || !anchor || !root) return null;
const camera = viewer.camera;
if (camera?.positionWC && camera?.directionWC) {
const delta = Cesium.Cartesian3.subtract(
anchor,
camera.positionWC,
new Cesium.Cartesian3(),
);
if (Cesium.Cartesian3.dot(delta, camera.directionWC) <= 0) return null;
}
const pixel = Cesium.SceneTransforms.worldToWindowCoordinates(
viewer.scene,
anchor,
);
if (!anchor || !root) return null;
const camera = findCamera(viewer);
const query = findQuery(viewer);
if (!camera || !query) return null;
const pose = camera.pose();
if (dot(sub(anchor, pose.position), pose.direction) <= 0) return null;
const pixel = query.project(anchor);
if (!pixel) return null;
const canvasBounds = viewer.canvas?.getBoundingClientRect?.();
// The renderer's canvas; a viewer with no renderer bound, its own.
const canvas = canvasOf(viewer);
const canvasBounds = canvas?.getBoundingClientRect?.();
const rootBounds = root.getBoundingClientRect?.();
if (!canvasBounds || !rootBounds) return null;
const x = pixel.x + canvasBounds.left - rootBounds.left;
@@ -865,7 +870,7 @@ export function createBhoteKoshiEmbeddedMedia({
}
};
const removePostRender =
viewer.scene?.postRender?.addEventListener?.(position);
findFrame(viewer)?.on('postRender', () => position()) ?? null;
function hide({ immediate = false, preserveWarm = false } = {}) {
if (!preserveWarm) clearWarm();
+53
View File
@@ -10,6 +10,7 @@ import {
publicEmbeddedMediaUrl,
resolveEmbeddedMediaSource,
} from './bhoteKoshiEmbeddedMedia.js';
import { bindRenderer } from '../render/rendererOf.js';
test('Pinokio fallback never creates provider DOM or loads SDKs', async () => {
const unexpected = () => { throw new Error('Provider resource allocated in Pinokio'); };
@@ -417,3 +418,55 @@ test('a media card stays between the panels when right-to-left swaps their sides
assert.ok(left >= 340 + 18, `card at ${left}px lands on the context rail`);
assert.ok(left + 392 <= 1040 - 18, `card at ${left}px lands on the scene panel`);
});
test('a shown card follows its anchor through the renderer ports', () => {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {}; this.style = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
querySelector() { return null; }
getBoundingClientRect() { return { left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 }; }
append(...children) { for (const child of children) { child.remove(); child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const listeners = new Set();
const viewer = { canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
let pose = { position: { x: 0, y: 0, z: 0 }, direction: { x: 1, y: 0, z: 0 } };
const projected = [];
// The renderer's canvas, not the viewer's, places the card.
const unbind = bindRenderer(viewer, {
canvas: { getBoundingClientRect: () => ({ left: 10, top: 5 }) },
camera: { pose: () => pose },
query: { project: (p) => { projected.push(p); return { x: 300, y: 200 }; } },
frame: {
on(phase, cb) {
const entry = [phase, cb];
listeners.add(entry);
return () => listeners.delete(entry);
},
},
});
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef, globalRef: {} });
assert.deepEqual([...listeners].map(([phase]) => phase), ['postRender']);
const anchor = { x: 10, y: 0, z: 0 };
assert.equal(media.show({ observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor }), true);
const card = documentRef.body.children[0].children.find((node) => node.tag === 'section');
assert.equal(card.hidden, false);
assert.equal(projected.at(-1), anchor);
assert.equal(card.style.left, `${300 + 10 + 42}px`);
// Behind the eye: hidden on the next drawn frame.
pose = { ...pose, direction: { x: -1, y: 0, z: 0 } };
for (const [, cb] of listeners) cb();
assert.equal(card.hidden, true);
media.destroy();
assert.equal(listeners.size, 0);
unbind();
});
+294 -199
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { isPointerFree } from './inputOwnership.js';
import {
clearOverlaySource,
@@ -24,10 +23,21 @@ import {
resolveEmbeddedMediaSource,
} from './bhoteKoshiEmbeddedMedia.js';
import { acquireImageryComparison } from '../maps/imageryComparison.js';
import { createImagerySplit } from '../ui/imagerySplit.js';
import { createImagerySplit, globeSplitTarget } from '../ui/imagerySplit.js';
import { formatDate, t, tn, msg, onLocaleChange } from '../i18n/index.js';
import { useBhoteKoshiPanelStore } from '../ui/stores/bhoteKoshiPanel.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { heightsOf } from '../queries/heights.js';
import {
cameraOf,
canvasOf,
drawOf,
findCamera,
findGlobe,
} from '../render/rendererOf.js';
import { hexColor } from '../render/color.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import { clone, lerp, lerpInto, toRadians, vec } from '../geo/vector.js';
export const BHOTE_KOSHI_LAYER_ID = 'bhote-koshi-2026';
export const BHOTE_KOSHI_OVERLAY_SOURCE_ID = 'bhote-koshi-witnesses';
@@ -46,8 +56,24 @@ const SCENE_PATH_RENDER_HOLD = 'bhote-koshi-scene-path-travel';
const SCENE_MEDIA_MIN_PLAYBACK_SECONDS = 6;
const SCENE_MEDIA_EXIT_SECONDS = 0.65;
const BHOTE_EVENT_ACCENT = WORLD_OVERLAY_STYLE.accent;
const FLOOD_COLOR = Cesium.Color.fromCssColorString('#d8954e').withAlpha(0.68);
const SURGE_COLOR = Cesium.Color.fromCssColorString('#e8b47c');
const FLOOD_ACCENT = '#d8954e';
const FLOOD_HALO_COLOR = hexColor(FLOOD_ACCENT, 0.38);
const FLOOD_CORE_COLOR = hexColor(FLOOD_ACCENT, 0.96);
const SURGE_COLOR = hexColor('#e8b47c');
const SURGE_OUTLINE_COLOR = [0, 0, 0, 0.85];
const FLOOD_HALO_ID = 'bhote-koshi-flood-halo';
const FLOOD_CORE_ID = 'bhote-koshi-flood-core';
const SURGE_FRONT_ID = 'bhote-koshi-surge-front';
const IMAGERY_CREDIT = Object.freeze({
text: 'Vantor WorldView Open Data · CC BY-NC 4.0',
});
// Each layer's draw sets have ids of their own.
let layerSerial = 0;
/** Whether two positions are the same point; either may be null. */
const samePoint = (a, b) =>
a === b || (Boolean(a && b) && a.x === b.x && a.y === b.y && a.z === b.z);
const CINEMATIC_INPUT_EVENTS = Object.freeze(['pointerdown', 'wheel']);
const CINEMATIC_VIEW_SPECS = Object.freeze([
{
@@ -119,23 +145,25 @@ const DEFAULT_EVENT_LOADER = async () => {
throw new Error(`Bhote Koshi event pack unavailable (${response.status})`);
return response.json();
};
const DEFAULT_IMAGERY_PROVIDER_FACTORY = (url, options) =>
Cesium.SingleTileImageryProvider.fromUrl(url, options);
/** The globe port's spec for one of the event's images, over `rectangle`. */
const DEFAULT_IMAGERY_SPEC_FACTORY = (url, { rectangle, credit }) => ({
kind: 'single-image',
url,
rectangle,
credit,
});
/**
* Terrain heights under the observations, once the most detailed terrain
* has loaded. The bare ellipsoid answers no height, as there is no terrain
* to sample then.
*/
const DEFAULT_TERRAIN_SAMPLER = async (viewer, observations) => {
if (
!viewer?.terrainProvider ||
!viewer.terrainProvider.availability ||
typeof Cesium.sampleTerrainMostDetailed !== 'function'
) {
return null;
}
const cartographics = observations.map((observation) =>
Cesium.Cartographic.fromDegrees(observation.lon, observation.lat),
);
return Cesium.sampleTerrainMostDetailed(
viewer.terrainProvider,
cartographics,
);
if (!viewer) return null;
const heights = await heightsOf(viewer).batch(observations, {
against: 'terrain',
ellipsoidMisses: true,
});
return heights.map((height) => ({ height }));
};
const DEFAULT_MEDIA_LOADER = async (url, { signal } = {}) => {
if (typeof createImageBitmap !== 'function') {
@@ -187,7 +215,7 @@ export function visibleSegmentCount(progress, segmentCount) {
/**
* Build a corridor whose final vertex is the exact animated surge position.
* Returns true only when the Cesium polyline assignments need refreshing.
* Returns true only when the drawn corridor needs refreshing.
*/
export function updateCorridorPositionCache(progress, terrainPositions, cache) {
const positions = Array.isArray(terrainPositions) ? terrainPositions : [];
@@ -210,15 +238,15 @@ export function updateCorridorPositionCache(progress, terrainPositions, cache) {
const startIndex = Math.min(segmentCount - 1, Math.floor(scaledProgress));
const segmentProgress =
normalizedProgress >= 1 ? 1 : scaledProgress - startIndex;
cache.headPosition = Cesium.Cartesian3.lerp(
cache.headPosition = lerpInto(
positions[startIndex],
positions[startIndex + 1],
segmentProgress,
cache.headPosition || new Cesium.Cartesian3(),
cache.headPosition || vec(),
);
cache.positions = positions.slice(0, startIndex + 1);
if (segmentProgress > 0) {
cache.positions.push(Cesium.Cartesian3.clone(cache.headPosition));
cache.positions.push(clone(cache.headPosition));
}
return true;
}
@@ -525,19 +553,19 @@ export function sampleCinematicPose(progress, keyframes, result = {}) {
: (linearAmount - BHOTE_KOSHI_CAMERA_HOLD_RATIO) /
(1 - BHOTE_KOSHI_CAMERA_HOLD_RATIO);
const amount = travelAmount * travelAmount * (3 - 2 * travelAmount);
result.target = Cesium.Cartesian3.lerp(
result.target = lerpInto(
from.target,
to.target,
amount,
result.target || new Cesium.Cartesian3(),
result.target || vec(),
);
result.headingDeg = interpolateHeadingDegrees(
from.headingDeg,
to.headingDeg,
amount,
);
result.pitchDeg = Cesium.Math.lerp(from.pitchDeg, to.pitchDeg, amount);
result.rangeM = Cesium.Math.lerp(from.rangeM, to.rangeM, amount);
result.pitchDeg = lerp(from.pitchDeg, to.pitchDeg, amount);
result.rangeM = lerp(from.rangeM, to.rangeM, amount);
result.fromId = from.id;
result.toId = to.id;
return result;
@@ -891,25 +919,29 @@ function openExternal(url) {
function focusView(viewer, viewpoint) {
announceNavigationAuthority('bhote-koshi-event-focus');
const target = Cesium.Cartesian3.fromDegrees(
const target = fromDegrees(
viewpoint.lon,
viewpoint.lat,
viewpoint.targetElevationM,
);
const offset = new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(viewpoint.headingDeg),
Cesium.Math.toRadians(viewpoint.pitchDeg),
viewpoint.rangeM,
);
viewer.camera.cancelFlight?.();
viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(target, 80), {
offset,
duration: 2.2,
complete: () => {
viewer.camera.lookAt(target, offset);
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
const offset = {
heading: toRadians(viewpoint.headingDeg),
pitch: toRadians(viewpoint.pitchDeg),
range: viewpoint.rangeM,
};
const camera = cameraOf(viewer);
camera.cancelFlight();
camera.flyToBounds(
{ center: target, radius: 80 },
{
offset,
durationS: 2.2,
onComplete: () => {
camera.lookAt(target, offset);
camera.release();
},
},
});
);
}
function setElementProperty(element, property, value) {
@@ -987,7 +1019,7 @@ export function createBhoteKoshiEventLayer({
overlayHost = DEFAULT_OVERLAY_HOST,
renderHost = DEFAULT_RENDER_HOST,
eventLoader = DEFAULT_EVENT_LOADER,
imageryProviderFactory = DEFAULT_IMAGERY_PROVIDER_FACTORY,
imagerySpecFactory = DEFAULT_IMAGERY_SPEC_FACTORY,
terrainSampler = DEFAULT_TERRAIN_SAMPLER,
mediaLoader = DEFAULT_MEDIA_LOADER,
evidenceFrameFactory = createEvidenceFrame,
@@ -1013,12 +1045,19 @@ export function createBhoteKoshiEventLayer({
let _splitControl = null;
let _beforeLayer = null;
let _afterLayer = null;
let _imageryLayerCollection = null;
let _floodDataSource = null;
// An event image failed to load this enable: no comparison is shown.
let _imageryFailed = false;
const _serial = ++layerSerial;
// The flood's draw sets: the corridor's halo and core lines, and the
// surge front. Null while the layer is off.
let _floodSets = null;
let _floodSurfaceMode = null;
let _floodHalo = null;
let _floodCore = null;
let _surgePoint = null;
// What the flood shows, set as the event plays, and what was last drawn
// of it (`drawFlood`).
let _floodShow = false;
let _surgeShow = false;
let _surgePosition = null;
let _floodDrawn = null;
let _terrainPositions = [];
let _sourceShotPaths = new Map();
let _scenePathPositionCache = new Map();
@@ -1052,8 +1091,8 @@ export function createBhoteKoshiEventLayer({
let _cinematicKeyframes = [];
let _cinematicActive = false;
let _cinematicReplayArmed = false;
let _cinematicPose = { target: new Cesium.Cartesian3() };
let _cinematicOffset = new Cesium.HeadingPitchRange();
let _cinematicPose = { target: vec() };
const _cinematicOffset = { heading: 0, pitch: 0, range: 0 };
let _lastCinematicProgress = null;
let _cameraInputTarget = null;
let _evidenceClickTarget = null;
@@ -1068,7 +1107,6 @@ export function createBhoteKoshiEventLayer({
let _comparisonLease = null;
let _introTimer = null;
let _introGeneration = 0;
let _lastSurgePosition = null;
let _lastSurgeVisible = null;
let _presentation = 'standalone';
let _sceneBeatId = null;
@@ -1154,33 +1192,52 @@ export function createBhoteKoshiEventLayer({
}
async function createImagery(event) {
const rectangle = Cesium.Rectangle.fromDegrees(
event.imagery.rectangle.west,
event.imagery.rectangle.south,
event.imagery.rectangle.east,
event.imagery.rectangle.north,
);
const [beforeProvider, afterProvider] = await Promise.all([
imageryProviderFactory(eventAsset(event.imagery.before.path), {
rectangle,
credit: 'Vantor WorldView Open Data · CC BY-NC 4.0',
}),
imageryProviderFactory(eventAsset(event.imagery.after.path), {
rectangle,
credit: 'Vantor WorldView Open Data · CC BY-NC 4.0',
}),
_imageryFailed = false;
const { west, south, east, north } = event.imagery.rectangle;
const options = {
rectangle: { west, south, east, north },
credit: IMAGERY_CREDIT,
};
const [beforeSpec, afterSpec] = await Promise.all([
imagerySpecFactory(eventAsset(event.imagery.before.path), options),
imagerySpecFactory(eventAsset(event.imagery.after.path), options),
]);
if (!_enabled) return;
_imageryLayerCollection = _viewer.imageryLayers;
_beforeLayer = _imageryLayerCollection.addImageryProvider(beforeProvider);
_afterLayer = _imageryLayerCollection.addImageryProvider(afterProvider);
_beforeLayer.splitDirection = Cesium.SplitDirection.LEFT;
_afterLayer.splitDirection = Cesium.SplitDirection.RIGHT;
_beforeLayer.alpha = 0.96;
_afterLayer.alpha = 0.96;
const globe = findGlobe(_viewer);
if (!globe)
throw new Error('Bhote Koshi imagery needs a globe to drape on');
_beforeLayer = addEventImagery(globe, beforeSpec, 'left');
_afterLayer = addEventImagery(globe, afterSpec, 'right');
setSplit(_split);
}
/**
* One of the before/after images, on its side of the split, over every
* layer drawn so far. It drapes on the globe's surface only, as the
* comparison is drawn on terrain.
*/
function addEventImagery(globe, spec, split) {
const layer = globe.imagery.add(spec, globe.imagery.list().length);
layer.split = split;
layer.alpha = 0.96;
layer.drapeOn = 'surface';
layer.on('tileError', (error) => imageryFailed(error));
return layer;
}
/**
* An image that did not load: without both images there is nothing to
* compare, so the pair and the comparison's divider and labels go.
*/
function imageryFailed(error) {
if (_imageryFailed) return;
_imageryFailed = true;
console.warn('[Data:BhoteKoshi] Event imagery unavailable:', error);
removeImagery();
syncPresentationMode();
renderHost.request('bhote-koshi-imagery-failed');
}
async function resolveEvidenceAnchors(event, signal) {
const observations = Array.isArray(event.evidenceSpine)
? event.evidenceSpine
@@ -1197,9 +1254,10 @@ export function createBhoteKoshiEventLayer({
}
throwIfEnableCancelled(signal, _enabled);
return observations.map((observation, index) => {
const sampledHeight = Number(sampled?.[index]?.height);
// A miss is null or undefined, never sea level.
const sampledHeight = Number(sampled?.[index]?.height ?? Number.NaN);
const fallbackHeight = Number(observation.fallbackElevationM) || 0;
return Cesium.Cartesian3.fromDegrees(
return fromDegrees(
observation.lon,
observation.lat,
(Number.isFinite(sampledHeight) ? sampledHeight : fallbackHeight) + 18,
@@ -1240,7 +1298,7 @@ export function createBhoteKoshiEventLayer({
function showWitnessEmbed() {
const witness = _event?.witnessAnchors?.[0];
if (!witness?.sourceUrl) return false;
const anchor = Cesium.Cartesian3.fromDegrees(
const anchor = fromDegrees(
witness.lon,
witness.lat,
(Number(witness.elevationM) || 0) + 18,
@@ -1566,24 +1624,21 @@ export function createBhoteKoshiEventLayer({
const cached = _scenePathPositionCache.get(cacheKey);
if (cached) return cached;
const positions = (_sourceShotPaths.get(beatId) || []).map((point) => {
const position = Cesium.Cartographic.fromDegrees(point.lon, point.lat);
const position = { lon: point.lon, lat: point.lat };
let height;
// Some schematic reaches have a source elevation profile. Do not replace
// it with coarse mesh heights on entry/exit from the comparison surface:
// a single high sample can make the front dive backward in screen space.
if (_sceneControls.evidencePathElevation !== 'source') {
// Sample once while preparing the shot, never from an animation frame.
try {
height = _viewer?.scene?.sampleHeight?.(
position,
[_floodCore, _floodHalo, _surgePoint].filter(Boolean),
);
} catch {}
// The flood's own sets are not ground: queries see through them.
const heights = _viewer ? heightsOf(_viewer) : null;
height = heights?.now(position);
if (!Number.isFinite(height))
height = _viewer?.scene?.globe?.getHeight?.(position);
height = heights?.now(position, { against: 'terrain' });
}
if (!Number.isFinite(height)) height = point.fallbackElevationM;
return Cesium.Cartesian3.fromDegrees(point.lon, point.lat, height + 8);
return fromDegrees(point.lon, point.lat, height + 8);
});
_scenePathPositionCache.set(cacheKey, positions);
return positions;
@@ -2480,11 +2535,7 @@ export function createBhoteKoshiEventLayer({
const elevationOffsetM =
_presentation === BHOTE_KOSHI_SCENE_PRESENTATION ? 55 : 8;
_terrainPositions = event.reconstruction.corridor.map((point) =>
Cesium.Cartesian3.fromDegrees(
point.lon,
point.lat,
point.elevationM + elevationOffsetM,
),
fromDegrees(point.lon, point.lat, point.elevationM + elevationOffsetM),
);
prepareScenePath();
_evidenceTimeline = buildEvidenceTimeline(
@@ -2522,86 +2573,144 @@ export function createBhoteKoshiEventLayer({
updateProgress(_progress);
}
function createFloodDataSource() {
const tileSafe = usesPhotorealFloodSurface();
_floodSurfaceMode = tileSafe ? 'tiles' : 'terrain';
const haloMaterial = new Cesium.PolylineDashMaterialProperty({
color: FLOOD_COLOR.withAlpha(0.38),
dashLength: 18,
});
const coreMaterial = new Cesium.PolylineGlowMaterialProperty({
color: FLOOD_COLOR.withAlpha(0.96),
glowPower: 0.24,
taperPower: 0.7,
});
_floodDataSource = new Cesium.CustomDataSource('bhote-koshi-flood');
_floodHalo = _floodDataSource.entities.add({
id: 'bhote-koshi-flood-halo',
/** The flood's draw sets, drawing nothing until the event shows it. */
function createFloodSets() {
_floodSurfaceMode = usesPhotorealFloodSurface() ? 'tiles' : 'terrain';
const draw = drawOf(_viewer);
const prefix = `${BHOTE_KOSHI_LAYER_ID}:${_serial}`;
// Presentation only: clicks go through to what is under them.
_floodSets = {
lines: draw.lines({ id: `${prefix}:flood`, pickable: false }),
surge: draw.points({
id: `${prefix}:surge-front`,
pickable: false,
clampTo: 'both',
}),
};
resetFloodDrawn();
}
function resetFloodDrawn() {
_floodShow = false;
_surgeShow = false;
_surgePosition = null;
_lastSurgeVisible = null;
_floodDrawn = {
positions: null,
show: false,
polyline: {
positions: new Cesium.CallbackProperty(
() => _corridorPositionCache.positions,
false,
),
width: 18,
// Dynamic non-ground Cesium lines do not support depthFailMaterial.
// Classify the active surface so later-refined mesh tiles cannot bury it.
clampToGround: true,
material: haloMaterial,
classificationType: tileSafe
? Cesium.ClassificationType.BOTH
: Cesium.ClassificationType.TERRAIN,
surge: null,
surgeShow: false,
};
}
function removeFloodSets() {
_floodSets?.lines.dispose();
_floodSets?.surge.dispose();
_floodSets = null;
_floodSurfaceMode = null;
resetFloodDrawn();
}
/**
* The corridor's lines along `positions`: a dashed halo under a glowing
* core, draped on the surface the flood is drawn on (tiles too under
* photoreal, so later-refined tiles cannot bury it).
*/
function floodLines(positions, show) {
const clampTo = _floodSurfaceMode === 'tiles' ? 'both' : 'terrain';
return [
{
id: FLOOD_HALO_ID,
positions,
widthPx: 18,
mode: 'draped',
clampTo,
style: { kind: 'dash', color: FLOOD_HALO_COLOR, length: 18 },
show,
},
});
_floodCore = _floodDataSource.entities.add({
id: 'bhote-koshi-flood-core',
show: false,
polyline: {
positions: new Cesium.CallbackProperty(
() => _corridorPositionCache.positions,
false,
),
width: 5,
clampToGround: true,
material: coreMaterial,
classificationType: tileSafe
? Cesium.ClassificationType.BOTH
: Cesium.ClassificationType.TERRAIN,
{
id: FLOOD_CORE_ID,
positions,
widthPx: 5,
mode: 'draped',
clampTo,
style: {
kind: 'glow',
color: FLOOD_CORE_COLOR,
power: 0.24,
taper: 0.7,
},
show,
},
});
_surgePoint = _floodDataSource.entities.add({
id: 'bhote-koshi-surge-front',
show: false,
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize: 11,
color: SURGE_COLOR,
outlineColor: Cesium.Color.BLACK.withAlpha(0.85),
outlineWidth: 3,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: tileSafe ? Number.POSITIVE_INFINITY : 0,
},
});
_viewer.dataSources.add(_floodDataSource);
];
}
function surgeItem(position, show) {
return {
id: SURGE_FRONT_ID,
pos: position,
height: 'clampGround',
pixelSize: 11,
color: SURGE_COLOR,
outlineColor: SURGE_OUTLINE_COLOR,
outlineWidth: 3,
disableDepthTest:
_floodSurfaceMode === 'tiles' ? Number.POSITIVE_INFINITY : 0,
show,
};
}
/**
* Draw the flood as it now stands, changing only what changed: the
* corridor where it has grown to and whether it shows, and the surge
* front's place and whether it shows.
*/
function drawFlood() {
if (!_floodSets) return;
const drawn = _floodDrawn;
const positions = _corridorPositionCache.positions;
if (positions.length > 1) {
if (positions !== drawn.positions || _floodShow !== drawn.show) {
_floodSets.lines.upsert(floodLines(positions, _floodShow));
drawn.positions = positions;
drawn.show = _floodShow;
}
} else if (drawn.show) {
// Too short to be a line: the last one drawn hides, kept so the next
// can still be drawn where it moves in the same frame.
_floodSets.lines.upsert(floodLines(drawn.positions, false));
drawn.show = false;
}
if (
_surgePosition &&
(!samePoint(_surgePosition, drawn.surge) ||
_surgeShow !== drawn.surgeShow)
) {
drawn.surge = _surgePosition;
drawn.surgeShow = _surgeShow;
_floodSets.surge.upsert([surgeItem(drawn.surge, _surgeShow)]);
}
}
function syncFloodSurfaceMode() {
const nextMode = usesPhotorealFloodSurface() ? 'tiles' : 'terrain';
if (!_viewer || !_floodDataSource || _floodSurfaceMode === nextMode) return;
_viewer.dataSources.remove(_floodDataSource, true);
_floodDataSource = null;
_floodHalo = null;
_floodCore = null;
_surgePoint = null;
_lastSurgePosition = null;
_lastSurgeVisible = null;
if (!_viewer || !_floodSets || _floodSurfaceMode === nextMode) return;
// Drawn anew on the other surface as the event next moves on.
removeFloodSets();
_corridorPositionCache = { visibleCount: -1, positions: [] };
createFloodDataSource();
createFloodSets();
}
/** The canvas the scene is drawn on, for its pointer events. */
function sceneCanvas() {
if (!_viewer) return null;
return canvasOf(_viewer);
}
function createSplitControl(event) {
_splitControl = createImagerySplit({
scene: _viewer.scene,
// The split as the divider moves it: the globe's, through its port.
scene: globeSplitTarget(findGlobe(_viewer)),
initialValue: _split,
id: 'bhote-koshi-split-line',
handleClass: 'bhote-koshi-split-handle',
@@ -2621,7 +2730,7 @@ export function createBhoteKoshiEventLayer({
function applyCinematicCamera() {
if (
!_cinematicActive ||
!_viewer?.camera ||
!findCamera(_viewer) ||
_cinematicKeyframes.length === 0
)
return;
@@ -2632,10 +2741,10 @@ export function createBhoteKoshiEventLayer({
_cinematicPose,
);
if (!pose) return;
_cinematicOffset.heading = Cesium.Math.toRadians(pose.headingDeg);
_cinematicOffset.pitch = Cesium.Math.toRadians(pose.pitchDeg);
_cinematicOffset.heading = toRadians(pose.headingDeg);
_cinematicOffset.pitch = toRadians(pose.pitchDeg);
_cinematicOffset.range = pose.rangeM;
_viewer.camera.lookAt(pose.target, _cinematicOffset);
findCamera(_viewer)?.lookAt(pose.target, _cinematicOffset);
_lastCinematicProgress = _progress;
}
@@ -2705,7 +2814,7 @@ export function createBhoteKoshiEventLayer({
_cinematicActive = true;
_lastCinematicProgress = null;
announceNavigationAuthority('bhote-koshi-cinematic');
_viewer?.camera?.cancelFlight?.();
findCamera(_viewer)?.cancelFlight();
}
syncCinematicButton();
return true;
@@ -2722,8 +2831,7 @@ export function createBhoteKoshiEventLayer({
}
_cinematicActive = false;
_lastCinematicProgress = null;
if (releaseCamera)
_viewer?.camera?.lookAtTransform?.(Cesium.Matrix4.IDENTITY);
if (releaseCamera) findCamera(_viewer)?.release();
syncCinematicButton();
renderHost.request('bhote-koshi-cinematic-stop');
}
@@ -2757,7 +2865,7 @@ export function createBhoteKoshiEventLayer({
}
function attachCameraInputRelease() {
_cameraInputTarget = _viewer?.scene?.canvas || null;
_cameraInputTarget = sceneCanvas();
for (const type of CINEMATIC_INPUT_EVENTS) {
_cameraInputTarget?.addEventListener?.(type, handleManualCameraInput);
}
@@ -2803,7 +2911,7 @@ export function createBhoteKoshiEventLayer({
}
function attachEvidenceCardActivation() {
_evidenceClickTarget = _viewer?.scene?.canvas || null;
_evidenceClickTarget = sceneCanvas();
_evidenceClickTarget?.addEventListener?.('click', handleEvidenceCardClick);
}
@@ -3252,7 +3360,8 @@ export function createBhoteKoshiEventLayer({
function syncPresentationMode() {
const sceneDirected = _presentation === BHOTE_KOSHI_SCENE_PRESENTATION;
const imageryAvailable =
!sceneDirected || _sceneControls.imageryComparison === true;
!_imageryFailed &&
(!sceneDirected || _sceneControls.imageryComparison === true);
const scrubberAvailable =
!sceneDirected || Boolean(_sceneController?.seekScene);
const knownSceneBeat =
@@ -3302,13 +3411,13 @@ export function createBhoteKoshiEventLayer({
}
function updateFloodTrace(progress) {
if (!_floodHalo || !_floodCore) return;
if (!_floodSets) return;
if (
_presentation === BHOTE_KOSHI_SCENE_PRESENTATION &&
_sceneSurface !== BHOTE_KOSHI_SCENE_EVIDENCE_BEAT
) {
_floodHalo.show = false;
_floodCore.show = false;
_floodShow = false;
drawFlood();
return;
}
if (
@@ -3319,31 +3428,24 @@ export function createBhoteKoshiEventLayer({
)
)
return;
const positions = _corridorPositionCache.positions;
_floodHalo.show = positions.length > 1;
_floodCore.show = positions.length > 1;
_floodShow = _corridorPositionCache.positions.length > 1;
drawFlood();
}
function updateSurgeFront(progress) {
if (!_surgePoint) return;
if (!_floodSets) return;
if (
_presentation === BHOTE_KOSHI_SCENE_PRESENTATION &&
_sceneSurface !== BHOTE_KOSHI_SCENE_EVIDENCE_BEAT
) {
_surgePoint.show = false;
_surgeShow = false;
drawFlood();
return;
}
const headPosition = _corridorPositionCache.headPosition;
if (
headPosition &&
!Cesium.Cartesian3.equals(_lastSurgePosition, headPosition)
) {
_surgePoint.position = headPosition;
_lastSurgePosition = Cesium.Cartesian3.clone(
headPosition,
_lastSurgePosition || new Cesium.Cartesian3(),
);
}
// A copy, as the cache's head is written in place as the flood moves.
if (headPosition && !samePoint(_surgePosition, headPosition))
_surgePosition = clone(headPosition);
const visible =
Boolean(headPosition) &&
progress > 0 &&
@@ -3352,9 +3454,10 @@ export function createBhoteKoshiEventLayer({
sceneKeepsFloodVisible() ||
progress < 1);
if (_lastSurgeVisible !== visible) {
_surgePoint.show = visible;
_surgeShow = visible;
_lastSurgeVisible = visible;
}
drawFlood();
}
function updateProgress(progress) {
@@ -3455,11 +3558,10 @@ export function createBhoteKoshiEventLayer({
}
function removeImagery() {
if (_beforeLayer) _imageryLayerCollection?.remove(_beforeLayer, true);
if (_afterLayer) _imageryLayerCollection?.remove(_afterLayer, true);
_beforeLayer?.remove();
_afterLayer?.remove();
_beforeLayer = null;
_afterLayer = null;
_imageryLayerCollection = null;
}
async function init(viewer) {
@@ -3493,7 +3595,7 @@ export function createBhoteKoshiEventLayer({
throwIfEnableCancelled(signal, _enabled);
await syncTerrainComparison();
throwIfEnableCancelled(signal, _enabled);
createFloodDataSource();
createFloodSets();
createSplitControl(event);
_panelRefs = createPanelRecords(event);
_panelOwner = {};
@@ -3618,14 +3720,7 @@ export function createBhoteKoshiEventLayer({
closeFrame(slot.poster);
}
_evidenceFrameSlots = [];
if (_floodDataSource) _viewer.dataSources.remove(_floodDataSource, true);
_floodDataSource = null;
_floodSurfaceMode = null;
_floodHalo = null;
_floodCore = null;
_surgePoint = null;
_lastSurgePosition = null;
_lastSurgeVisible = null;
removeFloodSets();
if (_panelOwner && panelStore.panel?.owner === _panelOwner) {
panelStore.connect(null);
panelStore.publish(null);
+291 -135
View File
@@ -1,3 +1,6 @@
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { fakeGlobePort } from '../testSupport/fakeGlobePort.mjs';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
@@ -231,16 +234,27 @@ function installEventDom() {
return { body, removedProperties };
}
function eventViewer(splitPosition = 0.37) {
const imagery = [];
const removedImagery = [];
const dataSources = [];
const removedDataSources = [];
/**
* A viewer with fake draw and globe ports bound, under the Cesium camera
* port over a fake camera. `_test` reads what the event draws: its imagery
* layers (`imagery`, `removedImagery`), its flood sets (`floodSets`, live
* or not) and a flood item by id (`flood`); `scene.splitPosition` is the
* globe's split.
*/
function eventViewer(splitPosition = 0.37, ports = {}) {
const draw = fakeDrawPort();
const globe = fakeGlobePort();
globe.imagery.setSplit(splitPosition);
const canvas = new FakeElement('canvas');
const cameraLooks = [];
const cameraTransforms = [];
return {
scene: { splitPosition, canvas },
const floodSets = () => [...draw.sets.values()].filter(({ spec }) => spec.id.startsWith(`${BHOTE_KOSHI_LAYER_ID}:`));
const liveFloodSets = () => floodSets().filter((set) => !set.disposed);
const viewer = {
scene: {
get splitPosition() { return globe.imagery.getSplit(); },
canvas,
},
camera: {
cancelFlight() {},
lookAt(target, offset) {
@@ -251,28 +265,38 @@ function eventViewer(splitPosition = 0.37) {
},
lookAtTransform(transform) { cameraTransforms.push(transform); },
},
imageryLayers: {
addImageryProvider(provider) {
const layer = { provider };
imagery.push(layer);
return layer;
},
remove(layer) { removedImagery.push(layer); },
},
dataSources: {
add(source) { dataSources.push(source); },
remove(source) { removedDataSources.push(source); },
},
_test: {
imagery,
removedImagery,
dataSources,
removedDataSources,
draw,
globe,
imagery: globe.added,
get removedImagery() { return globe.added.filter((layer) => layer.removed); },
floodSets,
liveFloodSets,
/** The live flood item with this id, or undefined. */
flood(id) {
for (const set of liveFloodSets()) if (set.items.has(id)) return set.items.get(id);
return undefined;
},
/** Reads the flood item with this id as it is drawn now: whether it shows, its positions or position. */
floodView(id) {
const view = viewer._test;
return {
get show() { return view.floodShows(id); },
get positions() { return view.flood(id)?.positions; },
get position() { return view.flood(id)?.pos; },
};
},
/** Whether the flood item with this id is drawn showing. */
floodShows(id) {
for (const set of liveFloodSets()) if (set.items.has(id)) return set.items.get(id).show !== false;
return false;
},
canvas,
cameraLooks,
cameraTransforms,
},
};
return bindFakeCesiumCamera(viewer, { draw, globe, ...ports });
}
test('public lifecycle restores Nepal scene ownership without forwarding origin to enable', async () => {
@@ -293,7 +317,7 @@ test('public lifecycle restores Nepal scene ownership without forwarding origin
const mapCalls = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { const error = new Error('No bundled clip'); error.name = 'AbortError'; throw error; },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -316,16 +340,11 @@ test('public lifecycle restores Nepal scene ownership without forwarding origin
assert.equal(layer.getPlaybackState().enabled, true);
assert.deepEqual(mapCalls, [], `${initialMap}/${origin}: preserve the shot map`);
assert.equal(activeMap, initialMap);
const floodSource = viewer._test.dataSources.at(-1);
for (const id of ['bhote-koshi-flood-halo', 'bhote-koshi-flood-core']) {
const line = floodSource.entities.getById(id).polyline;
assert.equal(line.clampToGround.getValue(), true, 'dynamic trail follows the rendered surface');
assert.equal(line.classificationType.getValue(), initialMap === 'photoreal'
? Cesium.ClassificationType.BOTH : Cesium.ClassificationType.TERRAIN);
assert.equal(line.depthFailMaterial, undefined, 'do not rely on unsupported dynamic depth-fail rendering');
}
assert.equal(floodSource.entities.getById('bhote-koshi-surge-front').point.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND);
const floodSets = viewer._test.liveFloodSets();
assert.deepEqual(floodSets.map(({ kind }) => kind), ['lines', 'points']);
assert.ok(floodSets.every(({ spec }) => spec.pickable === false));
assert.equal(floodSets[1].spec.clampTo, 'both', 'the surge front clamps to the ground');
assert.ok(floodSets.every(({ items }) => items.size === 0), 'a panel-only shot draws no flood');
assert.deepEqual(viewer._test.cameraLooks, [], 'enable must not focus the corridor');
assert.deepEqual(timers, [], 'enable must not schedule independent playback');
assert.equal(layer.getPlaybackState().playing, false);
@@ -355,7 +374,7 @@ test('trimmed scene media holds through provider startup, playback and fade, the
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { const error = new Error('No bundled clip'); error.name = 'AbortError'; throw error; },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -403,7 +422,7 @@ test('Pinokio source-card fallback selects authored Director dwell, not an impos
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async url => ({ url }),
imagerySpecFactory: async url => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { throw Object.assign(new Error('No bundled clip'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -448,7 +467,7 @@ test('saved autoplay controls cannot authorize media; live shot ownership is can
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async url => ({ url }),
imagerySpecFactory: async url => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { throw Object.assign(new Error('No bundled clip'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -838,12 +857,10 @@ test('Bhote Koshi failed direct enable restores the prior map and shared split',
let generation = 7;
const viewer = {
scene: { splitPosition: 0.37 },
imageryLayers: { remove() {} },
dataSources: { remove() {} },
};
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async () => { throw new Error('fixture image failure'); },
imagerySpecFactory: async () => { throw new Error('fixture image failure'); },
overlayHost: {
setEntries() {},
setVisible(id, visible) { overlayCalls.push(['visible', id, visible]); },
@@ -946,7 +963,7 @@ test('Bhote Koshi disable preserves an operator-selected map and tears down ever
const renderCalls = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
overlayHost: {
setEntries() {},
setVisible(id, visible) { overlayCalls.push(['visible', id, visible]); },
@@ -971,7 +988,7 @@ test('Bhote Koshi disable preserves an operator-selected map and tears down ever
try {
assert.equal(await layer.enable(viewer, { origin: 'scene' }), true);
assert.equal(viewer._test.imagery.length, 2);
assert.equal(viewer._test.dataSources.length, 1);
assert.equal(viewer._test.floodSets().length, 2);
assert.ok(eventPanel());
assert.ok(eventSplit());
@@ -981,7 +998,7 @@ test('Bhote Koshi disable preserves an operator-selected map and tears down ever
assert.deepEqual(mapCalls, ['esri-imagery']);
assert.equal(viewer._test.removedImagery.length, 2);
assert.equal(viewer._test.removedDataSources.length, 1);
assert.equal(viewer._test.liveFloodSets().length, 0, 'its flood sets let go');
assert.equal(eventPanel(), undefined);
assert.equal(eventSplit(), undefined);
assert.equal(viewer.scene.splitPosition, 0.37);
@@ -1013,7 +1030,7 @@ test('Bhote Koshi disable stops active playback and releases its global render h
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderHost: {
request() {},
@@ -1071,7 +1088,7 @@ test('Bhote Koshi passive restores do not start off-screen playback', async () =
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
embeddedMediaFactory: () => ({ show() {}, hide() {}, pause() {}, destroy() {} }),
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderHost: { request() {}, hold() {}, release() {} },
@@ -1120,7 +1137,7 @@ test('Bhote Koshi standalone Scene keeps its Esri cinematic contract', async ()
const mapCalls = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1195,7 +1212,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership
const overlayVisibility = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1375,7 +1392,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership
'bhote-koshi-flood-core',
'bhote-koshi-surge-front',
]) {
assert.equal(viewer._test.dataSources[0].entities.getById(id).show, false);
assert.equal(viewer._test.floodShows(id), false);
}
panel.querySelector('[data-action="play"]').dispatch('click');
await Promise.resolve();
@@ -1464,9 +1481,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership
assert.ok(entries
.filter((entry) => entry.id.startsWith('evidence-breadcrumb-'))
.every((entry) => entry.position() == null));
assert.equal(viewer._test.dataSources.filter((source) => (
!viewer._test.removedDataSources.includes(source)
)).length, 1, 'surface transitions leave exactly one active event surface');
assert.equal(viewer._test.liveFloodSets().length, 2, 'surface transitions leave exactly one active event surface');
assert.equal(viewer._test.cameraLooks.length, 0, 'consecutive beats never write the camera');
}
panel.querySelector('[data-action="open-source"]').dispatch('click');
@@ -1485,7 +1500,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership
'disable revokes the pending real-time scene-clock scrub frame',
);
assert.deepEqual(mapCalls, []);
assert.equal(viewer._test.removedDataSources.length, viewer._test.dataSources.length);
assert.equal(viewer._test.liveFloodSets().length, 0);
} finally {
globalThis.document = originalDocument;
globalThis.window = originalWindow;
@@ -1506,7 +1521,7 @@ test('Nepal hybrid comparison preserves native split and terrain-clamped flood t
const comparisonCalls = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1540,17 +1555,17 @@ test('Nepal hybrid comparison preserves native split and terrain-clamped flood t
assert.equal(viewer._test.imagery.length, 2);
assert.ok(viewer._test.imagery.every((imageryLayer) => imageryLayer.show === true));
assert.equal(viewer.scene.splitPosition, 0.5);
assert.equal(viewer._test.imagery[0].splitDirection, Cesium.SplitDirection.LEFT);
assert.equal(viewer._test.imagery[1].splitDirection, Cesium.SplitDirection.RIGHT);
assert.equal(viewer._test.imagery[0].split, 'left');
assert.equal(viewer._test.imagery[1].split, 'right');
assert.ok(viewer._test.imagery.every((imageryLayer) => imageryLayer.alpha === 0.96 && imageryLayer.drapeOn === 'surface'));
layer.setParams({ split: 0.25 });
assert.equal(viewer.scene.splitPosition, 0.25);
const flood = viewer._test.dataSources[0].entities.getById('bhote-koshi-flood-core');
const surge = viewer._test.dataSources[0].entities.getById('bhote-koshi-surge-front');
assert.equal(flood.polyline.clampToGround.getValue(), true);
assert.equal(
surge.point.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND,
);
const flood = viewer._test.flood('bhote-koshi-flood-core');
const surge = viewer._test.flood('bhote-koshi-surge-front');
assert.equal(flood.mode, 'draped');
assert.equal(flood.clampTo, 'terrain', 'the comparison surface is terrain');
assert.equal(surge.height, 'clampGround');
assert.equal(surge.disableDepthTest, 0);
layer.setParams({
presentation: 'scene-beat',
@@ -1561,9 +1576,12 @@ test('Nepal hybrid comparison preserves native split and terrain-clamped flood t
assert.ok(viewer._test.imagery.every((imageryLayer) => imageryLayer.show === false));
assert.equal(comparisonCalls.at(-1), null);
const tileFlood = viewer._test.dataSources.at(-1).entities.getById('bhote-koshi-flood-core');
assert.equal(tileFlood.polyline.clampToGround.getValue(), true);
assert.equal(tileFlood.polyline.classificationType.getValue(), Cesium.ClassificationType.BOTH);
assert.equal(viewer._test.flood('bhote-koshi-flood-core'), undefined, 'drawn anew on the tiles as the event plays');
layer.setParams({ progress: 0.6 }, { origin: 'scene' });
const tileFlood = viewer._test.flood('bhote-koshi-flood-core');
assert.equal(tileFlood.mode, 'draped');
assert.equal(tileFlood.clampTo, 'both', 'photoreal drapes it on tiles too');
assert.equal(viewer._test.flood('bhote-koshi-surge-front').disableDepthTest, Number.POSITIVE_INFINITY);
await layer.disable();
assert.equal(viewer._test.removedImagery.length, 2);
@@ -1650,7 +1668,7 @@ test('Bhote Koshi publishes the evidence spine once and scrubs through cards and
const publications = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1747,7 +1765,7 @@ test('Bhote Koshi keeps one local fallback video active and unloads it on beat c
};
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1848,7 +1866,7 @@ test('Upper Valley Collapse autoplays its muted local fallback without starting
};
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1924,7 +1942,7 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
let activeCard = null;
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2015,7 +2033,7 @@ test('Nepal evidence shots resume the standalone callout and flood sequence from
const releases = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2073,8 +2091,8 @@ test('Nepal evidence shots resume the standalone callout and flood sequence from
layer.setSceneMediaPlayback({ sceneId: 'scene', shotId: 'shot', token: { cancelled: false } });
await layer.enable(viewer, { origin: 'scene' });
const card = entries.find(({ id }) => id === 'evidence-card-gyirong-border-gate');
const flood = viewer._test.dataSources[0].entities.getById('bhote-koshi-flood-core');
const surge = viewer._test.dataSources[0].entities.getById('bhote-koshi-surge-front');
const flood = viewer._test.floodView('bhote-koshi-flood-core');
const surge = viewer._test.floodView('bhote-koshi-surge-front');
assert.equal(card.position(), null, 'the evidence card is absent during the camera flight');
assert.equal(flood.show, false);
assert.equal(surge.show, false);
@@ -2186,7 +2204,7 @@ test('Bhote Koshi beat controls keep cards, flood, camera, and panel on the one
const publications = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2239,8 +2257,8 @@ test('Bhote Koshi beat controls keep cards, flood, camera, and panel on the one
panel.querySelector('[data-role="beat-meta"]').textContent,
'PROPAGATION / TIME UNVERIFIED / 5 SOURCES',
);
const flood = viewer._test.dataSources[0].entities.getById('bhote-koshi-flood-core');
assert.ok(flood.polyline.positions.getValue().length > 1);
const flood = viewer._test.floodView('bhote-koshi-flood-core');
assert.ok(flood.positions.length > 1);
assert.equal(
body.children.some((element) => element.id === 'bhote-koshi-story-strap'),
false,
@@ -2306,7 +2324,7 @@ test('Bhote Koshi repeated event frames republish no panel and churn no camera',
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2336,7 +2354,10 @@ test('Bhote Koshi repeated event frames republish no panel and churn no camera',
const panelStore = useBhoteKoshiPanelStore(applicationPinia());
const published = panelStore.panel;
const cameraLookCount = viewer._test.cameraLooks.length;
const floodWrites = () => viewer._test.liveFloodSets().map(({ writes }) => writes);
const drawnWrites = floodWrites();
for (let index = 0; index < 20; index += 1) progress.dispatch('input');
assert.deepEqual(floodWrites(), drawnWrites, 'unchanged frames draw no flood again');
assert.ok(panelStore.panel === published, 'unchanged frames do not republish the panel');
assert.equal(
@@ -2389,7 +2410,7 @@ test('Bhote Koshi cinematic camera stays synchronized through pause and determin
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2470,7 +2491,7 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2552,7 +2573,7 @@ test('Bhote Koshi closes a poster that resolves after disable', async () => {
const poster = { closed: false, close() { this.closed = true; } };
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async () => [{ height: 2800 }],
mediaLoader: async (url) => {
assert.equal(url, '/events/bhote-koshi-2026/evidence-09.jpg');
@@ -2592,13 +2613,15 @@ test('every sourced shot grows its tail with its head, keeps its own card, and c
globalThis.performance = { now: () => now };
globalThis.requestAnimationFrame = (callback) => { frames.set(++nextFrame, callback); return nextFrame; };
globalThis.cancelAnimationFrame = (id) => frames.delete(id);
const viewer = eventViewer();
let heightSamples = 0;
viewer.scene.sampleHeight = () => { heightSamples++; return 1500; };
let surfaceHeight = 1500;
const viewer = eventViewer(0.37, {
query: { sampleHeightNow: () => { heightSamples++; return surfaceHeight; } },
});
let entries = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async () => null,
mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); },
overlayHost: { setEntries(_id, value) { entries = value; }, setVisible() {}, clearSource() {} },
@@ -2618,23 +2641,23 @@ test('every sourced shot grows its tail with its head, keeps its own card, and c
try {
layer.setParams(params(SOURCE_PATH_BEAT_IDS[0], false));
await layer.enable(viewer, { origin: 'scene' });
const source = viewer._test.dataSources.at(-1);
const flood = source.entities.getById('bhote-koshi-flood-core');
const surge = source.entities.getById('bhote-koshi-surge-front');
const flood = viewer._test.floodView('bhote-koshi-flood-core');
const surge = viewer._test.floodView('bhote-koshi-surge-front');
for (const id of SOURCE_PATH_BEAT_IDS) {
layer.setParams(params(id, false));
assert.equal(flood.show, false, `${id}: hide the previous route during flight`);
assert.equal(surge.show, false);
layer.setParams(params(id, true));
const sampleCount = heightSamples;
assert.ok(sampleCount > 0, 'surface heights are sampled while preparing the shot');
let previousLength = 0;
for (const elapsed of [400, 1800, 4000]) {
advance(elapsed);
const points = flood.polyline.positions.getValue();
const points = flood.positions;
assert.ok(points.length >= previousLength);
assert.equal(flood.show, true);
assert.equal(surge.show, true);
assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position.getValue()), `${id}: tail must reach head in every frame`);
assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position), `${id}: tail must reach head in every frame`);
previousLength = points.length;
}
assert.equal(heightSamples, sampleCount, 'do not resample geometry during motion');
@@ -2649,28 +2672,27 @@ test('every sourced shot grows its tail with its head, keeps its own card, and c
assert.equal(flood.show, false, 'new shot clears its tail before the first animation frame');
assert.equal(surge.show, false);
advance(1800);
const headBeforeSync = Cesium.Cartesian3.clone(surge.position.getValue());
const headBeforeSync = Cesium.Cartesian3.clone(surge.position);
const frameBeforeSync = nextFrame;
layer.setParams(params('dhunche', true));
assert.equal(nextFrame, frameBeforeSync, 'repeated settled notification does not restart the reveal');
assert.ok(Cesium.Cartesian3.equals(headBeforeSync, surge.position.getValue()));
assert.ok(Cesium.Cartesian3.equals(headBeforeSync, surge.position));
advance(2200);
assert.ok(!Cesium.Cartesian3.equals(headBeforeSync, surge.position.getValue()));
assert.ok(!Cesium.Cartesian3.equals(headBeforeSync, surge.position));
// The comparison exit can expose coarse photogrammetry samples a kilometre
// above the river. Dhunche's schematic profile must not dive through them.
viewer.scene.sampleHeight = () => { heightSamples++; return 2703; };
viewer.scene.globe = { getHeight: () => 0 };
surfaceHeight = 2703;
layer.setParams(params('dhunche', false, 'source', 'source'));
const samplesBeforeProfile = heightSamples;
layer.setParams(params('dhunche', true, 'source', 'source'));
for (const elapsed of [40, 400, 1800, 4000]) {
advance(elapsed);
const points = flood.polyline.positions.getValue();
const points = flood.positions;
for (const position of points) {
const height = Cesium.Cartographic.fromCartesian(position).height;
assert.ok(height >= 1307 && height <= 1332, `source profile stays near river elevation, got ${height}`);
}
assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position.getValue()));
assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position));
}
assert.equal(heightSamples, samplesBeforeProfile, 'source elevation does not sample the changing mesh');
layer.setParams(params('charaudi', false, 'none'));
@@ -2700,7 +2722,7 @@ test('media-led upper-valley shots retain only their upstream prefix during came
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async url => ({ url }),
imagerySpecFactory: async url => ({ url }),
terrainSampler: async () => null,
mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -2725,12 +2747,11 @@ test('media-led upper-valley shots retain only their upstream prefix during came
try {
layer.setParams(params('debris-dammed-lake', false));
await layer.enable(viewer, { origin: 'scene' });
const source = viewer._test.dataSources.at(-1);
const flood = source.entities.getById('bhote-koshi-flood-core');
const surge = source.entities.getById('bhote-koshi-surge-front');
const flood = viewer._test.floodView('bhote-koshi-flood-core');
const surge = viewer._test.floodView('bhote-koshi-surge-front');
layer.setParams(params('debris-dammed-lake', true));
finishReveal();
const lakeTail = flood.polyline.positions.getValue().map(point => Cesium.Cartesian3.clone(point));
const lakeTail = flood.positions.map(({ x, y, z }) => ({ x, y, z }));
assert.ok(lakeTail.length > 1);
const origin = Cesium.Cartographic.fromCartesian(lakeTail[0]);
assert.ok(Math.abs(Cesium.Math.toDegrees(origin.longitude) - 85.48476) < 1e-6);
@@ -2738,16 +2759,16 @@ test('media-led upper-valley shots retain only their upstream prefix during came
'the rendered trail starts at the lake reach, not the earlier trigger reach');
layer.setParams(params('second-landslide', false));
assert.equal(flood.show, true, 'lake trail survives departure before the next camera settles');
assert.deepEqual(flood.polyline.positions.getValue(), lakeTail, 'retain the prefix without revealing the next segment');
assert.ok(Cesium.Cartesian3.equals(surge.position.getValue(), lakeTail.at(-1)));
assert.deepEqual(flood.positions, lakeTail, 'retain the prefix without revealing the next segment');
assert.ok(Cesium.Cartesian3.equals(surge.position, lakeTail.at(-1)));
layer.setParams(params('second-landslide', true));
assert.deepEqual(flood.polyline.positions.getValue(), lakeTail, 'arrival does not clear the prefix');
assert.deepEqual(flood.positions, lakeTail, 'arrival does not clear the prefix');
finishReveal();
assert.ok(flood.polyline.positions.getValue().length > lakeTail.length);
assert.ok(flood.positions.length > lakeTail.length);
layer.setParams(params('debris-dammed-lake', false));
assert.equal(flood.show, false, 'backward replay trims future segments instead of retaining stale history');
layer.setParams(params('second-landslide', false));
assert.deepEqual(flood.polyline.positions.getValue(), lakeTail, 'direct load reconstructs the same prefix');
assert.deepEqual(flood.positions, lakeTail, 'direct load reconstructs the same prefix');
layer.setParams(params('second-landslide', false, { evidencePathPersistent: false }));
assert.equal(flood.show, false, 'nonpersistent shots retain their arrival gate');
for (const beatId of ['devighat-taadi-khola-bridge', 'charaudi', 'final-view']) {
@@ -2756,13 +2777,13 @@ test('media-led upper-valley shots retain only their upstream prefix during came
evidencePathDuringMedia: false, evidenceMediaAutoplay: beatId !== 'final-view',
};
layer.setParams(params(beatId, false, historyControls));
const completedTail = [...flood.polyline.positions.getValue()];
const completedTail = [...flood.positions];
assert.ok(completedTail.length > 100, `${beatId}: direct load reconstructs full sourced history`);
layer.setParams(params(beatId, true, historyControls));
assert.deepEqual(flood.polyline.positions.getValue(), completedTail,
assert.deepEqual(flood.positions, completedTail,
`${beatId}: arrival must not reset the completed history`);
finishReveal();
assert.deepEqual(flood.polyline.positions.getValue(), completedTail,
assert.deepEqual(flood.positions, completedTail,
`${beatId}: media/card reveal must not erase or regrow completed history`);
}
await layer.disable();
@@ -2798,7 +2819,7 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async () => null,
mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -2840,44 +2861,42 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidenceSequence: true,
}));
await layer.enable(viewer, { origin: 'scene' });
let source = viewer._test.dataSources.at(-1);
let flood = source.entities.getById('bhote-koshi-flood-core');
let surge = source.entities.getById('bhote-koshi-surge-front');
const timureStart = flood.polyline.positions.getValue().length;
let flood = viewer._test.floodView('bhote-koshi-flood-core');
let surge = viewer._test.floodView('bhote-koshi-surge-front');
const timureStart = flood.positions.length;
assert.ok(timureStart > 1, 'the completed Border Gate prefix is already visible during travel');
assert.equal(surge.show, true);
advance(420);
const earlyTimureLength = flood.polyline.positions.getValue().length;
const earlyTimureLength = flood.positions.length;
assert.ok(earlyTimureLength > timureStart,
'the trail leads during the opening tenth of camera travel instead of waiting for arrival');
advance(2880);
const timureEnd = flood.polyline.positions.getValue().length;
const timureEnd = flood.positions.length;
assert.ok(timureEnd > timureStart);
assert.equal(flood.show, true, 'the completed tail remains visible at the next point');
assert.ok(Cesium.Cartesian3.equals(flood.polyline.positions.getValue().at(-1), surge.position.getValue()));
assert.ok(Cesium.Cartesian3.equals(flood.positions.at(-1), surge.position));
layer.setParams(params('syabru-besi', 'comparison', travel(2), {
evidenceSequence: true,
}));
assert.ok(flood.polyline.positions.getValue().length >= timureEnd,
assert.ok(flood.positions.length >= timureEnd,
'the Timure segment remains painted when Syabru travel starts');
advance(3300);
assert.equal(surge.show, true, 'the amber head remains visible at comparison completion');
assert.ok(Cesium.Cartesian3.equals(flood.polyline.positions.getValue().at(-1), surge.position.getValue()));
assert.ok(Cesium.Cartesian3.equals(flood.positions.at(-1), surge.position));
layer.setParams(params('dhunche', 'source', travel(3), {
evidencePathHistory: true,
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
source = viewer._test.dataSources.at(-1);
flood = source.entities.getById('bhote-koshi-flood-core');
surge = source.entities.getById('bhote-koshi-surge-front');
const dhuncheStart = flood.polyline.positions.getValue().length;
flood = viewer._test.floodView('bhote-koshi-flood-core');
surge = viewer._test.floodView('bhote-koshi-surge-front');
const dhuncheStart = flood.positions.length;
assert.ok(dhuncheStart >= event.reconstruction.corridor.length,
'the comparison corridor survives the transition onto Google photogrammetry');
advance(3300);
const dhuncheEnd = flood.polyline.positions.getValue().length;
const dhuncheEnd = flood.positions.length;
assert.ok(dhuncheEnd > dhuncheStart);
assert.equal(surge.show, true);
@@ -2886,11 +2905,11 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
assert.ok(flood.polyline.positions.getValue().length >= dhuncheEnd,
assert.ok(flood.positions.length >= dhuncheEnd,
'the completed Dhunche segment never disappears');
advance(900);
const frozenHead = Cesium.Cartesian3.clone(surge.position.getValue());
const frozenLength = flood.polyline.positions.getValue().length;
const frozenHead = Cesium.Cartesian3.clone(surge.position);
const frozenLength = flood.positions.length;
layer.setParams(params('mailung-upper-trishuli', 'source', travel(4, 4.2, {
active: false, cancelled: true,
}), {
@@ -2899,8 +2918,8 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidenceHoldCard: true,
}));
assert.equal(frames.size, 0, 'cancelling camera travel revokes the path animation frame');
assert.equal(flood.polyline.positions.getValue().length, frozenLength);
assert.ok(Cesium.Cartesian3.equals(surge.position.getValue(), frozenHead));
assert.equal(flood.positions.length, frozenLength);
assert.ok(Cesium.Cartesian3.equals(surge.position, frozenHead));
assert.ok(holds.includes('bhote-koshi-scene-path-travel'));
assert.ok(releases.includes('bhote-koshi-scene-path-travel'));
@@ -2912,16 +2931,16 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
const startLength = flood.polyline.positions.getValue().length;
const startLength = flood.positions.length;
assert.ok(startLength >= previousCompleteLength,
`${beatId} retains every completed upstream segment while travel begins`);
advance(3300);
const completeLength = flood.polyline.positions.getValue().length;
const completeLength = flood.positions.length;
assert.ok(completeLength > startLength, `${beatId} grows its own segment during travel`);
assert.equal(flood.show, true);
assert.equal(surge.show, true);
assert.ok(Cesium.Cartesian3.equals(
flood.polyline.positions.getValue().at(-1), surge.position.getValue(),
flood.positions.at(-1), surge.position,
));
previousCompleteLength = completeLength;
}
@@ -2940,20 +2959,20 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
assert.ok(flood.polyline.positions.getValue().length > dhuncheEnd,
assert.ok(flood.positions.length > dhuncheEnd,
'a direct Bidur load reconstructs its complete upstream prefix');
advance(3300);
assert.equal(flood.polyline.positions.getValue().length, bidurCompleteLength);
assert.equal(flood.positions.length, bidurCompleteLength);
layer.setParams(params('dhunche', 'source', travel(travelId++), {
evidencePathHistory: true,
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
assert.ok(flood.polyline.positions.getValue().length < bidurCompleteLength,
assert.ok(flood.positions.length < bidurCompleteLength,
'backward navigation trims unsupported downstream history immediately');
advance(3300);
assert.equal(flood.polyline.positions.getValue().length, dhuncheEnd);
assert.equal(flood.positions.length, dhuncheEnd);
// The deadline is independent of RAF, so a throttled render loop still
// completes the active segment before the camera's longer flight ends.
@@ -2967,7 +2986,7 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
now += deadlineEntry[1].delay;
deadlineEntry[1].callback();
assert.equal(frames.size, 0, 'the deadline cancels a stalled animation frame');
assert.ok(flood.polyline.positions.getValue().length > dhuncheEnd);
assert.ok(flood.positions.length > dhuncheEnd);
layer.setParams({
presentation: 'scene-beat', sceneSurface: 'evidence-beat', beatId: 'charaudi',
@@ -2992,3 +3011,140 @@ test('Bhote Koshi corridor remains ordered downstream and inside the imagery rec
priorChainage = point.chainageM;
}
});
test('an evidence point whose terrain sample misses sits at its fallback elevation, not sea level', async () => {
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
installEventDom();
globalThis.window = { setTimeout: () => 71, clearTimeout() {} };
const viewer = eventViewer();
const publications = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: null })),
mediaLoader: async () => {
const error = new Error('fixture media intentionally unavailable');
error.name = 'AbortError';
throw error;
},
overlayHost: { setEntries(_source, entries) { publications.push(entries); }, setVisible() {}, clearSource() {} },
renderHost: { request() {}, hold() {}, release() {} },
});
try {
layer.setParams({
presentation: 'scene-beat',
sceneSurface: 'evidence-beat',
beatId: 'gyirong-border-gate',
}, { origin: 'scene' });
await layer.enable(viewer, { origin: 'scene' });
const card = publications.at(-1).find((entry) => entry.id === 'evidence-card-gyirong-border-gate');
const fallback = event.evidenceSpine.find(({ id }) => id === 'gyirong-border-gate').fallbackElevationM;
assert.ok(fallback > 100, 'the fixture has a real fallback elevation');
const height = Cesium.Cartographic.fromCartesian(card.position()).height;
assert.ok(Math.abs(height - (fallback + 18)) < 1, `card at ${height} m`);
await layer.disable();
} finally {
await layer.destroy();
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
for (const [source, expected] of [['terrain', 'sampled'], ['ellipsoid', 'fallback']]) {
test(`the default terrain sampler places an evidence point at a ${source} answer's ${expected} height`, async () => {
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
installEventDom();
globalThis.window = { setTimeout: () => 71, clearTimeout() {} };
const asked = [];
const query = {
async sampleHeight(points, options) {
asked.push(options);
return points.map(() => ({ height: 1234, source, confidence: 1, lod: 'finest' }));
},
};
const viewer = eventViewer(0.37, { query });
const publications = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imagerySpecFactory: async (url) => ({ url }),
mediaLoader: async () => {
const error = new Error('fixture media intentionally unavailable');
error.name = 'AbortError';
throw error;
},
overlayHost: { setEntries(_source, entries) { publications.push(entries); }, setVisible() {}, clearSource() {} },
renderHost: { request() {}, hold() {}, release() {} },
});
try {
layer.setParams({
presentation: 'scene-beat',
sceneSurface: 'evidence-beat',
beatId: 'gyirong-border-gate',
}, { origin: 'scene' });
await layer.enable(viewer, { origin: 'scene' });
assert.deepEqual(asked, [{ against: 'terrain', mostDetailed: true }]);
const card = publications.at(-1).find((entry) => entry.id === 'evidence-card-gyirong-border-gate');
const fallback = event.evidenceSpine.find(({ id }) => id === 'gyirong-border-gate').fallbackElevationM;
const height = Cesium.Cartographic.fromCartesian(card.position()).height;
const want = (expected === 'sampled' ? 1234 : fallback) + 18;
assert.ok(Math.abs(height - want) < 1, `card at ${height} m, not ${want} m`);
await layer.disable();
} finally {
await layer.destroy();
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
}
test('an event image that fails to load takes the comparison down, not the event', async (t) => {
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
installEventDom();
globalThis.window = { setTimeout: () => 71, clearTimeout() {} };
const warn = t.mock.method(console, 'warn', () => {});
const viewer = eventViewer();
const renders = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
embeddedMediaFactory: () => ({ show() {}, hide() {}, pause() {}, destroy() {} }),
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderHost: { request(reason) { renders.push(reason); }, hold() {}, release() {} },
});
try {
layer.setParams({ progress: 0.4 }, { origin: 'local-restore' });
assert.equal(await layer.enable(viewer), true);
const [before, after] = viewer._test.imagery;
assert.equal(before.spec.kind, 'single-image', 'the default spec is one image');
assert.deepEqual(Object.keys(before.spec.rectangle).sort(), ['east', 'north', 'south', 'west']);
assert.equal(before.spec.credit.text, 'Vantor WorldView Open Data · CC BY-NC 4.0');
assert.deepEqual(viewer._test.globe.layers, [before, after], 'the pair goes on top, before under after');
assert.equal(eventSplit().view.hidden, false);
assert.equal(eventPanel().querySelector('[data-role="imagery-comparison"]').hidden, false);
after.fail({ tile: { x: 0, y: 0, level: 0 }, status: 404 });
assert.ok(before.removed && after.removed, 'neither image is left to compare');
assert.equal(eventSplit().view.hidden, true);
assert.equal(eventPanel().querySelector('[data-role="imagery-comparison"]').hidden, true);
assert.equal(layer.getPlaybackState().enabled, true, 'the event itself stays on');
assert.ok(renders.includes('bhote-koshi-imagery-failed'));
assert.equal(warn.mock.callCount(), 1);
before.fail({ tile: { x: 0, y: 0, level: 0 } });
assert.equal(warn.mock.callCount(), 1, 'a removed layer reports nothing more');
await layer.disable();
assert.equal(await layer.enable(viewer), true);
assert.equal(viewer._test.globe.layers.length, 2, 'the next enable tries the images again');
assert.equal(eventSplit().view.hidden, false);
await layer.disable();
} finally {
await layer.destroy();
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
+333 -291
View File
@@ -1,9 +1,13 @@
import * as Cesium from 'cesium';
import {
clearOverlaySource,
setOverlayEntries,
} from '../overlays/worldOverlay.js';
import { governorRequestRender } from '../renderGovernor.js';
import { drawOf, findCamera } from '../render/rendererOf.js';
import { hexColor } from '../render/color.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import { toRadians } from '../geo/vector.js';
import { lengthFraction } from '../geo/polyline.js';
import {
BHOTE_KOSHI_LOCATOR_CREDIT,
registerDynamicCredit,
@@ -144,10 +148,11 @@ const NEARBY_CITIES = Object.freeze([
placement: 'right-lower',
}),
]);
const BORDER_COLOR = Cesium.Color.fromCssColorString('#20e7f2');
const BORDER_ACCENT = '#20e7f2';
const INCIDENT_ACCENT = '#ffad55';
const INCIDENT_COLOR = Cesium.Color.fromCssColorString(INCIDENT_ACCENT);
// Each layer's draw sets have ids of their own.
let layerSerial = 0;
const DEFAULT_OVERLAY_HOST = Object.freeze({
setEntries: setOverlayEntries,
@@ -194,10 +199,6 @@ function presentationUsesBoundary(value) {
);
}
function presentationAnimatesBoundary(value) {
return value === BHOTE_KOSHI_REGIONAL_PRESENTATION;
}
function smoothstep(from, to, value) {
if (to <= from) return value >= to ? 1 : 0;
const amount = Math.max(0, Math.min(1, (value - from) / (to - from)));
@@ -219,26 +220,21 @@ export function anchoredCalloutPresentation(elapsedMs) {
};
}
/** Return the progressive prefix used by the animated Nepal border. */
export function revealPolylinePositions(positions, progress) {
if (!Array.isArray(positions) || positions.length < 2) return [];
/**
* How much of a line's length is drawn when it is revealed vertex by
* vertex: `progress` of its vertices (the head between two of them), as a
* fraction of its length, for the draw port's `revealFraction`.
* @param {Array<{x: number, y: number, z: number}>} positions
* @param {number} progress 0..1
*/
export function revealLengthFraction(positions, progress) {
if (!Array.isArray(positions) || positions.length < 2) return 0;
const clamped = Math.max(0, Math.min(1, Number(progress) || 0));
if (clamped >= 1) return positions;
if (clamped >= 1) return 1;
if (clamped <= 0) return 0;
const scaled = clamped * (positions.length - 1);
const completed = Math.floor(scaled);
const revealed = positions.slice(0, completed + 1);
const next = Math.min(completed + 1, positions.length - 1);
if (next > completed) {
revealed.push(
Cesium.Cartesian3.lerp(
positions[completed],
positions[next],
scaled - completed,
new Cesium.Cartesian3(),
),
);
}
return revealed.length >= 2 ? revealed : [positions[0], positions[0]];
const index = Math.floor(scaled);
return lengthFraction(positions, index, scaled - index);
}
/** Close a region ring without duplicating an already-closed final vertex. */
@@ -285,14 +281,27 @@ export function createBhoteKoshiLocatorLayer({
cancelDelay = (handle) => clearTimeout(handle),
} = {}) {
let _viewer = null;
let _dataSource = null;
const _serial = ++layerSerial;
// Whether the layer draws: from enable until it is let go.
let _drawing = false;
let _sets = null;
// What the presentation draws, each item worked out for the time now:
// pulsing halos, lines revealed as they grow, and the country fill, drawn
// once it is due.
let _halos = [];
let _lines = [];
let _fill = null;
let _fillShown = false;
// Each line's reveal and show as last drawn.
const _drawnLines = new Map();
// Each halo's look as last drawn.
const _drawnHalos = new Map();
let _enabled = false;
let _boundaryReady = false;
let _boundaryResolved = false;
let _boundaryRing = null;
let _generation = 0;
let _presentation = BHOTE_KOSHI_REGIONAL_PRESENTATION;
let _borderAnimationFrame = null;
let _calloutPulseFrame = null;
let _triggerApproachTimer = null;
let _removeTriggerMoveStart = null;
@@ -332,30 +341,164 @@ export function createBhoteKoshiLocatorLayer({
_removeTriggerMoveEnd = null;
const wasInFlight = _triggerApproachInFlight;
_triggerApproachInFlight = false;
if (wasInFlight) _viewer?.camera?.cancelFlight?.();
if (wasInFlight) findCamera(_viewer)?.cancelFlight();
if (!preserveCallout) _triggerCalloutStartedAt = Number.POSITIVE_INFINITY;
}
function stopAnimations() {
if (_borderAnimationFrame !== null) cancelFrame(_borderAnimationFrame);
if (_calloutPulseFrame !== null) cancelFrame(_calloutPulseFrame);
_borderAnimationFrame = null;
_calloutPulseFrame = null;
_placeRevealMoving = false;
_placeRevealSettledAt = Number.POSITIVE_INFINITY;
clearTriggerApproach();
}
function removeDataSource() {
function removeDrawn() {
stopAnimations();
overlayHost.clearSource(BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID);
if (_dataSource && _viewer?.dataSources)
_viewer.dataSources.remove(_dataSource, true);
_dataSource = null;
if (_sets) for (const set of Object.values(_sets)) set.dispose();
_sets = null;
_drawing = false;
resetDrawn();
}
function resetDrawn() {
_halos = [];
_lines = [];
_fill = null;
_fillShown = false;
_drawnLines.clear();
_drawnHalos.clear();
}
/** The layer's draw sets, made on first use: fill under lines under halos. */
function drawSets() {
if (_sets) return _sets;
const draw = drawOf(_viewer);
const prefix = `${BHOTE_KOSHI_LOCATOR_LAYER_ID}:${_serial}`;
// Presentation only: clicks go through to what is under them.
_sets = {
fill: draw.shapes({ id: `${prefix}:fill`, pickable: false }),
lines: draw.lines({ id: `${prefix}:lines`, pickable: false }),
halos: draw.points({ id: `${prefix}:halos`, pickable: false }),
};
return _sets;
}
/** Draw the presentation as it now stands, in place of what was drawn. */
function commitDrawn() {
const sets = drawSets();
_drawnLines.clear();
_fillShown = Boolean(_fill?.visible());
sets.fill.set(_fillShown ? [_fill.item] : []);
sets.lines.set(
_lines.map((line) => {
const item = line();
_drawnLines.set(item.id, lineKey(item));
return item;
}),
);
_drawnHalos.clear();
sets.halos.set(
_halos.map((halo) => {
const item = halo();
_drawnHalos.set(item.id, haloKey(item));
return item;
}),
);
}
const haloKey = (item) =>
`${item.pixelSize}:${item.color}:${item.outlineColor}:${item.show}`;
const lineKey = (item) => `${item.revealFraction}:${item.show !== false}`;
/**
* Bring what is drawn to the time now: halos pulse, lines that grew or
* showed are changed in place, and the fill shows once it is due.
*/
function syncDrawn() {
if (!_drawing || !_sets) return;
if (!_fillShown && _fill?.visible()) {
_fillShown = true;
_sets.fill.set([_fill.item]);
}
const changed = [];
for (const line of _lines) {
const item = line();
const key = lineKey(item);
if (_drawnLines.get(item.id) === key) continue;
_drawnLines.set(item.id, key);
changed.push(item);
}
if (changed.length) _sets.lines.upsert(changed);
const pulsed = [];
for (const halo of _halos) {
const item = halo();
const key = haloKey(item);
if (_drawnHalos.get(item.id) === key) continue;
_drawnHalos.set(item.id, key);
pulsed.push(item);
}
if (pulsed.length) _sets.halos.upsert(pulsed);
}
/**
* A pulsing halo point: `progress()` (0..1) sizes it and fades its fill
* and ring (`fillAlpha`, `ringAlpha`), shown while `visible()`.
*/
function addHalo({
id,
subject,
color,
visible,
progress,
fillAlpha,
ringAlpha,
scaleByDistance,
}) {
const pos = { lon: subject.lon, lat: subject.lat, height: subject.heightM };
_halos.push(() => {
const p = progress();
return {
id,
pos,
pixelSize: CALLOUT_RING_MIN_SIZE_PX + CALLOUT_RING_SIZE_RANGE_PX * p,
color: hexColor(color, fillAlpha(p)),
outlineColor: hexColor(color, ringAlpha(p)),
outlineWidth: 2,
disableDepthTest: Number.POSITIVE_INFINITY,
scaleByDistance,
show: visible(),
};
});
}
/**
* A draped line revealed vertex by vertex as `progress()` runs 0..1,
* shown while `visible()`.
*/
function addRevealedLine({
id,
positions,
widthPx,
color,
progress,
visible,
}) {
_lines.push(() => ({
id,
positions,
widthPx,
mode: 'draped',
clampTo: 'both',
style: { kind: 'solid', color },
revealFraction: revealLengthFraction(positions, progress()),
show: visible(),
}));
}
function addCallout(
dataSource,
subject,
color,
{
@@ -365,51 +508,27 @@ export function createBhoteKoshiLocatorLayer({
showAnchor = true,
} = {},
) {
const position = Cesium.Cartesian3.fromDegrees(
subject.lon,
subject.lat,
subject.heightM,
);
const position = fromDegrees(subject.lon, subject.lat, subject.heightM);
const visibleAt = sequenceStartedAt + visibleAfterMs;
const isVisible = () => now() >= visibleAt;
const pulseProgress = () => {
const elapsed = Math.max(0, now() - visibleAt);
return (elapsed % CALLOUT_PULSE_DURATION_MS) / CALLOUT_PULSE_DURATION_MS;
};
const ringSize = new Cesium.CallbackProperty(() => {
return (
CALLOUT_RING_MIN_SIZE_PX + CALLOUT_RING_SIZE_RANGE_PX * pulseProgress()
);
}, false);
const ringColor = new Cesium.CallbackProperty((_time, result) => {
const dynamicColor = Cesium.Color.clone(color, result);
dynamicColor.alpha = isVisible() ? 0.14 * (1 - pulseProgress()) : 0;
return dynamicColor;
}, false);
const ringOutlineColor = new Cesium.CallbackProperty((_time, result) => {
const dynamicColor = Cesium.Color.clone(color, result);
dynamicColor.alpha = isVisible()
? 0.08 + 0.72 * (1 - pulseProgress())
: 0;
return dynamicColor;
}, false);
if (showAnchor) {
dataSource.entities.add({
addHalo({
id: `${subject === INCIDENT ? 'bhote-koshi-incident' : 'nepal-context'}-halo`,
position,
show: new Cesium.CallbackProperty(isVisible, false),
point: {
pixelSize: ringSize,
color: ringColor,
outlineColor: ringOutlineColor,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(
250000,
0.8,
25000000,
1.35,
),
subject,
color,
visible: isVisible,
progress: pulseProgress,
fillAlpha: (p) => (isVisible() ? 0.14 * (1 - p) : 0),
ringAlpha: (p) => (isVisible() ? 0.08 + 0.72 * (1 - p) : 0),
scaleByDistance: {
near: 250000,
nearValue: 0.8,
far: 25000000,
farValue: 1.35,
},
});
}
@@ -498,25 +617,22 @@ export function createBhoteKoshiLocatorLayer({
_placeRevealSettledAt = Number.POSITIVE_INFINITY;
publishOverlayEntries();
}
syncDrawn();
requestRender('bhote-koshi-locator-callout-pulse');
_calloutPulseFrame = scheduleFrame(pulseFrame);
};
_calloutPulseFrame = scheduleFrame(pulseFrame);
}
function addIncidentCallout(
dataSource,
sequenceStartedAt,
visibleAfterMs = 0,
) {
addCallout(dataSource, INCIDENT, INCIDENT_COLOR, {
function addIncidentCallout(sequenceStartedAt, visibleAfterMs = 0) {
addCallout(INCIDENT, INCIDENT_ACCENT, {
sequenceStartedAt,
visibleAfterMs,
});
}
function addTriggerRecordCallout(dataSource) {
const position = Cesium.Cartesian3.fromDegrees(
function addTriggerRecordCallout() {
const position = fromDegrees(
TRIGGER_RECORD.lon,
TRIGGER_RECORD.lat,
TRIGGER_RECORD.heightM,
@@ -531,30 +647,19 @@ export function createBhoteKoshiLocatorLayer({
CALLOUT_PULSE_DURATION_MS
);
};
dataSource.entities.add({
addHalo({
id: 'bhote-koshi-trigger-record-halo',
position,
show: new Cesium.CallbackProperty(isVisible, false),
point: {
pixelSize: new Cesium.CallbackProperty(
() =>
CALLOUT_RING_MIN_SIZE_PX +
CALLOUT_RING_SIZE_RANGE_PX * pulseProgress(),
false,
),
color: new Cesium.CallbackProperty((_time, result) => {
const color = Cesium.Color.clone(INCIDENT_COLOR, result);
color.alpha = 0.16 * (1 - pulseProgress());
return color;
}, false),
outlineColor: new Cesium.CallbackProperty((_time, result) => {
const color = Cesium.Color.clone(INCIDENT_COLOR, result);
color.alpha = isVisible() ? 0.08 + 0.78 * (1 - pulseProgress()) : 0;
return color;
}, false),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(3000, 1, 250000, 0.82),
subject: TRIGGER_RECORD,
color: INCIDENT_ACCENT,
visible: isVisible,
progress: pulseProgress,
fillAlpha: (p) => 0.16 * (1 - p),
ringAlpha: (p) => (isVisible() ? 0.08 + 0.78 * (1 - p) : 0),
scaleByDistance: {
near: 3000,
nearValue: 1,
far: 250000,
farValue: 0.82,
},
});
queueOverlayEntry({
@@ -618,8 +723,8 @@ export function createBhoteKoshiLocatorLayer({
_removeTriggerMoveEnd = null;
_triggerCalloutStartedAt = now();
requestRender('bhote-koshi-trigger-record-reveal');
const camera = _viewer?.camera;
if (!camera?.flyTo) return;
const port = findCamera(_viewer);
if (!port) return;
const generation = _generation;
_triggerApproachInFlight = true;
const finish = () => {
@@ -627,50 +732,54 @@ export function createBhoteKoshiLocatorLayer({
attempt.phase = 'finished';
_triggerApproachInFlight = false;
};
camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
TRIGGER_APPROACH_CAMERA.lon,
TRIGGER_APPROACH_CAMERA.lat,
TRIGGER_APPROACH_CAMERA.alt,
),
orientation: {
heading: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.heading),
pitch: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.pitch),
roll: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.roll),
port.flyTo(
{
lon: TRIGGER_APPROACH_CAMERA.lon,
lat: TRIGGER_APPROACH_CAMERA.lat,
height: TRIGGER_APPROACH_CAMERA.alt,
},
duration: TRIGGER_APPROACH_DURATION_SEC,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
complete: () => {
if (_triggerApproachAttempt !== attempt || attempt.phase !== 'flying')
return;
if (
!_enabled ||
generation !== _generation ||
_presentation !== BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION
) {
finish();
return;
}
attempt.phase = 'orbiting';
camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
TRIGGER_ORBIT_CAMERA.lon,
TRIGGER_ORBIT_CAMERA.lat,
TRIGGER_ORBIT_CAMERA.alt,
),
orientation: {
heading: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.heading),
pitch: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.pitch),
roll: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.roll),
},
duration: TRIGGER_ORBIT_DURATION_SEC,
easingFunction: Cesium.EasingFunction.SINUSOIDAL_IN_OUT,
complete: finish,
cancel: finish,
});
{
orientation: {
heading: toRadians(TRIGGER_APPROACH_CAMERA.heading),
pitch: toRadians(TRIGGER_APPROACH_CAMERA.pitch),
roll: toRadians(TRIGGER_APPROACH_CAMERA.roll),
},
durationS: TRIGGER_APPROACH_DURATION_SEC,
easing: 'cubicInOut',
onComplete: () => {
if (_triggerApproachAttempt !== attempt || attempt.phase !== 'flying')
return;
if (
!_enabled ||
generation !== _generation ||
_presentation !== BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION
) {
finish();
return;
}
attempt.phase = 'orbiting';
port.flyTo(
{
lon: TRIGGER_ORBIT_CAMERA.lon,
lat: TRIGGER_ORBIT_CAMERA.lat,
height: TRIGGER_ORBIT_CAMERA.alt,
},
{
orientation: {
heading: toRadians(TRIGGER_ORBIT_CAMERA.heading),
pitch: toRadians(TRIGGER_ORBIT_CAMERA.pitch),
roll: toRadians(TRIGGER_ORBIT_CAMERA.roll),
},
durationS: TRIGGER_ORBIT_DURATION_SEC,
easing: 'sineInOut',
onComplete: finish,
onCancel: finish,
},
);
},
onCancel: finish,
},
cancel: finish,
});
);
}
function armTriggerApproach() {
@@ -681,40 +790,36 @@ export function createBhoteKoshiLocatorLayer({
const attempt = { phase: 'armed' };
_triggerApproachAttempt = attempt;
const start = () => startTriggerApproach(attempt);
const camera = _viewer?.camera;
if (
!camera?.moveStart?.addEventListener ||
!camera?.moveEnd?.addEventListener
) {
const camera = findCamera(_viewer);
if (!camera) {
start();
return;
}
_removeTriggerMoveStart = camera.moveStart.addEventListener(() => {
_removeTriggerMoveStart = camera.on('moveStart', () => {
if (_triggerApproachAttempt !== attempt || attempt.phase !== 'armed')
return;
if (_triggerApproachTimer !== null) cancelDelay(_triggerApproachTimer);
_triggerApproachTimer = null;
_removeTriggerMoveStart?.();
_removeTriggerMoveStart = null;
_removeTriggerMoveEnd = camera.moveEnd.addEventListener(start);
_removeTriggerMoveEnd = camera.on('moveEnd', start);
});
_triggerApproachTimer = scheduleDelay(start, TRIGGER_APPROACH_ARM_MS);
}
function addNepalCallout(
dataSource,
sequenceStartedAt = now(),
labelPlacement = 'right',
{ showAnchor = true } = {},
) {
addCallout(dataSource, NEPAL, BORDER_COLOR, {
addCallout(NEPAL, BORDER_ACCENT, {
labelPlacement,
sequenceStartedAt,
showAnchor,
});
}
function addNearbyCityCallouts(dataSource, sequenceStartedAt) {
function addNearbyCityCallouts(sequenceStartedAt) {
NEARBY_CITIES.forEach((city, index) => {
const visibleAt =
sequenceStartedAt +
@@ -724,11 +829,7 @@ export function createBhoteKoshiLocatorLayer({
smoothstep(0, 1, (now() - visibleAt) / CITY_CALLOUT_REVEAL_MS);
const labelOnLeft = city.placement === 'left';
const labelLower = city.placement === 'right-lower';
const position = Cesium.Cartesian3.fromDegrees(
city.lon,
city.lat,
city.heightM,
);
const position = fromDegrees(city.lon, city.lat, city.heightM);
queueOverlayEntry({
id: `bhote-koshi-city-${city.id}`,
position,
@@ -765,7 +866,6 @@ export function createBhoteKoshiLocatorLayer({
}
function addIncidentPlaceCallouts(
dataSource,
sequenceStartedAt,
{ pulseHalos = false, places = INCIDENT_OVERVIEW_PLACES } = {},
) {
@@ -778,11 +878,7 @@ export function createBhoteKoshiLocatorLayer({
smoothstep(0, 1, (now() - visibleAt) / PLACE_CALLOUT_REVEAL_MS);
const labelOnLeft = place.placement === 'left';
const labelLower = place.placement === 'right-lower';
const position = Cesium.Cartesian3.fromDegrees(
place.lon,
place.lat,
place.heightM,
);
const position = fromDegrees(place.lon, place.lat, place.heightM);
if (pulseHalos) {
const pulseSequenceDurationMs =
PLACE_CALLOUT_STAGGER_MS * places.length;
@@ -810,30 +906,19 @@ export function createBhoteKoshiLocatorLayer({
Math.min(1, pulseWindowElapsed() / PLACE_CALLOUT_STAGGER_MS),
);
};
dataSource.entities.add({
addHalo({
id: `bhote-koshi-place-${place.id}-halo`,
position,
show: new Cesium.CallbackProperty(pulseIsActive, false),
point: {
pixelSize: new Cesium.CallbackProperty(
() =>
CALLOUT_RING_MIN_SIZE_PX +
CALLOUT_RING_SIZE_RANGE_PX * pulseProgress(),
false,
),
color: new Cesium.CallbackProperty((_time, result) => {
const color = Cesium.Color.clone(INCIDENT_COLOR, result);
color.alpha = 0.16 * (1 - pulseProgress());
return color;
}, false),
outlineColor: new Cesium.CallbackProperty((_time, result) => {
const color = Cesium.Color.clone(INCIDENT_COLOR, result);
color.alpha = 0.08 + 0.78 * (1 - pulseProgress());
return color;
}, false),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(5000, 1, 500000, 0.82),
subject: place,
color: INCIDENT_ACCENT,
visible: pulseIsActive,
progress: pulseProgress,
fillAlpha: (p) => 0.16 * (1 - p),
ringAlpha: (p) => 0.08 + 0.78 * (1 - p),
scaleByDistance: {
near: 5000,
nearValue: 1,
far: 500000,
farValue: 0.82,
},
});
}
@@ -872,105 +957,67 @@ export function createBhoteKoshiLocatorLayer({
});
}
function addIncidentFloodPath(dataSource, sequenceStartedAt) {
function addIncidentFloodPath(sequenceStartedAt) {
const positions = BHOTE_KOSHI_FLOOD_PATH.map(([lon, lat]) =>
Cesium.Cartesian3.fromDegrees(lon, lat),
fromDegrees(lon, lat),
);
const drawStartedAt = sequenceStartedAt + FLOOD_PATH_START_DELAY_MS;
const animatedPositions = new Cesium.CallbackProperty(
() =>
revealPolylinePositions(
positions,
(now() - drawStartedAt) / FLOOD_PATH_DRAW_DURATION_MS,
),
false,
);
dataSource.entities.add({
addRevealedLine({
id: 'bhote-koshi-flood-path',
show: new Cesium.CallbackProperty(() => now() >= drawStartedAt, false),
polyline: {
positions: animatedPositions,
width: 3.5,
clampToGround: true,
material: BORDER_COLOR.withAlpha(0.96),
classificationType: Cesium.ClassificationType.BOTH,
},
positions,
widthPx: 3.5,
color: hexColor(BORDER_ACCENT, 0.96),
progress: () => (now() - drawStartedAt) / FLOOD_PATH_DRAW_DURATION_MS,
visible: () => now() >= drawStartedAt,
});
}
function addNepalBoundary(dataSource, ring, sequenceStartedAt) {
function addNepalBoundary(ring, sequenceStartedAt) {
const closed = closeRegionRing(ring);
if (closed.length < 4) return false;
const positions = Cesium.Cartesian3.fromDegreesArray(closed.flat());
const hierarchy = new Cesium.PolygonHierarchy(positions.slice(0, -1));
const positions = closed.map(([lon, lat]) => fromDegrees(lon, lat));
const drawStartedAt = sequenceStartedAt + BORDER_START_DELAY_MS;
const animatedPositions = new Cesium.CallbackProperty(
() =>
revealPolylinePositions(
positions,
(now() - drawStartedAt) / BORDER_DRAW_DURATION_MS,
),
false,
);
dataSource.entities.add({
id: 'nepal-border-fill',
show: new Cesium.CallbackProperty(() => now() >= drawStartedAt, false),
polygon: {
hierarchy,
material: BORDER_COLOR.withAlpha(0.055),
classificationType: Cesium.ClassificationType.BOTH,
const progress = () => (now() - drawStartedAt) / BORDER_DRAW_DURATION_MS;
_fill = {
visible: () => now() >= drawStartedAt,
item: {
id: 'nepal-border-fill',
geometry: {
kind: 'polygon',
rings: [closed.slice(0, -1).map(([lon, lat]) => ({ lon, lat }))],
},
fill: hexColor(BORDER_ACCENT, 0.055),
height: 'clampGround',
clampTo: 'both',
},
});
dataSource.entities.add({
id: 'nepal-border-halo',
polyline: {
positions: animatedPositions,
width: 5,
clampToGround: true,
material: BORDER_COLOR.withAlpha(0.12),
classificationType: Cesium.ClassificationType.BOTH,
},
});
dataSource.entities.add({
id: 'nepal-border-highlight',
polyline: {
positions: animatedPositions,
width: 2.5,
clampToGround: true,
material: BORDER_COLOR.withAlpha(0.96),
classificationType: Cesium.ClassificationType.BOTH,
},
});
const generation = _generation;
const drawFrame = () => {
if (
!_enabled ||
generation !== _generation ||
!presentationAnimatesBoundary(_presentation)
)
return;
requestRender('bhote-koshi-locator-border-draw');
if (now() - drawStartedAt < BORDER_DRAW_DURATION_MS) {
_borderAnimationFrame = scheduleFrame(drawFrame);
} else {
_borderAnimationFrame = null;
}
};
_borderAnimationFrame = scheduleFrame(drawFrame);
for (const [id, widthPx, alpha] of [
['nepal-border-halo', 5, 0.12],
['nepal-border-highlight', 2.5, 0.96],
])
addRevealedLine({
id,
positions,
widthPx,
color: hexColor(BORDER_ACCENT, alpha),
progress,
visible: () => true,
});
// The callout pulse draws each step of the reveal (`syncDrawn`).
return true;
}
function renderPresentation() {
if (!_dataSource) return;
if (!_drawing) return;
stopAnimations();
overlayHost.clearSource(BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID);
_overlayEntries = [];
_dataSource.entities.removeAll();
resetDrawn();
if (_presentation === NEPAL_CONTEXT_PRESENTATION) {
addNepalCallout(_dataSource);
addNepalCallout();
} else if (_presentation === BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION) {
const sequenceStartedAt = now();
addIncidentPlaceCallouts(_dataSource, sequenceStartedAt, {
addIncidentPlaceCallouts(sequenceStartedAt, {
pulseHalos: true,
places: INCIDENT_OVERVIEW_PLACES,
});
@@ -987,8 +1034,8 @@ export function createBhoteKoshiLocatorLayer({
PLACE_CALLOUT_START_DELAY_MS -
(INCIDENT_OVERVIEW_PLACES.length - 1) * PLACE_CALLOUT_STAGGER_MS -
PLACE_CALLOUT_REVEAL_MS;
addIncidentFloodPath(_dataSource, sequenceStartedAt);
addIncidentPlaceCallouts(_dataSource, settledPlacesAt);
addIncidentFloodPath(sequenceStartedAt);
addIncidentPlaceCallouts(settledPlacesAt);
} else if (_presentation === BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION) {
const sequenceStartedAt = now();
const settledPathAt =
@@ -1000,21 +1047,22 @@ export function createBhoteKoshiLocatorLayer({
PLACE_CALLOUT_START_DELAY_MS -
(INCIDENT_OVERVIEW_PLACES.length - 1) * PLACE_CALLOUT_STAGGER_MS -
PLACE_CALLOUT_REVEAL_MS;
addIncidentFloodPath(_dataSource, settledPathAt);
addIncidentPlaceCallouts(_dataSource, settledPlacesAt);
addIncidentFloodPath(settledPathAt);
addIncidentPlaceCallouts(settledPlacesAt);
} else if (_presentation === BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION) {
const sequenceStartedAt = now();
const settledPathAt =
sequenceStartedAt -
FLOOD_PATH_START_DELAY_MS -
FLOOD_PATH_DRAW_DURATION_MS;
addIncidentFloodPath(_dataSource, settledPathAt);
addTriggerRecordCallout(_dataSource);
addIncidentFloodPath(settledPathAt);
addTriggerRecordCallout();
armTriggerApproach();
} else {
const sequenceStartedAt = now();
addNepalCallout(_dataSource, sequenceStartedAt, 'left');
addNepalCallout(sequenceStartedAt, 'left');
if (!_boundaryResolved) {
commitDrawn();
publishOverlayEntries();
startCalloutAnimation();
requestRender('bhote-koshi-locator-presentation');
@@ -1023,24 +1071,20 @@ export function createBhoteKoshiLocatorLayer({
if (_presentation === BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION) {
const settledAt =
sequenceStartedAt - BORDER_START_DELAY_MS - BORDER_DRAW_DURATION_MS;
if (_boundaryRing)
addNepalBoundary(_dataSource, _boundaryRing, settledAt);
addIncidentCallout(
_dataSource,
sequenceStartedAt - CALLOUT_REVEAL_DURATION_MS,
);
addNearbyCityCallouts(_dataSource, sequenceStartedAt);
if (_boundaryRing) addNepalBoundary(_boundaryRing, settledAt);
addIncidentCallout(sequenceStartedAt - CALLOUT_REVEAL_DURATION_MS);
addNearbyCityCallouts(sequenceStartedAt);
} else {
if (_boundaryRing)
addNepalBoundary(_dataSource, _boundaryRing, sequenceStartedAt);
if (_boundaryRing) addNepalBoundary(_boundaryRing, sequenceStartedAt);
const incidentDelayMs = _boundaryRing
? BORDER_START_DELAY_MS +
BORDER_DRAW_DURATION_MS +
INCIDENT_CALLOUT_GAP_MS
: BORDER_START_DELAY_MS;
addIncidentCallout(_dataSource, sequenceStartedAt, incidentDelayMs);
addIncidentCallout(sequenceStartedAt, incidentDelayMs);
}
}
commitDrawn();
publishOverlayEntries({ moving: _placeRevealMoving });
startCalloutAnimation();
requestRender('bhote-koshi-locator-presentation');
@@ -1058,11 +1102,9 @@ export function createBhoteKoshiLocatorLayer({
_boundaryResolved = false;
_boundaryRing = null;
const generation = ++_generation;
removeDataSource();
const dataSource = new Cesium.CustomDataSource('bhote-koshi-locator');
_dataSource = dataSource;
removeDrawn();
_drawing = true;
renderPresentation();
viewer.dataSources.add(dataSource);
registerDynamicCredit(viewer, BHOTE_KOSHI_LOCATOR_CREDIT);
showOsmCredit(viewer, BHOTE_KOSHI_LOCATOR_LAYER_ID);
requestRender('bhote-koshi-locator-callout');
@@ -1084,7 +1126,7 @@ export function createBhoteKoshiLocatorLayer({
return true;
} catch (error) {
if (error?.name === 'AbortError') {
if (generation === _generation) removeDataSource();
if (generation === _generation) removeDrawn();
throw error;
}
console.warn(
@@ -1106,7 +1148,7 @@ export function createBhoteKoshiLocatorLayer({
_boundaryResolved = false;
_boundaryRing = null;
_generation += 1;
removeDataSource();
removeDrawn();
requestRender('bhote-koshi-locator-disable');
return true;
}
+241 -155
View File
@@ -1,3 +1,6 @@
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFile } from 'node:fs/promises';
@@ -24,32 +27,58 @@ import {
createBhoteKoshiLocatorLayer,
largestGeoJsonRing,
NEPAL_CONTEXT_PRESENTATION,
revealPolylinePositions,
revealLengthFraction,
} from './bhoteKoshiLocator.js';
function viewerFixture() {
const added = [];
const removed = [];
return {
/**
* A viewer with a fake draw port bound; with `camera`, the Cesium camera
* port over that fake camera too. `_test` reads what is drawn: every live
* item by id (`drawn`), and `sets` of the layer.
*/
function viewerFixture({ camera } = {}) {
const draw = fakeDrawPort();
const viewer = {
creditDisplay: { addStaticCredit() {}, removeStaticCredit() {} },
dataSources: {
add(source) {
added.push(source);
},
remove(source) {
removed.push(source);
},
},
_test: { added, removed },
};
if (camera) {
viewer.camera = camera;
bindFakeCesiumCamera(viewer, { draw });
} else bindRenderer(viewer, { draw });
const live = () =>
[...draw.sets.values()].filter(
(set) => !set.disposed && set.spec.id.startsWith('bhote-koshi-locator:'),
);
viewer._test = {
draw,
live,
/** Every live item, by id. */
drawn() {
const items = new Map();
for (const set of live())
for (const [id, item] of set.items) items.set(id, item);
return items;
},
ids: () => [...viewer._test.drawn().keys()],
item: (id) => viewer._test.drawn().get(id),
};
return viewer;
}
/** Frames that run only when a test ticks them. */
function nonRunningAnimation() {
let queued = [];
return {
scheduleFrame() {
return 1;
scheduleFrame(callback) {
queued.push(callback);
return queued.length;
},
cancelFrame() {},
/** Run the frames asked for so far (each asks for its next). */
tick() {
const run = queued;
queued = [];
for (const callback of run) callback();
},
};
}
@@ -132,21 +161,18 @@ test('Bhote Koshi locator selects the largest GeoJSON country exterior', () => {
);
});
test('Bhote Koshi locator reveals a border progressively', () => {
test('Bhote Koshi locator reveals a border progressively, vertex by vertex', () => {
const positions = [
new Cesium.Cartesian3(0, 0, 0),
new Cesium.Cartesian3(10, 0, 0),
new Cesium.Cartesian3(20, 0, 0),
{ x: 0, y: 0, z: 0 },
{ x: 10, y: 0, z: 0 },
{ x: 40, y: 0, z: 0 },
];
assert.deepEqual(revealPolylinePositions(positions, 0), [
positions[0],
positions[0],
]);
assert.deepEqual(revealPolylinePositions(positions, 0.25), [
positions[0],
new Cesium.Cartesian3(5, 0, 0),
]);
assert.equal(revealPolylinePositions(positions, 1), positions);
assert.equal(revealLengthFraction(positions, 0), 0);
// A quarter of the vertices: halfway along the first, shorter segment.
assert.equal(revealLengthFraction(positions, 0.25), 5 / 40);
assert.equal(revealLengthFraction(positions, 0.75), 25 / 40);
assert.equal(revealLengthFraction(positions, 1), 1);
assert.equal(revealLengthFraction(positions.slice(0, 1), 0.5), 0);
});
test('Bhote Koshi locator stages its anchored callout from dot to leader to text', () => {
@@ -169,6 +195,7 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident',
const overlayHost = overlayHostFixture();
const renders = [];
let nowMs = 0;
const frames = nonRunningAnimation();
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => ({
name: 'Nepal',
@@ -182,24 +209,29 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident',
requestRender: (reason) => renders.push(reason),
overlayHost,
now: () => nowMs,
...nonRunningAnimation(),
...frames,
});
assert.equal(await layer.init(viewer), true);
assert.equal(await layer.enable(viewer, { origin: 'scene' }), true);
assert.equal(viewer._test.added.length, 1);
const source = viewer._test.added[0];
const ids = source.entities.values.map((entity) => entity.id);
const sets = viewer._test.live();
assert.deepEqual(
sets.map(({ kind }) => kind),
['shapes', 'lines', 'points'],
'the fill under the lines under the halos',
);
assert.ok(sets.every(({ spec }) => spec.pickable === false));
// The fill is drawn once it is due, below.
const ids = viewer._test.ids();
for (const id of [
'nepal-context-halo',
'nepal-border-fill',
'nepal-border-highlight',
'bhote-koshi-incident-halo',
]) {
assert.ok(ids.includes(id), `${id} belongs to the regional sequence`);
}
const incidentHalo = source.entities.getById('bhote-koshi-incident-halo');
const border = source.entities.getById('nepal-border-highlight');
const incidentHalo = () => viewer._test.item('bhote-koshi-incident-halo');
const border = () => viewer._test.item('nepal-border-highlight');
const publication = overlayHost._test.publications.at(-1);
assert.equal(publication.sourceId, BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID);
assert.equal(publication.entries.length, 2);
@@ -225,15 +257,31 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident',
assert.equal(incident.contentAlpha(), 0);
assert.equal(incident.presentationScale(), 0.96);
assert.equal(nepal.sourceAlpha(), 0);
assert.ok(border.polyline.positions.getValue().length < 5);
assert.equal(incidentHalo.show.getValue(), false);
assert.equal(incidentHalo.point.pixelSize.getValue(), 16);
assert.equal(border().revealFraction, 0);
assert.equal(border().mode, 'draped');
assert.equal(border().positions.length, 5);
assert.equal(viewer._test.item('nepal-border-fill'), undefined);
assert.equal(incidentHalo().show, false);
assert.equal(incidentHalo().pixelSize, 16);
nowMs = 800;
frames.tick();
const fill = viewer._test.item('nepal-border-fill');
assert.equal(fill.height, 'clampGround', 'the fill, due, drapes');
assert.equal(fill.geometry.rings[0].length, 4);
assert.ok(border().revealFraction > 0 && border().revealFraction < 0.1);
nowMs = 3100;
frames.tick();
assert.equal(nepal.sourceAlpha(), 1);
assert.equal(border.polyline.positions.getValue().length, 5);
assert.equal(incidentHalo.show.getValue(), false);
assert.equal(border().revealFraction, 1);
assert.equal(incidentHalo().show, false);
const lines = sets.find(({ kind }) => kind === 'lines');
const lineWrites = lines.writes;
nowMs = 3300;
assert.equal(incidentHalo.show.getValue(), true);
frames.tick();
frames.tick();
assert.equal(lines.writes, lineWrites, 'settled lines are not drawn again');
assert.equal(incidentHalo().show, true);
assert.equal(incidentHalo().disableDepthTest, Number.POSITIVE_INFINITY);
assert.equal(incident.sourceAlpha(), 0);
nowMs = 4500;
assert.equal(incident.sourceAlpha(), 1);
@@ -247,7 +295,7 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident',
assert.ok(renders.includes('bhote-koshi-locator-boundary'));
assert.equal(await layer.disable(), true);
assert.equal(viewer._test.removed.length, 1);
assert.equal(viewer._test.live().length, 0, 'its sets let go');
assert.equal(
overlayHost._test.clears.at(-1),
BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID,
@@ -275,10 +323,7 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide
layer.setParams({ presentation: NEPAL_CONTEXT_PRESENTATION });
await layer.enable(viewer);
assert.deepEqual(
viewer._test.added[0].entities.values.map((entity) => entity.id),
['nepal-context-halo'],
);
assert.deepEqual(viewer._test.ids(), ['nepal-context-halo']);
const nepalLabel = overlayHost._test.publications.at(-1).entries[0];
assert.equal(nepalLabel.variant, 'label');
assert.equal(nepalLabel.placement, 'right');
@@ -298,11 +343,8 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide
);
layer.setParams({ presentation: BHOTE_KOSHI_REGIONAL_PRESENTATION });
assert.ok(viewer._test.added[0].entities.getById('nepal-border-highlight'));
assert.equal(
viewer._test.added[0].entities.getById('bhote-koshi-city-kathmandu'),
undefined,
);
assert.ok(viewer._test.item('nepal-border-highlight'));
assert.equal(viewer._test.item('bhote-koshi-city-kathmandu'), undefined);
assert.equal(
overlayHost._test.publications
.at(-1)
@@ -311,10 +353,7 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide
);
layer.setParams({ presentation: NEPAL_CONTEXT_PRESENTATION });
assert.deepEqual(
viewer._test.added[0].entities.values.map((entity) => entity.id),
['nepal-context-halo'],
);
assert.deepEqual(viewer._test.ids(), ['nepal-context-halo']);
await layer.destroy();
});
@@ -336,7 +375,10 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
});
layer.setParams({ presentation: BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION });
await layer.enable(viewer);
const source = viewer._test.added[0];
const tick = () => {
const frame = pulseFrame;
frame?.();
};
const event = JSON.parse(
await readFile(
new URL(
@@ -348,7 +390,7 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
);
assert.equal(event.evidenceSpine.length, 16);
assert.equal(event.evidenceSpine.at(-1).id, 'charaudi');
assert.equal(source.entities.values.length, 15);
assert.equal(viewer._test.ids().length, 15);
const labels = overlayHost._test.publications.at(-1).entries;
assert.equal(labels.length, 15);
assert.equal(overlayHost._test.publications.at(-1).options.moving, true);
@@ -371,10 +413,11 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
nowMs = 349 + index * 650;
assert.equal(pin.sourceAlpha(), 0);
nowMs += 1;
tick();
assert.equal(pin.sourceAlpha(), 0);
assert.equal(
source.entities.values.filter(
(entity) => entity.id.endsWith('-halo') && entity.show.getValue(),
[...viewer._test.drawn().values()].filter(
(item) => item.id.endsWith('-halo') && item.show,
).length,
1,
);
@@ -384,10 +427,10 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
assert.ok(nowMs < INCIDENT_OVERVIEW_HOLD_SEC * 1000);
// A repeat halo cycle must not erase already revealed labels.
nowMs = 350 + 15 * 650;
tick();
assert.equal(
source.entities
.getById('bhote-koshi-place-immediate-collapse-viewpoint-halo')
.show.getValue(),
viewer._test.item('bhote-koshi-place-immediate-collapse-viewpoint-halo')
.show,
true,
);
assert.equal(
@@ -405,9 +448,7 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
assert.equal(overlayHost._test.publications.at(-1).options.moving, false);
layer.setParams({ presentation: BHOTE_KOSHI_REGIONAL_PRESENTATION });
assert.equal(
source.entities.values.some((entity) =>
entity.id.startsWith('bhote-koshi-place-'),
),
viewer._test.ids().some((id) => id.startsWith('bhote-koshi-place-')),
false,
);
await layer.destroy();
@@ -457,18 +498,18 @@ test('Bhote Koshi flood path draws a solid cyan sourced route after the place sh
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
let nowMs = 0;
const frames = nonRunningAnimation();
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
requestRender() {},
overlayHost,
now: () => nowMs,
...nonRunningAnimation(),
...frames,
});
layer.setParams({ presentation: BHOTE_KOSHI_FLOOD_PATH_PRESENTATION });
await layer.enable(viewer);
const source = viewer._test.added[0];
const path = source.entities.getById('bhote-koshi-flood-path');
const path = () => viewer._test.item('bhote-koshi-flood-path');
const labels = overlayHost._test.publications.at(-1).entries;
const trigger = labels.find(
({ id }) => id === 'bhote-koshi-place-immediate-collapse-viewpoint',
@@ -477,46 +518,56 @@ test('Bhote Koshi flood path draws a solid cyan sourced route after the place sh
({ id }) => id === 'bhote-koshi-place-bidur-trishuli-bridge',
);
assert.equal(source.entities.values.length, 1);
assert.equal(viewer._test.ids().length, 1);
assert.equal(labels.length, 15);
assert.equal(bidur.title, '14 · BIDUR BRIDGE');
for (const place of INCIDENT_OVERVIEW_PLACES) {
const pin = labels.find(({ id }) => id === `bhote-koshi-place-${place.id}`);
assert.equal(pin.sourceAlpha(), 1, place.id);
}
assert.equal(path.polyline.clampToGround.getValue(), true);
assert.ok(path.polyline.material instanceof Cesium.ColorMaterialProperty);
assert.equal(path().mode, 'draped');
assert.equal(path().clampTo, 'both');
assert.equal(path().widthPx, 3.5);
assert.equal(path().style.kind, 'solid');
const color = Cesium.Color.fromCssColorString('#20e7f2').withAlpha(0.96);
assert.ok(
path.polyline.material.color
.getValue()
.equalsEpsilon(
Cesium.Color.fromCssColorString('#20e7f2').withAlpha(0.96),
path().style.color.every(
(value, i) =>
Math.abs(value - Cesium.Color.pack(color, [])[i]) <
Cesium.Math.EPSILON7,
),
),
);
assert.equal(path.show.getValue(), false);
assert.equal(path().show, false);
assert.equal(trigger.sourceAlpha(), 1);
assert.equal(bidur.sourceAlpha(), 1);
nowMs = 250;
assert.equal(path.show.getValue(), true);
assert.equal(path.polyline.positions.getValue().length, 2);
frames.tick();
assert.equal(path().show, true);
assert.equal(path().revealFraction, 0);
nowMs = 2250;
const halfwayCount = path.polyline.positions.getValue().length;
assert.ok(Math.abs(halfwayCount - BHOTE_KOSHI_FLOOD_PATH.length / 2) <= 2);
frames.tick();
// Halfway through its vertices.
const positions = path().positions;
assert.equal(path().revealFraction, revealLengthFraction(positions, 0.5));
assert.ok(path().revealFraction > 0.2 && path().revealFraction < 0.8);
nowMs = 4250;
assert.equal(
path.polyline.positions.getValue().length,
BHOTE_KOSHI_FLOOD_PATH.length,
);
frames.tick();
assert.equal(path().revealFraction, 1);
assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH[0], [85.48476, 28.33255]);
// More observation pins must not extend or straighten the sourced route.
assert.deepEqual(
path.polyline.positions.getValue(),
BHOTE_KOSHI_FLOOD_PATH.map(([lon, lat]) =>
Cesium.Cartesian3.fromDegrees(lon, lat),
),
);
assert.equal(positions.length, BHOTE_KOSHI_FLOOD_PATH.length);
positions.forEach((position, i) => {
const [lon, lat] = BHOTE_KOSHI_FLOOD_PATH[i];
assert.ok(
Cesium.Cartesian3.equalsEpsilon(
position,
Cesium.Cartesian3.fromDegrees(lon, lat),
0,
1e-6,
),
);
});
assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH.at(-1), [85.14943, 27.92177]);
assert.equal(layer.getStats().coverage, 'Bhote Koshi · Flood path');
assert.deepEqual(layer.getParams(), {
@@ -547,11 +598,10 @@ test('Bhote Koshi path-overview presentation keeps the route settled without Nep
layer.setParams({ presentation: BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION });
await layer.enable(viewer);
const source = viewer._test.added[0];
const path = source.entities.getById('bhote-koshi-flood-path');
const path = viewer._test.item('bhote-koshi-flood-path');
const labels = overlayHost._test.publications.at(-1).entries;
assert.equal(source.entities.values.length, 1);
assert.equal(viewer._test.ids().length, 1);
assert.equal(labels.length, 15);
for (const [index, place] of INCIDENT_OVERVIEW_PLACES.entries()) {
const pin = labels.find(({ id }) => id === `bhote-koshi-place-${place.id}`);
@@ -561,23 +611,21 @@ test('Bhote Koshi path-overview presentation keeps the route settled without Nep
);
assert.equal(pin.sourceAlpha(), 1);
}
assert.equal(path.show.getValue(), true);
assert.equal(
path.polyline.positions.getValue().length,
BHOTE_KOSHI_FLOOD_PATH.length,
);
assert.equal(path.show, true);
assert.equal(path.revealFraction, 1);
assert.equal(path.positions.length, BHOTE_KOSHI_FLOOD_PATH.length);
assert.ok(
Cesium.Cartesian3.equals(
path.polyline.positions.getValue()[0],
Cesium.Cartesian3.equalsEpsilon(
path.positions[0],
Cesium.Cartesian3.fromDegrees(85.48476, 28.33255),
0,
1e-6,
),
);
assert.equal(source.entities.getById('nepal-border-fill'), undefined);
assert.equal(source.entities.getById('nepal-border-highlight'), undefined);
assert.equal(viewer._test.item('nepal-border-fill'), undefined);
assert.equal(viewer._test.item('nepal-border-highlight'), undefined);
assert.equal(
source.entities.getById(
'bhote-koshi-place-immediate-collapse-viewpoint-halo',
),
viewer._test.item('bhote-koshi-place-immediate-collapse-viewpoint-halo'),
undefined,
);
assert.equal(layer.getStats().coverage, 'Bhote Koshi · Path overview');
@@ -604,14 +652,13 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details',
preview: true,
});
await layer.enable(viewer);
const source = viewer._test.added[0];
const publication = overlayHost._test.publications.at(-1);
const record = publication.entries[0];
assert.deepEqual(
source.entities.values.map(({ id }) => id),
['bhote-koshi-flood-path', 'bhote-koshi-trigger-record-halo'],
);
assert.deepEqual(viewer._test.ids(), [
'bhote-koshi-flood-path',
'bhote-koshi-trigger-record-halo',
]);
assert.equal(record.title, 'USGS INITIAL REPORT');
assert.deepEqual(record.details, [
'26 AUG 2026 · 08:37 NPT',
@@ -624,7 +671,7 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details',
assert.equal(record.sourceAlpha(), 0);
nowMs = 1200;
assert.equal(record.sourceAlpha(), 1);
assert.equal(source.entities.getById('nepal-border-highlight'), undefined);
assert.equal(viewer._test.item('nepal-border-highlight'), undefined);
assert.equal(layer.getStats().coverage, 'Bhote Koshi · Trigger record');
assert.deepEqual(layer.getParams(), {
presentation: BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION,
@@ -633,20 +680,21 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details',
});
test('Bhote Koshi trigger-record waits for the scene camera, zooms, then orbits', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
const moveStart = new Cesium.Event();
const moveEnd = new Cesium.Event();
const flights = [];
let armedCallback = null;
viewer.camera = {
moveStart,
moveEnd,
flyTo(options) {
flights.push(options);
const viewer = viewerFixture({
camera: {
moveStart,
moveEnd,
flyTo(options) {
flights.push(options);
},
cancelFlight() {},
},
cancelFlight() {},
};
});
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
requestRender() {},
@@ -688,21 +736,24 @@ test('Bhote Koshi trigger-record waits for the scene camera, zooms, then orbits'
for (const phase of ['timer', 'move-end', 'approach', 'orbit']) {
test(`Scene Stop revokes locator ${phase} and stale callbacks cannot own a successor`, async () => {
const viewer = viewerFixture();
const timers = new Map();
const callbacks = [];
const flights = [];
let nextTimer = 0;
const moveStart = new Cesium.Event();
const moveEnd = new Cesium.Event();
viewer.camera = {
moveStart,
moveEnd,
flyTo(options) {
flights.push(options);
const viewer = viewerFixture({
camera: {
moveStart,
moveEnd,
flyTo(options) {
flights.push(options);
},
cancelFlight() {},
},
cancelFlight() {},
};
});
// The renderer's camera port relays these; the layer's own come on top.
const portListeners = [moveStart, moveEnd].map((e) => e.numberOfListeners);
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
overlayHost: overlayHostFixture(),
@@ -745,8 +796,10 @@ for (const phase of ['timer', 'move-end', 'approach', 'orbit']) {
const oldFlights = [...flights];
SceneDirector.prototype.stopScene.call(director);
assert.equal(timers.size, 0, 'Stop cancels the actual delayed work');
assert.equal(moveStart.numberOfListeners, 0);
assert.equal(moveEnd.numberOfListeners, 0);
assert.deepEqual(
[moveStart, moveEnd].map((e) => e.numberOfListeners),
portListeners,
);
callbacks[0]();
moveEnd.raiseEvent();
for (const flight of oldFlights) flight.complete();
@@ -807,8 +860,7 @@ test('Bhote Koshi locator keeps the regional context settled while nearby cities
layer.setParams({ presentation: BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION });
await layer.enable(viewer);
const source = viewer._test.added[0];
const borderFill = source.entities.getById('nepal-border-fill');
const borderFill = viewer._test.item('nepal-border-fill');
const entries = overlayHost._test.publications.at(-1).entries;
const incident = entries.find(
({ id }) => id === 'bhote-koshi-incident-callout',
@@ -823,7 +875,8 @@ test('Bhote Koshi locator keeps the regional context settled while nearby cities
({ id }) => id === 'bhote-koshi-city-dhulikhel',
);
assert.equal(borderFill.show.getValue(), true);
assert.ok(borderFill, 'the settled fill is drawn at once');
assert.equal(viewer._test.item('nepal-border-highlight').revealFraction, 1);
assert.equal(incident.contentAlpha(), 1);
assert.equal(kathmandu.title, 'KATHMANDU');
assert.equal(bhaktapur.title, 'BHAKTAPUR');
@@ -866,9 +919,7 @@ test('Bhote Koshi locator degrades to labels when the regional boundary is unava
});
try {
await layer.enable(viewer);
const ids = viewer._test.added[0].entities.values.map(
(entity) => entity.id,
);
const ids = viewer._test.ids();
assert.ok(ids.includes('nepal-context-halo'));
assert.ok(ids.includes('bhote-koshi-incident-halo'));
assert.equal(ids.includes('bhote-koshi-city-kathmandu'), false);
@@ -899,15 +950,9 @@ test('Bhote Koshi regional locator waits for its boundary before starting the fu
});
const enabling = layer.enable(viewer);
assert.ok(viewer._test.added[0].entities.getById('nepal-context-halo'));
assert.equal(
viewer._test.added[0].entities.getById('nepal-border-highlight'),
undefined,
);
assert.equal(
viewer._test.added[0].entities.getById('bhote-koshi-incident-halo'),
undefined,
);
assert.ok(viewer._test.item('nepal-context-halo'));
assert.equal(viewer._test.item('nepal-border-highlight'), undefined);
assert.equal(viewer._test.item('bhote-koshi-incident-halo'), undefined);
assert.equal(overlayHost._test.publications.length, 1);
assert.deepEqual(
overlayHost._test.publications[0].entries.map(({ id }) => id),
@@ -923,14 +968,9 @@ test('Bhote Koshi regional locator waits for its boundary before starting the fu
],
});
await enabling;
assert.ok(
viewer._test.added[0].entities.getById('bhote-koshi-incident-halo'),
);
assert.ok(viewer._test.added[0].entities.getById('nepal-border-highlight'));
assert.equal(
viewer._test.added[0].entities.getById('bhote-koshi-city-kathmandu'),
undefined,
);
assert.ok(viewer._test.item('bhote-koshi-incident-halo'));
assert.ok(viewer._test.item('nepal-border-highlight'));
assert.equal(viewer._test.item('bhote-koshi-city-kathmandu'), undefined);
assert.equal(overlayHost._test.publications.length, 2);
assert.deepEqual(
overlayHost._test.publications.at(-1).entries.map(({ id }) => id),
@@ -960,6 +1000,52 @@ test('Bhote Koshi locator cancels a stale boundary resolution and removes its su
[88, 30],
],
});
assert.ok(viewer._test.live().length > 0, 'drawn while it resolves');
await assert.rejects(enabling, (error) => error?.name === 'AbortError');
assert.equal(viewer._test.removed.length, 1);
assert.equal(viewer._test.live().length, 0, 'let go');
});
test('Bhote Koshi locator layers draw sets of their own, and halos only as they change', async () => {
const viewer = viewerFixture();
const ring = [
[80, 26],
[88, 26],
[88, 30],
[80, 30],
];
let nowMs = 0;
const frames = nonRunningAnimation();
const make = () =>
createBhoteKoshiLocatorLayer({
boundaryResolver: async () => ({ name: 'Nepal', ring }),
requestRender() {},
overlayHost: overlayHostFixture(),
now: () => nowMs,
...frames,
});
const first = make();
const second = make();
assert.equal(await first.enable(viewer, { origin: 'scene' }), true);
assert.equal(await second.enable(viewer, { origin: 'scene' }), true);
const ids = viewer._test.live().map(({ spec }) => spec.id);
assert.equal(ids.length, 6);
assert.equal(new Set(ids).size, 6, 'no two layers share a set');
// Before the incident halo is due, nothing about any halo changes.
const halos = viewer._test.live().filter(({ kind }) => kind === 'points');
nowMs = 100;
frames.tick();
const writes = halos.map((set) => set.writes);
frames.tick();
frames.tick();
assert.deepEqual(
halos.map((set) => set.writes),
writes,
'unchanged halos are not drawn again',
);
assert.equal(await first.disable(), true);
assert.equal(viewer._test.live().length, 3, 'the other layer keeps its sets');
assert.equal(await second.disable(), true);
assert.equal(viewer._test.live().length, 0);
});
+25 -15
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { fromDegrees } from '../geo/ellipsoid.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import {
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
_clearBikeshareSelectionForTest,
@@ -19,17 +20,17 @@ function makeRecord() {
isInstalled: true,
isRenting: false,
isReturning: true,
point: {
position: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 2),
show: true,
},
key: 'austin-capmetro:3790',
position: fromDegrees(-97.7431, 30.2672, 2),
pixelSize: 8,
color: [0, 1, 0, 1],
};
}
test('selected bikeshare entry preserves source copy and protected-lane policy', () => {
const record = makeRecord();
const entry = createBikeshareSelectedOverlayEntry('austin-capmetro:3790', record);
assert.equal(entry.position, record.point.position);
assert.equal(entry.position, record.position);
assert.equal(entry.title, 'Congress & 6th');
assert.deepEqual(entry.details, [
'🚲 7 avail · 4 docks · 11 cap',
@@ -44,7 +45,7 @@ test('selected bikeshare entry preserves source copy and protected-lane policy',
assert.equal(entry.horizonCull, true);
});
test('real station select/clear path publishes one card and creates no native label graphic', () => {
test('real station select/clear path publishes one card and draws no native label', () => {
const calls = [];
const overlayHost = {
setEntries: (...args) => calls.push(['entries', ...args]),
@@ -53,27 +54,36 @@ test('real station select/clear path publishes one card and creates no native la
};
const key = 'austin-capmetro:3790';
const record = makeRecord();
const viewer = { entities: new Cesium.EntityCollection() };
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
_setBikeshareSelectionStateForTest({ viewer, key, record, overlayHost });
const live = (suffix) =>
[...draw.sets.values()].find((set) => !set.disposed && set.spec.id.endsWith(suffix));
const stations = live(':stations');
const selected = live(':selected');
try {
_selectBikeshareStationForTest(key);
assert.equal(record.point.show, false);
assert.equal(viewer.entities.values.length, 1, 'runtime guard requires a real selected entity');
assert.equal(viewer.entities.values[0].label, undefined);
assert.ok(viewer.entities.values[0].point, 'selected point highlight remains native');
assert.equal(stations.items.get(key).show, false, 'the station’s own dot is hidden');
assert.equal(selected.items.size, 1, 'one highlight dot replaces it');
const [highlight] = selected.items.values();
assert.equal(highlight.pos, record.position);
assert.deepEqual(highlight.color, [0, 1, 1, 1], 'cyan');
assert.equal(highlight.pixelSize, 14);
assert.equal(highlight.disableDepthTest, Infinity);
const publication = calls.find(([type]) => type === 'entries');
assert.ok(publication);
assert.equal(publication[1], 'bikeshare-selected');
assert.equal(publication[2].length, 1);
assert.equal(publication[2][0].position, record.point.position);
assert.equal(publication[2][0].position, record.position);
assert.deepEqual(publication[3], BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS);
_clearBikeshareSelectionForTest();
assert.equal(record.point.show, true);
assert.equal(viewer.entities.values.length, 0);
assert.equal(stations.items.get(key).show, true);
assert.equal(selected.items.size, 0);
assert.deepEqual(calls.at(-1), ['clear', 'bikeshare-selected']);
} finally {
_clearBikeshareSelectionForTest();
unbind();
}
});
+29 -20
View File
@@ -8,6 +8,8 @@ import { readFileSync } from 'node:fs';
import * as Cesium from 'cesium';
import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
import { createAnnotationResolver } from '../annotations/resolver.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { createWorldAnnotationRenderer } from '../annotations/worldAnnotationRenderer.js';
const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
@@ -21,7 +23,7 @@ const DATA_MODULES = [
'./local_data/wof_neighborhoods/files.js',
];
/** Modules that use Cesium for outlines but must not draw text with it. */
/** Modules that draw outlines but must not draw text with Cesium. */
const CESIUM_MODULES = [
'../annotations/resolver.js',
'../annotations/worldAnnotationRenderer.js',
@@ -109,21 +111,22 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label',
featureSource,
});
const primitives = [];
const dataSources = [];
const viewer = {
camera: {
positionCartographic: Cesium.Cartographic.fromDegrees(
-97.7431,
30.2672,
3000,
),
const draw = fakeDrawPort();
// The resolver reads the camera through the renderer's camera port; the
// world renderer draws through its draw port.
const viewer = bindFakeCesiumCamera(
{
camera: {
positionCartographic: Cesium.Cartographic.fromDegrees(
-97.7431,
30.2672,
3000,
),
},
scene: { primitives: { add: (p) => primitives.push(p) } },
},
scene: { primitives: { add: (p) => primitives.push(p) } },
dataSources: {
add: (ds) => dataSources.push(ds),
remove() {},
},
};
{ draw },
);
const renderer = createWorldAnnotationRenderer(viewer);
for (const [target, lon, lat] of [
['Austin', -97.7431, 30.2672],
@@ -135,8 +138,8 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label',
3000,
);
const resolved = await resolveAnnotationTarget({
// The resolver reads only the camera (no scene to pick from).
viewer: { camera: viewer.camera },
// The resolver reads only the camera (no query port to pick with).
viewer,
target,
footprint: true,
deferFootprint: true,
@@ -155,8 +158,14 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label',
});
}
assert.equal(primitives.length, 0, 'no primitive collections');
const entities = dataSources.flatMap((ds) => ds.entities.values);
assert.ok(entities.length >= 2, 'the outlines were drawn');
for (const entity of entities) assert.equal(entity.label, undefined);
const live = [...draw.sets.values()].filter((record) => !record.disposed);
const items = live.flatMap((record) => [...record.items.values()]);
assert.ok(items.length >= 2, 'the outlines were drawn');
// Fills and lines only: no point, text or label is drawn for a name.
assert.deepEqual([...new Set(live.map((record) => record.kind))].sort(), [
'lines',
'shapes',
]);
for (const item of items) assert.equal(item.label, undefined);
renderer.destroy();
});
+23 -4
View File
@@ -1,10 +1,29 @@
import * as Cesium from 'cesium';
import { toRadians } from '../geo/index.js';
import { findCamera } from '../render/rendererOf.js';
/** The camera port's pose, or null when there is none to read. */
function poseOf(viewer) {
try {
return findCamera(viewer)?.pose() ?? null;
} catch {
return null;
}
}
/** Camera range with breathing room in both viewport dimensions. */
export function rangeForBoundingSphere(viewer, radius) {
const frustum = viewer.camera?.frustum;
const verticalFov = Number(frustum?.fov) || Cesium.Math.toRadians(60);
const aspectRatio = Math.max(0.5, Number(frustum?.aspectRatio) || 1);
const pose = poseOf(viewer);
const fovy = Number(pose?.fovy);
const aspect = Number(pose?.aspectRatio);
// The frustum's field of view: along its wider side.
const fov =
fovy > 0 && aspect > 1
? 2 * Math.atan(Math.tan(fovy / 2) * aspect)
: fovy > 0
? fovy
: NaN;
const verticalFov = fov || toRadians(60);
const aspectRatio = Math.max(0.5, aspect || 1);
const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * aspectRatio);
const limitingFov = Math.min(verticalFov, horizontalFov);
// Target 57% sphere occupancy so perspective still leaves at least 40%
+36
View File
@@ -0,0 +1,36 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { rangeForBoundingSphere } from './cameraFraming.js';
/** The range as it was read from Cesium's frustum before the camera port. */
function rangeFromFrustum(frustum, radius) {
const verticalFov = frustum.fov;
const aspectRatio = Math.max(0.5, frustum.aspectRatio);
const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * aspectRatio);
const limitingFov = Math.min(verticalFov, horizontalFov);
return (radius / Math.sin((limitingFov * 0.57) / 2)) * 1.05;
}
for (const aspectRatio of [16 / 9, 390 / 844, 1]) {
test(`framing reads the frustum's field of view through the camera port (aspect ${aspectRatio.toFixed(2)})`, () => {
const frustum = new Cesium.PerspectiveFrustum({
fov: Math.PI / 3,
aspectRatio,
near: 1,
far: 1e8,
});
const viewer = bindFakeCesiumCamera({ camera: { frustum } });
const range = rangeForBoundingSphere(viewer, 250);
assert.ok(
Math.abs(range - rangeFromFrustum(frustum, 250)) < 1e-6,
`${range} vs ${rangeFromFrustum(frustum, 250)}`,
);
});
}
test('framing without a camera assumes a 60 degree square view', () => {
const expected = rangeFromFrustum({ fov: Math.PI / 3, aspectRatio: 1 }, 100);
assert.ok(Math.abs(rangeForBoundingSphere({}, 100) - expected) < 1e-9);
});
-93
View File
@@ -1,93 +0,0 @@
// src/data/cameraSensitivity.js
/**
* Shared claims on `camera.percentageChanged`.
*
* `camera.changed` fires once the view has moved by this fraction, and it is a
* single number on the camera that every listener in the app shares. Several
* layers want it finer than the default — traffic, bikeshare and transit all
* ask for 0.05 so they notice they have entered a coverage area — and each of
* them used to write the number directly and hand back whatever it remembered.
*
* That cannot work, because a number is not an owner. Two layers asking for the
* same 0.05 write the same value, so when the first one leaves it sees its own
* number still in place, concludes nothing else has claimed it, and restores
* the coarse default out from under a layer that is still running. The symptom
* is a camera-driven layer that quietly stops noticing the camera: Transit is
* turned off and Bikeshare stops loading new cities until something else nudges
* it.
*
* So ownership is tracked explicitly. Claims are named, the camera gets the
* finest value anyone has asked for, and the original value returns only when
* the last claim is gone. Claiming twice under one name replaces that claim.
*
* This is bookkeeping, not policy: it never decides what a layer should ask
* for, only that nobody's answer is taken away while they still need it.
*/
/** @type {WeakMap<object, {base: number, claims: Map<string, number>}>} */
const _cameras = new WeakMap();
/** The value Cesium starts a camera at, used when the camera reports nothing. */
const DEFAULT_PERCENTAGE_CHANGED = 0.5;
function ledgerFor(camera) {
let ledger = _cameras.get(camera);
if (!ledger) {
const base = Number.isFinite(camera.percentageChanged)
? camera.percentageChanged
: DEFAULT_PERCENTAGE_CHANGED;
ledger = { base, claims: new Map() };
_cameras.set(camera, ledger);
}
return ledger;
}
function applyLedger(camera, ledger) {
let value = ledger.base;
for (const claimed of ledger.claims.values()) {
if (claimed < value) value = claimed;
}
camera.percentageChanged = value;
return value;
}
/**
* Ask for a camera-change sensitivity at least as fine as `value`.
* @param {object|null|undefined} camera A Cesium camera (or anything with `percentageChanged`).
* @param {string} owner Stable claim name, usually the layer id.
* @param {number} value Requested `percentageChanged`.
* @returns {number|null} The value now in force, or null when there is no camera.
*/
export function claimCameraSensitivity(camera, owner, value) {
if (!camera || !owner || !Number.isFinite(value)) return null;
const ledger = ledgerFor(camera);
ledger.claims.set(owner, value);
return applyLedger(camera, ledger);
}
/**
* Give up one claim. The camera keeps the finest value still claimed by
* somebody else, and returns to its original only when none are left.
* @param {object|null|undefined} camera
* @param {string} owner
* @returns {number|null} The value now in force, or null when there is no camera.
*/
export function releaseCameraSensitivity(camera, owner) {
if (!camera || !owner) return null;
const ledger = _cameras.get(camera);
if (!ledger) return null;
if (!ledger.claims.delete(owner)) return camera.percentageChanged;
const applied = applyLedger(camera, ledger);
if (ledger.claims.size === 0) _cameras.delete(camera);
return applied;
}
/**
* Who currently holds a claim. For tests and diagnostics only.
* @param {object|null|undefined} camera
* @returns {Array<string>}
*/
export function cameraSensitivityClaims(camera) {
const ledger = camera ? _cameras.get(camera) : null;
return ledger ? [...ledger.claims.keys()] : [];
}
+1
View File
@@ -66,6 +66,7 @@ export const materializeCctvVisibleCoverageEntities =
export const _extractPickedCameraIdForTest =
layer._extractPickedCameraIdForTest;
export const _setCctvCoverageStateForTest = layer._setCctvCoverageStateForTest;
export const _cctvIconsForTest = layer._cctvIconsForTest;
export const focusCctvRecord = layer.focusCctvRecord;
export const maybeAutoHop = layer.maybeAutoHop;
export const openingCameraId = layer.openingCameraId;
+177 -141
View File
@@ -13,6 +13,11 @@
//
// computeFrustumGeometry is PURE (no viewer, no scene queries) so it runs under
// plain node:test.
import {
bindFakeCesiumCamera,
followEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { entityFollowTarget, followedOf } from './followed.js';
import { test } from 'node:test';
// Preserve structural pins across component qualification and formatter wrapping.
function componentFunctionSource(fn) {
@@ -32,6 +37,7 @@ import cctvLayer, {
_extractPickedCameraIdForTest,
_updateCctvProjectionPlaneForTest,
_setCctvCoverageStateForTest,
_cctvIconsForTest,
_pushAmbientCardEntriesForTest,
_setCctvOverlayHostForTest,
activationProbeClampRange,
@@ -82,27 +88,12 @@ import {
IDLE_CAMERA_COLOR,
LIVE_CAMERA_COLOR,
} from '../layers/cctv/policy.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs';
const ASPECT = 16 / 9;
const toRad = (deg) => (deg * Math.PI) / 180;
const GESTURE_TYPES = {
LEFT_DOWN: 'left-down',
MOUSE_MOVE: 'mouse-move',
LEFT_UP: 'left-up',
LEFT_CLICK: 'left-click',
};
function makeGestureHandler() {
const actions = new Map();
return {
setInputAction(callback, type) {
actions.set(type, callback);
},
fire(type, event) {
actions.get(type)?.(event);
},
};
}
const GESTURE_TYPES = FAKE_EVENT_TYPES;
// Same spherical earth radius projectPoint uses (R = 6371 km) so the
// lat/lon→metres conversion in the assertions matches the module's math.
const M_PER_DEG = (Math.PI / 180) * 6371000;
@@ -293,15 +284,9 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
coverageEntities: [],
projection: null,
}));
const inserted = [];
const viewer = {
entities: {
add(entity) {
inserted.push(entity);
return entity;
},
},
};
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const inserted = () => draw.find('cctv:')?.items ?? new Map();
const activeRecord = records.at(-1);
try {
@@ -316,10 +301,16 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
(record) => record.coverageEntities.length > 0,
);
assert.equal(
inserted.length,
inserted().size,
14 * 5,
'default COVERAGE ON builds the 14-camera visible cohort',
);
assert.ok(
[...inserted().keys()].every((id) =>
/^cctv-cam-\d+-(ray-..|cap)$/.test(id),
),
'coverage lines keep the cctv-<id>-<role> ids',
);
assert.equal(materialized.length, 14);
assert.equal(
activeRecord.coverageEntities.length,
@@ -335,7 +326,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
...records[0],
camera: { ...records[0].camera, id: 'projection-only' },
coverageEntities: [],
projection: { planeEntity: { show: false } },
projection: { plane: { show: false } },
};
_setCctvCoverageStateForTest({
viewer,
@@ -350,22 +341,31 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
projectionOnly.coverageEntities.every((entity) => entity.show),
'COVERAGE OFF keeps the active projection frustum materialized and visible',
);
assert.ok(
projectionOnly.coverageEntities.every(
(entity) => inserted().get(entity.id)?.show === true,
),
'and draws it',
);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
}
});
test('camera icons are violet for video feeds, cyan for stills, amber when active', () => {
const record = (id, feedType) => ({
camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 },
billboard: {},
// Every catalog record is placed as it is made, and drawn there.
position: { x: 6378137, y: 0, z: 0 },
coverageEntities: [],
projection: null,
});
const idleVideo = record('idle-hls', 'hls');
const idleStill = record('idle-image', 'image');
const activeVideo = record('active-hls', 'hls');
const viewer = { entities: { add: (entity) => entity } };
const viewer = {};
const { unbind } = bindFakeDraw(viewer);
try {
// Disabled keeps the active video camera from opening a real projection;
@@ -378,18 +378,23 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ
coverageMode: 'off',
});
refreshCoverageStyles();
assert.equal(idleVideo.billboard.color, LIVE_CAMERA_COLOR);
assert.equal(idleStill.billboard.color, IDLE_CAMERA_COLOR);
assert.equal(activeVideo.billboard.color, ACTIVE_CAMERA_COLOR);
const icons = _cctvIconsForTest();
const color = (record) => icons.item(record.camera.id).color;
assert.deepEqual(color(idleVideo), LIVE_CAMERA_COLOR);
assert.deepEqual(color(idleStill), IDLE_CAMERA_COLOR);
assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR);
assert.equal(icons.item(activeVideo.camera.id).scale, 1.25);
assert.equal(icons.item(idleVideo.camera.id).scale, 1);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
}
});
test('geometry drain pacing yields to tracked and cockpit camera ownership', () => {
assert.deepEqual(cctvGeometryDrainPacing(), { batchSize: 4, delayMs: 120 });
assert.deepEqual(
cctvGeometryDrainPacing({ trackedEntity: { id: 'flight-1' } }),
cctvGeometryDrainPacing({ followed: { key: 'flights:1' } }),
{ batchSize: 2, delayMs: 250 },
);
assert.deepEqual(cctvGeometryDrainPacing({ cockpitActive: true }), {
@@ -404,13 +409,13 @@ test('geometry drain pacing yields to tracked and cockpit camera ownership', ()
});
test('geometry drain rechecks pacing when tracking releases between batches', () => {
let trackedEntity = { id: 'flight-1' };
let followed = { key: 'flights:1' };
const queue = Array.from({ length: 10 }, (_, index) => index + 1);
const visited = [];
const runBatch = () =>
processCctvGeometryDrainBatch({
queue,
readOwnership: () => ({ trackedEntity, cockpitActive: false }),
readOwnership: () => ({ followed, cockpitActive: false }),
visit: (record) => visited.push(record),
progress: () => {},
complete: () => {},
@@ -420,7 +425,7 @@ test('geometry drain rechecks pacing when tracking releases between batches', ()
assert.deepEqual(trackedBatch, { hasMore: true, batchSize: 2, delayMs: 250 });
assert.deepEqual(visited, [1, 2]);
trackedEntity = null;
followed = null;
const untrackedBatch = runBatch();
assert.deepEqual(untrackedBatch, {
hasMore: true,
@@ -696,18 +701,16 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
camera: { id: 'a' },
activationDone: true,
probeClampRangeM: 105,
billboard: { color: 'keep-color', scale: 1.25 },
coverageEntities: [{ show: true }, { show: true }],
projection: { planeEntity: { show: true } },
viewshedPrimitive: viewshedA,
projection: { plane: { show: true } },
viewshedVolume: viewshedA,
},
{
camera: { id: 'b' },
activationDone: true,
probeClampRangeM: 146,
billboard: { color: 'keep-color', scale: 1 },
projection: null,
viewshedPrimitive: viewshedB,
viewshedVolume: viewshedB,
},
];
const destroyed = [];
@@ -716,7 +719,7 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
records,
(record) => {
destroyed.push(record.camera.id);
record.viewshedPrimitive = null;
record.viewshedVolume = null;
},
'a',
);
@@ -727,10 +730,10 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
),
[false, false],
);
assert.equal(records[0].projection.planeEntity.show, false);
assert.equal(records[0].projection.plane.show, false);
assert.deepEqual(destroyed, ['a', 'b']);
assert.equal(records[0].viewshedPrimitive, null);
assert.equal(records[1].viewshedPrimitive, null);
assert.equal(records[0].viewshedVolume, null);
assert.equal(records[1].viewshedVolume, null);
assert.deepEqual(
records.map((record) => record.probeClampRangeM),
[null, null],
@@ -739,13 +742,6 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
records.map((record) => record.activationDone),
[false, true],
);
assert.deepEqual(
records.map((record) => record.billboard),
[
{ color: 'keep-color', scale: 1.25 },
{ color: 'keep-color', scale: 1 },
],
);
});
test('real active monitor plane owns one protected host label and no native label entity', () => {
@@ -755,7 +751,8 @@ test('real active monitor plane owns one protected host label and no native labe
setVisible: (...args) => calls.push(['visible', ...args]),
clearSource: (...args) => calls.push(['clear', ...args]),
};
const viewer = { entities: new Cesium.EntityCollection() };
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const record = {
camera: {
...UNCLAMPED_CAMERA,
@@ -779,17 +776,23 @@ test('real active monitor plane owns one protected host label and no native labe
});
refreshCoverageStyles();
assert.ok(runtime.plane, 'runtime guard requires a real monitor plane');
const planes = draw.find('cctv:')
? [...draw.sets.values()].filter((set) => set.kind === 'quads')
: [];
assert.equal(planes.length, 1, 'the plane draws as a quad');
const quad = planes[0].items.get(`cctv-${record.camera.id}-plane`);
assert.ok(quad, 'under its cctv-<id>-plane id');
assert.equal(quad.alpha, 0.95);
assert.deepEqual(quad.size, [
record.frustumGeometry.halfW * 2,
record.frustumGeometry.halfH * 2,
]);
assert.ok(quad.outline, 'with its outline');
assert.equal(quad.meta.cameraId, record.camera.id);
assert.ok(
runtime.planeEntity,
'runtime guard requires a real monitor-plane entity',
);
assert.equal(runtime.planeEntity.label, undefined);
assert.ok(
runtime.planeEntity.plane,
'monitor plane geometry remains native',
);
assert.ok(
viewer.entities.values.every((entity) => entity.label === undefined),
[...draw.sets.values()].every((set) => set.kind !== 'labels'),
'and no native label',
);
const publication = calls.find(
([type, sourceId]) =>
@@ -805,7 +808,8 @@ test('real active monitor plane owns one protected host label and no native labe
assert.equal(entry.position(), runtime.labelPosition);
assert.equal(entry.protected, true);
assert.equal(entry.paintLane, 'selected');
assert.equal(runtime.planeEntity.show, true);
assert.equal(runtime.plane.show, true);
assert.equal(quad.show, true, 'shown once projected');
const cachedPosition = runtime.labelPosition;
record.frustumPositions.label = Cesium.Cartesian3.add(
@@ -833,7 +837,8 @@ test('real active monitor plane owns one protected host label and no native labe
showProjection: false,
});
refreshCoverageStyles();
assert.equal(runtime.planeEntity.show, false);
assert.equal(runtime.plane.show, false);
assert.equal(planes[0].items.get(quad.id).show, false);
assert.deepEqual(calls.slice(-2), [
['clear', 'cctv-projection'],
['visible', 'cctv-projection', false],
@@ -841,6 +846,7 @@ test('real active monitor plane owns one protected host label and no native labe
} finally {
_setCctvCoverageStateForTest({ enabled: false });
_setCctvOverlayHostForTest();
unbind();
}
});
@@ -893,13 +899,18 @@ test('CCTV disable→enable defers the active-camera re-probe until its next act
test('CCTV focus distinguishes tracking ownership from a missing active camera', () => {
let flyCalls = 0;
const viewer = {
trackedEntity: { id: 'tracked-flight' },
camera: {
flyToBoundingSphere() {
flyCalls += 1;
},
},
// 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: {},
};
bindFakeCesiumCamera(viewer);
followEntity(viewer, { id: 'tracked-flight' });
const record = {
camera: { rangeM: 210, headingDeg: 41 },
position: { x: 1, y: 2, z: 3 },
@@ -931,6 +942,7 @@ test('CCTV focus reports when the camera flight starts', () => {
},
},
};
bindFakeCesiumCamera(viewer);
const record = {
camera: { rangeM: 210, headingDeg: 41 },
position: { x: 1, y: 2, z: 3 },
@@ -951,6 +963,7 @@ test('CCTV focus refuses camera flights while cockpit owns the view', () => {
},
},
};
bindFakeCesiumCamera(viewer);
const record = {
camera: { rangeM: 210, headingDeg: 41 },
position: { x: 1, y: 2, z: 3 },
@@ -1003,7 +1016,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
assert.deepEqual(requests, [{ cameraId: 'atx-cam-3' }]);
assert.match(
componentFunctionSource(cctvLayer.init),
/bindCctvWorldClickGesture\(_clickHandler/,
/bindCctvWorldClickGesture\(\s*input,/,
);
assert.match(
componentFunctionSource(cctvLayer.init),
@@ -1026,10 +1039,8 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
// ─── Empty-space deselection and stable null-active state ──────────────────
function makeDeselectViewer() {
return {
entities: new Cesium.EntityCollection(),
const viewer = {
isDestroyed: () => false,
trackedEntity: { id: 'sibling-track-owner' },
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 4_000),
positionCartographic: Cesium.Cartographic.fromDegrees(
@@ -1052,6 +1063,20 @@ function makeDeselectViewer() {
requestRender() {},
},
};
// The layer's lines and plane draw through this. The eye has a pose only
// once a test places it (`viewer.eye`, degrees and metres).
viewer.draw = bindFakeDraw(viewer, {
camera: {
pose: () => (viewer.eye ? { ...viewer.eye } : undefined),
on: () => () => {},
// A sibling layer's follow owns the camera.
followed: entityFollowTarget({ id: 'sibling-track-owner' }, {}),
follow(target) {
this.followed = target;
},
},
}).draw;
return viewer;
}
function makeDeselectRecord(id, index = 0) {
@@ -1085,7 +1110,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
assert.equal(cctvEmptyClickDeselects(null, { activeCameraId: null }), false);
assert.equal(
cctvEmptyClickDeselects(
{ id: 'registered-sibling' },
{ set: 'flights:1', id: 'registered-sibling', surface: false },
{
activeCameraId: 'cam-1',
},
@@ -1094,7 +1119,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
assert.equal(
cctvEmptyClickDeselects(
{ id: { id: 'unregistered-local-entity' } },
{ set: '', id: 'unregistered-local-entity', surface: false },
{
activeCameraId: 'cam-1',
},
@@ -1103,7 +1128,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
assert.equal(
cctvEmptyClickDeselects(
{ primitive: { id: 'unregistered-primitive' } },
{ set: '', id: 'unregistered-primitive', surface: false },
{
activeCameraId: 'cam-1',
},
@@ -1112,7 +1137,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
assert.equal(
cctvEmptyClickDeselects(
{ id: '' },
{ set: '', id: '', surface: false },
{
activeCameraId: 'cam-1',
},
@@ -1122,13 +1147,13 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
assert.equal(
cctvEmptyClickDeselects(
{ primitive: {} },
{ set: '', id: null, surface: false },
{
activeCameraId: 'cam-1',
},
),
true,
'an ID-less surface pick remains true empty space',
'something with no id remains true empty space',
);
const initSource = componentFunctionSource(cctvLayer.init);
@@ -1142,55 +1167,86 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
});
test('CCTV camera extraction requires layer ownership, not a colliding sibling ID', () => {
const billboard = { id: 'shared-id' };
const ownedCoverageEntity = {
id: 'cctv-shared-id-cap',
properties: { cctvCameraId: 'shared-id' },
};
const record = {
...makeDeselectRecord('shared-id'),
billboard,
coverageEntities: [ownedCoverageEntity],
};
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const record = makeDeselectRecord('shared-id');
_setCctvCoverageStateForTest({
viewer,
records: [record],
activeCameraId: 'shared-id',
});
try {
refreshCoverageStyles();
const coverage = [...draw.sets.values()].find(
(set) => set.kind === 'lines' && set.spec.id.startsWith('cctv:'),
);
assert.ok(coverage.items.has('cctv-shared-id-cap'));
const lineHit = (set, id) => ({
set,
id,
meta: { cameraId: 'shared-id' },
surface: false,
});
assert.equal(
_extractPickedCameraIdForTest({ id: 'shared-id', primitive: billboard }),
_extractPickedCameraIdForTest({
set: _cctvIconsForTest().setId,
id: 'shared-id',
surface: false,
}),
'shared-id',
);
assert.equal(
_extractPickedCameraIdForTest({
set: 'sibling:1:icons',
id: 'shared-id',
primitive: { id: 'shared-id' },
surface: false,
}),
null,
'a sibling primitive with the same canonical ID cannot activate CCTV',
);
assert.equal(
_extractPickedCameraIdForTest({ id: { id: 'shared-id' } }),
null,
'a sibling Entity with the same canonical ID cannot activate CCTV',
);
assert.equal(
_extractPickedCameraIdForTest({ id: ownedCoverageEntity }),
'shared-id',
'an exact stored CCTV coverage Entity retains activation ownership',
"a sibling set's icon with the same canonical ID cannot activate CCTV",
);
assert.equal(
_extractPickedCameraIdForTest({
id: {
id: 'sibling-entity',
properties: { cctvCameraId: 'shared-id' },
},
set: _cctvIconsForTest().setId,
id: 'not-a-camera',
surface: false,
}),
null,
'an id the icon book does not draw is not a camera',
);
assert.equal(
_extractPickedCameraIdForTest(
lineHit(coverage.spec.id, 'cctv-shared-id-cap'),
),
'shared-id',
'a coverage line the record draws retains activation ownership',
);
assert.equal(
_extractPickedCameraIdForTest(
lineHit('sibling:1:lines', 'cctv-shared-id-cap'),
),
null,
"a sibling set's item with a CCTV id and meta cannot activate CCTV",
);
assert.equal(
_extractPickedCameraIdForTest({
set: 'sibling:1:entities',
id: 'sibling-entity',
meta: { cctvCameraId: 'shared-id', cameraId: 'shared-id' },
surface: false,
}),
null,
'a sibling cannot impersonate CCTV by copying its property shape',
);
assert.equal(
_extractPickedCameraIdForTest(
lineHit(coverage.spec.id, 'cctv-shared-id-stray'),
),
null,
'a camera id alone is not ownership: the record must draw the item',
);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
}
});
@@ -1231,7 +1287,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
pitch: viewer.camera.pitch,
roll: viewer.camera.roll,
transform: Cesium.Matrix4.clone(viewer.camera.transform),
trackedEntity: viewer.trackedEntity,
followed: followedOf(viewer),
};
assert.equal(deactivateActiveCamera(), true);
@@ -1244,7 +1300,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
assert.equal(publications.at(-1).activeCameraId, null);
assert.equal(publications.at(-1).activeCamera, null);
assert.equal(publications.at(-1).enabled, true);
assert.equal(runtime.planeEntity.show, false);
assert.equal(runtime.plane.show, false);
assert.equal(record.probeClampRangeM, null);
assert.equal(record.activationDone, false);
assert.deepEqual(viewer.camera.positionWC, pose.positionWC);
@@ -1256,7 +1312,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
assert.equal(viewer.camera.pitch, pose.pitch);
assert.equal(viewer.camera.roll, pose.roll);
assert.deepEqual(viewer.camera.transform, pose.transform);
assert.equal(viewer.trackedEntity, pose.trackedEntity);
assert.equal(followedOf(viewer), pose.followed);
assert.equal(viewer.camera.flyCalls || 0, 0);
unsubscribe();
} finally {
@@ -1314,16 +1370,7 @@ test('CCTV opens on the camera nearest the viewer, not the first in the catalog'
// QA 2026-11-05: at King's Cross, turning CCTV on showed a Sydney camera,
// the first catalog record, instead of the TfL camera 0.3 km away.
const viewer = makeDeselectViewer();
viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-0.1209,
51.5295,
187,
);
viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-0.1209,
51.5295,
187,
);
viewer.eye = { lon: -0.1209, lat: 51.5295, height: 187 };
const sydney = makeDeselectRecord('au-sydney');
sydney.camera = { ...sydney.camera, lat: -34.03, lon: 151.11 };
const london = makeDeselectRecord('gb-kings-cross');
@@ -1358,11 +1405,7 @@ test('the opening camera follows a shared view that lands after CCTV turned on,
// A share link turns CCTV on before its flight lands, so enable() picks
// from the startup view; the flight's settled move re-picks near London.
const viewer = makeDeselectViewer();
viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-0.1209,
51.5295,
187,
);
viewer.eye = { lon: -0.1209, lat: 51.5295, height: 187 };
const sydney = makeDeselectRecord('au-sydney');
sydney.camera = { ...sydney.camera, lat: -34.03, lon: 151.11 };
const london = makeDeselectRecord('gb-kings-cross');
@@ -1529,29 +1572,22 @@ test('active CCTV camera is absent from host by default and protected only when
test('CCTV drag-then-release over a camera is inert, while a clean tap activates and dispatches', () => {
let timeMs = 0;
let activationCalls = 0;
const handler = makeGestureHandler();
const { input, handler } = fakeInput({ scene: {} }, { now: () => timeMs });
const target = new EventTarget();
const requests = [];
target.addEventListener(CCTV_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
bindCctvWorldClickGesture(
handler,
() => {
activateCctvCameraFromWorldClick(
'atx-cam-3',
() => {
activationCalls += 1;
return CCTV_ACTIVATION_RESULT.ACTIVATED;
},
target,
);
},
{
now: () => timeMs,
eventTypes: GESTURE_TYPES,
},
);
bindCctvWorldClickGesture(input, () => {
activateCctvCameraFromWorldClick(
'atx-cam-3',
() => {
activationCalls += 1;
return CCTV_ACTIVATION_RESULT.ACTIVATED;
},
target,
);
});
handler.fire(GESTURE_TYPES.LEFT_DOWN, { position: { x: 10, y: 10 } });
timeMs = 20;
+241 -224
View File
@@ -8,7 +8,7 @@
* - Pure drag math (this top section): ray↔axis closest-point, ray↔plane
* intersection with a grazing-angle guard, ring angles. All unit-tested
* under node:test with zero scene dependencies.
* - createCalibrationGizmo (below): the entity + ScreenSpaceEventHandler
* - createCalibrationGizmo (below): the draw-set + pointer-input
* controller that renders grab-able handles on the ACTIVE camera and turns
* drags into calibration patches through a narrow callback interface. It
* never touches the layer's records/stores directly.
@@ -23,8 +23,10 @@
* throttled hover picks while ADJUST mode is on) — the layer's zero-steady-state-query
* invariant is untouched.
*/
import * as Cesium from 'cesium';
import { isPointerFree } from './inputOwnership.js';
import { inputFor } from '../input/dispatcher.js';
import { canvasOf, drawOf, findQuery } from '../render/rendererOf.js';
import { eastNorthUp } from '../geo/frames.js';
import { add, dot, scale, sub } from '../geo/vector.js';
// Grazing guard (spec §5): reject plane intersections when the view ray is
// nearly parallel to the constraint plane — the hit point races to infinity
@@ -33,8 +35,6 @@ const GRAZING_DOT_MIN = 0.08;
// Near-parallel guard for ray/axis closest-point (denominator 1 - (d·a)²).
const PARALLEL_EPS = 1e-6;
const scratchW = new Cesium.Cartesian3();
/**
* Parameter t (metres) along an axis line of the point on that axis closest
* to a mouse ray. Both directions must be normalized.
@@ -43,60 +43,52 @@ const scratchW = new Cesium.Cartesian3();
* t = (e − b·d) / (1 − b²) with b = rayDir·axisDir, w = rayOrigin − axisOrigin,
* d = rayDir·w, e = axisDir·w.
*
* @param {Cesium.Cartesian3} rayOrigin
* @param {Cesium.Cartesian3} rayDir - Unit.
* @param {Cesium.Cartesian3} axisOrigin
* @param {Cesium.Cartesian3} axisDir - Unit.
* Vectors are ECEF `{x, y, z}`.
* @param {{x: number, y: number, z: number}} rayOrigin
* @param {{x: number, y: number, z: number}} rayDir - Unit.
* @param {{x: number, y: number, z: number}} axisOrigin
* @param {{x: number, y: number, z: number}} axisDir - Unit.
* @returns {number|null} Axis parameter in metres, or null when near-parallel.
*/
export function closestParamOnAxis(rayOrigin, rayDir, axisOrigin, axisDir) {
const b = Cesium.Cartesian3.dot(rayDir, axisDir);
const b = dot(rayDir, axisDir);
const denom = 1 - b * b;
if (Math.abs(denom) < PARALLEL_EPS) return null;
const w = Cesium.Cartesian3.subtract(rayOrigin, axisOrigin, scratchW);
const d = Cesium.Cartesian3.dot(rayDir, w);
const e = Cesium.Cartesian3.dot(axisDir, w);
const w = sub(rayOrigin, axisOrigin);
const d = dot(rayDir, w);
const e = dot(axisDir, w);
return (e - b * d) / denom;
}
/**
* Intersects a mouse ray with a plane, refusing grazing configurations
* (|rayDir·normal| < 0.08) and hits behind the ray origin.
* @param {Cesium.Cartesian3} rayOrigin
* @param {Cesium.Cartesian3} rayDir - Unit.
* @param {Cesium.Cartesian3} planeOrigin
* @param {Cesium.Cartesian3} planeNormal - Unit.
* @returns {Cesium.Cartesian3|null} Hit point (new instance), or null.
* @param {{x: number, y: number, z: number}} rayOrigin
* @param {{x: number, y: number, z: number}} rayDir - Unit.
* @param {{x: number, y: number, z: number}} planeOrigin
* @param {{x: number, y: number, z: number}} planeNormal - Unit.
* @returns {{x: number, y: number, z: number}|null} Hit point (new), or null.
*/
export function rayPlaneIntersect(rayOrigin, rayDir, planeOrigin, planeNormal) {
const denom = Cesium.Cartesian3.dot(rayDir, planeNormal);
const denom = dot(rayDir, planeNormal);
if (Math.abs(denom) < GRAZING_DOT_MIN) return null;
const toPlane = Cesium.Cartesian3.subtract(planeOrigin, rayOrigin, scratchW);
const s = Cesium.Cartesian3.dot(toPlane, planeNormal) / denom;
const s = dot(sub(planeOrigin, rayOrigin), planeNormal) / denom;
if (s < 0) return null;
const hit = Cesium.Cartesian3.multiplyByScalar(
rayDir,
s,
new Cesium.Cartesian3(),
);
return Cesium.Cartesian3.add(rayOrigin, hit, hit);
return add(rayOrigin, scale(rayDir, s));
}
/**
* Angle (radians, atan2 convention) of a point around a ring center in the
* plane spanned by two orthonormal basis vectors.
* @param {Cesium.Cartesian3} hitPoint - Point on/near the ring plane.
* @param {Cesium.Cartesian3} center - Ring center.
* @param {Cesium.Cartesian3} basisA - In-plane unit vector (angle 0).
* @param {Cesium.Cartesian3} basisB - In-plane unit vector (angle +90°).
* @param {{x: number, y: number, z: number}} hitPoint - Point on/near the ring plane.
* @param {{x: number, y: number, z: number}} center - Ring center.
* @param {{x: number, y: number, z: number}} basisA - In-plane unit vector (angle 0).
* @param {{x: number, y: number, z: number}} basisB - In-plane unit vector (angle +90°).
* @returns {number} Angle in (−π, π].
*/
export function ringAngle(hitPoint, center, basisA, basisB) {
const v = Cesium.Cartesian3.subtract(hitPoint, center, scratchW);
return Math.atan2(
Cesium.Cartesian3.dot(v, basisB),
Cesium.Cartesian3.dot(v, basisA),
);
const v = sub(hitPoint, center);
return Math.atan2(dot(v, basisB), dot(v, basisA));
}
/**
@@ -117,9 +109,9 @@ export function signedAngleDelta(fromRad, toRad) {
// Gizmo controller
// ---------------------------------------------------------------------------
/** Entity id prefix for every gizmo part — the layer's pick-owner regex and
* click-to-select guard key off this. Gizmo entities NEVER carry a
* `cctvCameraId` property, so the layer's selection path ignores them. */
/** Item id prefix for every gizmo part — the layer's pick-owner regex and
* click-to-select guard key off this. Gizmo parts NEVER get a camera id in
* the layer's pick store, so the layer's selection path ignores them. */
export const GIZMO_ID_PREFIX = 'cctv-gizmo-';
const RING_SEGMENTS = 96;
@@ -130,42 +122,46 @@ const ARROW_LENGTH_FACTOR = 1.6;
const DRAG_THROTTLE_MS = 16;
const HOVER_THROTTLE_MS = 120;
const COLOR_RING_HEADING = Cesium.Color.fromCssColorString('#35d8ff');
const COLOR_RING_PITCH = Cesium.Color.fromCssColorString('#ff5fd0');
const COLOR_MOVE_EAST = Cesium.Color.fromCssColorString('#ff5252');
const COLOR_MOVE_NORTH = Cesium.Color.fromCssColorString('#52ff7a');
const COLOR_MOVE_UP = Cesium.Color.fromCssColorString('#5b8cff');
const COLOR_HANDLE = Cesium.Color.fromCssColorString('#ffd97a');
/** A `#rrggbb` colour at `alpha`, as the renderer's 0..1 RGBA. */
function rgba(hex, alpha = 1) {
const n = Number.parseInt(hex.slice(1), 16);
return [
((n >> 16) & 255) / 255,
((n >> 8) & 255) / 255,
(n & 255) / 255,
alpha,
];
}
const COLOR_RING_HEADING = '#35d8ff';
const COLOR_RING_PITCH = '#ff5fd0';
const COLOR_MOVE_EAST = '#ff5252';
const COLOR_MOVE_NORTH = '#52ff7a';
const COLOR_MOVE_UP = '#5b8cff';
const COLOR_HANDLE = '#ffd97a';
const HANDLE_OUTLINE = [0, 0, 0, 0.7];
const toRadians = (deg) => (deg * Math.PI) / 180;
const toDeg = (rad) => (rad * 180) / Math.PI;
/**
* Local ENU unit axes at an ECEF position.
* @param {Cesium.Cartesian3} position
* @returns {{east: Cesium.Cartesian3, north: Cesium.Cartesian3, up: Cesium.Cartesian3}}
* @param {{x: number, y: number, z: number}} position
* @returns {{east: object, north: object, up: object}}
*/
function enuAxes(position) {
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const rot = Cesium.Matrix4.getMatrix3(frame, new Cesium.Matrix3());
return {
east: Cesium.Matrix3.getColumn(rot, 0, new Cesium.Cartesian3()),
north: Cesium.Matrix3.getColumn(rot, 1, new Cesium.Cartesian3()),
up: Cesium.Matrix3.getColumn(rot, 2, new Cesium.Cartesian3()),
};
const frame = eastNorthUp(position);
return { east: frame.x, north: frame.y, up: frame.z };
}
/** a*sa + b*sb (fresh Cartesian3). */
/** a*sa + b*sb. */
function combine2(a, sa, b, sb) {
const out = Cesium.Cartesian3.multiplyByScalar(
a,
sa,
new Cesium.Cartesian3(),
);
const t = Cesium.Cartesian3.multiplyByScalar(b, sb, new Cesium.Cartesian3());
return Cesium.Cartesian3.add(out, t, out);
return add(scale(a, sa), scale(b, sb));
}
/** The midpoint of two points. */
const midpoint = (a, b) => scale(add(a, b), 0.5);
/**
* View-frame unit vectors for a pose within a local ENU frame: horizontal
* forward, viewer-right, and the full pitched view axis.
@@ -192,25 +188,57 @@ function ringPositions(center, radius, basisA, basisB) {
const positions = [];
for (let i = 0; i <= RING_SEGMENTS; i++) {
const angle = (i / RING_SEGMENTS) * 2 * Math.PI;
const offset = combine2(
basisA,
Math.cos(angle) * radius,
basisB,
Math.sin(angle) * radius,
positions.push(
add(
center,
combine2(
basisA,
Math.cos(angle) * radius,
basisB,
Math.sin(angle) * radius,
),
),
);
positions.push(Cesium.Cartesian3.add(center, offset, offset));
}
return positions;
}
/** The ring and arrow parts: their colour, width and whether an arrow. */
const LINE_PARTS = Object.freeze([
['ring-heading', COLOR_RING_HEADING, 3, false],
['ring-pitch', COLOR_RING_PITCH, 3, false],
['move-east', COLOR_MOVE_EAST, 12, true],
['move-north', COLOR_MOVE_NORTH, 12, true],
['move-up', COLOR_MOVE_UP, 12, true],
]);
/** The point parts (an arrow's tip included): colour and first size. */
const POINT_PARTS = Object.freeze([
['move-east', COLOR_MOVE_EAST, 14],
['move-north', COLOR_MOVE_NORTH, 14],
['move-up', COLOR_MOVE_UP, 14],
['handle-range', COLOR_HANDLE, 13],
['handle-fov-l', COLOR_HANDLE, 10],
['handle-fov-r', COLOR_HANDLE, 10],
]);
/** Every part a pick can grab. */
const PARTS = new Set([
...LINE_PARTS.map(([part]) => part),
...POINT_PARTS.map(([part]) => part),
]);
let gizmoInstances = 0;
/**
* Creates the calibration gizmo controller (design §3c). Renders grab-able
* handles for the ACTIVE camera's 7 calibration DOF and turns pointer drags
* into calibration patches through a narrow callback interface — the gizmo
* never touches layer records/stores directly.
* never touches layer records/stores directly. It draws through the
* renderer's draw port (a line set for the rings and arrows, a point set
* for the handles and arrow tips, each item `cctv-gizmo-<part>`) and picks
* and casts rays through its query port.
*
* @param {Object} deps
* @param {Cesium.Viewer} deps.viewer
* @param {object} deps.viewer - The viewer whose renderer draws it.
* @param {function(): Object|null} deps.getActiveRecord - Returns the record
* the gizmo should attach to, or null to hide (layer decides: enabled +
* calibration mode + active camera).
@@ -221,7 +249,7 @@ function ringPositions(center, radius, basisA, basisB) {
* end, for the PINNED drag record.
* @returns {{setEnabled: function(boolean): void, refresh: function(): void,
* destroy: function(): void, isDragging: function(): boolean,
* isEnabled: function(): boolean}}
* isEnabled: function(): boolean, partsForTest: function(): Object}}
*/
export function createCalibrationGizmo({
viewer,
@@ -234,73 +262,70 @@ export function createCalibrationGizmo({
let hoveredId = null;
let lastDragAt = 0;
let lastHoverAt = 0;
const entities = new Map(); // part -> Entity
// Whether the parts are drawn now, and each point part's pixel size.
let shown = false;
const pointSizes = new Map(POINT_PARTS.map(([part, , size]) => [part, size]));
// The parts' geometry as last drawn: ECEF line positions and point spots.
const linePositions = new Map();
const pointPositions = new Map();
const scene = viewer.scene;
const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
const input = inputFor(viewer);
let releaseCamera = null;
/** Adds (or re-adds) a gizmo entity, clearing any stale duplicate id. */
function addEntity(part, options) {
const id = `${GIZMO_ID_PREFIX}${part}`;
const stale = viewer.entities.getById(id);
if (stale) viewer.entities.remove(stale);
const entity = viewer.entities.add({ id, show: false, ...options });
entities.set(part, entity);
return entity;
}
const instance = ++gizmoInstances;
const draw = drawOf(viewer);
const lines = draw.lines({ id: `cctv-gizmo:${instance}:lines` });
const points = draw.points({ id: `cctv-gizmo:${instance}:points` });
function polylinePart(part, color, width, arrow = false) {
addEntity(part, {
...(arrow
? {
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize: 14,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.7),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
}
: {}),
polyline: {
positions: [],
width,
material: arrow
? new Cesium.PolylineArrowMaterialProperty(color)
: color.withAlpha(0.9),
/** The rings and arrows as they now are. */
function lineItems() {
const items = [];
for (const [part, color, widthPx, arrow] of LINE_PARTS) {
const positions = linePositions.get(part);
if (!positions) continue;
items.push({
id: `${GIZMO_ID_PREFIX}${part}`,
positions,
widthPx,
mode: '3d',
style: arrow
? { kind: 'arrow', color: rgba(color) }
: { kind: 'solid', color: rgba(color, 0.9) },
// Standard gizmo convention: parts behind geometry stay clearly
// visible, just dimmed (a street-level mount buries half the heading
// ring in sloped photogrammetry tiles — smoke-tested 2026-07-05).
depthFailMaterial: color.withAlpha(0.45),
},
});
depthFail: { kind: 'solid', color: rgba(color, 0.45) },
show: shown,
});
}
return items;
}
function pointPart(part, color, pixelSize) {
addEntity(part, {
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.7),
/** The handles and arrow tips as they now are. */
function pointItems() {
const items = [];
for (const [part, color] of POINT_PARTS) {
const pos = pointPositions.get(part);
if (!pos) continue;
items.push({
id: `${GIZMO_ID_PREFIX}${part}`,
pos,
pixelSize: pointSizes.get(part),
color: rgba(color),
outlineColor: HANDLE_OUTLINE,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
disableDepthTest: Number.POSITIVE_INFINITY,
show: shown,
});
}
return items;
}
polylinePart('ring-heading', COLOR_RING_HEADING, 3);
polylinePart('ring-pitch', COLOR_RING_PITCH, 3);
polylinePart('move-east', COLOR_MOVE_EAST, 12, true);
polylinePart('move-north', COLOR_MOVE_NORTH, 12, true);
polylinePart('move-up', COLOR_MOVE_UP, 12, true);
pointPart('handle-range', COLOR_HANDLE, 13);
pointPart('handle-fov-l', COLOR_HANDLE, 10);
pointPart('handle-fov-r', COLOR_HANDLE, 10);
function hideAll() {
for (const entity of entities.values()) entity.show = false;
if (!shown) return;
shown = false;
lines.upsert(lineItems());
points.upsert(pointItems());
}
/** Recomputes every handle's geometry from the active record's CURRENT pose
@@ -328,69 +353,52 @@ export function createCalibrationGizmo({
);
const arrowLen = radius * ARROW_LENGTH_FACTOR;
entities.get('ring-heading').polyline.positions = ringPositions(
mount,
radius,
axes.north,
axes.east,
linePositions.set(
'ring-heading',
ringPositions(mount, radius, axes.north, axes.east),
);
entities.get('ring-pitch').polyline.positions = ringPositions(
mount,
radius,
forwardHoriz,
axes.up,
linePositions.set(
'ring-pitch',
ringPositions(mount, radius, forwardHoriz, axes.up),
);
const arrowTo = (dir) => [
mount,
Cesium.Cartesian3.add(
mount,
Cesium.Cartesian3.multiplyByScalar(
dir,
arrowLen,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
),
];
const eastArrow = arrowTo(axes.east);
const northArrow = arrowTo(axes.north);
const upArrow = arrowTo(axes.up);
entities.get('move-east').polyline.positions = eastArrow;
entities.get('move-east').position = eastArrow[1];
entities.get('move-north').polyline.positions = northArrow;
entities.get('move-north').position = northArrow[1];
entities.get('move-up').polyline.positions = upArrow;
entities.get('move-up').position = upArrow[1];
entities.get('handle-range').position = positions.capCenter;
entities.get('handle-fov-l').position = Cesium.Cartesian3.midpoint(
positions.tl,
positions.bl,
new Cesium.Cartesian3(),
);
entities.get('handle-fov-r').position = Cesium.Cartesian3.midpoint(
positions.tr,
positions.br,
new Cesium.Cartesian3(),
);
for (const entity of entities.values()) entity.show = true;
const arrowTo = (dir) => [mount, add(mount, scale(dir, arrowLen))];
for (const [part, dir] of [
['move-east', axes.east],
['move-north', axes.north],
['move-up', axes.up],
]) {
const arrow = arrowTo(dir);
linePositions.set(part, arrow);
pointPositions.set(part, arrow[1]);
}
pointPositions.set('handle-range', positions.capCenter);
pointPositions.set('handle-fov-l', midpoint(positions.tl, positions.bl));
pointPositions.set('handle-fov-r', midpoint(positions.tr, positions.br));
shown = true;
lines.upsert(lineItems());
points.upsert(pointItems());
}
/** Extracts a gizmo part name from a pick result, or null. */
function gizmoPartFrom(picked) {
const id = picked?.id?.id ?? picked?.id;
/** The gizmo part a pick hit is, or null. */
function gizmoPartFrom(hit) {
if (!hit || (hit.set !== lines.id && hit.set !== points.id)) return null;
const id = hit.id;
if (typeof id !== 'string' || !id.startsWith(GIZMO_ID_PREFIX)) return null;
return id.slice(GIZMO_ID_PREFIX.length);
const part = id.slice(GIZMO_ID_PREFIX.length);
return PARTS.has(part) ? part : null;
}
function pickGizmoPart(windowPosition) {
const query = findQuery(viewer);
if (!query || !windowPosition) return null;
const { x, y } = windowPosition;
// Gizmo primitives render depth-test-free and should be the topmost pick.
// Take the cheap single-result path first: a full drillPick can stall for
// tens of seconds under software GL even when its first result is already
// the gizmo. Retain drillPick for uncommon overlap/fallback cases.
try {
const picked = scene.pick(windowPosition, 14, 14);
const part = gizmoPartFrom(picked);
if (part && entities.get(part)?.show) return part;
const part = gizmoPartFrom(query.pick(x, y, { width: 14, height: 14 }));
if (part && shown) return part;
} catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] pick threw:', err?.message || err);
@@ -399,7 +407,8 @@ export function createCalibrationGizmo({
let results = [];
try {
results = scene.drillPick(windowPosition, 6, 14, 14) || [];
results =
query.drillPick(x, y, { limit: 6, width: 14, height: 14 }) || [];
} catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] drillPick threw:', err?.message || err);
@@ -409,52 +418,54 @@ export function createCalibrationGizmo({
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug(
'[CCTV:gizmo] drillPick @',
windowPosition?.x,
windowPosition?.y,
x,
y,
'→',
JSON.stringify(
results.map((r) =>
String(r?.id?.id ?? r?.id ?? r?.primitive?.constructor?.name),
results.map((hit) =>
hit.surface ? '(surface)' : `${hit.set}/${hit.id}`,
),
),
);
}
for (const picked of results) {
const part = gizmoPartFrom(picked);
if (part && entities.get(part)?.show) return part;
for (const hit of results) {
const part = gizmoPartFrom(hit);
if (part && shown) return part;
}
return null;
}
function pickRay(windowPosition) {
try {
return viewer.camera.getPickRay(windowPosition) || null;
return (
findQuery(viewer)?.pickRay(windowPosition.x, windowPosition.y) || null
);
} catch {
return null;
}
}
function setCursor(value) {
if (scene.canvas?.style) scene.canvas.style.cursor = value;
const style = canvasOf(viewer)?.style;
if (style) style.cursor = value;
}
function setHovered(part) {
const nextId = part ? `${GIZMO_ID_PREFIX}${part}` : null;
if (nextId === hoveredId) return;
hoveredId = nextId;
// Hover feedback must NEVER touch polyline geometry: a width change makes
// Cesium rebuild the batched polyline primitive, and until the next render
// the part vanishes from the pick buffer — so the very hover that finds a
// ring makes the following LEFT_DOWN miss it (root-caused via the QA
// harness's synthetic drag, 2026-07-05). Rings/arrows get cursor feedback
// only; point handles are PointPrimitives (live-updatable, no rebuild), so
// they keep the size bump.
for (const [name, entity] of entities.entries()) {
if (!entity.point) continue;
// Hover feedback must NEVER touch line geometry: a width change rebuilds
// the line, and until the next render the part vanishes from the pick
// buffer — so the very hover that finds a ring makes the following
// LEFT_DOWN miss it (root-caused via the QA harness's synthetic drag,
// 2026-07-05). Rings/arrows get cursor feedback only; point handles
// (an arrow's tip included) change size in place, so they keep the size
// bump.
for (const [name] of POINT_PARTS) {
const hot = hoveredId === `${GIZMO_ID_PREFIX}${name}`;
entity.point.pixelSize =
(name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0);
pointSizes.set(name, (name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0));
}
points.upsert(pointItems());
setCursor(hoveredId ? 'grab' : '');
}
@@ -468,8 +479,8 @@ export function createCalibrationGizmo({
const ray = pickRay(windowPosition);
if (!ray) return false;
const mount = Cesium.Cartesian3.clone(positions.mount);
const capCenter = Cesium.Cartesian3.clone(positions.capCenter);
const mount = { ...positions.mount };
const capCenter = { ...positions.capCenter };
const axes = enuAxes(mount);
const { forwardHoriz, right, view } = viewAxesFor(
camera.headingDeg,
@@ -533,9 +544,7 @@ export function createCalibrationGizmo({
drag = state;
setCursor('grabbing');
if (scene.screenSpaceCameraController) {
scene.screenSpaceCameraController.enableInputs = false;
}
releaseCamera = input.suspendCamera('cctv-gizmo-drag');
return true;
}
@@ -596,12 +605,7 @@ export function createCalibrationGizmo({
if (part === 'handle-fov-l' || part === 'handle-fov-r') {
const hit = rayPlaneIntersect(ray.origin, ray.direction, capCenter, view);
if (!hit) return null;
const lateral = Math.abs(
Cesium.Cartesian3.dot(
Cesium.Cartesian3.subtract(hit, capCenter, new Cesium.Cartesian3()),
right,
),
);
const lateral = Math.abs(dot(sub(hit, capCenter), right));
const halfW = Math.max(0.5, lateral);
const fovDeg = toDeg(
2 * Math.atan(halfW / Math.max(1, drag.effectiveRangeM)),
@@ -615,9 +619,8 @@ export function createCalibrationGizmo({
if (!drag) return;
const record = drag.record;
drag = null;
if (scene.screenSpaceCameraController) {
scene.screenSpaceCameraController.enableInputs = true;
}
releaseCamera?.();
releaseCamera = null;
setCursor(hoveredId ? 'grab' : '');
endPatch(record);
}
@@ -629,18 +632,21 @@ export function createCalibrationGizmo({
}
}
handler.setInputAction((event) => {
// A tool owns the pointer (src/data/inputOwnership.js): yield the press.
if (!isPointerFree()) return;
// An ambient press: the dispatcher withholds it while a tool owns the pointer
// (src/data/inputOwnership.js).
const offDown = input.onPointer('down', (event) => {
if (!enabled) return;
// A release Cesium never reported (one with a modifier key held) leaves
// the last drag open; a new press ends it, hold and patch included.
if (drag) endDrag();
const part = pickGizmoPart(event.position);
debugLog('LEFT_DOWN', event.position, 'part:', part);
if (!part) return;
const started = beginDrag(part, event.position);
debugLog('beginDrag', part, '→', started);
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
});
handler.setInputAction((event) => {
const offMove = input.onPointer('move', (event) => {
if (!enabled) return;
const now = Date.now();
if (drag) {
@@ -667,12 +673,12 @@ export function createCalibrationGizmo({
if (now - lastHoverAt < HOVER_THROTTLE_MS) return;
lastHoverAt = now;
setHovered(pickGizmoPart(event.endPosition));
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
});
handler.setInputAction(() => {
const offUp = input.onPointer('up', () => {
if (!enabled) return;
endDrag();
}, Cesium.ScreenSpaceEventType.LEFT_UP);
});
return {
setEnabled(value) {
@@ -688,14 +694,25 @@ export function createCalibrationGizmo({
refresh,
destroy() {
if (drag) endDrag();
handler.destroy();
for (const entity of entities.values()) {
viewer.entities.remove(entity);
}
entities.clear();
offDown();
offMove();
offUp();
lines.dispose();
points.dispose();
setCursor('');
},
isDragging: () => !!drag,
isEnabled: () => enabled,
/**
* The parts as last drawn, by item id, for the QA harness: whether each
* shows, a line's `positions` and a point's `pos` (an arrow has both).
*/
partsForTest() {
const parts = {};
for (const item of [...lineItems(), ...pointItems()])
parts[item.id] = { ...parts[item.id], ...item };
for (const item of lineItems()) parts[item.id].show = item.show;
return parts;
},
};
}
+351 -19
View File
@@ -8,66 +8,99 @@
// - rayPlaneIntersect refuses grazing rays (|dir·normal| < 0.08 — spec §5
// precision guard) and behind-origin hits;
// - ringAngle/signedAngleDelta give quadrant-correct, wrap-safe angles for
// the heading/pitch ring drags.
// the heading/pitch ring drags;
// - the controller ends an open drag, and its camera hold, on the next press.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
GIZMO_ID_PREFIX,
closestParamOnAxis,
createCalibrationGizmo,
rayPlaneIntersect,
ringAngle,
signedAngleDelta,
} from './cctvGizmo.js';
import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { fromDegrees } from '../geo/ellipsoid.js';
import { add, distance, negate, normalize, scale } from '../geo/vector.js';
const c3 = (x, y, z) => new Cesium.Cartesian3(x, y, z);
const c3 = (x, y, z) => ({ x, y, z });
test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', () => {
// Axis along +X from origin. Ray shooting straight down (-Z) from (10, 0, 5):
// nearest axis point is x=10 → t=10.
const t = closestParamOnAxis(c3(10, 0, 5), c3(0, 0, -1), c3(0, 0, 0), c3(1, 0, 0));
const t = closestParamOnAxis(
c3(10, 0, 5),
c3(0, 0, -1),
c3(0, 0, 0),
c3(1, 0, 0),
);
assert.ok(Math.abs(t - 10) < 1e-9, `expected 10, got ${t}`);
});
test('closestParamOnAxis: skew ray resolves to the geometric closest point', () => {
// Axis +X. Ray from (0, 10, 0) toward (1, -1, 0)/√2 passes closest to the
// axis around x=10 (it reaches y=0 at x=10).
const dir = Cesium.Cartesian3.normalize(c3(1, -1, 0), new Cesium.Cartesian3());
const dir = normalize(c3(1, -1, 0));
const t = closestParamOnAxis(c3(0, 10, 0), dir, c3(0, 0, 0), c3(1, 0, 0));
assert.ok(Math.abs(t - 10) < 1e-6, `expected ~10, got ${t}`);
});
test('closestParamOnAxis: axis origin offset shifts the parameter', () => {
const t = closestParamOnAxis(c3(10, 0, 5), c3(0, 0, -1), c3(4, 0, 0), c3(1, 0, 0));
const t = closestParamOnAxis(
c3(10, 0, 5),
c3(0, 0, -1),
c3(4, 0, 0),
c3(1, 0, 0),
);
assert.ok(Math.abs(t - 6) < 1e-9, `expected 6, got ${t}`);
});
test('closestParamOnAxis: near-parallel ray/axis returns null', () => {
assert.equal(closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)), null);
const nearly = Cesium.Cartesian3.normalize(c3(1, 1e-9, 0), new Cesium.Cartesian3());
assert.equal(closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)), null);
assert.equal(
closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)),
null,
);
const nearly = normalize(c3(1, 1e-9, 0));
assert.equal(
closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)),
null,
);
});
test('rayPlaneIntersect: straight-on hit lands at the expected point', () => {
const hit = rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, -1), c3(0, 0, 0), c3(0, 0, 1));
const hit = rayPlaneIntersect(
c3(0, 0, 10),
c3(0, 0, -1),
c3(0, 0, 0),
c3(0, 0, 1),
);
assert.ok(hit, 'expected a hit');
assert.ok(Cesium.Cartesian3.distance(hit, c3(0, 0, 0)) < 1e-9);
assert.ok(distance(hit, c3(0, 0, 0)) < 1e-9);
});
test('rayPlaneIntersect: oblique hit resolves correctly', () => {
const dir = Cesium.Cartesian3.normalize(c3(1, 0, -1), new Cesium.Cartesian3());
const dir = normalize(c3(1, 0, -1));
const hit = rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1));
assert.ok(hit);
assert.ok(Cesium.Cartesian3.distance(hit, c3(5, 0, 0)) < 1e-9, `got ${hit}`);
assert.ok(distance(hit, c3(5, 0, 0)) < 1e-9, `got ${JSON.stringify(hit)}`);
});
test('rayPlaneIntersect: grazing ray (|dir·n| < 0.08) returns null', () => {
// dir almost in-plane: z component 0.05 < 0.08 threshold.
const dir = Cesium.Cartesian3.normalize(c3(1, 0, -0.05), new Cesium.Cartesian3());
assert.equal(rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)), null);
const dir = normalize(c3(1, 0, -0.05));
assert.equal(
rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)),
null,
);
});
test('rayPlaneIntersect: plane behind the ray origin returns null', () => {
assert.equal(rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, 1), c3(0, 0, 0), c3(0, 0, 1)), null);
assert.equal(
rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, 1), c3(0, 0, 0), c3(0, 0, 1)),
null,
);
});
test('ringAngle: quadrant sweep in the (basisA, basisB) frame', () => {
@@ -75,9 +108,15 @@ test('ringAngle: quadrant sweep in the (basisA, basisB) frame', () => {
const a = c3(1, 0, 0);
const b = c3(0, 1, 0);
assert.ok(Math.abs(ringAngle(c3(5, 0, 0), center, a, b) - 0) < 1e-9);
assert.ok(Math.abs(ringAngle(c3(0, 5, 0), center, a, b) - Math.PI / 2) < 1e-9);
assert.ok(Math.abs(Math.abs(ringAngle(c3(-5, 0, 0), center, a, b)) - Math.PI) < 1e-9);
assert.ok(Math.abs(ringAngle(c3(0, -5, 0), center, a, b) + Math.PI / 2) < 1e-9);
assert.ok(
Math.abs(ringAngle(c3(0, 5, 0), center, a, b) - Math.PI / 2) < 1e-9,
);
assert.ok(
Math.abs(Math.abs(ringAngle(c3(-5, 0, 0), center, a, b)) - Math.PI) < 1e-9,
);
assert.ok(
Math.abs(ringAngle(c3(0, -5, 0), center, a, b) + Math.PI / 2) < 1e-9,
);
});
test('signedAngleDelta: shortest-path wrap', () => {
@@ -86,3 +125,296 @@ test('signedAngleDelta: shortest-path wrap', () => {
assert.ok(Math.abs(signedAngleDelta(d2r(-170), d2r(170)) - d2r(-20)) < 1e-9);
assert.ok(Math.abs(signedAngleDelta(d2r(10), d2r(30)) - d2r(20)) < 1e-9);
});
/**
* A viewer double drawing through a fake draw port, whose query port picks
* `picked` and casts the ray `ray` (a ray,
* or a function of the window position).
*/
function gizmoViewer(t, { picked, ray }) {
const viewer = {
scene: {
canvas: { style: {} },
screenSpaceCameraController: { enableInputs: true },
},
};
const queries = [];
const { draw, unbind } = bindFakeDraw(viewer, {
query: {
pick: (x, y, window) => (queries.push(['pick', window]), picked()),
drillPick: (x, y, options) => (queries.push(['drill', options]), []),
pickRay: (x, y) => (typeof ray === 'function' ? ray(x, y) : ray),
},
});
t.after(unbind);
return { viewer, draw, queries };
}
const mount = fromDegrees(0, 0, 10);
const east = c3(0, 1, 0); // east at lon 0, lat 0
const gizmoRecord = () => ({
frustumPositions: {
mount,
capCenter: mount,
tl: mount,
tr: mount,
bl: mount,
br: mount,
},
frustumGeometry: { rangeM: 50 },
camera: {
headingDeg: 0,
pitchDeg: 0,
rangeM: 50,
calibration: {},
basePose: {},
},
});
test('the gizmo draws its parts through the draw port, shown in ADJUST mode only', (t) => {
const { viewer, draw } = gizmoViewer(t, { picked: () => null, ray: null });
const { input } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
const lines = draw.find('cctv-gizmo:');
const points = [...draw.sets.values()].find(
(set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'),
);
assert.equal(lines.kind, 'lines');
assert.equal(lines.items.size, 0, 'nothing drawn before ADJUST');
gizmo.setEnabled(true);
assert.deepEqual(
[...lines.items.keys()],
['ring-heading', 'ring-pitch', 'move-east', 'move-north', 'move-up'].map(
(part) => GIZMO_ID_PREFIX + part,
),
);
assert.deepEqual(
[...points.items.keys()],
[
'move-east',
'move-north',
'move-up',
'handle-range',
'handle-fov-l',
'handle-fov-r',
].map((part) => GIZMO_ID_PREFIX + part),
);
const ring = lines.items.get(`${GIZMO_ID_PREFIX}ring-heading`);
assert.equal(ring.mode, '3d');
assert.equal(ring.widthPx, 3);
assert.equal(ring.positions.length, 97, 'a closed 96-segment ring');
assert.ok(Math.abs(ring.style.color[3] - 0.9) < 1e-12);
assert.ok(Math.abs(ring.depthFail.color[3] - 0.45) < 1e-12);
const arrow = lines.items.get(`${GIZMO_ID_PREFIX}move-up`);
assert.equal(arrow.style.kind, 'arrow');
assert.equal(arrow.widthPx, 12);
// The up arrow runs 1.6 ring radii (6 m minimum at a 50 m range) up.
assert.ok(
distance(arrow.positions[1], add(mount, scale(c3(1, 0, 0), 9.6))) < 1e-6,
);
const tip = points.items.get(`${GIZMO_ID_PREFIX}move-up`);
assert.deepEqual(tip.pos, arrow.positions[1]);
assert.equal(tip.pixelSize, 14);
assert.equal(tip.disableDepthTest, Number.POSITIVE_INFINITY);
assert.ok(
[...lines.items.values(), ...points.items.values()].every(
(item) => item.show,
),
);
gizmo.setEnabled(false);
assert.ok(
[...lines.items.values(), ...points.items.values()].every(
(item) => !item.show,
),
'hidden off ADJUST',
);
gizmo.destroy();
assert.equal(lines.disposed, true);
assert.equal(points.disposed, true);
});
test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => {
let lineSet = null;
const { viewer, draw, queries } = gizmoViewer(t, {
picked: () => ({
set: lineSet,
id: `${GIZMO_ID_PREFIX}move-up`,
surface: false,
}),
ray: { origin: add(mount, scale(east, 100)), direction: negate(east) },
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const ended = [];
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch: (r) => ended.push(r),
});
t.after(() => gizmo.destroy());
lineSet = draw.find('cctv-gizmo:').spec.id;
gizmo.setEnabled(true);
const controller = viewer.scene.screenSpaceCameraController;
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), true);
assert.deepEqual(queries[0], ['pick', { width: 14, height: 14 }]);
assert.equal(controller.enableInputs, false);
// The release came with a modifier key held: Cesium raised no LEFT_UP.
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.deepEqual(ended, [record], 'the open drag was committed');
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false);
assert.equal(controller.enableInputs, true, 'no hold was stranded');
});
test('a pick of another set or a stray id is no gizmo part', (t) => {
let picked = null;
const { viewer, draw } = gizmoViewer(t, {
picked: () => picked,
ray: { origin: add(mount, scale(east, 100)), direction: negate(east) },
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
gizmo.setEnabled(true);
picked = { set: 'other', id: `${GIZMO_ID_PREFIX}move-up`, surface: false };
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false, 'another set');
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } });
picked = {
set: draw.find('cctv-gizmo:').spec.id,
id: `${GIZMO_ID_PREFIX}nothing`,
surface: false,
};
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false, 'no such part');
});
test('dragging the east arrow moves the camera east by what the pointer travelled', (t) => {
const up = c3(1, 0, 0); // up at lon 0, lat 0
let lineSet = null;
const { viewer, draw } = gizmoViewer(t, {
picked: () => ({
set: lineSet,
id: `${GIZMO_ID_PREFIX}move-east`,
surface: false,
}),
// Straight down onto the east axis, `x` metres east of the mount.
ray: (x) => ({
origin: add(add(mount, scale(east, x)), scale(up, 100)),
direction: negate(up),
}),
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
record.camera.calibration = { offsetEastM: 2 };
const patches = [];
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch: (patch, pinned) => patches.push([patch, pinned]),
endPatch() {},
});
t.after(() => gizmo.destroy());
lineSet = draw.find('cctv-gizmo:').spec.id;
gizmo.setEnabled(true);
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), true);
assert.equal(viewer.scene.canvas.style.cursor, 'grabbing');
handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, {
startPosition: { x: 5, y: 5 },
endPosition: { x: 12, y: 5 },
});
assert.equal(patches.length, 1);
const [patch, pinned] = patches[0];
assert.equal(pinned, record, 'patched on the record dragged');
assert.ok(Math.abs(patch.offsetEastM - 9) < 1e-6, `${patch.offsetEastM}`);
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 12, y: 5 } });
assert.equal(gizmo.isDragging(), false);
});
test('hovering a handle grows it and shows the grab cursor', (t) => {
let pointSet = null;
let over = true;
const { viewer, draw } = gizmoViewer(t, {
picked: () =>
over
? {
set: pointSet,
id: `${GIZMO_ID_PREFIX}handle-range`,
surface: false,
}
: null,
ray: null,
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
const points = [...draw.sets.values()].find(
(set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'),
);
pointSet = points.spec.id;
gizmo.setEnabled(true);
const size = () =>
points.items.get(`${GIZMO_ID_PREFIX}handle-range`).pixelSize;
assert.equal(size(), 13);
handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, {
startPosition: { x: 5, y: 5 },
endPosition: { x: 6, y: 5 },
});
assert.equal(size(), 17);
assert.equal(viewer.scene.canvas.style.cursor, 'grab');
});
test('the harness reads each part as drawn, an arrow with its line and tip', (t) => {
const { viewer } = gizmoViewer(t, { picked: () => null, ray: null });
const { input } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
assert.deepEqual(gizmo.partsForTest(), {}, 'nothing drawn before ADJUST');
gizmo.setEnabled(true);
const parts = gizmo.partsForTest();
const arrow = parts[`${GIZMO_ID_PREFIX}move-east`];
assert.equal(arrow.positions.length, 2, 'its line');
assert.deepEqual(arrow.pos, arrow.positions[1], 'its tip');
assert.equal(arrow.show, true);
assert.equal(parts[`${GIZMO_ID_PREFIX}ring-heading`].show, true);
assert.ok(parts[`${GIZMO_ID_PREFIX}handle-range`].pos);
gizmo.setEnabled(false);
assert.ok(
Object.values(gizmo.partsForTest()).every((part) => part.show === false),
);
});
+88 -69
View File
@@ -2,10 +2,13 @@
// near the screen show, a zoomed-out view keeps one camera per world-anchored
// cell, and the layer's UI state never rebuilds every camera for a listener
// that does not read the list.
import { test } from 'node:test';
import { afterEach, test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import cctvLayer, {
_cctvIconsForTest,
_setCctvCoverageStateForTest,
_viewRecordIdsForTest,
refreshHorizonCulling,
@@ -14,18 +17,10 @@ import cctvLayer, {
const WIDTH = 800;
const HEIGHT = 600;
/**
* Records at the given [lon, lat] degrees near the origin, each drawn at the
* screen point `screenAt` gives it (default: the middle of the screen).
*/
function recordsAt(
lonLats,
screenAt = () => ({ x: WIDTH / 2, y: HEIGHT / 2 }),
) {
const screenByPosition = new Map();
/** Records at the given [lon, lat] degrees near the origin. */
function recordsAt(lonLats) {
const records = lonLats.map(([lon, lat], index) => {
const position = Cesium.Cartesian3.fromDegrees(lon, lat, 10);
screenByPosition.set(position, screenAt(index));
return {
camera: {
id: `cam-${index}`,
@@ -39,36 +34,62 @@ function recordsAt(
rangeM: 145,
mountHeightM: 8,
},
position,
billboard: { position, show: true },
position: { x: position.x, y: position.y, z: position.z },
coverageEntities: [],
projection: null,
};
});
return { records, screenByPosition };
return { records };
}
function viewerAt(heightM, screenByPosition, shiftX = 0) {
return {
isDestroyed: () => false,
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, heightM),
positionCartographic: { latitude: 0, longitude: 0, height: heightM },
frustum: { fovy: Math.PI / 3 },
/**
* A viewer looking straight down from `heightM` over `lonDeg` on the
* equator, north up, through a camera port: the view pass projects the
* cameras from its pose.
*/
function viewerAt(heightM, lonDeg = 0) {
const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM);
const down = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const north = { x: 0, y: 0, z: 1 };
const right = Cesium.Cartesian3.cross(down, north, new Cesium.Cartesian3());
const { port } = fakeCameraPort({
pose: {
lon: lonDeg,
lat: 0,
height: heightM,
position: { x: eye.x, y: eye.y, z: eye.z },
direction: { x: down.x, y: down.y, z: down.z },
up: north,
right: { x: right.x, y: right.y, z: right.z },
fovy: Math.PI / 3,
aspectRatio: WIDTH / HEIGHT,
near: 0.1,
far: 5e8,
},
scene: {
});
const viewer = {};
bindings.push(
bindRenderer(viewer, {
camera: port,
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
cartesianToCanvasCoordinates: (position) => {
const screen = screenByPosition.get(position);
return screen && { x: screen.x + shiftX, y: screen.y };
},
},
};
}),
);
return viewer;
}
/** The renderers bound for the running test, let go when it ends. */
const bindings = [];
afterEach(() => {
for (const unbind of bindings.splice(0)) unbind();
});
function shownIds(records) {
const icons = _cctvIconsForTest();
return records
.filter((record) => record.billboard.show)
.filter((record) => icons.item(record.camera.id)?.show === true)
.map((record) => record.camera.id)
.sort();
}
@@ -82,9 +103,9 @@ const CLUSTER = [
];
test('zoomed out, cameras sharing a ground cell show one icon', () => {
const { records, screenByPosition } = recordsAt(CLUSTER);
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
});
assert.equal(
@@ -99,34 +120,34 @@ test('zoomed out, cameras sharing a ground cell show one icon', () => {
});
test('a pan keeps the same winners, and an unchanged view keeps its list', () => {
const { records, screenByPosition } = recordsAt(CLUSTER, (index) => ({
x: 100 + index * 7,
y: 300,
}));
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
});
refreshHorizonCulling();
const before = shownIds(records);
const list = _viewRecordIdsForTest();
for (const shiftX of [3, 11, 20, 37]) {
// A pan of a few to some 40 px (a pixel is about 30 m from 20 km up).
for (const shiftM of [90, 330, 600, 1110]) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition, shiftX),
viewer: viewerAt(20_000, shiftM / 111_320),
records,
});
refreshHorizonCulling();
assert.deepEqual(shownIds(records), before, `pan by ${shiftX} px`);
assert.deepEqual(shownIds(records), before, `pan by ${shiftM} m`);
}
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing');
assert.deepEqual(_viewRecordIdsForTest(), list);
});
test('a small zoom within one cell size keeps the same winners', () => {
const { records, screenByPosition } = recordsAt(CLUSTER);
const { records } = recordsAt(CLUSTER);
const shownAt = (heightM) => {
_setCctvCoverageStateForTest({
viewer: viewerAt(heightM, screenByPosition),
viewer: viewerAt(heightM),
records,
});
refreshHorizonCulling();
@@ -138,11 +159,11 @@ test('a small zoom within one cell size keeps the same winners', () => {
});
test('a healthy camera wins its cell over an unknown one', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2));
const { records } = recordsAt(CLUSTER.slice(0, 2));
// Whichever camera the id order would pick, the healthy one must win.
for (const id of ['cam-0', 'cam-1']) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
healthById: new Map([[id, { status: 'ok' }]]),
});
@@ -152,30 +173,31 @@ test('a healthy camera wins its cell over an unknown one', () => {
});
test('the active camera always shows, even in a crowded cell', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 3));
const { records } = recordsAt(CLUSTER.slice(0, 3));
for (const active of records) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
activeCameraId: active.camera.id,
});
refreshHorizonCulling();
assert.ok(active.billboard.show, `${active.camera.id} shows while active`);
const icons = _cctvIconsForTest();
assert.ok(
icons.item(active.camera.id).show,
`${active.camera.id} shows while active`,
);
}
});
test('close up, every camera near the screen shows and far-off ones hide', () => {
const { records, screenByPosition } = recordsAt(
[
[0, 0],
[0.0001, 0],
[0.0002, 0],
],
(index) =>
index === 2 ? { x: WIDTH * 3, y: HEIGHT / 2 } : { x: 100, y: 100 },
);
// From 300 m up the screen spans some 460 m: the third camera is 1.1 km off.
const { records } = recordsAt([
[0, 0],
[0.0001, 0],
[0.01, 0],
]);
_setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition),
viewer: viewerAt(300),
records,
});
refreshHorizonCulling();
@@ -183,9 +205,9 @@ test('close up, every camera near the screen shows and far-off ones hide', () =>
});
test('a disabled layer skips the view pass', () => {
const { records, screenByPosition } = recordsAt(CLUSTER);
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
enabled: false,
});
@@ -194,9 +216,9 @@ test('a disabled layer skips the view pass', () => {
});
test('UI state builds the full camera list only when it is read', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2));
const { records } = recordsAt(CLUSTER.slice(0, 2));
_setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition),
viewer: viewerAt(300),
records,
});
refreshHorizonCulling();
@@ -227,16 +249,13 @@ test('UI state builds the full camera list only when it is read', () => {
});
test('the camera picker lists the view, with the active camera first', () => {
const { records, screenByPosition } = recordsAt(
[
[0, 0],
[0.0001, 0],
[0.0002, 0],
],
(index) => (index === 1 ? { x: WIDTH * 3, y: 0 } : { x: 100, y: 100 }),
);
const { records } = recordsAt([
[0, 0],
[0.01, 0],
[0.0002, 0],
]);
_setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition),
viewer: viewerAt(300),
records,
activeCameraId: 'cam-1',
});
+14 -56
View File
@@ -6,17 +6,17 @@
*
* Two responsibilities, both pure of layer state:
* - Color identity: a stable per-camera hue (golden-angle spaced over the
* id-sorted catalog index) and the derived fill/line Cesium colors.
* - Volume geometry: a translucent frustum pyramid primitive built FROM the
* exact frustumCartesians positions the wireframe uses — welded by
* construction, never recomputed independently. 5 vertices, 6 triangles,
* synchronous build (trivially small), no picking.
* id-sorted catalog index) and the derived fill/line renderer colors.
* - Volume geometry: the vertex and index buffers of a translucent frustum
* pyramid built FROM the exact frustumCartesians positions the wireframe
* uses — welded by construction, never recomputed independently. 5
* vertices, 6 triangles; the layer's rendering part draws them.
*
* Nothing here queries the scene or persists anything: colors are
* presentation-only and volumes are rebuilt only at the moments the frustum
* wireframe already rewrites (pose edits / visible-set changes).
*/
import * as Cesium from 'cesium';
import { hslColor } from '../render/color.js';
/** Golden angle in degrees — maximally spreads consecutive indices around the hue wheel. */
const GOLDEN_ANGLE_DEG = 137.50776405003785;
@@ -43,15 +43,16 @@ export function cameraHue(index) {
* Derived viewshed colors for a hue: translucent volume fills (idle/active)
* and wireframe line tints (idle/active), all in the same hue family.
* @param {number} hueDeg - Hue in degrees.
* @returns {{fill: Cesium.Color, fillActive: Cesium.Color, line: Cesium.Color, lineActive: Cesium.Color}}
* @returns {{fill: number[], fillActive: number[], line: number[], lineActive: number[]}}
* Renderer colours, [r, g, b, a] in 0..1.
*/
export function viewshedColors(hueDeg) {
const hue = (((Number(hueDeg) % 360) + 360) % 360) / 360;
return {
fill: Cesium.Color.fromHsl(hue, 0.85, 0.6, FILL_ALPHA_IDLE),
fillActive: Cesium.Color.fromHsl(hue, 0.85, 0.6, FILL_ALPHA_ACTIVE),
line: Cesium.Color.fromHsl(hue, 0.9, 0.65, LINE_ALPHA_IDLE),
lineActive: Cesium.Color.fromHsl(hue, 0.9, 0.7, LINE_ALPHA_ACTIVE),
fill: hslColor(hue, 0.85, 0.6, FILL_ALPHA_IDLE),
fillActive: hslColor(hue, 0.85, 0.6, FILL_ALPHA_ACTIVE),
line: hslColor(hue, 0.9, 0.65, LINE_ALPHA_IDLE),
lineActive: hslColor(hue, 0.9, 0.7, LINE_ALPHA_ACTIVE),
};
}
@@ -61,8 +62,8 @@ export function viewshedColors(hueDeg) {
* the apex + the far cap split into 2 triangles. Pure — this is the ONLY
* geometry definition (weld-by-construction with the wireframe, which draws
* its rays/cap from the same 5 Cartesians).
* @param {{mount: Cesium.Cartesian3, tl: Cesium.Cartesian3, tr: Cesium.Cartesian3,
* br: Cesium.Cartesian3, bl: Cesium.Cartesian3}} positions - frustumCartesians shape.
* @param {{mount: object, tl: object, tr: object, br: object, bl: object}}
* positions - frustumCartesians shape: ECEF points with x, y and z.
* @returns {{positions: Float64Array, indices: Uint16Array}}
*/
export function frustumVolumeGeometryData(positions) {
@@ -85,46 +86,3 @@ export function frustumVolumeGeometryData(positions) {
]);
return { positions: flat, indices };
}
/**
* Builds the translucent frustum-volume primitive for one camera.
* Synchronous (6 triangles — cheaper than the async geometry pipeline's
* bookkeeping), unlit flat color, both faces visible (the viewer is routinely
* inside or behind a cone), never pickable (clicks fall through to the
* billboard/wireframe/plane, whose pick semantics are established).
* @param {Object} positions - frustumCartesians shape (see frustumVolumeGeometryData).
* @param {Cesium.Color} color - Per-camera fill color (already alpha'd).
* @returns {Cesium.Primitive}
*/
export function createFrustumVolumePrimitive(positions, color) {
const { positions: flat, indices } = frustumVolumeGeometryData(positions);
const geometry = new Cesium.Geometry({
attributes: {
position: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.DOUBLE,
componentsPerAttribute: 3,
values: flat,
}),
},
indices,
primitiveType: Cesium.PrimitiveType.TRIANGLES,
boundingSphere: Cesium.BoundingSphere.fromVertices(Array.from(flat)),
});
return new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry,
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
},
}),
appearance: new Cesium.PerInstanceColorAppearance({
flat: true,
translucent: true,
renderState: {
cull: { enabled: false },
},
}),
asynchronous: false,
allowPicking: false,
});
}
+18 -6
View File
@@ -62,14 +62,26 @@ test('cameraHue: consecutive indices separated by >= 80 degrees', () => {
test('viewshedColors: fill/line pairs with the designed alphas', () => {
const colors = viewshedColors(210);
for (const key of ['fill', 'fillActive', 'line', 'lineActive']) {
assert.ok(colors[key] instanceof Cesium.Color, `${key} must be a Cesium.Color`);
assert.ok(Array.isArray(colors[key]) && colors[key].length === 4, `${key} must be a renderer colour`);
}
assert.ok(Math.abs(colors.fill.alpha - 0.12) < 1e-6);
assert.ok(Math.abs(colors.fillActive.alpha - 0.22) < 1e-6);
assert.ok(Math.abs(colors.line.alpha - 0.85) < 1e-6);
assert.ok(Math.abs(colors.lineActive.alpha - 1.0) < 1e-6);
assert.ok(Math.abs(colors.fill[3] - 0.12) < 1e-6);
assert.ok(Math.abs(colors.fillActive[3] - 0.22) < 1e-6);
assert.ok(Math.abs(colors.line[3] - 0.85) < 1e-6);
assert.ok(Math.abs(colors.lineActive[3] - 1.0) < 1e-6);
// Same hue family: fill and line of the same hue must not be gray.
assert.ok(colors.line.red !== colors.line.green || colors.line.green !== colors.line.blue);
assert.ok(colors.line[0] !== colors.line[1] || colors.line[1] !== colors.line[2]);
});
test('viewshedColors: the same colours the renderer derived from the hue', () => {
const asArray = (c) => [c.red, c.green, c.blue, c.alpha];
for (const hueDeg of [0, 137.5, 210, 359.9, -30]) {
const hue = (((hueDeg % 360) + 360) % 360) / 360;
const colors = viewshedColors(hueDeg);
assert.deepEqual(colors.fill, asArray(Cesium.Color.fromHsl(hue, 0.85, 0.6, 0.12)));
assert.deepEqual(colors.fillActive, asArray(Cesium.Color.fromHsl(hue, 0.85, 0.6, 0.22)));
assert.deepEqual(colors.line, asArray(Cesium.Color.fromHsl(hue, 0.9, 0.65, 0.85)));
assert.deepEqual(colors.lineActive, asArray(Cesium.Color.fromHsl(hue, 0.9, 0.7, 1.0)));
}
});
/** Minimal frustumCartesians-shaped fixture. */
+4 -4
View File
@@ -27,8 +27,8 @@ const LAYERS = [
_setTrackedFlightRefreshStateForTest({
icao24,
entity: null,
billboard: candidateBillboard(icao24),
billboardCollection: { show: true, remove() {} },
icon: candidateBillboard(icao24),
iconLayer: { show: true, remove() {} },
viewer: candidateViewer(),
tracked: false,
meta: {
@@ -48,8 +48,8 @@ const LAYERS = [
_setTrackedMilitaryRefreshStateForTest({
icao24,
entity: null,
billboard: candidateBillboard(icao24),
billboardCollection: { show: true, remove() {} },
icon: candidateBillboard(icao24),
iconLayer: { show: true, remove() {} },
viewer: candidateViewer(),
tracked: false,
meta: {
+47 -18
View File
@@ -1,4 +1,5 @@
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import assert from 'node:assert/strict';
@@ -12,6 +13,11 @@ import assert from 'node:assert/strict';
* regression would silently revert. These assertions pin the decisions.
*/
const DRAW_MODELS_SOURCE = readFileSync(
new URL('../render/cesium/drawModels.js', import.meta.url),
'utf8',
);
const LAYERS = [
{ name: 'flights', path: new URL('./flights.js', import.meta.url) },
{ name: 'militaryFlights', path: new URL('./militaryFlights.js', import.meta.url) },
@@ -28,10 +34,11 @@ for (const layer of LAYERS) {
const source = readLayerSource(layer.path);
test(`${layer.name}: every GLB creation bypasses the tile-contended frame-spread queue`, () => {
const calls = [...source.matchAll(/_createModel\(\s*\w+,\s*\{([\s\S]*?)\n\s*\}\)/g)];
assert.ok(calls.length >= 2, `expected fleet and tracked model calls; found ${calls.length}`);
assert.doesNotMatch(source, /Cesium\.Model\.fromGltfAsync\(/,
'every model is built from the loaded fleet set through _createModel');
// The fleet and tracked models are draw-port models sets; the Cesium
// draw port creates every model off the frame-spread queue.
assert.match(source, /\.models\(\{\s*id:/, 'the layer draws its models as draw-port models sets');
const calls = [...DRAW_MODELS_SOURCE.matchAll(/Cesium\.Model\.fromGltfAsync\(\{([\s\S]*?)\}\)/g)];
assert.ok(calls.length >= 1, 'the draw port creates models');
for (const [index, call] of calls.entries()) {
assert.match(call[1], /\basynchronous:\s*false\b/,
`_createModel call ${index + 1} must keep bounded GLB readiness independent of tile jobs`);
@@ -41,9 +48,9 @@ for (const layer of LAYERS) {
test(`${layer.name}: Cockpit 3D obeys the shared Display toggle`, () => {
const regime = /^([ \t]*)function _modelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.ok(regime, '_modelRegimeActive is defined');
assert.match(regime, /if\s*\(\s*!(?:flightState\.)?_models3dEnabled,?\s*\)\s*return\s*false;/,
assert.match(regime, /if\s*\(\s*!(?:(?:flightState|state)\.)?_models3dEnabled,?\s*\)\s*return\s*false;/,
'OFF must keep Cockpit AIR contacts in 2D');
assert.doesNotMatch(regime, /!(?:flightState\.)?_models3dEnabled\s*&&\s*!(?:flightState\.)?_cockpitContactMode/,
assert.doesNotMatch(regime, /!(?:(?:flightState|state)\.)?_models3dEnabled\s*&&\s*!(?:(?:flightState|state)\.)?_cockpitContactMode/,
'Cockpit must not bypass the owner-visible Display toggle');
});
@@ -55,7 +62,7 @@ for (const layer of LAYERS) {
// suppression is now an explicit early return.
const regime = /^([ \t]*)function _trackedModelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.ok(regime, '_trackedModelRegimeActive is defined');
assert.match(regime, /if\s*\(\s*!(?:flightState\.)?_trackedIcao\s*\|\|\s*(?:flightState\.)?_cockpitContactMode\s*\|\|[\s\S]*?return\s*false;/,
assert.match(regime, /if\s*\(\s*!(?:(?:flightState|state)\.)?_trackedIcao\s*\|\|\s*(?:(?:flightState|state)\.)?_cockpitContactMode\s*\|\|[\s\S]*?return\s*false;/,
'_trackedModelRegimeActive excludes cockpit');
const tracked = /^([ \t]*)function _updateTrackedModel\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.ok(tracked, '_updateTrackedModel is defined');
@@ -72,37 +79,59 @@ for (const layer of LAYERS) {
const add = /^([ \t]*)function _modelAddDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
const keep = /^([ \t]*)function _modelKeepDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.match(add, /(?:flightState\.)?_models3dMode\s*===\s*'all'\s*\?\s*MODEL_ALL_ADD_M\s*:\s*MODEL_PROX_ADD_M/);
assert.match(keep, /(?:flightState\.)?_models3dMode\s*===\s*'all'\s*\?\s*MODEL_ALL_KEEP_M\s*:\s*MODEL_PROX_KEEP_M/);
assert.match(add, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_ADD_M\s*:\s*(?:policy\.)?MODEL_PROX_ADD_M/);
assert.match(keep, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_KEEP_M\s*:\s*(?:policy\.)?MODEL_PROX_KEEP_M/);
assert.doesNotMatch(add, /COCKPIT_MODEL_ADD_M/);
assert.doesNotMatch(keep, /COCKPIT_MODEL_KEEP_M/);
const cap = /^([ \t]*)function _modelCap\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.match(cap, /Math\.min\(\s*COCKPIT_MODEL_MAX/,
assert.match(cap, /Math\.min\(\s*(?:policy\.)?COCKPIT_MODEL_MAX/,
'Cockpit keeps its 60-model performance ceiling');
});
test(`${layer.name}: near AIR state is independent from model admission`, () => {
assert.match(source, /nextCockpitNearContacts\(/,
'Cockpit derives a separate near-contact hysteresis set');
assert.match(source, /isCockpitContact && !isCockpitNear[\s\S]*cockpitContactDotImage\(\)/,
assert.match(source, /!state\._cockpitNearContacts\.has\(icao24\);\s*const look = cockpitDot\s*\?\s*\{\s*image: cockpitDotImage\(\)/,
'only out-of-range Cockpit contacts become dots');
// `_iconKind` is identity for every unconverted contact (see
// tr3bRegistry.test.mjs) — it only swaps the glyph for a contact the
// operator explicitly converted into a TR-3B.
assert.match(source, /bb\.image\s*=\s*aircraftIcon\(\s*_iconKind\(\s*icao24,\s*meta\?\.klass,?\s*\)(,\s*bb\._gevIconLarge\s*\?\s*TRACKED_ICON_PX\s*:\s*undefined)?,?\s*\)/,
assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*(?:FLEET_ICON_PX,?\s*)?\)/,
'near contacts and model fallbacks retain the class-derived aircraft silhouette');
assert.match(source, /bb\.rotation\s*=\s*0;/,
assert.match(source, /color: rgba\(rendering\._cockpitContactColor\(icao24, info\)\),\s*rotationMode: 'screen',/,
'far dots are reset to a rotation-free presentation');
assert.match(source, /\(\s*!(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isCockpitNear,?\s*\)\s*&&\s*\(\s*doRotations\s*\|\|\s*revealed,?\s*\)/,
assert.match(source, /color: rgba\(rendering\._fleetBillboardColor\(icao24, info\)\),\s*rotationMode: 'course',/,
'near 2D silhouettes continue to receive projected course');
assert.match(source, /if\s*\(\s*bb\.show,?\s*\)\s*bb\.show\s*=\s*false;\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/,
'the gap-proof billboard-to-model handoff remains intact');
assert.match(source, /icons\.setShown\(icao24, false\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/,
'the gap-proof icon-to-model handoff remains intact');
});
test(`${layer.name}: Cockpit exit clears near state before restoring map presentation`, () => {
const setMode = /^([ \t]*)function _setCockpitContactMode\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.match(setMode, /else\s*(?:flightState\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/);
assert.match(setMode, /for\s*\(\s*const\s*\[icao24,\s*bb\]\s*of\s*(?:flightState\.)?_billboards,?\s*\)\s*(?:parts\.\w+\.)?_applyFleetBillboardPresentation\(\s*icao24,\s*bb,?\s*\);/);
assert.match(setMode, /else\s*(?:(?:flightState|state)\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/);
assert.match(setMode, /for \(const icao24 of (?:flightState\._)?icons\?\.ids\(\) \?\? \[\]\)\s*parts\.icons\._applyIconPresentation\(icao24\);/);
});
}
// The source reads above include the shared model module, so they pass from it
// alone. These pin that each layer actually builds its models from it, and that
// flights keeps its own hooks.
const RENDERING = {
flights: new URL('../layers/flights/rendering.js', import.meta.url),
militaryFlights: new URL('../layers/military/rendering.js', import.meta.url),
};
for (const [name, url] of Object.entries(RENDERING)) {
test(`${name}: 3D models come from the shared aircraft model module`, () => {
const source = readFileSync(url, 'utf8');
assert.match(source, /createAircraftModels\(\{/);
assert.match(source, /\.\.\.models\b/);
});
}
test('flights: model eligibility nudges enrichment and the tick floors grounded icons', () => {
const source = readFileSync(RENDERING.flights, 'utf8');
assert.match(source, /onModelEligible:[\s\S]*?_requestTypeEnrichment\(icao24, true\)/);
assert.match(source, /afterReplan:[\s\S]*?_floorGroundedIcons\(/);
});
Loaded 100 of 1125 files, more files were not shown because too many files have changed in this diff. Show more