mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-24 12:12:19 +00:00
Merge remote-tracking branch 'origin/main' into denis/iss-live-telemetry
# Conflicts: # docs/CURRENT-STATE.md # scripts/package-boundaries.json # src/layers/satellites/interaction.js # src/layers/satellites/lifecycle.js # src/layers/satellites/tracking.js
This commit is contained in:
commit
fd3ca679ec
1125 files changed
+149994
-45970
No files matched your search
+43
-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,6 +64,7 @@ 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';
|
||||
@@ -94,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.
|
||||
@@ -212,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({
|
||||
@@ -393,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,
|
||||
@@ -465,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,
|
||||
@@ -479,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,
|
||||
});
|
||||
@@ -1060,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'),
|
||||
@@ -1241,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: () =>
|
||||
@@ -1517,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),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1537,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,
|
||||
});
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1802,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}
|
||||
*/
|
||||
|
||||
|
||||
+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',
|
||||
|
||||
@@ -11,6 +11,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';
|
||||
|
||||
@@ -89,6 +95,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 } = {},
|
||||
@@ -115,7 +169,6 @@ function fixture(
|
||||
// Each placed camera: where it is and where it looks.
|
||||
const shots = [];
|
||||
const viewer = {
|
||||
trackedEntity: undefined,
|
||||
clock: { currentTime: null },
|
||||
camera: {
|
||||
cancelFlight() {},
|
||||
@@ -142,6 +195,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: {
|
||||
@@ -369,10 +427,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],
|
||||
@@ -380,6 +438,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();
|
||||
@@ -415,7 +485,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();
|
||||
@@ -818,7 +888,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');
|
||||
@@ -868,7 +938,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');
|
||||
@@ -906,6 +976,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.
|
||||
@@ -929,6 +1000,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();
|
||||
@@ -1504,7 +1579,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.
|
||||
@@ -1530,7 +1605,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);
|
||||
|
||||
+140
-190
@@ -1,5 +1,25 @@
|
||||
/** 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,
|
||||
@@ -31,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,
|
||||
@@ -77,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 });
|
||||
@@ -93,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;
|
||||
@@ -133,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,
|
||||
@@ -156,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) &&
|
||||
@@ -165,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)
|
||||
@@ -173,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;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -200,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 {
|
||||
@@ -219,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;
|
||||
}
|
||||
@@ -254,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
|
||||
@@ -314,7 +340,7 @@ function updateVessel(nowMs) {
|
||||
*/
|
||||
function updateSubject(nowMs) {
|
||||
const provider = this.subjectProvider;
|
||||
if (this.viewer.trackedEntity?.position) {
|
||||
if (isFollowing(this.viewer)) {
|
||||
this.exit({ restoreTracking: false });
|
||||
return;
|
||||
}
|
||||
@@ -374,13 +400,7 @@ function updateSubject(nowMs) {
|
||||
this.surfaceWaitStartedMs = 0;
|
||||
this.surfaceAcquiring = false;
|
||||
this.subjectHeightM = heightM;
|
||||
const target = Cesium.Cartesian3.fromDegrees(
|
||||
frame.longitude,
|
||||
frame.latitude,
|
||||
heightM,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
this.scratchTarget,
|
||||
);
|
||||
const target = fromDegrees(frame.longitude, frame.latitude, heightM);
|
||||
const dtSec = cockpitSubjectStepSec(nowMs - this.lastFrameMs, intervalMs);
|
||||
this.lastFrameMs = nowMs;
|
||||
if (frame.headingDeg !== null) {
|
||||
@@ -426,7 +446,7 @@ function updateSubject(nowMs) {
|
||||
* 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 {Cesium.Cartesian3} target Authoritative subject position.
|
||||
* @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.
|
||||
@@ -440,7 +460,7 @@ function updateSubject(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;
|
||||
}
|
||||
@@ -452,15 +472,13 @@ 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)
|
||||
@@ -471,40 +489,20 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
// 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(
|
||||
@@ -514,15 +512,9 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -532,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(
|
||||
@@ -571,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(
|
||||
@@ -643,83 +627,50 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
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,
|
||||
);
|
||||
const cameraCartographic = toCartographicRadians(eye);
|
||||
if (groundClamp && cameraCartographic) {
|
||||
const cameraLat = Cesium.Math.toDegrees(cameraCartographic.latitude);
|
||||
const cameraLon = Cesium.Math.toDegrees(cameraCartographic.longitude);
|
||||
const cameraLat = toDegrees(cameraCartographic.lat);
|
||||
const cameraLon = toDegrees(cameraCartographic.lon);
|
||||
const cameraFloorM = this.services.cachedGroundFloor(cameraLat, cameraLon);
|
||||
if (Number.isFinite(cameraFloorM)) {
|
||||
cockpitFloorM = Math.max(
|
||||
@@ -748,28 +699,27 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) {
|
||||
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) {
|
||||
cameraCartographic.height += this.subjectLiftM;
|
||||
Cesium.Ellipsoid.WGS84.cartographicToCartesian(
|
||||
cameraCartographic,
|
||||
this.scratchCamera,
|
||||
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';
|
||||
|
||||
+18
-18
@@ -1,4 +1,6 @@
|
||||
/** 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,
|
||||
@@ -36,6 +38,7 @@ import {
|
||||
import {
|
||||
onOrbitalClick,
|
||||
onOrbitalDoubleClick,
|
||||
orbitalSiteUnder,
|
||||
routeSceneClick,
|
||||
toggleOrbitalFocus,
|
||||
} from './cockpitOrbitalFocus.js';
|
||||
@@ -107,7 +110,6 @@ import { DEFAULT_RADAR_RANGE_NM, nextRadarRange } from '../cockpitRadar.js';
|
||||
import { VESSEL_BRIDGE_PITCH_DEG } from '../cockpitSubjects.js';
|
||||
import { stepLook } from '../cockpitLook.js';
|
||||
import { createCockpitSubjectCaller } from '../cockpitSubjectProviders.js';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/** Whether the user asked for reduced motion: look turns then jump. */
|
||||
function prefersReducedMotion() {
|
||||
@@ -137,11 +139,15 @@ 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', 'satellite' or a provider's kind while active;
|
||||
* which subject the camera rides.
|
||||
@@ -175,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;
|
||||
@@ -311,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();
|
||||
}),
|
||||
@@ -340,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,
|
||||
@@ -351,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 },
|
||||
@@ -498,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.
|
||||
|
||||
@@ -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 {
|
||||
@@ -11,6 +12,7 @@ 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 {
|
||||
@@ -56,6 +58,7 @@ export class CockpitCoordinator {
|
||||
meshFloorPreferred,
|
||||
warmGroundFloor,
|
||||
sampleMeshFloorCells,
|
||||
trackedEntityDrawn,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
fetchRegionalBrief,
|
||||
@@ -84,6 +87,7 @@ export class CockpitCoordinator {
|
||||
meshFloorPreferred,
|
||||
warmGroundFloor,
|
||||
sampleMeshFloorCells,
|
||||
trackedEntityDrawn,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
fetchRegionalBrief,
|
||||
@@ -142,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')
|
||||
@@ -253,12 +257,12 @@ export class CockpitCoordinator {
|
||||
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
|
||||
|
||||
@@ -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';
|
||||
@@ -78,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) },
|
||||
@@ -98,6 +106,9 @@ 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,
|
||||
@@ -179,8 +190,9 @@ 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) => {
|
||||
@@ -534,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();
|
||||
|
||||
+99
-37
@@ -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,13 +36,8 @@ 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:
|
||||
@@ -54,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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,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();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -99,6 +99,7 @@ export function syncContextLayout() {
|
||||
let safeBottom = window.innerHeight - 24;
|
||||
for (const selector of [
|
||||
'#cesium-credits',
|
||||
'#gev-credits',
|
||||
'#command-dock',
|
||||
'#view-switcher',
|
||||
]) {
|
||||
|
||||
@@ -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 { useCockpitStore } from './stores/cockpit.js';
|
||||
import { useHudStore } from './stores/hud.js';
|
||||
@@ -117,10 +128,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;
|
||||
},
|
||||
};
|
||||
@@ -204,7 +214,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) {
|
||||
@@ -237,7 +247,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 },
|
||||
@@ -254,41 +263,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 },
|
||||
@@ -317,6 +331,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() {},
|
||||
@@ -328,11 +351,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;
|
||||
@@ -344,6 +369,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;
|
||||
@@ -356,7 +382,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,
|
||||
@@ -368,12 +398,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() {
|
||||
@@ -602,7 +640,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);
|
||||
@@ -688,7 +726,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);
|
||||
@@ -878,14 +916,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);
|
||||
});
|
||||
|
||||
@@ -1006,7 +1062,7 @@ test('an aircraft and a satellite first seen in one sync: the aircraft takes ent
|
||||
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).
|
||||
@@ -1136,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,
|
||||
@@ -1184,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: {
|
||||
@@ -1437,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, {
|
||||
@@ -1530,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,
|
||||
|
||||
@@ -10,6 +10,10 @@ import { CockpitViewController } from './cockpitController.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',
|
||||
@@ -42,7 +46,6 @@ function fixture(t) {
|
||||
const listeners = () => ({ addEventListener: () => () => {} });
|
||||
const entity = { position: {}, show: true };
|
||||
const viewer = {
|
||||
trackedEntity: entity,
|
||||
camera: { cancelFlight() {} },
|
||||
entities: { contains: (candidate) => candidate === entity },
|
||||
scene: {
|
||||
@@ -51,6 +54,8 @@ function fixture(t) {
|
||||
},
|
||||
trackedEntityChanged: listeners(),
|
||||
};
|
||||
bindFakeCesiumCamera(viewer, { frame: { on: () => () => {} } });
|
||||
followEntity(viewer, entity);
|
||||
const cockpit = new CockpitViewController(viewer, {
|
||||
services: {
|
||||
flightsLayer: { getTrackedInfo: () => INFO, refreshTr3b() {} },
|
||||
|
||||
@@ -18,6 +18,11 @@ import { getLocale, setLocale } from '../i18n/index.js';
|
||||
import { COCKPIT_GROUND_WAIT_TIMEOUT_MS } from './cockpitPresentation.js';
|
||||
import { COCKPIT_SUBJECT_LIFT_MPS } from '../cockpitMath.js';
|
||||
import { vesselCockpitInfo } from '../layers/vessels/cockpitSubject.js';
|
||||
import {
|
||||
bindFakeCesiumCamera,
|
||||
followEntity,
|
||||
} from '../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
|
||||
|
||||
const LAT = 47;
|
||||
const LON = 8;
|
||||
@@ -139,7 +144,6 @@ function fixture(t, { providers = [], vessel = null, layerOn = true } = {}) {
|
||||
gevTrackedId: 'flights:abc123',
|
||||
};
|
||||
const viewer = {
|
||||
trackedEntity: undefined,
|
||||
clock: { currentTime: null },
|
||||
camera: {
|
||||
heading: 0,
|
||||
@@ -158,6 +162,10 @@ function fixture(t, { providers = [], vessel = null, layerOn = true } = {}) {
|
||||
},
|
||||
trackedEntityChanged: listeners(),
|
||||
};
|
||||
// The Cockpit drives the camera, follows and reads frames through ports:
|
||||
// the Cesium camera port over the fake camera, the scene's fake frame and
|
||||
// query ports.
|
||||
bindFakeCesiumCamera(viewer, fakeScenePorts(viewer));
|
||||
let vesselSelected = vessel;
|
||||
let trackedAircraftInfo = null;
|
||||
let floorM = FLOOR_M;
|
||||
@@ -240,7 +248,7 @@ function fixture(t, { providers = [], vessel = null, layerOn = true } = {}) {
|
||||
/** Track the fixture's aircraft as Live Flights does, or untrack it. */
|
||||
trackAircraft(info) {
|
||||
trackedAircraftInfo = info;
|
||||
viewer.trackedEntity = info ? aircraft : undefined;
|
||||
followEntity(viewer, info ? aircraft : null);
|
||||
},
|
||||
setFloor(value) {
|
||||
floorM = value;
|
||||
@@ -980,7 +988,7 @@ test('an aircraft tracked during the view ends it, never adopted', async (t) =>
|
||||
const { cockpit, viewer, aircraft } = fixture(t, { providers: [ride] });
|
||||
cockpit.syncEntry();
|
||||
cockpit.enter();
|
||||
viewer.trackedEntity = aircraft;
|
||||
followEntity(viewer, aircraft);
|
||||
assert.equal(cockpit._adoptTrackedEntity(performance.now()), false);
|
||||
clock.advance(16);
|
||||
cockpit.update();
|
||||
|
||||
@@ -1,29 +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 || '',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -139,15 +155,11 @@ export function entryCandidates(nowMs = performance.now()) {
|
||||
list.push({ kind, id, seenAtMs: seen.get(kind).atMs, ...entry });
|
||||
};
|
||||
const aircraft = this.readAircraftInfo();
|
||||
if (aircraft && this.viewer.trackedEntity?.position)
|
||||
const followed = aircraft ? followedOf(this.viewer) : null;
|
||||
if (aircraft && followed?.entity?.position)
|
||||
note(
|
||||
'aircraft',
|
||||
String(
|
||||
this.viewer.trackedEntity.gevTrackedId ||
|
||||
aircraft.icao24 ||
|
||||
aircraft.id ||
|
||||
'aircraft',
|
||||
),
|
||||
String(followed.key || aircraft.icao24 || aircraft.id || 'aircraft'),
|
||||
{
|
||||
order: BUILT_IN_ENTRY_ORDER.aircraft,
|
||||
allowed: () => this.isEntryAllowed(),
|
||||
@@ -211,8 +223,8 @@ export function resolveEntry(nowMs = performance.now()) {
|
||||
/**
|
||||
* The layer the active view rides: Live AIS Vessels on a bridge, Satellites
|
||||
* in orbit, a provider's own layer, 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.
|
||||
* 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() {
|
||||
@@ -222,13 +234,13 @@ export function readSubjectLayerId() {
|
||||
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 kind entry would take, the first in entry order's (resolveEntry): a
|
||||
* Cesium-tracked aircraft, the tracked satellite, the selected vessel or a
|
||||
* followed aircraft, the tracked satellite, the selected vessel or a
|
||||
* provider's candidate.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
@@ -377,8 +389,8 @@ export function navigateContext(direction, options = {}) {
|
||||
}
|
||||
|
||||
export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
|
||||
// An aircraft tracked from the bridge, from orbit or from a provider's view
|
||||
// ends that view (see the camera updates); it is never adopted as its
|
||||
// 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' ||
|
||||
@@ -386,7 +398,8 @@ export function _adoptTrackedEntity(nowMs, suppliedInfo = null) {
|
||||
this.subjectProvider
|
||||
)
|
||||
return false;
|
||||
const nextEntity = this.viewer.trackedEntity;
|
||||
const nextFollowed = followedOf(this.viewer);
|
||||
const nextEntity = nextFollowed?.entity;
|
||||
if (
|
||||
!this.active ||
|
||||
!nextEntity?.position ||
|
||||
@@ -395,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;
|
||||
@@ -479,7 +493,7 @@ function enterSubject(provider) {
|
||||
? document.activeElement
|
||||
: null;
|
||||
this.onCameraTakeover?.();
|
||||
this.viewer.camera.cancelFlight();
|
||||
cameraOf(this.viewer).cancelFlight();
|
||||
this.subjectKind = provider.kind;
|
||||
this.subjectProvider = provider;
|
||||
this.subjectId = candidate.id;
|
||||
@@ -490,7 +504,7 @@ function enterSubject(provider) {
|
||||
this.vesselFix = null;
|
||||
this.trackedEntity = null;
|
||||
this.heading = normalizeHeading(
|
||||
frame.headingDeg ?? cameraHeadingDeg(this.viewer.camera),
|
||||
frame.headingDeg ?? cameraHeadingDeg(cameraOf(this.viewer).pose()),
|
||||
);
|
||||
this.lastFrameMs = performance.now();
|
||||
this.lastCameraUpdateMs = 0;
|
||||
@@ -507,8 +521,9 @@ function enterSubject(provider) {
|
||||
this.resetLook({ immediate: true });
|
||||
this.active = true;
|
||||
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', 'cockpit-subject');
|
||||
this._tr3bSignature = null;
|
||||
Object.assign(this.presence, {
|
||||
@@ -575,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
|
||||
@@ -584,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;
|
||||
@@ -607,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();
|
||||
@@ -628,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');
|
||||
@@ -710,6 +728,7 @@ 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;
|
||||
@@ -726,6 +745,7 @@ export function exit({ restoreTracking = true } = {}) {
|
||||
this.subjectId = null;
|
||||
this.services.releaseContinuousRender('cockpit');
|
||||
this.trackedEntity = null;
|
||||
this.trackedFollow = null;
|
||||
this.heading = null;
|
||||
this.resetLook({ immediate: true });
|
||||
this.cockpitAnchorValid = false;
|
||||
@@ -760,9 +780,11 @@ export function exit({ restoreTracking = true } = {}) {
|
||||
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);
|
||||
@@ -776,8 +798,8 @@ export function exit({ restoreTracking = true } = {}) {
|
||||
{ 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.
|
||||
|
||||
@@ -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: {} });
|
||||
|
||||
@@ -261,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({
|
||||
@@ -691,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>/);
|
||||
@@ -742,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,
|
||||
|
||||
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, []);
|
||||
});
|
||||
@@ -494,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,
|
||||
@@ -803,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');
|
||||
});
|
||||
+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,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),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
nextSheet,
|
||||
sheetForPanelId,
|
||||
} from './mobileShell.js';
|
||||
import { withEntityRecord } from '../data/entityRecords.js';
|
||||
|
||||
function element(tag, document) {
|
||||
const node = new EventTarget();
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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',
|
||||
@@ -352,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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+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();
|
||||
|
||||
+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');
|
||||
}
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
import { useStatusStore } from './stores/status.js';
|
||||
import { applicationPinia } from './vueRuntime.js';
|
||||
import { describeError } from '../app/errors.js';
|
||||
import { appRootUrl } from '../share/shareLinkPath.js';
|
||||
|
||||
/**
|
||||
* Show a recoverable notice when the globe stops drawing, instead of a black
|
||||
* globe behind working controls. Retry restarts the render loop, or reloads
|
||||
* after a lost WebGL context; Reset opens the app's root address. With
|
||||
* `allowReload: false`, Reset is dropped and a lost context shows no notice:
|
||||
* only a reload draws again, and the page says so itself.
|
||||
* Returns a function that removes the notice.
|
||||
*/
|
||||
export function installRenderFailureNotice(
|
||||
viewer,
|
||||
{
|
||||
store = useStatusStore(applicationPinia()),
|
||||
locationRef = globalThis.location,
|
||||
allowReload = true,
|
||||
logError = (error) =>
|
||||
console.error('[Render] The globe stopped drawing:', error),
|
||||
} = {},
|
||||
) {
|
||||
const { scene } = viewer;
|
||||
const { canvas } = viewer;
|
||||
let notice = null;
|
||||
let contextLost = false;
|
||||
// With rethrowRenderErrors, Scene throws the error it has just raised;
|
||||
// the render() wrapper must not raise it again.
|
||||
let raisedByScene = null;
|
||||
let frameFailed = false;
|
||||
let removeFrameListeners = null;
|
||||
|
||||
function retry() {
|
||||
if (contextLost) {
|
||||
locationRef.reload();
|
||||
return;
|
||||
}
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
scene.requestRender();
|
||||
}
|
||||
|
||||
function reset() {
|
||||
locationRef.assign(appRootUrl(locationRef.href));
|
||||
}
|
||||
|
||||
function stopWatchingFrames() {
|
||||
removeFrameListeners?.();
|
||||
removeFrameListeners = null;
|
||||
}
|
||||
|
||||
function clear() {
|
||||
stopWatchingFrames();
|
||||
if (store.renderFailure === notice) store.publishRenderFailure(null);
|
||||
notice = null;
|
||||
}
|
||||
|
||||
// Cesium raises postRender after a failed frame too, so only a frame that
|
||||
// starts and ends without a render error clears the notice.
|
||||
function watchFrames() {
|
||||
if (removeFrameListeners || contextLost) return;
|
||||
const removeStart = scene.preUpdate.addEventListener(() => {
|
||||
frameFailed = false;
|
||||
raisedByScene = null;
|
||||
});
|
||||
const removeEnd = scene.postRender.addEventListener(() => {
|
||||
if (!frameFailed) clear();
|
||||
});
|
||||
removeFrameListeners = () => {
|
||||
removeStart();
|
||||
removeEnd();
|
||||
};
|
||||
}
|
||||
|
||||
function present(detail) {
|
||||
const reason = contextLost ? 'context-lost' : 'render-error';
|
||||
// A loop restarted into the same error keeps the notice as it was.
|
||||
if (notice?.reason === reason && notice.detail === detail) return;
|
||||
notice = {
|
||||
reason,
|
||||
detail,
|
||||
retry,
|
||||
reset: allowReload ? reset : null,
|
||||
};
|
||||
store.publishRenderFailure(notice);
|
||||
watchFrames();
|
||||
}
|
||||
|
||||
const onRenderError = (_scene, error) => {
|
||||
raisedByScene = { error };
|
||||
frameFailed = true;
|
||||
logError(error);
|
||||
// A lost context fails every frame after it; the notice keeps saying why.
|
||||
if (contextLost) return;
|
||||
present(error ? describeError(error) : '');
|
||||
};
|
||||
const onContextLost = () => {
|
||||
contextLost = true;
|
||||
// No frame can clear this one; only a reload draws again.
|
||||
stopWatchingFrames();
|
||||
// A page that must not reload has nothing to offer: an inline panel
|
||||
// shows its own lost-context notice (src/app/globePanelRuntime.js).
|
||||
if (!allowReload) {
|
||||
clear();
|
||||
return;
|
||||
}
|
||||
present('');
|
||||
};
|
||||
|
||||
const removeRenderError = scene.renderError.addEventListener(onRenderError);
|
||||
// An error thrown outside Scene's error handling (a frame listener, onTick,
|
||||
// resize) stops the loop without a renderError. Raise one, so Cesium, an
|
||||
// inline panel's timer and this notice all see it. First finish the event
|
||||
// raises it cut short, so listeners added or removed meanwhile apply.
|
||||
const unguard = ['resize', 'render'].map((name) =>
|
||||
reportThrown(viewer.cesiumWidget, name, (error) => {
|
||||
frameEvents(viewer).forEach(finishRaise);
|
||||
if (!raisedByScene || raisedByScene.error !== error)
|
||||
scene.renderError.raiseEvent(scene, error);
|
||||
raisedByScene = null;
|
||||
}),
|
||||
);
|
||||
canvas.addEventListener('webglcontextlost', onContextLost);
|
||||
return () => {
|
||||
removeRenderError();
|
||||
unguard.forEach((restore) => restore());
|
||||
canvas.removeEventListener('webglcontextlost', onContextLost);
|
||||
clear();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Events Cesium raises in a frame outside Scene's error handling, which a
|
||||
* listener's error can leave mid-raise. Only top-level tilesets are reached.
|
||||
*/
|
||||
function frameEvents(viewer) {
|
||||
const { scene } = viewer;
|
||||
const events = [
|
||||
scene.preUpdate,
|
||||
scene.postUpdate,
|
||||
scene.preRender,
|
||||
scene.postRender,
|
||||
scene.camera?.changed,
|
||||
scene.camera?.moveStart,
|
||||
scene.camera?.moveEnd,
|
||||
viewer.clock?.onTick,
|
||||
viewer.clock?.onStop,
|
||||
scene.globe?.tileLoadProgressEvent,
|
||||
];
|
||||
const primitives = scene.primitives;
|
||||
for (let i = 0; i < (primitives?.length ?? 0); i += 1) {
|
||||
const tileset = primitives.get(i);
|
||||
events.push(
|
||||
tileset?.loadProgress,
|
||||
tileset?.allTilesLoaded,
|
||||
tileset?.initialTilesLoaded,
|
||||
);
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish a raise a throwing listener cut short. Until a raise ends, Cesium's
|
||||
* `Event` only queues added and removed listeners; apply that queue.
|
||||
* These are Cesium's private fields (`_invokingListeners`, `_toAdd`,
|
||||
* `_toRemove`, `_listeners`, and the widget's `_renderLoopRunning`), checked
|
||||
* against cesium 1.138 / @cesium/engine 22.3.0; the render loop fixture tests
|
||||
* drive the real classes and fail when an upgrade renames them.
|
||||
*/
|
||||
function finishRaise(event) {
|
||||
if (!event?._invokingListeners) return;
|
||||
event._invokingListeners = false;
|
||||
for (const [listener, scopes] of event._toAdd) {
|
||||
const added = event._listeners.get(listener) ?? new Set();
|
||||
scopes.forEach((scope) => added.add(scope));
|
||||
event._listeners.set(listener, added);
|
||||
}
|
||||
event._toAdd.clear();
|
||||
for (const [listener, scopes] of event._toRemove) {
|
||||
const left = event._listeners.get(listener);
|
||||
scopes.forEach((scope) => left?.delete(scope));
|
||||
if (left?.size === 0) event._listeners.delete(listener);
|
||||
}
|
||||
event._toRemove.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Report an error the widget's `name` method throws, and rethrow it.
|
||||
*
|
||||
* A render error marks the loop stopped, but a call made while it ran leaves
|
||||
* its next frame queued, and that frame stops it. Keep the loop marked
|
||||
* running, so a Retry or a shown tab before that frame starts no second loop.
|
||||
* After a throw, the loop's own catch still marks it stopped.
|
||||
*/
|
||||
function reportThrown(widget, name, report) {
|
||||
const original = widget?.[name];
|
||||
if (typeof original !== 'function') return () => {};
|
||||
const own = Object.hasOwn(widget, name);
|
||||
const guarded = function (...args) {
|
||||
const looping = widget._renderLoopRunning;
|
||||
try {
|
||||
return original.apply(this, args);
|
||||
} catch (error) {
|
||||
report(error);
|
||||
throw error;
|
||||
} finally {
|
||||
if (looping) widget._renderLoopRunning = true;
|
||||
}
|
||||
};
|
||||
widget[name] = guarded;
|
||||
return () => {
|
||||
if (widget[name] !== guarded) return;
|
||||
if (own) widget[name] = original;
|
||||
else delete widget[name];
|
||||
};
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { installRenderFailureNotice } from './renderFailure.js';
|
||||
|
||||
function fixture(t, options = {}) {
|
||||
const canvasListeners = new Map();
|
||||
const scene = {
|
||||
renderError: new Cesium.Event(),
|
||||
preUpdate: new Cesium.Event(),
|
||||
postRender: new Cesium.Event(),
|
||||
requestRender() {
|
||||
this.requests = (this.requests ?? 0) + 1;
|
||||
},
|
||||
};
|
||||
const viewer = {
|
||||
scene,
|
||||
useDefaultRenderLoop: true,
|
||||
canvas: {
|
||||
addEventListener: (name, listener) => canvasListeners.set(name, listener),
|
||||
removeEventListener: (name, listener) => {
|
||||
if (canvasListeners.get(name) === listener)
|
||||
canvasListeners.delete(name);
|
||||
},
|
||||
},
|
||||
};
|
||||
const store = {
|
||||
renderFailure: null,
|
||||
published: [],
|
||||
publishRenderFailure(next) {
|
||||
this.renderFailure = next;
|
||||
this.published.push(next);
|
||||
},
|
||||
};
|
||||
const visits = [];
|
||||
const locationRef = {
|
||||
href: 'https://gev.example/share/AQc?lang=ru#lat=48.8584&lon=2.2945',
|
||||
reload: () => visits.push('reload'),
|
||||
assign: (url) => visits.push(String(url)),
|
||||
};
|
||||
const logged = [];
|
||||
const uninstall = installRenderFailureNotice(viewer, {
|
||||
store,
|
||||
locationRef,
|
||||
logError: (error) => logged.push(error),
|
||||
...options,
|
||||
});
|
||||
t.after(uninstall);
|
||||
// One Cesium frame: preUpdate, an optional render error, then postRender,
|
||||
// which Cesium raises after a failed frame too.
|
||||
const frame = (error) => {
|
||||
scene.preUpdate.raiseEvent(scene);
|
||||
if (error) {
|
||||
viewer.useDefaultRenderLoop = false;
|
||||
scene.renderError.raiseEvent(scene, error);
|
||||
}
|
||||
scene.postRender.raiseEvent(scene);
|
||||
};
|
||||
return {
|
||||
viewer,
|
||||
scene,
|
||||
store,
|
||||
visits,
|
||||
logged,
|
||||
uninstall,
|
||||
frame,
|
||||
loseContext: () => canvasListeners.get('webglcontextlost')?.({}),
|
||||
canvasListeners,
|
||||
};
|
||||
}
|
||||
|
||||
test('a render error shows a notice that survives the failed frame', (t) => {
|
||||
const f = fixture(t);
|
||||
assert.equal(f.store.renderFailure, null);
|
||||
const error = new Error('Expected width to be greater than 0');
|
||||
f.frame(error);
|
||||
const notice = f.store.renderFailure;
|
||||
assert.equal(notice.reason, 'render-error');
|
||||
assert.equal(notice.detail, 'Expected width to be greater than 0');
|
||||
assert.equal(typeof notice.retry, 'function');
|
||||
assert.equal(typeof notice.reset, 'function');
|
||||
assert.deepEqual(f.logged, [error]);
|
||||
});
|
||||
|
||||
test('Retry restarts the render loop and a clean frame clears the notice', (t) => {
|
||||
const f = fixture(t);
|
||||
f.frame(new Error('boom'));
|
||||
f.store.renderFailure.retry();
|
||||
assert.equal(f.viewer.useDefaultRenderLoop, true);
|
||||
assert.equal(f.scene.requests, 1);
|
||||
assert.ok(f.store.renderFailure, 'the notice waits for a frame');
|
||||
f.frame();
|
||||
assert.equal(f.store.renderFailure, null);
|
||||
// Clearing stops the per-frame listeners.
|
||||
assert.equal(f.scene.preUpdate.numberOfListeners, 0);
|
||||
assert.equal(f.scene.postRender.numberOfListeners, 0);
|
||||
});
|
||||
|
||||
test('a loop restarted into the same error keeps one notice', (t) => {
|
||||
const f = fixture(t);
|
||||
f.frame(new Error('boom'));
|
||||
const first = f.store.renderFailure;
|
||||
f.store.renderFailure.retry();
|
||||
f.frame(new Error('boom'));
|
||||
assert.equal(f.store.renderFailure, first);
|
||||
assert.equal(f.store.published.length, 1);
|
||||
f.frame(new Error('other'));
|
||||
assert.equal(f.store.renderFailure.detail, 'other');
|
||||
assert.ok(!f.store.published.includes(null), 'no new appearance');
|
||||
});
|
||||
|
||||
test('a new failure after recovery is a new appearance', (t) => {
|
||||
const f = fixture(t);
|
||||
f.frame(new Error('boom'));
|
||||
f.store.renderFailure.retry();
|
||||
f.frame();
|
||||
f.frame(new Error('boom'));
|
||||
assert.deepEqual(
|
||||
f.store.published.map((notice) => notice?.reason ?? null),
|
||||
['render-error', null, 'render-error'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a render error without a value shows no detail', (t) => {
|
||||
const f = fixture(t);
|
||||
f.viewer.useDefaultRenderLoop = false;
|
||||
f.scene.renderError.raiseEvent(f.scene, undefined);
|
||||
assert.equal(f.store.renderFailure.reason, 'render-error');
|
||||
assert.equal(f.store.renderFailure.detail, '');
|
||||
});
|
||||
|
||||
test('Reset opens the app root without the restored view', (t) => {
|
||||
const f = fixture(t);
|
||||
f.frame(new Error('boom'));
|
||||
f.store.renderFailure.reset();
|
||||
assert.deepEqual(f.visits, ['https://gev.example/?lang=ru']);
|
||||
});
|
||||
|
||||
test('a lost context offers a reload and no frame clears it', (t) => {
|
||||
const f = fixture(t);
|
||||
f.loseContext();
|
||||
const notice = f.store.renderFailure;
|
||||
assert.equal(notice.reason, 'context-lost');
|
||||
assert.equal(notice.detail, '');
|
||||
// Cesium's next frame then fails on the dead drawing buffer.
|
||||
f.frame(new Error('Expected width to be greater than 0'));
|
||||
assert.equal(f.store.renderFailure, notice, 'the notice keeps saying why');
|
||||
f.frame();
|
||||
assert.ok(f.store.renderFailure, 'a lost context never draws again');
|
||||
f.store.renderFailure.retry();
|
||||
assert.deepEqual(f.visits, ['reload']);
|
||||
});
|
||||
|
||||
test('a page that must not reload offers neither reload nor reset', (t) => {
|
||||
const f = fixture(t, { allowReload: false });
|
||||
f.frame(new Error('boom'));
|
||||
assert.equal(typeof f.store.renderFailure.retry, 'function');
|
||||
assert.equal(f.store.renderFailure.reset, null);
|
||||
// Only a reload draws again, which this page must not offer: the notice
|
||||
// goes, and the page's own lost-context notice speaks instead.
|
||||
f.loseContext();
|
||||
assert.equal(f.store.renderFailure, null);
|
||||
f.frame(new Error('Expected width to be greater than 0'));
|
||||
assert.equal(f.store.renderFailure, null);
|
||||
});
|
||||
|
||||
test('uninstall removes the listeners and the notice', (t) => {
|
||||
const f = fixture(t);
|
||||
f.frame(new Error('boom'));
|
||||
f.uninstall();
|
||||
assert.equal(f.store.renderFailure, null);
|
||||
assert.equal(f.scene.renderError.numberOfListeners, 0);
|
||||
assert.equal(f.scene.postRender.numberOfListeners, 0);
|
||||
assert.equal(f.canvasListeners.size, 0);
|
||||
f.frame(new Error('later'));
|
||||
assert.equal(f.store.renderFailure, null);
|
||||
});
|
||||
@@ -1,207 +0,0 @@
|
||||
// Retry after a scene event listener throws. Cesium's Event.raiseEvent has no
|
||||
// try/finally, so the event stays mid-raise and only queues listener changes.
|
||||
// Drives Cesium's real Event and startRenderLoop.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { installRenderFailureNotice } from './renderFailure.js';
|
||||
import { renderLoopFixture } from './renderLoopFixture.mjs';
|
||||
|
||||
function setup() {
|
||||
// Scene.render as in Scene.js:4369: preUpdate always, preRender/postRender
|
||||
// only when a frame is rendered (requestRenderMode idle skips them).
|
||||
const scene = {
|
||||
renderError: new Cesium.Event(),
|
||||
preUpdate: new Cesium.Event(),
|
||||
preRender: new Cesium.Event(),
|
||||
postRender: new Cesium.Event(),
|
||||
requestRenderMode: true,
|
||||
_renderRequested: false,
|
||||
rendered: 0,
|
||||
requestRender() {
|
||||
this._renderRequested = true;
|
||||
},
|
||||
initializeFrame() {},
|
||||
render(time) {
|
||||
this.preUpdate.raiseEvent(this, time);
|
||||
const shouldRender = !this.requestRenderMode || this._renderRequested;
|
||||
if (!shouldRender) return;
|
||||
this._renderRequested = false;
|
||||
this.preRender.raiseEvent(this, time);
|
||||
this.rendered += 1;
|
||||
this.postRender.raiseEvent(this, time);
|
||||
},
|
||||
};
|
||||
return { scene, ...renderLoopFixture(scene) };
|
||||
}
|
||||
|
||||
for (const eventName of ['postRender', 'preUpdate']) {
|
||||
test(`idle: a ${eventName} listener that threw once; a successful Retry clears the notice`, () => {
|
||||
const { scene, viewer, store, runFrames, restore } = setup();
|
||||
try {
|
||||
let broken = true;
|
||||
scene[eventName].addEventListener(() => {
|
||||
if (broken) throw new TypeError('listener failed');
|
||||
});
|
||||
scene.requestRender();
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
runFrames(1);
|
||||
assert.equal(store.renderFailure?.reason, 'render-error');
|
||||
assert.equal(viewer.useDefaultRenderLoop, false);
|
||||
broken = false; // the cause goes away
|
||||
store.renderFailure.retry();
|
||||
const before = scene.rendered;
|
||||
runFrames(10); // idle: no camera move, no render request
|
||||
assert.ok(scene.rendered > before, 'the globe drew again');
|
||||
assert.equal(store.renderFailure, null, 'the notice is cleared');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('a throwing postRender listener removed before Retry is not called again', () => {
|
||||
const { scene, viewer, store, runFrames, restore } = setup();
|
||||
try {
|
||||
let calls = 0;
|
||||
const remove = scene.postRender.addEventListener(() => {
|
||||
calls += 1;
|
||||
throw new TypeError('layer listener failed');
|
||||
});
|
||||
scene.requestRender();
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
runFrames(1);
|
||||
assert.equal(store.renderFailure?.reason, 'render-error');
|
||||
remove(); // the user turns the layer off
|
||||
store.renderFailure.retry();
|
||||
runFrames(5);
|
||||
assert.equal(calls, 1, 'the removed listener ran again after Retry');
|
||||
assert.equal(viewer.useDefaultRenderLoop, true, 'the loop keeps running');
|
||||
assert.equal(store.renderFailure, null, 'the notice is cleared');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
const listenerCount = (event) =>
|
||||
[...event._listeners.values()].reduce((sum, scopes) => sum + scopes.size, 0);
|
||||
|
||||
// While the loop is stopped, a layer turned off and on again, or a ground
|
||||
// task in worldAnnotationRenderer that starts, times out and starts again.
|
||||
const RESUBSCRIBE = {
|
||||
'turned off and on': (event, listener) => {
|
||||
event.removeEventListener(listener);
|
||||
event.addEventListener(listener);
|
||||
},
|
||||
'added, removed and added again': (event, listener) => {
|
||||
event.addEventListener(listener);
|
||||
event.removeEventListener(listener);
|
||||
event.addEventListener(listener);
|
||||
},
|
||||
};
|
||||
|
||||
for (const [name, resubscribe] of Object.entries(RESUBSCRIBE)) {
|
||||
test(`a listener ${name} while the loop is stopped runs after Retry`, () => {
|
||||
const { scene, viewer, store, runFrames, restore } = setup();
|
||||
try {
|
||||
let broken = true;
|
||||
scene.postRender.addEventListener(() => {
|
||||
if (broken) throw new TypeError('layer listener failed');
|
||||
});
|
||||
let calls = 0;
|
||||
const listener = () => {
|
||||
calls += 1;
|
||||
};
|
||||
if (name === 'turned off and on')
|
||||
scene.postRender.addEventListener(listener);
|
||||
scene.requestRender();
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
runFrames(1);
|
||||
assert.equal(store.renderFailure?.reason, 'render-error');
|
||||
resubscribe(scene.postRender, listener);
|
||||
broken = false;
|
||||
store.renderFailure.retry();
|
||||
calls = 0;
|
||||
scene.requestRender();
|
||||
runFrames(3);
|
||||
assert.ok(calls > 0, 'the re-added listener runs after Retry');
|
||||
assert.equal(
|
||||
scene.postRender.numberOfListeners,
|
||||
listenerCount(scene.postRender),
|
||||
);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Every event a listener's error can cut short is finished when the error
|
||||
// surfaces, so a listener added at once is subscribed.
|
||||
const FRAME_EVENTS = {
|
||||
'scene.preUpdate': (v) => v.scene.preUpdate,
|
||||
'scene.postUpdate': (v) => v.scene.postUpdate,
|
||||
'scene.preRender': (v) => v.scene.preRender,
|
||||
'scene.postRender': (v) => v.scene.postRender,
|
||||
'camera.changed': (v) => v.scene.camera.changed,
|
||||
'camera.moveStart': (v) => v.scene.camera.moveStart,
|
||||
'camera.moveEnd': (v) => v.scene.camera.moveEnd,
|
||||
'clock.onTick': (v) => v.clock.onTick,
|
||||
'clock.onStop': (v) => v.clock.onStop,
|
||||
'globe.tileLoadProgressEvent': (v) => v.scene.globe.tileLoadProgressEvent,
|
||||
'tileset.loadProgress': (v) => v.scene.primitives.get(0).loadProgress,
|
||||
'tileset.allTilesLoaded': (v) => v.scene.primitives.get(0).allTilesLoaded,
|
||||
'tileset.initialTilesLoaded': (v) =>
|
||||
v.scene.primitives.get(0).initialTilesLoaded,
|
||||
};
|
||||
|
||||
for (const [name, pick] of Object.entries(FRAME_EVENTS)) {
|
||||
test(`a listener that throws in ${name} leaves it finished`, () => {
|
||||
const events = () => ({
|
||||
changed: new Cesium.Event(),
|
||||
moveStart: new Cesium.Event(),
|
||||
moveEnd: new Cesium.Event(),
|
||||
});
|
||||
const tileset = {
|
||||
loadProgress: new Cesium.Event(),
|
||||
allTilesLoaded: new Cesium.Event(),
|
||||
initialTilesLoaded: new Cesium.Event(),
|
||||
};
|
||||
const viewer = {
|
||||
scene: {
|
||||
renderError: new Cesium.Event(),
|
||||
preUpdate: new Cesium.Event(),
|
||||
postUpdate: new Cesium.Event(),
|
||||
preRender: new Cesium.Event(),
|
||||
postRender: new Cesium.Event(),
|
||||
camera: events(),
|
||||
globe: { tileLoadProgressEvent: new Cesium.Event() },
|
||||
primitives: { length: 1, get: () => tileset },
|
||||
},
|
||||
clock: { onTick: new Cesium.Event(), onStop: new Cesium.Event() },
|
||||
canvas: { addEventListener() {}, removeEventListener() {} },
|
||||
cesiumWidget: {
|
||||
_renderLoopRunning: false,
|
||||
render: () => pick(viewer).raiseEvent(),
|
||||
},
|
||||
};
|
||||
const store = { publishRenderFailure() {} };
|
||||
const uninstall = installRenderFailureNotice(viewer, {
|
||||
store,
|
||||
locationRef: { href: 'https://gev.example/', reload() {}, assign() {} },
|
||||
logError() {},
|
||||
});
|
||||
try {
|
||||
const event = pick(viewer);
|
||||
event.addEventListener(() => {
|
||||
throw new TypeError('listener failed');
|
||||
});
|
||||
assert.throws(() => viewer.cesiumWidget.render(), TypeError);
|
||||
assert.equal(event._invokingListeners, false);
|
||||
const listener = () => {};
|
||||
event.addEventListener(listener);
|
||||
assert.ok(event._listeners.has(listener));
|
||||
} finally {
|
||||
uninstall();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// Errors thrown in the render loop outside Scene's tryAndCatchError. Drives
|
||||
// Cesium's real startRenderLoop through the useDefaultRenderLoop setter.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { renderLoopFixture } from './renderLoopFixture.mjs';
|
||||
|
||||
function runLoop(render) {
|
||||
const scene = {
|
||||
renderError: new Cesium.Event(),
|
||||
preUpdate: new Cesium.Event(),
|
||||
postRender: new Cesium.Event(),
|
||||
requestRender() {},
|
||||
initializeFrame() {},
|
||||
render,
|
||||
};
|
||||
const fixture = renderLoopFixture(scene);
|
||||
fixture.viewer.useDefaultRenderLoop = true;
|
||||
fixture.runFrames(3);
|
||||
return { ...fixture, uninstall: fixture.restore };
|
||||
}
|
||||
|
||||
test('an error thrown outside tryAndCatchError still shows the notice', () => {
|
||||
// Scene.render raises preRender outside tryAndCatchError (Scene.js:4439),
|
||||
// so a listener's exception propagates.
|
||||
const { widget, store, logged, uninstall } = runLoop(function () {
|
||||
this.preUpdate.raiseEvent(this);
|
||||
throw new TypeError("Cannot read properties of undefined (reading 'x')");
|
||||
});
|
||||
assert.equal(widget.useDefaultRenderLoop, false);
|
||||
assert.equal(store.renderFailure?.reason, 'render-error');
|
||||
assert.equal(logged.length, 1);
|
||||
uninstall();
|
||||
});
|
||||
|
||||
test('an error Scene raised and threw on with rethrowRenderErrors is reported once', () => {
|
||||
const { store, logged, uninstall } = runLoop(function () {
|
||||
this.preUpdate.raiseEvent(this);
|
||||
const error = new Error('boom');
|
||||
this.renderError.raiseEvent(this, error);
|
||||
throw error;
|
||||
});
|
||||
assert.equal(store.renderFailure?.detail, 'boom');
|
||||
assert.equal(logged.length, 1);
|
||||
uninstall();
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
// Retry after an error Scene catches itself: the loop is marked stopped but
|
||||
// its next frame is still queued, so an early Retry must not start a second
|
||||
// loop. Drives Cesium's real startRenderLoop and useDefaultRenderLoop setter.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { renderLoopFixture } from './renderLoopFixture.mjs';
|
||||
|
||||
function setup({ targetFrameRate } = {}) {
|
||||
const scene = {
|
||||
renderError: new Cesium.Event(),
|
||||
preUpdate: new Cesium.Event(),
|
||||
preRender: new Cesium.Event(),
|
||||
postRender: new Cesium.Event(),
|
||||
broken: false,
|
||||
drawn: 0,
|
||||
requestRender() {},
|
||||
initializeFrame() {},
|
||||
// Scene.render (Scene.js:4369): an update error is caught by
|
||||
// tryAndCatchError, which raises renderError and returns normally.
|
||||
render(time) {
|
||||
this.drawn += 1;
|
||||
this.preUpdate.raiseEvent(this, time);
|
||||
if (this.broken) this.renderError.raiseEvent(this, new Error('boom'));
|
||||
this.preRender.raiseEvent(this, time);
|
||||
this.postRender.raiseEvent(this, time);
|
||||
},
|
||||
};
|
||||
return { scene, ...renderLoopFixture(scene, { targetFrameRate }) };
|
||||
}
|
||||
|
||||
for (const targetFrameRate of [undefined, 60]) {
|
||||
test(`targetFrameRate ${targetFrameRate}: Retry before the next frame after an error Scene caught keeps one render loop`, () => {
|
||||
const { frames, scene, viewer, store, runFrames, restore } = setup({
|
||||
targetFrameRate,
|
||||
});
|
||||
try {
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
runFrames(2);
|
||||
scene.broken = true;
|
||||
runFrames(1);
|
||||
assert.equal(store.renderFailure?.reason, 'render-error');
|
||||
// The cause is gone; Retry runs (a queued Enter on the focused Retry)
|
||||
// before the loop's next animation frame.
|
||||
scene.broken = false;
|
||||
store.renderFailure.retry();
|
||||
assert.equal(frames.length, 1, 'one animation frame queued after Retry');
|
||||
scene.drawn = 0;
|
||||
runFrames(3);
|
||||
assert.equal(store.renderFailure, null);
|
||||
assert.equal(scene.drawn, 3, 'the globe draws once a frame');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('control: Retry after the next frame ran keeps one render loop', () => {
|
||||
const { frames, scene, viewer, store, runFrames, restore } = setup();
|
||||
try {
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
runFrames(2);
|
||||
scene.broken = true;
|
||||
runFrames(1);
|
||||
scene.broken = false;
|
||||
runFrames(1);
|
||||
assert.equal(frames.length, 0, 'the stopped loop queued nothing');
|
||||
store.renderFailure.retry();
|
||||
scene.drawn = 0;
|
||||
runFrames(3);
|
||||
assert.equal(scene.drawn, 3);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a tab hidden and shown again before the next frame after an error Scene caught keeps one render loop', () => {
|
||||
const { scene, viewer, runFrames, restore } = setup();
|
||||
try {
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
runFrames(2);
|
||||
scene.broken = true;
|
||||
runFrames(1);
|
||||
scene.broken = false;
|
||||
// src/app/tools.js turns the loop off while the tab is hidden and back on
|
||||
// when it is shown, before the queued frame runs.
|
||||
viewer.useDefaultRenderLoop = false;
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
scene.drawn = 0;
|
||||
runFrames(3);
|
||||
assert.equal(scene.drawn, 3, 'the globe draws once a frame');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
@@ -1,72 +0,0 @@
|
||||
// A widget on Cesium's real CesiumWidget.prototype (startRenderLoop, the
|
||||
// useDefaultRenderLoop setter, render) around a scene double, with animation
|
||||
// frames queued by hand and the render failure notice installed.
|
||||
import * as Cesium from 'cesium';
|
||||
import { installRenderFailureNotice } from './renderFailure.js';
|
||||
|
||||
export function renderLoopFixture(
|
||||
scene,
|
||||
{ targetFrameRate, viewer: viewerExtras = {}, notice = {} } = {},
|
||||
) {
|
||||
const frames = [];
|
||||
const previousRaf = globalThis.requestAnimationFrame;
|
||||
globalThis.requestAnimationFrame = (fn) => frames.push(fn);
|
||||
const widget = Object.create(Cesium.CesiumWidget.prototype);
|
||||
Object.assign(widget, {
|
||||
_scene: scene,
|
||||
_clock: { tick() {} },
|
||||
_canRender: true,
|
||||
_useDefaultRenderLoop: false,
|
||||
_renderLoopRunning: false,
|
||||
// What src/app/scene.js passes to the viewer.
|
||||
_showRenderLoopErrors: false,
|
||||
_targetFrameRate: targetFrameRate,
|
||||
isDestroyed: () => false,
|
||||
resize() {},
|
||||
});
|
||||
// CesiumWidget's own renderError handler, which marks the loop stopped.
|
||||
scene.renderError.addEventListener(() => {
|
||||
widget._useDefaultRenderLoop = false;
|
||||
widget._renderLoopRunning = false;
|
||||
});
|
||||
const viewer = Object.assign(
|
||||
{
|
||||
scene,
|
||||
cesiumWidget: widget,
|
||||
canvas: { addEventListener() {}, removeEventListener() {} },
|
||||
get useDefaultRenderLoop() {
|
||||
return widget.useDefaultRenderLoop;
|
||||
},
|
||||
set useDefaultRenderLoop(value) {
|
||||
widget.useDefaultRenderLoop = value;
|
||||
},
|
||||
},
|
||||
viewerExtras,
|
||||
);
|
||||
const store = {
|
||||
renderFailure: null,
|
||||
publishRenderFailure(next) {
|
||||
this.renderFailure = next;
|
||||
},
|
||||
};
|
||||
const logged = [];
|
||||
const uninstall = installRenderFailureNotice(viewer, {
|
||||
store,
|
||||
locationRef: { href: 'https://gev.example/', reload() {}, assign() {} },
|
||||
logError: (error) => logged.push(error),
|
||||
...notice,
|
||||
});
|
||||
let time = 0;
|
||||
const runFrames = (n) => {
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
// Above a 60 fps target's interval, so every frame draws.
|
||||
time += 17;
|
||||
for (const fn of frames.splice(0)) fn(time);
|
||||
}
|
||||
};
|
||||
const restore = () => {
|
||||
uninstall();
|
||||
globalThis.requestAnimationFrame = previousRaf;
|
||||
};
|
||||
return { frames, widget, viewer, store, logged, runFrames, restore };
|
||||
}
|
||||
@@ -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 () => {},
|
||||
|
||||
+182
-105
@@ -1,5 +1,26 @@
|
||||
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,
|
||||
@@ -20,21 +41,95 @@ const KIND_BY_LAYER = new Map(
|
||||
);
|
||||
/** 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
|
||||
@@ -49,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 (
|
||||
@@ -87,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,
|
||||
},
|
||||
@@ -127,72 +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 (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;
|
||||
@@ -203,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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -9,7 +9,7 @@ import { markRaw, shallowRef } from 'vue';
|
||||
* bar the FPS readout createFrameRateMonitor() publishes. Each label keeps its
|
||||
* last text while hidden, so the next change flaps from what was shown. The
|
||||
* render failure notice is what installRenderFailureNotice()
|
||||
* (src/ui/renderFailure.js) publishes while the globe cannot draw.
|
||||
* (src/render/cesium/renderFailure.js) publishes while the globe cannot draw.
|
||||
*/
|
||||
export const useStatusStore = defineStore('gev-status', () => {
|
||||
/**
|
||||
|
||||
@@ -380,6 +380,10 @@ body:not(.ui-clean-view):not(.recording-mode) #cesium-credits {
|
||||
bottom: calc(2vh + 4.7rem + var(--world-timeline-lift, 0px));
|
||||
}
|
||||
|
||||
body:not(.ui-clean-view):not(.recording-mode) #gev-credits {
|
||||
bottom: calc(2vh + 4.7rem + var(--world-timeline-lift, 0px));
|
||||
}
|
||||
|
||||
#intel-hud[data-variant='minimal'] .hud-bottom-left {
|
||||
bottom: calc(2vh + 5.4rem + var(--world-timeline-lift, 0px));
|
||||
}
|
||||
|
||||
@@ -462,6 +462,19 @@ body:not(.ui-clean-view):not(.recording-mode):has(
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
body:not(.ui-clean-view):not(.recording-mode) #gev-credits,
|
||||
body:not(.ui-clean-view):not(.recording-mode):has(
|
||||
#intel-hud[data-variant='minimal'].active
|
||||
)
|
||||
#gev-credits {
|
||||
right: auto;
|
||||
bottom: calc(2vh + 5rem + var(--world-timeline-lift, 0px));
|
||||
left: 1.5rem;
|
||||
width: auto !important;
|
||||
max-width: calc(100vw - 3rem);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
#intel-hud[data-variant='tactical'] .hud-bottom-left,
|
||||
#intel-hud[data-variant='tactical'] .hud-bottom-right {
|
||||
bottom: calc(2vh + 6.5rem + var(--world-timeline-lift, 0px));
|
||||
@@ -492,6 +505,16 @@ body:not(.ui-clean-view):not(.recording-mode):has(
|
||||
max-width: calc(100vw - 1.5rem);
|
||||
}
|
||||
|
||||
body:not(.ui-clean-view):not(.recording-mode) #gev-credits,
|
||||
body:not(.ui-clean-view):not(.recording-mode):has(
|
||||
#intel-hud[data-variant='minimal'].active
|
||||
)
|
||||
#gev-credits {
|
||||
bottom: calc(2vh + 5rem + var(--world-timeline-lift, 0px));
|
||||
left: 0.75rem;
|
||||
max-width: calc(100vw - 1.5rem);
|
||||
}
|
||||
|
||||
#command-dock .gev-voice-error-tray {
|
||||
width: min(24rem, calc(100vw - 1.5rem));
|
||||
}
|
||||
|
||||
@@ -220,6 +220,10 @@ body:not(.ui-clean-view):not(.recording-mode) #cesium-credits {
|
||||
bottom: calc(2vh + 7rem + var(--world-timeline-lift, 0px));
|
||||
}
|
||||
|
||||
body:not(.ui-clean-view):not(.recording-mode) #gev-credits {
|
||||
bottom: calc(2vh + 7rem + var(--world-timeline-lift, 0px));
|
||||
}
|
||||
|
||||
body:not(.ui-clean-view):not(.recording-mode):has(
|
||||
#intel-hud[data-variant='minimal'].active
|
||||
)
|
||||
@@ -230,6 +234,16 @@ body:not(.ui-clean-view):not(.recording-mode):has(
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
body:not(.ui-clean-view):not(.recording-mode):has(
|
||||
#intel-hud[data-variant='minimal'].active
|
||||
)
|
||||
#gev-credits {
|
||||
right: 36px;
|
||||
left: auto;
|
||||
width: min(340px, calc(100vw - 72px)) !important;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
body.ui-clean-view #command-dock,
|
||||
body.recording-mode #command-dock {
|
||||
opacity: 0 !important;
|
||||
@@ -244,6 +258,13 @@ body.recording-mode #cesium-credits {
|
||||
left: 36px;
|
||||
}
|
||||
|
||||
body.ui-clean-view #gev-credits,
|
||||
body.recording-mode #gev-credits {
|
||||
right: auto;
|
||||
bottom: 36px;
|
||||
left: 36px;
|
||||
}
|
||||
|
||||
#intel-hud[data-variant='minimal'] .hud-bottom-left {
|
||||
bottom: calc(2vh + 7.5rem + var(--world-timeline-lift, 0px));
|
||||
}
|
||||
@@ -279,6 +300,10 @@ body.recording-mode #cesium-credits {
|
||||
bottom: calc(2vh + 9.5rem + var(--world-timeline-lift, 0px));
|
||||
}
|
||||
|
||||
body:not(.ui-clean-view):not(.recording-mode) #gev-credits {
|
||||
bottom: calc(2vh + 9.5rem + var(--world-timeline-lift, 0px));
|
||||
}
|
||||
|
||||
#intel-hud[data-variant='minimal'] .hud-bottom-left {
|
||||
bottom: calc(2vh + 12rem + var(--world-timeline-lift, 0px));
|
||||
}
|
||||
|
||||
Vendored
+91
@@ -332,6 +332,97 @@ body.cockpit-mode #cockpit-cloud-effects.active {
|
||||
color: rgba(232, 234, 237, 0.7);
|
||||
}
|
||||
|
||||
/* The application's own attribution line (src/ui/creditsView.js), for a
|
||||
renderer without a credit display of its own: the same place and look. */
|
||||
#gev-credits {
|
||||
position: fixed;
|
||||
bottom: 36px;
|
||||
left: 36px;
|
||||
z-index: 90;
|
||||
max-width: 90vw;
|
||||
white-space: nowrap;
|
||||
pointer-events: auto;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
color: rgba(232, 234, 237, 0.55);
|
||||
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.9);
|
||||
}
|
||||
#gev-credits a,
|
||||
#gev-credits .gev-credits-expand {
|
||||
color: rgba(232, 234, 237, 0.7);
|
||||
}
|
||||
#gev-credits .gev-credit-logo {
|
||||
height: 14px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
#gev-credits .gev-credits-expand {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
font: inherit;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.gev-credits-panel {
|
||||
position: fixed;
|
||||
bottom: 60px;
|
||||
left: 36px;
|
||||
z-index: 200;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 470px;
|
||||
max-width: calc(100vw - 2rem);
|
||||
max-height: min(70dvh, 36rem);
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(232, 234, 237, 0.2);
|
||||
border-radius: 6px;
|
||||
background: rgba(16, 18, 22, 0.94);
|
||||
color: rgba(232, 234, 237, 0.85);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
}
|
||||
.gev-credits-panel[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.gev-credits-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 14px 4px 20px;
|
||||
}
|
||||
.gev-credits-close {
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.gev-credits-list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
padding: 4px 20px 14px 40px;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.gev-credits-list > li {
|
||||
padding-bottom: 5px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.gev-credits-list a {
|
||||
color: rgba(232, 234, 237, 0.85);
|
||||
}
|
||||
@media (max-width: 575px) {
|
||||
.gev-credits-panel {
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
max-height: 100dvh;
|
||||
border-radius: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Cesium's stock attribution lightbox grows with every registered data source.
|
||||
Keep the title and close affordance fixed while the complete, unabridged
|
||||
credit list wraps and scrolls inside a compact panel. */
|
||||
|
||||
@@ -407,6 +407,18 @@ body.mobile-shell:not(.recording-mode):not(.cockpit-mode):not(.ui-clean-view)
|
||||
scale: 0.8;
|
||||
}
|
||||
|
||||
body.mobile-shell:not(.recording-mode):not(.cockpit-mode):not(.ui-clean-view)
|
||||
#gev-credits {
|
||||
right: auto;
|
||||
bottom: calc(var(--mobile-tab-space) + 106px + var(--world-timeline-lift, 0px)) !important;
|
||||
left: 10px;
|
||||
width: calc((100vw - 20px) / 0.8) !important;
|
||||
max-width: none !important;
|
||||
white-space: normal;
|
||||
transform-origin: left bottom;
|
||||
scale: 0.8;
|
||||
}
|
||||
|
||||
/* An open sheet lifts the required attribution above everything it covers. */
|
||||
body.mobile-shell[data-mobile-sheet]:not(.recording-mode):not(
|
||||
.cockpit-mode
|
||||
@@ -416,6 +428,14 @@ body.mobile-shell[data-mobile-sheet]:not(.recording-mode):not(
|
||||
z-index: 166;
|
||||
}
|
||||
|
||||
body.mobile-shell[data-mobile-sheet]:not(.recording-mode):not(
|
||||
.cockpit-mode
|
||||
):not(.ui-clean-view)
|
||||
#gev-credits {
|
||||
bottom: calc(var(--mobile-sheet-cover, 0px) + 6px) !important;
|
||||
z-index: 166;
|
||||
}
|
||||
|
||||
/* The view switcher clears the tab bar and the voice bar, opposite the credit. */
|
||||
body.mobile-shell:not(.cockpit-mode) #view-switcher {
|
||||
right: 12px;
|
||||
|
||||
@@ -13,6 +13,8 @@ import { registerHooks } from 'node:module';
|
||||
import { presentSelectedVessel } from '../../hudReadouts.js';
|
||||
import { useHudStore } from '../stores/hud.js';
|
||||
import IntelHudView from './IntelHudView.vue';
|
||||
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
|
||||
import { toDegrees as deg } from '../../geo/index.js';
|
||||
|
||||
const MGRS_STUB_URL = 'gev-test-stub:mgrs';
|
||||
registerHooks({
|
||||
@@ -35,8 +37,6 @@ registerHooks({
|
||||
|
||||
const { IntelHUD } = await import('../../hud.js');
|
||||
|
||||
const listeners = () => ({ addEventListener() {}, removeEventListener() {} });
|
||||
|
||||
function mount(t) {
|
||||
document.body.replaceChildren();
|
||||
const pinia = createPinia();
|
||||
@@ -44,16 +44,11 @@ function mount(t) {
|
||||
const app = createApp(IntelHudView).use(pinia);
|
||||
app.mount(document.body.appendChild(document.createElement('div')));
|
||||
const hud = new IntelHUD(
|
||||
{},
|
||||
{
|
||||
camera: {
|
||||
pitch: -Math.PI / 2,
|
||||
positionCartographic: { latitude: 0.7, longitude: -1.2, height: 500 },
|
||||
computeViewRectangle: () => undefined,
|
||||
moveStart: listeners(),
|
||||
moveEnd: listeners(),
|
||||
},
|
||||
},
|
||||
{
|
||||
camera: fakeCameraPort({
|
||||
pose: { lat: deg(0.7), lon: deg(-1.2), height: 500 },
|
||||
}).port,
|
||||
// No AI summary: the readouts are what this test renders.
|
||||
summaryService: { configured: async () => false },
|
||||
publish: (view) => store.publish(view),
|
||||
|
||||
@@ -19,7 +19,7 @@ import VisualPresets from './VisualPresets.vue';
|
||||
// and each publishes them; until they do, the panel shows its initial markup.
|
||||
// Draw and Import live in UTILITIES (LayerPanelsView).
|
||||
const display = useDisplayStore();
|
||||
const { view, models3d, parameters, cockpitPortal } = storeToRefs(display);
|
||||
const { view, models3d, parameters, cockpitPortal, groups, sky } = storeToRefs(display);
|
||||
// A control's change goes to its owner (DisplayBindings).
|
||||
const act = (name, ...args) => display.act(name, ...args);
|
||||
const pct = (value) => `${value}%`;
|
||||
@@ -44,6 +44,13 @@ const celestialTitle = computed(() =>
|
||||
? t('Celestial ring — available in Normal style')
|
||||
: t('Celestial ring — reveal the full globe'),
|
||||
);
|
||||
const skyRows = computed(() => [
|
||||
{ key: 'atmosphere', label: t('Atmosphere'), icon: 'public' },
|
||||
{ key: 'lighting', label: t('Day and night'), icon: 'adjust' },
|
||||
{ key: 'sun', label: t('Sun'), icon: 'light_mode' },
|
||||
{ key: 'moon', label: t('Moon'), icon: 'dark_mode' },
|
||||
{ key: 'stars', label: t('Stars'), icon: 'flare' },
|
||||
]);
|
||||
const models3dOn = computed(() => models3d.value?.pressed ?? true);
|
||||
const modelsMode = computed(() => models3d.value?.mode ?? 'proximity');
|
||||
const modelsOptions = computed(() => [
|
||||
@@ -197,6 +204,37 @@ const allocationOptions = computed(() => [
|
||||
<span class="pp-label">{{ t('Celestial') }}</span>
|
||||
</UiButton>
|
||||
</div>
|
||||
<!-- Sky: only where the renderer has a sky to set. -->
|
||||
<div v-if="sky" class="pp-toggle-group" id="sky-group">
|
||||
<label v-for="row in skyRows" :key="row.key" class="pp-toggle-btn pp-scope-toggle" :id="`sky-${row.key}-row`">
|
||||
<span class="pp-icon material-symbols-outlined" aria-hidden="true">{{ row.icon }}</span>
|
||||
<span class="pp-label">{{ row.label }}</span>
|
||||
<input type="checkbox" :id="`sky-${row.key}-toggle`" @change="act('setSkySwitch', row.key, $event.target.checked)" :checked="sky.switches[row.key]" />
|
||||
</label>
|
||||
<div class="pp-slider-row visible" id="sky-milkyway-row">
|
||||
<span class="pp-slider-mini-label">{{ t('Milky Way') }}</span>
|
||||
<UiSlider class="pp-slider" id="sky-milkyway-slider" @update:model-value="act('setSkyMilkyWay', $event)" min="0" max="100" :model-value="sky.milkyWay" :aria-label="t('Milky Way')" />
|
||||
<span class="pp-slider-value">{{ pct(sky.milkyWay) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Groups the application adds (store `publishGroup`). -->
|
||||
<div v-for="group in groups" :key="group.id" class="pp-toggle-group" :id="`${group.id}-group`">
|
||||
<template v-for="row in group.rows" :key="row.id">
|
||||
<label v-if="row.kind === 'toggle'" class="pp-toggle-btn pp-scope-toggle" :title="row.title">
|
||||
<span v-if="row.icon" class="pp-icon material-symbols-outlined" aria-hidden="true">{{ row.icon }}</span>
|
||||
<span class="pp-label">{{ row.label }}</span>
|
||||
<input type="checkbox" :id="`${group.id}-${row.id}-toggle`" @change="row.onChange?.($event.target.checked)" :checked="row.checked" />
|
||||
</label>
|
||||
<div v-else-if="row.kind === 'note'" class="pp-slider-row visible" :id="`${group.id}-${row.id}`">
|
||||
<span class="pp-slider-mini-label">{{ row.text }}</span>
|
||||
</div>
|
||||
<div v-else-if="row.kind === 'slider'" class="pp-slider-row visible" :id="`${group.id}-${row.id}-row`">
|
||||
<span class="pp-slider-mini-label">{{ row.label }}</span>
|
||||
<UiSlider class="pp-slider" :id="`${group.id}-${row.id}-slider`" @update:model-value="row.onChange?.($event)" :min="String(row.min)" :max="String(row.max)" :model-value="row.value" :aria-label="row.label" />
|
||||
<span class="pp-slider-value" :id="`${group.id}-${row.id}-value`">{{ pct(row.value) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<div class="pp-toggle-group">
|
||||
<button class="pp-toggle-btn" :class="{ active: view?.bloom.active }" :aria-pressed="String(Boolean(view?.bloom.active))" id="bloom-toggle" @click="act('toggleBloom')" :title="t('Bloom / Glow')">
|
||||
<span class="pp-icon">✨</span>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { msg, t } from '../../../i18n/index.js';
|
||||
import { useStatusStore } from '../../stores/status.js';
|
||||
import UiButton from '../../kit/UiButton.vue';
|
||||
|
||||
// Published by installRenderFailureNotice() (src/ui/renderFailure.js).
|
||||
// Published by installRenderFailureNotice() (src/render/cesium/renderFailure.js).
|
||||
const { renderFailure: failure } = storeToRefs(useStatusStore());
|
||||
const panel = ref(null);
|
||||
const MESSAGES = {
|
||||
|
||||
+138
-107
@@ -1,126 +1,173 @@
|
||||
import { PostProcessStage } from 'cesium';
|
||||
import {
|
||||
bloomStrengthFromIntensity,
|
||||
clampBloomIntensity,
|
||||
BLOOM_INTENSITY_DEFAULT,
|
||||
} from '../bloom.js';
|
||||
import {
|
||||
STYLES,
|
||||
SHARPEN_SHADER,
|
||||
TRANSITION_DURATION_MS,
|
||||
} from './visualPresets.js';
|
||||
import { registerStyleStages } from '../styles/styleStages.js';
|
||||
import { STYLES, TRANSITION_DURATION_MS } from './visualPresets.js';
|
||||
|
||||
/** Own the post-process stages and their animation, without DOM dependencies. */
|
||||
/** Below this a style draws nothing, so it runs no pass. */
|
||||
const OFF = 0.001;
|
||||
|
||||
/**
|
||||
* A style as the renderer contract defines it
|
||||
* (`src/render/contract/effects.d.ts`).
|
||||
* @param {string} name
|
||||
* @param {{fragmentShader: string, uniforms?: Record<string, {default: number, min: number, max: number}>}} shader
|
||||
*/
|
||||
export function styleDefinition(name, shader) {
|
||||
return {
|
||||
id: name,
|
||||
params: Object.entries(shader.uniforms || {}).map(([key, meta]) => ({
|
||||
key,
|
||||
min: meta.min,
|
||||
max: meta.max,
|
||||
default: meta.default,
|
||||
})),
|
||||
animated: shader.fragmentShader.includes('uniform float time'),
|
||||
shader: { glsl: shader.fragmentShader },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's records of the visual styles, bloom and sharpen, and their
|
||||
* crossfades, driven onto the renderer's effects port. Each style's record
|
||||
* (`stages[name]`) holds its intensity and parameter values in `uniforms`,
|
||||
* written through to the renderer, and `enabled`, whether it draws. The
|
||||
* renderer animates `time` for an animated style; this keeps only the
|
||||
* crossfades' frames. No DOM dependencies.
|
||||
*/
|
||||
export class VisualEffects {
|
||||
/**
|
||||
* @param {object} options - Viewer, render ownership callbacks and optional clocks.
|
||||
* Construction is inert; initStyles/initPostProcess retain startup ordering.
|
||||
* @param {object} options - The renderer's effects port (null: records
|
||||
* only), the viewer, a getter for the globe's sky port the anime
|
||||
* style dims (null: the sky is left alone), render ownership
|
||||
* callbacks and optional clocks. Construction is inert;
|
||||
* initStyles/initPostProcess retain startup ordering.
|
||||
*/
|
||||
constructor({
|
||||
effects = null,
|
||||
viewer,
|
||||
sky = null,
|
||||
requestRender,
|
||||
holdRender,
|
||||
releaseRender,
|
||||
requestFrame = (callback) => requestAnimationFrame(callback),
|
||||
cancelFrame = (id) => cancelAnimationFrame(id),
|
||||
now = () => performance.now(),
|
||||
wallNow = () => Date.now(),
|
||||
createStage = (options) => new PostProcessStage(options),
|
||||
}) {
|
||||
this.effects = effects;
|
||||
this.viewer = viewer;
|
||||
this.sky = sky;
|
||||
this.requestRender = requestRender;
|
||||
this.holdRender = holdRender;
|
||||
this.releaseRender = releaseRender;
|
||||
this.requestFrame = requestFrame;
|
||||
this.cancelFrame = cancelFrame;
|
||||
this.now = now;
|
||||
this.wallNow = wallNow;
|
||||
this.createStage = createStage;
|
||||
this.stages = {};
|
||||
this.transitions = new Map();
|
||||
this.startTime = wallNow();
|
||||
this.bloomEnabled = false;
|
||||
this.sharpenEnabled = false;
|
||||
this.bloomIntensity = BLOOM_INTENSITY_DEFAULT;
|
||||
this.sharpenIntensity = 0.49;
|
||||
this.bloomStage = null;
|
||||
this.sharpenStage = null;
|
||||
this.postProcessReady = false;
|
||||
this.frameId = null;
|
||||
this.stopped = false;
|
||||
this.destroyed = false;
|
||||
this.stageEntries = [];
|
||||
this.previousBloom = null;
|
||||
// What the renderer draws: its style, and the styles it replaced while
|
||||
// they fade out (`EffectsPort.setStyle`).
|
||||
this.rendererStyle = null;
|
||||
this.drawn = new Set();
|
||||
this.offs = [];
|
||||
this.forgetStages = () => {};
|
||||
}
|
||||
|
||||
initStyles() {
|
||||
if (this.stopped || this.stageEntries.length) return;
|
||||
for (const [name, shader] of Object.entries(STYLES)) {
|
||||
const uniforms = { intensity: 0.0 };
|
||||
if (shader.fragmentShader.includes('uniform float time'))
|
||||
uniforms.time = 0.0;
|
||||
for (const [name, meta] of Object.entries(shader.uniforms || {}))
|
||||
uniforms[name] = meta.default;
|
||||
const stage = this.createStage({
|
||||
name: `godsEyeView_${name}`,
|
||||
fragmentShader: shader.fragmentShader,
|
||||
uniforms,
|
||||
});
|
||||
stage.enabled = false;
|
||||
this.viewer.scene.postProcessStages.add(stage);
|
||||
this.stages[name] = stage;
|
||||
const definition = styleDefinition(name, shader);
|
||||
const off = this.effects?.defineStyle(definition);
|
||||
if (off) this.offs.push(off);
|
||||
this.effects?.setStyleIntensity(name, 0);
|
||||
this.stages[name] = this.styleRecord(name, definition);
|
||||
}
|
||||
this.stageEntries = Object.entries(this.stages);
|
||||
this.forgetStages = registerStyleStages(this.viewer, this.stages);
|
||||
}
|
||||
|
||||
/** A style's record, its uniforms written through to the renderer. */
|
||||
styleRecord(name, definition) {
|
||||
let intensity = 0;
|
||||
const values = Object.fromEntries(
|
||||
definition.params.map((p) => [p.key, p.default]),
|
||||
);
|
||||
const uniforms = {};
|
||||
Object.defineProperty(uniforms, 'intensity', {
|
||||
enumerable: true,
|
||||
get: () => intensity,
|
||||
set: (value) => {
|
||||
intensity = value;
|
||||
this.pushIntensity(name, value);
|
||||
},
|
||||
});
|
||||
for (const { key } of definition.params)
|
||||
Object.defineProperty(uniforms, key, {
|
||||
enumerable: true,
|
||||
get: () => values[key],
|
||||
set: (value) => {
|
||||
values[key] = value;
|
||||
if (!this.destroyed)
|
||||
this.effects?.setStyleParams(name, { [key]: value });
|
||||
},
|
||||
});
|
||||
return { name, enabled: false, uniforms };
|
||||
}
|
||||
|
||||
/**
|
||||
* A style's intensity on the renderer. Raised from nothing, it becomes
|
||||
* the renderer's style, so it draws; the style it replaces fades out
|
||||
* there at the intensity this keeps writing, as every stage with an
|
||||
* intensity drew before.
|
||||
*/
|
||||
pushIntensity(name, value) {
|
||||
if (this.destroyed || !this.effects) return;
|
||||
this.effects.setStyleIntensity(name, value);
|
||||
// Once stopped, a write only tunes what already draws.
|
||||
if (this.stopped) return;
|
||||
if (value > OFF) {
|
||||
if (!this.drawn.has(name)) {
|
||||
const previous = this.rendererStyle;
|
||||
if (previous && !(this.stages[previous]?.uniforms.intensity > OFF))
|
||||
this.drawn.delete(previous);
|
||||
this.effects.setStyle(name);
|
||||
this.rendererStyle = name;
|
||||
this.drawn.add(name);
|
||||
}
|
||||
} else if (name !== this.rendererStyle) {
|
||||
this.drawn.delete(name);
|
||||
}
|
||||
}
|
||||
|
||||
initPostProcess(sharpenIntensity = this.sharpenIntensity) {
|
||||
if (this.stopped || this.sharpenStage) return;
|
||||
this.bloomStage = this.viewer.scene.postProcessStages.bloom;
|
||||
const names = [
|
||||
'glowOnly',
|
||||
'contrast',
|
||||
'brightness',
|
||||
'delta',
|
||||
'sigma',
|
||||
'stepSize',
|
||||
];
|
||||
this.previousBloom = {
|
||||
enabled: this.bloomStage.enabled,
|
||||
uniforms: Object.fromEntries(
|
||||
names.map((name) => [name, this.bloomStage.uniforms[name]]),
|
||||
),
|
||||
};
|
||||
this.bloomStage.enabled = false;
|
||||
Object.assign(this.bloomStage.uniforms, {
|
||||
glowOnly: false,
|
||||
contrast: 256.0,
|
||||
brightness: -0.35,
|
||||
delta: 0.25,
|
||||
sigma: 0.35,
|
||||
stepSize: 1.0,
|
||||
if (this.stopped || this.postProcessReady) return;
|
||||
this.postProcessReady = true;
|
||||
this.effects?.bloom({
|
||||
enabled: false,
|
||||
strength: bloomStrengthFromIntensity(this.bloomIntensity),
|
||||
});
|
||||
this.sharpenStage = this.createStage({
|
||||
name: 'godsEyeView_sharpen',
|
||||
fragmentShader: SHARPEN_SHADER,
|
||||
uniforms: { amount: 1.3 },
|
||||
});
|
||||
this.sharpenStage.enabled = false;
|
||||
this.viewer.scene.postProcessStages.add(this.sharpenStage);
|
||||
this.effects?.sharpen({ enabled: false, amount: sharpenIntensity });
|
||||
this.applySharpenIntensity(sharpenIntensity);
|
||||
}
|
||||
|
||||
setStageIntensity(stage, value) {
|
||||
if (this.stopped || !stage) return;
|
||||
stage.uniforms.intensity = value;
|
||||
stage.enabled = value > 0.001;
|
||||
stage.enabled = value > OFF;
|
||||
// Anime's bands turn the faint Milky Way into blotches, and depth cannot
|
||||
// tell the sky from far geometry, so the glow fades with the style.
|
||||
if (
|
||||
stage === this.stages.anime &&
|
||||
this.viewer.scene.skyBox?.milkyWayVisibility !== undefined
|
||||
)
|
||||
this.viewer.scene.skyBox.milkyWayVisibility = 1 - value;
|
||||
if (stage.enabled && stage.uniforms.time !== undefined)
|
||||
this.startAnimationLoop();
|
||||
if (stage === this.stages.anime) this.sky?.()?.set({ milkyWay: 1 - value });
|
||||
this.requestRender('style-stage');
|
||||
}
|
||||
|
||||
@@ -130,26 +177,19 @@ export class VisualEffects {
|
||||
}
|
||||
|
||||
syncBloomEnabled() {
|
||||
if (this.stopped || !this.bloomStage) return;
|
||||
this.bloomStage.enabled =
|
||||
this.bloomEnabled &&
|
||||
bloomStrengthFromIntensity(this.bloomIntensity) > 0.06;
|
||||
if (this.stopped || !this.postProcessReady) return;
|
||||
this.effects?.bloom({ enabled: this.bloomEnabled });
|
||||
}
|
||||
|
||||
applyBloomIntensity(intensity) {
|
||||
if (this.stopped) return;
|
||||
this.bloomIntensity = clampBloomIntensity(intensity);
|
||||
this.requestRender('bloom');
|
||||
if (!this.bloomStage) return;
|
||||
const rawStrength = bloomStrengthFromIntensity(this.bloomIntensity);
|
||||
const strength = rawStrength <= 0.06 ? 0.0 : (rawStrength - 0.06) / 0.94;
|
||||
const eased = strength * strength * (3.0 - 2.0 * strength);
|
||||
this.bloomStage.uniforms.contrast = 255.0 - eased * 168.0;
|
||||
this.bloomStage.uniforms.brightness = -0.5 + eased * 0.36;
|
||||
this.bloomStage.uniforms.sigma = 0.28 + eased * 6.3;
|
||||
this.bloomStage.uniforms.delta = 0.2 + eased * 2.25;
|
||||
this.bloomStage.uniforms.stepSize = 1.0 + eased * 1.25;
|
||||
this.syncBloomEnabled();
|
||||
if (!this.postProcessReady) return;
|
||||
this.effects?.bloom({
|
||||
enabled: this.bloomEnabled,
|
||||
strength: bloomStrengthFromIntensity(this.bloomIntensity),
|
||||
});
|
||||
}
|
||||
|
||||
setBloomEnabled(enabled) {
|
||||
@@ -162,20 +202,18 @@ export class VisualEffects {
|
||||
/**
|
||||
* Sharpen runs only when it is on and its slider is above 0, as the style
|
||||
* stages do: the pass costs the same at any amount (~1.5 ms GPU per frame
|
||||
* on the Arc, 2026-10-24), and `0.1 + value * 2` still sharpened at 0.
|
||||
* on the Arc, 2026-10-24), and its gain still sharpened at 0.
|
||||
*/
|
||||
syncSharpenEnabled() {
|
||||
if (this.stopped || !this.sharpenStage) return;
|
||||
this.sharpenStage.enabled =
|
||||
this.sharpenEnabled && this.sharpenIntensity > 0.001;
|
||||
if (this.stopped || !this.postProcessReady) return;
|
||||
this.effects?.sharpen({ enabled: this.sharpenEnabled });
|
||||
}
|
||||
|
||||
applySharpenIntensity(value) {
|
||||
if (this.stopped) return;
|
||||
this.sharpenIntensity = value;
|
||||
if (this.sharpenStage)
|
||||
this.sharpenStage.uniforms.amount = 0.1 + value * 2.0;
|
||||
this.syncSharpenEnabled();
|
||||
if (this.postProcessReady)
|
||||
this.effects?.sharpen({ enabled: this.sharpenEnabled, amount: value });
|
||||
this.requestRender('sharpen');
|
||||
}
|
||||
|
||||
@@ -192,12 +230,12 @@ export class VisualEffects {
|
||||
this.startAnimationLoop();
|
||||
}
|
||||
|
||||
/** Steps the crossfades each frame, holding frames while one runs. */
|
||||
startAnimationLoop() {
|
||||
if (this.stopped || this.frameId !== null) return;
|
||||
const update = () => {
|
||||
if (this.stopped) return;
|
||||
const now = this.now();
|
||||
const elapsedSec = (this.wallNow() - this.startTime) / 1000.0;
|
||||
for (const [name, transition] of this.transitions) {
|
||||
const t = Math.min(
|
||||
(now - transition.start) / TRANSITION_DURATION_MS,
|
||||
@@ -213,14 +251,7 @@ export class VisualEffects {
|
||||
this.transitions.delete(name);
|
||||
}
|
||||
}
|
||||
let animatedStageVisible = false;
|
||||
for (const [, stage] of this.stageEntries) {
|
||||
if (stage.enabled && stage.uniforms.time !== undefined) {
|
||||
stage.uniforms.time = elapsedSec;
|
||||
if (stage.uniforms.intensity > 0.001) animatedStageVisible = true;
|
||||
}
|
||||
}
|
||||
const needed = this.transitions.size > 0 || animatedStageVisible;
|
||||
const needed = this.transitions.size > 0;
|
||||
if (needed) this.holdRender('style-anim');
|
||||
else this.releaseRender('style-anim');
|
||||
this.frameId = needed ? this.requestFrame(update) : null;
|
||||
@@ -228,7 +259,7 @@ export class VisualEffects {
|
||||
this.frameId = this.requestFrame(update);
|
||||
}
|
||||
|
||||
/** Revoke animation synchronously while callers finish releasing the stages. */
|
||||
/** Revoke animation synchronously while callers finish releasing the styles. */
|
||||
stop() {
|
||||
if (this.stopped) return;
|
||||
this.stopped = true;
|
||||
@@ -238,17 +269,17 @@ export class VisualEffects {
|
||||
this.transitions.clear();
|
||||
}
|
||||
|
||||
/** Remove owned stages and restore the borrowed bloom stage after callers release it. */
|
||||
/** Remove the styles from the renderer and turn bloom and sharpen off. */
|
||||
destroy() {
|
||||
if (this.destroyed) return;
|
||||
this.stop();
|
||||
this.destroyed = true;
|
||||
const stages = this.viewer.scene.postProcessStages;
|
||||
for (const [, stage] of this.stageEntries) stages.remove(stage);
|
||||
if (this.sharpenStage) stages.remove(this.sharpenStage);
|
||||
if (this.bloomStage && this.previousBloom) {
|
||||
Object.assign(this.bloomStage.uniforms, this.previousBloom.uniforms);
|
||||
this.bloomStage.enabled = this.previousBloom.enabled;
|
||||
this.forgetStages();
|
||||
for (const off of this.offs) off();
|
||||
this.offs = [];
|
||||
if (this.postProcessReady) {
|
||||
this.effects?.bloom({ enabled: false });
|
||||
this.effects?.sharpen({ enabled: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
+128
-29
@@ -1,7 +1,10 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { VisualEffects } from './visualEffects.js';
|
||||
import { MILKY_WAY_INTENSITY, StarrySky } from '../sky/starrySky.js';
|
||||
import { createCesiumEffects } from '../render/cesium/effects.js';
|
||||
import { styleStagesOf } from '../styles/styleStages.js';
|
||||
import { createCesiumGlobe } from '../render/cesium/globe.js';
|
||||
import { MILKY_WAY_INTENSITY, StarrySky } from '../render/cesium/starrySky.js';
|
||||
import {
|
||||
GLOBAL_POST_DEFAULTS,
|
||||
STYLE_PRESET_DEFAULTS,
|
||||
@@ -14,9 +17,10 @@ function fixture() {
|
||||
const frames = new Map();
|
||||
const stages = new Set();
|
||||
const holds = new Set();
|
||||
const portHolds = new Set();
|
||||
const requests = [];
|
||||
const bloom = {
|
||||
enabled: true,
|
||||
enabled: false,
|
||||
uniforms: {
|
||||
glowOnly: true,
|
||||
contrast: 3,
|
||||
@@ -36,10 +40,40 @@ function fixture() {
|
||||
return stages.delete(stage);
|
||||
},
|
||||
};
|
||||
const effects = new VisualEffects({
|
||||
viewer: {
|
||||
scene: { postProcessStages: pipeline, skyBox: { milkyWayVisibility: 1 } },
|
||||
const scene = {
|
||||
postProcessStages: pipeline,
|
||||
skyBox: { milkyWayVisibility: 1 },
|
||||
};
|
||||
const preRender = new Set();
|
||||
const renderer = createCesiumEffects(scene, {
|
||||
capabilities: new Set(['styles', 'bloom', 'sharpen']),
|
||||
frame: {
|
||||
on(phase, cb) {
|
||||
preRender.add(cb);
|
||||
return () => preRender.delete(cb);
|
||||
},
|
||||
holdContinuous(reason) {
|
||||
const hold = {};
|
||||
portHolds.add(hold);
|
||||
return () => portHolds.delete(hold);
|
||||
},
|
||||
requestRender() {},
|
||||
},
|
||||
report: (error) => {
|
||||
throw error;
|
||||
},
|
||||
createStage: (options) => ({ ...options, enabled: true }),
|
||||
});
|
||||
// The sky the anime style dims is the globe port's, over the scene.
|
||||
const viewer = { scene };
|
||||
const globe = createCesiumGlobe(viewer, {
|
||||
capabilities: new Set(),
|
||||
requestRender() {},
|
||||
}).port;
|
||||
const effects = new VisualEffects({
|
||||
effects: renderer.port,
|
||||
viewer,
|
||||
sky: () => globe.sky,
|
||||
requestRender: (reason) => requests.push(reason),
|
||||
holdRender: (reason) => holds.add(reason),
|
||||
releaseRender: (reason) => holds.delete(reason),
|
||||
@@ -50,8 +84,6 @@ function fixture() {
|
||||
},
|
||||
cancelFrame: (id) => frames.delete(id),
|
||||
now: () => time,
|
||||
wallNow: () => 10_000 + time,
|
||||
createStage: (options) => ({ ...options, enabled: true }),
|
||||
});
|
||||
function tick(value) {
|
||||
time = value;
|
||||
@@ -59,11 +91,20 @@ function fixture() {
|
||||
frames.clear();
|
||||
for (const callback of pending) callback();
|
||||
}
|
||||
/** The renderer's stage for a style, or sharpen. */
|
||||
const stage = (name) =>
|
||||
[...stages].find(
|
||||
(s) => s.name === `effects_style_${name}` || s.name === `effects_${name}`,
|
||||
);
|
||||
return {
|
||||
effects,
|
||||
renderer,
|
||||
frames,
|
||||
stages,
|
||||
stage,
|
||||
holds,
|
||||
portHolds,
|
||||
preRender,
|
||||
requests,
|
||||
bloom,
|
||||
originalBloom,
|
||||
@@ -86,7 +127,10 @@ test('construction is inert and initialization creates one owned pipeline', () =
|
||||
f.effects.initStyles();
|
||||
f.effects.initPostProcess();
|
||||
assert.equal(f.stages.size, 6);
|
||||
assert.ok([...f.stages].every((stage) => !stage.enabled));
|
||||
assert.equal(styleStagesOf(f.effects.viewer), f.effects.stages);
|
||||
f.effects.destroy();
|
||||
assert.equal(styleStagesOf(f.effects.viewer), null);
|
||||
});
|
||||
|
||||
test('crossfade uses the established 500ms easing and settles without idle frames', () => {
|
||||
@@ -104,6 +148,8 @@ test('crossfade uses the established 500ms easing and settles without idle frame
|
||||
assert.equal(f.effects.stages.noir.uniforms.intensity, 0.125);
|
||||
f.tick(250);
|
||||
assert.equal(f.effects.stages.noir.uniforms.intensity, 0.5);
|
||||
assert.equal(f.stage('noir').uniforms.intensity, 0.5);
|
||||
assert.equal(f.stage('noir').enabled, true);
|
||||
f.tick(500);
|
||||
assert.equal(f.effects.stages.noir.uniforms.intensity, 1);
|
||||
assert.equal(f.effects.transitions.size, 0);
|
||||
@@ -132,32 +178,82 @@ test('a superseding transition starts from the current rendered intensity', () =
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
test('only visible animated stages keep the animation clock and render hold alive', () => {
|
||||
test('only visible animated stages keep the renderer’s clock and hold alive', () => {
|
||||
const f = fixture();
|
||||
f.effects.initStyles();
|
||||
const animated = f.effects.stages.retro;
|
||||
assert.notEqual(animated.uniforms.time, undefined);
|
||||
f.effects.setStageIntensity(animated, 1);
|
||||
f.tick(1000);
|
||||
assert.equal(animated.uniforms.time, 1);
|
||||
assert.equal(f.frames.size, 1);
|
||||
assert.equal(f.holds.size, 1);
|
||||
assert.equal(f.portHolds.size, 1);
|
||||
for (const cb of f.preRender) cb({ now: performance.now() + 1000 });
|
||||
assert.ok(f.stage('retro').uniforms.time > 0.9);
|
||||
assert.equal(f.frames.size, 0, 'no frames of its own');
|
||||
f.effects.setStageIntensity(animated, 0);
|
||||
f.tick(1100);
|
||||
assert.equal(f.frames.size, 0);
|
||||
assert.equal(f.portHolds.size, 0);
|
||||
assert.equal(f.holds.size, 0);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
test('a crossfade draws both styles until the old one reaches 0', () => {
|
||||
const f = fixture();
|
||||
f.effects.initStyles();
|
||||
f.effects.setStageIntensity(f.effects.stages.noir, 1);
|
||||
f.effects.startTransition('noir', 1, 0);
|
||||
f.effects.startTransition('thermal', 0, 1);
|
||||
f.tick(250);
|
||||
assert.equal(f.stage('noir').enabled, true);
|
||||
assert.equal(f.stage('thermal').enabled, true);
|
||||
assert.equal(f.stage('noir').uniforms.intensity, 0.5);
|
||||
assert.equal(f.stage('thermal').uniforms.intensity, 0.5);
|
||||
f.tick(500);
|
||||
assert.equal(f.stage('noir').enabled, false);
|
||||
assert.equal(f.stage('thermal').enabled, true);
|
||||
// Back again before the first fade-in ends: all three may draw at once.
|
||||
f.effects.startTransition('thermal', 1, 0);
|
||||
f.effects.startTransition('noir', 0, 1);
|
||||
f.tick(600);
|
||||
f.effects.startTransition('retro', 0, 1);
|
||||
f.tick(700);
|
||||
assert.deepEqual(
|
||||
['retro', 'thermal', 'noir'].map((name) => f.stage(name).enabled),
|
||||
[true, true, true],
|
||||
);
|
||||
f.tick(1300);
|
||||
assert.deepEqual(
|
||||
Object.entries(f.effects.stages)
|
||||
.filter(([, stage]) => stage.enabled)
|
||||
.map(([name]) => name)
|
||||
.sort(),
|
||||
['noir', 'retro'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
['retro', 'thermal', 'noir'].map((name) => f.stage(name).enabled),
|
||||
[true, false, true],
|
||||
);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
test('style parameters are written through to the renderer', () => {
|
||||
const f = fixture();
|
||||
f.effects.initStyles();
|
||||
assert.equal(f.effects.stages.thermal.uniforms.pixelation, 1.5);
|
||||
f.effects.stages.thermal.uniforms.pixelation = 4;
|
||||
assert.equal(f.stage('thermal').uniforms.pixelation, 4);
|
||||
assert.equal(f.effects.stages.thermal.uniforms.pixelation, 4);
|
||||
assert.equal(f.effects.stages.thermal.uniforms.unknown, undefined);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
test('direct Cockpit intensity writes are reconciled before rendering', () => {
|
||||
const f = fixture();
|
||||
f.effects.initStyles();
|
||||
f.effects.stages.thermal.uniforms.intensity = 1;
|
||||
f.effects.syncStagesEnabledFromIntensity();
|
||||
assert.equal(f.effects.stages.thermal.enabled, true);
|
||||
assert.equal(f.stage('thermal').enabled, true);
|
||||
f.effects.stages.thermal.uniforms.intensity = 0;
|
||||
f.effects.syncStagesEnabledFromIntensity();
|
||||
assert.equal(f.effects.stages.thermal.enabled, false);
|
||||
assert.equal(f.stage('thermal').enabled, false);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
@@ -199,8 +295,11 @@ test('bloom retains its dead zone, normalized intensity and independent toggle',
|
||||
f.effects.setBloomEnabled(true);
|
||||
f.effects.applyBloomIntensity(0);
|
||||
assert.equal(f.bloom.enabled, false);
|
||||
f.effects.applyBloomIntensity(12);
|
||||
assert.equal(f.bloom.enabled, false, 'the dead zone');
|
||||
f.effects.applyBloomIntensity(200);
|
||||
assert.equal(f.bloom.enabled, true);
|
||||
assert.equal(f.bloom.uniforms.glowOnly, false);
|
||||
assert.equal(f.bloom.uniforms.contrast, 87);
|
||||
f.effects.setBloomEnabled(false);
|
||||
assert.equal(f.effects.bloomIntensity, 200);
|
||||
@@ -213,14 +312,14 @@ test('bloom retains its dead zone, normalized intensity and independent toggle',
|
||||
test('sharpen uses the existing uniform scale and keeps values while disabled', () => {
|
||||
const f = fixture();
|
||||
f.effects.initPostProcess(0.49);
|
||||
assert.equal(f.effects.sharpenStage.uniforms.amount, 1.08);
|
||||
assert.equal(f.stage('sharpen').uniforms.amount, 1.08);
|
||||
f.effects.applySharpenIntensity(1);
|
||||
f.effects.setSharpenEnabled(true);
|
||||
assert.equal(f.effects.sharpenStage.uniforms.amount, 2.1);
|
||||
assert.equal(f.effects.sharpenStage.enabled, true);
|
||||
assert.equal(f.stage('sharpen').uniforms.amount, 2.1);
|
||||
assert.equal(f.stage('sharpen').enabled, true);
|
||||
f.effects.setSharpenEnabled(false);
|
||||
assert.equal(f.effects.sharpenIntensity, 1);
|
||||
assert.equal(f.effects.sharpenStage.enabled, false);
|
||||
assert.equal(f.stage('sharpen').enabled, false);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
@@ -228,17 +327,13 @@ test('sharpen at 0 runs no pass, and comes back with the slider', () => {
|
||||
const f = fixture();
|
||||
f.effects.initPostProcess(0.49);
|
||||
f.effects.setSharpenEnabled(true);
|
||||
assert.equal(f.effects.sharpenStage.enabled, true);
|
||||
assert.equal(f.stage('sharpen').enabled, true);
|
||||
f.effects.applySharpenIntensity(0);
|
||||
assert.equal(
|
||||
f.effects.sharpenStage.enabled,
|
||||
false,
|
||||
'no residual sharpen at 0',
|
||||
);
|
||||
assert.equal(f.stage('sharpen').enabled, false, 'no residual sharpen at 0');
|
||||
f.effects.setSharpenEnabled(true);
|
||||
assert.equal(f.effects.sharpenStage.enabled, false, 'on at 0 is still off');
|
||||
assert.equal(f.stage('sharpen').enabled, false, 'on at 0 is still off');
|
||||
f.effects.applySharpenIntensity(0.2);
|
||||
assert.equal(f.effects.sharpenStage.enabled, true);
|
||||
assert.equal(f.stage('sharpen').enabled, true);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
@@ -262,13 +357,17 @@ test('stop revokes pending work immediately but retains stages until final destr
|
||||
assert.equal(f.frames.size, 0);
|
||||
assert.equal(f.effects.stages.retro.uniforms.intensity, intensity);
|
||||
f.effects.destroy();
|
||||
assert.equal(f.stages.size, 1, 'the styles go; sharpen is the renderer’s');
|
||||
assert.equal(f.stage('sharpen').enabled, false);
|
||||
assert.equal(f.bloom.enabled, false);
|
||||
f.effects.destroy();
|
||||
f.renderer.dispose();
|
||||
assert.equal(f.stages.size, 0);
|
||||
assert.deepEqual(
|
||||
f.bloom,
|
||||
f.originalBloom,
|
||||
'borrowed bloom configuration is restored',
|
||||
'the renderer gives the bloom configuration back',
|
||||
);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
test('destroying one instance does not remove another pipeline or clock', () => {
|
||||
|
||||
@@ -5,6 +5,12 @@ import { useDisplayStore } from './stores/display.js';
|
||||
import { applicationPinia } from './vueRuntime.js';
|
||||
import { onLocaleChange, t } from '../i18n/index.js';
|
||||
import { UiLifetime } from './uiLifetime.js';
|
||||
import {
|
||||
findEffects,
|
||||
findFrame,
|
||||
findGlobe,
|
||||
releaseUnboundEffects,
|
||||
} from '../render/rendererOf.js';
|
||||
import {
|
||||
VisualEffects,
|
||||
STYLES,
|
||||
@@ -208,7 +214,9 @@ export class VisualSettings {
|
||||
setStyleParameter: (name, value) => this.setStyleParameter(name, value),
|
||||
});
|
||||
this._visualEffects = new VisualEffects({
|
||||
effects: findEffects(viewer),
|
||||
viewer,
|
||||
sky: () => findGlobe(viewer)?.sky,
|
||||
requestRender: services.governorRequestRender,
|
||||
holdRender: services.holdContinuousRender,
|
||||
releaseRender: services.releaseContinuousRender,
|
||||
@@ -450,17 +458,17 @@ export class VisualSettings {
|
||||
// (owner cockpit-FLIR field rounds, 2026-08-16). IR sensors see through
|
||||
// haze, so the boost styles simply turn fog off; the prior state restores
|
||||
// on exit. Transition-guarded so repeated syncs don't clobber the saved value.
|
||||
const scene = this.viewer?.scene;
|
||||
if (scene?.fog && irBoost !== this._irBoostActive) {
|
||||
// The globe's sky draws the fog; setting it asks for a frame.
|
||||
const sky = findGlobe(this.viewer)?.sky;
|
||||
if (sky && irBoost !== this._irBoostActive) {
|
||||
this._irBoostActive = irBoost;
|
||||
if (irBoost) {
|
||||
this._irFogWasEnabled = scene.fog.enabled;
|
||||
scene.fog.enabled = false;
|
||||
this._irFogWasEnabled = sky.get().fog;
|
||||
sky.set({ fog: false });
|
||||
} else if (this._irFogWasEnabled != null) {
|
||||
scene.fog.enabled = this._irFogWasEnabled;
|
||||
sky.set({ fog: this._irFogWasEnabled });
|
||||
this._irFogWasEnabled = null;
|
||||
}
|
||||
scene.requestRender?.();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -658,7 +666,7 @@ export class VisualSettings {
|
||||
fadeRatio: this._detectionFadePct / 100,
|
||||
outsideOpacity: this._detectionOutsidePct / 100,
|
||||
});
|
||||
this.viewer.scene.requestRender?.();
|
||||
findFrame(this.viewer)?.requestRender('detection-tuning');
|
||||
}
|
||||
|
||||
_setDetectionAllocation(strategy, { syncShare = true, persist = true } = {}) {
|
||||
@@ -1651,8 +1659,9 @@ export class VisualSettings {
|
||||
}
|
||||
releaseIrBoost() {
|
||||
if (!this._irBoostActive) return;
|
||||
if (this._irFogWasEnabled != null && this.viewer?.scene?.fog)
|
||||
this.viewer.scene.fog.enabled = this._irFogWasEnabled;
|
||||
const sky = findGlobe(this.viewer)?.sky;
|
||||
if (this._irFogWasEnabled != null && sky)
|
||||
sky.set({ fog: this._irFogWasEnabled });
|
||||
this._dataManager?.setLayerParams('flights', { irBoost: false });
|
||||
this._dataManager?.setLayerParams('military', { irBoost: false });
|
||||
this._irBoostActive = false;
|
||||
@@ -1662,5 +1671,7 @@ export class VisualSettings {
|
||||
this.stop();
|
||||
this.releaseIrBoost();
|
||||
this._visualEffects.destroy();
|
||||
// On a viewer with no renderer bound, its bloom comes back as it was.
|
||||
releaseUnboundEffects(this.viewer, this._visualEffects.effects);
|
||||
}
|
||||
}
|
||||
+24
-13
@@ -21,11 +21,12 @@ const utc = (time) =>
|
||||
? `${formatUtcDayMonth(time)} ${utcClock(time)}`
|
||||
: t('Unavailable');
|
||||
const clockTime = (time) => utcClock(time) || t('Unavailable');
|
||||
const age = (time) => {
|
||||
const minutes = Math.max(
|
||||
0,
|
||||
Math.floor((Date.now() - Date.parse(time)) / 60_000),
|
||||
);
|
||||
// Ages are measured from `nowMs`: the world clock's time at a past time, the
|
||||
// wall clock while live.
|
||||
const minutesBefore = (time, nowMs = Date.now()) =>
|
||||
Math.max(0, Math.floor((nowMs - Date.parse(time)) / 60_000));
|
||||
const age = (time, nowMs) => {
|
||||
const minutes = minutesBefore(time, nowMs);
|
||||
return minutes >= 60
|
||||
? t('{hours}h {minutes}m ago', {
|
||||
hours: Math.floor(minutes / 60),
|
||||
@@ -33,12 +34,21 @@ const age = (time) => {
|
||||
})
|
||||
: t('{minutes}m ago', { minutes });
|
||||
};
|
||||
const historyTime = (time) =>
|
||||
t('{time} · {minutes} min ago', {
|
||||
time: clockTime(time),
|
||||
minutes: Math.max(0, Math.floor((Date.now() - Date.parse(time)) / 60_000)),
|
||||
});
|
||||
const dated = (time) => `${utc(time)} · ${age(time)}`;
|
||||
// A frame's time on the timeline: its age while live; at a past time, the
|
||||
// clock time alone, as the timeline time is the one it is measured from.
|
||||
const historyTime = (time, state) =>
|
||||
state?.mode === 'history'
|
||||
? clockTime(time)
|
||||
: t('{time} · {minutes} min ago', {
|
||||
time: clockTime(time),
|
||||
minutes: minutesBefore(time),
|
||||
});
|
||||
const dated = (time, nowMs) => `${utc(time)} · ${age(time, nowMs)}`;
|
||||
/** The time the observed products show: the timeline time, or now while live. */
|
||||
const shownNow = (state) =>
|
||||
state?.mode === 'history' && Number.isFinite(Date.parse(state.target))
|
||||
? Date.parse(state.target)
|
||||
: Date.now();
|
||||
const set = (node, key, value) => {
|
||||
if (node[key] !== value) node[key] = value;
|
||||
};
|
||||
@@ -151,7 +161,7 @@ export function createWeatherPanel({
|
||||
? t('No frame within {gap} min of {time}', { gap, time })
|
||||
: t('No frame within {gap} h of {time}', { gap: gap / 60, time });
|
||||
} else if (shown) {
|
||||
detail = dated(shown);
|
||||
detail = dated(shown, shownNow(state));
|
||||
if (state.mode === 'history')
|
||||
detail =
|
||||
Date.parse(shown) === Date.parse(state.target)
|
||||
@@ -163,7 +173,8 @@ export function createWeatherPanel({
|
||||
valid: utc(summary.validTime),
|
||||
issued: utc(summary.issuedTime),
|
||||
});
|
||||
if (state.mode === 'history')
|
||||
// Unless its source follows the timeline, wind stays at the live edge.
|
||||
if (state.mode === 'history' && !clock?.follows?.(id))
|
||||
detail = t('{detail} · Does not follow history', { detail });
|
||||
}
|
||||
const lines = [
|
||||
|
||||
@@ -6,6 +6,7 @@ import { setLocale } from '../i18n/index.js';
|
||||
import { createWeatherPanel } from './weatherPanel.js';
|
||||
import { railDocumentFixture as railFixture } from './railTestFixture.mjs';
|
||||
import { createAirQualityLayer } from '../layers/airQuality/index.js';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
const ticks = ['2026-09-22T01:00:00Z', '2026-09-22T01:05:00Z'];
|
||||
const wind = {
|
||||
id: 'wind',
|
||||
@@ -517,9 +518,10 @@ test('compact lines show observation age, forecast validity, storm selection or
|
||||
'Forecast · valid 09-22 01:00 UTC',
|
||||
);
|
||||
f.state({ mode: 'history', target: ticks[1] });
|
||||
// At a past time a frame's age counts from the timeline time.
|
||||
assert.equal(
|
||||
compact(radar.id).textContent,
|
||||
'09-22 01:05 UTC · 8m ago · synced',
|
||||
'09-22 01:05 UTC · 0m ago · synced',
|
||||
);
|
||||
assert.equal(
|
||||
compact(wind.id).textContent,
|
||||
@@ -534,7 +536,7 @@ test('compact lines show observation age, forecast validity, storm selection or
|
||||
});
|
||||
assert.equal(
|
||||
compact(radar.id).textContent,
|
||||
'09-22 01:00 UTC · 13m ago · nearest',
|
||||
'09-22 01:00 UTC · 5m ago · nearest',
|
||||
);
|
||||
clickHeader(f, wind.id);
|
||||
assert.equal(
|
||||
@@ -732,7 +734,9 @@ test('air-quality readout renders its band legend, Canada coverage and worst-fir
|
||||
},
|
||||
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
|
||||
});
|
||||
layer.init({ dataSources: { add() {}, remove() {} } });
|
||||
const viewer = {};
|
||||
bindFakeDraw(viewer);
|
||||
layer.init(viewer);
|
||||
layer.enable();
|
||||
await layer.update();
|
||||
const f = fixture();
|
||||
@@ -791,3 +795,43 @@ test('source-supplied legend units are shown as given; catalog units are transla
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
|
||||
test('at a past time, frame ages count from the timeline time, not now, and the frame time is that time', (t) => {
|
||||
t.mock.timers.enable({
|
||||
apis: ['Date'],
|
||||
now: Date.parse('2032-01-01T00:00:00Z'),
|
||||
});
|
||||
const f = fixture();
|
||||
const view = createWeatherPanel(f);
|
||||
view.update([radar]);
|
||||
f.state({
|
||||
mode: 'history',
|
||||
target: '2026-09-22T01:20:00Z',
|
||||
products: [{ id: radar.id, shown: ticks[1], selected: ticks[1] }],
|
||||
});
|
||||
assert.equal(
|
||||
line(f, radar.id, 'time').textContent,
|
||||
'09-22 01:05 UTC · 15m ago · nearest',
|
||||
);
|
||||
// The panel's frame time is the timeline time alone, with no age.
|
||||
assert.equal(frameTime(f).textContent, '01:20 UTC');
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
test('the wind card notes it stays live only while its source does not follow the timeline', () => {
|
||||
const f = fixture();
|
||||
const following = new Set();
|
||||
f.clock.follows = (id) => following.has(id);
|
||||
const view = createWeatherPanel(f);
|
||||
view.update([wind, radar]);
|
||||
f.state({ mode: 'history', target: ticks[1] });
|
||||
assert.match(line(f, 'wind', 'time').textContent, /Does not follow history/);
|
||||
following.add('wind');
|
||||
f.state({ target: ticks[0] });
|
||||
assert.match(line(f, 'wind', 'time').textContent, /^Forecast · valid /);
|
||||
assert.doesNotMatch(
|
||||
line(f, 'wind', 'time').textContent,
|
||||
/Does not follow history/,
|
||||
);
|
||||
view.destroy();
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { h, nextTick, shallowRef } from 'vue';
|
||||
import { canvasOf, findCamera, findFrame } from '../render/rendererOf.js';
|
||||
import WildlifeSightingCard from './views/panels/WildlifeSightingCard.vue';
|
||||
import {
|
||||
panWildlifeSighting,
|
||||
@@ -66,9 +67,7 @@ export function createWildlifeSightingCard({
|
||||
|
||||
function observeLayout(elements) {
|
||||
const next = new Set(
|
||||
[host.firstElementChild, viewer?.scene?.canvas, ...elements].filter(
|
||||
Boolean,
|
||||
),
|
||||
[host.firstElementChild, canvasOf(viewer), ...elements].filter(Boolean),
|
||||
);
|
||||
let changed = false;
|
||||
for (const element of observed) {
|
||||
@@ -211,7 +210,7 @@ export function createWildlifeSightingCard({
|
||||
const outside = (event) => {
|
||||
if (!selected.value || host.contains(event.target)) return;
|
||||
// The layer selects on pointer-up; its following click must keep the card open.
|
||||
const canvas = viewer?.scene?.canvas;
|
||||
const canvas = canvasOf(viewer);
|
||||
if (canvas && (event.target === canvas || canvas.contains?.(event.target)))
|
||||
return;
|
||||
layer.clearSightingSelection();
|
||||
@@ -221,29 +220,27 @@ export function createWildlifeSightingCard({
|
||||
const onResize = () => position();
|
||||
windowRef?.addEventListener('resize', onResize);
|
||||
|
||||
function listen(event, callback) {
|
||||
const remove = event?.addEventListener?.(callback);
|
||||
function listen(camera, event, callback) {
|
||||
const remove = camera?.on(event, callback);
|
||||
if (typeof remove === 'function') removers.push(remove);
|
||||
else if (event?.removeEventListener)
|
||||
removers.push(() => event.removeEventListener(callback));
|
||||
}
|
||||
function startFrameUpdates() {
|
||||
if (!selected.value || removeFrame) return;
|
||||
// Installed only for camera motion; an idle card has zero per-frame work.
|
||||
removeFrame =
|
||||
viewer?.scene?.preRender?.addEventListener?.(() => position()) || null;
|
||||
removeFrame = findFrame(viewer)?.on('preRender', () => position()) || null;
|
||||
}
|
||||
listen(viewer?.camera?.moveStart, () => {
|
||||
const camera = viewer ? findCamera(viewer) : null;
|
||||
listen(camera, 'moveStart', () => {
|
||||
moving = true;
|
||||
startFrameUpdates();
|
||||
});
|
||||
listen(viewer?.camera?.moveEnd, () => {
|
||||
listen(camera, 'moveEnd', () => {
|
||||
moving = false;
|
||||
removeFrame?.();
|
||||
removeFrame = null;
|
||||
position();
|
||||
});
|
||||
listen(viewer?.camera?.changed, () => {
|
||||
listen(camera, 'changed', () => {
|
||||
if (!moving) position();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import test from 'node:test';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import { bindWildlifeViewer } from '../testSupport/wildlifeViewer.mjs';
|
||||
import { nextTick } from 'vue';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { getLocale, setLocale, t } from '../i18n/index.js';
|
||||
@@ -97,9 +99,10 @@ function fixture(
|
||||
const changed = events();
|
||||
const preRender = events();
|
||||
const viewer = {
|
||||
scene: { canvas, preRender, pick: () => picked },
|
||||
scene: { canvas, preRender },
|
||||
camera: { moveStart, moveEnd, changed },
|
||||
};
|
||||
bindWildlifeViewer(viewer);
|
||||
const state = {
|
||||
enabled: true,
|
||||
destroyed: false,
|
||||
@@ -111,7 +114,7 @@ function fixture(
|
||||
contextIds: new Set(),
|
||||
viewer,
|
||||
};
|
||||
let picked = null;
|
||||
let picked;
|
||||
let hit = null;
|
||||
let onClick;
|
||||
let clears = 0;
|
||||
@@ -123,17 +126,16 @@ function fixture(
|
||||
state,
|
||||
services: {
|
||||
now: () => NOW,
|
||||
cesium: { ScreenSpaceEventType: { LEFT_CLICK: 0 } },
|
||||
overlayHost: {
|
||||
setEntries: (id, entries) => overlays.set(id, entries),
|
||||
hitTest: (_x, _y, { sourceId }) =>
|
||||
hit?.sourceId === sourceId ? hit : null,
|
||||
},
|
||||
screenSpaceEventHandlerFactory: () => ({
|
||||
setInputAction(fn) {
|
||||
input: () => ({
|
||||
onClick(fn) {
|
||||
onClick = fn;
|
||||
return () => (onClick = null);
|
||||
},
|
||||
destroy() {},
|
||||
}),
|
||||
focus: { requestWorldFocus: (value) => flights.push(value) },
|
||||
},
|
||||
@@ -204,10 +206,8 @@ function fixture(
|
||||
staleListener: () => staleListener,
|
||||
clears: () => clears,
|
||||
async click(kind = 'dot', target = initialRow) {
|
||||
picked =
|
||||
kind === 'icon'
|
||||
? { primitive: { id: `wildlife:${target.stableId}` } }
|
||||
: { id: `wildlife:${target.stableId}` };
|
||||
// Dots and icons alike are picked by their item id.
|
||||
picked = `wildlife:${target.stableId}`;
|
||||
hit =
|
||||
kind === 'ambient photo card'
|
||||
? {
|
||||
@@ -217,7 +217,12 @@ function fixture(
|
||||
}),
|
||||
}
|
||||
: null;
|
||||
onClick({ position: { x: 50, y: 50 } });
|
||||
// What is exactly under the click, as the layer reads it.
|
||||
onClick({
|
||||
screenPosition: { x: 50, y: 50 },
|
||||
topHit: { set: 'wildlife', id: picked },
|
||||
id: picked,
|
||||
});
|
||||
await settle();
|
||||
},
|
||||
async publish(next) {
|
||||
@@ -482,38 +487,40 @@ test('a selected dot flies to its true position and its card pans clear of chrom
|
||||
test('the camera correction preserves altitude and orientation and honors reduced motion', () => {
|
||||
const flights = [];
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 250_000),
|
||||
positionWC: fromDegrees(0, 0, 250_000),
|
||||
positionCartographic: { height: 250_000 },
|
||||
heading: 0.2,
|
||||
pitch: -1.2,
|
||||
roll: 0.1,
|
||||
pickEllipsoid: (p) => Cesium.Cartesian3.fromDegrees(p.x / 100, p.y / 100),
|
||||
flyTo: (value) => flights.push(value),
|
||||
};
|
||||
const viewer = {
|
||||
camera,
|
||||
scene: {
|
||||
canvas: { getBoundingClientRect: () => rect(0, 0, 1200, 900) },
|
||||
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
|
||||
},
|
||||
};
|
||||
bindWildlifeViewer(viewer, {
|
||||
query: { pickEllipsoid: (x, y) => fromDegrees(x / 100, y / 100) },
|
||||
});
|
||||
for (const reduced of [false, true]) {
|
||||
assert.equal(
|
||||
panWildlifeSighting(viewer, { x: 10, y: 10 }, { x: 30, y: 50 }, reduced),
|
||||
true,
|
||||
);
|
||||
const flight = flights.at(-1);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(flight.destination).height - 250_000,
|
||||
) < 0.001,
|
||||
);
|
||||
assert.ok(Math.abs(toLonLatH(flight.destination).height - 250_000) < 0.001);
|
||||
assert.deepEqual(flight.orientation, {
|
||||
heading: 0.2,
|
||||
pitch: -1.2,
|
||||
roll: 0.1,
|
||||
});
|
||||
assert.equal(flight.duration, reduced ? 0 : 0.22);
|
||||
assert.equal(
|
||||
flight.easingFunction,
|
||||
Cesium.EasingFunction.QUADRATIC_OUT,
|
||||
'eased as before',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import { horizonFrom } from '../geo/horizon.js';
|
||||
import { add, sub } from '../geo/vector.js';
|
||||
import { canvasOf, findCamera, findQuery } from '../render/rendererOf.js';
|
||||
import { WORLD_OVERLAY_OCCLUDER_SELECTORS } from '../overlays/worldOverlayChrome.js';
|
||||
|
||||
// DOM cards also avoid the HUD edges and responsive sheet containers.
|
||||
@@ -38,7 +41,7 @@ export function readWildlifeCardSafeArea({
|
||||
viewer,
|
||||
windowRef = globalThis.window,
|
||||
}) {
|
||||
const canvasRect = viewer?.scene?.canvas?.getBoundingClientRect?.();
|
||||
const canvasRect = canvasOf(viewer)?.getBoundingClientRect?.();
|
||||
const width =
|
||||
windowRef?.innerWidth || documentRef.documentElement.clientWidth;
|
||||
const height =
|
||||
@@ -209,66 +212,51 @@ export function placeWildlifeSightingCard(point, size, safeArea) {
|
||||
|
||||
/** Project a front-side sighting into viewport coordinates. */
|
||||
export function projectWildlifeSighting(viewer, row, layer) {
|
||||
const camera = viewer ? findCamera(viewer) : null;
|
||||
const query = viewer ? findQuery(viewer) : null;
|
||||
if (
|
||||
!viewer?.scene ||
|
||||
!camera ||
|
||||
!query ||
|
||||
!Number.isFinite(row?.lat) ||
|
||||
!Number.isFinite(row?.lon)
|
||||
)
|
||||
return null;
|
||||
const position =
|
||||
layer?.getSightingPosition?.(row.stableId) ||
|
||||
Cesium.Cartesian3.fromDegrees(row.lon, row.lat);
|
||||
const ellipsoid = viewer.scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84;
|
||||
if (
|
||||
viewer.camera?.positionWC &&
|
||||
new Cesium.EllipsoidalOccluder(
|
||||
ellipsoid,
|
||||
viewer.camera.positionWC,
|
||||
).isPointVisible(position) !== true
|
||||
)
|
||||
layer?.getSightingPosition?.(row.stableId) || fromDegrees(row.lon, row.lat);
|
||||
if (horizonFrom(camera.pose().position).isPointVisible(position) !== true)
|
||||
return null;
|
||||
const point = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
viewer.scene,
|
||||
position,
|
||||
);
|
||||
const point = query.project(position);
|
||||
if (!point) return null;
|
||||
const rect = viewer.scene.canvas?.getBoundingClientRect?.();
|
||||
const rect = canvasOf(viewer)?.getBoundingClientRect?.();
|
||||
return { x: point.x + (rect?.left || 0), y: point.y + (rect?.top || 0) };
|
||||
}
|
||||
|
||||
/** Translate the camera by the smallest screen correction and preserve its
|
||||
* altitude/orientation. A card must never zoom merely to reveal its anchor. */
|
||||
export function panWildlifeSighting(viewer, from, to, reducedMotion = false) {
|
||||
const camera = viewer?.camera;
|
||||
if (!camera?.pickEllipsoid || !camera.flyTo) return false;
|
||||
const rect = viewer.scene.canvas.getBoundingClientRect();
|
||||
const local = (p) => new Cesium.Cartesian2(p.x - rect.left, p.y - rect.top);
|
||||
const ellipsoid = viewer.scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84;
|
||||
const start = camera.pickEllipsoid(local(from), ellipsoid);
|
||||
const finish = camera.pickEllipsoid(local(to), ellipsoid);
|
||||
if (!start || !finish || !camera.positionWC) return false;
|
||||
const delta = Cesium.Cartesian3.subtract(
|
||||
start,
|
||||
finish,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const destination = Cesium.Cartesian3.add(
|
||||
camera.positionWC,
|
||||
delta,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const cartographic = ellipsoid.cartesianToCartographic(destination);
|
||||
if (!cartographic) return false;
|
||||
cartographic.height = camera.positionCartographic.height;
|
||||
camera.flyTo({
|
||||
destination: ellipsoid.cartographicToCartesian(cartographic),
|
||||
orientation: {
|
||||
heading: camera.heading,
|
||||
pitch: camera.pitch,
|
||||
roll: camera.roll,
|
||||
const camera = viewer ? findCamera(viewer) : null;
|
||||
const query = viewer ? findQuery(viewer) : null;
|
||||
const canvas = canvasOf(viewer);
|
||||
if (!camera || !query || !canvas) return false;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const pick = (p) => query.pickEllipsoid(p.x - rect.left, p.y - rect.top);
|
||||
const start = pick(from);
|
||||
const finish = pick(to);
|
||||
if (!start || !finish) return false;
|
||||
const pose = camera.pose();
|
||||
const destination = toLonLatH(add(pose.position, sub(start, finish)));
|
||||
if (!destination) return false;
|
||||
camera.flyTo(
|
||||
{ lon: destination.lon, lat: destination.lat, height: pose.height },
|
||||
{
|
||||
orientation: {
|
||||
heading: pose.heading,
|
||||
pitch: pose.pitch,
|
||||
roll: pose.roll,
|
||||
},
|
||||
durationS: reducedMotion ? 0 : 0.22,
|
||||
easing: 'quadraticOut',
|
||||
},
|
||||
duration: reducedMotion ? 0 : 0.22,
|
||||
easingFunction: Cesium.EasingFunction.QUADRATIC_OUT,
|
||||
});
|
||||
);
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user