Draw the transit trail through the draw port and take it off the Cesium list

The selected vehicle's trail is now two draw-port line sets instead of
Cesium primitives. The body is each run of joined history subdivisions as
draped lines in two lanes, a dark 5 px backing under the 3 px mode colour.
A subdivision shows once the vehicle has passed it and fades with its age;
both are written in place as segment shows and colours, once a second or
at a crossing, and a new mode colour is written the same way. The head is
the subdivision the vehicle is on, in the same two lanes, revealed up to
the vehicle with revealFraction: it is drawn anew only at a crossing.
Shows are written only when they change.

The transit tests bind a fake draw port, and the transit QA script finds
the trail's primitives by their draw set.
This commit is contained in:
Sameh Khamis committed 2026-11-07 07:41:00 -08:00
1 parent e8872ab419
commit 87c80856c2
7 files changed
+495 -568

No files matched your search

+182 -214
View File
@@ -1,4 +1,19 @@
import * as Cesium from 'cesium';
/**
* @module contactTrailRenderer
* @description The selected transit vehicle's trail, drawn through the
* renderer's draw port as draped lines: a history body and a moving head.
*
* The body is every subdivision of the vehicle's history, each a segment of
* a draped line in two lanes (a dark 5 px backing under a 3 px line in the
* mode colour). A segment shows once the vehicle has passed it and fades
* with its age; both change in place (`segmentShow`, `segmentColors`), so
* the body is rebuilt only when the history changes. The head is the
* subdivision the vehicle is on, revealed up to the vehicle
* (`revealFraction`): it is drawn anew only where the vehicle crosses into
* the next subdivision, and a frame writes how far it is revealed.
*/
import { cssColor } from '../render/color.js';
import { findDraw } from '../render/rendererOf.js';
const ALPHA_STOPS = [
[0, 0.8],
@@ -19,95 +34,126 @@ export function trailAlpha(ageMs) {
return 0.08;
}
/** One static history batch and one frequently updated head. Never entities. */
export function createContactTrailRenderer(scene) {
const ground =
!!scene.frameState?.context &&
Cesium.GroundPolylinePrimitive.isSupported(scene);
const collection = ground ? scene.groundPrimitives : scene.primitives;
// One 25 m corridor is clipped in material coordinates. Only subdivision
// crossings build geometry; frame updates write a scalar, never vertex buffers.
const headMaterial = (alpha) =>
new Cesium.Material({
fabric: {
type: 'TransitTrailHead',
uniforms: {
color: new Cesium.Color(0.37, 0.94, 0.54, alpha),
fraction: 0,
backing: true,
},
source: `czm_material czm_getMaterial(czm_materialInput materialInput) {
if (materialInput.st.s > fraction) discard;
czm_material m = czm_getDefaultMaterial(materialInput);
bool edge = abs(materialInput.st.t - 0.5) > 0.3;
m.diffuse = czm_gammaCorrect(vec4(edge && backing ? vec3(0.02, 0.03, 0.05) : color.rgb, 1.0)).rgb;
m.alpha = color.a;
return m;
}`,
},
translucent: true,
});
const material = headMaterial(0.8),
depthMaterial = headMaterial(0.55);
depthMaterial.uniforms.backing = false;
const head = { positions: [], show: false, width: 3, material };
/** The backing lane's colour, under the mode colour. */
const BACKING = [0.02, 0.03, 0.05];
/** Alpha of the head, and of a body segment the vehicle has just passed. */
const HEAD_ALPHA = 0.8;
const WHITE = [1, 1, 1, 1];
/** The two lanes, drawn in this order: the backing, then the line. */
const LANES = [
{ name: 'backing', widthPx: 5, dark: true },
{ name: 'line', widthPx: 3, dark: false },
];
/** Uniquifier for each renderer's set ids. */
let trailSeq = 0;
const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;
/**
* The history as runs of joined segments (each segment starting where the
* one before it ends), so each lane is a few lines rather than one a
* segment. `first` is the index of the run's first segment; a segment with
* no length ends a run.
*/
function runsOf(segments) {
const runs = [];
let run = null;
for (let i = 0; i < segments.length; i++) {
const [from, to] = segments[i].positions;
if (!from || !to) run = null;
else if (run && samePoint(run.positions.at(-1), from))
run.positions.push(to);
else runs.push((run = { first: i, positions: [from, to] }));
}
return runs;
}
/**
* The trail renderer of one selection, over `viewer`'s draw port. Never
* entities; nothing it draws takes part in picks.
* @param {object} viewer
*/
export function createContactTrailRenderer(viewer) {
const draw = findDraw(viewer);
const prefix = `transit-trail:${++trailSeq}`;
const body = draw?.lines({ id: `${prefix}:body`, pickable: false }) ?? null;
const headLines =
draw?.lines({ id: `${prefix}:head`, pickable: false, show: false }) ?? null;
/** What the head draws now, for diagnostics: its start to the vehicle. */
const endpoint = { x: 0, y: 0, z: 0 };
const headPositions = [null, endpoint];
const head = { positions: [], show: false, width: 3 };
const backing = { positions: [], show: false, width: 5 };
let headPrimitive = null,
headRebuilds = 0;
function geometry(positions, width, material = false) {
return ground
? new Cesium.GroundPolylineGeometry({ positions, width, granularity: 0 })
: new Cesium.PolylineGeometry({
positions,
width,
arcType: Cesium.ArcType.NONE,
vertexFormat: material
? Cesium.PolylineMaterialAppearance.VERTEX_FORMAT
: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
});
}
function primitive(instances, appearance, depthFailAppearance) {
return ground
? new Cesium.GroundPolylinePrimitive({
geometryInstances: instances,
appearance,
classificationType: Cesium.ClassificationType.BOTH,
allowPicking: false,
asynchronous: true,
show: visible,
})
: new Cesium.Primitive({
geometryInstances: instances,
appearance,
depthFailAppearance,
allowPicking: false,
asynchronous: false,
show: visible,
});
}
let body = null,
segments = [],
let segments = [],
runs = [],
revision = -1,
visible = true,
style = '#5EF08A';
style = '#5EF08A',
styleColor = cssColor(style).slice(0, 3);
let lastSecond = -1,
completed = -1,
active = null;
const styleColor = Cesium.Color.fromCssColorString(style);
const attributeIds = [];
const color = new Cesium.Color(),
endpoint = new Cesium.Cartesian3();
const headPositions = [new Cesium.Cartesian3(), endpoint];
let rebuilds = 0;
function tint(alpha, dark = false) {
if (dark) {
color.red = 0.02;
color.green = 0.03;
color.blue = 0.05;
} else Cesium.Color.clone(styleColor, color);
color.alpha = alpha;
return color;
active = null,
revealed = -1,
restyled = false;
let rebuilds = 0,
headRebuilds = 0;
const tint = (alpha, dark) => [...(dark ? BACKING : styleColor), alpha];
/** The body's lines: each lane's runs, segments shown up to `done`. */
function bodyLines(displayT, done) {
const lines = [];
for (const lane of LANES)
for (let r = 0; r < runs.length; r++) {
const run = runs[r];
const count = run.positions.length - 1;
const segmentColors = new Array(count);
const segmentShow = new Array(count);
for (let k = 0; k < count; k++) {
const i = run.first + k;
const alpha =
displayT === null
? HEAD_ALPHA
: trailAlpha(displayT - segments[i].toT);
segmentColors[k] = tint(alpha, lane.dark);
segmentShow[k] = i <= done;
}
lines.push({
id: `${lane.name}:${r}`,
positions: run.positions,
widthPx: lane.widthPx,
mode: 'draped',
clampTo: 'both',
// Every segment has its own colour: the line's own never
// changes, so a new mode colour is written in place.
style: { kind: 'solid', color: lane.dark ? [...BACKING, 1] : WHITE },
segmentColors,
segmentShow,
});
}
return lines;
}
/** The head's lines over `segment`, revealed to `fraction`. */
function headItems(segment, fraction) {
return LANES.map((lane) => ({
id: lane.name,
positions: segment.positions,
widthPx: lane.widthPx,
mode: 'draped',
clampTo: 'both',
style: { kind: 'solid', color: tint(HEAD_ALPHA, lane.dark) },
revealFraction: fraction,
}));
}
// Written only when it changes: a renderer may redraw for each write.
function showHead(show) {
head.show = backing.show = show;
if (headLines && headLines.show !== show) headLines.show = show;
}
function replaceHistory(next) {
if (next.revision === revision) return;
revision = next.revision;
@@ -115,51 +161,22 @@ export function createContactTrailRenderer(scene) {
completed = -1;
lastSecond = -1;
active = null;
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = null;
head.show = backing.show = false;
if (body) collection.remove(body);
body = null;
const instances = [];
attributeIds.length = 0;
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
attributeIds.push([`${i}:0`, `${i}:1`]);
if (segment.positions.length < 2) continue;
for (let lane = 0; lane < 2; lane++) {
instances.push(
new Cesium.GeometryInstance({
id: `${i}:${lane}`,
geometry: geometry(segment.positions, lane ? 3 : 5),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.8, !lane),
),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.55),
),
show: new Cesium.ShowGeometryInstanceAttribute(false),
},
}),
);
}
}
if (instances.length) {
body = collection.add(
primitive(
instances,
new Cesium.PolylineColorAppearance({ translucent: true }),
new Cesium.PolylineColorAppearance({ translucent: true }),
),
);
rebuilds++;
revealed = -1;
showHead(false);
headLines?.clear();
runs = runsOf(segments);
if (!body) return;
if (!runs.length) {
body.clear();
return;
}
body.set(bodyLines(null, -1));
rebuilds++;
}
function setDisplaySample(sample, renderedPosition) {
if (!sample || !renderedPosition) {
head.show = false;
backing.show = false;
if (headPrimitive) headPrimitive.show = false;
showHead(false);
return;
}
const second = Math.floor(sample.displayT / 1000);
@@ -179,114 +196,67 @@ export function createContactTrailRenderer(scene) {
candidate.toSeq === sample.toSeq
? candidate
: null;
if (body?.ready && done !== completed) {
for (
let i = Math.min(done, completed) + 1;
i <= Math.max(done, completed);
i++
) {
for (let lane = 0; lane < 2; lane++) {
const attributes = body.getGeometryInstanceAttributes(
attributeIds[i][lane],
);
if (!attributes) continue;
// Cesium getters return copies. Write back the array we changed.
const show = attributes.show;
show[0] = i <= done ? 1 : 0;
attributes.show = show;
}
}
// Passed segments show, and every segment fades with its age, once a
// second; the port writes only the segments that change.
if (body && runs.length && (done !== completed || second !== lastSecond)) {
body.upsert(bodyLines(sample.displayT, done));
completed = done;
}
if (body?.ready && second !== lastSecond) {
for (let i = 0; i < segments.length; i++) {
const alpha = trailAlpha(sample.displayT - segments[i].toT);
for (let lane = 0; lane < 2; lane++) {
const attributes = body.getGeometryInstanceAttributes(
attributeIds[i][lane],
);
if (!attributes) continue;
const rgba = attributes.color;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(alpha, !lane),
rgba,
);
attributes.color = rgba;
if (!ground) {
const depthRgba = attributes.depthFailColor;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(0.55),
depthRgba,
);
attributes.depthFailColor = depthRgba;
}
}
}
lastSecond = second;
}
const show = visible && !!segment && sample.fraction < 1;
head.show = show;
backing.show = show;
if (headPrimitive) headPrimitive.show = show;
const show =
visible &&
!!segment?.positions[0] &&
!!segment.positions[1] &&
sample.fraction < 1;
showHead(show);
if (!show) return;
if (active !== segment) {
active = segment;
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = collection.add(
primitive(
new Cesium.GeometryInstance({
geometry: geometry(segment.positions, 5, true),
}),
new Cesium.PolylineMaterialAppearance({
material,
translucent: true,
}),
new Cesium.PolylineMaterialAppearance({
material: depthMaterial,
translucent: true,
}),
),
);
headRebuilds++;
headPositions[0] = segment.positions[0];
headPositions[1] = endpoint;
}
Cesium.Cartesian3.clone(renderedPosition, endpoint);
head.positions = headPositions;
backing.positions = headPositions;
material.uniforms.fraction = Math.max(
const fraction = Math.max(
0,
Math.min(
1,
(sample.displayT - segment.fromT) / (segment.toT - segment.fromT),
),
);
depthMaterial.uniforms.fraction = material.uniforms.fraction;
Cesium.Color.clone(tint(0.8), material.uniforms.color);
Cesium.Color.clone(tint(0.55), depthMaterial.uniforms.color);
if (active !== segment || restyled) {
if (active !== segment) headRebuilds++;
active = segment;
restyled = false;
revealed = fraction;
headLines?.set(headItems(segment, fraction));
} else if (fraction !== revealed) {
revealed = fraction;
headLines?.upsert(headItems(segment, fraction));
}
headPositions[0] = segment.positions[0];
endpoint.x = renderedPosition.x;
endpoint.y = renderedPosition.y;
endpoint.z = renderedPosition.z;
head.positions = backing.positions = headPositions;
}
return {
replaceHistory,
setDisplaySample,
setStyle(next) {
if (next === style) return;
style = next;
Cesium.Color.fromCssColorString(style, styleColor);
styleColor = cssColor(style)?.slice(0, 3) ?? styleColor;
// Faded again in the new colour on the next sample, and the head
// drawn in it.
lastSecond = -1;
restyled = true;
},
setVisible(next) {
visible = next;
if (headPrimitive) headPrimitive.show = next && head.show;
if (body) body.show = next;
if (body && body.show !== next) body.show = next;
if (!next) showHead(false);
},
destroy() {
if (body) collection.remove(body);
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = null;
material.destroy();
depthMaterial.destroy();
body = null;
body?.dispose();
headLines?.dispose();
segments = [];
runs = [];
active = null;
},
diagnostics() {
return {
@@ -294,13 +264,11 @@ export function createContactTrailRenderer(scene) {
rebuilds,
segments: segments.length,
body,
headLines,
head,
backing,
headPrimitive,
headStrategy: ground
? 'draped corridor with material clip'
: 'depth-fail corridor with material clip',
ground,
headStrategy: 'draped lines revealed to the vehicle',
ground: !!draw,
headRebuilds,
entitiesAdded: 0,
};