Draw the traffic heat-lines through the draw port, batching alike draped glow lines in the Cesium draw port

This commit is contained in:
Sameh Khamis committed 2026-11-07 23:16:11 -08:00
1 parent bbd6049e21
commit 5715bf9df3
11 files changed
+608 -193

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createRendering } from './rendering.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import {
HEAT_JAM_BASE_ALPHA,
HEAT_JAM_COLOR,
HEAT_JAM_PULSE_ALPHA,
HEAT_LINE_CAP,
HEAT_LINE_JAM_WIDTH,
HEAT_LINE_SLOW_WIDTH,
HEAT_SLOW_COLOR,
} from './policy.js';
/** A road of `length` metres along x, in the flow bucket `level` gives. */
const road = (level, length = 100, x = 0) => ({
flow: { level },
segmentDist: [length],
waypoints: [
{ x, y: 6378137, z: 0 },
{ x: x + length, y: 6378137, z: 0 },
],
});
function setup({
live = true,
heatline = true,
preset = 'normal',
supported = true,
} = {}) {
const draw = fakeDrawPort();
const demand = [];
const state = {
_viewer: {},
_liveMode: live,
_presetDots: 'on',
_stylePreset: preset,
_heatJam: [],
_heatLineCount: 0,
_heatSupported: supported,
_heatSet: draw.lines({ id: 'traffic:1:heat', clampTo: 'tiles' }),
};
const rendering = createRendering({
state,
services: {},
parts: {
style: { heatlineOn: () => heatline },
animation: { syncRenderDemand: () => demand.push(state._heatLineCount) },
},
source: {},
});
const items = () => [...draw.set('traffic:1:heat').items.values()];
return {
state,
rendering,
items,
demand,
record: draw.set('traffic:1:heat'),
};
}
test('congested roads drape heat-lines on the tiles: jam glowing, slow flat', () => {
const { state, rendering, items, demand } = setup();
rendering.rebuildHeatLines([
road(0.9), // free: none
road(0.2, 50, 1), // jam
road(0.6, 80, 2), // slow
{ ...road(0.2), flow: { level: 0.2, closure: true } }, // closed: none
]);
const lines = items();
assert.equal(lines.length, 2);
const [jam, slow] = lines;
assert.equal(jam.mode, 'draped');
assert.equal(jam.clampTo, 'tiles');
assert.equal(jam.widthPx, HEAT_LINE_JAM_WIDTH);
assert.deepEqual(jam.style, {
kind: 'glow',
color: [...HEAT_JAM_COLOR.slice(0, 3), HEAT_JAM_BASE_ALPHA],
power: 0.25,
});
assert.deepEqual(jam.positions, [
{ x: 1, y: 6378137, z: 0 },
{ x: 51, y: 6378137, z: 0 },
]);
assert.equal(slow.widthPx, HEAT_LINE_SLOW_WIDTH);
assert.deepEqual(slow.style, { kind: 'solid', color: HEAT_SLOW_COLOR });
assert.equal(state._heatLineCount, 2);
assert.equal(rendering.heatPulsing(), true);
assert.deepEqual(demand, [2]);
});
test('the jam heat-lines pulse together, recoloured where they are', () => {
const { rendering, items, record } = setup();
rendering.rebuildHeatLines([road(0.2), road(0.25, 50), road(0.6)]);
const writes = record.writes;
rendering.pulseHeatLines(260 * (Math.PI / 2));
assert.equal(record.writes, writes + 1, 'one upsert a frame');
const alpha = HEAT_JAM_BASE_ALPHA + HEAT_JAM_PULSE_ALPHA;
const [a, b, slow] = items();
assert.ok(Math.abs(a.style.color[3] - alpha) < 1e-12);
assert.equal(b.style, a.style);
assert.equal(slow.style.kind, 'solid', 'slow lines do not pulse');
});
test('heat-lines are capped jam first, longest first', () => {
const { items } = (() => {
const s = setup();
const roads = [];
for (let i = 0; i < HEAT_LINE_CAP; i++) roads.push(road(0.6, 10 + i));
roads.push(road(0.2, 5));
s.rendering.rebuildHeatLines(roads);
return s;
})();
const lines = items();
assert.equal(lines.length, HEAT_LINE_CAP);
assert.equal(lines[0].style.kind, 'glow', 'the jam line kept first');
assert.equal(lines[1].widthPx, HEAT_LINE_SLOW_WIDTH);
assert.equal(lines[1].positions[1].x, 10 + HEAT_LINE_CAP - 1);
});
test('mono presets draw heat-lines in luminance', () => {
const { rendering, items } = setup({ preset: 'surveillance' });
rendering.rebuildHeatLines([road(0.2), road(0.6)]);
const [jam, slow] = items();
assert.deepEqual(jam.style.color, [1, 1, 1, HEAT_JAM_BASE_ALPHA]);
assert.deepEqual(slow.style.color, [0.7, 0.7, 0.7, HEAT_SLOW_COLOR[3]]);
});
test('no heat-lines in simulation or with the mode off, and removal empties the set', () => {
for (const options of [{ live: false }, { heatline: false }]) {
const { rendering, items, record } = setup(options);
rendering.rebuildHeatLines([road(0.2)]);
assert.equal(items().length, 0);
assert.equal(record.writes, 0, 'an empty set is left alone');
assert.equal(rendering.heatPulsing(), false);
}
const { state, rendering, items } = setup();
rendering.rebuildHeatLines([road(0.2)]);
rendering.removeHeatLines();
assert.equal(items().length, 0);
assert.equal(state._heatLineCount, 0);
assert.equal(rendering.heatPulsing(), false);
rendering.pulseHeatLines(0);
assert.equal(items().length, 0, 'nothing to pulse');
});
test('where lines cannot drape, no heat-lines are drawn and that is said once', (t) => {
const warn = t.mock.method(console, 'warn', () => {});
const { state, rendering, items } = setup({ supported: null });
state._viewer = { scene: {} };
rendering.rebuildHeatLines([road(0.2)]);
rendering.rebuildHeatLines([road(0.2)]);
assert.equal(items().length, 0);
assert.equal(state._heatSupported, false);
assert.equal(warn.mock.callCount(), 1);
assert.equal(rendering.heatPulsing(), false);
});
+20 -7
View File
@@ -24,19 +24,30 @@ export function createLifecycle({
const methods = {
/**
* One-time initialisation. Makes the dots' draw set (hidden); it is
* shown and hidden with the layer, and let go on destroy.
* One-time initialisation. Makes the dots' draw set (hidden; it is
* shown and hidden with the layer) and the heat-lines' (emptied when
* the layer is disabled); both are let go on destroy.
*
* @param {Cesium.Viewer} viewer - The Cesium viewer instance.
*/
init(viewer) {
layerState._viewer = viewer;
layerState._dotSet?.dispose();
layerState._dotSet = drawOf(viewer).points({
id: `traffic:${++instances}:dots`,
layerState._heatSet?.dispose();
const instance = ++instances;
const draw = drawOf(viewer);
layerState._dotSet = draw.points({
id: `traffic:${instance}:dots`,
blend: 'translucent',
show: false,
});
// Draped on the 3D tiles only, as the dots' roads are sampled there.
layerState._heatSet = draw.lines({
id: `traffic:${instance}:heat`,
clampTo: 'tiles',
});
layerState._heatJam = [];
layerState._heatLineCount = 0;
layerState._dots = [];
layerState._roads = [];
layerState._count = 0;
@@ -194,16 +205,18 @@ export function createLifecycle({
},
/**
* Permanently tear down the layer. Disables it, lets the dots' draw set
* go, and clears the tile cache.
* Permanently tear down the layer. Disables it, lets the dots' and
* heat-lines' draw sets go, and clears the tile cache.
*
* @param {Cesium.Viewer} viewer - The Cesium viewer instance.
*/
destroy(viewer) {
this.disable(viewer);
parts.rendering.removeHeatLines();
layerState._dotSet?.dispose();
layerState._dotSet = null;
parts.rendering.removeHeatLines();
layerState._heatSet?.dispose();
layerState._heatSet = null;
layerState._tileCache.clear();
resetFlowTileCache();
layerState._count = 0;
+1 -1
View File
@@ -591,7 +591,7 @@ test('a closure that empties the population mid-correction settles heights and c
corrected[0].flow = { level: 0, closure: true };
for (let i = 0; i < 20 && h.state._dots.length; i++) h.frame();
assert.equal(h.state._dots.length, 0);
assert.equal(h.state._heatJamPrim, null);
assert.equal(h.state._heatLineCount, 0);
assert.equal(h.state._renderHeld, false);
assert.equal(h.state._heightPending, false);
assert.equal(h.state._populationPending, false);
+3 -3
View File
@@ -16,9 +16,9 @@ test('traffic render demand follows animated population and jam lines across emp
parts: {
retention: { clear() {} },
rendering: {
heatPulsing: () => Boolean(state._heatJamPrim),
heatPulsing: () => Boolean(state._heatJam?.length),
removeHeatLines() {
state._heatJamPrim = null;
state._heatJam = [];
},
},
},
@@ -31,7 +31,7 @@ test('traffic render demand follows animated population and jam lines across emp
assert.deepEqual(calls, [['hold', 'traffic']]);
animation.clearDots();
assert.deepEqual(calls.at(-1), ['release', 'traffic']);
state._heatJamPrim = {};
state._heatJam = [{}];
animation.syncRenderDemand();
assert.deepEqual(calls.at(-1), ['hold', 'traffic']);
state._enabled = false;
+73 -167
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { flowBucket } from '../../data/trafficFlowStyle.js';
import { trafficStyleProfile } from '../../data/trafficPresetStyle.js';
import {
@@ -11,83 +10,17 @@ import {
HEAT_LINE_SLOW_WIDTH,
TRAFFIC_TIMING_ENABLED,
} from './policy.js';
import { distance } from '../../geo/vector.js';
import { findCamera } from '../../render/rendererOf.js';
// What the dots' surface is, and whether it has loaded, the renderer
// contract cannot say: the Cesium adapter reads it off the scene.
import {
drapesLines,
surfaceTilesReady,
surfaceKey as trafficSurfaceKey,
} from '../../render/cesium/surfaceState.js';
/**
* Whether the surface the dots sit on has loaded what is in view: the
* globe's tiles while it is shown, otherwise every shown 3D tileset (and
* there is one). The globe port's settle states cannot say whether any
* tileset is drawn at all, so this reads the scene.
* @param {object|undefined} viewer
*/
export function surfaceTilesReady(viewer) {
const scene = viewer?.scene;
if (!scene) return false;
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
let found = false;
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
const primitive = scene.primitives.get(i);
if (!primitive.show || typeof primitive.tilesLoaded !== 'boolean') continue;
found = true;
if (!primitive.tilesLoaded) return false;
}
return found;
}
// Stable ids for the objects heights are sampled from (tilesets, terrain).
const surfaceIds = new WeakMap();
let nextSurfaceId = 1;
const surfaceId = (object) => {
if (!object || typeof object !== 'object') return 0;
if (!surfaceIds.has(object)) surfaceIds.set(object, nextSurfaceId++);
return surfaceIds.get(object);
};
/**
* Name what heights are sampled against: the terrain provider when the globe
* is shown, otherwise the set of visible 3D tilesets. A map-provider switch
* changes it and invalidates every cached height. The renderer contract
* names no surface identity, so this reads the scene.
* @param {object|undefined} viewer
*/
const surfaceKeys = new WeakMap();
export function trafficSurfaceKey(viewer) {
const scene = viewer?.scene;
if (!scene) return '';
let state = surfaceKeys.get(scene);
if (!state) {
state = { globe: null, terrain: null, tiles: [], key: '' };
surfaceKeys.set(scene, state);
}
const globe = Boolean(scene.globe?.show);
const terrain = globe ? scene.globe.terrainProvider : null;
let changed = state.globe !== globe || state.terrain !== terrain;
let count = 0;
if (!globe) {
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
const primitive = scene.primitives.get(i);
if (!primitive?.show || typeof primitive.tilesLoaded !== 'boolean')
continue;
if (state.tiles[count] !== primitive) {
state.tiles[count] = primitive;
changed = true;
}
count++;
}
}
if (count !== state.tiles.length) {
state.tiles.length = count;
changed = true;
}
if (changed) {
state.globe = globe;
state.terrain = terrain;
// Allocate only when the actual map surface changes, never per frame.
state.key = globe
? `globe:${surfaceId(terrain)}`
: `tiles:${state.tiles.map(surfaceId).join(',')}`;
}
return state.key;
}
export { surfaceTilesReady, trafficSurfaceKey };
export function createRendering({
state: layerState,
@@ -112,21 +45,11 @@ export function createRendering({
: roads;
}
/** Remove both heat-line ground primitives from the scene. */
/** Take every heat-line down. */
function removeHeatLines() {
if (layerState._heatJamPrim) {
layerState._viewer?.scene.groundPrimitives.remove(
layerState._heatJamPrim,
);
layerState._heatJamPrim = null;
}
if (layerState._heatSlowPrim) {
layerState._viewer?.scene.groundPrimitives.remove(
layerState._heatSlowPrim,
);
layerState._heatSlowPrim = null;
}
if (layerState._heatLineCount) layerState._heatSet?.clear();
layerState._heatJam = [];
layerState._heatLineCount = 0;
parts.animation.syncRenderDemand?.();
}
@@ -135,32 +58,35 @@ export function createRendering({
* Rebuild the congestion heat-line underlay (jam-viz heatline prototype):
* slow/jam roads drape a corridor line onto the rendered 3D tiles — glowing
* pulsing red for jam, faint flat amber for slow — with the dots animating
* on top. Two batched GroundPolylinePrimitives (one per bucket) so the jam
* batch pulses through one shared material. Capped at HEAT_LINE_CAP (jam
* first, longest first); overflow is logged. No-op in sim mode, when the
* heatline mode is off, or without ground-primitive support.
* on top. Lines of the layer's heat-line draw set, draped on the tiles;
* the jam lines pulse together (`pulseHeatLines`). Capped at
* HEAT_LINE_CAP (jam first, longest first); overflow is logged. No-op in
* sim mode, when the heatline mode is off, or where lines cannot drape.
*
* @param {Array} roads - Road objects visible in the current render.
*/
function rebuildHeatLines(roads) {
removeHeatLines();
if (
!layerState._viewer ||
!layerState._heatSet ||
!layerState._liveMode ||
!parts.style.heatlineOn()
)
) {
removeHeatLines();
return;
}
if (layerState._heatSupported === null) {
layerState._heatSupported = Cesium.GroundPolylinePrimitive.isSupported(
layerState._viewer.scene,
);
layerState._heatSupported = drapesLines(layerState._viewer);
if (!layerState._heatSupported)
console.warn(
'[Data:Traffic] GroundPolylinePrimitive unsupported — heat-lines disabled',
'[Data:Traffic] Draped lines unsupported — heat-lines disabled',
);
}
if (!layerState._heatSupported) return;
if (!layerState._heatSupported) {
removeHeatLines();
return;
}
const candidates = [];
for (const road of roads) {
@@ -177,63 +103,37 @@ export function createRendering({
);
const kept = candidates.slice(0, HEAT_LINE_CAP);
const instancesFor = (bucket, width) =>
kept
.filter((c) => c.bucket === bucket)
.map(
(c) =>
new Cesium.GeometryInstance({
geometry: new Cesium.GroundPolylineGeometry({
// A snapshot of the waypoints, as the renderer's points.
positions: c.road.waypoints.map((p) =>
Cesium.Cartesian3.clone(p),
),
width,
}),
}),
);
// Mono presets (NVG/FLIR/noir) discard hue — heat-lines re-encode in
// luminance like the dots: jam = white glow, slow = faint gray.
const monoHeat =
layerState._presetDots === 'on' &&
trafficStyleProfile(layerState._stylePreset) === 'mono';
const jamLineColor = monoHeat
? Cesium.Color.WHITE
: new Cesium.Color(...HEAT_JAM_COLOR);
const slowLineColor = monoHeat
? new Cesium.Color(0.7, 0.7, 0.7, HEAT_SLOW_COLOR[3])
: new Cesium.Color(...HEAT_SLOW_COLOR);
layerState._heatJamRgb = monoHeat ? [1, 1, 1] : HEAT_JAM_COLOR.slice(0, 3);
const jamStyle = jamLineStyle(HEAT_JAM_BASE_ALPHA);
const slowStyle = {
kind: 'solid',
color: monoHeat ? [0.7, 0.7, 0.7, HEAT_SLOW_COLOR[3]] : HEAT_SLOW_COLOR,
};
const jamInstances = instancesFor('jam', HEAT_LINE_JAM_WIDTH);
if (jamInstances.length) {
layerState._heatJamPrim = layerState._viewer.scene.groundPrimitives.add(
new Cesium.GroundPolylinePrimitive({
geometryInstances: jamInstances,
classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
appearance: new Cesium.PolylineMaterialAppearance({
material: Cesium.Material.fromType('PolylineGlow', {
color: jamLineColor.withAlpha(HEAT_JAM_BASE_ALPHA),
glowPower: 0.25,
}),
}),
}),
);
}
const slowInstances = instancesFor('slow', HEAT_LINE_SLOW_WIDTH);
if (slowInstances.length) {
layerState._heatSlowPrim = layerState._viewer.scene.groundPrimitives.add(
new Cesium.GroundPolylinePrimitive({
geometryInstances: slowInstances,
classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
appearance: new Cesium.PolylineMaterialAppearance({
material: Cesium.Material.fromType('Color', {
color: slowLineColor,
}),
}),
}),
);
const items = [];
const jam = [];
for (let i = 0; i < kept.length; i++) {
const { road, bucket } = kept[i];
const item = {
id: `heat:${i}`,
// A snapshot of the waypoints, as the renderer's points.
positions: road.waypoints.map((p) => ({ x: p.x, y: p.y, z: p.z })),
widthPx: bucket === 'jam' ? HEAT_LINE_JAM_WIDTH : HEAT_LINE_SLOW_WIDTH,
mode: 'draped',
clampTo: 'tiles',
style: bucket === 'jam' ? jamStyle : slowStyle,
};
items.push(item);
if (bucket === 'jam') jam.push(item);
}
if (items.length || layerState._heatLineCount)
layerState._heatSet.set(items);
layerState._heatJam = jam;
layerState._heatLineCount = kept.length;
parts.animation.syncRenderDemand?.();
@@ -244,19 +144,29 @@ export function createRendering({
}
}
/** The jam heat-lines' glow at `alpha`. */
const jamLineStyle = (alpha) => ({
kind: 'glow',
color: [...layerState._heatJamRgb, alpha],
power: 0.25,
});
/** Whether jam heat-lines are drawn, which pulse every frame. */
const heatPulsing = () => Boolean(layerState._heatJamPrim);
const heatPulsing = () => Boolean(layerState._heatJam?.length);
/**
* Throb the jam heat-lines (~1.6 s period): one shared material uniform
* for the whole jam batch, no geometry rebuild.
* Throb the jam heat-lines (~1.6 s period): one colour for them all,
* each line recoloured where it is, no geometry rebuilt.
* @param {number} now - Epoch ms.
*/
function pulseHeatLines(now) {
if (layerState._heatJamPrim?.appearance) {
layerState._heatJamPrim.appearance.material.uniforms.color.alpha =
HEAT_JAM_BASE_ALPHA + HEAT_JAM_PULSE_ALPHA * Math.sin(now / 260);
}
const jam = layerState._heatJam;
if (!jam?.length || !layerState._heatSet) return;
const style = jamLineStyle(
HEAT_JAM_BASE_ALPHA + HEAT_JAM_PULSE_ALPHA * Math.sin(now / 260),
);
for (const item of jam) item.style = style;
layerState._heatSet.upsert(jam);
}
/**
@@ -300,7 +210,10 @@ export function createRendering({
// nadir view: oblique pitches put the loaded roads many km away even at
// low altitude. Probe three roads and stretch the curves accordingly.
let areaDist = altitude;
if (layerState._viewer && filteredRoads.length) {
const eye = filteredRoads.length
? findCamera(layerState._viewer)?.pose()?.position
: null;
if (eye) {
const probes = [
filteredRoads[0],
filteredRoads[Math.floor(filteredRoads.length / 2)],
@@ -308,14 +221,7 @@ export function createRendering({
];
for (const probe of probes) {
const wp = probe?.waypoints?.[0];
if (wp)
areaDist = Math.max(
areaDist,
Cesium.Cartesian3.distance(
layerState._viewer.camera.positionWC,
wp,
),
);
if (wp) areaDist = Math.max(areaDist, distance(eye, wp));
}
}
layerState._fadeScaleFar = Math.max(8000, areaDist * 1.5);
+10 -8
View File
@@ -167,24 +167,26 @@ export function createState({ services }) {
layerState._jamViz = 'density';
/**
* Congestion heat-lines are GroundPolylinePrimitive batches draped onto the
* rendered 3D tiles (ClassificationType.CESIUM_3D_TILE). One
* primitive per bucket so the jam batch can pulse via a single shared
* material uniform.
* Congestion heat-lines: a lines draw set draped onto the rendered 3D
* tiles, made at init.
* @type {object|null}
*/
layerState._heatJamPrim = null;
layerState._heatSet = null;
/** @type {object|null} Slow-bucket heat-line batch. */
/** @type {Array} The jam heat-line items, recoloured as they pulse. */
layerState._heatSlowPrim = null;
layerState._heatJam = [];
/** @type {number[]} The jam heat-lines' colour, without its alpha. */
layerState._heatJamRgb = [1, 1, 1];
/** @type {number} Heat-lines in the current render (stats). */
layerState._heatLineCount = 0;
/** @type {boolean|null} GroundPolylinePrimitive.isSupported, checked once. */
/** @type {boolean|null} Whether lines can drape here, checked once. */
layerState._heatSupported = null;