Moving layers redraw as fast as they move on screen, 3 to 30 times a second

Satellites, flights and vessels held the render loop at the display's rate
while they were on, so a view of slow-moving marks drew 100-170 frames a
second. Each now reads how fast its fastest mark crosses the screen and asks
for a frame whenever that mark would move half a pixel: never fewer than 3 a
second (animated marks never stall), never more than 30 (room in the frame
for the rest of the scene). Below 12 a second the layer asks for one frame at
a time on a timer; from there it holds the loop at 15, 20 or 30, rates the
display divides evenly (renderPace.js).

The render governor takes a rate per hold: the highest asked wins, a hold
with no rate draws at the display's rate. Following a target is capped at
30. Steering the camera (a drag, a pinch, the wheel) still draws at the
display's rate; it ends when the last pointer lifts, the wheel rests, or the
page loses focus or is hidden.

Draw sets whose motion clock is the owner's ('frames: owner') ask for no
frames for moving rows or for rows written in place; the owner's pace does.
The vessels layer places its contacts at most 30 times a second and writes
every move of a pass to its icons in one batch.

Measured in Chrome on a still camera (draws a second, before -> after):
satellites over the whole globe 162 -> 6, at 1,500 km 114 -> 30; flights over
the whole globe 132 -> 10, Europe 53 -> 5, London 114 -> 9. Planes move at
most 0.6 px between draws.
This commit is contained in:
Sameh Khamis committed 2026-11-23 18:56:44 -08:00
1 parent 43bd25382d
commit d50f04efeb
30 files changed
+1249 -69

No files matched your search

