mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-17 00:32:21 +00:00
Three fixes to how the globe draws and reports loading. **The idle frame rate is the app's rule.** The Cesium frame port capped the loop at `IDLE_FRAME_RATE` whenever nothing held it, so the rule lived inside the renderer. The render governor now sets the rate: the display's own while the loop is held, `IDLE_FRAME_RATE` while not. The frame port gains `onHeldChange(cb)`, which says when its first hold is taken and its last released (animated visual styles included), so the governor hears every hold. The quality setting's frame-rate cap is kept apart from the governor's rate, and the loop draws at the lower of the two, so neither overwrites the other. **Line batching is timed.** A line set waited 30 drawn frames before its unchanged lines settled into a static batch (300 for the long wait), so the batch built twice as fast at 120 Hz as at 60 Hz, and took seconds at the idle rate. It now waits `SETTLE_MS` (500 ms) and `LONG_SETTLE_MS` (5 s), and moved shapes go back into their batches on the same timing. **KEY REQUIRED.** A layer that cannot load without a provider key ended the global status chip LOAD FAILED. The chip now has a KEY REQUIRED outcome, ranked below a real failure: a layer whose stats say `keyRequired` ends KEY REQUIRED, any other failure still ends LOAD FAILED. Vessels report a missing AISStream key as `keyRequired` and name the key in the panel; a later outage clears it, as it is no longer the key that is missing. Checked: the full suite (new tests for `onHeldChange`, the quality cap against the governor's rate, timed settling, and the chip with and without a key), format, boundaries, build, the stub renderer boot and the Cesium conformance run; in the browser, the idle and held frame rates; and the first-run check now asserts that with no keys set the chip never says LOAD FAILED.
358 lines
12 KiB
JavaScript
358 lines
12 KiB
JavaScript
/**
|
|
* @module render/cesium/frame
|
|
* @description A frame port (`src/render/contract/frame.d.ts`) over a Cesium
|
|
* viewer with no renderer bound, built when code first
|
|
* asks `findFrame` for one (`rendererOf.js`). The renderer's own frame port
|
|
* (`ports.js`) runs the loop on demand; this one leaves the viewer's loop as
|
|
* its owner set it up and only listens to it, asks it for frames and holds
|
|
* it drawing: its `mode` is the viewer's, and `requestRender` and holds draw
|
|
* a frame however the viewer's loop runs. `setTime`, `suspend` and
|
|
* `setTargetFps` are the viewer's own clock, loop and rate.
|
|
*
|
|
* A `preUpdate` FrameTime's `rendering` says, when read, whether the tick
|
|
* draws by the scene's own test so far (`willDraw`, which the renderer's
|
|
* frame port makes too) or a hold, and once the tick has drawn or not,
|
|
* which it did. `suspend` stops and resumes the viewer's default loop;
|
|
* resumed, the loop is as its owner had it.
|
|
*/
|
|
import * as Cesium from 'cesium';
|
|
import { provideUnboundFrame } from '../rendererOf.js';
|
|
import { listenerList, uncaught } from './common.js';
|
|
import {
|
|
atEndOfTick,
|
|
lastRenderTime,
|
|
lastSeenCamera,
|
|
renderPending,
|
|
} from './internals.js';
|
|
|
|
const PHASES = ['preUpdate', 'preRender', 'postRender'];
|
|
|
|
const scratchPosition0 = new Cesium.Cartesian3();
|
|
const scratchPosition1 = new Cesium.Cartesian3();
|
|
|
|
/** Cesium's own test (`View.js`) for whether the camera moved. */
|
|
function cameraEqual(camera0, camera1, epsilon) {
|
|
const maximumPositionComponent = Math.max(
|
|
Cesium.Cartesian3.maximumComponent(
|
|
Cesium.Cartesian3.abs(camera0.position, scratchPosition0),
|
|
),
|
|
Cesium.Cartesian3.maximumComponent(
|
|
Cesium.Cartesian3.abs(camera1.position, scratchPosition1),
|
|
),
|
|
);
|
|
const scalar = 1 / Math.max(1, maximumPositionComponent);
|
|
Cesium.Cartesian3.multiplyByScalar(
|
|
camera0.position,
|
|
scalar,
|
|
scratchPosition0,
|
|
);
|
|
Cesium.Cartesian3.multiplyByScalar(
|
|
camera1.position,
|
|
scalar,
|
|
scratchPosition1,
|
|
);
|
|
return (
|
|
Cesium.Cartesian3.equalsEpsilon(
|
|
scratchPosition0,
|
|
scratchPosition1,
|
|
epsilon,
|
|
) &&
|
|
Cesium.Cartesian3.equalsEpsilon(
|
|
camera0.direction,
|
|
camera1.direction,
|
|
epsilon,
|
|
) &&
|
|
Cesium.Cartesian3.equalsEpsilon(camera0.up, camera1.up, epsilon) &&
|
|
Cesium.Cartesian3.equalsEpsilon(camera0.right, camera1.right, epsilon) &&
|
|
Cesium.Matrix4.equalsEpsilon(
|
|
camera0.transform,
|
|
camera1.transform,
|
|
epsilon,
|
|
) &&
|
|
camera0.frustum.equalsEpsilon(camera1.frustum, epsilon)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Whether the scene's tick draws: the test `Scene.render` makes just after
|
|
* `preUpdate`, made here so `preUpdate` can say. Not seen: a request made
|
|
* in between, by a `camera.moveEnd` listener (Cesium raises it there); no
|
|
* listener of the app's does that, and the answer is corrected at preRender.
|
|
* @param {object} scene Cesium Scene.
|
|
* @param {object} [time] The tick's scene time, a Cesium JulianDate.
|
|
* @returns {boolean}
|
|
*/
|
|
export function willDraw(scene, time) {
|
|
if (!scene.requestRenderMode || renderPending(scene)) return true;
|
|
if (scene.mode === Cesium.SceneMode.MORPHING) return true;
|
|
const seen = lastSeenCamera(scene);
|
|
if (!seen || !cameraEqual(scene.camera, seen, Cesium.Math.EPSILON15))
|
|
return true;
|
|
const last = lastRenderTime(scene);
|
|
const max = scene.maximumRenderTimeChange;
|
|
return (
|
|
last !== undefined &&
|
|
max !== undefined &&
|
|
Math.abs(
|
|
Cesium.JulianDate.secondsDifference(
|
|
last,
|
|
time ?? Cesium.JulianDate.now(),
|
|
),
|
|
) > max
|
|
);
|
|
}
|
|
|
|
/**
|
|
* The contract's `renderNow` on `owner`'s scene: draw a frame at the
|
|
* clock's time even when nothing asked for one, or with `ifDue` run one
|
|
* frame of the widget's own loop (`render()`: the camera's flight and
|
|
* input, the clock's tick, then a draw if one is due); throw the error
|
|
* Cesium caught and raised on `renderError` when the frame failed.
|
|
* @param {object} owner A Cesium `Viewer` or `CesiumWidget`.
|
|
* @param {{ifDue?: boolean}} [options]
|
|
*/
|
|
export function renderNow(owner, { ifDue = false } = {}) {
|
|
const scene = owner.scene;
|
|
let failure = null;
|
|
const off = scene.renderError?.addEventListener((_scene, error) => {
|
|
failure ??= { error };
|
|
});
|
|
try {
|
|
if (ifDue) owner.render();
|
|
else scene.forceRender(owner.clock?.currentTime);
|
|
} finally {
|
|
off?.();
|
|
}
|
|
if (failure) throw failure.error;
|
|
}
|
|
|
|
/**
|
|
* @param {object} viewer A Cesium `Viewer` or `CesiumWidget`.
|
|
* @returns {{port: import('../contract/frame').FramePort,
|
|
* dispose: () => void}}
|
|
*/
|
|
export function createSceneFrame(viewer) {
|
|
const scene = viewer.scene;
|
|
const listeners = Object.fromEntries(
|
|
PHASES.map((phase) => [phase, listenerList(uncaught)]),
|
|
);
|
|
let frames = 0;
|
|
let rendered = 0;
|
|
let tickNow = performance.now();
|
|
let dt = 0;
|
|
// Reasons asked for since the last drawn frame; those a drawing frame
|
|
// answers are the first `answering`.
|
|
const pendingReasons = [];
|
|
let answering = 0;
|
|
let disposed = false;
|
|
let suspended = false;
|
|
// Whether the viewer ran Cesium's own loop, for `suspend` to give back.
|
|
const ownLoop = viewer.useDefaultRenderLoop !== false;
|
|
// The preUpdate FrameTime of the tick under way, until it settles.
|
|
let liveTick = null;
|
|
// The time Cesium stamps the frame in `preUpdate` with, while it runs.
|
|
let stampTime = null;
|
|
const settleTick = (drawn) => {
|
|
if (liveTick)
|
|
Object.defineProperty(liveTick, 'rendering', {
|
|
value: drawn,
|
|
enumerable: true,
|
|
});
|
|
liveTick = null;
|
|
};
|
|
const holds = new Map();
|
|
// Told when the first hold is taken and the last released.
|
|
const heldListeners = listenerList(uncaught);
|
|
const pendingRenders = new Set();
|
|
const gone = () => disposed || scene.isDestroyed?.();
|
|
const sceneTime = (time) =>
|
|
Cesium.JulianDate.toDate(
|
|
time ?? viewer.clock?.currentTime ?? Cesium.JulianDate.now(),
|
|
).getTime();
|
|
|
|
const onPhase = (phase) => (_scene, time) => {
|
|
if (phase === 'preUpdate') {
|
|
settleTick(false);
|
|
// A tick that does not draw settles at its end; one that does, at
|
|
// preRender.
|
|
atEndOfTick(scene, () => void settleTick(false));
|
|
const now = performance.now();
|
|
dt = (now - tickNow) / 1000;
|
|
tickNow = now;
|
|
frames += 1;
|
|
}
|
|
if (phase === 'preRender') {
|
|
settleTick(true);
|
|
answering = pendingReasons.length;
|
|
}
|
|
if (phase === 'postRender') {
|
|
rendered += 1;
|
|
pendingReasons.splice(0, answering);
|
|
answering = 0;
|
|
// Held: the next frame is asked for as this one ends.
|
|
if (holds.size) scene.requestRender();
|
|
}
|
|
if (listeners[phase].size === 0) return;
|
|
const t = {
|
|
frame: frames,
|
|
time: sceneTime(time),
|
|
now: tickNow,
|
|
dt,
|
|
rendering: true,
|
|
};
|
|
// Read as it is asked: what earlier listeners asked for counts.
|
|
if (phase === 'preUpdate') {
|
|
stampTime = time ?? null;
|
|
Object.defineProperty(t, 'rendering', {
|
|
enumerable: true,
|
|
configurable: true,
|
|
get: () => holds.size > 0 || willDraw(scene, time),
|
|
});
|
|
liveTick = t;
|
|
}
|
|
try {
|
|
listeners[phase].fire(t);
|
|
} finally {
|
|
stampTime = null;
|
|
}
|
|
};
|
|
const removers = PHASES.map((phase) =>
|
|
scene[phase].addEventListener(onPhase(phase)),
|
|
);
|
|
// A render error stops Cesium's own loop until something starts it again
|
|
// (the render failure notice's Retry): `stopped` in the diagnostics.
|
|
let failed = false;
|
|
const offError = scene.renderError?.addEventListener(() => {
|
|
failed = true;
|
|
});
|
|
if (offError) removers.push(offError);
|
|
const stopped = () => {
|
|
if (failed && viewer.useDefaultRenderLoop !== false) failed = false;
|
|
return failed;
|
|
};
|
|
|
|
const port = {
|
|
on(phase, cb) {
|
|
const list = listeners[phase];
|
|
if (!list) throw new TypeError(`Unknown frame phase: ${phase}`);
|
|
return list.on(cb);
|
|
},
|
|
requestRender(reason = 'unspecified') {
|
|
if (gone()) return;
|
|
// During a draw the reasons it answers are spoken for.
|
|
if (!pendingReasons.includes(reason, answering))
|
|
pendingReasons.push(reason);
|
|
scene.requestRender();
|
|
},
|
|
holdContinuous(reason) {
|
|
if (disposed) return () => {};
|
|
const first = holds.size === 0;
|
|
holds.set(reason, (holds.get(reason) ?? 0) + 1);
|
|
if (!gone()) scene.requestRender();
|
|
if (first) heldListeners.fire(true);
|
|
let released = false;
|
|
return () => {
|
|
if (released) return;
|
|
released = true;
|
|
const left = holds.get(reason) - 1;
|
|
if (left > 0) holds.set(reason, left);
|
|
else holds.delete(reason);
|
|
// What changed in the last held frame still gets drawn.
|
|
if (!gone()) scene.requestRender();
|
|
if (holds.size === 0) heldListeners.fire(false);
|
|
};
|
|
},
|
|
onHeldChange: (cb) => heldListeners.on(cb),
|
|
mode: () => (scene.requestRenderMode ? 'demand' : 'continuous'),
|
|
diagnostics: () => ({
|
|
mode: port.mode(),
|
|
frames,
|
|
rendered,
|
|
pendingReasons: [...pendingReasons],
|
|
holds: [...holds].flatMap(([reason, n]) => Array(n).fill(reason)),
|
|
suspended,
|
|
stopped: stopped(),
|
|
targetFps: viewer.targetFrameRate > 0 ? viewer.targetFrameRate : 0,
|
|
}),
|
|
suspend(hidden) {
|
|
if (Boolean(hidden) === suspended) return;
|
|
suspended = Boolean(hidden);
|
|
// Resumed, the loop runs as its owner had it (perhaps their own).
|
|
viewer.useDefaultRenderLoop = suspended ? false : ownLoop;
|
|
if (!suspended && !gone()) scene.requestRender();
|
|
},
|
|
renderNow: (options) => renderNow(viewer, options),
|
|
renderOnce({ timeoutMs } = {}) {
|
|
if (gone()) return Promise.resolve();
|
|
return new Promise((resolve, reject) => {
|
|
let timer;
|
|
const settle = (error) => {
|
|
off();
|
|
clearTimeout(timer);
|
|
pendingRenders.delete(done);
|
|
if (error) reject(error);
|
|
else resolve();
|
|
};
|
|
const done = () => settle();
|
|
const off = scene.postRender.addEventListener(done);
|
|
pendingRenders.add(done);
|
|
if (timeoutMs !== undefined)
|
|
timer = setTimeout(
|
|
() => settle(new Error('renderOnce timed out')),
|
|
timeoutMs,
|
|
);
|
|
scene.requestRender();
|
|
});
|
|
},
|
|
setTargetFps(fps) {
|
|
viewer.targetFrameRate = fps > 0 ? fps : undefined;
|
|
},
|
|
setTime(ms) {
|
|
const clock = viewer.clock;
|
|
const time = Cesium.JulianDate.fromDate(new Date(ms));
|
|
const changed = !Cesium.JulianDate.equals(clock.currentTime, time);
|
|
clock.currentTime = time;
|
|
// In `preUpdate` the frame under way draws at it: Cesium stamps the
|
|
// frame with this object next.
|
|
if (stampTime) {
|
|
Cesium.JulianDate.clone(time, stampTime);
|
|
// Later preUpdate listeners read the frame's time from the tick.
|
|
if (liveTick) liveTick.time = ms;
|
|
} else if (changed) port.requestRender('time');
|
|
},
|
|
time: () => sceneTime(),
|
|
};
|
|
|
|
return {
|
|
port,
|
|
dispose() {
|
|
disposed = true;
|
|
settleTick(false);
|
|
for (const off of removers.splice(0)) off();
|
|
for (const list of Object.values(listeners)) list.clear();
|
|
heldListeners.clear();
|
|
holds.clear();
|
|
// Waits settle rather than stay attached to a scene gone quiet.
|
|
for (const done of [...pendingRenders]) done();
|
|
},
|
|
};
|
|
}
|
|
|
|
// A Cesium viewer with no renderer bound to it gets a
|
|
// frame port over its scene when code first asks `findFrame` for one.
|
|
provideUnboundFrame((viewer) => {
|
|
const scene = viewer.scene;
|
|
// By shape, not `instanceof`: the viewer may come from another
|
|
// copy of Cesium.
|
|
if (
|
|
PHASES.some(
|
|
(phase) => typeof scene?.[phase]?.addEventListener !== 'function',
|
|
) ||
|
|
typeof scene.requestRender !== 'function' ||
|
|
typeof scene.forceRender !== 'function' ||
|
|
!viewer.clock
|
|
)
|
|
return null;
|
|
return createSceneFrame(viewer);
|
|
});
|