Move the bikeshare layer onto the renderer's draw and camera ports

Station dots and the selected-station highlight are now two point draw
sets, picked through the draw hit, and the layer follows the camera
through the camera port at its own threshold instead of the shared
percentageChanged ledger. Altitude and view centre come from the camera
pose and view rectangle. All five bikeshare files leave the Cesium
allow-list.

The Cesium draw port now keeps a rebuilt host in its place in the scene
instead of re-adding it on top, tags hosts with their set id so sprite
order can raise a draw set (registerSpriteSet), and restyles unclamped
points in place when they have not moved, so a status poll or selection
no longer rebuilds every station. Other draw-port layers (cyclone
markers, earthquake discs) now also keep their first-build slot rather
than jumping above the sprite layers on each rebuild.
This commit is contained in:
Sameh Khamis committed 2026-11-06 20:26:35 -08:00
1 parent 2b66c46a30
commit 8c6fa6258b
22 files changed
+732 -249

No files matched your search

+122 -10
View File
@@ -67,6 +67,24 @@ const classificationOf = (clampTo = 'both') =>
tiles: Cesium.ClassificationType.CESIUM_3D_TILE,
})[clampTo] ?? Cesium.ClassificationType.BOTH;
/** A distance curve as Cesium's, or undefined. */
const nearFarOf = (curve) =>
curve
? new Cesium.NearFarScalar(
curve.near,
curve.nearValue,
curve.far,
curve.farValue,
)
: undefined;
/** Cesium's point blending for a set's `blend`. */
const pointBlendOf = (blend) =>
({
opaque: Cesium.BlendOption.OPAQUE,
translucent: Cesium.BlendOption.TRANSLUCENT,
})[blend] ?? Cesium.BlendOption.OPAQUE_AND_TRANSLUCENT;
const ANCHORS = {
center: Cesium.VerticalOrigin.CENTER,
bottom: Cesium.VerticalOrigin.BOTTOM,
@@ -115,6 +133,7 @@ export function createCesiumDraw({ scene, report }) {
const rebuild = () => {
record.pickIds = [];
record.placed = [];
record.patchable = null;
build(record);
setsVersion += 1;
};
@@ -128,6 +147,13 @@ export function createCesiumDraw({ scene, report }) {
requestRender();
},
upsert(list) {
// Items that only change how they look are changed where they are.
if (patchPoints(record, list)) {
for (const item of list) items.set(item.id, item);
setsVersion += 1;
requestRender();
return;
}
for (const item of list) items.set(item.id, item);
rebuild();
requestRender();
@@ -145,9 +171,10 @@ export function createCesiumDraw({ scene, report }) {
setOptions(options) {
const culled = spec.horizonCull;
const clampTo = spec.clampTo;
const blend = spec.blend;
Object.assign(spec, options);
// What clamped items clamp to is built into them.
if (spec.clampTo !== clampTo) rebuild();
// What clamped items clamp to, and how points blend, are built in.
if (spec.clampTo !== clampTo || spec.blend !== blend) rebuild();
setsVersion += 1;
showHosts(record);
// No longer culled: what the cull hid comes back.
@@ -203,6 +230,17 @@ export function createCesiumDraw({ scene, report }) {
function replaceHost(record, host, ground = null, own = null) {
const old = record.host;
const waiting = ground?.length ? ground : null;
// The set keeps its place among the scene's primitives: a rebuild draws
// where it drew, so stacking (and picks among overlapping items) does
// not change with each update. Its place is under whatever was above
// the host it replaces (indices shift as older hosts go).
const slot = old ? slotOf(old) : -1;
const above =
slot >= 0 && slot + 1 < scene.primitives.length
? scene.primitives.get(slot + 1)
: null;
// Named for code that orders the scene's primitives (`spriteOrder.js`).
host.drawSetId = record.spec.id;
// Only old ground primitives wait for the new ones: the rest of the old
// host goes now, as the new host's own parts draw at once.
if (
@@ -222,10 +260,20 @@ export function createCesiumDraw({ scene, report }) {
record.ground = waiting;
record.own = waiting ? own : null;
record.host = host;
scene.primitives.add(host);
const at = above ? slotOf(above) : -1;
if (at >= 0) scene.primitives.add(host, at);
else scene.primitives.add(host);
showHosts(record);
}
/** Where `primitive` is among the scene's primitives, or -1. */
function slotOf(primitive) {
const primitives = scene.primitives;
const n = primitives?.length ?? 0;
for (let i = 0; i < n; i++) if (primitives.get(i) === primitive) return i;
return -1;
}
function showHosts(record) {
const show = record.spec.show !== false;
if (record.host) record.host.show = show;
@@ -284,7 +332,9 @@ export function createCesiumDraw({ scene, report }) {
/** Remember a drawn point or icon for the horizon cull. */
function place(record, primitive, position, shown) {
record.placed.push({ primitive, position, shown });
const placed = { primitive, position, shown };
record.placed.push(placed);
return placed;
}
// Atlases icons name images from, by id: `{atlas, slot}` reads the slot
@@ -353,17 +403,24 @@ export function createCesiumDraw({ scene, report }) {
);
let primitive;
if (heightReference === Cesium.HeightReference.NONE) {
points ??= new Cesium.PointPrimitiveCollection();
points ??= new Cesium.PointPrimitiveCollection({
blendOption: pointBlendOf(record.spec.blend),
});
primitive = points.add({
position,
pixelSize: item.pixelSize,
color: toColor(item.color),
outlineColor: toColor(item.outlineColor ?? [0, 0, 0, 0]),
outlineWidth: item.outlineWidth ?? 0,
disableDepthTestDistance: item.disableDepthTest ?? 0,
...pointLook(item),
show,
id: pickId(record, item),
});
const placed = place(record, primitive, position, show);
record.patchable ??= new Map();
record.patchable.set(item.id, {
primitive,
placed,
at: placeOf(item),
lodGroup: item.lodGroup,
});
continue;
} else {
// Point primitives cannot follow the ground.
dots ??= new Cesium.BillboardCollection({ scene });
@@ -385,6 +442,61 @@ export function createCesiumDraw({ scene, report }) {
replaceHost(record, host);
}
/** How a point primitive draws an unclamped point item. */
function pointLook(item) {
return {
pixelSize: item.pixelSize,
color: toColor(item.color),
outlineColor: toColor(item.outlineColor ?? [0, 0, 0, 0]),
outlineWidth: item.outlineWidth ?? 0,
disableDepthTestDistance: item.disableDepthTest ?? 0,
scaleByDistance: nearFarOf(item.scaleByDistance),
translucencyByDistance: nearFarOf(item.fadeByDistance),
};
}
const PLACE_KEYS = ['x', 'y', 'z', 'lon', 'lat', 'height'];
/**
* Where an item is, as its values when drawn: a caller may change the
* position object it passes and send the same one again.
*/
const placeOf = (item) =>
PLACE_KEYS.map((key) => item.pos?.[key]).concat(item.height);
/**
* Upsert unclamped points in place, without a rebuild, when every item
* is one the set draws as a point primitive now and keeps its position,
* height mode and LOD group: then only how it looks, its `meta` and
* whether it shows change. False, changing nothing, otherwise.
*/
function patchPoints(record, list) {
const patchable = record.patchable;
if (record.kind !== 'points' || !patchable) return false;
for (const item of list) {
const was = patchable.get(item.id);
if (
!was ||
heightReferenceOf(item.height, record.spec.clampTo) !==
Cesium.HeightReference.NONE ||
item.lodGroup !== was.lodGroup ||
placeOf(item).some((value, i) => value !== was.at[i])
)
return false;
}
for (const item of list) {
const was = patchable.get(item.id);
const show = item.show !== false;
Object.assign(was.primitive, pointLook(item));
was.primitive.id.meta = item.meta;
was.placed.shown = show;
// As a rebuild would; the horizon cull, where it runs, hides it again
// past the horizon before the next frame draws.
was.primitive.show = show;
}
return true;
}
/**
* A clamped point as Cesium's entity points draw one: a billboard of a
* dot drawn at its pixel size, one texture per look.
+233
View File
@@ -448,3 +448,236 @@ test('the cyclones layer draws clamped dots, draped tracks and holed cones on a
rendering.destroy();
assert.equal(scene.added.length, 0);
});
test('point sets blend as asked and fall off with distance', () => {
const { scene, draw } = drawOver();
const set = draw.points({ id: 'falloff', blend: 'translucent' });
set.set([
{
id: 'a',
pos: { lon: 0, lat: 0, height: 2 },
pixelSize: 6,
color: [1, 0, 0, 0.5],
scaleByDistance: { near: 200, nearValue: 1.35, far: 1e5, farValue: 0.4 },
fadeByDistance: { near: 200, nearValue: 1, far: 2e5, farValue: 0.15 },
},
{ id: 'b', pos: { lon: 1, lat: 0 }, pixelSize: 6, color: '#fff' },
]);
const [points] = scene.added;
assert.equal(points.blendOption, Cesium.BlendOption.TRANSLUCENT);
const a = points.get(0);
assert.ok(
Cesium.NearFarScalar.equals(
a.scaleByDistance,
new Cesium.NearFarScalar(200, 1.35, 1e5, 0.4),
),
);
assert.ok(
Cesium.NearFarScalar.equals(
a.translucencyByDistance,
new Cesium.NearFarScalar(200, 1, 2e5, 0.15),
),
);
assert.equal(points.get(1).scaleByDistance, undefined, 'none asked');
set.setOptions({ blend: 'opaque' });
assert.equal(scene.added[0].blendOption, Cesium.BlendOption.OPAQUE);
set.setOptions({ blend: undefined });
assert.equal(
scene.added[0].blendOption,
Cesium.BlendOption.OPAQUE_AND_TRANSLUCENT,
'the default, as before',
);
set.dispose();
});
test('the bikeshare layer draws its stations as point primitives on a viewer of its own', async () => {
const { createState } = await import('../../layers/bikeshare/state.js');
const { createModel } = await import('../../layers/bikeshare/model.js');
const { createRendering } =
await import('../../layers/bikeshare/rendering.js');
const { createSelection } =
await import('../../layers/bikeshare/selection.js');
const scene = fakeScene();
const viewer = { scene };
const services = {
render: { governorRequestRender() {} },
overlays: {
setOverlayEntries() {},
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
};
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source: {} };
parts.model = createModel(context);
parts.rendering = createRendering(context);
parts.selection = createSelection(context);
state._viewer = viewer;
parts.rendering.attachSets(viewer);
state._stationSet.show = true;
const info = parts.model.parseStationInformation({
data: {
stations: [
{ station_id: 'a', name: 'A', lat: 30.26, lon: -97.74, capacity: 20 },
{ station_id: 'b', name: 'B', lat: 30.27, lon: -97.75, capacity: 4 },
],
},
});
parts.rendering.ensureCityPoints('austin', info);
parts.rendering.applyStatusToPoints(
'austin',
parts.model.parseStationStatus({
data: {
stations: [
{ station_id: 'a', num_bikes_available: 18, num_docks_available: 2 },
],
},
}),
);
const points = scene.added.find((host) => host.get(0)?.id?.id === 'austin:a');
assert.ok(points instanceof Cesium.PointPrimitiveCollection);
assert.equal(points.blendOption, Cesium.BlendOption.TRANSLUCENT);
assert.equal(points.length, 2);
const a = points.get(0);
assert.match(a.id.set, /^bikeshare:\d+:stations$/);
assert.equal(a.disableDepthTestDistance, 2500);
assert.equal(a.outlineWidth, 1);
assert.ok(
a.color.equalsEpsilon(
Cesium.Color.fromCssColorString('#00ff88').withAlpha(0.95),
1e-9,
),
'plenty of bikes: green, as before',
);
assert.ok(
Cesium.Cartesian3.equalsEpsilon(
a.position,
Cesium.Cartesian3.fromDegrees(-97.74, 30.26, 2),
0,
1e-6,
),
);
assert.ok(
Cesium.NearFarScalar.equals(
a.scaleByDistance,
new Cesium.NearFarScalar(200, 1.35, 130000, 0.4),
),
);
// Selected: its own dot goes, a cyan one over everything takes its place.
parts.selection._selectStation('austin:a');
const stations = scene.added.find(
(host) => host.get(0)?.id?.set === a.id.set,
);
assert.equal(stations.get(0).show, false);
const highlight = scene.added.find((host) =>
host.get(0)?.id?.set?.endsWith(':selected'),
);
const dot = highlight.get(0);
assert.ok(Cesium.Color.equals(dot.color, Cesium.Color.CYAN));
assert.equal(dot.pixelSize, 14);
assert.equal(dot.outlineWidth, 2);
assert.equal(dot.disableDepthTestDistance, Infinity);
parts.selection._clearSelection();
parts.rendering.detachSets();
assert.equal(scene.added.length, 0);
});
test('a rebuilt set keeps its place among the scene primitives, and names its host', async () => {
const {
registerSpriteSet,
registerSpriteCollection,
restoreSpriteOrder,
unregisterSpriteCollection,
} = await import('../../data/spriteOrder.js');
const scene = fakeScene();
scene.primitives = new Cesium.PrimitiveCollection();
const { draw } = drawOver(scene);
const below = scene.primitives.add(new Cesium.PrimitiveCollection());
const set = draw.points({ id: 'kept' });
set.set([]);
const above = scene.primitives.add(new Cesium.PrimitiveCollection());
const order = () => {
const out = [];
for (let i = 0; i < scene.primitives.length; i++) {
const p = scene.primitives.get(i);
out.push(p === below ? 'below' : p === above ? 'above' : p.drawSetId);
}
return out;
};
assert.deepEqual(order(), ['below', 'kept', 'above']);
set.set([{ id: 'a', pos: { lon: 0, lat: 0 }, pixelSize: 4, color: '#fff' }]);
set.upsert([
{ id: 'b', pos: { lon: 1, lat: 0 }, pixelSize: 4, color: '#fff' },
]);
assert.deepEqual(
order(),
['below', 'kept', 'above'],
'not raised by updates',
);
// The sprite order finds the set's host by its id, whichever host it is.
const cctv = registerSpriteCollection('cctv', below);
const flights = registerSpriteCollection('flights', above);
const entry = registerSpriteSet('bikeshare', 'kept');
scene.primitives.raiseToTop(below);
assert.deepEqual(order(), ['kept', 'above', 'below']);
restoreSpriteOrder({ scene });
assert.deepEqual(order(), ['below', 'kept', 'above']);
unregisterSpriteCollection('bikeshare', entry);
unregisterSpriteCollection('cctv', cctv);
unregisterSpriteCollection('flights', flights);
set.dispose();
});
test('restyling points that stay put changes them in place; moving one rebuilds', () => {
const { scene, draw } = drawOver();
const set = draw.points({ id: 'restyled', blend: 'translucent' });
const dot = (id, lon, extra = {}) => ({
id,
pos: { lon, lat: 0, height: 2 },
pixelSize: 6,
color: [1, 0, 0, 1],
...extra,
});
set.set([dot('a', 0), dot('b', 1)]);
const [host] = scene.added;
const a = host.get(0);
set.upsert([
dot('a', 0, { color: [0, 1, 0, 1], pixelSize: 9, show: false, meta: 7 }),
]);
assert.equal(scene.added[0], host, 'the same collection');
assert.equal(host.get(0), a, 'the same point');
assert.ok(Cesium.Color.equals(a.color, Cesium.Color.LIME));
assert.equal(a.pixelSize, 9);
assert.equal(a.show, false);
assert.equal(a.id.meta, 7, 'picks read the new meta');
assert.equal(set.size(), 2);
set.upsert([dot('b', 2)]);
assert.notEqual(scene.added[0], host, 'moved: rebuilt');
set.upsert([dot('c', 3)]);
assert.equal(set.size(), 3, 'a new item rebuilds too');
assert.equal(scene.added[0].length, 3);
set.dispose();
});
test('a position object changed and sent again moves its point', () => {
const { scene, draw } = drawOver();
const set = draw.points({ id: 'moved-in-place' });
const item = {
id: 'a',
pos: { lon: 0, lat: 0 },
pixelSize: 4,
color: '#fff',
};
set.set([item]);
const host = scene.added[0];
item.pos.lon = 90;
set.upsert([item]);
assert.notEqual(scene.added[0], host, 'rebuilt where it now is');
const at = Cesium.Cartographic.fromCartesian(scene.added[0].get(0).position);
assert.ok(Math.abs(Cesium.Math.toDegrees(at.longitude) - 90) < 1e-9);
set.dispose();
});