Idle frame rate in the app, timed line batching, KEY REQUIRED status

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.
This commit is contained in:
Sameh Khamis committed 2026-11-16 14:10:01 -08:00
1 parent 84d3e7b5ce
commit 0ed6cde956
33 files changed
+629 -179

No files matched your search

-3
View File
@@ -30,7 +30,6 @@ import { bindRenderer } from '../rendererOf.js';
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../../globeInView.js';
import { createCesiumInput } from './input.js';
import { cesiumCapabilities, createCesiumPorts } from './ports.js';
import { IDLE_FRAME_RATE } from '../../renderGovernor.js';
import { cesiumMapEngine } from './mapEngine.js';
import { installFreeLookHeightLimit } from './freeLookLimit.js';
import { trimStaleSceneCommands } from './sceneCommandRelease.js';
@@ -128,8 +127,6 @@ export function createCesiumRendererPlugin({
capabilities = new ReadonlySet(cesiumCapabilities(viewer.scene));
ports = createCesiumPorts(viewer, {
capabilities,
// Ticking at the display's rate only while anything moves.
idleFps: IDLE_FRAME_RATE,
credentials: { googleApiKey, googleTokens, worldDataToken },
...(cameraController ? { cameraController } : {}),
...(clock ? { now, date: () => clock.date() } : {}),
+19 -5
View File
@@ -3,7 +3,14 @@ import test from 'node:test';
import * as Cesium from 'cesium';
import { CONTRACT_VERSION, checkRendererShape } from '../contract/index.js';
import { rendererOf } from '../rendererOf.js';
import { IDLE_FRAME_RATE } from '../../renderGovernor.js';
import {
_resetRenderGovernorForTest,
holdContinuousRender,
IDLE_FRAME_RATE,
installRenderGovernor,
releaseContinuousRender,
uninstallRenderGovernor,
} from '../../renderGovernor.js';
import { cesiumMapEngine } from './mapEngine.js';
import {
ReadonlySet,
@@ -169,7 +176,7 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
assert.deepEqual(log, ['resize', 'destroy'], 'destroying twice is safe');
});
test('the application’s loop ticks at the idle rate while nothing moves, and at the display’s while anything does', async (t) => {
test('with the governor installed, the loop ticks at the idle rate while nothing moves, and at the display’s while anything does, the renderer’s own holds included', async (t) => {
withDocument(t, fakeDocument());
let viewer;
const plugin = createCesiumRendererPlugin({
@@ -184,12 +191,19 @@ test('the application’s loop ticks at the idle rate while nothing moves, and a
container: {},
signal: new AbortController().signal,
});
installRenderGovernor(renderer.frame);
t.after(() => _resetRenderGovernorForTest());
assert.equal(viewer.targetFrameRate, IDLE_FRAME_RATE, 'idle');
holdContinuousRender('flights');
assert.equal(viewer.targetFrameRate, undefined, 'a layer moving');
releaseContinuousRender('flights');
assert.equal(viewer.targetFrameRate, IDLE_FRAME_RATE);
assert.equal(renderer.frame.diagnostics().targetFps, 0, 'no cap');
const release = renderer.frame.holdContinuous('flights');
assert.equal(viewer.targetFrameRate, undefined);
// As animated visual styles hold it (effects.js).
const release = renderer.frame.holdContinuous('effects:animated');
assert.equal(viewer.targetFrameRate, undefined, 'the renderer’s own hold');
release();
assert.equal(viewer.targetFrameRate, IDLE_FRAME_RATE);
uninstallRenderGovernor(renderer.frame);
renderer.destroy();
});
+3 -2
View File
@@ -106,8 +106,9 @@ export function createApplicationViewer({
}),
);
try {
// Until the frame port takes over (appRenderer.js), tick at the idle
// rate so the startup load does not compete with drawing at 240 fps.
// Until the render governor takes over (src/renderGovernor.js, installed
// by src/app/scene.js), tick at the idle rate so the startup load does
// not compete with drawing at 240 fps.
viewer.targetFrameRate = IDLE_FRAME_RATE;
// No double-click follow or zoom: the Viewer's own (it tracked or
// zoomed to the entity picked) is off. Following is a layer's click.
+38 -28
View File
@@ -413,18 +413,25 @@ function flowTime(speed) {
}
/**
* Drawn frames a line set's lines stay unchanged before the solid ones
* among them settle into a static batch (`settleLines`).
* Milliseconds a line set's lines stay unchanged before the solid ones
* among them settle into a static batch (`settleLines`), and a shape set's
* moved shapes go back into its batches (`settleShapes`). Timed, so a
* batch builds as soon at every refresh rate.
*/
export const SETTLE_FRAMES = 30;
export const SETTLE_MS = 500;
/**
* Fewer lines than this left in the collection beside a static batch wait
* `LONG_SETTLE_FRAMES` to settle, as rebuilding the batch for them costs
* `LONG_SETTLE_MS` to settle, as rebuilding the batch for them costs
* more than drawing them in the collection for a while.
*/
export const FEW_LOOSE_LINES = 64;
export const LONG_SETTLE_FRAMES = 300;
export const LONG_SETTLE_MS = 5000;
/** A line set's settling: waiting the short time, the long one, or done. */
const SETTLE_SHORT = 0;
const SETTLE_LONG = 1;
const SETTLE_DONE = 2;
/**
* Clamped fills a set draws alone at most, each where it last moved
@@ -452,12 +459,14 @@ const animating = (record) => record.gpu?.animating();
* @param {{scene: object, report: (error: unknown) => void,
* capabilities?: ReadonlySet<string>,
* requestRender?: (reason: string) => void,
* date?: () => number}} options `capabilities` gate
* date?: () => number,
* now?: () => number}} options `capabilities` gate
* the GPU icon sets' members (by default they all are); `requestRender`,
* the frame port's, asks for the frames a GPU icon set needs on its own
* (its images packed), under the reason `icons:<set id>` (by default the
* scene's, with no reason); `date`, the epoch ms a `live` motion clock
* reads (by default the system clock's).
* reads (by default the system clock's); `now`, the milliseconds settling
* waits are timed by (`performance.now` by default).
*/
export function createCesiumDraw({
scene,
@@ -465,6 +474,7 @@ export function createCesiumDraw({
capabilities = new Set(GPU_ICON_CAPABILITIES),
requestRender: requestFrame = null,
date = null,
now = () => performance.now(),
}) {
const sets = new Map();
// Fields share the sets' ids.
@@ -3107,7 +3117,8 @@ export function createCesiumDraw({
record.lineBox = settling ? own : null;
record.batch = null;
record.batchPending = null;
record.settled = 0;
record.changedAt = now();
record.settleStage = SETTLE_SHORT;
if (!draped.size && !glows.size && !alone.length && !groundPieces.length) {
noteFlows(record);
return replaceHost(record, own);
@@ -3581,7 +3592,8 @@ export function createCesiumDraw({
* still building drew them as they were, so it is dropped.
*/
function unsettle(record) {
record.settled = 0;
record.changedAt = now();
record.settleStage = SETTLE_SHORT;
const pending = record.batchPending;
if (!pending) return;
record.batchPending = null;
@@ -3736,10 +3748,10 @@ export function createCesiumDraw({
}
/**
* After a draw: a line set whose lines have not changed for
* `SETTLE_FRAMES` drawn frames starts building its static batch, of all
* its lines that `settles`, once some are still in the collection (when
* it has a batch and only a few are, after `LONG_SETTLE_FRAMES`); one
* After a draw: a line set whose lines have not changed for `SETTLE_MS`
* starts building its static batch, of all its lines that `settles`, once
* some are still in the collection (when it has a batch and only a few
* are, after `LONG_SETTLE_MS`); one
* built swaps in for the collection's lines it draws (`swapBatch`).
* Unchanged lines in a polyline collection cost a material id a line
* every frame; in a batch they cost nothing until they change.
@@ -3750,13 +3762,10 @@ export function createCesiumDraw({
swapBatch(record);
return;
}
if (record.settled > LONG_SETTLE_FRAMES) return;
record.settled += 1;
if (
record.settled !== SETTLE_FRAMES &&
record.settled !== LONG_SETTLE_FRAMES
)
return;
if (record.settleStage === SETTLE_DONE) return;
const wait =
record.settleStage === SETTLE_SHORT ? SETTLE_MS : LONG_SETTLE_MS;
if (now() - record.changedAt < wait) return;
// The lines that can settle still in the collection: a batch is
// rebuilt whole for them, so a few wait longer, as a few cost little.
let loose = 0;
@@ -3765,10 +3774,12 @@ export function createCesiumDraw({
if (
record.batch &&
loose < FEW_LOOSE_LINES &&
record.settled < LONG_SETTLE_FRAMES
)
record.settleStage === SETTLE_SHORT
) {
record.settleStage = SETTLE_LONG;
return;
record.settled = LONG_SETTLE_FRAMES + 1;
}
record.settleStage = SETTLE_DONE;
if (!loose) return;
const members = [];
for (const [itemId, part] of record.lineParts) {
@@ -5007,7 +5018,7 @@ export function createCesiumDraw({
if (part.batch.ready) showOn(part.batch, part.id, false);
}
hideRetiringShape(record, item.id);
record.shapesStill = 0;
record.shapesMovedAt = now();
part.solo = true;
part.pendingShow = undefined;
part.look = lookOf(item);
@@ -5081,7 +5092,7 @@ export function createCesiumDraw({
/**
* After a draw: a shape set whose shapes drawn alone have not moved for
* `SETTLE_FRAMES` drawn frames rebuilds, so they go back into its
* `SETTLE_MS` rebuilds, so they go back into its
* batches; the host drawing them alone draws until the rebuild is ready.
*/
function settleShapes(record) {
@@ -5093,9 +5104,8 @@ export function createCesiumDraw({
break;
}
if (!alone) return;
record.shapesStill = (record.shapesStill ?? 0) + 1;
if (record.shapesStill < SETTLE_FRAMES) return;
record.shapesStill = 0;
if (now() - record.shapesMovedAt < SETTLE_MS) return;
record.shapesMovedAt = now();
record.rebuild();
requestRender();
}
+58 -15
View File
@@ -5,10 +5,10 @@ import { bindRenderer, drawOf, findDraw } from '../rendererOf.js';
import {
createCesiumDraw,
FEW_LOOSE_LINES,
LONG_SETTLE_FRAMES,
LONG_SETTLE_MS,
MOVING_SHAPES,
revealUniform,
SETTLE_FRAMES,
SETTLE_MS,
unboundDrawPart,
} from './draw.js';
import { drawHitOf } from './drawHit.js';
@@ -93,6 +93,19 @@ test('nothing to draw into, no port', () => {
});
/** A draw port over a fake scene, with its frame hooks. */
/**
* Settling waits are timed. A test that settles times them by `frameClock`
* (`timeFrames`), which each fake frame moves on by `FRAME_MS`.
*/
const FRAME_MS = 20;
const SETTLE_FRAMES = SETTLE_MS / FRAME_MS;
const LONG_SETTLE_FRAMES = LONG_SETTLE_MS / FRAME_MS;
const frameClock = { ms: 0 };
function timeFrames(t) {
frameClock.ms = 0;
t.mock.method(performance, 'now', () => frameClock.ms);
}
function drawOver(scene = fakeScene()) {
const viewer = { scene };
const draw = drawOf(viewer);
@@ -100,6 +113,7 @@ function drawOver(scene = fakeScene()) {
scene,
draw,
frame() {
frameClock.ms += FRAME_MS;
scene.preRender.raiseEvent();
scene.postRender.raiseEvent();
},
@@ -2978,8 +2992,9 @@ function settlingSet(id = 'stems') {
};
}
test('unchanged solid 3D lines settle into a static batch, changed there in place', () =>
test('unchanged solid 3D lines settle into a static batch, changed there in place', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const { set, frame } = s;
const stem = settleStem;
@@ -3114,8 +3129,24 @@ test('unchanged solid 3D lines settle into a static batch, changed there in plac
set.dispose();
}));
test('many lines left beside a static batch settle as soon as they are unchanged', () =>
test('lines settle after the same time at any refresh rate', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
s.set.set([settleStem('a', 100)]);
const host = s.host();
// Two frames are enough when they are half a second apart.
frameClock.ms = SETTLE_MS - FRAME_MS - 1;
s.frame();
assert.equal(host.length, 1, 'not before the time');
s.frame();
assert.equal(host.length, 2, 'building once it has passed');
s.set.dispose();
}));
test('many lines left beside a static batch settle as soon as they are unchanged', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const { set } = s;
const stems = (height) =>
@@ -3134,8 +3165,9 @@ test('many lines left beside a static batch settle as soon as they are unchanged
set.dispose();
}));
test('an outlined solid line draws one outline material, recoloured in place, and never settles', () =>
test('an outlined solid line draws one outline material, recoloured in place, and never settles', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const outlined = (core, halo) =>
settleStem('ring', 100, {
@@ -3177,8 +3209,9 @@ test('an outlined solid line draws one outline material, recoloured in place, an
s.set.dispose();
}));
test('a line that moves by as many points is written into the points it draws; by more, it takes new ones', () =>
test('a line that moves by as many points is written into the points it draws; by more, it takes new ones', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const style = {
kind: 'solid',
@@ -3232,8 +3265,9 @@ test('a line that moves by as many points is written into the points it draws; b
s.set.dispose();
}));
test('a line under half a pixel wide, which the collection does not draw, never settles', () =>
test('a line under half a pixel wide, which the collection does not draw, never settles', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
s.set.set([
settleStem('thin', 100, { widthPx: 0.25 }),
@@ -3248,8 +3282,9 @@ test('a line under half a pixel wide, which the collection does not draw, never
s.set.dispose();
}));
test('a settling line set keeps what was drawn, not the item a caller changes in place', () =>
test('a settling line set keeps what was drawn, not the item a caller changes in place', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const { set } = s;
const a = settleStem('a', 100);
@@ -3276,8 +3311,9 @@ test('a settling line set keeps what was drawn, not the item a caller changes in
set.dispose();
}));
test('a settling line set rebuilt or gone while its batch builds, or after the viewer went, lets the batch go', () =>
test('a settling line set rebuilt or gone while its batch builds, or after the viewer went, lets the batch go', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const { set } = s;
set.set([settleStem('a', 100), settleStem('b', 200)]);
@@ -3308,17 +3344,22 @@ test('a settling line set rebuilt or gone while its batch builds, or after the v
set.dispose();
}));
test('a static batch that fails to build is reported once, and its lines stay in the collection', () =>
test('a static batch that fails to build is reported once, and its lines stay in the collection', (t) =>
withImageClasses(() => {
timeFrames(t);
const scene = fakeScene();
const reported = [];
const part = createCesiumDraw({
scene,
report: (error) => reported.push(error),
});
const afterFrame = () => {
frameClock.ms += FRAME_MS;
part.afterRender();
};
const set = part.port.lines({ id: 'failing' });
set.set([settleStem('a', 100)]);
for (let i = 0; i < SETTLE_FRAMES; i++) part.afterRender();
for (let i = 0; i < SETTLE_FRAMES; i++) afterFrame();
const host = scene.added[0];
const batch = host.get(1);
assert.ok(batch, 'building');
@@ -3326,11 +3367,11 @@ test('a static batch that fails to build is reported once, and its lines stay in
// batch keeps the error rather than throw it every frame.
batch.update({ passes: { render: true }, mode: Cesium.SceneMode.SCENE3D });
assert.ok(batch.failed, 'kept');
part.afterRender();
afterFrame();
assert.deepEqual(reported, [batch.failed]);
assert.equal(host.length, 1, 'the build is gone');
assert.equal(host.get(0).length, 1, 'the collection draws the line');
for (let i = 0; i < SETTLE_FRAMES * 2; i++) part.afterRender();
for (let i = 0; i < SETTLE_FRAMES * 2; i++) afterFrame();
assert.equal(host.length, 1, 'it settles no more');
assert.equal(reported.length, 1);
set.dispose();
@@ -7482,8 +7523,9 @@ test('an inertial line with a depth-fail style draws behind the surface too, tur
set.dispose();
}));
test('a pattern line draws its image along it, repeated, and an inertial line turns with the sky', () =>
test('a pattern line draws its image along it, repeated, and an inertial line turns with the sky', (t) =>
withImageClasses(() => {
timeFrames(t);
const { scene, draw, frame } = drawOver();
const set = draw.lines({ id: 'orbit-rings' });
const ring = [
@@ -7777,8 +7819,9 @@ const firstGround = (host) => {
return null;
};
test('moved clamped fills go back into a rebuilt batch once they have been still for a while', () =>
test('moved clamped fills go back into a rebuilt batch once they have been still for a while', (t) =>
withTerrainHeights(() => {
timeFrames(t);
const { scene, draw, frame } = drawOver();
const set = draw.shapes({ id: 'settling' });
set.set([groundBox('a', 1), groundBox('b', 2)]);
+7
View File
@@ -161,6 +161,8 @@ export function createSceneFrame(viewer) {
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) =>
@@ -244,8 +246,10 @@ export function createSceneFrame(viewer) {
},
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;
@@ -255,8 +259,10 @@ export function createSceneFrame(viewer) {
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(),
@@ -324,6 +330,7 @@ export function createSceneFrame(viewer) {
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();
+17
View File
@@ -190,6 +190,23 @@ test('a built frame port counts holds per reason, times out a wait, and settles
unbind();
});
test('a built frame port says when its first hold is taken and its last released', () => {
const viewer = fakeViewer();
viewer.useDefaultRenderLoop = false;
const frame = frameOf(viewer);
const heard = [];
const off = frame.onHeldChange((held) => heard.push(held));
const a = frame.holdContinuous('spin');
const b = frame.holdContinuous('glow');
a();
assert.deepEqual(heard, [true], 'once for the first hold');
b();
assert.deepEqual(heard, [true, false], 'once for the last release');
off();
frame.holdContinuous('spin')();
assert.deepEqual(heard, [true, false], 'nothing once off');
});
test('renderNow throws the error Cesium raises on renderError', () => {
const listeners = new Set();
const failure = new Error('worker failed');
+1
View File
@@ -149,6 +149,7 @@ export const CESIUM_CHECKS = new Set([
'renderer.releaseUnused',
'renderer.whenSettled',
'renderer.resize',
'frame.onHeldChange',
'frame.setTargetFps',
'globe.setTerrain',
'globe.setPhotoreal',
+31 -23
View File
@@ -116,22 +116,18 @@ const destroyedError = () => new Error('renderer destroyed');
* @param {{capabilities: ReadonlySet<string>, credentials?: object,
* cameraController?: import('../contract/camera').CameraControllerFactory,
* now?: () => number,
* date?: () => number,
* idleFps?: number}} options
* date?: () => number}} options
* The renderer's capabilities, which gate the members that need them, and
* the credentials its globe loads photoreal tiles and world data with
* (`googleApiKey`, `googleTokens`, `worldDataToken`). `now` is the clock
* each tick reads (`performance.now` by default; a test's virtual one);
* `date`, the epoch ms a `live` motion clock reads (the system clock's by
* default). With `idleFps`, the loop ticks at most that often while no
* hold is out (Cesium ticks its clock and every update listener each
* animation frame even when it draws nothing), and at the display's rate
* while one is; `setTargetFps` then caps both, and the loop starts with no
* cap of its own. Without it, the widget's own rate is the cap.
* With
* `cameraController`, the camera port is that controller's over Cesium's
* camera (`controlledCamera.js`); the ports then have `attachInput` and
* `suspendCamera`, which the renderer's input port is wired with.
* default). The loop's rate starts as the widget's own; once set, it is
* the lower of `setTargetFps`'s and the quality port's `targetFps` cap.
* With `cameraController`, the camera port is that controller's over
* Cesium's camera (`controlledCamera.js`); the ports then have
* `attachInput` and `suspendCamera`, which the renderer's input port is
* wired with.
*/
export function createCesiumPorts(
widget,
@@ -141,7 +137,6 @@ export function createCesiumPorts(
cameraController,
now: clockNow = () => performance.now(),
date = null,
idleFps = 0,
},
) {
const scene = widget.scene;
@@ -290,27 +285,30 @@ export function createCesiumPorts(
// Holds keep the loop drawing every frame; counted per reason.
const holds = new Map();
// Told when the first hold is taken and the last released.
const heldListeners = listenerList(report);
function applyHolds() {
const continuous = holds.size > 0;
if (idleFps > 0) applyRate();
if (scene.requestRenderMode === !continuous) return;
scene.requestRenderMode = !continuous;
}
/** The loop's rate: the cap, and at most `idleFps` while nothing holds. */
function applyRate() {
const idle = holds.size === 0 && idleFps > 0;
const rate =
idle && !(targetFps > 0 && targetFps < idleFps) ? idleFps : targetFps;
widget.targetFrameRate = rate || undefined;
heldListeners.fire(continuous);
}
// On demand means drawn when asked, held or the view changed: never
// because scene time moved on by itself. With no holds yet, it starts so.
scene.maximumRenderTimeChange = Infinity;
scene.requestRenderMode = true;
let suspended = false;
let targetFps =
idleFps <= 0 && widget.targetFrameRate > 0 ? widget.targetFrameRate : 0;
if (idleFps > 0) applyRate();
// The rate `setTargetFps` asks for (the application's), and the quality
// port's cap; the loop draws at the lower of those set.
let targetFps = widget.targetFrameRate > 0 ? widget.targetFrameRate : 0;
let qualityFps = 0;
function applyRate() {
const rate =
targetFps > 0 && qualityFps > 0
? Math.min(targetFps, qualityFps)
: targetFps || qualityFps;
widget.targetFrameRate = rate || undefined;
}
// Pending one-shot renders; disposal rejects them rather than leave them
// attached to a scene that will not render again.
@@ -369,6 +367,7 @@ export function createCesiumPorts(
if (holds.size === 0) scene.requestRender();
};
},
onHeldChange: (cb) => heldListeners.on(cb),
/** Cesium can idle, so it draws on demand. */
mode: () => 'demand',
diagnostics: () => ({
@@ -429,6 +428,7 @@ export function createCesiumPorts(
capabilities,
requestRender: (reason) => frame.requestRender(reason),
date,
now: clockNow,
});
const { port: draw, sets, tilesets } = drawPart;
@@ -494,6 +494,13 @@ export function createCesiumPorts(
report,
tickStarted: () => tickNow,
gl: capabilities.has('gpuTiming') ? webglContext(scene) : null,
fpsCap: {
get: () => qualityFps,
set(fps) {
qualityFps = fps > 0 ? fps : 0;
applyRate();
},
},
});
const creditsPart = createCesiumCredits({
@@ -837,6 +844,7 @@ export function createCesiumPorts(
// A listener that disposes the renderer stops the rest of its event.
for (const list of Object.values(rendererListeners)) list.clear();
for (const list of Object.values(frameListeners)) list.clear();
heldListeners.clear();
drawPart.dispose();
cameraPart.dispose();
creditsPart.dispose();
+32 -18
View File
@@ -507,26 +507,40 @@ test('suspend stops the loop at once and resumes it; target fps caps it', () =>
ports.dispose();
});
test('with an idle rate, idle ticks at it and anything held draws at the display rate', () => {
test('the quality cap and the rate setTargetFps asks for draw at the lower, and neither overwrites the other', () => {
const { widget } = tickingWidget();
const ports = createCesiumPorts(widget, { capabilities: all });
assert.equal(ports.quality.get().targetFps, 0, 'no cap by default');
ports.quality.set({ targetFps: 30 });
ports.frame.setTargetFps(60);
assert.equal(widget.targetFrameRate, 30, 'the cap is lower');
ports.frame.setTargetFps(0);
assert.equal(widget.targetFrameRate, 30, 'the cap holds at the display rate');
assert.equal(ports.quality.get().targetFps, 30, 'the cap reads back');
ports.frame.setTargetFps(24);
assert.equal(widget.targetFrameRate, 24, 'the asked rate is lower');
ports.quality.set({ targetFps: 0 });
assert.equal(widget.targetFrameRate, 24, 'cap lifted');
ports.dispose();
});
test('the loop says when its first hold is taken and its last released, and leaves its rate alone', () => {
const { widget } = tickingWidget();
widget.targetFrameRate = 60;
const ports = createCesiumPorts(widget, { capabilities: all, idleFps: 60 });
assert.equal(widget.targetFrameRate, 60, 'idle: the idle rate');
assert.equal(ports.frame.diagnostics().targetFps, 0, 'no cap of its own');
const release = ports.frame.holdContinuous('flights');
assert.equal(widget.targetFrameRate, undefined, 'held: the display rate');
release();
assert.equal(widget.targetFrameRate, 60);
// A cap holds while held, and idle ticks at the lower of the two.
ports.frame.setTargetFps(30);
assert.equal(widget.targetFrameRate, 30);
const again = ports.frame.holdContinuous('flights');
assert.equal(widget.targetFrameRate, 30);
ports.frame.setTargetFps(120);
assert.equal(widget.targetFrameRate, 120);
again();
assert.equal(widget.targetFrameRate, 60);
assert.equal(ports.frame.diagnostics().targetFps, 120);
const ports = createCesiumPorts(widget, { capabilities: all });
assert.equal(ports.frame.diagnostics().targetFps, 60, 'the widget’s cap');
const heard = [];
const off = ports.frame.onHeldChange((held) => heard.push(held));
const flights = ports.frame.holdContinuous('flights');
const effects = ports.frame.holdContinuous('effects:animated');
flights();
assert.deepEqual(heard, [true], 'once for the first hold');
effects();
assert.deepEqual(heard, [true, false], 'once for the last release');
assert.equal(widget.targetFrameRate, 60, 'its rate is its caller’s');
off();
ports.frame.holdContinuous('flights')();
assert.deepEqual(heard, [true, false], 'heard no more once off');
ports.dispose();
});
+11 -4
View File
@@ -15,7 +15,10 @@
* at 0. While tile detail is lowered, a tileset added later is brought
* to it on the next drawn frame; an error is written only when it
* changes, since each write resets the tileset's memory-adjusted error.
* - `targetFps`: the frame port's target frame rate, 0 for none.
* - `targetFps`: a cap on the loop's frame rate, 0 for none (`fpsCap`: by
* default the frame port's own `setTargetFps`; the renderer's ports keep
* it apart from the rate the application sets there, and draw at the
* lower of the two).
*
* Building the port changes nothing in the scene; each setting is applied
* when it is first set, and a detail set back to 1 hands each tileset and
@@ -156,6 +159,10 @@ export function createCesiumQuality(
limits = Cesium.ContextLimits,
tickStarted = null,
gl = webglContext(widget.scene),
fpsCap = {
get: () => frame.diagnostics?.().targetFps ?? 0,
set: (fps) => frame.setTargetFps(fps),
},
},
) {
const scene = widget.scene;
@@ -171,7 +178,7 @@ export function createCesiumQuality(
: [];
// What the scene had before the port first changed it: the defaults.
const builtFps = frame.diagnostics?.().targetFps ?? 0;
const builtFps = fpsCap.get();
let msaaAtBuild = null;
let shadowsAtBuild = null;
// Cesium clamps the count to the context's only when it is set.
@@ -334,7 +341,7 @@ export function createCesiumQuality(
},
targetFps(value) {
const fps = inRange(value, 0, MAX_FPS);
if (fps !== null) frame.setTargetFps(fps);
if (fps !== null) fpsCap.set(fps);
},
};
@@ -343,7 +350,7 @@ export function createCesiumQuality(
pixelRatio,
tiles3dDetail: detail.tiles,
terrainDetail: detail.terrain,
targetFps: frame.diagnostics?.().targetFps ?? 0,
targetFps: fpsCap.get(),
};
if (scene.shadowMap) settings.shadows = Boolean(scene.shadowMap.enabled);
if (msaaOptions().length > 1)
+20
View File
@@ -5769,6 +5769,26 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
);
},
),
check(
'frame.onHeldChange',
'onHeldChange is told the first hold and the last release, whoever holds, and nothing once off',
(h, r) => {
const heard = [];
const off = r.frame.onHeldChange((held) => heard.push(held));
try {
const one = r.frame.holdContinuous('conformance:one');
const two = r.frame.holdContinuous('conformance:two');
one();
deepEqual(heard, [true], 'once for the first hold');
two();
deepEqual(heard, [true, false], 'once for the last release');
} finally {
off();
}
r.frame.holdContinuous('conformance:after')();
deepEqual(heard, [true, false], 'nothing once off');
},
),
check(
'frame.setTargetFps',
'setTargetFps caps the loop; diagnostics say the cap, 0 the display rate',
+5
View File
@@ -73,6 +73,11 @@ export interface FramePort {
requestRender(reason: string): void;
/** Keep drawing every frame until released. Holds are counted. */
holdContinuous(reason: string): Release;
/**
* Hear the loop start drawing every frame (its first hold, whoever took
* it) and stop (its last released): `true` held, `false` not.
*/
onHeldChange(cb: (held: boolean) => void): Off;
mode(): 'demand' | 'continuous';
diagnostics(): FrameDiagnostics;
/** Stop ticking while the page is hidden; resume on `false`. */
+1
View File
@@ -118,6 +118,7 @@ export const PORTS = deepFreeze({
'on',
'requestRender',
'holdContinuous',
'onHeldChange',
'mode',
'diagnostics',
'suspend',
+20 -1
View File
@@ -187,6 +187,16 @@ export function createStubRenderer(options = {}) {
const pendingReasons = [];
const continuous = new Map();
let holdSeq = 0;
// Told when the first hold is taken and the last released.
const heldListeners = new Set();
function tellHeld(held) {
for (const entry of [...heldListeners])
try {
entry.cb(held);
} catch (error) {
report(error);
}
}
const phaseListeners = { preUpdate: [], preRender: [], postRender: [] };
// The frame under way while its `preUpdate` listeners run.
let updating = null;
@@ -345,7 +355,16 @@ export function createStubRenderer(options = {}) {
holdContinuous(reason) {
const key = ++holdSeq;
continuous.set(key, String(reason));
return () => continuous.delete(key);
if (continuous.size === 1) tellHeld(true);
return () => {
if (!continuous.delete(key)) return;
if (continuous.size === 0) tellHeld(false);
};
},
onHeldChange(cb) {
const entry = { cb };
heldListeners.add(entry);
return () => heldListeners.delete(entry);
},
mode: () => 'demand',
diagnostics: () => ({