+3 -1
View File
@@ -39,6 +39,7 @@ import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
import {
getRenderGovernorDiagnostics,
governorRequestRender,
FOLLOW_FRAME_RATE,
holdContinuousRender,
releaseContinuousRender,
} from '../renderGovernor.js';
@@ -273,7 +274,8 @@ export function createApplicationTools({
// The follow camera recomputes the tracked target's dead-reckon position
// every frame — tracking anything is a per-frame animation. (perf wave 2)
const removeTrackingListener = onFollowChanged(viewer, (followed) => {
if (followed) holdContinuousRender('tracked-entity');
if (followed)
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
else releaseContinuousRender('tracked-entity');
});
+15 -1
View File
@@ -465,6 +465,8 @@ export function createAircraftIcons({
* @type {Map<string, {drawn: number, checked: number}>}
*/
const rotors = new Map();
/** When a rotor in view was last given a new frame (wall ms). */
let rotorDrawnAtMs = -Infinity;
/** The delayed instant (epoch ms) every untracked contact is drawn at. */
const _displayMs = () =>
@@ -492,7 +494,8 @@ export function createAircraftIcons({
const motionClock = (scene) =>
scene
? { kind: 'scene' }
: { kind: 'live', delayMs: displayDelay.currentMs };
: // The layer's pace asks for the frames its moving rows need.
{ kind: 'live', delayMs: displayDelay.currentMs, frames: 'owner' };
/**
* Once a frame: move the display delay on, and put the set's motion on
@@ -930,6 +933,7 @@ export function createAircraftIcons({
const query = viewer ? findQuery(viewer) : null;
const eye = viewer ? findCamera(viewer)?.pose()?.position : null;
let active = 0;
let fading = 0;
for (const id of icons.ids()) {
if (!icons.shown(id) && !state._models.has(id)) continue;
const item = icons.item(id);
@@ -952,10 +956,13 @@ export function createAircraftIcons({
spriteHalfHeightPx: item.size[1] * half,
});
if (focus.active || focus.transitioning) active++;
if (focus.transitioning) fading++;
if (focusAlphaNeedsWrite(current, focus.factor))
icons.setFocus(id, focus.factor);
}
state._iconFocusActive = active;
// Rows still fading in or out, for the layer's pace.
state._iconFocusFading = fading;
}
/**
@@ -1043,6 +1050,7 @@ export function createAircraftIcons({
if (!_aboveHorizon(position, occluder)) continue;
if (inView && !inView(position)) continue;
rotor.drawn = frame;
rotorDrawnAtMs = nowMs;
if (tracked) {
parts.tracking?._syncTrackedBillboardImage?.();
continue;
@@ -1106,6 +1114,11 @@ export function createAircraftIcons({
return rotors.size > 0;
}
/** When a rotor in view was last given a new frame (wall ms), for the pace. */
function _rotorDrawnAtMs() {
return rotorDrawnAtMs;
}
/** Add a row for a new contact, hidden while it is the tracked one. */
function _addIcon(icao24) {
state._icons.put(_baseItem(icao24, icao24 !== state._trackedIcao), {
@@ -1178,6 +1191,7 @@ export function createAircraftIcons({
_fleetLook,
_turnRotors,
_rotorsTurning,
_rotorDrawnAtMs,
_addIcon,
_forgetContact,
_iconIds,
+25 -5
View File
@@ -37,7 +37,11 @@ test('following the world clock, contacts draw at the world’s time on the scen
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
// Live: a poll interval behind real time, on the delayed live clock.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 30_000,
frames: 'owner',
});
assert.equal(icons._displayMs(), Date.now() - 30_000);
following = true;
assert.equal(icons._displayMs(), WORLD_MS, 'the world’s time, no delay');
@@ -45,7 +49,11 @@ test('following the world clock, contacts draw at the world’s time on the scen
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 30_000,
frames: 'owner',
});
icons._disposeIcons();
});
@@ -68,7 +76,11 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 30_000,
frames: 'owner',
});
// Reports 90 s old every 30 s: the delay heads for about two minutes.
for (let i = 0; i < 20; i++)
delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000);
@@ -76,7 +88,11 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
t.mock.timers.setTime(WORLD_MS + 10_000);
icons._syncMotionClock();
// 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 });
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 32_000,
frames: 'owner',
});
assert.equal(icons._displayMs(), Date.now() - 32_000);
// Following the world clock: no delay, and it is not moved on meanwhile.
following = true;
@@ -87,7 +103,11 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
assert.equal(delay.currentMs, 32_000);
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 });
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 34_000,
frames: 'owner',
});
icons._disposeIcons();
});
+77
View File
@@ -14,6 +14,12 @@ import {
showModel,
} from './modelRecord.js';
import { modelDrawnScale } from './modelVisualAnchor.js';
import {
createRenderPace,
createScreenSpeed,
paceHzForSpeed,
} from '../renderPace.js';
import { ROTOR_FPS } from './rotorFrames.js';
import { fleetModelSet, fleetPartTable } from './fleetModels.js';
import { aircraftLayerPartState } from './modelPartDrivers.js';
import { findCamera, findDraw, rendererOf } from '../render/rendererOf.js';
@@ -119,6 +125,70 @@ export function createAircraftModels({
let instances = 0;
/** The fleet items this tick wrote, sent together when it ends. */
let pendingItems = [];
// The pace: how often the fleet is drawn while nothing else draws
// (renderPace.js). The icons move on the GPU, so a frame is all a move
// takes; an airliner crosses a hundredth of a pixel a second on the whole
// globe and hundreds from close by, so the rate follows the fastest icon
// in view.
const pace = createRenderPace({ owner: setPrefix, render: services.render });
const screenSpeed = createScreenSpeed();
/** How often the icons' on-screen speed is read, in ms. */
const PACE_READ_MS = 250;
/** Each icon's move is read over this much of its drawn path, in ms. */
const PACE_SPAN_MS = 1000;
/** While icons fade for a focus change, they are drawn this often. */
const PACE_FADE_HZ = 20;
/** A rotor drawn this recently is in view. */
const PACE_ROTOR_SEEN_MS = 600;
let paceReadMs = -Infinity;
let pacePxPerSec = 0;
/**
* The fastest icon in view's speed on screen, in pixels a second: each
* shown icon's drawn position now and PACE_SPAN_MS on, which takes in a
* new fix being blended in as well as its flight.
*/
function _readIconSpeed(pose) {
const icons = state._icons;
if (!icons || !screenSpeed.begin(pose, _viewport().height)) return 0;
const t = parts.icons._displayMs();
for (const id of icons.ids()) {
if (!icons.shown(id)) continue;
screenSpeed.add(
icons.position(id, t),
icons.position(id, t + PACE_SPAN_MS),
);
}
return screenSpeed.pxPerSec(PACE_SPAN_MS / 1000);
}
/**
* Draws a second the fleet needs as the camera stands (the pace clamps
* it to its range). Infinity: as often as the pace allows.
*/
function _paceHz(nowMs = Date.now()) {
const pose = _pose();
if (!pose?.position) return Infinity;
// Models, and the Cockpit's contacts, are moved on every frame.
if (
state._cockpitContactMode ||
state._models.size ||
_modelRegimeActive(pose)
)
return Infinity;
if (nowMs - paceReadMs >= PACE_READ_MS) {
paceReadMs = nowMs;
pacePxPerSec = _readIconSpeed(pose);
}
let hz = paceHzForSpeed(pacePxPerSec);
if (state._iconFocusFading > 0 && hz < PACE_FADE_HZ) hz = PACE_FADE_HZ;
// A helicopter in view turns its rotor ROTOR_FPS times a second.
const rotorAtMs = parts.icons._rotorDrawnAtMs?.() ?? -Infinity;
if (nowMs - rotorAtMs < PACE_ROTOR_SEEN_MS && hz < ROTOR_FPS)
hz = ROTOR_FPS;
return hz;
}
/** The ground sample's exclusions, kept while the sets they name live. */
let exclusions = null;
@@ -952,6 +1022,7 @@ export function createAircraftModels({
}
}
state._icons?.flush();
pace.set(_paceHz());
}
}
@@ -1136,5 +1207,11 @@ export function createAircraftModels({
_handBackDeselected,
_updateTrackedModel,
_fleetTick,
_paceHz,
_startPace: () => {
paceReadMs = -Infinity;
pace.start();
},
_stopPace: pace.stop,
};
}
+18 -14
View File
@@ -34,6 +34,7 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { PACE_MIN_HZ } from '../renderPace.js';
import {
DETECTION_ENABLE_FADE_MS,
@@ -448,31 +449,34 @@ test('the render-governor gate covers the parked case, with teeth on the painter
// until some unrelated frame happens along.
//
// It cannot, and the reason is structural rather than lucky: an AIR bracket can
// only exist while an aircraft layer is enabled, and both aircraft layers take a
// continuous-render hold for their own per-frame fleet animation. So for exactly
// as long as there is anything to bracket, the scene is rendering every frame
// and the overlay repaints with it. (Measured live 2026-08-23 on a parked
// camera: an outside-aircraft population change moved the painted bracket count
// with no camera input, holds = ["flights"], requestRenderMode = false.)
// only exist while an aircraft layer is enabled, and both aircraft layers pace
// the render loop for their fleet (src/renderPace.js): never fewer than
// PACE_MIN_HZ frames a second however still the camera, more as the fleet
// moves faster on screen. So for exactly as long as there is anything to
// bracket, the scene keeps drawing and the overlay repaints with it, at most a
// third of a second behind. (Before the pace the layers held the loop on every
// frame; measured live 2026-08-23 on a parked camera, an outside-aircraft
// population change moved the painted bracket count with no camera input.)
//
// That is a COUPLING, so it deserves a pin. If a later perf pass strips these
// holds the way it stripped detection's — a reasonable-looking change — bracket
// That is a COUPLING, so it deserves a pin. If a later perf pass stops the
// aircraft layers pacing, or lets the pace's floor reach zero, bracket
// promptness goes with them, silently. This test is where that shows up.
test('aircraft brackets stay prompt because the aircraft layers hold the render loop', async () => {
test('aircraft brackets stay prompt because the aircraft layers pace the render loop', async () => {
assert.ok(PACE_MIN_HZ >= 3, 'a still scene still draws a few times a second');
for (const file of ['./flights.js', './militaryFlights.js']) {
const source = readLayerSource(new URL(file, import.meta.url));
const enable = /\n([ \t]*)enable\([\s\S]*?\n\1\},/.exec(source)?.[0];
assert.ok(enable, `${file}: enable() is still identifiable`);
assert.match(
enable,
/holdContinuousRender\('(flights|military)'\)/,
`${file}: enabling the layer must hold continuous render — detection no longer ` +
'holds one, so this is what keeps its AIR brackets repainting on a parked scene',
/parts\.rendering\._startPace\(\)/,
`${file}: enabling the layer must start its pace — detection no longer ` +
'holds the loop, so this is what keeps its AIR brackets repainting on a parked scene',
);
assert.match(
source,
/releaseContinuousRender\('(flights|military)'\)/,
`${file}: and the hold must be released, or the governor can never idle`,
/parts\.rendering\._stopPace\(\)/,
`${file}: and the pace must be stopped, or the governor can never idle`,
);
}
});
+4 -4
View File
@@ -11,7 +11,6 @@ export function createLifecycle({
}) {
const { clearFocusTarget } = services.focus;
const { onMilitaryLayerActiveChange } = services.militaryRegistry;
const { holdContinuousRender, releaseContinuousRender } = services.render;
const { ensureGeoidReady } = services.geoid;
const { registerPickOwner, unregisterPickOwner } = services.picking;
@@ -112,7 +111,8 @@ export function createLifecycle({
*/
enable(viewer) {
if (flightState._icons) flightState._icons.show = true;
holdContinuousRender('flights'); // per-frame animator (perf wave 2)
// Drawn as often as the fleet moves on screen (renderPace.js).
parts.rendering._startPace();
parts.rendering._setModelsShown(true);
parts.tracking._setCockpitContactMode(
document.body.classList.contains('cockpit-mode'),
@@ -168,7 +168,7 @@ export function createLifecycle({
parts.controller._abortActiveUpdates();
parts.tracking._cancelPendingTrackingRestore();
if (flightState._icons) flightState._icons.show = false;
releaseContinuousRender('flights');
parts.rendering._stopPace();
parts.rendering._releaseModels();
parts.rendering._setModelsShown(false);
parts.tracking._clearTracking();
@@ -208,7 +208,7 @@ export function createLifecycle({
flightState._enrichActive = 0;
flightState._enrichLastDispatchMs = 0;
parts.controller._abortActiveUpdates();
releaseContinuousRender('flights'); // direct-destroy path (perf wave 2 fix)
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
parts.tracking._clearTracking();
parts.tracking._destroyTrail();
parts.tracking._cancelPendingTrackingRestore();
+4 -4
View File
@@ -10,7 +10,6 @@ export function createLifecycle({
resolveAsset,
}) {
const { clearFocusTarget } = services.focus;
const { holdContinuousRender, releaseContinuousRender } = services.render;
const { ensureGeoidReady } = services.geoid;
const { registerPickOwner, unregisterPickOwner } = services.picking;
const { setMilitaryLayerActive } = services.militaryRegistry;
@@ -93,7 +92,8 @@ export function createLifecycle({
*/
enable(viewer) {
if (flightState._icons) flightState._icons.show = true;
holdContinuousRender('military'); // per-frame animator (perf wave 2)
// Drawn as often as the fleet moves on screen (renderPace.js).
parts.rendering._startPace();
parts.rendering._setModelsShown(true);
parts.tracking._setCockpitContactMode(
document.body.classList.contains('cockpit-mode'),
@@ -151,7 +151,7 @@ export function createLifecycle({
parts.controller._abortActiveUpdates();
parts.tracking._cancelPendingTrackingRestore();
if (flightState._icons) flightState._icons.show = false;
releaseContinuousRender('military');
parts.rendering._stopPace();
parts.rendering._releaseModels();
parts.rendering._setModelsShown(false);
parts.tracking._clearTracking();
@@ -191,7 +191,7 @@ export function createLifecycle({
flightState.timeline?.stop();
flightState.lifetime.abort();
parts.controller._abortActiveUpdates();
releaseContinuousRender('military'); // direct-destroy path (perf wave 2 fix)
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
parts.tracking._clearTracking();
parts.tracking._destroyTrail();
parts.tracking._cancelPendingTrackingRestore();
+2
View File
@@ -292,6 +292,8 @@ function recordingRendering(state) {
if (point) point.show = show;
},
_setPointsShown() {},
_startPace() {},
_stopPace() {},
_setOrbitPathShown(noradId, show) {
if (state._orbitPaths.has(noradId)) rings.set(noradId, show);
},
+4 -4
View File
@@ -30,7 +30,6 @@ export function createLifecycle({
// Unregistered on destroy, so a page that builds the app again holds no old layer; init
// registers it again.
let uncover = worldClock.register(clockSource);
const { holdContinuousRender, releaseContinuousRender } = services.render;
const { registerPickOwner, unregisterPickOwner } = services.picking;
/** Run the shared per-frame tick before each frame draws. */
@@ -98,7 +97,8 @@ export function createLifecycle({
enable(viewer) {
layerState._enabled = true;
holdContinuousRender('satellites'); // per-frame animator (perf wave 2)
// Drawn as often as the dots move on screen (rendering.js, the pace).
parts.rendering._startPace();
parts.rendering._setPointsShown(
parts.controls.satelliteVisualsVisible(
layerState._enabled,
@@ -137,7 +137,7 @@ export function createLifecycle({
parts.catalog._abortActiveUpdates();
parts.tracking._cancelPendingTrackingRestore();
layerState._enabled = false;
releaseContinuousRender('satellites');
parts.rendering._stopPace();
parts.rendering._setPointsShown(false);
parts.rendering._setOrbitPathsShown(false);
for (const model of parts.stationModels ?? [])
@@ -165,7 +165,7 @@ export function createLifecycle({
parts.catalog._abortActiveUpdates();
uncover?.();
uncover = null;
releaseContinuousRender('satellites'); // direct-destroy path (perf wave 2 fix)
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
layerState._enabled = false;
parts.tracking._clearTracking();
parts.tracking._cancelPendingTrackingRestore();
+101 -1
View File
@@ -2,6 +2,11 @@ import { drawOf, findCamera, findQuery } from '../../render/rendererOf.js';
import { distance } from '../../geo/vector.js';
import { gstime } from 'satellite.js';
import { reckonEarthFixed, sampleOrbit } from './motion.js';
import {
createRenderPace,
createScreenSpeed,
paceHzForSpeed,
} from '../../renderPace.js';
import {
ISS_NORAD,
ORBIT_REBAKE_MS,
@@ -104,6 +109,49 @@ export function createRendering({
/** The frame the tick last ran in: the tracked sample's cache key. */
let renderedFrame = -1;
// The pace: how often the dots are drawn while nothing else draws. A dot
// in low orbit crosses under half a pixel a second on the whole globe and
// hundreds of pixels a second from close by, so the rate follows the
// fastest dot in view (renderPace.js) instead of holding the loop at the
// display's rate.
const pace = createRenderPace({
owner: 'satellites',
render: services.render,
});
const screenSpeed = createScreenSpeed();
/** While dots fade for a focus change, they are drawn this often. */
const PACE_FADE_HZ = 20;
/** The least time a reading spans: shorter, and the clock's jitter shows. */
const PACE_READ_MS = 100;
/** Wall time of the last reading of the dots' speed, and its result. */
let paceWallMs = 0;
let pacePxPerSec = 0;
/** Where the eye was at the last reading: a dot's move is taken from it. */
const paceEye = { x: 0, y: 0, z: 0 };
const paceEyeMove = { x: 0, y: 0, z: 0 };
let paceFading = false;
/** Whether the layer is on and paced: its dots' speed is read. */
let pacing = false;
/** Set the rate from the fastest dot seen; called once a drawn frame. */
function _applyPace() {
let hz = paceHzForSpeed(pacePxPerSec);
if (paceFading && hz < PACE_FADE_HZ) hz = PACE_FADE_HZ;
pace.set(hz);
}
function _startPace() {
pacing = true;
paceWallMs = 0;
pacePxPerSec = 0;
pace.start();
}
function _stopPace() {
pacing = false;
pace.stop();
}
/**
* Build the rigid ECEF transform that keeps an orbit path baked at one GMST
* aligned with live SGP4 positions propagated at another epoch: a column-
@@ -654,6 +702,26 @@ export function createRendering({
function _reckonPoints(nowMs) {
const gmst = gstime(new Date(nowMs));
// The pace's reading, at most every PACE_READ_MS: how far the fastest
// dot in view moved on screen since the last one.
const wallMs = performance.now();
const sinceS = (wallMs - paceWallMs) / 1000;
const reading = pacing && wallMs - paceWallMs >= PACE_READ_MS;
const camera = reading ? findCamera(layerState._viewer) : null;
const view = camera?.pose?.() ?? null;
const eye = view?.position;
// The eye's own move since the last reading: a camera riding one
// satellite sees its neighbours nearly still.
if (eye) {
paceEyeMove.x = eye.x - paceEye.x;
paceEyeMove.y = eye.y - paceEye.y;
paceEyeMove.z = eye.z - paceEye.z;
}
const measure =
reading &&
sinceS < 5 &&
screenSpeed.begin(view, camera?.viewport?.().height, paceEyeMove);
const lastWallMs = paceWallMs;
for (const [noradId, point] of layerState._points) {
if (!point.show || noradId === layerState._trackedNorad) continue;
const sat = layerState._catalog.get(noradId);
@@ -669,7 +737,24 @@ export function createRendering({
reckonEarthFixed(sample, nowMs, gmst, point.pos);
_markDirty(noradId);
sat.reckonedAtMs = nowMs;
if (!reading) continue;
// Where the dot was at the last reading, kept on its satellite. One
// not read then (hidden, or just loaded) is not measured: it jumps.
const from = (sat.paceFrom ??= { x: 0, y: 0, z: 0, atMs: -1 });
if (measure && from.atMs === lastWallMs) screenSpeed.add(from, point.pos);
from.x = point.pos.x;
from.y = point.pos.y;
from.z = point.pos.z;
from.atMs = wallMs;
}
if (!reading) return;
if (eye) {
paceEye.x = eye.x;
paceEye.y = eye.y;
paceEye.z = eye.z;
}
if (measure) pacePxPerSec = screenSpeed.pxPerSec(sinceS);
paceWallMs = wallMs;
}
/**
@@ -691,6 +776,7 @@ export function createRendering({
renderedFrame = Number.isFinite(t?.frame) ? t.frame : renderedFrame + 1;
if (layerState._enabled) _tickAfterFrame();
_flushPoints();
_applyPace();
}
/** The tick's part read before the frame's own sample is taken. */
@@ -733,10 +819,18 @@ export function createRendering({
if (layerState._params.showPoints) {
const worldMs = layerState.now();
// The dots move at the pace, not on every drawn frame: moving them
// asks for the next frame, so a frame drawn for any reason would keep
// the loop drawing; and a drag over the whole globe need not send
// every dot to the GPU sixty times a second to move it a hair.
if (pace.take()) {
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
layerState._lastReckonMs = worldMs;
_reckonPoints(worldMs);
}
} else {
pacePxPerSec = 0;
}
// Keep the tracked satellite's (hidden) dot on the per-frame epoch shared
// with label + camera — runs after _propagateAll so the per-frame sample
@@ -781,8 +875,10 @@ export function createRendering({
if (
!layerState._params.showPoints ||
!focusPassIsNeeded(target, layerState._activeFocusCount)
)
) {
paceFading = false;
return;
}
if (nowMs - layerState._lastFocusUpdate < 80) return;
layerState._lastFocusUpdate = nowMs;
const query = findQuery(layerState._viewer);
@@ -837,6 +933,7 @@ export function createRendering({
).color,
});
layerState._activeFocusCount = result.activeCount;
paceFading = Boolean(result.transitioning);
}
/**
@@ -939,6 +1036,9 @@ export function createRendering({
_propagateAll,
_reckonPoints,
_preRenderTick,
_startPace,
_stopPace,
_paceForTest: () => ({ ...pace.state(), pxPerSec: pacePxPerSec }),
_updatePointFocus,
applySatellitePointFocusDeemphasis,
_flushPoints,
+71 -9
View File
@@ -5,6 +5,8 @@ import { VISIBILITY_UPDATE_MS } from './policy.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { layerPlacement } from '../../data/placementProvider.js';
import * as Cesium from 'cesium';
import { PACE_MAX_HZ, PACE_MIN_HZ } from '../../renderPace.js';
import { createVesselIconBook } from './iconBook.js';
// The layer must let the scene idle: it asks for frames for forced passes,
// for vessels that move, and one trailing frame after the camera stops, and
@@ -270,7 +272,7 @@ test('a placement that places nothing asks for no frames; one that places a draw
assert.deepEqual(requests, ['ais-vessels-placement']);
});
test('a vessel moving visibly asks for its next frame as soon as it moves half a pixel; a slow one once a second', (t) => {
test('a vessel moving visibly asks for its next frame as soon as it moves half a pixel, at most 30 a second; a slow one three times a second', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
@@ -295,23 +297,24 @@ test('a vessel moving visibly asks for its next frame as soon as it moves half a
};
drawnVisual({ camera, scene: {}, canvas: { clientHeight: 1000 } });
// How long after a pass the next frame is asked for, once the vessel moved
// `dLat` in the 16 ms since the pass before.
// `dLat` in the 40 ms since the pass before (passes come at most 30 a
// second, so a frame 16 ms on would not move it).
const waitAfterStep = (dLat) => {
layer.testing._runPlacementPassForTest();
advance(1_000); // whatever frame that asked for comes and goes
assert.equal(timers.size, 0);
mono += 16;
mono += 40;
spot = { lat: spot.lat + dLat, lon: spot.lon };
layer.testing._runPlacementPassForTest();
assert.equal(timers.size, 1);
const [timer] = [...timers.values()];
return timer.at - now();
};
// About 11 m in a frame, 20 km away: over half a pixel, so the next frame
// is asked for within the frame.
assert.ok(waitAfterStep(0.0001) <= 16);
// About 1 cm in a frame: half a pixel takes seconds, so once a second.
assert.equal(waitAfterStep(0.0000001), 1000);
// About 11 m in a pass, 20 km away: over half a pixel, so the next frame
// is asked for within the pass's own span.
assert.ok(waitAfterStep(0.0001) <= 40);
// About 1 cm in a frame: half a pixel takes seconds, so at the floor.
assert.ok(Math.abs(waitAfterStep(0.0000001) - 1000 / PACE_MIN_HZ) < 1e-6);
// A 2D view 40 km across in 1,000 px: 11 m is over a quarter pixel, so the
// next frame comes within two frames.
camera.frustum = new Cesium.OrthographicOffCenterFrustum({
@@ -324,7 +327,20 @@ test('a vessel moving visibly asks for its next frame as soon as it moves half a
});
camera.viewMatrix = Cesium.Matrix4.IDENTITY;
drawnVisual({ camera, scene: {}, canvas: { clientWidth: 1000 } });
assert.ok(waitAfterStep(0.0001) <= 32);
assert.ok(waitAfterStep(0.0001) <= 80);
// A frame sooner than a thirtieth of a second after a pass moves nothing:
// the next pass is asked for when one may come.
mono += 100;
spot = { lat: spot.lat + 0.001, lon: spot.lon };
layer.testing._runPlacementPassForTest();
advance(1_000);
const drawn = layer.testing._vesselVisualForTest(record).drawnLat;
mono += 16;
spot = { lat: spot.lat + 0.001, lon: spot.lon };
layer.testing._runPlacementPassForTest();
assert.equal(layer.testing._vesselVisualForTest(record).drawnLat, drawn);
const [held] = [...timers.values()];
assert.ok(Math.abs(held.at - now() - (1000 / PACE_MAX_HZ - 16)) < 1e-6);
});
test('following the clock moves drawn vessels in place each world time, prepares missing ones and leaves hidden ones be', (t) => {
@@ -722,3 +738,49 @@ test('following the clock, a vessel the visibility pass shows before the clock p
);
assert.ok(Math.abs(Cesium.Math.toDegrees(latitude) - 52.43) < 1e-6);
});
test('a placement pass writes the vessels it moved to the set at once, not one a vessel', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
const spots = new Map([
['111', { lat: 51.93, lon: 4.05 }],
['222', { lat: 51.94, lon: 4.06 }],
]);
const { layer, camera } = setup({
placement: { layer: () => ({ place: (id) => spots.get(id) }) },
});
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const writes = [];
const icons = createVesselIconBook({
id: 'vessels',
upsert: (list) => writes.push(list.map((item) => item.id)),
remove: noop,
});
const records = [
{ mmsi: '111', lat: 51.93, lon: 4.05 },
{ mmsi: '222', lat: 51.94, lon: 4.06 },
];
const viewer = { camera, scene: {}, canvas: { clientHeight: 1000 } };
bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({ viewer, records, icons });
for (const record of records) {
const visual = layer.testing._prepareVesselVisualForTest(record);
visual.visible = true;
// Drawn already, as the layer draws a vessel it was sent.
icons.put({ id: visual.iconId }, { expiresAt: null });
}
layer.testing._runPlacementPassForTest();
mono += 100;
for (const [id, spot] of spots)
spots.set(id, { lat: spot.lat + 0.001, lon: spot.lon });
writes.length = 0;
layer.testing._runPlacementPassForTest();
assert.deepEqual(writes, [['111', '222']]);
});
+98 -9
View File
@@ -48,13 +48,19 @@ import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { cssColor } from '../../render/color.js';
import { KNOT_MPS } from '../../data/units.js';
import { PACE_MAX_HZ, PACE_MIN_HZ, PACE_STEP_PX } from '../../renderPace.js';
/** A moving vessel's next frame is asked for once it would move this far on
* screen (pixels), so it glides when it moves visibly and the scene idles
* when it does not. */
const VESSEL_STEP_PX = 0.5;
/** A frame is asked for at least this often while any drawn vessel moves. */
const PLACEMENT_FRAME_MS = 1000;
const VESSEL_STEP_PX = PACE_STEP_PX;
/** A frame is asked for at least this often while any drawn vessel moves:
* the floor every moving layer keeps (renderPace.js). */
const PLACEMENT_FRAME_MS = 1000 / PACE_MIN_HZ;
/** And at most this often: the most a moving layer draws (renderPace.js). */
const PLACEMENT_MIN_WAIT_MS = 1000 / PACE_MAX_HZ;
/** While vessels' emphasis changes for a focus, they are drawn this often. */
const VESSEL_FOCUS_FPS = 20;
/** How often each vessel not drawn moves on as the world clock plays (wall
* ms), so one that comes into view is judged where it is. */
const HIDDEN_FOLLOW_MS = 250;
@@ -482,6 +488,12 @@ export function createRendering({
function putIcon(visual, item) {
if (!segmentsOn()) {
planFrom.delete(item.id);
// In a placement pass, written with the pass's others at its end:
// one write to the set, not one a vessel.
if (placedIcons && state.icons.expiresAt(item.id) === undefined) {
placedIcons.push(item);
return;
}
state.icons.put(item, { expiresAt: null });
return;
}
@@ -989,13 +1001,47 @@ export function createRendering({
return Math.abs(atMs - clockStep.atMs) * clockStep.pxPerMs < VESSEL_STEP_PX;
}
// Live with a host-supplied placement, vessels move on between refreshes:
// drawn where it places them every frame, with the next frame asked for
// as soon as a drawn vessel would move visibly, so they move while the
// scene idles.
// Live with a host-supplied placement, vessels move on between refreshes.
// Drawn ones move once the fastest would have moved VESSEL_STEP_PX on
// screen since the pass that last moved them, at least three times a second
// and at most thirty (renderPace.js), and
// at once when the camera moves or zooms, new rows come or a vessel comes
// into view (underClockStep, on wall time). Moving an icon asks for a
// frame, so moving them on every frame would draw every frame: the frames
// between are left alone, and the next one is asked for when it is due.
let placementDue = true;
/** The icons a placement pass moved, while it runs (`putIcon`). */
let placedIcons = null;
/** Wall ms of the last pass that moved live-placed vessels. */
let placedWallMs = -Infinity;
function followPlacements() {
const nowMs = vesselState._aisRuntime.now();
const wallMs = performance.now();
// Never more often than a moving layer draws: a pass moving icons asks
// for a frame of its own, so without this a vessel close by moving
// over half a pixel a frame would draw every frame.
const sinceMs = wallMs - placedWallMs;
if (!placementDue && sinceMs < PLACEMENT_MIN_WAIT_MS) {
askFrameIn(PLACEMENT_MIN_WAIT_MS - sinceMs);
return;
}
if (!placementDue && underClockStep(nowMs, wallMs)) {
askFrameIn(
Math.max(
0,
Math.min(
PLACEMENT_FRAME_MS - (wallMs - clockStep.wallMs),
VESSEL_STEP_PX / clockStep.pxPerMs - (nowMs - clockStep.atMs),
),
),
);
return;
}
placementDue = false;
placedWallMs = wallMs;
const motion = startMotionPass();
placedIcons = [];
try {
// Drawn vessels only, as a sprite or a model: a hidden one is placed
// again when it is drawn.
for (const record of state.records.all) {
@@ -1005,10 +1051,38 @@ export function createRendering({
const placed = services.placement.place(record.id, nowMs);
if (placed) motion.moving = true;
const { lat, lon } = placed ?? record;
// How fast it moves is measured over the time since it was last
// placed.
const elapsedMs =
placed && visual.placedAtMs > 0
? nowMs - visual.placedAtMs
: undefined;
visual.placedAtMs = placed ? nowMs : undefined;
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveDrawnVisual(record, visual, lat, lon, motion);
moveDrawnVisual(
record,
visual,
lat,
lon,
motion,
elapsedMs > 0 ? elapsedMs : undefined,
);
}
} finally {
const moved = placedIcons;
placedIcons = null;
state.icons?.putMany(moved);
}
askMotionFrame(motion);
noteClockStep(nowMs, motion);
}
/** Move live-placed vessels on the next frame however little they moved,
* and ask for that frame: new rows came, or a vessel came into view. */
function placeNow() {
if (!services.placement || followsClock(vesselState)) return;
placementDue = true;
if (state.feed.enabled) governorRequestRender('ais-vessels-placement');
}
// One pass of moving vessels: whether any drawn vessel is moving, how far
@@ -1126,6 +1200,12 @@ export function createRendering({
/** Ask for a vessel frame `waitMs` from now; one already asked for no
* later stands. */
function askFrameIn(waitMs) {
// A frame sooner than the next pass may come would move nothing, then
// ask again: two frames a move.
waitMs = Math.max(
waitMs,
PLACEMENT_MIN_WAIT_MS - (performance.now() - placedWallMs),
);
const runtime = vesselState._aisRuntime;
const dueMs = runtime.now() + waitMs;
if (placementFrameTimer !== null) {
@@ -1143,6 +1223,7 @@ export function createRendering({
function cancelPlacementFrame() {
motionPassWallMs = null;
forgetClockStep();
placementDue = true;
drawnBehind = false;
hiddenFollowedAtWallMs = null;
if (placementFrameTimer === null) return;
@@ -1171,6 +1252,8 @@ export function createRendering({
function updateVisibility(force = false) {
if (!state.feed.enabled) return;
if (force) governorRequestRender('ais-vessels-update');
// New rows are drawn where they were reported: placed before they show.
if (force) placementDue = true;
const now = focusNowMs(performance.now());
const focusTarget = getFocusTarget();
const regularPass =
@@ -1230,9 +1313,13 @@ export function createRendering({
// The time the clock pass drew (a playing clock's time moves on within
// the frame), so only vessels it did not reach are moved.
const catchUpAtMs = worldMs === null ? null : (clockPassAtMs ?? worldMs);
let cameIntoView = false;
for (const record of state.records.all) {
const visual = getVisual(record);
const wasVisible = visual.visible;
visual.visible = isVisible(visual.cullPosition, occluder, record);
// One that comes into view was not placed while hidden.
if (visual.visible && wasVisible === false) cameIntoView = true;
// One in view that the clock passes have not moved to the time yet
// (a seek while paused shows it before its turn) is moved there and
// judged again: no later pass would move it while the clock rests.
@@ -1246,6 +1333,7 @@ export function createRendering({
if (visual.seen !== seenYet(record)) syncRecordIcon(record);
if (visual.visible) labelCandidates.push(record);
}
if (cameIntoView) placeNow();
updateClusteredLabels(labelCandidates);
}
if (focusPass && query && pose) {
@@ -1258,8 +1346,9 @@ export function createRendering({
cameraDistanceFor: (position) => distance(pose.position, position),
});
state.activeFocusCount = result.activeCount;
// Drawn while emphasis changes, at the rate fades draw elsewhere.
if (result.activeCount > 0 || result.transitioning)
holdContinuousRender('ais-vessels');
holdContinuousRender('ais-vessels', { maxFps: VESSEL_FOCUS_FPS });
else releaseContinuousRender('ais-vessels');
}
}
+9 -3
View File
@@ -796,16 +796,20 @@ export function createCesiumDraw({
setsVersion += 1;
};
record.rebuild = rebuild;
// A set whose owner asks for its frames is changed in place without
// asking for one: the owner writes it as a frame begins (asking then
// would draw that frame twice), or its next frame draws the change.
const ownerFrames = () => spec.motionClock?.frames === 'owner';
// Changed in place: what height queries see through may have changed.
const patched = () => {
setsVersion += 1;
requestRender();
if (!ownerFrames()) requestRender();
};
// Icons changed in place: height queries see through the sets' pick
// ids, which an icon keeps, so only icons added or gone change them.
const iconsPatched = (synced) => {
if (synced === ICONS_CHANGED) setsVersion += 1;
requestRender();
if (!ownerFrames()) requestRender();
};
// A shape's pulse the renderer cannot run is refused before anything
// changes.
@@ -925,7 +929,9 @@ export function createCesiumDraw({
spec.motionClock?.kind === 'live'
) {
spec.motionClock = options.motionClock;
requestRender();
// A set whose owner asks for its frames reads the new delay in
// the owner's next one: the delay alone asks for none.
if (options.motionClock.frames !== 'owner') requestRender();
return;
}
// Refused, changing nothing, where icons on the GPU cannot take it
+6
View File
@@ -163,6 +163,8 @@ export function createSceneFrame(viewer) {
const holds = new Map();
// Told when the first hold is taken and the last released.
const heldListeners = listenerList(uncaught);
// Told every hold taken or released.
const holdsListeners = listenerList(uncaught);
const pendingRenders = new Set();
const gone = () => disposed || scene.isDestroyed?.();
const sceneTime = (time) =>
@@ -250,6 +252,7 @@ export function createSceneFrame(viewer) {
holds.set(reason, (holds.get(reason) ?? 0) + 1);
if (!gone()) scene.requestRender();
if (first) heldListeners.fire(true);
holdsListeners.fire();
let released = false;
return () => {
if (released) return;
@@ -260,9 +263,11 @@ export function createSceneFrame(viewer) {
// What changed in the last held frame still gets drawn.
if (!gone()) scene.requestRender();
if (holds.size === 0) heldListeners.fire(false);
holdsListeners.fire();
};
},
onHeldChange: (cb) => heldListeners.on(cb),
onHoldsChange: (cb) => holdsListeners.on(cb),
mode: () => (scene.requestRenderMode ? 'demand' : 'continuous'),
diagnostics: () => ({
mode: port.mode(),
@@ -331,6 +336,7 @@ export function createSceneFrame(viewer) {
for (const off of removers.splice(0)) off();
for (const list of Object.values(listeners)) list.clear();
heldListeners.clear();
holdsListeners.clear();
holds.clear();
// Waits settle rather than stay attached to a scene gone quiet.
for (const done of [...pendingRenders]) done();
+7 -1
View File
@@ -870,7 +870,13 @@ export function createGpuIcons({
},
/** Whether a live-clock row is still moving: frames should keep coming. */
animating() {
if (spec.motionClock?.kind === 'scene' || spec.show === false)
// A set whose owner asks for its frames (`frames: 'owner'`) is not
// kept drawing by its moving rows.
if (
spec.motionClock?.kind === 'scene' ||
spec.motionClock?.frames === 'owner' ||
spec.show === false
)
return false;
return set.count > 0 && clockMs() < movingUntil;
},
+34
View File
@@ -221,6 +221,40 @@ test('rows moving on a live clock keep frames coming until their segments end',
assert.equal(scene.renders, onScene);
});
test('a live set whose owner asks for its frames asks for none itself', () => {
const { scene, part, draw } = drawOver();
const set = draw.icons({
id: 'gpu:owned',
motionClock: { kind: 'live', delayMs: 2000, frames: 'owner' },
});
const now = Date.now();
const to = ecef(Cesium.Cartesian3.fromDegrees(4.2, 51.95, 2));
set.set([
icon('a', {
motion: { kind: 'lerp', from: ecef(AT), to, t0: now, t1: now + 60000 },
}),
]);
const moving = scene.renders;
part.afterRender();
assert.equal(scene.renders, moving, 'moving rows ask for no frame');
set.setOptions({
motionClock: { kind: 'live', delayMs: 3000, frames: 'owner' },
});
assert.equal(scene.renders, moving, 'a new delay asks for no frame');
// A row restyled in place, as the owner does when a frame begins (a
// helicopter's rotor), asks for none either: that frame draws it.
set.upsert([
icon('a', {
scale: 2,
motion: { kind: 'lerp', from: ecef(AT), to, t0: now, t1: now + 60000 },
}),
]);
assert.equal(scene.renders, moving, 'a write in place asks for no frame');
set.setOptions({ motionClock: { kind: 'live', delayMs: 4000 } });
part.afterRender();
assert.ok(scene.renders > moving, 'back to the set: frames again');
});
test('a set that recedes draws on the GPU, every row receding by the set’s parameters, and changes live', () => {
const { scene, part, draw } = drawOver();
// An item's own `recede` is not the contract's: it changes nothing.
+1
View File
@@ -158,6 +158,7 @@ export const CESIUM_CHECKS = new Set([
'renderer.whenSettled',
'renderer.resize',
'frame.onHeldChange',
'frame.onHoldsChange',
'frame.setTargetFps',
'globe.setTerrain',
'globe.setPhotoreal',
+9
View File
@@ -96,6 +96,8 @@ export function cesiumCapabilities(scene, only) {
// Cesium's AUTODETECT tracking frame (`follow.js`).
'followAutodetect',
'cameraChangeThreshold',
// Every hold and release is told (`onHoldsChange`).
'holdChanges',
// The zoom-out guard reads the scene's own controller and frame events.
...(scene?.screenSpaceCameraController && scene?.preRender
? ['keepEarthFramed']
@@ -302,7 +304,10 @@ export function createCesiumPorts(
const holds = new Map();
// Told when the first hold is taken and the last released.
const heldListeners = listenerList(report);
// Told every hold taken or released.
const holdsListeners = listenerList(report);
function applyHolds() {
holdsListeners.fire();
const continuous = holds.size > 0;
if (scene.requestRenderMode === !continuous) return;
scene.requestRenderMode = !continuous;
@@ -383,6 +388,9 @@ export function createCesiumPorts(
};
},
onHeldChange: (cb) => heldListeners.on(cb),
...(capabilities.has('holdChanges')
? { onHoldsChange: (cb) => holdsListeners.on(cb) }
: {}),
/** Cesium can idle, so it draws on demand. */
mode: () => 'demand',
diagnostics: () => ({
@@ -862,6 +870,7 @@ export function createCesiumPorts(
for (const list of Object.values(rendererListeners)) list.clear();
for (const list of Object.values(frameListeners)) list.clear();
heldListeners.clear();
holdsListeners.clear();
drawPart.dispose();
cameraPart.dispose();
creditsPart.dispose();
+1
View File
@@ -15,6 +15,7 @@ test('capabilities follow what the scene supports', () => {
'pointVisibility',
'followAutodetect',
'cameraChangeThreshold',
'holdChanges',
'columns',
'motionSegments',
'courseGlide',
+20
View File
@@ -6618,6 +6618,26 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
deepEqual(heard, [true, false], 'nothing once off');
},
),
check(
'frame.onHoldsChange',
'onHoldsChange is told every hold and release, whoever holds, and nothing once off',
(h, r) => {
let heard = 0;
const off = r.frame.onHoldsChange(() => (heard += 1));
try {
const one = r.frame.holdContinuous('conformance:one');
const two = r.frame.holdContinuous('conformance:two');
one();
two();
equal(heard, 4, 'two holds and two releases');
} finally {
off();
}
r.frame.holdContinuous('conformance:after')();
equal(heard, 4, 'nothing once off');
},
{ capability: 'holdChanges' },
),
check(
'frame.setTargetFps',
'setTargetFps caps the loop; diagnostics say the cap, 0 the display rate',
+3 -1
View File
@@ -228,4 +228,6 @@ export type Capability =
/** Reading the frame the eye is placed in (`camera.followFrame`). */
| 'followFrame'
/** A `threshold` per `changed` listener (`camera.on`). */
| 'cameraChangeThreshold';
| 'cameraChangeThreshold'
/** Hearing every hold taken or released (`frame.onHoldsChange`). */
| 'holdChanges';
+14 -1
View File
@@ -133,7 +133,20 @@ export interface SetSpec {
* `live` (the default) is wall time minus `delayMs`, as a live feed is
* drawn a little behind real time; `scene` is the frame port's scene time.
*/
motionClock?: { kind: 'live'; delayMs?: number } | { kind: 'scene' };
motionClock?:
| {
kind: 'live';
delayMs?: number;
/**
* Who asks for the frames moving rows need: the set itself, one after
* another while a row moves (the default), or its `owner`, at the
* rate the rows move on screen. An owner's set may also draw a
* change written in place on the owner's next frame without asking
* for one (the owner writes as a frame begins).
*/
frames?: 'set' | 'owner';
}
| { kind: 'scene' };
show?: boolean;
}
+6
View File
@@ -78,6 +78,12 @@ export interface FramePort {
* it) and stop (its last released): `true` held, `false` not.
*/
onHeldChange(cb: (held: boolean) => void): Off;
/**
* `holdChanges`: hear every hold taken or released, whoever holds
* (diagnostics' `holds` has changed), where `onHeldChange` hears only the
* first hold and the last release.
*/
onHoldsChange?(cb: () => void): Off;
mode(): 'demand' | 'continuous';
diagnostics(): FrameDiagnostics;
/** Stop ticking while the page is hidden; resume on `false`. */
+5 -3
View File
@@ -55,6 +55,7 @@ export const CAPABILITIES = Object.freeze([
'occlusionTest',
'pointVisibility',
'keepEarthFramed',
'holdChanges',
]);
/** @type {readonly import('./frame').FrameStep[]} */
@@ -120,8 +121,8 @@ export const PORTS = deepFreeze({
'destroy',
),
),
frame: Object.fromEntries(
required(
frame: Object.fromEntries([
...required(
'on',
'requestRender',
'holdContinuous',
@@ -135,7 +136,8 @@ export const PORTS = deepFreeze({
'setTime',
'time',
),
),
['onHoldsChange', 'holdChanges'],
]),
globe: Object.fromEntries([
...required(
'setBase',
+21
View File
@@ -190,6 +190,16 @@ export function createStubRenderer(options = {}) {
let holdSeq = 0;
// Told when the first hold is taken and the last released.
const heldListeners = new Set();
const holdsListeners = new Set();
function tellHolds() {
for (const entry of [...holdsListeners])
if (holdsListeners.has(entry))
try {
entry.cb();
} catch (error) {
report(error);
}
}
function tellHeld(held) {
for (const entry of [...heldListeners])
try {
@@ -359,9 +369,11 @@ export function createStubRenderer(options = {}) {
const key = ++holdSeq;
continuous.set(key, String(reason));
if (continuous.size === 1) tellHeld(true);
tellHolds();
return () => {
if (!continuous.delete(key)) return;
if (continuous.size === 0) tellHeld(false);
tellHolds();
};
},
onHeldChange(cb) {
@@ -369,6 +381,15 @@ export function createStubRenderer(options = {}) {
heldListeners.add(entry);
return () => heldListeners.delete(entry);
},
...(capabilities.has('holdChanges')
? {
onHoldsChange(cb) {
const entry = { cb };
holdsListeners.add(entry);
return () => holdsListeners.delete(entry);
},
}
: {}),
mode: () => 'demand',
diagnostics: () => ({
mode: 'demand',
+140 -7
View File
@@ -29,8 +29,13 @@
* short stable strings ('flights', 'traffic', 'style-anim', …) so the
* diagnostics read like a story.
*
* Frame rate: while the loop is held it draws at the display's own refresh
* rate; while nothing holds it, the governor caps it at IDLE_FRAME_RATE,
* Frame rate: a hold may say the most frames a second it needs
* (`holdContinuousRender(owner, { maxFps })`); while held the loop draws at
* the highest rate its holders asked for, and at the display's own refresh
* rate as soon as one holder asked for none. Moving layers hold through
* their pace (renderPace.js) at 15 to 30; a followed target counts as
* FOLLOW_FRAME_RATE unless a pointer or the wheel is steering the camera.
* While nothing holds it, the governor caps it at IDLE_FRAME_RATE,
* because Cesium still ticks the clock, data sources and every
* pre/post-update listener once per animation frame even when it skips the
* draw. The frame port says when its first hold is taken and its last
@@ -42,11 +47,19 @@
* The governor is O(1) passive: no per-frame work of its own, ever.
*/
import { PACE_MAX_HZ } from './renderPace.js';
/** @typedef {import('./render/contract/frame').FramePort} FramePort */
/** @typedef {import('./render/contract/camera').CameraPort} CameraPort */
/** Frames a second the loop ticks while nothing moves. */
export const IDLE_FRAME_RATE = 60;
/**
* Frames a second for a camera that only rides along with what it follows:
* the most a moving layer draws (renderPace.js), leaving room in the frame
* for everything else. The person steering it still gets the display's rate.
*/
export const FOLLOW_FRAME_RATE = PACE_MAX_HZ;
let _frame = null;
/** Owners holding, each with the frame port's release once installed. */
@@ -56,11 +69,108 @@ let _removeCameraListeners = null;
/** Stops hearing the installed port's holds. */
let _offHeldChange = null;
/** The loop's rate: the display's while held, IDLE_FRAME_RATE while not. */
function applyRate(held) {
_frame?.setTargetFps(held ? 0 : IDLE_FRAME_RATE);
/** The most frames a second each owner said its hold needs; none: the display's. */
const _rateOf = new Map();
/**
* Whether a pointer is down, or the wheel turned in the last moment: the
* person is steering the camera. Kept apart, so the wheel's moment ending
* never ends a drag.
*/
const _pointersDown = new Set();
let _wheeling = false;
let _steeringTimer = null;
const steering = () => _pointersDown.size > 0 || _wheeling;
/**
* The camera's own moves (a drag, a zoom, a flight) draw at the display's
* rate. A camera carried by what it follows needs only the follow rate,
* unless the person is steering it at the same time.
*/
function cameraRate() {
return !steering() && _holds.has('tracked-entity') ? FOLLOW_FRAME_RATE : 0;
}
/**
* The rate while held: the highest any holder asked for, and the display's
* (0) as soon as one holder asked for none. The renderer's own holds
* (animated styles) ask for none; a frame port with `onHoldsChange` says
* when one is taken or let go, and one without it is heard at the loop's
* first hold and last release only.
*/
function heldRate() {
let rate = 0;
for (const owner of _frame.diagnostics().holds) {
const asked = owner === 'camera' ? cameraRate() : _rateOf.get(owner);
if (!asked) return 0;
if (asked > rate) rate = asked;
}
return rate;
}
/** The loop's rate: the holders' while held, IDLE_FRAME_RATE while not. */
function applyRate(held = (_frame?.diagnostics().holds.length ?? 0) > 0) {
_frame?.setTargetFps(held ? heldRate() : IDLE_FRAME_RATE);
}
/** Change the steering inputs, and the rate if steering changed. */
function changeSteering(change) {
const was = steering();
change();
if (steering() !== was) applyRate();
}
/**
* Pointer and wheel input on the page: the person is steering the camera.
* A release the page never hears (the pointer let go over another window)
* ends when the page loses focus or is hidden.
*/
function watchSteering(target, { schedule, unschedule }) {
if (typeof target?.addEventListener !== 'function') return null;
// Every pointer down counts (a pinch is two), until it is let go.
const down = (event) =>
changeSteering(() => _pointersDown.add(event?.pointerId ?? 0));
const up = (event) =>
changeSteering(() => _pointersDown.delete(event?.pointerId ?? 0));
const allUp = () => changeSteering(() => _pointersDown.clear());
// The window's own blur, not an element's inside the page.
const blur = (event) => {
if (!event || event.target === target) allUp();
};
const wheel = () => {
changeSteering(() => (_wheeling = true));
if (_steeringTimer !== null) unschedule(_steeringTimer);
_steeringTimer = schedule(() => {
_steeringTimer = null;
changeSteering(() => (_wheeling = false));
}, 300);
};
const hidden = () => {
if (globalThis.document?.visibilityState === 'hidden') allUp();
};
const options = { passive: true, capture: true };
target.addEventListener('pointerdown', down, options);
target.addEventListener('pointerup', up, options);
target.addEventListener('pointercancel', up, options);
target.addEventListener('blur', blur, options);
target.addEventListener('wheel', wheel, options);
const doc = globalThis.document;
doc?.addEventListener?.('visibilitychange', hidden);
return () => {
target.removeEventListener('pointerdown', down, options);
target.removeEventListener('pointerup', up, options);
target.removeEventListener('pointercancel', up, options);
target.removeEventListener('blur', blur, options);
target.removeEventListener('wheel', wheel, options);
doc?.removeEventListener?.('visibilitychange', hidden);
if (_steeringTimer !== null) unschedule(_steeringTimer);
_steeringTimer = null;
_pointersDown.clear();
_wheeling = false;
};
}
/** Stops hearing the pointer and the wheel. */
let _removeSteeringListeners = null;
/** Debug trail of the most recent one-shot render requests (idle mode only). */
const _recentRequests = [];
const RECENT_REQUEST_CAP = 16;
@@ -185,11 +295,21 @@ export function installRenderGovernor(
if (_frame) releaseFrameHolds();
_offHeldChange?.();
_frame = frame;
_offHeldChange = frame.onHeldChange(applyRate);
const offHeld = frame.onHeldChange(applyRate);
const offHolds = frame.onHoldsChange?.(() => applyRate()) ?? null;
_offHeldChange = () => {
offHeld();
offHolds?.();
};
applyRate(frame.diagnostics().holds.length > 0);
for (const ownerId of _holds.keys()) holdOnFrame(ownerId);
}
_removeCameraListeners = watchCameraMotion(camera, { schedule, unschedule });
_removeSteeringListeners?.();
_removeSteeringListeners = watchSteering(globalThis.window, {
schedule,
unschedule,
});
}
function releaseFrameHolds() {
@@ -206,10 +326,15 @@ function releaseFrameHolds() {
* @param {string} ownerId Short stable id, e.g. 'flights', 'traffic'.
* @returns {void}
*/
export function holdContinuousRender(ownerId) {
export function holdContinuousRender(ownerId, { maxFps = 0 } = {}) {
if (!ownerId) return;
if (maxFps > 0) _rateOf.set(ownerId, maxFps);
else _rateOf.delete(ownerId);
if (!_holds.has(ownerId)) _holds.set(ownerId, null);
holdOnFrame(ownerId);
// A second holder, or a new rate, changes the rate without changing
// whether the loop is held.
applyRate();
}
/**
@@ -223,7 +348,9 @@ export function releaseContinuousRender(ownerId) {
if (!ownerId || !_holds.has(ownerId)) return;
const release = _holds.get(ownerId);
_holds.delete(ownerId);
_rateOf.delete(ownerId);
release?.();
applyRate();
}
/**
@@ -262,11 +389,14 @@ export function uninstallRenderGovernor(frame) {
if (!_frame || _frame !== frame) return;
_removeCameraListeners?.();
_removeCameraListeners = null;
_removeSteeringListeners?.();
_removeSteeringListeners = null;
releaseFrameHolds();
_offHeldChange?.();
_offHeldChange = null;
_frame = null;
_holds.clear();
_rateOf.clear();
_recentRequests.length = 0;
}
@@ -274,9 +404,12 @@ export function uninstallRenderGovernor(frame) {
export function _resetRenderGovernorForTest() {
_removeCameraListeners?.();
_removeCameraListeners = null;
_removeSteeringListeners?.();
_removeSteeringListeners = null;
_offHeldChange?.();
_offHeldChange = null;
_frame = null;
_holds.clear();
_rateOf.clear();
_recentRequests.length = 0;
}
+124
View File
@@ -9,6 +9,7 @@ import {
_resetRenderGovernorForTest,
uninstallRenderGovernor,
IDLE_FRAME_RATE,
FOLLOW_FRAME_RATE,
} from './renderGovernor.js';
import { framePortFor } from './testSupport/fakeFramePort.mjs';
@@ -293,3 +294,126 @@ test('installing again drops a camera hold the old listeners can no longer relea
assert.equal(scene.requestRenderMode, true);
assert.equal(timers.pending, 0);
});
test('a hold may cap the rate: the highest asked wins, an uncapped hold is the display rate', () => {
const { viewer, scene } = makeViewer();
const frame = framePortFor(viewer.scene);
installRenderGovernor(frame);
holdContinuousRender('satellites', { maxFps: 15 });
assert.equal(scene.targetFps, 15);
holdContinuousRender('flights', { maxFps: 30 });
assert.equal(scene.targetFps, 30, 'the highest asked');
holdContinuousRender('flights', { maxFps: 20 });
assert.equal(scene.targetFps, 20, 'a holder lowering its rate');
holdContinuousRender('traffic');
assert.equal(scene.targetFps, 0, 'a hold without a rate: the display rate');
releaseContinuousRender('traffic');
assert.equal(scene.targetFps, 20);
releaseContinuousRender('flights');
assert.equal(scene.targetFps, 15);
releaseContinuousRender('satellites');
assert.equal(scene.targetFps, IDLE_FRAME_RATE);
});
test('the renderer holding the loop itself asks for no rate: the display rate', () => {
const { viewer, scene } = makeViewer();
const frame = framePortFor(viewer.scene);
installRenderGovernor(frame);
const release = frame.holdContinuous('effects:animated');
holdContinuousRender('satellites', { maxFps: 15 });
assert.equal(scene.targetFps, 0);
release();
assert.equal(scene.targetFps, 15, 'heard as soon as the renderer lets go');
const again = frame.holdContinuous('effects:animated');
assert.equal(scene.targetFps, 0, 'and as soon as it holds again');
again();
releaseContinuousRender('satellites');
assert.equal(scene.targetFps, IDLE_FRAME_RATE);
});
test('a camera carried by a followed target draws at the follow rate unless a pointer steers it', () => {
const previousWindow = globalThis.window;
const page = new EventTarget();
globalThis.window = page;
try {
const { viewer, scene } = makeViewer();
const camera = makeCamera();
installRenderGovernor(framePortFor(viewer.scene), { camera });
camera.raise('moveStart');
assert.equal(scene.targetFps, 0, 'a camera move: the display rate');
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE, 'following');
assert.equal(FOLLOW_FRAME_RATE, 30);
page.dispatchEvent(new Event('pointerdown'));
assert.equal(scene.targetFps, 0, 'steering: the display rate');
page.dispatchEvent(new Event('pointerup'));
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE);
releaseContinuousRender('tracked-entity');
assert.equal(scene.targetFps, 0, 'the camera moving on its own');
camera.raise('moveEnd');
assert.equal(scene.targetFps, IDLE_FRAME_RATE);
} finally {
_resetRenderGovernorForTest();
if (previousWindow === undefined) delete globalThis.window;
else globalThis.window = previousWindow;
}
});
test('steering ends when the page loses focus, and a wheel moment ending never ends a drag', () => {
const previousWindow = globalThis.window;
const page = new EventTarget();
globalThis.window = page;
try {
const timers = fakeTimers();
const { viewer, scene } = makeViewer();
installRenderGovernor(framePortFor(viewer.scene), timers);
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
holdContinuousRender('camera');
page.dispatchEvent(new Event('pointerdown'));
assert.equal(scene.targetFps, 0, 'dragging: the display rate');
// Let go over another window: the page never hears the release.
page.dispatchEvent(new Event('blur'));
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE, 'focus lost: steering ends');
// A wheel turn, then a drag begun before its moment ends.
page.dispatchEvent(new Event('wheel'));
page.dispatchEvent(new Event('pointerdown'));
timers.run();
assert.equal(scene.targetFps, 0, 'the drag goes on at the display rate');
page.dispatchEvent(new Event('pointerup'));
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE);
} finally {
_resetRenderGovernorForTest();
if (previousWindow === undefined) delete globalThis.window;
else globalThis.window = previousWindow;
}
});
test('a pinch steers until its last finger lifts; an element losing focus is not the page losing it', () => {
const previousWindow = globalThis.window;
const page = new EventTarget();
globalThis.window = page;
try {
const { viewer, scene } = makeViewer();
installRenderGovernor(framePortFor(viewer.scene), fakeTimers());
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
holdContinuousRender('camera');
const pointer = (type, pointerId) => Object.assign(new Event(type), { pointerId });
page.dispatchEvent(pointer('pointerdown', 1));
page.dispatchEvent(pointer('pointerdown', 2));
page.dispatchEvent(pointer('pointerup', 1));
assert.equal(scene.targetFps, 0, 'one finger still down');
// The search box's blur reaches the window's capturing listener.
const field = new EventTarget();
field.addEventListener('blur', () => {});
const blur = new Event('blur');
Object.defineProperty(blur, 'target', { value: field });
page.dispatchEvent(blur);
assert.equal(scene.targetFps, 0, 'still steering');
page.dispatchEvent(pointer('pointerup', 2));
assert.equal(scene.targetFps, FOLLOW_FRAME_RATE);
} finally {
_resetRenderGovernorForTest();
if (previousWindow === undefined) delete globalThis.window;
else globalThis.window = previousWindow;
}
});
+228
View File
@@ -0,0 +1,228 @@
/**
* Draws a moving layer as often as its marks move on screen, in place of a
* hold on the render loop for as long as the layer is on.
*
* A mark should move at most PACE_STEP_PX between two draws, so a layer
* needs `fastest on-screen speed / PACE_STEP_PX` draws a second. The pace
* keeps that between PACE_MIN_HZ (animated marks never stall) and
* PACE_MAX_HZ (room in the frame for everything else the scene draws).
* Below PACE_HOLD_HZ it asks for one frame at a time on a timer, so the
* loop stays on demand; from there it holds the loop at a rate the display
* divides evenly (the render governor's rate per hold).
*
* The person steering the camera still draws at the display's rate: that is
* the camera's hold, not a layer's (see renderGovernor.js).
*/
/** The most a mark may move on screen between two draws, in pixels. */
export const PACE_STEP_PX = 0.5;
/** Draws a second however slowly the marks move. */
export const PACE_MIN_HZ = 3;
/** Draws a second however fast the marks move. */
export const PACE_MAX_HZ = 30;
/** From this many draws a second the pace holds the loop instead. */
export const PACE_HOLD_HZ = 12;
/** Below this the hold is let go again (a gap, so it does not flap; above
* ROTOR_FPS, so a turning rotor alone draws on the timer at its own rate). */
export const PACE_RELEASE_HZ = 11;
/** Held rates, each dividing 60 and 120 evenly so draws come at even gaps. */
const HELD_RATES = [15, 20, 30];
/** Draws a second for marks crossing the screen at `pxPerSec`. */
export function paceHzForSpeed(pxPerSec) {
return pxPerSec / PACE_STEP_PX;
}
/** The held rate for a need of `hz` draws a second. */
function heldRateFor(hz) {
for (const rate of HELD_RATES) if (hz <= rate) return rate;
return PACE_MAX_HZ;
}
/**
* @param {object} options
* @param {string} options.owner The hold's owner id ('flights', 'satellites').
* @param {object} [options.render] The render governor's calls
* (holdContinuousRender, releaseContinuousRender, governorRequestRender).
* @param {Function} [options.setTimeout] Injectable timers for tests.
* @param {Function} [options.clearTimeout]
* @param {() => number} [options.now] Injectable wall clock (ms) for tests.
*/
export function createRenderPace({
owner,
render,
setTimeout: schedule = globalThis.setTimeout,
clearTimeout: unschedule = globalThis.clearTimeout,
now = () => globalThis.performance?.now() ?? Date.now(),
}) {
const hold = render?.holdContinuousRender ?? (() => {});
const release = render?.releaseContinuousRender ?? (() => {});
const request = render?.governorRequestRender ?? (() => {});
let running = false;
let hz = PACE_MIN_HZ;
let held = false;
/** The rate the hold asked for, or -1 while not held. */
let heldFps = -1;
let timer = null;
let timerHz = 0;
/** Whether the timer's wait ended: the marks move on the next frame. */
let due = false;
/** Wall ms the marks last moved. */
let movedMs = -Infinity;
function arm() {
if (!running || held) return;
if (timer !== null) {
// A pending wait at a much slower rate is cut short.
if (hz <= timerHz * 1.5) return;
unschedule(timer);
}
timerHz = hz;
timer = schedule(() => {
timer = null;
due = true;
request(owner);
arm();
}, 1000 / hz);
}
/**
* Set the draws a second needed now (any number: it is clamped to the
* pace's range; Infinity asks for the most). Called once a drawn frame.
*/
function set(needHz) {
if (!running) return;
const clamped = Math.min(
PACE_MAX_HZ,
needHz >= PACE_MIN_HZ ? needHz : PACE_MIN_HZ,
);
// Up at once, down gently: the fastest mark leaving the view is no
// reason to step the next one.
hz = clamped >= hz ? clamped : Math.max(clamped, hz * 0.9);
const wantHold = held ? hz >= PACE_RELEASE_HZ : hz >= PACE_HOLD_HZ;
if (wantHold) {
const maxFps = heldRateFor(hz);
if (!held || maxFps !== heldFps) hold(owner, { maxFps });
heldFps = maxFps;
if (timer !== null) unschedule(timer);
timer = null;
} else if (held) {
release(owner);
heldFps = -1;
}
held = wantHold;
arm();
}
/**
* Whether the layer's marks should move in this frame, for a layer that
* moves them itself (moving them asks for a frame, so a layer moving them
* on every drawn frame keeps the loop drawing). Marks the move when true.
*/
function take() {
const at = now();
if (!running || held || due || at - movedMs >= 1000 / hz) {
due = false;
movedMs = at;
return true;
}
return false;
}
function start() {
if (running) return;
running = true;
// Until the first frame says what is needed.
hz = PACE_RELEASE_HZ;
due = true;
movedMs = -Infinity;
request(owner);
arm();
}
function stop() {
running = false;
if (timer !== null) unschedule(timer);
timer = null;
held = false;
heldFps = -1;
due = false;
release(owner);
}
return {
set,
take,
start,
stop,
state: () => ({ running, hz, held, heldFps }),
};
}
/** cos 60°: marks further than this from the view's axis are not read. */
const VIEW_COS = 0.5;
/**
* Reads how fast the fastest mark crosses the screen, from each mark's move
* as an angle at the eye. Use: `begin` with the camera, `add` each mark's
* two positions (ECEF), then `pxPerSec` with the time between them.
* The flat screen stretches an angle away from its centre by 1 / cos², so
* that is applied too.
*/
export function createScreenSpeed() {
let eye = null;
let dir = null;
let ex = 0;
let ey = 0;
let ez = 0;
let focal = 0;
let fastest2 = 0;
return {
/**
* @param {{position: {x,y,z}, direction: {x,y,z}, fovy: number}|null} pose
* @param {number} heightPx The canvas's height in CSS pixels.
* @param {{x,y,z}} [eyeMove] How far the eye itself moved between the
* two positions: a camera riding one mark sees its neighbours nearly
* still.
* @returns {boolean} Whether there is a camera to read with.
*/
begin(pose, heightPx, eyeMove = null) {
fastest2 = 0;
eye = pose?.position ?? null;
dir = pose?.direction ?? null;
if (!eye || !dir || !(pose.fovy > 0)) {
eye = null;
return false;
}
ex = eyeMove?.x ?? 0;
ey = eyeMove?.y ?? 0;
ez = eyeMove?.z ?? 0;
focal = (heightPx || 900) / 2 / Math.tan(pose.fovy / 2);
return true;
},
/** One mark's move from `from` to `to` (ECEF metres). */
add(from, to) {
if (!eye || !from || !to) return;
const dx = to.x - eye.x;
const dy = to.y - eye.y;
const dz = to.z - eye.z;
const range2 = dx * dx + dy * dy + dz * dz;
const along = dx * dir.x + dy * dir.y + dz * dir.z;
if (!(along > 0) || along * along < VIEW_COS * VIEW_COS * range2) return;
const mx = to.x - from.x - ex;
const my = to.y - from.y - ey;
const mz = to.z - from.z - ez;
// The angle the move subtends, stretched by 1 / cos² off the centre.
const turn2 =
((mx * mx + my * my + mz * mz) * range2) /
(along * along * along * along);
if (turn2 > fastest2) fastest2 = turn2;
},
/** The fastest mark's on-screen speed, for moves `seconds` apart. */
pxPerSec(seconds) {
if (!eye || !(seconds > 0)) return 0;
return (Math.sqrt(fastest2) * focal) / seconds;
},
};
}
+191
View File
@@ -0,0 +1,191 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
createRenderPace,
createScreenSpeed,
paceHzForSpeed,
PACE_MAX_HZ,
PACE_MIN_HZ,
PACE_STEP_PX,
} from './renderPace.js';
/** A pace with fake timers, clock and render calls. */
function makePace() {
const calls = [];
const timers = new Map();
let nextId = 1;
let nowMs = 0;
const pace = createRenderPace({
owner: 'dots',
render: {
holdContinuousRender: (owner, options) =>
calls.push(['hold', owner, options.maxFps]),
releaseContinuousRender: (owner) => calls.push(['release', owner]),
governorRequestRender: (owner) => calls.push(['request', owner]),
},
setTimeout(fn, ms) {
const id = nextId++;
timers.set(id, { fn, ms });
return id;
},
clearTimeout: (id) => timers.delete(id),
now: () => nowMs,
});
return {
pace,
calls,
timers,
advance(ms) {
nowMs += ms;
},
fire() {
const [id, timer] = [...timers][0];
timers.delete(id);
timer.fn();
return timer.ms;
},
};
}
test('a mark may move half a pixel between draws', () => {
assert.equal(PACE_STEP_PX, 0.5);
assert.equal(paceHzForSpeed(1), 2);
assert.equal(paceHzForSpeed(10), 20);
});
test('slow marks are drawn three times a second, one frame at a time', () => {
const { pace, calls, timers, fire } = makePace();
pace.start();
pace.set(0.2);
pace.set(0.2);
// From the starting rate it eases down, never below the floor.
for (let i = 0; i < 40; i++) pace.set(0.2);
assert.equal(pace.state().hz, PACE_MIN_HZ);
assert.equal(pace.state().held, false);
assert.ok(timers.size === 1, 'one wait out');
// The wait out from the start runs out, then the next is at the floor.
fire();
assert.equal(fire(), 1000 / PACE_MIN_HZ);
assert.deepEqual(calls.at(-1), ['request', 'dots']);
assert.ok(!calls.some(([kind]) => kind === 'hold'));
});
test('fast marks hold the loop at a rate the display divides, never above 30', () => {
const { pace, calls, timers } = makePace();
pace.start();
pace.set(13);
assert.deepEqual(calls.at(-1), ['hold', 'dots', 15]);
assert.equal(timers.size, 0, 'held: no waits');
pace.set(18);
assert.deepEqual(calls.at(-1), ['hold', 'dots', 20]);
pace.set(500);
assert.deepEqual(calls.at(-1), ['hold', 'dots', PACE_MAX_HZ]);
assert.equal(pace.state().hz, PACE_MAX_HZ);
pace.set(Infinity);
assert.equal(pace.state().heldFps, PACE_MAX_HZ);
// The same rate again asks the governor for nothing.
const before = calls.length;
pace.set(40);
assert.equal(calls.length, before);
});
test('the hold is let go below the release rate, not at the hold rate', () => {
const { pace, calls } = makePace();
pace.start();
pace.set(14);
assert.equal(pace.state().held, true);
// Down gently: a tenth a frame at most.
for (let i = 0; i < 2; i++) pace.set(10);
assert.equal(pace.state().held, true, 'still above the release rate');
for (let i = 0; i < 20; i++) pace.set(1);
assert.equal(pace.state().held, false);
assert.ok(calls.some(([kind]) => kind === 'release'));
});
test('marks a layer moves itself move at the pace, and on every frame while held', () => {
const { pace, advance, fire } = makePace();
pace.start();
assert.equal(pace.take(), true, 'first frame moves');
assert.equal(pace.take(), false, 'same instant: no move');
for (let i = 0; i < 40; i++) pace.set(0);
advance(100);
assert.equal(pace.take(), false, 'too soon at three a second');
fire();
assert.equal(pace.take(), true, 'the wait ended');
advance(1000 / PACE_MIN_HZ);
assert.equal(pace.take(), true, 'a third of a second on');
pace.set(30);
assert.equal(pace.take(), true);
assert.equal(pace.take(), true, 'held: every drawn frame');
});
test('stopping lets the hold go and ends the waits; a stopped pace moves every frame', () => {
const { pace, calls, timers } = makePace();
pace.start();
pace.set(25);
pace.stop();
assert.deepEqual(calls.at(-1), ['release', 'dots']);
assert.equal(timers.size, 0);
pace.set(25);
assert.equal(pace.state().held, false, 'set does nothing once stopped');
assert.equal(pace.take(), true);
assert.equal(pace.take(), true);
});
/** A camera at `z` metres up the z axis looking down it, 60° field. */
function poseAt(z) {
return {
position: { x: 0, y: 0, z },
direction: { x: 0, y: 0, z: -1 },
fovy: Math.PI / 3,
};
}
test('screen speed: a move across the view axis, from its angle at the eye', () => {
const speed = createScreenSpeed();
assert.equal(speed.begin(poseAt(1000), 1000), true);
// 10 m sideways at 1 km ahead, over one second.
speed.add({ x: 0, y: 0, z: 0 }, { x: 10, y: 0, z: 0 });
const focal = 500 / Math.tan(Math.PI / 6);
// Measured at the move's end: 10 m off-axis, a hair off-centre.
const px = speed.pxPerSec(1);
assert.ok(Math.abs(px - (10 / 1000) * focal) / px < 0.001, `${px}`);
assert.ok(Math.abs(speed.pxPerSec(2) - px / 2) < 1e-9);
});
test('screen speed: the fastest mark counts, marks behind or far off-axis do not', () => {
const speed = createScreenSpeed();
speed.begin(poseAt(1000), 1000);
speed.add({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });
speed.add({ x: 0, y: 0, z: 0 }, { x: 5, y: 0, z: 0 });
// Behind the eye.
speed.add({ x: 0, y: 0, z: 2000 }, { x: 500, y: 0, z: 2000 });
// 80° off the axis.
speed.add({ x: 5000, y: 0, z: 900 }, { x: 5500, y: 0, z: 900 });
const focal = 500 / Math.tan(Math.PI / 6);
assert.ok(Math.abs(speed.pxPerSec(1) - (5 / 1000) * focal) < 0.01);
});
test('screen speed: a mark moving with the eye stands still on screen', () => {
const speed = createScreenSpeed();
speed.begin(poseAt(1000), 1000, { x: 7, y: 0, z: 0 });
speed.add({ x: 0, y: 0, z: 0 }, { x: 7, y: 0, z: 0 });
assert.equal(speed.pxPerSec(1), 0);
});
test('screen speed: no camera, no reading', () => {
const speed = createScreenSpeed();
assert.equal(speed.begin(null, 900), false);
speed.add({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });
assert.equal(speed.pxPerSec(1), 0);
});
test('a need of ten a second, once held, falls back to single frames at ten', () => {
const { pace, timers } = makePace();
pace.start();
pace.set(30);
for (let i = 0; i < 40; i++) pace.set(10);
assert.equal(pace.state().held, false);
assert.equal(Math.round(pace.state().hz), 10);
assert.equal(timers.size, 1);
});
+8 -1
View File
@@ -4,7 +4,8 @@
* Cesium port does (`src/render/cesium/ports.js`): holds, counted per
* reason, keep `requestRenderMode` false; releasing the last asks for one
* frame; a request is the scene's `requestRender`; the first hold and the
* last release are told to `onHeldChange`; a rate set is kept as the
* last release are told to `onHeldChange`, every hold and release to
* `onHoldsChange`; a rate set is kept as the
* scene's `targetFps`. Only the members the governor uses. One port per
* scene, so a test can uninstall what it installed.
* @param {{requestRenderMode?: boolean, requestRender?: () => void}} scene
@@ -20,10 +21,12 @@ const ports = new WeakMap();
function makePort(scene) {
const holds = new Map();
const heldListeners = new Set();
const holdsListeners = new Set();
let wasHeld = false;
const apply = () => {
const held = holds.size > 0;
scene.requestRenderMode = !held;
for (const cb of [...holdsListeners]) cb();
if (held === wasHeld) return;
wasHeld = held;
for (const cb of [...heldListeners]) cb(held);
@@ -34,6 +37,10 @@ function makePort(scene) {
heldListeners.add(cb);
return () => heldListeners.delete(cb);
},
onHoldsChange(cb) {
holdsListeners.add(cb);
return () => holdsListeners.delete(cb);
},
diagnostics: () => ({ holds: [...holds.keys()] }),
setTargetFps(fps) {
scene.targetFps = fps;