mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 09:12:18 +00:00
Merge main into german/i18n-plurals-context
The catalogs conflicted only on neighbouring lines: no key changed on both sides, so they are merged key by key in main's order. Main removed the rail timeline, the other user of plain "Latest", so that entry is pruned and the News test no longer checks the timeline's wording.
This commit is contained in:
commit
49409ba8f1
1502 files changed
+180715
-47887
No files matched your search
@@ -25,7 +25,9 @@ const items = computed(() =>
|
||||
id: panel.id,
|
||||
icon: item?.icon ?? PANEL_RAIL_FALLBACK_ICON,
|
||||
// Static markup is translated at boot, so a host's title already is.
|
||||
label: item ? t(item.label) : panel.title,
|
||||
label: item
|
||||
? t(item.label, item.context && { context: item.context })
|
||||
: panel.title,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
+61
-29
@@ -1,3 +1,5 @@
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { readEntityRecord } from '../data/entityRecords.js';
|
||||
import { nextTick } from 'vue';
|
||||
import { resolveImageryHost } from '../layers/weather/imageryHost.js';
|
||||
import { ShellFacade } from './shellFacade.js';
|
||||
@@ -34,7 +36,10 @@ import {
|
||||
setCyberSonarControls,
|
||||
} from './cyberSonarControls.js';
|
||||
|
||||
import * as Cesium from 'cesium';
|
||||
import { toDegrees, toRadians } from '../geo/index.js';
|
||||
// A viewer with no renderer bound gets its ports (camera, effects, globe)
|
||||
// once its owner has loaded the package's `./render/cesium/unbound` export.
|
||||
import { cameraOf, canvasOf, findCamera } from '../render/rendererOf.js';
|
||||
|
||||
import { aircraftTrackingTarget } from '../cockpitTracking.js';
|
||||
|
||||
@@ -59,12 +64,14 @@ import { applicationPinia, createUiRuntime } from './vueRuntime.js';
|
||||
import { useContextStore } from './stores/context.js';
|
||||
import { useMissionReplayStore } from './stores/missionReplay.js';
|
||||
import { useCelestialRingStore } from './stores/celestialRing.js';
|
||||
import { icrfToFixedAxes } from '../sky/icrf.js';
|
||||
import { useWorldOverlayActionsStore } from './stores/worldOverlayActions.js';
|
||||
import { useAwarenessDirectionStore } from './stores/awarenessDirection.js';
|
||||
import { useHudStore } from './stores/hud.js';
|
||||
import { useDisplayStore } from './stores/display.js';
|
||||
import { useLocaleStore } from './stores/locale.js';
|
||||
import { useLocationStore } from './stores/location.js';
|
||||
import { installRailEdgeScroll } from './railEdgeScroll.js';
|
||||
import { useCockpitStore } from './stores/cockpit.js';
|
||||
import { useGlobeActionsStore } from './stores/globeActions.js';
|
||||
import { useRecordingStore } from './stores/recording.js';
|
||||
@@ -93,7 +100,7 @@ import { preloadOwnerFlags } from './ownerFlag.js';
|
||||
|
||||
export class StyleManager extends ShellFacade {
|
||||
/**
|
||||
* @param {Cesium.Viewer} viewer - The CesiumJS viewer instance.
|
||||
* @param {object} viewer - The scene object the renderer draws.
|
||||
* @param {object} [options]
|
||||
* @param {boolean} [options.localePicker=true] - false removes the language
|
||||
* picker, for a host that offers its own language choice.
|
||||
@@ -164,6 +171,8 @@ export class StyleManager extends ShellFacade {
|
||||
});
|
||||
// Vue views share this runtime and its stores; dispose unmounts them.
|
||||
this._ui = createUiRuntime({ pinia: applicationPinia() });
|
||||
// Scrolling at a screen edge steps through that side's rail panels.
|
||||
this._removeRailEdgeScroll = installRailEdgeScroll();
|
||||
this._feedback = new ShellFeedback({
|
||||
readLayers: () => withPlacePacks(this._dataManager?.getAll?.() || []),
|
||||
});
|
||||
@@ -209,8 +218,8 @@ export class StyleManager extends ShellFacade {
|
||||
this._showGlobalStatusNotice(message, options),
|
||||
feedback: this._feedback,
|
||||
updateFeedback: () => this._updateGlobalLoadingFeedback(),
|
||||
applyFollowOffset: (entity, offset) =>
|
||||
applyShareFollowOffset(viewer, entity, offset),
|
||||
applyFollowOffset: (followed, offset) =>
|
||||
applyShareFollowOffset(viewer, followed, offset),
|
||||
});
|
||||
|
||||
this._visualSettings = new VisualSettings({
|
||||
@@ -223,6 +232,7 @@ export class StyleManager extends ShellFacade {
|
||||
getDetectionTuning: services.getDetectionTuning,
|
||||
getKeyholeFadeTuning: services.getKeyholeFadeTuning,
|
||||
getScopeMaskFeather: services.getScopeMaskFeather,
|
||||
getScopeMaskOpacity: services.getScopeMaskOpacity,
|
||||
getScopeTerminusOverride: services.getScopeTerminusOverride,
|
||||
governorRequestRender: services.governorRequestRender,
|
||||
holdContinuousRender: services.holdContinuousRender,
|
||||
@@ -236,6 +246,7 @@ export class StyleManager extends ShellFacade {
|
||||
setKeyholeFadeTuning: services.setKeyholeFadeTuning,
|
||||
setScopeMaskEnabled: services.setScopeMaskEnabled,
|
||||
setScopeMaskFeather: services.setScopeMaskFeather,
|
||||
setScopeMaskOpacity: services.setScopeMaskOpacity,
|
||||
},
|
||||
elements: {
|
||||
_ppToggles: this._ppToggles,
|
||||
@@ -388,6 +399,13 @@ export class StyleManager extends ShellFacade {
|
||||
meshFloorPreferred: services.meshFloorPreferred,
|
||||
warmGroundFloor: services.warmGroundFloor,
|
||||
sampleMeshFloorCells: services.sampleMeshFloorCells,
|
||||
// Whether the aircraft Cockpit flies still draws: an entity of the
|
||||
// viewer's own (the scene's `viewerDrawsEntity` says), or a tracked
|
||||
// contact whose layer draws it through the draw port and says so in
|
||||
// its entity record.
|
||||
trackedEntityDrawn: (entity) =>
|
||||
services.viewerDrawsEntity?.(entity) === true ||
|
||||
readEntityRecord(entity)?.drawn?.() === true,
|
||||
holdContinuousRender: services.holdContinuousRender,
|
||||
releaseContinuousRender: services.releaseContinuousRender,
|
||||
fetchRegionalBrief: services.fetchRegionalBrief,
|
||||
@@ -400,6 +418,9 @@ export class StyleManager extends ShellFacade {
|
||||
owner: 'cockpit-orbit',
|
||||
switchPolicy: 'esri-if-photoreal',
|
||||
}) ?? null,
|
||||
// The application's own first-person subjects
|
||||
// (src/cockpitSubjectProviders.js), checked by the coordinator.
|
||||
cockpitSubjects: services.cockpitSubjects,
|
||||
},
|
||||
elements: {
|
||||
_ppToggles: this._ppToggles,
|
||||
@@ -457,6 +478,8 @@ export class StyleManager extends ShellFacade {
|
||||
this.celestialRing = new CelestialRing(viewer, {
|
||||
enabled: false,
|
||||
store: useCelestialRingStore(applicationPinia()),
|
||||
// The precise frame, once the sky has loaded its tables.
|
||||
preciseFrameAt: icrfToFixedAxes,
|
||||
onAutoDisable: () =>
|
||||
this.setCelestialRingEnabled(false, {
|
||||
syncShare: !!this.shareLinkManager,
|
||||
@@ -471,7 +494,7 @@ export class StyleManager extends ShellFacade {
|
||||
},
|
||||
isNavigationCurrent: (generation) =>
|
||||
generation === this._navigationGeneration,
|
||||
cancelOwnedNavigation: () => this.viewer.camera.cancelFlight(),
|
||||
cancelOwnedNavigation: () => cameraOf(this.viewer).cancelFlight(),
|
||||
// A host may open a share code without a `/share/<code>` address.
|
||||
initialShareCode,
|
||||
});
|
||||
@@ -588,6 +611,10 @@ export class StyleManager extends ShellFacade {
|
||||
this._setDetectionAllocation(...args),
|
||||
_setDetectionFade: (...args) => this._setDetectionFade(...args),
|
||||
_setScope: (...args) => this._visualSettings._setScope(...args),
|
||||
_applyGlobalPostDefaults: (...args) =>
|
||||
this._applyGlobalPostDefaults(...args),
|
||||
_adoptDetectionAsRestore: () =>
|
||||
this._visualSettings.adoptDetectionAsRestore(),
|
||||
setCelestialRingEnabled: (...args) =>
|
||||
this.setCelestialRingEnabled(...args),
|
||||
_setModels3dEnabled: (...args) => this._setModels3dEnabled(...args),
|
||||
@@ -1048,7 +1075,7 @@ export class StyleManager extends ShellFacade {
|
||||
_radioVolumeValue: this._radioVolumeValue,
|
||||
},
|
||||
radio: radioLayer,
|
||||
canvas: this.viewer?.canvas,
|
||||
canvas: canvasOf(this.viewer) ?? undefined,
|
||||
actions: {
|
||||
isRegistered: () => this._dataManager?.layers?.has('radio'),
|
||||
isEnabled: () => this._dataManager?.isEnabled('radio'),
|
||||
@@ -1197,6 +1224,11 @@ export class StyleManager extends ShellFacade {
|
||||
toggleEnabled: (...args) => this._toggleCctvEnabled(...args),
|
||||
runExplicitFocus: (...args) => this._runExplicitCctvFocus(...args),
|
||||
setPanelCollapsed: (...args) => this.setPanelCollapsed(...args),
|
||||
// Clear selected data layers and Context isolation switch the layer
|
||||
// off without the user asking: the panel keeps its state for both.
|
||||
preservePanelState: () =>
|
||||
this._preservePanelStateDuringLayerClear ||
|
||||
this._contextSuspendsLayer('cctv'),
|
||||
showToast: (message) => this._showToast(message),
|
||||
syncViewport: () => this._syncCctvPanelViewport(),
|
||||
},
|
||||
@@ -1224,7 +1256,7 @@ export class StyleManager extends ShellFacade {
|
||||
setEnabled: (next) =>
|
||||
this._dataManager.setEnabled('cctv', next, { origin: 'user' }),
|
||||
readOwnership: () => ({
|
||||
trackedEntity: this.viewer?.trackedEntity,
|
||||
followed: followedOf(this.viewer),
|
||||
cockpitActive: !!this.cockpitView?.active,
|
||||
}),
|
||||
shouldFocus: () =>
|
||||
@@ -1500,15 +1532,16 @@ export class StyleManager extends ShellFacade {
|
||||
* @returns {{lat: number, lon: number, alt: number, heading: number, pitch: number, roll: number}|null}
|
||||
*/
|
||||
getCameraState() {
|
||||
const carto = this.viewer.camera.positionCartographic;
|
||||
if (!carto) return null;
|
||||
const pose = findCamera(this.viewer)?.pose();
|
||||
if (!pose || !Number.isFinite(pose.lat) || !Number.isFinite(pose.lon))
|
||||
return null;
|
||||
return {
|
||||
lat: Cesium.Math.toDegrees(carto.latitude),
|
||||
lon: Cesium.Math.toDegrees(carto.longitude),
|
||||
alt: carto.height,
|
||||
heading: Cesium.Math.toDegrees(this.viewer.camera.heading),
|
||||
pitch: Cesium.Math.toDegrees(this.viewer.camera.pitch),
|
||||
roll: Cesium.Math.toDegrees(this.viewer.camera.roll),
|
||||
lat: pose.lat,
|
||||
lon: pose.lon,
|
||||
alt: pose.height,
|
||||
heading: toDegrees(pose.heading),
|
||||
pitch: toDegrees(pose.pitch),
|
||||
roll: toDegrees(pose.roll),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1520,20 +1553,18 @@ export class StyleManager extends ShellFacade {
|
||||
*/
|
||||
applyCameraState(cameraState, duration = 2.8) {
|
||||
if (!cameraState) return;
|
||||
this.viewer.camera.flyTo({
|
||||
destination: Cesium.Cartesian3.fromDegrees(
|
||||
cameraState.lon,
|
||||
cameraState.lat,
|
||||
cameraState.alt,
|
||||
),
|
||||
orientation: {
|
||||
heading: Cesium.Math.toRadians(cameraState.heading || 0),
|
||||
pitch: Cesium.Math.toRadians(cameraState.pitch || -35),
|
||||
roll: Cesium.Math.toRadians(cameraState.roll || 0),
|
||||
cameraOf(this.viewer).flyTo(
|
||||
{ lon: cameraState.lon, lat: cameraState.lat, height: cameraState.alt },
|
||||
{
|
||||
orientation: {
|
||||
heading: toRadians(cameraState.heading || 0),
|
||||
pitch: toRadians(cameraState.pitch || -35),
|
||||
roll: toRadians(cameraState.roll || 0),
|
||||
},
|
||||
durationS: Math.max(0.2, duration || 0),
|
||||
easing: 'cubicInOut',
|
||||
},
|
||||
duration: Math.max(0.2, duration || 0),
|
||||
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
|
||||
});
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1785,7 +1816,7 @@ export class StyleManager extends ShellFacade {
|
||||
* altitude ceiling, and only the nearest MODEL_MAX in view are admitted, so
|
||||
* the default costs nothing at globe scale. `all` is the deliberate opt-in;
|
||||
* turning the toggle off returns the fleet to flat billboards. The TRACKED
|
||||
* contact is independent of this toggle (see trackedModelRegime.js).
|
||||
* contact follows the same rule: selecting a contact never changes its form.
|
||||
* @returns {void}
|
||||
*/
|
||||
|
||||
@@ -1848,6 +1879,7 @@ export class StyleManager extends ShellFacade {
|
||||
const { destroyTrackedReadout, destroyWorldOverlay, destroyDetection } =
|
||||
this.services;
|
||||
if (this._disposed) return;
|
||||
this._removeRailEdgeScroll?.();
|
||||
this._shareRestoration.destroy();
|
||||
this._feedback.clearLoadingStatus();
|
||||
this._disposed = true;
|
||||
|
||||
@@ -280,7 +280,7 @@ test('a tracked flight’s photo shows under its name, credited and linked to it
|
||||
test('no photo renders without one', async (t) => {
|
||||
const { panel, publish } = fixture(t);
|
||||
await publish({ ...results(), photo: null });
|
||||
assert.equal(panel().querySelector('.military-awareness-photo'), null);
|
||||
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
|
||||
});
|
||||
|
||||
test('a photo whose image fails to load is hidden until another arrives', async (t) => {
|
||||
@@ -290,10 +290,10 @@ test('a photo whose image fails to load is hidden until another arrives', async
|
||||
.querySelector('.military-awareness-photo img')
|
||||
.dispatchEvent(new Event('error'));
|
||||
await nextTick();
|
||||
assert.equal(panel().querySelector('.military-awareness-photo'), null);
|
||||
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
|
||||
// A repaint with the same photo keeps it hidden.
|
||||
await publish({ ...results({ previousDisabled: false }), photo: photo() });
|
||||
assert.equal(panel().querySelector('.military-awareness-photo'), null);
|
||||
assert.equal(panel().querySelector('.military-awareness-photo') === null, true);
|
||||
// Another plane's photo shows.
|
||||
const next = photo({ src: 'https://t.plnspttrs.net/2/def456_280.jpg' });
|
||||
await publish({ ...results(), photo: next });
|
||||
|
||||
+121
-126
@@ -1,142 +1,139 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { isPickedWorldPosition } from '../data/scenePick.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
followedOf,
|
||||
followedPosition,
|
||||
isFollowing,
|
||||
onFollowChanged,
|
||||
} from '../data/followed.js';
|
||||
import {
|
||||
clamp,
|
||||
eastNorthUp,
|
||||
inverseFramePoint,
|
||||
magnitude,
|
||||
negativePiToPi,
|
||||
toDegrees,
|
||||
toRadians,
|
||||
TWO_PI,
|
||||
zeroToTwoPi,
|
||||
} from '../geo/index.js';
|
||||
import {
|
||||
canvasOf,
|
||||
findCamera,
|
||||
findFrame,
|
||||
findQuery,
|
||||
} from '../render/rendererOf.js';
|
||||
import { placeFollowEye } from './shareFollow.js';
|
||||
|
||||
function trackedTarget(viewer) {
|
||||
const entity = viewer.trackedEntity;
|
||||
// Read the visual's sample first; sampling a flight CallbackProperty twice
|
||||
// can advance dead reckoning ahead of the displayed aircraft.
|
||||
return (
|
||||
entity?.gevDisplayPosition?.() ||
|
||||
entity?.position?.getValue(viewer.clock?.currentTime)
|
||||
);
|
||||
// The visual's sample first: sampling a flight CallbackProperty twice can
|
||||
// advance dead reckoning ahead of the displayed aircraft.
|
||||
return followedPosition(viewer, followedOf(viewer));
|
||||
}
|
||||
|
||||
export const OBLIQUE_PITCH = Cesium.Math.toRadians(-35);
|
||||
export const STRAIGHT_DOWN_PITCH = Cesium.Math.toRadians(-89);
|
||||
const OBLIQUE_THRESHOLD = Cesium.Math.toRadians(-60);
|
||||
export const OBLIQUE_PITCH = toRadians(-35);
|
||||
export const STRAIGHT_DOWN_PITCH = toRadians(-89);
|
||||
const OBLIQUE_THRESHOLD = toRadians(-60);
|
||||
const EPSILON10 = 1e-10;
|
||||
|
||||
function normalizedHeading(heading) {
|
||||
const wrapped = Cesium.Math.zeroToTwoPi(
|
||||
Number.isFinite(heading) ? heading : 0,
|
||||
);
|
||||
return Math.abs(wrapped - Cesium.Math.TWO_PI) < Cesium.Math.EPSILON10
|
||||
? 0
|
||||
: wrapped;
|
||||
const wrapped = zeroToTwoPi(Number.isFinite(heading) ? heading : 0);
|
||||
return Math.abs(wrapped - TWO_PI) < EPSILON10 ? 0 : wrapped;
|
||||
}
|
||||
|
||||
/** The camera port's pose, or null when there is none to read. */
|
||||
function poseOf(camera) {
|
||||
try {
|
||||
return camera?.pose() ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Cubic ease in and out, 0..1 to 0..1. */
|
||||
function cubicInOut(k) {
|
||||
if (k < 0.5) return 4 * k * k * k;
|
||||
const f = 2 * k - 2;
|
||||
return 0.5 * f * f * f + 1;
|
||||
}
|
||||
|
||||
/** Return the world position under the center of the canvas, when available. */
|
||||
export function pickViewTarget(viewer) {
|
||||
const scene = viewer?.scene;
|
||||
const camera = viewer?.camera;
|
||||
const canvas = scene?.canvas;
|
||||
if (!scene || !camera || !canvas) return null;
|
||||
const query = findQuery(viewer);
|
||||
const canvas = canvasOf(viewer);
|
||||
if (!query || !canvas) return null;
|
||||
const width = canvas.clientWidth || canvas.width || 0;
|
||||
const height = canvas.clientHeight || canvas.height || 0;
|
||||
if (!width || !height) return null;
|
||||
const center = new Cesium.Cartesian2(width / 2, height / 2);
|
||||
let target = null;
|
||||
|
||||
if (scene.pickPositionSupported && typeof scene.pickPosition === 'function') {
|
||||
const x = width / 2;
|
||||
const y = height / 2;
|
||||
const attempt = (pick) => {
|
||||
try {
|
||||
target = scene.pickPosition(center);
|
||||
return pick();
|
||||
} catch {
|
||||
target = null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// Terrain before the ellipsoid: globe.pick intersects the rendered surface,
|
||||
// so over keyless elevated terrain it returns the ground the operator is
|
||||
// looking at. pickEllipsoid answers with sea level, which on a plateau sits
|
||||
// far below the view and would swing the camera on every tilt.
|
||||
if (
|
||||
!isPickedWorldPosition(target) &&
|
||||
typeof camera.getPickRay === 'function'
|
||||
) {
|
||||
try {
|
||||
target = scene.globe?.pick(camera.getPickRay(center), scene) || null;
|
||||
} catch {
|
||||
target = null;
|
||||
}
|
||||
}
|
||||
if (
|
||||
!isPickedWorldPosition(target) &&
|
||||
typeof camera.pickEllipsoid === 'function'
|
||||
) {
|
||||
try {
|
||||
target = camera.pickEllipsoid(center, Cesium.Ellipsoid.WGS84);
|
||||
} catch {
|
||||
target = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
// Depth first: what is drawn under the centre, tiles included.
|
||||
let target = attempt(() => query.pickPosition(x, y));
|
||||
// Terrain before the ellipsoid: the globe pick intersects the rendered
|
||||
// surface, so over keyless elevated terrain it returns the ground the
|
||||
// operator is looking at. The ellipsoid answers with sea level, which on a
|
||||
// plateau sits far below the view and would swing the camera on every tilt.
|
||||
if (!isPickedWorldPosition(target))
|
||||
target = attempt(() => query.pickGlobe(query.pickRay(x, y)));
|
||||
if (!isPickedWorldPosition(target))
|
||||
target = attempt(() => query.pickEllipsoid(x, y));
|
||||
return isPickedWorldPosition(target) ? target : null;
|
||||
}
|
||||
|
||||
/** Describe the camera as an orbit around the current viewport center. */
|
||||
export function readCameraTargetFrame(viewer) {
|
||||
const camera = viewer?.camera;
|
||||
const target = viewer?.trackedEntity
|
||||
const pose = poseOf(findCamera(viewer));
|
||||
const target = isFollowing(viewer)
|
||||
? trackedTarget(viewer)
|
||||
: pickViewTarget(viewer);
|
||||
if (!camera || !target || !isPickedWorldPosition(camera.positionWC))
|
||||
return null;
|
||||
if (!pose || !target || !isPickedWorldPosition(pose.position)) return null;
|
||||
|
||||
const transform = Cesium.Transforms.eastNorthUpToFixedFrame(target);
|
||||
const inverse = Cesium.Matrix4.inverseTransformation(
|
||||
transform,
|
||||
new Cesium.Matrix4(),
|
||||
);
|
||||
const localOffset = Cesium.Matrix4.multiplyByPoint(
|
||||
inverse,
|
||||
camera.positionWC,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const range = Cesium.Cartesian3.magnitude(localOffset);
|
||||
const localOffset = inverseFramePoint(eastNorthUp(target), pose.position);
|
||||
const range = magnitude(localOffset);
|
||||
if (!Number.isFinite(range) || range < 1) return null;
|
||||
|
||||
const pitch = -Math.asin(Cesium.Math.clamp(localOffset.z / range, -1, 1));
|
||||
// Cesium places a lookAt camera at range * (-sin h cos p, -cos h cos p,
|
||||
// -sin p) in the target's east-north-up frame, so recovering h means
|
||||
// negating BOTH horizontal components. Negating only the north one reads
|
||||
// every heading as its mirror image (30 deg comes back as 330), which would
|
||||
// make north-up rotate the wrong way from three quarters of the compass.
|
||||
const pitch = -Math.asin(clamp(localOffset.z / range, -1, 1));
|
||||
// A lookAt camera sits at range * (-sin h cos p, -cos h cos p, -sin p) in
|
||||
// the target's east-north-up frame, so recovering h means negating BOTH
|
||||
// horizontal components. Negating only the north one reads every heading
|
||||
// as its mirror image (30 deg comes back as 330), which would make north-up
|
||||
// rotate the wrong way from three quarters of the compass.
|
||||
const targetHeading = Math.atan2(-localOffset.x, -localOffset.y);
|
||||
const heading = normalizedHeading(
|
||||
pitch < Cesium.Math.toRadians(-88.5) ? camera.heading : targetHeading,
|
||||
pitch < toRadians(-88.5) ? pose.heading : targetHeading,
|
||||
);
|
||||
return { target, range, heading, pitch };
|
||||
}
|
||||
|
||||
/** Apply an orbit frame, then return the camera to Cesium's fixed-world frame. */
|
||||
/** Apply an orbit frame, then return the camera to the world frame. */
|
||||
function setCameraTargetFrame(viewer, frame) {
|
||||
const camera = viewer?.camera;
|
||||
const camera = findCamera(viewer);
|
||||
if (!camera || !frame?.target || !Number.isFinite(frame.range)) return false;
|
||||
const offset = {
|
||||
heading: normalizedHeading(frame.heading),
|
||||
pitch: frame.pitch,
|
||||
range: frame.range,
|
||||
};
|
||||
try {
|
||||
const trackedTransform = viewer.trackedEntity
|
||||
? Cesium.Matrix4.clone(camera.transform)
|
||||
: null;
|
||||
camera.lookAt(
|
||||
frame.target,
|
||||
new Cesium.HeadingPitchRange(
|
||||
normalizedHeading(frame.heading),
|
||||
frame.pitch,
|
||||
frame.range,
|
||||
),
|
||||
);
|
||||
if (trackedTransform) {
|
||||
// Preserve EntityView's reference frame (including satellite frames).
|
||||
// Its next update carries this new local offset along with the target.
|
||||
camera.lookAtTransform(trackedTransform);
|
||||
viewer.scene?.requestRender?.();
|
||||
return true;
|
||||
}
|
||||
const destination = Cesium.Cartesian3.clone(camera.positionWC);
|
||||
const direction = Cesium.Cartesian3.clone(camera.directionWC);
|
||||
const up = Cesium.Cartesian3.clone(camera.upWC);
|
||||
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
|
||||
if (destination && direction && up) {
|
||||
camera.setView({ destination, orientation: { direction, up } });
|
||||
}
|
||||
viewer.scene?.requestRender?.();
|
||||
// Following keeps the follow's own frame (satellite frames included):
|
||||
// its next update carries the new offset along with the target.
|
||||
if (isFollowing(viewer))
|
||||
return placeFollowEye(viewer, frame.target, offset);
|
||||
camera.lookAt(frame.target, offset);
|
||||
const pose = camera.pose();
|
||||
camera.release();
|
||||
if (pose?.position && pose.direction && pose.up)
|
||||
camera.setView({
|
||||
destination: pose.position,
|
||||
orientation: { direction: pose.direction, up: pose.up },
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
@@ -179,8 +176,8 @@ export function resetCameraNorth(viewer) {
|
||||
return setCameraTargetFrame(viewer, { ...frame, heading: 0 });
|
||||
}
|
||||
|
||||
function headingDegrees(camera) {
|
||||
return Cesium.Math.toDegrees(normalizedHeading(camera?.heading));
|
||||
function headingDegrees(viewer) {
|
||||
return toDegrees(normalizedHeading(poseOf(findCamera(viewer))?.heading));
|
||||
}
|
||||
|
||||
/** Ease an orbit without handing off the entity that owns the follow camera. */
|
||||
@@ -197,29 +194,28 @@ export function createCameraOrientationAnimator(
|
||||
};
|
||||
function animate(frame, destination) {
|
||||
cancel();
|
||||
if (!viewer.scene?.preUpdate?.addEventListener || duration <= 0)
|
||||
const frames = findFrame(viewer);
|
||||
if (!frames || duration <= 0)
|
||||
return setCameraTargetFrame(viewer, { ...frame, ...destination });
|
||||
const entity = viewer.trackedEntity;
|
||||
const followed = followedOf(viewer);
|
||||
pending = destination;
|
||||
const start = now();
|
||||
const headingDelta = Cesium.Math.negativePiToPi(
|
||||
destination.heading - frame.heading,
|
||||
);
|
||||
remove = viewer.scene.preUpdate.addEventListener(() => {
|
||||
if (viewer.isDestroyed?.() || viewer.trackedEntity !== entity) {
|
||||
const headingDelta = negativePiToPi(destination.heading - frame.heading);
|
||||
remove = frames.on('preUpdate', () => {
|
||||
if (viewer.isDestroyed?.() || followedOf(viewer) !== followed) {
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
const progress = Cesium.Math.clamp((now() - start) / duration, 0, 1);
|
||||
const eased = Cesium.EasingFunction.CUBIC_IN_OUT(progress);
|
||||
const target = entity ? trackedTarget(viewer) : frame.target;
|
||||
const progress = clamp((now() - start) / duration, 0, 1);
|
||||
const eased = cubicInOut(progress);
|
||||
const target = followed ? trackedTarget(viewer) : frame.target;
|
||||
if (
|
||||
!isPickedWorldPosition(target) ||
|
||||
!setCameraTargetFrame(viewer, {
|
||||
...frame,
|
||||
target,
|
||||
heading: frame.heading + headingDelta * eased,
|
||||
pitch: Cesium.Math.lerp(frame.pitch, destination.pitch, eased),
|
||||
pitch: (1 - eased) * frame.pitch + eased * destination.pitch,
|
||||
})
|
||||
) {
|
||||
cancel();
|
||||
@@ -227,7 +223,7 @@ export function createCameraOrientationAnimator(
|
||||
}
|
||||
if (progress === 1) cancel();
|
||||
});
|
||||
viewer.scene.requestRender?.();
|
||||
frames.requestRender('camera-orientation');
|
||||
return true;
|
||||
}
|
||||
return {
|
||||
@@ -280,7 +276,7 @@ export function bindCameraOrientationControls({
|
||||
if (destroyed) return;
|
||||
const next = {
|
||||
tilted,
|
||||
heading: Math.round(headingDegrees(viewer?.camera)) % 360,
|
||||
heading: Math.round(headingDegrees(viewer)) % 360,
|
||||
};
|
||||
publish?.(next);
|
||||
}
|
||||
@@ -326,20 +322,19 @@ export function bindCameraOrientationControls({
|
||||
sync();
|
||||
}
|
||||
|
||||
const subscribe = (event, handler) => {
|
||||
const remove = event?.addEventListener?.(handler);
|
||||
const subscribe = (remove) => {
|
||||
if (typeof remove === 'function') removers.push(remove);
|
||||
};
|
||||
// The needle follows every frame the scene draws. `camera.changed` is NOT
|
||||
// enough: it only fires past `camera.percentageChanged`, so a rotation of a
|
||||
// few degrees leaves the needle pointing at the old bearing.
|
||||
subscribe(viewer?.scene?.preRender, sync);
|
||||
// The needle follows every frame the scene draws. The camera's `changed`
|
||||
// is NOT enough: it only fires past its threshold, so a rotation of a few
|
||||
// degrees leaves the needle pointing at the old bearing.
|
||||
subscribe(findFrame(viewer)?.on('preRender', sync));
|
||||
// The exact tilt state is refreshed once per gesture, not once per frame —
|
||||
// moveEnd fires when the camera stops, which is where the pick is affordable.
|
||||
subscribe(viewer?.camera?.moveEnd, refreshTilt);
|
||||
subscribe(viewer?.trackedEntityChanged, animator.cancel);
|
||||
subscribe(findCamera(viewer)?.on('moveEnd', refreshTilt));
|
||||
if (viewer) removers.push(onFollowChanged(viewer, animator.cancel));
|
||||
for (const type of ['pointerdown', 'wheel']) {
|
||||
const canvas = viewer?.scene?.canvas;
|
||||
const canvas = canvasOf(viewer);
|
||||
canvas?.addEventListener?.(type, animator.cancel, { passive: true });
|
||||
removers.push(() => canvas?.removeEventListener?.(type, animator.cancel));
|
||||
}
|
||||
|
||||
@@ -12,6 +12,39 @@ import {
|
||||
toggleCameraTilt,
|
||||
} from './cameraOrientationControls.js';
|
||||
import { NavigationController } from './navigationController.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import {
|
||||
createCesiumQuery,
|
||||
queryCapabilities,
|
||||
} from '../render/cesium/query.js';
|
||||
import {
|
||||
bindFakeCesiumCamera,
|
||||
followEntity,
|
||||
followedEntity,
|
||||
} from '../testSupport/fakeCameraPort.mjs';
|
||||
import { entityFollowTarget } from '../data/followed.js';
|
||||
import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs';
|
||||
import { entityRecord } from '../data/entityRecords.js';
|
||||
|
||||
/**
|
||||
* Bind the camera, query and frame ports over a viewer double, as the
|
||||
* renderer does: the Cesium query port over its scene, and the frame
|
||||
* phases from the scene's own events.
|
||||
*/
|
||||
function withPorts(viewer, { frames = true } = {}) {
|
||||
return bindFakeCesiumCamera(viewer, {
|
||||
query: createCesiumQuery({
|
||||
scene: viewer.scene,
|
||||
camera: viewer.camera,
|
||||
draw: { sets: new Map(), version: () => 0 },
|
||||
capabilities: new Set(queryCapabilities(viewer.scene)),
|
||||
}),
|
||||
...(frames ? { frame: fakeSceneFrame(viewer) } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/** Coordinates only, as the query port answers. */
|
||||
const plain = (p) => ({ x: p.x, y: p.y, z: p.z });
|
||||
|
||||
function createViewer({ cameraPosition, target, pickPosition = null } = {}) {
|
||||
const calls = [];
|
||||
@@ -25,7 +58,7 @@ function createViewer({ cameraPosition, target, pickPosition = null } = {}) {
|
||||
heading: Cesium.Math.toRadians(90),
|
||||
changed,
|
||||
pickEllipsoid: () => surface,
|
||||
getPickRay: () => ({}),
|
||||
getPickRay: () => new Cesium.Ray(),
|
||||
lookAt(targetValue, offset) {
|
||||
calls.push({ type: 'lookAt', target: targetValue, offset });
|
||||
},
|
||||
@@ -46,7 +79,7 @@ function createViewer({ cameraPosition, target, pickPosition = null } = {}) {
|
||||
requestRender: () => calls.push({ type: 'requestRender' }),
|
||||
},
|
||||
};
|
||||
return { viewer, calls, target: surface };
|
||||
return { viewer: withPorts(viewer), calls, target: surface };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,8 +129,12 @@ function createRealCamera() {
|
||||
return { camera, scene };
|
||||
}
|
||||
|
||||
/** A viewer whose center pick is a fixed ground point and whose camera is real. */
|
||||
function createRealViewer(target) {
|
||||
/**
|
||||
* A viewer whose center pick is a fixed ground point and whose camera is
|
||||
* real. Without `frames` it has no frame loop, so orientation changes land
|
||||
* at once rather than easing.
|
||||
*/
|
||||
function createRealViewer(target, { frames = true } = {}) {
|
||||
const { camera, scene } = createRealCamera();
|
||||
scene.pickPositionSupported = false;
|
||||
scene.pickPosition = () => null;
|
||||
@@ -106,8 +143,16 @@ function createRealViewer(target) {
|
||||
// The binding drives the needle from the scene's per-frame signal, not from
|
||||
// `camera.changed`, so the fixture has to carry one.
|
||||
scene.preRender = new Cesium.Event();
|
||||
camera.getPickRay = () => ({});
|
||||
return { viewer: { camera, scene }, target };
|
||||
camera.getPickRay = () => new Cesium.Ray();
|
||||
// Cesium's entity tracking, without entities of its own: the camera port
|
||||
// follows on a tracking widget of the fake's.
|
||||
const viewer = {
|
||||
camera,
|
||||
scene,
|
||||
trackedEntityChanged: new Cesium.Event(),
|
||||
entities: {},
|
||||
};
|
||||
return { viewer: withPorts(viewer, { frames }), target };
|
||||
}
|
||||
|
||||
/** Place a real camera in an orbit around `target` and release the frame. */
|
||||
@@ -277,7 +322,7 @@ test('tilt alternates at globe range, not only at map range', () => {
|
||||
|
||||
test('the button shows the state the next click will produce, at every range', () => {
|
||||
for (const range of [3_000, 18_000_000]) {
|
||||
const { viewer } = createRealViewer(AUSTIN_GROUND);
|
||||
const { viewer } = createRealViewer(AUSTIN_GROUND, { frames: false });
|
||||
orbit(viewer, AUSTIN_GROUND, 0, STRAIGHT_DOWN_PITCH, range);
|
||||
const bar = recorder();
|
||||
const controls = bindCameraOrientationControls({
|
||||
@@ -408,9 +453,13 @@ test('a sky-facing camera yields no frame and both actions decline', () => {
|
||||
scene.pickPosition = () => null;
|
||||
scene.globe.pick = () => undefined;
|
||||
scene.requestRender = () => {};
|
||||
camera.getPickRay = () => ({});
|
||||
camera.pickEllipsoid = () => undefined;
|
||||
const viewer = { camera, scene };
|
||||
// 1000 km up, looking above the horizon: no ray from the centre meets
|
||||
// the ellipsoid.
|
||||
camera.setView({
|
||||
destination: Cesium.Cartesian3.fromDegrees(-97.74, 30.27, 1_000_000),
|
||||
orientation: { heading: 0, pitch: Cesium.Math.toRadians(30), roll: 0 },
|
||||
});
|
||||
const viewer = withPorts({ camera, scene });
|
||||
|
||||
assert.equal(readCameraTargetFrame(viewer), null);
|
||||
assert.equal(toggleCameraTilt(viewer), false);
|
||||
@@ -424,16 +473,16 @@ test('center picking prefers terrain over the ellipsoid and falls through an inv
|
||||
const { viewer } = createViewer({ pickPosition: () => invalid });
|
||||
viewer.scene.globe.pick = () => terrain;
|
||||
viewer.camera.pickEllipsoid = () => sea;
|
||||
assert.equal(
|
||||
assert.deepEqual(
|
||||
pickViewTarget(viewer),
|
||||
terrain,
|
||||
plain(terrain),
|
||||
'the rendered ground wins over sea level',
|
||||
);
|
||||
|
||||
viewer.scene.globe.pick = () => null;
|
||||
assert.equal(
|
||||
assert.deepEqual(
|
||||
pickViewTarget(viewer),
|
||||
sea,
|
||||
plain(sea),
|
||||
'the ellipsoid still answers when nothing is under the cursor',
|
||||
);
|
||||
});
|
||||
@@ -453,7 +502,7 @@ test('tilt preserves the picked target and range while choosing oblique pitch',
|
||||
const result = toggleCameraTilt(viewer);
|
||||
const lookAt = calls.find((call) => call.type === 'lookAt');
|
||||
assert.deepEqual(result, { tilted: true, pitch: OBLIQUE_PITCH });
|
||||
assert.equal(lookAt.target, target);
|
||||
assert.ok(Cesium.Cartesian3.equals(lookAt.target, target));
|
||||
assert.equal(lookAt.offset.range, before.range);
|
||||
assert.equal(lookAt.offset.pitch, OBLIQUE_PITCH);
|
||||
assert.ok(calls.some((call) => call.type === 'lookAtTransform'));
|
||||
@@ -523,8 +572,8 @@ for (const [label, altitude, range] of [
|
||||
position: new Cesium.CallbackPositionProperty(() => target, false),
|
||||
trackingReferenceFrame: Cesium.TrackingReferenceFrame.ENU,
|
||||
});
|
||||
entity.gevDisplayPosition = () => target;
|
||||
viewer.trackedEntity = entity;
|
||||
entityRecord(entity).displayPosition = () => target;
|
||||
followEntity(viewer, entity);
|
||||
const follow = new Cesium.EntityView(entity, viewer.scene);
|
||||
follow.update(viewer.clock.currentTime);
|
||||
viewer.camera.lookAt(
|
||||
@@ -553,7 +602,7 @@ for (const [label, altitude, range] of [
|
||||
follow.update(viewer.clock.currentTime);
|
||||
const transform = Cesium.Matrix4.clone(viewer.camera.transform);
|
||||
viewer.scene.preUpdate.raiseEvent();
|
||||
assert.equal(viewer.trackedEntity, entity);
|
||||
assert.equal(followedEntity(viewer), entity);
|
||||
assert.ok(
|
||||
Cesium.Matrix4.equalsEpsilon(
|
||||
viewer.camera.transform,
|
||||
@@ -573,7 +622,7 @@ for (const [label, altitude, range] of [
|
||||
}
|
||||
target = Cesium.Cartesian3.fromDegrees(-96, 31, altitude);
|
||||
follow.update(viewer.clock.currentTime);
|
||||
assert.equal(viewer.trackedEntity, entity);
|
||||
assert.equal(followedEntity(viewer), entity);
|
||||
assert.ok(Math.abs(readCameraTargetFrame(viewer).range - range) < 1e-5);
|
||||
});
|
||||
}
|
||||
@@ -587,10 +636,10 @@ test('orientation animation cancels on replacement and explicit cancellation', (
|
||||
animator.animate(frame, { heading: 0, pitch: STRAIGHT_DOWN_PITCH });
|
||||
animator.animate(frame, { heading: 0, pitch: OBLIQUE_PITCH });
|
||||
assert.equal(viewer.scene.preUpdate.numberOfListeners, 1);
|
||||
viewer.trackedEntity = {};
|
||||
followEntity(viewer, {});
|
||||
viewer.scene.preUpdate.raiseEvent();
|
||||
assert.equal(viewer.scene.preUpdate.numberOfListeners, 0);
|
||||
viewer.trackedEntity = undefined;
|
||||
followEntity(viewer, null);
|
||||
animator.animate(frame, { heading: 0, pitch: STRAIGHT_DOWN_PITCH });
|
||||
animator.cancel();
|
||||
assert.equal(viewer.scene.preUpdate.numberOfListeners, 0);
|
||||
@@ -599,10 +648,18 @@ test('orientation animation cancels on replacement and explicit cancellation', (
|
||||
test('orientation navigation preserves follow and selection; new navigation cancels animation', () => {
|
||||
const calls = [];
|
||||
const entity = {};
|
||||
const viewer = {
|
||||
trackedEntity: entity,
|
||||
camera: { cancelFlight: () => calls.push('cancel-flight') },
|
||||
};
|
||||
const viewer = {};
|
||||
bindRenderer(viewer, {
|
||||
camera: {
|
||||
cancelFlight: () => calls.push('cancel-flight'),
|
||||
// The camera follows `entity`.
|
||||
followed: entityFollowTarget(entity, {}),
|
||||
follow(target) {
|
||||
this.followed = target;
|
||||
},
|
||||
on: () => () => {},
|
||||
},
|
||||
});
|
||||
let cockpit = false;
|
||||
const navigation = new NavigationController({
|
||||
viewer,
|
||||
@@ -619,7 +676,7 @@ test('orientation navigation preserves follow and selection; new navigation canc
|
||||
navigation.runOrientation('camera', () => 'animated'),
|
||||
'animated',
|
||||
);
|
||||
assert.equal(viewer.trackedEntity, entity);
|
||||
assert.equal(followedEntity(viewer), entity);
|
||||
assert.deepEqual(calls, [
|
||||
'cancel-orientation',
|
||||
'interrupt-motion',
|
||||
|
||||
@@ -54,6 +54,7 @@ export class CctvControls {
|
||||
this._cctvSummaryTypingTimer = null;
|
||||
this._lastCctvSummaryText = '';
|
||||
this._lastSeenCctvActiveId = null;
|
||||
this._wasCctvEnabled = false;
|
||||
this._cctvChipHideTimer = null;
|
||||
this._cctvChipWasBusy = false;
|
||||
// The camera grid chip as last published; its label stays while hidden.
|
||||
|
||||
@@ -513,3 +513,96 @@ test('the panel meta line reads a bearing that rounds to north as HDG 0°', () =
|
||||
assert.match(meta(359.4), /· HDG 359° ·/);
|
||||
assert.match(meta(359.6), /· HDG 0° ·/);
|
||||
});
|
||||
|
||||
/** The panel collapses the test asked for, as `[panelId, collapsed]` pairs. */
|
||||
function collapseCalls(controls) {
|
||||
const calls = [];
|
||||
controls.actions.setPanelCollapsed = (panelId, collapsed) => {
|
||||
calls.push([panelId, collapsed]);
|
||||
// The panel chrome owns the class the controls read back.
|
||||
controls._cctvPanel.classList.toggle('collapsed', collapsed);
|
||||
};
|
||||
return calls;
|
||||
}
|
||||
|
||||
const activeState = {
|
||||
enabled: true,
|
||||
count: 1,
|
||||
cameraIndex: [],
|
||||
activeCameraId: camera.id,
|
||||
activeCamera: camera,
|
||||
};
|
||||
|
||||
test('switching the layer off collapses the panel it opened', (t) => {
|
||||
const { controls } = panel(t);
|
||||
const calls = collapseCalls(controls);
|
||||
controls._renderCctvState(activeState);
|
||||
assert.deepEqual(calls, [['cctv-panel', false]]);
|
||||
// The layer keeps its active camera while off.
|
||||
controls._renderCctvState({ ...activeState, enabled: false });
|
||||
assert.deepEqual(calls.at(-1), ['cctv-panel', true]);
|
||||
// A panel reopened by hand stays open through later notifications while
|
||||
// the layer is off: only the on → off change collapses.
|
||||
controls._cctvPanel.classList.remove('collapsed');
|
||||
controls._renderCctvState({ ...activeState, enabled: false });
|
||||
assert.equal(calls.length, 2);
|
||||
assert.equal(controls._cctvPanel.classList.contains('collapsed'), false);
|
||||
});
|
||||
|
||||
test('a layer that was never on leaves an open panel alone', (t) => {
|
||||
const { controls } = panel(t);
|
||||
const calls = collapseCalls(controls);
|
||||
controls._renderCctvState({ enabled: false, count: 3, cameraIndex: [] });
|
||||
controls._renderCctvState({ enabled: false, count: 3, cameraIndex: [] });
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
test('the data manager switching the layer off collapses the panel too', (t) => {
|
||||
const { controls } = panel(t);
|
||||
const calls = collapseCalls(controls);
|
||||
let on = true;
|
||||
controls.actions.isEnabled = () => on;
|
||||
controls._renderCctvState(activeState);
|
||||
on = false;
|
||||
controls._renderCctvState(activeState);
|
||||
assert.deepEqual(calls.at(-1), ['cctv-panel', true]);
|
||||
});
|
||||
|
||||
test('a layer the application suspends keeps its panel through the round trip', (t) => {
|
||||
const { controls } = panel(t);
|
||||
const calls = collapseCalls(controls);
|
||||
// Clear selected data layers and Context isolation both answer true.
|
||||
let suspended = true;
|
||||
controls.actions.preservePanelState = () => suspended;
|
||||
controls._renderCctvState(activeState);
|
||||
controls._renderCctvState({ ...activeState, enabled: false });
|
||||
assert.equal(controls._cctvPanel.classList.contains('collapsed'), false);
|
||||
suspended = false;
|
||||
controls._renderCctvState(activeState);
|
||||
assert.equal(controls._cctvPanel.classList.contains('collapsed'), false);
|
||||
assert.ok(calls.every(([, collapsed]) => collapsed === false));
|
||||
// The next switch-off is the user's again.
|
||||
controls._renderCctvState({ ...activeState, enabled: false });
|
||||
assert.deepEqual(calls.at(-1), ['cctv-panel', true]);
|
||||
});
|
||||
|
||||
test('a panel the accordion folded still has its saved state closed', (t) => {
|
||||
const { controls } = panel(t);
|
||||
controls._renderCctvState(activeState);
|
||||
const calls = [];
|
||||
controls.actions.setPanelCollapsed = (...args) => calls.push(args);
|
||||
// Folded for layout only: the class is there, the saved state is open. The
|
||||
// panel chrome tells the two apart, so the controls always ask it.
|
||||
controls._cctvPanel.classList.add('collapsed');
|
||||
controls._renderCctvState({ ...activeState, enabled: false });
|
||||
assert.deepEqual(calls, [['cctv-panel', true]]);
|
||||
});
|
||||
|
||||
test('the meta line of a disabled layer does not describe its last camera', () => {
|
||||
const off = { ...activeState, enabled: false, count: 3 };
|
||||
assert.equal(
|
||||
presentCctvPanel(off, false).meta,
|
||||
'3 cameras loaded · enable CCTV to activate',
|
||||
);
|
||||
assert.match(presentCctvPanel(activeState, true).meta, /^Austin · HDG /);
|
||||
});
|
||||
@@ -90,7 +90,9 @@ export function presentCctvPanel(state, enabled) {
|
||||
}
|
||||
|
||||
function metaText(state, enabled, activeCamera, catalogCount) {
|
||||
if (activeCamera) {
|
||||
// The layer keeps its active camera while off: a disabled panel must not
|
||||
// describe a feed it no longer shows.
|
||||
if (enabled && activeCamera) {
|
||||
const provider = cctvSourceLabelText(
|
||||
activeCamera.sourceLabel || activeCamera.provider || 'Configured Source',
|
||||
);
|
||||
@@ -188,6 +190,20 @@ export function _renderCctvState(state) {
|
||||
});
|
||||
}
|
||||
this._lastSeenCctvActiveId = effectiveActiveId;
|
||||
// Switching the layer off closes the panel it opened: nothing is left to
|
||||
// show. Only the on → off change collapses, so a panel the user opens
|
||||
// while the layer is off stays open. Clear selected data layers and
|
||||
// Context isolation keep the panel: the layer comes back with it. The
|
||||
// panel chrome decides whether anything changes: a panel the desktop
|
||||
// accordion only folded still has an open saved state to close.
|
||||
if (
|
||||
this._wasCctvEnabled &&
|
||||
!enabled &&
|
||||
!this.actions.preservePanelState?.()
|
||||
) {
|
||||
this.actions.setPanelCollapsed('cctv-panel', true);
|
||||
}
|
||||
this._wasCctvEnabled = enabled;
|
||||
|
||||
this._updateCctvSyncChip(state?.loading, enabled);
|
||||
|
||||
|
||||
@@ -12,6 +12,12 @@ import { useCockpitStore } from './stores/cockpit.js';
|
||||
import CockpitView from './views/CockpitView.vue';
|
||||
import ContextView from './views/ContextView.vue';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
bindFakeCesiumCamera,
|
||||
followEntity,
|
||||
followedEntity,
|
||||
} from '../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
|
||||
import { vesselCockpitInfo } from '../layers/vessels/cockpitSubject.js';
|
||||
import { VesselRecords } from '../layers/vessels/records.js';
|
||||
|
||||
@@ -90,6 +96,54 @@ function vesselLayer(record) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The query port over the test's fake scene, as the Cesium adapter answers
|
||||
* it: a position is drawn where `scene.cartesianToCanvasCoordinates` says;
|
||||
* heights come from `scene.sampleHeight` (loaded tiles, at once) and
|
||||
* `scene.sampleHeightMostDetailed` (the full-detail read), per probe.
|
||||
*/
|
||||
/** The surfaces the bridge's height reads asked for, in order. */
|
||||
const surfacesAsked = [];
|
||||
|
||||
function sceneQuery(viewer, ports) {
|
||||
const scene = () => viewer.scene;
|
||||
const cartographic = ({ lon, lat }) =>
|
||||
Cesium.Cartographic.fromDegrees(lon, lat);
|
||||
return {
|
||||
...ports.query,
|
||||
project: (position) =>
|
||||
scene().cartesianToCanvasCoordinates?.(position, {}) ?? null,
|
||||
sampleHeightNow(point, options = {}) {
|
||||
surfacesAsked.push(options.against ?? 'surface');
|
||||
const height = scene().sampleHeight?.(cartographic(point));
|
||||
return Number.isFinite(height) ? height : null;
|
||||
},
|
||||
sampleHeight(points, { mostDetailed = false, against = 'surface' } = {}) {
|
||||
surfacesAsked.push(against);
|
||||
if (
|
||||
!mostDetailed ||
|
||||
typeof scene().sampleHeightMostDetailed !== 'function'
|
||||
)
|
||||
return Promise.resolve(points.map(() => null));
|
||||
// Answered as soon as the scene's read lands, as the adapter does.
|
||||
return scene()
|
||||
.sampleHeightMostDetailed(points.map(cartographic))
|
||||
.then((sampled) =>
|
||||
(sampled || []).map((position) =>
|
||||
Number.isFinite(position?.height)
|
||||
? {
|
||||
height: position.height,
|
||||
confidence: 1,
|
||||
source: 'tiles',
|
||||
lod: 'finest',
|
||||
}
|
||||
: null,
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fixture(
|
||||
t,
|
||||
{ bridgeAllowed = true, record = RECORD, aircraftInfo = null } = {},
|
||||
@@ -116,7 +170,6 @@ function fixture(
|
||||
// Each placed camera: where it is and where it looks.
|
||||
const shots = [];
|
||||
const viewer = {
|
||||
trackedEntity: undefined,
|
||||
clock: { currentTime: null },
|
||||
camera: {
|
||||
cancelFlight() {},
|
||||
@@ -143,6 +196,11 @@ function fixture(
|
||||
const disableFlights = () => {
|
||||
flightsEnabled = false;
|
||||
};
|
||||
// The Cockpit drives the camera, reads frames and queries the scene
|
||||
// through ports: the Cesium camera port over the fake camera, and a query
|
||||
// that answers from the test's scene (`sceneQuery`).
|
||||
const ports = fakeScenePorts(viewer);
|
||||
bindFakeCesiumCamera(viewer, { ...ports, query: sceneQuery(viewer, ports) });
|
||||
const cockpit = new CockpitViewController(viewer, {
|
||||
services: {
|
||||
flightsLayer: {
|
||||
@@ -397,10 +455,10 @@ test('tracking an aircraft from the bridge ends it without refocusing the vessel
|
||||
const { cockpit, viewer, vessels, aircraft } = fixture(t);
|
||||
cockpit.enter();
|
||||
await settle();
|
||||
viewer.trackedEntity = aircraft;
|
||||
followEntity(viewer, aircraft);
|
||||
cockpit.update();
|
||||
assert.equal(cockpit.active, false);
|
||||
assert.equal(viewer.trackedEntity, aircraft, 'the aircraft keeps tracking');
|
||||
assert.equal(followedEntity(viewer), aircraft, 'the aircraft keeps tracking');
|
||||
assert.equal(aircraft.show, true, 'the aircraft was never adopted');
|
||||
assert.deepEqual(vessels.calls, [
|
||||
['subject', RECORD.id],
|
||||
@@ -408,6 +466,18 @@ test('tracking an aircraft from the bridge ends it without refocusing the vessel
|
||||
]);
|
||||
});
|
||||
|
||||
test('following a satellite or a site from the bridge ends it too', async (t) => {
|
||||
const { cockpit, viewer, vessels } = fixture(t);
|
||||
cockpit.enter();
|
||||
await settle();
|
||||
// A satellite's or an installation's follow carrier has no position of
|
||||
// its own (the camera reads the follow target's).
|
||||
followEntity(viewer, { id: 'satellites:25544', noradId: 25544 });
|
||||
cockpit.update();
|
||||
assert.equal(cockpit.active, false);
|
||||
assert.deepEqual(vessels.calls.at(-1), ['subject', null]);
|
||||
});
|
||||
|
||||
test('a vessel that leaves the selection ends the bridge', async (t) => {
|
||||
const { cockpit, vessels } = fixture(t);
|
||||
cockpit.enter();
|
||||
@@ -443,7 +513,7 @@ test("turning off the ridden aircraft's layer ends the cockpit", async (t) => {
|
||||
const { cockpit, viewer, aircraft, disableFlights } = fixture(t, {
|
||||
aircraftInfo,
|
||||
});
|
||||
viewer.trackedEntity = aircraft;
|
||||
followEntity(viewer, aircraft);
|
||||
assert.equal(cockpit.enter({ kind: 'aircraft' }), true);
|
||||
await settle();
|
||||
cockpit.update();
|
||||
@@ -846,7 +916,7 @@ test('arrows do nothing new in an aircraft cockpit', async (t) => {
|
||||
const { cockpit, viewer, aircraft, shots, store } = fixture(t, {
|
||||
aircraftInfo,
|
||||
});
|
||||
viewer.trackedEntity = aircraft;
|
||||
followEntity(viewer, aircraft);
|
||||
assert.equal(cockpit.enter({ kind: 'aircraft' }), true);
|
||||
await settle();
|
||||
assert.equal(cockpit.subjectKind, 'aircraft');
|
||||
@@ -867,7 +937,7 @@ test('arrows do nothing new in an aircraft cockpit', async (t) => {
|
||||
near(after.pitchDeg, before.pitchDeg, 'the aircraft pitch', 1e-6);
|
||||
assert.deepEqual(cockpit.lookTarget, { yawDeg: 0, pitchDeg: -2 });
|
||||
assert.equal(store.instruments.look.offset, false);
|
||||
assert.equal(document.querySelector('.cockpit-look'), null);
|
||||
assert.equal(document.querySelector('.cockpit-look') === null, true);
|
||||
// The tape stays on the aircraft's heading, with no bow or stern marks.
|
||||
const centre = store.instruments.compass.find(
|
||||
(division) => division.slot === 0,
|
||||
@@ -877,7 +947,7 @@ test('arrows do nothing new in an aircraft cockpit', async (t) => {
|
||||
prograde: null,
|
||||
retrograde: null,
|
||||
});
|
||||
assert.equal(document.querySelector('.cockpit-compass-marker'), null);
|
||||
assert.equal(document.querySelector('.cockpit-compass-marker') === null, true);
|
||||
assert.doesNotMatch(
|
||||
document.querySelector('.cockpit-help').textContent,
|
||||
/ARROWS LOOK/,
|
||||
@@ -896,7 +966,7 @@ test('C neither enters nor leaves an aircraft cockpit', async (t) => {
|
||||
onGround: false,
|
||||
};
|
||||
const { cockpit, viewer, aircraft } = fixture(t, { aircraftInfo });
|
||||
viewer.trackedEntity = aircraft;
|
||||
followEntity(viewer, aircraft);
|
||||
const outside = press(cockpit, 'c');
|
||||
await settle();
|
||||
assert.equal(cockpit.active, false, 'C does not enter');
|
||||
@@ -934,6 +1004,7 @@ test('a bridge on a river above sea level rides the water, not the geoid', async
|
||||
clock.set(START_MS);
|
||||
const record = { ...RECORD, lastPositionEpoch: START_MS / 1000 };
|
||||
const river = fixture(t, { record });
|
||||
surfacesAsked.length = 0;
|
||||
const probed = [];
|
||||
// The ship's own model reads 40 m; the ring finds the river at 27 m and
|
||||
// a quay at 33 m.
|
||||
@@ -957,6 +1028,10 @@ test('a bridge on a river above sea level rides the water, not the geoid', async
|
||||
0.5,
|
||||
);
|
||||
assert.equal(probed[0], 9, 'the ship and eight probes around it');
|
||||
// The drawn surface, the globe's terrain included, as the scene's own
|
||||
// sample read it.
|
||||
assert.ok(surfacesAsked.length > 0);
|
||||
assert.deepEqual([...new Set(surfacesAsked)], ['surface']);
|
||||
const reads = probed.length;
|
||||
frames(river.cockpit, clock, river.shots, 20);
|
||||
await settle();
|
||||
@@ -1288,7 +1363,7 @@ test('a ship with neither heading nor course makes up no direction', async (t) =
|
||||
prograde: null,
|
||||
retrograde: null,
|
||||
});
|
||||
assert.equal(document.querySelector('.cockpit-compass-marker'), null);
|
||||
assert.equal(document.querySelector('.cockpit-compass-marker') === null, true);
|
||||
assert.match(
|
||||
$('.cockpit-visor-status-right').textContent,
|
||||
/NO HEADING · AIS/,
|
||||
@@ -1544,7 +1619,7 @@ test('a followed aircraft keeps its own double-click hit area', async (t) => {
|
||||
onGround: false,
|
||||
};
|
||||
const { cockpit, viewer, aircraft } = fixture(t, { aircraftInfo });
|
||||
viewer.trackedEntity = aircraft;
|
||||
followEntity(viewer, aircraft);
|
||||
heightSensitiveProjection(viewer);
|
||||
// Drawn at (400, -2700) as the press begins, at (600, -2700) by the
|
||||
// double-click: a click there is not on the aircraft.
|
||||
@@ -1570,7 +1645,7 @@ test("a ship's double-click memory does not carry over to an aircraft followed s
|
||||
// The press finds the ship at (400, 300).
|
||||
cockpit.onScenePointerDown(1000);
|
||||
// Within the memory, an aircraft is followed, drawn elsewhere.
|
||||
viewer.trackedEntity = aircraft;
|
||||
followEntity(viewer, aircraft);
|
||||
heightSensitiveProjection(viewer, { x: 900 });
|
||||
assert.equal(cockpit.onSceneDoubleClick({ x: 400, y: 300 }, 1250), false);
|
||||
assert.equal(cockpit.active, false);
|
||||
|
||||
@@ -164,7 +164,7 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
!Number.isFinite(info.longitude)
|
||||
)
|
||||
return;
|
||||
const subjectId = `${info.layerId || 'aircraft'}:${info.icao24 || (info.kind === 'vessel' ? info.id : '') || info.noradId || info.registration || info.callsign || 'unknown'}`;
|
||||
const subjectId = `${info.layerId || 'aircraft'}:${info.icao24 || (info.kind === 'vessel' || info.generic === true ? info.id : '') || info.noradId || info.registration || info.callsign || 'unknown'}`;
|
||||
if (subjectId !== this.regionalBriefSubjectId) {
|
||||
this.regionalBriefAbort?.abort();
|
||||
this.regionalBriefAbort = null;
|
||||
|
||||
+294
-180
@@ -1,8 +1,30 @@
|
||||
/** Camera placement, ground acquisition and motion correction for the Cockpit controller. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { cameraOf, findFrame, findQuery } from '../render/rendererOf.js';
|
||||
import { heightsOf } from '../queries/heights.js';
|
||||
import { followedPosition, isFollowing } from '../data/followed.js';
|
||||
import { readEntityRecord } from '../data/entityRecords.js';
|
||||
import { trackedEntityDrawn } from './cockpitTrackingController.js';
|
||||
import {
|
||||
add,
|
||||
clone,
|
||||
eastNorthUp,
|
||||
frameVector,
|
||||
fromDegrees,
|
||||
fromRadians,
|
||||
magnitude,
|
||||
normalize,
|
||||
scale,
|
||||
sub,
|
||||
toCartographicRadians,
|
||||
toDegrees,
|
||||
toRadians,
|
||||
vec,
|
||||
} from '../geo/index.js';
|
||||
import {
|
||||
cockpitAnchorCorrectionStep,
|
||||
cockpitGroundSafeHeight,
|
||||
easeCockpitLift,
|
||||
cockpitSubjectStepSec,
|
||||
cockpitSurfaceWaitExpired,
|
||||
cockpitUiUpdateDue,
|
||||
slewHeading,
|
||||
@@ -16,6 +38,7 @@ import {
|
||||
waterlineProbePoints,
|
||||
} from '../cockpitSubjects.js';
|
||||
import { easeLook } from '../cockpitLook.js';
|
||||
import { cockpitSubjectFrame } from '../cockpitSubjectProviders.js';
|
||||
import {
|
||||
COCKPIT_HEADING_SLEW_DPS,
|
||||
COCKPIT_FORWARD_OFFSET_M,
|
||||
@@ -28,6 +51,17 @@ import {
|
||||
COCKPIT_GROUND_WAIT_TIMEOUT_MS,
|
||||
} from './cockpitPresentation.js';
|
||||
|
||||
/**
|
||||
* Where the aircraft Cockpit flies is now: its follow target's position at
|
||||
* scene time (what the drawn entity's position reads), or, for a target
|
||||
* with none, where it is shown.
|
||||
*/
|
||||
export function trackedPositionNow(viewer, followed) {
|
||||
if (typeof followed?.position === 'function')
|
||||
return followed.position(findFrame(viewer)?.time() ?? Date.now());
|
||||
return followedPosition(viewer, followed);
|
||||
}
|
||||
|
||||
/** The aircraft eye: just ahead of and above the reported position. */
|
||||
const AIRCRAFT_CAMERA_PROFILE = Object.freeze({
|
||||
forwardM: COCKPIT_FORWARD_OFFSET_M,
|
||||
@@ -53,6 +87,10 @@ export function update() {
|
||||
}
|
||||
|
||||
const nowMs = performance.now();
|
||||
if (this.subjectProvider) {
|
||||
updateSubject.call(this, nowMs);
|
||||
return;
|
||||
}
|
||||
if (this.subjectKind === 'vessel') {
|
||||
updateVessel.call(this, nowMs);
|
||||
return;
|
||||
@@ -70,7 +108,7 @@ export function update() {
|
||||
if (
|
||||
!info ||
|
||||
!this.trackedEntity ||
|
||||
!this.viewer.entities.contains(this.trackedEntity)
|
||||
!trackedEntityDrawn.call(this, this.trackedEntity)
|
||||
) {
|
||||
if (nowMs < this.contextNavigationDeadlineMs) return;
|
||||
this.exit({ restoreTracking: false });
|
||||
@@ -86,10 +124,7 @@ export function update() {
|
||||
return;
|
||||
this.lastCameraUpdateMs = nowMs;
|
||||
|
||||
const target = this.trackedEntity.position.getValue(
|
||||
this.viewer.clock.currentTime,
|
||||
this.scratchTarget,
|
||||
);
|
||||
const target = trackedPositionNow(this.viewer, this.trackedFollow);
|
||||
if (!target) return;
|
||||
const dtSec = Math.min(0.1, Math.max(0, (nowMs - this.lastFrameMs) / 1000));
|
||||
this.lastFrameMs = nowMs;
|
||||
@@ -126,20 +161,20 @@ function vesselSurfaceM(info, nowMs, at = info) {
|
||||
const seaM = Number.isFinite(info.seaSurfaceHeightM)
|
||||
? info.seaSurfaceHeightM
|
||||
: 0;
|
||||
const scene = this.viewer.scene;
|
||||
const query = findQuery(this.viewer) ? heightsOf(this.viewer) : null;
|
||||
let read =
|
||||
this.vesselWaterline?.vesselId === info.id ? this.vesselWaterline : null;
|
||||
if (
|
||||
typeof scene?.sampleHeightMostDetailed === 'function' &&
|
||||
query &&
|
||||
(!read || nowMs - read.sampledMs >= VESSEL_WATERLINE_REFRESH_MS)
|
||||
) {
|
||||
const probes = waterlineProbePoints(at.latitude, at.longitude).map(
|
||||
({ lat, lon }) => Cesium.Cartographic.fromDegrees(lon, lat),
|
||||
({ lat, lon }) => ({ lon, lat }),
|
||||
);
|
||||
if (!read) {
|
||||
read = {
|
||||
vesselId: info.id,
|
||||
heightM: loadedWaterlineM(scene, probes, seaM),
|
||||
heightM: loadedWaterlineM(query, probes, seaM),
|
||||
sampledMs: nowMs,
|
||||
// Whether a full-detail read has answered for this ship.
|
||||
landed: false,
|
||||
@@ -149,7 +184,7 @@ function vesselSurfaceM(info, nowMs, at = info) {
|
||||
} else {
|
||||
read.sampledMs = nowMs;
|
||||
if (read.inFlight && !read.landed) {
|
||||
const loadedM = loadedWaterlineM(scene, probes, seaM);
|
||||
const loadedM = loadedWaterlineM(query, probes, seaM);
|
||||
// Taking a river back to the sea is the full-detail read's to say.
|
||||
const lowers =
|
||||
Number.isFinite(read.heightM) &&
|
||||
@@ -158,7 +193,7 @@ function vesselSurfaceM(info, nowMs, at = info) {
|
||||
if (Number.isFinite(loadedM) && !lowers) read.heightM = loadedM;
|
||||
}
|
||||
}
|
||||
if (!read.inFlight) readWaterline.call(this, read, scene, probes, seaM);
|
||||
if (!read.inFlight) readWaterline.call(this, read, query, probes, seaM);
|
||||
}
|
||||
return read && Number.isFinite(read.heightM)
|
||||
? Math.max(seaM, read.heightM)
|
||||
@@ -166,25 +201,26 @@ function vesselSurfaceM(info, nowMs, at = info) {
|
||||
}
|
||||
|
||||
/** Start one full-detail water read for `read`; its answer lands on it. */
|
||||
function readWaterline(read, scene, probes, seaM) {
|
||||
function readWaterline(read, query, probes, seaM) {
|
||||
read.inFlight = true;
|
||||
Promise.resolve()
|
||||
.then(() => scene.sampleHeightMostDetailed(probes))
|
||||
.then(
|
||||
(samples) => {
|
||||
if (this.vesselWaterline !== read) return;
|
||||
read.inFlight = false;
|
||||
// However late it lands, it applies; one that sampled nothing (tiles
|
||||
// not loaded yet) is no answer and keeps the height already read.
|
||||
const heights = (samples || []).map((sample) => sample?.height);
|
||||
if (!heights.some(Number.isFinite)) return;
|
||||
read.landed = true;
|
||||
read.heightM = vesselWaterlineM(seaM, heights);
|
||||
},
|
||||
() => {
|
||||
if (this.vesselWaterline === read) read.inFlight = false;
|
||||
},
|
||||
);
|
||||
// An async read: a failure arrives as a rejection, never a throw here.
|
||||
// The drawn surface, globe included, as the scene's own sample read it:
|
||||
// a lake on a globe map stands on its terrain.
|
||||
query.batch(probes).then(
|
||||
(samples) => {
|
||||
if (this.vesselWaterline !== read) return;
|
||||
read.inFlight = false;
|
||||
// However late it lands, it applies; one that sampled nothing (tiles
|
||||
// not loaded yet) is no answer and keeps the height already read.
|
||||
const heights = samples || [];
|
||||
if (!heights.some(Number.isFinite)) return;
|
||||
read.landed = true;
|
||||
read.heightM = vesselWaterlineM(seaM, heights);
|
||||
},
|
||||
() => {
|
||||
if (this.vesselWaterline === read) read.inFlight = false;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -193,11 +229,9 @@ function readWaterline(read, scene, probes, seaM) {
|
||||
* probe met loaded geometry: nothing sampled is no answer, not the sea, so it
|
||||
* never undoes a river height a full read set.
|
||||
*/
|
||||
function loadedWaterlineM(scene, probes, seaM) {
|
||||
if (typeof scene.sampleHeight !== 'function') return null;
|
||||
if (scene.sampleHeightSupported === false) return null;
|
||||
function loadedWaterlineM(query, probes, seaM) {
|
||||
try {
|
||||
const heights = probes.map((probe) => scene.sampleHeight(probe));
|
||||
const heights = probes.map((probe) => query.now(probe));
|
||||
if (!heights.some(Number.isFinite)) return null;
|
||||
return vesselWaterlineM(seaM, heights);
|
||||
} catch {
|
||||
@@ -212,9 +246,10 @@ function loadedWaterlineM(scene, probes, seaM) {
|
||||
* correction each new fix brings.
|
||||
*/
|
||||
function updateVessel(nowMs) {
|
||||
// Tracking an aircraft from the bridge clears the vessel selection; end the
|
||||
// bridge and leave Cesium tracking with that aircraft.
|
||||
if (this.viewer.trackedEntity?.position) {
|
||||
// Tracking anything from the bridge (an aircraft, a satellite, a site)
|
||||
// takes the camera: entry stopped every follow, so any follow now is
|
||||
// another's. End the bridge and leave the camera following it.
|
||||
if (isFollowing(this.viewer)) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
@@ -247,13 +282,11 @@ function updateVessel(nowMs) {
|
||||
);
|
||||
// The radar centres here too, so it agrees with the view out the window.
|
||||
this.vesselFix = fix;
|
||||
const target = Cesium.Cartesian3.fromDegrees(
|
||||
const target = fromDegrees(
|
||||
fix.longitude,
|
||||
fix.latitude,
|
||||
// Read the water where the ship is now, not at its last report.
|
||||
vesselSurfaceM.call(this, info, nowMs, fix),
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
this.scratchTarget,
|
||||
);
|
||||
// The target advances in wall-clock time, so the anchor must too: the
|
||||
// aircraft path's 0.1 s step cap would leave a slow-frame or hitching bridge
|
||||
@@ -297,10 +330,123 @@ function updateVessel(nowMs) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drive the camera from an application provider's subject: read its frame,
|
||||
* stand the eye `eye.upM` above `heightM` (the shared floor where the frame
|
||||
* gives none) and slew toward its heading. A frame that is null, malformed or
|
||||
* for another subject ends the view, as an aircraft tracked meanwhile does.
|
||||
* The update runs on the provider's `cameraIntervalMs` (0: every frame), and
|
||||
* its rates advance by the time that interval spans (cockpitSubjectStepSec).
|
||||
*/
|
||||
function updateSubject(nowMs) {
|
||||
const provider = this.subjectProvider;
|
||||
if (isFollowing(this.viewer)) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
const intervalMs = provider.cameraIntervalMs ?? COCKPIT_CAMERA_UPDATE_MS;
|
||||
if (!cockpitUiUpdateDue(nowMs, this.lastCameraUpdateMs, intervalMs)) return;
|
||||
this.lastCameraUpdateMs = nowMs;
|
||||
const frame = cockpitSubjectFrame(
|
||||
this.callSubject(provider, 'read', [nowMs, this.subjectContext()], null),
|
||||
this.subjectId,
|
||||
);
|
||||
if (!frame) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
this.lastSubjectFrame = frame;
|
||||
let heightM = frame.heightM;
|
||||
if (heightM === null) {
|
||||
this.services.warmGroundFloor?.([
|
||||
{ lat: frame.latitude, lon: frame.longitude },
|
||||
]);
|
||||
const floorM = this.services.cachedGroundFloor?.(
|
||||
frame.latitude,
|
||||
frame.longitude,
|
||||
);
|
||||
// A frame with no height stands on the shared floor; while that is cold
|
||||
// it keeps the height it last stood at.
|
||||
heightM = Number.isFinite(floorM) ? floorM : this.subjectHeightM;
|
||||
}
|
||||
if (!Number.isFinite(heightM)) {
|
||||
// Nothing to stand on yet, from the first frame: the camera stays where
|
||||
// it is while the floor is acquired, its HUD saying so, rather than
|
||||
// standing on the ellipsoid (kilometres underground on a plateau). The
|
||||
// wait is bounded as the built-in views' is. Unlike a parked aircraft,
|
||||
// whose fallback is its own reported altitude, such a subject has no
|
||||
// height at all to fall back to: any number would be a guess, so the
|
||||
// view ends and the provider gets its subject back.
|
||||
if (!this.surfaceWaitStartedMs) this.surfaceWaitStartedMs = nowMs;
|
||||
if (
|
||||
cockpitSurfaceWaitExpired(
|
||||
nowMs,
|
||||
this.surfaceWaitStartedMs,
|
||||
COCKPIT_GROUND_WAIT_TIMEOUT_MS,
|
||||
)
|
||||
) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
this.surfaceAcquiring = true;
|
||||
if (
|
||||
cockpitUiUpdateDue(nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS)
|
||||
) {
|
||||
this.lastHudUpdateMs = nowMs;
|
||||
this.updateHud(this.subjectInfo(frame), nowMs);
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.surfaceWaitStartedMs = 0;
|
||||
this.surfaceAcquiring = false;
|
||||
this.subjectHeightM = heightM;
|
||||
const target = fromDegrees(frame.longitude, frame.latitude, heightM);
|
||||
const dtSec = cockpitSubjectStepSec(nowMs - this.lastFrameMs, intervalMs);
|
||||
this.lastFrameMs = nowMs;
|
||||
if (frame.headingDeg !== null) {
|
||||
const rate = provider.headingSlewDps ?? COCKPIT_HEADING_SLEW_DPS;
|
||||
this.heading =
|
||||
rate === Infinity
|
||||
? frame.headingDeg
|
||||
: slewHeading(
|
||||
this.heading ?? frame.headingDeg,
|
||||
frame.headingDeg,
|
||||
rate * dtSec,
|
||||
);
|
||||
}
|
||||
let look = null;
|
||||
if (provider.look) {
|
||||
this.lookView = easeLook(
|
||||
this.lookView,
|
||||
this.lookTarget,
|
||||
nowMs - (this.lookLastMs || nowMs),
|
||||
);
|
||||
this.lookLastMs = nowMs;
|
||||
look = this.lookView;
|
||||
}
|
||||
placeCamera.call(
|
||||
this,
|
||||
target,
|
||||
this.subjectInfo(frame),
|
||||
nowMs,
|
||||
dtSec,
|
||||
{
|
||||
forwardM: frame.eye.forwardM,
|
||||
upM: frame.eye.upM,
|
||||
pitchDeg: frame.eye.pitchDeg,
|
||||
minClearanceM: frame.eye.minClearanceM,
|
||||
},
|
||||
look,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Place the camera for one update: advance the inertial anchor, clamp it and
|
||||
* the eye against the rendered surface, and look along the slewed heading.
|
||||
* @param {Cesium.Cartesian3} target Authoritative subject position.
|
||||
* A subject with `anchor: 'exact'` keeps the anchor on its target (its layer
|
||||
* already moves it smoothly), and one with `groundClamp: false` (inside a
|
||||
* structure, say) is never pushed up to the floor: a lift it had eases out.
|
||||
* @param {{x: number, y: number, z: number}} target Authoritative subject position.
|
||||
* @param {object} info Subject info; `motionCourse` (when present) is the
|
||||
* direction the subject moves, otherwise it moves where it faces.
|
||||
* @param {number} nowMs Frame time.
|
||||
@@ -314,8 +460,9 @@ function updateVessel(nowMs) {
|
||||
*/
|
||||
function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
if (!this.cockpitAnchorValid) {
|
||||
Cesium.Cartesian3.clone(target, this.cockpitAnchor);
|
||||
this.cockpitAnchor = clone(target);
|
||||
this.cockpitAnchorValid = true;
|
||||
this.subjectLiftM = null;
|
||||
}
|
||||
|
||||
// First-person motion cannot use the delayed feed correction as a raw
|
||||
@@ -325,73 +472,49 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
// display position at a bounded rate. This preserves the layer's required
|
||||
// 15/30-second interpolation and per-frame cache without exposing its
|
||||
// sample-boundary corrections to the camera.
|
||||
const headingRad = Cesium.Math.toRadians(this.heading ?? 0);
|
||||
const headingRad = toRadians(this.heading ?? 0);
|
||||
const courseRad = Number.isFinite(info.motionCourse)
|
||||
? Cesium.Math.toRadians(info.motionCourse)
|
||||
? toRadians(info.motionCourse)
|
||||
: headingRad;
|
||||
const pitchRad = Cesium.Math.toRadians(
|
||||
look ? look.pitchDeg : profile.pitchDeg,
|
||||
);
|
||||
const pitchRad = toRadians(look ? look.pitchDeg : profile.pitchDeg);
|
||||
const viewHeadingRad = look
|
||||
? Cesium.Math.toRadians((this.heading ?? 0) + look.yawDeg)
|
||||
? toRadians((this.heading ?? 0) + look.yawDeg)
|
||||
: headingRad;
|
||||
const speedMps = Number.isFinite(info.velocityMps)
|
||||
? Math.max(0, info.velocityMps)
|
||||
: 0;
|
||||
|
||||
if (info.stale) {
|
||||
const groundClamp = info.groundClamp !== false;
|
||||
if (info.stale || info.anchor === 'exact') {
|
||||
// A feed backoff has no authoritative velocity epoch to advance from.
|
||||
// Hold the cockpit on the exact layer-rendered position so the camera
|
||||
// cannot coast away while the icon correctly remains fixed.
|
||||
Cesium.Cartesian3.clone(target, this.cockpitAnchor);
|
||||
this.cockpitAnchor = clone(target);
|
||||
} else {
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
const horizontal = normalize(
|
||||
frameVector(
|
||||
eastNorthUp(this.cockpitAnchor),
|
||||
vec(Math.sin(courseRad), Math.cos(courseRad), 0),
|
||||
),
|
||||
);
|
||||
this.cockpitAnchor = add(
|
||||
this.cockpitAnchor,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
this.scratchEnu,
|
||||
);
|
||||
this.scratchLocal.x = Math.sin(courseRad);
|
||||
this.scratchLocal.y = Math.cos(courseRad);
|
||||
this.scratchLocal.z = 0;
|
||||
Cesium.Matrix4.multiplyByPointAsVector(
|
||||
this.scratchEnu,
|
||||
this.scratchLocal,
|
||||
this.scratchHorizontal,
|
||||
);
|
||||
Cesium.Cartesian3.normalize(this.scratchHorizontal, this.scratchHorizontal);
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
this.scratchHorizontal,
|
||||
speedMps * dtSec,
|
||||
this.scratchAdvance,
|
||||
);
|
||||
Cesium.Cartesian3.add(
|
||||
this.cockpitAnchor,
|
||||
this.scratchAdvance,
|
||||
this.cockpitAnchor,
|
||||
);
|
||||
Cesium.Cartesian3.subtract(
|
||||
target,
|
||||
this.cockpitAnchor,
|
||||
this.scratchCorrection,
|
||||
);
|
||||
const correctionDistanceM = Cesium.Cartesian3.magnitude(
|
||||
this.scratchCorrection,
|
||||
scale(horizontal, speedMps * dtSec),
|
||||
);
|
||||
const correction = sub(target, this.cockpitAnchor);
|
||||
const correctionDistanceM = magnitude(correction);
|
||||
// An application subject's step is already bounded by its own update
|
||||
// interval (cockpitSubjectStepSec); the built-in views keep the 0.1 s.
|
||||
const correctionStepM = cockpitAnchorCorrectionStep(
|
||||
correctionDistanceM,
|
||||
speedMps,
|
||||
dtSec,
|
||||
info.generic === true ? dtSec : undefined,
|
||||
);
|
||||
if (correctionStepM > 0 && correctionDistanceM > 0) {
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
this.scratchCorrection,
|
||||
correctionStepM / correctionDistanceM,
|
||||
this.scratchCorrection,
|
||||
);
|
||||
Cesium.Cartesian3.add(
|
||||
this.cockpitAnchor,
|
||||
this.scratchCorrection,
|
||||
this.cockpitAnchor = add(
|
||||
this.cockpitAnchor,
|
||||
scale(correction, correctionStepM / correctionDistanceM),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -401,23 +524,15 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
// between fixes. Clamp it against the same mesh-first shared floor used by
|
||||
// aircraft rendering. For a slow contact whose floor cell is still cold,
|
||||
// its already-clamped render position is a conservative temporary floor.
|
||||
const anchorCartographic = Cesium.Cartographic.fromCartesian(
|
||||
this.cockpitAnchor,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
this.scratchAnchorCartographic,
|
||||
);
|
||||
const targetCartographic = Cesium.Cartographic.fromCartesian(
|
||||
target,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
this.scratchTargetCartographic,
|
||||
);
|
||||
const anchorCartographic = toCartographicRadians(this.cockpitAnchor);
|
||||
const targetCartographic = toCartographicRadians(target);
|
||||
// A bridge's target is its fix dead-reckoned up to minutes ahead: read
|
||||
// the floor where the ship is now, as its water is.
|
||||
const floorAt =
|
||||
info.kind === 'vessel'
|
||||
info.kind === 'vessel' && targetCartographic
|
||||
? {
|
||||
latitude: Cesium.Math.toDegrees(targetCartographic.latitude),
|
||||
longitude: Cesium.Math.toDegrees(targetCartographic.longitude),
|
||||
latitude: toDegrees(targetCartographic.lat),
|
||||
longitude: toDegrees(targetCartographic.lon),
|
||||
}
|
||||
: info;
|
||||
let cockpitFloorM = this.services.cachedGroundFloor(
|
||||
@@ -440,11 +555,11 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
)
|
||||
) {
|
||||
this.lastGroundProbeMs = nowMs;
|
||||
const viewerCartographic = this.viewer.camera.positionCartographic;
|
||||
this.services.sampleMeshFloorCells(this.viewer.scene, groundPoint, {
|
||||
excludeObjects: [this.trackedEntity],
|
||||
viewerLat: Cesium.Math.toDegrees(viewerCartographic.latitude),
|
||||
viewerLon: Cesium.Math.toDegrees(viewerCartographic.longitude),
|
||||
const eye = cameraOf(this.viewer).pose();
|
||||
this.services.sampleMeshFloorCells(this.viewer, groundPoint, {
|
||||
sets: readEntityRecord(this.trackedEntity)?.groundSets?.() ?? [],
|
||||
viewerLat: eye.lat,
|
||||
viewerLon: eye.lon,
|
||||
});
|
||||
}
|
||||
cockpitFloorM = this.services.cachedMeshFloor(
|
||||
@@ -498,90 +613,64 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
cockpitFloorM =
|
||||
targetCartographic.height - this.services.GROUND_FLOOR_LIFT_M;
|
||||
}
|
||||
if (anchorCartographic && Number.isFinite(cockpitFloorM)) {
|
||||
// An application subject's anchor is where its provider puts it; only its
|
||||
// eye is kept out of the floor, below.
|
||||
if (
|
||||
groundClamp &&
|
||||
info.generic !== true &&
|
||||
anchorCartographic &&
|
||||
Number.isFinite(cockpitFloorM)
|
||||
) {
|
||||
const minimumAnchorHeightM = cockpitGroundSafeHeight(
|
||||
anchorCartographic.height,
|
||||
cockpitFloorM,
|
||||
profile.minClearanceM - profile.upM,
|
||||
);
|
||||
if (minimumAnchorHeightM !== anchorCartographic.height) {
|
||||
anchorCartographic.height = minimumAnchorHeightM;
|
||||
Cesium.Ellipsoid.WGS84.cartographicToCartesian(
|
||||
anchorCartographic,
|
||||
this.cockpitAnchor,
|
||||
this.cockpitAnchor = fromRadians(
|
||||
anchorCartographic.lon,
|
||||
anchorCartographic.lat,
|
||||
minimumAnchorHeightM,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Rebuild the local frame at the stabilized anchor after advancing it.
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
this.cockpitAnchor,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
this.scratchEnu,
|
||||
const enu = eastNorthUp(this.cockpitAnchor);
|
||||
const horizontal = normalize(
|
||||
frameVector(enu, vec(Math.sin(headingRad), Math.cos(headingRad), 0)),
|
||||
);
|
||||
this.scratchLocal.x = Math.sin(headingRad);
|
||||
this.scratchLocal.y = Math.cos(headingRad);
|
||||
this.scratchLocal.z = 0;
|
||||
Cesium.Matrix4.multiplyByPointAsVector(
|
||||
this.scratchEnu,
|
||||
this.scratchLocal,
|
||||
this.scratchHorizontal,
|
||||
const forward = normalize(
|
||||
frameVector(
|
||||
enu,
|
||||
vec(
|
||||
Math.sin(viewHeadingRad) * Math.cos(pitchRad),
|
||||
Math.cos(viewHeadingRad) * Math.cos(pitchRad),
|
||||
Math.sin(pitchRad),
|
||||
),
|
||||
),
|
||||
);
|
||||
Cesium.Cartesian3.normalize(this.scratchHorizontal, this.scratchHorizontal);
|
||||
|
||||
this.scratchLocal.x = Math.sin(viewHeadingRad) * Math.cos(pitchRad);
|
||||
this.scratchLocal.y = Math.cos(viewHeadingRad) * Math.cos(pitchRad);
|
||||
this.scratchLocal.z = Math.sin(pitchRad);
|
||||
Cesium.Matrix4.multiplyByPointAsVector(
|
||||
this.scratchEnu,
|
||||
this.scratchLocal,
|
||||
this.scratchForward,
|
||||
const up = normalize(
|
||||
frameVector(
|
||||
enu,
|
||||
vec(
|
||||
-Math.sin(viewHeadingRad) * Math.sin(pitchRad),
|
||||
-Math.cos(viewHeadingRad) * Math.sin(pitchRad),
|
||||
Math.cos(pitchRad),
|
||||
),
|
||||
),
|
||||
);
|
||||
Cesium.Cartesian3.normalize(this.scratchForward, this.scratchForward);
|
||||
|
||||
this.scratchLocal.x = -Math.sin(viewHeadingRad) * Math.sin(pitchRad);
|
||||
this.scratchLocal.y = -Math.cos(viewHeadingRad) * Math.sin(pitchRad);
|
||||
this.scratchLocal.z = Math.cos(pitchRad);
|
||||
Cesium.Matrix4.multiplyByPointAsVector(
|
||||
this.scratchEnu,
|
||||
this.scratchLocal,
|
||||
this.scratchUp,
|
||||
);
|
||||
Cesium.Cartesian3.normalize(this.scratchUp, this.scratchUp);
|
||||
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
this.scratchHorizontal,
|
||||
profile.forwardM,
|
||||
this.scratchCamera,
|
||||
);
|
||||
Cesium.Cartesian3.add(
|
||||
this.cockpitAnchor,
|
||||
this.scratchCamera,
|
||||
this.scratchCamera,
|
||||
);
|
||||
Cesium.Matrix4.getTranslation(this.scratchEnu, this.scratchTarget);
|
||||
Cesium.Cartesian3.normalize(this.scratchTarget, this.scratchTarget);
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
this.scratchTarget,
|
||||
profile.upM,
|
||||
this.scratchTarget,
|
||||
);
|
||||
Cesium.Cartesian3.add(
|
||||
this.scratchCamera,
|
||||
this.scratchTarget,
|
||||
this.scratchCamera,
|
||||
let eye = add(
|
||||
add(this.cockpitAnchor, scale(horizontal, profile.forwardM)),
|
||||
scale(normalize(enu.origin), profile.upM),
|
||||
);
|
||||
|
||||
// Recheck at the final forward-offset camera coordinate because a taxiing
|
||||
// aircraft can cross into an adjacent coarse floor cell between updates.
|
||||
const cameraCartographic = Cesium.Cartographic.fromCartesian(
|
||||
this.scratchCamera,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
this.scratchCameraCartographic,
|
||||
);
|
||||
if (cameraCartographic) {
|
||||
const cameraLat = Cesium.Math.toDegrees(cameraCartographic.latitude);
|
||||
const cameraLon = Cesium.Math.toDegrees(cameraCartographic.longitude);
|
||||
const cameraCartographic = toCartographicRadians(eye);
|
||||
if (groundClamp && cameraCartographic) {
|
||||
const cameraLat = toDegrees(cameraCartographic.lat);
|
||||
const cameraLon = toDegrees(cameraCartographic.lon);
|
||||
const cameraFloorM = this.services.cachedGroundFloor(cameraLat, cameraLon);
|
||||
if (Number.isFinite(cameraFloorM)) {
|
||||
cockpitFloorM = Math.max(
|
||||
@@ -589,23 +678,48 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
cameraFloorM,
|
||||
);
|
||||
}
|
||||
const safeHeightM = cockpitGroundSafeHeight(
|
||||
let safeHeightM = cockpitGroundSafeHeight(
|
||||
cameraCartographic.height,
|
||||
cockpitFloorM,
|
||||
profile.minClearanceM,
|
||||
);
|
||||
// An application subject's eye rides its provider's smoothed height:
|
||||
// the clearance over the coarse, refining floor eases in and out
|
||||
// rather than jumping at each cell (easeCockpitLift).
|
||||
if (info.generic === true) {
|
||||
const hardM =
|
||||
cockpitGroundSafeHeight(cameraCartographic.height, cockpitFloorM, 0) -
|
||||
cameraCartographic.height;
|
||||
this.subjectLiftM = easeCockpitLift(
|
||||
this.subjectLiftM,
|
||||
safeHeightM - cameraCartographic.height,
|
||||
hardM,
|
||||
dtSec,
|
||||
);
|
||||
safeHeightM = cameraCartographic.height + this.subjectLiftM;
|
||||
}
|
||||
if (safeHeightM !== cameraCartographic.height) {
|
||||
cameraCartographic.height = safeHeightM;
|
||||
Cesium.Ellipsoid.WGS84.cartographicToCartesian(
|
||||
cameraCartographic,
|
||||
this.scratchCamera,
|
||||
eye = fromRadians(
|
||||
cameraCartographic.lon,
|
||||
cameraCartographic.lat,
|
||||
safeHeightM,
|
||||
);
|
||||
}
|
||||
} else if (info.generic === true) {
|
||||
// Inside a structure the floor holds the eye up no more: the lift it gave
|
||||
// goes at the rate it came (easeCockpitLift), never at once.
|
||||
this.subjectLiftM = easeCockpitLift(this.subjectLiftM, 0, 0, dtSec);
|
||||
if (cameraCartographic && this.subjectLiftM > 0)
|
||||
eye = fromRadians(
|
||||
cameraCartographic.lon,
|
||||
cameraCartographic.lat,
|
||||
cameraCartographic.height + this.subjectLiftM,
|
||||
);
|
||||
}
|
||||
|
||||
this.viewer.camera.setView({
|
||||
destination: this.scratchCamera,
|
||||
orientation: { direction: this.scratchForward, up: this.scratchUp },
|
||||
cameraOf(this.viewer).setView({
|
||||
destination: eye,
|
||||
orientation: { direction: forward, up },
|
||||
});
|
||||
if (cockpitUiUpdateDue(nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS)) {
|
||||
this.lastHudUpdateMs = nowMs;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Contact readouts and nearby-signal presentation for the Cockpit controller. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { toLonLatH } from '../geo/index.js';
|
||||
import { formatNumber, t, tn } from '../i18n/index.js';
|
||||
import { sourceStatusLabel } from './layerNames.js';
|
||||
import { unitLabel } from './unitLabels.js';
|
||||
@@ -186,14 +186,9 @@ export function updateContext(info, heading) {
|
||||
Number.isFinite(info.latitude) &&
|
||||
Number.isFinite(info.longitude)
|
||||
) {
|
||||
const cartographic = Cesium.Cartographic.fromCartesian(closest.position);
|
||||
const bearing = cartographic
|
||||
? bearingBetweenCoordinates(
|
||||
info.latitude,
|
||||
info.longitude,
|
||||
Cesium.Math.toDegrees(cartographic.latitude),
|
||||
Cesium.Math.toDegrees(cartographic.longitude),
|
||||
)
|
||||
const at = toLonLatH(closest.position);
|
||||
const bearing = at
|
||||
? bearingBetweenCoordinates(info.latitude, info.longitude, at.lat, at.lon)
|
||||
: null;
|
||||
relative = relativeBearing(bearing, heading);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
showContextCard,
|
||||
updateContext,
|
||||
} from './cockpitContext.js';
|
||||
import { fromDegrees } from '../geo/index.js';
|
||||
import { createContextState } from './cockpitContextState.js';
|
||||
import {
|
||||
dropCockpitSignal,
|
||||
@@ -173,6 +174,40 @@ test('a snapshot fills the card and keeps classes other code sets', async (t) =>
|
||||
assert.equal(layouts.length, 1);
|
||||
});
|
||||
|
||||
test('when the tracked aircraft is the subject, the bearing points at the nearest contact', async (t) => {
|
||||
const tracked = { layerId: 'flights', id: 'abc123', label: 'ABC123' };
|
||||
const contact = (lon, lat) =>
|
||||
snapshot({
|
||||
subject: tracked,
|
||||
cohorts: [
|
||||
{
|
||||
id: 'flights',
|
||||
label: 'Flights',
|
||||
count: 1,
|
||||
relationship: 'OBSERVED',
|
||||
nearest: [
|
||||
{ id: 'N1', distanceM: 96_000, position: fromDegrees(lon, lat) },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const { text, owner } = fixture(t, contact(-96, 30));
|
||||
// Due east of a north-facing nose.
|
||||
updateContext.call(owner, INFO, 0);
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-context-bearing'), 'R 090°');
|
||||
// Due north: inside the dead-ahead cone.
|
||||
owner.snapshot = contact(-97, 31);
|
||||
updateContext.call(owner, INFO, 0);
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-context-bearing'), 'AHEAD');
|
||||
// Due west of a nose turned to the north-east.
|
||||
owner.snapshot = contact(-98, 30);
|
||||
updateContext.call(owner, INFO, 45);
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-context-bearing'), 'L 135°');
|
||||
});
|
||||
|
||||
test('each count names the provider its snapshot reports, with its feed state', async (t) => {
|
||||
const reported = snapshot();
|
||||
reported.cohorts[0].source = 'adsb.lol';
|
||||
|
||||
+99
-23
@@ -1,14 +1,22 @@
|
||||
/** Coordinate Cockpit lifecycle through supplied aircraft, terrain, rendering and briefing operations. */
|
||||
import { onFollowChanged } from '../data/followed.js';
|
||||
import { canvasOf, frameOf } from '../render/rendererOf.js';
|
||||
import {
|
||||
readAircraftInfo,
|
||||
readSatelliteInfo,
|
||||
readVesselInfo,
|
||||
readSubjectCandidate,
|
||||
readSubjectLayerId,
|
||||
subjectContext,
|
||||
subjectInfo,
|
||||
entryCandidates,
|
||||
resolveEntry,
|
||||
resolveEntryKind,
|
||||
dispatchCockpitModeChanged,
|
||||
toggleTrackedTr3b,
|
||||
syncTr3bToggle,
|
||||
syncEntry,
|
||||
refreshSubjectWords,
|
||||
publishPresenceView,
|
||||
navigateContext,
|
||||
_adoptTrackedEntity,
|
||||
@@ -30,6 +38,7 @@ import {
|
||||
import {
|
||||
onOrbitalClick,
|
||||
onOrbitalDoubleClick,
|
||||
orbitalSiteUnder,
|
||||
routeSceneClick,
|
||||
toggleOrbitalFocus,
|
||||
} from './cockpitOrbitalFocus.js';
|
||||
@@ -100,7 +109,7 @@ import {
|
||||
import { DEFAULT_RADAR_RANGE_NM, nextRadarRange } from '../cockpitRadar.js';
|
||||
import { VESSEL_BRIDGE_PITCH_DEG } from '../cockpitSubjects.js';
|
||||
import { stepLook } from '../cockpitLook.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createCockpitSubjectCaller } from '../cockpitSubjectProviders.js';
|
||||
|
||||
/** Whether the user asked for reduced motion: look turns then jump. */
|
||||
function prefersReducedMotion() {
|
||||
@@ -120,6 +129,8 @@ export class CockpitViewController {
|
||||
isEntryAllowed = null,
|
||||
isBridgeEntryAllowed = null,
|
||||
isOrbitEntryAllowed = null,
|
||||
subjectProviders = [],
|
||||
isSubjectEntryAllowed = null,
|
||||
isUtilityDisclosureOpen = null,
|
||||
onEntered = null,
|
||||
onExited = null,
|
||||
@@ -128,16 +139,37 @@ export class CockpitViewController {
|
||||
publish = {},
|
||||
} = {},
|
||||
) {
|
||||
// Before anything subscribes: a viewer with no frame port throws here.
|
||||
const frame = frameOf(viewer);
|
||||
this.viewer = viewer;
|
||||
this.services = services;
|
||||
this.destroyed = false;
|
||||
this.disposed = false;
|
||||
this.active = false;
|
||||
/** Gives camera input back; held from enter to exit. */
|
||||
this.releaseCameraInput = null;
|
||||
/**
|
||||
* 'aircraft', 'vessel' or 'satellite' while active; which subject the
|
||||
* camera rides.
|
||||
* 'aircraft', 'vessel', 'satellite' or a provider's kind while active;
|
||||
* which subject the camera rides.
|
||||
*/
|
||||
this.subjectKind = null;
|
||||
/**
|
||||
* The application's subject providers (cockpitSubjectProviders.js),
|
||||
* checked by the coordinator; the one ridden while active, else null.
|
||||
*/
|
||||
this.subjectProviders = Array.isArray(subjectProviders)
|
||||
? subjectProviders
|
||||
: [];
|
||||
this.subjectProvider = null;
|
||||
/** The ridden provider subject's last frame and normalized HUD view. */
|
||||
this.lastSubjectFrame = null;
|
||||
this.subjectHud = null;
|
||||
/** The Live Signals rows the provider's HUD view pushed. */
|
||||
this.subjectSignalKeys = new Set();
|
||||
/** Provider methods run through one guard: a throw warns once. */
|
||||
this.callSubject = createCockpitSubjectCaller();
|
||||
/** The look's rest pitch for a provider's view; null on a bridge. */
|
||||
this.lookRestPitchDeg = null;
|
||||
/**
|
||||
* The vessel subject's id or the satellite's NORAD id; aircraft are
|
||||
* identified by trackedEntity.
|
||||
@@ -149,6 +181,8 @@ export class CockpitViewController {
|
||||
*/
|
||||
this.orbital = null;
|
||||
this.trackedEntity = null;
|
||||
/** What the camera followed before Cockpit took it, to follow again. */
|
||||
this.trackedFollow = null;
|
||||
this.trackedEntityWasShown = true;
|
||||
this.heading = null;
|
||||
this.lastFrameMs = 0;
|
||||
@@ -160,6 +194,10 @@ export class CockpitViewController {
|
||||
this.surfaceWaitStartedMs = 0;
|
||||
this.surfaceAcquiring = false;
|
||||
this.surfaceFallback = false;
|
||||
/** The height an application subject's frame last stood at (m). */
|
||||
this.subjectHeightM = null;
|
||||
/** The ground clamp's eased lift under that subject's eye (m). */
|
||||
this.subjectLiftM = null;
|
||||
/**
|
||||
* Where the bridge view is turned to (`lookTarget`) and where the camera
|
||||
* looks on its way there (`lookView`): yaw off the bow, starboard
|
||||
@@ -203,6 +241,11 @@ export class CockpitViewController {
|
||||
typeof isOrbitEntryAllowed === 'function'
|
||||
? isOrbitEntryAllowed
|
||||
: () => false;
|
||||
// Nor a provider's subject without a gate for it.
|
||||
this.isSubjectEntryAllowed =
|
||||
typeof isSubjectEntryAllowed === 'function'
|
||||
? isSubjectEntryAllowed
|
||||
: () => false;
|
||||
this.isUtilityDisclosureOpen =
|
||||
typeof isUtilityDisclosureOpen === 'function'
|
||||
? isUtilityDisclosureOpen
|
||||
@@ -246,7 +289,14 @@ export class CockpitViewController {
|
||||
entryAvailable: false,
|
||||
// Which subject the entry button would enter, and the active subject.
|
||||
entryKind: null,
|
||||
// A provider's entry face, `{icon, label}`; null for the built-ins.
|
||||
entryFace: null,
|
||||
subjectKind: null,
|
||||
// While a provider's subject is ridden: its HUD and exit labels, and
|
||||
// `{aheadLabel}` when it looks around.
|
||||
subjectGeneric: false,
|
||||
subjectLabels: null,
|
||||
subjectLook: null,
|
||||
tr3b: null,
|
||||
context: false,
|
||||
// The Contact and briefing cards' collapse, which their toggles show.
|
||||
@@ -269,28 +319,17 @@ export class CockpitViewController {
|
||||
this.regionalBriefSubjectId = null;
|
||||
this.contextLayoutFrame = null;
|
||||
this.contextLayoutStamp = null;
|
||||
this.scratchTarget = new Cesium.Cartesian3();
|
||||
this.cockpitAnchor = new Cesium.Cartesian3();
|
||||
/** Where the Cockpit eye is carried from, as ECEF; see cockpitCamera.js. */
|
||||
this.cockpitAnchor = null;
|
||||
this.cockpitAnchorValid = false;
|
||||
this.scratchCamera = new Cesium.Cartesian3();
|
||||
this.scratchAdvance = new Cesium.Cartesian3();
|
||||
this.scratchCorrection = new Cesium.Cartesian3();
|
||||
this.scratchForward = new Cesium.Cartesian3();
|
||||
this.scratchHorizontal = new Cesium.Cartesian3();
|
||||
this.scratchUp = new Cesium.Cartesian3();
|
||||
this.scratchLocal = new Cesium.Cartesian3();
|
||||
this.scratchEnu = new Cesium.Matrix4();
|
||||
this.scratchAnchorCartographic = new Cesium.Cartographic();
|
||||
this.scratchCameraCartographic = new Cesium.Cartographic();
|
||||
this.scratchTargetCartographic = new Cesium.Cartographic();
|
||||
this._listenerRemovers = [onLocaleChange(() => this.relocalize())];
|
||||
|
||||
// Camera mutations belong before scene update/culling. Changing the camera
|
||||
// from preRender makes 3D Tiles discover a new view after traversal and can
|
||||
// create a self-sustaining refinement loop under a moving cockpit camera.
|
||||
this._listenerRemovers.push(
|
||||
viewer.scene.preUpdate.addEventListener(() => this.update()),
|
||||
viewer.trackedEntityChanged.addEventListener(() => {
|
||||
frame.on('preUpdate', () => this.update()),
|
||||
onFollowChanged(viewer, () => {
|
||||
if (this.active) this._adoptTrackedEntity(performance.now());
|
||||
else this.syncEntry();
|
||||
}),
|
||||
@@ -298,7 +337,7 @@ export class CockpitViewController {
|
||||
this._listen(this.entry, 'click', () => this.enter());
|
||||
// Double-clicking the followed track is a third way in.
|
||||
this._listen(
|
||||
viewer.scene?.canvas,
|
||||
canvasOf(viewer),
|
||||
'pointerdown',
|
||||
() => this.onScenePointerDown(),
|
||||
true,
|
||||
@@ -309,7 +348,7 @@ export class CockpitViewController {
|
||||
// In orbit the wheel steps the optical zoom (Cesium's own wheel zoom is
|
||||
// off while the Cockpit holds the camera).
|
||||
this._listen(
|
||||
viewer.scene?.canvas,
|
||||
canvasOf(viewer),
|
||||
'wheel',
|
||||
(event) => this.onOrbitalWheel(event),
|
||||
{ passive: false },
|
||||
@@ -456,6 +495,9 @@ export class CockpitViewController {
|
||||
onOrbitalDoubleClick(position) {
|
||||
return onOrbitalDoubleClick.call(this, position);
|
||||
}
|
||||
orbitalSiteUnder(position) {
|
||||
return orbitalSiteUnder.call(this, position);
|
||||
}
|
||||
/**
|
||||
* A site's orbital Live Signals row: focus that site, switch to it, or end
|
||||
* the focus held on it.
|
||||
@@ -508,6 +550,21 @@ export class CockpitViewController {
|
||||
if (reset && hadFocus) this.mapViewButton?.focus({ preventScroll: true });
|
||||
return reset;
|
||||
}
|
||||
readSubjectCandidate(provider) {
|
||||
return readSubjectCandidate.call(this, provider);
|
||||
}
|
||||
subjectContext() {
|
||||
return subjectContext.call(this);
|
||||
}
|
||||
subjectInfo(frame) {
|
||||
return subjectInfo.call(this, frame);
|
||||
}
|
||||
entryCandidates(nowMs) {
|
||||
return entryCandidates.call(this, nowMs);
|
||||
}
|
||||
resolveEntry(nowMs) {
|
||||
return resolveEntry.call(this, nowMs);
|
||||
}
|
||||
readSubjectLayerId() {
|
||||
return readSubjectLayerId.call(this);
|
||||
}
|
||||
@@ -529,6 +586,9 @@ export class CockpitViewController {
|
||||
syncEntry() {
|
||||
return syncEntry.call(this);
|
||||
}
|
||||
refreshSubjectWords() {
|
||||
return refreshSubjectWords.call(this);
|
||||
}
|
||||
navigateContext(direction, options) {
|
||||
return navigateContext.call(this, direction, options);
|
||||
}
|
||||
@@ -568,6 +628,19 @@ export class CockpitViewController {
|
||||
presentLook() {
|
||||
return presentLook.call(this);
|
||||
}
|
||||
/** Whether the active view looks around: a bridge, or a provider's with `look`. */
|
||||
get looksAround() {
|
||||
return (
|
||||
this.active &&
|
||||
(this.subjectKind === 'vessel' || Boolean(this.subjectProvider?.look))
|
||||
);
|
||||
}
|
||||
/** Where the look rests: the bridge's pitch, or the provider's. */
|
||||
get lookRestPitch() {
|
||||
return Number.isFinite(this.lookRestPitchDeg)
|
||||
? this.lookRestPitchDeg
|
||||
: VESSEL_BRIDGE_PITCH_DEG;
|
||||
}
|
||||
/**
|
||||
* Turn the bridge view one arrow step (see `lookKeyStep`). The camera
|
||||
* eases there unless the user prefers reduced motion.
|
||||
@@ -575,7 +648,7 @@ export class CockpitViewController {
|
||||
* @returns {boolean} True when a bridge view was turned.
|
||||
*/
|
||||
turnLook(step) {
|
||||
if (!this.active || this.subjectKind !== 'vessel' || !step) return false;
|
||||
if (!this.looksAround || !step) return false;
|
||||
this.lookTarget = stepLook(this.lookTarget, step);
|
||||
if (prefersReducedMotion()) this.lookView = { ...this.lookTarget };
|
||||
this.presentLook();
|
||||
@@ -588,7 +661,7 @@ export class CockpitViewController {
|
||||
* as entry and exit do.
|
||||
*/
|
||||
resetLook({ immediate = false } = {}) {
|
||||
this.lookTarget = { yawDeg: 0, pitchDeg: VESSEL_BRIDGE_PITCH_DEG };
|
||||
this.lookTarget = { yawDeg: 0, pitchDeg: this.lookRestPitch };
|
||||
if (immediate || prefersReducedMotion())
|
||||
this.lookView = { ...this.lookTarget };
|
||||
this.lookLastMs = performance.now();
|
||||
@@ -601,7 +674,7 @@ export class CockpitViewController {
|
||||
* @returns {boolean} True on a bridge.
|
||||
*/
|
||||
lookAhead() {
|
||||
if (!this.active || this.subjectKind !== 'vessel') return false;
|
||||
if (!this.looksAround) return false;
|
||||
const button = document.getElementById('cockpit-look-ahead');
|
||||
const hadFocus = !!button && button.contains(document.activeElement);
|
||||
this.resetLook();
|
||||
@@ -718,6 +791,9 @@ export class CockpitViewController {
|
||||
this.relocalizeBrief();
|
||||
this.publishVision(createVisionState(this.visionMode));
|
||||
this.routeSignature = null;
|
||||
// A provider's words, ridden or on the entry, follow the language.
|
||||
this.refreshSubjectWords();
|
||||
if (!this.active) this.syncEntry();
|
||||
if (this.active && this.lastSubjectInfo) {
|
||||
this.rewordingSignals = true;
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { CockpitViewController } from './cockpitController.js';
|
||||
import { withEntityRecord } from '../data/entityRecords.js';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { entityFollowTarget, followedOf } from '../data/followed.js';
|
||||
import {
|
||||
cockpitAnchorCorrectionStep,
|
||||
cockpitGroundSafeHeight,
|
||||
} from '../cockpitMath.js';
|
||||
import {
|
||||
COCKPIT_FORWARD_OFFSET_M,
|
||||
COCKPIT_MIN_GROUND_CLEARANCE_M,
|
||||
COCKPIT_UP_OFFSET_M,
|
||||
COCKPIT_VIEW_PITCH_DEG,
|
||||
} from './cockpitPresentation.js';
|
||||
|
||||
function environment() {
|
||||
const original = { document: globalThis.document, window: globalThis.window };
|
||||
@@ -22,13 +36,32 @@ function environment() {
|
||||
const viewer = {
|
||||
scene: {
|
||||
preUpdate: event,
|
||||
screenSpaceCameraController: { enableInputs: false },
|
||||
screenSpaceCameraController: { enableInputs: true },
|
||||
},
|
||||
trackedEntityChanged: event,
|
||||
entities: { contains: () => false },
|
||||
};
|
||||
// What the camera follows, as a layer's follow sets it.
|
||||
const camera = {
|
||||
followed: null,
|
||||
follow(target) {
|
||||
camera.followed = target;
|
||||
},
|
||||
on: (name, fn) =>
|
||||
name === 'followChanged' ? event.addEventListener(fn) : () => {},
|
||||
};
|
||||
// The renderer's frame port: Cockpit moves the camera on its preUpdate.
|
||||
bindRenderer(viewer, {
|
||||
camera,
|
||||
frame: {
|
||||
on: (phase, fn) =>
|
||||
phase === 'preUpdate' ? event.addEventListener(fn) : () => {},
|
||||
},
|
||||
});
|
||||
/** Follow a holder of an entity record, as a layer's follow does. */
|
||||
const follow = (holder) =>
|
||||
camera.follow(holder ? entityFollowTarget(holder, {}) : null);
|
||||
return {
|
||||
viewer,
|
||||
follow,
|
||||
callbacks,
|
||||
restore() {
|
||||
Object.assign(globalThis, original);
|
||||
@@ -61,7 +94,14 @@ test('disposing an active Cockpit releases the supplied render owner without ret
|
||||
const owner = new CockpitViewController(env.viewer, {
|
||||
services: { releaseContinuousRender: (reason) => released.push(reason) },
|
||||
});
|
||||
// Entered: the cockpit holds camera input, as enter() takes it.
|
||||
const { input } = fakeInput(env.viewer);
|
||||
owner.active = true;
|
||||
owner.releaseCameraInput = input.suspendCamera('cockpit');
|
||||
assert.equal(
|
||||
env.viewer.scene.screenSpaceCameraController.enableInputs,
|
||||
false,
|
||||
);
|
||||
owner.dispose();
|
||||
owner.dispose();
|
||||
assert.deepEqual(released, ['cockpit']);
|
||||
@@ -69,7 +109,7 @@ test('disposing an active Cockpit releases the supplied render owner without ret
|
||||
env.viewer.scene.screenSpaceCameraController.enableInputs,
|
||||
true,
|
||||
);
|
||||
assert.equal(env.viewer.trackedEntity, undefined);
|
||||
assert.equal(followedOf(env.viewer), null);
|
||||
assert.equal(owner.active, false);
|
||||
} finally {
|
||||
env.restore();
|
||||
@@ -95,9 +135,9 @@ test('aircraft identity is read from the supplied layer instances', () => {
|
||||
militaryFlightsLayer: { getTrackedInfo: () => military },
|
||||
},
|
||||
});
|
||||
env.viewer.trackedEntity = { gevTrackedId: 'military:def456' };
|
||||
env.follow(withEntityRecord({}, { trackedId: 'military:def456' }));
|
||||
assert.deepEqual(owner.readAircraftInfo(), military);
|
||||
env.viewer.trackedEntity = { gevTrackedId: 'flights:abc123' };
|
||||
env.follow(withEntityRecord({}, { trackedId: 'flights:abc123' }));
|
||||
assert.deepEqual(owner.readAircraftInfo(), civilian);
|
||||
owner.dispose();
|
||||
} finally {
|
||||
@@ -244,3 +284,287 @@ test('the weather toggle flips from its own state, however fast it is pressed',
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The Cockpit eye as cockpitCamera.js computed it with Cesium's own maths,
|
||||
* for one update: the anchor advanced along the heading and pulled toward
|
||||
* the target (held on it when stale), lifted to the floor, then the eye
|
||||
* set forward and up from it and lifted again.
|
||||
*/
|
||||
function cesiumCockpitEye(
|
||||
Cesium,
|
||||
{ target, anchor, info, heading, dtSec, floorM, liftM },
|
||||
) {
|
||||
const { Cartesian3, Matrix4, Transforms, Cartographic, Ellipsoid } = Cesium;
|
||||
const h = Cesium.Math.toRadians(heading);
|
||||
const p = Cesium.Math.toRadians(COCKPIT_VIEW_PITCH_DEG);
|
||||
const speed = Math.max(0, info.velocityMps);
|
||||
const along = (origin, x, y, z) =>
|
||||
Cartesian3.normalize(
|
||||
Matrix4.multiplyByPointAsVector(
|
||||
Transforms.eastNorthUpToFixedFrame(origin, Ellipsoid.WGS84),
|
||||
new Cartesian3(x, y, z),
|
||||
new Cartesian3(),
|
||||
),
|
||||
new Cartesian3(),
|
||||
);
|
||||
let a = Cartesian3.clone(anchor ?? target);
|
||||
if (info.stale) a = Cartesian3.clone(target);
|
||||
else {
|
||||
const horizontal = along(a, Math.sin(h), Math.cos(h), 0);
|
||||
a = Cartesian3.add(
|
||||
a,
|
||||
Cartesian3.multiplyByScalar(horizontal, speed * dtSec, new Cartesian3()),
|
||||
new Cartesian3(),
|
||||
);
|
||||
const correction = Cartesian3.subtract(target, a, new Cartesian3());
|
||||
const distance = Cartesian3.magnitude(correction);
|
||||
const step = cockpitAnchorCorrectionStep(distance, speed, dtSec);
|
||||
if (step > 0 && distance > 0)
|
||||
a = Cartesian3.add(
|
||||
a,
|
||||
Cartesian3.multiplyByScalar(
|
||||
correction,
|
||||
step / distance,
|
||||
new Cartesian3(),
|
||||
),
|
||||
new Cartesian3(),
|
||||
);
|
||||
}
|
||||
const anchorCarto = Cartographic.fromCartesian(a);
|
||||
let floor = floorM;
|
||||
const targetCarto = Cartographic.fromCartesian(target);
|
||||
if (!Number.isFinite(floor) && speed < 90) floor = targetCarto.height - liftM;
|
||||
if (Number.isFinite(floor)) {
|
||||
const minimum = cockpitGroundSafeHeight(
|
||||
anchorCarto.height,
|
||||
floor,
|
||||
COCKPIT_MIN_GROUND_CLEARANCE_M - COCKPIT_UP_OFFSET_M,
|
||||
);
|
||||
if (minimum !== anchorCarto.height) {
|
||||
anchorCarto.height = minimum;
|
||||
a = Ellipsoid.WGS84.cartographicToCartesian(anchorCarto);
|
||||
}
|
||||
}
|
||||
const horizontal = along(a, Math.sin(h), Math.cos(h), 0);
|
||||
const forward = along(
|
||||
a,
|
||||
Math.sin(h) * Math.cos(p),
|
||||
Math.cos(h) * Math.cos(p),
|
||||
Math.sin(p),
|
||||
);
|
||||
const up = along(
|
||||
a,
|
||||
-Math.sin(h) * Math.sin(p),
|
||||
-Math.cos(h) * Math.sin(p),
|
||||
Math.cos(p),
|
||||
);
|
||||
let eye = Cartesian3.add(
|
||||
Cartesian3.add(
|
||||
a,
|
||||
Cartesian3.multiplyByScalar(
|
||||
horizontal,
|
||||
COCKPIT_FORWARD_OFFSET_M,
|
||||
new Cartesian3(),
|
||||
),
|
||||
new Cartesian3(),
|
||||
),
|
||||
Cartesian3.multiplyByScalar(
|
||||
Cartesian3.normalize(a, new Cartesian3()),
|
||||
COCKPIT_UP_OFFSET_M,
|
||||
new Cartesian3(),
|
||||
),
|
||||
new Cartesian3(),
|
||||
);
|
||||
const eyeCarto = Cartographic.fromCartesian(eye);
|
||||
const safe = cockpitGroundSafeHeight(
|
||||
eyeCarto.height,
|
||||
floor,
|
||||
COCKPIT_MIN_GROUND_CLEARANCE_M,
|
||||
);
|
||||
if (safe !== eyeCarto.height) {
|
||||
eyeCarto.height = safe;
|
||||
eye = Ellipsoid.WGS84.cartographicToCartesian(eyeCarto);
|
||||
}
|
||||
return { eye, forward, up, anchor: a };
|
||||
}
|
||||
|
||||
/** A Cockpit flying `info` over `target`, its camera writes in `views`. */
|
||||
function cockpitOver({ info, target, services = {} }) {
|
||||
const views = [];
|
||||
const viewer = {
|
||||
trackedEntityChanged: { addEventListener: () => () => {} },
|
||||
};
|
||||
bindRenderer(viewer, {
|
||||
frame: { on: () => () => {}, time: () => 0 },
|
||||
camera: {
|
||||
followed: null,
|
||||
on: () => () => {},
|
||||
pose: () => ({ lat: 30.2, lon: -97.7 }),
|
||||
setView: (view) => views.push(view),
|
||||
},
|
||||
});
|
||||
const owner = new CockpitViewController(viewer, {
|
||||
services: {
|
||||
flightsLayer: { getTrackedInfo: () => info },
|
||||
militaryFlightsLayer: {},
|
||||
cachedGroundFloor: () => null,
|
||||
trackedEntityDrawn: () => true,
|
||||
releaseContinuousRender() {},
|
||||
...services,
|
||||
},
|
||||
});
|
||||
owner.updateHud = () => {};
|
||||
owner.active = true;
|
||||
owner.heading = info.track;
|
||||
owner.trackedEntity = {};
|
||||
owner.trackedFollow = { key: 'flights:abc123', position: () => target };
|
||||
return { owner, viewer, views };
|
||||
}
|
||||
|
||||
const near = (a, b, eps, what) =>
|
||||
assert.ok(
|
||||
Math.abs(a.x - b.x) <= eps &&
|
||||
Math.abs(a.y - b.y) <= eps &&
|
||||
Math.abs(a.z - b.z) <= eps,
|
||||
`${what}: ${JSON.stringify(a)} vs ${JSON.stringify(b)}`,
|
||||
);
|
||||
|
||||
test('Cockpit places the eye at its aircraft as the Cesium maths did', async () => {
|
||||
const Cesium = await import('cesium');
|
||||
const env = environment();
|
||||
const realNow = performance.now;
|
||||
try {
|
||||
const target = Cesium.Cartesian3.fromDegrees(-97.67, 30.19, 1200);
|
||||
const info = {
|
||||
icao24: 'abc123',
|
||||
layerId: 'flights',
|
||||
track: 72,
|
||||
velocityMps: 200,
|
||||
latitude: 30.19,
|
||||
longitude: -97.67,
|
||||
onGround: false,
|
||||
stale: true,
|
||||
};
|
||||
const { owner, views } = cockpitOver({ info, target });
|
||||
// Held on the target while the feed is stale.
|
||||
owner.update();
|
||||
let expected = cesiumCockpitEye(Cesium, {
|
||||
target,
|
||||
info,
|
||||
heading: 72,
|
||||
dtSec: 0,
|
||||
liftM: 0,
|
||||
});
|
||||
near(views[0].destination, expected.eye, 1e-6, 'stale eye');
|
||||
near(views[0].orientation.direction, expected.forward, 1e-12, 'direction');
|
||||
near(views[0].orientation.up, expected.up, 1e-12, 'up');
|
||||
|
||||
// Live: the anchor coasts 80 ms along the heading and is pulled toward
|
||||
// where the layer now shows the aircraft.
|
||||
info.stale = false;
|
||||
const anchor = Cesium.Cartesian3.clone(expected.anchor);
|
||||
const moved = Cesium.Cartesian3.fromDegrees(-97.6698, 30.1901, 1210);
|
||||
owner.trackedFollow.position = () => moved;
|
||||
let now = owner.lastFrameMs + 80;
|
||||
performance.now = () => now;
|
||||
owner.update();
|
||||
expected = cesiumCockpitEye(Cesium, {
|
||||
target: moved,
|
||||
anchor,
|
||||
info,
|
||||
heading: 72,
|
||||
dtSec: 0.08,
|
||||
liftM: 0,
|
||||
});
|
||||
assert.equal(views.length, 2);
|
||||
near(views[1].destination, expected.eye, 1e-6, 'live eye');
|
||||
near(views[1].orientation.direction, expected.forward, 1e-12, 'direction');
|
||||
near(views[1].orientation.up, expected.up, 1e-12, 'up');
|
||||
|
||||
// An aircraft its layer no longer draws ends Cockpit.
|
||||
owner.services.trackedEntityDrawn = () => false;
|
||||
now += 80;
|
||||
owner.update();
|
||||
assert.equal(owner.active, false);
|
||||
assert.equal(views.length, 2);
|
||||
owner.dispose();
|
||||
} finally {
|
||||
performance.now = realNow;
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a grounded Cockpit probes the mesh from the camera and keeps the eye above the floor', async () => {
|
||||
const Cesium = await import('cesium');
|
||||
const env = environment();
|
||||
try {
|
||||
// Reported below the apron: the floor lifts the anchor and the eye.
|
||||
const target = Cesium.Cartesian3.fromDegrees(-97.67, 30.19, 120);
|
||||
const info = {
|
||||
icao24: 'abc123',
|
||||
layerId: 'flights',
|
||||
track: 300,
|
||||
velocityMps: 0,
|
||||
latitude: 30.19,
|
||||
longitude: -97.67,
|
||||
onGround: true,
|
||||
stale: true,
|
||||
};
|
||||
const probes = [];
|
||||
const { owner, viewer, views } = cockpitOver({
|
||||
info,
|
||||
target,
|
||||
services: {
|
||||
cachedGroundFloor: () => 140,
|
||||
warmGroundFloor() {},
|
||||
cachedMeshFloor: () => null,
|
||||
meshFloorPreferred: () => true,
|
||||
sampleMeshFloorCells: (...args) => probes.push(args),
|
||||
GROUND_FLOOR_LIFT_M: 0,
|
||||
},
|
||||
});
|
||||
// The tracked contact names the draw sets its probe sees through.
|
||||
withEntityRecord(owner.trackedEntity, {
|
||||
groundSets: () => ['flights-models:1', 'flights-tracked-icon:1'],
|
||||
});
|
||||
// The surface wait is over: Cockpit flies on the ground floor.
|
||||
owner.surfaceWaitStartedMs = -1e9;
|
||||
owner.update();
|
||||
assert.equal(probes.length, 1);
|
||||
const [host, points, options] = probes[0];
|
||||
assert.equal(host, viewer);
|
||||
assert.deepEqual(points, [{ lat: 30.19, lon: -97.67 }]);
|
||||
assert.deepEqual(options, {
|
||||
sets: ['flights-models:1', 'flights-tracked-icon:1'],
|
||||
viewerLat: 30.2,
|
||||
viewerLon: -97.7,
|
||||
});
|
||||
const expected = cesiumCockpitEye(Cesium, {
|
||||
target,
|
||||
info,
|
||||
heading: 300,
|
||||
dtSec: 0,
|
||||
floorM: 140,
|
||||
liftM: 0,
|
||||
});
|
||||
assert.equal(views.length, 1);
|
||||
// The floor lifts round-trip through geodetic heights: the shared geo helpers' and
|
||||
// Cesium's agree to well under a millimetre there.
|
||||
near(views[0].destination, expected.eye, 1e-4, 'eye');
|
||||
const height = Cesium.Cartographic.fromCartesian(
|
||||
new Cesium.Cartesian3(
|
||||
views[0].destination.x,
|
||||
views[0].destination.y,
|
||||
views[0].destination.z,
|
||||
),
|
||||
).height;
|
||||
assert.ok(
|
||||
height >= 140 + COCKPIT_MIN_GROUND_CLEARANCE_M - 1e-6,
|
||||
`${height}`,
|
||||
);
|
||||
owner.dispose();
|
||||
} finally {
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { nextTick } from 'vue';
|
||||
import { CockpitViewController, CockpitDisplayPortal } from './cockpit.js';
|
||||
import {
|
||||
@@ -5,10 +6,13 @@ import {
|
||||
bridgeEntryAllowed,
|
||||
cockpitEntryAllowed,
|
||||
orbitEntryAllowed,
|
||||
subjectEntryAllowed,
|
||||
} from '../contextModePolicy.js';
|
||||
import { cockpitSubjectProviders } from '../cockpitSubjectProviders.js';
|
||||
import { formatAwarenessLabel } from '../data/militaryAwarenessEngine.js';
|
||||
import { enterCockpitWithTracking } from '../cockpitTracking.js';
|
||||
import { cockpitVisionModeForStyle } from '../cockpitVisionPolicy.js';
|
||||
import { readEntityRecord } from '../data/entityRecords.js';
|
||||
|
||||
/** Own Cockpit entry/rollback, readouts and the single Display portal. */
|
||||
export class CockpitCoordinator {
|
||||
@@ -54,14 +58,18 @@ export class CockpitCoordinator {
|
||||
meshFloorPreferred,
|
||||
warmGroundFloor,
|
||||
sampleMeshFloorCells,
|
||||
trackedEntityDrawn,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
fetchRegionalBrief,
|
||||
regionalDistanceM,
|
||||
weatherCodeLabel,
|
||||
acquireOrbitImagery,
|
||||
cockpitSubjects,
|
||||
} = services;
|
||||
this._cockpitDisplayPortal = null;
|
||||
// The application's own subjects (services.cockpitSubjects), checked once.
|
||||
const subjectProviders = cockpitSubjectProviders(cockpitSubjects ?? []);
|
||||
this.cockpitView = new CockpitViewController(viewer, {
|
||||
services: {
|
||||
flightsLayer,
|
||||
@@ -79,6 +87,7 @@ export class CockpitCoordinator {
|
||||
meshFloorPreferred,
|
||||
warmGroundFloor,
|
||||
sampleMeshFloorCells,
|
||||
trackedEntityDrawn,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
fetchRegionalBrief,
|
||||
@@ -108,6 +117,21 @@ export class CockpitCoordinator {
|
||||
vesselsEnabled: !!this._dataManager?.isEnabled('ais-live-vessels'),
|
||||
contextModeChanging: this._contextModeChanging,
|
||||
}),
|
||||
subjectProviders,
|
||||
// A provider's subject needs its own layer on, no Context change in
|
||||
// flight, and the provider's own say.
|
||||
isSubjectEntryAllowed: (provider, candidate) =>
|
||||
subjectEntryAllowed({
|
||||
layerEnabled: this._isLayerEnabled(provider.layerId),
|
||||
contextModeChanging: this._contextModeChanging,
|
||||
providerAllows:
|
||||
this.cockpitView?.callSubject(
|
||||
provider,
|
||||
'isEntryAllowed',
|
||||
[candidate],
|
||||
false,
|
||||
) === true,
|
||||
}),
|
||||
isOrbitEntryAllowed: () =>
|
||||
orbitEntryAllowed({
|
||||
satellitesEnabled: !!this._dataManager?.isEnabled('satellites'),
|
||||
@@ -122,9 +146,9 @@ export class CockpitCoordinator {
|
||||
onExited: () => this.exitPanels(),
|
||||
onRide: (layerId) => this._adoptRiddenLayer(layerId),
|
||||
restoreTrackingFrame: (entity) => {
|
||||
const [layerId, ...idParts] = String(entity?.gevTrackedId || '').split(
|
||||
':',
|
||||
);
|
||||
const [layerId, ...idParts] = String(
|
||||
readEntityRecord(entity)?.trackedId || '',
|
||||
).split(':');
|
||||
const trackedId = idParts.join(':');
|
||||
if (!trackedId) return false;
|
||||
if (layerId === 'flights')
|
||||
@@ -197,6 +221,9 @@ export class CockpitCoordinator {
|
||||
this.cockpitView.subjectKind === 'satellite'
|
||||
)
|
||||
return 'Cockpit is in an orbital view — exit it first, then track an aircraft to enter Cockpit';
|
||||
// And in an application's own first-person view.
|
||||
if (this.cockpitView?.active && this.cockpitView.subjectProvider)
|
||||
return 'Cockpit is in another first-person view — exit it first, then track an aircraft to enter Cockpit';
|
||||
if (!this._aircraftLayerEnabled)
|
||||
return 'No aircraft layer is on — turn on Flights or Military Flights and track an aircraft to enter Cockpit';
|
||||
return null;
|
||||
@@ -216,15 +243,26 @@ export class CockpitCoordinator {
|
||||
active && this.cockpitView?.subjectKind === 'satellite'
|
||||
? this.cockpitView.readSatelliteInfo?.()
|
||||
: null;
|
||||
// And a provider's subject in use.
|
||||
const provided =
|
||||
active && this.cockpitView?.subjectProvider
|
||||
? {
|
||||
kind: this.cockpitView.subjectProvider.kind,
|
||||
id: this.cockpitView.subjectId,
|
||||
layerId: this.cockpitView.subjectProvider.layerId,
|
||||
callsign: null,
|
||||
name: this.cockpitView.lastSubjectFrame?.name ?? null,
|
||||
}
|
||||
: null;
|
||||
const gateOpen = Boolean(this.cockpitView?.isEntryAllowed?.());
|
||||
// "Could Cockpit be ENTERED right now" — so it is false while already
|
||||
// inside, unconditionally. Cockpit takes the entity off
|
||||
// `viewer.trackedEntity` on entry and NEXT puts one back, which made this
|
||||
// the camera's follow on entry and NEXT puts one back, which made this
|
||||
// flip true/false between calls while `active` stayed true; readers
|
||||
// (including the voice model) read that as a broken half-entered state.
|
||||
const entryAllowed =
|
||||
!active &&
|
||||
Boolean(gateOpen && info && this.viewer?.trackedEntity?.position);
|
||||
Boolean(gateOpen && info && followedOf(this.viewer)?.entity?.position);
|
||||
// Entry needs only the ridden aircraft's own layer: with one tracked,
|
||||
// that layer; with none, any aircraft layer to track one from.
|
||||
const subjectLayerOff = info
|
||||
@@ -244,30 +282,32 @@ export class CockpitCoordinator {
|
||||
? 'subject-layer-off'
|
||||
: 'no-tracked-aircraft',
|
||||
visionMode: this.cockpitView?.visionMode || null,
|
||||
subject: satellite
|
||||
? {
|
||||
kind: 'satellite',
|
||||
id: satellite.id,
|
||||
layerId: satellite.layerId,
|
||||
callsign: null,
|
||||
name: satellite.name,
|
||||
}
|
||||
: vessel
|
||||
subject: provided
|
||||
? provided
|
||||
: satellite
|
||||
? {
|
||||
kind: 'vessel',
|
||||
id: vessel.id,
|
||||
layerId: vessel.layerId,
|
||||
kind: 'satellite',
|
||||
id: satellite.id,
|
||||
layerId: satellite.layerId,
|
||||
callsign: null,
|
||||
name: vessel.name,
|
||||
name: satellite.name,
|
||||
}
|
||||
: info
|
||||
: vessel
|
||||
? {
|
||||
kind: 'aircraft',
|
||||
id: info.icao24 || info.id || null,
|
||||
layerId: info.layerId || null,
|
||||
callsign: info.callsign || null,
|
||||
kind: 'vessel',
|
||||
id: vessel.id,
|
||||
layerId: vessel.layerId,
|
||||
callsign: null,
|
||||
name: vessel.name,
|
||||
}
|
||||
: null,
|
||||
: info
|
||||
? {
|
||||
kind: 'aircraft',
|
||||
id: info.icao24 || info.id || null,
|
||||
layerId: info.layerId || null,
|
||||
callsign: info.callsign || null,
|
||||
}
|
||||
: null,
|
||||
navigation: snapshot
|
||||
? {
|
||||
canPrevious: Boolean(snapshot.navigation?.canPrevious),
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
// A double-click on the followed track enters first person, and the
|
||||
// renderer's own double-click follow is held off for that press, so it
|
||||
// cannot let go of the track first.
|
||||
//
|
||||
// Run with: npm test
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
fakeInput,
|
||||
FakeScreenSpaceEventHandler,
|
||||
FAKE_EVENT_TYPES,
|
||||
} from '../input/testDoubles.mjs';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { entityFollowTarget } from '../data/followed.js';
|
||||
import { createCesiumInput } from '../render/cesium/input.js';
|
||||
import { routeSceneDoubleClick, onSceneDoubleClick } from './cockpitInput.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
|
||||
function harness(t, { stock = null } = {}) {
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
|
||||
const viewer = {
|
||||
scene: {
|
||||
pick: () => null,
|
||||
},
|
||||
clock: { currentTime: 0 },
|
||||
};
|
||||
// The followed aircraft is drawn at (100, 100).
|
||||
const project = () => ({ x: 100, y: 100 });
|
||||
// With `stock`, the renderer's own input port takes the viewer's stock
|
||||
// double-click follow and runs it as the app's does; else the fake input.
|
||||
// The camera port follows the aircraft, as the flights layer's follow does.
|
||||
const camera = { followed: null, on: () => () => {} };
|
||||
const input = stock
|
||||
? cesiumInput(viewer, stock, project, camera)
|
||||
: fakeInput(viewer);
|
||||
if (!stock) bindRenderer(viewer, { query: { project }, camera });
|
||||
const entity = {
|
||||
id: 'flights:abc',
|
||||
position: { getValue: () => ({ x: 1, y: 2, z: 3 }) },
|
||||
};
|
||||
camera.followed = entityFollowTarget(entity, {
|
||||
position: () => entity.position.getValue(),
|
||||
frame: 'enu',
|
||||
viewFrom: { x: 0, y: -1000, z: 500 },
|
||||
});
|
||||
const controller = {
|
||||
viewer,
|
||||
active: false,
|
||||
destroyed: false,
|
||||
entered: 0,
|
||||
holds: 0,
|
||||
// Counted here, unless the test watches the renderer's own hold.
|
||||
...(stock
|
||||
? {}
|
||||
: {
|
||||
holdStockFollow() {
|
||||
this.holds += 1;
|
||||
return () => {
|
||||
this.holds -= 1;
|
||||
};
|
||||
},
|
||||
}),
|
||||
resolveEntryKind: () => 'aircraft',
|
||||
enter() {
|
||||
this.entered += 1;
|
||||
},
|
||||
onSceneDoubleClick(position) {
|
||||
return onSceneDoubleClick.call(this, position);
|
||||
},
|
||||
};
|
||||
const stop = routeSceneDoubleClick.call(controller);
|
||||
t.after(() => {
|
||||
stop();
|
||||
input.destroy();
|
||||
});
|
||||
return { input, controller, stop };
|
||||
}
|
||||
|
||||
/** The Cesium renderer's input port over a fake handler, with `follow` as
|
||||
* the viewer's stock double-click follow. */
|
||||
function cesiumInput(viewer, follow, project, camera) {
|
||||
const stock = new FakeScreenSpaceEventHandler();
|
||||
stock.setInputAction(follow, FAKE_EVENT_TYPES.LEFT_DOUBLE_CLICK);
|
||||
viewer.screenSpaceEventHandler = stock;
|
||||
viewer.scene.canvas = {
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
const handler = new FakeScreenSpaceEventHandler();
|
||||
const query = { project, pick: () => null, drillPick: () => [] };
|
||||
const made = createCesiumInput(viewer, {
|
||||
query,
|
||||
createHandler: () => handler,
|
||||
report: (error) => {
|
||||
throw error;
|
||||
},
|
||||
document: null,
|
||||
});
|
||||
bindRenderer(viewer, { input: made.port, query, camera });
|
||||
const T = FAKE_EVENT_TYPES;
|
||||
const fire = (type) => (position) => handler.fire(type, { position });
|
||||
return {
|
||||
down: fire(T.LEFT_DOWN),
|
||||
up: fire(T.LEFT_UP),
|
||||
click: fire(T.LEFT_CLICK),
|
||||
tap(position) {
|
||||
handler.fire(T.LEFT_DOWN, { position });
|
||||
handler.fire(T.LEFT_UP, { position });
|
||||
handler.fire(T.LEFT_CLICK, { position });
|
||||
},
|
||||
dblclick: fire(T.LEFT_DOUBLE_CLICK),
|
||||
stockEnabled: (name) => made.port.behaviours[name].enabled,
|
||||
destroy: () => made.dispose(),
|
||||
};
|
||||
}
|
||||
|
||||
const doubleClick = (input, position) => {
|
||||
input.tap(position);
|
||||
input.down(position);
|
||||
input.up(position);
|
||||
input.dblclick(position);
|
||||
};
|
||||
|
||||
test('a double-click on the followed track enters, with the stock follow held off for the press', async (t) => {
|
||||
const { input, controller } = harness(t);
|
||||
const on = { x: 110, y: 95 };
|
||||
input.down(on);
|
||||
assert.equal(
|
||||
input.stockEnabled('dblclickFollow'),
|
||||
false,
|
||||
'held at the press',
|
||||
);
|
||||
input.up(on);
|
||||
input.click(on);
|
||||
input.down(on);
|
||||
input.up(on);
|
||||
input.dblclick(on);
|
||||
assert.equal(controller.entered, 1);
|
||||
// Given back once the double-click's dispatch is over.
|
||||
await Promise.resolve();
|
||||
assert.equal(controller.holds, 0, 'given back');
|
||||
});
|
||||
|
||||
test("a double-click elsewhere is the renderer's own", (t) => {
|
||||
const { input, controller } = harness(t);
|
||||
const off = { x: 400, y: 300 };
|
||||
input.down(off);
|
||||
assert.equal(controller.holds, 0);
|
||||
doubleClick(input, off);
|
||||
assert.equal(controller.entered, 0);
|
||||
assert.equal(controller.holds, 0);
|
||||
});
|
||||
|
||||
test('a single press on the track gives the stock follow back at its release, or by itself', (t) => {
|
||||
const { input, controller } = harness(t);
|
||||
input.tap({ x: 100, y: 100 });
|
||||
assert.equal(controller.holds, 0, 'given back at the release');
|
||||
t.mock.timers.tick(700);
|
||||
input.down({ x: 100, y: 100 });
|
||||
assert.equal(controller.holds, 1);
|
||||
t.mock.timers.tick(700);
|
||||
assert.equal(controller.holds, 0, 'a press never released lets go');
|
||||
assert.equal(controller.entered, 0);
|
||||
});
|
||||
|
||||
test("a double-click that starts on the track and ends off it is the renderer's own", (t) => {
|
||||
const follows = [];
|
||||
const { input, controller } = harness(t, {
|
||||
stock: (event) => follows.push(event.position),
|
||||
});
|
||||
const on = { x: 120, y: 100 };
|
||||
const off = { x: 140, y: 100 };
|
||||
// As Cesium raises them: each press clicks, then the double-click.
|
||||
input.tap(on);
|
||||
input.tap(off);
|
||||
input.dblclick(off);
|
||||
assert.equal(controller.entered, 0);
|
||||
assert.equal(follows.length, 1, 'the stock follow ran');
|
||||
assert.equal(input.stockEnabled('dblclickFollow'), true);
|
||||
});
|
||||
|
||||
test('a press elsewhere just before cannot make a press on the track keep its hold', (t) => {
|
||||
const follows = [];
|
||||
const { input, controller } = harness(t, {
|
||||
stock: (event) => follows.push(event.position),
|
||||
});
|
||||
input.tap({ x: 500, y: 500 });
|
||||
input.tap({ x: 120, y: 100 });
|
||||
input.tap({ x: 140, y: 100 });
|
||||
input.dblclick({ x: 140, y: 100 });
|
||||
assert.equal(controller.entered, 0);
|
||||
assert.equal(follows.length, 1, 'the stock follow ran');
|
||||
});
|
||||
|
||||
test('a press on the track long after the last keeps no hold past its release', (t) => {
|
||||
const { input, controller } = harness(t);
|
||||
const on = { x: 100, y: 100 };
|
||||
input.tap(on);
|
||||
t.mock.timers.tick(701);
|
||||
input.down(on);
|
||||
input.up(on);
|
||||
assert.equal(controller.holds, 0, 'it cannot end a double-click');
|
||||
input.down(on);
|
||||
input.up(on);
|
||||
assert.equal(controller.holds, 1, 'a quick second press keeps it');
|
||||
});
|
||||
|
||||
test('a double-click that ends on the track holds the stock follow off', async (t) => {
|
||||
const follows = [];
|
||||
const { input, controller } = harness(t, {
|
||||
stock: (event) => follows.push(event.position),
|
||||
});
|
||||
const on = { x: 110, y: 95 };
|
||||
input.tap({ x: 140, y: 100 });
|
||||
input.tap(on);
|
||||
input.dblclick(on);
|
||||
assert.equal(controller.entered, 1);
|
||||
assert.deepEqual(follows, [], 'the stock follow did not run');
|
||||
await Promise.resolve();
|
||||
assert.equal(input.stockEnabled('dblclickFollow'), true, 'given back');
|
||||
});
|
||||
|
||||
test('subscribers after the Cockpit find the stock follow held through the double-click', async (t) => {
|
||||
const { input, controller } = harness(t, { stock: () => {} });
|
||||
// A layer's own follow on a double-click, subscribed after the Cockpit
|
||||
// (Mapped Installations follows a site only while the stock follow runs).
|
||||
const seen = [];
|
||||
const off = inputFor(controller.viewer).onPointer('dblclick', () =>
|
||||
seen.push(input.stockEnabled('dblclickFollow')),
|
||||
);
|
||||
t.after(off);
|
||||
const on = { x: 110, y: 95 };
|
||||
input.tap(on);
|
||||
input.tap(on);
|
||||
input.dblclick(on);
|
||||
assert.deepEqual(seen, [false], 'held for the whole dispatch');
|
||||
await Promise.resolve();
|
||||
assert.equal(input.stockEnabled('dblclickFollow'), true, 'given back after');
|
||||
});
|
||||
|
||||
test('an active Cockpit leaves presses alone, and stopping lets a hold go', (t) => {
|
||||
const { input, controller, stop } = harness(t);
|
||||
controller.active = true;
|
||||
input.down({ x: 100, y: 100 });
|
||||
assert.equal(controller.holds, 0);
|
||||
controller.active = false;
|
||||
input.down({ x: 100, y: 100 });
|
||||
assert.equal(controller.holds, 1);
|
||||
stop();
|
||||
assert.equal(controller.holds, 0);
|
||||
});
|
||||
@@ -9,6 +9,13 @@ import assert from 'node:assert/strict';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, defineComponent, h, nextTick } from 'vue';
|
||||
import { DataLayerManager } from '../data/manager.js';
|
||||
import { withEntityRecord } from '../data/entityRecords.js';
|
||||
import {
|
||||
bindFakeCesiumCamera,
|
||||
followEntity,
|
||||
} from '../testSupport/fakeCameraPort.mjs';
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
|
||||
import { createDependencies } from '../layers/awareness/dependencies.js';
|
||||
import { CockpitCoordinator } from './cockpitCoordinator.js';
|
||||
import { ContextControls } from './contextControls.js';
|
||||
@@ -55,8 +62,11 @@ function fixture(
|
||||
changing = false,
|
||||
dataManager: suppliedManager = null,
|
||||
readContext = null,
|
||||
subjects = [],
|
||||
vessel = null,
|
||||
} = {},
|
||||
) {
|
||||
let selectedVessel = vessel;
|
||||
document.body.replaceChildren();
|
||||
const host = document.body.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
@@ -75,17 +85,18 @@ function fixture(
|
||||
tracked?.layerId === layerId && dataManager.isEnabled(layerId)
|
||||
? tracked.info
|
||||
: null;
|
||||
const entityFor = (subject) => ({
|
||||
position: { getValue: () => null },
|
||||
show: true,
|
||||
gevTrackedId: subject ? `${subject.layerId}:${subject.info.icao24}` : '',
|
||||
});
|
||||
const entityFor = (subject) =>
|
||||
withEntityRecord(
|
||||
{ position: { getValue: () => null }, show: true },
|
||||
{
|
||||
trackedId: subject ? `${subject.layerId}:${subject.info.icao24}` : '',
|
||||
},
|
||||
);
|
||||
const entities = new Set();
|
||||
const entity = entityFor(tracked);
|
||||
entities.add(entity);
|
||||
const listeners = () => ({ addEventListener: () => () => {} });
|
||||
const viewer = {
|
||||
trackedEntity: tracked ? entity : undefined,
|
||||
clock: { currentTime: null },
|
||||
camera: { cancelFlight() {}, frustum: { fov: 1, aspectRatio: 1 } },
|
||||
entities: { contains: (candidate) => entities.has(candidate) },
|
||||
@@ -95,13 +106,22 @@ function fixture(
|
||||
},
|
||||
trackedEntityChanged: listeners(),
|
||||
};
|
||||
// The Cockpit reads frames, the camera and what it follows through ports.
|
||||
bindFakeCesiumCamera(viewer, fakeScenePorts(viewer));
|
||||
if (tracked) followEntity(viewer, entity);
|
||||
const context = { mode: contextMode, changing };
|
||||
const coordinator = new CockpitCoordinator({
|
||||
viewer,
|
||||
services: {
|
||||
flightsLayer: { getTrackedInfo: trackedFrom('flights') },
|
||||
militaryFlightsLayer: { getTrackedInfo: trackedFrom('military') },
|
||||
aisLiveVesselsLayer: { getCockpitSubject: () => null },
|
||||
// Like the layer, no subject while Live AIS Vessels is off.
|
||||
aisLiveVesselsLayer: {
|
||||
getCockpitSubject: () =>
|
||||
selectedVessel && layers.has('ais-live-vessels')
|
||||
? { ...selectedVessel }
|
||||
: null,
|
||||
},
|
||||
// Like the layer, no subject while Satellites is off.
|
||||
satellitesLayer: {
|
||||
getCockpitSubject: () =>
|
||||
@@ -113,6 +133,7 @@ function fixture(
|
||||
isTr3b: () => false,
|
||||
holdContinuousRender() {},
|
||||
releaseContinuousRender() {},
|
||||
cockpitSubjects: subjects,
|
||||
},
|
||||
elements: {},
|
||||
operations: {
|
||||
@@ -147,6 +168,7 @@ function fixture(
|
||||
'cockpit-mode',
|
||||
'cockpit-bridge',
|
||||
'cockpit-orbit',
|
||||
'cockpit-subject',
|
||||
);
|
||||
});
|
||||
/** Turn a layer off and tell the Context owner, as the data manager does. */
|
||||
@@ -168,13 +190,39 @@ function fixture(
|
||||
/** Track another aircraft, as Contacts navigation does mid-session. */
|
||||
const retrack = (subject) => {
|
||||
tracked = subject;
|
||||
viewer.trackedEntity = entityFor(subject);
|
||||
entities.add(viewer.trackedEntity);
|
||||
const next = entityFor(subject);
|
||||
entities.add(next);
|
||||
followEntity(viewer, next);
|
||||
};
|
||||
/** Select a vessel on the map, or none. */
|
||||
const selectVessel = (info) => {
|
||||
selectedVessel = info;
|
||||
};
|
||||
const $ = (selector) => document.querySelector(selector);
|
||||
return { $, coordinator, cockpit, store, layers, disable, retrack, pinia };
|
||||
return {
|
||||
$,
|
||||
coordinator,
|
||||
cockpit,
|
||||
store,
|
||||
layers,
|
||||
disable,
|
||||
retrack,
|
||||
selectVessel,
|
||||
pinia,
|
||||
};
|
||||
}
|
||||
|
||||
/** A selected vessel as the AIS layer gives it to the bridge view. */
|
||||
const VESSEL = Object.freeze({
|
||||
id: '211000001',
|
||||
name: 'EXAMPLE',
|
||||
latitude: 54,
|
||||
longitude: 10,
|
||||
headingDeg: 90,
|
||||
courseDeg: 90,
|
||||
speedMps: 5,
|
||||
});
|
||||
|
||||
test('a civilian aircraft enters with Live Flights alone: no Contacts, no Military', (t) => {
|
||||
const { coordinator, cockpit } = fixture(t, {
|
||||
enabled: ['flights'],
|
||||
@@ -498,8 +546,10 @@ test('a ride handed to an aircraft on a layer Contacts turned on keeps that laye
|
||||
await settle();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
// NEXT hands the view to a military aircraft; Contacts turned its layer on.
|
||||
// The follow's change adopts it as the ridden aircraft: the Cockpit
|
||||
// takes the camera from the follow.
|
||||
retrack({ layerId: 'military', info: MILITARY });
|
||||
assert.equal(cockpit._adoptTrackedEntity(performance.now()), true);
|
||||
assert.equal(followedOf(cockpit.viewer), null, 'adopted');
|
||||
assert.equal(cockpit.readSubjectLayerId(), 'military');
|
||||
await manager.setEnabled('ais-live-vessels', false, { origin: 'user' });
|
||||
await settle();
|
||||
@@ -567,6 +617,32 @@ test('the readout entry reads BRIDGE for a selected vessel', async (t) => {
|
||||
assert.match(readoutEntry.textContent, /BRIDGE/);
|
||||
});
|
||||
|
||||
test('without providers the built-in order decides: a vessel selected after an aircraft still reads COCKPIT', async (t) => {
|
||||
const { $, cockpit, store, selectVessel } = fixture(t, {
|
||||
enabled: ['flights', 'ais-live-vessels'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
cockpit.syncEntry();
|
||||
assert.equal(store.presence.entryKind, 'aircraft');
|
||||
await new Promise((resolve) => setTimeout(resolve, 2));
|
||||
selectVessel(VESSEL);
|
||||
cockpit.syncEntry();
|
||||
await nextTick();
|
||||
assert.equal(store.presence.entryKind, 'aircraft');
|
||||
assert.match($('#cockpit-entry-readout').textContent, /COCKPIT/);
|
||||
// And the other way round: an aircraft tracked after the vessel.
|
||||
const later = fixture(t, {
|
||||
enabled: ['flights', 'ais-live-vessels'],
|
||||
vessel: VESSEL,
|
||||
});
|
||||
later.cockpit.syncEntry();
|
||||
assert.equal(later.store.presence.entryKind, 'vessel');
|
||||
await new Promise((resolve) => setTimeout(resolve, 2));
|
||||
later.retrack({ layerId: 'flights', info: CIVIL });
|
||||
later.cockpit.syncEntry();
|
||||
assert.equal(later.store.presence.entryKind, 'aircraft');
|
||||
});
|
||||
|
||||
test('a tracked satellite needs Satellites on for the ORBIT entry', async (t) => {
|
||||
const { $, cockpit } = fixture(t, { satellite: SATELLITE });
|
||||
cockpit.syncEntry();
|
||||
@@ -648,3 +724,148 @@ test('turning Satellites off ends the orbital view', (t) => {
|
||||
disable('satellites');
|
||||
assert.equal(cockpit.active, false);
|
||||
});
|
||||
|
||||
/** An application provider whose subject sits on `example-layer`. */
|
||||
function exampleSubject() {
|
||||
const released = [];
|
||||
return {
|
||||
released,
|
||||
provider: {
|
||||
kind: 'example-kind',
|
||||
layerId: 'example-layer',
|
||||
entryFace: { icon: 'commute', label: 'RIDE' },
|
||||
labels: { view: 'Example view', exit: 'Exit example', exitText: 'EXIT' },
|
||||
candidate: () => ({ id: 'a1', name: 'Example 12' }),
|
||||
hold: () => true,
|
||||
read: () => ({
|
||||
id: 'a1',
|
||||
name: 'Example 12',
|
||||
latitude: 30,
|
||||
longitude: -97,
|
||||
heightM: 200,
|
||||
headingDeg: 90,
|
||||
eye: { upM: 2 },
|
||||
}),
|
||||
hud: () => ({ title: 'Example 12' }),
|
||||
release: (id, { restore }) => released.push([id, restore]),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("a provider's subject needs only its own layer, and never a Context change in flight", async (t) => {
|
||||
const { provider } = exampleSubject();
|
||||
let changing = false;
|
||||
const off = fixture(t, { subjects: [provider] });
|
||||
off.cockpit.syncEntry();
|
||||
await nextTick();
|
||||
assert.equal(off.$('#cockpit-entry').hidden, true, 'its layer is off');
|
||||
assert.equal(off.cockpit.enter(), false);
|
||||
const on = fixture(t, {
|
||||
enabled: ['example-layer'],
|
||||
subjects: [provider],
|
||||
readContext: () => ({ mode: null, changing }),
|
||||
});
|
||||
changing = true;
|
||||
on.cockpit.syncEntry();
|
||||
await nextTick();
|
||||
assert.equal(on.$('#cockpit-entry').hidden, true, 'Context is changing');
|
||||
changing = false;
|
||||
on.cockpit.syncEntry();
|
||||
await nextTick();
|
||||
assert.equal(on.$('#cockpit-entry').hidden, false);
|
||||
assert.match(on.$('#cockpit-entry').textContent, /RIDE/);
|
||||
assert.match(on.$('#cockpit-entry-readout').textContent, /commute/);
|
||||
});
|
||||
|
||||
test("a provider's view reports its subject, refuses voice entry and ends with its layer", async (t) => {
|
||||
const { provider, released } = exampleSubject();
|
||||
const { cockpit, coordinator, disable } = fixture(t, {
|
||||
enabled: ['example-layer', 'flights'],
|
||||
subjects: [provider],
|
||||
});
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
const state = coordinator.getCockpitState();
|
||||
assert.equal(state.active, true);
|
||||
assert.deepEqual(state.subject, {
|
||||
kind: 'example-kind',
|
||||
id: 'a1',
|
||||
layerId: 'example-layer',
|
||||
callsign: null,
|
||||
name: 'Example 12',
|
||||
});
|
||||
assert.equal(coordinator.controlCockpit('enter').ok, false);
|
||||
assert.match(coordinator._cockpitEntryRefusal(), /another first-person view/);
|
||||
disable('flights');
|
||||
assert.equal(cockpit.active, true, 'another layer is free to go off');
|
||||
disable('example-layer');
|
||||
assert.equal(cockpit.active, false, 'its own layer going off ends it');
|
||||
assert.deepEqual(released, [['a1', false]]);
|
||||
});
|
||||
|
||||
test("a provider's guards: a throwing candidate, gate or release, and a gate that is not true", async (t) => {
|
||||
const warned = [];
|
||||
t.mock.method(console, 'warn', (message) => warned.push(String(message)));
|
||||
const entered = (provider) => {
|
||||
const { cockpit } = fixture(t, {
|
||||
enabled: ['example-layer'],
|
||||
subjects: [provider],
|
||||
});
|
||||
cockpit.syncEntry();
|
||||
return { cockpit, entered: cockpit.enter() };
|
||||
};
|
||||
const { provider: base } = exampleSubject();
|
||||
// A candidate() that throws offers nothing.
|
||||
const noCandidate = entered({
|
||||
...base,
|
||||
candidate: () => {
|
||||
throw new Error('candidate failed');
|
||||
},
|
||||
});
|
||||
assert.equal(noCandidate.entered, false);
|
||||
assert.equal(noCandidate.cockpit.resolveEntry(), null);
|
||||
// An isEntryAllowed() that throws, or answers anything but true, shuts
|
||||
// the gate.
|
||||
for (const isEntryAllowed of [
|
||||
() => {
|
||||
throw new Error('gate failed');
|
||||
},
|
||||
() => 1,
|
||||
() => 'yes',
|
||||
() => ({}),
|
||||
]) {
|
||||
const gated = entered({ ...base, isEntryAllowed });
|
||||
assert.equal(gated.entered, false, String(isEntryAllowed));
|
||||
assert.equal(gated.cockpit.active, false);
|
||||
}
|
||||
// A release() that throws still ends the view.
|
||||
const { provider } = exampleSubject();
|
||||
const releasing = entered({
|
||||
...provider,
|
||||
release: () => {
|
||||
throw new Error('release failed');
|
||||
},
|
||||
});
|
||||
assert.equal(releasing.entered, true);
|
||||
assert.equal(releasing.cockpit.exit(), true);
|
||||
assert.equal(releasing.cockpit.active, false);
|
||||
assert.equal(document.body.classList.contains('cockpit-subject'), false);
|
||||
for (const method of ['candidate', 'isEntryAllowed', 'release'])
|
||||
assert.ok(
|
||||
warned.some((line) => line.includes(`${method}() failed`)),
|
||||
method,
|
||||
);
|
||||
});
|
||||
|
||||
test('a malformed provider is left out and the built-in kinds are unchanged', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const { cockpit } = fixture(t, {
|
||||
enabled: ['flights'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
subjects: [{ kind: 'aircraft', layerId: 'flights' }],
|
||||
});
|
||||
assert.deepEqual(cockpit.subjectProviders, []);
|
||||
cockpit.syncEntry();
|
||||
assert.equal(cockpit.enter(), true);
|
||||
assert.equal(cockpit.subjectKind, 'aircraft');
|
||||
});
|
||||
+106
-38
@@ -1,7 +1,11 @@
|
||||
/** Route Cockpit keys while preserving the active disclosure and form-control owner. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { lookKeyStep } from '../cockpitLook.js';
|
||||
import { isPointerFree } from '../data/inputOwnership.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import { findInput, findQuery } from '../render/rendererOf.js';
|
||||
import { trackedPositionNow } from './cockpitCamera.js';
|
||||
|
||||
/** How far from the followed track a double-click may land, CSS pixels. */
|
||||
export const SUBJECT_DOUBLE_CLICK_RADIUS_PX = 32;
|
||||
@@ -32,15 +36,13 @@ export const DOUBLE_CLICK_MEMORY_MS = 700;
|
||||
|
||||
/** Where the track `kind` would ride is drawn now, as a world position. */
|
||||
function subjectWorldPosition(kind) {
|
||||
if (kind === 'aircraft') {
|
||||
return (
|
||||
this.viewer.trackedEntity?.position?.getValue?.(
|
||||
this.viewer.clock?.currentTime,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
if (kind === 'aircraft')
|
||||
return trackedPositionNow(this.viewer, followedOf(this.viewer));
|
||||
if (kind === 'satellite')
|
||||
return this.services.satellitesLayer?.getCockpitPosition?.() ?? null;
|
||||
// An application's subject has no position before its view is entered:
|
||||
// the selected vessel's sprite must not stand in for it.
|
||||
if (kind !== 'vessel') return null;
|
||||
const info = this.readVesselInfo();
|
||||
if (!Number.isFinite(info?.latitude) || !Number.isFinite(info?.longitude))
|
||||
return null;
|
||||
@@ -51,19 +53,15 @@ function subjectWorldPosition(kind) {
|
||||
: Number.isFinite(info.seaSurfaceHeightM)
|
||||
? info.seaSurfaceHeightM
|
||||
: 0;
|
||||
return Cesium.Cartesian3.fromDegrees(info.longitude, info.latitude, heightM);
|
||||
return fromDegrees(info.longitude, info.latitude, heightM);
|
||||
}
|
||||
|
||||
/** The followed track's canvas position now, or null off screen. */
|
||||
function subjectCanvasPosition() {
|
||||
const kind = this.resolveEntryKind();
|
||||
const world = kind ? subjectWorldPosition.call(this, kind) : null;
|
||||
const scene = this.viewer.scene;
|
||||
if (!world || typeof scene?.cartesianToCanvasCoordinates !== 'function')
|
||||
return null;
|
||||
return (
|
||||
scene.cartesianToCanvasCoordinates(world, new Cesium.Cartesian2()) ?? null
|
||||
);
|
||||
if (!world) return null;
|
||||
return findQuery(this.viewer)?.project(world) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -120,34 +118,101 @@ export function onSceneDoubleClick(position, nowMs = performance.now()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Hold the renderer's own double-click follow off; returns the release. */
|
||||
const holdStockFollow = (viewer) =>
|
||||
findInput(viewer)?.behaviours?.dblclickFollow?.suppress?.() ?? null;
|
||||
|
||||
/**
|
||||
* Take the scene's double-click through the Cockpit first. Cesium's Viewer
|
||||
* installs its own (pickAndTrackObject), which untracks whenever the pick is
|
||||
* not an Entity: on a followed aircraft's model, a primitive, it would drop
|
||||
* the very track the double-click means to ride. A double-click on the
|
||||
* followed track is the Cockpit's, as is one on a mapped ground point in
|
||||
* orbit (a focus); any other goes on to Cesium's.
|
||||
* @returns {() => void} Puts Cesium's handler back, unless another owner
|
||||
* (the draw tool borrows it) has replaced ours since.
|
||||
* How long a press on the followed track keeps the stock follow off, and
|
||||
* how soon after a press the next one may end a double-click with it.
|
||||
*/
|
||||
const SUBJECT_PRESS_HOLD_MS = 700;
|
||||
|
||||
/** How far apart, CSS pixels, two presses of one double-click may land. */
|
||||
const DOUBLE_CLICK_SLOP_PX = 8;
|
||||
|
||||
/**
|
||||
* Take the scene's double-click on the followed track for the Cockpit. The
|
||||
* renderer's own double-click follow lets go of whatever is followed when
|
||||
* the double-click does not land on something it can follow itself: on a
|
||||
* followed aircraft's model it would drop the very track the double-click
|
||||
* means to ride. It runs before any subscriber and cannot be refused from
|
||||
* one, so a press on the followed track holds it off for that press
|
||||
* (`behaviours.dblclickFollow`, a hold a `down` subscriber takes covers its
|
||||
* press), and the double-click it ends in enters. A double-click anywhere
|
||||
* else is the renderer's, as before. The renderer decides a double-click's
|
||||
* stock follow from its second press, as the hold stood when that press
|
||||
* went down, so a press that cannot end a double-click on the track (no
|
||||
* press on the track came just before it, at about the same spot) gives
|
||||
* its hold back at its release: a second press off the track then finds
|
||||
* the follow free. In orbit a press on a mapped ground point holds it
|
||||
* off the same way, and the double-click it ends in is a focus. `this.holdStockFollow`, when set, takes
|
||||
* the hold in place of the renderer's input port (tests).
|
||||
* @returns {() => void} Stops listening and lets any hold go.
|
||||
*/
|
||||
export function routeSceneDoubleClick() {
|
||||
const handler = this.viewer.screenSpaceEventHandler;
|
||||
if (typeof handler?.setInputAction !== 'function') return () => {};
|
||||
const type = Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK;
|
||||
const stock = handler.getInputAction?.(type) ?? null;
|
||||
const routed = (event) => {
|
||||
if (this.onSceneDoubleClick(event?.position)) return;
|
||||
let input;
|
||||
try {
|
||||
input = inputFor(this.viewer);
|
||||
} catch {
|
||||
// A viewer with no input to take (headless tools, partial stubs) has no
|
||||
// double-click to route.
|
||||
return () => {};
|
||||
}
|
||||
let release = null;
|
||||
let timer = null;
|
||||
// The last left press (when, where, and whether it was on the track),
|
||||
// and whether the held press could end a double-click on the track.
|
||||
let last = null;
|
||||
let endsDouble = false;
|
||||
const drop = () => {
|
||||
globalThis.clearTimeout(timer);
|
||||
timer = null;
|
||||
release?.();
|
||||
release = null;
|
||||
};
|
||||
// Ambient `down`/`up` are the unmodified left button's, while the
|
||||
// pointer is free.
|
||||
const offDown = input.onPointer('down', ({ position }) => {
|
||||
drop();
|
||||
const at = Date.now();
|
||||
const onSubject =
|
||||
!this.destroyed &&
|
||||
isPointerFree() &&
|
||||
(this.active
|
||||
? Boolean(this.orbitalSiteUnder?.(position))
|
||||
: doubleClickHitsSubject(position, subjectCanvasPosition.call(this)));
|
||||
endsDouble =
|
||||
!!last?.onSubject &&
|
||||
at - last.at <= SUBJECT_PRESS_HOLD_MS &&
|
||||
Math.hypot(position?.x - last.x, position?.y - last.y) <=
|
||||
DOUBLE_CLICK_SLOP_PX;
|
||||
last = { at, x: position?.x, y: position?.y, onSubject };
|
||||
if (!onSubject) return;
|
||||
release = this.holdStockFollow
|
||||
? this.holdStockFollow()
|
||||
: holdStockFollow(this.viewer);
|
||||
// A press that ends in no double-click gives the follow back by itself.
|
||||
timer = globalThis.setTimeout(drop, SUBJECT_PRESS_HOLD_MS);
|
||||
});
|
||||
const offUp = input.onPointer('up', () => {
|
||||
if (!endsDouble) drop();
|
||||
});
|
||||
const offDouble = input.onPointer('dblclick', ({ position }) => {
|
||||
// In orbit, a double-click on a mapped ground point is a focus, never a
|
||||
// retarget that would end the view.
|
||||
if (this.onOrbitalDoubleClick?.(event?.position)) return;
|
||||
stock?.(event);
|
||||
};
|
||||
handler.setInputAction(routed, type);
|
||||
if (!this.onSceneDoubleClick(position))
|
||||
this.onOrbitalDoubleClick?.(position);
|
||||
// The hold covers the whole double-click: it is given back once the
|
||||
// dispatch is over.
|
||||
|
||||
queueMicrotask(drop);
|
||||
});
|
||||
return () => {
|
||||
if (handler.isDestroyed?.() || handler.getInputAction?.(type) !== routed)
|
||||
return;
|
||||
if (stock) handler.setInputAction(stock, type);
|
||||
else handler.removeInputAction(type);
|
||||
offDown();
|
||||
offUp();
|
||||
offDouble();
|
||||
drop();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -189,7 +254,7 @@ const LOOK_KEY_OWNERS = [
|
||||
* @returns {boolean} True when the key was taken.
|
||||
*/
|
||||
function handleLookKey(event) {
|
||||
if (!this.active || this.subjectKind !== 'vessel') return false;
|
||||
if (!this.looksAround) return false;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return false;
|
||||
const step = lookKeyStep(event.key, event.shiftKey);
|
||||
const reset = !event.repeat && (event.key === 'Home' || event.key === '0');
|
||||
@@ -245,6 +310,9 @@ export function onKeyDown(event) {
|
||||
if (event.target?.closest?.('.cesium-credit-lightbox')) return;
|
||||
// An open Display or Radio popover takes Escape itself.
|
||||
if (this.isUtilityDisclosureOpen?.()) return;
|
||||
// So do the Data Layers search field and filter menu.
|
||||
if (event.target?.closest?.('.layer-finder__field, .layer-finder__menu'))
|
||||
return;
|
||||
if (this.context?.contains(event.target) && !this.contextCollapsed) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
|
||||
@@ -52,7 +52,7 @@ function createRimState(value) {
|
||||
*/
|
||||
export function createInstrumentState() {
|
||||
return {
|
||||
// 'aircraft' or 'vessel': which readouts the HUD labels and shows.
|
||||
// 'aircraft', 'vessel' or 'subject': which readouts the HUD shows.
|
||||
kind: 'aircraft',
|
||||
layer: null,
|
||||
callsign: t('AIRCRAFT'),
|
||||
@@ -76,6 +76,19 @@ export function createInstrumentState() {
|
||||
look: { offset: false, yawDeg: 0, readout: '' },
|
||||
clock: '--:--:--Z',
|
||||
position: '--° · --°',
|
||||
// A provider subject's HUD (kind 'subject', cockpitSubjectProviders.js):
|
||||
// its kicker, speed unit and tag, readouts, sources, banner, veil and
|
||||
// progress line, all worded by the provider.
|
||||
kicker: '',
|
||||
speedUnit: '',
|
||||
speedTag: '',
|
||||
speedTone: 'normal',
|
||||
readouts: [],
|
||||
sources: [],
|
||||
banner: null,
|
||||
veil: null,
|
||||
progress: null,
|
||||
lookEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -86,8 +99,10 @@ export function createInstrumentState() {
|
||||
*/
|
||||
export function createRouteState() {
|
||||
return {
|
||||
// A vessel's card shows only the free-text AIS destination.
|
||||
// A vessel's card shows only the free-text AIS destination; a provider's
|
||||
// subject's (kind 'subject') carries its own title.
|
||||
kind: 'aircraft',
|
||||
title: '',
|
||||
visible: false,
|
||||
from: t('UNKNOWN'),
|
||||
to: t('UNKNOWN'),
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
vesselCameraProfile,
|
||||
} from '../cockpitSubjects.js';
|
||||
import { lookIsOffset, lookReadoutParts, wrapLookYaw } from '../cockpitLook.js';
|
||||
import { cockpitSubjectHudView } from '../cockpitSubjectProviders.js';
|
||||
import {
|
||||
RADAR_MAX_CONTACTS,
|
||||
radarPicture,
|
||||
@@ -90,6 +91,13 @@ export function publishInstrumentsView() {
|
||||
compass: view.compass.map((division) => ({ ...division })),
|
||||
compassMarkers: { ...view.compassMarkers },
|
||||
look: { ...view.look },
|
||||
// A provider's view model is rebuilt on each HUD update, never edited
|
||||
// in place, so it is published as it stands.
|
||||
readouts: view.readouts,
|
||||
sources: view.sources,
|
||||
banner: view.banner,
|
||||
veil: view.veil,
|
||||
progress: view.progress,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -118,24 +126,162 @@ function wordLook({ side, bearingDeg, elevation, angleDeg }) {
|
||||
*/
|
||||
export function presentLook() {
|
||||
const target = this.lookTarget;
|
||||
// A provider's view words its own readout (its HUD view's `lookReadout`).
|
||||
const provider = Boolean(this.subjectProvider);
|
||||
const rest = provider ? this.lookRestPitch : VESSEL_BRIDGE_PITCH_DEG;
|
||||
const offset =
|
||||
this.active &&
|
||||
this.subjectKind === 'vessel' &&
|
||||
lookIsOffset(target, VESSEL_BRIDGE_PITCH_DEG);
|
||||
(this.active && this.subjectKind === 'vessel') ||
|
||||
(provider && this.looksAround)
|
||||
? lookIsOffset(target, rest)
|
||||
: false;
|
||||
this.instruments.look = offset
|
||||
? {
|
||||
offset: true,
|
||||
yawDeg: wrapLookYaw(target.yawDeg),
|
||||
readout: wordLook(lookReadoutParts(target, VESSEL_BRIDGE_PITCH_DEG)),
|
||||
readout: provider
|
||||
? (this.subjectHud?.lookReadout ?? '')
|
||||
: wordLook(lookReadoutParts(target, VESSEL_BRIDGE_PITCH_DEG)),
|
||||
}
|
||||
: { offset: false, yawDeg: 0, readout: '' };
|
||||
}
|
||||
|
||||
/** Live Signals' tone for a provider's signal row. */
|
||||
const SUBJECT_SIGNAL_TONES = Object.freeze({
|
||||
warning: 'warning',
|
||||
alert: 'warning',
|
||||
});
|
||||
|
||||
/**
|
||||
* Present a provider subject's HUD: its view model (cockpitSubjectHudView)
|
||||
* in the generic readouts, the compass at the camera's heading, the route
|
||||
* card, and its signals in Live Signals. A HUD view that is null, a `hud()`
|
||||
* that throws, or a view whose reading throws keeps the last one. Contact
|
||||
* navigation stays with aircraft, so the Contact card is withdrawn.
|
||||
*/
|
||||
function updateSubjectHud(info, nowMs, forceContext) {
|
||||
const provider = this.subjectProvider;
|
||||
this.lastSubjectInfo = info;
|
||||
const frame = this.lastSubjectFrame;
|
||||
const look = {
|
||||
yawDeg: this.lookTarget?.yawDeg ?? 0,
|
||||
pitchDeg: this.lookTarget?.pitchDeg ?? 0,
|
||||
offset:
|
||||
this.looksAround && lookIsOffset(this.lookTarget, this.lookRestPitch),
|
||||
};
|
||||
const raw = frame
|
||||
? this.callSubject(
|
||||
provider,
|
||||
'hud',
|
||||
[frame, Object.freeze({ ...this.subjectContext(), look })],
|
||||
null,
|
||||
)
|
||||
: null;
|
||||
if (raw != null)
|
||||
this.subjectHud = cockpitSubjectHudView(raw) ?? this.subjectHud;
|
||||
const hud = this.subjectHud ?? cockpitSubjectHudView(null);
|
||||
const view = this.instruments;
|
||||
view.kind = 'subject';
|
||||
view.trackSource = null;
|
||||
view.kicker = hud.kicker || provider.labels.kicker;
|
||||
view.callsign = hud.title || info.name || '';
|
||||
// While the floor under a subject with no height is acquired
|
||||
// (cockpitCamera.js), the meta line says so in place of the provider's.
|
||||
const acquiring = this.surfaceAcquiring === true;
|
||||
view.meta.text = acquiring ? t('ACQUIRING SURFACE') : hud.meta.text;
|
||||
view.meta.tone = acquiring ? 'warning' : hud.meta.tone;
|
||||
view.meta.emergency = !acquiring && hud.meta.tone === 'alert';
|
||||
const speed = hud.speed?.value ?? null;
|
||||
view.speed = hud.speed
|
||||
? {
|
||||
text: speed === null ? '---' : formatNumber(Math.round(speed)),
|
||||
value: speed === null ? null : Math.round(speed),
|
||||
immediate: forceContext,
|
||||
}
|
||||
: null;
|
||||
view.speedUnit = hud.speed?.unit ?? '';
|
||||
view.speedTag = hud.speed?.tag ?? '';
|
||||
view.speedTone = hud.speed?.tone ?? 'normal';
|
||||
view.speedRim.unavailable = true;
|
||||
view.altitude = null;
|
||||
view.altitudeRim.unavailable = true;
|
||||
view.course = null;
|
||||
const heading = normalizeHeading(this.heading ?? info.track ?? 0);
|
||||
view.heading = {
|
||||
text: formatHeadingReadout(heading),
|
||||
value: heading,
|
||||
immediate: forceContext,
|
||||
};
|
||||
const viewHeading = normalizeHeading(
|
||||
heading + (provider.look ? (this.lookView?.yawDeg ?? 0) : 0),
|
||||
);
|
||||
view.compass = scrollingCompassDivisions(viewHeading).map((division) => ({
|
||||
slot: division.slot,
|
||||
heading: division.heading,
|
||||
active: division.nearest,
|
||||
label: compassPointLabel(formatCompassDivision(division.heading)),
|
||||
}));
|
||||
view.compassMarkers = {
|
||||
prograde: compassMarkerSlot(heading, viewHeading),
|
||||
retrograde: compassMarkerSlot(heading + 180, viewHeading),
|
||||
};
|
||||
view.clock = new Date().toISOString().slice(11, 19) + 'Z';
|
||||
view.position = `${formatCockpitCoordinate(info.latitude, 'N', 'S')} · ${formatCockpitCoordinate(info.longitude, 'E', 'W')}`;
|
||||
view.readouts = hud.readouts;
|
||||
view.sources = hud.sources;
|
||||
view.banner = hud.banner;
|
||||
view.veil = hud.veil;
|
||||
view.progress = hud.progress;
|
||||
view.lookEnabled = Boolean(provider.look);
|
||||
view.layer = provider.layerId;
|
||||
this.presentLook();
|
||||
this.publishInstrumentsView();
|
||||
const route = this.routeView;
|
||||
route.kind = 'subject';
|
||||
route.title = hud.route?.title ?? '';
|
||||
route.from = hud.route?.from ?? '';
|
||||
route.to = hud.route?.to ?? '';
|
||||
route.status = hud.route?.status ?? '';
|
||||
route.visible = Boolean(hud.route);
|
||||
// No destination arrow; clearing also publishes the card.
|
||||
this.clearPredictiveRoute();
|
||||
if (
|
||||
forceContext ||
|
||||
cockpitUiUpdateDue(
|
||||
nowMs,
|
||||
this.lastContextUpdateMs,
|
||||
COCKPIT_CONTEXT_UPDATE_MS,
|
||||
)
|
||||
) {
|
||||
this.lastContextUpdateMs = nowMs;
|
||||
this.updateLocalPosition(info);
|
||||
this.maybeRefreshRegionalBrief(info);
|
||||
this.showContextCard(false);
|
||||
const keys = new Set();
|
||||
for (const signal of hud.signals) {
|
||||
const key = `subject:${signal.id}`;
|
||||
keys.add(key);
|
||||
this.pushCockpitSignal(
|
||||
key,
|
||||
SUBJECT_SIGNAL_TONES[signal.tone] ?? 'info',
|
||||
signal.title,
|
||||
signal.detail || signal.title,
|
||||
);
|
||||
}
|
||||
for (const key of this.subjectSignalKeys ?? [])
|
||||
if (!keys.has(key)) this.dropCockpitSignal(key);
|
||||
this.subjectSignalKeys = keys;
|
||||
}
|
||||
}
|
||||
|
||||
export function updateHud(
|
||||
info,
|
||||
nowMs = performance.now(),
|
||||
forceContext = false,
|
||||
) {
|
||||
if (this.subjectProvider && info?.generic === true) {
|
||||
updateSubjectHud.call(this, info, nowMs, forceContext);
|
||||
return;
|
||||
}
|
||||
if (info?.kind === 'vessel') {
|
||||
updateVesselHud.call(this, info, nowMs, forceContext);
|
||||
return;
|
||||
|
||||
@@ -99,6 +99,7 @@ export function syncContextLayout() {
|
||||
let safeBottom = window.innerHeight - 24;
|
||||
for (const selector of [
|
||||
'#cesium-credits',
|
||||
'#gev-credits',
|
||||
'#command-dock',
|
||||
'#view-switcher',
|
||||
]) {
|
||||
|
||||
@@ -45,7 +45,7 @@ function fixture(t) {
|
||||
test('the orbital HUD is hidden until a satellite view is published', async (t) => {
|
||||
const f = fixture(t);
|
||||
assert.equal(f.section().hidden, true);
|
||||
assert.equal(f.section().querySelector('#cockpit-orbital-zoom-in'), null);
|
||||
assert.equal(f.section().querySelector('#cockpit-orbital-zoom-in') === null, true);
|
||||
});
|
||||
|
||||
test('a published orbital view renders its readouts and zoom controls', async (t) => {
|
||||
@@ -97,7 +97,7 @@ test('an unknown velocity leaves its row out', async (t) => {
|
||||
const f = fixture(t);
|
||||
f.store.publishOrbital({ ...VIEW, velocityMps: null });
|
||||
await nextTick();
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-velocity'), null);
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-velocity') === null, true);
|
||||
assert.equal(f.text('.cockpit-orbital-altitude'), '418 KM');
|
||||
});
|
||||
|
||||
@@ -145,7 +145,7 @@ test('publishing null hides the orbital HUD again', async (t) => {
|
||||
f.store.publishOrbital(null);
|
||||
await nextTick();
|
||||
assert.equal(f.section().hidden, true);
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-name'), null);
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-name') === null, true);
|
||||
});
|
||||
|
||||
const ISS_TLE = Object.freeze({
|
||||
@@ -160,7 +160,7 @@ test('the place below shows at the top once known', async (t) => {
|
||||
const f = fixture(t);
|
||||
f.store.publishOrbital({ ...VIEW, place: undefined });
|
||||
await nextTick();
|
||||
assert.equal(f.section().querySelector('#cockpit-orbital-over'), null);
|
||||
assert.equal(f.section().querySelector('#cockpit-orbital-over') === null, true);
|
||||
const over = () =>
|
||||
f.section().querySelector('#cockpit-orbital-over strong')?.textContent;
|
||||
f.store.publishOrbital({
|
||||
@@ -195,7 +195,7 @@ test('the place below shows at the top once known', async (t) => {
|
||||
// says nothing rather than call land open ocean.
|
||||
f.store.publishOrbital({ ...VIEW, place: null });
|
||||
await nextTick();
|
||||
assert.equal(document.querySelector('#cockpit-orbital-over'), null);
|
||||
assert.equal(document.querySelector('#cockpit-orbital-over') === null, true);
|
||||
});
|
||||
|
||||
test('an owner country shows its flag from the sheet, or its code if the sheet will not load', async (t) => {
|
||||
@@ -216,7 +216,7 @@ test('an owner country shows its flag from the sheet, or its code if the sheet w
|
||||
owner: { countryCode: 'US', label: 'USA' },
|
||||
});
|
||||
await nextTick();
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-flag'), null);
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-flag') === null, true);
|
||||
assert.equal(images.length, 1, 'the sheet is asked for');
|
||||
images[0].onerror();
|
||||
await settle();
|
||||
@@ -244,7 +244,7 @@ test('an owner country shows its flag from the sheet, or its code if the sheet w
|
||||
flag.style.backgroundPosition,
|
||||
ownerFlagStyle('FR').backgroundPosition,
|
||||
);
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-owner-badge'), null);
|
||||
assert.equal(f.section().querySelector('.cockpit-orbital-owner-badge') === null, true);
|
||||
});
|
||||
|
||||
test('the readout names the owner, operator and element set', async (t) => {
|
||||
@@ -327,7 +327,7 @@ test('unknown identity fields leave their rows out', async (t) => {
|
||||
'.cockpit-orbital-ident',
|
||||
'#cockpit-orbital-tle',
|
||||
])
|
||||
assert.equal(f.section().querySelector(selector), null, selector);
|
||||
assert.equal(f.section().querySelector(selector) === null, true, selector);
|
||||
// An element set with no NORAD id still dates itself.
|
||||
f.store.publishOrbital({ ...VIEW, tle: ISS_TLE });
|
||||
await nextTick();
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
* (src/ui/cockpitOrbitalView.js); its state lives on the orbital session, so
|
||||
* it ends with the session.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import { findQuery } from '../render/rendererOf.js';
|
||||
import { clampOrbitalLook, easeLook } from '../cockpitLook.js';
|
||||
import { ORBITAL_EARTH_RADIUS_M } from '../cockpitOrbital.js';
|
||||
import {
|
||||
@@ -113,11 +115,11 @@ function sitePosition(site) {
|
||||
: null;
|
||||
}
|
||||
|
||||
/** The mapped site a canvas position shows, through the layer's pick ids. */
|
||||
/** The mapped site a canvas position shows, through the layer's picks. */
|
||||
function siteAt(controller, position) {
|
||||
let picked = null;
|
||||
try {
|
||||
picked = controller.viewer.scene?.pick?.(position) ?? null;
|
||||
picked = findQuery(controller.viewer)?.pick(position.x, position.y) ?? null;
|
||||
} catch {
|
||||
picked = null;
|
||||
}
|
||||
@@ -215,10 +217,25 @@ export function toggleOrbitalFocus(key) {
|
||||
return site ? startFocus.call(this, site) : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a press at `position` lands on a mapped ground point in orbit:
|
||||
* the double-click it may begin is a focus, so the renderer's own
|
||||
* double-click follow is held off for it.
|
||||
* @param {{x: number, y: number}|null|undefined} position Canvas position.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function orbitalSiteUnder(position) {
|
||||
if (!inOrbit(this) || !isPointerFree()) return false;
|
||||
if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y))
|
||||
return false;
|
||||
return Boolean(siteAt(this, position));
|
||||
}
|
||||
|
||||
/**
|
||||
* A double-click on the orbital picture. On a mapped ground point it keeps
|
||||
* or starts the focus on it (as a single click does) and is taken: Cesium's
|
||||
* own double-click would track that point, which ends the view. Any other
|
||||
* or starts the focus on it (as a single click does) and is taken: the
|
||||
* renderer's own double-click would follow that point, which ends the view
|
||||
* (its press held that follow off, `orbitalSiteUnder`). Any other
|
||||
* double-click, one a tool owns, and every one outside orbit go on.
|
||||
* @param {{x: number, y: number}|null|undefined} position Canvas position.
|
||||
* @returns {boolean} True when it landed on a ground point and was taken.
|
||||
@@ -257,27 +274,19 @@ export function onOrbitalClick(position) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Take the scene's single click through the orbital focus first, then hand
|
||||
* it on to Cesium's own (it picks into `selectedEntity`), as before.
|
||||
* @returns {() => void} Puts Cesium's handler back, unless another owner
|
||||
* (the draw tool borrows it) has replaced ours since.
|
||||
* Take the scene's single click through the orbital focus, alongside the
|
||||
* other click subscribers and the renderer's own select, as before.
|
||||
* @returns {() => void} Stops listening.
|
||||
*/
|
||||
export function routeSceneClick() {
|
||||
const handler = this.viewer.screenSpaceEventHandler;
|
||||
if (typeof handler?.setInputAction !== 'function') return () => {};
|
||||
const type = Cesium.ScreenSpaceEventType.LEFT_CLICK;
|
||||
const stock = handler.getInputAction?.(type) ?? null;
|
||||
const routed = (event) => {
|
||||
this.onOrbitalClick(event?.position);
|
||||
stock?.(event);
|
||||
};
|
||||
handler.setInputAction(routed, type);
|
||||
return () => {
|
||||
if (handler.isDestroyed?.() || handler.getInputAction?.(type) !== routed)
|
||||
return;
|
||||
if (stock) handler.setInputAction(stock, type);
|
||||
else handler.removeInputAction(type);
|
||||
};
|
||||
let input;
|
||||
try {
|
||||
input = inputFor(this.viewer);
|
||||
} catch {
|
||||
// A viewer with no input (headless tools, partial stubs) has no clicks.
|
||||
return () => {};
|
||||
}
|
||||
return input.onClick((event) => this.onOrbitalClick(event?.position));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -408,7 +417,7 @@ export function orbitalSitesInReach(info) {
|
||||
let sites = [];
|
||||
try {
|
||||
sites = layer.getNearby(
|
||||
Cesium.Cartesian3.fromDegrees(info.longitude, info.latitude, 0),
|
||||
fromDegrees(info.longitude, info.latitude, 0),
|
||||
rangeM,
|
||||
SITE_QUERY_MAX,
|
||||
);
|
||||
|
||||
@@ -12,6 +12,17 @@ import assert from 'node:assert/strict';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, defineComponent, h, nextTick } from 'vue';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
bindFakeCesiumCamera,
|
||||
followEntity,
|
||||
} from '../testSupport/fakeCameraPort.mjs';
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
|
||||
import {
|
||||
FAKE_EVENT_TYPES,
|
||||
FakeScreenSpaceEventHandler,
|
||||
fakeInput,
|
||||
} from '../input/testDoubles.mjs';
|
||||
import { CockpitViewController } from './cockpitController.js';
|
||||
import { setLocale, t as translate } from '../i18n/index.js';
|
||||
import { useCockpitStore } from './stores/cockpit.js';
|
||||
@@ -118,10 +129,9 @@ function installationsLayer() {
|
||||
const record = layer.records.find((r) => r.id === String(id));
|
||||
return record ? layer.withPosition(record) : null;
|
||||
},
|
||||
findByPick(picked) {
|
||||
const id =
|
||||
picked?.id?.installationId ||
|
||||
(typeof picked?.id?.id === 'string' ? picked.id.id : null);
|
||||
// A query hit on a named marker carries its installation id.
|
||||
findByPick(hit) {
|
||||
const id = hit?.meta?.installationId ?? null;
|
||||
return id ? layer.getById(id) : null;
|
||||
},
|
||||
};
|
||||
@@ -205,7 +215,7 @@ function satellitesLayer(viewer) {
|
||||
if (!positions.has(id)) return false;
|
||||
layer.calls.push(['track', id]);
|
||||
layer.tracked = id;
|
||||
viewer.trackedEntity = { position: { getValue: () => layer.position(id) } };
|
||||
followEntity(viewer, { position: { getValue: () => layer.position(id) } });
|
||||
return true;
|
||||
},
|
||||
setCockpitSubject(noradId) {
|
||||
@@ -238,7 +248,6 @@ function fixture(t, { reducedMotion = false } = {}) {
|
||||
const shots = [];
|
||||
const picks = new Map();
|
||||
const viewer = {
|
||||
trackedEntity: undefined,
|
||||
clock: { currentTime: null },
|
||||
camera: {
|
||||
frustum: { fov: 1, aspectRatio: ASPECT },
|
||||
@@ -255,41 +264,46 @@ function fixture(t, { reducedMotion = false } = {}) {
|
||||
scene: {
|
||||
preUpdate: listeners(),
|
||||
screenSpaceCameraController: { enableInputs: true },
|
||||
pick: (position) => picks.get(`${position.x},${position.y}`),
|
||||
},
|
||||
trackedEntityChanged: listeners(),
|
||||
};
|
||||
// The Viewer's own input handler: its single click picks into
|
||||
// selectedEntity; its double-click tracks what it picks, which would end
|
||||
// the orbital view.
|
||||
const actions = new Map();
|
||||
// The renderer's own click and double-click: its click picks into its
|
||||
// selection; its double-click follows what it picks, which would end the
|
||||
// orbital view. Counted when the scene's input lets them run.
|
||||
const handler = {
|
||||
stockClicks: 0,
|
||||
stockDoubleClicks: 0,
|
||||
getInputAction: (type) => actions.get(type),
|
||||
setInputAction: (action, type) => actions.set(type, action),
|
||||
removeInputAction: (type) => actions.delete(type),
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
handler.stock = () => {
|
||||
handler.stockClicks += 1;
|
||||
};
|
||||
handler.stockDouble = ({ position }) => {
|
||||
handler.stockDoubleClicks += 1;
|
||||
const picked = viewer.scene.pick(position);
|
||||
viewer.trackedEntity = picked
|
||||
? { position: { getValue: () => null } }
|
||||
: undefined;
|
||||
const picked = picks.get(`${position.x},${position.y}`);
|
||||
followEntity(viewer, picked ? { position: { getValue: () => null } } : null);
|
||||
};
|
||||
actions.set(Cesium.ScreenSpaceEventType.LEFT_CLICK, handler.stock);
|
||||
actions.set(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK, handler.stockDouble);
|
||||
viewer.screenSpaceEventHandler = handler;
|
||||
// The viewer's stock handler holds them, so the scene's input has them to
|
||||
// hold off.
|
||||
const stock = new FakeScreenSpaceEventHandler();
|
||||
stock.setInputAction(() => {}, FAKE_EVENT_TYPES.LEFT_CLICK);
|
||||
stock.setInputAction(handler.stockDouble, FAKE_EVENT_TYPES.LEFT_DOUBLE_CLICK);
|
||||
viewer.screenSpaceEventHandler = stock;
|
||||
|
||||
const sites = installationsLayer();
|
||||
const satellites = satellitesLayer(viewer);
|
||||
const modeEvents = [];
|
||||
const onMode = (event) => modeEvents.push(event.detail);
|
||||
window.addEventListener('gev:cockpit-mode-changed', onMode);
|
||||
// The Cockpit drives the camera, reads frames and picks through ports: the
|
||||
// Cesium camera port over the fake camera, and a pick that answers from
|
||||
// the named markers the test draws.
|
||||
const ports = fakeScenePorts(viewer);
|
||||
bindFakeCesiumCamera(viewer, {
|
||||
...ports,
|
||||
query: {
|
||||
...ports.query,
|
||||
pick: (x, y) =>
|
||||
picks.get(`${x},${y}`) ?? { set: '', id: '', surface: true },
|
||||
},
|
||||
});
|
||||
const input = fakeInput(viewer);
|
||||
const cockpit = new CockpitViewController(viewer, {
|
||||
services: {
|
||||
flightsLayer: { getTrackedInfo: () => null },
|
||||
@@ -318,6 +332,15 @@ function fixture(t, { reducedMotion = false } = {}) {
|
||||
signals: (rows) => store.publishSignals(rows),
|
||||
},
|
||||
});
|
||||
let stockHolds = 0;
|
||||
cockpit.holdStockFollow = () => {
|
||||
stockHolds += 1;
|
||||
let held = true;
|
||||
return () => {
|
||||
if (held) stockHolds -= 1;
|
||||
held = false;
|
||||
};
|
||||
};
|
||||
Object.assign(cockpit, {
|
||||
setVisionMode() {},
|
||||
showBriefPage() {},
|
||||
@@ -329,11 +352,13 @@ function fixture(t, { reducedMotion = false } = {}) {
|
||||
updateContext() {},
|
||||
updateRoute() {},
|
||||
});
|
||||
// Named markers pick as `{ installationId }`, as the layer draws them.
|
||||
// Named markers pick as items carrying `{ installationId }`, as the layer
|
||||
// draws them.
|
||||
for (const site of Object.values(SITES))
|
||||
picks.set(`${site.at.x},${site.at.y}`, {
|
||||
id: { installationId: site.id },
|
||||
primitive: {},
|
||||
set: 'installations:named',
|
||||
id: site.id,
|
||||
meta: { installationId: site.id },
|
||||
});
|
||||
|
||||
const originalNow = performance.now;
|
||||
@@ -345,6 +370,7 @@ function fixture(t, { reducedMotion = false } = {}) {
|
||||
t.after(() => {
|
||||
window.removeEventListener('gev:cockpit-mode-changed', onMode);
|
||||
cockpit.stop();
|
||||
input.destroy();
|
||||
app.unmount();
|
||||
globalThis.matchMedia = previousMatchMedia;
|
||||
performance.now = originalNow;
|
||||
@@ -357,7 +383,11 @@ function fixture(t, { reducedMotion = false } = {}) {
|
||||
cockpit.update();
|
||||
return shots.at(-1);
|
||||
};
|
||||
const fire = (type, position) => actions.get(type)?.({ position });
|
||||
/** A click, with the renderer's own click when the input lets it run. */
|
||||
const click = (position) => {
|
||||
if (input.stockEnabled('select')) handler.stockClicks += 1;
|
||||
input.tap(position);
|
||||
};
|
||||
return {
|
||||
$: (selector) => document.querySelector(selector),
|
||||
cockpit,
|
||||
@@ -369,12 +399,20 @@ function fixture(t, { reducedMotion = false } = {}) {
|
||||
satellites,
|
||||
modeEvents,
|
||||
frame,
|
||||
click: (position) => fire(Cesium.ScreenSpaceEventType.LEFT_CLICK, position),
|
||||
/** A double-click as Cesium fires it: two clicks, then the double. */
|
||||
input,
|
||||
click,
|
||||
/**
|
||||
* A double-click as the scene's input sees it: a click, a second press
|
||||
* and the double. The renderer's own follow runs unless the second
|
||||
* press held it off.
|
||||
*/
|
||||
doubleClick(position) {
|
||||
fire(Cesium.ScreenSpaceEventType.LEFT_CLICK, position);
|
||||
fire(Cesium.ScreenSpaceEventType.LEFT_CLICK, position);
|
||||
fire(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK, position);
|
||||
click(position);
|
||||
input.down(position);
|
||||
input.up(position);
|
||||
if (stockHolds === 0 && input.stockEnabled('dblclickFollow'))
|
||||
handler.stockDouble({ position });
|
||||
input.dblclick(position);
|
||||
},
|
||||
/** Rebuild the Context card on the next frame, past its clock. */
|
||||
refreshCard() {
|
||||
@@ -615,7 +653,7 @@ test('a double-click on a site focuses it and keeps the orbital view', async (t)
|
||||
const { cockpit, viewer, handler } = scene;
|
||||
scene.doubleClick(SITES.alpha.at);
|
||||
assert.equal(handler.stockDoubleClicks, 0, 'Cesium does not track the site');
|
||||
assert.equal(viewer.trackedEntity, undefined);
|
||||
assert.equal(followedOf(viewer), null);
|
||||
scene.frame();
|
||||
assert.equal(cockpit.active, true, 'still in orbit');
|
||||
assert.equal(cockpit.orbital.focus.key, SITES.alpha.id);
|
||||
@@ -701,7 +739,7 @@ test('a satellite row rides it, staying in orbit; RETURN goes back', async (t) =
|
||||
assert.equal(newTrack.length, 1);
|
||||
assert.ok(newTrack[0].timestamp > firstTrack.timestamp, 'the new ride’s own time');
|
||||
assert.deepEqual(satellites.calls.slice(-2), [['track', 49260], ['subject', 49260]]);
|
||||
assert.equal(viewer.trackedEntity, undefined, 'the Cockpit keeps the camera');
|
||||
assert.equal(followedOf(viewer), null, 'the Cockpit keeps the camera');
|
||||
assert.equal(cockpit.subjectId, 49260);
|
||||
assert.equal(cockpit.orbital.focus, null, 'the focus is reset');
|
||||
assert.equal(modeEvents.at(-1)?.active, true);
|
||||
@@ -891,14 +929,14 @@ test('reduced motion cuts onto the site, back, and between satellites', async (t
|
||||
assert.ok(Cesium.Cartesian3.distance(shot.destination, scene.satellites.position(49260)) < 1);
|
||||
});
|
||||
|
||||
test('stopping the Cockpit hands both clicks back to Cesium', async (t) => {
|
||||
const scene = fixture(t);
|
||||
const click = Cesium.ScreenSpaceEventType.LEFT_CLICK;
|
||||
const double = Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK;
|
||||
assert.notEqual(scene.handler.getInputAction(click), scene.handler.stock);
|
||||
test('stopping the Cockpit leaves both clicks to the renderer', async (t) => {
|
||||
const scene = await inOrbit(t);
|
||||
scene.cockpit.stop();
|
||||
assert.equal(scene.handler.getInputAction(click), scene.handler.stock);
|
||||
assert.equal(scene.handler.getInputAction(double), scene.handler.stockDouble);
|
||||
scene.doubleClick(SITES.alpha.at);
|
||||
assert.equal(scene.handler.stockClicks, 1, 'its own click runs');
|
||||
assert.equal(scene.handler.stockDoubleClicks, 1, 'and its own follow');
|
||||
assert.equal(scene.input.stockEnabled('select'), true);
|
||||
assert.equal(scene.input.stockEnabled('dblclickFollow'), true);
|
||||
});
|
||||
|
||||
test('the focused site keeps its row after nearer sites push it down', async (t) => {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* focus ends, and the camera hops along the great circle to the new
|
||||
* satellite. Bound to the Cockpit controller like the orbital view itself.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { stopFollowing } from '../data/followed.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { zoomTransitionProgress } from '../cockpitOrbital.js';
|
||||
import {
|
||||
@@ -122,8 +122,8 @@ export function switchOrbitalSatellite(noradId) {
|
||||
} catch {
|
||||
tracked = false;
|
||||
}
|
||||
// Tracking hands the camera to Cesium's follow; the orbital view keeps it.
|
||||
this.viewer.trackedEntity = undefined;
|
||||
// Tracking hands the camera to the follow; the orbital view keeps it.
|
||||
stopFollowing(this.viewer);
|
||||
const info = tracked ? this.readSatelliteInfo() : null;
|
||||
if (!info || String(info.noradId) !== String(noradId)) {
|
||||
// Nothing changed hands, or the layer could not take it: the view ends
|
||||
@@ -149,7 +149,6 @@ export function switchOrbitalSatellite(noradId) {
|
||||
state.verticalFov = null;
|
||||
state.place = undefined;
|
||||
state.placeTracker?.reset?.();
|
||||
state.prefetched?.clear?.();
|
||||
this.lastHudUpdateMs = 0;
|
||||
this.lastContextUpdateMs = 0;
|
||||
this.dispatchCockpitModeChanged(true, info);
|
||||
@@ -171,9 +170,10 @@ export function switchOrbitalSatellite(noradId) {
|
||||
* Where the camera is this frame: on the satellite, or part-way along a hop
|
||||
* to it, eased like a zoom step. The hop ends when it lands.
|
||||
* @param {object} state The orbital session.
|
||||
* @param {Cesium.Cartesian3} position The ridden satellite this frame.
|
||||
* @param {{x: number, y: number, z: number}} position The ridden
|
||||
* satellite this frame (ECEF).
|
||||
* @param {number} nowMs
|
||||
* @returns {Cesium.Cartesian3}
|
||||
* @returns {{x: number, y: number, z: number}}
|
||||
*/
|
||||
export function orbitalEyePosition(state, position, nowMs) {
|
||||
const hop = state.hop;
|
||||
@@ -190,5 +190,5 @@ export function orbitalEyePosition(state, position, nowMs) {
|
||||
state.hop = null;
|
||||
return position;
|
||||
}
|
||||
return new Cesium.Cartesian3(eye.x, eye.y, eye.z);
|
||||
return { x: eye.x, y: eye.y, z: eye.z };
|
||||
}
|
||||
+25
-222
@@ -1,20 +1,14 @@
|
||||
/** The orbital (satellite) view of the Cockpit controller: camera, zoom, look and HUD. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { isFollowing } from '../data/followed.js';
|
||||
import { cameraOf, canvasOf, findGlobe } from '../render/rendererOf.js';
|
||||
import { formatNumber, msg, t } from '../i18n/index.js';
|
||||
import {
|
||||
ORBITAL_DEFAULT_ZOOM,
|
||||
ORBITAL_PREFETCH_INTERVAL_MS,
|
||||
centreLinesFirst,
|
||||
ORBITAL_PREFETCH_MAX_TILES,
|
||||
ORBITAL_PREFETCH_MIN_ZOOM,
|
||||
ORBITAL_SETTLE_BLUR_PX,
|
||||
ORBITAL_ZOOM_LADDER,
|
||||
ORBITAL_ZOOM_TRANSITION_MS,
|
||||
cesiumFrustumFovRad,
|
||||
footprintWidthKm,
|
||||
fovForZoom,
|
||||
groundTrackAhead,
|
||||
imageryLevelForView,
|
||||
interpolateZoomFov,
|
||||
nadirOrientation,
|
||||
nextOrbitalZoom,
|
||||
@@ -27,7 +21,6 @@ import {
|
||||
previousOrbitalZoom,
|
||||
sensorStripFraction,
|
||||
sensorSwathZoom,
|
||||
tilesForPoints,
|
||||
wheelZoomStep,
|
||||
zoomSettleHolding,
|
||||
zoomTransitionState,
|
||||
@@ -79,27 +72,18 @@ const IDLE_TRANSITION = Object.freeze({
|
||||
const NADIR_LOOK = Object.freeze({ yawDeg: 0, pitchDeg: 0 });
|
||||
|
||||
/**
|
||||
* Start an orbital session's state. Keeps the camera's own field of view so
|
||||
* the exit can put it back exactly.
|
||||
* Start an orbital session's state. The exit gives the field of view back
|
||||
* to the renderer, as it was before the session.
|
||||
*/
|
||||
export function beginOrbital() {
|
||||
const frustum = this.viewer.camera?.frustum;
|
||||
const state = {
|
||||
imagery: acquireOrbitImagery(this.services),
|
||||
zoom: ORBITAL_DEFAULT_ZOOM,
|
||||
// Wheel scrolling summed toward the next zoom step (wheelZoomStep).
|
||||
wheel: null,
|
||||
// Imagery pre-loaded ahead of the ground track from 16x: when it last
|
||||
// looked ahead, and the tiles already asked for (oldest first).
|
||||
prefetchMs: -Infinity,
|
||||
prefetched: new Set(),
|
||||
// The provider those tiles came from, and the requests still in flight.
|
||||
prefetchProvider: null,
|
||||
prefetchRequests: new Set(),
|
||||
// A zoom step in flight: the magnification it started from and when.
|
||||
transition: null,
|
||||
previousUp: null,
|
||||
savedFov: Number.isFinite(frustum?.fov) ? frustum.fov : null,
|
||||
altitudeM: null,
|
||||
verticalFov: null,
|
||||
lastBriefMs: 0,
|
||||
@@ -129,11 +113,8 @@ export function endOrbital() {
|
||||
if (!state) return;
|
||||
this.orbital = null;
|
||||
state.placeTracker?.reset();
|
||||
// Pre-loads still queued or in flight are for a view no longer shown.
|
||||
for (const request of state.prefetchRequests) request.cancel?.();
|
||||
state.prefetchRequests.clear();
|
||||
const frustum = this.viewer.camera?.frustum;
|
||||
if (frustum && state.savedFov !== null) frustum.fov = state.savedFov;
|
||||
// The renderer's own field of view again, following the view's shape.
|
||||
cameraOf(this.viewer).setFov(null);
|
||||
// Back to the map the operator had, unless they picked another meanwhile.
|
||||
state.imagery?.release?.()?.catch?.(() => {});
|
||||
this.publishOrbital(null);
|
||||
@@ -150,10 +131,7 @@ function trackPlace(info, nowMs) {
|
||||
if (!state?.placeTracker) return;
|
||||
let nearKm = null;
|
||||
if (Number.isFinite(info.altitudeM)) {
|
||||
const frustum = this.viewer.camera?.frustum;
|
||||
const aspect = Number.isFinite(frustum?.aspectRatio)
|
||||
? frustum.aspectRatio
|
||||
: canvasAspect(this.viewer);
|
||||
const aspect = viewAspect(this.viewer);
|
||||
const fov = fovForZoom(orbitalBaseFovRad(info.altitudeM), state.zoom);
|
||||
// The field of view is vertical: aspect 1 gives the ground height.
|
||||
nearKm = nearPlaceRadiusKm(
|
||||
@@ -246,13 +224,7 @@ function applyFov(state, altitudeM, nowMs) {
|
||||
reading.transition = IDLE_TRANSITION;
|
||||
}
|
||||
state.verticalFov = reading.fov;
|
||||
const frustum = this.viewer.camera?.frustum;
|
||||
if (frustum && 'fov' in frustum) {
|
||||
const aspect = Number.isFinite(frustum.aspectRatio)
|
||||
? frustum.aspectRatio
|
||||
: canvasAspect(this.viewer);
|
||||
frustum.fov = cesiumFrustumFovRad(reading.fov, aspect);
|
||||
}
|
||||
cameraOf(this.viewer).setFov({ vertical: reading.fov });
|
||||
return reading;
|
||||
}
|
||||
|
||||
@@ -261,25 +233,18 @@ function applyFov(state, altitudeM, nowMs) {
|
||||
* globe; with the globe hidden (Google 3D kept) there is nothing to wait for.
|
||||
*/
|
||||
function tilesLoaded(viewer) {
|
||||
const globe = viewer.scene?.globe;
|
||||
return !globe?.show || globe.tilesLoaded !== false;
|
||||
const globe = findGlobe(viewer);
|
||||
if (!globe || globe.isGlobeVisible?.() === false) return true;
|
||||
return globe.isSettled('imagery') !== false;
|
||||
}
|
||||
|
||||
function canvasAspect(viewer) {
|
||||
const canvas = viewer.scene?.canvas;
|
||||
const canvas = canvasOf(viewer);
|
||||
const width = canvas?.clientWidth;
|
||||
const height = canvas?.clientHeight;
|
||||
return width > 0 && height > 0 ? width / height : 1;
|
||||
}
|
||||
|
||||
/** Copy a plain vector into a Cesium scratch. */
|
||||
function intoCartesian(vector, result) {
|
||||
result.x = vector.x;
|
||||
result.y = vector.y;
|
||||
result.z = vector.z;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drive the orbital camera for one rendered frame: at the satellite's own
|
||||
* per-frame position, looking at the Earth's centre with the ground track at
|
||||
@@ -290,8 +255,8 @@ function intoCartesian(vector, result) {
|
||||
*/
|
||||
export function updateOrbital(nowMs) {
|
||||
// Tracking anything from orbit (an aircraft, another satellite) ends the
|
||||
// view and leaves Cesium tracking with that target.
|
||||
if (this.viewer.trackedEntity?.position) {
|
||||
// view and leaves the camera following that target.
|
||||
if (isFollowing(this.viewer)) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
@@ -340,11 +305,15 @@ export function updateOrbital(nowMs) {
|
||||
});
|
||||
const zoomStepping = Boolean(state.transition);
|
||||
const reading = applyFov.call(this, state, info.altitudeM, nowMs);
|
||||
this.viewer.camera.setView({
|
||||
destination: eye,
|
||||
cameraOf(this.viewer).setView({
|
||||
destination: { x: eye.x, y: eye.y, z: eye.z },
|
||||
orientation: {
|
||||
direction: intoCartesian(view.direction, this.scratchForward),
|
||||
up: intoCartesian(view.up, this.scratchUp),
|
||||
direction: {
|
||||
x: view.direction.x,
|
||||
y: view.direction.y,
|
||||
z: view.direction.z,
|
||||
},
|
||||
up: { x: view.up.x, y: view.up.y, z: view.up.z },
|
||||
},
|
||||
});
|
||||
this.lastSubjectInfo = info;
|
||||
@@ -366,169 +335,6 @@ export function updateOrbital(nowMs) {
|
||||
this.lastContextUpdateMs = nowMs;
|
||||
updateOrbitalContext.call(this, info, nowMs);
|
||||
}
|
||||
prefetchImageryAhead.call(this, info, nowMs);
|
||||
}
|
||||
|
||||
/** Tiles remembered as asked for in one orbital session. */
|
||||
const PREFETCH_MEMORY = 512;
|
||||
|
||||
/** How far the shown time may be from now for the look-ahead to run, ms. */
|
||||
const PREFETCH_LIVE_TOLERANCE_MS = 60_000;
|
||||
|
||||
/**
|
||||
* From 16x the view is 10 to 40 km wide while the ground track moves about
|
||||
* 7 km/s, so the imagery under it arrives late. Every
|
||||
* ORBITAL_PREFETCH_INTERVAL_MS ask the globe's base imagery for the tiles
|
||||
* the view will need 5 to 20 s ahead (`groundTrackAhead`), at the level
|
||||
* Cesium will draw there (`imageryLevelForView`), so the browser has them
|
||||
* cached when the view gets there. The requests are throttled at the
|
||||
* lowest priority: Cesium's request scheduler declines one while the
|
||||
* imagery server's slots are taken by the tiles on screen or the scheduler
|
||||
* is full, and a declined tile is asked again on a later look-ahead. At most
|
||||
* ORBITAL_PREFETCH_MAX_TILES a time; the last PREFETCH_MEMORY tiles asked
|
||||
* for are not asked again unless their request failed, and a new base map
|
||||
* starts the memory over. Exit cancels the requests still pending. Nothing
|
||||
* below 16x, while the view is tilted off nadir (it no longer looks at the
|
||||
* track), with the world clock away from now (paused, played back), after
|
||||
* the exit, or with the globe hidden (Google 3D tiles drawn instead).
|
||||
* @returns {number} The tiles asked for.
|
||||
*/
|
||||
export function prefetchImageryAhead(info, nowMs) {
|
||||
const state = this.orbital;
|
||||
if (!state || !(state.zoom >= ORBITAL_PREFETCH_MIN_ZOOM)) return 0;
|
||||
// Tilted, the view looks off the track the pre-load follows.
|
||||
if (lookIsOffset(state.lookTarget, 0) || lookIsOffset(state.lookView, 0))
|
||||
return 0;
|
||||
if (nowMs - state.prefetchMs < ORBITAL_PREFETCH_INTERVAL_MS) return 0;
|
||||
// The look-ahead runs at live speed: with the world clock paused, played
|
||||
// back or moved, the view will not pass where it points.
|
||||
if (
|
||||
Number.isFinite(info.atMs) &&
|
||||
Math.abs(info.atMs - Date.now()) > PREFETCH_LIVE_TOLERANCE_MS
|
||||
)
|
||||
return 0;
|
||||
state.prefetchMs = nowMs;
|
||||
try {
|
||||
const globe = this.viewer.scene?.globe;
|
||||
if (!globe || globe.show === false) return 0;
|
||||
const provider = baseImageryProvider(this.viewer);
|
||||
if (!provider) return 0;
|
||||
// Another base map: its tiles have not been asked for.
|
||||
// A fresh set, so a late failure from the old map's requests cannot
|
||||
// drop a tile the new one has fetched.
|
||||
if (provider !== state.prefetchProvider) {
|
||||
for (const request of state.prefetchRequests) request.cancel?.();
|
||||
state.prefetchRequests = new Set();
|
||||
state.prefetched = new Set();
|
||||
state.prefetchProvider = provider;
|
||||
}
|
||||
const fov = fovForZoom(orbitalBaseFovRad(info.altitudeM), state.zoom);
|
||||
const viewKm = footprintWidthKm(
|
||||
info.altitudeM,
|
||||
fov,
|
||||
viewAspect(this.viewer),
|
||||
);
|
||||
// The ground one CSS pixel covers at the nadir point, as Cesium's
|
||||
// screen-space error measures it: the vertical field of view over the
|
||||
// canvas height, at the satellite's altitude.
|
||||
const canvas = this.viewer.scene?.canvas;
|
||||
const heightPx = canvas?.clientHeight || canvas?.height;
|
||||
const terrain =
|
||||
this.viewer.terrainProvider ?? this.viewer.scene?.globe?.terrainProvider;
|
||||
const level = imageryLevelForView(provider.tilingScheme, {
|
||||
metresPerPixel: (info.altitudeM * 2 * Math.tan(fov / 2)) / heightPx,
|
||||
latitudeDeg: info.latitude,
|
||||
geographic:
|
||||
provider.tilingScheme.projection instanceof Cesium.GeographicProjection,
|
||||
tileWidthPx: provider.tileWidth,
|
||||
minimumLevel: provider.minimumLevel,
|
||||
maximumLevel: provider.maximumLevel,
|
||||
maximumScreenSpaceError: globe.maximumScreenSpaceError,
|
||||
terrainLevelErrorM:
|
||||
typeof terrain?.getLevelMaximumGeometricError === 'function'
|
||||
? (terrainLevel) =>
|
||||
terrain.getLevelMaximumGeometricError(terrainLevel)
|
||||
: undefined,
|
||||
});
|
||||
if (level === null) return 0;
|
||||
const memory = state.prefetched;
|
||||
const tiles = tilesForPoints(
|
||||
provider.tilingScheme,
|
||||
centreLinesFirst(groundTrackAhead(info, viewKm)),
|
||||
level,
|
||||
{
|
||||
maxTiles: ORBITAL_PREFETCH_MAX_TILES,
|
||||
skip: (key) => memory.has(key),
|
||||
},
|
||||
);
|
||||
let asked = 0;
|
||||
for (const tile of tiles) {
|
||||
let pending;
|
||||
let request;
|
||||
try {
|
||||
// The tiles on screen keep their slots: Cesium's scheduler declines
|
||||
// this request while the imagery server's slots are taken (shared
|
||||
// with the globe's own tile requests, throttleByServer) or the
|
||||
// scheduler is full, and at the lowest priority it is the first
|
||||
// dropped from the priority heap, never one the screen asked for.
|
||||
pending = provider.requestImage(
|
||||
tile.x,
|
||||
tile.y,
|
||||
tile.level,
|
||||
(request = new Cesium.Request({
|
||||
throttle: true,
|
||||
throttleByServer: true,
|
||||
priority: Number.MAX_VALUE,
|
||||
type: Cesium.RequestType.IMAGERY,
|
||||
})),
|
||||
);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
// A provider that declines now (throttled) is asked again later.
|
||||
if (!pending) continue;
|
||||
const requests = state.prefetchRequests;
|
||||
requests.add(request);
|
||||
Promise.resolve(pending).then(
|
||||
() => requests.delete(request),
|
||||
(error) => {
|
||||
requests.delete(request);
|
||||
// Dropped by the scheduler (rejected with no error): asked again
|
||||
// later. A tile that failed to load stays remembered, so one
|
||||
// missing from the map is not asked for every look-ahead.
|
||||
if (error === undefined) memory.delete(tile.key);
|
||||
},
|
||||
);
|
||||
memory.add(tile.key);
|
||||
if (memory.size > PREFETCH_MEMORY)
|
||||
memory.delete(memory.values().next().value);
|
||||
asked += 1;
|
||||
}
|
||||
return asked;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider of the lowest shown imagery layer, the base map the globe
|
||||
* drapes, when it can be asked for a tile; else null.
|
||||
*/
|
||||
function baseImageryProvider(viewer) {
|
||||
const layers = viewer.imageryLayers ?? viewer.scene?.imageryLayers;
|
||||
const count = Number.isInteger(layers?.length) ? layers.length : 0;
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const layer = layers.get(i);
|
||||
if (!layer || layer.show === false || layer.alpha === 0) continue;
|
||||
const provider = layer.imageryProvider;
|
||||
if (
|
||||
typeof provider?.requestImage === 'function' &&
|
||||
typeof provider.tilingScheme?.positionToTileXY === 'function'
|
||||
)
|
||||
return provider;
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -626,9 +432,7 @@ export function publishOrbitalView(info, transition = IDLE_TRANSITION) {
|
||||
if (!state || !info) return;
|
||||
const focus = orbitalFocusReadout.call(this);
|
||||
const offset = Boolean(focus) || lookIsOffset(state.lookTarget, 0);
|
||||
const aspect = Number.isFinite(this.viewer.camera?.frustum?.aspectRatio)
|
||||
? this.viewer.camera.frustum.aspectRatio
|
||||
: canvasAspect(this.viewer);
|
||||
const aspect = viewAspect(this.viewer);
|
||||
const settledFov = fovForZoom(orbitalBaseFovRad(info.altitudeM), state.zoom);
|
||||
const footprintKm = footprintWidthKm(info.altitudeM, settledFov, aspect);
|
||||
// The strip is drawn over the picture, so it follows the view as a step
|
||||
@@ -848,9 +652,8 @@ function orbitalMaxZoomFor(info) {
|
||||
}
|
||||
|
||||
function viewAspect(viewer) {
|
||||
return Number.isFinite(viewer.camera?.frustum?.aspectRatio)
|
||||
? viewer.camera.frustum.aspectRatio
|
||||
: canvasAspect(viewer);
|
||||
const aspect = cameraOf(viewer).pose().aspectRatio;
|
||||
return Number.isFinite(aspect) && aspect > 0 ? aspect : canvasAspect(viewer);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,8 +15,6 @@ import CockpitView from './views/CockpitView.vue';
|
||||
import ContextView from './views/ContextView.vue';
|
||||
import IntelHudView from './views/IntelHudView.vue';
|
||||
import {
|
||||
ORBITAL_PREFETCH_INTERVAL_MS,
|
||||
ORBITAL_PREFETCH_MAX_TILES,
|
||||
ORBITAL_SETTLE_BLUR_PX,
|
||||
ORBITAL_SETTLE_MAX_MS,
|
||||
ORBITAL_ZOOM_TRANSITION_MS,
|
||||
@@ -25,8 +23,15 @@ import {
|
||||
orbitalBaseFovRad,
|
||||
} from '../cockpitOrbital.js';
|
||||
import { vesselCockpitInfo } from '../layers/vessels/cockpitSubject.js';
|
||||
import { prefetchImageryAhead } from './cockpitOrbitalView.js';
|
||||
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
|
||||
import {
|
||||
bindFakeCesiumCamera,
|
||||
followEntity,
|
||||
followedEntity,
|
||||
} from '../testSupport/fakeCameraPort.mjs';
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
|
||||
const ISS = Object.freeze({
|
||||
kind: 'satellite',
|
||||
@@ -97,7 +102,7 @@ function stockEventHandler(viewer) {
|
||||
};
|
||||
actions.set(DOUBLE_CLICK, () => {
|
||||
handler.stockCalls += 1;
|
||||
viewer.trackedEntity = undefined;
|
||||
followEntity(viewer, null);
|
||||
});
|
||||
return handler;
|
||||
}
|
||||
@@ -141,10 +146,18 @@ function fixture(
|
||||
gevTrackedId: aircraftInfo ? `flights:${aircraftInfo.icao24}` : '',
|
||||
};
|
||||
const viewer = {
|
||||
trackedEntity: undefined,
|
||||
clock: { currentTime: null },
|
||||
camera: {
|
||||
frustum: { fov: SAVED_FOV, aspectRatio: ASPECT },
|
||||
// Cesium's frustum: `fov` the wider angle, `fovy` the vertical one.
|
||||
frustum: {
|
||||
fov: SAVED_FOV,
|
||||
aspectRatio: ASPECT,
|
||||
get fovy() {
|
||||
return this.aspectRatio > 1
|
||||
? 2 * Math.atan(Math.tan(this.fov / 2) / this.aspectRatio)
|
||||
: this.fov;
|
||||
},
|
||||
},
|
||||
cancelFlight() {},
|
||||
setView({ destination, orientation }) {
|
||||
shots.push({
|
||||
@@ -164,6 +177,26 @@ function fixture(
|
||||
// Cesium's Viewer installs a double-click that untracks on any pick that
|
||||
// is not an Entity; the Cockpit routes it.
|
||||
viewer.screenSpaceEventHandler = stockEventHandler(viewer);
|
||||
// The Cockpit drives the camera, reads frames and the globe through ports:
|
||||
// the Cesium camera port over the fake camera, and a globe whose imagery
|
||||
// has loaded unless the test's `scene.globe` says otherwise.
|
||||
const ports = fakeScenePorts(viewer);
|
||||
bindFakeCesiumCamera(viewer, {
|
||||
...ports,
|
||||
// Where the test's scene says a position is drawn.
|
||||
query: {
|
||||
...ports.query,
|
||||
project: (position) =>
|
||||
viewer.scene.cartesianToCanvasCoordinates?.(position, {}) ?? null,
|
||||
},
|
||||
globe: {
|
||||
isGlobeVisible: () => viewer.scene.globe?.show !== false,
|
||||
isSettled: () => viewer.scene.globe?.tilesLoaded !== false,
|
||||
},
|
||||
});
|
||||
// The scene's input; the renderer's own double-click follow runs unless
|
||||
// something holds it off, as `stockEventHandler` counts it.
|
||||
const input = fakeInput(viewer);
|
||||
const satellites = satelliteLayer(satellite);
|
||||
const cockpit = new CockpitViewController(viewer, {
|
||||
services: {
|
||||
@@ -213,12 +246,22 @@ function fixture(
|
||||
updateContext() {},
|
||||
updateRoute() {},
|
||||
});
|
||||
let stockHolds = 0;
|
||||
cockpit.holdStockFollow = () => {
|
||||
stockHolds += 1;
|
||||
let held = true;
|
||||
return () => {
|
||||
if (held) stockHolds -= 1;
|
||||
held = false;
|
||||
};
|
||||
};
|
||||
const events = [];
|
||||
const onMode = (event) => events.push(event.detail);
|
||||
window.addEventListener('gev:cockpit-mode-changed', onMode);
|
||||
t.after(() => {
|
||||
window.removeEventListener('gev:cockpit-mode-changed', onMode);
|
||||
cockpit.stop();
|
||||
input.destroy();
|
||||
app.unmount();
|
||||
globalThis.matchMedia = previousMatchMedia;
|
||||
document.body.classList.remove(
|
||||
@@ -232,6 +275,8 @@ function fixture(
|
||||
$,
|
||||
cockpit,
|
||||
viewer,
|
||||
input,
|
||||
stockHeld: () => stockHolds > 0,
|
||||
satellites,
|
||||
store,
|
||||
shots,
|
||||
@@ -368,7 +413,7 @@ test('entering takes the camera and shows only the orbital HUD', async (t) => {
|
||||
assert.equal(cockpit.subjectKind, 'satellite');
|
||||
assert.equal(cockpit.subjectId, ISS.noradId);
|
||||
assert.deepEqual(satellites.calls, [['subject', ISS.noradId]]);
|
||||
assert.equal(viewer.trackedEntity, undefined);
|
||||
assert.equal(followedOf(viewer), null);
|
||||
assert.equal(viewer.scene.screenSpaceCameraController.enableInputs, false);
|
||||
assert.ok(document.body.classList.contains('cockpit-mode'));
|
||||
assert.ok(document.body.classList.contains('cockpit-orbit'));
|
||||
@@ -718,11 +763,11 @@ test('losing the satellite ends the view without refocusing it', async (t) => {
|
||||
|
||||
test('tracking an aircraft from orbit ends the view and keeps that tracking', async (t) => {
|
||||
const { cockpit, viewer, satellites, aircraft, clock } = await orbitAt(t);
|
||||
viewer.trackedEntity = aircraft;
|
||||
followEntity(viewer, aircraft);
|
||||
clock.advance(16);
|
||||
cockpit.update();
|
||||
assert.equal(cockpit.active, false);
|
||||
assert.equal(viewer.trackedEntity, aircraft);
|
||||
assert.equal(followedEntity(viewer), aircraft);
|
||||
assert.ok(!satellites.calls.some(([call]) => call === 'refocus'));
|
||||
});
|
||||
|
||||
@@ -744,7 +789,7 @@ test('+ and − mean nothing new in an aircraft cockpit or on a bridge', async (
|
||||
onGround: false,
|
||||
};
|
||||
const air = fixture(t, { satellite: null, aircraftInfo });
|
||||
air.viewer.trackedEntity = air.aircraft;
|
||||
followEntity(air.viewer, air.aircraft);
|
||||
assert.equal(air.cockpit.enter({ kind: 'aircraft' }), true);
|
||||
for (const key of ['+', '=', '-', '_'])
|
||||
assert.equal(press(air.cockpit, key).defaultPrevented, false, key);
|
||||
@@ -829,44 +874,53 @@ test('a map already leased elsewhere does not keep orbit out', async (t) => {
|
||||
* A double-click `offsetPx` from where the followed satellite is drawn, at
|
||||
* (400, 300) on the canvas, through Cesium's double-click handler.
|
||||
*/
|
||||
function doubleClickNearSatellite(viewer, offsetPx) {
|
||||
function doubleClickNearSatellite(scene, offsetPx) {
|
||||
const { viewer, input, stockHeld } = scene;
|
||||
viewer.scene.cartesianToCanvasCoordinates = (position, result) =>
|
||||
position ? Object.assign(result, { x: 400, y: 300 }) : undefined;
|
||||
const handler = viewer.screenSpaceEventHandler;
|
||||
const before = handler.stockCalls;
|
||||
handler.doubleClick({ x: 400 + offsetPx, y: 300 });
|
||||
const position = { x: 400 + offsetPx, y: 300 };
|
||||
input.tap(position);
|
||||
input.down(position);
|
||||
input.up(position);
|
||||
// The renderer's own follow runs unless the second press held it off.
|
||||
if (!stockHeld()) handler.doubleClick(position);
|
||||
input.dblclick(position);
|
||||
return { stock: handler.stockCalls > before };
|
||||
}
|
||||
|
||||
test('double-clicking the followed satellite enters the orbital view', async (t) => {
|
||||
const { viewer, store } = fixture(t);
|
||||
const miss = doubleClickNearSatellite(viewer, 60);
|
||||
const scene = fixture(t);
|
||||
const { store } = scene;
|
||||
const miss = doubleClickNearSatellite(scene, 60);
|
||||
assert.equal(miss.stock, true, 'a double-click elsewhere goes to Cesium');
|
||||
assert.equal(store.orbital, null);
|
||||
const hit = doubleClickNearSatellite(viewer, 20);
|
||||
const hit = doubleClickNearSatellite(scene, 20);
|
||||
assert.equal(hit.stock, false, 'Cesium never sees it');
|
||||
await settle();
|
||||
assert.ok(store.orbital, 'the orbital HUD is up');
|
||||
assert.equal(
|
||||
doubleClickNearSatellite(viewer, 0).stock,
|
||||
doubleClickNearSatellite(scene, 0).stock,
|
||||
true,
|
||||
'inside, a double-click is not the entry',
|
||||
);
|
||||
});
|
||||
|
||||
test('a double-click a tool owns, or one the gate refuses, does not enter', async (t) => {
|
||||
const { cockpit, viewer, store } = fixture(t, { orbitAllowed: false });
|
||||
const scene = fixture(t, { orbitAllowed: false });
|
||||
const { cockpit, store } = scene;
|
||||
// On the track but refused: no entry, and no untracking either.
|
||||
assert.equal(doubleClickNearSatellite(viewer, 0).stock, false);
|
||||
assert.equal(doubleClickNearSatellite(scene, 0).stock, false);
|
||||
assert.equal(store.orbital, null);
|
||||
cockpit.isOrbitEntryAllowed = () => true;
|
||||
// Drawing ends a shape with a double-click.
|
||||
const lease = claimPointer('draw');
|
||||
t.after(() => releasePointer(lease));
|
||||
doubleClickNearSatellite(viewer, 0);
|
||||
doubleClickNearSatellite(scene, 0);
|
||||
assert.equal(store.orbital, null);
|
||||
releasePointer(lease);
|
||||
doubleClickNearSatellite(viewer, 0);
|
||||
doubleClickNearSatellite(scene, 0);
|
||||
await settle();
|
||||
assert.ok(store.orbital);
|
||||
});
|
||||
@@ -882,20 +936,22 @@ test('a double-click on the followed aircraft model enters instead of untracking
|
||||
track: 45,
|
||||
onGround: false,
|
||||
};
|
||||
const { viewer, aircraft, store } = fixture(t, { aircraftInfo });
|
||||
viewer.trackedEntity = aircraft;
|
||||
const scene = fixture(t, { aircraftInfo });
|
||||
const { viewer, aircraft, store } = scene;
|
||||
followEntity(viewer, aircraft);
|
||||
// The model is a primitive, not an Entity: Cesium's own double-click
|
||||
// would untrack it.
|
||||
doubleClickNearSatellite(viewer, 0);
|
||||
doubleClickNearSatellite(scene, 0);
|
||||
await settle();
|
||||
assert.equal(viewer.screenSpaceEventHandler.stockCalls, 0);
|
||||
assert.equal(store.presence.active, true, 'the cockpit is entered');
|
||||
});
|
||||
|
||||
test('the Cockpit hands the double-click back to Cesium when it stops', async (t) => {
|
||||
const { cockpit, viewer } = fixture(t);
|
||||
const scene = fixture(t);
|
||||
const { cockpit, viewer } = scene;
|
||||
cockpit.stop();
|
||||
doubleClickNearSatellite(viewer, 0);
|
||||
doubleClickNearSatellite(scene, 0);
|
||||
assert.equal(viewer.screenSpaceEventHandler.stockCalls, 1);
|
||||
});
|
||||
|
||||
@@ -994,7 +1050,7 @@ test('a place that lands after the exit is dropped', async (t) => {
|
||||
assert.equal(store.orbital, null, 'no HUD comes back for a stale answer');
|
||||
});
|
||||
|
||||
test('a tracked aircraft takes entry before a tracked satellite', async (t) => {
|
||||
test('an aircraft and a satellite first seen in one sync: the aircraft takes entry, by the fixed order', async (t) => {
|
||||
const aircraftInfo = {
|
||||
icao24: 'abc123',
|
||||
callsign: 'TEST1',
|
||||
@@ -1006,7 +1062,10 @@ test('a tracked aircraft takes entry before a tracked satellite', async (t) => {
|
||||
onGround: false,
|
||||
};
|
||||
const { cockpit, viewer, aircraft, store } = fixture(t, { aircraftInfo });
|
||||
viewer.trackedEntity = aircraft;
|
||||
followEntity(viewer, aircraft);
|
||||
// The satellite and the aircraft are both new to this sync; the fixed order
|
||||
// decides between subjects first seen together. Selected one after the
|
||||
// other, the later one takes entry (cockpitEntryGate.test.mjs).
|
||||
cockpit.syncEntry();
|
||||
assert.equal(store.presence.entryKind, 'aircraft');
|
||||
});
|
||||
@@ -1133,33 +1192,6 @@ test('S does nothing in an orbital view, even with a SENSOR step', async (t) =>
|
||||
);
|
||||
});
|
||||
|
||||
/** A globe draping one Web Mercator imagery layer that records requests. */
|
||||
function imageryGlobe(viewer, { requestImage } = {}) {
|
||||
const requests = [];
|
||||
const requestObjects = [];
|
||||
const provider = {
|
||||
tilingScheme: new Cesium.WebMercatorTilingScheme(),
|
||||
tileWidth: 256,
|
||||
maximumLevel: 19,
|
||||
requestImage:
|
||||
requestImage ??
|
||||
((x, y, level, request) => {
|
||||
requests.push(`${level}/${x}/${y}`);
|
||||
requestObjects.push(request);
|
||||
return Promise.resolve({});
|
||||
}),
|
||||
};
|
||||
viewer.scene.globe = { show: true, tilesLoaded: true };
|
||||
viewer.scene.canvas = { clientWidth: 1600, clientHeight: 900 };
|
||||
viewer.imageryLayers = {
|
||||
length: 1,
|
||||
get: () => ({ show: true, alpha: 1, imageryProvider: provider }),
|
||||
};
|
||||
return { requests, requestObjects, provider };
|
||||
}
|
||||
|
||||
const WORLDVIEW_ON_TRACK = Object.freeze({ ...WORLDVIEW, groundTrackDeg: 52 });
|
||||
|
||||
test('the sensor strip follows the view through a zoom step, not ahead of it', async (t) => {
|
||||
const { cockpit, store, clock } = await orbitAt(t, {
|
||||
satellite: WORLDVIEW,
|
||||
@@ -1181,84 +1213,6 @@ test('the sensor strip follows the view through a zoom step, not ahead of it', a
|
||||
assert.ok(midway > atOne && midway < atTwo, 'part-way through the step');
|
||||
});
|
||||
|
||||
test('from 16x the imagery ahead of the ground track is pre-loaded', async (t) => {
|
||||
const { cockpit, viewer, store, clock } = await orbitAt(t, {
|
||||
satellite: WORLDVIEW_ON_TRACK,
|
||||
});
|
||||
const { requests } = imageryGlobe(viewer);
|
||||
for (const zoom of [2, 4, 8]) {
|
||||
press(cockpit, '+');
|
||||
assert.equal(store.orbital.zoom, zoom);
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
}
|
||||
assert.deepEqual(requests, [], 'nothing below 16x');
|
||||
press(cockpit, '+');
|
||||
assert.equal(store.orbital.zoom, 16);
|
||||
clock.advance(16);
|
||||
cockpit.update();
|
||||
assert.ok(requests.length > 0, 'tiles ahead are asked for');
|
||||
assert.ok(requests.length <= ORBITAL_PREFETCH_MAX_TILES, 'bounded');
|
||||
assert.equal(new Set(requests.map((key) => key.split('/')[0])).size, 1);
|
||||
const first = requests.length;
|
||||
// Not again until the interval has passed, and never the same tile twice.
|
||||
clock.advance(16);
|
||||
cockpit.update();
|
||||
assert.equal(requests.length, first);
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
assert.equal(new Set(requests).size, requests.length, 'no repeats');
|
||||
// A tighter zoom needs a finer level.
|
||||
press(cockpit, '+');
|
||||
assert.equal(store.orbital.zoom, 32);
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
const levels = requests.map((key) => Number(key.split('/')[0]));
|
||||
assert.equal(levels.at(-1), levels[0] + 1);
|
||||
// Back below 16x, and after the exit: no more work.
|
||||
const before = requests.length;
|
||||
press(cockpit, '-');
|
||||
press(cockpit, '-');
|
||||
assert.equal(store.orbital.zoom, 8);
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
assert.equal(requests.length, before, 'stops below 16x');
|
||||
press(cockpit, '+');
|
||||
cockpit.exit();
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
assert.equal(
|
||||
prefetchImageryAhead.call(cockpit, WORLDVIEW_ON_TRACK, Infinity),
|
||||
0,
|
||||
);
|
||||
assert.equal(requests.length, before, 'stops after the exit');
|
||||
});
|
||||
|
||||
test('the pre-load skips a hidden globe and a provider that cannot fetch', async (t) => {
|
||||
const { cockpit, viewer, store, clock } = await orbitAt(t, {
|
||||
satellite: WORLDVIEW_ON_TRACK,
|
||||
});
|
||||
const { requests, provider } = imageryGlobe(viewer);
|
||||
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
|
||||
assert.equal(store.orbital.zoom, 16);
|
||||
// Google 3D tiles drawn, the globe hidden: nothing to pre-load.
|
||||
viewer.scene.globe.show = false;
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
assert.deepEqual(requests, []);
|
||||
viewer.scene.globe.show = true;
|
||||
// No requestImage, or one that throws: no error, nothing remembered.
|
||||
delete provider.requestImage;
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
assert.doesNotThrow(() => cockpit.update());
|
||||
provider.requestImage = () => {
|
||||
throw new Error('offline');
|
||||
};
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
assert.doesNotThrow(() => cockpit.update());
|
||||
assert.equal(store.orbital.zoom, 16, 'the view carries on');
|
||||
});
|
||||
|
||||
test('an unconfirmed sensor swath is drawn but adds no zoom steps', async (t) => {
|
||||
const { store } = await orbitAt(t, {
|
||||
satellite: {
|
||||
@@ -1434,45 +1388,6 @@ test('the readout says OFF-NADIR while the view is tilted', async (t) => {
|
||||
);
|
||||
});
|
||||
|
||||
test('the pre-load is throttled, at the level Cesium draws, and waits out a tilt', async (t) => {
|
||||
const { cockpit, viewer, store, clock } = await orbitAt(t, {
|
||||
satellite: WORLDVIEW_ON_TRACK,
|
||||
});
|
||||
const { requests, requestObjects } = imageryGlobe(viewer);
|
||||
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
|
||||
assert.equal(store.orbital.zoom, 16);
|
||||
// Tilted off nadir the view looks away from the track: nothing asked.
|
||||
press(cockpit, 'ArrowRight');
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
assert.deepEqual(requests, [], 'nothing while tilted');
|
||||
press(cockpit, 'Home');
|
||||
for (let frame = 0; frame < 30; frame += 1) {
|
||||
clock.advance(16);
|
||||
cockpit.update();
|
||||
}
|
||||
assert.ok(requests.length > 0, 'back at nadir it pre-loads');
|
||||
// Every request may be declined while Cesium is busy with the screen.
|
||||
for (const request of requestObjects) {
|
||||
assert.ok(request instanceof Cesium.Request);
|
||||
assert.equal(request.throttle, true);
|
||||
assert.equal(request.throttleByServer, true);
|
||||
assert.equal(
|
||||
request.priority,
|
||||
Number.MAX_VALUE,
|
||||
'never ahead of the screen',
|
||||
);
|
||||
assert.equal(request.type, Cesium.RequestType.IMAGERY);
|
||||
}
|
||||
// The level Cesium's own selection takes for this view, worked by hand:
|
||||
// at 16x from 617 km the 900 px canvas is ~49.5 m a pixel. The ellipsoid
|
||||
// terrain's level-zero error is 6378137 · 2π / 4 / 128 ≈ 78,272 m; it first
|
||||
// meets Cesium's screen-space error of 2 px (≤ 99 m) at level 10, 76.4 m.
|
||||
// A Web Mercator level-zero texel at 30° is 6378137 · 2π · cos 30° / 256
|
||||
// ≈ 135,570 m, so the imagery level is round(log2(135,570 / 76.4)) = 11.
|
||||
assert.equal(Number(requests[0].split('/')[0]), 11);
|
||||
});
|
||||
|
||||
test('the TLE age is measured from the time the satellite is shown at', async (t) => {
|
||||
const DAY = 86_400_000;
|
||||
const { store } = await orbitAt(t, {
|
||||
@@ -1527,76 +1442,6 @@ test('a SAR swath reads but draws no strip under nadir', async (t) => {
|
||||
assert.equal(store.orbital.sensor.stripFraction, null);
|
||||
});
|
||||
|
||||
test('exit cancels pending pre-loads, and a dropped one is asked again', async (t) => {
|
||||
const { cockpit, viewer, store, clock } = await orbitAt(t, {
|
||||
satellite: WORLDVIEW_ON_TRACK,
|
||||
});
|
||||
const asked = [];
|
||||
let fail = true;
|
||||
const pending = [];
|
||||
imageryGlobe(viewer, {
|
||||
requestImage: (x, y, level, request) => {
|
||||
asked.push(`${level}/${x}/${y}`);
|
||||
// Cesium's scheduler drops a request by rejecting with no error.
|
||||
if (fail) return Promise.reject(undefined);
|
||||
pending.push(request);
|
||||
return new Promise(() => {});
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
|
||||
assert.equal(store.orbital.zoom, 16);
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
await settle();
|
||||
const firstAsk = asked.slice();
|
||||
assert.ok(firstAsk.length > 0);
|
||||
fail = false;
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
assert.deepEqual(asked.slice(firstAsk.length), firstAsk, 'asked again');
|
||||
assert.ok(pending.length > 0);
|
||||
cockpit.exit();
|
||||
assert.ok(
|
||||
pending.every((request) => request.cancelled === true),
|
||||
'cancelled on exit',
|
||||
);
|
||||
});
|
||||
|
||||
test('the pre-load waits while the world clock is away from now', async (t) => {
|
||||
const { cockpit, viewer, store, clock } = await orbitAt(t, {
|
||||
satellite: { ...WORLDVIEW_ON_TRACK, atMs: START_MS - 3_600_000 },
|
||||
});
|
||||
const { requests } = imageryGlobe(viewer);
|
||||
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
|
||||
assert.equal(store.orbital.zoom, 16);
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
assert.deepEqual(requests, []);
|
||||
});
|
||||
|
||||
test('a tile that fails to load is not asked again', async (t) => {
|
||||
const { cockpit, viewer, store, clock } = await orbitAt(t, {
|
||||
satellite: WORLDVIEW_ON_TRACK,
|
||||
});
|
||||
const asked = [];
|
||||
imageryGlobe(viewer, {
|
||||
requestImage: (x, y, level) => {
|
||||
asked.push(`${level}/${x}/${y}`);
|
||||
return Promise.reject(new Error('404'));
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 4; i += 1) press(cockpit, '+');
|
||||
assert.equal(store.orbital.zoom, 16);
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
await settle();
|
||||
const first = asked.length;
|
||||
assert.ok(first > 0);
|
||||
clock.advance(ORBITAL_PREFETCH_INTERVAL_MS);
|
||||
cockpit.update();
|
||||
assert.equal(new Set(asked).size, asked.length, 'none asked twice');
|
||||
});
|
||||
|
||||
test('back to nadir from past the limb, the sensor waits for the view', async (t) => {
|
||||
const { cockpit, store, clock } = await orbitAt(t, {
|
||||
satellite: GEO_IMAGER,
|
||||
|
||||
@@ -11,6 +11,10 @@ import { setLocale } from '../i18n/index.js';
|
||||
import { useCockpitStore } from './stores/cockpit.js';
|
||||
import CockpitView from './views/CockpitView.vue';
|
||||
import ContextView from './views/ContextView.vue';
|
||||
import {
|
||||
bindFakeCesiumCamera,
|
||||
followEntity,
|
||||
} from '../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
const INFO = Object.freeze({
|
||||
icao24: 'abc123',
|
||||
@@ -43,7 +47,6 @@ function fixture(t) {
|
||||
const listeners = () => ({ addEventListener: () => () => {} });
|
||||
const entity = { position: {}, show: true };
|
||||
const viewer = {
|
||||
trackedEntity: entity,
|
||||
camera: { cancelFlight() {} },
|
||||
entities: { contains: (candidate) => candidate === entity },
|
||||
scene: {
|
||||
@@ -52,6 +55,8 @@ function fixture(t) {
|
||||
},
|
||||
trackedEntityChanged: listeners(),
|
||||
};
|
||||
bindFakeCesiumCamera(viewer, { frame: { on: () => () => {} } });
|
||||
followEntity(viewer, entity);
|
||||
const cockpit = new CockpitViewController(viewer, {
|
||||
services: {
|
||||
flightsLayer: { getTrackedInfo: () => INFO, refreshTr3b() {} },
|
||||
|
||||
@@ -27,9 +27,11 @@ export const COCKPIT_UTILITY_REC_GAP_PX = 12;
|
||||
|
||||
export const COCKPIT_UTILITY_SIGNAL_GAP_PX = 8;
|
||||
|
||||
export const COCKPIT_UTILITY_MIN_TOP_PX = 96;
|
||||
// Display and Radio start where the left rail does (max(206px, 22vh) in
|
||||
// cockpit-panels.css), so the two rails' tops line up.
|
||||
export const COCKPIT_UTILITY_MIN_TOP_PX = 206;
|
||||
|
||||
export const COCKPIT_UTILITY_MIN_TOP_RATIO = 0.12;
|
||||
export const COCKPIT_UTILITY_MIN_TOP_RATIO = 0.22;
|
||||
|
||||
export const COCKPIT_UTILITY_LAUNCHER_MIN_HEIGHT_PX = 50;
|
||||
|
||||
@@ -184,11 +186,15 @@ const COCKPIT_ENTRY_FACES = Object.freeze({
|
||||
});
|
||||
|
||||
/**
|
||||
* The entry's glyph and localized label for the subject it would ride.
|
||||
* @param {'aircraft'|'vessel'|'satellite'|null|undefined} kind
|
||||
* The entry's glyph and localized label for the subject it would ride. An
|
||||
* application provider's subject brings its own face, already in the page's
|
||||
* language (`presence.entryFace`).
|
||||
* @param {string|null|undefined} kind
|
||||
* @param {{icon: string, label: string}|null} [face]
|
||||
* @returns {{icon: string, label: string}}
|
||||
*/
|
||||
export function cockpitEntryFace(kind) {
|
||||
const face = COCKPIT_ENTRY_FACES[kind] ?? COCKPIT_ENTRY_FACES.aircraft;
|
||||
return { icon: face.icon, label: t(face.label) };
|
||||
export function cockpitEntryFace(kind, face = null) {
|
||||
if (face?.icon && face?.label) return { icon: face.icon, label: face.label };
|
||||
const known = COCKPIT_ENTRY_FACES[kind] ?? COCKPIT_ENTRY_FACES.aircraft;
|
||||
return { icon: known.icon, label: t(known.label) };
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,25 +1,45 @@
|
||||
/** Tracking identity, entry, exit and contact navigation for the Cockpit controller. */
|
||||
import { t } from '../i18n/index.js';
|
||||
import { cameraOf } from '../render/rendererOf.js';
|
||||
import {
|
||||
formatHeadingReadout,
|
||||
normalizeHeading,
|
||||
resolveTrackedAircraftInfo,
|
||||
} from '../cockpitMath.js';
|
||||
import {
|
||||
followedOf,
|
||||
resumeFollowing,
|
||||
stopFollowing,
|
||||
} from '../data/followed.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import {
|
||||
cockpitSubjectCandidate,
|
||||
cockpitSubjectFrame,
|
||||
} from '../cockpitSubjectProviders.js';
|
||||
|
||||
/** The camera's own heading in degrees, or 0 when it has none. */
|
||||
function cameraHeadingDeg(camera) {
|
||||
const heading = camera?.heading;
|
||||
/**
|
||||
* Whether the aircraft entity Cockpit holds still draws, as its services
|
||||
* say; true when they cannot say.
|
||||
*/
|
||||
export function trackedEntityDrawn(entity) {
|
||||
const drawn = this.services.trackedEntityDrawn;
|
||||
return typeof drawn === 'function' ? drawn(entity) !== false : true;
|
||||
}
|
||||
|
||||
/** A camera pose's heading in degrees, or 0 when it has none. */
|
||||
function cameraHeadingDeg(pose) {
|
||||
const heading = pose?.heading;
|
||||
return Number.isFinite(heading) ? (heading * 180) / Math.PI : 0;
|
||||
}
|
||||
|
||||
export function readAircraftInfo() {
|
||||
// In cockpit mode the controller takes the entity off `viewer.trackedEntity`
|
||||
// (see update()), so the cockpit's own handle is the tracked identity there.
|
||||
const trackedEntity = this.viewer?.trackedEntity || this.trackedEntity;
|
||||
// In cockpit mode the controller stops the camera following (see enter()),
|
||||
// so the cockpit's own handle is the tracked identity there.
|
||||
const followed = followedOf(this.viewer) || this.trackedFollow;
|
||||
return resolveTrackedAircraftInfo({
|
||||
civilian: this.services.flightsLayer.getTrackedInfo?.() || null,
|
||||
military: this.services.militaryFlightsLayer.getTrackedInfo?.() || null,
|
||||
trackedId: trackedEntity?.gevTrackedId || '',
|
||||
trackedId: followed?.key || '',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -33,41 +53,206 @@ export function readSatelliteInfo() {
|
||||
return this.services.satellitesLayer?.getCockpitSubject?.() || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What an application subject provider would have entry ride now, or null.
|
||||
* @param {object} provider A provider from cockpitSubjectProviders.
|
||||
* @returns {{id: string, name: string, face: object|null}|null}
|
||||
*/
|
||||
export function readSubjectCandidate(provider) {
|
||||
return cockpitSubjectCandidate(
|
||||
this.callSubject(provider, 'candidate', [], null),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a provider's `read` and `hud` receive besides the frame: the shared
|
||||
* ground floor at a point (metres, or null), a way to warm its cells, and the
|
||||
* floor service's lift.
|
||||
*/
|
||||
export function subjectContext() {
|
||||
this._subjectContext ??= Object.freeze({
|
||||
groundHeightAt: (latitude, longitude) => {
|
||||
const height = this.services.cachedGroundFloor?.(latitude, longitude);
|
||||
return Number.isFinite(height) ? height : null;
|
||||
},
|
||||
warmGround: (points) => {
|
||||
this.services.warmGroundFloor?.(points);
|
||||
},
|
||||
liftM: Number.isFinite(this.services.GROUND_FLOOR_LIFT_M)
|
||||
? this.services.GROUND_FLOOR_LIFT_M
|
||||
: 0,
|
||||
});
|
||||
return this._subjectContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ridden provider subject as the camera and HUD read it: the frame's
|
||||
* place and motion, named like the built-in kinds' info.
|
||||
* @param {object} frame From cockpitSubjectFrame.
|
||||
*/
|
||||
export function subjectInfo(frame) {
|
||||
return {
|
||||
kind: this.subjectProvider?.kind ?? null,
|
||||
generic: true,
|
||||
layerId: this.subjectProvider?.layerId ?? null,
|
||||
id: frame.id,
|
||||
name: frame.name,
|
||||
latitude: frame.latitude,
|
||||
longitude: frame.longitude,
|
||||
track: frame.headingDeg,
|
||||
motionCourse: frame.courseDeg,
|
||||
velocityMps: frame.speedMps ?? 0,
|
||||
stale: frame.stale,
|
||||
groundClamp: frame.groundClamp,
|
||||
anchor: frame.anchor,
|
||||
onGround: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** The built-in kinds' fixed entry order. */
|
||||
const BUILT_IN_ENTRY_ORDER = Object.freeze({
|
||||
aircraft: 0,
|
||||
satellite: 1,
|
||||
vessel: 2,
|
||||
});
|
||||
|
||||
/**
|
||||
* Every subject entry could ride now, in entry order: a tracked aircraft,
|
||||
* the tracked satellite, the selected vessel and each provider's candidate.
|
||||
* The built-in kinds keep their fixed order (aircraft, satellite, vessel),
|
||||
* whenever each was selected. A provider's candidate goes ahead of them only
|
||||
* when it was selected after every built-in one present: a train picked
|
||||
* after an aircraft was tracked takes entry, an aircraft tracked after it
|
||||
* takes it back. Providers' candidates are ordered most recently selected
|
||||
* first, then by priority. A candidate's time is when this controller first
|
||||
* saw it (it looks on its entry cadence and on tracking changes), or saw it
|
||||
* selected again: another subject of a built-in kind, a provider candidate
|
||||
* whose `selectedAt` changes, or one without a `selectedAt` whose id changes.
|
||||
* A new id under the same `selectedAt` is the same selection, as when a
|
||||
* train's selection moves to another feed's copy of it. One
|
||||
* first seen together with a built-in candidate comes after it. With no
|
||||
* provider, entry is the built-in order alone. Each carries `allowed()`, its
|
||||
* kind's entry gate.
|
||||
* @param {number} [nowMs]
|
||||
* @returns {Array<{kind: string, id: string, seenAtMs: number, order: number,
|
||||
* allowed: () => boolean, provider?: object, candidate?: object}>}
|
||||
*/
|
||||
export function entryCandidates(nowMs = performance.now()) {
|
||||
const seen = (this._entrySeen ??= new Map());
|
||||
const list = [];
|
||||
const note = (kind, id, entry, selectedAt = null) => {
|
||||
const last = seen.get(kind);
|
||||
// A provider's token says when its subject was selected: a new id under
|
||||
// the same token (a train handed to another feed's copy of it) is not a
|
||||
// new selection. Without a token, a new id is.
|
||||
if (
|
||||
!last ||
|
||||
last.selectedAt !== selectedAt ||
|
||||
(selectedAt === null && last.id !== id)
|
||||
)
|
||||
seen.set(kind, { id, selectedAt, atMs: nowMs });
|
||||
else if (last.id !== id) seen.set(kind, { ...last, id });
|
||||
list.push({ kind, id, seenAtMs: seen.get(kind).atMs, ...entry });
|
||||
};
|
||||
const aircraft = this.readAircraftInfo();
|
||||
const followed = aircraft ? followedOf(this.viewer) : null;
|
||||
if (aircraft && followed?.entity?.position)
|
||||
note(
|
||||
'aircraft',
|
||||
String(followed.key || aircraft.icao24 || aircraft.id || 'aircraft'),
|
||||
{
|
||||
order: BUILT_IN_ENTRY_ORDER.aircraft,
|
||||
allowed: () => this.isEntryAllowed(),
|
||||
},
|
||||
);
|
||||
const satellite = this.readSatelliteInfo();
|
||||
if (satellite)
|
||||
note('satellite', String(satellite.noradId ?? satellite.id ?? ''), {
|
||||
order: BUILT_IN_ENTRY_ORDER.satellite,
|
||||
allowed: () => this.isOrbitEntryAllowed(),
|
||||
});
|
||||
const vessel = this.readVesselInfo();
|
||||
if (vessel)
|
||||
note('vessel', String(vessel.id ?? ''), {
|
||||
order: BUILT_IN_ENTRY_ORDER.vessel,
|
||||
allowed: () => this.isBridgeEntryAllowed(),
|
||||
});
|
||||
this.subjectProviders.forEach((provider, index) => {
|
||||
const candidate = this.readSubjectCandidate(provider);
|
||||
if (candidate)
|
||||
note(
|
||||
provider.kind,
|
||||
candidate.id,
|
||||
{
|
||||
order: 3 + index,
|
||||
provider,
|
||||
candidate,
|
||||
allowed: () => this.isSubjectEntryAllowed(provider, candidate),
|
||||
},
|
||||
candidate.selectedAt,
|
||||
);
|
||||
});
|
||||
// A subject gone and back counts as selected again.
|
||||
for (const kind of [...seen.keys()])
|
||||
if (!list.some((entry) => entry.kind === kind)) seen.delete(kind);
|
||||
const builtIns = list
|
||||
.filter((entry) => !entry.provider)
|
||||
.sort((a, b) => a.order - b.order);
|
||||
const provided = list
|
||||
.filter((entry) => entry.provider)
|
||||
.sort((a, b) => b.seenAtMs - a.seenAtMs || a.order - b.order);
|
||||
const builtInSeenAtMs = Math.max(
|
||||
-Infinity,
|
||||
...builtIns.map((entry) => entry.seenAtMs),
|
||||
);
|
||||
const later = provided.filter((entry) => entry.seenAtMs > builtInSeenAtMs);
|
||||
const earlier = provided.filter((entry) => entry.seenAtMs <= builtInSeenAtMs);
|
||||
return [...later, ...builtIns, ...earlier];
|
||||
}
|
||||
|
||||
/**
|
||||
* The subject entry would ride: the first in entry order (entryCandidates).
|
||||
* It decides alone, so when its own gate is shut entry is unavailable rather
|
||||
* than taken by the next one.
|
||||
* @returns {object|null} An entry of entryCandidates, or null.
|
||||
*/
|
||||
export function resolveEntry(nowMs = performance.now()) {
|
||||
return this.entryCandidates(nowMs)[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The layer the active view rides: Live AIS Vessels on a bridge, Satellites
|
||||
* in orbit, else the aircraft's own layer. It is read from the tracked
|
||||
* entity's id once the layer has dropped its tracking, so a layer turned off
|
||||
* still names itself.
|
||||
* @returns {'flights'|'military'|'ais-live-vessels'|'satellites'|null}
|
||||
* in orbit, a provider's own layer, else the aircraft's own layer. It is read
|
||||
* from the followed aircraft's key once the layer has dropped its tracking,
|
||||
* so a layer turned off still names itself.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function readSubjectLayerId() {
|
||||
if (!this.active) return null;
|
||||
if (this.subjectProvider) return this.subjectProvider.layerId;
|
||||
if (this.subjectKind === 'vessel') return 'ais-live-vessels';
|
||||
if (this.subjectKind === 'satellite') return 'satellites';
|
||||
const layerId = this.readAircraftInfo()?.layerId;
|
||||
if (layerId) return layerId;
|
||||
const [prefix] = String(this.trackedEntity?.gevTrackedId || '').split(':');
|
||||
const [prefix] = String(this.trackedFollow?.key || '').split(':');
|
||||
return ['flights', 'military'].includes(prefix) ? prefix : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The subject entry would take: a Cesium-tracked aircraft first, then the
|
||||
* tracked satellite, else the selected vessel. Vessels never take Cesium
|
||||
* tracking, so an aircraft and a vessel cannot be live through the same owner.
|
||||
* @returns {'aircraft'|'satellite'|'vessel'|null}
|
||||
* The kind entry would take, the first in entry order's (resolveEntry): a
|
||||
* followed aircraft, the tracked satellite, the selected vessel or a
|
||||
* provider's candidate.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function resolveEntryKind() {
|
||||
if (this.readAircraftInfo() && this.viewer.trackedEntity?.position)
|
||||
return 'aircraft';
|
||||
if (this.readSatelliteInfo()) return 'satellite';
|
||||
return this.readVesselInfo() ? 'vessel' : null;
|
||||
return this.resolveEntry()?.kind ?? null;
|
||||
}
|
||||
|
||||
export function dispatchCockpitModeChanged(active, info = null) {
|
||||
const subjectId = active
|
||||
? String(
|
||||
info?.icao24 ||
|
||||
(info?.kind === 'vessel' ? info.id : '') ||
|
||||
(info?.kind === 'vessel' || info?.generic === true ? info.id : '') ||
|
||||
info?.noradId ||
|
||||
'',
|
||||
)
|
||||
@@ -76,9 +261,13 @@ export function dispatchCockpitModeChanged(active, info = null) {
|
||||
: null;
|
||||
const layerId =
|
||||
active &&
|
||||
['flights', 'military', 'ais-live-vessels', 'satellites'].includes(
|
||||
(['flights', 'military', 'ais-live-vessels', 'satellites'].includes(
|
||||
info?.layerId,
|
||||
)
|
||||
) ||
|
||||
(info?.generic === true &&
|
||||
this.subjectProviders.some(
|
||||
(provider) => provider.layerId === info.layerId,
|
||||
)))
|
||||
? info.layerId
|
||||
: null;
|
||||
window.dispatchEvent(
|
||||
@@ -127,40 +316,60 @@ export function syncTr3bToggle(info) {
|
||||
this.publishPresenceView();
|
||||
}
|
||||
|
||||
/**
|
||||
* Word the ridden provider subject's labels and Look ahead button again,
|
||||
* after a change of the page's language: a provider may give them as
|
||||
* functions (cockpitSubjectProviders).
|
||||
*/
|
||||
export function refreshSubjectWords() {
|
||||
const provider = this.subjectProvider;
|
||||
if (!this.active || !provider) return;
|
||||
this.presence.subjectLabels = { ...provider.labels };
|
||||
const look = provider.look;
|
||||
this.presence.subjectLook = look ? { aheadLabel: look.aheadLabel } : null;
|
||||
this.publishPresenceView();
|
||||
}
|
||||
|
||||
export function syncEntry() {
|
||||
if (this.destroyed) return false;
|
||||
if (this.active) return;
|
||||
const info = this.readAircraftInfo();
|
||||
const trackedContact = !!(info && this.viewer.trackedEntity?.position);
|
||||
this.syncTr3bToggle(trackedContact ? info : null);
|
||||
const orbitContact = !trackedContact && !!this.readSatelliteInfo();
|
||||
const bridgeContact =
|
||||
!trackedContact && !orbitContact && !!this.readVesselInfo();
|
||||
let entryKind = null;
|
||||
if (trackedContact) entryKind = this.isEntryAllowed() ? 'aircraft' : null;
|
||||
else if (orbitContact)
|
||||
entryKind = this.isOrbitEntryAllowed() ? 'satellite' : null;
|
||||
else if (bridgeContact)
|
||||
entryKind = this.isBridgeEntryAllowed() ? 'vessel' : null;
|
||||
const candidates = this.entryCandidates(performance.now());
|
||||
const tracked = candidates.some(({ kind }) => kind === 'aircraft');
|
||||
this.syncTr3bToggle(tracked ? this.readAircraftInfo() : null);
|
||||
// The first in entry order decides alone (resolveEntry).
|
||||
const chosen = candidates[0] ?? null;
|
||||
const entryKind = chosen?.allowed() ? chosen.kind : null;
|
||||
const face =
|
||||
entryKind && chosen.provider
|
||||
? (chosen.candidate.face ?? chosen.provider.entryFace)
|
||||
: null;
|
||||
const available = entryKind !== null;
|
||||
// Change-only publishes: this runs on a preUpdate cadence, and a fresh
|
||||
// presence every frame would re-render the views even when nothing
|
||||
// changed. (perf item 9)
|
||||
if (
|
||||
this.presence.entryAvailable === available &&
|
||||
this.presence.entryKind === entryKind
|
||||
this.presence.entryKind === entryKind &&
|
||||
this.presence.entryFace?.icon === face?.icon &&
|
||||
this.presence.entryFace?.label === face?.label
|
||||
)
|
||||
return;
|
||||
this.presence.entryAvailable = available;
|
||||
this.presence.entryKind = entryKind;
|
||||
this.presence.entryFace = face && { icon: face.icon, label: face.label };
|
||||
this.publishPresenceView();
|
||||
}
|
||||
|
||||
export function navigateContext(direction, options = {}) {
|
||||
if (this.destroyed) return false;
|
||||
// Contact navigation moves between aircraft; a bridge does not jump ship
|
||||
// and an orbital view stays with its satellite.
|
||||
if (this.subjectKind === 'vessel' || this.subjectKind === 'satellite')
|
||||
// Contact navigation moves between aircraft; a bridge does not jump ship,
|
||||
// an orbital view stays with its satellite and a provider's view with its
|
||||
// subject.
|
||||
if (
|
||||
this.subjectKind === 'vessel' ||
|
||||
this.subjectKind === 'satellite' ||
|
||||
this.subjectProvider
|
||||
)
|
||||
return false;
|
||||
const method = direction < 0 ? 'navigatePrevious' : 'navigateNext';
|
||||
const wasActive = this.active;
|
||||
@@ -180,11 +389,17 @@ export function navigateContext(direction, options = {}) {
|
||||
}
|
||||
|
||||
export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
|
||||
// An aircraft tracked from the bridge or from orbit ends that view (see the
|
||||
// vessel and orbital camera updates); it is never adopted as its subject.
|
||||
if (this.subjectKind === 'vessel' || this.subjectKind === 'satellite')
|
||||
// An aircraft followed from the bridge, from orbit or from a provider's
|
||||
// view ends that view (see the camera updates); it is never adopted as its
|
||||
// subject.
|
||||
if (
|
||||
this.subjectKind === 'vessel' ||
|
||||
this.subjectKind === 'satellite' ||
|
||||
this.subjectProvider
|
||||
)
|
||||
return false;
|
||||
const nextEntity = this.viewer.trackedEntity;
|
||||
const nextFollowed = followedOf(this.viewer);
|
||||
const nextEntity = nextFollowed?.entity;
|
||||
if (
|
||||
!this.active ||
|
||||
!nextEntity?.position ||
|
||||
@@ -193,13 +408,14 @@ export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
|
||||
return false;
|
||||
const info = suppliedInfo || this.readAircraftInfo();
|
||||
if (!info) return false;
|
||||
if (this.trackedEntity && this.viewer.entities.contains(this.trackedEntity)) {
|
||||
if (this.trackedEntity && trackedEntityDrawn.call(this, this.trackedEntity)) {
|
||||
this.trackedEntity.show = this.trackedEntityWasShown;
|
||||
}
|
||||
this.trackedEntity = nextEntity;
|
||||
this.trackedFollow = nextFollowed;
|
||||
this.trackedEntityWasShown = nextEntity.show;
|
||||
nextEntity.show = false;
|
||||
this.viewer.trackedEntity = undefined;
|
||||
stopFollowing(this.viewer);
|
||||
this.cockpitAnchorValid = false;
|
||||
this.heading = normalizeHeading(info.track ?? 0);
|
||||
this.lastFrameMs = nowMs;
|
||||
@@ -213,16 +429,154 @@ export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Enter first person on a tracked aircraft or, with none tracked, the
|
||||
* tracked satellite's orbital view or the selected vessel's bridge.
|
||||
* @param {{kind?: 'aircraft'|'satellite'|'vessel'|null}} [options] Restrict
|
||||
* entry to one subject kind; voice entry is aircraft-only.
|
||||
* Enter a provider's view on its candidate: hold it, read a first frame, then
|
||||
* take the camera as the built-in views do. Entry fails when the gate is shut,
|
||||
* the hold answers anything but `true` or no frame comes; past the gate, a
|
||||
* failed entry releases the subject, since the hold may have taken it.
|
||||
* @param {object} provider From cockpitSubjectProviders.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function enterSubject(provider) {
|
||||
const candidate = this.readSubjectCandidate(provider);
|
||||
if (!candidate || !this.isSubjectEntryAllowed(provider, candidate))
|
||||
return false;
|
||||
const failed = {};
|
||||
const release = () =>
|
||||
this.callSubject(provider, 'release', [candidate.id, { restore: false }]);
|
||||
// An asynchronous hold may land after it was refused: it is released
|
||||
// again once it settles, unless this subject is being ridden by then.
|
||||
const releaseLate = () => {
|
||||
if (
|
||||
this.active &&
|
||||
this.subjectProvider === provider &&
|
||||
this.subjectId === candidate.id
|
||||
)
|
||||
return;
|
||||
release();
|
||||
};
|
||||
const held = this.callSubject(
|
||||
provider,
|
||||
'hold',
|
||||
[candidate.id],
|
||||
failed,
|
||||
releaseLate,
|
||||
);
|
||||
if (held !== true) {
|
||||
// `false` refuses entry; a hold that threw, returned a promise or
|
||||
// answered anything else (warned of once) may still have taken the
|
||||
// subject. Each is released.
|
||||
if (held !== false && held !== failed)
|
||||
this.callSubject.warnOnce(
|
||||
provider,
|
||||
'hold',
|
||||
'must return true or false; entry refused',
|
||||
held,
|
||||
);
|
||||
release();
|
||||
return false;
|
||||
}
|
||||
const frame = cockpitSubjectFrame(
|
||||
this.callSubject(
|
||||
provider,
|
||||
'read',
|
||||
[performance.now(), this.subjectContext()],
|
||||
null,
|
||||
),
|
||||
candidate.id,
|
||||
);
|
||||
if (!frame) {
|
||||
this.callSubject(provider, 'release', [candidate.id, { restore: false }]);
|
||||
return false;
|
||||
}
|
||||
this.entryFocusOrigin =
|
||||
document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null;
|
||||
this.onCameraTakeover?.();
|
||||
cameraOf(this.viewer).cancelFlight();
|
||||
this.subjectKind = provider.kind;
|
||||
this.subjectProvider = provider;
|
||||
this.subjectId = candidate.id;
|
||||
this.lastSubjectFrame = frame;
|
||||
this.subjectHud = null;
|
||||
this.subjectSignalKeys = new Set();
|
||||
this.vesselWaterline = null;
|
||||
this.vesselFix = null;
|
||||
this.trackedEntity = null;
|
||||
this.heading = normalizeHeading(
|
||||
frame.headingDeg ?? cameraHeadingDeg(cameraOf(this.viewer).pose()),
|
||||
);
|
||||
this.lastFrameMs = performance.now();
|
||||
this.lastCameraUpdateMs = 0;
|
||||
this.lastHudUpdateMs = 0;
|
||||
this.lastContextUpdateMs = 0;
|
||||
this.contextNavigationDeadlineMs = 0;
|
||||
this.lastGroundProbeMs = 0;
|
||||
this.surfaceWaitStartedMs = 0;
|
||||
this.surfaceAcquiring = false;
|
||||
this.surfaceFallback = false;
|
||||
this.cockpitAnchorValid = false;
|
||||
this.subjectHeightM = null;
|
||||
this.lookRestPitchDeg = provider.look?.restPitchDeg ?? null;
|
||||
this.resetLook({ immediate: true });
|
||||
this.active = true;
|
||||
this.services.holdContinuousRender('cockpit');
|
||||
stopFollowing(this.viewer);
|
||||
this.releaseCameraInput?.();
|
||||
this.releaseCameraInput = inputFor(this.viewer).suspendCamera('cockpit');
|
||||
document.body.classList.add('cockpit-mode', 'cockpit-subject');
|
||||
this._tr3bSignature = null;
|
||||
Object.assign(this.presence, {
|
||||
active: true,
|
||||
entryAvailable: false,
|
||||
entryKind: null,
|
||||
entryFace: null,
|
||||
subjectKind: provider.kind,
|
||||
subjectGeneric: true,
|
||||
subjectLabels: { ...provider.labels },
|
||||
subjectLook: provider.look
|
||||
? { aheadLabel: provider.look.aheadLabel }
|
||||
: null,
|
||||
tr3b: null,
|
||||
});
|
||||
this.publishPresenceView();
|
||||
this.publishRadar(null);
|
||||
this.signalItems = [];
|
||||
this.signalSignatures.clear();
|
||||
this.showBriefPage(0);
|
||||
this.startBriefRotation();
|
||||
this.pushCockpitSignal('track', 'track', t('TRACK ACQUIRED'), frame.name);
|
||||
const info = this.subjectInfo(frame);
|
||||
this.updateHud(info, performance.now(), true);
|
||||
this.setVisionMode(this.getInitialVisionMode());
|
||||
this.scheduleContextLayout();
|
||||
Promise.resolve().then(() => {
|
||||
if (this.active && !this.destroyed)
|
||||
this.mapViewButton?.focus({ preventScroll: true });
|
||||
});
|
||||
this.onEntered?.();
|
||||
this.onRide?.(provider.layerId);
|
||||
this.dispatchCockpitModeChanged(true, info);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enter first person on the first subject in entry order (resolveEntry): a
|
||||
* tracked aircraft, the tracked satellite's orbital view, the selected
|
||||
* vessel's bridge or an application provider's subject.
|
||||
* @param {{kind?: string|null}} [options] Restrict entry to one subject kind;
|
||||
* voice entry is aircraft-only.
|
||||
* @returns {boolean} True when the view was entered.
|
||||
*/
|
||||
export function enter({ kind = null } = {}) {
|
||||
if (this.destroyed) return false;
|
||||
if (this.active) return false;
|
||||
const subjectKind = kind ?? this.resolveEntryKind() ?? 'aircraft';
|
||||
const provider = this.subjectProviders.find(
|
||||
(entry) => entry.kind === subjectKind,
|
||||
);
|
||||
if (provider) return enterSubject.call(this, provider);
|
||||
if (!['aircraft', 'satellite', 'vessel'].includes(subjectKind)) return false;
|
||||
const vessel = subjectKind === 'vessel';
|
||||
const satellite = subjectKind === 'satellite';
|
||||
const allowed = vessel
|
||||
@@ -236,8 +590,9 @@ export function enter({ kind = null } = {}) {
|
||||
: satellite
|
||||
? this.readSatelliteInfo()
|
||||
: this.readAircraftInfo();
|
||||
// Only an aircraft is ridden through its Cesium entity.
|
||||
const entity = vessel || satellite ? null : this.viewer.trackedEntity;
|
||||
// Only an aircraft is ridden through the followed entity.
|
||||
const followed = vessel || satellite ? null : followedOf(this.viewer);
|
||||
const entity = followed?.entity ?? null;
|
||||
if (!info || (!vessel && !satellite && !entity?.position)) return false;
|
||||
this.entryFocusOrigin =
|
||||
document.activeElement instanceof HTMLElement
|
||||
@@ -245,13 +600,14 @@ export function enter({ kind = null } = {}) {
|
||||
: null;
|
||||
// Retire deferred navigation before cancelFlight can run its callbacks.
|
||||
this.onCameraTakeover?.();
|
||||
this.viewer.camera.cancelFlight();
|
||||
cameraOf(this.viewer).cancelFlight();
|
||||
this.subjectKind = subjectKind;
|
||||
// Each session reads its own water: never a height left from the last.
|
||||
this.vesselWaterline = null;
|
||||
this.vesselFix = null;
|
||||
this.subjectId = vessel ? info.id : satellite ? info.noradId : null;
|
||||
this.trackedEntity = entity;
|
||||
this.trackedFollow = followed;
|
||||
if (entity) {
|
||||
this.trackedEntityWasShown = entity.show;
|
||||
entity.show = false;
|
||||
@@ -268,7 +624,7 @@ export function enter({ kind = null } = {}) {
|
||||
Number.isFinite(info.track)
|
||||
? info.track
|
||||
: vessel
|
||||
? cameraHeadingDeg(this.viewer.camera)
|
||||
? cameraHeadingDeg(cameraOf(this.viewer).pose())
|
||||
: 0,
|
||||
);
|
||||
this.lastFrameMs = performance.now();
|
||||
@@ -289,8 +645,9 @@ export function enter({ kind = null } = {}) {
|
||||
// runs on rendered frames, so idle mode would freeze the cockpit solid.
|
||||
// (perf wave 2)
|
||||
this.services.holdContinuousRender('cockpit');
|
||||
this.viewer.trackedEntity = undefined;
|
||||
this.viewer.scene.screenSpaceCameraController.enableInputs = false;
|
||||
stopFollowing(this.viewer);
|
||||
this.releaseCameraInput?.();
|
||||
this.releaseCameraInput = inputFor(this.viewer).suspendCamera('cockpit');
|
||||
document.body.classList.add('cockpit-mode');
|
||||
// Bridge styling reaches surfaces outside the HUD (exit row, side panels).
|
||||
if (vessel) document.body.classList.add('cockpit-bridge');
|
||||
@@ -373,16 +730,24 @@ export function enter({ kind = null } = {}) {
|
||||
export function exit({ restoreTracking = true } = {}) {
|
||||
if (!this.active) return false;
|
||||
const entity = this.trackedEntity;
|
||||
const followed = this.trackedFollow;
|
||||
const provider = this.subjectProvider;
|
||||
const providerSubject = provider ? this.subjectId : null;
|
||||
const vesselSubject = this.subjectKind === 'vessel' ? this.subjectId : null;
|
||||
const satelliteSubject =
|
||||
this.subjectKind === 'satellite' ? this.subjectId : null;
|
||||
this.active = false;
|
||||
this.subjectKind = null;
|
||||
this.subjectProvider = null;
|
||||
this.lastSubjectFrame = null;
|
||||
this.subjectHud = null;
|
||||
this.lookRestPitchDeg = null;
|
||||
this.vesselWaterline = null;
|
||||
this.vesselFix = null;
|
||||
this.subjectId = null;
|
||||
this.services.releaseContinuousRender('cockpit');
|
||||
this.trackedEntity = null;
|
||||
this.trackedFollow = null;
|
||||
this.heading = null;
|
||||
this.resetLook({ immediate: true });
|
||||
this.cockpitAnchorValid = false;
|
||||
@@ -401,6 +766,7 @@ export function exit({ restoreTracking = true } = {}) {
|
||||
'cockpit-mode',
|
||||
'cockpit-bridge',
|
||||
'cockpit-orbit',
|
||||
'cockpit-subject',
|
||||
);
|
||||
// The camera's own field of view returns before any follow resumes.
|
||||
this.endOrbital();
|
||||
@@ -408,22 +774,34 @@ export function exit({ restoreTracking = true } = {}) {
|
||||
this.publishUtilityLayout(null);
|
||||
this.presence.active = false;
|
||||
this.presence.subjectKind = null;
|
||||
this.presence.subjectGeneric = false;
|
||||
this.presence.subjectLabels = null;
|
||||
this.presence.subjectLook = null;
|
||||
this.publishPresenceView();
|
||||
this.routeView.visible = false;
|
||||
this.clearPredictiveRoute();
|
||||
this.publishRadar(null);
|
||||
this.setVisionMode('optical');
|
||||
this.viewer.scene.screenSpaceCameraController.enableInputs = true;
|
||||
if (entity && this.viewer.entities.contains(entity))
|
||||
entity.show = this.trackedEntityWasShown;
|
||||
this.releaseCameraInput?.();
|
||||
this.releaseCameraInput = null;
|
||||
const present = () =>
|
||||
Boolean(entity) && trackedEntityDrawn.call(this, entity);
|
||||
if (present()) entity.show = this.trackedEntityWasShown;
|
||||
this.trackedEntityWasShown = true;
|
||||
if (vesselSubject)
|
||||
this.services.aisLiveVesselsLayer?.setCockpitSubject?.(null);
|
||||
if (satelliteSubject !== null)
|
||||
this.services.satellitesLayer?.setCockpitSubject?.(null);
|
||||
// The provider gives its subject back; `restore` asks it to bring the map
|
||||
// back to it, as the built-in kinds' refocus does.
|
||||
if (provider)
|
||||
this.callSubject(provider, 'release', [
|
||||
providerSubject,
|
||||
{ restore: restoreTracking === true },
|
||||
]);
|
||||
this.dispatchCockpitModeChanged(false);
|
||||
if (restoreTracking && entity && this.viewer.entities.contains(entity)) {
|
||||
this.viewer.trackedEntity = entity;
|
||||
if (restoreTracking && present()) {
|
||||
resumeFollowing(this.viewer, followed);
|
||||
this.restoreTrackingFrame(entity);
|
||||
} else if (restoreTracking && vesselSubject) {
|
||||
// Back to the selected vessel's map view, through the layer's own focus.
|
||||
|
||||
@@ -450,3 +450,42 @@ test('the real layout pass drives the mounted controls: compact hides the collap
|
||||
assert.equal(cockpit.utilityLayout.top, '120.00px');
|
||||
assert.equal(strip.classList.contains('layout-primary-only'), false);
|
||||
});
|
||||
|
||||
test('the rail opens one panel at a time and reads as a disclosure', async (t) => {
|
||||
const { $, controls } = fixture(t);
|
||||
const item = (kind) =>
|
||||
document.querySelector(`[data-cockpit-rail-item="${kind}"]`);
|
||||
item('display').click();
|
||||
await nextTick();
|
||||
assert.equal($('cockpit-display-panel').hidden, false);
|
||||
assert.equal(item('display').getAttribute('aria-expanded'), 'true');
|
||||
assert.equal(
|
||||
item('display').getAttribute('aria-controls'),
|
||||
'cockpit-display-panel',
|
||||
);
|
||||
item('radio').click();
|
||||
await nextTick();
|
||||
assert.equal($('cockpit-display-panel').hidden, true);
|
||||
assert.equal($('cockpit-radio-panel').hidden, false);
|
||||
assert.equal(item('display').getAttribute('aria-expanded'), 'false');
|
||||
assert.equal(item('radio').getAttribute('aria-expanded'), 'true');
|
||||
item('radio').click();
|
||||
await nextTick();
|
||||
assert.equal(controls._cockpitDisclosureOpen('radio'), false);
|
||||
assert.equal(controls._cockpitDisclosureOpen('display'), false);
|
||||
});
|
||||
|
||||
test('collapsing an open panel hands focus to the rail when its toggle is hidden', async (t) => {
|
||||
const { $, controls } = fixture(t);
|
||||
const railItem = document.querySelector('[data-cockpit-rail-item="radio"]');
|
||||
// happy-dom lays nothing out: show the rail and hide the launcher's toggle
|
||||
// as the desktop look does.
|
||||
railItem.getClientRects = () => [{ width: 32, height: 32 }];
|
||||
$('cockpit-radio-toggle-btn').getClientRects = () => [];
|
||||
controls._setCockpitDisclosure('radio', true);
|
||||
await nextTick();
|
||||
document.querySelector('.cockpit-utility-collapse').click();
|
||||
await nextTick();
|
||||
assert.equal($('cockpit-radio-panel').hidden, true);
|
||||
assert.equal(document.activeElement, railItem);
|
||||
});
|
||||
@@ -142,7 +142,7 @@ test('the map source row renders the published chips and selects through the con
|
||||
assert.equal(osm.classList.contains('active'), true);
|
||||
assert.equal(osm.getAttribute('aria-pressed'), 'true');
|
||||
assert.equal(osm.hasAttribute('aria-label'), false);
|
||||
assert.equal(esri.querySelector('.map-stack-chip-req'), null);
|
||||
assert.equal(esri.querySelector('.map-stack-chip-req') === null, true);
|
||||
bing.click();
|
||||
esri.click();
|
||||
assert.deepEqual(selected, ['esri-imagery']);
|
||||
|
||||
@@ -56,6 +56,8 @@ import {
|
||||
isScopeMaskEnabled,
|
||||
setScopeMaskFeather,
|
||||
getScopeMaskFeather,
|
||||
setScopeMaskOpacity,
|
||||
getScopeMaskOpacity,
|
||||
setScopeTerminusOverride,
|
||||
getScopeTerminusOverride,
|
||||
clampScopeTerminusPct,
|
||||
@@ -112,6 +114,8 @@ export class StyleManager extends ApplicationShell {
|
||||
isScopeMaskEnabled,
|
||||
setScopeMaskFeather,
|
||||
getScopeMaskFeather,
|
||||
setScopeMaskOpacity,
|
||||
getScopeMaskOpacity,
|
||||
setScopeTerminusOverride,
|
||||
getScopeTerminusOverride,
|
||||
clampScopeTerminusPct,
|
||||
|
||||
@@ -51,6 +51,8 @@ export class ContextControls {
|
||||
this._contextRestoreState = null;
|
||||
this._contextLayerReactionPromises = new Set();
|
||||
this._preservePanelStateDuringLayerClear = false;
|
||||
/** Layers Context isolation is switching off right now. */
|
||||
this._isolatingLayerIds = new Set();
|
||||
this._userFacingContextNotificationTokens = new Set();
|
||||
this._clearSelectedLayersPromise = null;
|
||||
this._clearSelectedLayersManagerPromise = null;
|
||||
@@ -59,6 +61,16 @@ export class ContextControls {
|
||||
showToast(...args) {
|
||||
if (!this.destroyed) this.actions.showToast(...args);
|
||||
}
|
||||
/**
|
||||
* Whether Context isolation is switching this layer off right now: it is
|
||||
* suspended, and leaving the mode restores it. A switch-off by the user,
|
||||
* inside the mode or out of it, is not.
|
||||
* @param {string} layerId Layer id.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
suspendsLayer(layerId) {
|
||||
return this._isolatingLayerIds.has(layerId);
|
||||
}
|
||||
setClearBusy(...args) {
|
||||
if (!this.destroyed) this.actions.setClearBusy(...args);
|
||||
}
|
||||
|
||||
@@ -153,3 +153,56 @@ test('a rejected tracked reaction settles without an unhandled rejection', async
|
||||
await controls._waitForContextLayerSettlement();
|
||||
assert.equal(controls._contextLayerReactionPromises.size, 0);
|
||||
});
|
||||
|
||||
test('only a layer Context isolation is switching off is suspended', async (t) => {
|
||||
const { controls } = fixture(t);
|
||||
const enabled = new Set(['cctv']);
|
||||
// What the CCTV panel is told at each visibility change of its layer.
|
||||
const seen = [];
|
||||
controls._dataManager = {
|
||||
layers: new Map([['cctv', {}]]),
|
||||
getEnabledLayerIds: () => [...enabled],
|
||||
getLayerParams: () => null,
|
||||
setLayerParams() {},
|
||||
isEnabled: (layerId) => enabled.has(layerId),
|
||||
isEffectivelyEnabled: (layerId) => enabled.has(layerId),
|
||||
async setEnabled(layerId, next) {
|
||||
// The layer tells its panel it is off while it is being disabled.
|
||||
if (next) enabled.add(layerId);
|
||||
else enabled.delete(layerId);
|
||||
seen.push([layerId, next, controls.suspendsLayer(layerId)]);
|
||||
return true;
|
||||
},
|
||||
async restoreEnabledLayerIds(layerIds) {
|
||||
for (const layerId of layerIds) await this.setEnabled(layerId, true);
|
||||
},
|
||||
};
|
||||
assert.equal(controls.suspendsLayer('cctv'), false);
|
||||
controls._captureContextSessionSnapshot();
|
||||
await controls._clearLayersOutsideContextMode('flights');
|
||||
assert.deepEqual(seen, [['cctv', false, true]]);
|
||||
assert.equal(controls.suspendsLayer('cctv'), false, 'only while isolating');
|
||||
// Inside the mode the user turns CCTV back on, then off: their own.
|
||||
await controls._dataManager.setEnabled('cctv', true);
|
||||
await controls._dataManager.setEnabled('cctv', false);
|
||||
assert.deepEqual(seen.at(-1), ['cctv', false, false]);
|
||||
await controls._restoreContextSession();
|
||||
assert.equal(enabled.has('cctv'), true);
|
||||
// A switch-off after the mode is left is the user's own too.
|
||||
await controls._dataManager.setEnabled('cctv', false);
|
||||
assert.deepEqual(seen.at(-1), ['cctv', false, false]);
|
||||
});
|
||||
|
||||
test('a failed isolation leaves no layer suspended', async (t) => {
|
||||
const { controls } = fixture(t);
|
||||
controls._dataManager = {
|
||||
layers: new Map([['cctv', {}]]),
|
||||
isEffectivelyEnabled: () => true,
|
||||
isEnabled: () => true,
|
||||
setEnabled: async () => {
|
||||
throw new Error('disable failed');
|
||||
},
|
||||
};
|
||||
await assert.rejects(controls._clearLayersOutsideContextMode('flights'));
|
||||
assert.equal(controls.suspendsLayer('cctv'), false);
|
||||
});
|
||||
@@ -240,25 +240,35 @@ export async function _clearLayersOutsideContextMode(
|
||||
) {
|
||||
const allowed = contextAllowedLayerIds(mode);
|
||||
const pending = [];
|
||||
for (const [layerId] of this._dataManager.layers || []) {
|
||||
// Effective visibility: a disallowed layer still mid-ENABLING must be
|
||||
// isolated too, or it settles ON inside the exclusive mode.
|
||||
if (
|
||||
!allowed.has(layerId) &&
|
||||
this._dataManager.isEffectivelyEnabled(layerId)
|
||||
) {
|
||||
pending.push({
|
||||
layerId,
|
||||
transition: this._dataManager.setEnabled(layerId, false, {
|
||||
notificationToken,
|
||||
...(signal ? { signal } : {}),
|
||||
}),
|
||||
});
|
||||
// Panels read this while their layer goes off (suspendsLayer): a layer
|
||||
// isolation switches off is suspended, not switched off by the user.
|
||||
const isolating = [];
|
||||
let results;
|
||||
try {
|
||||
for (const [layerId] of this._dataManager.layers || []) {
|
||||
// Effective visibility: a disallowed layer still mid-ENABLING must be
|
||||
// isolated too, or it settles ON inside the exclusive mode.
|
||||
if (
|
||||
!allowed.has(layerId) &&
|
||||
this._dataManager.isEffectivelyEnabled(layerId)
|
||||
) {
|
||||
if (!this._isolatingLayerIds.has(layerId)) {
|
||||
this._isolatingLayerIds.add(layerId);
|
||||
isolating.push(layerId);
|
||||
}
|
||||
pending.push({
|
||||
layerId,
|
||||
transition: this._dataManager.setEnabled(layerId, false, {
|
||||
notificationToken,
|
||||
...(signal ? { signal } : {}),
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
results = await Promise.all(pending.map(({ transition }) => transition));
|
||||
} finally {
|
||||
for (const layerId of isolating) this._isolatingLayerIds.delete(layerId);
|
||||
}
|
||||
const results = await Promise.all(
|
||||
pending.map(({ transition }) => transition),
|
||||
);
|
||||
const failed = pending
|
||||
.filter(
|
||||
({ layerId }, index) =>
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* @module ui/creditsView
|
||||
* @description The attribution line, in the application's own DOM, for a
|
||||
* renderer that does not draw its own credit display: what the renderer's
|
||||
* credits port lists (its own credits, each base layer's, the layers' data
|
||||
* credits). Inline credits are shown on the line at the bottom left; the
|
||||
* rest are in the "Data attribution" list it opens. A credit is plain data
|
||||
* (`src/render/contract/credits.d.ts`): its text is set as text, and a link
|
||||
* or logo is kept only for a safe scheme.
|
||||
*/
|
||||
import { findCredits } from '../render/rendererOf.js';
|
||||
import {
|
||||
LINK_SCHEMES,
|
||||
LOGO_SCHEMES,
|
||||
safeUrl,
|
||||
splitLink,
|
||||
} from '../render/creditMarkup.js';
|
||||
import { onLocaleChange, t } from '../i18n/index.js';
|
||||
|
||||
const PANEL_ID = 'gev-credits-panel';
|
||||
|
||||
/** The credits once each, in order: the same text and link are one. */
|
||||
function distinct(list) {
|
||||
const seen = new Set();
|
||||
return list.filter((credit) => {
|
||||
const key = `${credit?.text ?? ''}\u0000${credit?.href ?? ''}`;
|
||||
if (!credit?.text || seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/** One credit as DOM: its logo or its text, linked when it has a link. */
|
||||
function creditElement(doc, credit) {
|
||||
const href = credit.href ? safeUrl(credit.href, LINK_SCHEMES) : null;
|
||||
const logoUrl = credit.logoUrl ? safeUrl(credit.logoUrl, LOGO_SCHEMES) : null;
|
||||
// Only the credit's linked words are the link, as the source wrote it.
|
||||
if (href && !logoUrl && credit.linkText) {
|
||||
const [before, words, after] = splitLink(credit);
|
||||
const element = doc.createElement('span');
|
||||
element.className = 'gev-credit';
|
||||
const link = doc.createElement('a');
|
||||
link.href = href;
|
||||
link.target = '_blank';
|
||||
link.rel = 'noopener noreferrer';
|
||||
link.textContent = words;
|
||||
element.append(before, link, after);
|
||||
return element;
|
||||
}
|
||||
const element = doc.createElement(href ? 'a' : 'span');
|
||||
element.className = 'gev-credit';
|
||||
if (href) {
|
||||
element.href = href;
|
||||
element.target = '_blank';
|
||||
element.rel = 'noopener noreferrer';
|
||||
}
|
||||
// A logo is drawn in place of the text, which names it (its alt text).
|
||||
const logo = credit.logoUrl ? safeUrl(credit.logoUrl, LOGO_SCHEMES) : null;
|
||||
if (logo) {
|
||||
const image = doc.createElement('img');
|
||||
image.className = 'gev-credit-logo';
|
||||
image.src = logo;
|
||||
image.alt = credit.text;
|
||||
element.append(image);
|
||||
} else element.textContent = credit.text;
|
||||
return element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show `viewer`'s renderer credits at the bottom left of `root`'s page.
|
||||
* @param {object} viewer The scene object, bound to its renderer.
|
||||
* @param {{root?: HTMLElement}} [options] Where the line goes (the body).
|
||||
* @returns {() => void} Removes it.
|
||||
*/
|
||||
export function mountCreditsView(viewer, { root = document.body } = {}) {
|
||||
const credits = findCredits(viewer);
|
||||
if (!credits || !root) return () => {};
|
||||
const doc = root.ownerDocument;
|
||||
const bar = doc.createElement('div');
|
||||
bar.id = 'gev-credits';
|
||||
bar.className = 'gev-credits';
|
||||
// Takes focus back from an emptied list when the line has no link.
|
||||
bar.tabIndex = -1;
|
||||
const line = doc.createElement('span');
|
||||
line.className = 'gev-credits-line';
|
||||
const expand = doc.createElement('button');
|
||||
expand.type = 'button';
|
||||
expand.className = 'gev-credits-expand';
|
||||
expand.setAttribute('aria-haspopup', 'dialog');
|
||||
expand.setAttribute('aria-controls', PANEL_ID);
|
||||
expand.setAttribute('aria-expanded', 'false');
|
||||
|
||||
const panel = doc.createElement('div');
|
||||
panel.id = PANEL_ID;
|
||||
panel.className = 'gev-credits-panel';
|
||||
panel.setAttribute('role', 'dialog');
|
||||
panel.hidden = true;
|
||||
const header = doc.createElement('div');
|
||||
header.className = 'gev-credits-header';
|
||||
const title = doc.createElement('span');
|
||||
title.className = 'gev-credits-title';
|
||||
title.id = `${PANEL_ID}-title`;
|
||||
panel.setAttribute('aria-labelledby', title.id);
|
||||
const close = doc.createElement('button');
|
||||
close.type = 'button';
|
||||
close.className = 'gev-credits-close';
|
||||
close.textContent = '×';
|
||||
header.append(title, close);
|
||||
const list = doc.createElement('ul');
|
||||
list.className = 'gev-credits-list';
|
||||
panel.append(header, list);
|
||||
bar.append(line, expand);
|
||||
root.append(bar, panel);
|
||||
|
||||
const label = () => {
|
||||
expand.textContent = t('Data attribution');
|
||||
title.textContent = t('Data provided by:');
|
||||
close.setAttribute('aria-label', t('Close data attribution'));
|
||||
};
|
||||
|
||||
const setOpen = (open, { focus = false } = {}) => {
|
||||
panel.hidden = !open;
|
||||
expand.setAttribute('aria-expanded', String(open));
|
||||
if (open) close.focus();
|
||||
else if (focus) expand.focus();
|
||||
};
|
||||
|
||||
const render = (all) => {
|
||||
const focused = panel.contains(doc.activeElement);
|
||||
const shown = distinct(Array.isArray(all) ? all : []);
|
||||
const inline = shown.filter((credit) => credit.inline);
|
||||
const listed = shown.filter((credit) => !credit.inline);
|
||||
line.replaceChildren();
|
||||
inline.forEach((credit, i) => {
|
||||
if (i) line.append(doc.createTextNode(' · '));
|
||||
line.append(creditElement(doc, credit));
|
||||
});
|
||||
if (inline.length && listed.length) line.append(doc.createTextNode(' · '));
|
||||
list.replaceChildren(
|
||||
...listed.map((credit) => {
|
||||
const item = doc.createElement('li');
|
||||
item.append(creditElement(doc, credit));
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
expand.hidden = listed.length === 0;
|
||||
if (expand.hidden && !panel.hidden) {
|
||||
// Focus in the list goes back to the line, not to the page.
|
||||
setOpen(false);
|
||||
if (focused) (line.querySelector('a') ?? bar).focus();
|
||||
} else if (focused && !panel.contains(doc.activeElement)) {
|
||||
// A link that focus was on was redrawn: focus stays in the list.
|
||||
close.focus();
|
||||
}
|
||||
};
|
||||
|
||||
const onExpand = () => setOpen(panel.hidden);
|
||||
const onClose = () => setOpen(false, { focus: true });
|
||||
// Escape in the open list closes it (it takes focus as it opens).
|
||||
const onKey = (event) => {
|
||||
if (event.key !== 'Escape' || panel.hidden) return;
|
||||
event.preventDefault();
|
||||
setOpen(false, { focus: true });
|
||||
};
|
||||
expand.addEventListener('click', onExpand);
|
||||
close.addEventListener('click', onClose);
|
||||
panel.addEventListener('keydown', onKey);
|
||||
label();
|
||||
render(credits.list());
|
||||
const offChange = credits.on('change', render);
|
||||
const offLocale = onLocaleChange(label);
|
||||
return () => {
|
||||
offChange();
|
||||
offLocale();
|
||||
expand.removeEventListener('click', onExpand);
|
||||
close.removeEventListener('click', onClose);
|
||||
panel.removeEventListener('keydown', onKey);
|
||||
bar.remove();
|
||||
panel.remove();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mountCreditsView } from './creditsView.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { createStubRenderer } from '../render/stub/index.js';
|
||||
|
||||
function scene() {
|
||||
document.body.replaceChildren();
|
||||
const renderer = createStubRenderer();
|
||||
const viewer = {};
|
||||
bindRenderer(viewer, renderer);
|
||||
return { viewer, renderer };
|
||||
}
|
||||
|
||||
test("the renderer's credits show on the line, and the rest in the list it opens", () => {
|
||||
const { viewer, renderer } = scene();
|
||||
renderer.credits.addStatic({
|
||||
text: 'Google',
|
||||
href: 'https://maps.google.com',
|
||||
inline: true,
|
||||
});
|
||||
const off = mountCreditsView(viewer);
|
||||
const line = document.querySelector('#gev-credits .gev-credits-line');
|
||||
assert.equal(line.textContent, 'Google');
|
||||
assert.equal(line.querySelector('a').href, 'https://maps.google.com/');
|
||||
const expand = document.querySelector('.gev-credits-expand');
|
||||
assert.equal(expand.hidden, true, 'nothing to list yet');
|
||||
|
||||
const remove = renderer.credits.addStatic({ text: 'Wildlife: iNaturalist' });
|
||||
renderer.credits.addStatic({ text: 'Wildlife: iNaturalist' });
|
||||
renderer.credits.addStatic({ text: 'OSM', href: 'javascript:alert(1)' });
|
||||
assert.equal(expand.hidden, false);
|
||||
assert.equal(expand.textContent, 'Data attribution');
|
||||
const panel = document.getElementById('gev-credits-panel');
|
||||
assert.equal(panel.hidden, true);
|
||||
expand.click();
|
||||
assert.equal(panel.hidden, false);
|
||||
assert.equal(expand.getAttribute('aria-expanded'), 'true');
|
||||
const items = [...panel.querySelectorAll('li')].map((li) => li.textContent);
|
||||
assert.deepEqual(items, ['Wildlife: iNaturalist', 'OSM'], 'once each');
|
||||
assert.equal(panel.querySelector('li:last-child a'), null, 'unsafe link');
|
||||
|
||||
panel.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
|
||||
);
|
||||
assert.equal(panel.hidden, true);
|
||||
assert.equal(document.activeElement, expand, 'focus goes back');
|
||||
|
||||
remove();
|
||||
assert.equal(
|
||||
[...panel.querySelectorAll('li')].length,
|
||||
2,
|
||||
'a duplicate still credits it',
|
||||
);
|
||||
off();
|
||||
assert.equal(document.getElementById('gev-credits'), null);
|
||||
assert.equal(document.getElementById('gev-credits-panel'), null);
|
||||
});
|
||||
|
||||
test('a credit with a logo is drawn as the logo, named by its text', () => {
|
||||
const { viewer, renderer } = scene();
|
||||
renderer.credits.addStatic({
|
||||
text: 'Google',
|
||||
logoUrl: 'https://example.com/logo.png',
|
||||
inline: true,
|
||||
});
|
||||
const off = mountCreditsView(viewer);
|
||||
const credit = document.querySelector('#gev-credits .gev-credit');
|
||||
const logo = credit.querySelector('img');
|
||||
assert.equal(logo.src, 'https://example.com/logo.png');
|
||||
assert.equal(logo.alt, 'Google', 'screen readers and copies keep the name');
|
||||
assert.equal(credit.textContent, '', 'the logo stands in place of the text');
|
||||
off();
|
||||
});
|
||||
|
||||
test('a viewer with no renderer shows no credits line', () => {
|
||||
document.body.replaceChildren();
|
||||
const off = mountCreditsView({});
|
||||
assert.equal(document.getElementById('gev-credits'), null);
|
||||
off();
|
||||
});
|
||||
|
||||
test('the credits line is placed wherever the renderer’s own display is', async () => {
|
||||
const { readFileSync, readdirSync } = await import('node:fs');
|
||||
const dir = new URL('./styles/', import.meta.url);
|
||||
const missing = [];
|
||||
for (const name of readdirSync(dir).filter((f) => f.endsWith('.css'))) {
|
||||
const css = readFileSync(new URL(name, dir), 'utf8').replace(
|
||||
/\/\*[\s\S]*?\*\//g,
|
||||
'',
|
||||
);
|
||||
const parts = [...css.matchAll(/([^{};]+)\{/g)]
|
||||
.map((match) => match[1].replace(/\s+/g, ' ').trim())
|
||||
.filter((selector) => !selector.startsWith('@'))
|
||||
.flatMap((selector) =>
|
||||
selector.split(/,(?![^(]*\))/).map((part) => part.trim()),
|
||||
);
|
||||
// The display's own selectors, without its inner parts, each with the
|
||||
// line's counterpart in the same stylesheet.
|
||||
for (const part of parts)
|
||||
if (
|
||||
/#cesium-credits$/.test(part) &&
|
||||
!parts.includes(part.replace('#cesium-credits', '#gev-credits'))
|
||||
)
|
||||
missing.push(`${name}: ${part}`);
|
||||
}
|
||||
assert.deepEqual(missing, []);
|
||||
});
|
||||
|
||||
test('focus in the list stays in it as it redraws, and goes to the line as it empties', () => {
|
||||
const { viewer, renderer } = scene();
|
||||
renderer.credits.addStatic({ text: 'Esri', inline: true });
|
||||
const remove = renderer.credits.addStatic({
|
||||
text: 'OSM',
|
||||
href: 'https://www.openstreetmap.org/copyright',
|
||||
});
|
||||
const off = mountCreditsView(viewer);
|
||||
const panel = document.getElementById('gev-credits-panel');
|
||||
document.querySelector('.gev-credits-expand').click();
|
||||
panel.querySelector('li a').focus();
|
||||
const removeOther = renderer.credits.addStatic({ text: 'NOAA' });
|
||||
assert.equal(panel.hidden, false);
|
||||
assert.ok(panel.contains(document.activeElement), 'still in the list');
|
||||
remove();
|
||||
removeOther();
|
||||
assert.equal(panel.hidden, true);
|
||||
assert.equal(
|
||||
document.activeElement,
|
||||
document.getElementById('gev-credits'),
|
||||
'a line with no link takes it',
|
||||
);
|
||||
off();
|
||||
});
|
||||
|
||||
test('a credit with linked words links only those words', () => {
|
||||
const { viewer, renderer } = scene();
|
||||
renderer.credits.addStatic({
|
||||
text: 'Street Level: imagery © Mapillary contributors, CC BY-SA 4.0',
|
||||
href: 'https://www.mapillary.com/',
|
||||
linkText: 'Mapillary',
|
||||
inline: true,
|
||||
});
|
||||
const off = mountCreditsView(viewer);
|
||||
const credit = document.querySelector('#gev-credits .gev-credit');
|
||||
const link = credit.querySelector('a');
|
||||
assert.equal(link.textContent, 'Mapillary');
|
||||
assert.equal(link.href, 'https://www.mapillary.com/');
|
||||
assert.equal(
|
||||
credit.textContent,
|
||||
'Street Level: imagery © Mapillary contributors, CC BY-SA 4.0',
|
||||
);
|
||||
off();
|
||||
});
|
||||
@@ -57,6 +57,9 @@ test('real runner and facade use visual settings, preserve visibility and return
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
scene: { canvas: new EventTarget() },
|
||||
get canvas() {
|
||||
return this.scene.canvas;
|
||||
},
|
||||
};
|
||||
try {
|
||||
const runner = createGevActionRunner({ styleManager: owner, viewer, dataManager: {} });
|
||||
|
||||
+49
-12
@@ -1,4 +1,11 @@
|
||||
import { getScopeMaskFeather, isScopeMaskEnabled, setScopeMaskEnabled, setScopeMaskFeather } from '../scopeMask.js';
|
||||
import {
|
||||
getScopeMaskFeather,
|
||||
getScopeMaskOpacity,
|
||||
isScopeMaskEnabled,
|
||||
setScopeMaskEnabled,
|
||||
setScopeMaskFeather,
|
||||
setScopeMaskOpacity,
|
||||
} from '../scopeMask.js';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
@@ -254,6 +261,7 @@ test('Display and voice HUD routes preserve explicit Cyber entry and exit author
|
||||
const viewer = {
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
canvas: eventSource,
|
||||
scene: { canvas: eventSource },
|
||||
};
|
||||
const runVoiceAction = createGevActionRunner({
|
||||
@@ -282,7 +290,7 @@ test('scope choice and expanded feather survive every HUD layout and both restor
|
||||
let shown = null;
|
||||
owner.store = { publish: (view) => (shown = view.scope) };
|
||||
await owner.restoreShareState({ scopeEnabled: false, scopeFeatherPct: 200 });
|
||||
assert.deepEqual(shown, { enabled: false, featherPct: 200 });
|
||||
assert.deepEqual(shown, { enabled: false, featherPct: 200, opacityPct: 100 });
|
||||
for (const layout of ['minimal', 'cyber', 'tactical']) {
|
||||
owner._setHudVariant(layout, { applyVisualDefaults: true });
|
||||
assert.equal(isScopeMaskEnabled(), false, layout);
|
||||
@@ -292,10 +300,44 @@ test('scope choice and expanded feather survive every HUD layout and both restor
|
||||
await owner.applyVisualState({ scope: { enabled: true, featherPct: 175 } });
|
||||
assert.equal(isScopeMaskEnabled(), true);
|
||||
assert.equal(getScopeMaskFeather(), 1.75);
|
||||
assert.deepEqual(shown, { enabled: true, featherPct: 175 });
|
||||
assert.deepEqual(shown, { enabled: true, featherPct: 175, opacityPct: 100 });
|
||||
await owner.applyVisualState({ scope: { featherPct: 500 } });
|
||||
assert.equal(getScopeMaskFeather(), 2);
|
||||
assert.deepEqual(shown, { enabled: true, featherPct: 200 });
|
||||
assert.deepEqual(shown, { enabled: true, featherPct: 200, opacityPct: 100 });
|
||||
});
|
||||
|
||||
test('a shared scope opacity is restored and rides in the next share state', async (t) => {
|
||||
const { owner } = styleOwner(t, 'tactical');
|
||||
const previous = getScopeMaskOpacity();
|
||||
t.after(() => setScopeMaskOpacity(previous));
|
||||
Object.assign(owner.services, {
|
||||
setScopeMaskEnabled() {},
|
||||
setScopeMaskFeather() {},
|
||||
setScopeMaskOpacity,
|
||||
});
|
||||
let shown = null;
|
||||
owner.store = { publish: (view) => (shown = view.scope) };
|
||||
await owner.restoreShareState({ scopeOpacityPct: 60 });
|
||||
assert.equal(getScopeMaskOpacity(), 0.6);
|
||||
assert.equal(shown.opacityPct, 60);
|
||||
// A state without it leaves the opacity alone.
|
||||
await owner.restoreShareState({ scopeFeatherPct: 80 });
|
||||
assert.equal(getScopeMaskOpacity(), 0.6);
|
||||
assert.equal(shown.opacityPct, 60);
|
||||
Object.assign(owner.services, {
|
||||
getDetectionTuning: () => ({ allocationStrategy: 'ELASTIC' }),
|
||||
getDetectionMode: () => 'OFF',
|
||||
isScopeMaskEnabled: () => true,
|
||||
getScopeMaskFeather: () => 0.8,
|
||||
getScopeMaskOpacity,
|
||||
getScopeTerminusOverride: () => null,
|
||||
});
|
||||
owner.readCelestialRing = () => null;
|
||||
assert.equal(owner._readShareState().options.scopeOpacityPct, 60);
|
||||
// A link asking for less than the floor opens at the floor, and says so.
|
||||
await owner.restoreShareState({ scopeOpacityPct: 20 });
|
||||
assert.equal(getScopeMaskOpacity(), 0.5);
|
||||
assert.equal(owner._readShareState().options.scopeOpacityPct, 50);
|
||||
});
|
||||
|
||||
test('a scene shot saved with the retired Snow style plays on Normal', async (t) => {
|
||||
@@ -650,8 +692,7 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', ()
|
||||
const hud = read('../hud.js');
|
||||
const hudView = read('./views/IntelHudView.vue');
|
||||
const detection = read('../data/detection.js');
|
||||
const civilRendering = read('../layers/flights/rendering.js');
|
||||
const militaryRendering = read('../layers/military/rendering.js');
|
||||
const aircraftModels = read('../data/aircraftModelLayer.js');
|
||||
const setHud = GEV_ACTION_SCHEMAS.find((schema) => schema.name === 'set_hud');
|
||||
|
||||
assert.match(display, /<option value="cyber">\{\{ t\('Cyber'\) \}\}<\/option>/);
|
||||
@@ -701,12 +742,8 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', ()
|
||||
);
|
||||
assert.doesNotMatch(detection, /sonarActive \? 1 : 0/);
|
||||
assert.match(
|
||||
civilRendering,
|
||||
/alpha: flightState\._irBoost \? 1 : treatment\.alpha/,
|
||||
);
|
||||
assert.match(
|
||||
militaryRendering,
|
||||
/baseAlpha:[\s\S]*?alpha: flightState\._irBoost \? 1 : treatment\.alpha/,
|
||||
aircraftModels,
|
||||
/alpha: state\._irBoost\s*\?\s*1\s*:\s*aircraftTreatmentAlpha\(/,
|
||||
);
|
||||
assert.match(
|
||||
cyberStyles,
|
||||
|
||||
@@ -105,6 +105,11 @@ export class DisplayBindings {
|
||||
this._setScope({ featherPct: value });
|
||||
this._syncShareState();
|
||||
},
|
||||
setScopeOpacity: (value) => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
this._setScope({ opacityPct: Number(value) });
|
||||
this._syncShareState();
|
||||
},
|
||||
setSharpenIntensity: (pct) => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
this._setSharpenIntensity(pct);
|
||||
@@ -168,6 +173,28 @@ export class DisplayBindings {
|
||||
this._syncModels3dModeRow();
|
||||
},
|
||||
setModelsMode: (mode) => this._setModels3dMode(mode),
|
||||
// Back to the out-of-the-box look: Normal style, the global post
|
||||
// defaults (bloom, sharpen, HUD, labels, celestial), scope on at full
|
||||
// feather and opacity, 3D aircraft on in Proximity.
|
||||
resetVisual: () => {
|
||||
this.shareLinkManager?.claimRestoreLane?.('visual');
|
||||
this.setStyle('normal', { userInitiated: true });
|
||||
// The HUD layout follows the Normal style, as choosing it does: the
|
||||
// Cyber HUD stays Cyber.
|
||||
this._applyGlobalPostDefaults({ keepHudVariant: true });
|
||||
this._setDetectionAllocation('ELASTIC');
|
||||
this._setScope({ enabled: true, featherPct: 100, opacityPct: 100 });
|
||||
this._setModels3dEnabled(true);
|
||||
this._setModels3dMode('proximity');
|
||||
this._syncModels3dModeRow?.();
|
||||
// Inside Contacts the detection shown is lent for the session, and
|
||||
// leaving puts back the state from before. A reset there is the user's
|
||||
// choice, so the defaults become what leaving puts back and what a
|
||||
// share link carries.
|
||||
this.claimDetection();
|
||||
this._adoptDetectionAsRestore?.();
|
||||
this._syncShareState();
|
||||
},
|
||||
});
|
||||
this._detachDisplayControls = () => store.detach(token);
|
||||
}
|
||||
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
/** A row of a group added to the Display panel. */
|
||||
export type DisplayGroupRow =
|
||||
| {
|
||||
kind: 'toggle';
|
||||
id: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
title?: string;
|
||||
checked: boolean;
|
||||
onChange(checked: boolean): void;
|
||||
}
|
||||
| {
|
||||
kind: 'slider';
|
||||
id: string;
|
||||
label: string;
|
||||
min: number;
|
||||
max: number;
|
||||
/** Shown in percent. */
|
||||
value: number;
|
||||
onChange(value: number): void;
|
||||
}
|
||||
| { kind: 'note'; id: string; text: string };
|
||||
|
||||
/**
|
||||
* Show the group `id` on the page's Display panel, under Effects, in place
|
||||
* where it is shown already; null takes it away.
|
||||
*/
|
||||
export function publishDisplayGroup(
|
||||
id: string,
|
||||
group: { rows: DisplayGroupRow[] } | null,
|
||||
): void;
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Groups of controls added to the Display panel, under
|
||||
* Effects: toggles, sliders and notes, each answered by whoever added it.
|
||||
*/
|
||||
import { applicationPinia } from './vueRuntime.js';
|
||||
import { useDisplayStore } from './stores/display.js';
|
||||
|
||||
/**
|
||||
* Show the group `id` on the page's Display panel as `group` describes it,
|
||||
* in place where it is shown already; null takes it away. A row is a
|
||||
* `toggle` (`{kind, id, label, icon?, title?, checked, onChange(checked)}`),
|
||||
* a `slider` (`{kind, id, label, min, max, value, onChange(value)}`, its
|
||||
* value shown in percent) or a `note` (`{kind, id, text}`). Publish it again
|
||||
* whenever what it shows changes.
|
||||
* @param {string} id
|
||||
* @param {?{rows: object[]}} group
|
||||
*/
|
||||
export function publishDisplayGroup(id, group) {
|
||||
useDisplayStore(applicationPinia()).publishGroup(id, group);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// src/ui/displayGroups.test.mjs — added groups reach the Display
|
||||
// panel's store on the page's Pinia.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { publishDisplayGroup } from './displayGroups.js';
|
||||
import { useDisplayStore } from './stores/display.js';
|
||||
import { applicationPinia } from './vueRuntime.js';
|
||||
|
||||
test('publishDisplayGroup shows a group on the page’s Display panel, and takes it away', () => {
|
||||
const store = useDisplayStore(applicationPinia());
|
||||
publishDisplayGroup('conditions', {
|
||||
rows: [{ kind: 'note', id: 'status', text: 'Nothing here' }],
|
||||
});
|
||||
assert.deepEqual(
|
||||
store.groups.map((g) => [g.id, g.rows.length]),
|
||||
[['conditions', 1]],
|
||||
);
|
||||
publishDisplayGroup('conditions', null);
|
||||
assert.deepEqual(store.groups, []);
|
||||
});
|
||||
+147
-11
@@ -108,7 +108,11 @@ test('bloom and sharpen render their state, slider and readout', async (t) => {
|
||||
await nextTick();
|
||||
assert.equal($('bloom-toggle').classList.contains('active'), false);
|
||||
assert.equal($('bloom-slider-row').classList.contains('visible'), false);
|
||||
assert.equal($('bloom-intensity-value').textContent, '140%', 'the amount stays');
|
||||
assert.equal(
|
||||
$('bloom-intensity-value').textContent,
|
||||
'140%',
|
||||
'the amount stays',
|
||||
);
|
||||
});
|
||||
|
||||
test('a publish never rewrites a slider the user is dragging', async (t) => {
|
||||
@@ -314,6 +318,73 @@ test('Scope and Celestial render what VisualSettings shows', async (t) => {
|
||||
assert.equal(celestial.title, 'Celestial ring — reveal the full globe');
|
||||
});
|
||||
|
||||
test('scope opacity renders what VisualSettings shows and sets the mask', async (t) => {
|
||||
const { store, $ } = fixture(t);
|
||||
const { owner } = settings(store);
|
||||
const mask = { opacity: 1 };
|
||||
owner.services = {
|
||||
...owner.services,
|
||||
setScopeMaskEnabled() {},
|
||||
setScopeMaskOpacity: (value) => (mask.opacity = value),
|
||||
};
|
||||
assert.equal($('scope-opacity-slider').value, '100');
|
||||
assert.equal($('scope-opacity-value').textContent, '100%');
|
||||
|
||||
owner._setScope({ opacityPct: 62.4 });
|
||||
await nextTick();
|
||||
assert.equal(mask.opacity, 0.62);
|
||||
assert.equal($('scope-opacity-slider').value, '62');
|
||||
assert.equal($('scope-opacity-value').textContent, '62%');
|
||||
assert.equal(store.view.scope.opacityPct, 62);
|
||||
|
||||
// No fainter than the floor, where the view would read as Scope off.
|
||||
owner._setScope({ opacityPct: 10 });
|
||||
await nextTick();
|
||||
assert.equal(mask.opacity, 0.5, 'floored');
|
||||
assert.equal($('scope-opacity-value').textContent, '50%');
|
||||
assert.equal($('scope-opacity-slider').min, '50');
|
||||
|
||||
// A value that is not a number changes nothing.
|
||||
owner._setScope({ opacityPct: Number.NaN });
|
||||
await nextTick();
|
||||
assert.equal($('scope-opacity-value').textContent, '50%');
|
||||
|
||||
owner._setScope({ opacityPct: 180 });
|
||||
await nextTick();
|
||||
assert.equal(mask.opacity, 1, 'clamped');
|
||||
assert.equal($('scope-opacity-value').textContent, '100%');
|
||||
|
||||
owner._setScope({ opacityPct: 70 }, { apply: false });
|
||||
await nextTick();
|
||||
assert.equal(mask.opacity, 1, 'only shown');
|
||||
assert.equal($('scope-opacity-value').textContent, '70%');
|
||||
|
||||
owner._setScope({ enabled: false });
|
||||
await nextTick();
|
||||
assert.equal($('scope-opacity-slider').disabled, true, 'off with the scope');
|
||||
assert.equal(store.view.scope.opacityPct, 70, 'kept while off');
|
||||
});
|
||||
|
||||
test('the Visual panel groups its controls and words its on/off pills', (t) => {
|
||||
const { $ } = fixture(t);
|
||||
const panel = $('pp-toggles');
|
||||
assert.deepEqual(
|
||||
[
|
||||
...panel.querySelectorAll(
|
||||
'.pp-section-heading, .visual-presets__heading',
|
||||
),
|
||||
].map((el) => el.textContent.trim()),
|
||||
['Look', 'MAP SOURCE 3D', 'Overlay', 'Effects'],
|
||||
);
|
||||
assert.equal(panel.querySelector('.pp-header-label').textContent, 'VISUAL');
|
||||
const body = panel.querySelector('.pp-panel-body');
|
||||
assert.equal(body.style.getPropertyValue('--pp-pill-on'), '"ON"');
|
||||
assert.equal(body.style.getPropertyValue('--pp-pill-off'), '"OFF"');
|
||||
const reset = panel.querySelector('.pp-reset-btn');
|
||||
assert.equal(reset, body.lastElementChild, 'the reset closes the panel');
|
||||
assert.equal(reset.textContent.trim(), 'restart_altReset to default');
|
||||
});
|
||||
|
||||
test('the 3D aircraft group renders what AircraftDisplay shows', async (t) => {
|
||||
const { store, $ } = fixture(t);
|
||||
const params = [];
|
||||
@@ -331,7 +402,10 @@ test('the 3D aircraft group renders what AircraftDisplay shows', async (t) => {
|
||||
assert.equal(coreClasses(button), 'pp-toggle-btn active');
|
||||
assert.equal(button.getAttribute('aria-pressed'), 'true');
|
||||
assert.equal(row.classList.contains('visible'), true);
|
||||
assert.equal($('models3d-mode-proximity').getAttribute('aria-checked'), 'true');
|
||||
assert.equal(
|
||||
$('models3d-mode-proximity').getAttribute('aria-checked'),
|
||||
'true',
|
||||
);
|
||||
|
||||
// The button leaves the row to its own sync.
|
||||
owner._setModels3dEnabled(false);
|
||||
@@ -347,7 +421,10 @@ test('the 3D aircraft group renders what AircraftDisplay shows', async (t) => {
|
||||
await nextTick();
|
||||
assert.equal(all.classList.contains('active'), true);
|
||||
assert.equal(all.getAttribute('aria-checked'), 'true');
|
||||
assert.equal($('models3d-mode-proximity').classList.contains('active'), false);
|
||||
assert.equal(
|
||||
$('models3d-mode-proximity').classList.contains('active'),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(params.at(-1), ['military', { models3dMode: 'all' }]);
|
||||
|
||||
owner._syncModels3dFromLayerState({
|
||||
@@ -376,12 +453,18 @@ test('the Draw controls render what the draw tool publishes', async (t) => {
|
||||
assert.equal(segment('area').getAttribute('aria-label'), 'Area');
|
||||
assert.equal(segment('area').title, 'Area');
|
||||
assert.equal(segment('area').textContent, 'pentagon');
|
||||
const swatch = (color) => document.querySelector(`#draw-colors [data-color="${color}"]`);
|
||||
const swatch = (color) =>
|
||||
document.querySelector(`#draw-colors [data-color="${color}"]`);
|
||||
assert.equal(swatch('primary').getAttribute('aria-checked'), 'true');
|
||||
assert.equal(swatch('amber').getAttribute('aria-label'), 'Amber');
|
||||
assert.equal($('draw-hint').textContent, '');
|
||||
|
||||
store.publishDraw({ active: true, shape: 'line', color: 'amber', hint: 'Click to add points.' });
|
||||
store.publishDraw({
|
||||
active: true,
|
||||
shape: 'line',
|
||||
color: 'amber',
|
||||
hint: 'Click to add points.',
|
||||
});
|
||||
await nextTick();
|
||||
assert.equal(swatch('amber').getAttribute('aria-checked'), 'true');
|
||||
assert.equal(swatch('primary').classList.contains('active'), false);
|
||||
@@ -411,12 +494,11 @@ test('the imported files render what the file import publishes and keep focus',
|
||||
const viewer = {
|
||||
container: document.createElement('div'),
|
||||
scene: { requestRender() {} },
|
||||
dataSources: { add: async (ds) => ds, remove: () => true },
|
||||
};
|
||||
const tool = initGeoFileImport({
|
||||
viewer,
|
||||
load: async (file) => ({
|
||||
dataSource: { show: true },
|
||||
drawing: { show: true, destroy() {} },
|
||||
name: file.name,
|
||||
format: file.name.endsWith('.kml') ? 'kml' : 'geojson',
|
||||
entityCount: 2,
|
||||
@@ -477,7 +559,10 @@ test('the imported files render what the file import publishes and keep focus',
|
||||
assert.equal(document.activeElement === button(first, 'toggle'), true);
|
||||
assert.equal(button(first, 'toggle').getAttribute('aria-pressed'), 'true');
|
||||
assert.equal(button(first, 'fly').title, 'Fly to <b>a</b>.geojson');
|
||||
assert.equal(button(first, 'remove').getAttribute('aria-label'), 'Remove <b>a</b>.geojson');
|
||||
assert.equal(
|
||||
button(first, 'remove').getAttribute('aria-label'),
|
||||
'Remove <b>a</b>.geojson',
|
||||
);
|
||||
|
||||
await press(button(first, 'remove'));
|
||||
assert.equal(rowsNow().length, 1);
|
||||
@@ -593,7 +678,11 @@ test('VisualSettings publishes a style’s parameters and writes a moved slider
|
||||
assert.equal(store.parameters, null, 'the sliders go with their owner');
|
||||
assert.equal($('param-slider-panel').classList.contains('active'), false);
|
||||
assert.equal(store.act('setStyleParameter', 'grainAmt', 0.2), undefined);
|
||||
assert.equal(owner.stages.noir.uniforms.grainAmt, 0.3, 'a stopped owner no longer answers');
|
||||
assert.equal(
|
||||
owner.stages.noir.uniforms.grainAmt,
|
||||
0.3,
|
||||
'a stopped owner no longer answers',
|
||||
);
|
||||
// An older owner's stop leaves a newer owner's rows.
|
||||
const newer = { style: 'noir', rows: [] };
|
||||
owner._parameters = { style: 'noir', rows: [] };
|
||||
@@ -605,10 +694,16 @@ test('VisualSettings publishes a style’s parameters and writes a moved slider
|
||||
test('the four Cockpit groups teleport to the published slots and back to their places', async (t) => {
|
||||
const { store, $ } = fixture(t);
|
||||
const groupOf = (id) => $(id).closest('.pp-toggle-group') ?? $(id);
|
||||
const ids = ['hud-toggle', 'detection-toggle', 'param-slider-panel', 'models3d-toggle'];
|
||||
const ids = [
|
||||
'hud-toggle',
|
||||
'detection-toggle',
|
||||
'param-slider-panel',
|
||||
'models3d-toggle',
|
||||
];
|
||||
const body = $('pp-toggles').querySelector('.pp-panel-body');
|
||||
const order = () =>
|
||||
[...body.children].filter((el) => el.matches('.pp-toggle-group, #param-slider-panel'))
|
||||
[...body.children]
|
||||
.filter((el) => el.matches('.pp-toggle-group, #param-slider-panel'))
|
||||
.map((el) => el.id || el.querySelector('[id]')?.id);
|
||||
const home = order();
|
||||
const popover = document.body.appendChild(document.createElement('div'));
|
||||
@@ -707,3 +802,44 @@ test('the real portal lays out once the groups have moved and puts back the focu
|
||||
await nextTick();
|
||||
assert.deepEqual(layouts, [true]);
|
||||
});
|
||||
|
||||
test('a group added to Effects shows its toggles, notes and sliders, and goes', async (t) => {
|
||||
const { store, $ } = fixture(t);
|
||||
const changes = [];
|
||||
store.publishGroup('conditions', {
|
||||
rows: [
|
||||
{
|
||||
kind: 'toggle',
|
||||
id: 'live',
|
||||
icon: 'partly_cloudy_day',
|
||||
label: 'Live',
|
||||
title: 'Live conditions',
|
||||
checked: true,
|
||||
onChange: (on) => changes.push(['live', on]),
|
||||
},
|
||||
{ kind: 'note', id: 'status', text: 'Nothing here' },
|
||||
{
|
||||
kind: 'slider',
|
||||
id: 'level',
|
||||
label: 'Level',
|
||||
min: 0,
|
||||
max: 100,
|
||||
value: 40,
|
||||
onChange: (value) => changes.push(['level', value]),
|
||||
},
|
||||
],
|
||||
});
|
||||
await nextTick();
|
||||
const toggle = $('conditions-live-toggle');
|
||||
assert.ok(toggle, 'its toggle is drawn');
|
||||
assert.equal(toggle.checked, true);
|
||||
assert.equal(toggle.closest('label').title, 'Live conditions');
|
||||
assert.equal($('conditions-status').textContent.trim(), 'Nothing here');
|
||||
assert.equal($('conditions-level-value').textContent.trim(), '40%');
|
||||
toggle.checked = false;
|
||||
toggle.dispatchEvent(new Event('change'));
|
||||
assert.deepEqual(changes, [['live', false]]);
|
||||
store.publishGroup('conditions', null);
|
||||
await nextTick();
|
||||
assert.equal($('conditions-group'), null, 'gone once removed');
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import { createApp, h, nextTick } from 'vue';
|
||||
import { createPinia } from 'pinia';
|
||||
import { useDisplayStore } from './stores/display.js';
|
||||
import { DisplayBindings } from './displayBindings.js';
|
||||
import { VisualSettings } from './visualSettings.js';
|
||||
import CommandDockView from './views/CommandDockView.vue';
|
||||
import DisplayControlsView from './views/DisplayControlsView.vue';
|
||||
import DrawControls from './views/panels/DrawControls.vue';
|
||||
@@ -231,3 +232,125 @@ test('several owners answer their own actions, the newest first', (t) => {
|
||||
['display', 'toggleBloom'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('the Visual panel’s scope opacity, reset and presets call their actions', async (t) => {
|
||||
const store = mount(t);
|
||||
const { calls } = recorder(store);
|
||||
const selected = [];
|
||||
store.connectMapSource({ select: async (id) => selected.push(id) });
|
||||
store.publishMapSource({
|
||||
status: { text: 'OSM', warn: false },
|
||||
chips: [
|
||||
{ id: 'photoreal', label: 'Google 3D', available: false },
|
||||
{ id: 'osm', label: 'OSM', available: true, active: true },
|
||||
],
|
||||
});
|
||||
await nextTick();
|
||||
input($('scope-opacity-slider'), 60);
|
||||
document.querySelector('#pp-toggles .pp-reset-btn').click();
|
||||
const presets = document.querySelector('#pp-toggles .visual-presets');
|
||||
presets.querySelector('[data-style="noir"]').click();
|
||||
const chips = presets.querySelectorAll('.visual-presets__chip');
|
||||
chips[0].click();
|
||||
chips[1].click();
|
||||
assert.deepEqual(calls, [
|
||||
['setScopeOpacity', 60],
|
||||
['resetVisual'],
|
||||
['setStyle', 'noir'],
|
||||
]);
|
||||
assert.deepEqual(selected, ['osm'], 'an unavailable source is not selected');
|
||||
// The presets follow the published style, as the dock's do.
|
||||
assert.equal(
|
||||
presets.querySelector('[data-style="normal"]').getAttribute('aria-pressed'),
|
||||
'true',
|
||||
);
|
||||
store.publishStyle({ name: 'noir', label: 'NOIR' });
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
presets.querySelector('[data-style="noir"]').getAttribute('aria-pressed'),
|
||||
'true',
|
||||
);
|
||||
assert.equal(
|
||||
presets.querySelector('[data-style="normal"]').getAttribute('aria-pressed'),
|
||||
'false',
|
||||
);
|
||||
// The dock keeps its own presets and map source beside them.
|
||||
assert.ok(
|
||||
document.querySelector('#control-panel .style-btn[data-style="noir"]'),
|
||||
);
|
||||
assert.ok($('map-stack-chips'));
|
||||
});
|
||||
|
||||
test('DisplayBindings sets the scope opacity and resets Visual to its defaults', (t) => {
|
||||
const store = mount(t);
|
||||
const calls = [];
|
||||
const bindings = new DisplayBindings({
|
||||
viewer: null,
|
||||
services: { isScopeMaskEnabled: () => true, cycleDetectionMode: () => {} },
|
||||
elements: { _locationSearch: document.createElement('input') },
|
||||
operations: {
|
||||
setStyle: (style, options) => calls.push(['style', style, options]),
|
||||
_applyGlobalPostDefaults: (options) =>
|
||||
calls.push(['postDefaults', options]),
|
||||
_setDetectionAllocation: (value) => calls.push(['allocation', value]),
|
||||
_setScope: (scope) => calls.push(['scope', scope]),
|
||||
_setModels3dEnabled: (on) => calls.push(['models3d', on]),
|
||||
_setModels3dMode: (mode) => calls.push(['models3dMode', mode]),
|
||||
_syncModels3dModeRow: () => calls.push(['models3dRow']),
|
||||
_syncShareState: () => calls.push(['share']),
|
||||
_adoptDetectionAsRestore: () => calls.push(['adoptDetection']),
|
||||
},
|
||||
readState: () => ({
|
||||
shareLinkManager: {
|
||||
claimRestoreLane: (lane) => calls.push(['claim', lane]),
|
||||
},
|
||||
}),
|
||||
claimDetection: () => calls.push(['claimDetection']),
|
||||
displayStore: store,
|
||||
});
|
||||
bindings._initUI();
|
||||
t.after(() => bindings.destroy());
|
||||
calls.length = 0;
|
||||
input($('scope-opacity-slider'), 65);
|
||||
assert.deepEqual(calls, [
|
||||
['claim', 'visual'],
|
||||
['scope', { opacityPct: 65 }],
|
||||
['share'],
|
||||
]);
|
||||
calls.length = 0;
|
||||
document.querySelector('#pp-toggles .pp-reset-btn').click();
|
||||
assert.deepEqual(calls, [
|
||||
['claim', 'visual'],
|
||||
['style', 'normal', { userInitiated: true }],
|
||||
['postDefaults', { keepHudVariant: true }],
|
||||
['allocation', 'ELASTIC'],
|
||||
['scope', { enabled: true, featherPct: 100, opacityPct: 100 }],
|
||||
['models3d', true],
|
||||
['models3dMode', 'proximity'],
|
||||
['models3dRow'],
|
||||
['claimDetection'],
|
||||
['adoptDetection'],
|
||||
['share'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('a reset inside Contacts makes the shown detection what leaving puts back', () => {
|
||||
const adopt = VisualSettings.prototype.adoptDetectionAsRestore;
|
||||
const live = { detectionMode: 'DENSE', densityPct: 75 };
|
||||
const inContacts = {
|
||||
_contactsDetectionRestore: { mode: 'OFF', densityPct: 50 },
|
||||
getDetectionState: () => live,
|
||||
};
|
||||
adopt.call(inContacts);
|
||||
assert.deepEqual(inContacts._contactsDetectionRestore, {
|
||||
mode: 'DENSE',
|
||||
densityPct: 75,
|
||||
});
|
||||
// Outside Contacts there is no saved state to change.
|
||||
const outside = {
|
||||
_contactsDetectionRestore: null,
|
||||
getDetectionState: () => live,
|
||||
};
|
||||
adopt.call(outside);
|
||||
assert.equal(outside._contactsDetectionRestore, null);
|
||||
});
|
||||
+38
-97
@@ -1,93 +1,39 @@
|
||||
/** Frame the complete finite footprint of a session-local file. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { guardCameraAboveGround } from '../cameraGroundGuard.js';
|
||||
import { rangeForBoundingSphere } from '../data/cameraFraming.js';
|
||||
import { cancelCameraArrival } from '../data/cameraArrival.js';
|
||||
import { distance, fromDegrees, toLonLatH } from '../geo/index.js';
|
||||
import { sphereFromPoints } from '../geo/sphere.js';
|
||||
import { heightsOf } from '../queries/heights.js';
|
||||
import { findCamera } from '../render/rendererOf.js';
|
||||
|
||||
/** All visible positions, path vertices, polygon rings, walls and overlay bounds. */
|
||||
export function dataSourcePoints(dataSource, time = Cesium.JulianDate.now()) {
|
||||
const points = [];
|
||||
const add = (position, grounded = false) => {
|
||||
if (
|
||||
!position ||
|
||||
![position.x, position.y, position.z].every(Number.isFinite)
|
||||
)
|
||||
return;
|
||||
const c = Cesium.Cartographic.fromCartesian(position);
|
||||
if (c && Number.isFinite(c.longitude) && Number.isFinite(c.latitude))
|
||||
points.push([
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
Cesium.Math.toDegrees(c.latitude),
|
||||
grounded ? 0 : c.height,
|
||||
]);
|
||||
};
|
||||
if (dataSource?.show === false) return points;
|
||||
for (const entity of dataSource?.importedEntities ??
|
||||
dataSource?.entities?.values ??
|
||||
[]) {
|
||||
if (entity.isShowing === false) continue;
|
||||
add(
|
||||
entity.position?.getValue?.(time),
|
||||
entity.billboard?.heightReference?.getValue?.(time) ===
|
||||
Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
);
|
||||
for (const graphic of [entity.polyline, entity.wall])
|
||||
for (const position of graphic?.positions?.getValue?.(time) || [])
|
||||
add(position, graphic.clampToGround?.getValue?.(time) === true);
|
||||
const rings = [entity.polygon?.hierarchy?.getValue?.(time)];
|
||||
while (rings.length) {
|
||||
const ring = rings.pop();
|
||||
for (const position of ring?.positions || [])
|
||||
add(
|
||||
position,
|
||||
entity.polygon?.perPositionHeight?.getValue?.(time) !== true,
|
||||
);
|
||||
for (const hole of ring?.holes || []) rings.push(hole);
|
||||
}
|
||||
const rectangle = entity.rectangle?.coordinates?.getValue?.(time);
|
||||
if (rectangle) {
|
||||
const bounds = Cesium.RectangleGeometry.computeRectangle({
|
||||
rectangle,
|
||||
rotation: entity.rectangle.rotation?.getValue?.(time) || 0,
|
||||
});
|
||||
for (const corner of [
|
||||
'southwest',
|
||||
'southeast',
|
||||
'northwest',
|
||||
'northeast',
|
||||
]) {
|
||||
const c = Cesium.Rectangle[corner](bounds);
|
||||
if (Number.isFinite(c.longitude) && Number.isFinite(c.latitude))
|
||||
points.push([
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
Cesium.Math.toDegrees(c.latitude),
|
||||
entity.rectangle.height?.getValue?.(time) || 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/** Fly synchronously to the footprint; later navigation always owns its camera. */
|
||||
export function flyToDataSource(
|
||||
/**
|
||||
* Fly synchronously to a footprint, `[lon, lat, height]` points (degrees,
|
||||
* metres) such as a file's (`importedDrawingPoints`); later navigation always
|
||||
* owns its camera. False when there is nothing to frame or no camera.
|
||||
*/
|
||||
export function flyToFootprint(
|
||||
viewer,
|
||||
dataSource,
|
||||
points,
|
||||
{ duration = 1.5, ground = null } = {},
|
||||
) {
|
||||
const points = dataSourcePoints(dataSource);
|
||||
if (!points.length) return false;
|
||||
if (!points?.length) return false;
|
||||
const camera = findCamera(viewer);
|
||||
if (!camera) return false;
|
||||
cancelCameraArrival(viewer);
|
||||
const positions = points.map(([lon, lat, height]) =>
|
||||
Cesium.Cartesian3.fromDegrees(lon, lat, height),
|
||||
fromDegrees(lon, lat, height),
|
||||
);
|
||||
const sphere = Cesium.BoundingSphere.fromPoints(positions);
|
||||
const center =
|
||||
Cesium.Cartographic.fromCartesian(sphere.center) ||
|
||||
Cesium.Cartographic.fromDegrees(points[0][0], points[0][1]);
|
||||
const lat = Cesium.Math.toDegrees(center.latitude),
|
||||
lon = Cesium.Math.toDegrees(center.longitude);
|
||||
const terrain = viewer.scene?.globe?.getHeight?.(center);
|
||||
const sphere = sphereFromPoints(positions);
|
||||
const center = toLonLatH(sphere.center) || {
|
||||
lon: points[0][0],
|
||||
lat: points[0][1],
|
||||
height: 0,
|
||||
};
|
||||
const { lat, lon } = center;
|
||||
const terrain = viewer
|
||||
? heightsOf(viewer).now({ lon, lat }, { against: 'terrain' })
|
||||
: null;
|
||||
const cached = ground?.cachedGroundFloor?.(lat, lon);
|
||||
const height =
|
||||
Number.isFinite(terrain) && terrain > 0
|
||||
@@ -98,25 +44,20 @@ export function flyToDataSource(
|
||||
? terrain
|
||||
: 0;
|
||||
ground?.warmGroundFloor?.([{ lat, lon }]);
|
||||
sphere.center = Cesium.Cartesian3.fromRadians(
|
||||
center.longitude,
|
||||
center.latitude,
|
||||
Math.max(0, height, center.height),
|
||||
);
|
||||
sphere.radius = 0;
|
||||
const framed = {
|
||||
center: fromDegrees(lon, lat, Math.max(0, height, center.height)),
|
||||
radius: 0,
|
||||
};
|
||||
for (const position of positions)
|
||||
sphere.radius = Math.max(
|
||||
sphere.radius,
|
||||
Cesium.Cartesian3.distance(sphere.center, position),
|
||||
);
|
||||
viewer.camera?.flyToBoundingSphere?.(sphere, {
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
viewer.camera.heading || 0,
|
||||
-Math.PI / 2,
|
||||
Math.max(800, rangeForBoundingSphere(viewer, sphere.radius)),
|
||||
),
|
||||
duration,
|
||||
complete: () => guardCameraAboveGround(viewer, { lat, lon }),
|
||||
framed.radius = Math.max(framed.radius, distance(framed.center, position));
|
||||
camera.flyToBounds(framed, {
|
||||
offset: {
|
||||
heading: camera.pose().heading || 0,
|
||||
pitch: -Math.PI / 2,
|
||||
range: Math.max(800, rangeForBoundingSphere(viewer, framed.radius)),
|
||||
},
|
||||
durationS: duration,
|
||||
onComplete: () => guardCameraAboveGround(viewer, { lat, lon }),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
+110
-88
@@ -1,34 +1,70 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { cancelCameraArrival } from '../data/cameraArrival.js';
|
||||
import { dataSourcePoints, flyToDataSource } from './flyToDataSource.js';
|
||||
import {
|
||||
cancelCameraArrival,
|
||||
ownCameraArrival,
|
||||
} from '../data/cameraArrival.js';
|
||||
import {
|
||||
createImportedDrawing,
|
||||
importedDrawingPoints,
|
||||
} from '../data/geoImportPins.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeSceneQuery } from '../testSupport/fakeCesiumScene.mjs';
|
||||
import { flyToFootprint } from './flyToDataSource.js';
|
||||
|
||||
/** As the file import flies to one of its files. */
|
||||
const flyToDataSource = (viewer, drawing) =>
|
||||
flyToFootprint(viewer, importedDrawingPoints(drawing));
|
||||
|
||||
/** An imported file's drawing of `features`, not drawn. */
|
||||
const drawingOf = (features) => createImportedDrawing({}, features);
|
||||
const pin = (lon, lat, height = 0, mode = 'absolute') => ({
|
||||
kind: 'pin',
|
||||
lon,
|
||||
lat,
|
||||
height,
|
||||
mode,
|
||||
image: 'pin.png',
|
||||
size: [32, 32],
|
||||
});
|
||||
const line = (coords, mode = 'draped') => ({
|
||||
kind: 'line',
|
||||
coords,
|
||||
mode,
|
||||
color: [1, 1, 1, 1],
|
||||
width: 1,
|
||||
});
|
||||
|
||||
/** A Cesium-shaped viewer double, bound to the camera and query ports. */
|
||||
const bound = (viewer) =>
|
||||
bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) });
|
||||
|
||||
function source() {
|
||||
const ds = new Cesium.CustomDataSource('t');
|
||||
ds.entities.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(-122.4862, 37.7694, -2667),
|
||||
billboard: { heightReference: Cesium.HeightReference.CLAMP_TO_GROUND },
|
||||
});
|
||||
ds.entities.add({
|
||||
polyline: {
|
||||
positions: Cesium.Cartesian3.fromDegreesArray([
|
||||
-122.49, 37.77, -122.48, 37.771,
|
||||
]),
|
||||
return drawingOf([
|
||||
pin(-122.4862, 37.7694, 0, 'clamp'),
|
||||
line([
|
||||
[-122.49, 37.77, 0],
|
||||
[-122.48, 37.771, 0],
|
||||
]),
|
||||
{
|
||||
kind: 'polygon',
|
||||
rings: [
|
||||
[
|
||||
[-122.5, 37.76, 0],
|
||||
[-122.49, 37.76, 0],
|
||||
[-122.49, 37.765, 0],
|
||||
],
|
||||
],
|
||||
clamp: true,
|
||||
fill: [1, 1, 1, 0.25],
|
||||
outline: null,
|
||||
},
|
||||
});
|
||||
ds.entities.add({
|
||||
polygon: {
|
||||
hierarchy: Cesium.Cartesian3.fromDegreesArray([
|
||||
-122.5, 37.76, -122.49, 37.76, -122.49, 37.765,
|
||||
]),
|
||||
},
|
||||
});
|
||||
return ds;
|
||||
]);
|
||||
}
|
||||
|
||||
test('points come from positions, lines and polygons, as lon/lat only', () => {
|
||||
const points = dataSourcePoints(source());
|
||||
const points = importedDrawingPoints(source());
|
||||
assert.equal(points.length, 6);
|
||||
assert.ok(Math.abs(points[0][0] + 122.4862) < 1e-6);
|
||||
assert.ok(Math.abs(points[0][1] - 37.7694) < 1e-6);
|
||||
@@ -36,26 +72,28 @@ test('points come from positions, lines and polygons, as lon/lat only', () => {
|
||||
|
||||
test('the camera frames the footprint at the surface, never a buried center', () => {
|
||||
const calls = [];
|
||||
const viewer = {
|
||||
const viewer = bound({
|
||||
scene: {},
|
||||
camera: {
|
||||
heading: 0,
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(-122.49, 37.77, 900),
|
||||
directionWC: new Cesium.Cartesian3(0, 0, -1),
|
||||
upWC: new Cesium.Cartesian3(0, 1, 0),
|
||||
flyToBoundingSphere: (sphere, options) => calls.push({ sphere, options }),
|
||||
},
|
||||
flyTo: () => calls.push('viewer.flyTo'),
|
||||
};
|
||||
});
|
||||
assert.equal(flyToDataSource(viewer, source()), true);
|
||||
const center = Cesium.Cartographic.fromCartesian(calls[0].sphere.center);
|
||||
assert.ok(Math.abs(center.height) < 50, `center height ${center.height}`);
|
||||
assert.ok(calls[0].options.offset.range >= 800);
|
||||
assert.equal(
|
||||
typeof calls[0].options.complete,
|
||||
'function',
|
||||
'the ground guard runs on landing',
|
||||
);
|
||||
assert.equal(
|
||||
flyToDataSource(viewer, new Cesium.CustomDataSource('empty')),
|
||||
false,
|
||||
);
|
||||
// Landing starts the ground guard, which takes over the arrival.
|
||||
let handedOver = false;
|
||||
ownCameraArrival(viewer, () => (handedOver = true));
|
||||
calls[0].options.complete();
|
||||
assert.equal(handedOver, true, 'the ground guard runs on landing');
|
||||
cancelCameraArrival(viewer);
|
||||
assert.equal(flyToDataSource(viewer, drawingOf([])), false);
|
||||
assert.equal(
|
||||
calls.length,
|
||||
1,
|
||||
@@ -67,13 +105,11 @@ test('a very long track is framed without spreading it into a call', () => {
|
||||
// 400k vertices: `push(...line)` throws RangeError (too many arguments)
|
||||
// well below this; the walk keeps a bounded sample and both ends.
|
||||
const n = 400_000;
|
||||
const line = new Array(n);
|
||||
for (let i = 0; i < n; i++)
|
||||
line[i] = Cesium.Cartesian3.fromDegrees(-120 + (i / n) * 2, 40);
|
||||
const ds = new Cesium.CustomDataSource('long');
|
||||
ds.entities.add({ polyline: { positions: line } });
|
||||
ds.entities.add({ position: Cesium.Cartesian3.fromDegrees(-110, 41) });
|
||||
const points = dataSourcePoints(ds);
|
||||
const coords = new Array(n);
|
||||
for (let i = 0; i < n; i++) coords[i] = [-120 + (i / n) * 2, 40, 0];
|
||||
const points = importedDrawingPoints(
|
||||
drawingOf([line(coords), pin(-110, 41)]),
|
||||
);
|
||||
assert.equal(points.length, n + 1, 'every vertex contributes to framing');
|
||||
const lons = points.map(([lon]) => lon);
|
||||
assert.ok(
|
||||
@@ -84,42 +120,45 @@ test('a very long track is framed without spreading it into a call', () => {
|
||||
});
|
||||
|
||||
test('framing includes a sparse interior outlier, walls and rotated overlays', () => {
|
||||
const ds = new Cesium.CustomDataSource('bounds');
|
||||
const line = Array.from({ length: 200031 }, () =>
|
||||
Cesium.Cartesian3.fromDegrees(0, 0),
|
||||
const coords = Array.from({ length: 200031 }, () => [0, 0, 0]);
|
||||
coords[12345] = [20, 10, 0];
|
||||
const points = importedDrawingPoints(
|
||||
drawingOf([
|
||||
line(coords),
|
||||
{
|
||||
kind: 'wall',
|
||||
coords: [
|
||||
[30, 10, 0],
|
||||
[31, 11, 0],
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'overlay',
|
||||
rect: { west: 40, south: 0, east: 41, north: 1 },
|
||||
rotation: Math.PI / 4,
|
||||
},
|
||||
]),
|
||||
);
|
||||
line[12345] = Cesium.Cartesian3.fromDegrees(20, 10);
|
||||
ds.entities.add({ polyline: { positions: line } });
|
||||
ds.entities.add({
|
||||
wall: { positions: Cesium.Cartesian3.fromDegreesArray([30, 10, 31, 11]) },
|
||||
});
|
||||
ds.entities.add({
|
||||
rectangle: {
|
||||
coordinates: Cesium.Rectangle.fromDegrees(40, 0, 41, 1),
|
||||
rotation: Math.PI / 4,
|
||||
},
|
||||
});
|
||||
const points = dataSourcePoints(ds);
|
||||
assert.ok(points.some(([lon]) => Math.abs(lon - 20) < 1e-6));
|
||||
assert.ok(points.some(([lon]) => Math.abs(lon - 31) < 1e-6));
|
||||
assert.ok(points.some(([lon]) => lon > 41));
|
||||
});
|
||||
|
||||
test('portrait framing accounts for FOV, high ground and symmetric extents', () => {
|
||||
const ds = new Cesium.CustomDataSource('view');
|
||||
ds.entities.add({
|
||||
polyline: {
|
||||
positions: Cesium.Cartesian3.fromDegreesArray([-105, 39, -104.9, 39]),
|
||||
},
|
||||
});
|
||||
const ds = drawingOf([
|
||||
line([
|
||||
[-105, 39, 0],
|
||||
[-104.9, 39, 0],
|
||||
]),
|
||||
]);
|
||||
const calls = [];
|
||||
const viewer = {
|
||||
const viewer = bound({
|
||||
scene: { globe: { getHeight: () => 2600 } },
|
||||
camera: {
|
||||
frustum: { fov: Math.PI / 3, aspectRatio: 390 / 844 },
|
||||
frustum: { fovy: Math.PI / 3, aspectRatio: 390 / 844 },
|
||||
flyToBoundingSphere: (sphere, options) => calls.push({ sphere, options }),
|
||||
},
|
||||
};
|
||||
});
|
||||
flyToDataSource(viewer, ds);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
@@ -130,34 +169,17 @@ test('portrait framing accounts for FOV, high ground and symmetric extents', ()
|
||||
viewer.camera.frustum.aspectRatio = 16 / 9;
|
||||
flyToDataSource(viewer, ds);
|
||||
assert.ok(calls[0].options.offset.range > calls[1].options.offset.range);
|
||||
const symmetric = {
|
||||
entities: {
|
||||
values: [
|
||||
{ position: { getValue: () => new Cesium.Cartesian3(6378137, 0, 0) } },
|
||||
{ position: { getValue: () => new Cesium.Cartesian3(-6378137, 0, 0) } },
|
||||
],
|
||||
},
|
||||
};
|
||||
const symmetric = drawingOf([pin(0, 0), pin(180, 0)]);
|
||||
assert.doesNotThrow(() => flyToDataSource(viewer, symmetric));
|
||||
assert.ok(Number.isFinite(calls.at(-1).options.offset.range));
|
||||
assert.doesNotThrow(() => calls.at(-1).options.complete());
|
||||
cancelCameraArrival(viewer);
|
||||
});
|
||||
|
||||
test('non-finite positions and hidden features never enter the camera footprint', () => {
|
||||
const position = (p) => ({ position: { getValue: () => p } });
|
||||
const points = dataSourcePoints({
|
||||
entities: {
|
||||
values: [
|
||||
position(new Cesium.Cartesian3(NaN, 1, 2)),
|
||||
{
|
||||
...position(Cesium.Cartesian3.fromDegrees(10, 10)),
|
||||
isShowing: false,
|
||||
},
|
||||
position(Cesium.Cartesian3.fromDegrees(20, 20)),
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(points.length, 1);
|
||||
assert.ok(Math.abs(points[0][0] - 20) < 1e-6);
|
||||
test('non-finite positions are refused and a hidden file has no footprint', () => {
|
||||
assert.throws(() => drawingOf([pin(Number.NaN, 1)]), /invalid point/);
|
||||
const drawing = drawingOf([pin(20, 20)]);
|
||||
assert.equal(importedDrawingPoints(drawing).length, 1);
|
||||
drawing.show = false;
|
||||
assert.deepEqual(importedDrawingPoints(drawing), []);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useStatusStore } from './stores/status.js';
|
||||
import { applicationPinia } from './vueRuntime.js';
|
||||
import { findFrame } from '../render/rendererOf.js';
|
||||
|
||||
/**
|
||||
* Count rendered globe frames while the optional readout is visible. The
|
||||
@@ -10,9 +11,9 @@ export function createFrameRateMonitor({
|
||||
documentRef = document,
|
||||
store = useStatusStore(applicationPinia()),
|
||||
}) {
|
||||
const frameEvent = viewer?.scene?.postRender;
|
||||
const frameOfViewer = () => findFrame(viewer);
|
||||
// A page without the scene chrome has no title bar to show it in.
|
||||
if (!documentRef.getElementById('title-bar') || !frameEvent)
|
||||
if (!documentRef.getElementById('title-bar') || !frameOfViewer())
|
||||
return { destroy() {} };
|
||||
|
||||
// i18n-ignore: FPS is a unit code, the same in every language
|
||||
@@ -43,7 +44,9 @@ export function createFrameRateMonitor({
|
||||
startedAt = performance.now();
|
||||
// i18n-ignore: FPS is a unit code, the same in every language
|
||||
present({ visible: true, text: 'FPS —' });
|
||||
removeFrameListener = frameEvent.addEventListener(() => {
|
||||
// Looked up when shown, so a renderer bound since creation is the one
|
||||
// counted.
|
||||
removeFrameListener = frameOfViewer()?.on('postRender', () => {
|
||||
frames++;
|
||||
});
|
||||
timer = setInterval(() => {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFrameRateMonitor } from './frameRateMonitor.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs';
|
||||
|
||||
function fixture(t) {
|
||||
const keys = new Set();
|
||||
@@ -27,6 +29,7 @@ function fixture(t) {
|
||||
},
|
||||
},
|
||||
};
|
||||
bindRenderer(viewer, { frame: fakeSceneFrame(viewer) });
|
||||
const monitor = createFrameRateMonitor({ viewer, documentRef, store });
|
||||
t.after(() => monitor.destroy());
|
||||
return {
|
||||
@@ -133,6 +136,7 @@ test("destroying an earlier monitor leaves a newer one's readout", () => {
|
||||
const viewer = {
|
||||
scene: { postRender: { addEventListener: () => () => {} } },
|
||||
};
|
||||
bindRenderer(viewer, { frame: fakeSceneFrame(viewer) });
|
||||
const first = createFrameRateMonitor({ viewer, documentRef, store });
|
||||
const second = createFrameRateMonitor({ viewer, documentRef, store });
|
||||
const shown = store.fps;
|
||||
|
||||
@@ -8,6 +8,8 @@ import { createPinia } from 'pinia';
|
||||
import { useStatusStore } from './stores/status.js';
|
||||
import { createFrameRateMonitor } from './frameRateMonitor.js';
|
||||
import SceneChromeView from './views/SceneChromeView.vue';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs';
|
||||
|
||||
test('the FPS readout sits in the title bar, hidden until the backquote key', async (t) => {
|
||||
document.body.replaceChildren();
|
||||
@@ -18,8 +20,12 @@ test('the FPS readout sits in the title bar, hidden until the backquote key', as
|
||||
const readout = () =>
|
||||
document.querySelector('#title-bar .frame-rate-readout');
|
||||
assert.equal(readout(), null, 'no readout without a monitor');
|
||||
const viewer = {
|
||||
scene: { postRender: { addEventListener: () => () => {} } },
|
||||
};
|
||||
bindRenderer(viewer, { frame: fakeSceneFrame(viewer) });
|
||||
const monitor = createFrameRateMonitor({
|
||||
viewer: { scene: { postRender: { addEventListener: () => () => {} } } },
|
||||
viewer,
|
||||
store: useStatusStore(pinia),
|
||||
});
|
||||
t.after(() => monitor.destroy());
|
||||
|
||||
+62
-26
@@ -4,8 +4,23 @@ import {
|
||||
MAX_IMPORTED_FILES,
|
||||
loadGeoFile,
|
||||
} from '../data/geoFileImport.js';
|
||||
import {
|
||||
importedDrawingPoints,
|
||||
removeImportedDrawing,
|
||||
showImportedDrawing,
|
||||
} from '../data/geoImportPins.js';
|
||||
import { formatNumber, t, tn, translateKnown } from '../i18n/index.js';
|
||||
import { flyToDataSource } from './flyToDataSource.js';
|
||||
import { flyToFootprint } from './flyToDataSource.js';
|
||||
import {
|
||||
canvasOf,
|
||||
findCamera,
|
||||
findFrame,
|
||||
findGlobe,
|
||||
} from '../render/rendererOf.js';
|
||||
|
||||
/** Fly to the whole footprint of one imported file's drawing. */
|
||||
const flyToDrawing = (viewer, drawing, options) =>
|
||||
flyToFootprint(viewer, importedDrawingPoints(drawing), options);
|
||||
|
||||
// One color per file, in import order, from the whiteboard palette.
|
||||
const COLORS = ['#39d0ff', '#ffb547', '#5dff9f', '#ff6b6b', '#8be9ff'];
|
||||
@@ -29,14 +44,14 @@ function localizedValues(values) {
|
||||
* renders them. `connect(actions)` answers the view's pick and row buttons
|
||||
* and returns their disconnect.
|
||||
* @returns {{destroy: Function, importFiles: Function, list: Function,
|
||||
* setVisible: Function, flyTo: Function, remove: Function,
|
||||
* setVisible: Function, flyTo: Function, remove: Function, drawn: Function,
|
||||
* diagnostics: Function}|null}
|
||||
*/
|
||||
export function initGeoFileImport({
|
||||
viewer,
|
||||
load = loadGeoFile,
|
||||
document: doc = globalThis.document,
|
||||
flyToSource = flyToDataSource,
|
||||
flyToSource = flyToDrawing,
|
||||
navigation = null,
|
||||
ground = null,
|
||||
subscribeMapSource = null,
|
||||
@@ -68,7 +83,7 @@ export function initGeoFileImport({
|
||||
hint = text || '';
|
||||
present();
|
||||
};
|
||||
const render = () => viewer.scene?.requestRender?.();
|
||||
const render = () => findFrame(viewer)?.requestRender('geo-import');
|
||||
let groundTimer,
|
||||
groundQueued = false,
|
||||
groundAgain = false;
|
||||
@@ -109,14 +124,20 @@ export function initGeoFileImport({
|
||||
}, 200);
|
||||
};
|
||||
removeMapSource = subscribeMapSource?.(scheduleGround);
|
||||
const ownEvent = (event, listener) => {
|
||||
const remove = event?.addEventListener?.(listener);
|
||||
if (remove) groundRemovers.push(remove);
|
||||
};
|
||||
ownEvent(viewer.camera?.moveEnd, scheduleGround);
|
||||
ownEvent(viewer.scene?.globe?.tileLoadProgressEvent, (pending) => {
|
||||
if (!pending) scheduleGround();
|
||||
});
|
||||
const camera = findCamera(viewer);
|
||||
if (camera) groundRemovers.push(camera.on('moveEnd', scheduleGround));
|
||||
// Terrain tiles finishing loading: the queue running dry, once each time.
|
||||
let terrainPending = null;
|
||||
const globe = findGlobe(viewer);
|
||||
if (globe)
|
||||
groundRemovers.push(
|
||||
globe.on('progress', (progress) => {
|
||||
const pending = progress.terrainPending;
|
||||
if (pending === terrainPending) return;
|
||||
terrainPending = pending;
|
||||
if (!pending) scheduleGround();
|
||||
}),
|
||||
);
|
||||
|
||||
/** Publish the file list and hint; the view renders them. */
|
||||
function present() {
|
||||
@@ -166,7 +187,7 @@ export function initGeoFileImport({
|
||||
const item = find(id);
|
||||
if (!item) return false;
|
||||
item.visible = Boolean(visible);
|
||||
item.dataSource.show = item.visible;
|
||||
showImportedDrawing(item.drawing, item.visible);
|
||||
if (item.visible) scheduleGround();
|
||||
present();
|
||||
render();
|
||||
@@ -177,7 +198,7 @@ export function initGeoFileImport({
|
||||
// destination's terrain has loaded (see ./flyToDataSource.js).
|
||||
const fly = (item) => {
|
||||
if (!item.visible) setVisible(item.id, true);
|
||||
flyToSource(viewer, item.dataSource, { ground });
|
||||
flyToSource(viewer, item.drawing, { ground });
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -214,7 +235,7 @@ export function initGeoFileImport({
|
||||
const at = imports.findIndex((item) => item.id === id);
|
||||
if (at < 0) return false;
|
||||
const [item] = imports.splice(at, 1);
|
||||
viewer.dataSources?.remove?.(item.dataSource, true);
|
||||
removeImportedDrawing(item.drawing);
|
||||
item.revoke?.();
|
||||
present();
|
||||
render();
|
||||
@@ -278,6 +299,18 @@ export function initGeoFileImport({
|
||||
loaded.revoke?.();
|
||||
break;
|
||||
}
|
||||
try {
|
||||
loaded.mount?.();
|
||||
} catch {
|
||||
// Something in it the renderer would not draw: refused whole.
|
||||
loaded.revoke?.();
|
||||
outcomes.push({
|
||||
name: fileName,
|
||||
ok: false,
|
||||
error: t('That file could not be read.'),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
colorAt += 1;
|
||||
seq += 1;
|
||||
const item = {
|
||||
@@ -289,17 +322,10 @@ export function initGeoFileImport({
|
||||
removed: loaded.removed || 0,
|
||||
color,
|
||||
visible: true,
|
||||
dataSource: loaded.dataSource,
|
||||
drawing: loaded.drawing,
|
||||
revoke: loaded.revoke,
|
||||
refreshGround: loaded.refreshGround,
|
||||
};
|
||||
await viewer.dataSources.add(item.dataSource);
|
||||
if (destroyed) {
|
||||
viewer.dataSources.remove?.(item.dataSource, true);
|
||||
item.revoke?.();
|
||||
break;
|
||||
}
|
||||
loaded.mount?.();
|
||||
imports.push(item);
|
||||
present();
|
||||
render();
|
||||
@@ -336,10 +362,10 @@ export function initGeoFileImport({
|
||||
const gesture = () => {
|
||||
cameraIntent += 1;
|
||||
};
|
||||
listen(viewer.scene?.canvas || container, 'pointerdown', gesture, {
|
||||
listen(canvasOf(viewer) || container, 'pointerdown', gesture, {
|
||||
passive: true,
|
||||
});
|
||||
listen(viewer.scene?.canvas || container, 'wheel', gesture, {
|
||||
listen(canvasOf(viewer) || container, 'wheel', gesture, {
|
||||
passive: true,
|
||||
});
|
||||
const hasFiles = (event) =>
|
||||
@@ -387,6 +413,16 @@ export function initGeoFileImport({
|
||||
setVisible,
|
||||
flyTo,
|
||||
remove,
|
||||
/** What a file drew: its sets' ids, whether shown, and their items. */
|
||||
drawn: (id) => {
|
||||
const item = imports.find((entry) => entry.id === id);
|
||||
if (!item?.drawing) return null;
|
||||
return {
|
||||
sets: { ...item.drawing.ids },
|
||||
show: item.drawing.show,
|
||||
...item.drawing.items?.(),
|
||||
};
|
||||
},
|
||||
diagnostics: () => ({
|
||||
files: imports.length,
|
||||
entities: imports.reduce((n, item) => n + item.entityCount, 0),
|
||||
@@ -402,7 +438,7 @@ export function initGeoFileImport({
|
||||
clearTimeout(groundTimer);
|
||||
for (const remove of groundRemovers) remove();
|
||||
for (const item of imports.splice(0)) {
|
||||
viewer.dataSources?.remove?.(item.dataSource, true);
|
||||
removeImportedDrawing(item.drawing);
|
||||
item.revoke?.();
|
||||
}
|
||||
for (const [target, type, listener, options] of listeners.splice(0))
|
||||
|
||||
+126
-21
@@ -1,6 +1,6 @@
|
||||
// Behavioral tests for DISPLAY ▸ Import: the controller is driven against
|
||||
// fake DOM and viewer doubles with an injected loader, and its observable
|
||||
// effects are asserted — data sources added and removed, the rows and hint it
|
||||
// effects are asserted — drawings mounted and removed, the rows and hint it
|
||||
// publishes, drop handling, the file limit, and what destroy() gives back.
|
||||
// The Display panel renders the published list (`displayPanel.test.mjs`);
|
||||
// real parsing and rendering run in `scripts/qa-geo-import.mjs`.
|
||||
@@ -9,6 +9,7 @@ import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { initGeoFileImport, summarize } from './geoFileImport.js';
|
||||
import { GeoImportError, MAX_IMPORTED_FILES } from '../data/geoFileImport.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
|
||||
class FakeClassList {
|
||||
constructor() {
|
||||
@@ -59,7 +60,13 @@ class FakeElement {
|
||||
}
|
||||
}
|
||||
|
||||
function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
function setup({
|
||||
load,
|
||||
navigation,
|
||||
flyToSource,
|
||||
subscribeMapSource,
|
||||
ports,
|
||||
} = {}) {
|
||||
const els = {
|
||||
'geo-import-button': new FakeElement('button', 'geo-import-button'),
|
||||
};
|
||||
@@ -78,18 +85,11 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
const viewer = {
|
||||
container: new FakeElement('div', 'cesiumContainer'),
|
||||
scene: { requestRender: () => (renders += 1) },
|
||||
dataSources: {
|
||||
add: async (ds) => {
|
||||
added.push(ds);
|
||||
return ds;
|
||||
},
|
||||
remove: (ds, destroy) => {
|
||||
removed.push({ ds, destroy });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
flyTo: (target) => flights.push(target),
|
||||
};
|
||||
// The renderer's ports, when the test gives them, bound before the import
|
||||
// starts as the application binds its renderer.
|
||||
if (ports) bindRenderer(viewer, ports);
|
||||
const revoked = [];
|
||||
const loads = [];
|
||||
const defaultLoad = async (file, opts) => {
|
||||
@@ -97,7 +97,7 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
if (file.fail) throw new GeoImportError(file.fail);
|
||||
if (file.crash) throw new Error('boom');
|
||||
return {
|
||||
dataSource: { show: true },
|
||||
drawing: { show: true },
|
||||
name: file.name,
|
||||
format: 'geojson',
|
||||
entityCount: 3,
|
||||
@@ -105,9 +105,24 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
revoke: () => revoked.push(file.name),
|
||||
};
|
||||
};
|
||||
// Each loaded file's drawing, recorded when the import mounts it and when
|
||||
// it takes it off the globe.
|
||||
const recorded = async (file, opts) => {
|
||||
const loaded = await (load || defaultLoad)(file, opts);
|
||||
const drawing = loaded.drawing ?? {};
|
||||
drawing.destroy = () => removed.push({ ds: drawing, destroy: true });
|
||||
return {
|
||||
...loaded,
|
||||
drawing,
|
||||
mount() {
|
||||
loaded.mount?.();
|
||||
added.push(drawing);
|
||||
},
|
||||
};
|
||||
};
|
||||
const tool = initGeoFileImport({
|
||||
viewer,
|
||||
load: load || defaultLoad,
|
||||
load: recorded,
|
||||
document,
|
||||
...(navigation ? { navigation } : {}),
|
||||
...(subscribeMapSource ? { subscribeMapSource } : {}),
|
||||
@@ -191,10 +206,19 @@ test('row buttons hide, show, fly to and remove a file', async () => {
|
||||
await t.tool.importFiles([file('a.gpx')]);
|
||||
const [{ id }] = t.tool.list();
|
||||
const ds = t.added[0];
|
||||
ds.ids = { icons: 'i', lines: 'l', shapes: 's' };
|
||||
ds.items = () => ({ icons: [{ id: 'p0' }], lines: [], shapes: [] });
|
||||
const glyphClick = (name) => press(t, rows(t)[0], name);
|
||||
assert.equal(ds.show, true);
|
||||
glyphClick('toggle');
|
||||
assert.equal(ds.show, false);
|
||||
assert.deepEqual(t.tool.drawn(id), {
|
||||
sets: { icons: 'i', lines: 'l', shapes: 's' },
|
||||
show: false,
|
||||
icons: [{ id: 'p0' }],
|
||||
lines: [],
|
||||
shapes: [],
|
||||
});
|
||||
assert.equal(t.tool.list()[0].visible, false);
|
||||
assert.equal(action(rows(t)[0], 'toggle').pressed, 'false');
|
||||
assert.equal(action(rows(t)[0], 'toggle').icon, 'visibility_off');
|
||||
@@ -207,6 +231,7 @@ test('row buttons hide, show, fly to and remove a file', async () => {
|
||||
assert.deepEqual(t.revoked, ['a.gpx']);
|
||||
assert.equal(t.tool.list().length, 0);
|
||||
assert.deepEqual(rows(t), []);
|
||||
assert.equal(t.tool.drawn(id), null);
|
||||
assert.equal(t.tool.remove(id), false);
|
||||
});
|
||||
|
||||
@@ -230,6 +255,32 @@ test('a refused file says why and does not stop the rest of the batch', async ()
|
||||
assert.equal(t.tool.list().length, 1);
|
||||
});
|
||||
|
||||
test('a file the renderer will not draw is refused and released, and the batch goes on', async () => {
|
||||
const t = setup({
|
||||
load: async (file) => ({
|
||||
drawing: { show: true },
|
||||
name: file.name,
|
||||
format: 'kml',
|
||||
entityCount: 1,
|
||||
revoke: () => t.revoked.push(file.name),
|
||||
mount() {
|
||||
if (file.name === 'odd.kml') throw new Error('refused');
|
||||
},
|
||||
}),
|
||||
});
|
||||
const out = await t.tool.importFiles([file('odd.kml'), file('good.kml')]);
|
||||
assert.deepEqual(
|
||||
out.map((o) => o.ok),
|
||||
[false, true],
|
||||
);
|
||||
assert.match(out[0].error, /could not be read\./);
|
||||
assert.deepEqual(t.revoked, ['odd.kml']);
|
||||
assert.deepEqual(
|
||||
t.tool.list().map((f) => f.name),
|
||||
['good.kml'],
|
||||
);
|
||||
});
|
||||
|
||||
test('the number of files on the globe is bounded', async () => {
|
||||
const t = setup();
|
||||
const many = Array.from({ length: MAX_IMPORTED_FILES + 2 }, (_, i) =>
|
||||
@@ -304,7 +355,7 @@ test('a file that finishes loading after destroy is released, not added', async
|
||||
load: async () => {
|
||||
await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: 'late',
|
||||
format: 'kml',
|
||||
entityCount: 1,
|
||||
@@ -408,7 +459,7 @@ test('a direct camera gesture cancels the fly-to of a file still being read', as
|
||||
name: 'slow.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -454,7 +505,7 @@ test('ground refresh coalesces map changes and releases its subscription on tear
|
||||
name: 'point.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
refreshGround: async () => refreshed++,
|
||||
}),
|
||||
});
|
||||
@@ -471,6 +522,60 @@ test('ground refresh coalesces map changes and releases its subscription on tear
|
||||
assert.equal(unsubscribed, 1);
|
||||
});
|
||||
|
||||
test('the camera settling and the terrain queue running dry refresh the ground, through the ports', async () => {
|
||||
const listeners = { moveEnd: new Set(), progress: new Set() };
|
||||
const on = (name) => (event, cb) => {
|
||||
assert.equal(event, name);
|
||||
listeners[name].add(cb);
|
||||
return () => listeners[name].delete(cb);
|
||||
};
|
||||
const reasons = [];
|
||||
let refreshed = 0;
|
||||
const t = setup({
|
||||
ports: {
|
||||
camera: { on: on('moveEnd') },
|
||||
globe: { on: on('progress') },
|
||||
frame: { requestRender: (reason) => reasons.push(reason) },
|
||||
},
|
||||
load: async () => ({
|
||||
name: 'point.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
drawing: {},
|
||||
refreshGround: async () => refreshed++,
|
||||
}),
|
||||
});
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 300));
|
||||
const progress = (terrainPending) => {
|
||||
for (const cb of [...listeners.progress])
|
||||
cb({ tilesPending: 0, imageryPending: 0, terrainPending });
|
||||
};
|
||||
await t.tool.importFiles([file('point.geojson')]);
|
||||
assert.ok(reasons.length > 0 && reasons.every((r) => r === 'geo-import'));
|
||||
for (const cb of [...listeners.moveEnd]) cb();
|
||||
await settle();
|
||||
assert.equal(refreshed, 1, 'the camera settling refreshes once');
|
||||
// The first report of an empty terrain queue counts, then only the queue
|
||||
// running dry again, once each time it does; progress that leaves the
|
||||
// terrain count where it was (imagery only) does not.
|
||||
progress(0);
|
||||
await settle();
|
||||
assert.equal(refreshed, 2);
|
||||
progress(0);
|
||||
await settle();
|
||||
assert.equal(refreshed, 2);
|
||||
progress(3);
|
||||
progress(1);
|
||||
await settle();
|
||||
assert.equal(refreshed, 2);
|
||||
progress(0);
|
||||
await settle();
|
||||
assert.equal(refreshed, 3);
|
||||
t.tool.destroy();
|
||||
assert.equal(listeners.moveEnd.size, 0);
|
||||
assert.equal(listeners.progress.size, 0);
|
||||
});
|
||||
|
||||
test('Fly to is an immediate navigation that Cockpit can refuse', async () => {
|
||||
const flown = [];
|
||||
const nav = navigationDouble({ immediate: false });
|
||||
@@ -505,7 +610,7 @@ test('a slow import does not fly once something newer took the camera', async ()
|
||||
load: async (f) => {
|
||||
await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
@@ -539,7 +644,7 @@ test('a queued import cannot fly over navigation that happened while it waited',
|
||||
load: async (f) => {
|
||||
if (f.name === 'first.geojson') await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
@@ -574,7 +679,7 @@ test('a refused deferred stamp (Cockpit) imports without flying', async () => {
|
||||
test('KML and KMZ rows say they keep their own styles instead of showing a color', async () => {
|
||||
const t = setup({
|
||||
load: async (f) => ({
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: f.name,
|
||||
format: f.name.endsWith('.kml') ? 'kml' : 'gpx',
|
||||
entityCount: 2,
|
||||
@@ -593,7 +698,7 @@ test('KML and KMZ rows say they keep their own styles instead of showing a color
|
||||
test('the map-object count in a row title keeps digit grouping', async () => {
|
||||
const t = setup({
|
||||
load: async (f) => ({
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 12345,
|
||||
|
||||
+48
-139
@@ -1,28 +1,29 @@
|
||||
/**
|
||||
* Box selection for the Recent Imagery layer: press on the world, drag, and
|
||||
* release to hand the layer a degrees box. Follows the draw tool's ownership
|
||||
* rules — the pointer is claimed for the session, the viewer's own click
|
||||
* actions are borrowed and given back, and `destroy()` returns everything —
|
||||
* and freezes the camera only while a drag is in progress.
|
||||
* rules — the pointer is claimed for the session (a newer claim cancels it),
|
||||
* the viewer's own click actions are suppressed and given back, and
|
||||
* `destroy()` returns everything — and holds the camera only while a drag is
|
||||
* in progress.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { pickWorldFromScreen } from '../annotations/annotationResolver.js';
|
||||
import {
|
||||
claimPointer,
|
||||
pointerOwner,
|
||||
releasePointer,
|
||||
} from '../data/inputOwnership.js';
|
||||
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
|
||||
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
|
||||
import { validateBox } from '../layers/recentImagery/model.js';
|
||||
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
|
||||
import { msg } from '../i18n/index.js';
|
||||
import { canvasOf } from '../render/rendererOf.js';
|
||||
|
||||
/** The id this tool claims the pointer under. */
|
||||
export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box';
|
||||
|
||||
/**
|
||||
* Wire the box tool.
|
||||
* @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, cesium?: object, pickWorld?: Function, documentRef?: object }} deps
|
||||
* @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, createPreview?: Function, inputFor?: Function, pickWorld?: Function, documentRef?: object }} deps
|
||||
* `onEscape` runs before the tool cancels on Escape; returning `true` claims
|
||||
* the key (it is still consumed) and leaves the tool armed.
|
||||
* `createPreview(viewer, dragBox)` draws the box being dragged
|
||||
* (`createImageryBoxPreview`).
|
||||
* @returns {{ start: () => boolean, cancel: (reason?: string) => void, isActive: () => boolean, destroy: () => Promise<void> } | null}
|
||||
*/
|
||||
export function initImageryBoxTool({
|
||||
@@ -31,22 +32,21 @@ export function initImageryBoxTool({
|
||||
onCancel,
|
||||
onActive,
|
||||
onEscape,
|
||||
cesium = Cesium,
|
||||
createPreview = createImageryBoxPreview,
|
||||
inputFor = defaultInputFor,
|
||||
pickWorld = pickWorldFromScreen,
|
||||
documentRef = globalThis.document,
|
||||
} = {}) {
|
||||
if (!viewer?.scene || typeof onBox !== 'function') return null;
|
||||
if (!viewer || typeof onBox !== 'function') return null;
|
||||
|
||||
let active = false;
|
||||
let destroyed = false;
|
||||
/** Drag corners in degrees; `anchor` is null while no drag is live. */
|
||||
let anchor = null;
|
||||
let corner = null;
|
||||
let handler = null;
|
||||
let unbindScene = null;
|
||||
let lease = null;
|
||||
let savedSingleClick = null;
|
||||
let savedDoubleClick = null;
|
||||
let savedCameraInputs = null;
|
||||
let releaseCamera = null;
|
||||
|
||||
const dragBox = () =>
|
||||
anchor && {
|
||||
@@ -56,68 +56,11 @@ export function initImageryBoxTool({
|
||||
north: Math.max(anchor.lat, corner.lat),
|
||||
};
|
||||
|
||||
const dataSource = new cesium.CustomDataSource(
|
||||
'gev-recent-imagery-box-preview',
|
||||
);
|
||||
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
|
||||
() => null,
|
||||
);
|
||||
const stroke = cesium.Color.fromCssColorString('#8be9ff');
|
||||
const previewRectangle = () => {
|
||||
const box = dragBox();
|
||||
return box
|
||||
? cesium.Rectangle.fromDegrees(box.west, box.south, box.east, box.north)
|
||||
: undefined;
|
||||
};
|
||||
const previewOutline = () => {
|
||||
const box = dragBox();
|
||||
if (!box) return [];
|
||||
return cesium.Cartesian3.fromDegreesArray([
|
||||
box.west,
|
||||
box.south,
|
||||
box.east,
|
||||
box.south,
|
||||
box.east,
|
||||
box.north,
|
||||
box.west,
|
||||
box.north,
|
||||
box.west,
|
||||
box.south,
|
||||
]);
|
||||
};
|
||||
const fill = dataSource.entities.add({
|
||||
show: false,
|
||||
rectangle: {
|
||||
coordinates: new cesium.CallbackProperty(previewRectangle, false),
|
||||
material: stroke.withAlpha(0.12),
|
||||
classificationType: cesium.ClassificationType.BOTH,
|
||||
},
|
||||
});
|
||||
// A rectangle graphic cannot draw a dashed edge on the ground, so the
|
||||
// outline is its own draped polyline traced round the same corners.
|
||||
const outline = dataSource.entities.add({
|
||||
show: false,
|
||||
polyline: {
|
||||
positions: new cesium.CallbackProperty(previewOutline, false),
|
||||
width: 2,
|
||||
clampToGround: true,
|
||||
classificationType: cesium.ClassificationType.BOTH,
|
||||
material: new cesium.PolylineDashMaterialProperty({
|
||||
color: stroke.withAlpha(0.95),
|
||||
dashLength: 12,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const requestRender = () => viewer.scene.requestRender?.();
|
||||
const setPreview = (visible) => {
|
||||
fill.show = visible;
|
||||
outline.show = visible;
|
||||
requestRender();
|
||||
};
|
||||
const preview = createPreview(viewer, dragBox);
|
||||
const setPreview = (visible) => preview.setVisible(visible);
|
||||
const worldAt = (position) => {
|
||||
if (!position) return null;
|
||||
const canvas = viewer.scene.canvas;
|
||||
const canvas = canvasOf(viewer);
|
||||
const w = canvas?.clientWidth || canvas?.width || 1;
|
||||
const h = canvas?.clientHeight || canvas?.height || 1;
|
||||
const point = pickWorld(viewer, position.x / w, position.y / h);
|
||||
@@ -125,19 +68,13 @@ export function initImageryBoxTool({
|
||||
const lat = Number(point?.lat);
|
||||
return Number.isFinite(lon) && Number.isFinite(lat) ? { lon, lat } : null;
|
||||
};
|
||||
const cameraController = () => viewer.scene.screenSpaceCameraController;
|
||||
|
||||
function freezeCamera() {
|
||||
const controller = cameraController();
|
||||
if (!controller || savedCameraInputs !== null) return;
|
||||
savedCameraInputs = controller.enableInputs;
|
||||
controller.enableInputs = false;
|
||||
releaseCamera ??= inputFor(viewer).suspendCamera('recent-imagery-box');
|
||||
}
|
||||
function thawCamera() {
|
||||
const controller = cameraController();
|
||||
if (controller && savedCameraInputs !== null)
|
||||
controller.enableInputs = savedCameraInputs;
|
||||
savedCameraInputs = null;
|
||||
releaseCamera?.();
|
||||
releaseCamera = null;
|
||||
}
|
||||
|
||||
function endDrag() {
|
||||
@@ -163,7 +100,7 @@ export function initImageryBoxTool({
|
||||
const point = anchor && !destroyed && worldAt(event.endPosition);
|
||||
if (!point) return;
|
||||
corner = point;
|
||||
requestRender();
|
||||
preview.changed();
|
||||
};
|
||||
const onUp = (event) => {
|
||||
if (!anchor || destroyed) return;
|
||||
@@ -190,45 +127,23 @@ export function initImageryBoxTool({
|
||||
};
|
||||
|
||||
function bindScene() {
|
||||
if (handler) return;
|
||||
handler = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
|
||||
handler.setInputAction(onDown, cesium.ScreenSpaceEventType.LEFT_DOWN);
|
||||
handler.setInputAction(onMove, cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||||
handler.setInputAction(onUp, cesium.ScreenSpaceEventType.LEFT_UP);
|
||||
const stock = viewer.screenSpaceEventHandler;
|
||||
if (stock) {
|
||||
savedSingleClick =
|
||||
stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK) || null;
|
||||
savedDoubleClick =
|
||||
stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
|
||||
null;
|
||||
stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
|
||||
}
|
||||
if (unbindScene) return;
|
||||
const input = inputFor(viewer);
|
||||
const held = { lease: () => lease };
|
||||
const offs = [
|
||||
input.onPointer('down', onDown, held),
|
||||
input.onPointer('move', onMove, held),
|
||||
input.onPointer('up', onUp, held),
|
||||
input.suppressStockClicks(),
|
||||
];
|
||||
unbindScene = () => offs.forEach((off) => off());
|
||||
documentRef?.addEventListener?.('keydown', onKey, true);
|
||||
documentRef?.body?.classList?.add?.('gev-imagery-box');
|
||||
}
|
||||
|
||||
function releaseScene() {
|
||||
if (handler) {
|
||||
handler.destroy();
|
||||
handler = null;
|
||||
}
|
||||
const stock = viewer.screenSpaceEventHandler;
|
||||
if (stock && savedSingleClick) {
|
||||
stock.setInputAction(
|
||||
savedSingleClick,
|
||||
cesium.ScreenSpaceEventType.LEFT_CLICK,
|
||||
);
|
||||
}
|
||||
if (stock && savedDoubleClick) {
|
||||
stock.setInputAction(
|
||||
savedDoubleClick,
|
||||
cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
|
||||
);
|
||||
}
|
||||
savedSingleClick = null;
|
||||
savedDoubleClick = null;
|
||||
unbindScene?.();
|
||||
unbindScene = null;
|
||||
documentRef?.removeEventListener?.('keydown', onKey, true);
|
||||
documentRef?.body?.classList?.remove?.('gev-imagery-box');
|
||||
}
|
||||
@@ -236,14 +151,16 @@ export function initImageryBoxTool({
|
||||
function setActive(next) {
|
||||
if (next === active) return active;
|
||||
if (next) {
|
||||
lease = claimPointer(IMAGERY_BOX_POINTER_OWNER);
|
||||
if (!lease) {
|
||||
onCancel?.(
|
||||
'pointer-busy',
|
||||
`${pointerOwner()} is using the pointer — close it first`,
|
||||
);
|
||||
return active;
|
||||
}
|
||||
// The newest claim takes over: a tool holding the pointer is told and
|
||||
// turns itself off, and a newer one cancels this session as if the
|
||||
// person had.
|
||||
const claimed = claimPointer(IMAGERY_BOX_POINTER_OWNER, {
|
||||
onLost: () => {
|
||||
if (lease === claimed) cancel();
|
||||
},
|
||||
});
|
||||
if (!claimed) return active;
|
||||
lease = claimed;
|
||||
active = true;
|
||||
bindScene();
|
||||
} else {
|
||||
@@ -264,7 +181,7 @@ export function initImageryBoxTool({
|
||||
}
|
||||
|
||||
return {
|
||||
/** Begin a box session. False when the pointer is held elsewhere. */
|
||||
/** Begin a box session, taking the pointer from any tool holding it. */
|
||||
start() {
|
||||
return !destroyed && setActive(true);
|
||||
},
|
||||
@@ -274,22 +191,14 @@ export function initImageryBoxTool({
|
||||
},
|
||||
/** Returns everything; resolves once the preview is detached. */
|
||||
destroy() {
|
||||
if (destroyed) return attaching;
|
||||
if (destroyed) return preview.destroy();
|
||||
if (active) setActive(false);
|
||||
destroyed = true;
|
||||
releaseScene();
|
||||
releasePointer(lease);
|
||||
lease = null;
|
||||
thawCamera();
|
||||
dataSource.entities.removeAll();
|
||||
attaching = attaching.then(() => {
|
||||
try {
|
||||
viewer.dataSources.remove(dataSource, true);
|
||||
} catch {
|
||||
/* viewer already disposed */
|
||||
}
|
||||
});
|
||||
return attaching;
|
||||
return preview.destroy();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -11,16 +11,20 @@ import {
|
||||
initImageryBoxTool,
|
||||
} from './imageryBoxTool.js';
|
||||
import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs';
|
||||
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
|
||||
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
function fixture(options = {}) {
|
||||
resetPointerOwnership();
|
||||
const fakes = boxToolFakes();
|
||||
const draw = fakeDrawPort();
|
||||
const boxes = [];
|
||||
const cancels = [];
|
||||
const actives = [];
|
||||
const tool = initImageryBoxTool({
|
||||
viewer: fakes.viewer,
|
||||
cesium: fakes.cesium,
|
||||
createPreview: (viewer, dragBox) =>
|
||||
createImageryBoxPreview(viewer, dragBox, { draw }),
|
||||
pickWorld: fakes.pickWorld,
|
||||
documentRef: fakes.documentRef,
|
||||
onBox: (box) => boxes.push(box),
|
||||
@@ -29,12 +33,35 @@ function fixture(options = {}) {
|
||||
...options,
|
||||
});
|
||||
const camera = fakes.viewer.scene.screenSpaceCameraController;
|
||||
// The stock action as it runs now: the input port holds them, so it is
|
||||
// the original while not suppressed, and none while it is.
|
||||
const stockAction = (type) =>
|
||||
fakes.viewer.screenSpaceEventHandler.getInputAction(fakes.types[type]);
|
||||
fakes.stockEnabled(type === 'LEFT_CLICK' ? 'select' : 'dblclickFollow')
|
||||
? type === 'LEFT_CLICK'
|
||||
? fakes.originalClick
|
||||
: fakes.originalDouble
|
||||
: undefined;
|
||||
// The preview's fill or outline set, while it is live.
|
||||
const previewSet = (part) =>
|
||||
[...draw.sets.values()].find(
|
||||
(r) =>
|
||||
!r.disposed &&
|
||||
r.spec.id.startsWith('recent-imagery-box:') &&
|
||||
r.spec.id.endsWith(`:${part}`),
|
||||
);
|
||||
// Whether the box shows: its fill and its outline, drawn and shown.
|
||||
const preview = () =>
|
||||
fakes.viewer.dataSources.sources[0]?.entities.values.every((e) => e.show);
|
||||
['fill', 'outline'].every((part) => {
|
||||
const set = previewSet(part);
|
||||
return (
|
||||
Boolean(set?.items.size) &&
|
||||
[...set.items.values()].every((item) => item.show !== false)
|
||||
);
|
||||
});
|
||||
return {
|
||||
...fakes,
|
||||
draw,
|
||||
previewSet,
|
||||
tool,
|
||||
boxes,
|
||||
cancels,
|
||||
@@ -55,8 +82,16 @@ test('a session claims the pointer, borrows the stock clicks, freezes the camera
|
||||
assert.equal(f.camera.enableInputs, true, 'not frozen before the press');
|
||||
f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } });
|
||||
assert.equal(f.camera.enableInputs, false);
|
||||
assert.equal(f.preview(), true);
|
||||
assert.equal(f.preview(), false, 'a press alone has no box to draw');
|
||||
f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 250 } });
|
||||
assert.equal(f.preview(), true, 'the box shows as it is dragged');
|
||||
const rect = () => f.previewSet('fill').items.get('box').geometry.rect;
|
||||
assert.deepEqual(
|
||||
Object.values(rect()).map((v) => Math.round(v * 1e6) / 1e6),
|
||||
[-97.85, 30.3, -97.8, 30.35],
|
||||
);
|
||||
assert.equal(f.previewSet('outline').items.get('edge').style.kind, 'dash');
|
||||
assert.equal(f.previewSet('outline').items.get('edge').mode, 'draped');
|
||||
f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 10 } }); // sky: ignored
|
||||
f.fire('LEFT_UP', { position: { x: 500, y: 250 } });
|
||||
assert.equal(f.boxes.length, 1);
|
||||
@@ -74,7 +109,7 @@ test('a session claims the pointer, borrows the stock clicks, freezes the camera
|
||||
assert.equal(f.preview(), false);
|
||||
assert.equal(f.documentRef.classes.has('gev-imagery-box'), false);
|
||||
assert.equal(f.documentRef.listeners.length, 0);
|
||||
assert.equal(f.handler(), null);
|
||||
assert.equal(f.bound(), false);
|
||||
assert.deepEqual(f.actives, [true, false]);
|
||||
await f.tool.destroy();
|
||||
});
|
||||
@@ -125,17 +160,36 @@ test('an Escape interceptor that claims the key leaves the tool armed; the next
|
||||
await f.tool.destroy();
|
||||
});
|
||||
|
||||
test('a held pointer refuses the session and nothing is borrowed', async () => {
|
||||
test('a session takes the pointer from another tool, which is told', async () => {
|
||||
const f = fixture();
|
||||
const lease = claimPointer('draw');
|
||||
assert.equal(f.tool.start(), false);
|
||||
assert.deepEqual(f.cancels, [
|
||||
['pointer-busy', 'draw is using the pointer — close it first'],
|
||||
]);
|
||||
assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick);
|
||||
assert.equal(f.handler(), null);
|
||||
releasePointer(lease);
|
||||
let lost = 0;
|
||||
claimPointer('draw', { onLost: () => (lost += 1) });
|
||||
assert.equal(f.tool.start(), true);
|
||||
assert.equal(pointerOwner(), IMAGERY_BOX_POINTER_OWNER);
|
||||
assert.equal(lost, 1);
|
||||
assert.deepEqual(f.cancels, []);
|
||||
await f.tool.destroy();
|
||||
});
|
||||
|
||||
test('a newer tool taking the pointer mid-drag cancels the session and returns everything', async () => {
|
||||
const f = fixture();
|
||||
f.tool.start();
|
||||
f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } });
|
||||
f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 250 } });
|
||||
assert.equal(f.camera.enableInputs, false);
|
||||
const lease = claimPointer('draw');
|
||||
assert.equal(f.tool.isActive(), false);
|
||||
assert.deepEqual(f.cancels, [['cancel', undefined]], 'as if cancelled');
|
||||
assert.deepEqual(f.actives, [true, false]);
|
||||
assert.equal(f.camera.enableInputs, true, 'the camera is back');
|
||||
assert.equal(f.preview(), false, 'no box is left on the globe');
|
||||
assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick);
|
||||
assert.equal(f.bound(), false);
|
||||
assert.equal(f.documentRef.classes.has('gev-imagery-box'), false);
|
||||
assert.equal(pointerOwner(), 'draw', 'the newer tool keeps it');
|
||||
f.fire('LEFT_UP', { position: { x: 500, y: 250 } });
|
||||
assert.deepEqual(f.boxes, [], 'the drag it ended hands over no box');
|
||||
releasePointer(lease);
|
||||
await f.tool.destroy();
|
||||
});
|
||||
|
||||
@@ -143,11 +197,14 @@ test('destroy mid-drag restores the camera, releases the claim and detaches the
|
||||
const f = fixture();
|
||||
f.tool.start();
|
||||
f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } });
|
||||
assert.equal(f.viewer.dataSources.sources.length, 1);
|
||||
await f.tool.destroy();
|
||||
assert.ok(f.previewSet('fill') && f.previewSet('outline'));
|
||||
const destroying = f.tool.destroy();
|
||||
assert.equal(f.tool.destroy(), destroying);
|
||||
await destroying;
|
||||
assert.equal(f.camera.enableInputs, true);
|
||||
assert.equal(pointerOwner(), null);
|
||||
assert.equal(f.viewer.dataSources.sources.length, 0);
|
||||
assert.equal(f.previewSet('fill'), undefined, 'the preview is gone');
|
||||
assert.equal(f.previewSet('outline'), undefined);
|
||||
assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick);
|
||||
assert.equal(f.tool.start(), false);
|
||||
assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null);
|
||||
|
||||
@@ -24,6 +24,26 @@ function defaultValueText(beforePercent, afterPercent) {
|
||||
return `A ${beforePercent} percent, B ${afterPercent} percent`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A globe port's split as `createImagerySplit` writes it (its `scene`): the
|
||||
* divider moves the globe's split through the port. Null when the globe
|
||||
* has no split.
|
||||
* @param {import('../render/contract/globe').GlobePort|null|undefined} globe
|
||||
* @returns {{splitPosition: number}|null}
|
||||
*/
|
||||
export function globeSplitTarget(globe) {
|
||||
const imagery = globe?.imagery;
|
||||
if (!imagery?.setSplit) return null;
|
||||
return {
|
||||
get splitPosition() {
|
||||
return imagery.getSplit();
|
||||
},
|
||||
set splitPosition(value) {
|
||||
imagery.setSplit(value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Split divider for before/after imagery comparison.
|
||||
*
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup>
|
||||
import { vClassToggle } from '../rail/classToggle.js';
|
||||
import UiPanelEdge from './UiPanelEdge.vue';
|
||||
import UiPanelToggle from './UiPanelToggle.vue';
|
||||
|
||||
// Core's panel, with a name, title, slots and v-model:collapsed. It draws Core's panel markup
|
||||
@@ -57,6 +58,7 @@ const emit = defineEmits(['update:collapsed']);
|
||||
<slot name="badge" />
|
||||
<span class="panel-divider"></span>
|
||||
<slot name="actions" />
|
||||
<UiPanelEdge v-if="props.collapsible" />
|
||||
<UiPanelToggle
|
||||
v-if="props.collapsible"
|
||||
:target="props.id"
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { panelEdge, panelSide, togglePanelEdge } from '../panelEdge.js';
|
||||
|
||||
// A panel header's edge switch: it slides this side's panels over their rail
|
||||
// to the screen edge, and back. The side comes from the column the panel is in.
|
||||
const button = ref(null);
|
||||
const side = ref('left');
|
||||
const on = computed(() => panelEdge.value[side.value]);
|
||||
function toggle() {
|
||||
side.value = panelSide(button.value);
|
||||
togglePanelEdge(side.value);
|
||||
}
|
||||
function sync() {
|
||||
side.value = panelSide(button.value);
|
||||
}
|
||||
// The layout moves some panels to the right column after they mount, so the
|
||||
// side is read again once that has happened.
|
||||
onMounted(() => {
|
||||
sync();
|
||||
globalThis.requestAnimationFrame?.(sync);
|
||||
});
|
||||
const icon = computed(() =>
|
||||
side.value === 'right' ? 'align_horizontal_right' : 'align_horizontal_left',
|
||||
);
|
||||
const label = computed(() =>
|
||||
on.value
|
||||
? t('Move panels back beside the rail')
|
||||
: t('Move panels over the rail, to the edge'),
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
ref="button"
|
||||
type="button"
|
||||
class="ui-panel-edge panel-edge-btn"
|
||||
:aria-pressed="String(on)"
|
||||
:aria-label="label"
|
||||
:title="label"
|
||||
@pointerenter="sync"
|
||||
@focus="sync"
|
||||
@click="toggle"
|
||||
>
|
||||
<span class="material-symbols-outlined" aria-hidden="true">{{ icon }}</span>
|
||||
</button>
|
||||
</template>
|
||||
@@ -1,3 +1,4 @@
|
||||
import { onFollowChanged } from '../data/followed.js';
|
||||
import { isExplicitLayerStateOrigin } from '../data/layerState.js';
|
||||
import {
|
||||
registerCctvFocusRequestListener,
|
||||
@@ -80,11 +81,13 @@ export class LayerBindings {
|
||||
window,
|
||||
this._worldRequestFocusHandler,
|
||||
);
|
||||
this._navigationOwnerChangedRemover =
|
||||
this.viewer.trackedEntityChanged.addEventListener((entity) => {
|
||||
if (entity && !this._disposed)
|
||||
this._navigationOwnerChangedRemover = onFollowChanged(
|
||||
this.viewer,
|
||||
(followed) => {
|
||||
if (followed && !this._disposed)
|
||||
this._stampNavigation({ cancelPendingSelection: false });
|
||||
});
|
||||
},
|
||||
);
|
||||
// Vessel/installation focus flies without ever assigning a tracked entity,
|
||||
// so it cannot reach the listener above. It announces instead.
|
||||
this._removeNavigationAuthorityListener =
|
||||
@@ -116,7 +119,6 @@ export class LayerBindings {
|
||||
this.runImmediateNavigation('route', navigate),
|
||||
floorFn: (lat, lon) => this.services.cachedGroundFloor(lat, lon),
|
||||
warmFn: (cells) => this.services.warmGroundFloor(cells),
|
||||
showToast: (message) => this._showToast(message),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
// src/ui/layerFinder.test.mjs — the Data Layers finder and section index work
|
||||
// on the rows LayerRows renders: search, the On/Off and category filter,
|
||||
// Escape, the clear request voice sends, and the group ticks.
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createApp, h, nextTick } from 'vue';
|
||||
import LayerFinder, {
|
||||
LAYER_FINDER_CLEAR_EVENT,
|
||||
} from './views/panels/LayerFinder.vue';
|
||||
import LayerSectionIndex from './views/panels/LayerSectionIndex.vue';
|
||||
|
||||
const ROWS = [
|
||||
{ group: 'movement', heading: 'Movement' },
|
||||
{ id: 'flights', name: 'Live Flights', english: 'Live Flights', on: true },
|
||||
{ id: 'ships', name: 'Ships', english: 'Ships', on: false },
|
||||
{ group: 'weather', heading: 'Weather' },
|
||||
{ id: 'radar', name: 'Radar météo', english: 'Weather Radar', on: false },
|
||||
];
|
||||
|
||||
const flush = async () => {
|
||||
await nextTick();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await nextTick();
|
||||
};
|
||||
|
||||
function fixture(t) {
|
||||
document.body.replaceChildren();
|
||||
// Frames run at once, so the observers' batching does not hold a test up.
|
||||
globalThis.requestAnimationFrame = (fn) => setTimeout(fn, 0);
|
||||
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
|
||||
const panel = document.body.appendChild(document.createElement('section'));
|
||||
panel.id = 'data-panel';
|
||||
const header = panel.appendChild(document.createElement('div'));
|
||||
const bar = panel.appendChild(document.createElement('div'));
|
||||
const list = panel.appendChild(document.createElement('div'));
|
||||
list.id = 'data-toggles';
|
||||
for (const row of ROWS) {
|
||||
if (row.heading) {
|
||||
const heading = list.appendChild(document.createElement('h3'));
|
||||
heading.className = 'data-layer-group-heading';
|
||||
heading.dataset.group = row.group;
|
||||
heading.textContent = row.heading;
|
||||
continue;
|
||||
}
|
||||
const el = list.appendChild(document.createElement('div'));
|
||||
el.className = 'data-toggle-row';
|
||||
el.dataset.layerId = row.id;
|
||||
el.dataset.layerName = row.english;
|
||||
el.innerHTML = `<span class="data-name">${row.name}</span><button class="data-toggle-btn${row.on ? ' active' : ''}"></button>`;
|
||||
}
|
||||
const index = panel.appendChild(document.createElement('div'));
|
||||
const apps = [
|
||||
createApp(() => h(LayerFinder, { part: 'buttons' })),
|
||||
createApp(() => h(LayerFinder, { part: 'bar' })),
|
||||
createApp(LayerSectionIndex),
|
||||
];
|
||||
apps[0].mount(header);
|
||||
apps[1].mount(bar);
|
||||
apps[2].mount(index);
|
||||
t.after(async () => {
|
||||
document.dispatchEvent(new CustomEvent(LAYER_FINDER_CLEAR_EVENT));
|
||||
for (const app of apps) app.unmount();
|
||||
});
|
||||
const shown = () =>
|
||||
[...list.querySelectorAll('.data-toggle-row:not(.is-filtered)')].map(
|
||||
(row) => row.dataset.layerId,
|
||||
);
|
||||
const search = async (text) => {
|
||||
if (!document.getElementById('layer-finder-input')) {
|
||||
document.getElementById('layer-finder-search-btn').click();
|
||||
await flush();
|
||||
}
|
||||
const input = document.getElementById('layer-finder-input');
|
||||
input.value = text;
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await flush();
|
||||
};
|
||||
const openFilter = async () => {
|
||||
document.querySelector('[aria-controls="layer-finder-menu"]').click();
|
||||
await flush();
|
||||
return document.getElementById('layer-finder-menu');
|
||||
};
|
||||
return { list, panel, shown, search, openFilter };
|
||||
}
|
||||
|
||||
test('search finds a layer by the name on screen or its English name', async (t) => {
|
||||
const { shown, search, list } = fixture(t);
|
||||
await search('météo');
|
||||
assert.deepEqual(shown(), ['radar']);
|
||||
await search('weather radar');
|
||||
assert.deepEqual(shown(), ['radar']);
|
||||
// The Movement heading has no rows left, so it is hidden too.
|
||||
assert.equal(
|
||||
list
|
||||
.querySelector('[data-group="movement"]')
|
||||
.classList.contains('is-filtered'),
|
||||
true,
|
||||
);
|
||||
await search('nothing like it');
|
||||
assert.deepEqual(shown(), []);
|
||||
assert.match(
|
||||
document.querySelector('.layer-finder__empty')?.textContent || '',
|
||||
/No layers match/,
|
||||
);
|
||||
});
|
||||
|
||||
test('On and Off follow whether the layer is enabled', async (t) => {
|
||||
const { shown, openFilter } = fixture(t);
|
||||
const menu = await openFilter();
|
||||
const on = [...menu.querySelectorAll('button')].find((b) =>
|
||||
b.textContent.trim().endsWith('On'),
|
||||
);
|
||||
on.click();
|
||||
await flush();
|
||||
assert.deepEqual(shown(), ['flights']);
|
||||
assert.equal(on.getAttribute('aria-pressed'), 'true');
|
||||
});
|
||||
|
||||
test('a chosen category survives its heading being translated', async (t) => {
|
||||
const { shown, openFilter, list } = fixture(t);
|
||||
const menu = await openFilter();
|
||||
[...menu.querySelectorAll('button')]
|
||||
.find((b) => b.textContent.trim().endsWith('Weather'))
|
||||
.click();
|
||||
await flush();
|
||||
assert.deepEqual(shown(), ['radar']);
|
||||
list.querySelector('[data-group="weather"]').textContent = 'Météo';
|
||||
await flush();
|
||||
assert.deepEqual(shown(), ['radar']);
|
||||
assert.match(
|
||||
document.querySelector('.layer-finder__chip').textContent,
|
||||
/Météo/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Escape in the search field closes it without reaching the panel', async (t) => {
|
||||
const { search, panel } = fixture(t);
|
||||
let reached = false;
|
||||
panel.addEventListener('keydown', () => (reached = true));
|
||||
await search('ships');
|
||||
document
|
||||
.getElementById('layer-finder-input')
|
||||
.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
|
||||
);
|
||||
await flush();
|
||||
assert.equal(reached, false);
|
||||
assert.equal(document.getElementById('layer-finder-input') === null, true);
|
||||
assert.equal(document.activeElement?.id, 'layer-finder-search-btn');
|
||||
});
|
||||
|
||||
test('the filter menu takes focus, moves with the arrows and closes on Escape', async (t) => {
|
||||
const { openFilter } = fixture(t);
|
||||
const menu = await openFilter();
|
||||
const buttons = [...menu.querySelectorAll('button')];
|
||||
assert.equal(document.activeElement, buttons[0]);
|
||||
menu.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }),
|
||||
);
|
||||
assert.equal(document.activeElement, buttons[1]);
|
||||
menu.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'End', bubbles: true }),
|
||||
);
|
||||
assert.equal(document.activeElement, buttons.at(-1));
|
||||
menu.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
|
||||
);
|
||||
await flush();
|
||||
assert.equal(document.getElementById('layer-finder-menu') === null, true);
|
||||
assert.equal(
|
||||
document.activeElement,
|
||||
document.querySelector('[aria-controls="layer-finder-menu"]'),
|
||||
);
|
||||
});
|
||||
|
||||
test('a clear request shows every row again', async (t) => {
|
||||
const { shown, search } = fixture(t);
|
||||
await search('ships');
|
||||
assert.deepEqual(shown(), ['ships']);
|
||||
document.dispatchEvent(new CustomEvent(LAYER_FINDER_CLEAR_EVENT));
|
||||
await flush();
|
||||
assert.deepEqual(shown(), ['flights', 'ships', 'radar']);
|
||||
});
|
||||
|
||||
test('the section index has a tick per group and drops filtered groups', async (t) => {
|
||||
const { search } = fixture(t);
|
||||
await flush();
|
||||
assert.equal(
|
||||
document.querySelectorAll('.layer-section-index__tick').length,
|
||||
2,
|
||||
);
|
||||
await search('ships');
|
||||
await flush();
|
||||
// One group left: no index.
|
||||
assert.equal(
|
||||
document.querySelectorAll('.layer-section-index__tick').length,
|
||||
0,
|
||||
);
|
||||
});
|
||||
@@ -22,9 +22,11 @@ defineProps({
|
||||
|
||||
<template>
|
||||
<template v-for="item in items" :key="item.key"
|
||||
><h3 v-if="item.heading" class="data-layer-group-heading">{{
|
||||
item.heading
|
||||
}}</h3
|
||||
><h3
|
||||
v-if="item.heading"
|
||||
class="data-layer-group-heading"
|
||||
:data-group="item.key"
|
||||
>{{ item.heading }}</h3
|
||||
><div
|
||||
v-else
|
||||
class="data-toggle-row"
|
||||
|
||||
+11
-1
@@ -60,6 +60,7 @@ export function layoutLeftPanelRail({
|
||||
stack.style.removeProperty('--left-stack-safe-bottom');
|
||||
stack.style.removeProperty('--left-stack-centered-height');
|
||||
stack.style.removeProperty('--panel-rail-offset');
|
||||
stack.style.removeProperty('--panel-rail-lift');
|
||||
stack.classList.remove('layout-exclusive');
|
||||
stack.dataset.layoutMode = 'mobile';
|
||||
settleSideAccordion({ panels, enabled: false, onCollapse });
|
||||
@@ -282,10 +283,19 @@ export function layoutLeftPanelRail({
|
||||
getComputedStyle(stack)
|
||||
.getPropertyValue?.('--panel-stack-top-pinned')
|
||||
?.trim() === '1';
|
||||
const railOffset = `${(topPinned ? 0 : safeTop - layoutTop).toFixed(1)}px`;
|
||||
// The stack itself rises by the lift below, by a different amount for a
|
||||
// tall panel than at rest; the rail takes up the difference.
|
||||
const lift = (top) => Math.min(0, obstacleSafeTop - top);
|
||||
const railOffset = `${(topPinned ? 0 : safeTop + lift(safeTop) - layoutTop - lift(layoutTop)).toFixed(1)}px`;
|
||||
if (stack.style.getPropertyValue('--panel-rail-offset') !== railOffset) {
|
||||
stack.style.setProperty('--panel-rail-offset', railOffset);
|
||||
}
|
||||
// How far the column can rise before it meets the HUD readout, so the rail
|
||||
// and any open panel sit just under it, whether or not a panel is open.
|
||||
const railLift = `${(topPinned ? 0 : lift(layoutTop)).toFixed(1)}px`;
|
||||
if (stack.style.getPropertyValue('--panel-rail-lift') !== railLift) {
|
||||
stack.style.setProperty('--panel-rail-lift', railLift);
|
||||
}
|
||||
stack.style.removeProperty('--left-stack-centered-height');
|
||||
for (const panel of panels)
|
||||
panel.style.removeProperty('--left-panel-allocated-height');
|
||||
|
||||
@@ -340,12 +340,12 @@ test('the provider settings corner shows the picker only while the shell publish
|
||||
app.mount(host);
|
||||
t.after(() => app.unmount());
|
||||
const store = useLocaleStore(pinia);
|
||||
assert.equal(document.getElementById('locale-picker'), null);
|
||||
assert.equal(document.getElementById('locale-picker') === null, true);
|
||||
store.publishPicker({ current: 'de', onSelect() {} });
|
||||
await nextTick();
|
||||
const code = document.querySelector('#corner-actions .locale-picker-code');
|
||||
assert.equal(code?.textContent, 'DE');
|
||||
store.publishPicker(null);
|
||||
await nextTick();
|
||||
assert.equal(document.getElementById('locale-picker'), null);
|
||||
assert.equal(document.getElementById('locale-picker') === null, true);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { findCamera } from '../render/rendererOf.js';
|
||||
import { stopFollowing } from '../data/followed.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createStateChannel } from '../app/stateChannel.js';
|
||||
import { LocationControls } from './location.js';
|
||||
@@ -367,9 +368,10 @@ export class LocationNavigation {
|
||||
} catch {
|
||||
/* best-effort release */
|
||||
}
|
||||
this.viewer.trackedEntity = undefined;
|
||||
this.viewer.camera.cancelFlight();
|
||||
this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
|
||||
stopFollowing(this.viewer);
|
||||
const camera = findCamera(this.viewer);
|
||||
camera?.cancelFlight();
|
||||
camera?.release();
|
||||
this._beginWorldJumpTransition();
|
||||
|
||||
let resolveReset;
|
||||
@@ -384,15 +386,19 @@ export class LocationNavigation {
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
this._endWorldJumpTransition();
|
||||
const carto = this.viewer.camera.positionCartographic;
|
||||
const pose = findCamera(this.viewer)?.pose();
|
||||
const result = {
|
||||
ok: !cancelled,
|
||||
action: 'zoom_to_globe',
|
||||
cancelled,
|
||||
heightKm: Math.round(GLOBE_VIEW.heightM / 1000),
|
||||
centeredOn: {
|
||||
latitude: Number(Cesium.Math.toDegrees(carto.latitude).toFixed(2)),
|
||||
longitude: Number(Cesium.Math.toDegrees(carto.longitude).toFixed(2)),
|
||||
latitude: Number.isFinite(pose?.lat)
|
||||
? Number(pose.lat.toFixed(2))
|
||||
: null,
|
||||
longitude: Number.isFinite(pose?.lon)
|
||||
? Number(pose.lon.toFixed(2))
|
||||
: null,
|
||||
},
|
||||
};
|
||||
this._publishGlobeResetting?.(false);
|
||||
@@ -402,7 +408,7 @@ export class LocationNavigation {
|
||||
};
|
||||
this._cancelGlobeReset = () => finish(true);
|
||||
timer = window.setTimeout(() => {
|
||||
const height = this.viewer.camera.positionCartographic?.height;
|
||||
const height = findCamera(this.viewer)?.pose().height;
|
||||
finish(
|
||||
!Number.isFinite(height) ||
|
||||
Math.abs(height - GLOBE_VIEW.heightM) > 1000,
|
||||
|
||||
@@ -368,7 +368,8 @@ export function initMobileShell({
|
||||
: sheet === 'search'
|
||||
? [dock]
|
||||
: sheet === 'more'
|
||||
? [element('right-context-rail'), dock]
|
||||
? // Visual lives in the left stack; the dock holds the presets.
|
||||
[element('left-panel-stack'), dock]
|
||||
: [element('right-context-rail')];
|
||||
return roots.find((root) => root?.contains(target));
|
||||
};
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
nextSheet,
|
||||
sheetForPanelId,
|
||||
} from './mobileShell.js';
|
||||
import { withEntityRecord } from '../data/entityRecords.js';
|
||||
|
||||
function element(tag, document) {
|
||||
const node = new EventTarget();
|
||||
@@ -623,7 +624,7 @@ test('the phone shell keeps the required attribution visible', () => {
|
||||
);
|
||||
const openDock = rule('body.mobile-shell[data-mobile-sheet] #command-dock');
|
||||
const railSheet = rule(
|
||||
"body.mobile-shell[data-mobile-sheet='more'] #right-context-rail",
|
||||
"body.mobile-shell[data-mobile-sheet='more'] #left-panel-stack",
|
||||
);
|
||||
assert.ok(z(sheetCredit) > z(openDock));
|
||||
assert.ok(z(sheetCredit) > z(railSheet));
|
||||
@@ -824,7 +825,7 @@ test('the tab-open callback reports only a successful manual opening', () => {
|
||||
test('manual Context opens the existing transaction without disabling the tracked aircraft', async () => {
|
||||
const calls = [];
|
||||
const tracked = { layerId: 'flights', icao24: 'abc123', callsign: 'EJA225' };
|
||||
const viewer = { trackedEntity: { gevTrackedId: 'flights:abc123' } };
|
||||
const viewer = { trackedEntity: withEntityRecord({}, { trackedId: 'flights:abc123' }) };
|
||||
const entity = viewer.trackedEntity;
|
||||
const enabled = new Set(['flights', 'weather']);
|
||||
const controls = new ContextControls({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { findCamera } from '../render/rendererOf.js';
|
||||
import { stopFollowing } from '../data/followed.js';
|
||||
import { cancelCameraArrival } from '../data/cameraArrival.js';
|
||||
import { createStateChannel } from '../app/stateChannel.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
beginDeferredNavigation,
|
||||
reassertNavigationHandoff,
|
||||
@@ -176,12 +177,13 @@ export class NavigationController {
|
||||
} catch {
|
||||
/* best-effort release */
|
||||
}
|
||||
this.viewer.trackedEntity = undefined;
|
||||
stopFollowing(this.viewer);
|
||||
this.interruptCameraMotion('explicit-navigation');
|
||||
this.stopOrbit();
|
||||
if (!preserveCameraFlight) this.viewer.camera.cancelFlight();
|
||||
const camera = findCamera(this.viewer);
|
||||
if (!preserveCameraFlight) camera?.cancelFlight();
|
||||
try {
|
||||
this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
|
||||
camera?.release();
|
||||
} catch {
|
||||
/* teardown race */
|
||||
}
|
||||
@@ -215,7 +217,7 @@ export class NavigationController {
|
||||
release: () => {
|
||||
this.interruptCameraMotion('camera-orientation');
|
||||
this.stopOrbit();
|
||||
this.viewer.camera.cancelFlight();
|
||||
findCamera(this.viewer)?.cancelFlight();
|
||||
},
|
||||
navigate,
|
||||
});
|
||||
|
||||
+13
-14
@@ -1,7 +1,7 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale, t as translate } from '../i18n/index.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { createNewsPanel } from './newsPanel.js';
|
||||
import {
|
||||
NEWS_CATEGORIES,
|
||||
@@ -157,7 +157,7 @@ test('the panel shows the last 24 h as event cards and opens once', () => {
|
||||
assert.equal(img.getAttribute('referrerpolicy'), 'no-referrer');
|
||||
assert.equal(first.querySelector('.news-card__credit').textContent, 'A');
|
||||
// A lone report has no picture.
|
||||
assert.equal(second.querySelector('.news-card__thumb'), null);
|
||||
assert.equal(second.querySelector('.news-card__thumb') === null, true);
|
||||
// A later update does not reopen a panel the reader collapsed.
|
||||
panel.classList.add('collapsed');
|
||||
news.update(view());
|
||||
@@ -193,8 +193,8 @@ test('a card click flies there; open, it links the source and closes', () => {
|
||||
test('filters, the Local section and empty or failed reads', () => {
|
||||
const { news, panel, calls } = fixture();
|
||||
news.update(view());
|
||||
assert.equal(panel.querySelector('[aria-label="Local"]'), null);
|
||||
assert.equal(panel.querySelector('.news-toggle'), null);
|
||||
assert.equal(panel.querySelector('[aria-label="Local"]') === null, true);
|
||||
assert.equal(panel.querySelector('.news-toggle') === null, true);
|
||||
const severity = panel.querySelector('select[aria-label="Severity"]');
|
||||
assert.equal(severity.value, '2');
|
||||
severity.value = '3';
|
||||
@@ -215,7 +215,7 @@ test('filters, the Local section and empty or failed reads', () => {
|
||||
panel.textContent,
|
||||
/No news matches these filters in the last 24 h/,
|
||||
);
|
||||
assert.equal(panel.querySelector('.news-readout__footer button'), null);
|
||||
assert.equal(panel.querySelector('.news-readout__footer button') === null, true);
|
||||
|
||||
// Local: no hotspot chips or severity floor, and its own empty states.
|
||||
const localView = (inView) =>
|
||||
@@ -226,9 +226,9 @@ test('filters, the Local section and empty or failed reads', () => {
|
||||
news.update(localView({ active: false }));
|
||||
const section = panel.querySelector('[aria-label="Local"]');
|
||||
assert.match(section.textContent, /Zoom in to see local news/);
|
||||
assert.equal(panel.querySelector('[data-chip-id="ua-ru-war"]'), null);
|
||||
assert.equal(panel.querySelector('select[aria-label="Severity"]'), null);
|
||||
assert.equal(panel.querySelector('[aria-label="Latest news"]'), null);
|
||||
assert.equal(panel.querySelector('[data-chip-id="ua-ru-war"]') === null, true);
|
||||
assert.equal(panel.querySelector('select[aria-label="Severity"]') === null, true);
|
||||
assert.equal(panel.querySelector('[aria-label="Latest news"]') === null, true);
|
||||
assert.equal(document.getElementById('news-panel-count').textContent, '0');
|
||||
news.update(
|
||||
localView({ active: true, items: [feedCardView(report('near'), NOW)] }),
|
||||
@@ -321,7 +321,7 @@ test('a card credits the service its report came through', () => {
|
||||
credited.querySelector('.news-card__via').textContent,
|
||||
'via GDELT Project',
|
||||
);
|
||||
assert.equal(own.querySelector('.news-card__via'), null);
|
||||
assert.equal(own.querySelector('.news-card__via') === null, true);
|
||||
news.destroy();
|
||||
});
|
||||
|
||||
@@ -371,7 +371,7 @@ test('scrolling to the end asks once per page, again after a filter change or a
|
||||
test('the window choice offers shorter windows; the longest is the server window', () => {
|
||||
const { news, panel, calls } = fixture();
|
||||
news.update(view({ windowHours: 12, windowChoices: [12, 6, 3, 1] }));
|
||||
assert.equal(panel.querySelector('.news-readout__window'), null);
|
||||
assert.equal(panel.querySelector('.news-readout__window') === null, true);
|
||||
const choice = panel.querySelector('select[aria-label="Time window"]');
|
||||
assert.deepEqual(
|
||||
[...choice.options].map((option) => option.textContent),
|
||||
@@ -425,13 +425,12 @@ test('the time window agrees with its number of hours', (t) => {
|
||||
news.destroy();
|
||||
});
|
||||
|
||||
test('the Latest news heading is worded apart from the timeline button (fr)', (t) => {
|
||||
test('the Latest news heading agrees with the news it heads (fr)', (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
setLocale('fr');
|
||||
const { news, panel } = fixture();
|
||||
news.update(view());
|
||||
assert.equal(panel.querySelector('.news-readout__head').textContent, 'Dernières');
|
||||
assert.equal(translate('Latest'), 'Dernière', 'the timeline keeps its own');
|
||||
news.destroy();
|
||||
});
|
||||
|
||||
@@ -460,7 +459,7 @@ test('a clip waits behind its picture and plays, on request, in the open card',
|
||||
news.update(view({ items: [feedCardView(clipped, NOW)] }));
|
||||
const card = panel.querySelector('.news-card');
|
||||
assert.equal(card.querySelector('.news-card__play').textContent, '▶');
|
||||
assert.equal(card.querySelector('video'), null);
|
||||
assert.equal(card.querySelector('video') === null, true);
|
||||
news.update(
|
||||
view({
|
||||
items: [feedCardView(clipped, NOW)],
|
||||
@@ -486,6 +485,6 @@ test('a clip waits behind its picture and plays, on request, in the open card',
|
||||
selected: feedCardView(clipped, NOW),
|
||||
}),
|
||||
);
|
||||
assert.equal(panel.querySelector('.news-card.is-open video'), null);
|
||||
assert.equal(panel.querySelector('.news-card.is-open video') === null, true);
|
||||
news.destroy();
|
||||
});
|
||||
@@ -141,6 +141,7 @@ test("UiPanel draws Core's panel markup and asks for the other state", async (t)
|
||||
'demo-badge',
|
||||
'panel-divider',
|
||||
'demo-action',
|
||||
'panel-edge-btn',
|
||||
'panel-collapse-btn',
|
||||
],
|
||||
);
|
||||
@@ -165,8 +166,8 @@ test('UiPanel without collapsible has no button, and glow is optional', (t) => {
|
||||
});
|
||||
const panel = document.getElementById('plain-panel');
|
||||
assert.equal(panel.tagName, 'SECTION');
|
||||
assert.equal(panel.querySelector('.panel-glow'), null);
|
||||
assert.equal(panel.querySelector('.panel-collapse-btn'), null);
|
||||
assert.equal(panel.querySelector('.panel-glow') === null, true);
|
||||
assert.equal(panel.querySelector('.panel-collapse-btn') === null, true);
|
||||
});
|
||||
|
||||
test('RailPanel follows the store, forwards clicks, and never restores a class its owner removed', async (t) => {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { ref } from 'vue';
|
||||
|
||||
// Panels can slide over their rail to the screen edge, one setting per side:
|
||||
// the left column moves onto the left rail, the right column onto the right
|
||||
// rail. Each panel header has the switch (UiPanelEdge); the choice is kept
|
||||
// for the next visit and shows as a body class the stylesheet reads.
|
||||
const KEY = 'gev.panelEdge';
|
||||
function read() {
|
||||
try {
|
||||
const saved = JSON.parse(globalThis.localStorage?.getItem(KEY) || '{}');
|
||||
return { left: saved.left === true, right: saved.right === true };
|
||||
} catch {
|
||||
return { left: false, right: false };
|
||||
}
|
||||
}
|
||||
|
||||
export const panelEdge = ref(read());
|
||||
|
||||
function apply() {
|
||||
const body = globalThis.document?.body;
|
||||
if (!body) return;
|
||||
body.classList.toggle('panels-edge-left', panelEdge.value.left);
|
||||
body.classList.toggle('panels-edge-right', panelEdge.value.right);
|
||||
}
|
||||
apply();
|
||||
|
||||
/** Which side a panel element sits on, from the column it is in. */
|
||||
export function panelSide(element) {
|
||||
return element?.closest?.('#right-context-rail, #cockpit-utility-controls')
|
||||
? 'right'
|
||||
: 'left';
|
||||
}
|
||||
|
||||
export function togglePanelEdge(side) {
|
||||
panelEdge.value = { ...panelEdge.value, [side]: !panelEdge.value[side] };
|
||||
try {
|
||||
globalThis.localStorage?.setItem(KEY, JSON.stringify(panelEdge.value));
|
||||
} catch {
|
||||
// Without storage the choice lasts for this visit.
|
||||
}
|
||||
apply();
|
||||
}
|
||||
@@ -27,6 +27,7 @@ const LEFT_STACK_OBSTACLE_SELECTOR = [
|
||||
'#cockpit-context',
|
||||
'#cesium-credits .cesium-credit-logoContainer',
|
||||
'#cesium-credits .cesium-credit-textContainer',
|
||||
'#gev-credits',
|
||||
'#location-bar',
|
||||
'#control-panel',
|
||||
'#gev-voice-control',
|
||||
@@ -58,6 +59,7 @@ const RIGHT_STACK_OBSTACLE_SELECTOR = [
|
||||
'#cockpit-signal-stream',
|
||||
'#cesium-credits .cesium-credit-logoContainer',
|
||||
'#cesium-credits .cesium-credit-textContainer',
|
||||
'#gev-credits',
|
||||
'#command-dock',
|
||||
'#gev-voice-control',
|
||||
'#world-timeline',
|
||||
@@ -189,7 +191,11 @@ export class PanelLayoutController {
|
||||
const stack = this._rightPanelStack;
|
||||
if (!stack || !this._ppToggles) return;
|
||||
|
||||
stack.prepend(this._ppToggles);
|
||||
// Visual (presets and display settings) is the last panel of the left
|
||||
// column, after the other tools, and opens from the left rail like them.
|
||||
if (typeof this._leftPanelStack?.append === 'function')
|
||||
this._leftPanelStack.append(this._ppToggles);
|
||||
else stack.prepend(this._ppToggles);
|
||||
const globalContextPanel = document.getElementById('global-context-panel');
|
||||
for (const panel of [
|
||||
this._cctvPanel,
|
||||
@@ -201,6 +207,9 @@ export class PanelLayoutController {
|
||||
if (!panel) continue;
|
||||
stack.insertBefore(panel, globalContextPanel);
|
||||
}
|
||||
// Context leads the right column: it is the panel for whatever is picked,
|
||||
// and the camera panels follow it.
|
||||
if (globalContextPanel) stack.prepend(globalContextPanel);
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
this._rightStackResizeObserver = new ResizeObserver(() => {
|
||||
this._scheduleRightPanelLayout();
|
||||
@@ -345,12 +354,13 @@ export class PanelLayoutController {
|
||||
attributeFilter: ['class', 'data-variant'],
|
||||
});
|
||||
}
|
||||
const credits = document.getElementById('cesium-credits');
|
||||
if (credits) {
|
||||
this._leftStackMutationObserver.observe(credits, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
});
|
||||
for (const id of ['cesium-credits', 'gev-credits']) {
|
||||
const credits = document.getElementById(id);
|
||||
if (credits)
|
||||
this._leftStackMutationObserver.observe(credits, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,9 +6,20 @@
|
||||
* @returns {number} Natural height in CSS pixels.
|
||||
*/
|
||||
export function measurePanelNaturalHeight(panel, getComputedStyle) {
|
||||
const inner = [...panel.children].find(
|
||||
const content = [...panel.children].filter(
|
||||
(child) => !child.classList.contains('panel-glow'),
|
||||
);
|
||||
// A panel built as a header row and a body (Visual) scrolls as a whole, so
|
||||
// its full scroll height is its natural height.
|
||||
if (content.length > 1) {
|
||||
const panelStyle = getComputedStyle(panel);
|
||||
return Math.ceil(
|
||||
panel.scrollHeight +
|
||||
(parseFloat(panelStyle.borderTopWidth) || 0) +
|
||||
(parseFloat(panelStyle.borderBottomWidth) || 0),
|
||||
);
|
||||
}
|
||||
const inner = content[0];
|
||||
if (!inner)
|
||||
return Math.ceil(
|
||||
panel.scrollHeight || panel.getBoundingClientRect().height,
|
||||
|
||||
@@ -9,7 +9,7 @@ export const PANEL_RAIL_FALLBACK_ICON = 'more_horiz';
|
||||
/**
|
||||
* How each side panel appears on its rail. Labels are the panels' own titles.
|
||||
* `shownBy` names a class the panel needs to be shown at all (`f` toggles
|
||||
* Data Layers' `active`).
|
||||
* Data Layers' `active`). `context` is the label's translation context.
|
||||
*/
|
||||
export const PANEL_RAIL_ITEMS = Object.freeze({
|
||||
'data-panel': {
|
||||
@@ -19,7 +19,9 @@ export const PANEL_RAIL_ITEMS = Object.freeze({
|
||||
},
|
||||
'utilities-panel': { icon: 'handyman', label: msg('UTILITIES') },
|
||||
'scene-panel': { icon: 'movie', label: msg('AUTHORING') },
|
||||
'pp-toggles': { icon: 'tune', label: msg('DISPLAY') },
|
||||
// `context` keeps the panel's name apart from the satellite class of the
|
||||
// same English word.
|
||||
'pp-toggles': { icon: 'palette', label: msg('VISUAL'), context: 'panel' },
|
||||
'cctv-panel': { icon: 'videocam', label: msg('CCTV') },
|
||||
'weather-panel': { icon: 'partly_cloudy_day', label: msg('WEATHER') },
|
||||
'news-panel': { icon: 'public', label: msg('NEWS') },
|
||||
|
||||
@@ -359,14 +359,23 @@ test('right rail aligns to the left rail buttons while the left stack is offset'
|
||||
assert.equal(f.stack.dataset.safeTop, '286.7');
|
||||
});
|
||||
|
||||
test('left rail buttons hold still while a tall panel moves the stack', () => {
|
||||
test('left rail buttons hold still whether the open panel is short or tall', () => {
|
||||
// Where the rail sits: the stack's top, the stack's rise, and the rail's
|
||||
// own offset inside the stack.
|
||||
const railTop = (stack) =>
|
||||
(parseFloat(stack.style.getPropertyValue('--left-stack-safe-top')) * 900) /
|
||||
100 +
|
||||
parseFloat(stack.style.getPropertyValue('--panel-rail-lift')) +
|
||||
parseFloat(stack.style.getPropertyValue('--panel-rail-offset'));
|
||||
const short = fixture('left');
|
||||
short.expand(short.first, 250);
|
||||
short.run();
|
||||
const f = fixture('left');
|
||||
f.expand(f.first, 900);
|
||||
f.run();
|
||||
assert.equal(f.stack.dataset.layoutMode, 'focus');
|
||||
assert.ok(
|
||||
parseFloat(f.stack.style.getPropertyValue('--panel-rail-offset')) > 0,
|
||||
);
|
||||
assert.notEqual(short.stack.dataset.layoutMode, 'focus');
|
||||
assert.ok(Math.abs(railTop(f.stack) - railTop(short.stack)) < 0.2);
|
||||
|
||||
// A theme that pins the stack's top (Cyber) leaves nothing to offset.
|
||||
f.stack.computed.getPropertyValue = (name) =>
|
||||
@@ -447,13 +456,17 @@ test('natural height includes visible content, margins and wrapper chrome, exclu
|
||||
// Outside measurement, CCTV is 391 px in focus and 629 px in normal mode;
|
||||
// Removing only the allocation leaves focus CSS active: its next reading is
|
||||
// 422 px, so the old decision exits focus and then re-enters on the 629 px read.
|
||||
function thrashingRightRail({ focused = false, weatherOpen = false } = {}) {
|
||||
function thrashingRightRail({
|
||||
focused = false,
|
||||
weatherOpen = false,
|
||||
tallId = 'cctv-panel',
|
||||
} = {}) {
|
||||
const f = fixture('right');
|
||||
f.options.windowRef.innerHeight = 920;
|
||||
f.options.leftStack.rect.top = 439.6;
|
||||
f.stack.computed.rowGap = '8px';
|
||||
const display = element('pp-toggles', { collapsed: true });
|
||||
const cctv = element('cctv-panel', { height: 629 });
|
||||
const cctv = element(tallId, { height: 629 });
|
||||
const weather = element('weather-panel', {
|
||||
height: 444,
|
||||
collapsed: !weatherOpen,
|
||||
@@ -524,8 +537,10 @@ for (const focused of [false, true]) {
|
||||
});
|
||||
}
|
||||
|
||||
// The hysteresis applies to panels that size to their content; CCTV and
|
||||
// Context take the column's full height whenever they are open.
|
||||
test('right rail keeps focus through 30 px content growth inside the hysteresis band', () => {
|
||||
const f = thrashingRightRail();
|
||||
const f = thrashingRightRail({ tallId: 'news-panel' });
|
||||
f.run();
|
||||
// Header + gap contribute 52 px: need moves 420 -> 450 -> 420.
|
||||
for (const height of [368, 398, 368, 398, 368]) {
|
||||
@@ -542,7 +557,7 @@ test('right rail keeps focus through 30 px content growth inside the hysteresis
|
||||
});
|
||||
|
||||
test('right rail enters focus only above available height and leaves below the full deadband', () => {
|
||||
const f = thrashingRightRail();
|
||||
const f = thrashingRightRail({ tallId: 'news-panel' });
|
||||
f.options.windowRef.innerHeight = 1000;
|
||||
f.options.leftStack.rect.top = 500;
|
||||
f.cctv.intrinsicHeight = 408; // Need equals available (460 px).
|
||||
@@ -559,6 +574,16 @@ test('right rail enters focus only above available height and leaves below the f
|
||||
assert.equal(f.stack.classList.contains('layout-focus'), false);
|
||||
});
|
||||
|
||||
test('an open CCTV panel takes the full column however short its content', () => {
|
||||
const f = thrashingRightRail();
|
||||
f.cctv.intrinsicHeight = 200;
|
||||
f.run();
|
||||
assert.equal(f.stack.classList.contains('layout-focus'), true);
|
||||
f.cctv.classList.add('collapsed');
|
||||
f.run();
|
||||
assert.equal(f.stack.classList.contains('layout-focus'), false);
|
||||
});
|
||||
|
||||
test('right rail settles a second tall panel through the accordion in one pass', () => {
|
||||
const f = thrashingRightRail({ weatherOpen: true });
|
||||
const modes = [];
|
||||
|
||||
@@ -135,8 +135,8 @@ test('the chip counts what is missing and the rows render from the status', asyn
|
||||
);
|
||||
assert.equal(field.type, 'password');
|
||||
assert.equal(field.placeholder, 'paste GOOGLE_MAPS_API_KEY');
|
||||
assert.equal(google.querySelector('.key-setup-remove'), null);
|
||||
assert.equal(google.querySelector('.key-setup-cloud-auth'), null);
|
||||
assert.equal(google.querySelector('.key-setup-remove') === null, true);
|
||||
assert.equal(google.querySelector('.key-setup-cloud-auth') === null, true);
|
||||
|
||||
const openai = $('[data-key-id="openai"]');
|
||||
assert.equal(openai.dataset.managed, 'file');
|
||||
@@ -159,7 +159,7 @@ test('the chip counts what is missing and the rows render from the status', asyn
|
||||
firms.querySelector('.key-setup-external').textContent,
|
||||
'configured externally',
|
||||
);
|
||||
assert.equal(firms.querySelector('.key-setup-fields'), null);
|
||||
assert.equal(firms.querySelector('.key-setup-fields') === null, true);
|
||||
});
|
||||
|
||||
test('the chip opens the dialog onto its first field; closing fades it and restores the status line', async (t) => {
|
||||
@@ -337,12 +337,12 @@ test('Cyber moves the chip into the top toolbar and other themes return it to th
|
||||
await wait();
|
||||
await nextTick();
|
||||
assert.equal(toolbar.lastElementChild?.id, 'key-setup-chip');
|
||||
assert.equal(corner.querySelector('#key-setup-chip'), null);
|
||||
assert.equal(corner.querySelector('#key-setup-chip') === null, true);
|
||||
document.documentElement.dataset.uiTheme = 'tactical';
|
||||
await wait();
|
||||
await nextTick();
|
||||
assert.equal(corner.firstElementChild?.id, 'key-setup-chip');
|
||||
assert.equal(toolbar.querySelector('#key-setup-chip'), null);
|
||||
assert.equal(toolbar.querySelector('#key-setup-chip') === null, true);
|
||||
delete document.documentElement.dataset.uiTheme;
|
||||
});
|
||||
|
||||
|
||||
+21
-13
@@ -1,5 +1,12 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { horizonOccluder } from '../data/iconOrientation.js';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { horizonFrom } from '../geo/horizon.js';
|
||||
import { distance } from '../geo/vector.js';
|
||||
import {
|
||||
canvasOf,
|
||||
findCamera,
|
||||
findFrame,
|
||||
findQuery,
|
||||
} from '../render/rendererOf.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
function isQuebecCamera(camera) {
|
||||
@@ -73,7 +80,7 @@ function mediaRefreshUrl(value) {
|
||||
* shows its details and the play control.
|
||||
*/
|
||||
export function createQuebecCctvOverlay(viewer) {
|
||||
if (!viewer?.scene || typeof document === 'undefined') return null;
|
||||
if (!viewer || typeof document === 'undefined') return null;
|
||||
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
@@ -170,7 +177,8 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
|
||||
function startRender() {
|
||||
if (!removeRender)
|
||||
removeRender = viewer.scene.postRender.addEventListener(updateMarker);
|
||||
removeRender =
|
||||
findFrame(viewer)?.on('postRender', () => updateMarker()) ?? null;
|
||||
}
|
||||
|
||||
function stopRender() {
|
||||
@@ -249,7 +257,7 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
if (changed || reselected) closedWindowCameraId = null;
|
||||
selected = camera;
|
||||
startRender();
|
||||
selectedPosition = Cesium.Cartesian3.fromDegrees(
|
||||
selectedPosition = fromDegrees(
|
||||
Number(camera.lon),
|
||||
Number(camera.lat),
|
||||
Number(camera.elevationM) || 10,
|
||||
@@ -331,11 +339,14 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
marker.hidden = true;
|
||||
return;
|
||||
}
|
||||
const canvas = viewer.scene.canvas;
|
||||
const point = viewer.scene.cartesianToCanvasCoordinates(selectedPosition);
|
||||
const canvas = canvasOf(viewer);
|
||||
const eye = findCamera(viewer)?.pose().position;
|
||||
const point = findQuery(viewer)?.project(selectedPosition) ?? null;
|
||||
const visible =
|
||||
point &&
|
||||
horizonOccluder(viewer.camera).isPointVisible(selectedPosition) &&
|
||||
canvas &&
|
||||
eye &&
|
||||
horizonFrom(eye).isPointVisible(selectedPosition) &&
|
||||
point.x >= 0 &&
|
||||
point.y >= 0 &&
|
||||
point.x <= canvas.clientWidth &&
|
||||
@@ -348,13 +359,10 @@ export function createQuebecCctvOverlay(viewer) {
|
||||
const rect = canvasRect;
|
||||
marker.style.left = `${rect.left + point.x}px`;
|
||||
marker.style.top = `${rect.top + point.y}px`;
|
||||
const distance = Cesium.Cartesian3.distance(
|
||||
viewer.camera.positionWC,
|
||||
selectedPosition,
|
||||
);
|
||||
const range = distance(eye, selectedPosition);
|
||||
marker.style.setProperty(
|
||||
'--qci-scale',
|
||||
String(Math.min(1, 600 / Math.max(1, distance))),
|
||||
String(Math.min(1, 600 / Math.max(1, range))),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Window } from 'happy-dom';
|
||||
import * as Cesium from 'cesium';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { createQuebecCctvOverlay } from './quebecCctvOverlay.js';
|
||||
|
||||
const MEDIA_URL =
|
||||
@@ -46,21 +48,22 @@ function mountOverlay(t, { play = () => Promise.resolve() } = {}) {
|
||||
};
|
||||
window.clearInterval = (id) => intervals.delete(id);
|
||||
const renderListeners = new Set();
|
||||
const viewer = {
|
||||
camera: {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(-73.5502, 45.51651, 1000),
|
||||
},
|
||||
scene: {
|
||||
canvas: { clientWidth: 800, clientHeight: 600 },
|
||||
cartesianToCanvasCoordinates: () => null,
|
||||
postRender: {
|
||||
addEventListener(fn) {
|
||||
renderListeners.add(fn);
|
||||
return () => renderListeners.delete(fn);
|
||||
},
|
||||
const viewer = { canvas: { clientWidth: 800, clientHeight: 600 } };
|
||||
const { unbind } = bindFakeDraw(viewer, {
|
||||
camera: fakeCameraPort({
|
||||
pose: { position: fromDegrees(-73.5502, 45.51651, 1000) },
|
||||
}).port,
|
||||
query: { project: () => null },
|
||||
frame: {
|
||||
on(phase, fn) {
|
||||
if (phase !== 'postRender') return () => {};
|
||||
renderListeners.add(fn);
|
||||
return () => renderListeners.delete(fn);
|
||||
},
|
||||
requestRender() {},
|
||||
},
|
||||
};
|
||||
});
|
||||
t.after(unbind);
|
||||
const overlay = createQuebecCctvOverlay(viewer);
|
||||
t.after(() => {
|
||||
overlay?.dispose();
|
||||
@@ -95,7 +98,11 @@ test('selecting a Québec camera contacts Québec 511 only after Play', (t) => {
|
||||
assert.equal(ui.renderListeners.size, 1);
|
||||
|
||||
ui.playButton().click();
|
||||
assert.deepEqual(ui.loads, [MEDIA_URL, MEDIA_URL], 'live player and map still');
|
||||
assert.deepEqual(
|
||||
ui.loads,
|
||||
[MEDIA_URL, MEDIA_URL],
|
||||
'live player and map still',
|
||||
);
|
||||
assert.equal(ui.playButton().hidden, true);
|
||||
assert.equal(ui.intervals.size, 1);
|
||||
|
||||
@@ -111,7 +118,11 @@ test('selecting a Québec camera contacts Québec 511 only after Play', (t) => {
|
||||
assert.equal(ui.playButton().hidden, false);
|
||||
|
||||
ui.overlay.setCamera(null);
|
||||
assert.equal(ui.renderListeners.size, 0, 'deselect drops the per-frame listener');
|
||||
assert.equal(
|
||||
ui.renderListeners.size,
|
||||
0,
|
||||
'deselect drops the per-frame listener',
|
||||
);
|
||||
});
|
||||
|
||||
test('a camera without browser media shows only its provider link', (t) => {
|
||||
@@ -155,7 +166,9 @@ test('an interrupted play() is not reported as an unavailable source', async (t)
|
||||
|
||||
test('a real play() failure is reported', async (t) => {
|
||||
const fail = () =>
|
||||
Promise.reject(new DOMException('no supported source', 'NotSupportedError'));
|
||||
Promise.reject(
|
||||
new DOMException('no supported source', 'NotSupportedError'),
|
||||
);
|
||||
const ui = mountOverlay(t, { play: fail });
|
||||
ui.overlay.setCamera(CAMERA);
|
||||
ui.playButton().click();
|
||||
@@ -188,5 +201,5 @@ test('the refresh timer reloads with a cache-buster, skips hidden tabs, and stop
|
||||
ui.overlay.dispose();
|
||||
assert.equal(ui.intervals.size, 0);
|
||||
assert.equal(ui.renderListeners.size, 0);
|
||||
assert.equal(ui.window.document.querySelector('.qci-panel'), null);
|
||||
assert.equal(ui.window.document.querySelector('.qci-panel') === null, true);
|
||||
});
|
||||
+22
-4
@@ -27,10 +27,18 @@ export function bindRadioControls() {
|
||||
this.store?.publishUtility({ ...this._cockpitDisclosure });
|
||||
if (displayOpen) this.actions.revealStyleParameters();
|
||||
if (!expanded && returnFocus) {
|
||||
(kind === 'display'
|
||||
? this._cockpitDisplayToggleBtn
|
||||
: this._cockpitRadioToggleBtn
|
||||
)?.focus({ preventScroll: true });
|
||||
// The desktop cockpit hides the launchers' toggles behind its rail, so
|
||||
// focus goes to whichever of the two is shown.
|
||||
const toggle =
|
||||
kind === 'display'
|
||||
? this._cockpitDisplayToggleBtn
|
||||
: this._cockpitRadioToggleBtn;
|
||||
const railItem = toggle?.ownerDocument?.querySelector?.(
|
||||
`[data-cockpit-rail-item="${kind}"]`,
|
||||
);
|
||||
(toggle?.getClientRects?.().length ? toggle : railItem || toggle)?.focus({
|
||||
preventScroll: true,
|
||||
});
|
||||
}
|
||||
if (
|
||||
!displayOpen &&
|
||||
@@ -444,6 +452,16 @@ export function bindRadioControls() {
|
||||
),
|
||||
toggleCockpitRadio: () =>
|
||||
setCockpitDisclosure('radio', !this._cockpitDisclosureOpen('radio')),
|
||||
/**
|
||||
* Open or close the cockpit's Display or Radio panel; opening one closes
|
||||
* the other.
|
||||
* @param {'display'|'radio'} kind
|
||||
* @param {{ returnFocus?: boolean }} [options]
|
||||
*/
|
||||
toggleCockpitUtility: (kind, { returnFocus = false } = {}) => {
|
||||
const open = !this._cockpitDisclosureOpen(kind);
|
||||
setCockpitDisclosure(kind, open, { returnFocus: !open && returnFocus });
|
||||
},
|
||||
/**
|
||||
* @param {string} filter
|
||||
* @returns {string} The station tag the filter shows afterwards.
|
||||
|
||||
@@ -1,178 +0,0 @@
|
||||
<script setup>
|
||||
import { computed, onBeforeUnmount, shallowRef, watch } from 'vue';
|
||||
import { formatUtcDayMonth, t } from '../../i18n/index.js';
|
||||
import { utcClock } from './utcClock.js';
|
||||
import UiSlider from '../kit/UiSlider.js';
|
||||
|
||||
// Stable native transport with local preview and a coalesced 150 ms drag
|
||||
// commit. While the handle is dragged the slider keeps the ticks it was
|
||||
// dragged over; the owner's updates apply once the drag ends.
|
||||
const props = defineProps({
|
||||
state: { type: Object, required: true },
|
||||
sliderClassName: { type: String, default: '' },
|
||||
heading: { type: Boolean, default: true },
|
||||
onCommit: { type: Function, default: () => {} },
|
||||
onPreview: { type: Function, default: () => {} },
|
||||
onStep: { type: Function, default: () => {} },
|
||||
onLatest: { type: Function, default: () => {} },
|
||||
onPlay: { type: Function, default: () => {} },
|
||||
});
|
||||
|
||||
const utc = (tick) =>
|
||||
Number.isFinite(Date.parse(tick))
|
||||
? `${formatUtcDayMonth(tick)} ${utcClock(tick)}`
|
||||
: '';
|
||||
|
||||
// What the slider shows: the owner's ticks, index and readout, frozen while
|
||||
// dragging.
|
||||
const shown = shallowRef({ ticks: [], index: 0, readout: '' });
|
||||
let dragging = false;
|
||||
let timer = null;
|
||||
let pending = null;
|
||||
let live = true;
|
||||
|
||||
const cancel = () => {
|
||||
if (timer !== null) clearTimeout(timer);
|
||||
timer = null;
|
||||
};
|
||||
const sync = () => {
|
||||
if (dragging) return;
|
||||
const ticks = [...props.state.ticks];
|
||||
shown.value = {
|
||||
ticks,
|
||||
index: Math.max(0, Math.min(props.state.index, ticks.length - 1)),
|
||||
readout: props.state.readout || '',
|
||||
};
|
||||
};
|
||||
watch(
|
||||
() => props.state,
|
||||
(state) => {
|
||||
if (state.disabled) {
|
||||
cancel();
|
||||
pending = null;
|
||||
dragging = false;
|
||||
}
|
||||
sync();
|
||||
},
|
||||
{ immediate: true, flush: 'sync' },
|
||||
);
|
||||
onBeforeUnmount(() => {
|
||||
live = false;
|
||||
cancel();
|
||||
});
|
||||
|
||||
const disabled = computed(() => Boolean(props.state.disabled));
|
||||
const latestActive = computed(() => props.state.mode === 'latest');
|
||||
const playing = computed(() => Boolean(props.state.playing));
|
||||
|
||||
function commit() {
|
||||
cancel();
|
||||
const value = pending;
|
||||
pending = null;
|
||||
if (live && value && !props.state.disabled)
|
||||
props.onCommit(value.tick, value.index);
|
||||
}
|
||||
function preview(event) {
|
||||
if (props.state.disabled) return;
|
||||
dragging = true;
|
||||
const index = Number(event.target.value);
|
||||
const tick = shown.value.ticks[index];
|
||||
if (!tick) return;
|
||||
pending = { tick, index };
|
||||
// Shown before the owner hears of it: an update from inside onPreview
|
||||
// must not move the handle back.
|
||||
shown.value = { ...shown.value, index };
|
||||
const readout = props.onPreview(tick, index);
|
||||
// The owner may have ended the drag (disabled) from inside onPreview.
|
||||
if (!dragging) return;
|
||||
if (typeof readout === 'string') shown.value = { ...shown.value, readout };
|
||||
if (timer === null) timer = setTimeout(commit, 150);
|
||||
}
|
||||
// The handle shows the shown index again. A drag that ends where it began
|
||||
// (an input and a cancel, or a refused commit, before the next render)
|
||||
// leaves the slider's model unchanged, so it would not render.
|
||||
const place = (input) => {
|
||||
const index = String(shown.value.index);
|
||||
if (input && input.value !== index) input.value = index;
|
||||
};
|
||||
function change(event) {
|
||||
if (props.state.disabled) return;
|
||||
const index = Number(event.target.value);
|
||||
pending = { tick: shown.value.ticks[index], index };
|
||||
dragging = false;
|
||||
commit();
|
||||
sync();
|
||||
place(event.target);
|
||||
}
|
||||
function reset(event) {
|
||||
cancel();
|
||||
pending = null;
|
||||
dragging = false;
|
||||
sync();
|
||||
place(event?.target);
|
||||
}
|
||||
function blur(event) {
|
||||
if (dragging) change(event);
|
||||
}
|
||||
const act = (fn) => {
|
||||
reset();
|
||||
if (live && !props.state.disabled) fn();
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="rail-timeline"
|
||||
><div v-if="heading" class="panel-title">{{ t('Observed history') }}</div
|
||||
><div class="rail-timeline-track"
|
||||
><button
|
||||
type="button"
|
||||
class="data-toggle-chip"
|
||||
:title="t('Earlier observation')"
|
||||
:disabled="disabled || state.index <= 0"
|
||||
@click="act(() => onStep(-1))"
|
||||
>‹</button
|
||||
><UiSlider
|
||||
:class="sliderClassName || undefined"
|
||||
min="0"
|
||||
:max="String(Math.max(0, shown.ticks.length - 1))"
|
||||
step="1"
|
||||
:model-value="String(shown.index)"
|
||||
:disabled="disabled"
|
||||
:aria-label="t('Observed history')"
|
||||
:aria-valuetext="utc(shown.ticks[shown.index])"
|
||||
@input="preview"
|
||||
@change="change"
|
||||
@pointercancel="reset"
|
||||
@blur="blur"
|
||||
/><button
|
||||
type="button"
|
||||
class="data-toggle-chip"
|
||||
:title="t('Later observation')"
|
||||
:disabled="disabled || state.index >= state.ticks.length - 1"
|
||||
@click="act(() => onStep(1))"
|
||||
>›</button
|
||||
><div class="rail-timeline-endpoints"
|
||||
><span>{{ utcClock(shown.ticks[0]) }}</span
|
||||
><span>{{ utcClock(shown.ticks.at(-1)) }}</span></div
|
||||
></div
|
||||
><div class="rail-timeline-controls"
|
||||
><button
|
||||
type="button"
|
||||
:class="`data-toggle-chip${latestActive ? ' active' : ''}`"
|
||||
:title="t('Newest frame per product')"
|
||||
:disabled="disabled"
|
||||
:aria-pressed="String(latestActive)"
|
||||
@click="act(onLatest)"
|
||||
>{{ t('Latest') }}</button
|
||||
><button
|
||||
type="button"
|
||||
:class="`data-toggle-chip${playing ? ' active' : ''}`"
|
||||
:title="t('Replay observed history')"
|
||||
:disabled="disabled"
|
||||
:aria-pressed="String(playing)"
|
||||
@click="act(onPlay)"
|
||||
>{{ playing ? t('Pause') : t('Play') }}</button
|
||||
><span class="rail-timeline-readout">{{ shown.readout }}</span></div
|
||||
></section
|
||||
>
|
||||
</template>
|
||||
@@ -0,0 +1,393 @@
|
||||
// Edge scrolling for the side rails. While the pointer is in a screen edge's
|
||||
// strip (from the edge to just past its rail), that rail's border lights up,
|
||||
// and the scroll wheel steps to the next or previous panel on that side
|
||||
// instead of zooming the globe, wrapping round at either end. The open item's
|
||||
// highlight slides between items however the panel changes, and a panel
|
||||
// opened by the wheel slides in from the direction of travel.
|
||||
|
||||
/** How far past the rail the strip reaches, in pixels. */
|
||||
const STRIP_MARGIN = 16;
|
||||
/** Wheel travel (pixels) that counts as one step. */
|
||||
const STEP_DELTA = 40;
|
||||
/**
|
||||
* A pause this long (ms) with no wheel events ends a scroll gesture. One
|
||||
* gesture moves one step, however long it runs, trackpad coasting included.
|
||||
*/
|
||||
const GESTURE_GAP_MS = 180;
|
||||
/** After a step, how long (ms) before the same motion can count as a new flick. */
|
||||
const STEP_COOLDOWN_MS = 220;
|
||||
/**
|
||||
* The least time (ms) between two steps, whatever the wheel does. A motion
|
||||
* that would step sooner waits and steps once the gap has passed (one step
|
||||
* held at most), so panels never switch back to back and no step is lost.
|
||||
*/
|
||||
const STEP_GAP_MS = 500;
|
||||
/** A wheel event this large (pixels) is a mouse wheel notch, not a trackpad. */
|
||||
const NOTCH_DELTA = 100;
|
||||
/** The widest the strip gets, measured from the screen edge, whatever shape the rail takes. */
|
||||
const STRIP_MAX = 84;
|
||||
/**
|
||||
* After a step, how long (ms) the rest of that gesture is still swallowed once
|
||||
* the pointer has left the strip, so trackpad coasting does not go on to zoom
|
||||
* the globe. Past it, the wheel belongs to whatever is under the pointer.
|
||||
*/
|
||||
const COAST_MAX_MS = 800;
|
||||
/** Pixels per wheel line, for mice that report lines rather than pixels. */
|
||||
const LINE_PX = 16;
|
||||
/**
|
||||
* Things in the strip that keep their own pointer and wheel behaviour: any
|
||||
* control, and every panel in either side's stack (a panel scrolls itself).
|
||||
*/
|
||||
const OWN_CONTROLS =
|
||||
'a, button, input, select, textarea, dialog, [role="dialog"], .ui-panel, #left-panel-stack > :not(.gev-panel-rail), #right-context-rail > :not(.gev-panel-rail), #first-run-launcher, #cesium-credits, #world-timeline';
|
||||
|
||||
/**
|
||||
* @param {Document} [doc]
|
||||
* @returns {() => void} removes the listeners and observers
|
||||
*/
|
||||
export function installRailEdgeScroll(doc = globalThis.document) {
|
||||
const win = doc?.defaultView;
|
||||
if (!doc || !win) return () => {};
|
||||
const coarse = win.matchMedia?.('(pointer: coarse)');
|
||||
|
||||
let hot = null;
|
||||
let travel = 0;
|
||||
let lastWheel = 0;
|
||||
let lastSpeed = 0;
|
||||
let stepped = false;
|
||||
/** When the last step was taken, the fastest the gesture has been, and whether it has slowed since. */
|
||||
let steppedAt = 0;
|
||||
/** A step waiting for the gap to pass, if any. */
|
||||
let heldStep = 0;
|
||||
let peakSpeed = 0;
|
||||
let slowed = false;
|
||||
let frame = 0;
|
||||
/** Set once removed, so frames already queued do nothing. */
|
||||
let removed = false;
|
||||
|
||||
// Clean view and recording hide the rails with visibility and opacity,
|
||||
// which keep their boxes, so a box alone does not mean the rail shows.
|
||||
const showing = (node) =>
|
||||
node.getBoundingClientRect().width > 0 &&
|
||||
(typeof node.checkVisibility !== 'function' ||
|
||||
node.checkVisibility({
|
||||
visibilityProperty: true,
|
||||
opacityProperty: true,
|
||||
}));
|
||||
|
||||
// Which screen edge a rail is on comes from where it is, not its name: in a
|
||||
// right-to-left language the left stack sits on the right.
|
||||
const rails = () =>
|
||||
['left', 'right']
|
||||
.map((name) => doc.querySelector(`.ui-rail--${name}`))
|
||||
.filter((rail) => rail && showing(rail))
|
||||
.map((rail) => {
|
||||
const box = rail.getBoundingClientRect();
|
||||
const middle = doc.documentElement.clientWidth / 2;
|
||||
return {
|
||||
side: box.left + box.width / 2 < middle ? 'left' : 'right',
|
||||
rail,
|
||||
};
|
||||
});
|
||||
|
||||
const items = (rail) =>
|
||||
// Only items that show: a theme or mode may hide some, and the wheel must
|
||||
// not open those.
|
||||
[...rail.querySelectorAll('.ui-rail__item')].filter(
|
||||
(item) => !item.disabled && showing(item),
|
||||
);
|
||||
|
||||
// ── The sliding highlight ──
|
||||
// Each rail draws it as a ::before under its items, placed by custom
|
||||
// properties; the open item's own background steps aside while it shows.
|
||||
// Vue rewrites a rail's class list when it folds its labels, so whether the
|
||||
// highlight is showing is kept here, and the classes are put back each time.
|
||||
const gliding = new WeakSet();
|
||||
|
||||
function glide(rail) {
|
||||
if (removed) return;
|
||||
rail.classList.toggle('ui-rail--edge-hot', rail === hot);
|
||||
const on = rail.querySelector('.ui-rail__item[aria-pressed="true"]');
|
||||
if (!on?.offsetWidth) {
|
||||
gliding.delete(rail);
|
||||
rail.classList.remove('ui-rail--glide');
|
||||
return;
|
||||
}
|
||||
const railBox = rail.getBoundingClientRect();
|
||||
const box = on.getBoundingClientRect();
|
||||
const shown = gliding.has(rail);
|
||||
// A rail opening its first panel folds its labelled pills to icons, the
|
||||
// buttons shrinking over a few frames; the highlight waits until the open
|
||||
// button is an icon again (square) rather than fading in at a pill's
|
||||
// width and then shrinking.
|
||||
if (
|
||||
!shown &&
|
||||
(rail.classList.contains('ui-rail--expanded') ||
|
||||
box.width > box.height + 2)
|
||||
)
|
||||
return;
|
||||
// Appearing from nothing: jump into place, then fade in.
|
||||
rail.classList.toggle('ui-rail--glide-jump', !shown);
|
||||
rail.style.setProperty(
|
||||
'--rail-glide-x',
|
||||
`${box.left - railBox.left - rail.clientLeft}px`,
|
||||
);
|
||||
rail.style.setProperty(
|
||||
'--rail-glide-y',
|
||||
`${box.top - railBox.top - rail.clientTop}px`,
|
||||
);
|
||||
rail.style.setProperty('--rail-glide-w', `${box.width}px`);
|
||||
rail.style.setProperty('--rail-glide-h', `${box.height}px`);
|
||||
rail.classList.add('ui-rail--glide');
|
||||
gliding.add(rail);
|
||||
if (!shown)
|
||||
win.requestAnimationFrame(() =>
|
||||
rail.classList.remove('ui-rail--glide-jump'),
|
||||
);
|
||||
}
|
||||
|
||||
// Follow the rails for a few frames after any change, as their items
|
||||
// resize while labels fold away.
|
||||
function follow(frames = 24) {
|
||||
win.cancelAnimationFrame(frame);
|
||||
let left = frames;
|
||||
const tick = () => {
|
||||
if (removed) return;
|
||||
watchRails();
|
||||
doc.querySelectorAll('.ui-rail').forEach(glide);
|
||||
if ((left -= 1) > 0) frame = win.requestAnimationFrame(tick);
|
||||
};
|
||||
tick();
|
||||
}
|
||||
|
||||
const observer =
|
||||
typeof win.MutationObserver === 'function'
|
||||
? new win.MutationObserver((records) => {
|
||||
// A rail item opened or closed. Nothing here writes aria-pressed,
|
||||
// and the work waits for the next frame, so this never feeds itself.
|
||||
if (
|
||||
records.some((record) =>
|
||||
record.target.classList?.contains('ui-rail__item'),
|
||||
)
|
||||
)
|
||||
win.requestAnimationFrame(() => follow());
|
||||
})
|
||||
: null;
|
||||
observer?.observe(doc.body, {
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ['aria-pressed'],
|
||||
});
|
||||
|
||||
// A rail also changes shape with nothing pressed or released: hidden and
|
||||
// shown again (Context docked and undocked), or turned from a column to a
|
||||
// row (panels moved to the screen edge). Its highlight is placed again
|
||||
// whenever its size changes, so it is never left where an icon was.
|
||||
const sized =
|
||||
typeof win.ResizeObserver === 'function'
|
||||
? new win.ResizeObserver(() => follow(2))
|
||||
: null;
|
||||
const watched = new WeakSet();
|
||||
const watchRails = () => {
|
||||
if (!sized) return;
|
||||
doc.querySelectorAll('.ui-rail').forEach((rail) => {
|
||||
if (watched.has(rail)) return;
|
||||
watched.add(rail);
|
||||
sized.observe(rail);
|
||||
});
|
||||
};
|
||||
watchRails();
|
||||
|
||||
// ── The edge strip ──
|
||||
/** The rail whose strip holds the point, unless a control there owns it. */
|
||||
function railAt(x, target) {
|
||||
if (doc.body.classList.contains('mobile-shell') || coarse?.matches)
|
||||
return null;
|
||||
for (const { side, rail } of rails()) {
|
||||
const box = rail.getBoundingClientRect();
|
||||
// From the screen edge to just past the rail, but never wider than a
|
||||
// rail's own column: a rail laid out as a row across the top of its
|
||||
// panels would otherwise claim most of the panel's width.
|
||||
const width = doc.documentElement.clientWidth;
|
||||
const inStrip =
|
||||
side === 'left'
|
||||
? x <= Math.min(box.right + STRIP_MARGIN, STRIP_MAX)
|
||||
: x >= Math.max(box.left - STRIP_MARGIN, width - STRIP_MAX);
|
||||
if (!inStrip) continue;
|
||||
if (rail.contains(target)) return rail;
|
||||
if (target?.closest?.(OWN_CONTROLS)) return null;
|
||||
return rail;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function setHot(rail) {
|
||||
if (rail === hot) return;
|
||||
// A held step belongs to the strip it was made in; leaving drops it, so
|
||||
// coming back later does not set it off with no wheel turned.
|
||||
if (heldStep) {
|
||||
win.clearTimeout(heldStep);
|
||||
heldStep = 0;
|
||||
}
|
||||
hot?.classList.remove('ui-rail--edge-hot');
|
||||
hot = rail;
|
||||
travel = 0;
|
||||
hot?.classList.add('ui-rail--edge-hot');
|
||||
follow(2);
|
||||
}
|
||||
|
||||
function onMove(event) {
|
||||
setHot(railAt(event.clientX, event.target));
|
||||
}
|
||||
|
||||
function onLeave(event) {
|
||||
if (!event.relatedTarget) setHot(null);
|
||||
}
|
||||
|
||||
function step(direction) {
|
||||
const list = items(hot);
|
||||
if (!list.length) return;
|
||||
const current = list.findIndex(
|
||||
(item) => item.getAttribute('aria-pressed') === 'true',
|
||||
);
|
||||
// Past either end, carry on from the other.
|
||||
const nextIndex =
|
||||
current < 0
|
||||
? direction > 0
|
||||
? 0
|
||||
: list.length - 1
|
||||
: (current + direction + list.length) % list.length;
|
||||
if (nextIndex === current) return;
|
||||
const target = list[nextIndex];
|
||||
target.click();
|
||||
const panel = doc.getElementById(target.dataset.railItem);
|
||||
if (panel) {
|
||||
panel.classList.remove('rail-switch-down', 'rail-switch-up');
|
||||
void panel.offsetWidth;
|
||||
panel.classList.add(
|
||||
direction > 0 ? 'rail-switch-down' : 'rail-switch-up',
|
||||
);
|
||||
// The classes come off when the slide ends, or after a moment where
|
||||
// there is no slide to end (reduced motion).
|
||||
const settle = () => {
|
||||
win.clearTimeout(timer);
|
||||
panel.removeEventListener('animationend', settle);
|
||||
panel.classList.remove('rail-switch-down', 'rail-switch-up');
|
||||
};
|
||||
const timer = win.setTimeout(settle, 600);
|
||||
panel.addEventListener('animationend', settle);
|
||||
}
|
||||
follow();
|
||||
}
|
||||
|
||||
function onWheel(event) {
|
||||
// Pinch zoom, and sideways or empty moves (trackpads send them mid-swipe),
|
||||
// are left alone: they neither step nor turn a gesture round.
|
||||
if (event.ctrlKey || !event.deltaY) return;
|
||||
const now = win.performance?.now?.() ?? Date.now();
|
||||
const inGesture = now - lastWheel <= GESTURE_GAP_MS;
|
||||
// Recheck: the pointer may not have moved since the panels changed.
|
||||
const stillHot =
|
||||
Boolean(hot) && railAt(event.clientX, event.target) === hot;
|
||||
if (!stillHot) {
|
||||
setHot(null);
|
||||
// The rest of a gesture that has already stepped is used up here, so
|
||||
// its coasting does not go on to zoom the globe or scroll what opened
|
||||
// under the pointer.
|
||||
if (stepped && inGesture && now - steppedAt <= COAST_MAX_MS) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
lastWheel = now;
|
||||
}
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// Line- and page-based wheels report far smaller numbers than pixels.
|
||||
const deltaY =
|
||||
event.deltaMode === 1
|
||||
? event.deltaY * LINE_PX
|
||||
: event.deltaMode === 2
|
||||
? event.deltaY * win.innerHeight
|
||||
: event.deltaY;
|
||||
const speed = Math.abs(deltaY);
|
||||
// A new gesture: after a pause, after turning round, a mouse wheel notch,
|
||||
// or a fresh flick while the last one is still coasting. A flick is a
|
||||
// rise in speed after the gesture has clearly slowed, and not in the
|
||||
// moment after a step: a swipe is still speeding up when it first steps.
|
||||
const turned = travel && Math.sign(deltaY) !== Math.sign(travel);
|
||||
const cooled = now - steppedAt > STEP_COOLDOWN_MS;
|
||||
// Every event from a line- or page-based wheel is a notch.
|
||||
const notch =
|
||||
stepped && cooled && (speed >= NOTCH_DELTA || event.deltaMode > 0);
|
||||
const flick =
|
||||
stepped && cooled && slowed && speed > Math.max(8, lastSpeed * 1.8);
|
||||
if (!inGesture || turned || notch || flick) {
|
||||
// A held step belongs to the motion it came from; a reversal or a new
|
||||
// flick replaces it rather than queueing behind it.
|
||||
if (turned && heldStep) {
|
||||
win.clearTimeout(heldStep);
|
||||
heldStep = 0;
|
||||
}
|
||||
travel = 0;
|
||||
stepped = false;
|
||||
peakSpeed = 0;
|
||||
slowed = false;
|
||||
}
|
||||
lastWheel = now;
|
||||
lastSpeed = speed;
|
||||
peakSpeed = Math.max(peakSpeed, speed);
|
||||
if (stepped) {
|
||||
if (speed < peakSpeed * 0.5) slowed = true;
|
||||
return;
|
||||
}
|
||||
travel += deltaY;
|
||||
if (Math.abs(travel) < STEP_DELTA) return;
|
||||
stepped = true;
|
||||
const direction = Math.sign(travel);
|
||||
const wait = STEP_GAP_MS - (now - steppedAt);
|
||||
if (wait <= 0) {
|
||||
steppedAt = now;
|
||||
step(direction);
|
||||
return;
|
||||
}
|
||||
// Too soon after the last step: hold this one until the gap has passed.
|
||||
if (heldStep) return;
|
||||
const heldRail = hot;
|
||||
heldStep = win.setTimeout(() => {
|
||||
heldStep = 0;
|
||||
// The pointer may have left the strip, or moved to the other rail,
|
||||
// meanwhile; then nothing steps.
|
||||
if (!hot || hot !== heldRail) return;
|
||||
steppedAt = win.performance?.now?.() ?? Date.now();
|
||||
step(direction);
|
||||
}, wait);
|
||||
}
|
||||
|
||||
const onResize = () => follow(2);
|
||||
doc.addEventListener('pointermove', onMove, { passive: true });
|
||||
doc.addEventListener('pointerout', onLeave, { passive: true });
|
||||
win.addEventListener('wheel', onWheel, { capture: true, passive: false });
|
||||
win.addEventListener('resize', onResize, { passive: true });
|
||||
follow();
|
||||
|
||||
return () => {
|
||||
removed = true;
|
||||
win.clearTimeout(heldStep);
|
||||
setHot(null);
|
||||
observer?.disconnect();
|
||||
sized?.disconnect();
|
||||
win.cancelAnimationFrame(frame);
|
||||
doc.removeEventListener('pointermove', onMove);
|
||||
doc.removeEventListener('pointerout', onLeave);
|
||||
win.removeEventListener('wheel', onWheel, { capture: true });
|
||||
win.removeEventListener('resize', onResize);
|
||||
doc.querySelectorAll('.ui-rail').forEach((rail) => {
|
||||
rail.classList.remove(
|
||||
'ui-rail--glide',
|
||||
'ui-rail--glide-jump',
|
||||
'ui-rail--edge-hot',
|
||||
);
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Window } from 'happy-dom';
|
||||
import { installRailEdgeScroll } from './railEdgeScroll.js';
|
||||
|
||||
// A page with a left and a right rail of three items each, laid out by hand:
|
||||
// happy-dom does no layout, so boxes and the clock are stubbed.
|
||||
function page({ rtl = false } = {}) {
|
||||
const window = new Window({ width: 1600, height: 900 });
|
||||
const doc = window.document;
|
||||
let now = 1000;
|
||||
const timers = new Map();
|
||||
let nextTimer = 1;
|
||||
window.performance.now = () => now;
|
||||
window.setTimeout = (fn, ms) => {
|
||||
const id = nextTimer++;
|
||||
timers.set(id, { fn, at: now + ms });
|
||||
return id;
|
||||
};
|
||||
window.clearTimeout = (id) => timers.delete(id);
|
||||
window.requestAnimationFrame = () => 0;
|
||||
window.cancelAnimationFrame = () => {};
|
||||
Object.defineProperty(doc.documentElement, 'clientWidth', { value: 1600 });
|
||||
const box = (el, left, top, width, height) => {
|
||||
el.getBoundingClientRect = () => ({
|
||||
left,
|
||||
top,
|
||||
width,
|
||||
height,
|
||||
right: left + width,
|
||||
bottom: top + height,
|
||||
});
|
||||
Object.defineProperty(el, 'offsetWidth', { get: () => width });
|
||||
};
|
||||
const clicks = [];
|
||||
const rail = (name, left) => {
|
||||
const el = doc.createElement('div');
|
||||
el.className = `ui-rail ui-rail--${name}`;
|
||||
box(el, left, 200, 40, 120);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const item = doc.createElement('button');
|
||||
item.className = 'ui-rail__item';
|
||||
item.dataset.railItem = `${name}-${i}`;
|
||||
item.setAttribute('aria-pressed', i === 0 ? 'true' : 'false');
|
||||
box(item, left + 4, 204 + i * 40, 32, 32);
|
||||
item.addEventListener('click', () => {
|
||||
clicks.push(item.dataset.railItem);
|
||||
for (const other of el.children)
|
||||
other.setAttribute('aria-pressed', String(other === item));
|
||||
});
|
||||
el.append(item);
|
||||
}
|
||||
doc.body.append(el);
|
||||
return el;
|
||||
};
|
||||
// In a right-to-left language the left stack's rail is on the right edge.
|
||||
const left = rail('left', rtl ? 1550 : 10);
|
||||
const right = rail('right', rtl ? 10 : 1550);
|
||||
const remove = installRailEdgeScroll(doc);
|
||||
const wheel = (x, deltaY, { deltaMode = 0, target = doc.body } = {}) => {
|
||||
// happy-dom leaves clientX off these events, so it is set by hand.
|
||||
const at = (event) => Object.defineProperty(event, 'clientX', { value: x });
|
||||
target.dispatchEvent(
|
||||
at(new window.PointerEvent('pointermove', { bubbles: true })),
|
||||
);
|
||||
const event = at(
|
||||
new window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
deltaY,
|
||||
deltaMode,
|
||||
}),
|
||||
);
|
||||
target.dispatchEvent(event);
|
||||
return event;
|
||||
};
|
||||
const advance = (ms) => {
|
||||
now += ms;
|
||||
for (const [id, timer] of [...timers]) {
|
||||
if (timer.at > now) continue;
|
||||
timers.delete(id);
|
||||
timer.fn();
|
||||
}
|
||||
};
|
||||
return { window, doc, left, right, clicks, wheel, advance, remove };
|
||||
}
|
||||
|
||||
test('a wheel in the left strip steps that rail and keeps the globe from zooming', () => {
|
||||
const p = page();
|
||||
const event = p.wheel(20, 120);
|
||||
assert.equal(event.defaultPrevented, true);
|
||||
assert.deepEqual(p.clicks, ['left-1']);
|
||||
p.remove();
|
||||
});
|
||||
|
||||
test('a line-based mouse wheel steps one panel per notch', () => {
|
||||
const p = page();
|
||||
p.wheel(20, 3, { deltaMode: 1 });
|
||||
p.advance(600);
|
||||
p.wheel(20, 3, { deltaMode: 1 });
|
||||
assert.deepEqual(p.clicks, ['left-1', 'left-2']);
|
||||
p.remove();
|
||||
});
|
||||
|
||||
test('a rail hidden by clean view or recording leaves the wheel to the globe', () => {
|
||||
const p = page();
|
||||
p.left.checkVisibility = () => false;
|
||||
const event = p.wheel(20, 120);
|
||||
assert.equal(event.defaultPrevented, false);
|
||||
assert.deepEqual(p.clicks, []);
|
||||
p.remove();
|
||||
});
|
||||
|
||||
test('right to left: the wheel at each screen edge steps the rail on that edge', () => {
|
||||
const p = page({ rtl: true });
|
||||
p.wheel(1580, 120);
|
||||
p.advance(600);
|
||||
p.wheel(20, 120);
|
||||
assert.deepEqual(p.clicks, ['left-1', 'right-1']);
|
||||
p.remove();
|
||||
});
|
||||
|
||||
test('after a step, the wheel goes back to the page once the coasting is over', () => {
|
||||
const p = page();
|
||||
p.wheel(20, 120);
|
||||
// The pointer moves off the strip while the gesture still coasts.
|
||||
let event;
|
||||
for (let i = 0; i < 20; i++) {
|
||||
p.advance(100);
|
||||
event = p.wheel(800, 30);
|
||||
}
|
||||
assert.equal(event.defaultPrevented, false);
|
||||
assert.deepEqual(p.clicks, ['left-1']);
|
||||
p.remove();
|
||||
});
|
||||
|
||||
test('a held step is dropped when the pointer leaves the strip, even if it comes back', () => {
|
||||
const p = page();
|
||||
p.wheel(20, 120);
|
||||
p.advance(250);
|
||||
p.wheel(20, -120); // turns round: a second step, held for the gap
|
||||
p.wheel(800, 0); // leaves the strip
|
||||
p.wheel(20, 0); // and returns before the gap ends
|
||||
p.advance(600);
|
||||
assert.deepEqual(p.clicks, ['left-1']);
|
||||
p.remove();
|
||||
});
|
||||
|
||||
test('removing it stops edge scrolling', () => {
|
||||
const p = page();
|
||||
p.remove();
|
||||
const event = p.wheel(20, 120);
|
||||
assert.equal(event.defaultPrevented, false);
|
||||
assert.deepEqual(p.clicks, []);
|
||||
});
|
||||
|
||||
test('a sideways move mid-swipe neither turns the gesture round nor steps again', () => {
|
||||
const p = page();
|
||||
p.wheel(20, 60);
|
||||
p.advance(50);
|
||||
const sideways = p.wheel(20, 0);
|
||||
p.advance(50);
|
||||
p.wheel(20, 40); // the same swipe coasting on
|
||||
assert.equal(sideways.defaultPrevented, false);
|
||||
assert.deepEqual(p.clicks, ['left-1']);
|
||||
p.remove();
|
||||
});
|
||||
|
||||
test('an open dialog near the edge keeps its own wheel', () => {
|
||||
const p = page();
|
||||
const dialog = p.doc.createElement('dialog');
|
||||
p.doc.body.append(dialog);
|
||||
const event = p.wheel(20, 120, { target: dialog });
|
||||
assert.equal(event.defaultPrevented, false);
|
||||
assert.deepEqual(p.clicks, []);
|
||||
p.remove();
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import { h, render } from 'vue';
|
||||
import RailTimeline from './rail/RailTimeline.vue';
|
||||
|
||||
export { utcClock } from './rail/utcClock.js';
|
||||
|
||||
/**
|
||||
* Stable native transport with local preview and a coalesced 150 ms drag
|
||||
* commit. Renders the RailTimeline component into `container` and patches it
|
||||
* synchronously on every update.
|
||||
*/
|
||||
export function createRailTimeline({
|
||||
container,
|
||||
document = container?.ownerDocument,
|
||||
sliderClassName = '',
|
||||
heading = true,
|
||||
onCommit = () => {},
|
||||
onPreview = () => {},
|
||||
onStep = () => {},
|
||||
onLatest = () => {},
|
||||
onPlay = () => {},
|
||||
} = {}) {
|
||||
if (!document?.createElement || !container) return null;
|
||||
let destroyed = false;
|
||||
const paint = (state) =>
|
||||
render(
|
||||
h(RailTimeline, {
|
||||
state,
|
||||
sliderClassName,
|
||||
heading,
|
||||
onCommit,
|
||||
onPreview,
|
||||
onStep,
|
||||
onLatest,
|
||||
onPlay,
|
||||
}),
|
||||
container,
|
||||
);
|
||||
paint({
|
||||
ticks: [],
|
||||
index: 0,
|
||||
mode: 'latest',
|
||||
playing: false,
|
||||
readout: '',
|
||||
disabled: true,
|
||||
});
|
||||
return {
|
||||
update(state) {
|
||||
if (!destroyed) paint(state);
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
render(null, container);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { assertSameNode } from '../testSupport/domAssert.mjs';
|
||||
import { nextTick } from 'vue';
|
||||
import { createRailTimeline } from './railTimeline.js';
|
||||
import { railDocumentFixture as railFixture } from './railTestFixture.mjs';
|
||||
const ticks = [
|
||||
'2026-09-22T01:00:00Z',
|
||||
'2026-09-22T01:05:00Z',
|
||||
'2026-09-22T01:10:00Z',
|
||||
];
|
||||
const props = {
|
||||
ticks,
|
||||
index: 2,
|
||||
mode: 'latest',
|
||||
playing: false,
|
||||
readout: 'Latest',
|
||||
disabled: false,
|
||||
};
|
||||
test('preview is immediate, commits are coalesced and the drag DOM and tick mapping stay stable', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const f = railFixture();
|
||||
const previews = [];
|
||||
const commits = [];
|
||||
const view = createRailTimeline({
|
||||
...f,
|
||||
onPreview: (tick) => {
|
||||
previews.push(tick);
|
||||
return tick;
|
||||
},
|
||||
onCommit: (tick) => commits.push(tick),
|
||||
});
|
||||
view.update(props);
|
||||
const slider = f.find((n) => n.tagName === 'INPUT');
|
||||
const row = slider.parentElement;
|
||||
assert.equal(slider.getAttribute('aria-label'), 'Observed history');
|
||||
slider.value = '0';
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
assert.deepEqual(commits, []);
|
||||
assert.deepEqual(previews, [ticks[0]]);
|
||||
await nextTick();
|
||||
assert.equal(slider.getAttribute('aria-valuetext'), '09-22 01:00 UTC');
|
||||
view.update({
|
||||
...props,
|
||||
ticks: ticks.slice(1),
|
||||
index: 1,
|
||||
readout: 'Refresh',
|
||||
});
|
||||
assertSameNode(slider.parentElement, row);
|
||||
assertSameNode(row.children[1], slider);
|
||||
assert.equal(slider.value, '0');
|
||||
assert.equal(slider.max, '2');
|
||||
assert.equal(
|
||||
f.find((n) => n.className === 'rail-timeline-readout').textContent,
|
||||
ticks[0],
|
||||
);
|
||||
t.mock.timers.tick(149);
|
||||
assert.equal(commits.length, 0);
|
||||
slider.value = '1';
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
t.mock.timers.tick(1);
|
||||
assert.deepEqual(commits, [ticks[1]]);
|
||||
slider.value = '2';
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
slider.dispatchEvent(new Event('change'));
|
||||
assert.deepEqual(commits, [ticks[1], ticks[2]]);
|
||||
t.mock.timers.tick(150);
|
||||
assert.equal(commits.length, 2);
|
||||
await nextTick();
|
||||
assert.equal(slider.max, '1', 'release applies the latest update');
|
||||
view.destroy();
|
||||
});
|
||||
test('identical updates write nothing; controls call actions and destruction cancels commits', (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const f = railFixture();
|
||||
const calls = [];
|
||||
const view = createRailTimeline({
|
||||
...f,
|
||||
onCommit: () => calls.push('commit'),
|
||||
onStep: (n) => calls.push(n),
|
||||
onLatest: () => calls.push('latest'),
|
||||
onPlay: () => calls.push('play'),
|
||||
});
|
||||
view.update({ ...props, index: 1 });
|
||||
f.writes();
|
||||
view.update({ ...props, index: 1 });
|
||||
assert.equal(f.writes(), 0);
|
||||
for (const label of ['‹', '›', 'Latest', 'Play'])
|
||||
f.find((n) => n.textContent === label).click();
|
||||
assert.deepEqual(calls, [-1, 1, 'latest', 'play']);
|
||||
view.update({ ...props, playing: true });
|
||||
assert.ok(f.find((n) => n.textContent === 'Pause'));
|
||||
const slider = f.find((n) => n.tagName === 'INPUT');
|
||||
slider.value = '0';
|
||||
slider.dispatchEvent(new Event('change'));
|
||||
assert.equal(calls.at(-1), 'commit');
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
view.destroy();
|
||||
t.mock.timers.tick(150);
|
||||
assert.equal(calls.length, 5);
|
||||
assert.equal(f.container.children.length, 0);
|
||||
});
|
||||
|
||||
test('observed history label and endpoint times track the advertised tick range', () => {
|
||||
const f = railFixture();
|
||||
const view = createRailTimeline(f);
|
||||
view.update(props);
|
||||
assert.equal(
|
||||
f.find((n) => n.className === 'panel-title').textContent,
|
||||
'Observed history',
|
||||
);
|
||||
const endpoints = f.find((n) => n.className === 'rail-timeline-endpoints');
|
||||
assert.equal(endpoints.parentElement.className, 'rail-timeline-track');
|
||||
assert.deepEqual(
|
||||
[...endpoints.children].map((n) => n.textContent),
|
||||
['01:00 UTC', '01:10 UTC'],
|
||||
);
|
||||
view.update({ ...props, ticks: ticks.slice(1) });
|
||||
assert.equal(endpoints.children[0].textContent, '01:05 UTC');
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
test('an update from inside the preview neither moves the handle back nor survives a disable', async () => {
|
||||
const f = railFixture();
|
||||
let view;
|
||||
let next = null;
|
||||
const commits = [];
|
||||
view = createRailTimeline({
|
||||
...f,
|
||||
onPreview: () => {
|
||||
if (next) view.update(next);
|
||||
return 'preview';
|
||||
},
|
||||
onCommit: (tick, index) => commits.push(index),
|
||||
});
|
||||
view.update(props);
|
||||
const slider = f.find((n) => n.tagName === 'INPUT');
|
||||
next = { ...props, readout: 'Refresh' };
|
||||
slider.value = '0';
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
assert.equal(slider.value, '0');
|
||||
slider.dispatchEvent(new Event('change'));
|
||||
assert.deepEqual(commits, [0]);
|
||||
next = { ...props, disabled: true };
|
||||
slider.value = '1';
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
await nextTick();
|
||||
assert.equal(slider.value, '2', 'the disabled owner keeps its position');
|
||||
assert.equal(slider.getAttribute('aria-valuetext'), '09-22 01:10 UTC');
|
||||
view.destroy();
|
||||
});
|
||||
test('a drag that ends where it began puts the handle back on the shown index', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const f = railFixture();
|
||||
const commits = [];
|
||||
const view = createRailTimeline({
|
||||
...f,
|
||||
onCommit: (tick) => commits.push(tick),
|
||||
});
|
||||
view.update(props);
|
||||
await nextTick();
|
||||
const slider = f.find((n) => n.tagName === 'INPUT');
|
||||
slider.value = '0';
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
slider.dispatchEvent(new Event('pointercancel'));
|
||||
await nextTick();
|
||||
assert.equal(slider.value, '2', 'a cancelled drag');
|
||||
assert.deepEqual(commits, []);
|
||||
// A refused commit: the owner keeps its index.
|
||||
slider.value = '1';
|
||||
slider.dispatchEvent(new Event('input'));
|
||||
slider.dispatchEvent(new Event('change'));
|
||||
await nextTick();
|
||||
assert.deepEqual(commits, [ticks[1]]);
|
||||
assert.equal(slider.value, '2', 'a refused commit');
|
||||
view.destroy();
|
||||
});
|
||||
+5
-11
@@ -17,7 +17,7 @@ import {
|
||||
tn,
|
||||
translateKnown,
|
||||
} from '../i18n/index.js';
|
||||
import { createImagerySplit } from './imagerySplit.js';
|
||||
import { createImagerySplit, globeSplitTarget } from './imagerySplit.js';
|
||||
import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue';
|
||||
import {
|
||||
PRODUCTS,
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
} from '../layers/recentImagery/model.js';
|
||||
import { displayDay, displayMetres } from '../layers/recentImagery/display.js';
|
||||
import { formatQuantity } from './unitLabels.js';
|
||||
import { pointerOwnerName } from '../data/pointerOwnerNames.js';
|
||||
import { canvasOf, findFrame, findGlobe } from '../render/rendererOf.js';
|
||||
|
||||
const PANEL_ID = 'recent-imagery-panel';
|
||||
const OVERVIEW_MIN_BOX_KM = 25;
|
||||
@@ -49,7 +49,6 @@ const LAYER_NOTICES = new Set([
|
||||
// imageryBoxTool.js); fixed refusals there are msg() text for translateKnown.
|
||||
const TOO_LARGE = /^(Box|View) is ([\d,]+) km wide · limit ([\d,]+) km$/;
|
||||
const POLAR = /^Imagery stops at ±([\d.]+)° latitude$/;
|
||||
const POINTER_BUSY = /^(.+) is using the pointer — close it first$/;
|
||||
|
||||
/**
|
||||
* The notice line in the UI language: notices and box refusals arrive in
|
||||
@@ -68,11 +67,6 @@ export function localizeNotice(text) {
|
||||
maximumFractionDigits: 2,
|
||||
}),
|
||||
});
|
||||
const busy = POINTER_BUSY.exec(text);
|
||||
if (busy)
|
||||
return t('{owner} is using the pointer — close it first', {
|
||||
owner: translateKnown(pointerOwnerName(busy[1])),
|
||||
});
|
||||
const tooLarge = TOO_LARGE.exec(text);
|
||||
if (!tooLarge) return translateKnown(text);
|
||||
const values = {
|
||||
@@ -206,7 +200,7 @@ export function createRecentImageryPanel({
|
||||
fetchImpl = globalThis.fetch?.bind(globalThis),
|
||||
createObjectUrl = (blob) => URL.createObjectURL(blob),
|
||||
revokeObjectUrl = (url) => URL.revokeObjectURL(url),
|
||||
requestRender = () => viewer?.scene?.requestRender?.(),
|
||||
requestRender = () => findFrame(viewer)?.requestRender('recent-imagery'),
|
||||
} = {}) {
|
||||
const document = container?.ownerDocument;
|
||||
if (!document?.createElement || !layer) return null;
|
||||
@@ -702,7 +696,7 @@ export function createRecentImageryPanel({
|
||||
}
|
||||
if (!live || split || destroyed) return;
|
||||
split = createSplit({
|
||||
scene: viewer?.scene,
|
||||
scene: globeSplitTarget(findGlobe(viewer)),
|
||||
initialValue: snapshot.split,
|
||||
id: 'recent-imagery-split-line',
|
||||
handleClass: 'recent-imagery-split-handle',
|
||||
@@ -723,7 +717,7 @@ export function createRecentImageryPanel({
|
||||
right: rightPercent,
|
||||
}),
|
||||
getViewportWidth: () =>
|
||||
Number(viewer?.scene?.canvas?.clientWidth) ||
|
||||
Number(canvasOf(viewer)?.clientWidth) ||
|
||||
Number(document.documentElement?.clientWidth) ||
|
||||
0,
|
||||
onChange: (value) => layer.setSplit(value),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
@@ -15,6 +16,8 @@ import {
|
||||
response,
|
||||
settle,
|
||||
} from '../layers/recentImagery/testDoubles.mjs';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeGlobePort } from '../testSupport/fakeGlobePort.mjs';
|
||||
|
||||
const S18 = 'S30:2026-09-18';
|
||||
const L16 = 'L30:2026-09-16';
|
||||
@@ -128,6 +131,8 @@ function fixture({ fetchImpl, controller = fakeController() } = {}) {
|
||||
camera: {},
|
||||
scene: { canvas: { clientWidth: 1000 }, requestRender() {} },
|
||||
};
|
||||
const globe = fakeGlobePort();
|
||||
bindFakeCesiumCamera(viewer, { globe });
|
||||
layer.init(viewer);
|
||||
layer.attachMapStackController(controller);
|
||||
let active = false;
|
||||
@@ -210,6 +215,7 @@ function fixture({ fetchImpl, controller = fakeController() } = {}) {
|
||||
...dom,
|
||||
layer,
|
||||
viewer,
|
||||
globe,
|
||||
renderer,
|
||||
thumbnails,
|
||||
catalog,
|
||||
@@ -801,9 +807,7 @@ test('an oversized box offers ZOOM IN in a fixed slot at the end of the notice l
|
||||
const f = fixture();
|
||||
const flights = [];
|
||||
f.viewer.scene.canvas.clientHeight = 500;
|
||||
f.viewer.scene.ellipsoid = {
|
||||
cartographicToCartesian: (c) => ({ ...c }),
|
||||
};
|
||||
f.viewer.scene.ellipsoid = Cesium.Ellipsoid.WGS84;
|
||||
Object.assign(f.viewer.camera, {
|
||||
frustum: { fovy: 2 * Math.atan(Math.tan(Math.PI / 6) / 2) },
|
||||
flyTo: (options) => flights.push(options),
|
||||
@@ -835,7 +839,9 @@ test('an oversized box offers ZOOM IN in a fixed slot at the end of the notice l
|
||||
assert.equal(flights.length, 1);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
flights[0].destination.height - 400_000 / (2 * Math.tan(Math.PI / 6)),
|
||||
Cesium.Ellipsoid.WGS84.cartesianToCartographic(flights[0].destination)
|
||||
.height -
|
||||
400_000 / (2 * Math.tan(Math.PI / 6)),
|
||||
) < 1e-6,
|
||||
);
|
||||
// Another refusal has nothing to fit; a box that succeeds hides it again.
|
||||
@@ -876,6 +882,9 @@ test('the divider exists only while a swipe is live, labelled A / B or IMAGE / B
|
||||
assert.equal(f.splits.length, 1);
|
||||
assert.deepEqual(labels(), ['IMAGE', 'BASEMAP']);
|
||||
assert.equal(f.splits[0].options.id, 'recent-imagery-split-line');
|
||||
// The divider moves the globe's split, through the renderer's globe port.
|
||||
f.splits[0].options.scene.splitPosition = 0.3;
|
||||
assert.equal(f.globe.imagery.getSplit(), 0.3);
|
||||
assert.deepEqual(swapState(), [false, false, 'false', 'false']);
|
||||
assert.deepEqual(directions(), ['left', undefined]);
|
||||
// VS BASEMAP: SWAP puts the image right of the basemap, and back.
|
||||
|
||||
@@ -10,7 +10,6 @@ import { localizeNotice } from './recentImagery.js';
|
||||
const REFUSALS = [
|
||||
'Drag to size the box', // imageryBoxTool.js, click without drag
|
||||
'Press on the ground, not the sky', // imageryBoxTool.js
|
||||
'draw is using the pointer — close it first', // imageryBoxTool.js, pointer busy
|
||||
'Point the camera at the ground to use the view', // layers/recentImagery/index.js
|
||||
'That point cannot anchor a box', // layers/recentImagery/index.js
|
||||
...[
|
||||
@@ -26,62 +25,12 @@ const REFUSALS = [
|
||||
}),
|
||||
];
|
||||
|
||||
// The pointer-busy refusal names the owner by its internal id; the notice
|
||||
// shows the tool's name instead, in English too.
|
||||
const SHOWN_EN = new Map([
|
||||
[
|
||||
'draw is using the pointer — close it first',
|
||||
'Draw is using the pointer — close it first',
|
||||
],
|
||||
]);
|
||||
|
||||
test('en: refusals stay English', () => {
|
||||
setLocale('en');
|
||||
for (const text of REFUSALS)
|
||||
assert.equal(localizeNotice(text), SHOWN_EN.get(text) ?? text);
|
||||
for (const text of REFUSALS) assert.equal(localizeNotice(text), text);
|
||||
assert.ok(REFUSALS.includes('Imagery stops at ±85.05° latitude'));
|
||||
});
|
||||
|
||||
test('E3/E12: the pointer owner is named by its tool, never by its id', () => {
|
||||
const owners = {
|
||||
en: {
|
||||
draw: 'Draw',
|
||||
directions: 'Directions',
|
||||
'recent-imagery-box': 'Recent imagery',
|
||||
},
|
||||
ru: {
|
||||
draw: 'Рисование',
|
||||
directions: 'Маршруты',
|
||||
'recent-imagery-box': 'Свежие снимки',
|
||||
},
|
||||
es: {
|
||||
draw: 'Dibujo',
|
||||
directions: 'Indicaciones',
|
||||
'recent-imagery-box': 'Imágenes recientes',
|
||||
},
|
||||
};
|
||||
try {
|
||||
for (const [locale, names] of Object.entries(owners)) {
|
||||
setLocale(locale);
|
||||
for (const [id, name] of Object.entries(names)) {
|
||||
const shown = localizeNotice(
|
||||
`${id} is using the pointer — close it first`,
|
||||
);
|
||||
assert.ok(shown.includes(name), `${locale} ${id}: ${shown}`);
|
||||
assert.ok(!shown.includes(id), `${locale} ${id} leaked: ${shown}`);
|
||||
}
|
||||
}
|
||||
setLocale('en');
|
||||
assert.equal(
|
||||
localizeNotice('measure is using the pointer — close it first'),
|
||||
'measure is using the pointer — close it first',
|
||||
'an unregistered owner falls back to its id',
|
||||
);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: box-tool and model refusals are translated`, () => {
|
||||
setLocale(locale);
|
||||
@@ -92,10 +41,6 @@ for (const locale of ['es', 'ru']) {
|
||||
localizeNotice('Imagery stops at ±85.05° latitude'),
|
||||
/85,05/,
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
localizeNotice('draw is using the pointer — close it first'),
|
||||
/\bdraw\b/,
|
||||
);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
// The scene chrome renders the render failure notice and its actions.
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createApp, nextTick } from 'vue';
|
||||
import { createPinia } from 'pinia';
|
||||
import { useStatusStore } from './stores/status.js';
|
||||
import SceneChromeView from './views/SceneChromeView.vue';
|
||||
|
||||
function mount(t) {
|
||||
document.body.replaceChildren();
|
||||
const pinia = createPinia();
|
||||
const app = createApp(SceneChromeView).use(pinia);
|
||||
app.mount(document.body.appendChild(document.createElement('div')));
|
||||
t.after(() => app.unmount());
|
||||
return useStatusStore(pinia);
|
||||
}
|
||||
|
||||
const notice = () => document.getElementById('render-failure');
|
||||
const buttons = () =>
|
||||
[...(notice()?.querySelectorAll('button') ?? [])].map((button) =>
|
||||
button.textContent.trim(),
|
||||
);
|
||||
|
||||
test('a render failure shows an alert dialog that moves focus to Retry', async (t) => {
|
||||
const store = mount(t);
|
||||
assert.equal(notice(), null, 'no notice while the globe draws');
|
||||
const calls = [];
|
||||
store.publishRenderFailure({
|
||||
reason: 'render-error',
|
||||
detail: 'Expected width to be greater than 0',
|
||||
retry: () => calls.push('retry'),
|
||||
reset: () => calls.push('reset'),
|
||||
});
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
const element = notice();
|
||||
assert.equal(element.getAttribute('role'), 'alertdialog');
|
||||
assert.equal(
|
||||
document.getElementById(element.getAttribute('aria-labelledby'))
|
||||
.textContent,
|
||||
'The globe stopped drawing',
|
||||
);
|
||||
assert.match(
|
||||
document.getElementById(element.getAttribute('aria-describedby'))
|
||||
.textContent,
|
||||
/^Rendering stopped after an error\./,
|
||||
);
|
||||
assert.equal(
|
||||
element.querySelector('.render-failure-detail').textContent,
|
||||
'Expected width to be greater than 0',
|
||||
);
|
||||
assert.deepEqual(buttons(), ['Retry', 'Reset view']);
|
||||
assert.equal(document.activeElement?.textContent.trim(), 'Retry');
|
||||
for (const button of element.querySelectorAll('button')) button.click();
|
||||
assert.deepEqual(calls, ['retry', 'reset']);
|
||||
store.publishRenderFailure(null);
|
||||
await nextTick();
|
||||
assert.equal(notice(), null);
|
||||
});
|
||||
|
||||
test('a lost context offers Reload, and a panel that cannot reload offers nothing', async (t) => {
|
||||
const store = mount(t);
|
||||
store.publishRenderFailure({
|
||||
reason: 'context-lost',
|
||||
detail: '',
|
||||
retry: () => {},
|
||||
reset: () => {},
|
||||
});
|
||||
await nextTick();
|
||||
assert.match(
|
||||
document.getElementById('render-failure-message').textContent,
|
||||
/3D graphics/,
|
||||
);
|
||||
assert.equal(notice().querySelector('.render-failure-detail') === null, true);
|
||||
assert.deepEqual(buttons(), ['Reload', 'Reset view']);
|
||||
store.publishRenderFailure({
|
||||
reason: 'context-lost',
|
||||
detail: '',
|
||||
retry: null,
|
||||
reset: null,
|
||||
});
|
||||
await nextTick();
|
||||
assert.deepEqual(buttons(), []);
|
||||
assert.equal(notice().querySelector('.render-failure-hint') === null, true);
|
||||
});
|
||||
|
||||
const failure = () => ({
|
||||
reason: 'render-error',
|
||||
detail: '',
|
||||
retry: () => {},
|
||||
reset: null,
|
||||
});
|
||||
const settle = async () => {
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
};
|
||||
|
||||
test('focus goes back where it was when the globe draws again', async (t) => {
|
||||
const store = mount(t);
|
||||
const search = document.body.appendChild(document.createElement('input'));
|
||||
search.focus();
|
||||
store.publishRenderFailure(failure());
|
||||
await settle();
|
||||
assert.equal(document.activeElement?.textContent.trim(), 'Retry');
|
||||
store.publishRenderFailure(null);
|
||||
await settle();
|
||||
assert.equal(document.activeElement, search);
|
||||
});
|
||||
|
||||
// The globe's canvas, as CesiumWidget builds it inside the container.
|
||||
const addGlobeCanvas = () => {
|
||||
const widget = document.createElement('div');
|
||||
widget.className = 'cesium-widget';
|
||||
document.getElementById('cesiumContainer').appendChild(widget);
|
||||
return widget.appendChild(document.createElement('canvas'));
|
||||
};
|
||||
|
||||
test('focus goes to the globe canvas when the element it came from is gone', async (t) => {
|
||||
const store = mount(t);
|
||||
const canvas = addGlobeCanvas();
|
||||
const search = document.body.appendChild(document.createElement('input'));
|
||||
search.focus();
|
||||
store.publishRenderFailure(failure());
|
||||
await settle();
|
||||
search.remove();
|
||||
store.publishRenderFailure(null);
|
||||
await settle();
|
||||
// The map's keys, Enter to finish a drawing among them, read the canvas
|
||||
// as the map (src/annotations/drawTool.js).
|
||||
assert.equal(document.activeElement, canvas);
|
||||
assert.equal(canvas.getAttribute('tabindex'), '-1');
|
||||
canvas.blur();
|
||||
assert.equal(canvas.hasAttribute('tabindex'), false, 'only this once');
|
||||
});
|
||||
|
||||
test('focus goes to the globe canvas when the element it came from cannot take it', async (t) => {
|
||||
const store = mount(t);
|
||||
const canvas = addGlobeCanvas();
|
||||
const button = document.body.appendChild(document.createElement('button'));
|
||||
button.focus();
|
||||
store.publishRenderFailure(failure());
|
||||
await settle();
|
||||
button.disabled = true;
|
||||
store.publishRenderFailure(null);
|
||||
await settle();
|
||||
assert.equal(document.activeElement, canvas);
|
||||
// A press on the globe leaves focus on the page again, as Cesium has it.
|
||||
canvas.dispatchEvent(new Event('pointerdown'));
|
||||
assert.equal(document.activeElement, document.body);
|
||||
assert.equal(canvas.hasAttribute('tabindex'), false);
|
||||
});
|
||||
|
||||
test('focus the user moved while the notice was up stays put', async (t) => {
|
||||
const store = mount(t);
|
||||
store.publishRenderFailure(failure());
|
||||
await settle();
|
||||
const chat = document.body.appendChild(document.createElement('textarea'));
|
||||
chat.focus();
|
||||
store.publishRenderFailure(null);
|
||||
await settle();
|
||||
assert.equal(document.activeElement, chat);
|
||||
});
|
||||
|
||||
test('the globe drawing from the start leaves focus alone', async (t) => {
|
||||
mount(t);
|
||||
await settle();
|
||||
assert.equal(document.activeElement, document.body);
|
||||
assert.equal(
|
||||
document.getElementById('cesiumContainer').hasAttribute('tabindex'),
|
||||
false,
|
||||
);
|
||||
});
|
||||
@@ -31,6 +31,20 @@ function settledLeftRailTop(leftStack, viewportHeight, getComputedStyle) {
|
||||
return Number.isFinite(targetPct) ? (targetPct * viewportHeight) / 100 : top;
|
||||
}
|
||||
|
||||
/**
|
||||
* An element's CSS `top` in pixels where it will settle: the end of a running
|
||||
* `top` transition, else its computed value. NaN when it cannot be read.
|
||||
*/
|
||||
function settledCssTop(element, getComputedStyle) {
|
||||
if (!element) return NaN;
|
||||
const transition = element
|
||||
.getAnimations?.()
|
||||
.find((animation) => animation.transitionProperty === 'top');
|
||||
const target = parseFloat(transition?.effect?.getKeyframes?.().at(-1)?.top);
|
||||
if (Number.isFinite(target)) return target;
|
||||
return parseFloat(getComputedStyle(element).top);
|
||||
}
|
||||
|
||||
/**
|
||||
* Measure and place the right panel rail for one synchronous layout pass.
|
||||
* The caller owns scheduling, obstacle selection, disclosure preferences and
|
||||
@@ -126,9 +140,20 @@ export function layoutRightPanelRail({
|
||||
viewportHeight,
|
||||
getComputedStyle,
|
||||
);
|
||||
// Align with the left rail's buttons, which hold still while its stack moves.
|
||||
const leftRailOffset =
|
||||
parseFloat(leftStack?.style.getPropertyValue('--panel-rail-offset')) || 0;
|
||||
// Align with the left rail's buttons, which hold still while its stack moves:
|
||||
// the rail's own settled `top` inside the stack, so every left layout is
|
||||
// followed (a layout may pin the rail to the stack's top whatever the
|
||||
// offset says). The stack's offset is the fallback when there is no rail.
|
||||
const leftRailInset = settledCssTop(
|
||||
leftStack?.querySelector?.('.gev-panel-rail') ?? null,
|
||||
getComputedStyle,
|
||||
);
|
||||
// A rail that sits lower in its stack has only made room above itself for
|
||||
// the open panel's own icon, which stays at the stack's top: the column's
|
||||
// top has not moved, so that inset is not followed.
|
||||
const leftRailOffset = Number.isFinite(leftRailInset)
|
||||
? Math.min(0, leftRailInset)
|
||||
: parseFloat(leftStack?.style.getPropertyValue('--panel-rail-offset')) || 0;
|
||||
const alignedTop = Number.isFinite(leftStackTop)
|
||||
? leftStackTop + leftRailOffset
|
||||
: viewportHeight * 0.26;
|
||||
@@ -206,6 +231,18 @@ export function layoutRightPanelRail({
|
||||
0,
|
||||
) +
|
||||
gap * Math.max(0, measuredPanels.length - 1);
|
||||
// An open Context panel takes the column's full height: up to just under
|
||||
// the HUD readouts at the top of the screen, down to the usual bottom.
|
||||
// CCTV does the same, so its feed and controls have the room.
|
||||
const FULL_HEIGHT = new Set(['global-context-panel', 'cctv-panel']);
|
||||
const contextOpen = panels.some(
|
||||
(panel) =>
|
||||
FULL_HEIGHT.has(panel.id) && !panel.classList.contains('collapsed'),
|
||||
);
|
||||
// Every panel starts level with the left rail, open or not, so the two
|
||||
// rails line up in every HUD layout (Minimal has no top-right readout to
|
||||
// push this column down) and switching between Context, CCTV and Street
|
||||
// Level does not move it. Only the two above also stretch to the bottom.
|
||||
const layout = resolveHudRailLayout({
|
||||
viewportHeight,
|
||||
panelHeight: naturalHeight,
|
||||
@@ -221,9 +258,11 @@ export function layoutRightPanelRail({
|
||||
const { safeTop, safeBottom, maxHeight: availableHeight } = layout;
|
||||
const stabilityBand = Math.max(48, viewportHeight * 0.06);
|
||||
const wasFocused = stack.classList.contains('layout-focus');
|
||||
const shouldFocus = wasFocused
|
||||
? naturalHeight >= availableHeight - stabilityBand
|
||||
: naturalHeight > availableHeight;
|
||||
const shouldFocus =
|
||||
contextOpen ||
|
||||
(wasFocused
|
||||
? naturalHeight >= availableHeight - stabilityBand
|
||||
: naturalHeight > availableHeight);
|
||||
const layoutTop = shouldFocus ? safeTop : layout.top;
|
||||
const collapsedHeight = visiblePanels.reduce(
|
||||
(total, panel) =>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { parseSharePath } from '../share/shareLinkPath.js';
|
||||
import { decodeShareView } from '../share/viewCodec.js';
|
||||
import { applicationPinia } from './vueRuntime.js';
|
||||
import { useGlobeActionsStore } from './stores/globeActions.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
/** The decoded view of a `/share/<code>` link. */
|
||||
const sharedState = (href) =>
|
||||
@@ -28,7 +29,7 @@ function makeManager(href, { positioned = true } = {}) {
|
||||
roll: 0,
|
||||
},
|
||||
};
|
||||
return new ShareLinkManager(viewer);
|
||||
return new ShareLinkManager(bindFakeCesiumCamera(viewer));
|
||||
}
|
||||
|
||||
function installClipboard(writeText) {
|
||||
@@ -190,7 +191,7 @@ test('the shell’s camera controls answer tilt and north-up and publish their s
|
||||
const store = useGlobeActionsStore(applicationPinia());
|
||||
const navigations = [];
|
||||
const owner = {
|
||||
viewer: { camera: { heading: 0 } },
|
||||
viewer: bindFakeCesiumCamera({ camera: { heading: 0 } }),
|
||||
_navigation: {
|
||||
runOrientation: (noun, navigate) => {
|
||||
navigations.push(noun);
|
||||
@@ -230,7 +231,7 @@ test('a shell that goes after a newer one leaves the newer one’s bar state', (
|
||||
const shellWith = () => {
|
||||
const owner = {
|
||||
_disposed: false,
|
||||
viewer: { camera: { heading: 0 } },
|
||||
viewer: bindFakeCesiumCamera({ camera: { heading: 0 } }),
|
||||
_navigation: { runOrientation: (_noun, navigate) => navigate() },
|
||||
_showToast() {},
|
||||
clearSelectedLayers: async () => {},
|
||||
@@ -268,7 +269,7 @@ test('an older shell that answers again shows its clear and its unchanged camera
|
||||
const shellWith = (heading) => {
|
||||
const owner = {
|
||||
_disposed: false,
|
||||
viewer: { camera: { heading } },
|
||||
viewer: bindFakeCesiumCamera({ camera: { heading } }),
|
||||
_navigation: { runOrientation: (_noun, navigate) => navigate() },
|
||||
_showToast() {},
|
||||
clearSelectedLayers: async () => {},
|
||||
|
||||
+187
-107
@@ -1,5 +1,27 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { trackedDisplayPositionForCamera } from '../data/trackedCamera.js';
|
||||
import { findCamera, findFrame } from '../render/rendererOf.js';
|
||||
import { followedOf, followedPosition } from '../data/followed.js';
|
||||
import { toLonLatH } from '../geo/ellipsoid.js';
|
||||
import {
|
||||
eastNorthUp,
|
||||
framePoint,
|
||||
frameVector,
|
||||
inverseFramePoint,
|
||||
inverseFrameVector,
|
||||
isIdentity,
|
||||
offsetFromHeadingPitchRange,
|
||||
} from '../geo/frames.js';
|
||||
import {
|
||||
add,
|
||||
cross,
|
||||
dot,
|
||||
magnitude,
|
||||
negate,
|
||||
normalize,
|
||||
scale,
|
||||
sub,
|
||||
vec,
|
||||
} from '../geo/vector.js';
|
||||
import { createFrameWait } from '../time/frameWait.js';
|
||||
import {
|
||||
SHARE_VIEW_ENTITY_KINDS,
|
||||
SHARE_VIEW_FOLLOW_RANGE_MAX_M,
|
||||
@@ -17,22 +39,97 @@ import {
|
||||
const KIND_BY_LAYER = new Map(
|
||||
SHARE_VIEW_ENTITY_KINDS.map((entry) => [entry.layerId, entry.kind]),
|
||||
);
|
||||
const MAX_FRAMES = 120;
|
||||
/** Drawn time (ms) to wait for the follow to frame the entity. */
|
||||
const MAX_FRAMING_WAIT_MS = 2_000;
|
||||
const EPSILON10 = 1e-10;
|
||||
|
||||
/** Where `followed` is shown now, as an ECEF position, or null. */
|
||||
function shownAt(viewer, followed) {
|
||||
const p = followedPosition(viewer, followed);
|
||||
return p ? vec(p.x, p.y, p.z) : null;
|
||||
}
|
||||
|
||||
/** `position`'s local east/north/up offset from `origin`, in metres. */
|
||||
function enuOffset(origin, position) {
|
||||
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
|
||||
const local = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Matrix4.inverseTransformation(frame, new Cesium.Matrix4()),
|
||||
position,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const local = inverseFramePoint(eastNorthUp(origin), position);
|
||||
return { east: local.x, north: local.y, up: local.z };
|
||||
}
|
||||
|
||||
/** A column-major 4×4 frame-to-ECEF matrix as a frame of axes and origin. */
|
||||
const frameOfMatrix = (m) => ({
|
||||
x: vec(m[0], m[1], m[2]),
|
||||
y: vec(m[4], m[5], m[6]),
|
||||
z: vec(m[8], m[9], m[10]),
|
||||
origin: vec(m[12], m[13], m[14]),
|
||||
});
|
||||
|
||||
/** The frame the camera's eye is in now, or null when it cannot say. */
|
||||
function eyeFrame(camera) {
|
||||
const matrix = camera?.followFrame?.();
|
||||
return matrix ? frameOfMatrix(matrix) : null;
|
||||
}
|
||||
|
||||
/** The angle between two vectors, as the default renderer measures it. */
|
||||
function angleBetween(a, b) {
|
||||
const unitA = normalize(a);
|
||||
const unitB = normalize(b);
|
||||
return Math.atan2(magnitude(cross(unitA, unitB)), dot(unitA, unitB));
|
||||
}
|
||||
|
||||
/**
|
||||
* The eye at `offset` in `frame`, looking at the frame's origin with the
|
||||
* frame's z as up, in the world: where a look at a frame's origin from an
|
||||
* offset puts it.
|
||||
*/
|
||||
function lookingAtOrigin(frame, offset) {
|
||||
const direction = normalize(negate(offset));
|
||||
let right = cross(direction, vec(0, 0, 1));
|
||||
if (dot(right, right) < EPSILON10) right = vec(1, 0, 0);
|
||||
right = normalize(right);
|
||||
const up = normalize(cross(right, direction));
|
||||
return {
|
||||
position: framePoint(frame, offset),
|
||||
direction: frameVector(frame, direction),
|
||||
up: frameVector(frame, up),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The heading, pitch and roll that turn the east-north-up frame at
|
||||
* `position` onto `direction` and `up`, exactly: straight down included,
|
||||
* where a renderer reading angles off a direction rounds the roll away.
|
||||
*/
|
||||
function anglesAt(position, direction, up) {
|
||||
const enu = eastNorthUp(position);
|
||||
const d = inverseFrameVector(enu, direction);
|
||||
const u = inverseFrameVector(enu, up);
|
||||
// From both components: near straight down `asin` would lose precision.
|
||||
const pitch = Math.atan2(d.z, Math.hypot(d.x, d.y));
|
||||
// Straight up or down, any heading will do: the roll takes the rest.
|
||||
const a = Math.abs(d.x) + Math.abs(d.y) > 0 ? Math.atan2(d.y, d.x) : 0;
|
||||
const across = vec(-Math.sin(a), Math.cos(a), 0);
|
||||
const lifted = vec(
|
||||
Math.cos(a) * -Math.sin(pitch),
|
||||
Math.sin(a) * -Math.sin(pitch),
|
||||
Math.cos(pitch),
|
||||
);
|
||||
return {
|
||||
heading: Math.PI / 2 - a,
|
||||
pitch,
|
||||
roll: Math.atan2(-dot(u, across), dot(u, lifted)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Put the eye at a world pose, keeping the frame the camera is in. */
|
||||
function placeEye(camera, eye) {
|
||||
camera.setView({
|
||||
destination: eye.position,
|
||||
orientation: anglesAt(eye.position, eye.direction, eye.up),
|
||||
});
|
||||
}
|
||||
|
||||
/** Degrees to the share format's 10⁻⁴-degree coordinate precision. */
|
||||
const toCoordinate = (radians) =>
|
||||
Math.round(Cesium.Math.toDegrees(radians) * 1e4) / 1e4;
|
||||
const toCoordinate = (degrees) => Math.round(degrees * 1e4) / 1e4;
|
||||
|
||||
/**
|
||||
* The selected vessel as a thing view's subject: its drawn position as the
|
||||
@@ -47,20 +144,20 @@ const toCoordinate = (radians) =>
|
||||
function selectedVesselSubject(cameraPosition, vessel, nowMs) {
|
||||
const id = String(vessel?.id || '');
|
||||
if (!id || !vessel.position) return null;
|
||||
const fixAt = Cesium.Cartographic.fromCartesian(vessel.position);
|
||||
const cameraAt = Cesium.Cartographic.fromCartesian(cameraPosition);
|
||||
const fixAt = toLonLatH(vessel.position);
|
||||
const cameraAt = toLonLatH(cameraPosition);
|
||||
if (!fixAt || !cameraAt) return null;
|
||||
const lastKnown = {
|
||||
lat: toCoordinate(fixAt.latitude),
|
||||
lon: toCoordinate(fixAt.longitude),
|
||||
lat: toCoordinate(fixAt.lat),
|
||||
lon: toCoordinate(fixAt.lon),
|
||||
alt: Math.round(fixAt.height),
|
||||
observedAtMs: Number.isFinite(vessel.observedAtMs)
|
||||
? vessel.observedAtMs
|
||||
: nowMs,
|
||||
};
|
||||
const offset = followOffsetFor(lastKnown, {
|
||||
lat: Cesium.Math.toDegrees(cameraAt.latitude),
|
||||
lon: Cesium.Math.toDegrees(cameraAt.longitude),
|
||||
lat: cameraAt.lat,
|
||||
lon: cameraAt.lon,
|
||||
alt: cameraAt.height,
|
||||
});
|
||||
if (
|
||||
@@ -85,36 +182,30 @@ export function readShareFollowSubject({
|
||||
nowMs = Date.now(),
|
||||
readSelectedVessel = null,
|
||||
}) {
|
||||
const cameraPosition = viewer?.camera?.positionWC;
|
||||
const cameraPosition = viewer ? findCamera(viewer)?.pose().position : null;
|
||||
if (!cameraPosition) return null;
|
||||
const tracked = viewer.trackedEntity;
|
||||
if (!tracked) {
|
||||
const followed = followedOf(viewer);
|
||||
if (!followed) {
|
||||
const vessel = readSelectedVessel?.() ?? null;
|
||||
return vessel ? selectedVesselSubject(cameraPosition, vessel, nowMs) : null;
|
||||
}
|
||||
const trackedId = String(tracked?.gevTrackedId || '');
|
||||
const trackedId = String(followed.key || '');
|
||||
const separator = trackedId.indexOf(':');
|
||||
if (separator <= 0) return null;
|
||||
const kind = KIND_BY_LAYER.get(trackedId.slice(0, separator));
|
||||
const id = trackedId.slice(separator + 1);
|
||||
const target = kind
|
||||
? trackedDisplayPositionForCamera(
|
||||
tracked,
|
||||
viewer.clock.currentTime,
|
||||
new Cesium.Cartesian3(),
|
||||
)
|
||||
: null;
|
||||
const target = kind ? shownAt(viewer, followed) : null;
|
||||
if (!kind || !id || !target) return null;
|
||||
const offset = followOffsetFromEnu(enuOffset(target, cameraPosition));
|
||||
const fix = Cesium.Cartographic.fromCartesian(target);
|
||||
const fix = toLonLatH(target);
|
||||
if (!offset || !fix) return null;
|
||||
return {
|
||||
kind,
|
||||
id,
|
||||
offset,
|
||||
lastKnown: {
|
||||
lat: Cesium.Math.toDegrees(fix.latitude),
|
||||
lon: Cesium.Math.toDegrees(fix.longitude),
|
||||
lat: fix.lat,
|
||||
lon: fix.lon,
|
||||
alt: fix.height,
|
||||
observedAtMs: nowMs,
|
||||
},
|
||||
@@ -125,71 +216,57 @@ export function readShareFollowSubject({
|
||||
const MAX_TURN_PER_FRAME = Math.PI / 3;
|
||||
|
||||
/**
|
||||
* Put the camera at a shared follow offset from `entity` once following it
|
||||
* has framed the camera. Cesium keeps the offset afterwards, as it keeps one
|
||||
* Put the camera at a shared follow offset from `followed` (what
|
||||
* `followedOf` gave) once following it has framed the camera. The renderer keeps the offset afterwards, as it keeps one
|
||||
* the user orbits to. The camera swings round the entity at most 60° a frame:
|
||||
* the follow's own guard treats a jump to the far side as the camera crossing
|
||||
* through the entity and puts it back. Returns a disposer.
|
||||
*/
|
||||
export function applyShareFollowOffset(viewer, entity, offset) {
|
||||
if (!viewer?.scene?.preUpdate || !entity || !(offset?.range > 0))
|
||||
return () => {};
|
||||
export function applyShareFollowOffset(viewer, followed, offset) {
|
||||
const frames = viewer ? findFrame(viewer) : null;
|
||||
if (!frames || !followed || !(offset?.range > 0)) return () => {};
|
||||
const local = followOffsetToEnu(offset);
|
||||
let frames = 0;
|
||||
let count = 0;
|
||||
const framingWait = createFrameWait(MAX_FRAMING_WAIT_MS);
|
||||
let remove = null;
|
||||
const stop = () => {
|
||||
remove?.();
|
||||
remove = null;
|
||||
};
|
||||
remove = viewer.scene.preUpdate.addEventListener(() => {
|
||||
if (viewer.isDestroyed?.() || viewer.trackedEntity !== entity) {
|
||||
remove = frames.on('preUpdate', () => {
|
||||
if (followedOf(viewer) !== followed) {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
frames += 1;
|
||||
const camera = viewer.camera;
|
||||
count += 1;
|
||||
// Let the follow frame the camera first (its first frame), then move it.
|
||||
const camera = findCamera(viewer);
|
||||
const frame = eyeFrame(camera);
|
||||
const ported = camera?.followed === followed;
|
||||
const framed =
|
||||
frames > 1 &&
|
||||
!Cesium.Matrix4.equals(camera.transform, Cesium.Matrix4.IDENTITY);
|
||||
const target = framed
|
||||
? trackedDisplayPositionForCamera(
|
||||
entity,
|
||||
viewer.clock.currentTime,
|
||||
new Cesium.Cartesian3(),
|
||||
)
|
||||
: null;
|
||||
count > 1 &&
|
||||
(ported ? camera.followFramed : frame !== null && !isIdentity(frame));
|
||||
const target = framed && frame ? shownAt(viewer, followed) : null;
|
||||
if (!target) {
|
||||
if (frames >= MAX_FRAMES) stop();
|
||||
if (framingWait.tick()) stop();
|
||||
return;
|
||||
}
|
||||
// The offset is east/north/up at the entity; the follow's own frame may
|
||||
// differ, so place the camera in world space and re-express it there.
|
||||
const world = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(target),
|
||||
new Cesium.Cartesian3(local.east, local.north, local.up),
|
||||
new Cesium.Cartesian3(),
|
||||
const world = framePoint(
|
||||
eastNorthUp(target),
|
||||
vec(local.east, local.north, local.up),
|
||||
);
|
||||
const goal = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Matrix4.inverseTransformation(
|
||||
camera.transform,
|
||||
new Cesium.Matrix4(),
|
||||
),
|
||||
world,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const from = Cesium.Cartesian3.clone(
|
||||
camera.position,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const angle =
|
||||
Cesium.Cartesian3.magnitude(from) > 0
|
||||
? Cesium.Cartesian3.angleBetween(from, goal)
|
||||
: 0;
|
||||
const goal = inverseFramePoint(frame, world);
|
||||
const from =
|
||||
(ported && camera.followOffset.get()) ||
|
||||
inverseFramePoint(frame, camera.pose().position);
|
||||
const angle = magnitude(from) > 0 ? angleBetween(from, goal) : 0;
|
||||
const done = !(angle > MAX_TURN_PER_FRAME);
|
||||
const next = done ? goal : turnToward(from, goal, MAX_TURN_PER_FRAME);
|
||||
camera.lookAtTransform(camera.transform, next);
|
||||
viewer.scene.requestRender?.();
|
||||
// Through the port when it follows: its close-range guard keeps the eye.
|
||||
if (ported) camera.followOffset.set(next);
|
||||
else placeEye(camera, lookingAtOrigin(frame, next));
|
||||
if (done) stop();
|
||||
});
|
||||
return stop;
|
||||
@@ -200,44 +277,47 @@ export function applyShareFollowOffset(viewer, entity, offset) {
|
||||
* fraction of the way: one frame of the swing round the entity.
|
||||
*/
|
||||
function turnToward(from, to, step) {
|
||||
const angle = Cesium.Cartesian3.angleBetween(from, to);
|
||||
const unitFrom = Cesium.Cartesian3.normalize(from, new Cesium.Cartesian3());
|
||||
const angle = angleBetween(from, to);
|
||||
const unitFrom = normalize(from);
|
||||
// The direction perpendicular to `from` in the plane toward `to` (or any
|
||||
// perpendicular when they are opposite).
|
||||
let toward = Cesium.Cartesian3.subtract(
|
||||
Cesium.Cartesian3.normalize(to, new Cesium.Cartesian3()),
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
let toward = sub(normalize(to), scale(unitFrom, Math.cos(angle)));
|
||||
if (magnitude(toward) < 1e-9)
|
||||
toward = cross(
|
||||
unitFrom,
|
||||
Math.cos(angle),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
if (Cesium.Cartesian3.magnitude(toward) < 1e-9)
|
||||
toward = Cesium.Cartesian3.cross(
|
||||
unitFrom,
|
||||
Math.abs(unitFrom.z) < 0.9
|
||||
? Cesium.Cartesian3.UNIT_Z
|
||||
: Cesium.Cartesian3.UNIT_X,
|
||||
new Cesium.Cartesian3(),
|
||||
Math.abs(unitFrom.z) < 0.9 ? vec(0, 0, 1) : vec(1, 0, 0),
|
||||
);
|
||||
Cesium.Cartesian3.normalize(toward, toward);
|
||||
toward = normalize(toward);
|
||||
const length =
|
||||
Cesium.Cartesian3.magnitude(from) +
|
||||
(Cesium.Cartesian3.magnitude(to) - Cesium.Cartesian3.magnitude(from)) *
|
||||
(step / angle);
|
||||
const direction = Cesium.Cartesian3.add(
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
unitFrom,
|
||||
Math.cos(step),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
Cesium.Cartesian3.multiplyByScalar(
|
||||
toward,
|
||||
Math.sin(step),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
new Cesium.Cartesian3(),
|
||||
magnitude(from) + (magnitude(to) - magnitude(from)) * (step / angle);
|
||||
const direction = add(
|
||||
scale(unitFrom, Math.cos(step)),
|
||||
scale(toward, Math.sin(step)),
|
||||
);
|
||||
return Cesium.Cartesian3.multiplyByScalar(direction, length, direction);
|
||||
return scale(direction, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the eye of a camera that follows something at `offset` (heading,
|
||||
* pitch, range) from `target`, keeping the follow's own reference frame
|
||||
* (a satellite's included): the follow's next update carries the new offset
|
||||
* along with the target. False when the camera cannot say which frame it
|
||||
* is in.
|
||||
* @param {object} viewer
|
||||
* @param {{x: number, y: number, z: number}} target
|
||||
* @param {{heading: number, pitch: number, range: number}} offset
|
||||
*/
|
||||
export function placeFollowEye(viewer, target, offset) {
|
||||
const camera = findCamera(viewer);
|
||||
if (!eyeFrame(camera)) return false;
|
||||
// Where looking at `target` from `offset` in its east-north-up frame puts
|
||||
// the eye, placed in the world while the camera stays in its frame.
|
||||
placeEye(
|
||||
camera,
|
||||
lookingAtOrigin(
|
||||
eastNorthUp(vec(target.x, target.y, target.z)),
|
||||
offsetFromHeadingPitchRange(offset.heading, offset.pitch, offset.range),
|
||||
),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// The share follow in a follow's own frame: a satellite's is not
|
||||
// east-north-up, and the eye placed in it must land where Cesium's own
|
||||
// calls put it.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { applyShareFollowOffset, placeFollowEye } from './shareFollow.js';
|
||||
import { followOffsetToEnu } from '../share/viewCodec.js';
|
||||
import { withEntityRecord } from '../data/entityRecords.js';
|
||||
import { entityFollowTarget, followedOf } from '../data/followed.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { findCamera, rendererOf } from '../render/rendererOf.js';
|
||||
|
||||
function realCamera() {
|
||||
const scene = {
|
||||
canvas: { clientWidth: 1200, clientHeight: 800, width: 1200, height: 800 },
|
||||
drawingBufferWidth: 1200,
|
||||
drawingBufferHeight: 800,
|
||||
mapProjection: new Cesium.GeographicProjection(Cesium.Ellipsoid.WGS84),
|
||||
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
|
||||
mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL,
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
pixelRatio: 1,
|
||||
preUpdate: new Cesium.Event(),
|
||||
requestRender() {},
|
||||
};
|
||||
const camera = new Cesium.Camera(scene);
|
||||
scene.camera = camera;
|
||||
return { camera, scene };
|
||||
}
|
||||
|
||||
const TARGET = Cesium.Cartesian3.fromDegrees(-97, 30, 400_000);
|
||||
const START = new Cesium.Cartesian3(900, -1500, 700);
|
||||
|
||||
/**
|
||||
* An orbit frame at the target, turned away from east-north-up as a
|
||||
* satellite's frame from its motion is.
|
||||
*/
|
||||
function orbitFrame() {
|
||||
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(TARGET);
|
||||
const turn = Cesium.Matrix3.multiply(
|
||||
Cesium.Matrix3.fromRotationZ(0.7),
|
||||
Cesium.Matrix3.fromRotationX(0.3),
|
||||
new Cesium.Matrix3(),
|
||||
);
|
||||
return Cesium.Matrix4.multiply(
|
||||
enu,
|
||||
Cesium.Matrix4.fromRotation(turn),
|
||||
new Cesium.Matrix4(),
|
||||
);
|
||||
}
|
||||
|
||||
/** A real camera following in the orbit frame, its viewer bound to ports. */
|
||||
function following(start = START) {
|
||||
const { camera, scene } = realCamera();
|
||||
camera.lookAtTransform(orbitFrame(), start);
|
||||
const viewer = {
|
||||
camera,
|
||||
scene,
|
||||
clock: { currentTime: Cesium.JulianDate.now() },
|
||||
};
|
||||
bindFakeCesiumCamera(viewer, {
|
||||
frame: {
|
||||
on: (phase, cb) =>
|
||||
phase === 'preUpdate' ? scene.preUpdate.addEventListener(cb) : () => {},
|
||||
},
|
||||
});
|
||||
// The port follows the satellite, already framed in its orbit frame; its
|
||||
// follow offset is the eye in that frame, as the Cesium follow's is.
|
||||
const renderer = rendererOf(viewer);
|
||||
const port = renderer.camera;
|
||||
const followed = entityFollowTarget(
|
||||
withEntityRecord(
|
||||
{},
|
||||
{ trackedId: 'satellites:25544', displayPosition: () => TARGET },
|
||||
),
|
||||
{ position: () => TARGET, frame: 'autodetect' },
|
||||
);
|
||||
renderer.camera = Object.create(port, {
|
||||
followed: { get: () => followed },
|
||||
followFramed: { get: () => true },
|
||||
followOffset: {
|
||||
value: Object.freeze({
|
||||
get() {
|
||||
const p = camera.position;
|
||||
return { x: p.x, y: p.y, z: p.z };
|
||||
},
|
||||
set(offset) {
|
||||
camera.lookAtTransform(
|
||||
camera.transform,
|
||||
new Cesium.Cartesian3(offset.x, offset.y, offset.z),
|
||||
);
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
return viewer;
|
||||
}
|
||||
|
||||
function samePose(actual, expected) {
|
||||
for (const key of ['positionWC', 'directionWC', 'upWC'])
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.equalsEpsilon(
|
||||
actual[key],
|
||||
expected[key],
|
||||
0,
|
||||
key === 'positionWC' ? 1e-6 : 1e-9,
|
||||
),
|
||||
`${key}: ${actual[key]} vs ${expected[key]}`,
|
||||
);
|
||||
assert.ok(
|
||||
Cesium.Matrix4.equalsEpsilon(actual.transform, expected.transform, 1e-9),
|
||||
'the camera stays in the follow frame',
|
||||
);
|
||||
}
|
||||
|
||||
const snapshot = (camera) => ({
|
||||
positionWC: Cesium.Cartesian3.clone(camera.positionWC),
|
||||
directionWC: Cesium.Cartesian3.clone(camera.directionWC),
|
||||
upWC: Cesium.Cartesian3.clone(camera.upWC),
|
||||
transform: Cesium.Matrix4.clone(camera.transform),
|
||||
});
|
||||
|
||||
for (const [label, offset] of [
|
||||
['oblique', { heading: 0.4, pitch: -0.6, range: 2500 }],
|
||||
// The top-down view: angles read off a direction would lose its roll.
|
||||
['straight down', { heading: 0, pitch: -89 * (Math.PI / 180), range: 2500 }],
|
||||
])
|
||||
test(`placing the follow eye keeps an orbit frame and lands where lookAt puts it (${label})`, () => {
|
||||
// What Cesium's own calls did: look at the target, then re-enter the
|
||||
// follow's frame keeping the world pose.
|
||||
const { camera: reference } = realCamera();
|
||||
reference.lookAtTransform(orbitFrame(), START);
|
||||
const tracked = Cesium.Matrix4.clone(reference.transform);
|
||||
reference.lookAt(
|
||||
TARGET,
|
||||
new Cesium.HeadingPitchRange(offset.heading, offset.pitch, offset.range),
|
||||
);
|
||||
reference.lookAtTransform(tracked);
|
||||
|
||||
const viewer = following();
|
||||
assert.equal(placeFollowEye(viewer, TARGET, offset), true);
|
||||
samePose(snapshot(viewer.camera), snapshot(reference));
|
||||
});
|
||||
|
||||
for (const offset of [
|
||||
{ range: 1800, heading: 20, pitch: -30 },
|
||||
{ range: 1800, heading: 20, pitch: -88 },
|
||||
])
|
||||
test(`a shared offset is re-expressed in an orbit frame as Cesium’s own calls did (pitch ${offset.pitch})`, () => {
|
||||
const local = followOffsetToEnu(offset);
|
||||
// What Cesium's own calls did in one frame: the goal in the follow frame,
|
||||
// and the eye looking at its origin from there. The eye starts a little
|
||||
// off the goal, so one frame's turn reaches it.
|
||||
const world = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(TARGET),
|
||||
new Cesium.Cartesian3(local.east, local.north, local.up),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const goal = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Matrix4.inverseTransformation(orbitFrame(), new Cesium.Matrix4()),
|
||||
world,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const start = new Cesium.Cartesian3(goal.x * 1.2, goal.y, goal.z * 0.8);
|
||||
const { camera: reference } = realCamera();
|
||||
reference.lookAtTransform(orbitFrame(), start);
|
||||
reference.lookAtTransform(reference.transform, goal);
|
||||
|
||||
const viewer = following(start);
|
||||
// The camera port's own listeners stay; the offset's goes on arrival.
|
||||
const own = viewer.scene.preUpdate.numberOfListeners;
|
||||
applyShareFollowOffset(viewer, followedOf(viewer), offset);
|
||||
viewer.scene.preUpdate.raiseEvent();
|
||||
viewer.scene.preUpdate.raiseEvent();
|
||||
assert.equal(viewer.scene.preUpdate.numberOfListeners, own, 'it arrives');
|
||||
samePose(snapshot(viewer.camera), snapshot(reference));
|
||||
});
|
||||
|
||||
test('placing the follow eye does nothing on a camera that cannot say its frame', () => {
|
||||
const viewer = following();
|
||||
const port = findCamera(viewer);
|
||||
Object.defineProperty(port, 'followFrame', { value: undefined });
|
||||
const before = snapshot(viewer.camera);
|
||||
assert.equal(
|
||||
placeFollowEye(viewer, TARGET, { heading: 0, pitch: -0.5, range: 900 }),
|
||||
false,
|
||||
);
|
||||
samePose(snapshot(viewer.camera), before);
|
||||
});
|
||||
+164
-49
@@ -19,6 +19,10 @@ import {
|
||||
followCameraFor,
|
||||
followOffsetToEnu,
|
||||
} from '../share/viewCodec.js';
|
||||
import { entityRecord, withEntityRecord } from '../data/entityRecords.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { entityFollowTarget, followedOf } from '../data/followed.js';
|
||||
import { rendererOf } from '../render/rendererOf.js';
|
||||
|
||||
const NOW_MS = Date.now();
|
||||
const FIX = { lat: 37.6213, lon: -122.379, alt: 3200 };
|
||||
@@ -121,13 +125,114 @@ function fakeViewer() {
|
||||
|
||||
const flush = () => new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
/** A frame port whose preUpdate is the fake viewer's scene's, read when subscribed. */
|
||||
const preUpdateFrame = (viewer) => ({
|
||||
on: (phase, cb) =>
|
||||
phase === 'preUpdate'
|
||||
? (viewer.scene?.preUpdate?.addEventListener(cb) ?? (() => {}))
|
||||
: () => {},
|
||||
});
|
||||
|
||||
/**
|
||||
* Give `viewer`'s bound camera port a follow, as the Cesium renderer's is:
|
||||
* `follow(target)` sets `followed` and raises `followChanged`; a follow is
|
||||
* framed at once, and its offset is the fake camera's eye in its frame, set
|
||||
* by `lookAtTransform` in the frame it is in. Returns the port.
|
||||
*/
|
||||
function followingPort(viewer) {
|
||||
const renderer = rendererOf(viewer);
|
||||
const port = renderer.camera;
|
||||
const listeners = new Set();
|
||||
let followed = null;
|
||||
renderer.camera = Object.create(port, {
|
||||
followed: { get: () => followed },
|
||||
followFramed: { get: () => followed !== null },
|
||||
follow: {
|
||||
value(target) {
|
||||
followed = target;
|
||||
for (const cb of [...listeners]) cb();
|
||||
},
|
||||
},
|
||||
followOffset: {
|
||||
value: Object.freeze({
|
||||
get() {
|
||||
const p = followed ? viewer.camera.position : null;
|
||||
return p ? { x: p.x, y: p.y, z: p.z } : null;
|
||||
},
|
||||
set(offset) {
|
||||
if (!followed) return;
|
||||
viewer.camera.lookAtTransform(
|
||||
viewer.camera.transform,
|
||||
new Cesium.Cartesian3(offset.x, offset.y, offset.z),
|
||||
);
|
||||
},
|
||||
}),
|
||||
},
|
||||
on: {
|
||||
value(event, cb, options) {
|
||||
if (event !== 'followChanged') return port.on(event, cb, options);
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
},
|
||||
},
|
||||
});
|
||||
return renderer.camera;
|
||||
}
|
||||
|
||||
/** Follow `entity` (an entity holder) through `viewer`'s camera port. */
|
||||
const followIn = (viewer, entity) =>
|
||||
rendererOf(viewer).camera.follow(
|
||||
entity ? entityFollowTarget(entity, {}) : null,
|
||||
);
|
||||
|
||||
/**
|
||||
* A Cesium-shaped camera in `transform` with its eye at `position` there:
|
||||
* a view set on it (a world pose) lands in that frame, and each eye it is
|
||||
* given is recorded in `looks`, in the frame.
|
||||
*/
|
||||
function cameraInFrame(transform, position, looks) {
|
||||
return {
|
||||
transform,
|
||||
position,
|
||||
get positionWC() {
|
||||
return Cesium.Matrix4.multiplyByPoint(
|
||||
this.transform,
|
||||
this.position,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
},
|
||||
setView({ destination }) {
|
||||
const local = Cesium.Matrix4.multiplyByPoint(
|
||||
Cesium.Matrix4.inverseTransformation(
|
||||
this.transform,
|
||||
new Cesium.Matrix4(),
|
||||
),
|
||||
destination,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
looks.push(local);
|
||||
this.position = local;
|
||||
},
|
||||
// As the follow moves the eye: an eye in the frame.
|
||||
lookAtTransform(frame, offset) {
|
||||
this.transform = frame;
|
||||
const local = Cesium.Cartesian3.clone(offset);
|
||||
looks.push(local);
|
||||
this.position = local;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A ShareRestoration over a real ShareLinkManager, as the shell wires them. */
|
||||
function openPage(t, href, { managerOptions = {}, tracking = null } = {}) {
|
||||
const page = installPage(t, href);
|
||||
const clock = installManualTimers(t);
|
||||
const viewer = fakeViewer();
|
||||
const restores = [];
|
||||
const manager = new ShareLinkManager(viewer, {
|
||||
// Bound first with a frame port: the share follow runs on its preUpdate.
|
||||
bindFakeCesiumCamera(viewer, { frame: preUpdateFrame(viewer) });
|
||||
followingPort(viewer);
|
||||
const manager = new ShareLinkManager(bindFakeCesiumCamera(viewer), {
|
||||
onRestore: async (state) => restores.push(state),
|
||||
isNavigationCurrent: () => true,
|
||||
...managerOptions,
|
||||
@@ -248,7 +353,7 @@ test('a thing view turns its layer on, follows by id and frames the shared offse
|
||||
const page = openPage(t, `http://localhost/share/${aircraftCode()}`, {
|
||||
tracking: (owner) => {
|
||||
// What the coordinator does when the aircraft is in the feed.
|
||||
owner.viewer.trackedEntity = entity;
|
||||
followIn(owner.viewer, entity);
|
||||
owner._handleShareTrackingRestoreStatus({
|
||||
layerId: 'flights',
|
||||
targetId: 'a1b2c3',
|
||||
@@ -272,19 +377,20 @@ test('a thing view turns its layer on, follows by id and frames the shared offse
|
||||
},
|
||||
isDestroyed: () => false,
|
||||
});
|
||||
Object.assign(page.viewer.camera, {
|
||||
transform: Cesium.Transforms.eastNorthUpToFixedFrame(target),
|
||||
// The app's own follow framing: south of the aircraft and above it.
|
||||
position: new Cesium.Cartesian3(0, -4800, 3300),
|
||||
lookAtTransform(transform, offset) {
|
||||
looks.push(offset);
|
||||
this.position = Cesium.Cartesian3.clone(offset);
|
||||
},
|
||||
});
|
||||
entity = {
|
||||
gevTrackedId: 'flights:a1b2c3',
|
||||
gevDisplayPosition: () => target,
|
||||
};
|
||||
// The app's own follow framing: south of the aircraft and above it.
|
||||
const followCamera = cameraInFrame(
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(target),
|
||||
new Cesium.Cartesian3(0, -4800, 3300),
|
||||
looks,
|
||||
);
|
||||
Object.defineProperties(
|
||||
page.viewer.camera,
|
||||
Object.getOwnPropertyDescriptors(followCamera),
|
||||
);
|
||||
entity = withEntityRecord(
|
||||
{},
|
||||
{ trackedId: 'flights:a1b2c3', displayPosition: () => target },
|
||||
);
|
||||
|
||||
const parsed = page.manager._parseShareCode(aircraftCode());
|
||||
assert.deepEqual(parsed.layerState.enabledLayerIds, ['flights']);
|
||||
@@ -305,7 +411,8 @@ test('a thing view turns its layer on, follows by id and frames the shared offse
|
||||
Math.abs(Cesium.Math.toDegrees(destination.longitude) - camera.lon) < 1e-3,
|
||||
);
|
||||
// Once followed, the camera takes the shared offset after the follow's
|
||||
// own first frame.
|
||||
// own first frame. (The restore's own views do not count.)
|
||||
looks.length = 0;
|
||||
assert.equal(listeners.length, 1);
|
||||
listeners[0]();
|
||||
assert.equal(looks.length, 0);
|
||||
@@ -440,7 +547,7 @@ test('a shared vessel is selected once the vessel feed has it', async (t) => {
|
||||
|
||||
test('the share button links to /share/<code>, following the followed entity', (t) => {
|
||||
installPage(t, 'https://gev.example/?lang=ru#v=2&lat=1&lon=2');
|
||||
const manager = new ShareLinkManager(fakeViewer());
|
||||
const manager = new ShareLinkManager(bindFakeCesiumCamera(fakeViewer()));
|
||||
// A fresh session's look, as the app reports it at start-up.
|
||||
manager.onToggleChange(false, true, {
|
||||
hudVisible: true,
|
||||
@@ -486,14 +593,16 @@ test('the followed entity is read in the share format, and its offset round-trip
|
||||
new Cesium.Cartesian3(local.east, local.north, local.up),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const viewer = {
|
||||
const viewer = bindFakeCesiumCamera({
|
||||
camera: { positionWC: cameraPosition },
|
||||
clock: { currentTime: Cesium.JulianDate.now() },
|
||||
trackedEntity: {
|
||||
gevTrackedId: 'military:ae1234',
|
||||
gevDisplayPosition: () => target,
|
||||
},
|
||||
};
|
||||
});
|
||||
followingPort(viewer);
|
||||
const entity = withEntityRecord(
|
||||
{},
|
||||
{ trackedId: 'military:ae1234', displayPosition: () => target },
|
||||
);
|
||||
followIn(viewer, entity);
|
||||
const subject = readShareFollowSubject({ viewer, nowMs: NOW_MS });
|
||||
assert.equal(subject.kind, 'military_aircraft');
|
||||
assert.equal(subject.id, 'ae1234');
|
||||
@@ -501,10 +610,10 @@ test('the followed entity is read in the share format, and its offset round-trip
|
||||
assert.ok(Math.abs(subject.lastKnown.lat - FIX.lat) < 1e-9);
|
||||
assert.ok(Math.abs(subject.lastKnown.alt - FIX.alt) < 1e-3);
|
||||
// A followed entity the share format has no kind for is not a thing view.
|
||||
viewer.trackedEntity.gevTrackedId = 'local-adsb:abc';
|
||||
entityRecord(entity).trackedId = 'local-adsb:abc';
|
||||
assert.equal(readShareFollowSubject({ viewer }), null);
|
||||
// Nor is a camera that follows nothing (a selected vessel is not followed).
|
||||
viewer.trackedEntity = undefined;
|
||||
followIn(viewer, null);
|
||||
assert.equal(readShareFollowSubject({ viewer }), null);
|
||||
});
|
||||
|
||||
@@ -512,7 +621,7 @@ test('a shared offset on the far side swings round, never jumping through the en
|
||||
const target = Cesium.Cartesian3.fromDegrees(FIX.lon, FIX.lat, FIX.alt);
|
||||
const listeners = [];
|
||||
const looks = [];
|
||||
const entity = { gevDisplayPosition: () => target };
|
||||
const entity = withEntityRecord({}, { displayPosition: () => target });
|
||||
const viewer = {
|
||||
clock: { currentTime: Cesium.JulianDate.now() },
|
||||
scene: {
|
||||
@@ -523,28 +632,29 @@ test('a shared offset on the far side swings round, never jumping through the en
|
||||
},
|
||||
},
|
||||
},
|
||||
trackedEntity: entity,
|
||||
camera: {
|
||||
transform: Cesium.Transforms.eastNorthUpToFixedFrame(target),
|
||||
position: new Cesium.Cartesian3(0, -4800, 3300),
|
||||
lookAtTransform(transform, offset) {
|
||||
looks.push(Cesium.Cartesian3.clone(offset));
|
||||
this.position = Cesium.Cartesian3.clone(offset);
|
||||
},
|
||||
},
|
||||
camera: cameraInFrame(
|
||||
Cesium.Transforms.eastNorthUpToFixedFrame(target),
|
||||
new Cesium.Cartesian3(0, -4800, 3300),
|
||||
looks,
|
||||
),
|
||||
};
|
||||
bindFakeCesiumCamera(viewer, { frame: preUpdateFrame(viewer) });
|
||||
followingPort(viewer);
|
||||
followIn(viewer, entity);
|
||||
// Looking south at the nose: the opposite side of the app's framing.
|
||||
const offset = { range: 5800, heading: 180, pitch: -35 };
|
||||
applyShareFollowOffset(viewer, entity, offset);
|
||||
// The camera port's own listeners stay; the offset's is the one added.
|
||||
const own = listeners.length;
|
||||
applyShareFollowOffset(viewer, followedOf(viewer), offset);
|
||||
let previous = viewer.camera.position;
|
||||
for (let frame = 0; frame < 10 && listeners.length; frame += 1) {
|
||||
listeners[0]();
|
||||
for (let frame = 0; frame < 10 && listeners.length > own; frame += 1) {
|
||||
listeners[own]();
|
||||
const now = viewer.camera.position;
|
||||
// The follow's guard treats a turn of 90° or more as a crossing.
|
||||
assert.ok(Cesium.Cartesian3.angleBetween(previous, now) < Math.PI / 2);
|
||||
previous = now;
|
||||
}
|
||||
assert.equal(listeners.length, 0, 'it arrives');
|
||||
assert.equal(listeners.length, own, 'it arrives');
|
||||
assert.ok(looks.length >= 2, `${looks.length} steps`);
|
||||
const expected = followOffsetToEnu(offset);
|
||||
const last = looks.at(-1);
|
||||
@@ -565,10 +675,13 @@ test('applying a follow offset gives up when the follow ends', () => {
|
||||
},
|
||||
},
|
||||
trackedEntity: null,
|
||||
camera: {},
|
||||
};
|
||||
bindFakeCesiumCamera(viewer, { frame: preUpdateFrame(viewer) });
|
||||
const own = listeners.length;
|
||||
applyShareFollowOffset(viewer, {}, OFFSET);
|
||||
listeners[0]();
|
||||
assert.equal(listeners.length, 0);
|
||||
listeners[own]();
|
||||
assert.equal(listeners.length, own);
|
||||
});
|
||||
|
||||
test('long links and hash navigation are unaffected by a share code start', async (t) => {
|
||||
@@ -615,7 +728,7 @@ test('a selected vessel is the subject when the camera follows nothing', (t) =>
|
||||
installPage(t, 'https://gev.example/');
|
||||
const offset = { range: 6400, heading: 250, pitch: -28 };
|
||||
const { vessel, camera } = cameraAround(offset);
|
||||
const viewer = fakeViewer();
|
||||
const viewer = bindFakeCesiumCamera(fakeViewer());
|
||||
viewer.camera.positionWC = camera;
|
||||
const fixAtMs = Math.floor(NOW_MS / 1000) * 1000 - 90_000;
|
||||
let selected = { id: VESSEL_UUID, position: vessel, observedAtMs: fixAtMs };
|
||||
@@ -702,19 +815,21 @@ test('a followed aircraft or satellite keeps priority over a selected vessel', (
|
||||
position: vessel,
|
||||
observedAtMs: NOW_MS,
|
||||
});
|
||||
const viewer = {
|
||||
const viewer = bindFakeCesiumCamera({
|
||||
camera: { positionWC: camera },
|
||||
clock: { currentTime: Cesium.JulianDate.now() },
|
||||
trackedEntity: {
|
||||
gevTrackedId: 'satellites:25544',
|
||||
gevDisplayPosition: () => vessel,
|
||||
},
|
||||
};
|
||||
});
|
||||
followingPort(viewer);
|
||||
const entity = withEntityRecord(
|
||||
{},
|
||||
{ trackedId: 'satellites:25544', displayPosition: () => vessel },
|
||||
);
|
||||
followIn(viewer, entity);
|
||||
const subject = readShareFollowSubject({ viewer, readSelectedVessel });
|
||||
assert.equal(subject.kind, 'satellite');
|
||||
// A followed entity the share format cannot name is still followed: the
|
||||
// link is a place view, not the selected vessel.
|
||||
viewer.trackedEntity.gevTrackedId = 'local-adsb:abc';
|
||||
entityRecord(entity).trackedId = 'local-adsb:abc';
|
||||
assert.equal(readShareFollowSubject({ viewer, readSelectedVessel }), null);
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import { canPresentDeferredStatusNotice } from '../loadingFeedback.js';
|
||||
import { t, msg, formatDate } from '../i18n/index.js';
|
||||
import { SHARE_VIEW_ENTITY_KINDS } from '../share/follow.js';
|
||||
import { UiLifetime } from './uiLifetime.js';
|
||||
import { followedOf } from '../data/followed.js';
|
||||
import { canvasOf } from '../render/rendererOf.js';
|
||||
import { isWorldTime, worldClock } from '../time/worldClock.js';
|
||||
|
||||
// A link made away from live opens at its world time, paused. One without a
|
||||
@@ -259,14 +261,14 @@ export class ShareRestoration {
|
||||
this.navigation._stampNavigation(options),
|
||||
);
|
||||
};
|
||||
this.viewer?.canvas?.addEventListener(
|
||||
canvasOf(this.viewer)?.addEventListener(
|
||||
'pointerdown',
|
||||
this._initialShareGestureHandler,
|
||||
{
|
||||
passive: true,
|
||||
},
|
||||
);
|
||||
this.viewer?.canvas?.addEventListener(
|
||||
canvasOf(this.viewer)?.addEventListener(
|
||||
'wheel',
|
||||
this._initialShareGestureHandler,
|
||||
{
|
||||
@@ -487,17 +489,16 @@ export class ShareRestoration {
|
||||
/** Frame a shared entity the camera now follows from the shared offset. */
|
||||
_applySharedFollowOffset(result) {
|
||||
const view = this._sharedThingFor(result);
|
||||
const entity = this.viewer?.trackedEntity;
|
||||
const followed = followedOf(this.viewer);
|
||||
// Only a link made while following carries a real offset (with the fix);
|
||||
// a long link's follow keeps the app's own framing.
|
||||
if (
|
||||
!view?.lastKnown ||
|
||||
String(entity?.gevTrackedId || '') !==
|
||||
`${result.layerId}:${result.targetId}`
|
||||
String(followed?.key || '') !== `${result.layerId}:${result.targetId}`
|
||||
)
|
||||
return;
|
||||
this._stopFollowOffset?.();
|
||||
this._stopFollowOffset = this.applyFollowOffset?.(entity, view.offset);
|
||||
this._stopFollowOffset = this.applyFollowOffset?.(followed, view.offset);
|
||||
}
|
||||
|
||||
cancelSelection() {
|
||||
@@ -661,11 +662,11 @@ export class ShareRestoration {
|
||||
share: null,
|
||||
layers: [],
|
||||
});
|
||||
this.viewer?.canvas?.removeEventListener(
|
||||
canvasOf(this.viewer)?.removeEventListener(
|
||||
'pointerdown',
|
||||
this._initialShareGestureHandler,
|
||||
);
|
||||
this.viewer?.canvas?.removeEventListener(
|
||||
canvasOf(this.viewer)?.removeEventListener(
|
||||
'wheel',
|
||||
this._initialShareGestureHandler,
|
||||
);
|
||||
|
||||
@@ -501,14 +501,6 @@ export class ShellFacade {
|
||||
return this._visualSettings.sharpenEnabled;
|
||||
}
|
||||
|
||||
get _bloomStage() {
|
||||
return this._visualEffects.bloomStage;
|
||||
}
|
||||
|
||||
get _sharpenStage() {
|
||||
return this._visualEffects.sharpenStage;
|
||||
}
|
||||
|
||||
/** Settle only the search generation that still owns the shared input UI. */
|
||||
_settleLocationSearchUi(generation, options) {
|
||||
return this._navigation._settleLocationSearchUi(...arguments);
|
||||
@@ -891,6 +883,10 @@ export class ShellFacade {
|
||||
return this._contextControls?._preservePanelStateDuringLayerClear ?? false;
|
||||
}
|
||||
|
||||
_contextSuspendsLayer(layerId) {
|
||||
return this._contextControls?.suspendsLayer(layerId) ?? false;
|
||||
}
|
||||
|
||||
_runUserFacingContextAction(...args) {
|
||||
return this._contextControls?._runUserFacingContextAction(...args);
|
||||
}
|
||||
|
||||
@@ -259,7 +259,7 @@ test('recording restores the original HUD after repeated entry and revokes retai
|
||||
}
|
||||
});
|
||||
|
||||
test('weather rail orders between CCTV and Context, observes and presents chrome', (t) => {
|
||||
test('Context leads the right rail, weather follows CCTV, observes and presents chrome', (t) => {
|
||||
const f = fixture();
|
||||
const observed = new Set();
|
||||
const previousResizeObserver = globalThis.ResizeObserver;
|
||||
@@ -319,7 +319,7 @@ test('weather rail orders between CCTV and Context, observes and presents chrome
|
||||
owner._initRightPanelAdaptiveLayout();
|
||||
assert.deepEqual(
|
||||
stack.children.map((panel) => panel.id),
|
||||
['pp-toggles', 'cctv-panel', 'weather-panel', 'global-context-panel'],
|
||||
['global-context-panel', 'pp-toggles', 'cctv-panel', 'weather-panel'],
|
||||
);
|
||||
assert.ok(observed.has(weather));
|
||||
// Moving a panel into the rail leaves its state as it was.
|
||||
|
||||
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { LocationNavigation } from './locationNavigation.js';
|
||||
import { LayerBindings } from './layerBindings.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
|
||||
function replaceWindow(t, value) {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
@@ -128,12 +129,16 @@ test('camera-entry listeners are removed before any asynchronous layer cleanup',
|
||||
const { owner } = bindings(t);
|
||||
let changes = 0;
|
||||
let trackedCallback;
|
||||
owner.viewer = { trackedEntityChanged: {
|
||||
addEventListener(callback) {
|
||||
// What the camera follows changes through its port's followChanged.
|
||||
owner.viewer = {};
|
||||
bindRenderer(owner.viewer, { camera: {
|
||||
followed: null,
|
||||
on(event, callback) {
|
||||
if (event !== 'followChanged') return () => {};
|
||||
trackedCallback = callback;
|
||||
return () => { changes += 1; };
|
||||
},
|
||||
} };
|
||||
} });
|
||||
owner._stampNavigation = () => { changes += 100; };
|
||||
owner.observeCamera();
|
||||
owner.stop();
|
||||
|
||||
@@ -117,6 +117,19 @@ test('visual teardown restores owned fog and aircraft sensor state once', async
|
||||
});
|
||||
const calls = [];
|
||||
const viewer = { scene: { fog: { enabled: false } } };
|
||||
// The fog is the globe port's sky, which writes the scene's, as the
|
||||
// renderer's does.
|
||||
const { bindRenderer } = await import('../render/rendererOf.js');
|
||||
bindRenderer(viewer, {
|
||||
globe: {
|
||||
sky: {
|
||||
get: () => ({ fog: viewer.scene.fog.enabled }),
|
||||
set(settings) {
|
||||
if ('fog' in settings) viewer.scene.fog.enabled = settings.fog;
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const owner = new VisualSettings({
|
||||
viewer,
|
||||
elements: {},
|
||||
|
||||
@@ -28,6 +28,46 @@ export const useDisplayStore = defineStore('gev-display', () => {
|
||||
models3d.value = markRaw(next);
|
||||
}
|
||||
|
||||
/**
|
||||
* The groups added under Effects, in the order first
|
||||
* published: each `{id, rows}`. A row is a `toggle` (`{kind, id, label,
|
||||
* icon?, title?, checked, onChange(checked)}`), a `slider` (`{kind, id,
|
||||
* label, min, max, value, onChange(value)}`, its value shown in percent)
|
||||
* or a `note` (`{kind, id, text}`).
|
||||
*/
|
||||
const groups = shallowRef([]);
|
||||
|
||||
/**
|
||||
* Show the group `id` as `group` describes it, in place where it is shown
|
||||
* already; null takes it away.
|
||||
* @param {string} id
|
||||
* @param {?{rows: object[]}} group
|
||||
*/
|
||||
function publishGroup(id, group) {
|
||||
const at = groups.value.findIndex((g) => g.id === id);
|
||||
const next = [...groups.value];
|
||||
if (!group) {
|
||||
if (at < 0) return;
|
||||
next.splice(at, 1);
|
||||
} else {
|
||||
const shown = markRaw({ id, rows: [...(group.rows ?? [])] });
|
||||
if (at < 0) next.push(shown);
|
||||
else next[at] = shown;
|
||||
}
|
||||
groups.value = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Sky group, `{switches, milkyWay}` (switches by name, the Milky Way
|
||||
* in percent); null where the renderer has no sky to set.
|
||||
*/
|
||||
const sky = shallowRef(null);
|
||||
|
||||
/** @param {?object} next A fresh presentation of the Sky group. */
|
||||
function publishSky(next) {
|
||||
sky.value = next && markRaw(next);
|
||||
}
|
||||
|
||||
/** The Draw controls; null until the draw tool first renders. */
|
||||
const draw = shallowRef(null);
|
||||
|
||||
@@ -108,6 +148,10 @@ export const useDisplayStore = defineStore('gev-display', () => {
|
||||
publish,
|
||||
models3d,
|
||||
publishModels3d,
|
||||
groups,
|
||||
publishGroup,
|
||||
sky,
|
||||
publishSky,
|
||||
draw,
|
||||
publishDraw,
|
||||
geoImport,
|
||||
|
||||
Loaded 100 of 1502 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user