diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index ef692e542..bbe0c0e36 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -6,13 +6,19 @@ it meets the contract. The contract is version `0`. Today the application still drives Cesium directly; later work moves the layers onto the contract one family at a time. -The package exports three modules: +The package exports four modules: -| Export | What it is | -| ---------------------------------- | ------------------------------------------------------------------------------ | -| `gods-eye-view/render/contract` | The types, one `.d.ts` per port, plus the run-time member list and shape check | -| `gods-eye-view/render/stub` | A renderer that draws nothing, for tests | -| `gods-eye-view/render/conformance` | The conformance suite, reference scenes and visual comparison | +| Export | What it is | +| ------------------------------------ | -------------------------------------------------------------------------------------- | +| `gods-eye-view/render/contract` | The types, one `.d.ts` per port, plus the run-time member list and shape check | +| `gods-eye-view/render/stub` | A renderer that draws nothing, for tests | +| `gods-eye-view/render/camera/events` | The camera port's events: `changed` per listener, `moveStart`/`moveEnd`, command hooks | +| `gods-eye-view/render/conformance` | The conformance suite, reference scenes and visual comparison | + +A camera of its own (a camera controller over a renderer without one) can +take the camera events from `render/camera/events` and the geodesy it needs +(`geodesicAt`, `horizonFrom` and the rest) from `gods-eye-view/geo`, so it +measures and fires exactly as the stub does. ## Ports @@ -179,6 +185,9 @@ in memory and draws nothing. It has: `renderer.testing` drives it with `tick()`, `advance(ms)`, `pointer(type, x, y)`, `scriptPicks`, `setHeights` and `cacheHeight`, and records its calls. +`testing.drawnPosition({ set, id }, aheadMs)` is where it draws an item now +(or `aheadMs` from now), so a +camera that is not the stub's own can follow drawn items there. A listener that throws with nothing subscribed to `error` goes to `reportError`; Node has none, so the stub rethrows it on a microtask and `node:test` fails the running test. A test that expects a throw subscribes diff --git a/package.json b/package.json index cd98ee3f7..89ef24474 100644 --- a/package.json +++ b/package.json @@ -298,6 +298,7 @@ "./geo": "./src/geo/index.js", "./render/contract": "./src/render/contract/index.js", "./render/stub": "./src/render/stub/index.js", + "./render/camera/events": "./src/render/camera/events.js", "./render/cesium/unbound": "./src/render/cesium/unbound.js", "./render/conformance": "./src/render/conformance/index.js" } diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a88788895..c32a26926 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -888,6 +888,7 @@ "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/ui/cockpitBriefPages.js", "src/ui/cockpitContextState.js", @@ -1177,6 +1178,7 @@ "src/ui/visualSettings.js", "src/worldFocus.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/vector.js", "src/geo/ellipsoid.js", "src/geo/frames.js", @@ -1848,6 +1850,7 @@ "src/render/cesium/camera.js", "src/render/camera/events.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/celestial.js", "src/geo/ellipsoid.js", "src/geo/quaternion.js", @@ -1996,6 +1999,7 @@ "modules": [ "src/data/satelliteClass.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/data/satellitePass.js", "src/sources/tle.js", @@ -2279,6 +2283,8 @@ "src/render/camera/poseSignature.js", "src/data/militaryAwarenessEngine.js", "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/horizon.js", "src/geo/julian.js", "src/data/installationNames.js", "src/layers/awareness/controls.js", @@ -2348,6 +2354,7 @@ "src/layers/traffic/animation.js", "src/layers/traffic/controls.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/layers/traffic/flow.js", "src/layers/traffic/flowDecode.js", @@ -2629,6 +2636,7 @@ "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/layers/streetLevel/credits.js", "src/render/creditMarkup.js", "src/layers/streetLevel/providers/mapillary/index.js", @@ -2724,6 +2732,7 @@ "src/layers/alpr/index.js", "src/data/followed.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/layers/alpr/model.js", "src/layers/alpr/policy.js", @@ -2989,6 +2998,7 @@ "src/i18n/marker.js", "src/maps/availability.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/maps/catalog.js", "src/maps/controller.js", @@ -4958,6 +4968,7 @@ "src/render/rendererOf.js", "src/render/camera/events.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -5664,6 +5675,7 @@ "src/data/terrainHeights.js", "src/data/transit.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/data/transitFeeds.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", @@ -5751,6 +5763,7 @@ "src/render/cesium/iconOrientation.js", "src/layers/transit/selection.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/layers/transit/state.js", "src/layers/transit/testing.js", @@ -6284,6 +6297,8 @@ "exports": ["./agent/world-packet"], "modules": [ "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/horizon.js", "src/geo/julian.js", "src/geo/vector.js", "src/geo/ellipsoid.js", @@ -6314,6 +6329,8 @@ "exports": ["./geo"], "modules": [ "src/geo/index.js", + "src/geo/horizon.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/geo/vector.js", "src/geo/ellipsoid.js", @@ -6324,7 +6341,12 @@ "external": [] }, "render": { - "exports": ["./render/contract", "./render/stub", "./render/conformance"], + "exports": [ + "./render/contract", + "./render/stub", + "./render/camera/events", + "./render/conformance" + ], "modules": [ "src/render/contract/index.js", "src/render/stub/index.js", diff --git a/src/geo/index.js b/src/geo/index.js index c064bd24c..e8fc0111d 100644 --- a/src/geo/index.js +++ b/src/geo/index.js @@ -2,8 +2,9 @@ * @module geo * @description Cesium-free geodesy and vector maths: WGS84, ECEF and * geodetic conversions, east-north-up frames, quaternions, and the sun and - * moon. Plain numbers and `{x, y, z}` objects only, so code that needs - * maths but not a renderer does not import one. + * moon, a point along a geodesic and the ellipsoid's horizon. Plain numbers + * and `{x, y, z}` objects only, so code that needs maths but not a renderer + * does not import one. */ export * from './vector.js'; export * from './ellipsoid.js'; @@ -11,3 +12,5 @@ export * from './frames.js'; export * from './celestial.js'; export * from './julian.js'; export * from './quaternion.js'; +export { geodesicAt } from './geodesic.js'; +export { horizonFrom } from './horizon.js'; diff --git a/src/render/camera/events.js b/src/render/camera/events.js index 9b40fc3cb..e7516960c 100644 --- a/src/render/camera/events.js +++ b/src/render/camera/events.js @@ -1,15 +1,22 @@ /** * @module render/camera/events - * @description The camera port's events, shared by the Cesium port and the stub: the - * listener lists, delivery (a throwing listener is reported, the rest still - * run), and the contract's per-listener `changed` measure. A renderer calls - * `stepChanged()` once per frame and `emit()` for the events its engine + * @description The camera port's events, shared by the renderer, the stub and + * camera controllers (the package's `./render/camera/events` + * export): + * the listener lists, delivery (a throwing listener is reported, the rest + * still run), the contract's per-listener `changed` measure, move detection + * (`moveStart` on a change, `moveEnd` 500 ms after the last one, never + * while following) and the command hooks (`onCommand`). A renderer calls + * `stepChanged()` and `stepMoveDetection()` once per frame, `command()` + * before each camera command, and `emit()` for the events its engine * raises. */ import { acosClamped, distance, dot } from '../../geo/index.js'; const TWO_PI = Math.PI * 2; +/** `moveEnd` waits this long after the last change, ms, as the reference does. */ +export const MOVE_END_WAIT_MS = 500; /** The contract's camera events. */ export const CAMERA_EVENTS = Object.freeze([ @@ -26,15 +33,43 @@ const angleDelta = (a, b) => { return (d > Math.PI ? TWO_PI - d : d) / Math.PI; }; +/** + * Whether two world views are the same: the same position, and directions + * and ups whose dot products are each one's own. + */ +function sameView(a, b) { + return ( + a && + b && + distance(a.position, b.position) === 0 && + dot(a.direction, b.direction) === dot(a.direction, a.direction) && + dot(a.up, b.up) === dot(a.up, a.up) + ); +} + /** * @param {{pose: () => import('../contract/camera').CameraPose, + * world?: () => {position: object, direction: object, up: object}, + * following?: () => boolean, * report: (error: unknown) => void, thresholds?: boolean}} options `pose` - * is read only while a `changed` listener is registered; `thresholds` + * is read only while a `changed` listener is registered; `world` (the + * eye in world coordinates; `pose()` when omitted) and `following` (no + * `moveEnd` while true) are read by `stepMoveDetection`; `thresholds` * false (a renderer without `cameraChangeThreshold`) ignores a listener's * own threshold, so every listener fires at 0.5. */ -export function createCameraEvents({ pose, report, thresholds = true }) { +export function createCameraEvents({ + pose, + world = pose, + following = () => false, + report, + thresholds = true, +}) { const listeners = Object.fromEntries(CAMERA_EVENTS.map((e) => [e, []])); + const commandHooks = []; + let lastView = null; + let moving = false; + let lastMovedAt = 0; function deliver(entry) { if (!entry.live) return; @@ -109,13 +144,81 @@ export function createCameraEvents({ pose, report, thresholds = true }) { } } - /** Drop every listener, including those of an event under way. */ + /** + * Once a frame, after `preUpdate`: `moveStart` when the eye changed since + * the last frame, `moveEnd` once it has not for 500 ms (`now`, ms) and + * nothing is followed. + * @param {number} now + */ + function stepMoveDetection(now) { + const v = world(); + const current = { position: v.position, direction: v.direction, up: v.up }; + const changed = lastView && !sameView(lastView, current); + lastView = current; + if (changed) { + lastMovedAt = now; + if (!moving) { + moving = true; + emit('moveStart'); + } + } else if ( + moving && + !following() && + now - lastMovedAt >= MOVE_END_WAIT_MS + ) { + moving = false; + emit('moveEnd'); + } + } + + /** + * Tell every command hook about a command before it runs. + * @param {import('../contract/camera').CameraCommand['kind']} kind + */ + function command(kind) { + for (const entry of commandHooks.slice()) { + if (!entry.live) continue; + try { + entry.cb({ kind }); + } catch (error) { + report(error); + } + } + } + + /** + * The contract's `onCommand`. Each registration is its own: its `Off` + * removes only it, once. + * @param {(command: import('../contract/camera').CameraCommand) => void} cb + * @returns {() => void} + */ + function onCommand(cb) { + const entry = { cb, live: true }; + commandHooks.push(entry); + return () => { + entry.live = false; + const i = commandHooks.indexOf(entry); + if (i >= 0) commandHooks.splice(i, 1); + }; + } + + /** Drop every listener and hook, including those of an event under way. */ function clear() { for (const list of Object.values(listeners)) { for (const entry of list) entry.live = false; list.length = 0; } + for (const entry of commandHooks) entry.live = false; + commandHooks.length = 0; } - return { on, emit, stepChanged, clear }; + return { + on, + emit, + stepChanged, + stepMoveDetection, + command, + onCommand, + clear, + }; } diff --git a/src/render/camera/events.test.mjs b/src/render/camera/events.test.mjs new file mode 100644 index 000000000..d2e81750d --- /dev/null +++ b/src/render/camera/events.test.mjs @@ -0,0 +1,90 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createCameraEvents, MOVE_END_WAIT_MS } from './events.js'; +import { geodesicAt, horizonFrom } from '../../geo/index.js'; + +const view = (x) => ({ + position: { x, y: 0, z: 0 }, + direction: { x: -1, y: 0, z: 0 }, + up: { x: 0, y: 0, z: 1 }, +}); + +test('moveStart on a change, moveEnd once nothing moved for 500 ms and nothing is followed', () => { + let eye = view(7e6); + let following = false; + const seen = []; + const events = createCameraEvents({ + pose: () => eye, + world: () => eye, + following: () => following, + report: (error) => assert.fail(error), + }); + events.on('moveStart', () => seen.push('start')); + events.on('moveEnd', () => seen.push('end')); + events.stepMoveDetection(0); + eye = view(7e6 + 1); + events.stepMoveDetection(16); + assert.deepEqual(seen, ['start']); + events.stepMoveDetection(16 + MOVE_END_WAIT_MS - 1); + assert.deepEqual(seen, ['start']); + // A later change starts the wait again, and moveStart is not repeated. + eye = view(7e6 + 2); + events.stepMoveDetection(400); + events.stepMoveDetection(16 + MOVE_END_WAIT_MS); + assert.deepEqual(seen, ['start']); + events.stepMoveDetection(400 + MOVE_END_WAIT_MS - 1); + assert.deepEqual(seen, ['start']); + following = true; + events.stepMoveDetection(400 + MOVE_END_WAIT_MS); + assert.deepEqual(seen, ['start'], 'never while following'); + following = false; + events.stepMoveDetection(401 + MOVE_END_WAIT_MS); + assert.deepEqual(seen, ['start', 'end']); +}); + +test('command hooks run before each command, each registration on its own', () => { + const events = createCameraEvents({ pose: () => view(1), report() {} }); + const seen = []; + const hook = (c) => seen.push(c.kind); + const offFirst = events.onCommand(hook); + events.onCommand(hook); + events.command('setView'); + assert.deepEqual(seen, ['setView', 'setView']); + offFirst(); + offFirst(); + events.command('flyTo'); + assert.deepEqual(seen, ['setView', 'setView', 'flyTo'], 'one twin is left'); + // A hook removed by an earlier one in the same delivery does not run. + const order = []; + const removing = createCameraEvents({ pose: () => view(1), report() {} }); + let offSecond = null; + removing.onCommand(() => { + order.push('first'); + offSecond(); + }); + offSecond = removing.onCommand(() => order.push('second')); + removing.command('setView'); + removing.command('setView'); + assert.deepEqual(order, ['first', 'first']); + const reported = []; + const throwing = createCameraEvents({ + pose: () => view(1), + report: (error) => reported.push(error.message), + }); + throwing.onCommand(() => { + throw new Error('boom'); + }); + throwing.onCommand(() => seen.push('after')); + throwing.command('flyTo'); + assert.deepEqual(reported, ['boom']); + assert.equal(seen.at(-1), 'after'); +}); + +test('the geo export has the geodesic point and the horizon test', () => { + const half = geodesicAt(0, 0, Math.PI / 2, 0, 0.5); + assert.ok(Math.abs(half.lon - Math.PI / 4) < 1e-12); + assert.ok(Math.abs(half.lat) < 1e-12); + const horizon = horizonFrom({ x: 7e6, y: 0, z: 0 }); + assert.equal(horizon.isPointVisible({ x: 6378137, y: 0, z: 0 }), true); + assert.equal(horizon.isPointVisible({ x: -6378137, y: 0, z: 0 }), false); +}); diff --git a/src/render/stub/camera.js b/src/render/stub/camera.js index 69f081f4b..d887cba99 100644 --- a/src/render/stub/camera.js +++ b/src/render/stub/camera.js @@ -47,7 +47,6 @@ import { createCameraEvents } from '../camera/events.js'; import { geodesicAt } from '../../geo/geodesic.js'; const DEFAULT_FOV = Math.PI / 3; -const MOVE_END_WAIT_MS = 500; const MINIMUM_ZOOM = 100; const DEFAULT_SPHERE_OFFSET = Object.freeze({ heading: 0, @@ -98,17 +97,23 @@ export function createStubCamera({ const near = 1; const far = 5e8; - const events = createCameraEvents({ pose, report, thresholds }); - const { emit, on, stepChanged } = events; - const commandHooks = []; + const events = createCameraEvents({ + pose, + world: () => ({ + position: positionWC(), + direction: directionWC(), + up: upWC(), + }), + following: () => Boolean(followed), + report, + thresholds, + }); + const { emit, on, stepChanged, command, onCommand } = events; const holds = new Map(); let holdSeq = 0; let flight = null; let followed = null; let followFramed = false; - let lastPose = null; - let moving = false; - let lastMovedAt = 0; let coast = Object.freeze({ drag: 0.4, zoom: 0.2 }); const controls = { @@ -202,17 +207,6 @@ export function createStubCamera({ }; } - function command(kind) { - for (const hook of commandHooks.slice()) { - if (!commandHooks.includes(hook)) continue; - try { - hook({ kind }); - } catch (error) { - report(error); - } - } - } - /** Place the eye at `destination` (world) with `orientation` in its east-north-up frame. */ function placeAt(destination, hpr) { const kept = frame; @@ -727,35 +721,8 @@ export function createStubCamera({ // --- Events ---------------------------------------------------------------- - function sameView(a, b) { - return ( - a && - b && - distance(a.position, b.position) === 0 && - dot(a.direction, b.direction) === dot(a.direction, a.direction) && - dot(a.up, b.up) === dot(a.up, a.up) - ); - } - function stepMoveDetection() { - const current = { - position: positionWC(), - direction: directionWC(), - up: upWC(), - }; - const changed = lastPose && !sameView(lastPose, current); - lastPose = current; - const t = now(); - if (changed) { - lastMovedAt = t; - if (!moving) { - moving = true; - emit('moveStart'); - } - } else if (moving && !followed && t - lastMovedAt >= MOVE_END_WAIT_MS) { - moving = false; - emit('moveEnd'); - } + events.stepMoveDetection(now()); } function matrices() { @@ -844,13 +811,7 @@ export function createStubCamera({ followOffset, controls, on, - onCommand(cb) { - commandHooks.push(cb); - return () => { - const i = commandHooks.indexOf(cb); - if (i >= 0) commandHooks.splice(i, 1); - }; - }, + onCommand, matrices, }; diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 7d02093ae..edfa96b1a 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -1600,6 +1600,13 @@ export function createStubRenderer(options = {}) { canvas.width = viewport.width; canvas.height = viewport.height; }, + /** + * Where a drawn item is drawn now (or `aheadMs` from now), ECEF, or + * null: what the stub's own camera follows for a target's `item`, for + * a camera of someone else's driving the stub (the `camera.followItem` + * conformance check). + */ + drawnPosition: (ref, aheadMs = 0) => drawnPosition(ref, aheadMs), /** What a set holds. */ setRecord: (id) => sets.get(id) ?? null, sets: () => [...sets.keys()], @@ -1624,6 +1631,7 @@ export function createStubRenderer(options = {}) { * @property {(point: object, height: number) => void} cacheHeight * @property {(kind: string, value: boolean) => void} setSettled * @property {(size: {width?: number, height?: number}) => void} setViewport + * @property {(ref: {set: string, id: string|number}, aheadMs?: number) => {x: number, y: number, z: number}|null} drawnPosition * @property {(id: string) => object|null} setRecord * @property {() => string[]} sets * @property {Array<{port: string, member: string, args: unknown[]}>} calls diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index 28e78c2e9..547fbc148 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -130,3 +130,56 @@ test('a draped rectangle across the antimeridian picks on both sides of it, turn assert.ok(!picked(179.5, 0), 'and narrows it'); r.destroy(); }); + +test('the stub says where it draws an item, for a camera that is not its own', () => { + const r = createStubRenderer(); + const t0 = r.frame.time(); + const from = toEcef({ lon: -97.74, lat: 30.27, height: 1000 }); + const to = toEcef({ lon: -97.7, lat: 30.27, height: 1000 }); + const set = r.draw.icons({ id: 'drawn', motionClock: { kind: 'scene' } }); + set.set([ + { + id: 'm', + pos: from, + image: 'data:,', + size: [16, 16], + motion: { kind: 'lerp', from, to, t0, t1: t0 + 60000 }, + }, + ]); + const at = (p) => [p.x, p.y, p.z]; + assert.deepEqual( + at(r.testing.drawnPosition({ set: 'drawn', id: 'm' })), + at(from), + ); + r.frame.setTime(t0 + 30000); + const mid = r.testing.drawnPosition({ set: 'drawn', id: 'm' }); + for (const k of ['x', 'y', 'z']) + assert.ok(Math.abs(mid[k] - (from[k] + to[k]) / 2) < 1e-6, k); + const ahead = r.testing.drawnPosition({ set: 'drawn', id: 'm' }, 30000); + for (const k of ['x', 'y', 'z']) + assert.ok(Math.abs(ahead[k] - to[k]) < 1e-6, k); + assert.equal(r.testing.drawnPosition({ set: 'drawn', id: 'gone' }), null); + assert.equal(r.testing.drawnPosition({ set: 'nothing', id: 'm' }), null); + r.destroy(); +}); + +test('the stub camera ends no move while it follows', () => { + const r = createStubRenderer(); + const seen = []; + r.camera.on('moveStart', () => seen.push('start')); + r.camera.on('moveEnd', () => seen.push('end')); + r.testing.tick(); + const target = toEcef({ lon: -97.74, lat: 30.27, height: 0 }); + r.camera.follow({ + key: 'still', + position: () => target, + frame: 'enu', + viewFrom: { x: 0, y: -500, z: 300 }, + }); + r.testing.advance(2000); + assert.deepEqual(seen, ['start'], 'moveEnd waits for the follow to end'); + r.camera.follow(null); + r.testing.advance(1000); + assert.deepEqual(seen, ['start', 'end']); + r.destroy(); +});