Replace Cesium monkey-patches with hooks and keep internals in one module

The arrival ground guard replaced camera.flyTo, flyToBoundingSphere,
setView, lookAt and cancelFlight with wrappers so a direct caller would stop
it. It now remembers the pose it started on and, before each retry, yields
if a flight is under way or the camera has moved across the ground, down or
around. A straight rise is not a move: Cesium's terrain collision lifts a
buried eye that way as tiles load, which is the case the guard exists for.
This also catches owners the wrappers missed (a pose written directly,
lookAtTransform), and no camera method is replaced.

Recent imagery and weather overwrote provider.requestImage (weather also
provider.credit) to ration tiles. They now state that policy as a hook with
withTileRequestHook(provider, { requestImage, credit }) from
src/render/cesium/tileRequests.js, which hands Cesium a provider delegating
to the original and leaves the original untouched.

Every private Cesium field the app reaches goes through a named helper in
src/render/cesium/internals.js: the main and offscreen pick views and their
command extents, a billboard's collection, a cluster's point collection,
the widget's render-loop latch, the WebGL context and the current camera
flight. internals.test.mjs fails when the installed Cesium stops declaring
one of them, and a source scan fails on private access anywhere else. The
cyber sonar's primitives.update wrap stays until the effects work.

Live (Austin, keyless globe): a buried eye is lifted to 253 m over a 133 m
surface; a setView or flyTo by another caller makes the guard yield; radar
loads its tiles through the hook. Documented in docs/APPLICATION.md and
docs/CURRENT-STATE.md.
This commit is contained in:
Sameh Khamis committed 2026-11-04 11:15:35 -08:00
1 parent 9bdeffeca3
commit 18d6e3292d
18 files changed
+597 -125

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
/**
* @module render/cesium/internals
* @description Every read or write of a private Cesium field, in one place.
*
* The app otherwise uses Cesium's public API. Each helper here names one private
* field the app depends on and says why; `internals.test.mjs` fails when the
* installed Cesium no longer declares one of them, and a source scan fails
* when a private field is reached anywhere else.
*/
/**
* The scene's main view, whose per-pass command arrays outlive a frame.
* Used by `sceneCommandRelease.js` to drop references to destroyed commands.
* @param {object} scene Cesium Scene.
* @returns {object|undefined} Cesium `View`.
*/
export function defaultView(scene) {
return scene?._defaultView;
}
/**
* The offscreen view `sampleHeight` and `pickFromRay` render into.
* @param {object} scene Cesium Scene.
* @returns {object|undefined} Cesium `View`.
*/
export function pickOffscreenView(scene) {
return scene?._picking?._pickOffscreenView;
}
/**
* A view's command-extent records, each holding the command it last drew.
* @param {object} view Cesium `View`.
* @returns {Array<{command: object}>}
*/
export function commandExtents(view) {
return view?._commandExtents || [];
}
/**
* The collection a picked billboard belongs to; Cesium's pick result names
* the billboard, not its collection.
* @param {object} billboard Cesium Billboard.
* @returns {object|undefined} Cesium BillboardCollection.
*/
export function billboardCollectionOf(billboard) {
return billboard?._billboardCollection;
}
/**
* The point collection an `EntityCluster` draws its cluster markers into.
* @param {object} clustering Cesium EntityCluster.
* @returns {object|null} Cesium PointPrimitiveCollection.
*/
export function clusterPointCollection(clustering) {
return clustering?._clusterPointCollection || null;
}
/**
* Close the widget's pending render-loop latch after `useDefaultRenderLoop`
* is set false, so a callback already queued sees the loop as stopped and
* manual renders start without waiting a vsync.
* @param {object} viewer Cesium Viewer.
*/
export function closeRenderLoopLatch(viewer) {
const widget = viewer?._cesiumWidget;
if (widget) widget._renderLoopRunning = false;
}
/**
* The scene's WebGL context, for diagnostics that read the GPU directly.
* @param {object} scene Cesium Scene.
* @returns {WebGLRenderingContext|WebGL2RenderingContext|undefined}
*/
export function webglContext(scene) {
return scene?.context?._gl;
}
/**
* Whether a camera flight is under way. Cesium clears it before calling a
* flight's `complete`, so it reads false inside that callback.
* @param {object} camera Cesium Camera.
* @returns {boolean}
*/
export function cameraFlightActive(camera) {
return camera?._currentFlight != null;
}
+140
View File
@@ -0,0 +1,140 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import {
billboardCollectionOf,
cameraFlightActive,
closeRenderLoopLatch,
clusterPointCollection,
commandExtents,
defaultView,
pickOffscreenView,
webglContext,
} from './internals.js';
const ROOT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'..',
'..',
'..',
);
const require = createRequire(import.meta.url);
const packageSource = (name) =>
path.join(path.dirname(require.resolve(`${name}/package.json`)), 'Source');
const ENGINE = packageSource('@cesium/engine');
const WIDGETS = packageSource('@cesium/widgets');
test('every private field the app reaches is still declared by the installed Cesium', () => {
const fields = [
[ENGINE, 'Scene/Scene.js', '_defaultView'],
[ENGINE, 'Scene/Scene.js', '_picking'],
[ENGINE, 'Scene/Picking.js', '_pickOffscreenView'],
[ENGINE, 'Scene/View.js', '_commandExtents'],
[ENGINE, 'Scene/Billboard.js', '_billboardCollection'],
[ENGINE, 'DataSources/EntityCluster.js', '_clusterPointCollection'],
[ENGINE, 'Widget/CesiumWidget.js', '_renderLoopRunning'],
[WIDGETS, 'Viewer/Viewer.js', '_cesiumWidget'],
[ENGINE, 'Renderer/Context.js', '_gl'],
[ENGINE, 'Scene/Camera.js', '_currentFlight'],
];
const missing = fields.filter(
([root, file, field]) =>
!new RegExp(`this\\.${field}\\s*=`).test(
fs.readFileSync(path.join(root, file), 'utf8'),
),
);
assert.deepEqual(missing, []);
});
test('the helpers read and write exactly those fields', () => {
const view = { _commandExtents: [{ command: {} }] };
assert.equal(defaultView({ _defaultView: view }), view);
assert.equal(
pickOffscreenView({ _picking: { _pickOffscreenView: view } }),
view,
);
assert.equal(commandExtents(view), view._commandExtents);
assert.deepEqual(commandExtents(undefined), []);
const collection = {};
assert.equal(
billboardCollectionOf({ _billboardCollection: collection }),
collection,
);
assert.equal(
clusterPointCollection({ _clusterPointCollection: collection }),
collection,
);
assert.equal(clusterPointCollection(undefined), null);
const widget = { _renderLoopRunning: true };
closeRenderLoopLatch({ _cesiumWidget: widget });
assert.equal(widget._renderLoopRunning, false);
closeRenderLoopLatch({});
const gl = {};
assert.equal(webglContext({ context: { _gl: gl } }), gl);
assert.equal(cameraFlightActive({ _currentFlight: {} }), true);
assert.equal(cameraFlightActive({ _currentFlight: undefined }), false);
});
test('private Cesium fields are reached only through internals.js', () => {
// A private field is one Cesium assigns as `this._name`. The app's own objects
// use underscore fields too, and some share a name with one of Cesium's,
// so a name the app itself defines (on `this`, a state object or as a key) is
// the app's; any other `._name` from Cesium's set is a private Cesium read.
const walk = (dir, filter) =>
fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) return walk(full, filter);
return filter(entry.name) ? [full] : [];
});
const cesiumPrivate = new Set();
for (const file of [
...walk(ENGINE, (name) => name.endsWith('.js')),
...walk(WIDGETS, (name) => name.endsWith('.js')),
])
for (const [, name] of fs
.readFileSync(file, 'utf8')
.matchAll(/this\._([A-Za-z]\w*)/g))
cesiumPrivate.add(name);
const INTERNALS = 'src/render/cesium/internals.js';
const sources = walk(path.join(ROOT, 'src'), (name) =>
/\.(js|vue)$/.test(name),
)
.map((file) => path.relative(ROOT, file))
.filter((file) => file !== INTERNALS)
.map((file) => [
file,
fs
.readFileSync(path.join(ROOT, file), 'utf8')
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/^\s*\/\/.*$/gm, ''),
]);
const coreOwn = new Set();
const definitions = [
/\b(?:this|\w*[sS]tate|owner|self|parts|anno|entry|record|rec|cal|label|controller)\._([A-Za-z]\w*)\s*=(?!=)/g,
/^\s*(?:static\s+)?(?:async\s+)?_([A-Za-z]\w*)\s*[(=:;]/gm,
/[{,]\s*_([A-Za-z]\w*)\s*:/g,
];
for (const [, code] of sources)
for (const pattern of definitions)
for (const [, name] of code.matchAll(pattern)) coreOwn.add(name);
// A Cesium object's private field is flagged whatever the app names its own
// fields: on a receiver that is a Cesium object, or by bracket access.
const CESIUM_RECEIVER =
/\b_?(?:viewer|scene|camera|globe|context|frameState|clustering|tileset|imageryProvider|terrainProvider|screenSpaceCameraController|cesiumWidget|imageryLayers|primitives|dataSources|entities|clock)\??\._([A-Za-z]\w*)\b/g;
const BRACKET = /\[\s*['"`]_([A-Za-z]\w*)['"`]\s*\]/g;
const offenders = [];
for (const [file, code] of sources) {
for (const [, name] of code.matchAll(/\._([A-Za-z]\w*)\b/g))
if (cesiumPrivate.has(name) && !coreOwn.has(name))
offenders.push(`${file} ._${name}`);
for (const pattern of [CESIUM_RECEIVER, BRACKET])
for (const [, name] of code.matchAll(pattern))
if (cesiumPrivate.has(name)) offenders.push(`${file} ._${name}`);
}
assert.deepEqual([...new Set(offenders)], []);
});
+50
View File
@@ -0,0 +1,50 @@
/**
* @module render/cesium/tileRequests
* @description Admission hooks for an imagery provider's tile requests.
*
* A layer that rations its tiles (a request budget, readiness accounting,
* dropping a frame that is no longer shown) states that policy as a hook
* instead of replacing the provider's `requestImage`. The provider itself is
* left untouched: the returned provider delegates everything to it through
* its prototype and routes only tile requests, and optionally the credit,
* through the hook.
*
* Fields Cesium writes onto a provider land on the returned one, so a
* provider that reads such a field itself (a time-dynamic WMTS provider's
* `_reload`) is not suited; the URL-template and raster providers that use
* hooks today read none.
*/
/**
* @typedef {object} TileRequest
* @property {number} x
* @property {number} y
* @property {number} level
* @property {object} [request] Cesium `Request`, when Cesium passed one.
*/
/**
* @param {object} provider A Cesium imagery provider (or one built by the app).
* @param {object} hooks
* @param {(tile: TileRequest, issue: () => Promise<any>|undefined) => Promise<any>|undefined} [hooks.requestImage]
* Decides each request. `issue()` asks the provider; returning `undefined`
* defers the tile, and Cesium asks again on a later frame.
* @param {() => object} [hooks.credit] The credit Cesium shows for the layer,
* read every frame, so it can change without restaging the imagery.
* @returns {object} A provider to hand to `ImageryLayer`.
*/
export function withTileRequestHook(provider, { requestImage, credit } = {}) {
const hooked = Object.create(provider);
if (requestImage)
hooked.requestImage = (x, y, level, request) =>
requestImage({ x, y, level, request }, () =>
provider.requestImage(x, y, level, request),
);
if (credit)
Object.defineProperty(hooked, 'credit', {
configurable: true,
enumerable: true,
get: credit,
});
return hooked;
}
+68
View File
@@ -0,0 +1,68 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { withTileRequestHook } from './tileRequests.js';
class Provider {
constructor() {
this._tilingScheme = { name: 'geographic' };
this.calls = [];
}
get tilingScheme() {
return this._tilingScheme;
}
get credit() {
return 'stock';
}
requestImage(x, y, level, request) {
this.calls.push([x, y, level, request]);
return Promise.resolve({ x, y, level });
}
}
test('the hook decides each tile request and issues it on the provider', async () => {
const provider = new Provider();
const seen = [];
const hooked = withTileRequestHook(provider, {
requestImage: (tile, issue) => {
seen.push(tile);
return tile.level > 3 ? undefined : issue();
},
});
const request = {};
assert.deepEqual(await hooked.requestImage(1, 2, 3, request), {
x: 1,
y: 2,
level: 3,
});
assert.equal(hooked.requestImage(1, 2, 4), undefined, 'deferred');
assert.deepEqual(seen, [
{ x: 1, y: 2, level: 3, request },
{ x: 1, y: 2, level: 4, request: undefined },
]);
assert.deepEqual(provider.calls, [[1, 2, 3, request]]);
});
test('the provider itself is left untouched and still read through', () => {
const provider = new Provider();
const own = Object.getOwnPropertyNames(provider);
let credit = 'first';
const hooked = withTileRequestHook(provider, {
requestImage: (_tile, issue) => issue(),
credit: () => credit,
});
assert.deepEqual(Object.getOwnPropertyNames(provider), own);
assert.equal(provider.requestImage, Provider.prototype.requestImage);
assert.equal(provider.credit, 'stock');
assert.equal(hooked.tilingScheme, provider.tilingScheme);
assert.equal(hooked.credit, 'first');
credit = 'refreshed';
assert.equal(hooked.credit, 'refreshed', 'read every time');
});
test('without hooks the provider answers as it is', () => {
const provider = new Provider();
const hooked = withTileRequestHook(provider);
hooked.requestImage(0, 0, 0);
assert.equal(provider.calls.length, 1);
assert.equal(hooked.credit, 'stock');
});