Compare commits

..
Author SHA1 Message Date
Sameh Khamis 170b817679 Placed flights no longer replan in step: far ones less often, every row's atlas look-up cheaper
A placed contact's segment ran exactly a second, so a fleet planned
together ran out together: every second one or two fleet passes replanned
all of it (about ten thousand contacts) and rewrote every icon row, a frame
of 40-120 ms of work, longer on a busy machine.

Each contact's plans now run between half and one and a half times their
length, by its id, so the fleet's plans run out spread over the passes. A
contact out of view, or farther than 300 km from the eye, is planned for
4 s instead of 1 s: off screen its path is not seen, and that far a
straight segment of that length is well under a pixel off it. The fleet
pass hands the camera to the replan for this; any other plan (a new
report, a handover) is a near one.

The icon atlas finds a slot by URL, then size, instead of building a
"size|url" key string on every look-up; an aircraft's icon URL is an SVG
data URL of kilobytes, looked up twice for every row written.

Measured in Chrome over London with about ten thousand flights: icon rows
rewritten a second fell from about 1,700 to about 70, and the fleet pass's
longest tasks from 40-120 ms of CPU to 10-40 ms.
2026-11-23 19:29:15 -08:00
Sameh Khamis d50f04efeb 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.
2026-11-23 18:56:44 -08:00
46 changed files with 1566 additions and 330 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
- Icons keep their glyph when a stylesheet brings jQuery UI's `.ui-icon`
rule into the page, as some browser extensions do on every site: it pushed
each icon out of its box, leaving empty buttons (Sameh Khamis, @samehkhamis, #1917).
@@ -1,4 +0,0 @@
- Merge the Satellites row's class chips and its list of counts into one pill
per class. A class that is on shows its point colour, its name and how many
are loaded; a class that is off shows only its name (Sameh Khamis,
@samehkhamis, #1918).
+5 -5
View File
@@ -7817,13 +7817,13 @@ silently demoting every later lookup for the session.
- **World-space headings at every angle** (`src/data/screenRotation.js`; the scene-reading helpers in `src/render/cesium/iconOrientation.js`): aircraft/vessel icon rotation uses the camera right/up basis per tick (alignedAxis always ZERO), which is exact at screen center and for orthographic/nadir views and remains stable through >180° tracked orbits. Perspective rays vary across the viewport, so off-center contacts at oblique pitch can diverge from an exact finite-difference window projection; a regression test pins that known regime, and field evidence decides whether to adopt exact projection with the basis method as fallback. Fleet rotations refresh on camera-pose change; tracked entities per frame. Billboards are horizon-culled via a shared EllipsoidalOccluder.
- **Military/OpenSky reconciliation** (`src/data/militaryRegistry.js`): known-military ICAOs render amber in the flights layer (60s self-poll of the cached mil endpoint when the military layer is off) and are suppressed there while the military layer renders them.
- **Satellites**: core catalog from CelesTrak's stations, visual, GPS, GLONASS, Galileo, GEO, resource, weather, planet, SAR and science groups, tracking lands ~726km out via `viewFrom` (tracked entity owns a point graphic so the tracking camera engages), rings realign via primitive modelMatrix (no per-second rebuild flicker), optional `setParams({catalog:'dense'})` Starlink mode.
- **Satellite classes** (`src/layers/satellites/classes.js`): every satellite is filed under one of six classes, each with its own point colour and toggle chip (the chip shows the colour while the class is on): STATIONS (warm white), IMAGING (cyan), TELECOM (violet; communications and navigation, so GPS, GLONASS, Galileo and BeiDou read as one family), STARLINK (dim slate), PROBES (muted blue-gray) and DEBRIS (receding brown-gray). That module is the single source of truth for class, label and colour, so the dot, the card and the chip's swatch cannot disagree. Two deliberate palette rules: no class may sit in the 40–48° amber band, which is the app-wide known-military convention; and STARLINK stays far below PROBES in Rec.601 luminance so the dense shell stays separable when NVG/FLIR collapse the scene to one channel. The ISS keeps its long-standing red hero dot rather than the STATIONS colour — it carries a permanent name label and its card still reads `STATIONS · ISS`; it is a station whichever group ingested it, so a stations-feed outage cannot refile it. `src/data/satelliteClass.js` keeps the group-based labels beneath the classes: the constellation subtype and a group's own label for a satellite with no class. The tracked satellite's dot keeps that colour too: tracking draws it larger (14 px), white-outlined and over everything, never in another colour (`_addTrackedEntity`, `src/layers/satellites/rendering.js`).
- **Satellite classes** (`src/layers/satellites/classes.js`): every satellite is filed under one of six classes, each with its own point colour, legend swatch and toggle: STATIONS (warm white), IMAGING (cyan), TELECOM (violet; communications and navigation, so GPS, GLONASS, Galileo and BeiDou read as one family), STARLINK (dim slate), PROBES (muted blue-gray) and DEBRIS (receding brown-gray). That module is the single source of truth for class, label and colour, so the dot, the card and the legend swatch cannot disagree. Two deliberate palette rules: no class may sit in the 40–48° amber band, which is the app-wide known-military convention; and STARLINK stays far below PROBES in Rec.601 luminance so the dense shell stays separable when NVG/FLIR collapse the scene to one channel. The ISS keeps its long-standing red hero dot rather than the STATIONS colour — it carries a permanent name label and its card still reads `STATIONS · ISS`; it is a station whichever group ingested it, so a stations-feed outage cannot refile it. `src/data/satelliteClass.js` keeps the group-based labels beneath the classes: the constellation subtype and a group's own label for a satellite with no class. The tracked satellite's dot keeps that colour too: tracking draws it larger (14 px), white-outlined and over everything, never in another colour (`_addTrackedEntity`, `src/layers/satellites/rendering.js`).
- Class is also a **text field**, not just a color: `TELECOM · GPS` / `STARLINK` / `STATIONS · ISS` leads the tracked card's detail block and replaces the raw CelesTrak tag on the detection-overlay label. Because that canvas composites above the post-FX chain, the class stays readable in NVG/FLIR after the in-scene dot colors are flattened.
- The satellites row in DATA LAYERS carries per-layer sub-controls (`DataLayerManager._syncRowControls`, the first consumer of the optional `getRowControls()` layer hook): one chip per class (the STARLINK chip exposes the existing `catalog` param); a class that is on shows its point colour, its name and its live count in its chip (`swatch` and `count`, drawn by `src/ui/rail/RailChips.vue`), and a class that is off shows only its name; and an info line while SATCAT is stale or unavailable (`Classes may lag: SATCAT is a cached copy` / `Classes may lag: SATCAT unavailable`). Default is the sparse core catalog. The chips are stateless — each declares the params to apply and the manager owns the write — so the Space Missions capture/restore path over the same param stays authoritative. Controls stay hidden while the layer is off. An explicit CORE or DENSE choice participates in versioned local and share-link state; temporary Space Missions overrides do not.
- **Class toggles** (`src/layers/satellites/classes.js`): the layer row carries one chip per class — STATIONS, IMAGING, TELECOM (communications and navigation), PROBES (science, technology development and demonstration, unknown purpose) and DEBRIS (rocket bodies, fragments, unknown objects launched before last year and dead payloads) on by default, so the layer shows what it did before classes; STARLINK off, as DENSE was. Points of a hidden class stay built and are only hidden, so a toggle needs no reload; hidden classes are left out of the detection overlay, the voice/framing position lists and analyst answers (the tracked satellite still answers), and only the chips of classes on screen carry a colour and a count; an on class with nothing loaded shows its colour without a count. The class comes, strongest evidence first, from CelesTrak SATCAT (object type and operational status, fetched per group through `/api/celestrak-satcat/<group>`, cached a day by the proxy; the layer keeps a current read six hours rather than asking on every five-minute update), the bundled UCS Satellite Database pack (UCS-Satellite-Database 5-1-2023: operator, owner country and purpose; `src/data/local_data/ucs_satellites/`), name patterns for satellites launched after May 2023, and finally the CelesTrak groups the TLE came in (a mission group such as `weather` before the orbit group `geo`; a UCS purpose of "Unknown" counts as none). Only crewed stations and the craft that visit them, by name, are STATIONS: the CubeSats CelesTrak's stations group also carries after their deployment from the ISS are classed like any other satellite. A payload whose SATCAT record gives no status, with no UCS record and no recognisable name, that launched 20 or more years ago (SATCAT's launch date, else the TLE designator's year) is presumed dead and filed as debris; without a SATCAT record (a failed read) nothing is presumed. To cover imaging launched after the UCS snapshot the core catalog also reads CelesTrak's `resource`, `weather`, `planet`, `sar` and `science` groups. Debris can be tracked but is never ridden: the orbital entry gate (`orbitEntryAllowed`) refuses it, so no ORBIT entry is offered and double-click does nothing for it. Retired stations and the shuttles have re-entered and have no orbit to show. An explicit class choice is kept in local and share-link state as the `classes` option, one letter per class shown (`sitpd`: stations, imaging, telecom, probes, debris; `0`: none; `src/data/satelliteClassMask.js`), and the layer takes those letters back through `setParams({classes})`; STARLINK maps to the existing `catalog: 'dense'` param instead.
- The satellites row in DATA LAYERS carries per-layer sub-controls (`DataLayerManager._syncRowControls`, the first consumer of the optional `getRowControls()` layer hook): one chip per class (the STARLINK chip exposes the existing `catalog` param), a swatch legend with live per-class counts, and an info line while SATCAT is stale or unavailable (`Classes may lag: SATCAT is a cached copy` / `Classes may lag: SATCAT unavailable`). Default is the sparse core catalog. The chips are stateless — each declares the params to apply and the manager owns the write — so the Space Missions capture/restore path over the same param stays authoritative. Controls stay hidden while the layer is off. An explicit CORE or DENSE choice participates in versioned local and share-link state; temporary Space Missions overrides do not.
- **Class toggles** (`src/layers/satellites/classes.js`): the layer row carries one chip per class — STATIONS, IMAGING, TELECOM (communications and navigation), PROBES (science, technology development and demonstration, unknown purpose) and DEBRIS (rocket bodies, fragments, unknown objects launched before last year and dead payloads) on by default, so the layer shows what it did before classes; STARLINK off, as DENSE was. Points of a hidden class stay built and are only hidden, so a toggle needs no reload; hidden classes are left out of the detection overlay, the voice/framing position lists and analyst answers (the tracked satellite still answers), and the legend keys only the classes on screen. The class comes, strongest evidence first, from CelesTrak SATCAT (object type and operational status, fetched per group through `/api/celestrak-satcat/<group>`, cached a day by the proxy; the layer keeps a current read six hours rather than asking on every five-minute update), the bundled UCS Satellite Database pack (UCS-Satellite-Database 5-1-2023: operator, owner country and purpose; `src/data/local_data/ucs_satellites/`), name patterns for satellites launched after May 2023, and finally the CelesTrak groups the TLE came in (a mission group such as `weather` before the orbit group `geo`; a UCS purpose of "Unknown" counts as none). Only crewed stations and the craft that visit them, by name, are STATIONS: the CubeSats CelesTrak's stations group also carries after their deployment from the ISS are classed like any other satellite. A payload whose SATCAT record gives no status, with no UCS record and no recognisable name, that launched 20 or more years ago (SATCAT's launch date, else the TLE designator's year) is presumed dead and filed as debris; without a SATCAT record (a failed read) nothing is presumed. To cover imaging launched after the UCS snapshot the core catalog also reads CelesTrak's `resource`, `weather`, `planet`, `sar` and `science` groups. Debris can be tracked but is never ridden: the orbital entry gate (`orbitEntryAllowed`) refuses it, so no ORBIT entry is offered and double-click does nothing for it. Retired stations and the shuttles have re-entered and have no orbit to show. An explicit class choice is kept in local and share-link state as the `classes` option, one letter per class shown (`sitpd`: stations, imaging, telecom, probes, debris; `0`: none; `src/data/satelliteClassMask.js`), and the layer takes those letters back through `setParams({classes})`; STARLINK maps to the existing `catalog: 'dense'` param instead.
- The satellite Cockpit subject (`getCockpitSubject()`) also carries `satelliteClass`, `cosparId` (from SATCAT, else TLE line 1), `tle` (`{line1, line2, epochMs}`), `owner` (`{countryCode, label}`: ISO 3166-1 alpha-2 for a single country, `null` code for organisations such as ESA, EUMETSAT or Intelsat and for joint owners) and `operator` (UCS; SpaceX for Starlink). UCS names the operator's country and wins over the SATCAT owner code; CelesTrak's CIS (former USSR) is filed under Russia.
- **The STARLINK chip (formerly DENSE) reports the dense LOAD, not the catalog param.** The param flips synchronously while the Starlink shell takes seconds to arrive over a chunked load, and CelesTrak 502s that feed regularly. So the chip reads `STARLINK ···` (busy, disabled) while loading, ACTIVE only once dense points are actually on screen, and `STARLINK ✕` with the reason on hover when the load fails — a failure also reverts `catalog` to `core`, drops any partial chunk, and leaves the chip clickable to retry. A load is judged by points added, not by HTTP status: a 200 carrying an empty body, a passed-through HTML error page, or only TLEs the core catalog already owns fails with the same revert semantics as a 502. Any explicit request for `core` clears a latched error even when the mode does not change, so a Space Missions restore of an already-core snapshot never leaves the user with a failure they did not cause. Because the load settles asynchronously, the layer pushes a re-render through the optional `setRowControlsListener()` hook; nothing else would repaint that row before the 5-minute catalog refresh, so the counts would otherwise sit stale.
- **A dependency owner takes the row with it.** Space Missions borrows this layer for TLE lookup with `showPoints:false`; while points are hidden the layer returns empty row controls, so no count describes an empty sky and the chip cannot accept a write that the owner's restore would silently revert.
- **The STARLINK chip (formerly DENSE) reports the dense LOAD, not the catalog param.** The param flips synchronously while the Starlink shell takes seconds to arrive over a chunked load, and CelesTrak 502s that feed regularly. So the chip reads `STARLINK ···` (busy, disabled) while loading, ACTIVE only once dense points are actually on screen, and `STARLINK ✕` with the reason on hover when the load fails — a failure also reverts `catalog` to `core`, drops any partial chunk, and leaves the chip clickable to retry. A load is judged by points added, not by HTTP status: a 200 carrying an empty body, a passed-through HTML error page, or only TLEs the core catalog already owns fails with the same revert semantics as a 502. Any explicit request for `core` clears a latched error even when the mode does not change, so a Space Missions restore of an already-core snapshot never leaves the user with a failure they did not cause. Because the load settles asynchronously, the layer pushes a re-render through the optional `setRowControlsListener()` hook; nothing else would repaint that row before the 5-minute catalog refresh, so the count and legend would otherwise sit stale.
- **A dependency owner takes the row with it.** Space Missions borrows this layer for TLE lookup with `showPoints:false`; while points are hidden the layer returns empty row controls, so the legend never describes an empty sky and the chip cannot accept a write that the owner's restore would silently revert.
- The detection-overlay record cache (`_detectionObjects`) is cleared with the catalog on every rebuild: it stamps id/class at creation only, and a rebuild can re-tag a satellite when a partial CelesTrak outage changes which group wins dedupe.
- **Catalog numbers above 99999** can be written in a TLE as Alpha-5: a letter A–Z, skipping I and O, for the first two digits, so `A0000` is 100000 and `Z9999` is 339999. CelesTrak's TLE feed carries no satellite above 99999 (that needs the OMM feed, #1191), so this is compatibility with Alpha-5 TLEs. `src/sources/tle.js` decodes the field through one shared helper: `noradIdFromSatnum()` for the satellites layer, which keys and deduplicates its catalog by that number, and `tleCatalogNumber()` for the satellite tools. Plain digits read as before (`noradIdFromSatnum()` accepts any length, as an OMM satrec carries the number unpadded); a malformed field — a sign, decimal point, hex, exponent, embedded space, stray or lowercase letter, or blank — is rejected rather than partly read, as `NaN` in the layer and `null` in the tools.
- **CCTV estimated bearings:** a camera whose pack marks `headingConfidence: 'low'` (the id-hash
+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');
});
+72 -12
View File
@@ -10,6 +10,7 @@ import { straightSegment } from './fixCurve.js';
import {
norm180,
distance,
distanceSquared,
clone,
copyInto,
toDegrees,
@@ -385,8 +386,32 @@ let instances = 0;
/** A plan that ran out longer ago than this (ms) is not eased away from. */
const RECOVER_STALE_PLAN_MS = 1_000;
/** How far ahead (ms) a placed contact's segment runs before it is asked again. */
/** How far ahead (ms) a placed contact's segment runs before it is asked
* again, in view and near the eye. */
const PLACED_PLAN_MS = 1000;
/** The same out of view, or farther than PLACED_NEAR_M from the eye: off
* screen a contact's path is not seen, and that far a straight segment
* over this long (half as long again at most, as spread) is well under a
* pixel off it. Asking for each contact every second would rewrite the
* whole fleet every second. */
const PLACED_FAR_PLAN_MS = 4000;
/** Nearer the eye than this (m), a placed contact in view is planned every
* PLACED_PLAN_MS. */
const PLACED_NEAR_M = 300_000;
/**
* Each contact's plans run between 1/2 and 3/2 of their length, by its id,
* so the fleet's plans run out spread over the passes, not together in one
* (contacts first planned in the same pass would otherwise stay in step).
*/
export function placedPlanSpread(id) {
let hash = 2166136261;
for (let i = 0; i < id.length; i++) {
hash ^= id.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return 0.5 + ((hash >>> 0) % 1024) / 1024;
}
/** A display delay that never changes (ms). */
function fixedDelay(ms) {
@@ -465,6 +490,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 +519,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
@@ -815,12 +843,28 @@ export function createAircraftIcons({
planFrom.set(icao24, validFrom);
}
/** The camera, while the fleet pass re-plans the rows that ran out:
* `{eye, inView(position)}` (null: every plan is a near one). */
let planView = null;
/** How long a placed contact at `position` is planned for (ms). */
function _placedPlanMs(icao24, position) {
const near =
!planView ||
(distanceSquared(planView.eye, position) <
PLACED_NEAR_M * PLACED_NEAR_M &&
planView.inView(position));
return (
(near ? PLACED_PLAN_MS : PLACED_FAR_PLAN_MS) * placedPlanSpread(icao24)
);
}
/**
* Plan a live contact a host-supplied placement places: from where it
* places it at `t` (display ms, the live clock's delayed time) to where it
* places it PLACED_PLAN_MS on, asked again when that runs out. Display
* time is wall time less the display delay, so the placement is asked at
* the wall times the segment's ends stand for.
* places it a plan's length on (`_placedPlanMs`), asked again when that
* runs out. Display time is wall time less the display delay, so the
* placement is asked at the wall times the segment's ends stand for.
* @returns {boolean} False when there is no placement, the layer follows
* the world clock, or it has no answer for this contact.
*/
@@ -839,7 +883,7 @@ export function createAircraftIcons({
)
return true;
easeEnds.delete(icao24);
const t1 = t + PLACED_PLAN_MS;
const t1 = t + _placedPlanMs(icao24, from);
const to = vec();
const end = placeAt(icao24, t1 + leadMs, info, history, to);
const motion = end
@@ -903,12 +947,17 @@ export function createAircraftIcons({
* moved back (a seek, or the clock run backward): it is drawn where it was
* then, as it is when the time moves on.
*/
function _replanExpired(t) {
if (followsClock() && t < replannedAt)
for (const [icao24, from] of planFrom)
if (from > t) _planIcon(icao24, { rewound: true });
replannedAt = t;
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
function _replanExpired(t, view = null) {
planView = view;
try {
if (followsClock() && t < replannedAt)
for (const [icao24, from] of planFrom)
if (from > t) _planIcon(icao24, { rewound: true });
replannedAt = t;
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
} finally {
planView = null;
}
}
/**
@@ -930,6 +979,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 +1002,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 +1096,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 +1160,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 +1237,7 @@ export function createAircraftIcons({
_fleetLook,
_turnRotors,
_rotorsTurning,
_rotorDrawnAtMs,
_addIcon,
_forgetContact,
_iconIds,
+133 -5
View File
@@ -5,6 +5,7 @@ import {
createAircraftIcons,
createContactIcons,
floorCoastArc,
placedPlanSpread,
} from './aircraftIconLayer.js';
import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js';
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
@@ -37,7 +38,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 +50,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 +77,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 +89,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 +104,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();
});
@@ -481,3 +502,110 @@ test('back at live, a placed contact eases from where it is drawn over a recover
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
);
});
/** A layer whose placement has every contact flying east from `at(id)`. */
function placedFleet(ids, at) {
const state = {
now: () => Date.now(),
_icons: createContactIcons(),
_positionHistory: new Map(ids.map((id) => [id, [{ epochMs: WORLD_MS }]])),
records: { data: new Map(ids.map((id) => [id, {}])) },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs },
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
placeAt: (id, wallMs, _info, _history, out) => {
Object.assign(out, at(id, wallMs));
return { courseDeg: 90, speedMps: 200 };
},
});
for (const id of ids)
state._icons.put(
{
id,
pos: at(id, WORLD_MS),
motion: { kind: 'hold', courseDeg: 90 },
course: 90,
size: [20, 20],
},
{ expiresAt: -Infinity },
);
return { icons, set: state._icons };
}
test('a placed fleet planned in one pass runs out spread over the passes after it, not together', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const ids = Array.from({ length: 400 }, (_, i) =>
(0xa00000 + i * 37).toString(16),
);
const { icons, set } = placedFleet(ids, () => fromDegrees(0, 30, 3_000));
icons._replanExpired(Date.now());
const ends = ids.map((id) => set.expires(id) - WORLD_MS);
for (const ms of ends) assert.ok(ms >= 500 && ms < 1_500, `${ms} ms`);
// An 80 ms pass (the fleet's tick) has an eighth of the fleet at most.
const perPass = new Map();
for (const ms of ends) {
const pass = Math.floor(ms / 80);
perPass.set(pass, (perPass.get(pass) ?? 0) + 1);
}
assert.ok(
Math.max(...perPass.values()) <= ids.length / 8,
`${Math.max(...perPass.values())} in one pass`,
);
// Planned again when it runs out, each runs as long as before, from then.
const first = new Map(ids.map((id) => [id, set.expires(id)]));
t.mock.timers.tick(1_500);
icons._replanExpired(Date.now());
for (const id of ids) {
const item = set.item(id);
assert.equal(item.motion.t0, Date.now(), id);
assert.equal(
set.expires(id) - Date.now(),
first.get(id) - WORLD_MS,
`${id} runs as long`,
);
}
});
test('a placed contact far from the eye or out of view is planned for longer than a near one in view', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const where = {
n: fromDegrees(0, 30, 3_000),
f: fromDegrees(10, 30, 3_000),
o: fromDegrees(0.01, 30, 3_000),
};
const ids = Object.keys(where);
const { icons, set } = placedFleet(ids, (id) => where[id]);
const eye = fromDegrees(0, 30, 60_000);
const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
// In view: all but 'o', told apart by where the placement puts it.
const view = { eye, inView: (p) => metres(p, where.o) > 1 };
const length = (id) =>
(set.expires(id) - set.item(id).motion.t0) / placedPlanSpread(id);
icons._replanExpired(Date.now(), view);
assert.ok(Math.abs(length('n') - 1_000) < 1, `near ${length('n')}`);
assert.ok(Math.abs(length('f') - 4_000) < 1, `far ${length('f')}`);
assert.ok(Math.abs(length('o') - 4_000) < 1, `out of view ${length('o')}`);
// The camera is the pass's only: a contact planned after it, as a new
// report plans it, takes a near plan, even after a pass that threw.
icons._planIcon('f');
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a pass ${length('f')}`);
t.mock.timers.tick(5_000);
assert.throws(() =>
icons._replanExpired(Date.now(), {
eye,
inView: () => {
throw new Error('camera gone');
},
}),
);
icons._planIcon('f');
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a throw ${length('f')}`);
});
+85 -1
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());
}
}
@@ -970,7 +1041,14 @@ export function createAircraftModels({
if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts();
parts.icons._syncImageSwitch();
parts.icons._replanExpired(t);
// Far and out-of-view contacts are planned for longer (the camera says
// which are which).
parts.icons._replanExpired(
t,
pose?.position
? { eye: pose.position, inView: (position) => inView(pose, position) }
: null,
);
const renderTime = parts.motion._displayTimeAt(
t,
state._scratchFleetRenderTime,
@@ -1136,5 +1214,11 @@ export function createAircraftModels({
_handBackDeselected,
_updateTrackedModel,
_fleetTick,
_paceHz,
_startPace: () => {
paceReadMs = -Infinity;
pace.start();
},
_stopPace: pace.stop,
};
}
+19 -1
View File
@@ -114,11 +114,14 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
};
let now = 1_000_000;
let iconRecedeSyncs = 0;
const replanViews = [];
const parts = {
icons: {
_displayMs: () => now,
_syncImageSwitch() {},
_replanExpired() {},
_replanExpired(_t, view) {
replanViews.push(view);
},
_focusIcons() {},
_occluder: () => null,
_aboveHorizon: () => true,
@@ -160,6 +163,9 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
failNextUpsert: () => (failNextUpsert = true),
/** How often the icons were told to recede by the tuning as it is now. */
iconRecedeSyncs: () => iconRecedeSyncs,
/** The camera each fleet tick re-planned the icons with. */
replanViews,
eye,
/** Mark a contact as not there yet at the time drawn, or there again. */
setUnseen(id, value) {
if (value) unseenIds.add(id);
@@ -476,3 +482,15 @@ test('the selected contact keeps a loaded, hidden fleet model that takes it back
assert.equal(f.fleet().items.get('a1').show, true);
assert.equal(f.shown.get('a1'), false);
});
test('the fleet tick re-plans the icons with the camera: its eye, and what it sees', () => {
const f = fleetFixture(new Map([['a1', far(1)]]));
f.tick();
const [view] = f.replanViews;
assert.equal(view.eye, f.eye);
// The camera looks along -z: ahead of the eye is in view, behind it not.
const ahead = { x: f.eye.x, y: f.eye.y, z: f.eye.z - 10_000 };
const behind = { x: f.eye.x, y: f.eye.y, z: f.eye.z + 10_000 };
assert.equal(view.inView(ahead), true);
assert.equal(view.inView(behind), false);
});
+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`,
);
}
});
+9 -5
View File
@@ -65,7 +65,10 @@ const START_SIZE_PX = 1024;
const MAX_SIZE_PX = 4096;
function createAtlas() {
const slotOfKey = new Map();
// By URL, then by size: a URL is hashed once as it is, where a key built
// from it would be a new string to hash on every look-up (an SVG data URL
// runs to kilobytes, and a fleet's write looks up two a row).
const slotsOfUrl = new Map();
const entries = [];
const listeners = new Set();
const atlas = {
@@ -90,8 +93,8 @@ function createAtlas() {
* @returns {number}
*/
slot(url, sizePx, source) {
const key = `${sizePx}|${url}`;
const known = slotOfKey.get(key);
let bySize = slotsOfUrl.get(url);
const known = bySize?.get(sizePx);
if (known !== undefined) return known;
if (entries.length >= MAX_ICON_SLOTS)
throw new RangeError(
@@ -100,7 +103,8 @@ function createAtlas() {
const slot = entries.length;
const entry = { url, sizePx, image: null, x: 0, y: 0 };
entries.push(entry);
slotOfKey.set(key, slot);
if (!bySize) slotsOfUrl.set(url, (bySize = new Map()));
bySize.set(sizePx, slot);
if (source) placeLoaded(entry, source);
else load(entry);
return slot;
@@ -108,7 +112,7 @@ function createAtlas() {
/** Whether `url` at `sizePx` already has a slot. */
has(url, sizePx) {
return slotOfKey.has(`${sizePx}|${url}`);
return slotsOfUrl.get(url)?.has(sizePx) === true;
},
/** Whether a slot's image is packed and drawable. */
+24
View File
@@ -0,0 +1,24 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { iconAtlas } from './iconAtlas.js';
test('an atlas slot is one per image and size, and has() agrees with slot()', () => {
const url = `data:image/svg+xml;charset=utf-8,${'%3Csvg%3E'.repeat(400)}#slots`;
const other = `${url}-other`;
assert.equal(iconAtlas.has(url, 20), false);
const small = iconAtlas.slot(url, 20);
assert.equal(iconAtlas.has(url, 20), true);
assert.equal(iconAtlas.slot(url, 20), small, 'the same image and size');
// A copy of the URL, not the same string, finds it too.
assert.equal(iconAtlas.slot(url.slice(0), 20), small);
assert.equal(iconAtlas.has(url, 40), false, 'another size is another slot');
const large = iconAtlas.slot(url, 40);
assert.notEqual(large, small);
assert.equal(iconAtlas.has(url, 40), true);
assert.equal(
iconAtlas.has(other, 20),
false,
'another image is another slot',
);
assert.notEqual(iconAtlas.slot(other, 20), small);
});
+20 -34
View File
@@ -14,7 +14,6 @@ import satellitesLayer, {
_setDenseCatalogStateForTest,
} from './satellites.js';
import { CATALOG_GROUPS } from '../layers/satellites/policy.js';
import { SATELLITE_CLASS_DISPLAY } from '../layers/satellites/classes.js';
/**
* A real, parseable TLE under an arbitrary 5-digit catalog number, so the dense
@@ -202,12 +201,11 @@ test('STARLINK reports loading, then ACTIVE only once the points exist', async (
assert.equal(settled.label, 'STARLINK');
assert.deepEqual(settled.params, { catalog: 'core' }, 'a settled chip toggles back off');
// The completion pushed a refresh, and the STARLINK chip gained its swatch
// and count with it — without that push the row would keep the pre-load
// counts for 5 minutes.
// The completion pushed a refresh, and the legend gained STARLINK with it —
// without that push the row would keep the pre-load counts for 5 minutes.
assert.ok(refreshes.length >= 2, 'load start and load completion each pushed a refresh');
assert.equal(settled.swatch, SATELLITE_CLASS_DISPLAY.starlink.color);
assert.equal(settled.count, 1);
const legend = satellitesLayer.getRowControls().legend;
assert.equal(legend.some((row) => row.klass === 'starlink'), true);
} finally {
globalThis.fetch = originalFetch;
_clearDenseCatalogStateForTest();
@@ -233,8 +231,11 @@ test('a failed STARLINK load reverts the mode rather than leaving an active chip
assert.match(settled.title, /502/, 'the chip explains why');
assert.equal(satellitesLayer.getParams().catalog, 'core', 'the mode reverts to reality');
assert.deepEqual(settled.params, { catalog: 'dense' }, 'clicking retries');
assert.equal(settled.swatch, undefined, 'no STARLINK swatch when nothing loaded');
assert.equal(settled.count, undefined, 'and no STARLINK count');
assert.equal(
satellitesLayer.getRowControls().legend.some((row) => row.klass === 'starlink'),
false,
'no STARLINK class is advertised when nothing loaded',
);
assert.ok(pushes >= 2, 'the failure pushed its own refresh');
// Retrying against a healthy feed clears the error — it does not latch.
@@ -317,10 +318,10 @@ test('an explicit return to core clears a failure the user never caused', async
}
});
test('a real stations-feed outage keeps the ISS counted under STATIONS', async () => {
test('a real stations-feed outage keeps the ISS under STATIONS in the legend', async () => {
// End-to-end version of the tally rule: drive a real rebuild in which only
// the `visual` group answers, so the ISS is genuinely ingested as `visual`.
// The STATIONS chip must still count it or it disagrees with the card.
// The legend must still file it under STATION or it disagrees with the card.
const originalFetch = globalThis.fetch;
const log = console.log;
const warn = console.warn;
@@ -338,14 +339,13 @@ test('a real stations-feed outage keeps the ISS counted under STATIONS', async (
assert.equal(_catalogGroupForTest(25544), 'visual',
'the outage really did ingest the ISS from the visual group');
const counted = satellitesLayer
.getRowControls()
.chips.filter((entry) => entry.count !== undefined);
assert.deepEqual(counted.map((entry) => [entry.id, entry.count]), [['class-stations', 1]],
'STATIONS survives the outage because the ISS is counted there, and only there');
const legend = satellitesLayer.getRowControls().legend;
assert.equal(legend.find((row) => row.klass === 'stations')?.count, 1,
'STATIONS survives the outage because the ISS is counted there');
assert.equal(legend.length, 1, 'and it is not also counted under another class');
const [iss] = satellitesLayer.getAnalystRecords();
assert.equal(iss?.satelliteClass, 'STATIONS · ISS',
'the card says the same thing the chip does');
'the card says the same thing the legend does');
} finally {
console.log = log;
console.warn = warn;
@@ -405,7 +405,7 @@ test('a dependency owner hiding the points surrenders the whole row', async () =
satellitesLayer.setParams({ showPoints: false });
const owned = satellitesLayer.getRowControls();
assert.deepEqual(owned.chips, [], 'no chip to click while the owner holds the params');
assert.equal(owned.legend, undefined, 'no counts describing an empty sky');
assert.deepEqual(owned.legend, [], 'no legend describing an empty sky');
satellitesLayer.setParams({ showPoints: true });
assert.equal(satellitesLayer.getRowControls().chips.length, 6, 'released on restore');
@@ -448,30 +448,16 @@ test('every class but Starlink shows by default; each class chip turns its class
false,
);
assert.deepEqual(chip('telecom').params, { classes: { telecom: false } });
// One pill per class carries what the legend did: an on class shows its
// point colour and its count beside its name, an off one only its name.
const controls = satellitesLayer.getRowControls();
assert.equal(controls.legend, undefined, 'no separate list of counts');
assert.deepEqual(
controls.chips.map((entry) => [entry.id, entry.swatch, entry.count]),
[
['class-stations', SATELLITE_CLASS_DISPLAY.stations.color, 1],
['class-imaging', SATELLITE_CLASS_DISPLAY.imaging.color, 1],
['class-telecom', SATELLITE_CLASS_DISPLAY.telecom.color, 1],
['catalog', undefined, undefined],
// On, but nothing of the class is loaded: the colour shows, no count.
['class-probes', SATELLITE_CLASS_DISPLAY.probes.color, undefined],
['class-debris', SATELLITE_CLASS_DISPLAY.debris.color, 1],
],
satellitesLayer.getRowControls().legend.map((row) => row.klass),
['stations', 'imaging', 'telecom', 'debris'],
'the legend keys only what is on screen',
);
satellitesLayer.setParams(chip('telecom').params);
satellitesLayer.setParams(chip('debris').params);
assert.deepEqual(shown(), [25544, 90002], 'telecom and debris off');
assert.equal(chip('debris').active, false);
assert.equal(chip('debris').swatch, undefined, 'an off pill drops its colour');
assert.equal(chip('debris').count, undefined, 'and its count');
assert.equal(chip('debris').label, 'DEBRIS', 'and keeps its name');
assert.deepEqual(satellitesLayer.getParams().classes, {
stations: true,
imaging: true,
+11 -6
View File
@@ -3,7 +3,10 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createFlightState } from './state.js';
import { createIcons } from './icons.js';
import { createContactIcons } from '../../data/aircraftIconLayer.js';
import {
createContactIcons,
placedPlanSpread,
} from '../../data/aircraftIconLayer.js';
import { layerPlacement } from '../../data/placementProvider.js';
import {
aircraftMotionRegime,
@@ -269,8 +272,10 @@ test('a live contact a placement places is drawn along where it places it', (t)
const now = icons._displayMs();
const leadMs = Date.now() - now;
icons._planIcon('p');
// A plan's length, as this contact's are spread (a second on average).
const planMs = 1000 * placedPlanSpread('p');
// Asked for the wall times the segment's ends stand for.
assert.deepEqual(asked, [now + leadMs, now + 1000 + leadMs]);
assert.deepEqual(asked, [now + leadMs, now + planMs + leadMs]);
assert.equal(regimes.length, 0, 'its own motion is not planned');
const item = set.item('p');
assert.equal(item.motion.kind, 'lerp');
@@ -284,16 +289,16 @@ test('a live contact a placement places is drawn along where it places it', (t)
Cesium.Cartesian3.distance(
item.motion.to,
Cesium.Cartesian3.fromDegrees(
(now + 1000 + leadMs - t0) / 10_000,
(now + planMs + leadMs - t0) / 10_000,
30,
2000,
),
) < 1e-6,
);
assert.equal(item.motion.t0, now);
assert.equal(item.motion.t1, now + 1000);
assert.ok(Math.abs(item.motion.courseSlopeDeg - 1) < 1e-9);
assert.equal(set.expires('p'), now + 1000);
assert.equal(item.motion.t1, now + planMs);
assert.ok(Math.abs(item.motion.courseSlopeDeg - planMs / 1000) < 1e-9);
assert.equal(set.expires('p'), now + planMs);
// No answer: the layer's own motion plans it.
places = false;
+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);
},
+36 -30
View File
@@ -105,7 +105,7 @@ export function createControls({ state: layerState, services, parts, source }) {
};
}
/** Tell the manager to re-render this layer's row (chip state and counts). */
/** Tell the manager to re-render this layer's row (chip state / legend counts). */
function _notifyRowControls() {
try {
@@ -116,7 +116,7 @@ export function createControls({ state: layerState, services, parts, source }) {
}
/**
* Per-class tally for the row's class chips, cached against the catalog revision.
* Per-class tally for the row legend, cached against the catalog revision.
* Without the cache this scans ~10.7k entries in dense mode on every panel
* refresh, and any layer polling on the 1s stats timer refreshes the panel.
* @returns {Record<string, number>} Class key → count.
@@ -712,10 +712,8 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Layer-row sub-controls (DataLayerManager row-controls contract): one
* toggle chip per satellite class (src/layers/satellites/classes.js). A
* class that is on carries its point colour (`swatch`) and, once any of
* it is loaded, its count, so the point colours are learnable; a class
* that is off carries only its name.
* toggle chip per satellite class (src/layers/satellites/classes.js), and a legend
* of the classes on screen so the point colours are learnable.
*
* Chips are stateless — each declares the params to apply and the manager
* owns the write, so the Space Missions snapshot/restore path (which drives
@@ -725,41 +723,49 @@ export function createControls({ state: layerState, services, parts, source }) {
* STARLINK is the dense catalog (chip id `catalog`) and reports the dense
* LOAD state, not the param: the param flips synchronously while the shell
* takes seconds to arrive and frequently 502s, so ACTIVE means "Starlink
* points are on screen" and nothing less. The class tally is cached
* points are on screen" and nothing less. The legend tally is cached
* against the catalog revision. While SATCAT is stale or unavailable the
* info line says the classes may lag (see `classEvidenceNotice`).
* @returns {{ chips: Array<object>, info: string, infoTitle: string }}
* Row controls.
* @returns {{ chips: Array<object>, legend: Array<object>, info: string,
* infoTitle: string }} Row controls.
*/
getRowControls() {
// A dependency owner (Space Missions) borrows this layer for TLE lookup
// with showPoints:false. Nothing is rendered, so a count would describe an
// with showPoints:false. Nothing is rendered, so a legend would describe an
// empty sky and a chip write would be silently reverted by that owner's
// restore. Surrender the row rather than lie about it.
if (!layerState._params.showPoints) return { chips: [] };
if (!layerState._params.showPoints) return { chips: [], legend: [] };
const classes = _classes();
const chips = SATELLITE_CLASS_IDS.map((id) =>
id === 'starlink'
? _starlinkChip()
: {
id: `class-${id}`,
label: t(SATELLITE_CLASS_DISPLAY[id].label),
active: classes[id] === true,
state: classes[id] === true ? 'active' : 'idle',
title: t(SATELLITE_CLASS_DISPLAY[id].blurb),
params: { classes: { [id]: classes[id] !== true } },
},
);
const counts = _classTally();
const chips = SATELLITE_CLASS_IDS.map((id) => {
const chip =
const legend = [];
for (const id of SATELLITE_CLASS_IDS) {
const shown =
id === 'starlink'
? _starlinkChip()
: {
id: `class-${id}`,
label: t(SATELLITE_CLASS_DISPLAY[id].label),
active: classes[id] === true,
state: classes[id] === true ? 'active' : 'idle',
title: t(SATELLITE_CLASS_DISPLAY[id].blurb),
params: { classes: { [id]: classes[id] !== true } },
};
// The colour key and count ride on a class that is on; an off
// class is its name alone.
if (!chip.active) return chip;
chip.swatch = SATELLITE_CLASS_DISPLAY[id].color;
if (counts[id] > 0) chip.count = counts[id];
return chip;
});
return { chips, ...classEvidenceNotice() };
? layerState._params.catalog === 'dense'
: classes[id] === true;
if (!shown || !(counts[id] > 0)) continue;
legend.push({
klass: id,
label: t(SATELLITE_CLASS_DISPLAY[id].label),
color: SATELLITE_CLASS_DISPLAY[id].color,
blurb: t(SATELLITE_CLASS_DISPLAY[id].blurb),
count: counts[id],
});
}
return { chips, legend, ...classEvidenceNotice() };
},
/**
+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();
+104 -4
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,9 +819,17 @@ export function createRendering({
if (layerState._params.showPoints) {
const worldMs = layerState.now();
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
layerState._lastReckonMs = worldMs;
_reckonPoints(worldMs);
// 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
@@ -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']]);
});
+108 -19
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,26 +1001,88 @@ 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();
// 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) {
const visual = visualRecords.get(record);
if (!visual?.position) continue;
if (!drawnNow(record, visual)) continue;
const placed = services.placement.place(record.id, nowMs);
if (placed) motion.moving = true;
const { lat, lon } = placed ?? record;
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveDrawnVisual(record, visual, lat, lon, motion);
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) {
const visual = visualRecords.get(record);
if (!visual?.position) continue;
if (!drawnNow(record, visual)) continue;
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,
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;
+1 -6
View File
@@ -525,12 +525,7 @@ export class LayerPanel {
row.controls = false;
return null;
}
// A chip's count is shortened as the row's is.
const chips = (controls?.chips || []).map((chip) =>
Number.isFinite(chip.count)
? { ...chip, countText: formatCount(chip.count) }
: chip,
);
const chips = controls?.chips || [];
const legend = (controls?.legend || []).map((item) => ({
color: item.color,
blurb: item.blurb,
-22
View File
@@ -509,25 +509,3 @@ test('a layer with no feed in view says why instead of "never"', async () => {
setLocale('en');
}
});
test('a chip count is shortened like the row count', async () => {
const { LayerPanel } = await import('./layerPanel.js');
const panel = Object.create(LayerPanel.prototype);
panel._rowControlsFor = () => ({
chips: [
{ id: 'a', label: 'A', active: true, swatch: '#fff', count: 10700 },
{ id: 'b', label: 'B', active: true, swatch: '#fff', count: 42 },
{ id: 'c', label: 'C', active: false },
],
});
const { chips, hidden } = panel._presentControls(
{},
{ id: 'x', enabled: true },
);
assert.equal(hidden, false);
assert.deepEqual(
chips.map((chip) => chip.countText),
['10.7K', '42', undefined],
);
assert.equal(chips[0].swatch, '#fff', 'the rest of the chip passes through');
});
-58
View File
@@ -272,61 +272,3 @@ test('a core row carries no library entry attribute', () => {
assert.equal(element.hasAttribute('data-library-entry'), false);
render(null, container);
});
const classRow = (chips) => ({
...row(false),
key: 'satellites',
id: 'satellites',
controls: { hidden: false, chips, legend: [], list: null },
});
test('a keyed chip carries its swatch and count while on, only its name while off', () => {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const picks = [];
const on = {
id: 'class-imaging',
label: 'IMAGING',
active: true,
swatch: '#4fd8ff',
countText: '1.2K',
};
render(
h(LayerRows, {
items: [classRow([on])],
onChip: (id, chipId) => picks.push([id, chipId]),
}),
container,
);
const button = container.querySelector('[data-chip-id="class-imaging"]');
assert.equal(button.getAttribute('aria-pressed'), 'true');
const [swatch, name, count] = button.children;
assert.ok(swatch.classList.contains('data-toggle-chip-swatch'));
assert.equal(swatch.style.background, '#4fd8ff');
assert.equal(swatch.getAttribute('aria-hidden'), 'true');
assert.equal(name.textContent, 'IMAGING');
assert.ok(count.classList.contains('data-toggle-chip-count'));
assert.equal(count.textContent, '1.2K');
assert.ok(button.classList.contains('chip-keyed'));
assert.equal(button.textContent, 'IMAGING 1.2K', 'name and count read apart');
button.click();
assert.deepEqual(picks, [['satellites', 'class-imaging']]);
// Off: the same pill, its name alone.
render(
h(LayerRows, {
items: [
classRow([{ id: 'class-imaging', label: 'IMAGING', active: false }]),
],
}),
container,
);
const off = container.querySelector('[data-chip-id="class-imaging"]');
assert.equal(off.getAttribute('aria-pressed'), 'false');
assert.equal(off.textContent, 'IMAGING');
assert.equal(off.querySelector('.data-toggle-chip-swatch'), null);
assert.equal(off.querySelector('.data-toggle-chip-count'), null);
assert.equal(off.classList.contains('chip-keyed'), false);
assert.equal(container.querySelector('.data-toggle-legend-item'), null);
render(null, container);
});
+5 -18
View File
@@ -5,16 +5,14 @@ import UiIcon from '../kit/UiIcon.vue';
// Keyed chips shared by rail cards; the owner decides what a click does.
// An `icon` chip shows a Material Symbol (named in index.html's `icon_names`
// subset) with its label as the accessible name and tip; an `action` chip
// (Zoom, Remove) is a plain button, not an on/off toggle. A `swatch` chip
// (a CSS colour) keys what it turns on: the colour before its label and, with
// `countText`, how many after it; the owner leaves both off a chip that is off.
// (Zoom, Remove) is a plain button, not an on/off toggle.
defineProps({
chips: { type: Array, default: () => [] },
onSelect: { type: Function, default: () => {} },
});
const chipClass = (chip) =>
`data-toggle-chip chip-${chip.state || (chip.active ? 'active' : 'idle')}${chip.icon ? ' chip-icon' : ''}${chip.swatch && !chip.icon ? ' chip-keyed' : ''}`;
`data-toggle-chip chip-${chip.state || (chip.active ? 'active' : 'idle')}${chip.icon ? ' chip-icon' : ''}`;
</script>
<template>
@@ -33,19 +31,8 @@ const chipClass = (chip) =>
:aria-busy="String(Boolean(chip.busy))"
@click="onSelect(chip)"
><UiIcon v-if="chip.icon" :name="chip.icon" :size="null" /><template
v-else-if="chip.swatch"
><span
class="data-toggle-chip-swatch"
aria-hidden="true"
:style="{ background: chip.swatch }"
></span
><span>{{ chip.label }}</span
><template v-if="chip.countText"
>{{ ' '
}}<span class="data-toggle-chip-count">{{
chip.countText
}}</span></template
></template
><template v-else>{{ chip.label }}</template></UiButton
v-else
>{{ chip.label }}</template
></UiButton
>
</template>
-21
View File
@@ -1,21 +0,0 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
const kit = readFileSync(new URL('./kit.css', import.meta.url), 'utf8').replace(
/\/\*[\s\S]*?\*\//g,
'',
);
test("an icon's glyph stays in its box under a page-wide jQuery UI .ui-icon rule", () => {
const rule = kit.match(/\.ui-icon\.ui-icon\s*\{([^}]*)\}/);
assert.ok(rule, 'a doubled class outranks a single-class .ui-icon rule');
for (const declaration of [
/text-indent:\s*0/,
/overflow:\s*visible/,
/background-image:\s*none/,
/width:\s*auto/,
/height:\s*auto/,
])
assert.match(rule[1], declaration);
});
-12
View File
@@ -40,18 +40,6 @@
user-select: none;
}
/* The icon is a font ligature; `ui-icon` is also jQuery UI's sprite-icon class, and a stylesheet
that brings jQuery UI's rule into the page (some browser extensions inject it everywhere) pushes
the glyph out of its box (`text-indent: -99999px`, `overflow: hidden`, a 16 px box). The doubled
class outranks that rule and sets only what the kit never sets elsewhere. */
.ui-icon.ui-icon {
text-indent: 0;
overflow: visible;
background-image: none;
width: auto;
height: auto;
}
.ui-tooltip {
position: relative;
display: inline-flex;
+1 -11
View File
@@ -942,15 +942,6 @@ html:not([lang='en'])
background: var(--accent-dim);
}
/* A keyed chip (RailChips.vue `swatch`): the colour of what it turns on before
its label and the count after it, while it is on, in the chip's own type.
Off, it is a plain chip. */
.data-toggle-chip.chip-keyed {
display: inline-flex;
align-items: center;
gap: 4px;
}
/* Async sub-controls: a chip must never read ACTIVE before the data it turns
on actually exists, so loading and failure are their own visible states. */
.data-toggle-chip:disabled {
@@ -980,8 +971,7 @@ html:not([lang='en'])
cursor: default;
}
.data-toggle-legend-swatch,
.data-toggle-chip-swatch {
.data-toggle-legend-swatch {
width: 6px;
height: 6px;
border-radius: 50%;