Ease street traffic heights through the query and camera ports

Height easing projects waypoints through the query port and keeps them
beyond the camera's near plane from its pose, instead of the Cesium view
matrix and scene transforms. Point maths uses new allocation-free geo
helpers (distanceSquared, copyInto, lerpInto), which road selection now
shares. Retention leaves the Cesium allow-list.
This commit is contained in:
Sameh Khamis committed 2026-11-07 00:09:10 -08:00
1 parent ecaa965b69
commit 0933ff49ff
7 files changed
+328 -89

No files matched your search

+36
View File
@@ -2,10 +2,13 @@ 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 { import {
copyInto,
distance, distance,
distanceSquared,
eastNorthUp, eastNorthUp,
fromDegrees, fromDegrees,
geodeticSurfaceNormal, geodeticSurfaceNormal,
lerpInto,
rayEllipsoid, rayEllipsoid,
scaleToGeodeticSurface, scaleToGeodeticSurface,
toCartographicRadians, toCartographicRadians,
@@ -209,3 +212,36 @@ test('a ray meets the ellipsoid where Cesium picks it', () => {
} }
assert.ok(misses > 0 && misses < 200, 'hits and misses both tried'); assert.ok(misses > 0 && misses < 200, 'hits and misses both tried');
}); });
test('in-place vector helpers match the default renderer bit for bit', () => {
const a = fromDegrees(-97.7431, 30.2672, 151.25);
const b = fromDegrees(-97.7402, 30.2691, 180.5);
const ca = new Cesium.Cartesian3(a.x, a.y, a.z);
const cb = new Cesium.Cartesian3(b.x, b.y, b.z);
assert.equal(
distanceSquared(a, b),
Cesium.Cartesian3.distanceSquared(ca, cb),
);
assert.equal(
Math.sqrt(distanceSquared(a, b)),
Cesium.Cartesian3.distance(ca, cb),
);
for (const t of [0, 0.137, 0.5, 1]) {
const out = { x: 0, y: 0, z: 0 };
assert.equal(lerpInto(a, b, t, out), out);
assert.deepEqual(
{ ...out },
{ ...Cesium.Cartesian3.lerp(ca, cb, t, new Cesium.Cartesian3()) },
);
}
const into = { x: 1, y: 2, z: 3 };
assert.equal(copyInto(a, into), into);
assert.deepEqual(into, { x: a.x, y: a.y, z: a.z });
// In place: lerping a point toward a target writes over it safely.
const p = { ...a };
lerpInto(p, b, 0.25, p);
assert.deepEqual(
{ ...p },
{ ...Cesium.Cartesian3.lerp(ca, cb, 0.25, new Cesium.Cartesian3()) },
);
});
+24
View File
@@ -20,6 +20,30 @@ export const cross = (a, b) =>
export const magnitude = (a) => Math.sqrt(dot(a, a)); export const magnitude = (a) => Math.sqrt(dot(a, a));
/** Straight-line (chord) distance, not along the surface. */ /** Straight-line (chord) distance, not along the surface. */
export const distance = (a, b) => magnitude(sub(a, b)); export const distance = (a, b) => magnitude(sub(a, b));
/**
* The squared chord distance, allocating nothing: what per-frame code
* compares and, through `Math.sqrt`, measures with (bit for bit `distance`).
*/
export function distanceSquared(a, b) {
const x = a.x - b.x,
y = a.y - b.y,
z = a.z - b.z;
return x * x + y * y + z * z;
}
/** Write `from` into `out` and return it. */
export function copyInto(from, out) {
out.x = from.x;
out.y = from.y;
out.z = from.z;
return out;
}
/** Linear interpolation from `a` (t = 0) to `b` (t = 1), written into `out`. */
export function lerpInto(a, b, t, out) {
out.x = (1 - t) * a.x + t * b.x;
out.y = (1 - t) * a.y + t * b.y;
out.z = (1 - t) * a.z + t * b.z;
return out;
}
export function normalize(a) { export function normalize(a) {
const m = magnitude(a); const m = magnitude(a);
return vec(a.x / m, a.y / m, a.z / m); return vec(a.x / m, a.y / m, a.z / m);
+21 -3
View File
@@ -6,6 +6,7 @@ import { createFlow } from './flow.js';
import { createRetention } from './retention.js'; import { createRetention } from './retention.js';
import { createControls } from './controls.js'; import { createControls } from './controls.js';
import { createState } from './state.js'; import { createState } from './state.js';
import { bindRenderer } from '../../render/rendererOf.js';
const bounds = { west: 0, east: 0.01, south: 0, north: 0.01 }; const bounds = { west: 0, east: 0.01, south: 0, north: 0.01 };
const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); }; const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); };
@@ -75,6 +76,23 @@ test('superseding a stalled pass aborts promptly without clearing newer loading'
clearTimeout(h.state._retryTimer); clearTimeout(h.state._retryTimer);
}); });
// The camera-plane scenes below, as the renderer's ports see them: the eye
// and the near plane, and window positions from the scene itself.
const ANGLE = 35 * Math.PI / 180;
function portView(scene) {
const viewer = { scene };
const position = { x: 0, y: 0, z: 450 };
const direction = { x: 0, y: Math.cos(ANGLE), z: -Math.sin(ANGLE) };
bindRenderer(viewer, {
camera: { pose: () => ({ position: { ...position }, direction: { ...direction }, near: scene.camera.frustum.near }) },
query: { project(p) {
const s = C.SceneTransforms.worldToWindowCoordinates(scene, new C.Cartesian3(p.x, p.y, p.z));
return s ? { x: s.x, y: s.y } : null;
} },
});
return viewer;
}
for (const y of [-175, -200, -300]) test(`off-screen camera-plane height correction settles without holding public loading (${y})`, () => { for (const y of [-175, -200, -300]) test(`off-screen camera-plane height correction settles without holding public loading (${y})`, () => {
const angle = 35 * Math.PI / 180; const angle = 35 * Math.PI / 180;
const scene = { const scene = {
@@ -87,7 +105,7 @@ for (const y of [-175, -200, -300]) test(`off-screen camera-plane height correct
}; };
const point = new C.Cartesian3(0, y, 100), target = new C.Cartesian3(0, y, 197); const point = new C.Cartesian3(0, y, 100), target = new C.Cartesian3(0, y, 197);
const state = createState({ services: {} }); const state = createState({ services: {} });
Object.assign(state, { _viewer: { scene }, _roads: [{ heightMoving: true, waypoints: [point], targetWaypoints: [target], segmentDist: [] }] }); Object.assign(state, { _viewer: portView(scene), _roads: [{ heightMoving: true, waypoints: [point], targetWaypoints: [target], segmentDist: [] }] });
const retention = createRetention({ state, parts: {} }); const retention = createRetention({ state, parts: {} });
retention.easeHeights(1 / 60); retention.easeHeights(1 / 60);
const controls = createControls({ state, services: {}, source: { getFlowSessionStats: () => ({}) }, parts: { model: { trafficFeedPresentation: () => ({}) } } }); const controls = createControls({ state, services: {}, source: { getFlowSessionStats: () => ({}) }, parts: { model: { trafficFeedPresentation: () => ({}) } } });
@@ -111,7 +129,7 @@ test('visible corrections use the pixel limit without the off-screen world-speed
frustum: new C.PerspectiveFrustum({ fov: Math.PI / 3, aspectRatio: 1.6, near: 1, far: 1e7 }) }, frustum: new C.PerspectiveFrustum({ fov: Math.PI / 3, aspectRatio: 1.6, near: 1, far: 1e7 }) },
}; };
const point = new C.Cartesian3(0, 1000, 0), target = new C.Cartesian3(0, 1000, 300); const point = new C.Cartesian3(0, 1000, 0), target = new C.Cartesian3(0, 1000, 300);
const state = { _viewer: { scene }, _roads: [{ heightMoving: true, waypoints: [point], targetWaypoints: [target], segmentDist: [] }] }; const state = { _viewer: portView(scene), _roads: [{ heightMoving: true, waypoints: [point], targetWaypoints: [target], segmentDist: [] }] };
const retention = createRetention({ state, parts: {} }); const retention = createRetention({ state, parts: {} });
let loadingFrames = 0, maxPixels = 0; let loadingFrames = 0, maxPixels = 0;
for (let frame = 0; frame < 180; frame++) { for (let frame = 0; frame < 180; frame++) {
@@ -137,7 +155,7 @@ for (const targetHeight of [200, 2000]) test(`visible height steps stay pixel-li
frustum: new C.PerspectiveFrustum({ fov: Math.PI / 3, aspectRatio: 1.6, near: 1, far: 1e7 }) }, frustum: new C.PerspectiveFrustum({ fov: Math.PI / 3, aspectRatio: 1.6, near: 1, far: 1e7 }) },
}; };
const point = new C.Cartesian3(0, 50, 400), target = new C.Cartesian3(0, 50, targetHeight); const point = new C.Cartesian3(0, 50, 400), target = new C.Cartesian3(0, 50, targetHeight);
const state = { _viewer: { scene }, _roads: [{ heightMoving: true, waypoints: [point], targetWaypoints: [target], segmentDist: [] }] }; const state = { _viewer: portView(scene), _roads: [{ heightMoving: true, waypoints: [point], targetWaypoints: [target], segmentDist: [] }] };
const before = C.SceneTransforms.worldToWindowCoordinates(scene, point); const before = C.SceneTransforms.worldToWindowCoordinates(scene, point);
assert.ok(before.y > 0 && before.y < 800); assert.ok(before.y > 0 && before.y < 800);
const trial = C.Cartesian3.lerp(point, target, 0.2, new C.Cartesian3()); const trial = C.Cartesian3.lerp(point, target, 0.2, new C.Cartesian3());
+4 -17
View File
@@ -1,6 +1,6 @@
import { roadIdentity } from './retention.js'; import { roadIdentity } from './retention.js';
import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js'; import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js';
import { distance, dot, sub } from '../../geo/vector.js'; import { copyInto, distance, distanceSquared } from '../../geo/vector.js';
import { findCamera, findQuery } from '../../render/rendererOf.js'; import { findCamera, findQuery } from '../../render/rendererOf.js';
import { import {
prepareRoadSurfaces, prepareRoadSurfaces,
@@ -16,19 +16,6 @@ import {
import { msg } from '../../i18n/index.js'; import { msg } from '../../i18n/index.js';
import { nextTask } from '../../sources/vectorTiles.js'; import { nextTask } from '../../sources/vectorTiles.js';
/** Squared straight-line distance, as the default renderer computes it. */
function distanceSquared(a, b) {
const d = sub(a, b);
return dot(d, d);
}
/** Copy `from`'s coordinates into the point `to`, in place. */
function copyPoint(from, to) {
to.x = from.x;
to.y = from.y;
to.z = from.z;
}
export function createFlow({ state: layerState, services, parts, source }) { export function createFlow({ state: layerState, services, parts, source }) {
const { registerDynamicCredit, TOMTOM_CREDIT } = services.credits; const { registerDynamicCredit, TOMTOM_CREDIT } = services.credits;
const { fetchFlowForBounds } = source; const { fetchFlowForBounds } = source;
@@ -314,7 +301,7 @@ export function createFlow({ state: layerState, services, parts, source }) {
const prepared = !refining && preparedRoads.get(road.key); const prepared = !refining && preparedRoads.get(road.key);
if (prepared) { if (prepared) {
for (let i = 0; i < road.waypoints.length; i++) for (let i = 0; i < road.waypoints.length; i++)
copyPoint(prepared.waypoints[i], road.waypoints[i]); copyInto(prepared.waypoints[i], road.waypoints[i]);
} else if ( } else if (
(!road.surfaceReady || refining) && (!road.surfaceReady || refining) &&
(localHeights.length || depthHeight !== undefined) (localHeights.length || depthHeight !== undefined)
@@ -330,7 +317,7 @@ export function createFlow({ state: layerState, services, parts, source }) {
Number.isFinite(floor) && Math.abs(floor) <= 9000 Number.isFinite(floor) && Math.abs(floor) <= 9000
? Math.max(floor, layerState._viewHeightEstimate) ? Math.max(floor, layerState._viewHeightEstimate)
: layerState._viewHeightEstimate; : layerState._viewHeightEstimate;
copyPoint( copyInto(
fromDegrees(lon, lat, height + DOT_HEIGHT_OFFSET), fromDegrees(lon, lat, height + DOT_HEIGHT_OFFSET),
road.waypoints[i], road.waypoints[i],
); );
@@ -442,7 +429,7 @@ export function createFlow({ state: layerState, services, parts, source }) {
const prepared = !refining && preparedRoads.get(road.key); const prepared = !refining && preparedRoads.get(road.key);
if (prepared) { if (prepared) {
for (let i = 0; i < road.waypoints.length; i++) for (let i = 0; i < road.waypoints.length; i++)
copyPoint(prepared.waypoints[i], road.waypoints[i]); copyInto(prepared.waypoints[i], road.waypoints[i]);
for (let i = 0; i < road.segmentDist.length; i++) for (let i = 0; i < road.segmentDist.length; i++)
road.segmentDist[i] = prepared.segmentDist[i]; road.segmentDist[i] = prepared.segmentDist[i];
road.surfaceReady = true; road.surfaceReady = true;
+158 -12
View File
@@ -6,6 +6,8 @@ import { createStyle } from './style.js';
import { createModel } from './model.js'; import { createModel } from './model.js';
import { createAnimation } from './animation.js'; import { createAnimation } from './animation.js';
import { DOT_HEIGHT_OFFSET } from './policy.js'; import { DOT_HEIGHT_OFFSET } from './policy.js';
import { bindRenderer } from '../../render/rendererOf.js';
import '../../render/cesium/camera.js';
import { import {
createRetention, createRetention,
DOT_CHANGE_BUDGET, DOT_CHANGE_BUDGET,
@@ -597,23 +599,31 @@ test('a closure that empties the population mid-correction settles heights and c
assert.equal(h.state._renderHeld, false); assert.equal(h.state._renderHeld, false);
}); });
test('large height corrections obey a screen-pixel bound and reuse projection scratch objects', (t) => { test('large height corrections obey a screen-pixel bound through the query port', (t) => {
const h = setup(t); const h = setup(t);
h.state._viewer.scene = { h.state._viewer.scene = {
canvas: { clientWidth: 1280, clientHeight: 2000 }, canvas: { clientWidth: 1280, clientHeight: 2000 },
camera: {}, camera: {},
frameState: {}, frameState: {},
}; };
const scratch = new Set(); // The eye at the earth's centre looking out through the roads, so every
t.mock.method( // waypoint is beyond the near plane; window y is ten pixels a metre.
C.SceneTransforms, t.after(
'worldToWindowCoordinates', bindRenderer(h.state._viewer, {
(_scene, point, result) => { camera: {
scratch.add(result); pose: () => ({
result.x = 0; position: { x: 0, y: 0, z: 0 },
result.y = C.Cartographic.fromCartesian(point).height * 10; direction: { x: 1, y: 0, z: 0 },
return result; near: 1,
}, }),
},
query: {
project(point) {
const p = new C.Cartesian3(point.x, point.y, point.z);
return { x: 0, y: C.Cartographic.fromCartesian(p).height * 10 };
},
},
}),
); );
h.parts.retention.reconcile(h.roads(), 450, true); h.parts.retention.reconcile(h.roads(), 450, true);
h.settle(); h.settle();
@@ -632,7 +642,6 @@ test('large height corrections obey a screen-pixel bound and reuse projection sc
); );
assert.equal(dot.id, id); assert.equal(dot.id, id);
assert.equal(h.state._heightPending, false); assert.equal(h.state._heightPending, false);
assert.equal(scratch.size, 2);
}); });
test('grounded vehicles respect mesh occlusion even after live congestion changes', (t) => { test('grounded vehicles respect mesh occlusion even after live congestion changes', (t) => {
@@ -801,3 +810,140 @@ test('selection asks the query port for depth and screen positions, and the came
unbind(); unbind();
} }
}); });
test('height easing stops visible waypoints at the camera near plane', () => {
const viewer = {
scene: {
canvas: { clientWidth: 1000, clientHeight: 800 },
camera: {},
frameState: {},
},
};
// Every point projects to the same pixel, so only the near plane can stop
// a step: the eye at the origin looks along +x with its near plane at 1.
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({
position: { x: 0, y: 0, z: 0 },
direction: { x: 1, y: 0, z: 0 },
near: 1,
}),
},
query: { project: () => ({ x: 10, y: 10 }) },
});
try {
const point = { x: 100, y: 0, z: 0 };
const state = {
_viewer: viewer,
_roads: [
{
heightMoving: true,
waypoints: [point],
targetWaypoints: [{ x: -100, y: 0, z: 0 }],
segmentDist: [],
},
],
};
const retention = createRetention({ state, parts: {} });
for (let frame = 0; frame < 120; frame++) retention.easeHeights(1 / 60);
assert.ok(point.x > 1, `stopped short of the near plane at ${point.x}`);
assert.ok(point.x < 2, 'but eased up to it');
assert.equal(state._heightPending, true);
} finally {
unbind();
}
});
/** A scene with a real camera, which the Cesium camera and query ports read. */
function cesiumScene() {
const scene = {
canvas: { clientWidth: 1280, clientHeight: 800, width: 1280, height: 800 },
drawingBufferWidth: 1280,
drawingBufferHeight: 800,
mapProjection: new C.GeographicProjection(),
mode: C.SceneMode.SCENE3D,
frameState: { mode: C.SceneMode.SCENE3D },
pick: () => undefined,
drillPick: () => [],
};
for (const name of ['preUpdate', 'preRender', 'postRender', 'postUpdate'])
scene[name] = new C.Event();
scene.camera = new C.Camera(scene);
scene.camera.frustum.near = 1;
scene.camera.frustum.aspectRatio = 1.6;
return scene;
}
test('height easing through the Cesium ports stops at the near plane of a looked-at camera', () => {
const scene = cesiumScene();
const centre = C.Cartesian3.fromDegrees(0, 0, 0);
// A transformed camera: lookAt leaves the camera in the target's frame.
scene.camera.lookAt(centre, new C.HeadingPitchRange(0, -0.5, 600));
const viewer = { scene, camera: scene.camera };
const eyeDepth = (p) =>
-C.Matrix4.multiplyByPoint(scene.camera.viewMatrix, p, new C.Cartesian3())
.z;
// Along the view ray through the eye: the point stays at the canvas
// centre, so only the near plane can stop it.
const { positionWC: eye, directionWC: ahead } = scene.camera;
const along = (metres) =>
C.Cartesian3.add(
eye,
C.Cartesian3.multiplyByScalar(ahead, metres, new C.Cartesian3()),
new C.Cartesian3(),
);
const point = along(300);
const target = along(-300);
assert.ok(eyeDepth(point) > 1 && eyeDepth(target) < 1);
const state = {
_viewer: viewer,
_roads: [
{
heightMoving: true,
waypoints: [point],
targetWaypoints: [target],
segmentDist: [],
},
],
};
const retention = createRetention({ state, parts: {} });
let maxPixels = 0;
for (let frame = 0; frame < 240; frame++) {
const before = C.SceneTransforms.worldToWindowCoordinates(scene, point);
retention.easeHeights(1 / 60);
const after = C.SceneTransforms.worldToWindowCoordinates(scene, point);
if (before && after)
maxPixels = Math.max(maxPixels, C.Cartesian2.distance(before, after));
assert.ok(
eyeDepth(point) > 1,
`frame ${frame} stays beyond the near plane`,
);
}
assert.ok(maxPixels <= 12.01, `${maxPixels} px a frame`);
assert.ok(
eyeDepth(point) < 3,
`eased up to the near plane: ${eyeDepth(point)}`,
);
assert.equal(state._heightPending, true);
});
test('height easing without a query port moves at the world-speed cap', () => {
const scene = {
canvas: { clientWidth: 1280, clientHeight: 800 },
};
const point = { x: 0, y: 0, z: 0 };
const state = {
_viewer: { scene },
_roads: [
{
heightMoving: true,
waypoints: [point],
targetWaypoints: [{ x: 0, y: 0, z: 100 }],
segmentDist: [],
},
],
};
createRetention({ state, parts: {} }).easeHeights(1 / 60);
assert.ok(Math.abs(point.z - 2) < 1e-9, `${point.z} m, 120 m/s for a frame`);
assert.equal(state._heightPending, true);
});
+85 -56
View File
@@ -1,4 +1,10 @@
import * as Cesium from 'cesium'; import {
copyInto,
distanceSquared,
equalsEpsilon,
lerpInto,
} from '../../geo/vector.js';
import { findCamera, findQuery } from '../../render/rendererOf.js';
import { MAX_DOTS, roadDotBudget } from './policy.js'; import { MAX_DOTS, roadDotBudget } from './policy.js';
export const DOT_CHANGE_BUDGET = 768; export const DOT_CHANGE_BUDGET = 768;
@@ -12,31 +18,41 @@ export function roadIdentity(road) {
/** Retain one road and its dot population across tile and surface publications. */ /** Retain one road and its dot population across tile and surface publications. */
export function createRetention({ state, parts }) { export function createRetention({ state, parts }) {
const records = new Map(); const records = new Map();
const heightStep = new Cesium.Cartesian3(); const heightStep = { x: 0, y: 0, z: 0 };
const screenFrom = new Cesium.Cartesian2(); const near = (a, b) =>
const screenTo = new Cesium.Cartesian2(); equalsEpsilon(a.x, b.x, 0.01) &&
const eye = new Cesium.Cartesian3(); equalsEpsilon(a.y, b.y, 0.01) &&
function projectSafely(scene, point, screen) { equalsEpsilon(a.z, b.z, 0.01);
if (scene.camera.viewMatrix) { const pointDistance = (a, b) => Math.sqrt(distanceSquared(a, b));
Cesium.Matrix4.multiplyByPoint(scene.camera.viewMatrix, point, eye); /**
if (eye.z >= -(scene.camera.frustum?.near || 0)) return false; * A point's window position, or null when it is on or behind the near
* plane (where a projection folds back onto the screen) or does not
* project.
*/
function projectSafely(view, point) {
const { pose, query } = view;
if (pose) {
const { position: eye, direction: d } = pose;
const depth =
d.x * (point.x - eye.x) +
d.y * (point.y - eye.y) +
d.z * (point.z - eye.z);
if (depth <= (pose.near || 0)) return null;
} }
return ( const screen = query.project(point);
Boolean( return screen && Number.isFinite(screen.x) && Number.isFinite(screen.y)
Cesium.SceneTransforms.worldToWindowCoordinates(scene, point, screen), ? screen
) && : null;
Number.isFinite(screen.x) &&
Number.isFinite(screen.y)
);
} }
function nearCanvas(scene, point, screen) { function nearCanvas(view, point) {
return ( const screen = projectSafely(view, point);
projectSafely(scene, point, screen) && return screen &&
screen.x >= -100 && screen.x >= -100 &&
screen.x <= scene.canvas.clientWidth + 100 && screen.x <= view.width + 100 &&
screen.y >= -100 && screen.y >= -100 &&
screen.y <= scene.canvas.clientHeight + 100 screen.y <= view.height + 100
); ? screen
: null;
} }
let timer = null; let timer = null;
let altitude = 0; let altitude = 0;
@@ -139,12 +155,14 @@ export function createRetention({ state, parts }) {
// so an asynchronous height pass cannot move half a road in one frame. // so an asynchronous height pass cannot move half a road in one frame.
const road = { const road = {
...candidate, ...candidate,
waypoints: candidate.waypoints.map((p) => Cesium.Cartesian3.clone(p)), waypoints: candidate.waypoints.map(({ x, y, z }) => ({ x, y, z })),
segmentDist: candidate.segmentDist.slice(), segmentDist: candidate.segmentDist.slice(),
source: candidate, source: candidate,
targetWaypoints: candidate.waypoints.map((p) => targetWaypoints: candidate.waypoints.map(({ x, y, z }) => ({
Cesium.Cartesian3.clone(p), x,
), y,
z,
})),
heightMoving: false, heightMoving: false,
}; };
record = { road, dots: [], target: 0, wanted: true }; record = { road, dots: [], target: 0, wanted: true };
@@ -154,19 +172,12 @@ export function createRetention({ state, parts }) {
record.road.flow = candidate.flow; record.road.flow = candidate.flow;
record.road.densityWeight = candidate.densityWeight; record.road.densityWeight = candidate.densityWeight;
for (let i = 0; i < candidate.waypoints.length; i++) { for (let i = 0; i < candidate.waypoints.length; i++) {
if ( const target = record.road.targetWaypoints[i];
!Cesium.Cartesian3.equalsEpsilon( // A waypoint the retained road lacks counts as moved and is not
record.road.targetWaypoints[i], // written, as before.
candidate.waypoints[i], if (!target || !near(target, candidate.waypoints[i]))
0,
0.01,
)
)
record.road.heightMoving = state._heightPending = true; record.road.heightMoving = state._heightPending = true;
Cesium.Cartesian3.clone( if (target) copyInto(candidate.waypoints[i], target);
candidate.waypoints[i],
record.road.targetWaypoints[i],
);
} }
} }
record.wanted = true; record.wanted = true;
@@ -189,11 +200,27 @@ export function createRetention({ state, parts }) {
if (!state._dots.length && timer === null) pump(); if (!state._dots.length && timer === null) pump();
else schedule(); else schedule();
} }
/**
* What height easing reads of the view once a frame: the canvas size, the
* query port to project with and the camera pose for the near plane. Null
* when nothing can be projected yet.
*/
function frameView() {
const viewer = state._viewer;
const scene = viewer?.scene;
if (!scene?.canvas?.clientHeight) return null;
const query = findQuery(viewer);
if (!query) return null;
return {
query,
pose: findCamera(viewer)?.pose() ?? null,
width: scene.canvas.clientWidth,
height: scene.canvas.clientHeight,
};
}
function easeHeights(dt) { function easeHeights(dt) {
const blend = Math.min(1, dt * 12); const blend = Math.min(1, dt * 12);
const scene = state._viewer?.scene; let view;
const canProject =
scene?.canvas?.clientHeight && scene.camera && scene.frameState;
state._heightPending = false; state._heightPending = false;
for (let r = 0; r < state._roads.length; r++) { for (let r = 0; r < state._roads.length; r++) {
const road = state._roads[r]; const road = state._roads[r];
@@ -202,25 +229,27 @@ export function createRetention({ state, parts }) {
for (let i = 0; i < road.waypoints.length; i++) { for (let i = 0; i < road.waypoints.length; i++) {
const point = road.waypoints[i], const point = road.waypoints[i],
target = road.targetWaypoints[i]; target = road.targetWaypoints[i];
if (Cesium.Cartesian3.distanceSquared(point, target) < 0.0001) if (distanceSquared(point, target) < 0.0001) copyInto(target, point);
Cesium.Cartesian3.clone(target, point);
else { else {
const visible = canProject && nearCanvas(scene, point, screenFrom); if (view === undefined) view = frameView();
const screenFrom = view && nearCanvas(view, point);
const visible = Boolean(screenFrom);
let step = visible let step = visible
? blend ? blend
: Math.min( : Math.min(blend, (120 * dt) / pointDistance(point, target));
blend,
(120 * dt) / Cesium.Cartesian3.distance(point, target),
);
if (visible) { if (visible) {
let safe = false; let safe = false;
for (let attempt = 0; attempt < 16; attempt++) { for (let attempt = 0; attempt < 16; attempt++) {
Cesium.Cartesian3.lerp(point, target, step, heightStep); lerpInto(point, target, step, heightStep);
if (!projectSafely(scene, heightStep, screenTo)) { const screenTo = projectSafely(view, heightStep);
if (!screenTo) {
step *= 0.5; step *= 0.5;
continue; continue;
} }
const pixels = Cesium.Cartesian2.distance(screenFrom, screenTo); const pixels = Math.hypot(
screenFrom.x - screenTo.x,
screenFrom.y - screenTo.y,
);
if (pixels <= 12) { if (pixels <= 12) {
safe = true; safe = true;
break; break;
@@ -229,13 +258,13 @@ export function createRetention({ state, parts }) {
} }
if (!safe) step = 0; if (!safe) step = 0;
} }
state._heightPending ||= !canProject || visible; state._heightPending ||= !view || visible;
Cesium.Cartesian3.lerp(point, target, step, point); lerpInto(point, target, step, point);
moving = true; moving = true;
} }
} }
for (let i = 0; i < road.segmentDist.length; i++) for (let i = 0; i < road.segmentDist.length; i++)
road.segmentDist[i] = Cesium.Cartesian3.distance( road.segmentDist[i] = pointDistance(
road.waypoints[i], road.waypoints[i],
road.waypoints[i + 1], road.waypoints[i + 1],
); );
@@ -255,9 +284,9 @@ export function createRetention({ state, parts }) {
for (const road of roads) { for (const road of roads) {
if (!road.heightMoving) continue; if (!road.heightMoving) continue;
for (let i = 0; i < road.waypoints.length; i++) for (let i = 0; i < road.waypoints.length; i++)
Cesium.Cartesian3.clone(road.targetWaypoints[i], road.waypoints[i]); copyInto(road.targetWaypoints[i], road.waypoints[i]);
for (let i = 0; i < road.segmentDist.length; i++) for (let i = 0; i < road.segmentDist.length; i++)
road.segmentDist[i] = Cesium.Cartesian3.distance( road.segmentDist[i] = pointDistance(
road.waypoints[i], road.waypoints[i],
road.waypoints[i + 1], road.waypoints[i + 1],
); );
-1
View File
@@ -97,7 +97,6 @@
"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",
"src/layers/traffic/retention.js",
"src/layers/traffic/style.js", "src/layers/traffic/style.js",
"src/layers/traffic/surface.js", "src/layers/traffic/surface.js",
"src/layers/transit/height.js", "src/layers/transit/height.js",