Listen to the camera through the camera port in the transit layer

Transit lowered the one camera-change threshold every listener shared to
0.05, through a claim ledger. The camera port measures each listener
against its own threshold, so Transit now asks for 0.05 on its own port
listener, nobody else's trigger changes, and the ledger goes.

A new listener measures from the view at the next tick, so the layer looks
at the view once more after that tick, and a move made in between is not
missed. Disable always removes both subscriptions.

The billboards, the occluder and frustum checks and the frame probe still
drive Cesium, so the renderer stays on the Cesium list.
This commit is contained in:
Sameh Khamis committed 2026-11-08 19:00:37 -08:00
1 parent d513034f3d
commit b5fa86a20a
11 files changed
+115 -213

No files matched your search

+1 -3
View File
@@ -63,9 +63,7 @@ export function createLifecycle({
const now = Date.now();
// "Did the camera move" uses the same quantization as the fleet
// rotation pass's cameraPoseSignature (render/cesium/iconOrientation;
// keep the two in step), read from the camera port's pose, rather than
// camera.changed, whose granularity is globally degraded by other layers
// mutating camera.percentageChanged.
// keep the two in step), read from the camera port's pose.
const poseSig = cameraMotionSignature(layerState.viewer);
if (poseSig !== layerState.lastCameraPoseSig) {
layerState.lastCameraPoseSig = poseSig;
+1 -1
View File
@@ -19,7 +19,7 @@ import { TRANSIT_POLL_MS } from './policy.js';
* and height maps, the in-flight requests, the manager handle and the overlay
* host all live on the instance this returns, and `destroy()` releases every
* shared registration it took (sprite collection, pick owner, render hold,
* camera sensitivity).
* camera listener).
*
* @param {{services: object}} options
* @returns {object} The data-layer module the manager registers.
+6 -7
View File
@@ -5,8 +5,7 @@ import { TRANSIT_ENABLED_FEEDS } from '../../data/transitFeeds.js';
/**
* Init / enable / disable / update / destroy for one Transit layer instance.
* Everything acquired here is released here — primitives, listeners, the sprite
* registration, the pick owner, the render hold, and the camera sensitivity
* this layer borrowed.
* registration, the pick owner, the render hold, and the camera listener.
* @param {object} context
* @returns {object}
*/
@@ -139,7 +138,8 @@ export function createLifecycle({ state, services, parts }) {
registerPickOwner('transit', (pickedId) => state._vehicles.has(pickedId));
if (!state._cameraChangedAttached) {
parts.rendering.watchCamera(viewer, parts.viewport.onCameraChanged);
state._cameraChangedAttached = true;
// Attached only with a camera to listen to, so a later enable retries.
state._cameraChangedAttached = state._cameraChangedOff !== null;
}
parts.rendering.startFrames(viewer);
parts.viewport.runProximityCheck();
@@ -169,10 +169,9 @@ export function createLifecycle({ state, services, parts }) {
state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, false);
parts.selection.removeClickHandler();
unregisterPickOwner('transit');
if (state._cameraChangedAttached) {
parts.rendering.unwatchCamera(viewer, parts.viewport.onCameraChanged);
state._cameraChangedAttached = false;
}
// Unconditional: whatever watching started, none of it outlives this.
parts.rendering.unwatchCamera();
state._cameraChangedAttached = false;
parts.rendering.stopFrames();
parts.ingestion.abortAllInFlight();
state._activeFeeds.clear();
+71 -68
View File
@@ -28,11 +28,6 @@ const lat = (entry) =>
Cesium.Math.toDegrees(
Cesium.Cartographic.fromCartesian(entry.marker.position).latitude,
);
import {
cameraSensitivityClaims,
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
import {
_resetRenderGovernorForTest,
getRenderGovernorDiagnostics,
@@ -209,6 +204,8 @@ function harness(
const preRender = new Cesium.Event();
const cameraChanged = new Cesium.Event();
const cameraListeners = new Set();
const preUpdates = new Set();
const viewer = {
camera: {
changed: cameraChanged,
@@ -317,7 +314,28 @@ function harness(
const unbindCamera = bindRenderer(viewer, {
draw,
query: fakeSceneQuery(viewer),
// Only the tick the layer's camera listener waits on.
frame: {
on(phase, cb) {
if (phase !== 'preUpdate') return () => {};
preUpdates.add(cb);
return () => preUpdates.delete(cb);
},
requestRender() {},
},
camera: {
// `changed` listeners, each at its own threshold, fired by the fake
// camera's own event as a real camera move fires them.
on(event, cb, options = {}) {
if (event !== 'changed') return () => {};
const listener = { cb, threshold: options.threshold ?? 0.5 };
cameraListeners.add(listener);
const remove = cameraChanged.addEventListener(cb);
return () => {
cameraListeners.delete(listener);
remove();
};
},
pose() {
const carto = viewer.camera.positionCartographic;
return {
@@ -365,6 +383,16 @@ function harness(
layer,
viewer,
draw,
/** One frame tick, as the frame port's `preUpdate` hears it. */
tick() {
for (const cb of [...preUpdates]) cb({ frame: 0 });
},
/** Move the view rectangle without the camera reporting the move. */
moveQuietly(next) {
Object.assign(viewRect, next);
},
/** The thresholds of the camera port's `changed` listeners. */
cameraThresholds: () => [...cameraListeners].map((l) => l.threshold),
input,
primitives,
sprites,
@@ -878,63 +906,42 @@ test('the render hold follows real motion, and is released when everything settl
);
assert.equal(app.viewer.scene.requestRenderMode, true);
});
test('disable hands back the camera sensitivity it borrowed', async (t) => {
test('the layer listens to the camera at its own fine threshold while enabled', async (t) => {
const app = harness(t);
assert.equal(app.viewer.camera.percentageChanged, 0.5);
assert.deepEqual(app.cameraThresholds(), []);
app.layer.enable(app.viewer);
assert.equal(
app.viewer.camera.percentageChanged,
0.05,
'the layer needs a finer camera trigger',
assert.deepEqual(
app.cameraThresholds(),
[0.05],
'the layer needs a finer camera trigger, as its own',
);
app.layer.disable(app.viewer);
assert.equal(app.viewer.camera.percentageChanged, 0.5, 'and gives it back');
});
test('disable leaves the fine camera trigger another layer asked for', async (t) => {
// The sequence that broke it: two layers ask for the SAME sensitivity, so
// the value on the camera cannot say who owns it. Transit used to compare
// the number, find its own 0.05 still there, and hand the coarse default
// back while Bikeshare was still driving off the fine one.
const app = harness(t);
assert.equal(app.viewer.camera.percentageChanged, 0.5);
app.layer.enable(app.viewer);
assert.equal(app.viewer.camera.percentageChanged, 0.05);
claimCameraSensitivity(app.viewer.camera, 'bikeshare', 0.05);
app.layer.disable(app.viewer);
assert.equal(
app.viewer.camera.percentageChanged,
0.05,
'bikeshare is still enabled, so the fine trigger stays',
);
assert.deepEqual(cameraSensitivityClaims(app.viewer.camera), ['bikeshare']);
releaseCameraSensitivity(app.viewer.camera, 'bikeshare');
assert.equal(
app.viewer.camera.percentageChanged,
0.5,
'and the original returns once the last claim is gone',
);
assert.deepEqual(cameraSensitivityClaims(app.viewer.camera), []);
});
test('a finer claim wins while it stands, and the coarser one survives it', async (t) => {
const app = harness(t);
app.layer.enable(app.viewer);
claimCameraSensitivity(app.viewer.camera, 'traffic', 0.01);
assert.equal(app.viewer.camera.percentageChanged, 0.01);
releaseCameraSensitivity(app.viewer.camera, 'traffic');
assert.equal(
app.viewer.camera.percentageChanged,
0.05,
'transit still needs its own trigger',
'and leaves the camera every other listener shares as it was',
);
app.layer.disable(app.viewer);
assert.equal(app.viewer.camera.percentageChanged, 0.5);
assert.deepEqual(app.cameraThresholds(), [], 'and stops on disable');
});
test('a move before the camera listener first measures is still looked at', async (t) => {
const app = harness(t);
app.layer.enable(app.viewer);
// The move lands before the listener's first tick, so it is the view the
// listener measures from and never reports.
app.moveQuietly({ west: -71.2, south: 10, east: -71.0, north: 10.2 });
app.tick();
assert.ok(app.state()._viewBounds.south > 40, 'not looked at yet');
app.tick();
assert.ok(
app.state()._viewBounds.south < 11,
'looked at once the first tick is past',
);
app.moveQuietly({ west: -71.2, south: 42.3, east: -71.0, north: 42.5 });
app.tick();
app.tick();
assert.ok(app.state()._viewBounds.south < 11, 'once, not every tick');
app.layer.disable(app.viewer);
});
test('destroy releases every shared registration this layer took', async (t) => {
@@ -957,6 +964,7 @@ test('destroy releases every shared registration this layer took', async (t) =>
assert.equal(app.primitives.length, 2);
app.layer.destroy(app.viewer);
assert.deepEqual(app.cameraThresholds(), [], 'the camera listener goes');
assert.equal(
app.sprites.has('transit'),
false,
@@ -3617,7 +3625,7 @@ test('reject then selected history backfill cannot resurrect a 111 km displaceme
assert.equal(entry.track.resets, 0);
});
test('the actual Transit lifecycle retains its sensitivity in every enable/disable order, Traffic and Bikeshare among them', async (t) => {
test('the actual Transit lifecycle keeps exactly its own camera listener in every enable/disable order, Traffic and Bikeshare among them', async (t) => {
const { createLifecycle: trafficLifecycle } =
await import('../traffic/lifecycle.js');
const { createLifecycle: bikeLifecycle } =
@@ -3696,6 +3704,7 @@ test('the actual Transit lifecycle retains its sensitivity in every enable/disab
},
transit: app.layer,
};
// Only transit listens on this viewer's camera port.
const claimants = new Set(['transit']);
const orders = [
['traffic', 'bikeshare', 'transit'],
@@ -3718,27 +3727,21 @@ test('the actual Transit lifecycle retains its sensitivity in every enable/disab
assert.equal(trafficCamera.listenerCount('changed'), 1);
assert.equal(trafficFrames.size, 1);
}
assert.equal(
app.viewer.camera.percentageChanged,
active.size ? 0.05 : 0.5,
);
assert.deepEqual(
new Set(cameraSensitivityClaims(app.viewer.camera)),
active,
app.cameraThresholds(),
active.has('transit') ? [0.05] : [],
);
assert.equal(app.viewer.camera.percentageChanged, 0.5);
}
for (const id of disable) {
layers[id].disable(app.viewer);
active.delete(id);
assert.equal(
app.viewer.camera.percentageChanged,
active.size ? 0.05 : 0.5,
assert.deepEqual(
app.cameraThresholds(),
active.has('transit') ? [0.05] : [],
`${enable} / ${disable} after ${id}`,
);
assert.deepEqual(
new Set(cameraSensitivityClaims(app.viewer.camera)),
active,
);
assert.equal(app.viewer.camera.percentageChanged, 0.5);
}
assert.equal(bikeCamera.listenerCount('changed'), 0);
assert.equal(trafficCamera.listenerCount('changed'), 0);
+1 -1
View File
@@ -35,7 +35,7 @@ export const ACTIVATION_ENTER_ALTITUDE_M = ACTIVATION_ALTITUDE_M - 150_000;
export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 150_000;
/** Debounce (ms) for camera-change proximity checks. */
export const CAMERA_DEBOUNCE_MS = 340;
/** Camera sensitivity this layer asks for while it is enabled. */
/** The `changed` threshold this layer's camera listener asks for. */
export const CAMERA_PERCENTAGE_CHANGED = 0.05;
/** Extra coverage radius (km) granted to a feed that is already active, so it does not flap at the edge. */
export const RANGE_SLACK_KM = 40;
+28 -23
View File
@@ -2,11 +2,9 @@ import * as Cesium from 'cesium';
// The Cesium camera factory: given a viewer of a caller's own, with no
// renderer bound, the layer's camera reads find a camera port.
import '../../render/cesium/camera.js';
import '../../render/cesium/frame.js';
import { webglContext } from '../../render/cesium/internals.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
import { findCamera, findFrame } from '../../render/rendererOf.js';
import {
cameraPoseSignature,
perspectiveProjectedRotation,
@@ -122,32 +120,39 @@ export function createRendering({ state, services, parts }) {
}
/**
* Listen for the camera moving, borrowing its change sensitivity through
* the shared claim ledger.
* Listen for the camera moving, at this layer's own threshold.
*
* `camera.changed` fires on a percentage of the view moving, and this layer
* needs a finer trigger than the default to notice it has entered a feed's
* coverage. It is a single shared number, so the claim is registered by name
* rather than written directly: comparing the VALUE on the way out could not
* tell this layer's 0.05 from anybody else's, and handing back the coarse
* default while Bikeshare was still relying on a fine one was exactly the
* bug that produced.
* The camera port measures `changed` per listener, so this layer's finer
* trigger (it needs to notice it has entered a feed's coverage) is its own
* and leaves every other listener's untouched.
* @param {object} viewer
* @param {() => void} onChanged
*/
function watchCamera(viewer, onChanged) {
viewer.camera.changed.addEventListener(onChanged);
claimCameraSensitivity(
viewer?.camera,
'transit',
CAMERA_PERCENTAGE_CHANGED,
);
unwatchCamera();
state._cameraChangedOff =
findCamera(viewer)?.on('changed', onChanged, {
threshold: CAMERA_PERCENTAGE_CHANGED,
}) ?? null;
// A new listener measures from the view at the next tick, so a move made
// before that tick never reaches it: look again once that tick is past.
if (!state._cameraChangedOff) return;
let ticks = 0;
state._cameraFirstTickOff =
findFrame(viewer)?.on('preUpdate', () => {
if (++ticks < 2) return;
state._cameraFirstTickOff?.();
state._cameraFirstTickOff = null;
onChanged();
}) ?? null;
}
/** Stop listening and give the claim up; the camera keeps anyone else's. */
function unwatchCamera(viewer, onChanged) {
viewer.camera.changed.removeEventListener(onChanged);
releaseCameraSensitivity(viewer?.camera, 'transit');
/** Stop listening for the camera moving. */
function unwatchCamera() {
state._cameraChangedOff?.();
state._cameraChangedOff = null;
state._cameraFirstTickOff?.();
state._cameraFirstTickOff = null;
}
/** Run the per-frame glide before each render, once. */
+4 -4
View File
@@ -36,12 +36,12 @@ export function createState({ services }) {
state._generation = 0;
state._cameraChangedAttached = false;
/** Removes the camera port listener; null when not listening. */
state._cameraChangedOff = null;
/** Removes the one-shot look after the camera listener's first tick. */
state._cameraFirstTickOff = null;
state._cameraDebounceTimer = null;
state._altitudeGateOpen = false;
/** Camera sensitivity as we found it, so disable() can hand it back. */
state._priorPercentageChanged = null;
/** The value this layer actually wrote, for an identity-guarded restore. */
state._appliedPercentageChanged = null;
/** @type {(() => void)|null} */
state._preRenderRemove = null;