mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-19 17:52:21 +00:00
Merge branch 'main' into fix/i18n-installations-note
# Conflicts: # scripts/package-boundaries.json # src/layers/installations/controls.js
This commit is contained in:
commit
93b091d082
2063 files changed
+322399
-46202
No files matched your search
@@ -43,7 +43,11 @@ test('passive Contacts releases its installation anchor and subject refresh cann
|
||||
const subject = createSubject({ state, services, parts });
|
||||
subject.refreshSelectedSubject();
|
||||
assert.equal(anchors.length, 1);
|
||||
assert.ok(anchors[0] instanceof Cesium.Cartesian3);
|
||||
assert.deepEqual(
|
||||
{ ...anchors[0] },
|
||||
{ x: position.x, y: position.y, z: position.z },
|
||||
);
|
||||
assert.notEqual(anchors[0], position, 'a copy, not the subject’s own');
|
||||
controls.setParams({ passive: true });
|
||||
assert.equal(anchors.at(-1), null);
|
||||
const released = anchors.length;
|
||||
@@ -57,5 +61,8 @@ test('passive Contacts releases its installation anchor and subject refresh cann
|
||||
controls.setParams({ passive: false });
|
||||
assert.equal(activations, 1);
|
||||
subject.refreshSelectedSubject();
|
||||
assert.ok(anchors.at(-1) instanceof Cesium.Cartesian3);
|
||||
assert.deepEqual(
|
||||
{ ...anchors.at(-1) },
|
||||
{ x: position.x, y: position.y, z: position.z },
|
||||
);
|
||||
});
|
||||
@@ -17,11 +17,25 @@ export function createDependencies({
|
||||
parts.subject.refreshSelectedSubject(true);
|
||||
return;
|
||||
}
|
||||
if (adoptSelectedVessel()) return;
|
||||
if (layerState.autoFocusRetryPending) {
|
||||
layerState.autoFocusRetryPending = !parts.focus.focusAttentionTarget();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Take the selected AIS vessel as the subject, as its selection would have
|
||||
* had Contacts been on. A followed flight is checked first by the callers.
|
||||
* @returns {boolean} Whether a vessel became the subject.
|
||||
*/
|
||||
function adoptSelectedVessel() {
|
||||
const vessel = parts.subject.currentSelectedVesselSubject?.();
|
||||
if (!vessel) return false;
|
||||
layerState.autoFocusRetryPending = false;
|
||||
parts.subject.selectSubject(vessel);
|
||||
return Boolean(layerState.subject);
|
||||
}
|
||||
|
||||
async function enableDependencies(activationId = layerState.activationId) {
|
||||
const aircraftPending = [];
|
||||
for (const layerId of DEPENDENCIES) {
|
||||
@@ -104,6 +118,7 @@ export function createDependencies({
|
||||
const initialTrackedSubject = parts.subject.currentTrackedFlightSubject();
|
||||
if (initialTrackedSubject)
|
||||
parts.subject.selectSubject(initialTrackedSubject);
|
||||
else adoptSelectedVessel();
|
||||
return enableDependencies(activationId)
|
||||
.then(() => {
|
||||
if (
|
||||
@@ -121,6 +136,7 @@ export function createDependencies({
|
||||
parts.subject.selectSubject(layerState.subject);
|
||||
return;
|
||||
}
|
||||
if (adoptSelectedVessel()) return;
|
||||
if (layerState.autoFocusAttempted) return;
|
||||
layerState.autoFocusRetryPending = !parts.focus.focusAttentionTarget();
|
||||
})
|
||||
|
||||
@@ -11,22 +11,27 @@ import { useAwarenessDirectionStore } from '../../ui/stores/awarenessDirection.j
|
||||
import AwarenessDirection from '../../ui/views/panels/AwarenessDirection.vue';
|
||||
import { createState } from './state.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
/** The rendering part over a subject with one military contact due east. */
|
||||
function overlay(screenAngle) {
|
||||
const state = createState({ services: {} });
|
||||
const container = document.body.appendChild(document.createElement('div'));
|
||||
const subject = Cesium.Cartesian3.fromDegrees(0, 0, 1000);
|
||||
Object.assign(state, {
|
||||
viewer: {
|
||||
container,
|
||||
scene: { canvas: { clientWidth: 800, clientHeight: 600 } },
|
||||
camera: {
|
||||
heading: 0,
|
||||
rightWC: new Cesium.Cartesian3(0, 1, 0),
|
||||
upWC: new Cesium.Cartesian3(0, 0, 1),
|
||||
},
|
||||
const camera = fakeCameraPort({
|
||||
pose: { heading: 0, right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
|
||||
});
|
||||
const viewer = {
|
||||
container,
|
||||
get canvas() {
|
||||
return this.scene?.canvas;
|
||||
},
|
||||
scene: { canvas: { clientWidth: 800, clientHeight: 600 } },
|
||||
};
|
||||
bindRenderer(viewer, { camera: camera.port });
|
||||
Object.assign(state, {
|
||||
viewer,
|
||||
enabled: true,
|
||||
subject: { position: subject, layerId: 'military' },
|
||||
results: {
|
||||
@@ -65,7 +70,7 @@ function overlay(screenAngle) {
|
||||
},
|
||||
parts: {},
|
||||
});
|
||||
return { state, container, rendering };
|
||||
return { state, container, rendering, camera };
|
||||
}
|
||||
|
||||
test('the overlay publishes the compass and the nearest contact bearings', () => {
|
||||
@@ -108,14 +113,14 @@ test('an unstable frame keeps the last stable bearing, until the overlay is remo
|
||||
{ angle: 2, opacity: 0.5, stable: false },
|
||||
];
|
||||
const previous = [];
|
||||
const { state, rendering } = overlay((x, y, last) => {
|
||||
const { state, rendering, camera } = overlay((x, y, last) => {
|
||||
previous.push(last);
|
||||
return answers.shift() ?? { angle: last ?? 0, opacity: 1, stable: true };
|
||||
});
|
||||
rendering.updateDirectionOverlay();
|
||||
assert.equal(state.directionAngles[0], 1);
|
||||
// The heading turns, so the next frame recomputes the contact.
|
||||
state.viewer.camera.heading = 0.1;
|
||||
camera.setPose({ heading: 0.1 });
|
||||
rendering.updateDirectionOverlay();
|
||||
assert.equal(previous[1], 1, 'the unstable frame is given the last angle');
|
||||
assert.equal(state.directionAngles[0], 1, 'and does not replace it');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { VESSEL_FOCUS_RADIUS_M } from './policy.js';
|
||||
import { cameraOf, findCamera } from '../../render/rendererOf.js';
|
||||
import { clone, distance } from '../../geo/index.js';
|
||||
|
||||
export function createFocus({ state: layerState, services, parts, source }) {
|
||||
const flightsLayer = services.flights;
|
||||
@@ -45,9 +46,9 @@ export function createFocus({ state: layerState, services, parts, source }) {
|
||||
)
|
||||
return true;
|
||||
announceNavigationAuthority('context-vessel-focus');
|
||||
layerState.viewer.camera.flyToBoundingSphere(
|
||||
new Cesium.BoundingSphere(vessel.position, VESSEL_FOCUS_RADIUS_M),
|
||||
{ duration: 1.4 },
|
||||
cameraOf(layerState.viewer).flyToBounds(
|
||||
{ center: vessel.position, radius: VESSEL_FOCUS_RADIUS_M },
|
||||
{ durationS: 1.4 },
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@@ -74,7 +75,7 @@ export function createFocus({ state: layerState, services, parts, source }) {
|
||||
layerId,
|
||||
id: String(known.id || known.mmsi),
|
||||
label: known.label || known.name || known.callsign || String(id),
|
||||
position: Cesium.Cartesian3.clone(known.position),
|
||||
position: clone(known.position),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -106,13 +107,13 @@ export function createFocus({ state: layerState, services, parts, source }) {
|
||||
/**
|
||||
* Pick the observed candidate closest to the current view. This is intentionally
|
||||
* a navigation preference, not a risk, capability, or affiliation calculation.
|
||||
* @param {Array<{position: Cesium.Cartesian3}>} candidates Observed candidates.
|
||||
* @param {Array<{position: {x: number, y: number, z: number}}>} candidates Observed candidates.
|
||||
* @returns {Object|null} The best currently observable candidate.
|
||||
*/
|
||||
|
||||
function closestToCurrentView(candidates) {
|
||||
if (!Array.isArray(candidates) || !candidates.length) return null;
|
||||
const cameraPosition = layerState.viewer?.camera?.positionWC;
|
||||
const cameraPosition = findCamera(layerState.viewer)?.pose()?.position;
|
||||
if (!cameraPosition)
|
||||
return candidates.find((candidate) => candidate?.position) || null;
|
||||
|
||||
@@ -120,13 +121,10 @@ export function createFocus({ state: layerState, services, parts, source }) {
|
||||
let closestDistance = Infinity;
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate?.position) continue;
|
||||
const distance = Cesium.Cartesian3.distance(
|
||||
cameraPosition,
|
||||
candidate.position,
|
||||
);
|
||||
if (Number.isFinite(distance) && distance < closestDistance) {
|
||||
const metres = distance(cameraPosition, candidate.position);
|
||||
if (Number.isFinite(metres) && metres < closestDistance) {
|
||||
closest = candidate;
|
||||
closestDistance = distance;
|
||||
closestDistance = metres;
|
||||
}
|
||||
}
|
||||
return closest;
|
||||
@@ -180,9 +178,9 @@ export function createFocus({ state: layerState, services, parts, source }) {
|
||||
announceNavigationAuthority('context-vessel-autofocus', {
|
||||
cancelPendingSelection: false,
|
||||
});
|
||||
layerState.viewer.camera.flyToBoundingSphere(
|
||||
new Cesium.BoundingSphere(vessel.position, VESSEL_FOCUS_RADIUS_M),
|
||||
{ duration: 1.6 },
|
||||
cameraOf(layerState.viewer).flyToBounds(
|
||||
{ center: vessel.position, radius: VESSEL_FOCUS_RADIUS_M },
|
||||
{ durationS: 1.6 },
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ export function createHistory({ state: layerState, services, parts, source }) {
|
||||
return (
|
||||
items.find(
|
||||
(item) =>
|
||||
String(item?.icao24 || item?.mmsi || item?.id) === String(subject.id),
|
||||
String(item?.icao24 || item?.id || item?.mmsi) === String(subject.id),
|
||||
) || subject
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,14 @@ import { createControls } from './controls.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createState } from './state.js';
|
||||
|
||||
/** Construct one layer with its own scene state and supplied application services. */
|
||||
/**
|
||||
* Construct one layer with its own scene state and supplied application services.
|
||||
*
|
||||
* Its context rim is a renderer draw set (`drawOf(viewer)`) and its flights
|
||||
* go through `cameraOf`. Given a Cesium viewer with no
|
||||
* renderer bound, the caller loads the package's `./render/cesium/unbound`
|
||||
* export first.
|
||||
*/
|
||||
export function createAwarenessLayer({ services, source }) {
|
||||
const state = createState({ services });
|
||||
const parts = {};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { cameraPoseSignature } from '../../data/iconOrientation.js';
|
||||
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import { AWARENESS_RANGE_PULSE } from './policy.js';
|
||||
|
||||
export function createLifecycle({
|
||||
@@ -11,13 +11,13 @@ export function createLifecycle({
|
||||
|
||||
/**
|
||||
* Note the user handling the map's camera (pointer, wheel or touch on the
|
||||
* Cesium canvas, where its camera controller listens), so a camera move the
|
||||
* user made can wake the range pulses and one the app made (tracking,
|
||||
* cockpit, orbit, a fly-to) does not. Keys are left out: Cesium's camera
|
||||
* controller reads none, and typing elsewhere must not count. Nor does
|
||||
* input while the camera controller's inputs are off: the cockpit (or a
|
||||
* gizmo drag, or a drawing tool) owns the camera then, and the user's
|
||||
* gesture moves nothing.
|
||||
* renderer's canvas, where its camera controls listen), so a camera move
|
||||
* the user made can wake the range pulses and one the app made (tracking,
|
||||
* cockpit, orbit, a fly-to) does not. Keys are left out: the camera
|
||||
* controls read none, and typing elsewhere must not count. Nor does input
|
||||
* while the camera controls are suspended: the cockpit (or a gizmo drag,
|
||||
* or a drawing tool) owns the camera then, and the user's gesture moves
|
||||
* nothing.
|
||||
*/
|
||||
function noteCameraInput(event) {
|
||||
if (event?.type === 'pointermove' && !event.buttons) return;
|
||||
@@ -28,8 +28,9 @@ export function createLifecycle({
|
||||
followGesture(true);
|
||||
}
|
||||
|
||||
// A drag can leave the canvas, and Cesium follows it at document level
|
||||
// (in Firefox, and wherever there are no pointer events). So does this,
|
||||
// A drag can leave the canvas, and the camera controls follow it at
|
||||
// document level (in Firefox, and wherever there are no pointer events).
|
||||
// So does this,
|
||||
// from a gesture's start on the canvas to its end, so a long gesture keeps
|
||||
// the input window open the whole way.
|
||||
const GESTURE_MOVE_EVENTS = ['pointermove', 'touchmove'];
|
||||
@@ -56,7 +57,7 @@ export function createLifecycle({
|
||||
}
|
||||
|
||||
// A gesture ends with its last contact: lifting one finger of a pinch
|
||||
// leaves Cesium a one-finger drag.
|
||||
// leaves the camera controls a one-finger drag.
|
||||
function endGesture(event) {
|
||||
noteCameraInput(event);
|
||||
activePointers.delete(event?.pointerId);
|
||||
@@ -77,8 +78,7 @@ export function createLifecycle({
|
||||
}
|
||||
|
||||
function cameraInputsEnabled() {
|
||||
const controller = layerState.viewer?.scene?.screenSpaceCameraController;
|
||||
return controller?.enableInputs !== false;
|
||||
return findCamera(layerState.viewer)?.controls?.enabled !== false;
|
||||
}
|
||||
|
||||
const CAMERA_INPUT_EVENTS = [
|
||||
@@ -90,16 +90,22 @@ export function createLifecycle({
|
||||
];
|
||||
|
||||
/**
|
||||
* Quantized camera-pose signature, or '' when the camera cannot report a full
|
||||
* pose yet. An unknown pose reads as PARKED, so a camera that is still coming
|
||||
* up can never be mistaken for continuous movement.
|
||||
* @param {Cesium.Camera|null|undefined} camera
|
||||
* Quantized camera-pose signature (position to ~10 m, angles to ~0.06
|
||||
* degrees), or '' when the camera cannot report a full pose yet. An unknown
|
||||
* pose reads as PARKED, so a camera that is still coming up can never be
|
||||
* mistaken for continuous movement.
|
||||
* @param {object|null|undefined} viewer
|
||||
* @returns {string}
|
||||
*/
|
||||
|
||||
function cameraMotionSignature(camera) {
|
||||
if (!camera?.positionWC || !Number.isFinite(camera.heading)) return '';
|
||||
return cameraPoseSignature(camera);
|
||||
function cameraMotionSignature(viewer) {
|
||||
const pose = findCamera(viewer)?.pose();
|
||||
const p = pose?.position;
|
||||
if (!p || !Number.isFinite(pose.heading)) return '';
|
||||
return (
|
||||
`${Math.round(p.x / 10)}:${Math.round(p.y / 10)}:${Math.round(p.z / 10)}:` +
|
||||
`${pose.heading.toFixed(3)}:${pose.pitch.toFixed(3)}:${pose.roll.toFixed(3)}`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,23 +137,23 @@ export function createLifecycle({
|
||||
'gev:awareness-subject-cleared',
|
||||
layerState.subjectClearListener,
|
||||
);
|
||||
const input = layerState.viewer.canvas ?? layerState.viewer.scene?.canvas;
|
||||
const input = canvasOf(layerState.viewer);
|
||||
for (const type of CAMERA_INPUT_EVENTS)
|
||||
input?.addEventListener?.(type, noteCameraInput, { passive: true });
|
||||
layerState.cameraInputTarget = input ?? null;
|
||||
layerState.preRenderRemover =
|
||||
layerState.viewer.scene.preRender.addEventListener(() => {
|
||||
layerState.preRenderRemover = findFrame(layerState.viewer)?.on(
|
||||
'preRender',
|
||||
() => {
|
||||
if (!layerState.enabled) return;
|
||||
const now = Date.now();
|
||||
// Another owner took the camera: a gesture begun before it did must
|
||||
// not wake the pulses on that owner's first move.
|
||||
if (!cameraInputsEnabled())
|
||||
layerState.lastCameraInputMs = Number.NEGATIVE_INFINITY;
|
||||
// "Did the camera move" uses the SAME quantized pose signature the fleet
|
||||
// rotation pass gates on (iconOrientation.cameraPoseSignature) rather than
|
||||
// camera.changed, whose granularity is globally degraded by other layers
|
||||
// mutating camera.percentageChanged.
|
||||
const poseSig = cameraMotionSignature(layerState.viewer.camera);
|
||||
// "Did the camera move" uses the same quantization as the fleet
|
||||
// rotation pass's cameraPoseSignature (render/cesium/iconOrientation;
|
||||
// keep the two in step), read from the camera port's pose.
|
||||
const poseSig = cameraMotionSignature(layerState.viewer);
|
||||
if (poseSig !== layerState.lastCameraPoseSig) {
|
||||
layerState.lastCameraPoseSig = poseSig;
|
||||
layerState.lastCameraPoseChangeMs = now;
|
||||
@@ -183,7 +189,8 @@ export function createLifecycle({
|
||||
} else {
|
||||
parts.rendering.scheduleDirectionOverlayUpdate();
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
layerState.runtimeListenersAttached = true;
|
||||
}
|
||||
|
||||
@@ -335,6 +342,7 @@ export function createLifecycle({
|
||||
detachRuntimeListeners();
|
||||
parts.panel.clearPanel();
|
||||
parts.rendering.removeDirectionOverlay();
|
||||
parts.rendering.disposeVisual();
|
||||
layerState.subjectListener = null;
|
||||
layerState.contextListener = null;
|
||||
layerState.clearListener = null;
|
||||
|
||||
@@ -118,7 +118,7 @@ export function createPanel({ state: layerState, parts }) {
|
||||
.slice(page, page + AWARENESS_PAGE_SIZE)
|
||||
.map((item, index) => {
|
||||
const label = formatAwarenessLabel(item);
|
||||
const targetId = item.icao24 || item.mmsi || item.id;
|
||||
const targetId = item.icao24 || item.id || item.mmsi;
|
||||
const distance = presentAwarenessDistance(item.distanceM);
|
||||
if (!targetId)
|
||||
return {
|
||||
@@ -183,15 +183,56 @@ export function createPanel({ state: layerState, parts }) {
|
||||
: null;
|
||||
}
|
||||
|
||||
/** The credit line: the photographer, and an open photo's licence. A
|
||||
* photo whose answer names no photographer shows no photographer. */
|
||||
function photoCredit(photo) {
|
||||
if (photo.licence)
|
||||
return photo.photographer
|
||||
? t('Photo: {photographer} · {licence}', {
|
||||
photographer: photo.photographer,
|
||||
licence: photo.licence,
|
||||
})
|
||||
: t('Photo · {licence}', { licence: photo.licence });
|
||||
return photo.photographer
|
||||
? t('Photo © {photographer}', { photographer: photo.photographer })
|
||||
: '';
|
||||
}
|
||||
|
||||
/** The subject's photo with its credit, or null. The subject
|
||||
* refresh resolves it; only the subject it was resolved for shows it. */
|
||||
function presentPhoto(subject) {
|
||||
const held = layerState.subjectPhoto;
|
||||
if (
|
||||
!held ||
|
||||
held.layerId !== subject.layerId ||
|
||||
String(held.id) !== String(subject.id)
|
||||
)
|
||||
return null;
|
||||
const { photo } = held;
|
||||
return {
|
||||
src: photo.src,
|
||||
width: photo.width ?? null,
|
||||
height: photo.height ?? null,
|
||||
link: photo.link,
|
||||
credit: photoCredit(photo),
|
||||
};
|
||||
}
|
||||
|
||||
function renderResults() {
|
||||
if (!layerState.enabled || !layerState.results) return hidePanel();
|
||||
ensurePanel();
|
||||
layerState.panelRenders += 1;
|
||||
const { subject, cohorts } = layerState.results;
|
||||
const windowLabel = t('{distance} FLIGHT / VESSEL WINDOW', {
|
||||
distance: presentAwarenessDistance(AWARENESS_RADIUS_M),
|
||||
});
|
||||
publish({
|
||||
kind: 'results',
|
||||
subject: `${subject.label} · ${t('{distance} FLIGHT / VESSEL WINDOW', { distance: presentAwarenessDistance(AWARENESS_RADIUS_M) })}`,
|
||||
subject: `${subject.label} · ${windowLabel}`,
|
||||
subjectIdentity: { layerId: subject.layerId, id: subject.id },
|
||||
subjectLabel: subject.label,
|
||||
subjectNames: presentNames(subject.memberNames),
|
||||
photo: presentPhoto(subject),
|
||||
navigation: presentNavigation(),
|
||||
rows: cohorts.map(presentRow),
|
||||
note: t(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createPanel } from './panel.js';
|
||||
import { createSubject } from './subject.js';
|
||||
|
||||
test('a Contacts row names its provider as the Layers panel does, with its feed state', () => {
|
||||
const cohort = (id, source, sourceStatus) => ({
|
||||
@@ -36,3 +37,175 @@ test('a Contacts row names its provider as the Layers panel does, with its feed
|
||||
);
|
||||
state.offPanelLocale?.();
|
||||
});
|
||||
|
||||
const PHOTO = Object.freeze({
|
||||
src: 'https://t.plnspttrs.net/1/abc123_280.jpg',
|
||||
width: 280,
|
||||
height: 186,
|
||||
photographer: 'Jane Doe',
|
||||
link: 'https://www.planespotters.net/photo/1/n123ab',
|
||||
});
|
||||
|
||||
/** The published Contacts view for one subject and the refresh's photo. */
|
||||
function photoView(subject, subjectPhoto) {
|
||||
const state = {
|
||||
enabled: true,
|
||||
results: { subject, cohorts: [] },
|
||||
subjectPhoto,
|
||||
cohortPages: new Map(),
|
||||
panelListeners: new Set(),
|
||||
panelSignature: '',
|
||||
navigationIndex: 0,
|
||||
};
|
||||
const parts = {
|
||||
navigation: { canNavigateNext: () => false },
|
||||
rendering: { hideDirectionOverlay() {} },
|
||||
};
|
||||
createPanel({ state, parts }).renderResults();
|
||||
state.offPanelLocale?.();
|
||||
return state.panelView;
|
||||
}
|
||||
|
||||
const FLIGHT = Object.freeze({
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
label: 'N123AB',
|
||||
});
|
||||
|
||||
test('the Contacts view carries the tracked flight’s photo with its credit', () => {
|
||||
const view = photoView(FLIGHT, {
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
photo: PHOTO,
|
||||
});
|
||||
assert.deepEqual(view.photo, {
|
||||
src: PHOTO.src,
|
||||
width: 280,
|
||||
height: 186,
|
||||
link: PHOTO.link,
|
||||
credit: 'Photo © Jane Doe',
|
||||
});
|
||||
});
|
||||
|
||||
test('the Contacts view shows an uncredited photo with no credit line', () => {
|
||||
const view = photoView(FLIGHT, {
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
photo: { ...PHOTO, photographer: '' },
|
||||
});
|
||||
assert.equal(view.photo.src, PHOTO.src);
|
||||
assert.equal(view.photo.link, PHOTO.link);
|
||||
assert.equal(view.photo.credit, '');
|
||||
});
|
||||
|
||||
test('the Contacts view has no photo without one, or with another subject’s', () => {
|
||||
assert.equal(photoView(FLIGHT, null).photo, null);
|
||||
assert.equal(
|
||||
photoView(FLIGHT, { layerId: 'flights', id: 'def456', photo: PHOTO }).photo,
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
photoView(
|
||||
{ layerId: 'ais-live-vessels', id: 'abc123', label: 'VESSEL' },
|
||||
{ layerId: 'flights', id: 'abc123', photo: PHOTO },
|
||||
).photo,
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('the selected vessel shows its own photo, by its id', () => {
|
||||
const asked = [];
|
||||
const { resolveSubjectPhoto, subjectFromContext } = createSubject({
|
||||
state: {},
|
||||
services: {
|
||||
flights: {},
|
||||
military: {},
|
||||
vessels: {
|
||||
getVesselPhoto: (id) => {
|
||||
asked.push(id);
|
||||
return id === 'uuid-1' ? PHOTO : null;
|
||||
},
|
||||
},
|
||||
installations: {},
|
||||
},
|
||||
parts: { navigation: { isFlightLayer: () => false } },
|
||||
});
|
||||
assert.deepEqual(
|
||||
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-1' }),
|
||||
PHOTO,
|
||||
);
|
||||
assert.equal(
|
||||
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-2' }),
|
||||
null,
|
||||
);
|
||||
assert.deepEqual(asked, ['uuid-1', 'uuid-2']);
|
||||
const vessel = (label, mmsi) =>
|
||||
subjectFromContext({
|
||||
layerId: 'ais-live-vessels',
|
||||
id: 'ais-uuid-1',
|
||||
label,
|
||||
latitude: 38.3,
|
||||
longitude: -123.05,
|
||||
properties: { vesselId: 'uuid-1', mmsi },
|
||||
});
|
||||
assert.equal(
|
||||
vessel('USCGC SOCKEYE', '366999709').label,
|
||||
'USCGC SOCKEYE · MMSI 366999709',
|
||||
);
|
||||
assert.equal(vessel('USCGC SOCKEYE', '366999709').id, 'uuid-1');
|
||||
// A vessel named by its MMSI, or without one, is not given it twice.
|
||||
assert.equal(vessel('MMSI 366999709', '366999709').label, 'MMSI 366999709');
|
||||
assert.equal(vessel('USCGC SOCKEYE', null).label, 'USCGC SOCKEYE');
|
||||
});
|
||||
|
||||
test('only the tracked flight has a flight photo: not an installation, a military aircraft or another flight', () => {
|
||||
const tracked = {
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
label: 'N123AB',
|
||||
photo: PHOTO,
|
||||
};
|
||||
let current = tracked;
|
||||
let lookups = 0;
|
||||
const flights = {
|
||||
getTrackedSubject: () => {
|
||||
lookups += 1;
|
||||
return current;
|
||||
},
|
||||
};
|
||||
const military = {
|
||||
getTrackedSubject: () => ({ ...tracked, layerId: 'military' }),
|
||||
};
|
||||
const { resolveSubjectPhoto } = createSubject({
|
||||
state: {},
|
||||
services: { flights, military, vessels: {}, installations: {} },
|
||||
parts: {
|
||||
navigation: {
|
||||
isFlightLayer: (id) => id === 'flights' || id === 'military',
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }),
|
||||
PHOTO,
|
||||
);
|
||||
assert.equal(lookups, 1);
|
||||
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'def456' }), null);
|
||||
assert.equal(
|
||||
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'abc123' }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveSubjectPhoto({ layerId: 'military-installations', id: 'abc123' }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveSubjectPhoto({ layerId: 'military', id: 'abc123' }),
|
||||
null,
|
||||
);
|
||||
assert.equal(resolveSubjectPhoto(null), null);
|
||||
current = null;
|
||||
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
|
||||
current = { ...tracked, photo: null };
|
||||
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
|
||||
});
|
||||
@@ -49,7 +49,8 @@ export const CONTEXT_RIM_HEIGHT_M = 2500;
|
||||
* the FLIR, NVG and CRT styles. A bright core inside a dark halo keeps
|
||||
* luminance contrast on light and dark ground alike, and luminance is what
|
||||
* the monochrome styles keep. The core is the Context panel's blue; the halo
|
||||
* is the map-card ink. Widths are screen pixels; `outlineWidth` is per side.
|
||||
* is the map-card ink. Widths are screen pixels; `outlineWidth` is the
|
||||
* halo's width in all, half on each side.
|
||||
* It is drawn as an unpickable primitive, so clicks on its edge reach the
|
||||
* contacts underneath.
|
||||
* While the sonar pulses run, the ring dims to `restOpacity` and flashes
|
||||
@@ -74,30 +75,32 @@ export const AWARENESS_RANGE_RING_STYLE = Object.freeze({
|
||||
* over `fadeInFraction` of its travel, then fades as (1 - travel) to the
|
||||
* `fadeOutPower` down to `endOpacityFraction` of `peakOpacity`, so a pulse
|
||||
* is dim but still visible when it reaches the ring and the ring flashes.
|
||||
* Each line is `width` CSS pixels wide, its outer `outlineWidth` a dark
|
||||
* halo, in the ring's colours, as Cesium's polyline outline material draws.
|
||||
* Each front is a line `width` CSS pixels wide whose outer `outlineWidth`,
|
||||
* half on each side, is a dark halo, in the ring's colours.
|
||||
* Behind each line a radial gradient in the same blue fades inward over
|
||||
* `gradientDepthFraction` of the radius, at most
|
||||
* `gradientOpacity` strong. One unpickable disc draws the lines and the
|
||||
* gradient, so pulses never catch a click meant for a contact; its shader
|
||||
* takes at most four pulses. The disc follows the subject by a model-matrix
|
||||
* rotation, so it stays concentric with the ring, and is rebuilt only after
|
||||
* the subject moves `gradientRebuildM` from where it was built; while the
|
||||
* pulses rest the hidden disc is left alone and catches up when they wake. The
|
||||
* disc is hidden while the camera is below its height, where it would sweep
|
||||
* the sky.
|
||||
* `gradientDepthFraction` of the radius, at most `gradientOpacity` strong,
|
||||
* painted on a canvas that fills one flat ellipse at the rim. Lines and
|
||||
* ellipse are unpickable, so pulses never catch a click meant for a
|
||||
* contact. The ellipse is `gradientRebuildM` wider than the ring and moves
|
||||
* only after the subject moves that far from where it was built, the
|
||||
* canvas keeping the band concentric meanwhile; while the pulses rest the
|
||||
* hidden band is left alone and catches up when they wake. The band is
|
||||
* hidden while the camera is below its height, where it would sweep the
|
||||
* sky.
|
||||
* The pulses run for `activeMs` (three ring flashes) after a selection or
|
||||
* a camera move, fading in and out over `settleMs`, then rest: the ring
|
||||
* stays on screen, static, and nothing asks for frames, so a parked view
|
||||
* goes quiet again. Only a camera move within `inputWakeMs` of the user
|
||||
* handling the map (pointer, wheel or touch on the canvas, which covers a
|
||||
* drag's inertia, while the camera controls take input) wakes them; a moving subject and the app's own camera moves
|
||||
* (tracking, cockpit, orbit, a fly-to) do not. Below the disc's height they
|
||||
* (tracking, cockpit, orbit, a fly-to) do not. Below the band's height they
|
||||
* rest too. While they run they never hold
|
||||
* continuous rendering; each drawn frame arms one more request after the
|
||||
* Cyber sonar's 80 ms cadence, so the two never beat. When something else
|
||||
* already renders continuously they update every frame. Skipped under
|
||||
* prefers-reduced-motion. */
|
||||
* continuous rendering; each drawn frame arms one more step after the
|
||||
* Cyber sonar's 80 ms cadence, so the two never beat. Fronts and band,
|
||||
* fixed in the world, step at that cadence however many frames are
|
||||
* drawn, so they look the same whether the camera moves or not; crossing
|
||||
* the rim height shows or hides them at once.
|
||||
* Skipped under prefers-reduced-motion. */
|
||||
export const AWARENESS_RANGE_PULSE = Object.freeze({
|
||||
count: 3,
|
||||
periodMs: 9000,
|
||||
|
||||
@@ -0,0 +1,802 @@
|
||||
/**
|
||||
* @module layers/awareness/rangeRing
|
||||
* @description The Global Context range ring and its sonar pulses, drawn
|
||||
* through the renderer's draw port. The ring is a haloed line (a solid line
|
||||
* with an outline) 2.5 km above the ellipsoid. While pulses run, each pulse
|
||||
* front is a haloed line whose positions move each step, every
|
||||
* `CYBER_SONAR_RENDER_INTERVAL_MS` whether the camera moves or not. The
|
||||
* band behind the fronts is one flat ellipse at the same height filled
|
||||
* with a canvas painted anew each step (a new key for new content). Nothing here is
|
||||
* pickable, so a click or tap near the ring reaches the contact underneath.
|
||||
* Under reduced motion, or where the renderer has no frame hooks, the ring
|
||||
* alone is drawn and stays.
|
||||
*/
|
||||
import { CYBER_SONAR_RENDER_INTERVAL_MS } from '../../cyberSonar.js';
|
||||
import { AWARENESS_RADIUS_M } from '../../data/militaryAwarenessEngine.js';
|
||||
import {
|
||||
AWARENESS_RANGE_ECHO,
|
||||
AWARENESS_RANGE_PULSE,
|
||||
AWARENESS_RANGE_RING_STYLE,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
} from './policy.js';
|
||||
import {
|
||||
awarenessEchoStrength,
|
||||
clearAwarenessEchoField,
|
||||
setAwarenessEchoField,
|
||||
} from '../../awarenessEcho.js';
|
||||
import { WGS84, fromRadians, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { distance, sub } from '../../geo/vector.js';
|
||||
import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
|
||||
/**
|
||||
* A closed ring of positions `radiusM` along the surface from `groundCenter`,
|
||||
* raised to `heightM`. Each bearing steps over a sphere with the ellipsoid's
|
||||
* radius of curvature in that direction (Euler's formula), which keeps the
|
||||
* ring within ~50 m of the true geodesic radius at 250 km.
|
||||
* @param {{x: number, y: number, z: number}} groundCenter Ring centre on the ellipsoid.
|
||||
* @param {number} radiusM Surface radius in metres.
|
||||
* @param {number} heightM Height of the ring above the ellipsoid.
|
||||
* @param {number} [segments] Chords around the ring.
|
||||
* @returns {{x: number, y: number, z: number}[]} `segments + 1` positions;
|
||||
* the last repeats the first.
|
||||
*/
|
||||
export function awarenessRangeRingPositions(
|
||||
groundCenter,
|
||||
radiusM,
|
||||
heightM,
|
||||
segments = AWARENESS_RANGE_RING_STYLE.segments,
|
||||
) {
|
||||
const { up, bearings } = ringFrame(groundCenter, segments);
|
||||
const r2 = WGS84.radiiSquared;
|
||||
const positions = new Array(bearings.length);
|
||||
for (let i = 0; i < bearings.length; i++) {
|
||||
const { per, along } = bearings[i];
|
||||
const angular = radiusM * per;
|
||||
const cosA = Math.cos(angular);
|
||||
const sinA = Math.sin(angular);
|
||||
// The unit vector there on the sphere, taken as the ellipsoid's
|
||||
// surface normal (its latitude read as geodetic) and raised to
|
||||
// `heightM` along it, as `fromRadians` places a longitude and latitude.
|
||||
let nx = up[0] * cosA + along[0] * sinA;
|
||||
let ny = up[1] * cosA + along[1] * sinA;
|
||||
let nz = up[2] * cosA + along[2] * sinA;
|
||||
const length = Math.hypot(nx, ny, nz);
|
||||
nx /= length;
|
||||
ny /= length;
|
||||
nz /= length;
|
||||
const kx = r2.x * nx;
|
||||
const ky = r2.y * ny;
|
||||
const kz = r2.z * nz;
|
||||
const gamma = Math.sqrt(nx * kx + ny * ky + nz * kz);
|
||||
positions[i] = {
|
||||
x: kx / gamma + nx * heightM,
|
||||
y: ky / gamma + ny * heightM,
|
||||
z: kz / gamma + nz * heightM,
|
||||
};
|
||||
}
|
||||
return positions;
|
||||
}
|
||||
|
||||
/** The last ring frame made: fronts at one centre share it. */
|
||||
let lastRingFrame = null;
|
||||
|
||||
/**
|
||||
* What a ring about `groundCenter` needs but its radius: the centre's up
|
||||
* unit vector and, per bearing, the angle a metre of surface turns
|
||||
* (Euler's formula) and the unit vector along the great circle. Kept for
|
||||
* the last centre asked for.
|
||||
*/
|
||||
function ringFrame(groundCenter, segments) {
|
||||
const last = lastRingFrame;
|
||||
if (
|
||||
last?.segments === segments &&
|
||||
last.x === groundCenter.x &&
|
||||
last.y === groundCenter.y &&
|
||||
last.z === groundCenter.z
|
||||
)
|
||||
return last;
|
||||
const { lon, lat } = toLonLatH(groundCenter);
|
||||
const latitude = (lat * Math.PI) / 180;
|
||||
const longitude = (lon * Math.PI) / 180;
|
||||
const { x: a, z: b } = WGS84.radii;
|
||||
const e2 = 1 - (b * b) / (a * a);
|
||||
const sinLat = Math.sin(latitude);
|
||||
const cosLat = Math.cos(latitude);
|
||||
const sinLon = Math.sin(longitude);
|
||||
const cosLon = Math.cos(longitude);
|
||||
const w = 1 - e2 * sinLat * sinLat;
|
||||
const meridional = (a * (1 - e2)) / (w * Math.sqrt(w));
|
||||
const primeVertical = a / Math.sqrt(w);
|
||||
// Step along the great circle in 3D from the centre's up, north and east
|
||||
// unit vectors. Unlike the latitude/longitude destination formula, this
|
||||
// stays well conditioned at and next to the poles.
|
||||
const up = [cosLat * cosLon, cosLat * sinLon, sinLat];
|
||||
const north = [-sinLat * cosLon, -sinLat * sinLon, cosLat];
|
||||
const east = [-sinLon, cosLon, 0];
|
||||
const bearings = [];
|
||||
for (let i = 0; i <= segments; i++) {
|
||||
const bearing = ((i % segments) / segments) * 2 * Math.PI;
|
||||
const cosB = Math.cos(bearing);
|
||||
const sinB = Math.sin(bearing);
|
||||
bearings.push({
|
||||
per: (cosB * cosB) / meridional + (sinB * sinB) / primeVertical,
|
||||
along: north.map((n, k) => n * cosB + east[k] * sinB),
|
||||
});
|
||||
}
|
||||
lastRingFrame = {
|
||||
x: groundCenter.x,
|
||||
y: groundCenter.y,
|
||||
z: groundCenter.z,
|
||||
segments,
|
||||
up,
|
||||
bearings,
|
||||
};
|
||||
return lastRingFrame;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where pulse `index` is at `nowMs`: its radius and opacity. Pulses travel at
|
||||
* constant speed from `startFraction` of the range to the full range, fade in
|
||||
* over `fadeInFraction` of the way, then fade as (1 - travel) to the
|
||||
* `fadeOutPower` down to `endOpacityFraction` of the peak, so each is dim
|
||||
* but still visible when it reaches the range ring. The opacity already
|
||||
* includes `peakOpacity`.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {number} index Pulse number, 0 to `count - 1`.
|
||||
* @param {number} [radiusM] Range the pulses grow to.
|
||||
* @param {object} [pulse] Timing and shape, see `AWARENESS_RANGE_PULSE`.
|
||||
* @returns {{radiusM: number, alpha: number}}
|
||||
*/
|
||||
export function awarenessPulseState(
|
||||
nowMs,
|
||||
index,
|
||||
radiusM = AWARENESS_RADIUS_M,
|
||||
pulse = AWARENESS_RANGE_PULSE,
|
||||
) {
|
||||
const cycle = nowMs / pulse.periodMs + index / pulse.count;
|
||||
const phase = cycle - Math.floor(cycle);
|
||||
return {
|
||||
radiusM:
|
||||
radiusM * (pulse.startFraction + (1 - pulse.startFraction) * phase),
|
||||
alpha:
|
||||
pulse.peakOpacity *
|
||||
Math.min(1, phase / pulse.fadeInFraction) *
|
||||
(pulse.endOpacityFraction +
|
||||
(1 - pulse.endOpacityFraction) * (1 - phase) ** pulse.fadeOutPower),
|
||||
};
|
||||
}
|
||||
|
||||
const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
|
||||
|
||||
/** Whether the viewer asked the system for less motion. */
|
||||
function prefersReducedMotion() {
|
||||
return globalThis.matchMedia?.(REDUCED_MOTION_QUERY)?.matches ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far the pulses are switched on at `nowMs`: 0 at rest, rising to 1 over
|
||||
* `settleMs` from `wake.startMs` and falling back to 0 over `settleMs` up to
|
||||
* `wake.untilMs`.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {{startMs: number, untilMs: number}} wake Window from `wakeAwarenessPulses`.
|
||||
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
|
||||
* @returns {number} 0 to 1.
|
||||
*/
|
||||
export function awarenessPulseLevel(
|
||||
nowMs,
|
||||
wake,
|
||||
pulse = AWARENESS_RANGE_PULSE,
|
||||
) {
|
||||
const level = Math.min(
|
||||
(nowMs - wake.startMs) / pulse.settleMs,
|
||||
(wake.untilMs - nowMs) / pulse.settleMs,
|
||||
);
|
||||
return Math.max(0, Math.min(1, level));
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the pulses for `activeMs` from `nowMs`. A wake while they already run
|
||||
* keeps their current level, so they never jump back to full mid-fade.
|
||||
* @param {{startMs: number, untilMs: number}} wake Updated in place.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
|
||||
* @returns {{startMs: number, untilMs: number}} `wake`.
|
||||
*/
|
||||
export function wakeAwarenessPulses(
|
||||
wake,
|
||||
nowMs,
|
||||
pulse = AWARENESS_RANGE_PULSE,
|
||||
) {
|
||||
wake.startMs =
|
||||
nowMs - awarenessPulseLevel(nowMs, wake, pulse) * pulse.settleMs;
|
||||
wake.untilMs = nowMs + pulse.activeMs;
|
||||
return wake;
|
||||
}
|
||||
|
||||
/**
|
||||
* How strongly the 250 km ring shows at `nowMs` while pulses run: 1 as a
|
||||
* pulse front reaches it, fading over `flashMs`, so the ring appears once
|
||||
* per arriving pulse instead of standing on screen.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @returns {number} 0 to 1.
|
||||
*/
|
||||
export function awarenessRingFlash(nowMs) {
|
||||
return awarenessEchoStrength(
|
||||
nowMs,
|
||||
AWARENESS_RADIUS_M,
|
||||
AWARENESS_RADIUS_M,
|
||||
AWARENESS_RANGE_PULSE,
|
||||
{ fadeMs: AWARENESS_RANGE_RING_STYLE.flashMs },
|
||||
);
|
||||
}
|
||||
|
||||
/** `rgba(r, g, b, a)` as a draw-port colour, channels 0 to 1. */
|
||||
function rgba(css) {
|
||||
const [r, g, b, a = 1] = css.match(/[\d.]+/g).map(Number);
|
||||
return [r / 255, g / 255, b / 255, a];
|
||||
}
|
||||
|
||||
/** A colour with its alpha scaled by `alpha`. */
|
||||
const faded = ([r, g, b, a], alpha) => [r, g, b, a * alpha];
|
||||
|
||||
/**
|
||||
* A haloed line as the draw port draws it: `widthPx` wide, an outer
|
||||
* `haloPx` in all (half on each side) in the halo's colour, the rest in the
|
||||
* core's.
|
||||
* @returns {object} The line item.
|
||||
*/
|
||||
const haloedLine = (id, positions, { core, halo, widthPx, haloPx, show }) => ({
|
||||
id,
|
||||
positions,
|
||||
widthPx,
|
||||
mode: '3d',
|
||||
style: {
|
||||
kind: 'solid',
|
||||
color: core,
|
||||
outline: { color: halo, widthPx: haloPx },
|
||||
},
|
||||
show,
|
||||
});
|
||||
|
||||
/** Side of the band's canvas, pixels: the band is soft, 2 km a pixel. */
|
||||
export const AWARENESS_BAND_PIXELS = 256;
|
||||
|
||||
/**
|
||||
* The band behind the pulse fronts into `image` (an `ImageData` of
|
||||
* `size × size`): at each pixel, a fraction `r` of `rangeM` from the
|
||||
* subject, the sum over pulses of `alpha × t²` where the pulse's front is
|
||||
* within `gradientDepthFraction` of the range outside it (`t` is 1 at the
|
||||
* front, 0 that far inward), times `gradientOpacity`, in `rgb`. The canvas
|
||||
* spans `spanM` either side of its centre; the subject is `offset` metres
|
||||
* east and north of that centre.
|
||||
*
|
||||
* The band depends on the distance from the subject alone: its alpha byte
|
||||
* is tabulated along the radius, out to the range or the outermost front
|
||||
* if that is further, finer than a pixel, and each pixel looks it up. Which
|
||||
* entry each pixel reads changes only with the canvas, its span and the
|
||||
* subject's offset; `memo`, kept between calls, holds it, so a step that
|
||||
* only moves the fronts takes no square roots.
|
||||
* @param {{data: Uint8ClampedArray, width: number}} image
|
||||
* @param {{radii: number[], alphas: number[], rgb: number[], spanM: number,
|
||||
* rangeM: number, offset: {east: number, north: number}, pulse?: object}} band
|
||||
* @param {object} [memo] An object of the caller's, empty at first.
|
||||
*/
|
||||
export function paintAwarenessBand(image, band, memo = {}) {
|
||||
const { radii, alphas, rgb, spanM, rangeM, offset } = band;
|
||||
const pulse = band.pulse ?? AWARENESS_RANGE_PULSE;
|
||||
const size = image.width;
|
||||
const data = image.data;
|
||||
const depth = pulse.gradientDepthFraction;
|
||||
const opacity = pulse.gradientOpacity;
|
||||
let outer = 0;
|
||||
for (const radius of radii) outer = Math.max(outer, radius);
|
||||
const reach = Math.max(1, outer);
|
||||
const bins = 4 * size;
|
||||
// Past `reach` a pixel reads the last entry, which stays 0.
|
||||
if (memo.table?.length !== bins + 2) memo.table = new Uint8Array(bins + 2);
|
||||
const table = memo.table;
|
||||
for (let bin = 0; bin <= bins; bin++) {
|
||||
const at = (bin / bins) * reach;
|
||||
let sum = 0;
|
||||
for (let i = 0; i < radii.length; i++) {
|
||||
const inside = radii[i] - at;
|
||||
if (inside >= 0 && inside <= depth) {
|
||||
const t = 1 - inside / depth;
|
||||
sum += alphas[i] * t * t;
|
||||
}
|
||||
}
|
||||
// `Math.round` of a non-negative value.
|
||||
table[bin] = (Math.min(1, sum * opacity) * 255 + 0.5) | 0;
|
||||
}
|
||||
table[bins + 1] = 0;
|
||||
const key = `${size} ${spanM} ${rangeM} ${reach} ${offset.east} ${offset.north}`;
|
||||
if (memo.key !== key) {
|
||||
memo.key = key;
|
||||
const bin = (memo.bin =
|
||||
memo.bin?.length === size * size
|
||||
? memo.bin
|
||||
: new Uint16Array(size * size));
|
||||
const perPixel = (2 * spanM) / size / rangeM;
|
||||
const cx = size / 2 + offset.east / ((2 * spanM) / size);
|
||||
// Canvas rows run north to south.
|
||||
const cy = size / 2 - offset.north / ((2 * spanM) / size);
|
||||
const toBin = bins / reach;
|
||||
for (let y = 0; y < size; y++) {
|
||||
const dy = (y + 0.5 - cy) * perPixel;
|
||||
const dy2 = dy * dy;
|
||||
for (let x = 0; x < size; x++) {
|
||||
const dx = (x + 0.5 - cx) * perPixel;
|
||||
const at = Math.sqrt(dx * dx + dy2);
|
||||
bin[y * size + x] = at > reach ? bins + 1 : (at * toBin + 0.5) | 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
const bin = memo.bin;
|
||||
// Clamped as the image's bytes would clamp them.
|
||||
const [r, g, b] = rgb.map((c) =>
|
||||
Math.min(255, Math.max(0, Math.round(c * 255))),
|
||||
);
|
||||
// Whole pixels at a time where the bytes line up: each table entry as
|
||||
// the four bytes it writes, in the platform's byte order.
|
||||
if (data.byteOffset % 4 === 0 && data.length === bin.length * 4) {
|
||||
if (memo.pixels?.length !== table.length)
|
||||
memo.pixels = new Uint32Array(table.length);
|
||||
const pixels = memo.pixels;
|
||||
for (let i = 0; i < table.length; i++)
|
||||
pixels[i] = LITTLE_ENDIAN
|
||||
? (r | (g << 8) | (b << 16) | (table[i] << 24)) >>> 0
|
||||
: ((r << 24) | (g << 16) | (b << 8) | table[i]) >>> 0;
|
||||
const words = new Uint32Array(data.buffer, data.byteOffset, bin.length);
|
||||
for (let p = 0; p < bin.length; p++) words[p] = pixels[bin[p]];
|
||||
return;
|
||||
}
|
||||
for (let p = 0, k = 0; p < bin.length; p++, k += 4) {
|
||||
data[k] = r;
|
||||
data[k + 1] = g;
|
||||
data[k + 2] = b;
|
||||
data[k + 3] = table[bin[p]];
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether this platform stores the low byte of a word first. */
|
||||
const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
|
||||
|
||||
/** `p` in metres east and north of `origin`, in `origin`'s surface frame. */
|
||||
function eastNorth(origin, p) {
|
||||
const { lon, lat } = toLonLatH(origin);
|
||||
const l = (lon * Math.PI) / 180;
|
||||
const f = (lat * Math.PI) / 180;
|
||||
const d = sub(p, origin);
|
||||
return {
|
||||
east: -Math.sin(l) * d.x + Math.cos(l) * d.y,
|
||||
north:
|
||||
-Math.sin(f) * Math.cos(l) * d.x -
|
||||
Math.sin(f) * Math.sin(l) * d.y +
|
||||
Math.cos(f) * d.z,
|
||||
};
|
||||
}
|
||||
|
||||
/** Camera height above the ellipsoid, or NaN when the renderer cannot say. */
|
||||
function cameraHeightM(viewer) {
|
||||
return findCamera(viewer)?.pose()?.height ?? Number.NaN;
|
||||
}
|
||||
|
||||
/** Each instance's set ids are its own. */
|
||||
let instances = 0;
|
||||
|
||||
/**
|
||||
* The range ring and pulses of one awareness layer.
|
||||
* `layerState.visual` is what is drawn now, or null.
|
||||
* @param {object} options
|
||||
* @param {object} options.state
|
||||
* @param {(reason: string) => void} options.governorRequestRender
|
||||
* @param {(subject: object) => void} options.redraw Draws the subject's
|
||||
* ring again (a reduced-motion change).
|
||||
*/
|
||||
export function createRangeRing({
|
||||
state: layerState,
|
||||
governorRequestRender,
|
||||
redraw,
|
||||
}) {
|
||||
const instance = ++instances;
|
||||
/** The lines (ring and fronts) and the band's sets, on the viewer they draw on. */
|
||||
let sets = null;
|
||||
|
||||
function setsOn(viewer) {
|
||||
if (sets?.viewer === viewer) return sets;
|
||||
disposeSets();
|
||||
const draw = drawOf(viewer);
|
||||
sets = {
|
||||
viewer,
|
||||
lines: draw.lines({
|
||||
id: `awareness:${instance}:rim`,
|
||||
pickable: false,
|
||||
}),
|
||||
band: draw.shapes({
|
||||
id: `awareness:${instance}:band`,
|
||||
pickable: false,
|
||||
}),
|
||||
};
|
||||
return sets;
|
||||
}
|
||||
|
||||
function disposeSets() {
|
||||
sets?.lines.dispose();
|
||||
sets?.band.dispose();
|
||||
sets = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the range pulses again for `activeMs`, after a camera move. Call it
|
||||
* during a frame (lifecycle's preRender): that frame's postRender arms the
|
||||
* next request, so waking asks for no extra frame of its own. Pulses at
|
||||
* rest start in this frame; running ones keep their Cyber sonar interval,
|
||||
* however many frames a drag draws.
|
||||
*/
|
||||
function wakePulses() {
|
||||
const visual = layerState.visual;
|
||||
if (!visual?.wake) return;
|
||||
const nowMs = performance.now();
|
||||
wakeAwarenessPulses(visual.wake, nowMs);
|
||||
if (nowMs - visual.lastStepMs < CYBER_SONAR_RENDER_INTERVAL_MS) return;
|
||||
visual.lastStepMs = nowMs;
|
||||
visual.step(nowMs);
|
||||
}
|
||||
|
||||
function clearVisual() {
|
||||
const visual = layerState.visual;
|
||||
if (!visual) return;
|
||||
visual.stopPulses?.();
|
||||
visual.removeMotionListener?.();
|
||||
if (sets) {
|
||||
sets.lines.clear();
|
||||
sets.band.clear();
|
||||
}
|
||||
// Idle mode renders only on request; a removed ring must not linger.
|
||||
governorRequestRender('awareness-visual');
|
||||
clearAwarenessEchoField();
|
||||
layerState.visual = null;
|
||||
}
|
||||
|
||||
/** Let go of the sets too, as the layer goes. */
|
||||
function disposeVisual() {
|
||||
clearVisual();
|
||||
disposeSets();
|
||||
}
|
||||
|
||||
function renderVisual(subject) {
|
||||
const viewer = layerState.viewer;
|
||||
if (!viewer || !subject?.position) return;
|
||||
const location = toLonLatH(subject.position);
|
||||
if (!location) return;
|
||||
const groundCenter = fromRadians(
|
||||
(location.lon * Math.PI) / 180,
|
||||
(location.lat * Math.PI) / 180,
|
||||
0,
|
||||
);
|
||||
const key = `${subject.layerId}:${subject.id}`;
|
||||
const reducedMotion = prefersReducedMotion();
|
||||
const visual = layerState.visual;
|
||||
// A reduced-motion change rebuilds the visual, with or without pulses;
|
||||
// so does a ring drawn on another viewer (the layer re-initialized).
|
||||
if (
|
||||
visual?.key === key &&
|
||||
visual.viewer === viewer &&
|
||||
visual.reducedMotion === reducedMotion
|
||||
) {
|
||||
// Move the ring only after a meaningful displacement so live tracking
|
||||
// does not redraw it for sub-pixel motion every 750 ms.
|
||||
if (distance(visual.center, groundCenter) >= 250) {
|
||||
// The echo field reads `visual.center` in place and follows on its
|
||||
// own.
|
||||
Object.assign(visual.center, groundCenter);
|
||||
visual.ringPositions = awarenessRangeRingPositions(
|
||||
groundCenter,
|
||||
AWARENESS_RADIUS_M,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
);
|
||||
visual.lastStepMs = performance.now();
|
||||
visual.step(visual.lastStepMs);
|
||||
// Content actually changed — buy exactly one frame instead of holding.
|
||||
governorRequestRender('awareness-visual');
|
||||
}
|
||||
return;
|
||||
}
|
||||
clearVisual();
|
||||
const { lines, band } = setsOn(viewer);
|
||||
const frame = findFrame(viewer);
|
||||
// A renderer without frame hooks gets the static ring only, as the
|
||||
// Cyber sonar scene does. So does a viewer who prefers reduced motion.
|
||||
const animate = Boolean(!reducedMotion && frame?.on);
|
||||
// Pulses run from now until `wake.untilMs`, then rest.
|
||||
const wake = animate
|
||||
? wakeAwarenessPulses(
|
||||
{ startMs: -Infinity, untilMs: -Infinity },
|
||||
performance.now(),
|
||||
)
|
||||
: null;
|
||||
// From a camera below the rim height the band would sweep across the
|
||||
// sky, so the pulses are hidden there and rest with it: no flash, no
|
||||
// echoes, no frames.
|
||||
const belowRim = () => cameraHeightM(viewer) < CONTEXT_RIM_HEIGHT_M;
|
||||
// One step asks for the level at one time several times over; the
|
||||
// camera's pose is read once for them.
|
||||
let levelMemo = { nowMs: NaN, startMs: NaN, untilMs: NaN, level: 0 };
|
||||
const levelAt = (nowMs) => {
|
||||
if (!wake) return 0;
|
||||
const memo = levelMemo;
|
||||
if (
|
||||
memo.nowMs === nowMs &&
|
||||
memo.startMs === wake.startMs &&
|
||||
memo.untilMs === wake.untilMs
|
||||
)
|
||||
return memo.level;
|
||||
const level = belowRim() ? 0 : awarenessPulseLevel(nowMs, wake);
|
||||
levelMemo = {
|
||||
nowMs,
|
||||
startMs: wake.startMs,
|
||||
untilMs: wake.untilMs,
|
||||
level,
|
||||
};
|
||||
return level;
|
||||
};
|
||||
|
||||
const ring = AWARENESS_RANGE_RING_STYLE;
|
||||
const pulse = AWARENESS_RANGE_PULSE;
|
||||
const core = rgba(ring.color);
|
||||
const halo = rgba(ring.outlineColor);
|
||||
// While pulses run, the ring flashes as each one arrives and otherwise
|
||||
// dims to `restOpacity`; as they settle it returns to full and stays.
|
||||
const ringAlpha = (nowMs) => {
|
||||
const pulsed = Math.max(ring.restOpacity, awarenessRingFlash(nowMs));
|
||||
return 1 - levelAt(nowMs) * (1 - pulsed);
|
||||
};
|
||||
const center = { ...groundCenter };
|
||||
const next = {
|
||||
key,
|
||||
viewer,
|
||||
center,
|
||||
ringPositions: awarenessRangeRingPositions(
|
||||
groundCenter,
|
||||
AWARENESS_RADIUS_M,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
),
|
||||
reducedMotion,
|
||||
wake,
|
||||
stopPulses: null,
|
||||
removeMotionListener: null,
|
||||
step: () => {},
|
||||
/** When the pulses were last drawn as they were then. */
|
||||
lastStepMs: Number.NEGATIVE_INFINITY,
|
||||
};
|
||||
|
||||
/** The ring at `alpha` of its colours. */
|
||||
const ringItems = (alpha) => [
|
||||
haloedLine('ring', next.ringPositions, {
|
||||
core: faded(core, alpha),
|
||||
halo: faded(halo, alpha),
|
||||
widthPx: ring.width,
|
||||
haloPx: ring.outlineWidth,
|
||||
show: true,
|
||||
}),
|
||||
];
|
||||
|
||||
if (!animate) {
|
||||
lines.set(ringItems(1));
|
||||
next.step = () => lines.upsert(ringItems(1));
|
||||
} else {
|
||||
const count = pulse.count;
|
||||
// The band's ellipse is built around `bandCenter` and stands until
|
||||
// the subject has moved `gradientRebuildM` from it; meanwhile the
|
||||
// canvas draws the band about the subject, inside a margin as wide.
|
||||
const spanM = AWARENESS_RADIUS_M + pulse.gradientRebuildM;
|
||||
let bandCenter = null;
|
||||
let bandShown = null;
|
||||
// Two canvases in turn: a new key draws new content, and a renderer
|
||||
// that holds a canvas until its next frame never sees it rewritten.
|
||||
const doc = globalThis.document;
|
||||
const canvases = [0, 1].map(() => {
|
||||
const canvas = doc?.createElement?.('canvas');
|
||||
if (!canvas?.getContext) return null;
|
||||
canvas.width = canvas.height = AWARENESS_BAND_PIXELS;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) return null;
|
||||
return {
|
||||
canvas,
|
||||
context,
|
||||
image: context.createImageData(
|
||||
AWARENESS_BAND_PIXELS,
|
||||
AWARENESS_BAND_PIXELS,
|
||||
),
|
||||
};
|
||||
});
|
||||
const paints = canvases.every(Boolean);
|
||||
let painted = 0;
|
||||
let paintedMs = Number.NEGATIVE_INFINITY;
|
||||
// What each pixel reads, kept while the subject stays put.
|
||||
const bandMemo = {};
|
||||
|
||||
// The image last drawn: a resting band keeps it, hidden, so showing
|
||||
// it again changes it in place.
|
||||
let image = null;
|
||||
const bandItem = (show) => {
|
||||
const { lon, lat } = toLonLatH(bandCenter);
|
||||
return {
|
||||
id: 'band',
|
||||
geometry: {
|
||||
kind: 'ellipse',
|
||||
center: { lon, lat, height: CONTEXT_RIM_HEIGHT_M },
|
||||
semiMajor: spanM,
|
||||
semiMinor: spanM,
|
||||
},
|
||||
height: 'absolute',
|
||||
fill: { image },
|
||||
show,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Draw the pulses as they are at `nowMs`, and the ring where it now
|
||||
* is: the fronts, the band and the ring's flash.
|
||||
*/
|
||||
next.step = (nowMs) => {
|
||||
const level = levelAt(nowMs);
|
||||
const items = ringItems(ringAlpha(nowMs));
|
||||
const radii = [];
|
||||
const alphas = [];
|
||||
for (let index = 0; index < count; index++) {
|
||||
const state = awarenessPulseState(nowMs, index);
|
||||
radii.push(state.radiusM / AWARENESS_RADIUS_M);
|
||||
alphas.push(state.alpha * level);
|
||||
const front =
|
||||
level > 0
|
||||
? awarenessRangeRingPositions(
|
||||
center,
|
||||
state.radiusM,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
)
|
||||
: next.ringPositions;
|
||||
items.push(
|
||||
haloedLine(`pulse:${index}`, front, {
|
||||
core: faded(core, state.alpha * level),
|
||||
halo: faded(halo, state.alpha * level),
|
||||
widthPx: pulse.width,
|
||||
haloPx: pulse.outlineWidth,
|
||||
show: level > 0,
|
||||
}),
|
||||
);
|
||||
}
|
||||
lines.upsert(items);
|
||||
if (!paints) return;
|
||||
const show = level > 0;
|
||||
// A resting band stays where it was built, and catches up on wake.
|
||||
const rebuilt =
|
||||
show &&
|
||||
(!bandCenter ||
|
||||
distance(bandCenter, center) >= pulse.gradientRebuildM);
|
||||
if (rebuilt) bandCenter = { ...center };
|
||||
if (!bandCenter) return;
|
||||
if (!show) {
|
||||
if (bandShown) band.upsert([bandItem(false)]);
|
||||
bandShown = false;
|
||||
return;
|
||||
}
|
||||
// The soft band is painted at most once a Cyber sonar interval;
|
||||
// the fronts, crisp lines, move on every step.
|
||||
if (
|
||||
bandShown &&
|
||||
!rebuilt &&
|
||||
nowMs - paintedMs < CYBER_SONAR_RENDER_INTERVAL_MS
|
||||
)
|
||||
return;
|
||||
paintedMs = nowMs;
|
||||
const target = canvases[painted % 2];
|
||||
paintAwarenessBand(
|
||||
target.image,
|
||||
{
|
||||
radii,
|
||||
alphas,
|
||||
rgb: core,
|
||||
spanM,
|
||||
rangeM: AWARENESS_RADIUS_M,
|
||||
offset: eastNorth(bandCenter, center),
|
||||
},
|
||||
bandMemo,
|
||||
);
|
||||
target.context.putImageData(target.image, 0, 0);
|
||||
painted += 1;
|
||||
image = {
|
||||
canvas: target.canvas,
|
||||
key: `awareness-band:${instance}:${painted}`,
|
||||
};
|
||||
band.upsert([bandItem(true)]);
|
||||
bandShown = true;
|
||||
};
|
||||
|
||||
lines.set(ringItems(1));
|
||||
/** Draw the pulses at `nowMs` while they run or settle. */
|
||||
const stepRunning = (nowMs) => {
|
||||
if (levelAt(nowMs) > 0 || bandShown || ringAlpha(nowMs) < 1) {
|
||||
next.lastStepMs = nowMs;
|
||||
next.step(nowMs);
|
||||
}
|
||||
};
|
||||
next.lastStepMs = performance.now();
|
||||
next.step(next.lastStepMs);
|
||||
// Whether the camera was below the rim at the last step.
|
||||
let wasBelow = belowRim();
|
||||
// The fronts and band are fixed in the world: a camera move needs
|
||||
// nothing of them, so they step a Cyber sonar interval apart however
|
||||
// many frames are drawn, and look the same parked or moving. Each
|
||||
// frame checks only whether the camera crossed the rim height, which
|
||||
// shows or hides them at once. A step asks for the frame that draws
|
||||
// it, which is no reason to step again: a parked view draws one
|
||||
// frame each interval, as the timer below asks.
|
||||
const offPreRender = frame.on('preRender', () => {
|
||||
const nowMs = performance.now();
|
||||
const below = belowRim();
|
||||
if (
|
||||
below !== wasBelow ||
|
||||
nowMs - next.lastStepMs >= CYBER_SONAR_RENDER_INTERVAL_MS
|
||||
) {
|
||||
// A crossing at the instant of the last step must not reuse
|
||||
// that step's level.
|
||||
if (below !== wasBelow) levelMemo.nowMs = Number.NaN;
|
||||
wasBelow = below;
|
||||
stepRunning(nowMs);
|
||||
}
|
||||
});
|
||||
// Each drawn frame, whoever asked for it, arms one step a Cyber
|
||||
// sonar interval later, as the Cyber sonar scene does, whose changes
|
||||
// ask for the frame that draws them. Requests never land within
|
||||
// 80 ms of a frame, so they cannot beat the detection lane's 80 ms
|
||||
// gate, and they stop once the pulses rest.
|
||||
let timer = null;
|
||||
const offPostRender = frame.on('postRender', () => {
|
||||
globalThis.clearTimeout(timer);
|
||||
timer = null;
|
||||
const nowMs = performance.now();
|
||||
if ((nowMs < wake.untilMs || bandShown) && !belowRim())
|
||||
timer = globalThis.setTimeout(() => {
|
||||
timer = null;
|
||||
stepRunning(performance.now());
|
||||
governorRequestRender('awareness-pulse');
|
||||
}, CYBER_SONAR_RENDER_INTERVAL_MS);
|
||||
});
|
||||
next.stopPulses = () => {
|
||||
offPreRender();
|
||||
offPostRender();
|
||||
globalThis.clearTimeout(timer);
|
||||
timer = null;
|
||||
};
|
||||
// The detection overlay pulses the brackets of flights and vessels a
|
||||
// front crosses; it reads the centre in place, so it follows too.
|
||||
setAwarenessEchoField({
|
||||
center,
|
||||
radiusM: AWARENESS_RADIUS_M,
|
||||
pulse,
|
||||
echo: AWARENESS_RANGE_ECHO,
|
||||
level: levelAt,
|
||||
});
|
||||
}
|
||||
|
||||
// Turning reduced motion on or off mid-session rebuilds the visual.
|
||||
const motionQuery = globalThis.matchMedia?.(REDUCED_MOTION_QUERY);
|
||||
const onMotionChange = () => {
|
||||
if (layerState.subject) redraw(layerState.subject);
|
||||
};
|
||||
// Safari before 14 has only the older addListener / removeListener.
|
||||
if (motionQuery?.addEventListener)
|
||||
motionQuery.addEventListener('change', onMotionChange);
|
||||
else motionQuery?.addListener?.(onMotionChange);
|
||||
next.removeMotionListener = () => {
|
||||
if (motionQuery?.removeEventListener)
|
||||
motionQuery.removeEventListener('change', onMotionChange);
|
||||
else motionQuery?.removeListener?.(onMotionChange);
|
||||
};
|
||||
|
||||
layerState.visual = next;
|
||||
governorRequestRender('awareness-visual');
|
||||
}
|
||||
return { renderVisual, clearVisual, disposeVisual, wakePulses };
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import {
|
||||
CYBER_SONAR_RENDER_INTERVAL_MS,
|
||||
createCyberSonarSampler,
|
||||
isCyberContactSonarActive as isCyberSonarActive,
|
||||
} from '../../cyberSonar.js';
|
||||
@@ -11,339 +9,30 @@ import {
|
||||
AWARENESS_RADIUS_M,
|
||||
} from '../../data/militaryAwarenessEngine.js';
|
||||
import { bearingBetweenCoordinates } from '../../cockpitMath.js';
|
||||
import {
|
||||
AWARENESS_PAGE_SIZE,
|
||||
AWARENESS_RANGE_ECHO,
|
||||
AWARENESS_RANGE_PULSE,
|
||||
AWARENESS_RANGE_RING_STYLE,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
} from './policy.js';
|
||||
import { AWARENESS_PAGE_SIZE } from './policy.js';
|
||||
import { createRangeRing } from './rangeRing.js';
|
||||
import { formatAwarenessDirection } from './presentation.js';
|
||||
import { canvasOf, findCamera } from '../../render/rendererOf.js';
|
||||
import {
|
||||
awarenessEchoStrength,
|
||||
clearAwarenessEchoField,
|
||||
setAwarenessEchoField,
|
||||
} from '../../awarenessEcho.js';
|
||||
PI_OVER_TWO,
|
||||
dot,
|
||||
normalize,
|
||||
sub,
|
||||
toDegrees,
|
||||
toLonLatH,
|
||||
toRadians,
|
||||
} from '../../geo/index.js';
|
||||
|
||||
/**
|
||||
* A closed ring of positions `radiusM` along the surface from `groundCenter`,
|
||||
* raised to `heightM`. Each bearing steps over a sphere with the ellipsoid's
|
||||
* radius of curvature in that direction (Euler's formula), which keeps the
|
||||
* ring within ~50 m of the true geodesic radius at 250 km.
|
||||
* @param {Cesium.Cartesian3} groundCenter Ring centre on the ellipsoid.
|
||||
* @param {number} radiusM Surface radius in metres.
|
||||
* @param {number} heightM Height of the ring above the ellipsoid.
|
||||
* @param {number} [segments] Chords around the ring.
|
||||
* @returns {Cesium.Cartesian3[]} `segments + 1` positions; the last repeats the first.
|
||||
*/
|
||||
export function awarenessRangeRingPositions(
|
||||
groundCenter,
|
||||
radiusM,
|
||||
heightM,
|
||||
segments = AWARENESS_RANGE_RING_STYLE.segments,
|
||||
) {
|
||||
const { latitude, longitude } =
|
||||
Cesium.Cartographic.fromCartesian(groundCenter);
|
||||
const { x: a, z: b } = Cesium.Ellipsoid.WGS84.radii;
|
||||
const e2 = 1 - (b * b) / (a * a);
|
||||
const sinLat = Math.sin(latitude);
|
||||
const cosLat = Math.cos(latitude);
|
||||
const sinLon = Math.sin(longitude);
|
||||
const cosLon = Math.cos(longitude);
|
||||
const w = 1 - e2 * sinLat * sinLat;
|
||||
const meridional = (a * (1 - e2)) / (w * Math.sqrt(w));
|
||||
const primeVertical = a / Math.sqrt(w);
|
||||
// Step along the great circle in 3D from the centre's up, north and east
|
||||
// unit vectors. Unlike the latitude/longitude destination formula, this
|
||||
// stays well conditioned at and next to the poles.
|
||||
const up = [cosLat * cosLon, cosLat * sinLon, sinLat];
|
||||
const north = [-sinLat * cosLon, -sinLat * sinLon, cosLat];
|
||||
const east = [-sinLon, cosLon, 0];
|
||||
const positions = [];
|
||||
for (let i = 0; i <= segments; i++) {
|
||||
const bearing = ((i % segments) / segments) * Cesium.Math.TWO_PI;
|
||||
const cosB = Math.cos(bearing);
|
||||
const sinB = Math.sin(bearing);
|
||||
const angular =
|
||||
radiusM * ((cosB * cosB) / meridional + (sinB * sinB) / primeVertical);
|
||||
const cosA = Math.cos(angular);
|
||||
const sinA = Math.sin(angular);
|
||||
const [x, y, z] = up.map(
|
||||
(u, k) => u * cosA + (north[k] * cosB + east[k] * sinB) * sinA,
|
||||
);
|
||||
const lat = Math.atan2(z, Math.hypot(x, y));
|
||||
const lon = Math.atan2(y, x);
|
||||
positions.push(Cesium.Cartesian3.fromRadians(lon, lat, heightM));
|
||||
}
|
||||
return positions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where pulse `index` is at `nowMs`: its radius and opacity. Pulses travel at
|
||||
* constant speed from `startFraction` of the range to the full range, fade in
|
||||
* over `fadeInFraction` of the way, then fade as (1 - travel) to the
|
||||
* `fadeOutPower` down to `endOpacityFraction` of the peak, so each is dim
|
||||
* but still visible when it reaches the range ring. The opacity already
|
||||
* includes `peakOpacity`.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {number} index Pulse number, 0 to `count - 1`.
|
||||
* @param {number} [radiusM] Range the pulses grow to.
|
||||
* @param {object} [pulse] Timing and shape, see `AWARENESS_RANGE_PULSE`.
|
||||
* @returns {{radiusM: number, alpha: number}}
|
||||
*/
|
||||
export function awarenessPulseState(
|
||||
nowMs,
|
||||
index,
|
||||
radiusM = AWARENESS_RADIUS_M,
|
||||
pulse = AWARENESS_RANGE_PULSE,
|
||||
) {
|
||||
const cycle = nowMs / pulse.periodMs + index / pulse.count;
|
||||
const phase = cycle - Math.floor(cycle);
|
||||
return {
|
||||
radiusM:
|
||||
radiusM * (pulse.startFraction + (1 - pulse.startFraction) * phase),
|
||||
alpha:
|
||||
pulse.peakOpacity *
|
||||
Math.min(1, phase / pulse.fadeInFraction) *
|
||||
(pulse.endOpacityFraction +
|
||||
(1 - pulse.endOpacityFraction) * (1 - phase) ** pulse.fadeOutPower),
|
||||
};
|
||||
}
|
||||
|
||||
const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
|
||||
|
||||
/** Whether the viewer asked the system for less motion. */
|
||||
function prefersReducedMotion() {
|
||||
return globalThis.matchMedia?.(REDUCED_MOTION_QUERY)?.matches ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far the pulses are switched on at `nowMs`: 0 at rest, rising to 1 over
|
||||
* `settleMs` from `wake.startMs` and falling back to 0 over `settleMs` up to
|
||||
* `wake.untilMs`.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {{startMs: number, untilMs: number}} wake Window from `wakeAwarenessPulses`.
|
||||
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
|
||||
* @returns {number} 0 to 1.
|
||||
*/
|
||||
export function awarenessPulseLevel(
|
||||
nowMs,
|
||||
wake,
|
||||
pulse = AWARENESS_RANGE_PULSE,
|
||||
) {
|
||||
const level = Math.min(
|
||||
(nowMs - wake.startMs) / pulse.settleMs,
|
||||
(wake.untilMs - nowMs) / pulse.settleMs,
|
||||
);
|
||||
return Math.max(0, Math.min(1, level));
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the pulses for `activeMs` from `nowMs`. A wake while they already run
|
||||
* keeps their current level, so they never jump back to full mid-fade.
|
||||
* @param {{startMs: number, untilMs: number}} wake Updated in place.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
|
||||
* @returns {{startMs: number, untilMs: number}} `wake`.
|
||||
*/
|
||||
export function wakeAwarenessPulses(
|
||||
wake,
|
||||
nowMs,
|
||||
pulse = AWARENESS_RANGE_PULSE,
|
||||
) {
|
||||
wake.startMs =
|
||||
nowMs - awarenessPulseLevel(nowMs, wake, pulse) * pulse.settleMs;
|
||||
wake.untilMs = nowMs + pulse.activeMs;
|
||||
return wake;
|
||||
}
|
||||
|
||||
/**
|
||||
* How strongly the 250 km ring shows at `nowMs` while pulses run: 1 as a
|
||||
* pulse front reaches it, fading over `flashMs`, so the ring appears once
|
||||
* per arriving pulse instead of standing on screen.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @returns {number} 0 to 1.
|
||||
*/
|
||||
export function awarenessRingFlash(nowMs) {
|
||||
return awarenessEchoStrength(
|
||||
nowMs,
|
||||
AWARENESS_RADIUS_M,
|
||||
AWARENESS_RADIUS_M,
|
||||
AWARENESS_RANGE_PULSE,
|
||||
{ fadeMs: AWARENESS_RANGE_RING_STYLE.flashMs },
|
||||
);
|
||||
}
|
||||
|
||||
/** Most pulses the pulse shader draws; its uniforms are vec4s. */
|
||||
export const AWARENESS_PULSE_GRADIENT_MAX = 4;
|
||||
|
||||
/** The pulse disc's Cesium material type, one cached template per page. */
|
||||
const AWARENESS_PULSE_MATERIAL_TYPE = 'GevAwarenessPulseGradient';
|
||||
|
||||
// Ellipse texture coordinates put the centre at (0.5, 0.5) and the rim at
|
||||
// distance 0.5, so `r` is the fraction of the range. Each pulse is a line
|
||||
// `lineWidth` CSS pixels wide whose outer `haloWidth` is a dark halo, half
|
||||
// on each side, as Cesium's polyline outline material draws it, with a band
|
||||
// behind it that is strongest at the line and fades to nothing `depth`
|
||||
// inward. Widths come from the screen-space gradient of `r`, as Cesium's
|
||||
// contour material measures its lines; without derivatives the lines are
|
||||
// left out and only the band shows.
|
||||
const PULSE_GRADIENT_SOURCE = `
|
||||
uniform vec4 color;
|
||||
uniform vec4 lineColor;
|
||||
uniform vec4 haloColor;
|
||||
uniform vec4 radii;
|
||||
uniform vec4 alphas;
|
||||
uniform float depth;
|
||||
uniform float lineWidth;
|
||||
uniform float haloWidth;
|
||||
vec4 over(vec4 top, vec4 under) {
|
||||
float a = top.a + under.a * (1.0 - top.a);
|
||||
if (a <= 0.0) return vec4(0.0);
|
||||
return vec4((top.rgb * top.a + under.rgb * under.a * (1.0 - top.a)) / a, a);
|
||||
}
|
||||
czm_material czm_getMaterial(czm_materialInput materialInput) {
|
||||
czm_material material = czm_getDefaultMaterial(materialInput);
|
||||
float r = length(materialInput.st - vec2(0.5)) * 2.0;
|
||||
float band = 0.0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
float inside = radii[i] - r;
|
||||
if (inside >= 0.0 && inside <= depth) {
|
||||
float t = 1.0 - inside / depth;
|
||||
band += alphas[i] * t * t;
|
||||
}
|
||||
}
|
||||
vec4 result = vec4(color.rgb, clamp(band * color.a, 0.0, 1.0));
|
||||
#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))
|
||||
// Change in r per CSS pixel: the gradient's length per device pixel,
|
||||
// times the device pixels in one CSS pixel.
|
||||
float cssPx = max(length(vec2(dFdx(r), dFdy(r))), 1e-7) * czm_pixelRatio;
|
||||
float outerHalf = lineWidth * 0.5;
|
||||
float coreHalf = max(lineWidth - haloWidth, 0.0) * 0.5;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
float d = abs(radii[i] - r) / cssPx;
|
||||
float cover = clamp(outerHalf + 0.5 - d, 0.0, 1.0);
|
||||
if (cover <= 0.0) continue;
|
||||
float core = clamp(coreHalf + 0.5 - d, 0.0, 1.0);
|
||||
vec4 pulse = mix(haloColor, lineColor, core);
|
||||
result = over(vec4(pulse.rgb, pulse.a * cover * alphas[i]), result);
|
||||
}
|
||||
#endif
|
||||
material.diffuse = result.rgb;
|
||||
material.alpha = result.a;
|
||||
return material;
|
||||
}
|
||||
`;
|
||||
|
||||
/**
|
||||
* The pulses: one flat, translucent, unpickable disc the size of the range
|
||||
* ring whose shader draws each pulse line and the band behind it. Drawing
|
||||
* them here rather than as entities keeps them out of picking, so clicks and
|
||||
* taps near a pulse still reach the contact underneath. Moving pulses only
|
||||
* change its uniforms; the disc is rebuilt only when the subject moves.
|
||||
* @param {Cesium.Cartesian3} groundCenter Disc centre on the ellipsoid.
|
||||
* @param {Cesium.Material} material Shared pulse-gradient material.
|
||||
* @returns {Cesium.Primitive}
|
||||
*/
|
||||
function createPulseGradient(groundCenter, material) {
|
||||
return new Cesium.Primitive({
|
||||
geometryInstances: new Cesium.GeometryInstance({
|
||||
geometry: new Cesium.EllipseGeometry({
|
||||
center: groundCenter,
|
||||
semiMajorAxis: AWARENESS_RADIUS_M,
|
||||
semiMinorAxis: AWARENESS_RADIUS_M,
|
||||
height: CONTEXT_RIM_HEIGHT_M,
|
||||
granularity: Cesium.Math.toRadians(
|
||||
AWARENESS_RANGE_PULSE.gradientGranularityDeg,
|
||||
),
|
||||
vertexFormat:
|
||||
Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat,
|
||||
}),
|
||||
}),
|
||||
appearance: new Cesium.MaterialAppearance({
|
||||
material,
|
||||
flat: true,
|
||||
translucent: true,
|
||||
faceForward: true,
|
||||
}),
|
||||
asynchronous: false,
|
||||
allowPicking: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The ring's polyline geometry: `AWARENESS_RANGE_RING_STYLE.width` screen
|
||||
* pixels, straight chords between the given positions (they already follow
|
||||
* the surface), in the material appearance's vertex format.
|
||||
* @param {Cesium.Cartesian3[]} positions Ring positions.
|
||||
* @returns {object} PolylineGeometry options.
|
||||
*/
|
||||
export function awarenessRingGeometryOptions(positions) {
|
||||
return {
|
||||
positions,
|
||||
width: AWARENESS_RANGE_RING_STYLE.width,
|
||||
arcType: Cesium.ArcType.NONE,
|
||||
vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The 250 km ring as an unpickable polyline primitive in the ring's outline
|
||||
* material, so a click or tap on its edge reaches the contact underneath.
|
||||
* Its positions are geometry, so a moved subject rebuilds it; the material
|
||||
* is shared between builds so a flash keeps going.
|
||||
* @param {Cesium.Cartesian3[]} positions Ring positions.
|
||||
* @param {Cesium.Material} material Shared PolylineOutline material.
|
||||
* @returns {Cesium.Primitive}
|
||||
*/
|
||||
function createRingPrimitive(positions, material) {
|
||||
return new Cesium.Primitive({
|
||||
geometryInstances: new Cesium.GeometryInstance({
|
||||
geometry: new Cesium.PolylineGeometry(
|
||||
awarenessRingGeometryOptions(positions),
|
||||
),
|
||||
}),
|
||||
appearance: new Cesium.PolylineMaterialAppearance({
|
||||
material,
|
||||
translucent: true,
|
||||
}),
|
||||
asynchronous: false,
|
||||
allowPicking: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The rotation about the Earth's centre that carries `from` onto `to`, as a
|
||||
* model matrix, so a disc built around `from` sits around `to`.
|
||||
* @param {Cesium.Cartesian3} from Where the disc was built.
|
||||
* @param {Cesium.Cartesian3} to Where it should be.
|
||||
* @param {Cesium.Matrix4} [result]
|
||||
* @returns {Cesium.Matrix4}
|
||||
*/
|
||||
export function discFollowMatrix(from, to, result = new Cesium.Matrix4()) {
|
||||
const a = Cesium.Cartesian3.normalize(from, new Cesium.Cartesian3());
|
||||
const b = Cesium.Cartesian3.normalize(to, new Cesium.Cartesian3());
|
||||
const axis = Cesium.Cartesian3.cross(a, b, new Cesium.Cartesian3());
|
||||
const sin = Cesium.Cartesian3.magnitude(axis);
|
||||
if (sin < 1e-12) return Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY, result);
|
||||
const angle = Math.atan2(sin, Cesium.Cartesian3.dot(a, b));
|
||||
const rotation = Cesium.Matrix3.fromQuaternion(
|
||||
Cesium.Quaternion.fromAxisAngle(
|
||||
Cesium.Cartesian3.divideByScalar(axis, sin, axis),
|
||||
angle,
|
||||
),
|
||||
);
|
||||
return Cesium.Matrix4.fromRotationTranslation(
|
||||
rotation,
|
||||
Cesium.Cartesian3.ZERO,
|
||||
result,
|
||||
);
|
||||
}
|
||||
|
||||
/** Camera height above the ellipsoid, or NaN when the scene cannot say. */
|
||||
function cameraHeightM(scene) {
|
||||
return scene.camera?.positionCartographic?.height ?? Number.NaN;
|
||||
}
|
||||
// The ring's and the pulses' own arithmetic, for their tests.
|
||||
export {
|
||||
AWARENESS_BAND_PIXELS,
|
||||
awarenessPulseLevel,
|
||||
awarenessPulseState,
|
||||
awarenessRangeRingPositions,
|
||||
awarenessRingFlash,
|
||||
paintAwarenessBand,
|
||||
wakeAwarenessPulses,
|
||||
} from './rangeRing.js';
|
||||
|
||||
export function createRendering({
|
||||
state: layerState,
|
||||
@@ -353,6 +42,12 @@ export function createRendering({
|
||||
}) {
|
||||
const { getKeyholeGeometry, celestialScreenAngle } = services.geometry;
|
||||
const { governorRequestRender } = services.render;
|
||||
/** The range ring with its pulses (`rangeRing.js`). */
|
||||
const rangeRing = createRangeRing({
|
||||
state: layerState,
|
||||
governorRequestRender,
|
||||
redraw: (subject) => renderVisual(subject),
|
||||
});
|
||||
|
||||
const CARDINALS = [
|
||||
['N', 0],
|
||||
@@ -460,7 +155,7 @@ export function createRendering({
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = layerState.viewer.scene.canvas;
|
||||
const canvas = canvasOf(layerState.viewer);
|
||||
const width = canvas.clientWidth || canvas.width;
|
||||
const height = canvas.clientHeight || canvas.height;
|
||||
const sonar = isCyberSonarActive()
|
||||
@@ -478,9 +173,9 @@ export function createRendering({
|
||||
120,
|
||||
Math.min(geometry.radius - 48, geometry.radius * 0.66),
|
||||
);
|
||||
const cameraHeading = layerState.viewer.camera.heading || 0;
|
||||
const headingDeg =
|
||||
(Math.round(Cesium.Math.toDegrees(cameraHeading)) + 360) % 360;
|
||||
const pose = findCamera(layerState.viewer)?.pose();
|
||||
const cameraHeading = pose?.heading || 0;
|
||||
const headingDeg = (Math.round(toDegrees(cameraHeading)) + 360) % 360;
|
||||
const ring = {
|
||||
left: `${geometry.centerX - compassRadius}px`,
|
||||
top: `${geometry.centerY - compassRadius}px`,
|
||||
@@ -496,8 +191,8 @@ export function createRendering({
|
||||
top: `${geometry.centerY - compassRadius + 39}px`,
|
||||
};
|
||||
const labels = root.labels.map((label) => {
|
||||
const bearing = Cesium.Math.toRadians(label.bearing);
|
||||
const angle = bearing - cameraHeading - Cesium.Math.PI_OVER_TWO;
|
||||
const bearing = toRadians(label.bearing);
|
||||
const angle = bearing - cameraHeading - PI_OVER_TWO;
|
||||
const labelRadius = compassRadius - 17;
|
||||
return {
|
||||
...label,
|
||||
@@ -525,19 +220,15 @@ export function createRendering({
|
||||
marker.hidden = true;
|
||||
continue;
|
||||
}
|
||||
const direction = Cesium.Cartesian3.subtract(
|
||||
item.position,
|
||||
layerState.subject.position,
|
||||
layerState.DIRECTION_SCRATCH[index],
|
||||
);
|
||||
if (Cesium.Cartesian3.magnitudeSquared(direction) < 1) {
|
||||
const offset = sub(item.position, layerState.subject.position);
|
||||
if (dot(offset, offset) < 1 || !pose) {
|
||||
marker.hidden = true;
|
||||
continue;
|
||||
}
|
||||
Cesium.Cartesian3.normalize(direction, direction);
|
||||
const direction = normalize(offset);
|
||||
const projection = celestialScreenAngle(
|
||||
Cesium.Cartesian3.dot(direction, layerState.viewer.camera.rightWC),
|
||||
Cesium.Cartesian3.dot(direction, layerState.viewer.camera.upWC),
|
||||
dot(direction, pose.right),
|
||||
dot(direction, pose.up),
|
||||
layerState.directionAngles[index],
|
||||
);
|
||||
if (projection.stable)
|
||||
@@ -565,23 +256,15 @@ export function createRendering({
|
||||
transform: `translate(-50%, -50%) translate(${-Math.cos(projection.angle) * 56}px, ${-Math.sin(projection.angle) * 56}px)`,
|
||||
};
|
||||
const label = formatAwarenessLabel(item);
|
||||
const subjectCartographic = Cesium.Cartographic.fromCartesian(
|
||||
layerState.subject.position,
|
||||
undefined,
|
||||
layerState.SUBJECT_CARTOGRAPHIC_SCRATCH,
|
||||
);
|
||||
const targetCartographic = Cesium.Cartographic.fromCartesian(
|
||||
item.position,
|
||||
undefined,
|
||||
layerState.TARGET_CARTOGRAPHIC_SCRATCH[index],
|
||||
);
|
||||
const subjectLocation = toLonLatH(layerState.subject.position);
|
||||
const targetLocation = toLonLatH(item.position);
|
||||
const bearing =
|
||||
subjectCartographic && targetCartographic
|
||||
subjectLocation && targetLocation
|
||||
? bearingBetweenCoordinates(
|
||||
Cesium.Math.toDegrees(subjectCartographic.latitude),
|
||||
Cesium.Math.toDegrees(subjectCartographic.longitude),
|
||||
Cesium.Math.toDegrees(targetCartographic.latitude),
|
||||
Cesium.Math.toDegrees(targetCartographic.longitude),
|
||||
subjectLocation.lat,
|
||||
subjectLocation.lon,
|
||||
targetLocation.lat,
|
||||
targetLocation.lon,
|
||||
)
|
||||
: null;
|
||||
const bearingText = Number.isFinite(bearing)
|
||||
@@ -609,300 +292,20 @@ export function createRendering({
|
||||
* next request, so waking asks for no extra frame of its own.
|
||||
*/
|
||||
function wakePulses() {
|
||||
const wake = layerState.visual?.wake;
|
||||
if (!wake) return;
|
||||
wakeAwarenessPulses(wake, performance.now());
|
||||
followPulseDisc();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the pulse disc centred on the subject. Within `gradientRebuildM` of
|
||||
* where it was built, the disc is rotated about the Earth's centre onto
|
||||
* the subject by its model matrix, which keeps it concentric with the ring
|
||||
* at no build cost; the ellipsoid curves a little differently from that
|
||||
* sphere, a few tens of metres in height at 20 km. Further away it is
|
||||
* rebuilt, which costs a few milliseconds.
|
||||
*/
|
||||
function followPulseDisc() {
|
||||
const { gradient, gradientCenter, center } = layerState.visual;
|
||||
if (!gradient) return;
|
||||
if (
|
||||
Cesium.Cartesian3.distance(gradientCenter, center) <
|
||||
AWARENESS_RANGE_PULSE.gradientRebuildM
|
||||
) {
|
||||
gradient.modelMatrix = discFollowMatrix(
|
||||
gradientCenter,
|
||||
center,
|
||||
gradient.modelMatrix,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const primitives = layerState.viewer.scene.primitives;
|
||||
layerState.visual.gradient = primitives.add(
|
||||
createPulseGradient(center, gradient.appearance.material),
|
||||
);
|
||||
// Primitive.destroy leaves the material alone, so the new disc keeps
|
||||
// sharing it.
|
||||
primitives.remove(gradient);
|
||||
Cesium.Cartesian3.clone(center, gradientCenter);
|
||||
rangeRing.wakePulses();
|
||||
}
|
||||
|
||||
function clearVisual() {
|
||||
layerState.visual?.stopPulses?.();
|
||||
layerState.visual?.removeMotionListener?.();
|
||||
if (layerState.visual?.gradient && layerState.viewer)
|
||||
layerState.viewer.scene.primitives.remove(layerState.visual.gradient);
|
||||
if (layerState.visual?.ringPrimitive && layerState.viewer) {
|
||||
layerState.viewer.scene.primitives.remove?.(
|
||||
layerState.visual.ringPrimitive,
|
||||
);
|
||||
governorRequestRender('awareness-visual');
|
||||
}
|
||||
clearAwarenessEchoField();
|
||||
if (layerState.visual?.entities && layerState.viewer) {
|
||||
for (const entity of layerState.visual.entities)
|
||||
layerState.viewer.entities.remove(entity);
|
||||
// Idle mode renders only on request; a removed ring must not linger.
|
||||
governorRequestRender('awareness-visual');
|
||||
}
|
||||
layerState.visual = null;
|
||||
rangeRing.clearVisual();
|
||||
}
|
||||
|
||||
/** Let the ring's draw sets go, as the layer is destroyed. */
|
||||
function disposeVisual() {
|
||||
rangeRing.disposeVisual();
|
||||
}
|
||||
|
||||
function renderVisual(subject) {
|
||||
if (!layerState.viewer || !subject?.position) return;
|
||||
const cartographic = Cesium.Cartographic.fromCartesian(subject.position);
|
||||
if (!cartographic) return;
|
||||
const groundCenter = Cesium.Cartesian3.fromRadians(
|
||||
cartographic.longitude,
|
||||
cartographic.latitude,
|
||||
0,
|
||||
);
|
||||
const key = `${subject.layerId}:${subject.id}`;
|
||||
const reducedMotion = prefersReducedMotion();
|
||||
// A reduced-motion change rebuilds the visual, with or without pulses.
|
||||
if (
|
||||
layerState.visual?.key === key &&
|
||||
layerState.visual.reducedMotion === reducedMotion
|
||||
) {
|
||||
// Move the ring only after a meaningful displacement so live tracking
|
||||
// does not rebuild its geometry for sub-pixel motion every 750 ms.
|
||||
if (
|
||||
Cesium.Cartesian3.distance(layerState.visual.center, groundCenter) >=
|
||||
250
|
||||
) {
|
||||
const positions = awarenessRangeRingPositions(
|
||||
groundCenter,
|
||||
AWARENESS_RADIUS_M,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
);
|
||||
// The echo field reads `visual.center` in place and follows on its
|
||||
// own. The pulse disc follows by its model matrix and is rebuilt only
|
||||
// every `gradientRebuildM`: a build costs a few milliseconds.
|
||||
layerState.visual.ringPositions = positions;
|
||||
const { ringPrimitive } = layerState.visual;
|
||||
if (ringPrimitive) {
|
||||
const primitives = layerState.viewer.scene.primitives;
|
||||
layerState.visual.ringPrimitive = primitives.add(
|
||||
createRingPrimitive(positions, ringPrimitive.appearance.material),
|
||||
);
|
||||
primitives.remove(ringPrimitive);
|
||||
} else layerState.visual.ring.polyline.positions.setValue(positions);
|
||||
Cesium.Cartesian3.clone(groundCenter, layerState.visual.center);
|
||||
// A resting disc is hidden, so it catches up when the pulses wake.
|
||||
if (performance.now() < layerState.visual.wake?.untilMs)
|
||||
followPulseDisc();
|
||||
// Content actually changed — buy exactly one frame instead of holding.
|
||||
governorRequestRender('awareness-visual');
|
||||
}
|
||||
return;
|
||||
}
|
||||
clearVisual();
|
||||
|
||||
const entities = [];
|
||||
const scene = layerState.viewer.scene;
|
||||
// A viewer without a primitive collection or a preRender hook (headless
|
||||
// tools, partial stubs) gets the static ring only, as the Cyber sonar
|
||||
// scene does. So does a viewer who prefers reduced motion.
|
||||
const animate = Boolean(
|
||||
!reducedMotion &&
|
||||
scene?.primitives?.add &&
|
||||
scene?.preRender?.addEventListener &&
|
||||
scene?.postRender?.addEventListener,
|
||||
);
|
||||
// Pulses run from now until `wake.untilMs`, then rest.
|
||||
const wake = animate
|
||||
? wakeAwarenessPulses(
|
||||
{ startMs: -Infinity, untilMs: -Infinity },
|
||||
performance.now(),
|
||||
)
|
||||
: null;
|
||||
// From a camera below the rim height the disc would sweep across the sky,
|
||||
// so it is hidden there, and the pulses rest with it: no flash, no
|
||||
// echoes, no frames.
|
||||
const belowRim = () => cameraHeightM(scene) < CONTEXT_RIM_HEIGHT_M;
|
||||
const levelAt = (nowMs) =>
|
||||
wake && !belowRim() ? awarenessPulseLevel(nowMs, wake) : 0;
|
||||
|
||||
// A polyline, not an ellipse outline: WebGL draws ellipse outlines at
|
||||
// 1 px whatever `outlineWidth` says, and the ring needs a halo.
|
||||
const ring = AWARENESS_RANGE_RING_STYLE;
|
||||
const core = Cesium.Color.fromCssColorString(ring.color);
|
||||
const halo = Cesium.Color.fromCssColorString(ring.outlineColor);
|
||||
const ringPositions = awarenessRangeRingPositions(
|
||||
groundCenter,
|
||||
AWARENESS_RADIUS_M,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
);
|
||||
// While pulses run, the ring flashes as each one arrives and otherwise
|
||||
// dims to `restOpacity`; as they settle it returns to full and stays.
|
||||
const ringAlpha = (nowMs) => {
|
||||
const pulsed = Math.max(ring.restOpacity, awarenessRingFlash(nowMs));
|
||||
return 1 - levelAt(nowMs) * (1 - pulsed);
|
||||
};
|
||||
let ringEntity = null;
|
||||
let ringMaterial = null;
|
||||
let ringPrimitive = null;
|
||||
if (scene?.primitives?.add) {
|
||||
ringMaterial = Cesium.Material.fromType('PolylineOutline', {
|
||||
color: core.clone(),
|
||||
outlineColor: halo.clone(),
|
||||
outlineWidth: ring.outlineWidth,
|
||||
});
|
||||
ringPrimitive =
|
||||
scene.primitives.add(
|
||||
createRingPrimitive(ringPositions, ringMaterial),
|
||||
) ?? null;
|
||||
}
|
||||
if (!ringPrimitive) {
|
||||
// Headless tools and partial stubs have no primitive collection; they
|
||||
// get the static ring as an entity.
|
||||
ringEntity = layerState.viewer.entities.add({
|
||||
polyline: {
|
||||
positions: new Cesium.ConstantProperty(ringPositions),
|
||||
width: ring.width,
|
||||
arcType: Cesium.ArcType.NONE,
|
||||
material: new Cesium.PolylineOutlineMaterialProperty({
|
||||
color: core,
|
||||
outlineColor: halo,
|
||||
outlineWidth: ring.outlineWidth,
|
||||
}),
|
||||
},
|
||||
});
|
||||
entities.push(ringEntity);
|
||||
}
|
||||
|
||||
const center = Cesium.Cartesian3.clone(groundCenter);
|
||||
let gradient = null;
|
||||
let stopPulses = null;
|
||||
if (animate) {
|
||||
const pulse = AWARENESS_RANGE_PULSE;
|
||||
const count = Math.min(pulse.count, AWARENESS_PULSE_GRADIENT_MAX);
|
||||
const uniforms = {
|
||||
color: core.clone(),
|
||||
lineColor: core.clone(),
|
||||
haloColor: halo.clone(),
|
||||
radii: new Cesium.Cartesian4(),
|
||||
alphas: new Cesium.Cartesian4(),
|
||||
depth: pulse.gradientDepthFraction,
|
||||
lineWidth: pulse.width,
|
||||
haloWidth: pulse.outlineWidth,
|
||||
};
|
||||
uniforms.color.alpha = pulse.gradientOpacity;
|
||||
// A named type: Cesium caches every material type for the page's
|
||||
// lifetime, so an unnamed fabric (a fresh GUID each time) would leave
|
||||
// one entry per new visual. Built from the cached template, the
|
||||
// uniforms come back as plain copies; restore this visual's own.
|
||||
const material = new Cesium.Material({
|
||||
fabric: {
|
||||
type: AWARENESS_PULSE_MATERIAL_TYPE,
|
||||
uniforms,
|
||||
source: PULSE_GRADIENT_SOURCE,
|
||||
},
|
||||
translucent: true,
|
||||
});
|
||||
Object.assign(material.uniforms, uniforms);
|
||||
gradient = scene.primitives.add(
|
||||
createPulseGradient(groundCenter, material),
|
||||
);
|
||||
const radii = [0, 0, 0, 0];
|
||||
const alphas = [0, 0, 0, 0];
|
||||
const removePreRender = scene.preRender.addEventListener(() => {
|
||||
const nowMs = performance.now();
|
||||
const level = levelAt(nowMs);
|
||||
const alpha = ringAlpha(nowMs);
|
||||
ringMaterial.uniforms.color.alpha = core.alpha * alpha;
|
||||
ringMaterial.uniforms.outlineColor.alpha = halo.alpha * alpha;
|
||||
// The disc is looked up each frame: a subject move swaps it.
|
||||
const disc = layerState.visual?.gradient;
|
||||
if (disc) disc.show = level > 0;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const state = awarenessPulseState(nowMs, index);
|
||||
radii[index] = state.radiusM / AWARENESS_RADIUS_M;
|
||||
alphas[index] = state.alpha * level;
|
||||
}
|
||||
Cesium.Cartesian4.fromArray(radii, 0, material.uniforms.radii);
|
||||
Cesium.Cartesian4.fromArray(alphas, 0, material.uniforms.alphas);
|
||||
});
|
||||
// Each drawn frame, whoever asked for it, arms one request a Cyber
|
||||
// sonar interval later, as the Cyber sonar scene does. Requests never
|
||||
// land within 80 ms of a frame, so they cannot beat the detection
|
||||
// lane's 80 ms gate, and they stop once the pulses rest.
|
||||
let timer = null;
|
||||
const removePostRender = scene.postRender.addEventListener(() => {
|
||||
globalThis.clearTimeout(timer);
|
||||
timer = null;
|
||||
if (performance.now() < wake.untilMs && !belowRim())
|
||||
timer = globalThis.setTimeout(() => {
|
||||
timer = null;
|
||||
governorRequestRender('awareness-pulse');
|
||||
}, CYBER_SONAR_RENDER_INTERVAL_MS);
|
||||
});
|
||||
stopPulses = () => {
|
||||
removePreRender();
|
||||
removePostRender();
|
||||
globalThis.clearTimeout(timer);
|
||||
timer = null;
|
||||
};
|
||||
// The detection overlay pulses the brackets of flights and vessels a
|
||||
// front crosses; it reads the centre in place, so it follows too.
|
||||
setAwarenessEchoField({
|
||||
center,
|
||||
radiusM: AWARENESS_RADIUS_M,
|
||||
pulse,
|
||||
echo: AWARENESS_RANGE_ECHO,
|
||||
level: levelAt,
|
||||
});
|
||||
}
|
||||
|
||||
// Turning reduced motion on or off mid-session rebuilds the visual.
|
||||
const motionQuery = globalThis.matchMedia?.(REDUCED_MOTION_QUERY);
|
||||
const onMotionChange = () => {
|
||||
if (layerState.subject) renderVisual(layerState.subject);
|
||||
};
|
||||
// Safari before 14 has only the older addListener / removeListener.
|
||||
if (motionQuery?.addEventListener)
|
||||
motionQuery.addEventListener('change', onMotionChange);
|
||||
else motionQuery?.addListener?.(onMotionChange);
|
||||
|
||||
layerState.visual = {
|
||||
key,
|
||||
entities,
|
||||
ring: ringEntity,
|
||||
ringPrimitive,
|
||||
ringPositions,
|
||||
center,
|
||||
gradient,
|
||||
gradientCenter: Cesium.Cartesian3.clone(groundCenter),
|
||||
reducedMotion,
|
||||
wake,
|
||||
stopPulses,
|
||||
removeMotionListener: () => {
|
||||
if (motionQuery?.removeEventListener)
|
||||
motionQuery.removeEventListener('change', onMotionChange);
|
||||
else motionQuery?.removeListener?.(onMotionChange);
|
||||
},
|
||||
};
|
||||
governorRequestRender('awareness-visual');
|
||||
rangeRing.renderVisual(subject);
|
||||
}
|
||||
return {
|
||||
ensureDirectionOverlay,
|
||||
@@ -913,6 +316,7 @@ export function createRendering({
|
||||
cancelDirectionOverlayUpdate,
|
||||
updateDirectionOverlay,
|
||||
clearVisual,
|
||||
disposeVisual,
|
||||
renderVisual,
|
||||
wakePulses,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// src/layers/awareness/selectedVessel.test.mjs — Contacts turned on while an
|
||||
// AIS vessel is selected takes that vessel as its subject.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { summarizeAwarenessCohort } from '../../data/militaryAwarenessEngine.js';
|
||||
import { createState } from './state.js';
|
||||
import { createModel } from './model.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createSubject } from './subject.js';
|
||||
import { createHistory } from './history.js';
|
||||
import { createDependencies } from './dependencies.js';
|
||||
|
||||
const VESSEL_ID = '367000001';
|
||||
|
||||
/** Contacts parts over fake sources; focus records each nearest-flight pick. */
|
||||
function contacts(selection) {
|
||||
globalThis.document ??= { body: null };
|
||||
const noAircraft = {
|
||||
getAllPositions: () => [],
|
||||
getNearby: () => [],
|
||||
getTrackedSubject: () => null,
|
||||
};
|
||||
const services = {
|
||||
flights: noAircraft,
|
||||
military: noAircraft,
|
||||
vessels: {
|
||||
getNearby: () => [],
|
||||
getAllPositions: () => [],
|
||||
getSelectedInfo: () => selection.vessel,
|
||||
},
|
||||
installations: {
|
||||
getNearby: () => [],
|
||||
getStats: () => ({}),
|
||||
setContextAnchor() {},
|
||||
},
|
||||
};
|
||||
const state = createState({ services });
|
||||
state.enabled = true;
|
||||
state.passive = false;
|
||||
state.dataManager = {
|
||||
isEnabled: () => true,
|
||||
isEffectivelyEnabled: () => true,
|
||||
setEnabled: async () => true,
|
||||
getLayerLifecycleState: () => ({
|
||||
enabled: true,
|
||||
lifecycleState: 'enabled',
|
||||
}),
|
||||
layers: new Map(),
|
||||
};
|
||||
const focused = [];
|
||||
const parts = {
|
||||
navigation: {
|
||||
summarizeAwarenessCohortForNavigation: (items, source) =>
|
||||
summarizeAwarenessCohort(items, source),
|
||||
isFlightLayer: (id) => id === 'flights' || id === 'military',
|
||||
},
|
||||
rendering: { renderVisual() {}, scheduleDirectionOverlayUpdate() {} },
|
||||
panel: { renderResults() {}, startAwarenessPageRotation() {} },
|
||||
focus: {
|
||||
focusAttentionTarget() {
|
||||
focused.push('nearest');
|
||||
return true;
|
||||
},
|
||||
},
|
||||
};
|
||||
const context = { state, services, parts };
|
||||
parts.model = createModel(context);
|
||||
parts.queries = createQueries(context);
|
||||
parts.subject = createSubject(context);
|
||||
parts.history = createHistory(context);
|
||||
parts.dependencies = createDependencies(context);
|
||||
return { state, parts, focused };
|
||||
}
|
||||
|
||||
/** The vessel layer's answer for a selected Royal Prince. */
|
||||
const ROYAL_PRINCE = Object.freeze({
|
||||
id: VESSEL_ID,
|
||||
mmsi: VESSEL_ID,
|
||||
name: 'ROYAL PRINCE',
|
||||
latitude: 37.8,
|
||||
longitude: -122.4,
|
||||
});
|
||||
|
||||
test('Contacts turned on with a vessel selected takes it as the subject', async () => {
|
||||
const { state, parts, focused } = contacts({ vessel: ROYAL_PRINCE });
|
||||
await parts.dependencies.activateOperationalContext();
|
||||
assert.deepEqual(focused, [], 'no nearest flight is picked or followed');
|
||||
assert.equal(state.subject?.layerId, 'ais-live-vessels');
|
||||
assert.equal(state.subject?.id, VESSEL_ID);
|
||||
assert.match(state.subject.label, /ROYAL PRINCE/);
|
||||
});
|
||||
|
||||
test('a late source settling keeps the selected vessel, not a nearest flight', () => {
|
||||
const selection = { vessel: null };
|
||||
const { state, parts, focused } = contacts(selection);
|
||||
state.autoFocusRetryPending = true;
|
||||
selection.vessel = ROYAL_PRINCE;
|
||||
parts.dependencies.refreshAfterDeferredDependency(state.activationId);
|
||||
assert.deepEqual(focused, []);
|
||||
assert.equal(state.subject?.id, VESSEL_ID);
|
||||
});
|
||||
|
||||
test('with no vessel selected, Contacts still picks the nearest flight', async () => {
|
||||
const { state, parts, focused } = contacts({ vessel: null });
|
||||
await parts.dependencies.activateOperationalContext();
|
||||
assert.deepEqual(focused, ['nearest']);
|
||||
assert.equal(state.subject, null);
|
||||
});
|
||||
@@ -1,20 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
export function createState({ services }) {
|
||||
const state = {};
|
||||
|
||||
state.DIRECTION_SCRATCH = Array.from(
|
||||
{ length: 3 },
|
||||
() => new Cesium.Cartesian3(),
|
||||
);
|
||||
|
||||
state.SUBJECT_CARTOGRAPHIC_SCRATCH = new Cesium.Cartographic();
|
||||
|
||||
state.TARGET_CARTOGRAPHIC_SCRATCH = Array.from(
|
||||
{ length: 3 },
|
||||
() => new Cesium.Cartographic(),
|
||||
);
|
||||
|
||||
Object.assign(state, {
|
||||
viewer: null,
|
||||
dataManager: null,
|
||||
@@ -29,6 +15,8 @@ export function createState({ services }) {
|
||||
/** Stops following the manager's adoptions (see watchAdoptions). */
|
||||
unwatchAdoptions: null,
|
||||
subject: null,
|
||||
/** The tracked flight's photo with the subject it belongs to, or null. */
|
||||
subjectPhoto: null,
|
||||
results: null,
|
||||
visual: null,
|
||||
/** Whether layer views replace the panel's initial markup yet. */
|
||||
|
||||
+109
-39
@@ -1,10 +1,11 @@
|
||||
import { followedOf } from '../../data/followed.js';
|
||||
import {
|
||||
AWARENESS_RADIUS_M,
|
||||
AWARENESS_RELATIONSHIP,
|
||||
} from '../../data/militaryAwarenessEngine.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { layerFeedState } from '../../data/feedState.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { clone, distance, fromDegrees } from '../../geo/index.js';
|
||||
import {
|
||||
AWARENESS_QUERY_LIMIT,
|
||||
SOURCE_LABEL,
|
||||
@@ -25,6 +26,8 @@ function localizeCoverageLabel(label) {
|
||||
return label;
|
||||
}
|
||||
|
||||
/** @typedef {import('../../render/contract/common').Ecef} Ecef */
|
||||
|
||||
export function createSubject({ state: layerState, services, parts, source }) {
|
||||
const aisLiveVesselsLayer = services.vessels;
|
||||
const militaryInstallationsLayer = services.installations;
|
||||
@@ -85,7 +88,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
.getNearby(position, AWARENESS_RADIUS_M, AWARENESS_QUERY_LIMIT)
|
||||
.filter(
|
||||
(item) =>
|
||||
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'mmsi'),
|
||||
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'id'),
|
||||
);
|
||||
const coverage = installationsState.stats?.coverage;
|
||||
const installationRadius =
|
||||
@@ -200,17 +203,15 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the source-owned aircraft that currently owns Cesium tracking.
|
||||
* Resolve the source-owned aircraft that currently owns the follow camera.
|
||||
* Both flight layers may briefly retain local state during a cross-layer
|
||||
* handoff, so the viewer's normalized tracked identity is the tie-breaker.
|
||||
* @returns {{layerId: string, id: string, label: string, position: Cesium.Cartesian3}|null}
|
||||
* @returns {{layerId: string, id: string, label: string, position: Ecef}|null}
|
||||
* Detached awareness subject, or null when no flight owns the follow camera.
|
||||
*/
|
||||
|
||||
function currentTrackedFlightSubject() {
|
||||
const trackedKey = normalizeContextId(
|
||||
layerState.viewer?.trackedEntity?.gevTrackedId,
|
||||
);
|
||||
const trackedKey = normalizeContextId(followedOf(layerState.viewer)?.key);
|
||||
if (!trackedKey) return null;
|
||||
const subjects = [
|
||||
flightsLayer.getTrackedSubject?.(),
|
||||
@@ -250,7 +251,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
subject,
|
||||
parts.history.historySourceItem(subject),
|
||||
),
|
||||
position: Cesium.Cartesian3.clone(subject.position),
|
||||
position: clone(subject.position),
|
||||
});
|
||||
layerState.navigationIndex = layerState.navigationHistory.length - 1;
|
||||
}
|
||||
@@ -265,10 +266,10 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
* Resolve the currently displayed position for a selected live subject. Flight
|
||||
* tracking owns the motion callback, so awareness consumes its cached display
|
||||
* position instead of creating a second tracker or extrapolation path.
|
||||
* @param {{layerId: string, id: string, position: Cesium.Cartesian3}} subject Current subject.
|
||||
* @param {{layerId: string, id: string, position: Ecef}} subject Current subject.
|
||||
* @param {object} [options] Position materialization controls.
|
||||
* @param {boolean} [options.allowCollectionMaterialization=true] Whether a layer-wide fallback may run.
|
||||
* @returns {Cesium.Cartesian3|null} A cloned live position when one is available.
|
||||
* @returns {Ecef|null} A cloned live position when one is available.
|
||||
*/
|
||||
|
||||
function resolveSubjectPosition(
|
||||
@@ -277,16 +278,15 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
) {
|
||||
if (!subject?.position) return null;
|
||||
if (subject.layerId === 'flights' || subject.layerId === 'military') {
|
||||
const trackedPosition =
|
||||
layerState.viewer?.trackedEntity?.gevDisplayPosition?.();
|
||||
const followed = followedOf(layerState.viewer);
|
||||
const trackedPosition = followed?.displayPosition?.();
|
||||
if (trackedPosition) {
|
||||
return {
|
||||
position: Cesium.Cartesian3.clone(trackedPosition),
|
||||
position: clone(trackedPosition),
|
||||
// Only the follow camera's own contact proves presence this way; a
|
||||
// different tracked entity says nothing about this subject.
|
||||
presence:
|
||||
String(layerState.viewer?.trackedEntity?.gevTrackedId || '') ===
|
||||
subjectKey(subject)
|
||||
String(followed?.key || '') === subjectKey(subject)
|
||||
? SUBJECT_PRESENCE.LIVE
|
||||
: SUBJECT_PRESENCE.UNCHECKED,
|
||||
};
|
||||
@@ -296,7 +296,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
// awareness position instead of allocating/scanning up to 1,000 contacts.
|
||||
if (!allowCollectionMaterialization) {
|
||||
return {
|
||||
position: Cesium.Cartesian3.clone(subject.position),
|
||||
position: clone(subject.position),
|
||||
presence: SUBJECT_PRESENCE.UNCHECKED,
|
||||
};
|
||||
}
|
||||
@@ -311,7 +311,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
if (subject.layerId === 'ais-live-vessels') {
|
||||
if (!allowCollectionMaterialization) {
|
||||
return {
|
||||
position: Cesium.Cartesian3.clone(subject.position),
|
||||
position: clone(subject.position),
|
||||
presence: SUBJECT_PRESENCE.UNCHECKED,
|
||||
};
|
||||
}
|
||||
@@ -324,7 +324,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
// Mapped installations come from static geometry, not a live feed: there is
|
||||
// nothing to be culled from.
|
||||
return {
|
||||
position: Cesium.Cartesian3.clone(subject.position),
|
||||
position: clone(subject.position),
|
||||
presence: SUBJECT_PRESENCE.LIVE,
|
||||
};
|
||||
}
|
||||
@@ -338,10 +338,10 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
* ~11k contacts against a 1,000-row cap, so "not in the rows" is not "gone".
|
||||
* The rows are only consulted for a fresher position — a contact past the cap
|
||||
* keeps its last known position while still reading as present.
|
||||
* @param {{id: string, position: Cesium.Cartesian3}} subject Current subject.
|
||||
* @param {Array<{id: string, position: Cesium.Cartesian3}>} rows Live collection rows.
|
||||
* @param {{id: string, position: Ecef}} subject Current subject.
|
||||
* @param {Array<{id: string, position: Ecef}>} rows Live collection rows.
|
||||
* @param {{hasContact?: function}} layer The owning source layer.
|
||||
* @returns {{position: Cesium.Cartesian3, presence: string}} Position plus presence verdict.
|
||||
* @returns {{position: Ecef, presence: string}} Position plus presence verdict.
|
||||
*/
|
||||
|
||||
function collectionSubjectPosition(subject, rows, layer) {
|
||||
@@ -359,8 +359,8 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
: SUBJECT_PRESENCE.UNCHECKED;
|
||||
return {
|
||||
position: current?.position
|
||||
? Cesium.Cartesian3.clone(current.position)
|
||||
: Cesium.Cartesian3.clone(subject.position),
|
||||
? clone(current.position)
|
||||
: clone(subject.position),
|
||||
presence,
|
||||
};
|
||||
}
|
||||
@@ -378,19 +378,51 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
*
|
||||
* Identity (`subject.id`) is NEVER re-derived — only the rendered string.
|
||||
* @param {{layerId: string, id: string, label: string}} subject Current subject.
|
||||
* @param {?object} [tracked] The subject's tracked descriptor, when the
|
||||
* caller already has it (see trackedSubjectOf).
|
||||
* @returns {string} The current label, or the cached one when the owning layer
|
||||
* has no tracked subject (e.g. a cross-layer handoff is in flight).
|
||||
*/
|
||||
|
||||
function resolveSubjectLabel(subject) {
|
||||
if (!parts.navigation.isFlightLayer(subject?.layerId))
|
||||
return subject?.label;
|
||||
function resolveSubjectLabel(subject, tracked = trackedSubjectOf(subject)) {
|
||||
return tracked?.label || subject?.label;
|
||||
}
|
||||
|
||||
/**
|
||||
* The owning flight layer's tracked-subject descriptor when it describes
|
||||
* this subject, else null. Built once per refresh and shared by the label
|
||||
* and the photo.
|
||||
* @param {{layerId: string, id: string}|null} subject Current subject.
|
||||
* @returns {?{id: string, label: string, photo?: ?object}}
|
||||
*/
|
||||
function trackedSubjectOf(subject) {
|
||||
if (!parts.navigation.isFlightLayer(subject?.layerId)) return null;
|
||||
const layer =
|
||||
subject.layerId === 'flights' ? flightsLayer : militaryFlightsLayer;
|
||||
const tracked = layer.getTrackedSubject?.();
|
||||
if (tracked?.label && String(tracked.id) === String(subject.id))
|
||||
return tracked.label;
|
||||
return subject.label;
|
||||
return tracked && String(tracked.id) === String(subject.id)
|
||||
? tracked
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The subject's photo, for the Contacts panel: the tracked airliner's
|
||||
* Planespotters photo, or the selected vessel's Open Vessel Photos photo.
|
||||
*
|
||||
* The flights layer looks photos up only for the plane it tracks, the
|
||||
* vessel layer only for the vessel selected; an installation, a military
|
||||
* aircraft or an untracked flight has none.
|
||||
* @param {{layerId: string, id: string}|null} subject Current subject.
|
||||
* @param {?object} [tracked] The subject's tracked descriptor, when the
|
||||
* caller already has it.
|
||||
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string, licence?: string}}
|
||||
*/
|
||||
function resolveSubjectPhoto(subject, tracked = trackedSubjectOf(subject)) {
|
||||
if (subject?.layerId === 'ais-live-vessels')
|
||||
return aisLiveVesselsLayer.getVesselPhoto?.(subject.id) ?? null;
|
||||
return subject?.layerId === 'flights' && tracked?.photo
|
||||
? tracked.photo
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Refresh proximity counts/distances against the subject's current live position. */
|
||||
@@ -417,11 +449,24 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
if (presence === SUBJECT_PRESENCE.LIVE) layerState.subjectMissing = false;
|
||||
else if (presence === SUBJECT_PRESENCE.MISSING)
|
||||
layerState.subjectMissing = true;
|
||||
const nextLabel = resolveSubjectLabel(layerState.subject);
|
||||
const tracked = trackedSubjectOf(layerState.subject);
|
||||
const nextLabel = resolveSubjectLabel(layerState.subject, tracked);
|
||||
const labelChanged = nextLabel !== layerState.subject.label;
|
||||
// The panel reads the photo from here, with the subject it belongs to.
|
||||
const photo = resolveSubjectPhoto(layerState.subject, tracked);
|
||||
layerState.subjectPhoto = photo
|
||||
? {
|
||||
layerId: layerState.subject.layerId,
|
||||
id: layerState.subject.id,
|
||||
photo,
|
||||
}
|
||||
: null;
|
||||
// A photo arriving after selection is render-worthy on its own, as a label.
|
||||
const photoChanged =
|
||||
(photo?.src ?? null) !== (layerState.panelView?.photo?.src ?? null);
|
||||
layerState.subject = { ...layerState.subject, position, label: nextLabel };
|
||||
const movementM = layerState.lastEvaluatedPosition
|
||||
? Cesium.Cartesian3.distance(layerState.lastEvaluatedPosition, position)
|
||||
? distance(layerState.lastEvaluatedPosition, position)
|
||||
: Infinity;
|
||||
if (
|
||||
!parts.model.awarenessRefreshRequired({
|
||||
@@ -439,16 +484,13 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
// kept the ICAO hex until unrelated movement, a source-revision bump, or
|
||||
// page rotation happened to repaint it. Gated on an ACTUAL change so the
|
||||
// common no-op refresh (every 750 ms) still costs no repaint.
|
||||
if (labelChanged) parts.panel.renderResults();
|
||||
if (labelChanged || photoChanged) parts.panel.renderResults();
|
||||
parts.rendering.scheduleDirectionOverlayUpdate(force);
|
||||
return;
|
||||
}
|
||||
layerState.results = evaluateSubject(layerState.subject, sources);
|
||||
layerState.sourceRevision = nextSourceRevision;
|
||||
layerState.lastEvaluatedPosition = Cesium.Cartesian3.clone(
|
||||
position,
|
||||
layerState.lastEvaluatedPosition,
|
||||
);
|
||||
layerState.lastEvaluatedPosition = clone(position);
|
||||
for (const cohort of layerState.results.cohorts) {
|
||||
const maxPage = Math.max(
|
||||
0,
|
||||
@@ -475,15 +517,40 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
const latitude = Number(record.latitude);
|
||||
const longitude = Number(record.longitude);
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
||||
// A vessel reads as its name and MMSI; a vessel named by its MMSI alone
|
||||
// already carries it.
|
||||
const label = String(record.label || record.id);
|
||||
const mmsi = String(record.properties?.mmsi || '');
|
||||
return {
|
||||
layerId: record.layerId,
|
||||
id: record.properties?.mmsi || record.id,
|
||||
label: record.label || record.id,
|
||||
id: record.properties?.vesselId || record.id,
|
||||
// i18n-ignore: MMSI is a radio identity code, as on the vessel card
|
||||
label: mmsi && !label.includes(mmsi) ? `${label} · MMSI ${mmsi}` : label,
|
||||
memberNames: record.properties?.memberNames || [],
|
||||
position: Cesium.Cartesian3.fromDegrees(longitude, latitude, 0),
|
||||
position: fromDegrees(longitude, latitude, 0),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The AIS vessel the user has selected, as a subject. Contacts turned on
|
||||
* after the selection never heard its `gev:entity-selected`, so activation
|
||||
* asks the vessel layer and shapes its answer as that event's record.
|
||||
* @returns {object|null} Detached subject, or null when no vessel is selected.
|
||||
*/
|
||||
|
||||
function currentSelectedVesselSubject() {
|
||||
const info = aisLiveVesselsLayer.getSelectedInfo?.();
|
||||
if (!info?.id) return null;
|
||||
return subjectFromContext({
|
||||
layerId: 'ais-live-vessels',
|
||||
id: info.id,
|
||||
label: info.name || info.mmsi || info.id,
|
||||
latitude: info.latitude,
|
||||
longitude: info.longitude,
|
||||
properties: { vesselId: info.id, mmsi: info.mmsi },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that the current subject left its feed on its own.
|
||||
*
|
||||
@@ -502,6 +569,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
militaryInstallationsLayer.setContextAnchor?.(null);
|
||||
layerState.autoFocusRetryPending = false;
|
||||
layerState.subject = null;
|
||||
layerState.subjectPhoto = null;
|
||||
layerState.subjectMissing = false;
|
||||
layerState.results = null;
|
||||
layerState.navigationHistory = [];
|
||||
@@ -528,8 +596,10 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
resolveSubjectPosition,
|
||||
collectionSubjectPosition,
|
||||
resolveSubjectLabel,
|
||||
resolveSubjectPhoto,
|
||||
refreshSelectedSubject,
|
||||
subjectFromContext,
|
||||
currentSelectedVesselSubject,
|
||||
markSubjectEvicted,
|
||||
clearAwarenessSubject,
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user