Animate traffic on the frame port and follow the camera through the camera port

The traffic lifecycle listens on the frame port's preRender and on the
camera port's changed (at its own 5% threshold) and moveEnd, instead of
the scene's preRender, the camera's events and the shared
percentageChanged ledger. It no longer reaches Cesium and leaves the
allow-list; rendering.js, still listed for the surface identity, tile
readiness and draped-line support, now loads the unbound camera and
globe factories for the layer.
This commit is contained in:
Sameh Khamis committed 2026-11-07 23:16:11 -08:00
1 parent 5715bf9df3
commit 38e0750715
11 files changed
+163 -46

No files matched your search

+4 -3
View File
@@ -1041,7 +1041,7 @@ The view pass reruns while the camera moves, paced by its own cost. The camera
picker lists the cameras in view, active camera first, and closes with the
count of cameras outside the view.
Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and caches surface identity without allocating on unchanged frames.
Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and caches surface identity without allocating on unchanged frames. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger; only the surface identity, tile readiness and draped-line support are still read off the Cesium scene.
Traffic and bikeshare expose factories through `./layers/traffic` and
`./layers/bikeshare`. Traffic separates road requests, ingestion, animation,
@@ -6277,8 +6277,9 @@ on it.
Every failed read cancels its body and aborts its owned request, including
declared and streaming byte-cap failures.
- Development captures opened with `?trafficDebug=1` mint an interaction anchor
from the exact `camera.changed` event that arms each debounced load, then emit
scheduling-correlated User Timing entries for production `response.json`, road
from the exact camera-port `changed` event that arms each debounced load,
then emit scheduling-correlated User Timing entries for production
`response.json`, road
parse, dot construction, heat-line rebuild, and next-post-render
boundaries. Every trace is paired with the exact camera-change that scheduled
its load; mismatches are counted drops. Cesium's `moveEnd` remains a diagnostic
+3 -2
View File
@@ -117,8 +117,9 @@ async function moveCamera(page, view) {
});
// setView normally propagates through Cesium's render loop. Raising these
// explicitly makes the capture boundary deterministic across GPU speeds.
// Pairing still flows through camera.changed's schedule-time anchor; the
// synthetic moveEnd is emitted only as the same diagnostic used naturally.
// Traffic hears the synthetic moveEnd through the camera port and loads at
// once; the port measures its own `changed` on the next rendered tick, so
// the synthetic camera.changed reaches only the layers still on Cesium.
gev.viewer.camera.changed.raiseEvent();
gev.viewer.camera.moveEnd.raiseEvent();
return { beforeLastUpdate, boundaryTime };
+4 -3
View File
@@ -4,9 +4,10 @@
*
* `camera.changed` fires once the view has moved by this fraction, and it is a
* single number on the camera that every listener in the app shares. Several
* layers want it finer than the default — traffic and transit ask for 0.05 so
* they notice they have entered a coverage area (bikeshare did too, before it
* listened through the renderer's camera port at its own threshold) — and
* layers want it finer than the default — transit asks for 0.05 so it
* notices it has entered a coverage area (bikeshare and traffic did too,
* before they listened through the renderer's camera port at their own
* threshold) — and
* each of them used to write the number directly and hand back whatever it
* remembered.
*
+8
View File
@@ -245,8 +245,16 @@ test('traffic timing pairs real ordering to the scheduling change and guards re-
// The layer reads the camera through the renderer's camera port.
const { bindRenderer } = await server.ssrLoadModule('/src/render/rendererOf.js');
const degrees = (radians) => radians * 180 / Math.PI;
const cameraEvents = { moveEnd, changed };
const frameEvents = { preRender, postRender };
bindRenderer(viewer, {
// The scene's channels, raised by the test as Cesium would.
frame: {
on: (phase, cb) => frameEvents[phase].addEventListener(cb),
requestRender() {},
},
camera: {
on: (event, cb) => cameraEvents[event].addEventListener(cb),
pose: () => ({
lon: degrees(camera.positionCartographic.longitude),
lat: degrees(camera.positionCartographic.latitude),
+23 -26
View File
@@ -1,15 +1,6 @@
import { observeTrafficSurface } from './surface.js';
// Still Cesium for its events, so this layer loads the unbound
// camera factory (with its query port) and globe factory its other parts
// reach the renderer through.
import '../../render/cesium/camera.js';
import '../../render/cesium/globe.js';
import { TRAFFIC_TIMING_ENABLED } from './policy.js';
import { drawOf } from '../../render/rendererOf.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
import { CAMERA_CHANGED_THRESHOLD, TRAFFIC_TIMING_ENABLED } from './policy.js';
import { cameraOf, drawOf, frameOf } from '../../render/rendererOf.js';
/** Numbers each layer instance's draw sets apart. */
let instances = 0;
@@ -89,9 +80,9 @@ export function createLifecycle({
},
/**
* Enable the traffic layer. Shows the point collection, subscribes to the
* preRender animation loop and camera-change events, and kicks off an
* initial viewport check.
* Enable the traffic layer. Shows the dots, subscribes to the frame
* port's preRender for the animation and to the camera port's events,
* and kicks off an initial viewport check.
*
* @param {Cesium.Viewer} viewer - The Cesium viewer instance.
*/
@@ -104,27 +95,33 @@ export function createLifecycle({
layerState._lastAnimTime = 0;
if (layerState._dotSet) layerState._dotSet.show = true;
layerState._preRenderRemover = viewer.scene.preRender.addEventListener(
const camera = cameraOf(viewer);
layerState._preRenderRemover = frameOf(viewer).on(
'preRender',
parts.animation.animate,
);
if (TRAFFIC_TIMING_ENABLED) {
parts.timing.clearTrafficTimingEntries();
layerState._trafficTimingCurrentAnchor = null;
layerState._trafficTimingPostRenderRemovers = new Set();
layerState._trafficTimingMoveEndRemover =
viewer.camera.moveEnd.addEventListener(
parts.timing.markTrafficTimingMoveEnd,
);
layerState._trafficTimingMoveEndRemover = camera.on(
'moveEnd',
parts.timing.markTrafficTimingMoveEnd,
);
}
// Share the 5% movement threshold with other camera-driven layers.
viewer.camera.changed.addEventListener(parts.viewport.onCameraChanged);
// Its own 5% movement threshold: the camera measures it for this
// listener alone.
layerState._cameraRemover = camera.on(
'changed',
() => parts.viewport.onCameraChanged(),
{ threshold: CAMERA_CHANGED_THRESHOLD },
);
// Always inspect the final view, even when the last flight step is below
// camera.changed's movement threshold.
layerState._arrivalRemover = viewer.camera.moveEnd.addEventListener(() =>
// the changed threshold.
layerState._arrivalRemover = camera.on('moveEnd', () =>
parts.viewport.onCameraChanged({ immediate: true }),
);
claimCameraSensitivity(viewer.camera, 'traffic', 0.05);
// Enabling is explicit intent, not a camera gesture that needs settling.
parts.viewport.onCameraChanged({ immediate: true });
@@ -197,10 +194,10 @@ export function createLifecycle({
layerState._trafficTimingCurrentAnchor = null;
}
viewer.camera.changed.removeEventListener(parts.viewport.onCameraChanged);
layerState._cameraRemover?.();
layerState._cameraRemover = null;
layerState._arrivalRemover?.();
layerState._arrivalRemover = null;
releaseCameraSensitivity(viewer.camera, 'traffic');
if (layerState._dotSet) layerState._dotSet.show = false;
},
+79 -2
View File
@@ -3,7 +3,12 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createTrafficLayer } from './index.js';
import { findCamera } from '../../render/rendererOf.js';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
import {
bindFakeCesiumCamera,
fakeCameraPort,
} from '../../testSupport/fakeCameraPort.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
import { createLifecycle } from './lifecycle.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { sceneSurfacePorts } from '../../testSupport/fakeSceneSurface.mjs';
@@ -225,6 +230,75 @@ test('arrival below the camera change threshold loads the final city and unsubsc
assert.equal(viewer.camera.changed.numberOfListeners, ported.changed);
});
test('the layer animates on the frame port and leaves the shared camera threshold alone', async (t) => {
const frames = [];
const frame = {
on(phase, cb) {
const entry = { phase, cb };
frames.push(entry);
return () => frames.splice(frames.indexOf(entry), 1);
},
requestRender() {},
};
const { layer, viewer, tick } = setup(
t,
async (bounds) => roads(bounds),
undefined,
{ frame },
);
layer.enable(viewer);
assert.deepEqual(
frames.map((f) => f.phase),
['preRender'],
);
assert.equal(
viewer.camera.percentageChanged,
0.5,
'the shared threshold is left alone',
);
await tick(400);
layer.disable(viewer);
assert.equal(frames.length, 0);
});
test('the camera tells the layer once the view has moved 5%', (t) => {
const noop = () => {};
const calls = [];
const lifecycle = createLifecycle({
state: { _loadGeneration: 0 },
services: {},
source: {},
parts: {
animation: { animate: noop, clearDots: noop, syncRenderDemand: noop },
viewport: { onCameraChanged: (options) => calls.push(options) },
ingestion: { cancelActiveFetch: noop },
},
}).methods;
const camera = fakeCameraPort({ pose: { height: 1000 } });
const viewer = {};
t.after(
bindRenderer(viewer, {
camera: camera.port,
frame: { on: () => noop, requestRender: noop },
}),
);
t.mock.timers.enable({ apis: ['setInterval'] });
lifecycle.enable(viewer);
calls.length = 0;
camera.stepChanged();
camera.setPose({ position: { x: 30, y: 0, z: 0 } });
camera.stepChanged();
assert.equal(calls.length, 0, '3% is not enough');
camera.setPose({ position: { x: 70, y: 0, z: 0 } });
camera.stepChanged();
assert.deepEqual(calls, [undefined], '7% is, debounced as a camera move');
camera.emit('moveEnd');
assert.deepEqual(calls[1], { immediate: true }, 'arrival is immediate');
lifecycle.disable(viewer);
assert.equal(camera.listenerCount('changed'), 0);
assert.equal(camera.listenerCount('moveEnd'), 0);
});
test('parked failures back off and disabling cancels the scheduled retry', async (t) => {
let calls = 0;
const { layer, viewer, tick } = setup(t, async () => {
@@ -466,8 +540,10 @@ test('partial coverage retries while coarse roads render, then stops after three
test('an unready surface waits for drawn frames through the frame port, then refines once', async (t) => {
const listeners = new Set();
// The drawn frames; the animation runs on preRender.
const frame = {
on(phase, cb) {
if (phase === 'preRender') return () => {};
assert.equal(phase, 'postRender');
listeners.add(cb);
return () => listeners.delete(cb);
@@ -523,7 +599,8 @@ test('an unready surface waits for drawn frames through the frame port, then ref
test('disabling while a refinement waits drops its frame listener', async (t) => {
const listeners = new Set();
const frame = {
on(_phase, cb) {
on(phase, cb) {
if (phase === 'preRender') return () => {};
listeners.add(cb);
return () => listeners.delete(cb);
},
+7
View File
@@ -10,6 +10,13 @@ import { hexColor } from '../../render/color.js';
export const ACTIVATION_ALTITUDE = 8000;
/**
* How far the view moves before the camera tells the layer (the camera's
* `changed` threshold): fine, so it notices entering a coverage area.
*/
export const CAMERA_CHANGED_THRESHOLD = 0.05;
/** @const {number} Meters — above this altitude, only major roads are fetched */
export const FAST_FETCH_ALTITUDE = 4500;
+5
View File
@@ -12,6 +12,11 @@ import {
} from './policy.js';
import { distance } from '../../geo/vector.js';
import { findCamera } from '../../render/rendererOf.js';
// The layer's other parts reach the renderer through the unbound camera
// factory (with its query port) and globe factory, loaded here with the
// adapter this file needs.
import '../../render/cesium/camera.js';
import '../../render/cesium/globe.js';
// What the dots' surface is, and whether it has loaded, the renderer
// contract cannot say: the Cesium adapter reads it off the scene.
import {
+2 -6
View File
@@ -41,11 +41,11 @@ export function createState({ services }) {
layerState._enabled = false;
/** @type {Function|null} Disposer returned by preRender event subscription */
/** @type {Function|null} Disposer of the frame port's preRender listener */
layerState._preRenderRemover = null;
/** @type {Function|null} Disposer returned by camera.changed event subscription */
/** @type {Function|null} Disposers of the camera port's changed and moveEnd listeners */
layerState._cameraRemover = null;
layerState._arrivalRemover = null;
@@ -90,10 +90,6 @@ export function createState({ services }) {
layerState._lastViewCenter = null;
/** @type {number|null} camera.percentageChanged value before we overrode it, restored on disable */
layerState._prevPercentageChanged = null;
/** @type {boolean} Live TomTom flow mode — true iff /api/tomtom/status reports a key */
layerState._liveMode = false;
+28 -3
View File
@@ -3617,7 +3617,7 @@ test('reject then selected history backfill cannot resurrect a 111 km displaceme
assert.equal(entry.track.resets, 0);
});
test('actual Traffic and Transit lifecycles retain sensitivity in every enable/disable order, Bikeshare among them', async (t) => {
test('the actual Transit lifecycle retains its sensitivity in every enable/disable order, Traffic and Bikeshare among them', async (t) => {
const { createLifecycle: trafficLifecycle } =
await import('../traffic/lifecycle.js');
const { createLifecycle: bikeLifecycle } =
@@ -3670,15 +3670,33 @@ test('actual Traffic and Transit lifecycles retain sensitivity in every enable/d
const bikeViewer = {};
const unbindBike = bindRenderer(bikeViewer, { camera: bikeCamera.port });
t.after(unbindBike);
// So does traffic, which animates on its renderer's frame port.
const trafficCamera = fakeCameraPort();
const trafficViewer = {};
const trafficFrames = new Set();
const unbindTraffic = bindRenderer(trafficViewer, {
camera: trafficCamera.port,
frame: {
on(_phase, cb) {
trafficFrames.add(cb);
return () => trafficFrames.delete(cb);
},
requestRender: noop,
},
});
t.after(unbindTraffic);
const layers = {
traffic,
traffic: {
enable: () => traffic.enable(trafficViewer),
disable: () => traffic.disable(trafficViewer),
},
bikeshare: {
enable: () => bike.enable(bikeViewer),
disable: () => bike.disable(bikeViewer),
},
transit: app.layer,
};
const claimants = new Set(['traffic', 'transit']);
const claimants = new Set(['transit']);
const orders = [
['traffic', 'bikeshare', 'transit'],
['traffic', 'transit', 'bikeshare'],
@@ -3696,6 +3714,10 @@ test('actual Traffic and Transit lifecycles retain sensitivity in every enable/d
if (claimants.has(id)) active.add(id);
if (id === 'bikeshare')
assert.equal(bikeCamera.listenerCount('changed'), 1);
if (id === 'traffic') {
assert.equal(trafficCamera.listenerCount('changed'), 1);
assert.equal(trafficFrames.size, 1);
}
assert.equal(
app.viewer.camera.percentageChanged,
active.size ? 0.05 : 0.5,
@@ -3719,6 +3741,9 @@ test('actual Traffic and Transit lifecycles retain sensitivity in every enable/d
);
}
assert.equal(bikeCamera.listenerCount('changed'), 0);
assert.equal(trafficCamera.listenerCount('changed'), 0);
assert.equal(trafficCamera.listenerCount('moveEnd'), 0);
assert.equal(trafficFrames.size, 0);
}
} finally {
for (const layer of Object.values(layers)) layer.disable(app.viewer);
-1
View File
@@ -28,7 +28,6 @@
"src/layers/radio/rendering.js",
"src/layers/recentImagery/rendering.js",
"src/layers/satellites/rendering.js",
"src/layers/traffic/lifecycle.js",
"src/layers/traffic/rendering.js",
"src/layers/transit/rendering.js",
"src/layers/weather/shellRendering.js",