Read Street Level's camera and ground through the renderer's ports

The Street Level view maths no longer reads Cesium. The camera's place
comes from the camera port's pose; the visible box and the view focus
cast the query port's screen rays and meet them with the ground, the
WGS84 ellipsoid raised to the ground height, in geo; heights come from
the query port; the horizon cull for the marker and the cones tests
against an ellipsoid 1,000 m below WGS84 in geo and re-culls on the
frame port's pre-render. Ground clicks, the screen-centre aim, the
nearest-image point, photo framing, the coverage refresh and the ground
re-measure read the same ports and convert positions with geo.

geo's ellipsoid functions (toLonLatH, rayEllipsoid and those under them)
and horizonFrom take an optional ellipsoid, made with ellipsoidOf or
offsetEllipsoid; anything else, a map index included, means WGS84. Tests
check them against Cesium on raised and lowered ellipsoids.

view, index, cameraFraming, groundClick and selection leave the Cesium
allow-list. The Street Level entries are Cesium-free callers of the
unbound factories: given a viewer of a caller's own, with no renderer
bound, the caller loads ./render/cesium/unbound first. GhostMaps, which
uses the horizon cull and is still on the list, loads the camera factory
itself.

Differences the contract does not let us avoid:
- The ground under the camera no longer reads whether the globe is shown
  (the globe port has no visibility getter). Where 3D tiles answer under
  the camera they decide, as they did under Google 3D; elsewhere the
  terrain answers, then the drawn surface below the camera. Over 3D tiles
  shown on a map with the globe (and under other primitives at the
  nadir) those now count as ground.
- Without depth-texture support the query port answers no heights, the
  terrain included, so the ground then reads as the ellipsoid.
- selection and groundClick still read the click dispatcher's own pick
  for now; they move to draw-set hits with the coverage lines.
This commit is contained in:
Sameh Khamis committed 2026-11-07 01:40:32 -08:00
1 parent 30b6be1da0
commit a10f3a16e1
22 files changed
+567 -260

No files matched your search

