mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-17 08:42:21 +00:00
fix(globe): tighten the engine contract after review
Engine events get their own documented semantics (single registration, branded instances); the fake follows Cesium's roll sign, angle ranges, synchronous zero-duration flights, flyToSphere defaults and computeViewRectangle. The contract adds viewProjection, horizonVisible, flightActive, lookAtTransform/transform, zoomIn/zoomOut, input modifiers, terrainHeight and clampToHeight, with geometric suite checks. Engine import rules now follow each engine graph transitively.
This commit is contained in:
1 parent
528ec75f32
commit
708c96b6f6
8 files changed
+1300
-280
No files matched your search
+418
-201
@@ -3,12 +3,29 @@
|
||||
// against it, records every contract call and lets tests emit events, drive
|
||||
// input, advance frames and script pick/height/projection results through
|
||||
// `engine.fake`. It passes src/globe/testing/contractSuite.mjs.
|
||||
//
|
||||
// Simplifications against Cesium, which shell tests must not rely on:
|
||||
// - a flight interpolates the position linearly (eased) through space and
|
||||
// snaps the orientation at the end; Cesium arcs over the globe and turns
|
||||
// gradually. A flight without a duration lasts 3 s of fake frame time.
|
||||
// - moveStart/changed/moveEnd are detected once per `fake.frame()`, and
|
||||
// moveEnd fires after one frame without movement; Cesium waits 500 ms
|
||||
// (scene.cameraEventWaitTime) of wall time.
|
||||
// - nothing occludes picks or projection except where the contract says so
|
||||
// (horizonVisible); there is no terrain or scene geometry unless scripted.
|
||||
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { INPUT_TYPES, createEngineEvent } from '../contract.js';
|
||||
import { INPUT_TYPES, MODIFIERS, createEngineEvent } from '../contract.js';
|
||||
|
||||
const { cartesian2, cartesian3, cartographic, ellipsoid, math, matrix4 } = geo;
|
||||
const WGS84 = ellipsoid.WGS84;
|
||||
const RADII = WGS84.radii;
|
||||
const MAXIMUM_RADIUS = Math.max(RADII.x, RADII.y, RADII.z);
|
||||
const DEFAULT_FLIGHT_SECONDS = 3;
|
||||
const DEFAULT_ZOOM_AMOUNT = 100000; // Cesium's camera.defaultZoomAmount
|
||||
const MINIMUM_SPHERE_RANGE = 100;
|
||||
const NEAR = 1;
|
||||
const FAR = 1e9;
|
||||
const SCRIPTABLE = new Set([
|
||||
'pick',
|
||||
'drillPick',
|
||||
@@ -16,6 +33,8 @@ const SCRIPTABLE = new Set([
|
||||
'pickEllipsoid',
|
||||
'viewRectangle',
|
||||
'sampleHeight',
|
||||
'terrainHeight',
|
||||
'clampToHeight',
|
||||
'tilesLoaded',
|
||||
'worldToWindow',
|
||||
]);
|
||||
@@ -27,11 +46,26 @@ const EASINGS = {
|
||||
};
|
||||
|
||||
const copy3 = (value) => cartesian3.create(value.x, value.y, value.z);
|
||||
const scaled = (vector, scalar) =>
|
||||
cartesian3.multiplyByScalar(vector, scalar, cartesian3.create());
|
||||
const sum = (...vectors) =>
|
||||
vectors.reduce(
|
||||
(total, vector) => cartesian3.add(total, vector, total),
|
||||
cartesian3.create(),
|
||||
);
|
||||
const unit = (vector) => cartesian3.normalize(vector, cartesian3.create());
|
||||
const cross = (left, right) =>
|
||||
cartesian3.cross(left, right, cartesian3.create());
|
||||
|
||||
// An angle in [0, 2π), as Cesium's camera reports it.
|
||||
function wrapAngle(angle) {
|
||||
const value = math.zeroToTwoPi(angle);
|
||||
return value < 1e-12 || math.TWO_PI - value < 1e-12 ? 0 : value;
|
||||
}
|
||||
|
||||
// The local east/north/up axes at a position, in Earth-fixed coordinates.
|
||||
function localAxes(position) {
|
||||
const frame = matrix4.create();
|
||||
geo.transforms.eastNorthUpToFixedFrame(position, WGS84, frame);
|
||||
const frame = geo.transforms.eastNorthUpToFixedFrame(position, WGS84);
|
||||
return {
|
||||
east: cartesian3.create(frame[0], frame[1], frame[2]),
|
||||
north: cartesian3.create(frame[4], frame[5], frame[6]),
|
||||
@@ -40,14 +74,16 @@ function localAxes(position) {
|
||||
}
|
||||
|
||||
const combine = (axes, e, n, u) =>
|
||||
cartesian3.create(
|
||||
axes.east.x * e + axes.north.x * n + axes.up.x * u,
|
||||
axes.east.y * e + axes.north.y * n + axes.up.y * u,
|
||||
axes.east.z * e + axes.north.z * n + axes.up.z * u,
|
||||
);
|
||||
sum(scaled(axes.east, e), scaled(axes.north, n), scaled(axes.up, u));
|
||||
const toLocal = (axes, vector) => ({
|
||||
e: cartesian3.dot(vector, axes.east),
|
||||
n: cartesian3.dot(vector, axes.north),
|
||||
u: cartesian3.dot(vector, axes.up),
|
||||
});
|
||||
|
||||
// Direction and up for a heading/pitch/roll in the local frame at position.
|
||||
// Heading 0 looks north, positive pitch looks up, as in Cesium.
|
||||
// Direction and up for a heading/pitch/roll in the local frame at position,
|
||||
// as Cesium's setView builds them: heading 0 looks north, positive pitch looks
|
||||
// up, positive roll tilts `up` toward the camera's right.
|
||||
function orientationVectors(position, heading, pitch, roll) {
|
||||
const axes = localAxes(position);
|
||||
const cosPitch = Math.cos(pitch);
|
||||
@@ -58,54 +94,50 @@ function orientationVectors(position, heading, pitch, roll) {
|
||||
Math.sin(pitch),
|
||||
);
|
||||
const levelRight = combine(axes, Math.cos(heading), -Math.sin(heading), 0);
|
||||
const levelUp = cartesian3.cross(levelRight, direction, cartesian3.create());
|
||||
const up = cartesian3.create();
|
||||
cartesian3.add(
|
||||
cartesian3.multiplyByScalar(levelUp, Math.cos(roll), cartesian3.create()),
|
||||
cartesian3.multiplyByScalar(
|
||||
levelRight,
|
||||
-Math.sin(roll),
|
||||
cartesian3.create(),
|
||||
),
|
||||
up,
|
||||
const levelUp = cross(levelRight, direction);
|
||||
const up = sum(
|
||||
scaled(levelUp, Math.cos(roll)),
|
||||
scaled(levelRight, Math.sin(roll)),
|
||||
);
|
||||
return { direction, up: cartesian3.normalize(up, up) };
|
||||
return { direction: unit(direction), up: unit(up) };
|
||||
}
|
||||
|
||||
// Cesium's Camera heading/pitch/roll getters, in the local frame at position.
|
||||
function headingPitchRoll(position, direction, up) {
|
||||
const axes = localAxes(position);
|
||||
const e = cartesian3.dot(direction, axes.east);
|
||||
const n = cartesian3.dot(direction, axes.north);
|
||||
const u = cartesian3.dot(direction, axes.up);
|
||||
const pitch = Math.asin(math.clamp(u, -1, 1));
|
||||
// Looking straight up or down, heading follows the camera's up vector.
|
||||
const heading =
|
||||
Math.hypot(e, n) > 1e-9
|
||||
? math.zeroToTwoPi(Math.atan2(e, n))
|
||||
: math.zeroToTwoPi(
|
||||
Math.atan2(
|
||||
cartesian3.dot(up, axes.east) * -Math.sign(u),
|
||||
cartesian3.dot(up, axes.north) * -Math.sign(u),
|
||||
),
|
||||
);
|
||||
const level = orientationVectors(position, heading, pitch, 0);
|
||||
const levelRight = cartesian3.cross(
|
||||
level.direction,
|
||||
level.up,
|
||||
cartesian3.create(),
|
||||
const d = toLocal(axes, direction);
|
||||
const u = toLocal(axes, up);
|
||||
const r = toLocal(axes, cross(direction, up));
|
||||
const vertical = Math.abs(Math.abs(d.u) - 1) <= 1e-3;
|
||||
const raw = vertical
|
||||
? Math.atan2(u.n, u.e) - math.PI_OVER_TWO
|
||||
: Math.atan2(d.n, d.e) - math.PI_OVER_TWO;
|
||||
return {
|
||||
heading: wrapAngle(math.TWO_PI - math.zeroToTwoPi(raw)),
|
||||
pitch: math.PI_OVER_TWO - Math.acos(math.clamp(d.u, -1, 1)),
|
||||
roll: vertical ? 0 : wrapAngle(Math.atan2(-r.u, u.u)),
|
||||
};
|
||||
}
|
||||
|
||||
// Camera offset from a target for a HeadingPitchRange, in the target's frame.
|
||||
function offsetFromHeadingPitchRange(heading, pitch, range) {
|
||||
const p = math.clamp(pitch, -math.PI_OVER_TWO, math.PI_OVER_TWO);
|
||||
const cosPitch = Math.cos(p);
|
||||
return cartesian3.create(
|
||||
-Math.sin(heading) * cosPitch * range,
|
||||
-Math.cos(heading) * cosPitch * range,
|
||||
-Math.sin(p) * range,
|
||||
);
|
||||
const roll = Math.atan2(
|
||||
-cartesian3.dot(up, levelRight),
|
||||
cartesian3.dot(up, level.up),
|
||||
);
|
||||
return { heading, pitch, roll: Math.abs(roll) < 1e-12 ? 0 : roll };
|
||||
}
|
||||
|
||||
// Nearest intersection of a ray with the WGS84 ellipsoid, if any.
|
||||
function intersectEllipsoid(origin, direction) {
|
||||
const r = WGS84.radii;
|
||||
const o = [origin.x / r.x, origin.y / r.y, origin.z / r.z];
|
||||
const d = [direction.x / r.x, direction.y / r.y, direction.z / r.z];
|
||||
const o = [origin.x / RADII.x, origin.y / RADII.y, origin.z / RADII.z];
|
||||
const d = [
|
||||
direction.x / RADII.x,
|
||||
direction.y / RADII.y,
|
||||
direction.z / RADII.z,
|
||||
];
|
||||
const a = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
|
||||
const b = 2 * (o[0] * d[0] + o[1] * d[1] + o[2] * d[2]);
|
||||
const c = o[0] * o[0] + o[1] * o[1] + o[2] * o[2] - 1;
|
||||
@@ -115,11 +147,60 @@ function intersectEllipsoid(origin, direction) {
|
||||
const near = (-b - root) / (2 * a);
|
||||
const t = near > 0 ? near : (-b + root) / (2 * a);
|
||||
if (!(t > 0)) return undefined;
|
||||
return cartesian3.add(
|
||||
origin,
|
||||
cartesian3.multiplyByScalar(direction, t, cartesian3.create()),
|
||||
cartesian3.create(),
|
||||
return sum(origin, scaled(direction, t));
|
||||
}
|
||||
|
||||
// Cesium's computeHorizonQuad: four limb points around the camera's nadir.
|
||||
function horizonQuad(position) {
|
||||
const q = cartesian3.create(
|
||||
position.x / RADII.x,
|
||||
position.y / RADII.y,
|
||||
position.z / RADII.z,
|
||||
);
|
||||
const qMagnitude = cartesian3.magnitude(q);
|
||||
const qUnit = unit(q);
|
||||
let east;
|
||||
let north;
|
||||
if (cartesian3.equalsEpsilon(qUnit, cartesian3.UNIT_Z, math.EPSILON10)) {
|
||||
east = cartesian3.create(0, 1, 0);
|
||||
north = cartesian3.create(0, 0, 1);
|
||||
} else {
|
||||
east = unit(cross(cartesian3.UNIT_Z, qUnit));
|
||||
north = unit(cross(qUnit, east));
|
||||
}
|
||||
const center = scaled(qUnit, 1 / qMagnitude);
|
||||
const offset =
|
||||
Math.sqrt(Math.max(0, cartesian3.magnitudeSquared(q) - 1)) / qMagnitude;
|
||||
const point = (n, e) => {
|
||||
const p = sum(center, scaled(north, n * offset), scaled(east, e * offset));
|
||||
return cartesian3.create(p.x * RADII.x, p.y * RADII.y, p.z * RADII.z);
|
||||
};
|
||||
// Same order as the corner picks: upper-left, lower-left, lower-right, upper-right.
|
||||
return [point(1, -1), point(-1, -1), point(-1, 1), point(1, 1)];
|
||||
}
|
||||
|
||||
// Cesium's Rectangle.fromCartographicArray, including the antimeridian case.
|
||||
function rectangleFromCartographics(points) {
|
||||
let west = Infinity;
|
||||
let east = -Infinity;
|
||||
let westOverIDL = Infinity;
|
||||
let eastOverIDL = -Infinity;
|
||||
let south = Infinity;
|
||||
let north = -Infinity;
|
||||
for (const { longitude, latitude } of points) {
|
||||
west = Math.min(west, longitude);
|
||||
east = Math.max(east, longitude);
|
||||
south = Math.min(south, latitude);
|
||||
north = Math.max(north, latitude);
|
||||
const adjusted = longitude >= 0 ? longitude : longitude + math.TWO_PI;
|
||||
westOverIDL = Math.min(westOverIDL, adjusted);
|
||||
eastOverIDL = Math.max(eastOverIDL, adjusted);
|
||||
}
|
||||
if (east - west > eastOverIDL - westOverIDL) {
|
||||
west = westOverIDL > Math.PI ? westOverIDL - math.TWO_PI : westOverIDL;
|
||||
east = eastOverIDL > Math.PI ? eastOverIDL - math.TWO_PI : eastOverIDL;
|
||||
}
|
||||
return { west, south, east, north };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -153,6 +234,7 @@ export function createFakeEngine(options = {}) {
|
||||
};
|
||||
const inputs = new Map(INPUT_TYPES.map((type) => [type, new Set()]));
|
||||
const scripts = new Map();
|
||||
let transform = [...matrix4.IDENTITY];
|
||||
let percentageChanged = 0.5;
|
||||
let continuous = false;
|
||||
let flight = null;
|
||||
@@ -172,85 +254,63 @@ export function createFakeEngine(options = {}) {
|
||||
};
|
||||
const record = (method, args) => fake.calls.push({ method, args });
|
||||
|
||||
function setOrientation(position, orientation) {
|
||||
if (orientation && 'direction' in orientation) {
|
||||
state.position = copy3(position);
|
||||
state.direction = cartesian3.normalize(
|
||||
orientation.direction,
|
||||
cartesian3.create(),
|
||||
);
|
||||
state.up = cartesian3.normalize(orientation.up, cartesian3.create());
|
||||
return;
|
||||
}
|
||||
// Missing angles keep the current ones, measured where the camera is now.
|
||||
const current = poseAngles();
|
||||
state.position = copy3(position);
|
||||
const aspect = () => width / height;
|
||||
const right = () => unit(cross(state.direction, state.up));
|
||||
const poseAngles = () =>
|
||||
headingPitchRoll(state.position, state.direction, state.up);
|
||||
|
||||
// The pose for a destination and orientation; missing angles use `fallback`.
|
||||
function viewFor(position, orientation, fallback) {
|
||||
if (orientation && 'direction' in orientation)
|
||||
return {
|
||||
position: copy3(position),
|
||||
direction: unit(orientation.direction),
|
||||
up: unit(orientation.up),
|
||||
};
|
||||
const vectors = orientationVectors(
|
||||
state.position,
|
||||
orientation?.heading ?? current.heading,
|
||||
orientation?.pitch ?? current.pitch,
|
||||
orientation?.roll ?? current.roll,
|
||||
position,
|
||||
orientation?.heading ?? fallback.heading,
|
||||
orientation?.pitch ?? fallback.pitch,
|
||||
orientation?.roll ?? fallback.roll,
|
||||
);
|
||||
state.direction = vectors.direction;
|
||||
state.up = vectors.up;
|
||||
return { position: copy3(position), ...vectors };
|
||||
}
|
||||
// Cesium's setView/flyTo defaults for missing angles.
|
||||
const CESIUM_DEFAULTS = { heading: 0, pitch: -math.PI_OVER_TWO, roll: 0 };
|
||||
|
||||
function apply(view) {
|
||||
state.position = copy3(view.position);
|
||||
state.direction = copy3(view.direction);
|
||||
state.up = copy3(view.up);
|
||||
}
|
||||
|
||||
function poseAngles() {
|
||||
if (cartesian3.magnitudeSquared(state.direction) === 0)
|
||||
return { heading: 0, pitch: -math.PI_OVER_TWO, roll: 0 };
|
||||
return headingPitchRoll(state.position, state.direction, state.up);
|
||||
function setTransform(next, target) {
|
||||
transform = [...next];
|
||||
lookAtTarget = target ? copy3(target) : null;
|
||||
}
|
||||
|
||||
function right() {
|
||||
const result = cartesian3.cross(
|
||||
state.direction,
|
||||
state.up,
|
||||
cartesian3.create(),
|
||||
);
|
||||
return cartesian3.normalize(result, result);
|
||||
}
|
||||
|
||||
// Camera placed at `range` from target, looking at it, with heading/pitch
|
||||
// measured in the target's local frame (Cesium's HeadingPitchRange).
|
||||
function offsetView(target, heading, pitch, range) {
|
||||
const toTarget = orientationVectors(target, heading, pitch, 0);
|
||||
const position = cartesian3.subtract(
|
||||
target,
|
||||
cartesian3.multiplyByScalar(
|
||||
toTarget.direction,
|
||||
range,
|
||||
cartesian3.create(),
|
||||
),
|
||||
cartesian3.create(),
|
||||
);
|
||||
return { position, direction: toTarget.direction, up: toTarget.up };
|
||||
}
|
||||
|
||||
function scripted(name, args, fallback) {
|
||||
if (!scripts.has(name)) return fallback();
|
||||
const value = scripts.get(name);
|
||||
return typeof value === 'function' ? value(...args) : value;
|
||||
}
|
||||
|
||||
function startFlight(options, target) {
|
||||
if (flight) cancelCurrentFlight();
|
||||
const duration = Math.max(0, options.duration ?? 3);
|
||||
flight = {
|
||||
start: copy3(state.position),
|
||||
target,
|
||||
duration: duration * 1000,
|
||||
elapsed: 0,
|
||||
ease: EASINGS[options.easing] ?? EASINGS.cubicInOut,
|
||||
complete: options.complete,
|
||||
cancel: options.cancel,
|
||||
};
|
||||
if (duration === 0) applyFlightTarget(flight.target);
|
||||
}
|
||||
|
||||
function applyFlightTarget(target) {
|
||||
state.position = copy3(target.position);
|
||||
state.direction = copy3(target.direction);
|
||||
state.up = copy3(target.up);
|
||||
function lookAtFrame(frame, offset) {
|
||||
const local =
|
||||
offset && 'heading' in offset
|
||||
? offsetFromHeadingPitchRange(
|
||||
offset.heading,
|
||||
offset.pitch,
|
||||
offset.range,
|
||||
)
|
||||
: copy3(offset);
|
||||
const localDirection = unit(cartesian3.negate(local, cartesian3.create()));
|
||||
let localRight = cross(localDirection, cartesian3.UNIT_Z);
|
||||
if (cartesian3.magnitudeSquared(localRight) < math.EPSILON10)
|
||||
localRight = copy3(cartesian3.UNIT_X);
|
||||
localRight = unit(localRight);
|
||||
const localUp = unit(cross(localRight, localDirection));
|
||||
const vector = (value) =>
|
||||
unit(matrix4.multiplyByPointAsVector(frame, value, cartesian3.create()));
|
||||
apply({
|
||||
position: matrix4.multiplyByPoint(frame, local, cartesian3.create()),
|
||||
direction: vector(localDirection),
|
||||
up: vector(localUp),
|
||||
});
|
||||
}
|
||||
|
||||
function cancelCurrentFlight() {
|
||||
@@ -259,12 +319,29 @@ export function createFakeEngine(options = {}) {
|
||||
current?.cancel?.();
|
||||
}
|
||||
|
||||
function startFlight(flightOptions, target) {
|
||||
cancelCurrentFlight();
|
||||
const duration = flightOptions.duration ?? DEFAULT_FLIGHT_SECONDS;
|
||||
if (duration <= 0) {
|
||||
apply(target);
|
||||
flightOptions.complete?.();
|
||||
return;
|
||||
}
|
||||
flight = {
|
||||
start: copy3(state.position),
|
||||
target,
|
||||
duration: duration * 1000,
|
||||
elapsed: 0,
|
||||
ease: EASINGS[flightOptions.easing] ?? EASINGS.cubicInOut,
|
||||
complete: flightOptions.complete,
|
||||
cancel: flightOptions.cancel,
|
||||
};
|
||||
}
|
||||
|
||||
function advanceFlight(dt) {
|
||||
if (!flight) return;
|
||||
flight.elapsed += dt;
|
||||
const t = flight.duration
|
||||
? Math.min(1, flight.elapsed / flight.duration)
|
||||
: 1;
|
||||
const t = Math.min(1, flight.elapsed / flight.duration);
|
||||
if (t < 1) {
|
||||
cartesian3.lerp(
|
||||
flight.start,
|
||||
@@ -276,7 +353,7 @@ export function createFakeEngine(options = {}) {
|
||||
}
|
||||
const current = flight;
|
||||
flight = null;
|
||||
applyFlightTarget(current.target);
|
||||
apply(current.target);
|
||||
current.complete?.();
|
||||
}
|
||||
|
||||
@@ -333,8 +410,7 @@ export function createFakeEngine(options = {}) {
|
||||
const depth = cartesian3.dot(offset, state.direction);
|
||||
if (!(depth > 0)) return undefined;
|
||||
const tangent = Math.tan(fovy / 2);
|
||||
const ndcX =
|
||||
cartesian3.dot(offset, right()) / (depth * tangent * (width / height));
|
||||
const ndcX = cartesian3.dot(offset, right()) / (depth * tangent * aspect());
|
||||
const ndcY = cartesian3.dot(offset, state.up) / (depth * tangent);
|
||||
const x = ((ndcX + 1) / 2) * width;
|
||||
const y = ((1 - ndcY) / 2) * height;
|
||||
@@ -344,48 +420,136 @@ export function createFakeEngine(options = {}) {
|
||||
return result;
|
||||
}
|
||||
|
||||
function viewProjection(result = matrix4.create()) {
|
||||
const f = 1 / Math.tan(fovy / 2);
|
||||
const rows = [
|
||||
[right(), f / aspect()],
|
||||
[state.up, f],
|
||||
];
|
||||
const D = state.direction;
|
||||
const P = state.position;
|
||||
for (const [row, [axis, scale]] of rows.entries()) {
|
||||
result[row] = axis.x * scale;
|
||||
result[4 + row] = axis.y * scale;
|
||||
result[8 + row] = axis.z * scale;
|
||||
result[12 + row] = -cartesian3.dot(axis, P) * scale;
|
||||
}
|
||||
// Eye z is −direction·(p − position); clip.w = −z_eye.
|
||||
const A = (FAR + NEAR) / (NEAR - FAR);
|
||||
const B = (2 * FAR * NEAR) / (NEAR - FAR);
|
||||
result[2] = -D.x * A;
|
||||
result[6] = -D.y * A;
|
||||
result[10] = -D.z * A;
|
||||
result[14] = cartesian3.dot(D, P) * A + B;
|
||||
result[3] = D.x;
|
||||
result[7] = D.y;
|
||||
result[11] = D.z;
|
||||
result[15] = -cartesian3.dot(D, P);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Cesium's EllipsoidalOccluder.isPointVisible.
|
||||
function horizonVisible(position) {
|
||||
const camera = cartesian3.create(
|
||||
state.position.x / RADII.x,
|
||||
state.position.y / RADII.y,
|
||||
state.position.z / RADII.z,
|
||||
);
|
||||
const limbSquared = cartesian3.magnitudeSquared(camera) - 1;
|
||||
const target = cartesian3.create(
|
||||
position.x / RADII.x,
|
||||
position.y / RADII.y,
|
||||
position.z / RADII.z,
|
||||
);
|
||||
const vt = cartesian3.subtract(target, camera, cartesian3.create());
|
||||
const vtDotVc = -cartesian3.dot(vt, camera);
|
||||
const occluded =
|
||||
limbSquared < 0
|
||||
? vtDotVc > 0
|
||||
: vtDotVc > limbSquared &&
|
||||
(vtDotVc * vtDotVc) / cartesian3.magnitudeSquared(vt) > limbSquared;
|
||||
return !occluded;
|
||||
}
|
||||
|
||||
function ray(screen) {
|
||||
const tangent = Math.tan(fovy / 2);
|
||||
const ndcX = (2 * screen.x) / width - 1;
|
||||
const ndcY = 1 - (2 * screen.y) / height;
|
||||
const direction = combine(
|
||||
{ east: right(), north: state.up, up: state.direction },
|
||||
ndcX * tangent * (width / height),
|
||||
ndcY * tangent,
|
||||
1,
|
||||
const direction = sum(
|
||||
state.direction,
|
||||
scaled(right(), ndcX * tangent * aspect()),
|
||||
scaled(state.up, ndcY * tangent),
|
||||
);
|
||||
return {
|
||||
origin: copy3(state.position),
|
||||
direction: cartesian3.normalize(direction, direction),
|
||||
};
|
||||
return { origin: copy3(state.position), direction: unit(direction) };
|
||||
}
|
||||
|
||||
// Whether the sphere around the Earth is fully outside the view frustum.
|
||||
function globeOutsideFrustum() {
|
||||
const toCentre = cartesian3.negate(state.position, cartesian3.create());
|
||||
const D = state.direction;
|
||||
const tanY = Math.tan(fovy / 2);
|
||||
const tanX = tanY * aspect();
|
||||
const R = right();
|
||||
const U = state.up;
|
||||
const planes = [
|
||||
[D, NEAR],
|
||||
[unit(sum(scaled(R, -1), scaled(D, tanX))), 0],
|
||||
[unit(sum(R, scaled(D, tanX))), 0],
|
||||
[unit(sum(scaled(U, -1), scaled(D, tanY))), 0],
|
||||
[unit(sum(U, scaled(D, tanY))), 0],
|
||||
];
|
||||
return planes.some(
|
||||
([normal, offset]) =>
|
||||
cartesian3.dot(normal, toCentre) - offset < -MAXIMUM_RADIUS,
|
||||
);
|
||||
}
|
||||
|
||||
// Cesium's Camera.computeViewRectangle.
|
||||
function computedViewRectangle() {
|
||||
const corners = [
|
||||
if (globeOutsideFrustum()) return undefined;
|
||||
const horizon = horizonQuad(state.position);
|
||||
let hits = 0;
|
||||
const points = [
|
||||
[0, 0],
|
||||
[width, 0],
|
||||
[0, height],
|
||||
[width, height],
|
||||
[width / 2, 0],
|
||||
[width / 2, height],
|
||||
[0, height / 2],
|
||||
[width, height / 2],
|
||||
].map(([x, y]) =>
|
||||
intersectEllipsoid(
|
||||
[width, 0],
|
||||
].map(([x, y], index) => {
|
||||
const hit = intersectEllipsoid(
|
||||
state.position,
|
||||
ray(cartesian2.create(x, y)).direction,
|
||||
),
|
||||
);
|
||||
if (corners.some((corner) => !corner)) return undefined;
|
||||
const points = corners.map((corner) =>
|
||||
cartographic.fromCartesian(corner, WGS84),
|
||||
);
|
||||
return {
|
||||
west: Math.min(...points.map((point) => point.longitude)),
|
||||
south: Math.min(...points.map((point) => point.latitude)),
|
||||
east: Math.max(...points.map((point) => point.longitude)),
|
||||
north: Math.max(...points.map((point) => point.latitude)),
|
||||
};
|
||||
);
|
||||
if (hit) hits++;
|
||||
return cartographic.fromCartesian(hit ?? horizon[index], WGS84);
|
||||
});
|
||||
if (hits < 2)
|
||||
return {
|
||||
west: -Math.PI,
|
||||
south: -math.PI_OVER_TWO,
|
||||
east: Math.PI,
|
||||
north: math.PI_OVER_TWO,
|
||||
};
|
||||
const rectangle = rectangleFromCartographics(points);
|
||||
let travelled = 0;
|
||||
let last = points[3].longitude;
|
||||
for (const { longitude } of points) {
|
||||
const step = Math.abs(longitude - last);
|
||||
travelled += step > Math.PI ? math.TWO_PI - step : step;
|
||||
last = longitude;
|
||||
}
|
||||
if (math.equalsEpsilon(Math.abs(travelled), math.TWO_PI, 1e-9)) {
|
||||
rectangle.west = -Math.PI;
|
||||
rectangle.east = Math.PI;
|
||||
if (points[0].latitude >= 0) rectangle.north = math.PI_OVER_TWO;
|
||||
else rectangle.south = -math.PI_OVER_TWO;
|
||||
}
|
||||
return rectangle;
|
||||
}
|
||||
|
||||
function scripted(name, args, fallback) {
|
||||
if (!scripts.has(name)) return fallback();
|
||||
const value = scripts.get(name);
|
||||
return typeof value === 'function' ? value(...args) : value;
|
||||
}
|
||||
|
||||
const camera = {
|
||||
@@ -407,54 +571,84 @@ export function createFakeEngine(options = {}) {
|
||||
record('camera.setView', [view]);
|
||||
if (!view?.destination)
|
||||
throw new TypeError('setView needs a destination');
|
||||
setOrientation(view.destination, view.orientation);
|
||||
apply(viewFor(view.destination, view.orientation, CESIUM_DEFAULTS));
|
||||
},
|
||||
flyTo(flightOptions) {
|
||||
record('camera.flyTo', [flightOptions]);
|
||||
if (!flightOptions?.destination)
|
||||
throw new TypeError('flyTo needs a destination');
|
||||
startFlight(
|
||||
flightOptions,
|
||||
viewFor(
|
||||
flightOptions.destination,
|
||||
flightOptions.orientation,
|
||||
CESIUM_DEFAULTS,
|
||||
),
|
||||
);
|
||||
},
|
||||
flyToSphere(sphere, sphereOptions = {}) {
|
||||
record('camera.flyToSphere', [sphere, sphereOptions]);
|
||||
setTransform(matrix4.IDENTITY);
|
||||
let range = sphereOptions.range;
|
||||
if (!range) {
|
||||
const tanPhi = Math.tan(fovy / 2);
|
||||
const tanTheta = aspect() * tanPhi;
|
||||
range = Math.max(
|
||||
MINIMUM_SPHERE_RANGE,
|
||||
Math.max(sphere.radius / tanTheta, sphere.radius / tanPhi),
|
||||
);
|
||||
}
|
||||
const frame = geo.transforms.eastNorthUpToFixedFrame(
|
||||
sphere.center,
|
||||
WGS84,
|
||||
);
|
||||
const saved = {
|
||||
position: state.position,
|
||||
direction: state.direction,
|
||||
up: state.up,
|
||||
};
|
||||
setOrientation(flightOptions.destination, flightOptions.orientation);
|
||||
lookAtFrame(frame, {
|
||||
heading: sphereOptions.heading ?? 0,
|
||||
pitch: sphereOptions.pitch ?? -Math.PI / 4,
|
||||
range,
|
||||
});
|
||||
const target = {
|
||||
position: state.position,
|
||||
direction: state.direction,
|
||||
up: state.up,
|
||||
};
|
||||
Object.assign(state, saved);
|
||||
startFlight(flightOptions, target);
|
||||
},
|
||||
flyToSphere(sphere, sphereOptions = {}) {
|
||||
record('camera.flyToSphere', [sphere, sphereOptions]);
|
||||
const range =
|
||||
sphereOptions.range ??
|
||||
Math.max(sphere.radius / Math.sin(fovy / 2), 100);
|
||||
const target = offsetView(
|
||||
sphere.center,
|
||||
sphereOptions.heading ?? 0,
|
||||
sphereOptions.pitch ?? -0.5,
|
||||
range,
|
||||
);
|
||||
apply(saved);
|
||||
startFlight(sphereOptions, target);
|
||||
},
|
||||
flightActive: () => flight != null,
|
||||
lookAt(target, offset) {
|
||||
record('camera.lookAt', [target, offset]);
|
||||
lookAtTarget = copy3(target);
|
||||
applyFlightTarget(
|
||||
offsetView(target, offset.heading, offset.pitch, offset.range),
|
||||
);
|
||||
const frame = geo.transforms.eastNorthUpToFixedFrame(target, WGS84);
|
||||
setTransform(frame, target);
|
||||
lookAtFrame(frame, offset);
|
||||
},
|
||||
lookAtTransform(frame, offset) {
|
||||
record('camera.lookAtTransform', [frame, offset]);
|
||||
setTransform(frame, cartesian3.create(frame[12], frame[13], frame[14]));
|
||||
if (offset) lookAtFrame(frame, offset);
|
||||
},
|
||||
transform: () => [...transform],
|
||||
release() {
|
||||
record('camera.release', []);
|
||||
lookAtTarget = null;
|
||||
setTransform(matrix4.IDENTITY);
|
||||
},
|
||||
cancelFlight() {
|
||||
record('camera.cancelFlight', []);
|
||||
cancelCurrentFlight();
|
||||
},
|
||||
zoomIn(amount = DEFAULT_ZOOM_AMOUNT) {
|
||||
record('camera.zoomIn', [amount]);
|
||||
state.position = sum(state.position, scaled(state.direction, amount));
|
||||
},
|
||||
zoomOut(amount = DEFAULT_ZOOM_AMOUNT) {
|
||||
record('camera.zoomOut', [amount]);
|
||||
state.position = sum(state.position, scaled(state.direction, -amount));
|
||||
},
|
||||
viewRectangle() {
|
||||
record('camera.viewRectangle', []);
|
||||
return scripted('viewRectangle', [], computedViewRectangle);
|
||||
@@ -514,6 +708,8 @@ export function createFakeEngine(options = {}) {
|
||||
return cartesian2.clone(value, result);
|
||||
return value;
|
||||
},
|
||||
viewProjection,
|
||||
horizonVisible,
|
||||
},
|
||||
frames: {
|
||||
preUpdate: events['frames.preUpdate'],
|
||||
@@ -537,14 +733,27 @@ export function createFakeEngine(options = {}) {
|
||||
return scripted('sampleHeight', [position, exclude], () => undefined);
|
||||
},
|
||||
supported: true,
|
||||
terrainHeight(position) {
|
||||
record('surface.terrainHeight', [position]);
|
||||
return scripted('terrainHeight', [position], () => 0);
|
||||
},
|
||||
terrainHeightSupported: true,
|
||||
clampToHeight(position, exclude) {
|
||||
record('surface.clampToHeight', [position, exclude]);
|
||||
return scripted('clampToHeight', [position, exclude], () => undefined);
|
||||
},
|
||||
clampToHeightSupported: true,
|
||||
tilesLoaded: () => scripted('tilesLoaded', [], () => true),
|
||||
},
|
||||
input: {
|
||||
on(type, listener) {
|
||||
record('input.on', [type]);
|
||||
on(type, listener, inputOptions = {}) {
|
||||
record('input.on', [type, inputOptions]);
|
||||
const listeners = inputs.get(type);
|
||||
if (!listeners) throw new TypeError(`Unknown input type: ${type}`);
|
||||
const entry = (event) => listener(event);
|
||||
const modifier = inputOptions.modifier;
|
||||
if (modifier !== undefined && !MODIFIERS.includes(modifier))
|
||||
throw new TypeError(`Unknown input modifier: ${modifier}`);
|
||||
const entry = { listener, modifier };
|
||||
listeners.add(entry);
|
||||
return () => listeners.delete(entry);
|
||||
},
|
||||
@@ -598,11 +807,12 @@ export function createFakeEngine(options = {}) {
|
||||
pose.height ?? 1e7,
|
||||
WGS84,
|
||||
);
|
||||
setOrientation(
|
||||
position,
|
||||
pose.direction
|
||||
? { direction: pose.direction, up: pose.up }
|
||||
: { heading: pose.heading, pitch: pose.pitch, roll: pose.roll },
|
||||
apply(
|
||||
viewFor(
|
||||
position,
|
||||
pose.direction ? { direction: pose.direction, up: pose.up } : pose,
|
||||
poseAngles(),
|
||||
),
|
||||
);
|
||||
},
|
||||
setSize(nextWidth, nextHeight) {
|
||||
@@ -620,11 +830,15 @@ export function createFakeEngine(options = {}) {
|
||||
if (!event) throw new TypeError(`Unknown engine event: ${name}`);
|
||||
event.raiseEvent(...args);
|
||||
},
|
||||
/** Delivers an input event to `engine.input.on(type)` subscribers. */
|
||||
input(type, event) {
|
||||
/**
|
||||
* Delivers input to `engine.input.on(type)` subscribers registered for
|
||||
* `modifier` (none by default), as Cesium's ScreenSpaceEventHandler does.
|
||||
*/
|
||||
input(type, event, modifier) {
|
||||
const listeners = inputs.get(type);
|
||||
if (!listeners) throw new TypeError(`Unknown input type: ${type}`);
|
||||
for (const listener of [...listeners]) listener(event);
|
||||
for (const entry of [...listeners])
|
||||
if (entry.modifier === modifier) entry.listener(event);
|
||||
},
|
||||
/** Replaces a result with a value or a function of the call's arguments. */
|
||||
script(name, valueOrFunction) {
|
||||
@@ -635,7 +849,6 @@ export function createFakeEngine(options = {}) {
|
||||
unscript(name) {
|
||||
scripts.delete(name);
|
||||
},
|
||||
flying: () => flight != null,
|
||||
lookAtTarget: () => (lookAtTarget ? copy3(lookAtTarget) : undefined),
|
||||
/** Runs one frame: preUpdate, flight progress, preRender, camera events, postRender. */
|
||||
frame(dt = 16) {
|
||||
@@ -651,14 +864,18 @@ export function createFakeEngine(options = {}) {
|
||||
},
|
||||
});
|
||||
|
||||
fake.setPose({
|
||||
longitude: options.longitude ?? 0,
|
||||
latitude: options.latitude ?? 0,
|
||||
height: options.altitude ?? 1e7,
|
||||
heading: 0,
|
||||
pitch: -math.PI_OVER_TWO,
|
||||
roll: 0,
|
||||
});
|
||||
apply(
|
||||
viewFor(
|
||||
cartesian3.fromRadians(
|
||||
options.longitude ?? 0,
|
||||
options.latitude ?? 0,
|
||||
options.altitude ?? 1e7,
|
||||
WGS84,
|
||||
),
|
||||
CESIUM_DEFAULTS,
|
||||
CESIUM_DEFAULTS,
|
||||
),
|
||||
);
|
||||
lastFramePose = {
|
||||
position: copy3(state.position),
|
||||
direction: copy3(state.direction),
|
||||
|
||||
Reference in new issue
Block a user