diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 85018a9e5..6b2a644ff 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -110,7 +110,6 @@ "src/services/meshFloorSampler.js", "src/sky/starrySky.js", "src/ui/applicationShell.js", - "src/ui/cameraOrientationControls.js", "src/ui/cockpitCamera.js", "src/ui/cockpitContext.js", "src/ui/cockpitController.js", diff --git a/src/ui/cameraOrientationControls.js b/src/ui/cameraOrientationControls.js index bd8e6f988..a69621d87 100644 --- a/src/ui/cameraOrientationControls.js +++ b/src/ui/cameraOrientationControls.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { isPickedWorldPosition } from '../data/scenePick.js'; import { t } from '../i18n/index.js'; import { @@ -7,6 +6,19 @@ import { isFollowing, onFollowChanged, } from '../data/followed.js'; +import { + clamp, + eastNorthUp, + inverseFramePoint, + magnitude, + negativePiToPi, + toDegrees, + toRadians, + TWO_PI, + zeroToTwoPi, +} from '../geo/index.js'; +import { findCamera, findFrame, findQuery } from '../render/rendererOf.js'; +import { placeFollowEye } from './shareFollow.js'; function trackedTarget(viewer) { // The visual's sample first: sampling a flight CallbackProperty twice can @@ -14,131 +26,109 @@ function trackedTarget(viewer) { 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 = viewer?.scene?.canvas; + 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 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 = isFollowing(viewer) - ? 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; @@ -181,8 +171,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. */ @@ -199,21 +189,20 @@ 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 followed = followedOf(viewer); pending = destination; const start = now(); - const headingDelta = Cesium.Math.negativePiToPi( - destination.heading - frame.heading, - ); - remove = viewer.scene.preUpdate.addEventListener(() => { + 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 progress = clamp((now() - start) / duration, 0, 1); + const eased = cubicInOut(progress); const target = followed ? trackedTarget(viewer) : frame.target; if ( !isPickedWorldPosition(target) || @@ -221,7 +210,7 @@ export function createCameraOrientationAnimator( ...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(); @@ -229,7 +218,7 @@ export function createCameraOrientationAnimator( } if (progress === 1) cancel(); }); - viewer.scene.requestRender?.(); + frames.requestRender('camera-orientation'); return true; } return { @@ -282,7 +271,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); } @@ -328,17 +317,16 @@ 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(findCamera(viewer)?.on('moveEnd', refreshTilt)); if (viewer) removers.push(onFollowChanged(viewer, animator.cancel)); for (const type of ['pointerdown', 'wheel']) { const canvas = viewer?.scene?.canvas; diff --git a/src/ui/cameraOrientationControls.test.mjs b/src/ui/cameraOrientationControls.test.mjs index f7db379ef..277f07c24 100644 --- a/src/ui/cameraOrientationControls.test.mjs +++ b/src/ui/cameraOrientationControls.test.mjs @@ -13,8 +13,34 @@ import { } from './cameraOrientationControls.js'; import { NavigationController } from './navigationController.js'; import { bindRenderer } from '../render/rendererOf.js'; +import { + createCesiumQuery, + queryCapabilities, +} from '../render/cesium/query.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +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 = []; const changed = new Cesium.Event(); @@ -27,7 +53,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 }); }, @@ -48,7 +74,7 @@ function createViewer({ cameraPosition, target, pickPosition = null } = {}) { requestRender: () => calls.push({ type: 'requestRender' }), }, }; - return { viewer, calls, target: surface }; + return { viewer: withPorts(viewer), calls, target: surface }; } /** @@ -98,8 +124,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; @@ -108,8 +138,8 @@ 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(); + return { viewer: withPorts({ camera, scene }, { frames }), target }; } /** Place a real camera in an orbit around `target` and release the frame. */ @@ -279,7 +309,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({ @@ -410,9 +440,9 @@ test('a sky-facing camera yields no frame and both actions decline', () => { scene.pickPosition = () => null; scene.globe.pick = () => undefined; scene.requestRender = () => {}; - camera.getPickRay = () => ({}); + camera.getPickRay = () => new Cesium.Ray(); camera.pickEllipsoid = () => undefined; - const viewer = { camera, scene }; + const viewer = withPorts({ camera, scene }); assert.equal(readCameraTargetFrame(viewer), null); assert.equal(toggleCameraTilt(viewer), false); @@ -426,16 +456,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', ); }); @@ -455,7 +485,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')); diff --git a/src/ui/shareButton.test.mjs b/src/ui/shareButton.test.mjs index fd91708d6..bd5b3e543 100644 --- a/src/ui/shareButton.test.mjs +++ b/src/ui/shareButton.test.mjs @@ -191,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); @@ -231,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 () => {}, @@ -269,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 () => {}, diff --git a/src/ui/shareFollow.js b/src/ui/shareFollow.js index 3a14c298e..798e249d9 100644 --- a/src/ui/shareFollow.js +++ b/src/ui/shareFollow.js @@ -190,3 +190,24 @@ function turnToward(from, to, step) { ); return Cesium.Cartesian3.multiplyByScalar(direction, length, direction); } + +/** + * 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. Returns true. + * @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 = viewer.camera; + const trackedTransform = Cesium.Matrix4.clone(camera.transform); + camera.lookAt( + new Cesium.Cartesian3(target.x, target.y, target.z), + new Cesium.HeadingPitchRange(offset.heading, offset.pitch, offset.range), + ); + camera.lookAtTransform(trackedTransform); + viewer.scene?.requestRender?.(); + return true; +}