mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Define the renderer contract, with a stub renderer and a conformance suite
The renderer contract is what the application asks of a 3D renderer. It is nine ports (frame, globe, draw, camera, query, input, effects, credits, quality) plus the renderer itself, one strict .d.ts per port in src/render/contract/. PORTS lists every member at run time, and a TypeScript-compiler test fails when the list and the types disagree on one member. An optional member exists only with its capability; a required one answers null or empty without it. Nothing in the application uses the contract yet. The stub renderer (src/render/stub/) implements every port in memory and draws nothing. Its camera is a port of the default camera's maths: views, lookAt, flights with their height arc and easing, rectangle framing on the geodesic midpoint, the view rectangle with its horizon and pole cases, changed thresholds, follows, and flights that finish inside the call. The conformance suite (src/render/conformance/) runs 59 checks against a renderer through the contract alone, in Node or in a browser page. The camera checks compare traces recorded from Cesium's own Camera, headless on a virtual clock (scripts/record-camera-goldens.mjs), to 1 mm, 1e-9 and 1e-3 px. The other checks cover listener rules on every subscription, the frame loop, draw sets, picks, motion clocks, heights, leases, imagery, styles, credits and quality knobs. The stub passes all of them but the model check, which needs a glTF asset. Reference scenes draw one scene per primitive family, a city and a calibration path from orbit to the street, from contract calls only and with no network. /dev/conformance/ draws them on the Cesium scene renderer (src/render/cesium/sceneRenderer.js), records references through a dev-server-only, loopback-only endpoint, and compares captures with pixelmatch's antialias detection plus a solid-pixel count. Measured on Cesium: every MSAA setting passes, and a dropped 4 px point, a dropped 2 px line and a 1 px shift of the view fail. visual.js states the limits. The package exports ./render/contract, ./render/stub and ./render/conformance. Documented in docs/RENDERER-CONTRACT.md, docs/CODE-BOUNDARIES.md and docs/CURRENT-STATE.md.
This commit is contained in:
1 parent
464c29a9ed
commit
8db995acfc
65 files changed
+12759
-9
No files matched your search
@@ -0,0 +1,950 @@
|
||||
/**
|
||||
* @module render/stub/camera
|
||||
* @description The stub renderer's camera: exact poses for every camera
|
||||
* command of the contract, flights on the stub's clock, follows, holds and
|
||||
* events. It keeps the eye in a frame (the world, or a `lookAt` target's
|
||||
* east-north-up frame) the way the default renderer does, so commands made
|
||||
* in a target's frame behave the same.
|
||||
*/
|
||||
import {
|
||||
EPSILON10,
|
||||
IDENTITY,
|
||||
PI_OVER_TWO,
|
||||
TWO_PI,
|
||||
acosClamped,
|
||||
add,
|
||||
clone,
|
||||
cross,
|
||||
distance,
|
||||
dot,
|
||||
eastNorthUp,
|
||||
fromRadians,
|
||||
framePoint,
|
||||
frameVector,
|
||||
geodeticSurfaceNormal,
|
||||
headingOf,
|
||||
headingPitchRollColumns,
|
||||
inverseFramePoint,
|
||||
inverseFrameVector,
|
||||
isIdentity,
|
||||
negativePiToPi,
|
||||
magnitude,
|
||||
negate,
|
||||
normalize,
|
||||
offsetFromHeadingPitchRange,
|
||||
pitchOf,
|
||||
rollOf,
|
||||
rotate,
|
||||
scale,
|
||||
sub,
|
||||
toCartographicRadians,
|
||||
toDegrees,
|
||||
toEcef,
|
||||
toRadians,
|
||||
vec,
|
||||
zeroToTwoPi,
|
||||
} from './math.js';
|
||||
import { geodesicAt } from './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,
|
||||
pitch: -Math.PI / 4,
|
||||
range: 0,
|
||||
});
|
||||
|
||||
const EASINGS = {
|
||||
linear: (t) => t,
|
||||
quadraticInOut: (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2),
|
||||
cubicInOut: (t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2),
|
||||
quinticInOut: (t) => (t < 0.5 ? 16 * t ** 5 : 1 - (-2 * t + 2) ** 5 / 2),
|
||||
cubicOut: (t) => (t - 1) ** 3 + 1,
|
||||
};
|
||||
|
||||
/** Above this height, a descending flight eases out rather than in and out. */
|
||||
const DESCENT_EASE_HEIGHT = 11500;
|
||||
const ONE_DEGREE = Math.PI / 180;
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {() => {width: number, height: number}} options.viewport CSS size.
|
||||
* @param {() => number} options.now The stub's clock, ms.
|
||||
* @param {() => number} options.sceneTime Scene time, epoch ms.
|
||||
* @param {(reason: string) => void} options.requestRender
|
||||
* @param {(error: Error) => void} options.report
|
||||
*/
|
||||
export function createStubCamera({
|
||||
viewport,
|
||||
now,
|
||||
sceneTime,
|
||||
requestRender,
|
||||
report,
|
||||
drawnPosition = () => null,
|
||||
}) {
|
||||
// Local frame values; world values are `frame` applied to them.
|
||||
let frame = IDENTITY;
|
||||
let position = vec(0, 0, 0);
|
||||
let direction = vec(0, 0, -1);
|
||||
let up = vec(0, 1, 0);
|
||||
let right = vec(1, 0, 0);
|
||||
let fovy = null;
|
||||
let fov = DEFAULT_FOV;
|
||||
const near = 1;
|
||||
const far = 5e8;
|
||||
|
||||
const listeners = {
|
||||
changed: [],
|
||||
moveStart: [],
|
||||
moveEnd: [],
|
||||
followChanged: [],
|
||||
flightEnd: [],
|
||||
};
|
||||
const commandHooks = [];
|
||||
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;
|
||||
|
||||
const controls = {
|
||||
get enabled() {
|
||||
return holds.size === 0;
|
||||
},
|
||||
suspend(reason) {
|
||||
const key = ++holdSeq;
|
||||
holds.set(key, reason);
|
||||
return () => holds.delete(key);
|
||||
},
|
||||
enableTilt: true,
|
||||
enableRotate: true,
|
||||
enableZoom: true,
|
||||
minDistance: 1,
|
||||
maxDistance: Infinity,
|
||||
inertiaSpin: 0.9,
|
||||
inertiaTranslate: 0.9,
|
||||
inertiaZoom: 0.8,
|
||||
collision: 'none',
|
||||
zoomFactor: 5,
|
||||
pitchRange: [-Math.PI / 2, 0],
|
||||
zoomInputs: ['wheel', 'pinch', 'rightDrag'],
|
||||
};
|
||||
|
||||
function aspectRatio() {
|
||||
const { width, height } = viewport();
|
||||
return width / height;
|
||||
}
|
||||
|
||||
function verticalFov() {
|
||||
if (fovy !== null) return fovy;
|
||||
const aspect = aspectRatio();
|
||||
return aspect <= 1 ? fov : 2 * Math.atan(Math.tan(fov * 0.5) / aspect);
|
||||
}
|
||||
|
||||
const positionWC = () => framePoint(frame, position);
|
||||
const directionWC = () => normalize(frameVector(frame, direction));
|
||||
const upWC = () => normalize(frameVector(frame, up));
|
||||
const rightWC = () => normalize(frameVector(frame, right));
|
||||
|
||||
/** Move into a new frame, keeping the world pose. */
|
||||
function setFrame(next) {
|
||||
const p = positionWC();
|
||||
const d = directionWC();
|
||||
const u = upWC();
|
||||
frame = next;
|
||||
position = inverseFramePoint(frame, p);
|
||||
direction = inverseFrameVector(frame, d);
|
||||
up = inverseFrameVector(frame, u);
|
||||
right = cross(direction, up);
|
||||
}
|
||||
|
||||
/** Heading, pitch and roll in the east-north-up frame at the eye. */
|
||||
function eyeAngles() {
|
||||
return directionUpToAngles(positionWC(), {
|
||||
direction: directionWC(),
|
||||
up: upWC(),
|
||||
});
|
||||
}
|
||||
|
||||
function pose() {
|
||||
const p = positionWC();
|
||||
const c = toCartographicRadians(p) ?? { lon: 0, lat: 0, height: 0 };
|
||||
const a = eyeAngles();
|
||||
return {
|
||||
lon: toDegrees(c.lon),
|
||||
lat: toDegrees(c.lat),
|
||||
height: c.height,
|
||||
heading: a.heading,
|
||||
pitch: a.pitch,
|
||||
roll: a.roll,
|
||||
position: p,
|
||||
direction: directionWC(),
|
||||
up: upWC(),
|
||||
right: rightWC(),
|
||||
fovy: verticalFov(),
|
||||
aspectRatio: aspectRatio(),
|
||||
near,
|
||||
far,
|
||||
frameIsIdentity: isIdentity(frame),
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
const enu = eastNorthUp(destination);
|
||||
frame = enu;
|
||||
position = vec(0, 0, 0);
|
||||
const columns = headingPitchRollColumns(hpr.heading, hpr.pitch, hpr.roll);
|
||||
direction = columns.direction;
|
||||
up = columns.up;
|
||||
right = cross(direction, up);
|
||||
setFrame(kept);
|
||||
}
|
||||
|
||||
/** Orientation given as direction and up, as angles at `destination`. */
|
||||
function directionUpToAngles(destination, orientation) {
|
||||
const enu = eastNorthUp(destination);
|
||||
const d = inverseFrameVector(enu, orientation.direction);
|
||||
const u = inverseFrameVector(enu, orientation.up);
|
||||
const r = cross(d, u);
|
||||
return {
|
||||
heading: headingOf(d, u),
|
||||
pitch: pitchOf(d),
|
||||
roll: rollOf(d, u, r),
|
||||
};
|
||||
}
|
||||
|
||||
function resolveOrientation(destination, orientation = {}) {
|
||||
if (orientation && 'direction' in orientation)
|
||||
return directionUpToAngles(destination, orientation);
|
||||
return {
|
||||
heading: orientation?.heading ?? 0,
|
||||
pitch: orientation?.pitch ?? -PI_OVER_TWO,
|
||||
roll: orientation?.roll ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The eye over a rectangle that keeps all of it in view, as the default
|
||||
* renderer frames one: over the geodesic midpoint of its central meridian,
|
||||
* far enough for its corners, edge centres and (across the equator) its
|
||||
* equator points.
|
||||
*/
|
||||
function rectangleDestination(rect) {
|
||||
const { north, south, west } = {
|
||||
north: toRadians(rect.north),
|
||||
south: toRadians(rect.south),
|
||||
west: toRadians(rect.west),
|
||||
};
|
||||
let east = toRadians(rect.east);
|
||||
if (west > east) east += TWO_PI;
|
||||
const lon = (west + east) * 0.5;
|
||||
const lat =
|
||||
south < -PI_OVER_TWO + ONE_DEGREE && north > PI_OVER_TWO - ONE_DEGREE
|
||||
? 0
|
||||
: geodesicAt(lon, north, lon, south, 0.5).lat;
|
||||
const center = fromRadians(lon, lat, 0);
|
||||
const dir = negate(geodeticSurfaceNormal(center));
|
||||
const r = normalize(cross(dir, vec(0, 0, 1)));
|
||||
const u = cross(r, dir);
|
||||
const tanPhi = Math.tan(verticalFov() * 0.5);
|
||||
const tanTheta = aspectRatio() * tanPhi;
|
||||
const points = [
|
||||
[west, north],
|
||||
[east, south],
|
||||
[east, north],
|
||||
[west, south],
|
||||
[lon, north],
|
||||
[lon, south],
|
||||
];
|
||||
if (south < 0 && north > 0) points.push([west, 0], [east, 0]);
|
||||
let d = -Infinity;
|
||||
for (const [pointLon, pointLat] of points) {
|
||||
const corner = sub(fromRadians(pointLon, pointLat, 0), center);
|
||||
d = Math.max(
|
||||
d,
|
||||
Math.abs(dot(u, corner)) / tanPhi - dot(dir, corner),
|
||||
Math.abs(dot(r, corner)) / tanTheta - dot(dir, corner),
|
||||
);
|
||||
}
|
||||
return add(center, scale(dir, -d));
|
||||
}
|
||||
|
||||
function resolveDestination(destination, orientation) {
|
||||
const target =
|
||||
destination && 'rect' in destination
|
||||
? rectangleDestination(destination.rect)
|
||||
: destination
|
||||
? toEcef(destination)
|
||||
: positionWC();
|
||||
return {
|
||||
destination: target,
|
||||
angles: resolveOrientation(target, orientation),
|
||||
};
|
||||
}
|
||||
|
||||
function setView({ destination, orientation } = {}) {
|
||||
command('setView');
|
||||
const resolved = resolveDestination(destination, orientation);
|
||||
placeAt(resolved.destination, resolved.angles);
|
||||
requestRender('camera');
|
||||
}
|
||||
|
||||
function lookAtFrame(targetFrame, offset) {
|
||||
setFrame(targetFrame);
|
||||
position = offset;
|
||||
direction = normalize(negate(position));
|
||||
right = cross(direction, vec(0, 0, 1));
|
||||
if (dot(right, right) < EPSILON10) right = vec(1, 0, 0);
|
||||
right = normalize(right);
|
||||
up = normalize(cross(right, direction));
|
||||
}
|
||||
|
||||
function lookAt(target, offset) {
|
||||
command('lookAt');
|
||||
lookAtFrame(
|
||||
eastNorthUp(target),
|
||||
offsetFromHeadingPitchRange(offset.heading, offset.pitch, offset.range),
|
||||
);
|
||||
requestRender('camera');
|
||||
}
|
||||
|
||||
function release() {
|
||||
command('release');
|
||||
setFrame(IDENTITY);
|
||||
requestRender('camera');
|
||||
}
|
||||
|
||||
function finishFlight(outcome) {
|
||||
const f = flight;
|
||||
if (!f) return;
|
||||
flight = null;
|
||||
f.releaseHold();
|
||||
const cb = outcome === 'complete' ? f.onComplete : f.onCancel;
|
||||
try {
|
||||
cb?.();
|
||||
} catch (error) {
|
||||
report(error);
|
||||
}
|
||||
f.resolve(outcome);
|
||||
emit('flightEnd');
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the eye already stands at `destination` with `target` angles;
|
||||
* like the reference camera, by its position in its current frame.
|
||||
*/
|
||||
function alreadyThere(destination, target) {
|
||||
const p = position;
|
||||
const a = eyeAngles();
|
||||
const close = (x, y) =>
|
||||
Math.abs(x - y) <= EPSILON10 * Math.max(1, Math.abs(x), Math.abs(y));
|
||||
const sameAngle = (x, y) => close(negativePiToPi(x), negativePiToPi(y));
|
||||
return (
|
||||
close(p.x, destination.x) &&
|
||||
close(p.y, destination.y) &&
|
||||
close(p.z, destination.z) &&
|
||||
sameAngle(a.heading, target.heading) &&
|
||||
sameAngle(a.pitch, target.pitch) &&
|
||||
sameAngle(a.roll, target.roll)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A flight that ends inside the call, as the reference camera's does: a
|
||||
* duration of 0 or less lands at once, and one already at its destination
|
||||
* completes without moving.
|
||||
*/
|
||||
function instantFlight(destination, angles, durationS, options) {
|
||||
if (durationS !== undefined && durationS <= 0) {
|
||||
placeAt(destination, angles);
|
||||
requestRender('camera');
|
||||
} else if (!alreadyThere(destination, angles)) return null;
|
||||
let resolve;
|
||||
const done = new Promise((r) => (resolve = r));
|
||||
const handle = { done, cancel: () => {} };
|
||||
flight = {
|
||||
handle,
|
||||
releaseHold: () => {},
|
||||
onComplete: options?.onComplete,
|
||||
resolve,
|
||||
};
|
||||
finishFlight('complete');
|
||||
return handle;
|
||||
}
|
||||
|
||||
function startFlight(destination, angles, durationS, options) {
|
||||
if (flight) finishFlight('cancelled');
|
||||
if (options?.endFrame === 'world') setFrame(IDENTITY);
|
||||
const instant = instantFlight(destination, angles, durationS, options);
|
||||
if (instant) return instant;
|
||||
const startPos = positionWC();
|
||||
const duration =
|
||||
durationS ??
|
||||
Math.min(3, Math.ceil(distance(position, destination) / 1e6) + 2);
|
||||
const start = { pos: startPos, angles: eyeAngles() };
|
||||
const path = flightPath(destination, angles, options ?? {});
|
||||
let resolve;
|
||||
const done = new Promise((r) => (resolve = r));
|
||||
const handle = {
|
||||
done,
|
||||
cancel: () => {
|
||||
if (flight?.handle === handle) finishFlight('cancelled');
|
||||
},
|
||||
};
|
||||
flight = {
|
||||
handle,
|
||||
start,
|
||||
destination,
|
||||
angles,
|
||||
durationMs: duration * 1000,
|
||||
startedAt: null,
|
||||
path,
|
||||
easing:
|
||||
EASINGS[options?.easing] ??
|
||||
(path.startHeight > path.endHeight &&
|
||||
path.startHeight > DESCENT_EASE_HEIGHT
|
||||
? EASINGS.cubicOut
|
||||
: EASINGS.quinticInOut),
|
||||
onComplete: options?.onComplete,
|
||||
onCancel: options?.onCancel,
|
||||
releaseHold: controls.suspend('flight'),
|
||||
resolve,
|
||||
};
|
||||
requestRender('flight');
|
||||
return handle;
|
||||
}
|
||||
|
||||
function flyTo(destination, options = {}) {
|
||||
command('flyTo');
|
||||
const resolved = resolveDestination(destination, options.orientation);
|
||||
return startFlight(
|
||||
resolved.destination,
|
||||
resolved.angles,
|
||||
options.durationS,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
function flyToBounds(sphere, options = {}) {
|
||||
command('flyToBounds');
|
||||
setFrame(IDENTITY);
|
||||
const offset = { ...DEFAULT_SPHERE_OFFSET, ...(options.offset ?? {}) };
|
||||
if (!offset.range) {
|
||||
const tanPhi = Math.tan(verticalFov() * 0.5);
|
||||
const tanTheta = aspectRatio() * tanPhi;
|
||||
offset.range =
|
||||
sphere.radius === 0
|
||||
? MINIMUM_ZOOM
|
||||
: Math.max(sphere.radius / tanTheta, sphere.radius / tanPhi);
|
||||
offset.range = Math.min(
|
||||
controls.maxDistance,
|
||||
Math.max(controls.minDistance, offset.range),
|
||||
);
|
||||
}
|
||||
const enu = eastNorthUp(sphere.center);
|
||||
const eye = framePoint(
|
||||
enu,
|
||||
offsetFromHeadingPitchRange(offset.heading, offset.pitch, offset.range),
|
||||
);
|
||||
const dir = normalize(sub(sphere.center, eye));
|
||||
let u = enu.z;
|
||||
if (1 - Math.abs(dot(dir, u)) < 1e-6)
|
||||
u = rotate(enu.y, dir, offset.heading);
|
||||
const r = cross(dir, u);
|
||||
u = normalize(cross(r, dir));
|
||||
return startFlight(
|
||||
eye,
|
||||
directionUpToAngles(eye, { direction: dir, up: u }),
|
||||
options.durationS,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/** One frame of the flight in progress. */
|
||||
function stepFlight() {
|
||||
if (!flight) return;
|
||||
const t = now();
|
||||
if (flight.startedAt === null) {
|
||||
flight.startedAt = t;
|
||||
if (flight.durationMs > 0) return;
|
||||
}
|
||||
const elapsed = t - flight.startedAt;
|
||||
if (elapsed >= flight.durationMs) {
|
||||
placeAt(flight.destination, flight.angles);
|
||||
finishFlight('complete');
|
||||
return;
|
||||
}
|
||||
const s = flight.easing(elapsed / flight.durationMs);
|
||||
const { path } = flight;
|
||||
placeAt(
|
||||
fromRadians(
|
||||
path.startLon + (path.endLon - path.startLon) * s,
|
||||
path.startLat + (path.endLat - path.startLat) * s,
|
||||
path.height(s),
|
||||
),
|
||||
{
|
||||
heading:
|
||||
path.startHeading + (flight.angles.heading - path.startHeading) * s,
|
||||
pitch: path.pitch(s),
|
||||
roll: path.startRoll + (flight.angles.roll - path.startRoll) * s,
|
||||
},
|
||||
);
|
||||
requestRender('flight');
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference flight path, fixed when the flight starts: longitude and
|
||||
* latitude linear in eased time the short way round; height on an arc
|
||||
* over the higher end when the two ends are far apart on screen (or
|
||||
* below `maxHeight`); pitch linear, or straight down mid-flight when the
|
||||
* arc tops `pitchAdjustHeight`.
|
||||
*/
|
||||
function flightPath(destination, angles, options) {
|
||||
const from = toCartographicRadians(positionWC());
|
||||
const to = toCartographicRadians(destination);
|
||||
let startLon = zeroToTwoPi(from.lon);
|
||||
let endLon = zeroToTwoPi(to.lon);
|
||||
if (startLon - endLon < -Math.PI) startLon += TWO_PI;
|
||||
else if (startLon - endLon > Math.PI) endLon += TWO_PI;
|
||||
const now = eyeAngles();
|
||||
const height = heightCurve(
|
||||
destination,
|
||||
from.height,
|
||||
to.height,
|
||||
options.maxHeight,
|
||||
);
|
||||
return {
|
||||
startLon,
|
||||
endLon,
|
||||
startLat: from.lat,
|
||||
endLat: to.lat,
|
||||
startHeight: from.height,
|
||||
endHeight: to.height,
|
||||
height,
|
||||
pitch: pitchCurve(
|
||||
now.pitch,
|
||||
angles.pitch,
|
||||
height,
|
||||
options.pitchAdjustHeight,
|
||||
),
|
||||
startHeading: forLerp(now.heading, angles.heading),
|
||||
startRoll: forLerp(now.roll, angles.roll),
|
||||
};
|
||||
}
|
||||
|
||||
function heightCurve(destination, startHeight, endHeight, maxHeight) {
|
||||
let altitude = maxHeight;
|
||||
if (altitude === undefined) {
|
||||
const diff = sub(position, destination);
|
||||
const vertical = Math.abs(dot(diff, up));
|
||||
const horizontal = Math.abs(dot(diff, right));
|
||||
const tanHalf = Math.tan(0.5 * verticalFov());
|
||||
altitude = Math.min(
|
||||
Math.max(vertical / (aspectRatio() * tanHalf), horizontal / tanHalf) *
|
||||
0.2,
|
||||
1e9,
|
||||
);
|
||||
}
|
||||
if (Math.max(startHeight, endHeight) < altitude) {
|
||||
const power = 8;
|
||||
const factor = 1e6;
|
||||
const s = -(((altitude - startHeight) * factor) ** (1 / power));
|
||||
const e = ((altitude - endHeight) * factor) ** (1 / power);
|
||||
return (t) => -((t * (e - s) + s) ** power) / factor + altitude;
|
||||
}
|
||||
return (t) => startHeight + (endHeight - startHeight) * t;
|
||||
}
|
||||
|
||||
function pitchCurve(startPitch, endPitch, height, adjustHeight) {
|
||||
if (adjustHeight !== undefined && height(0.5) > adjustHeight) {
|
||||
const h0 = height(0);
|
||||
const h1 = height(1);
|
||||
const mid = height(0.5);
|
||||
return (t) => {
|
||||
const h = height(t);
|
||||
if (t <= 0.5)
|
||||
return (
|
||||
startPitch + (-Math.PI / 2 - startPitch) * ((h - h0) / (mid - h0))
|
||||
);
|
||||
return (
|
||||
-Math.PI / 2 + (endPitch + Math.PI / 2) * (1 - (h - h1) / (mid - h1))
|
||||
);
|
||||
};
|
||||
}
|
||||
return (t) => startPitch + (endPitch - startPitch) * t;
|
||||
}
|
||||
|
||||
/** The start angle moved by a turn so a straight blend takes the short way. */
|
||||
function forLerp(start, end) {
|
||||
let a = Math.abs(start - TWO_PI) <= 1e-11 ? 0 : start;
|
||||
if (end > a + Math.PI) a += TWO_PI;
|
||||
else if (end < a - Math.PI) a -= TWO_PI;
|
||||
return a;
|
||||
}
|
||||
|
||||
function cancelFlight() {
|
||||
command('cancelFlight');
|
||||
finishFlight('cancelled');
|
||||
}
|
||||
|
||||
function move(dir, metres) {
|
||||
const axis = {
|
||||
forward: direction,
|
||||
back: negate(direction),
|
||||
right,
|
||||
left: negate(right),
|
||||
up,
|
||||
down: negate(up),
|
||||
}[dir];
|
||||
position = add(position, scale(axis, metres));
|
||||
requestRender('camera');
|
||||
}
|
||||
|
||||
function look(dir, radians) {
|
||||
const [axis, sign] = {
|
||||
left: [up, -1],
|
||||
right: [up, 1],
|
||||
up: [right, -1],
|
||||
down: [right, 1],
|
||||
}[dir];
|
||||
const a = clone(axis);
|
||||
const angle = -(sign * radians);
|
||||
direction = rotate(direction, a, angle);
|
||||
up = rotate(up, a, angle);
|
||||
right = rotate(right, a, angle);
|
||||
requestRender('camera');
|
||||
}
|
||||
|
||||
function rotateAround(axis, radians) {
|
||||
const a = normalize(axis);
|
||||
position = rotate(position, a, -radians);
|
||||
direction = rotate(direction, a, -radians);
|
||||
up = rotate(up, a, -radians);
|
||||
right = cross(direction, up);
|
||||
up = cross(right, direction);
|
||||
requestRender('camera');
|
||||
}
|
||||
|
||||
function zoom(metres) {
|
||||
move('forward', metres);
|
||||
}
|
||||
|
||||
// --- Follow ----------------------------------------------------------------
|
||||
|
||||
/** Where the target is drawn, for a drawn item; otherwise its own answer. */
|
||||
const targetAt = (target, t, aheadMs = 0) =>
|
||||
(target.item && drawnPosition(target.item, aheadMs)) ||
|
||||
target.position(t + aheadMs);
|
||||
|
||||
function followFrame(target, t) {
|
||||
const at = targetAt(target, t);
|
||||
if (!at) return null;
|
||||
if (target.frame === 'autodetect') {
|
||||
const ahead = targetAt(target, t, 1000);
|
||||
const enu = eastNorthUp(at);
|
||||
if (ahead && distance(ahead, at) > 0.01) {
|
||||
const along = normalize(sub(ahead, at));
|
||||
const upAxis = enu.z;
|
||||
const forward = normalize(
|
||||
sub(along, scale(upAxis, dot(along, upAxis))),
|
||||
);
|
||||
const side = cross(forward, upAxis);
|
||||
return { x: side, y: forward, z: upAxis, origin: at };
|
||||
}
|
||||
return enu;
|
||||
}
|
||||
return eastNorthUp(at);
|
||||
}
|
||||
|
||||
function follow(target) {
|
||||
command('follow');
|
||||
followed = target;
|
||||
followFramed = false;
|
||||
if (!target) setFrame(IDENTITY);
|
||||
emit('followChanged');
|
||||
requestRender('follow');
|
||||
}
|
||||
|
||||
function stepFollow() {
|
||||
if (!followed) return;
|
||||
const t = sceneTime();
|
||||
const targetFrame = followFrame(followed, t);
|
||||
if (!targetFrame) return;
|
||||
if (!followFramed) {
|
||||
const viewFrom =
|
||||
typeof followed.viewFrom === 'function'
|
||||
? followed.viewFrom(t)
|
||||
: followed.viewFrom;
|
||||
let offset = clone(viewFrom);
|
||||
const range = magnitude(offset);
|
||||
const minRange = Math.max(
|
||||
followed.minRange ?? 0,
|
||||
followed.boundingRadius ?? 0,
|
||||
);
|
||||
if (range < minRange && range > 0)
|
||||
offset = scale(offset, minRange / range);
|
||||
lookAtFrame(targetFrame, offset);
|
||||
followFramed = true;
|
||||
return;
|
||||
}
|
||||
// Keep the eye's local offset in the moving frame.
|
||||
const keptPosition = position;
|
||||
const keptDirection = direction;
|
||||
const keptUp = up;
|
||||
frame = targetFrame;
|
||||
position = keptPosition;
|
||||
direction = keptDirection;
|
||||
up = keptUp;
|
||||
right = cross(direction, up);
|
||||
}
|
||||
|
||||
// --- Events ----------------------------------------------------------------
|
||||
|
||||
function emit(event) {
|
||||
for (const entry of listeners[event].slice()) {
|
||||
if (!entry.live) continue;
|
||||
try {
|
||||
entry.cb();
|
||||
} catch (error) {
|
||||
report(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function on(event, cb, options = {}) {
|
||||
const entry = {
|
||||
cb,
|
||||
live: true,
|
||||
threshold: options.threshold ?? 0.5,
|
||||
ref: null,
|
||||
};
|
||||
listeners[event].push(entry);
|
||||
return () => {
|
||||
entry.live = false;
|
||||
const list = listeners[event];
|
||||
const i = list.indexOf(entry);
|
||||
if (i >= 0) list.splice(i, 1);
|
||||
};
|
||||
}
|
||||
|
||||
/** How far the view moved from a listener's reference, as a fraction. */
|
||||
const angleDelta = (a, b) => {
|
||||
const d = Math.abs(a - b) % TWO_PI;
|
||||
return (d > Math.PI ? TWO_PI - d : d) / Math.PI;
|
||||
};
|
||||
|
||||
/**
|
||||
* Per listener, the reference camera's formula: heading and roll each
|
||||
* against their own last reported value, then direction and position
|
||||
* against the last reported view. Each can report in the same frame.
|
||||
*/
|
||||
function stepChanged() {
|
||||
const list = listeners.changed;
|
||||
if (!list.length) return;
|
||||
const current = pose();
|
||||
for (const entry of list.slice()) {
|
||||
if (!entry.live) continue;
|
||||
const t = entry.threshold;
|
||||
entry.heading ??= current.heading;
|
||||
entry.roll ??= current.roll;
|
||||
const headingF = angleDelta(entry.heading, current.heading);
|
||||
const rollF = angleDelta(entry.roll, current.roll);
|
||||
if (headingF > t) entry.heading = current.heading;
|
||||
if (rollF > t) entry.roll = current.roll;
|
||||
if (headingF > t || rollF > t) deliver(entry);
|
||||
if (!entry.view) {
|
||||
entry.view = {
|
||||
position: current.position,
|
||||
direction: current.direction,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
const dirF =
|
||||
acosClamped(dot(current.direction, entry.view.direction)) /
|
||||
(current.fovy * 0.5);
|
||||
const heightF =
|
||||
distance(current.position, entry.view.position) / current.height;
|
||||
if (dirF > t || heightF > t) {
|
||||
entry.view = {
|
||||
position: current.position,
|
||||
direction: current.direction,
|
||||
};
|
||||
deliver(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function deliver(entry) {
|
||||
if (!entry.live) return;
|
||||
try {
|
||||
entry.cb();
|
||||
} catch (error) {
|
||||
report(error);
|
||||
}
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
function matrices() {
|
||||
const p = positionWC();
|
||||
const d = directionWC();
|
||||
const u = upWC();
|
||||
const r = rightWC();
|
||||
// Column-major view matrix: rows are right, up and -direction.
|
||||
const view = new Float64Array([
|
||||
r.x,
|
||||
u.x,
|
||||
-d.x,
|
||||
0,
|
||||
r.y,
|
||||
u.y,
|
||||
-d.y,
|
||||
0,
|
||||
r.z,
|
||||
u.z,
|
||||
-d.z,
|
||||
0,
|
||||
-dot(r, p),
|
||||
-dot(u, p),
|
||||
dot(d, p),
|
||||
1,
|
||||
]);
|
||||
const top = near * Math.tan(verticalFov() * 0.5);
|
||||
const rightEdge = aspectRatio() * top;
|
||||
const projection = new Float64Array([
|
||||
near / rightEdge,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
near / top,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
-(far + near) / (far - near),
|
||||
-1,
|
||||
0,
|
||||
0,
|
||||
(-2 * far * near) / (far - near),
|
||||
0,
|
||||
]);
|
||||
return { view, projection };
|
||||
}
|
||||
|
||||
const followOffset = {
|
||||
get: () => (followed ? clone(position) : null),
|
||||
set: (offset) => {
|
||||
if (!followed) return;
|
||||
lookAtFrame(frame, clone(offset));
|
||||
requestRender('follow');
|
||||
},
|
||||
};
|
||||
|
||||
const port = {
|
||||
pose,
|
||||
setView,
|
||||
setFov({ vertical }) {
|
||||
fovy = vertical;
|
||||
requestRender('camera');
|
||||
},
|
||||
viewRectangle: () => null,
|
||||
flyTo,
|
||||
flyToBounds,
|
||||
cancelFlight,
|
||||
get flying() {
|
||||
return flight !== null;
|
||||
},
|
||||
lookAt,
|
||||
release,
|
||||
move,
|
||||
look,
|
||||
rotateAround,
|
||||
zoom,
|
||||
follow,
|
||||
get followed() {
|
||||
return followed;
|
||||
},
|
||||
get followFramed() {
|
||||
return followFramed;
|
||||
},
|
||||
followOffset,
|
||||
controls,
|
||||
on,
|
||||
onCommand(cb) {
|
||||
commandHooks.push(cb);
|
||||
return () => {
|
||||
const i = commandHooks.indexOf(cb);
|
||||
if (i >= 0) commandHooks.splice(i, 1);
|
||||
};
|
||||
},
|
||||
matrices,
|
||||
};
|
||||
|
||||
return {
|
||||
port,
|
||||
/** Ends a flight in progress as cancelled, without announcing a command. */
|
||||
endFlight: () => finishFlight('cancelled'),
|
||||
/** Advance camera steps of one frame, in the contract's order. */
|
||||
steps: { stepFlight, stepChanged, stepFollow, stepMoveDetection },
|
||||
eye: () => ({
|
||||
position: positionWC(),
|
||||
direction: directionWC(),
|
||||
up: upWC(),
|
||||
right: rightWC(),
|
||||
fovy: verticalFov(),
|
||||
aspectRatio: aspectRatio(),
|
||||
near,
|
||||
}),
|
||||
holds: () => [...holds.values()],
|
||||
setViewRectangle(fn) {
|
||||
port.viewRectangle = fn;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* @module render/stub/geodesic
|
||||
* @description The point a fraction of the way along the WGS84 geodesic
|
||||
* between two places: Vincenty's inverse formula, then the series the
|
||||
* default renderer interpolates with, term for term, so a rectangle's
|
||||
* centre matches its to floating-point noise.
|
||||
*/
|
||||
import { TWO_PI, WGS84 } from './math.js';
|
||||
|
||||
const EPSILON12 = 1e-12;
|
||||
const A = WGS84.radii.x;
|
||||
const B = WGS84.radii.z;
|
||||
const F = (A - B) / A;
|
||||
|
||||
function deltaLambda(sineAlpha, cos2Alpha, sigma, sinSigma, cosSigma, cos2Sm) {
|
||||
const C = (F * cos2Alpha * (4 + F * (4 - 3 * cos2Alpha))) / 16;
|
||||
return (
|
||||
(1 - C) *
|
||||
F *
|
||||
sineAlpha *
|
||||
(sigma + C * sinSigma * (cos2Sm + C * cosSigma * (2 * cos2Sm * cos2Sm - 1)))
|
||||
);
|
||||
}
|
||||
|
||||
/** Distance, start heading and u² of the geodesic from (lon1, lat1) to (lon2, lat2), radians. */
|
||||
function inverse(lon1, lat1, lon2, lat2) {
|
||||
const l = lon2 - lon1;
|
||||
const u1 = Math.atan((1 - F) * Math.tan(lat1));
|
||||
const u2 = Math.atan((1 - F) * Math.tan(lat2));
|
||||
const cosU1 = Math.cos(u1);
|
||||
const sinU1 = Math.sin(u1);
|
||||
const cosU2 = Math.cos(u2);
|
||||
const sinU2 = Math.sin(u2);
|
||||
const cc = cosU1 * cosU2;
|
||||
const cs = cosU1 * sinU2;
|
||||
const ss = sinU1 * sinU2;
|
||||
const sc = sinU1 * cosU2;
|
||||
let lambda = l;
|
||||
let lambdaDot = TWO_PI;
|
||||
let cosLambda;
|
||||
let sinLambda;
|
||||
let sigma;
|
||||
let cosSigma;
|
||||
let sinSigma;
|
||||
let cos2Alpha;
|
||||
let cos2Sm;
|
||||
do {
|
||||
cosLambda = Math.cos(lambda);
|
||||
sinLambda = Math.sin(lambda);
|
||||
const temp = cs - sc * cosLambda;
|
||||
sinSigma = Math.sqrt(cosU2 * cosU2 * sinLambda * sinLambda + temp * temp);
|
||||
cosSigma = ss + cc * cosLambda;
|
||||
sigma = Math.atan2(sinSigma, cosSigma);
|
||||
let sineAlpha;
|
||||
if (sinSigma === 0) {
|
||||
sineAlpha = 0;
|
||||
cos2Alpha = 1;
|
||||
} else {
|
||||
sineAlpha = (cc * sinLambda) / sinSigma;
|
||||
cos2Alpha = 1 - sineAlpha * sineAlpha;
|
||||
}
|
||||
lambdaDot = lambda;
|
||||
cos2Sm = cosSigma - (2 * ss) / cos2Alpha;
|
||||
if (!isFinite(cos2Sm)) cos2Sm = 0;
|
||||
lambda =
|
||||
l + deltaLambda(sineAlpha, cos2Alpha, sigma, sinSigma, cosSigma, cos2Sm);
|
||||
} while (Math.abs(lambda - lambdaDot) > EPSILON12);
|
||||
const uSquared = (cos2Alpha * (A * A - B * B)) / (B * B);
|
||||
const bigA =
|
||||
1 +
|
||||
(uSquared * (4096 + uSquared * (uSquared * (320 - 175 * uSquared) - 768))) /
|
||||
16384;
|
||||
const bigB =
|
||||
(uSquared * (256 + uSquared * (uSquared * (74 - 47 * uSquared) - 128))) /
|
||||
1024;
|
||||
const cos2Sm2 = cos2Sm * cos2Sm;
|
||||
const deltaSigma =
|
||||
bigB *
|
||||
sinSigma *
|
||||
(cos2Sm +
|
||||
(bigB *
|
||||
(cosSigma * (2 * cos2Sm2 - 1) -
|
||||
(bigB * cos2Sm * (4 * sinSigma * sinSigma - 3) * (4 * cos2Sm2 - 3)) /
|
||||
6)) /
|
||||
4);
|
||||
return {
|
||||
distance: B * bigA * (sigma - deltaSigma),
|
||||
startHeading: Math.atan2(cosU2 * sinLambda, cs - sc * cosLambda),
|
||||
uSquared,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The longitude and latitude (radians) `fraction` of the way along the
|
||||
* geodesic from (lon1, lat1) to (lon2, lat2).
|
||||
*/
|
||||
export function geodesicAt(lon1, lat1, lon2, lat2, fraction) {
|
||||
const { distance, startHeading, uSquared } = inverse(lon1, lat1, lon2, lat2);
|
||||
const cosH = Math.cos(startHeading);
|
||||
const sinH = Math.sin(startHeading);
|
||||
const tanU = (1 - F) * Math.tan(lat1);
|
||||
const cosU = 1 / Math.sqrt(1 + tanU * tanU);
|
||||
const sinU = cosU * tanU;
|
||||
const sigma1 = Math.atan2(tanU, cosH);
|
||||
const sineAlpha = cosU * sinH;
|
||||
const cos2Alpha = 1 - sineAlpha * sineAlpha;
|
||||
const cosAlpha = Math.sqrt(cos2Alpha);
|
||||
const u2 = uSquared / 4;
|
||||
const u4 = u2 * u2;
|
||||
const u6 = u4 * u2;
|
||||
const u8 = u4 * u4;
|
||||
const a0 = 1 + u2 - (3 * u4) / 4 + (5 * u6) / 4 - (175 * u8) / 64;
|
||||
const a1 = 1 - u2 + (15 * u4) / 8 - (35 * u6) / 8;
|
||||
const a2 = 1 - 3 * u2 + (35 * u4) / 4;
|
||||
const a3 = 1 - 5 * u2;
|
||||
const distanceRatio =
|
||||
a0 * sigma1 -
|
||||
(a1 * Math.sin(2 * sigma1) * u2) / 2 -
|
||||
(a2 * Math.sin(4 * sigma1) * u4) / 16 -
|
||||
(a3 * Math.sin(6 * sigma1) * u6) / 48 -
|
||||
(Math.sin(8 * sigma1) * 5 * u8) / 512;
|
||||
|
||||
const s = distanceRatio + (distance * fraction) / B;
|
||||
const cos2S = Math.cos(2 * s);
|
||||
const cos4S = Math.cos(4 * s);
|
||||
const cos6S = Math.cos(6 * s);
|
||||
const sin2S = Math.sin(2 * s);
|
||||
const sin4S = Math.sin(4 * s);
|
||||
const sin6S = Math.sin(6 * s);
|
||||
const sin8S = Math.sin(8 * s);
|
||||
const s2 = s * s;
|
||||
const s3 = s * s2;
|
||||
let sigma =
|
||||
(2 * s3 * u8 * cos2S) / 3 +
|
||||
s *
|
||||
(1 -
|
||||
u2 +
|
||||
(7 * u4) / 4 -
|
||||
(15 * u6) / 4 +
|
||||
(579 * u8) / 64 -
|
||||
(u4 - (15 * u6) / 4 + (187 * u8) / 16) * cos2S -
|
||||
((5 * u6) / 4 - (115 * u8) / 16) * cos4S -
|
||||
(29 * u8 * cos6S) / 16) +
|
||||
(u2 / 2 - u4 + (71 * u6) / 32 - (85 * u8) / 16) * sin2S +
|
||||
((5 * u4) / 16 - (5 * u6) / 4 + (383 * u8) / 96) * sin4S -
|
||||
s2 * ((u6 - (11 * u8) / 2) * sin2S + (5 * u8 * sin4S) / 2) +
|
||||
((29 * u6) / 96 - (29 * u8) / 16) * sin6S +
|
||||
(539 * u8 * sin8S) / 1536;
|
||||
|
||||
const theta = Math.asin(Math.sin(sigma) * cosAlpha);
|
||||
const lat = Math.atan((A / B) * Math.tan(theta));
|
||||
sigma -= sigma1;
|
||||
const cos2Sm = Math.cos(2 * sigma1 + sigma);
|
||||
const sinSigma = Math.sin(sigma);
|
||||
const cosSigma = Math.cos(sigma);
|
||||
const lambda = Math.atan2(
|
||||
sinSigma * sinH,
|
||||
cosU * cosSigma - sinU * sinSigma * cosH,
|
||||
);
|
||||
const l =
|
||||
lambda -
|
||||
deltaLambda(sineAlpha, cos2Alpha, sigma, sinSigma, cosSigma, cos2Sm);
|
||||
return { lon: lon1 + l, lat };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* @module render/stub/harness
|
||||
* @description The stub as the conformance suite's renderer under test, for
|
||||
* the Node test and the browser page alike.
|
||||
*/
|
||||
import { DEFAULT_TOLERANCE } from '../conformance/index.js';
|
||||
import { createStubRenderer } from './index.js';
|
||||
import { toEcef } from './math.js';
|
||||
|
||||
/** @returns {import('../conformance/index.js').ConformanceHarness} */
|
||||
export function createStubHarness(name = 'stub') {
|
||||
return {
|
||||
name,
|
||||
create: async ({ viewport, capabilities }) =>
|
||||
createStubRenderer({ viewport, capabilities }),
|
||||
frame: (r) => {
|
||||
r.testing.tick();
|
||||
},
|
||||
now: (r) => r.testing.now(),
|
||||
toEcef,
|
||||
tolerance: DEFAULT_TOLERANCE,
|
||||
flightPaths: 'trace',
|
||||
pointer: (r, type, x, y, extra) => r.testing.pointer(type, x, y, extra),
|
||||
scriptHeights: (r, fn) => r.testing.setHeights(fn),
|
||||
wallTime: (r) => r.testing.wallTime(),
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,310 @@
|
||||
/**
|
||||
* @module render/stub/math
|
||||
* @description The geodesy and vector maths the stub renderer poses its
|
||||
* camera with: WGS84, east-north-up frames, rigid transforms and the camera
|
||||
* angle conventions of the contract (heading clockwise from north, pitch
|
||||
* negative looking down). Plain objects and numbers, no engine.
|
||||
*
|
||||
* The formulas follow the default renderer's, step for step, so the stub's
|
||||
* poses match its reference traces to floating-point noise.
|
||||
*/
|
||||
|
||||
export const WGS84 = Object.freeze({
|
||||
radii: Object.freeze({ x: 6378137.0, y: 6378137.0, z: 6356752.3142451793 }),
|
||||
radiiSquared: Object.freeze({
|
||||
x: 6378137.0 * 6378137.0,
|
||||
y: 6378137.0 * 6378137.0,
|
||||
z: 6356752.3142451793 * 6356752.3142451793,
|
||||
}),
|
||||
oneOverRadii: Object.freeze({
|
||||
x: 1 / 6378137.0,
|
||||
y: 1 / 6378137.0,
|
||||
z: 1 / 6356752.3142451793,
|
||||
}),
|
||||
oneOverRadiiSquared: Object.freeze({
|
||||
x: 1 / (6378137.0 * 6378137.0),
|
||||
y: 1 / (6378137.0 * 6378137.0),
|
||||
z: 1 / (6356752.3142451793 * 6356752.3142451793),
|
||||
}),
|
||||
});
|
||||
|
||||
export const TWO_PI = Math.PI * 2;
|
||||
export const PI_OVER_TWO = Math.PI / 2;
|
||||
const EPSILON3 = 1e-3;
|
||||
const EPSILON10 = 1e-10;
|
||||
const EPSILON12 = 1e-12;
|
||||
const EPSILON14 = 1e-14;
|
||||
const CENTER_TOLERANCE_SQUARED = 0.1;
|
||||
|
||||
export const vec = (x = 0, y = 0, z = 0) => ({ x, y, z });
|
||||
export const clone = (a) => ({ x: a.x, y: a.y, z: a.z });
|
||||
export const add = (a, b) => vec(a.x + b.x, a.y + b.y, a.z + b.z);
|
||||
export const sub = (a, b) => vec(a.x - b.x, a.y - b.y, a.z - b.z);
|
||||
export const scale = (a, s) => vec(a.x * s, a.y * s, a.z * s);
|
||||
export const negate = (a) => vec(-a.x, -a.y, -a.z);
|
||||
export const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
|
||||
export const cross = (a, b) =>
|
||||
vec(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
|
||||
export const magnitude = (a) => Math.sqrt(dot(a, a));
|
||||
export const distance = (a, b) => magnitude(sub(a, b));
|
||||
export function normalize(a) {
|
||||
const m = magnitude(a);
|
||||
return vec(a.x / m, a.y / m, a.z / m);
|
||||
}
|
||||
|
||||
export const toRadians = (degrees) => (degrees * Math.PI) / 180;
|
||||
export const toDegrees = (radians) => (radians * 180) / Math.PI;
|
||||
export const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
|
||||
export const acosClamped = (v) => Math.acos(clamp(v, -1, 1));
|
||||
export const equalsEpsilon = (a, b, eps) => Math.abs(a - b) <= eps;
|
||||
|
||||
/** An angle in [0, 2π). */
|
||||
export function zeroToTwoPi(angle) {
|
||||
if (angle >= 0 && angle <= TWO_PI) return angle;
|
||||
const mod = ((angle % TWO_PI) + TWO_PI) % TWO_PI;
|
||||
if (Math.abs(mod) < EPSILON14 && Math.abs(angle) > EPSILON14) return TWO_PI;
|
||||
return mod;
|
||||
}
|
||||
|
||||
/** An angle in [-π, π]. */
|
||||
export function negativePiToPi(angle) {
|
||||
if (angle >= -Math.PI && angle <= Math.PI) return angle;
|
||||
return zeroToTwoPi(angle + Math.PI) - Math.PI;
|
||||
}
|
||||
|
||||
// --- Geodesy -----------------------------------------------------------------
|
||||
|
||||
export function geodeticSurfaceNormal(p) {
|
||||
const o = WGS84.oneOverRadiiSquared;
|
||||
return normalize(vec(p.x * o.x, p.y * o.y, p.z * o.z));
|
||||
}
|
||||
|
||||
function geodeticSurfaceNormalCartographic(lon, lat) {
|
||||
const cosLat = Math.cos(lat);
|
||||
return normalize(
|
||||
vec(cosLat * Math.cos(lon), cosLat * Math.sin(lon), Math.sin(lat)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Geodetic radians and metres to ECEF. */
|
||||
export function fromRadians(lon, lat, height = 0) {
|
||||
const n = geodeticSurfaceNormalCartographic(lon, lat);
|
||||
const r = WGS84.radiiSquared;
|
||||
let k = vec(r.x * n.x, r.y * n.y, r.z * n.z);
|
||||
const gamma = Math.sqrt(dot(n, k));
|
||||
k = scale(k, 1 / gamma);
|
||||
return add(k, scale(n, height));
|
||||
}
|
||||
|
||||
/** Geodetic degrees and metres to ECEF. */
|
||||
export const fromDegrees = (lon, lat, height = 0) =>
|
||||
fromRadians(toRadians(lon), toRadians(lat), height);
|
||||
|
||||
/** A position in either contract form, as ECEF. */
|
||||
export function toEcef(position) {
|
||||
if ('lon' in position && 'lat' in position)
|
||||
return fromDegrees(position.lon, position.lat, position.height ?? 0);
|
||||
return clone(position);
|
||||
}
|
||||
|
||||
/** The point on the ellipsoid along the geodetic normal, or null at the centre. */
|
||||
export function scaleToGeodeticSurface(p) {
|
||||
const { x: positionX, y: positionY, z: positionZ } = p;
|
||||
const oneOverRadiiX = WGS84.oneOverRadii.x;
|
||||
const oneOverRadiiY = WGS84.oneOverRadii.y;
|
||||
const oneOverRadiiZ = WGS84.oneOverRadii.z;
|
||||
const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
|
||||
const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
|
||||
const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
|
||||
const squaredNorm = x2 + y2 + z2;
|
||||
const ratio = Math.sqrt(1.0 / squaredNorm);
|
||||
const intersection = scale(p, ratio);
|
||||
if (squaredNorm < CENTER_TOLERANCE_SQUARED)
|
||||
return Number.isFinite(ratio) ? intersection : null;
|
||||
|
||||
const oneOverRadiiSquaredX = WGS84.oneOverRadiiSquared.x;
|
||||
const oneOverRadiiSquaredY = WGS84.oneOverRadiiSquared.y;
|
||||
const oneOverRadiiSquaredZ = WGS84.oneOverRadiiSquared.z;
|
||||
const gradient = vec(
|
||||
intersection.x * oneOverRadiiSquaredX * 2.0,
|
||||
intersection.y * oneOverRadiiSquaredY * 2.0,
|
||||
intersection.z * oneOverRadiiSquaredZ * 2.0,
|
||||
);
|
||||
let lambda = ((1.0 - ratio) * magnitude(p)) / (0.5 * magnitude(gradient));
|
||||
let correction = 0.0;
|
||||
let func, denominator, xMultiplier, yMultiplier, zMultiplier;
|
||||
let xMultiplier2, yMultiplier2, zMultiplier2;
|
||||
let xMultiplier3, yMultiplier3, zMultiplier3;
|
||||
do {
|
||||
lambda -= correction;
|
||||
xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
|
||||
yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
|
||||
zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
|
||||
xMultiplier2 = xMultiplier * xMultiplier;
|
||||
yMultiplier2 = yMultiplier * yMultiplier;
|
||||
zMultiplier2 = zMultiplier * zMultiplier;
|
||||
xMultiplier3 = xMultiplier2 * xMultiplier;
|
||||
yMultiplier3 = yMultiplier2 * yMultiplier;
|
||||
zMultiplier3 = zMultiplier2 * zMultiplier;
|
||||
func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
|
||||
denominator =
|
||||
x2 * xMultiplier3 * oneOverRadiiSquaredX +
|
||||
y2 * yMultiplier3 * oneOverRadiiSquaredY +
|
||||
z2 * zMultiplier3 * oneOverRadiiSquaredZ;
|
||||
const derivative = -2.0 * denominator;
|
||||
correction = func / derivative;
|
||||
} while (Math.abs(func) > EPSILON12);
|
||||
return vec(
|
||||
positionX * xMultiplier,
|
||||
positionY * yMultiplier,
|
||||
positionZ * zMultiplier,
|
||||
);
|
||||
}
|
||||
|
||||
/** ECEF to geodetic `{lon, lat}` radians and `height` metres, or null at the centre. */
|
||||
export function toCartographicRadians(p) {
|
||||
const surface = scaleToGeodeticSurface(p);
|
||||
if (!surface) return null;
|
||||
const n = geodeticSurfaceNormal(surface);
|
||||
const h = sub(p, surface);
|
||||
return {
|
||||
lon: Math.atan2(n.y, n.x),
|
||||
lat: Math.asin(n.z),
|
||||
height: Math.sign(dot(h, p)) * magnitude(h),
|
||||
};
|
||||
}
|
||||
|
||||
/** ECEF to `{lon, lat}` degrees and `height` metres. */
|
||||
export function toLonLatH(p) {
|
||||
const c = toCartographicRadians(p);
|
||||
if (!c) return null;
|
||||
return { lon: toDegrees(c.lon), lat: toDegrees(c.lat), height: c.height };
|
||||
}
|
||||
|
||||
// --- Rigid frames ------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A rigid frame: unit axes `x`, `y`, `z` (columns) and an `origin`, mapping
|
||||
* local coordinates to ECEF.
|
||||
* @typedef {{x: object, y: object, z: object, origin: object}} Frame
|
||||
*/
|
||||
|
||||
export const IDENTITY = Object.freeze({
|
||||
x: Object.freeze(vec(1, 0, 0)),
|
||||
y: Object.freeze(vec(0, 1, 0)),
|
||||
z: Object.freeze(vec(0, 0, 1)),
|
||||
origin: Object.freeze(vec(0, 0, 0)),
|
||||
});
|
||||
|
||||
export const isIdentity = (frame) =>
|
||||
frame === IDENTITY ||
|
||||
(frame.x.x === 1 &&
|
||||
frame.y.y === 1 &&
|
||||
frame.z.z === 1 &&
|
||||
frame.x.y === 0 &&
|
||||
frame.x.z === 0 &&
|
||||
frame.y.x === 0 &&
|
||||
frame.y.z === 0 &&
|
||||
frame.z.x === 0 &&
|
||||
frame.z.y === 0 &&
|
||||
frame.origin.x === 0 &&
|
||||
frame.origin.y === 0 &&
|
||||
frame.origin.z === 0);
|
||||
|
||||
/** East-north-up at `origin`. */
|
||||
export function eastNorthUp(origin) {
|
||||
if (
|
||||
equalsEpsilon(origin.x, 0, EPSILON14) &&
|
||||
equalsEpsilon(origin.y, 0, EPSILON14)
|
||||
) {
|
||||
// At a pole: east is +y, north points away from the pole.
|
||||
const sign = Math.sign(origin.z) || 1;
|
||||
return {
|
||||
x: vec(0, 1, 0),
|
||||
y: vec(-sign, 0, 0),
|
||||
z: vec(0, 0, sign),
|
||||
origin: clone(origin),
|
||||
};
|
||||
}
|
||||
const up = geodeticSurfaceNormal(origin);
|
||||
const east = normalize(vec(-origin.y, origin.x, 0));
|
||||
const north = cross(up, east);
|
||||
return { x: east, y: north, z: up, origin: clone(origin) };
|
||||
}
|
||||
|
||||
export const frameVector = (frame, v) =>
|
||||
vec(
|
||||
frame.x.x * v.x + frame.y.x * v.y + frame.z.x * v.z,
|
||||
frame.x.y * v.x + frame.y.y * v.y + frame.z.y * v.z,
|
||||
frame.x.z * v.x + frame.y.z * v.y + frame.z.z * v.z,
|
||||
);
|
||||
export const framePoint = (frame, p) =>
|
||||
add(frameVector(frame, p), frame.origin);
|
||||
export const inverseFrameVector = (frame, v) =>
|
||||
vec(dot(frame.x, v), dot(frame.y, v), dot(frame.z, v));
|
||||
export const inverseFramePoint = (frame, p) =>
|
||||
inverseFrameVector(frame, sub(p, frame.origin));
|
||||
|
||||
// --- Rotations ---------------------------------------------------------------
|
||||
|
||||
/** Rotate `v` about unit `axis` by `angle` (right-handed). */
|
||||
export function rotate(v, axis, angle) {
|
||||
const c = Math.cos(angle);
|
||||
const s = Math.sin(angle);
|
||||
const d = dot(axis, v);
|
||||
const k = cross(axis, v);
|
||||
return vec(
|
||||
v.x * c + k.x * s + axis.x * d * (1 - c),
|
||||
v.y * c + k.y * s + axis.y * d * (1 - c),
|
||||
v.z * c + k.z * s + axis.z * d * (1 - c),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The rotation the contract's heading, pitch and roll describe in a local
|
||||
* east-north-up frame, as its three columns: the direction, the left axis
|
||||
* and the up vector.
|
||||
*/
|
||||
export function headingPitchRollColumns(heading, pitch, roll) {
|
||||
const h = heading - PI_OVER_TWO;
|
||||
const rotateAll = (v) =>
|
||||
rotate(
|
||||
rotate(rotate(v, vec(1, 0, 0), roll), vec(0, 1, 0), -pitch),
|
||||
vec(0, 0, 1),
|
||||
-h,
|
||||
);
|
||||
return {
|
||||
direction: rotateAll(vec(1, 0, 0)),
|
||||
left: rotateAll(vec(0, 1, 0)),
|
||||
up: rotateAll(vec(0, 0, 1)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Heading of a local direction and up, radians clockwise from north. */
|
||||
export function headingOf(direction, up) {
|
||||
const h = !equalsEpsilon(Math.abs(direction.z), 1.0, EPSILON3)
|
||||
? Math.atan2(direction.y, direction.x) - PI_OVER_TWO
|
||||
: Math.atan2(up.y, up.x) - PI_OVER_TWO;
|
||||
return TWO_PI - zeroToTwoPi(h);
|
||||
}
|
||||
|
||||
export const pitchOf = (direction) => PI_OVER_TWO - acosClamped(direction.z);
|
||||
|
||||
export function rollOf(direction, up, right) {
|
||||
if (equalsEpsilon(Math.abs(direction.z), 1.0, EPSILON3)) return 0;
|
||||
return zeroToTwoPi(Math.atan2(-right.z, up.z) + TWO_PI);
|
||||
}
|
||||
|
||||
/** The local offset a heading, pitch and range puts the eye at. */
|
||||
export function offsetFromHeadingPitchRange(heading, pitch, range) {
|
||||
const p = clamp(pitch, -PI_OVER_TWO, PI_OVER_TWO);
|
||||
const h = zeroToTwoPi(heading) - PI_OVER_TWO;
|
||||
const offset = rotate(
|
||||
rotate(vec(1, 0, 0), vec(0, 1, 0), -p),
|
||||
vec(0, 0, 1),
|
||||
-h,
|
||||
);
|
||||
return scale(negate(offset), range);
|
||||
}
|
||||
|
||||
export { EPSILON10 };
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* @module render/stub/motion
|
||||
* @description Where a motion segment puts an icon at a time, exactly as
|
||||
* the contract's `MotionSegment` describes it.
|
||||
*/
|
||||
import { add, eastNorthUp, scale, sub } from './math.js';
|
||||
|
||||
const STRAIGHT_RAD_PER_S = 1e-4;
|
||||
|
||||
/**
|
||||
* @param {import('../contract/draw').MotionSegment} segment
|
||||
* @param {{x: number, y: number, z: number}} pos The item's own position (for `hold`).
|
||||
* @param {number} t Epoch ms on the set's motion clock.
|
||||
* @returns {{x: number, y: number, z: number}}
|
||||
*/
|
||||
export function motionPosition(segment, pos, t) {
|
||||
switch (segment.kind) {
|
||||
case 'hold':
|
||||
return pos;
|
||||
case 'lerp': {
|
||||
const span = segment.t1 - segment.t0;
|
||||
const s =
|
||||
span > 0
|
||||
? Math.min(1, Math.max(0, (t - segment.t0) / span))
|
||||
: t >= segment.t1
|
||||
? 1
|
||||
: 0;
|
||||
return add(segment.from, scale(sub(segment.to, segment.from), s));
|
||||
}
|
||||
case 'arc': {
|
||||
const dt = Math.min(
|
||||
segment.maxDtS,
|
||||
Math.max(segment.minDtS, (t - segment.t0) / 1000),
|
||||
);
|
||||
const track = (segment.trackDeg * Math.PI) / 180;
|
||||
const w = (segment.turnRateDps * Math.PI) / 180;
|
||||
const v = segment.speedMps;
|
||||
let east;
|
||||
let north;
|
||||
if (Math.abs(w) < STRAIGHT_RAD_PER_S) {
|
||||
east = v * dt * Math.sin(track);
|
||||
north = v * dt * Math.cos(track);
|
||||
} else {
|
||||
east = (v / w) * (Math.cos(track) - Math.cos(track + w * dt));
|
||||
north = (v / w) * (Math.sin(track + w * dt) - Math.sin(track));
|
||||
}
|
||||
const enu = eastNorthUp(segment.fix);
|
||||
return add(segment.fix, add(scale(enu.x, east), scale(enu.y, north)));
|
||||
}
|
||||
default:
|
||||
throw new Error(`unknown motion segment ${segment.kind}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createStubRenderer } from './index.js';
|
||||
import { createStubHarness } from './harness.js';
|
||||
import { runConformance } from '../conformance/index.js';
|
||||
|
||||
test('the stub passes the conformance suite', async () => {
|
||||
const report = await runConformance(createStubHarness());
|
||||
const failed = report.results.filter((r) => r.status === 'fail');
|
||||
assert.deepEqual(
|
||||
failed.map((r) => `${r.id}: ${r.detail}`),
|
||||
[],
|
||||
);
|
||||
const skipped = report.results
|
||||
.filter((r) => r.status === 'skip')
|
||||
.map((r) => r.id);
|
||||
// Only the model check, which needs a glTF asset the stub has no use for.
|
||||
assert.deepEqual(skipped, ['draw.models']);
|
||||
});
|
||||
|
||||
test('a frame runs the contract’s steps in order', () => {
|
||||
const r = createStubRenderer();
|
||||
r.frame.requestRender('test');
|
||||
r.testing.tick();
|
||||
assert.deepEqual(r.testing.lastSteps(), [
|
||||
'flight',
|
||||
'input',
|
||||
'changed',
|
||||
'follow',
|
||||
'preUpdate',
|
||||
'moveDetection',
|
||||
'preRender',
|
||||
'render',
|
||||
'postRender',
|
||||
]);
|
||||
r.testing.tick();
|
||||
assert.deepEqual(
|
||||
r.testing.lastSteps().at(-1),
|
||||
'moveDetection',
|
||||
'an idle frame stops before preRender',
|
||||
);
|
||||
});
|
||||
|
||||
test('a throwing listener with no error listener is reported and the frame goes on', async () => {
|
||||
const reported = [];
|
||||
const saved = globalThis.reportError;
|
||||
globalThis.reportError = (error) => reported.push(error.message);
|
||||
try {
|
||||
const r = createStubRenderer();
|
||||
r.frame.on('preUpdate', () => {
|
||||
throw new Error('phase');
|
||||
});
|
||||
let after = false;
|
||||
r.frame.on('preUpdate', () => (after = true));
|
||||
r.frame.requestRender('test');
|
||||
r.testing.tick();
|
||||
assert.ok(after, 'the next listener still ran');
|
||||
assert.equal(
|
||||
r.testing.lastSteps().at(-1),
|
||||
'postRender',
|
||||
'the frame ran on',
|
||||
);
|
||||
const flight = r.camera.flyTo(
|
||||
{ lon: 0, lat: 0, height: 1e6 },
|
||||
{
|
||||
durationS: 0,
|
||||
onComplete: () => {
|
||||
throw new Error('complete');
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.equal(await flight.done, 'complete', 'the flight still resolved');
|
||||
assert.deepEqual(reported, ['phase', 'complete']);
|
||||
} finally {
|
||||
globalThis.reportError = saved;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* @module render/stub/viewRectangle
|
||||
* @description The geodetic rectangle in view, as the default renderer
|
||||
* computes it: the canvas corners picked on the ellipsoid, with the horizon
|
||||
* standing in for a corner that misses, the whole globe when fewer than two
|
||||
* corners land, and the full longitude span when the view goes over a pole.
|
||||
*/
|
||||
import {
|
||||
TWO_PI,
|
||||
WGS84,
|
||||
add,
|
||||
cross,
|
||||
dot,
|
||||
magnitude,
|
||||
normalize,
|
||||
scale,
|
||||
sub,
|
||||
toCartographicRadians,
|
||||
toDegrees,
|
||||
vec,
|
||||
} from './math.js';
|
||||
|
||||
const EPSILON9 = 1e-9;
|
||||
const EPSILON10 = 1e-10;
|
||||
/** The reference renderer's epsilon test: absolute and relative at once. */
|
||||
const equalsEpsilon = (a, b, eps) =>
|
||||
Math.abs(a - b) <= eps * Math.max(1, Math.abs(a), Math.abs(b));
|
||||
|
||||
const WHOLE_GLOBE = Object.freeze({
|
||||
west: -180,
|
||||
south: -90,
|
||||
east: 180,
|
||||
north: 90,
|
||||
});
|
||||
|
||||
/** Whether the ellipsoid's bounding sphere lies wholly outside the view frustum. */
|
||||
function globeOutsideFrustum(pose) {
|
||||
const { position, direction, up, near, far } = pose;
|
||||
const top = near * Math.tan(pose.fovy * 0.5);
|
||||
const right = pose.aspectRatio * top;
|
||||
const r = cross(direction, up);
|
||||
const nearCenter = add(position, scale(direction, near));
|
||||
const farCenter = add(position, scale(direction, far));
|
||||
const sideNormals = [
|
||||
normalize(
|
||||
cross(normalize(sub(add(nearCenter, scale(r, -right)), position)), up),
|
||||
),
|
||||
normalize(cross(up, sub(add(nearCenter, scale(r, right)), position))),
|
||||
normalize(cross(r, sub(add(nearCenter, scale(up, -top)), position))),
|
||||
normalize(cross(sub(add(nearCenter, scale(up, top)), position), r)),
|
||||
];
|
||||
// Each plane's distance from the globe's centre (the origin).
|
||||
const distances = [
|
||||
...sideNormals.map((n) => -dot(n, position)),
|
||||
-dot(direction, nearCenter),
|
||||
dot(direction, farCenter),
|
||||
];
|
||||
const radius = WGS84.radii.x;
|
||||
return distances.some((d) => d < -radius);
|
||||
}
|
||||
|
||||
/** Where the ellipsoid's limb meets the view's four quadrants, from the eye. */
|
||||
function horizonQuad(p) {
|
||||
const radii = WGS84.radii;
|
||||
const q = vec(
|
||||
p.x * WGS84.oneOverRadii.x,
|
||||
p.y * WGS84.oneOverRadii.y,
|
||||
p.z * WGS84.oneOverRadii.z,
|
||||
);
|
||||
const qMagnitude = magnitude(q);
|
||||
const qUnit = normalize(q);
|
||||
let eUnit;
|
||||
let nUnit;
|
||||
const z = vec(0, 0, 1);
|
||||
if (
|
||||
equalsEpsilon(qUnit.x, 0, EPSILON10) &&
|
||||
equalsEpsilon(qUnit.y, 0, EPSILON10) &&
|
||||
equalsEpsilon(qUnit.z, 1, EPSILON10)
|
||||
) {
|
||||
eUnit = vec(0, 1, 0);
|
||||
nUnit = vec(0, 0, 1);
|
||||
} else {
|
||||
eUnit = normalize(cross(z, qUnit));
|
||||
nUnit = normalize(cross(qUnit, eUnit));
|
||||
}
|
||||
const wMagnitude = Math.sqrt(dot(q, q) - 1);
|
||||
const center = scale(qUnit, 1 / qMagnitude);
|
||||
const s = wMagnitude / qMagnitude;
|
||||
const eastOffset = scale(eUnit, s);
|
||||
const northOffset = scale(nUnit, s);
|
||||
const toWorld = (v) => vec(v.x * radii.x, v.y * radii.y, v.z * radii.z);
|
||||
return [
|
||||
toWorld(sub(add(center, northOffset), eastOffset)),
|
||||
toWorld(sub(sub(center, northOffset), eastOffset)),
|
||||
toWorld(add(sub(center, northOffset), eastOffset)),
|
||||
toWorld(add(add(center, northOffset), eastOffset)),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{position: object, direction: object, up: object, fovy: number,
|
||||
* aspectRatio: number, near: number, far: number}} pose The camera's pose.
|
||||
* @param {{width: number, height: number}} viewport CSS pixels.
|
||||
* @param {(x: number, y: number) => object|null} pickEllipsoid
|
||||
* @returns {{west: number, south: number, east: number, north: number}|null} Degrees.
|
||||
*/
|
||||
export function computeViewRectangle(pose, viewport, pickEllipsoid) {
|
||||
if (globeOutsideFrustum(pose)) return null;
|
||||
const { width, height } = viewport;
|
||||
const horizon = horizonQuad(pose.position);
|
||||
const corners = [
|
||||
[0, 0],
|
||||
[0, height],
|
||||
[width, height],
|
||||
[width, 0],
|
||||
];
|
||||
let hits = 0;
|
||||
const cartos = corners.map(([x, y], i) => {
|
||||
const hit = pickEllipsoid(x, y);
|
||||
if (hit) hits += 1;
|
||||
return toCartographicRadians(hit ?? horizon[i]);
|
||||
});
|
||||
if (hits < 2) return { ...WHOLE_GLOBE };
|
||||
|
||||
let west = Infinity;
|
||||
let east = -Infinity;
|
||||
let westOverIDL = Infinity;
|
||||
let eastOverIDL = -Infinity;
|
||||
let south = Infinity;
|
||||
let north = -Infinity;
|
||||
for (const c of cartos) {
|
||||
west = Math.min(west, c.lon);
|
||||
east = Math.max(east, c.lon);
|
||||
south = Math.min(south, c.lat);
|
||||
north = Math.max(north, c.lat);
|
||||
const lonAdjusted = c.lon >= 0 ? c.lon : c.lon + TWO_PI;
|
||||
westOverIDL = Math.min(westOverIDL, lonAdjusted);
|
||||
eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
|
||||
}
|
||||
if (east - west > eastOverIDL - westOverIDL) {
|
||||
west = westOverIDL;
|
||||
east = eastOverIDL;
|
||||
if (east > Math.PI) east -= TWO_PI;
|
||||
if (west > Math.PI) west -= TWO_PI;
|
||||
}
|
||||
|
||||
// Over a pole the corners circle it: the longitude turns a full circle.
|
||||
let turned = 0;
|
||||
let lastLon = cartos[3].lon;
|
||||
for (const c of cartos) {
|
||||
const diff = Math.abs(c.lon - lastLon);
|
||||
turned += diff > Math.PI ? TWO_PI - diff : diff;
|
||||
lastLon = c.lon;
|
||||
}
|
||||
if (equalsEpsilon(Math.abs(turned), TWO_PI, EPSILON9)) {
|
||||
west = -Math.PI;
|
||||
east = Math.PI;
|
||||
if (cartos[0].lat >= 0) north = Math.PI / 2;
|
||||
else south = -Math.PI / 2;
|
||||
}
|
||||
return {
|
||||
west: toDegrees(west),
|
||||
south: toDegrees(south),
|
||||
east: toDegrees(east),
|
||||
north: toDegrees(north),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user