+15
View File
@@ -2507,6 +2507,7 @@
"src/render/cesium/common.js", "src/render/cesium/common.js",
"src/layers/streetLevel/marker.js", "src/layers/streetLevel/marker.js",
"src/layers/streetLevel/view.js", "src/layers/streetLevel/view.js",
"src/geo/horizon.js",
"src/layers/streetLevel/uiState.js", "src/layers/streetLevel/uiState.js",
"src/layers/streetLevel/pickRouter.js", "src/layers/streetLevel/pickRouter.js",
"src/data/idSwitches.js", "src/data/idSwitches.js",
@@ -5742,6 +5743,7 @@
"exports": ["./layers/ghostmaps"], "exports": ["./layers/ghostmaps"],
"modules": [ "modules": [
"src/layers/ghostMaps/index.js", "src/layers/ghostMaps/index.js",
"src/geo/index.js",
"src/layers/ghostMaps/catalog.js", "src/layers/ghostMaps/catalog.js",
"src/layers/ghostMaps/records.js", "src/layers/ghostMaps/records.js",
"src/layers/ghostMaps/kml.js", "src/layers/ghostMaps/kml.js",
@@ -5767,6 +5769,9 @@
"src/data/followed.js", "src/data/followed.js",
"src/layers/streetLevel/tileMath.js", "src/layers/streetLevel/tileMath.js",
"src/layers/streetLevel/view.js", "src/layers/streetLevel/view.js",
"src/geo/ellipsoid.js",
"src/geo/horizon.js",
"src/geo/vector.js",
"src/data/inputOwnership.js", "src/data/inputOwnership.js",
"src/data/scenePick.js", "src/data/scenePick.js",
"src/input/sensorPick.js", "src/input/sensorPick.js",
@@ -5774,6 +5779,16 @@
"src/data/pickRegistry.js", "src/data/pickRegistry.js",
"src/input/dispatcher.js", "src/input/dispatcher.js",
"src/render/cesium/drawHit.js", "src/render/cesium/drawHit.js",
"src/render/cesium/camera.js",
"src/render/camera/events.js",
"src/geo/celestial.js",
"src/geo/quaternion.js",
"src/geo/frames.js",
"src/render/cesium/credits.js",
"src/render/creditMarkup.js",
"src/render/cesium/query.js",
"src/render/cesium/draw.js",
"src/render/cesium/frame.js",
"src/render/cesium/follow.js", "src/render/cesium/follow.js",
"src/render/cesium/cameraInput.js", "src/render/cesium/cameraInput.js",
"src/render/cesium/common.js", "src/render/cesium/common.js",
+59 -19
View File
@@ -47,11 +47,45 @@ export const WGS84 = Object.freeze({
}), }),
}); });
/**
* An ellipsoid with these radii, in the form `WGS84` has: for code that
* works on a surface other than WGS84 (the ground raised to a height, a
* horizon taken below it). Pass it as the trailing argument of the
* functions that take one.
* @param {{x: number, y: number, z: number}} radii
*/
export function ellipsoidOf({ x, y, z }) {
return Object.freeze({
radii: Object.freeze({ x, y, z }),
radiiSquared: Object.freeze({ x: x * x, y: y * y, z: z * z }),
oneOverRadii: Object.freeze({ x: 1 / x, y: 1 / y, z: 1 / z }),
oneOverRadiiSquared: Object.freeze({
x: 1 / (x * x),
y: 1 / (y * y),
z: 1 / (z * z),
}),
});
}
/** WGS84 with every radius `metres` longer (shorter, when negative). */
export function offsetEllipsoid(metres) {
const { x, y, z } = WGS84.radii;
return ellipsoidOf({ x: x + metres, y: y + metres, z: z + metres });
}
/**
* The ellipsoid a trailing argument names: one from `ellipsoidOf`, else
* WGS84 (so these functions can still be handed to `map`, whose index
* lands there).
*/
const ellipsoidArg = (ellipsoid) =>
ellipsoid?.oneOverRadiiSquared ? ellipsoid : WGS84;
const EPSILON12 = 1e-12; const EPSILON12 = 1e-12;
const CENTER_TOLERANCE_SQUARED = 0.1; const CENTER_TOLERANCE_SQUARED = 0.1;
export function geodeticSurfaceNormal(p) { export function geodeticSurfaceNormal(p, ellipsoid) {
const o = WGS84.oneOverRadiiSquared; const o = ellipsoidArg(ellipsoid).oneOverRadiiSquared;
return normalize(vec(p.x * o.x, p.y * o.y, p.z * o.z)); return normalize(vec(p.x * o.x, p.y * o.y, p.z * o.z));
} }
@@ -77,11 +111,12 @@ export const fromDegrees = (lon, lat, height = 0) =>
fromRadians(toRadians(lon), toRadians(lat), height); fromRadians(toRadians(lon), toRadians(lat), height);
/** The point on the ellipsoid along the geodetic normal, or null at the centre. */ /** The point on the ellipsoid along the geodetic normal, or null at the centre. */
export function scaleToGeodeticSurface(p) { export function scaleToGeodeticSurface(p, ellipsoid) {
const e = ellipsoidArg(ellipsoid);
const { x: positionX, y: positionY, z: positionZ } = p; const { x: positionX, y: positionY, z: positionZ } = p;
const oneOverRadiiX = WGS84.oneOverRadii.x; const oneOverRadiiX = e.oneOverRadii.x;
const oneOverRadiiY = WGS84.oneOverRadii.y; const oneOverRadiiY = e.oneOverRadii.y;
const oneOverRadiiZ = WGS84.oneOverRadii.z; const oneOverRadiiZ = e.oneOverRadii.z;
const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX; const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY; const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ; const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
@@ -91,9 +126,9 @@ export function scaleToGeodeticSurface(p) {
if (squaredNorm < CENTER_TOLERANCE_SQUARED) if (squaredNorm < CENTER_TOLERANCE_SQUARED)
return Number.isFinite(ratio) ? intersection : null; return Number.isFinite(ratio) ? intersection : null;
const oneOverRadiiSquaredX = WGS84.oneOverRadiiSquared.x; const oneOverRadiiSquaredX = e.oneOverRadiiSquared.x;
const oneOverRadiiSquaredY = WGS84.oneOverRadiiSquared.y; const oneOverRadiiSquaredY = e.oneOverRadiiSquared.y;
const oneOverRadiiSquaredZ = WGS84.oneOverRadiiSquared.z; const oneOverRadiiSquaredZ = e.oneOverRadiiSquared.z;
const gradient = vec( const gradient = vec(
intersection.x * oneOverRadiiSquaredX * 2.0, intersection.x * oneOverRadiiSquaredX * 2.0,
intersection.y * oneOverRadiiSquaredY * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0,
@@ -130,11 +165,14 @@ export function scaleToGeodeticSurface(p) {
); );
} }
/** ECEF to geodetic `{lon, lat}` radians and `height` metres, or null at the centre. */ /**
export function toCartographicRadians(p) { * ECEF to geodetic `{lon, lat}` radians and `height` metres, or null at the
const surface = scaleToGeodeticSurface(p); * centre; on `ellipsoid` (from `ellipsoidOf`) when given, else WGS84.
*/
export function toCartographicRadians(p, ellipsoid) {
const surface = scaleToGeodeticSurface(p, ellipsoid);
if (!surface) return null; if (!surface) return null;
const n = geodeticSurfaceNormal(surface); const n = geodeticSurfaceNormal(surface, ellipsoid);
const h = sub(p, surface); const h = sub(p, surface);
return { return {
lon: Math.atan2(n.y, n.x), lon: Math.atan2(n.y, n.x),
@@ -143,21 +181,23 @@ export function toCartographicRadians(p) {
}; };
} }
/** ECEF to `{lon, lat}` degrees and `height` metres. */ /** ECEF to `{lon, lat}` degrees and `height` metres, on `ellipsoid` as `toCartographicRadians`. */
export function toLonLatH(p) { export function toLonLatH(p, ellipsoid) {
const c = toCartographicRadians(p); const c = toCartographicRadians(p, ellipsoid);
if (!c) return null; if (!c) return null;
return { lon: toDegrees(c.lon), lat: toDegrees(c.lat), height: c.height }; return { lon: toDegrees(c.lon), lat: toDegrees(c.lat), height: c.height };
} }
/** /**
* Where a ray first meets the ellipsoid ahead of its origin, as Cesium's * Where a ray first meets the ellipsoid ahead of its origin, as Cesium's
* `camera.pickEllipsoid` takes the hit, or null when it misses. * `camera.pickEllipsoid` takes the hit, or null when it misses; on
* `ellipsoid` (from `ellipsoidOf`) when given, else WGS84.
* @param {{origin: {x: number, y: number, z: number}, * @param {{origin: {x: number, y: number, z: number},
* direction: {x: number, y: number, z: number}}} ray * direction: {x: number, y: number, z: number}}} ray
* @param {typeof WGS84} [ellipsoid]
*/ */
export function rayEllipsoid(ray) { export function rayEllipsoid(ray, ellipsoid) {
const r = WGS84.oneOverRadii; const r = ellipsoidArg(ellipsoid).oneOverRadii;
const q = vec(ray.origin.x * r.x, ray.origin.y * r.y, ray.origin.z * r.z); const q = vec(ray.origin.x * r.x, ray.origin.y * r.y, ray.origin.z * r.z);
const w = vec( const w = vec(
ray.direction.x * r.x, ray.direction.x * r.x,
+66
View File
@@ -6,9 +6,11 @@ import {
distance, distance,
distanceSquared, distanceSquared,
eastNorthUp, eastNorthUp,
ellipsoidOf,
fromDegrees, fromDegrees,
geodeticSurfaceNormal, geodeticSurfaceNormal,
lerpInto, lerpInto,
offsetEllipsoid,
rayEllipsoid, rayEllipsoid,
scaleToGeodeticSurface, scaleToGeodeticSurface,
toCartographicRadians, toCartographicRadians,
@@ -245,3 +247,67 @@ test('in-place vector helpers match the default renderer bit for bit', () => {
{ ...Cesium.Cartesian3.lerp(ca, cb, 0.25, new Cesium.Cartesian3()) }, { ...Cesium.Cartesian3.lerp(ca, cb, 0.25, new Cesium.Cartesian3()) },
); );
}); });
test('on another ellipsoid, rays and geodetic positions match the default renderer’s', () => {
const rand = random(7);
for (const metres of [1600, -1000, 30]) {
const ours = offsetEllipsoid(metres);
const theirs = new Cesium.Ellipsoid(
Cesium.Ellipsoid.WGS84.radii.x + metres,
Cesium.Ellipsoid.WGS84.radii.y + metres,
Cesium.Ellipsoid.WGS84.radii.z + metres,
);
for (let i = 0; i < 200; i++) {
const origin = Cesium.Cartesian3.fromDegrees(
rand() * 360 - 180,
rand() * 170 - 85,
100 + rand() * 2e5,
);
const target = Cesium.Cartesian3.fromDegrees(
rand() * 360 - 180,
rand() * 170 - 85,
);
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(target, origin, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const ray = new Cesium.Ray(origin, direction);
const span = Cesium.IntersectionTests.rayEllipsoid(ray, theirs);
const hit = rayEllipsoid({ origin, direction }, ours);
if (!span) {
assert.equal(hit, null);
continue;
}
const expected = Cesium.Ray.getPoint(
ray,
span.start > 0 ? span.start : span.stop,
);
assert.ok(distance(hit, expected) < 1e-3, `ray ${i} at ${metres} m`);
const carto = Cesium.Cartographic.fromCartesian(expected, theirs);
const deg = toLonLatH(expected, ours);
assert.ok(Math.abs(deg.lon - toDegrees(carto.longitude)) < 1e-9);
assert.ok(Math.abs(deg.lat - toDegrees(carto.latitude)) < 1e-9);
assert.ok(Math.abs(deg.height - carto.height) < 1e-3);
}
}
});
test('an ellipsoid argument that is not one (a map index) means WGS84', () => {
const p = fromDegrees(10, 20, 30);
assert.deepEqual(toLonLatH(p, 1), toLonLatH(p));
assert.deepEqual(
rayEllipsoid(
{ origin: { x: 1e7, y: 0, z: 0 }, direction: { x: -1, y: 0, z: 0 } },
0,
),
rayEllipsoid({
origin: { x: 1e7, y: 0, z: 0 },
direction: { x: -1, y: 0, z: 0 },
}),
);
assert.deepEqual(ellipsoidOf({ x: 1, y: 2, z: 4 }).oneOverRadiiSquared, {
x: 1,
y: 0.25,
z: 0.0625,
});
});
+5 -3
View File
@@ -8,10 +8,12 @@ import { WGS84 } from './ellipsoid.js';
/** /**
* A horizon test from `eye` (ECEF): `isPointVisible(p)` is false for a * A horizon test from `eye` (ECEF): `isPointVisible(p)` is false for a
* point the ellipsoid hides from it. * point the ellipsoid hides from it. `ellipsoid` (from `ellipsoidOf`) puts
* the horizon on another surface, as the occluder takes one.
*/ */
export function horizonFrom(eye) { export function horizonFrom(eye, ellipsoid) {
const o = WGS84.oneOverRadii; // Anything but an ellipsoid (a map index, say) means WGS84.
const o = (ellipsoid?.oneOverRadii ? ellipsoid : WGS84).oneOverRadii;
const cx = eye.x * o.x; const cx = eye.x * o.x;
const cy = eye.y * o.y; const cy = eye.y * o.y;
const cz = eye.z * o.z; const cz = eye.z * o.z;
+31 -1
View File
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import test from 'node:test'; import test from 'node:test';
import { fromDegrees } from './ellipsoid.js'; import { fromDegrees, offsetEllipsoid } from './ellipsoid.js';
import { horizonFrom } from './horizon.js'; import { horizonFrom } from './horizon.js';
test('the horizon hides what the default renderer’s occluder hides', () => { test('the horizon hides what the default renderer’s occluder hides', () => {
@@ -31,3 +31,33 @@ test('the horizon hides what the default renderer’s occluder hides', () => {
} }
} }
}); });
test('a horizon on a lowered ellipsoid hides what the occluder on it hides', () => {
let seed = 11;
const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const radii = Cesium.Ellipsoid.WGS84.radii;
const lowered = new Cesium.Ellipsoid(
radii.x - 1000,
radii.y - 1000,
radii.z - 1000,
);
for (let i = 0; i < 30; i++) {
const eye = fromDegrees(
random() * 360 - 180,
random() * 170 - 85,
i === 0 ? -1500 : random() * 2e5 - 500,
);
const occluder = new Cesium.EllipsoidalOccluder(
lowered,
new Cesium.Cartesian3(eye.x, eye.y, eye.z),
);
const horizon = horizonFrom(eye, offsetEllipsoid(-1000));
for (let k = 0; k < 50; k++) {
const p = fromDegrees(random() * 360 - 180, random() * 180 - 90, 0);
assert.equal(
horizon.isPointVisible(p),
occluder.isPointVisible(new Cesium.Cartesian3(p.x, p.y, p.z)),
);
}
}
});
+3
View File
@@ -15,6 +15,9 @@ import {
tn, tn,
} from '../../i18n/index.js'; } from '../../i18n/index.js';
import { createHorizonCull } from '../streetLevel/view.js'; import { createHorizonCull } from '../streetLevel/view.js';
// The horizon cull reads the camera and frame ports: a viewer of a
// caller's own gets them from the unbound factories this loads.
import '../../render/cesium/camera.js';
import { readGhostMapsKml } from './kml.js'; import { readGhostMapsKml } from './kml.js';
import { fieldLabel, parseDescriptionFields, wrapCardText } from './records.js'; import { fieldLabel, parseDescriptionFields, wrapCardText } from './records.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js'; import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
+11 -10
View File
@@ -1,7 +1,6 @@
import * as Cesium from 'cesium';
import { plausibleSurfaceHeight, sampledSurfaceHeight } from './view.js'; import { plausibleSurfaceHeight, sampledSurfaceHeight } from './view.js';
import { heightsFor } from '../../queries/heights.js'; import { toRadians } from '../../geo/index.js';
import { cameraOf } from '../../render/cesium/camera.js'; import { cameraOf, findQuery } from '../../render/rendererOf.js';
/** Fly the globe camera once to frame a photo after it opens. */ /** Fly the globe camera once to frame a photo after it opens. */
export function createCameraFraming({ state }) { export function createCameraFraming({ state }) {
@@ -29,11 +28,13 @@ export function createCameraFraming({ state }) {
* ellipsoid before tiles load, so only a plausible height counts. * ellipsoid before tiles load, so only a plausible height counts.
*/ */
function groundHeightAt(lon, lat, fallback) { function groundHeightAt(lon, lat, fallback) {
const scene = state.viewer?.scene; const viewer = state.viewer;
const carto = Cesium.Cartographic.fromDegrees(lon, lat); const point = { lon, lat };
let height = sampledSurfaceHeight(scene, carto); let height = sampledSurfaceHeight(viewer, point);
if (height === null && scene) if (height === null && viewer)
height = heightsFor(scene).now(carto, { against: 'terrain' }); height =
findQuery(viewer)?.sampleHeightNow(point, { against: 'terrain' }) ??
null;
if (!plausibleSurfaceHeight(height)) height = fallback; if (!plausibleSurfaceHeight(height)) height = fallback;
return plausibleSurfaceHeight(height) ? height : 0; return plausibleSurfaceHeight(height) ? height : 0;
} }
@@ -63,8 +64,8 @@ export function createCameraFraming({ state }) {
}, },
{ {
offset: { offset: {
heading: Cesium.Math.toRadians(bearing || 0), heading: toRadians(bearing || 0),
pitch: Cesium.Math.toRadians(-32), pitch: toRadians(-32),
range: 140, range: 140,
}, },
durationS: 1.6, durationS: 1.6,
+6 -9
View File
@@ -1,11 +1,11 @@
import * as Cesium from 'cesium';
import { GROUND_CLICK_MAX_HEIGHT_M } from './policy.js'; import { GROUND_CLICK_MAX_HEIGHT_M } from './policy.js';
import { cameraHeightAboveGround } from './view.js'; import { cameraHeightAboveGround } from './view.js';
import { toLonLatH } from '../../geo/index.js';
/** Whether the camera is low enough for a click on the ground to mean a street. */ /** Whether the camera is low enough for a click on the ground to mean a street. */
export function groundClickHeightOk(viewer) { export function groundClickHeightOk(viewer) {
if (!viewer?.camera?.positionCartographic) return false; const height = cameraHeightAboveGround(viewer);
return cameraHeightAboveGround(viewer) <= GROUND_CLICK_MAX_HEIGHT_M; return height !== null && height <= GROUND_CLICK_MAX_HEIGHT_M;
} }
/** /**
@@ -33,13 +33,10 @@ export function createGroundClick({ state, openNearest, isAvailable }) {
.map((entry) => entry.def.id); .map((entry) => entry.def.id);
if (!providerIds.length) return false; if (!providerIds.length) return false;
const position = scenePick.pickGroundPosition(state.viewer, screenPosition); const position = scenePick.pickGroundPosition(state.viewer, screenPosition);
const carto = position && Cesium.Cartographic.fromCartesian(position); const ground = position && toLonLatH(position);
if (!carto) return false; if (!ground) return false;
return openNearest( return openNearest(
{ { lon: ground.lon, lat: ground.lat },
lon: Cesium.Math.toDegrees(carto.longitude),
lat: Cesium.Math.toDegrees(carto.latitude),
},
{ providerIds, frame: false }, { providerIds, frame: false },
); );
}; };
+15 -8
View File
@@ -3,10 +3,16 @@ import test from 'node:test';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { createGroundClick, groundClickHeightOk } from './groundClick.js'; import { createGroundClick, groundClickHeightOk } from './groundClick.js';
import * as scenePick from '../../data/scenePick.js'; import * as scenePick from '../../data/scenePick.js';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
import { streetPorts } from '../../testSupport/streetLevelFakes.mjs';
const GROUND = Cesium.Cartesian3.fromDegrees(-121.4944, 38.5816, 10); const GROUND = Cesium.Cartesian3.fromDegrees(-121.4944, 38.5816, 10);
const TILESET = { isCesium3DTileset: true }; const TILESET = { isCesium3DTileset: true };
/** A viewer double bound to the camera and query ports, as the app binds its renderer. */
const viewerWith = (viewer) =>
bindFakeCesiumCamera(viewer, streetPorts(viewer));
/** /**
* A layer state with providers `{id, on, groundClick, configured, available}`; * A layer state with providers `{id, on, groundClick, configured, available}`;
* `picked` is where the depth buffer lands, `ellipsoid` the fallback hit. * `picked` is where the depth buffer lands, `ellipsoid` the fallback hit.
@@ -39,7 +45,7 @@ function harness({
], ],
), ),
), ),
viewer: { viewer: viewerWith({
scene: { pickPositionSupported: true, pickPosition: () => picked }, scene: { pickPositionSupported: true, pickPosition: () => picked },
camera: { camera: {
pickEllipsoid: () => ellipsoid, pickEllipsoid: () => ellipsoid,
@@ -49,7 +55,7 @@ function harness({
height, height,
), ),
}, },
}, }),
}; };
const openAtGround = createGroundClick({ const openAtGround = createGroundClick({
state, state,
@@ -120,12 +126,13 @@ test('nothing opens over another layer’s object, the sky, from high up, off it
}); });
test('street zoom is measured above the ground under the camera', () => { test('street zoom is measured above the ground under the camera', () => {
const viewer = (height) => ({ const viewer = (height) =>
camera: { viewerWith({
positionCartographic: Cesium.Cartographic.fromDegrees(0, 0, height), camera: {
}, positionCartographic: Cesium.Cartographic.fromDegrees(0, 0, height),
scene: { globe: { getHeight: () => 1500 } }, },
}); scene: { globe: { getHeight: () => 1500 } },
});
// 1,500 m up a plateau, 2,000 m above it: still a street. // 1,500 m up a plateau, 2,000 m above it: still a street.
assert.equal(groundClickHeightOk(viewer(3500)), true); assert.equal(groundClickHeightOk(viewer(3500)), true);
assert.equal(groundClickHeightOk(viewer(5000)), false); assert.equal(groundClickHeightOk(viewer(5000)), false);
+12 -18
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { createState } from './state.js'; import { createState } from './state.js';
import { createMarker } from './marker.js'; import { createMarker } from './marker.js';
import { createCameraFraming } from './cameraFraming.js'; import { createCameraFraming } from './cameraFraming.js';
@@ -14,7 +13,9 @@ import {
keyAlternatives, keyAlternatives,
summarizeCoverage, summarizeCoverage,
} from './uiState.js'; } from './uiState.js';
import { groundUnderCamera, viewCentre } from './view.js'; import { canvasSize, groundUnderCamera, viewCentre } from './view.js';
import { toLonLatH } from '../../geo/index.js';
import { findCamera } from '../../render/rendererOf.js';
import { createGroundClick, groundClickHeightOk } from './groundClick.js'; import { createGroundClick, groundClickHeightOk } from './groundClick.js';
import { msg, t, translateKnown } from '../../i18n/index.js'; import { msg, t, translateKnown } from '../../i18n/index.js';
import { import {
@@ -38,7 +39,9 @@ const GROUND_RETRY_MS = 1000;
* The core owns what they share: the filter and switches, the photo viewer * The core owns what they share: the filter and switches, the photo viewer
* host, the position marker, the click handler and nearest-image lookups. * host, the position marker, the click handler and nearest-image lookups.
* Providers own coverage, sequences and their viewer. One source is lit at * Providers own coverage, sequences and their viewer. One source is lit at
* a time. * a time. It reaches the camera, queries and frames through the renderer's
* ports; given a Cesium viewer with no renderer bound,
* the caller loads the package's `./render/cesium/unbound` export first.
* @param {{providers: Array<import('./registry.js').StreetLevelProvider>, services?: object}} options * @param {{providers: Array<import('./registry.js').StreetLevelProvider>, services?: object}} options
*/ */
export function createStreetLevelLayer({ export function createStreetLevelLayer({
@@ -209,7 +212,7 @@ export function createStreetLevelLayer({
function watchCamera(viewer) { function watchCamera(viewer) {
removeCameraListener?.(); removeCameraListener?.();
removeCameraListener = removeCameraListener =
viewer?.camera?.moveEnd?.addEventListener(remeasureGround) || null; (viewer && findCamera(viewer)?.on('moveEnd', remeasureGround)) || null;
} }
const activeEntries = () => const activeEntries = () =>
@@ -257,21 +260,12 @@ export function createStreetLevelLayer({
/** Ground under the screen centre; null for sky, undefined when it cannot aim. */ /** Ground under the screen centre; null for sky, undefined when it cannot aim. */
function screenCentreGround() { function screenCentreGround() {
const canvas = state.viewer?.scene?.canvas; const { width, height } = canvasSize(state.viewer);
const pick = state.services.scenePick?.pickGroundPosition; const pick = state.services.scenePick?.pickGroundPosition;
if (!pick || !canvas?.clientWidth || !canvas?.clientHeight) if (!pick || !width || !height) return undefined;
return undefined; const position = pick(state.viewer, { x: width / 2, y: height / 2 });
const position = pick(state.viewer, { const ground = position && toLonLatH(position);
x: canvas.clientWidth / 2, return ground ? { lon: ground.lon, lat: ground.lat } : null;
y: canvas.clientHeight / 2,
});
const carto = position && Cesium.Cartographic.fromCartesian(position);
return carto
? {
lon: Cesium.Math.toDegrees(carto.longitude),
lat: Cesium.Math.toDegrees(carto.latitude),
}
: null;
} }
/** `frame: false` keeps the camera where it is (the user picked the spot). */ /** `frame: false` keeps the camera where it is (the user picked the spot). */
+4 -2
View File
@@ -12,6 +12,7 @@ import {
fakeMapillarySource, fakeMapillarySource,
fakePhotoViewer, fakePhotoViewer,
fakeStreetLevelProvider as fakeProvider, fakeStreetLevelProvider as fakeProvider,
streetPorts,
} from '../../testSupport/streetLevelFakes.mjs'; } from '../../testSupport/streetLevelFakes.mjs';
import { setLocale } from '../../i18n/index.js'; import { setLocale } from '../../i18n/index.js';
@@ -331,7 +332,7 @@ function fakeViewer() {
disableRootEvents: true, disableRootEvents: true,
onwheel: null, onwheel: null,
}); });
return bindFakeCesiumCamera({ const viewer = {
credits, credits,
flights, flights,
scene: { scene: {
@@ -363,7 +364,8 @@ function fakeViewer() {
if (at !== -1) credits.splice(at, 1); if (at !== -1) credits.splice(at, 1);
}, },
}, },
}); };
return bindFakeCesiumCamera(viewer, streetPorts(viewer));
} }
/** A layer over `providers`, initialised and enabled on a stand-in viewer. */ /** A layer over `providers`, initialised and enabled on a stand-in viewer. */
+5 -3
View File
@@ -3,6 +3,7 @@ import { passesImageryFilter } from './filter.js';
import { groundUnderCamera, viewFocus, visibleBbox } from './view.js'; import { groundUnderCamera, viewFocus, visibleBbox } from './view.js';
import { tilesForBbox } from './tileMath.js'; import { tilesForBbox } from './tileMath.js';
import { msg } from '../../i18n/index.js'; import { msg } from '../../i18n/index.js';
import { findCamera } from '../../render/rendererOf.js';
/** Sequences per primitive: smaller batches build, and show, sooner. */ /** Sequences per primitive: smaller batches build, and show, sooner. */
const SEQUENCE_PRIMITIVE_BATCH = 120; const SEQUENCE_PRIMITIVE_BATCH = 120;
@@ -396,7 +397,7 @@ export function createLineCoverage({
*/ */
function wantedTiles(viewer) { function wantedTiles(viewer) {
const ground = groundUnderCamera(viewer); const ground = groundUnderCamera(viewer);
const cameraHeight = viewer.camera?.positionCartographic?.height; const cameraHeight = findCamera(viewer)?.pose().height;
const height = Number.isFinite(cameraHeight) const height = Number.isFinite(cameraHeight)
? cameraHeight - (ground ?? 0) ? cameraHeight - (ground ?? 0)
: null; : null;
@@ -456,8 +457,9 @@ export function createLineCoverage({
function attach(viewer) { function attach(viewer) {
detach(); detach();
const remove = viewer.camera.changed.addEventListener(scheduleRefresh); const camera = findCamera(viewer);
const removeEnd = viewer.camera.moveEnd.addEventListener(scheduleRefresh); const remove = camera?.on('changed', scheduleRefresh) ?? (() => {});
const removeEnd = camera?.on('moveEnd', scheduleRefresh) ?? (() => {});
state.coverage.removeCameraListener = () => { state.coverage.removeCameraListener = () => {
remove(); remove();
removeEnd(); removeEnd();
+8 -2
View File
@@ -10,7 +10,8 @@ import {
import { resolveFilter } from './filter.js'; import { resolveFilter } from './filter.js';
import { encodeCoverageTile } from './providers/mapillary/coverageFixture.mjs'; import { encodeCoverageTile } from './providers/mapillary/coverageFixture.mjs';
import { decodeCoverageTile } from './providers/mapillary/decode.js'; import { decodeCoverageTile } from './providers/mapillary/decode.js';
import { rayCamera } from '../../testSupport/streetLevelFakes.mjs'; import { rayCamera, streetPorts } from '../../testSupport/streetLevelFakes.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
import { import {
COLORS, COLORS,
COVERAGE_TUNING, COVERAGE_TUNING,
@@ -85,7 +86,7 @@ function tileCentre(lon, lat) {
/** A viewer looking straight down on a 0.004° square around `view`. */ /** A viewer looking straight down on a 0.004° square around `view`. */
function fakeViewer(view) { function fakeViewer(view) {
return { const viewer = {
view, view,
scene: { scene: {
canvas: { clientWidth: 100, clientHeight: 100 }, canvas: { clientWidth: 100, clientHeight: 100 },
@@ -101,6 +102,9 @@ function fakeViewer(view) {
height: view.height, height: view.height,
}; };
}, },
get positionWC() {
return Cesium.Cartesian3.fromDegrees(view.lon, view.lat, view.height);
},
pickEllipsoid(point) { pickEllipsoid(point) {
return Cesium.Cartesian3.fromDegrees( return Cesium.Cartesian3.fromDegrees(
view.lon - 0.002 + (point.x / 100) * 0.004, view.lon - 0.002 + (point.x / 100) * 0.004,
@@ -109,6 +113,8 @@ function fakeViewer(view) {
}, },
}, },
}; };
bindRenderer(viewer, streetPorts(viewer, { camera: true }));
return viewer;
} }
/** A source whose tile requests the test resolves, one call at a time. */ /** A source whose tile requests the test resolves, one call at a time. */
+3
View File
@@ -2,6 +2,8 @@ import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { createMarker } from './marker.js'; import { createMarker } from './marker.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { streetPorts } from '../../testSupport/streetLevelFakes.mjs';
/** A viewer whose camera is 20,000 km over `view`, and its pre-render listeners. */ /** A viewer whose camera is 20,000 km over `view`, and its pre-render listeners. */
function setup() { function setup() {
@@ -23,6 +25,7 @@ function setup() {
}, },
}, },
}; };
bindRenderer(viewer, streetPorts(viewer, { camera: true }));
const state = { const state = {
services: {}, services: {},
viewer, viewer,
@@ -9,7 +9,9 @@ import { validateProviders } from '../../registry.js';
import { import {
fakeMapillarySource, fakeMapillarySource,
rayCamera, rayCamera,
streetPorts,
} from '../../../../testSupport/streetLevelFakes.mjs'; } from '../../../../testSupport/streetLevelFakes.mjs';
import { bindRenderer } from '../../../../render/rendererOf.js';
function fakeContext(filter = { pano: 'all', sinceMs: null }) { function fakeContext(filter = { pano: 'all', sinceMs: null }) {
const opened = []; const opened = [];
@@ -105,7 +107,7 @@ function streetViewer() {
}), }),
{ changed: event(), moveEnd: event() }, { changed: event(), moveEnd: event() },
); );
return { const viewer = {
camera, camera,
scene: { scene: {
canvas: { clientWidth: 100, clientHeight: 100 }, canvas: { clientWidth: 100, clientHeight: 100 },
@@ -117,6 +119,8 @@ function streetViewer() {
requestRender() {}, requestRender() {},
}, },
}; };
bindRenderer(viewer, streetPorts(viewer, { camera: true }));
return viewer;
} }
test('coverage asks for no tiles before the key status is known, and none without a key', async (t) => { test('coverage asks for no tiles before the key status is known, and none without a key', async (t) => {
+3 -8
View File
@@ -1,6 +1,6 @@
import * as Cesium from 'cesium';
import { CLICK_PICK_WINDOW_PX, STREET_LEVEL_LAYER_ID } from './policy.js'; import { CLICK_PICK_WINDOW_PX, STREET_LEVEL_LAYER_ID } from './policy.js';
import { inputFor } from '../../input/dispatcher.js'; import { inputFor } from '../../input/dispatcher.js';
import { toLonLatH } from '../../geo/index.js';
/** One click handler for every provider's lines and cones, and the marker. */ /** One click handler for every provider's lines and cones, and the marker. */
export function createSelection({ state, parts }) { export function createSelection({ state, parts }) {
@@ -33,13 +33,8 @@ export function createSelection({ state, parts }) {
viewer, viewer,
screenPosition, screenPosition,
); );
const carto = position && Cesium.Cartographic.fromCartesian(position); const ground = position && toLonLatH(position);
return carto return ground ? { lon: ground.lon, lat: ground.lat } : null;
? {
lon: Cesium.Math.toDegrees(carto.longitude),
lat: Cesium.Math.toDegrees(carto.latitude),
}
: null;
} }
/** /**
@@ -3,6 +3,8 @@ import test from 'node:test';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { resolveFilter } from './filter.js'; import { resolveFilter } from './filter.js';
import { createSequenceCones, thinImages } from './sequenceCones.js'; import { createSequenceCones, thinImages } from './sequenceCones.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { streetPorts } from '../../testSupport/streetLevelFakes.mjs';
const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
@@ -192,6 +194,7 @@ test('cones behind the globe are hidden, and show again from the other side', as
}, },
}, },
}; };
bindRenderer(state.viewer, streetPorts(state.viewer, { camera: true }));
sequences.select('A'); sequences.select('A');
// One image under the camera, one near its antipode. // One image under the camera, one near its antipode.
source.last('A').resolve([ source.last('A').resolve([
+119 -110
View File
@@ -1,6 +1,18 @@
import * as Cesium from 'cesium';
import { wrapLon } from './tileMath.js'; import { wrapLon } from './tileMath.js';
import { heightsFor } from '../../queries/heights.js'; import {
offsetEllipsoid,
rayEllipsoid,
toLonLatH,
WGS84,
} from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distance } from '../../geo/vector.js';
import {
findCamera,
findFrame,
findQuery,
rendererOf,
} from '../../render/rendererOf.js';
/** Equirectangular metres between {lon, lat} points, the short way round ±180°; street scale. */ /** Equirectangular metres between {lon, lat} points, the short way round ±180°; street scale. */
export function metresBetween(a, b) { export function metresBetween(a, b) {
@@ -17,68 +29,85 @@ export function plausibleSurfaceHeight(height) {
} }
/** /**
* Height (m) of the rendered surface, 3D tiles included, at `carto`; null * Height (m) of the rendered surface, 3D tiles included, at `point`
* when unsampleable or implausible (`sampleHeight` reads kilometres * (`{lon, lat}` degrees); null when unsampleable or implausible
* underground before tiles load). * (`sampleHeight` reads kilometres underground before tiles load).
* `against: 'tiles'` reads the 3D tiles alone.
*/ */
export function sampledSurfaceHeight(scene, carto) { export function sampledSurfaceHeight(viewer, point, { against } = {}) {
const height = scene?.sampleHeightSupported const height =
? heightsFor(scene).now(carto) findQuery(viewer)?.sampleHeightNow(point, against ? { against } : {}) ??
: null; null;
return plausibleSurfaceHeight(height) ? height : null; return plausibleSurfaceHeight(height) ? height : null;
} }
/** The camera's pose, or null without one (or with no position). */
function poseOf(viewer) {
if (!viewer) return null;
const pose = findCamera(viewer)?.pose();
return pose && Number.isFinite(pose.height) ? pose : null;
}
/** /**
* Ellipsoidal height (m) of the ground under the camera, or null. Under * Ellipsoidal height (m) of the ground under the camera, or null. Where 3D
* Google 3D (globe hidden) the rendered surface counts, minus any roof above * tiles answer under the camera (Google 3D) they decide: their surface,
* the camera. * minus any roof above the camera, or null while they are still loading
* (they read kilometres underground then). Elsewhere the loaded terrain,
* else the drawn surface below the camera.
*/ */
export function groundUnderCamera(viewer) { export function groundUnderCamera(viewer) {
const carto = viewer?.camera?.positionCartographic; const pose = poseOf(viewer);
const scene = viewer?.scene; const query = pose && findQuery(viewer);
if (!carto || !scene) return null; if (!query) return null;
const globe = scene.globe; const point = { lon: pose.lon, lat: pose.lat };
if (globe && globe.show !== false) { const tiles = query.sampleHeightNow(point, { against: 'tiles' }) ?? null;
const ground = heightsFor(scene).now(carto, { against: 'terrain' }); if (tiles !== null)
if (ground !== null) return ground; return plausibleSurfaceHeight(tiles) && tiles < pose.height ? tiles : null;
} const terrain = query.sampleHeightNow(point, { against: 'terrain' }) ?? null;
const sampled = sampledSurfaceHeight(scene, carto); if (Number.isFinite(terrain)) return terrain;
return sampled !== null && sampled < carto.height ? sampled : null; const surface = sampledSurfaceHeight(viewer, point);
return surface !== null && surface < pose.height ? surface : null;
} }
/** The ellipsoid `height` metres above `ellipsoid` (the ground at that height). */ /** The ellipsoid `height` metres above WGS84 (the ground at that height). */
function raisedEllipsoid(ellipsoid, height) { function raisedEllipsoid(height) {
if (!Number.isFinite(height) || Math.abs(height) < 1) return ellipsoid; if (!Number.isFinite(height) || Math.abs(height) < 1) return WGS84;
const { x, y, z } = ellipsoid.radii; return offsetEllipsoid(height);
return new Cesium.Ellipsoid(x + height, y + height, z + height); }
/** The CSS size of the canvas the viewer draws on; zeros without one. */
export function canvasSize(viewer) {
const canvas = rendererOf(viewer)?.canvas ?? viewer?.canvas;
return {
width: canvas?.clientWidth || canvas?.width || 0,
height: canvas?.clientHeight || canvas?.height || 0,
};
} }
/** /**
* Where a screen point's ray meets the ground, as a Cartographic, or null. * Where a screen point's ray meets `ellipsoid`, as `{lon, lat}` degrees on
* `maxRange` (metres from the camera) drops hits near the horizon. * it, or null. `maxRange` (metres from the camera) drops hits near the
* horizon.
*/ */
function groundHit(camera, point, ellipsoid, maxRange) { function groundHit(query, x, y, ellipsoid, maxRange) {
let cartesian = null; let ray = null;
try { try {
cartesian = camera.pickEllipsoid(point, ellipsoid); ray = query.pickRay(x, y);
} catch { } catch {
cartesian = null; ray = null;
} }
if (!cartesian) return null; const hit = ray?.origin && ray.direction && rayEllipsoid(ray, ellipsoid);
if ( if (!hit) return null;
Number.isFinite(maxRange) && if (Number.isFinite(maxRange) && distance(hit, ray.origin) > maxRange)
camera.positionWC &&
Cesium.Cartesian3.distance(cartesian, camera.positionWC) > maxRange
)
return null; return null;
return Cesium.Cartographic.fromCartesian(cartesian, ellipsoid) || null; return toLonLatH(hit, ellipsoid);
} }
/** Camera height (m) above the ground under it. */ /** Camera height (m) above the ground under it. */
export function cameraHeightAboveGround(viewer) { export function cameraHeightAboveGround(viewer) {
const carto = viewer?.camera?.positionCartographic; const pose = poseOf(viewer);
if (!carto) return null; if (!pose) return null;
return carto.height - (groundUnderCamera(viewer) ?? 0); return pose.height - (groundUnderCamera(viewer) ?? 0);
} }
/** Screen rays per side, less one, that `visibleBbox` casts. */ /** Screen rays per side, less one, that `visibleBbox` casts. */
@@ -93,24 +122,22 @@ export function visibleBbox(
viewer, viewer,
{ groundHeight = null, maxRange = null } = {}, { groundHeight = null, maxRange = null } = {},
) { ) {
const scene = viewer?.scene; const query = viewer && findQuery(viewer);
const camera = viewer?.camera; if (!query || !poseOf(viewer)) return null;
if (!scene || !camera) return null; const { width, height } = canvasSize(viewer);
const width = scene.canvas?.clientWidth || scene.canvas?.width || 0;
const height = scene.canvas?.clientHeight || scene.canvas?.height || 0;
const hits = []; const hits = [];
if (width > 0 && height > 0) { if (width > 0 && height > 0) {
const ellipsoid = raisedEllipsoid( const ellipsoid = raisedEllipsoid(groundHeight);
scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84,
groundHeight,
);
const point = new Cesium.Cartesian2();
for (let i = 0; i <= BBOX_GRID; i++) { for (let i = 0; i <= BBOX_GRID; i++) {
for (let j = 0; j <= BBOX_GRID; j++) { for (let j = 0; j <= BBOX_GRID; j++) {
point.x = (width * i) / BBOX_GRID; const hit = groundHit(
point.y = (height * j) / BBOX_GRID; query,
const carto = groundHit(camera, point, ellipsoid, maxRange); (width * i) / BBOX_GRID,
if (carto) hits.push(carto); (height * j) / BBOX_GRID,
ellipsoid,
maxRange,
);
if (hit) hits.push(hit);
} }
} }
} }
@@ -119,9 +146,7 @@ export function visibleBbox(
let south = Infinity; let south = Infinity;
let east = -Infinity; let east = -Infinity;
let north = -Infinity; let north = -Infinity;
for (const carto of hits) { for (const { lon, lat } of hits) {
const lon = Cesium.Math.toDegrees(carto.longitude);
const lat = Cesium.Math.toDegrees(carto.latitude);
west = Math.min(west, lon); west = Math.min(west, lon);
east = Math.max(east, lon); east = Math.max(east, lon);
south = Math.min(south, lat); south = Math.min(south, lat);
@@ -133,8 +158,7 @@ export function visibleBbox(
if (east - west > 180) { if (east - west > 180) {
let west360 = Infinity; let west360 = Infinity;
let east360 = -Infinity; let east360 = -Infinity;
for (const carto of hits) { for (const { lon } of hits) {
const lon = Cesium.Math.toDegrees(carto.longitude);
const shifted = lon < 0 ? lon + 360 : lon; const shifted = lon < 0 ? lon + 360 : lon;
west360 = Math.min(west360, shifted); west360 = Math.min(west360, shifted);
east360 = Math.max(east360, shifted); east360 = Math.max(east360, shifted);
@@ -151,12 +175,8 @@ export function visibleBbox(
/** The point on the ground under the camera, as {lon, lat} degrees. */ /** The point on the ground under the camera, as {lon, lat} degrees. */
export function cameraNadir(viewer) { export function cameraNadir(viewer) {
const carto = viewer?.camera?.positionCartographic; const pose = poseOf(viewer);
if (!carto) return null; return pose ? { lon: pose.lon, lat: pose.lat } : null;
return {
lon: Cesium.Math.toDegrees(carto.longitude),
lat: Cesium.Math.toDegrees(carto.latitude),
};
} }
/** /**
@@ -168,24 +188,17 @@ export function viewFocus(
{ groundHeight = null, maxRange = null } = {}, { groundHeight = null, maxRange = null } = {},
) { ) {
const nadir = cameraNadir(viewer); const nadir = cameraNadir(viewer);
const scene = viewer?.scene; const { width, height } = canvasSize(viewer);
const width = scene?.canvas?.clientWidth || scene?.canvas?.width || 0; const query = nadir && findQuery(viewer);
const height = scene?.canvas?.clientHeight || scene?.canvas?.height || 0; if (!nadir || !query || !width || !height) return nadir;
if (!nadir || !width || !height) return nadir; const ahead = groundHit(
const hit = groundHit( query,
viewer.camera, width / 2,
new Cesium.Cartesian2(width / 2, height / 2), height / 2,
raisedEllipsoid( raisedEllipsoid(groundHeight),
scene.globe?.ellipsoid || Cesium.Ellipsoid.WGS84,
groundHeight,
),
maxRange, maxRange,
); );
if (!hit) return nadir; if (!ahead) return nadir;
const ahead = {
lon: Cesium.Math.toDegrees(hit.longitude),
lat: Cesium.Math.toDegrees(hit.latitude),
};
return { return {
lon: wrapLon(nadir.lon + wrapLon(ahead.lon - nadir.lon) / 2), lon: wrapLon(nadir.lon + wrapLon(ahead.lon - nadir.lon) / 2),
lat: (nadir.lat + ahead.lat) / 2, lat: (nadir.lat + ahead.lat) / 2,
@@ -197,60 +210,60 @@ export function viewFocus(
* (NYC −22 m), and an occluder at 0 m would hide the cones around it. * (NYC −22 m), and an occluder at 0 m would hide the cones around it.
*/ */
const HORIZON_CULL_DEPTH_M = 1000; const HORIZON_CULL_DEPTH_M = 1000;
const HORIZON_CULL_ELLIPSOID = new Cesium.Ellipsoid( const HORIZON_CULL_ELLIPSOID = offsetEllipsoid(-HORIZON_CULL_DEPTH_M);
Cesium.Ellipsoid.WGS84.radii.x - HORIZON_CULL_DEPTH_M,
Cesium.Ellipsoid.WGS84.radii.y - HORIZON_CULL_DEPTH_M,
Cesium.Ellipsoid.WGS84.radii.z - HORIZON_CULL_DEPTH_M,
);
/** /**
* Hide billboards and points behind the horizon: they skip the depth test, so * Hide markers behind the horizon: they skip the depth test, so nothing
* nothing else stops the far side drawing through the globe. Re-culls on * else stops the far side drawing through the globe. Re-culls before a
* pre-render after the camera moves; stops when nothing is left to cull. * frame draws after the camera moves; stops when nothing is left to cull.
* @param {{getViewer: () => object|null, items: () => Iterable<{position: object, show: boolean}>, onChange?: () => void}} options * Items are `{position, show}` (`position` ECEF); `onChange` hears the
* items whose `show` it changed.
* @param {{getViewer: () => object|null, items: () => Iterable<{position: {x: number, y: number, z: number}, show: boolean}>, onChange?: (changed: object[]) => void}} options
*/ */
export function createHorizonCull({ getViewer, items, onChange }) { export function createHorizonCull({ getViewer, items, onChange }) {
const occluder = new Cesium.EllipsoidalOccluder(HORIZON_CULL_ELLIPSOID);
let from = null; let from = null;
let stopListening = null; let stopListening = null;
/** Show what is in front of the horizon, hide the rest; the count seen. */ /** Show what is in front of the horizon, hide the rest; the count seen. */
function cull(list, position) { function cull(list, position) {
occluder.cameraPosition = position; const horizon = horizonFrom(position, HORIZON_CULL_ELLIPSOID);
let seen = 0; let seen = 0;
let changed = false; const changed = [];
for (const item of list) { for (const item of list) {
seen++; seen++;
const show = occluder.isPointVisible(item.position); const show = horizon.isPointVisible(item.position);
if (item.show !== show) { if (item.show !== show) {
item.show = show; item.show = show;
changed = true; changed.push(item);
} }
} }
if (changed) onChange?.(); if (changed.length) onChange?.(changed);
return seen; return seen;
} }
/** Cull everything from the camera at `position`; the count seen. */ /** Cull everything from the camera at `position`; the count seen. */
function cullAll(position) { function cullAll(position) {
from = Cesium.Cartesian3.clone(position, from); from = { x: position.x, y: position.y, z: position.z };
return cull(items(), position); return cull(items(), position);
} }
const eyeOf = (viewer) => (viewer ? poseOf(viewer)?.position : null) ?? null;
const same = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;
function onPreRender() { function onPreRender() {
const position = getViewer()?.camera?.positionWC; const position = eyeOf(getViewer());
if (!position || (from && Cesium.Cartesian3.equals(from, position))) return; if (!position || (from && same(from, position))) return;
if (!cullAll(position)) stop(); if (!cullAll(position)) stop();
} }
/** Cull `added` items (or all) now, then all again whenever the camera moves. */ /** Cull `added` items (or all) now, then all again whenever the camera moves. */
function update(added) { function update(added) {
const viewer = getViewer(); const viewer = getViewer();
const position = viewer?.camera?.positionWC; const position = eyeOf(viewer);
if (position && !(added ? cull(added, position) : cullAll(position))) if (position && !(added ? cull(added, position) : cullAll(position)))
return; return;
stopListening ||= stopListening ||=
viewer?.scene?.preRender?.addEventListener(onPreRender) || null; (viewer && findFrame(viewer)?.on('preRender', onPreRender)) || null;
} }
function stop() { function stop() {
@@ -273,10 +286,6 @@ export function viewCentre(viewer) {
if (lon > 180) lon -= 360; if (lon > 180) lon -= 360;
return { lat: (bbox[1] + bbox[3]) / 2, lon }; return { lat: (bbox[1] + bbox[3]) / 2, lon };
} }
const carto = viewer.camera?.positionCartographic; const pose = poseOf(viewer);
if (!carto) return null; return pose ? { lat: pose.lat, lon: pose.lon } : null;
return {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
};
} }
+87 -45
View File
@@ -10,12 +10,14 @@ import {
visibleBbox, visibleBbox,
} from './view.js'; } from './view.js';
import { latToTileY, lonToTileX, tilesForBbox } from './tileMath.js'; import { latToTileY, lonToTileX, tilesForBbox } from './tileMath.js';
import { rayCamera } from '../../testSupport/streetLevelFakes.mjs'; import { rayCamera, streetPorts } from '../../testSupport/streetLevelFakes.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
const RAD = Math.PI / 180; const RAD = Math.PI / 180;
/** A viewer 300 m above a street 1,600 m up (Denver-like). */ /** A viewer 300 m above a street 1,600 m up (Denver-like). */
function viewer({ globeShown, globeHeight }) { function viewer({ globeShown, globeHeight }) {
return { const view = {
camera: { camera: {
positionCartographic: { positionCartographic: {
longitude: -104.99 * RAD, longitude: -104.99 * RAD,
@@ -25,6 +27,7 @@ function viewer({ globeShown, globeHeight }) {
}, },
scene: { globe: { show: globeShown, getHeight: () => globeHeight } }, scene: { globe: { show: globeShown, getHeight: () => globeHeight } },
}; };
return bindFakeCesiumCamera(view, streetPorts(view));
} }
test('a shown globe answers the ground under the camera', () => { test('a shown globe answers the ground under the camera', () => {
@@ -34,22 +37,23 @@ test('a shown globe answers the ground under the camera', () => {
); );
}); });
test('a hidden globe (Google 3D) or a missing sample gives no ground', () => { test('without 3D tiles under the camera the terrain answers; a missing sample gives no ground', () => {
// A hidden globe's getHeight is ignored even when it returns a number. // No tiles drawn there: the terrain answers, globe shown or hidden.
assert.equal( assert.equal(
groundUnderCamera(viewer({ globeShown: false, globeHeight: 0 })), groundUnderCamera(viewer({ globeShown: false, globeHeight: 0 })),
null, 0,
); );
assert.equal( assert.equal(
groundUnderCamera(viewer({ globeShown: true, globeHeight: undefined })), groundUnderCamera(viewer({ globeShown: true, globeHeight: undefined })),
null, null,
); );
assert.equal(groundUnderCamera({}), null); assert.equal(groundUnderCamera({}), null);
assert.equal(groundUnderCamera(null), null);
}); });
/** The Denver viewer with Google 3D: no globe, a sampleable rendered surface. */ /** The Denver viewer with Google 3D: no globe, a sampleable rendered surface. */
function google3d(sample) { function google3d(sample) {
const view = viewer({ globeShown: false, globeHeight: 0 }); const view = viewer({ globeShown: false, globeHeight: undefined });
view.scene.sampleHeightSupported = true; view.scene.sampleHeightSupported = true;
view.scene.sampleHeight = () => sample; view.scene.sampleHeight = () => sample;
return view; return view;
@@ -59,6 +63,22 @@ test('on Google 3D the rendered surface answers the ground under the camera', ()
assert.equal(groundUnderCamera(google3d(1612)), 1612); assert.equal(groundUnderCamera(google3d(1612)), 1612);
}); });
test('where the 3D tiles answer, they decide, whatever the terrain says', () => {
const view = google3d(1612);
// A hidden globe's terrain can be stale (or the bare ellipsoid's 0).
view.scene.globe.getHeight = () => 0;
assert.equal(groundUnderCamera(view), 1612);
// A roof above the camera is not the ground, and tiles still loading
// (kilometres underground) are not either: unknown, so measured again.
view.scene.sampleHeight = () => 1950;
assert.equal(groundUnderCamera(view), null);
view.scene.sampleHeight = () => -14_886;
assert.equal(groundUnderCamera(view), null);
// No tiles there at all: the terrain answers.
view.scene.sampleHeight = () => undefined;
assert.equal(groundUnderCamera(view), 0);
});
test('an implausible or above-camera surface sample gives no ground', () => { test('an implausible or above-camera surface sample gives no ground', () => {
// Before tiles stream in, sampleHeight can read kilometres underground. // Before tiles stream in, sampleHeight can read kilometres underground.
assert.equal(groundUnderCamera(google3d(-14_886)), null); assert.equal(groundUnderCamera(google3d(-14_886)), null);
@@ -70,17 +90,29 @@ test('an implausible or above-camera surface sample gives no ground', () => {
/** A camera whose screen rays land on a grid of lon/lat points. */ /** A camera whose screen rays land on a grid of lon/lat points. */
function gridViewer(lons, lats) { function gridViewer(lons, lats) {
const points = []; const points = [];
for (const lat of lats) for (const lat of lats) for (const lon of lons) points.push([lon, lat]);
for (const lon of lons)
points.push(Cesium.Cartesian3.fromDegrees(lon, lat));
let next = 0; let next = 0;
return { const viewer = {};
scene: { canvas: { clientWidth: 100, clientHeight: 100 }, globe: {} }, bindRenderer(viewer, {
canvas: { clientWidth: 100, clientHeight: 100 },
camera: { camera: {
pickEllipsoid: () => points[next++ % points.length], pose: () => ({ lon: 0, lat: 0, height: 1000 }),
positionCartographic: { longitude: 0, latitude: 0, height: 1000 },
}, },
}; query: {
// Straight down onto the next grid point, from 1 km above it.
pickRay() {
const [lon, lat] = points[next++ % points.length];
const origin = Cesium.Cartesian3.fromDegrees(lon, lat, 1000);
const ground = Cesium.Cartesian3.fromDegrees(lon, lat);
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(ground, origin, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
return { origin, direction };
},
},
});
return viewer;
} }
test('a view across the date line is a narrow box with west > east', () => { test('a view across the date line is a narrow box with west > east', () => {
@@ -97,7 +129,7 @@ test('an ordinary view keeps west < east', () => {
/** A pinhole viewer `agl` m above ground `ground` m up, looking north. */ /** A pinhole viewer `agl` m above ground `ground` m up, looking north. */
function pinhole({ lon, lat, ground, agl, pitch, w = 1600, h = 900 }) { function pinhole({ lon, lat, ground, agl, pitch, w = 1600, h = 900 }) {
return { const view = {
scene: { scene: {
canvas: { clientWidth: w, clientHeight: h }, canvas: { clientWidth: w, clientHeight: h },
globe: { show: false, ellipsoid: Cesium.Ellipsoid.WGS84 }, globe: { show: false, ellipsoid: Cesium.Ellipsoid.WGS84 },
@@ -111,6 +143,7 @@ function pinhole({ lon, lat, ground, agl, pitch, w = 1600, h = 900 }) {
height: h, height: h,
}), }),
}; };
return bindFakeCesiumCamera(view, streetPorts(view));
} }
test('a tilted street view over high ground boxes the streets it looks at, not the horizon', () => { test('a tilted street view over high ground boxes the streets it looks at, not the horizon', () => {
@@ -236,49 +269,49 @@ test('metresBetween measures the short way round the date line', () => {
/** /**
* A horizon cull over `items` for a camera the test moves, with the frame's * A horizon cull over `items` for a camera the test moves, with the frame's
* pre-render listeners and a count of the points tested against the horizon. * pre-render listeners and a count of the camera poses read.
*/ */
function cullHarness(t, items) { function cullHarness(t, items) {
const visible = t.mock.method(
Cesium.EllipsoidalOccluder.prototype,
'isPointVisible',
);
const preRender = new Set(); const preRender = new Set();
const camera = { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1e7) }; let eye = Cesium.Cartesian3.fromDegrees(0, 0, 1e7);
const viewer = { let poses = 0;
camera, const viewer = {};
scene: { bindRenderer(viewer, {
preRender: { camera: {
addEventListener(listener) { pose: () => {
preRender.add(listener); poses++;
return () => preRender.delete(listener); return { lon: 0, lat: 0, height: 1e7, position: { ...eye } };
},
}, },
}, },
}; frame: {
on(phase, listener) {
assert.equal(phase, 'preRender');
preRender.add(listener);
return () => preRender.delete(listener);
},
},
});
// Items handed to a cull pass: what a still camera must not test again.
const tested = { count: 0 };
let changes = 0; let changes = 0;
const cull = createHorizonCull({ const cull = createHorizonCull({
getViewer: () => viewer, getViewer: () => viewer,
items: () => items, items: () => {
tested.count += items.length;
return items;
},
onChange: () => changes++, onChange: () => changes++,
}); });
return { return {
cull, cull,
preRender, preRender,
tested: () => visible.mock.callCount(), poses: () => poses,
tested: () => tested.count,
changes: () => changes, changes: () => changes,
frame: () => { frame: () => {
for (const listener of [...preRender]) listener(); for (const listener of [...preRender]) listener();
}, },
// Moved in place, as Cesium updates positionWC. moveTo: (lon, lat) => (eye = Cesium.Cartesian3.fromDegrees(lon, lat, 1e7)),
moveTo: (lon, lat) =>
Cesium.Cartesian3.fromDegrees(
lon,
lat,
1e7,
undefined,
camera.positionWC,
),
}; };
} }
@@ -337,11 +370,20 @@ function cullFrom(camera, points) {
position: Cesium.Cartesian3.fromDegrees(lon, lat, height), position: Cesium.Cartesian3.fromDegrees(lon, lat, height),
show: true, show: true,
})); }));
const viewer = {};
bindRenderer(viewer, {
camera: {
pose: () => ({
lon: camera[0],
lat: camera[1],
height: camera[2],
position: Cesium.Cartesian3.fromDegrees(...camera),
}),
},
frame: { on: () => () => {} },
});
const horizon = createHorizonCull({ const horizon = createHorizonCull({
getViewer: () => ({ getViewer: () => viewer,
camera: { positionWC: Cesium.Cartesian3.fromDegrees(...camera) },
scene: { preRender: { addEventListener: () => () => {} } },
}),
items: () => items, items: () => items,
}); });
horizon.update(); horizon.update();
-5
View File
@@ -86,14 +86,9 @@
"src/layers/satellites/state.js", "src/layers/satellites/state.js",
"src/layers/satellites/testing.js", "src/layers/satellites/testing.js",
"src/layers/satellites/tracking.js", "src/layers/satellites/tracking.js",
"src/layers/streetLevel/cameraFraming.js",
"src/layers/streetLevel/groundClick.js",
"src/layers/streetLevel/index.js",
"src/layers/streetLevel/lineCoverage.js", "src/layers/streetLevel/lineCoverage.js",
"src/layers/streetLevel/marker.js", "src/layers/streetLevel/marker.js",
"src/layers/streetLevel/selection.js",
"src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/view.js",
"src/layers/traffic/animation.js", "src/layers/traffic/animation.js",
"src/layers/traffic/lifecycle.js", "src/layers/traffic/lifecycle.js",
"src/layers/traffic/rendering.js", "src/layers/traffic/rendering.js",
+4
View File
@@ -79,6 +79,10 @@ const DRAW_FROM_CALLER = new Set([
'./layers/submarine-cables', './layers/submarine-cables',
'./layers/alpr', './layers/alpr',
'./layers/vessels', './layers/vessels',
'./layers/street-level',
'./layers/street-level/mapillary',
'./layers/street-level/kartaview',
'./layers/street-level/panoramax',
]); ]);
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
+103 -16
View File
@@ -191,7 +191,7 @@ export function fakeCesiumViewer({ view = false } = {}) {
}, },
}, },
); );
return bindFakeCesiumCamera({ const viewer = {
credits, credits,
flights, flights,
scene: { scene: {
@@ -212,7 +212,8 @@ export function fakeCesiumViewer({ view = false } = {}) {
if (at !== -1) credits.splice(at, 1); if (at !== -1) credits.splice(at, 1);
}, },
}, },
}); };
return bindFakeCesiumCamera(viewer, streetPorts(viewer));
} }
/** /**
@@ -249,23 +250,27 @@ export function rayCamera({
const halfY = Math.tan((fovY / 2) * RAD); const halfY = Math.tan((fovY / 2) * RAD);
const halfX = const halfX =
fovX == null ? halfY * (width / height) : Math.tan((fovX / 2) * RAD); fovX == null ? halfY * (width / height) : Math.tan((fovX / 2) * RAD);
/** The ray through a screen point, as the query port's `pickRay`. */
function pickRay(x, y) {
const sx = ((2 * x) / width - 1) * halfX;
const sy = (1 - (2 * y) / height) * halfY;
const local = [0, 1, 2].map((i) => forward[i] + sx * right[i] + sy * up[i]);
const direction = Cesium.Cartesian3.normalize(
Cesium.Matrix4.multiplyByPointAsVector(
frame,
new Cesium.Cartesian3(...local),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
return { origin: position, direction };
}
return { return {
positionWC: position, positionWC: position,
positionCartographic: Cesium.Cartographic.fromDegrees(lon, lat, altitude), positionCartographic: Cesium.Cartographic.fromDegrees(lon, lat, altitude),
pickRay,
pickEllipsoid(point, ellipsoid = Cesium.Ellipsoid.WGS84) { pickEllipsoid(point, ellipsoid = Cesium.Ellipsoid.WGS84) {
const sx = ((2 * point.x) / width - 1) * halfX; const { direction } = pickRay(point.x, point.y);
const sy = (1 - (2 * point.y) / height) * halfY;
const local = [0, 1, 2].map(
(i) => forward[i] + sx * right[i] + sy * up[i],
);
const direction = Cesium.Cartesian3.normalize(
Cesium.Matrix4.multiplyByPointAsVector(
frame,
new Cesium.Cartesian3(...local),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const ray = new Cesium.Ray(position, direction); const ray = new Cesium.Ray(position, direction);
const hit = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid); const hit = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
return hit ? Cesium.Ray.getPoint(ray, hit.start) : undefined; return hit ? Cesium.Ray.getPoint(ray, hit.start) : undefined;
@@ -273,6 +278,87 @@ export function rayCamera({
}; };
} }
/**
* The query, frame and canvas a Street Level layer reads, answered from a
* Cesium-shaped viewer double: rays from its camera's `pickRay` (else
* through what its `pickEllipsoid` hits), heights from its scene's
* `sampleHeight` (3D tiles: only while its globe is hidden) and its
* globe's `getHeight` (terrain), and pre-render from its scene's
* `preRender`. `draw` adds a draw port. For `bindFakeCesiumCamera`'s
* `ports`.
* @param {object} viewer
* @param {{draw?: object}} [options]
*/
export function streetPorts(viewer, { draw, camera = false } = {}) {
const finite = (height) => (Number.isFinite(height) ? height : null);
const cartographic = ({ lon, lat }) => ({
longitude: lon * RAD,
latitude: lat * RAD,
height: 0,
});
return {
get canvas() {
return viewer.scene?.canvas;
},
query: {
pickRay(x, y) {
const camera = viewer.camera ?? {};
if (camera.pickRay) return camera.pickRay(x, y);
const hit = camera.pickEllipsoid?.({ x, y });
const origin = camera.positionWC;
if (!hit || !origin) return null;
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(hit, origin, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
return { origin, direction };
},
sampleHeightNow(point, { against = 'surface' } = {}) {
const scene = viewer.scene ?? {};
if (against === 'terrain')
return finite(scene.globe?.getHeight?.(cartographic(point)));
if (!scene.sampleHeightSupported) return null;
if (against === 'tiles' && scene.globe?.show !== false) return null;
return finite(scene.sampleHeight?.(cartographic(point)));
},
},
frame: {
on(phase, cb) {
const event = viewer.scene?.[phase];
return event?.addEventListener?.(cb) ?? (() => {});
},
},
...(draw ? { draw } : {}),
...(camera ? { camera: liveCamera(viewer) } : {}),
};
}
/**
* A camera port over whatever camera double `viewer.camera` is when asked
* (tests swap it): its pose from `positionCartographic` and `positionWC`,
* its events from the double's own `changed` and `moveEnd`.
*/
export function liveCamera(viewer) {
return {
pose() {
const camera = viewer.camera ?? {};
const p = camera.positionWC;
const c =
camera.positionCartographic ??
(p && Cesium.Cartographic.fromCartesian(p));
return {
lon: c ? c.longitude / RAD : NaN,
lat: c ? c.latitude / RAD : NaN,
height: c ? c.height : NaN,
position: p ? { x: p.x, y: p.y, z: p.z } : null,
};
},
on(event, cb) {
return viewer.camera?.[event]?.addEventListener?.(cb) ?? (() => {});
},
};
}
/** The centre of the tile holding a point at zoom `z`, so a small view is one tile. */ /** The centre of the tile holding a point at zoom `z`, so a small view is one tile. */
export function tileCentre(lon, lat, z = 14) { export function tileCentre(lon, lat, z = 14) {
const x = lonToTileX(lon, z); const x = lonToTileX(lon, z);
@@ -325,7 +411,7 @@ export function coverageViewer(view, t) {
}, },
}; };
}; };
return { const viewer = {
view, view,
scene: { scene: {
canvas: { clientWidth: 100, clientHeight: 100 }, canvas: { clientWidth: 100, clientHeight: 100 },
@@ -360,4 +446,5 @@ export function coverageViewer(view, t) {
computeViewRectangle: () => undefined, computeViewRectangle: () => undefined,
}, },
}; };
return bindFakeCesiumCamera(viewer, streetPorts(viewer));
} }