Draw Radio stations and their clusters through the draw port and take the Radio renderer off the Cesium list

The stations, the cluster dots and the selected station's dot and bracket
are draw-port point and icon sets. Stations drawn too close together on
screen are grouped by geo/screenCluster.js as the default renderer's
entity clustering grouped them: the same boxes and screen coordinates, the
same reuse of the last pass's clusters when the eye comes lower, a pass
whenever the camera moves enough or a station is shown or hidden, and
stations a pass passes over hidden until the next. A cluster dot names its
seed station, so a click plays it as before. The Radio QA script reads the
drawn sets; the unused cluster-collection internals helper is gone.
This commit is contained in:
Sameh Khamis committed 2026-11-08 11:11:50 -08:00
1 parent b2502d6f37
commit a59f9b10b2
17 files changed
+1134 -352

No files matched your search

+28 -19
View File
@@ -5,6 +5,7 @@ import {
fakeCameraPort,
} from '../testSupport/fakeCameraPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import {
buildRadioTunerBand,
buildRadioTunerTicks,
@@ -405,7 +406,7 @@ test('destroy and re-init reset Radio audio ownership, volume, filter, and telem
radioLayer.destroy();
try {
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
radioLayer.enable();
radioLayer.setLifecyclePresentation({
lifecycleState: 'enabled', enabled: true, uncertain: false,
@@ -430,7 +431,7 @@ test('destroy and re-init reset Radio audio ownership, volume, filter, and telem
assert.equal(getRadioUIState().volume, 0.8);
assert.equal(getRadioUIState().effectiveVolume, 0.8);
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
assert.equal(audioInstances.length, 2, 're-init creates a clean Audio session');
const nextState = getRadioUIState();
for (const eventName of ['playing', 'pause', 'waiting', 'error']) {
@@ -524,7 +525,7 @@ test('late media errors after replacement or Pause cannot mutate the active stat
radioLayer.destroy();
try {
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
radioLayer.enable();
await radioLayer.update();
radioLayer.setLifecyclePresentation({
@@ -654,7 +655,7 @@ test('unusable directory responses preserve warm client state atomically', async
};
radioLayer.destroy();
try {
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
globalThis.fetch = async () => new Response(JSON.stringify({
stations: [station],
stale: false,
@@ -768,7 +769,7 @@ test('unusable directory responses preserve warm client state atomically', async
assert.equal(getRadioUIState().stale, true);
assert.equal(getRadioUIState().rejectedStationCount, 10_000);
radioLayer.destroy();
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
assert.equal(getRadioUIState().rejectedStationCount, 0);
assert.equal(getRadioUIState().degraded, false);
} finally {
@@ -826,7 +827,7 @@ test('tuner drag keeps one immutable catalog resolution through refresh and rele
radioLayer.destroy();
try {
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
radioLayer.enable();
await publish(stationA, 1);
assert.equal(radioLayer.beginTuning(), true);
@@ -933,7 +934,20 @@ test('failed exact tuner release cannot consume a stale playback fallback', asyn
test('tuner cancellation restores the frozen start marker after catalog removal', async () => {
const originalFetch = globalThis.fetch;
const originalAudio = globalThis.Audio;
const selectedEntities = new Map();
const draw = fakeDrawPort();
// The selected station's dot, from the layer's selected-marker set.
const selectedEntities = {
record: () =>
[...draw.sets.values()].find(
(set) => !set.disposed && set.spec.id.endsWith(':selected'),
),
get(id) {
return this.record()?.items.get(id);
},
has(id) {
return Boolean(this.get(id));
},
};
let playCalls = 0;
let flyToCalls = 0;
globalThis.Audio = class FakeAudio {
@@ -956,11 +970,6 @@ test('tuner cancellation restores the frozen start marker after catalog removal'
canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} },
requestRender() {},
},
dataSources: { add() {}, remove() {} },
entities: {
add(entity) { selectedEntities.set(entity.id, entity); return entity; },
remove(entity) { return selectedEntities.delete(entity?.id); },
},
};
const stationA = {
id: '00000000-0000-4000-8000-000000000051',
@@ -1000,7 +1009,7 @@ test('tuner cancellation restores the frozen start marker after catalog removal'
radioLayer.destroy();
try {
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw }));
radioLayer.enable();
radioLayer.setLifecyclePresentation({
lifecycleState: 'enabled', enabled: true, uncertain: false,
@@ -1020,7 +1029,7 @@ test('tuner cancellation restores the frozen start marker after catalog removal'
assert.equal(radioLayer.cancelTuning(), true);
const restoredMarker = selectedEntities.get(`radio:selected:${stationA.id}`);
assert.ok(restoredMarker, 'the frozen start marker remains visible after cancellation');
assert.deepEqual(restoredMarker.position, startMarker.position);
assert.deepEqual(restoredMarker.pos, startMarker.pos);
assert.equal(getRadioUIState().tuningRestoredStationId, stationA.id);
assert.equal(getRadioUIState().tuningActive, false);
assert.equal(getRadioUIState().selected, null, 'stale marker never becomes playback authority');
@@ -1109,7 +1118,7 @@ test('Radio public tuner, filter, and resume mutations require certain enabled l
radioLayer.destroy();
try {
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
radioLayer.enable();
await radioLayer.update();
radioLayer.setLifecyclePresentation({
@@ -1184,7 +1193,7 @@ test('tuner refuses a degraded fallback that has no accepted catalog generation'
acceptedGeneration: null,
updatedAt: new Date().toISOString(),
}), { status: 200, headers: { 'Content-Type': 'application/json' } });
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
radioLayer.enable();
await radioLayer.update();
@@ -1239,7 +1248,7 @@ test('accepted snapshots allowlist station fields and never regress generation i
radioLayer.destroy();
try {
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
serve([station], 1);
radioLayer.enable();
await radioLayer.update();
@@ -1350,7 +1359,7 @@ test('update abort, destroy, and re-init invalidate the prior session and reset
requestSignal = options.signal;
return new Promise((resolve) => { resolveFetch = resolve; });
};
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
radioLayer.enable();
const pending = radioLayer.update();
assert.equal(getRadioUIState().loading, true);
@@ -1359,7 +1368,7 @@ test('update abort, destroy, and re-init invalidate the prior session and reset
assert.equal(getRadioUIState().loading, false);
radioLayer.destroy();
radioLayer.init(bindFakeCesiumCamera(viewer));
radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() }));
const cleanState = getRadioUIState();
assert.deepEqual({
enabled: cleanState.enabled,
+4 -2
View File
@@ -3,6 +3,7 @@ import { EventEmitter } from 'node:events';
import https from 'node:https';
import { Readable } from 'node:stream';
import test from 'node:test';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { fetchPinnedRadioResponse } from '../../server/providers/radio/transport.js';
import {
createRadioProxyMiddleware,
@@ -575,9 +576,9 @@ test('server structural rejections reach the client diagnostic without discardin
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
// The stations draw through the renderer's draw port.
const { unbind } = bindFakeDraw(viewer);
radioLayer.destroy();
try {
globalThis.fetch = async () => new Response(response.body, {
@@ -597,5 +598,6 @@ test('server structural rejections reach the client diagnostic without discardin
} finally {
globalThis.fetch = originalFetch;
radioLayer.destroy();
unbind();
}
});
+206
View File
@@ -0,0 +1,206 @@
/**
* @module geo/screenCluster
* @description Screen-space clustering of points, as the default renderer's
* entity clustering groups them: each point not yet in a cluster, in order,
* takes every unclustered point whose screen position falls inside its own
* box (its pixel size grown by `pixelRange` on every side) into a cluster at
* the mean of their world positions, when they number at least
* `minimumClusterSize`. On a pass made closer to the ground than the last
* one, each cluster of the last pass that is still above the horizon first
* keeps the points inside its box, shrunk by how much closer the eye came
* (never below the box it was seeded with); only then are new ones seeded.
*
* The coordinates follow that renderer's choices so that the clusters are
* the same ones: points are boxed in window coordinates measured from the
* bottom (`height - y`), a last pass's clusters from the top, and a kept
* cluster's box reaches half its width left and up but its whole width
* right and down.
*/
/**
* @typedef {object} ScreenClusterPoint
* @property {string} id
* @property {{x: number, y: number, z: number}} position World position.
* @property {{x: number, y: number}} screen CSS pixels from the top left.
* @property {number} pixelSize Its drawn size, CSS pixels.
*/
/**
* @typedef {object} ScreenClusterState What a pass leaves for the next.
* @property {Array<{position: {x: number, y: number, z: number},
* width: number, height: number, minimumWidth: number,
* minimumHeight: number}>} clusters
* @property {number} height The eye's height above the ground at that pass.
*/
/**
* Cluster `points` (those shown, above the horizon and in front of the eye,
* in their drawing order).
* @param {object} options
* @param {ScreenClusterPoint[]} options.points
* @param {number} options.pixelRange
* @param {number} options.minimumClusterSize
* @param {number} options.viewHeight The view's height, CSS pixels.
* @param {number} options.eyeHeight The eye's height above the ground, m.
* @param {ScreenClusterState|null} [options.previous] The last pass's state.
* @param {(position: object) => ({x: number, y: number}|null)} options.project
* Window position of a world position, CSS pixels from the top left
* (null behind the eye).
* @param {(position: object) => boolean} options.isOccluded Whether the
* ellipsoid's horizon hides a world position.
* @returns {{clusters: Array<{position: {x: number, y: number, z: number},
* ids: string[]}>, single: string[], state: ScreenClusterState}}
* The clusters (each with its points' ids, its seed first), the ids of the
* points left on their own, and the state for the next pass.
*/
export function clusterScreenPoints({
points,
pixelRange,
minimumClusterSize,
viewHeight,
eyeHeight,
previous = null,
project,
isOccluded,
}) {
const n = points.length;
const xs = new Float64Array(n);
const ys = new Float64Array(n);
for (let i = 0; i < n; i++) {
xs[i] = points[i].screen.x;
ys[i] = viewHeight - points[i].screen.y;
}
const clustered = new Uint8Array(n);
const index = createGridIndex(xs, ys, Math.max(1, pixelRange * 2));
const clusters = [];
const kept = [];
if (n > 0 && previous && eyeHeight < previous.height) {
const factor = 1 - eyeHeight / previous.height;
for (const cluster of previous.clusters) {
if (isOccluded(cluster.position)) continue;
const coord = project(cluster.position);
if (!coord) continue;
cluster.width *= factor;
cluster.height *= factor;
const width = Math.max(cluster.width, cluster.minimumWidth);
const height = Math.max(cluster.height, cluster.minimumHeight);
const neighbors = index.range(
coord.x - width * 0.5,
coord.y - height * 0.5,
coord.x + width,
coord.y + height,
);
const ids = [];
for (const j of neighbors) if (!clustered[j]) ids.push(points[j].id);
if (ids.length >= minimumClusterSize) {
clusters.push({ position: { ...cluster.position }, ids });
kept.push(cluster);
for (const j of neighbors) clustered[j] = 1;
}
}
}
const single = [];
for (let i = 0; i < n; i++) {
if (clustered[i]) continue;
clustered[i] = 1;
const seed = points[i];
const box = pointBox(xs[i], ys[i], seed.pixelSize, pixelRange);
let minX = box.x;
let minY = box.y;
let maxX = box.x + box.width;
let maxY = box.y + box.height;
const neighbors = index.range(
box.x,
box.y,
box.x + box.width,
box.y + box.height,
);
const sum = { x: seed.position.x, y: seed.position.y, z: seed.position.z };
const ids = [seed.id];
for (const j of neighbors) {
if (clustered[j]) continue;
const other = points[j];
const near = pointBox(xs[j], ys[j], other.pixelSize, pixelRange);
sum.x += other.position.x;
sum.y += other.position.y;
sum.z += other.position.z;
minX = Math.min(minX, near.x);
minY = Math.min(minY, near.y);
maxX = Math.max(maxX, near.x + near.width);
maxY = Math.max(maxY, near.y + near.height);
ids.push(other.id);
}
if (ids.length >= minimumClusterSize) {
const position = {
x: sum.x / ids.length,
y: sum.y / ids.length,
z: sum.z / ids.length,
};
clusters.push({ position, ids });
kept.push({
position,
width: maxX - minX,
height: maxY - minY,
minimumWidth: box.width,
minimumHeight: box.height,
});
for (const j of neighbors) clustered[j] = 1;
} else single.push(seed.id);
}
return { clusters, single, state: { clusters: kept, height: eyeHeight } };
}
/** A point's box: its drawn square grown by `pixelRange` on every side. */
function pointBox(x, y, size, pixelRange) {
return {
x: x - size * 0.5 - pixelRange,
y: y - size * 0.5 - pixelRange,
width: size + pixelRange * 2,
height: size + pixelRange * 2,
};
}
/**
* A uniform grid over packed coordinates, answering which points lie in a
* box (bounds included), in ascending index order.
*/
function createGridIndex(xs, ys, cell) {
const buckets = new Map();
const key = (cx, cy) => `${cx}:${cy}`;
for (let i = 0; i < xs.length; i++) {
const k = key(Math.floor(xs[i] / cell), Math.floor(ys[i] / cell));
let bucket = buckets.get(k);
if (!bucket) buckets.set(k, (bucket = []));
bucket.push(i);
}
return {
range(minX, minY, maxX, maxY) {
const found = [];
if (!(maxX >= minX && maxY >= minY)) return found;
const x0 = Math.floor(minX / cell);
const x1 = Math.floor(maxX / cell);
const y0 = Math.floor(minY / cell);
const y1 = Math.floor(maxY / cell);
if ((x1 - x0 + 1) * (y1 - y0 + 1) > buckets.size) {
for (let i = 0; i < xs.length; i++)
if (xs[i] >= minX && xs[i] <= maxX && ys[i] >= minY && ys[i] <= maxY)
found.push(i);
return found;
}
for (let cx = x0; cx <= x1; cx++)
for (let cy = y0; cy <= y1; cy++)
for (const i of buckets.get(key(cx, cy)) ?? [])
if (
xs[i] >= minX &&
xs[i] <= maxX &&
ys[i] >= minY &&
ys[i] <= maxY
)
found.push(i);
return found.sort((a, b) => a - b);
},
};
}
+136
View File
@@ -0,0 +1,136 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { clusterScreenPoints } from './screenCluster.js';
/** A point at screen `x, y` whose world position is `x, y, 0` too. */
const at = (id, x, y, pixelSize = 13) => ({
id,
position: { x, y, z: 0 },
screen: { x, y },
pixelSize,
});
const run = (points, extra = {}) =>
clusterScreenPoints({
points,
pixelRange: 42,
minimumClusterSize: 3,
viewHeight: 1000,
eyeHeight: 1_000_000,
project: (p) => ({ x: p.x, y: p.y }),
isOccluded: () => false,
...extra,
});
test('points inside a seed’s grown box cluster at their mean, the seed first', () => {
const result = run([
at('a', 100, 100),
at('b', 140, 100),
at('c', 100, 140),
at('far', 600, 600),
]);
assert.equal(result.clusters.length, 1);
assert.deepEqual(result.clusters[0].ids, ['a', 'b', 'c']);
assert.deepEqual(result.clusters[0].position, {
x: 340 / 3,
y: 340 / 3,
z: 0,
});
assert.deepEqual(result.single, ['far']);
});
test('fewer than the minimum stay on their own, and a box reaches half the size plus the range', () => {
// 6.5 + 42 = 48.5 px each way from the seed.
const edge = run([
at('a', 100, 100),
at('b', 148.5, 100),
at('c', 100, 51.5),
]);
assert.deepEqual(edge.clusters[0].ids, ['a', 'b', 'c']);
const out = run([at('a', 100, 100), at('b', 148.6, 100), at('c', 100, 51.5)]);
assert.deepEqual(out.clusters, []);
assert.deepEqual(out.single, ['a', 'b', 'c']);
});
test('a point already clustered is not taken again by a later seed', () => {
const result = run([
at('a', 100, 100),
at('b', 120, 100),
at('c', 140, 100),
at('d', 160, 100),
at('e', 180, 100),
]);
assert.deepEqual(
result.clusters.map((c) => c.ids),
[['a', 'b', 'c']],
);
assert.deepEqual(result.single, ['d', 'e']);
});
test('zooming in keeps last pass’s clusters still in view before seeding anew', () => {
const points = [at('a', 100, 100), at('b', 140, 100), at('c', 100, 140)];
const first = run(points);
const [kept] = first.state.clusters;
assert.equal(kept.minimumWidth, 97);
// Closer, with the points spread past a fresh seed's box but inside the
// kept cluster's (its box is measured from the top, the points' from the
// bottom, as the default renderer measures them).
const spread = [at('a', 70, 930), at('b', 200, 800), at('c', 70, 800)];
const again = run(spread, {
eyeHeight: 900_000,
previous: first.state,
project: () => ({ x: 113, y: 113 }),
});
assert.equal(again.clusters.length, 1);
assert.deepEqual(again.clusters[0].position, first.clusters[0].position);
assert.deepEqual([...again.clusters[0].ids].sort(), ['a', 'b', 'c']);
// From higher up, the last pass is not consulted.
const higher = run(spread, {
eyeHeight: 1_100_000,
previous: first.state,
project: () => ({ x: 113, y: 113 }),
});
assert.deepEqual(higher.clusters, []);
// Nor a cluster now behind the horizon.
const hidden = run(spread, {
eyeHeight: 900_000,
previous: run(points).state,
project: () => ({ x: 113, y: 113 }),
isOccluded: () => true,
});
assert.deepEqual(hidden.clusters, []);
});
test('many points cluster as a scan of every point would', () => {
let seed = 7;
const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const points = Array.from({ length: 600 }, (_, i) =>
at(`p${i}`, random() * 1600, random() * 1000),
);
const result = run(points);
const all = [...result.single, ...result.clusters.flatMap((c) => c.ids)];
assert.equal(all.length, 600);
assert.equal(new Set(all).size, 600, 'each point once');
// Brute force, as the renderer does it.
const done = new Set();
const expected = [];
const inBox = (s, o) =>
Math.abs(o.screen.x - s.screen.x) <= 48.5 &&
Math.abs(o.screen.y - s.screen.y) <= 48.5;
for (const s of points) {
if (done.has(s.id)) continue;
done.add(s.id);
const ids = [s.id];
for (const o of points) if (!done.has(o.id) && inBox(s, o)) ids.push(o.id);
if (ids.length >= 3) {
expected.push(ids);
ids.forEach((id) => done.add(id));
}
}
assert.deepEqual(
result.clusters.map((c) => c.ids),
expected,
);
});
+44 -19
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { createLifecycle } from './lifecycle.js';
import { createRendering } from './rendering.js';
import { createState } from './state.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const overlays = () => ({
clearOverlaySource() {},
@@ -10,7 +11,7 @@ const overlays = () => ({
setOverlayEntries() {},
});
/** A viewer whose data sources and entities record what was done to them. */
/** A viewer whose data sources and entities would record what was done to them. */
function recordingViewer() {
const calls = [];
return {
@@ -24,7 +25,7 @@ function recordingViewer() {
};
}
test('the stations data source is added once, clustered, and removed with its listener', () => {
test('the stations draw sets are made once, cluster on camera moves, and go with their listener', () => {
const services = {
ground: { cachedGroundFloor: () => null },
overlays: overlays(),
@@ -33,28 +34,52 @@ test('the stations data source is added once, clustered, and removed with its li
const state = createState({ services });
const rendering = createRendering({ state, services, parts: {} });
const viewer = recordingViewer();
state._viewer = viewer;
const changed = new Set();
const camera = {
pose: () => null,
on(event, cb) {
assert.equal(event, 'changed');
changed.add(cb);
return () => changed.delete(cb);
},
};
const { draw, unbind } = bindFakeDraw(viewer, { camera });
try {
state._viewer = viewer;
rendering.installDataSource(viewer);
const source = state._dataSource;
assert.ok(source, 'a data source is made');
assert.equal(source.name, 'Radio stations');
assert.equal(source.clustering.enabled, true);
assert.equal(typeof state._removeClusterListener, 'function');
rendering.installDataSource(viewer);
assert.deepEqual(viewer.calls, [['add', source]], 'added once');
rendering.installDataSource(viewer);
const ids = () =>
[...draw.sets.values()]
.filter((set) => !set.disposed)
.map((set) => `${set.kind}:${set.spec.id.replace(/^radio:\d+:/, '')}`);
assert.deepEqual(ids(), [
'points:stations',
'points:clusters',
'points:selected',
'icons:selected-bracket',
]);
assert.equal(changed.size, 1, 'clusters again as the camera moves');
rendering.installDataSource(viewer);
assert.equal(ids().length, 4, 'made once');
rendering.setStationsShown(false);
assert.equal(source.show, false);
rendering.setStationsShown(false);
assert.equal(draw.find('radio:').show, false);
assert.equal(
[...draw.sets.values()].find((set) => set.spec.id.endsWith(':clusters'))
.show,
false,
);
rendering.removeDataSource();
assert.deepEqual(viewer.calls.at(-1), ['remove', source, true]);
assert.equal(state._dataSource, null);
assert.equal(state._removeClusterListener, null);
assert.equal(source.clustering.clusterEvent.numberOfListeners, 0);
rendering.removeDataSource();
assert.deepEqual(ids(), [], 'every set goes');
assert.equal(changed.size, 0, 'and its camera listener');
assert.deepEqual(viewer.calls, [], 'no Cesium data source or entity');
} finally {
unbind();
}
});
test('the lifecycle leaves the Cesium data source and entities to the rendering part', () => {
test("the lifecycle leaves the stations' draw sets to the rendering part", () => {
const services = { overlays: overlays() };
const state = createState({ services });
const done = [];
+317 -177
View File
@@ -1,9 +1,14 @@
import * as Cesium from 'cesium';
// The Cesium camera factory: given a viewer of a caller's own, with no
// renderer bound, the layer's flights and camera reads find a camera port.
import '../../render/cesium/camera.js';
import { clusterPointCollection as clusterPointsOf } from '../../render/cesium/internals.js';
import { horizonOccluder } from '../../render/cesium/iconOrientation.js';
import { cssColor } from '../../render/color.js';
import {
canvasOf,
drawOf,
findCamera,
findQuery,
} from '../../render/rendererOf.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distance } from '../../geo/vector.js';
import { clusterScreenPoints } from '../../geo/screenCluster.js';
import {
MARKER_LIFT_M,
RADIO_PREFIX,
@@ -15,8 +20,42 @@ import {
DEFAULT_RADIO_FILTER,
} from './policy.js';
/** Draw sets made so far, by every Radio layer: set ids unique to each. */
let instances = 0;
/** Where a station's dot shows: from the ground out to the globe view. */
const DISPLAY_RANGE = Object.freeze([
0,
RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M,
]);
const STATION_SCALE_BY_DISTANCE = Object.freeze({
near: 100_000,
nearValue: 1.15,
far: 12_000_000,
farValue: 1,
});
const BRACKET_SCALE_BY_DISTANCE = Object.freeze({
near: 100_000,
nearValue: 1,
far: 12_000_000,
farValue: 0.72,
});
const STATION_PIXEL_SIZE = 13;
const STATION_OUTLINE = cssColor('#071b25');
const BLACK = Object.freeze([0, 0, 0, 1]);
/** Stations' screen clustering, as the stations' data source clustered them. */
const CLUSTER_PIXEL_RANGE = 42;
const CLUSTER_MINIMUM_SIZE = 3;
/** A CSS colour with another alpha. */
function withAlpha(css, alpha) {
const [r, g, b] = cssColor(css) ?? [1, 1, 1];
return [r, g, b, alpha];
}
/**
* A station id from ordinary, selected, or Cesium cluster pick shapes.
* A station id from ordinary, selected, or cluster pick shapes: a pick id,
* a renderer pick's `{set, id}`, or a list of them.
* @param {object|null|undefined} picked A scene pick result.
* @returns {string|null}
*/
@@ -54,23 +93,92 @@ export function createRendering({
services.overlays;
const { governorRequestRender } = services.render;
/**
* The layer's draw sets (made with `installDataSource`): the station
* dots, the cluster dots that stand in for stations drawn too close
* together, and the selected station's dot and bracket.
*/
let sets = null;
/** The camera subscription that clusters the stations again as it moves. */
let offCameraChanged = null;
/** What the last clustering pass leaves for the next. */
let clusterState = null;
/**
* The clusters drawn now, each `{position, stationIds}` with its seed
* station first, and the stations they hold.
*/
let clusters = [];
let clusteredIds = new Set();
/**
* The stations the last clustering pass left on their own, or null before
* one: a station it passed over (past the horizon or behind the eye) is
* hidden until the next, as the default renderer's clustering hid it.
*/
let singleIds = null;
/** Each station dot's drawn show, by station id. */
const drawnShow = new Map();
/** The selected station's items while it has them, and whether shown. */
let selection = null;
function markerPosition(station, liftM = MARKER_LIFT_M) {
const floor = cachedGroundFloor(station.lat, station.lon);
return Cesium.Cartesian3.fromDegrees(
return fromDegrees(
station.lon,
station.lat,
(Number.isFinite(floor) ? floor : 0) + liftM,
);
}
/** The eye's pose, or null without a camera. */
const pose = () => findCamera(layerState._viewer)?.pose() ?? null;
/** A station's dot item, shown or not. */
function stationItem(record, show) {
const markerColor = parts.model.radioCategoryColor(
parts.model.radioStationCategoryId(record.station),
);
return {
id: `${RADIO_PREFIX}${record.station.id}`,
pos: record.position,
pixelSize: STATION_PIXEL_SIZE,
color: withAlpha(markerColor, 0.86),
outlineColor: STATION_OUTLINE,
outlineWidth: 1,
disableDepthTest: Infinity,
scaleByDistance: STATION_SCALE_BY_DISTANCE,
displayRange: DISPLAY_RANGE,
show,
};
}
/**
* Draw each station dot that is visible and not standing in a cluster,
* writing only the dots whose show changed.
*/
function syncStationShows() {
if (!sets) return false;
const changed = [];
for (const record of layerState._renderById.values()) {
const show =
record.visible &&
(singleIds
? singleIds.has(record.station.id)
: !clusteredIds.has(record.station.id));
if (drawnShow.get(record.station.id) === show) continue;
drawnShow.set(record.station.id, show);
changed.push(stationItem(record, show));
}
if (changed.length) sets.stations.upsert(changed);
return changed.length > 0;
}
function updateSelectionEntity() {
if (layerState._selectedEntity && layerState._viewer)
layerState._viewer.entities.remove(layerState._selectedEntity);
layerState._selectedEntity = null;
removeSelectionEntity();
const station = parts.queries.selectedPresentationStation();
if (
!parts.interaction.radioPresentationAllowed() ||
!layerState._viewer ||
!sets ||
!station
) {
scheduleRadioOverlayPublish();
@@ -79,41 +187,122 @@ export function createRendering({
const selectionColor = parts.model.radioCategoryColor(
parts.model.radioStationCategoryId(station),
);
const bracketImage = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(parts.labels.radioSelectionBracketSvg(selectionColor))}`;
layerState._selectedEntity = layerState._viewer.entities.add({
id: `${RADIO_PREFIX}selected:${station.id}`,
position: markerPosition(station, SELECTED_LIFT_M),
point: {
const id = `${RADIO_PREFIX}selected:${station.id}`;
const position = markerPosition(station, SELECTED_LIFT_M);
selection = {
position,
shown: true,
dot: {
id,
pos: position,
pixelSize: 14,
color: Cesium.Color.fromCssColorString(selectionColor),
outlineColor: Cesium.Color.BLACK,
color: cssColor(selectionColor),
outlineColor: BLACK,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
0,
RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M,
),
disableDepthTest: Infinity,
displayRange: DISPLAY_RANGE,
},
billboard: {
image: bracketImage,
width: 40,
height: 40,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
0,
RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M,
),
scaleByDistance: new Cesium.NearFarScalar(100_000, 1, 12_000_000, 0.72),
bracket: {
id,
pos: position,
image: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(parts.labels.radioSelectionBracketSvg(selectionColor))}`,
size: [40, 40],
disableDepthTest: Infinity,
displayRange: DISPLAY_RANGE,
scaleByDistance: BRACKET_SCALE_BY_DISTANCE,
},
});
};
sets.selectedDot.set([selection.dot]);
sets.selectedBracket.set([selection.bracket]);
scheduleRadioOverlayPublish();
}
function clusterPointCollection() {
return clusterPointsOf(layerState._dataSource?.clustering);
/** Show or hide the selected station's dot and bracket. */
function showSelection(shown) {
if (!selection || selection.shown === shown) return false;
selection.shown = shown;
sets.selectedDot.upsert([{ ...selection.dot, show: shown }]);
sets.selectedBracket.upsert([{ ...selection.bracket, show: shown }]);
return true;
}
/**
* Cluster the visible stations on screen, as the stations' data source
* clustered them (`geo/screenCluster.js`), draw each cluster as a dot
* sized by its count and coloured by its stations' category, and hide the
* stations it holds.
*/
function clusterStations() {
if (!sets) return;
const query = findQuery(layerState._viewer);
const eye = pose();
const points = [];
if (query && eye) {
const horizon = horizonFrom(eye.position);
for (const record of layerState._renderById.values()) {
if (!record.visible || !horizon.isPointVisible(record.position))
continue;
const screen = query.project(record.position);
if (!screen) continue;
points.push({
id: record.station.id,
position: record.position,
screen,
pixelSize: STATION_PIXEL_SIZE,
});
}
}
const viewHeight = canvasOf(layerState._viewer)?.clientHeight ?? 0;
const result = clusterScreenPoints({
points,
pixelRange: CLUSTER_PIXEL_RANGE,
minimumClusterSize: CLUSTER_MINIMUM_SIZE,
viewHeight,
eyeHeight: eye?.height ?? Number.POSITIVE_INFINITY,
previous: clusterState,
project: (position) => query.project(position),
isOccluded: (position) =>
!horizonFrom(eye.position).isPointVisible(position),
});
clusterState = result.state;
clusters = result.clusters.map(({ position, ids }) => ({
position,
stationIds: ids,
}));
clusteredIds = new Set(clusters.flatMap((cluster) => cluster.stationIds));
singleIds = query && eye ? new Set(result.single) : null;
sets.clusters.set(clusters.map(clusterItem));
syncStationShows();
scheduleRadioOverlayPublish();
}
/** A cluster's dot: its seed station's id, so a click plays that one. */
function clusterItem(cluster) {
const clusteredStations = [];
for (const stationId of cluster.stationIds) {
const station = layerState._renderById.get(stationId)?.station;
if (station) clusteredStations.push(station);
}
const clusterCategory = parts.model.radioClusterCategoryId(
clusteredStations,
layerState._filter,
);
return {
id: `${RADIO_PREFIX}${cluster.stationIds[0]}`,
pos: cluster.position,
pixelSize: Math.min(26, 12 + Math.log2(cluster.stationIds.length) * 1.6),
color: withAlpha(parts.model.radioCategoryColor(clusterCategory), 0.9),
outlineColor: BLACK,
outlineWidth: 2,
disableDepthTest: Infinity,
displayRange: DISPLAY_RANGE,
meta: { stationIds: cluster.stationIds },
};
}
/** The clusters drawn now: `{position, stationIds}`, seed first. */
function stationClusters() {
return clusters;
}
function publishRadioOverlayEntries() {
@@ -139,18 +328,9 @@ export function createRendering({
const clusterCandidates = [];
const clusteredStationIds = new Set();
const points = clusterPointCollection();
for (let index = 0; index < (points?.length || 0); index += 1) {
const point = points.get(index);
if (
!point?.show ||
!point.position ||
!Array.isArray(point.id) ||
point.id.length < 3
)
continue;
const stationIds = point.id
.map((entity) => String(entity?.id || '').slice(RADIO_PREFIX.length))
for (const cluster of clusters) {
if (cluster.stationIds.length < 3) continue;
const stationIds = cluster.stationIds
.filter((id) => {
const station = layerState._stationById.get(id);
return (
@@ -174,7 +354,7 @@ export function createRendering({
clusterCandidates.push({
id: `${stationIds[0]}:${stationIds.at(-1)}:${stationIds.length}`,
stationIds,
point,
point: cluster,
text: parts.model.radioClusterBadgeText(category, stationIds.length),
accent: parts.model.radioCategoryColor(category),
stationCount: stationIds.length,
@@ -196,11 +376,10 @@ export function createRendering({
if (clusterEntry) entries.push(clusterEntry);
}
const cameraPosition = layerState._viewer?.camera?.positionWC;
const eye = pose();
const cameraPosition = eye?.position ?? null;
const singletonAllowance = Math.min(
parts.clustering.radioSingletonLabelLimit(
layerState._viewer?.camera?.positionCartographic?.height,
),
parts.clustering.radioSingletonLabelLimit(eye?.height),
Math.max(
0,
RADIO_OVERLAY_COHORT_LIMIT - selectedClusterCandidates.length,
@@ -210,14 +389,14 @@ export function createRendering({
[...layerState._renderById.values()]
.filter(
(record) =>
record.entity?.show &&
record.visible &&
record.station?.id !== station?.id &&
!clusteredStationIds.has(record.station?.id),
)
.map((record) => ({
...record,
distanceM: cameraPosition
? Cesium.Cartesian3.distance(cameraPosition, record.position)
? distance(cameraPosition, record.position)
: Number.POSITIVE_INFINITY,
})),
singletonAllowance,
@@ -275,8 +454,9 @@ export function createRendering({
}
function updateRenderVisibility({ force = true } = {}) {
if (!layerState._viewer || !layerState._dataSource) return;
const cameraPosition = layerState._viewer.camera?.positionWC;
if (!layerState._viewer || !sets) return;
const eye = pose();
const cameraPosition = eye?.position ?? null;
if (
!force &&
!parts.navigation.radioCameraPositionChanged(
@@ -289,26 +469,31 @@ export function createRendering({
? { x: cameraPosition.x, y: cameraPosition.y, z: cameraPosition.z }
: null;
layerState._horizonScanCount += 1;
const occluder = horizonOccluder(layerState._viewer.camera);
let visibilityChanged = false;
// With no eye, as with no camera before, nothing is hidden by a horizon.
const visibleFrom = cameraPosition
? horizonFrom(cameraPosition)
: { isPointVisible: () => true };
let shownChanged = false;
for (const record of layerState._renderById.values()) {
const matches = parts.categories.stationMatchesRadioCategory(
record.station,
layerState._filter,
);
const visible = matches && occluder.isPointVisible(record.position);
if (record.entity.show !== visible) visibilityChanged = true;
record.entity.show = visible;
}
if (layerState._selectedEntity) {
const position = layerState._selectedEntity.position?.getValue?.(
Cesium.JulianDate.now(),
);
const selectedVisible = !position || occluder.isPointVisible(position);
if (layerState._selectedEntity.show !== selectedVisible)
visibilityChanged = true;
layerState._selectedEntity.show = selectedVisible;
const visible = matches && visibleFrom.isPointVisible(record.position);
if (visible !== record.visible) shownChanged = true;
record.visible = visible;
}
// A station shown or hidden clusters the stations again, as the default
// renderer's clustering did whenever one of its entities came or went.
let visibilityChanged = false;
if (shownChanged && sets.stations.show) {
clusterStations();
visibilityChanged = true;
} else visibilityChanged = syncStationShows();
if (selection)
visibilityChanged =
showSelection(visibleFrom.isPointVisible(selection.position)) ||
visibilityChanged;
scheduleRadioOverlayPublish();
// The horizon timer can commit AFTER the camera settles and the governor
// parks the scene — a changed show flag needs one frame. (perf wave 2 fix)
@@ -344,132 +529,88 @@ export function createRendering({
layerState._selectedId = null;
}
if (layerState._dataSource) layerState._dataSource.entities.removeAll();
layerState._renderById.clear();
drawnShow.clear();
clusteredIds = new Set();
singleIds = null;
const items = [];
for (const station of stations) {
const position = markerPosition(station);
const markerColor = parts.model.radioCategoryColor(
parts.model.radioStationCategoryId(station),
);
const entity = layerState._dataSource.entities.add({
id: `${RADIO_PREFIX}${station.id}`,
position,
point: {
pixelSize: 13,
color: Cesium.Color.fromCssColorString(markerColor).withAlpha(0.86),
outlineColor: Cesium.Color.fromCssColorString('#071b25'),
outlineWidth: 1,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(
100_000,
1.15,
12_000_000,
1,
),
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
0,
RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M,
),
},
});
layerState._renderById.set(station.id, { station, entity, position });
const record = { station, position: markerPosition(station) };
// Shown until the horizon pass below says otherwise.
record.visible = true;
layerState._renderById.set(station.id, record);
drawnShow.set(station.id, true);
items.push(stationItem(record, true));
}
sets?.stations.set(items);
updateSelectionEntity();
updateRenderVisibility();
clusterStations();
}
function installClusterStyling() {
if (!layerState._dataSource || layerState._removeClusterListener) return;
const clustering = layerState._dataSource.clustering;
clustering.enabled = true;
clustering.pixelRange = 42;
clustering.minimumClusterSize = 3;
clustering.clusterPoints = true;
clustering.clusterLabels = false;
clustering.clusterBillboards = false;
layerState._removeClusterListener =
clustering.clusterEvent.addEventListener((clusteredEntities, cluster) => {
const clusteredStations = [];
for (const entity of clusteredEntities) {
const stationId = String(entity.id || '').slice(RADIO_PREFIX.length);
const station = layerState._renderById.get(stationId)?.station;
if (station) clusteredStations.push(station);
}
const clusterCategory = parts.model.radioClusterCategoryId(
clusteredStations,
layerState._filter,
);
const clusterColor = Cesium.Color.fromCssColorString(
parts.model.radioCategoryColor(clusterCategory),
);
// Cesium assigns the entity-id array only to the generated cluster label.
// Mirror it to the visible point so clicking either part of the callout
// resolves the first station and remains a direct playback gesture.
cluster.point.id = clusteredEntities;
cluster.billboard.id = clusteredEntities;
cluster.label.show = false;
cluster.label.text = '';
cluster.point.show = true;
cluster.point.pixelSize = Math.min(
26,
12 + Math.log2(clusteredEntities.length) * 1.6,
);
cluster.point.color = clusterColor.withAlpha(0.9);
cluster.point.outlineColor = Cesium.Color.BLACK;
cluster.point.outlineWidth = 2;
cluster.point.disableDepthTestDistance = Number.POSITIVE_INFINITY;
cluster.point.distanceDisplayCondition =
new Cesium.DistanceDisplayCondition(
0,
RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M,
);
scheduleRadioOverlayPublish();
});
}
/**
* Add the stations' data source to the viewer, once, with its clustering.
* Make the stations' draw sets on the viewer's renderer (`drawOf`), once,
* and cluster the stations again whenever the camera moves enough.
* @param {object} viewer
*/
function installDataSource(viewer) {
if (layerState._dataSource) return;
layerState._dataSource = new Cesium.CustomDataSource('Radio stations');
viewer.dataSources.add(layerState._dataSource);
installClusterStyling();
if (sets) return;
const draw = drawOf(viewer);
const prefix = `radio:${++instances}`;
sets = {
stations: draw.points({ id: `${prefix}:stations` }),
clusters: draw.points({ id: `${prefix}:clusters` }),
selectedDot: draw.points({ id: `${prefix}:selected` }),
selectedBracket: draw.icons({ id: `${prefix}:selected-bracket` }),
};
offCameraChanged =
findCamera(viewer)?.on('changed', () => {
if (sets?.stations.show) clusterStations();
}) ?? null;
}
/** Stop styling clusters and take the data source off the viewer. */
/** Stop clustering and let the stations' draw sets go. */
function removeDataSource() {
layerState._removeClusterListener?.();
layerState._removeClusterListener = null;
if (layerState._dataSource && layerState._viewer)
layerState._viewer.dataSources.remove(layerState._dataSource, true);
layerState._dataSource = null;
offCameraChanged?.();
offCameraChanged = null;
if (sets) for (const set of Object.values(sets)) set.dispose();
sets = null;
selection = null;
clusterState = null;
clusters = [];
clusteredIds = new Set();
singleIds = null;
drawnShow.clear();
}
/** Show or hide the stations' entities. */
/** Show or hide the stations and their clusters. */
function setStationsShown(shown) {
if (layerState._dataSource) layerState._dataSource.show = shown;
if (!sets) return;
const was = sets.stations.show;
sets.stations.show = shown;
sets.clusters.show = shown;
// Hidden, the stations leave nothing for a later pass to keep, as the
// default renderer's clustering kept nothing of a hidden source.
if (!shown) clusterState = null;
if (shown && !was) clusterStations();
}
/** Remove the selected station's entity, if there is one. */
/** Take the selected station's dot and bracket down, if it has them. */
function removeSelectionEntity() {
if (layerState._selectedEntity && layerState._viewer)
layerState._viewer.entities.remove(layerState._selectedEntity);
layerState._selectedEntity = null;
if (!selection) return;
selection = null;
sets?.selectedDot.clear();
sets?.selectedBracket.clear();
}
/**
* Entity visibility changes do not invalidate Cesium's existing cluster
* primitives. Toggle a public clustering input twice to mark the current
* cluster set dirty without changing its effective configuration.
* Cluster the stations again now: a filter change hides or shows
* stations, which the camera's next move would otherwise wait for.
*/
function reclusterStations() {
if (!layerState._dataSource?.clustering?.enabled) return;
const clustering = layerState._dataSource.clustering;
const clusterPoints = clustering.clusterPoints;
clustering.clusterPoints = !clusterPoints;
clustering.clusterPoints = clusterPoints;
layerState._viewer?.scene?.requestRender();
if (!sets) return;
clusterStations();
governorRequestRender('radio-recluster');
}
return {
@@ -481,11 +622,10 @@ export function createRendering({
reclusterStations,
markerPosition,
updateSelectionEntity,
clusterPointCollection,
stationClusters,
publishRadioOverlayEntries,
scheduleRadioOverlayPublish,
updateRenderVisibility,
reconcileStations,
installClusterStyling,
};
}
+141
View File
@@ -0,0 +1,141 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { fromDegrees, toLonLatH, WGS84 } from '../../geo/ellipsoid.js';
import { radioStationIdFromPick } from './rendering.js';
import {
radioStationRow,
withRadioLayer,
} from '../../testSupport/radioLayerHarness.mjs';
import { radioLayer } from '../../data/radio.js';
const station = (n, lon, lat, tags = ['news']) =>
radioStationRow({
id: `00000000-0000-4000-8000-0000000000${String(n).padStart(2, '0')}`,
name: `Station ${n}`,
lon,
lat,
tags,
streamUrl: `https://radio.example.com/${n}.mp3`,
});
/**
* Camera and query ports over a flat projection, `pxPerDegree` CSS pixels a
* degree from (-98, 31) at the top left, with an eye over Austin.
*/
function flatRenderer() {
const listeners = new Set();
const view = { pxPerDegree: 1000, height: 1_000_000 };
const eye = () => fromDegrees(-97, 30, view.height);
return {
view,
listeners,
renderer: {
canvas: { clientWidth: 2000, clientHeight: 1000 },
camera: {
pose: () => ({ position: eye(), height: view.height }),
on(event, cb) {
if (event !== 'changed') return () => {};
listeners.add(cb);
return () => listeners.delete(cb);
},
},
query: {
project(p) {
const { lon, lat } = toLonLatH(p, WGS84);
return {
x: (lon + 98) * view.pxPerDegree,
y: (31 - lat) * view.pxPerDegree,
};
},
},
},
};
}
test('stations drawn close together on screen stand behind one cluster dot', async () => {
const flat = flatRenderer();
const stations = [
station(1, -97.0, 30.0),
station(2, -96.98, 30.0),
station(3, -97.0, 29.98),
station(4, -96.5, 30.0),
];
await withRadioLayer(
{ stations, renderer: flat.renderer },
async ({ draw }) => {
const set = (suffix) =>
[...draw.sets.values()].find(
(record) => !record.disposed && record.spec.id.endsWith(suffix),
);
const shown = () =>
[...set(':stations').items.values()]
.filter((item) => item.show)
.map((item) => item.id);
const clusters = set(':clusters');
assert.equal(clusters.items.size, 1, 'one cluster');
const [cluster] = clusters.items.values();
assert.equal(cluster.id, `radio:${stations[0].id}`, 'named by its seed');
assert.deepEqual(
cluster.meta.stationIds,
stations.slice(0, 3).map((s) => s.id),
);
// At the mean of its stations, sized by its count, news blue.
const { lon, lat } = toLonLatH(cluster.pos, WGS84);
assert.ok(
Math.abs(lon + 96.9933) < 1e-3 && Math.abs(lat - 29.9933) < 1e-3,
);
assert.equal(cluster.pixelSize, 12 + Math.log2(3) * 1.6);
assert.equal(cluster.outlineWidth, 2);
assert.deepEqual(
shown(),
[`radio:${stations[3].id}`],
'only the lone one',
);
// A click on the cluster plays its seed station.
assert.equal(
radioStationIdFromPick({
id: { set: clusters.spec.id, id: cluster.id },
}),
stations[0].id,
);
// Its badge is published with it.
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(radioLayer.getOverlayDiagnostics().clusterTexts.length, 1);
// Closer in, the stations spread apart: the camera's move clusters
// them again, and every station shows on its own.
flat.view.pxPerDegree = 20_000;
flat.view.height = 200_000;
for (const cb of flat.listeners) cb();
assert.equal(clusters.items.size, 0);
assert.equal(shown().length, 4);
},
);
});
test('a filter that hides stations clusters them again at once', async () => {
const flat = flatRenderer();
const stations = [
station(1, -97.0, 30.0, ['news']),
station(2, -96.98, 30.0, ['news']),
station(3, -97.0, 29.98, ['jazz']),
];
await withRadioLayer(
{ stations, renderer: flat.renderer },
async ({ draw }) => {
const set = (suffix) =>
[...draw.sets.values()].find(
(record) => !record.disposed && record.spec.id.endsWith(suffix),
);
radioLayer.setFilter('all');
assert.equal(set(':clusters').items.size, 1);
radioLayer.setFilter('news');
assert.equal(set(':clusters').items.size, 0, 'two left: no cluster');
const shown = [...set(':stations').items.values()].filter((i) => i.show);
assert.deepEqual(
shown.map((item) => item.id),
stations.slice(0, 2).map((s) => `radio:${s.id}`),
);
},
);
});
-6
View File
@@ -14,8 +14,6 @@ export function createState({ services }) {
layerState._viewer = null;
layerState._dataSource = null;
layerState._enabled = false;
layerState._managerLifecyclePresentation = null;
@@ -46,8 +44,6 @@ export function createState({ services }) {
layerState._selectedId = null;
layerState._selectedEntity = null;
layerState._selectionGeneration = 0;
layerState._selectionTimer = null;
@@ -136,8 +132,6 @@ export function createState({ services }) {
layerState._sessionGeneration = 0;
layerState._removeClusterListener = null;
layerState._overlayPublishTimer = null;
layerState._clusterOverlayIdentitySequence = 0;
+93
View File
@@ -3009,6 +3009,99 @@ test('the FIRMS layer draws its fire glows as one GPU icon set on a viewer of it
assert.equal(scene.added.length, 0);
});
test('the Radio layer draws its stations, clusters and selected marker as point and billboard sets', async () => {
const { withRadioLayer, radioStationRow } =
await import('../../testSupport/radioLayerHarness.mjs');
const { radioLayer, radioStationIdFromPick } =
await import('../../data/radio.js');
const { fromDegrees, toLonLatH, WGS84 } =
await import('../../geo/ellipsoid.js');
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
// A flat projection, 1000 CSS px a degree from (-98, 31) at the top left.
const renderer = {
draw: part.port,
canvas: { clientWidth: 2000, clientHeight: 1000 },
camera: {
pose: () => ({ position: fromDegrees(-97, 30, 1e6), height: 1e6 }),
on: () => () => {},
},
query: {
project(p) {
const { lon, lat } = toLonLatH(p, WGS84);
return { x: (lon + 98) * 1000, y: (31 - lat) * 1000 };
},
},
};
const station = (n, lon, lat) =>
radioStationRow({
id: `00000000-0000-4000-8000-0000000000${String(n).padStart(2, '0')}`,
name: `Station ${n}`,
lon,
lat,
tags: ['news'],
streamUrl: `https://radio.example.com/${n}.mp3`,
});
const stations = [
station(1, -97.0, 30.0),
station(2, -96.98, 30.0),
station(3, -97.0, 29.98),
station(4, -96.5, 30.0),
];
await withRadioLayer({ stations, renderer }, async () => {
const rows = (pattern) => {
const out = [];
for (const host of scene.added) {
const collections =
host instanceof Cesium.PrimitiveCollection
? [host.get(0), host.get(1)]
: [host];
for (const collection of collections)
for (let i = 0; i < (collection?.length ?? 0); i += 1) {
const primitive = collection.get(i);
if (pattern.test(primitive.id?.set)) out.push(primitive);
}
}
return out;
};
const dots = rows(/^radio:\d+:stations$/);
assert.equal(dots.length, 4);
assert.ok(dots.every((dot) => dot instanceof Cesium.PointPrimitive));
const lone = dots.find((dot) => dot.show);
assert.equal(lone.id.id, `radio:${stations[3].id}`, 'the others are in a cluster');
assert.equal(lone.pixelSize, 13);
assert.equal(lone.outlineWidth, 1);
assert.ok(Math.abs(lone.color.alpha - 0.86) < 1e-6);
assert.equal(lone.disableDepthTestDistance, Number.POSITIVE_INFINITY);
assert.equal(lone.distanceDisplayCondition.far, 50_000_000);
assert.equal(lone.scaleByDistance.nearValue, 1.15);
assert.equal(radioStationIdFromPick({ primitive: lone, id: lone.id }), stations[3].id);
const [cluster] = rows(/^radio:\d+:clusters$/);
assert.deepEqual(
cluster.id.meta.stationIds,
stations.slice(0, 3).map((s) => s.id),
);
assert.equal(cluster.pixelSize, 12 + Math.log2(3) * 1.6);
assert.equal(cluster.outlineWidth, 2);
assert.equal(radioStationIdFromPick({ primitive: cluster, id: cluster.id }), stations[0].id);
radioLayer.selectStation(stations[3].id, { autoplay: false, focus: false });
const [selected] = rows(/^radio:\d+:selected$/);
const [bracket] = rows(/^radio:\d+:selected-bracket$/);
assert.equal(selected.pixelSize, 14);
assert.equal(selected.id.id, `radio:selected:${stations[3].id}`);
assert.ok(bracket instanceof Cesium.Billboard);
assert.equal(bracket.width, 40);
assert.equal(bracket.scaleByDistance.farValue, 0.72);
assert.equal(radioStationIdFromPick({ primitive: bracket, id: bracket.id }), stations[3].id);
});
assert.equal(scene.added.length, 0, 'gone with the layer');
});
test('vessels on a host with no sprite-set registry still draw, and say so once', async (t) => {
const warnings = [];
t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
-9
View File
@@ -46,15 +46,6 @@ export function billboardCollectionOf(billboard) {
return billboard?._billboardCollection;
}
/**
* The point collection an `EntityCluster` draws its cluster markers into.
* @param {object} clustering Cesium EntityCluster.
* @returns {object|null} Cesium PointPrimitiveCollection.
*/
export function clusterPointCollection(clustering) {
return clustering?._clusterPointCollection || null;
}
/**
* Close the widget's pending render-loop latch after `useDefaultRenderLoop`
* is set false, so a callback already queued sees the loop as stopped and
-7
View File
@@ -10,7 +10,6 @@ import {
billboardLoadError,
cameraFlightActive,
closeRenderLoopLatch,
clusterPointCollection,
commandExtents,
creditDisplayContents,
defaultView,
@@ -43,7 +42,6 @@ test('every private field the app reaches is still declared by the installed Ces
[ENGINE, 'Scene/Picking.js', '_pickOffscreenView'],
[ENGINE, 'Scene/View.js', '_commandExtents'],
[ENGINE, 'Scene/Billboard.js', '_billboardCollection'],
[ENGINE, 'DataSources/EntityCluster.js', '_clusterPointCollection'],
[ENGINE, 'Widget/CesiumWidget.js', '_renderLoopRunning'],
[WIDGETS, 'Viewer/Viewer.js', '_cesiumWidget'],
[ENGINE, 'Renderer/Context.js', '_gl'],
@@ -125,11 +123,6 @@ test('the helpers read and write exactly those fields', () => {
billboardCollectionOf({ _billboardCollection: collection }),
collection,
);
assert.equal(
clusterPointCollection({ _clusterPointCollection: collection }),
collection,
);
assert.equal(clusterPointCollection(undefined), null);
const widget = { _renderLoopRunning: true };
closeRenderLoopLatch({ _cesiumWidget: widget });
assert.equal(widget._renderLoopRunning, false);
-1
View File
@@ -15,7 +15,6 @@
"src/layers/launches/launchPad.js",
"src/layers/launches/orbitRendering.js",
"src/layers/launches/rendering.js",
"src/layers/radio/rendering.js",
"src/layers/recentImagery/rendering.js",
"src/layers/satellites/rendering.js",
"src/layers/traffic/rendering.js",
+3
View File
@@ -92,6 +92,9 @@ const DRAW_FROM_CALLER = new Set([
// Its heat cells and fire glows draw through `drawOf`; its cards and LOD
// watcher read the eye, projection and frames through the ports.
'./layers/firms',
// Its station dots, clusters and selected marker draw through `drawOf`;
// it clusters them on screen through the camera and query ports.
'./layers/radio',
// Its data packs draw through `drawOf`; its flights ask `cameraOf`, which
// throws until then too.
'./scenes',
+18 -11
View File
@@ -1,4 +1,6 @@
import { radioLayer } from '../data/radio.js';
import { bindRenderer } from '../render/rendererOf.js';
import { bindFakeDraw } from './fakeDrawPort.mjs';
export function radioStationRow(overrides = {}) {
return {
@@ -21,11 +23,17 @@ export function radioStationRow(overrides = {}) {
}
/**
* Run `body` against an enabled `radioLayer` that serves `stations`.
* Run `body` against an enabled `radioLayer` that serves `stations`, drawing
* through `renderer.draw`, or a fake draw port (with `renderer`'s other
* ports, if given).
* Streams listed in `failingUrls` (mutable) reject play(); `body` receives the
* played URLs and the catalog, whose rows and generation the next update() serves.
* played URLs, the catalog, whose rows and generation the next update()
* serves, and the fake draw port.
*/
export async function withRadioLayer({ stations, failingUrls = [] }, body) {
export async function withRadioLayer(
{ stations, failingUrls = [], renderer = {} },
body,
) {
const originalFetch = globalThis.fetch;
const originalAudio = globalThis.Audio;
const playUrls = [];
@@ -76,24 +84,23 @@ export async function withRadioLayer({ stations, failingUrls = [] }, body) {
removeEventListener() {},
},
},
dataSources: { add() {}, remove() {} },
entities: {
add(entity) {
return entity;
},
remove() {},
},
};
// The stations draw through the renderer's draw port: `renderer.draw`
// when given, else a fake one.
const { draw, unbind } = renderer.draw
? { draw: renderer.draw, unbind: bindRenderer(viewer, renderer) }
: bindFakeDraw(viewer, renderer);
radioLayer.destroy();
try {
radioLayer.init(viewer);
radioLayer.enable();
await radioLayer.update();
await body({ playUrls, catalog });
await body({ playUrls, catalog, draw });
} finally {
globalThis.fetch = originalFetch;
if (originalAudio === undefined) delete globalThis.Audio;
else globalThis.Audio = originalAudio;
radioLayer.destroy();
unbind();
}
}