feat: add cesium traffic signal countdowns
This commit is contained in:
@@ -41,7 +41,7 @@
|
||||
setLoadingMessage("Loading model", config.glbName || "");
|
||||
const assets = await loadSceneAssets(viewer, metadata, placement);
|
||||
const trafficStart = Cesium.JulianDate.now();
|
||||
const trafficSignals = addTrafficSignals(viewer, signalData, trafficStart);
|
||||
const trafficSignals = addTrafficSignals(viewer, signalData, trafficStart, assets);
|
||||
const cruise = addVehicleCruises(viewer, routeData, signalData, trafficStart, config.vehicleModelNames, config.vehicleModelName);
|
||||
const cameras = createCameraPresets(viewer, metadata, placement, cruise);
|
||||
|
||||
@@ -297,7 +297,7 @@
|
||||
toggleVehicles.addEventListener("change", () => {
|
||||
for (const vehicle of cruise.vehicles) vehicle.entity.show = toggleVehicles.checked;
|
||||
});
|
||||
if (!trafficSignals.entities.length) {
|
||||
if (!trafficSignals.count) {
|
||||
signalsControl.classList.add("hidden");
|
||||
} else {
|
||||
toggleSignals.addEventListener("change", () => {
|
||||
@@ -464,145 +464,91 @@
|
||||
};
|
||||
}
|
||||
|
||||
function addTrafficSignals(viewer, signalData, start) {
|
||||
const anchors = (signalData?.signals || []).filter((signal) => Number.isFinite(signal.longitude) && Number.isFinite(signal.latitude));
|
||||
const entities = [];
|
||||
for (const signal of anchors) {
|
||||
const mastReach = Number(signal.mastReachMeters) || 4.5;
|
||||
const countdownOffset = -1.15;
|
||||
const polePosition = signalPosition(signal, 0, 0, 3.35);
|
||||
const headPosition = signalPosition(signal, 0, -mastReach, 6.25);
|
||||
const frame = signalHeadFrame(signal, headPosition);
|
||||
const pole = viewer.entities.add({
|
||||
position: polePosition,
|
||||
cylinder: { length: 6.7, topRadius: 0.10, bottomRadius: 0.14, material: Cesium.Color.fromCssColorString("#273139") },
|
||||
});
|
||||
// The mast arm begins at the curbside pole and reaches above the approach
|
||||
// lanes. A separate mast at the opposite approach controls oncoming cars.
|
||||
const arm = viewer.entities.add({
|
||||
polyline: {
|
||||
positions: [signalPosition(signal, 0, 0, 6.25), headPosition],
|
||||
width: 9,
|
||||
material: Cesium.Color.fromCssColorString("#273139"),
|
||||
arcType: Cesium.ArcType.NONE,
|
||||
},
|
||||
});
|
||||
const head = viewer.entities.add({
|
||||
position: headPosition,
|
||||
orientation: frame.orientation,
|
||||
box: { dimensions: new Cesium.Cartesian3(0.68, 0.30, 1.62), material: Cesium.Color.fromCssColorString("#182024") },
|
||||
});
|
||||
entities.push(pole, arm, head);
|
||||
for (const [index, state] of ["red", "yellow", "green"].entries()) {
|
||||
const bulb = viewer.entities.add({
|
||||
// The lens sits on the explicit approach-facing normal of the head,
|
||||
// not at an angle inferred from the box's local axes.
|
||||
position: signalLensPosition(headPosition, frame, 0.18, 0.49 - index * 0.50),
|
||||
ellipsoid: {
|
||||
radii: new Cesium.Cartesian3(0.22, 0.22, 0.22),
|
||||
material: new Cesium.ColorMaterialProperty(new Cesium.CallbackProperty((time) => signalColor(signal.phaseGroup, state, time, start), false)),
|
||||
},
|
||||
});
|
||||
entities.push(bulb);
|
||||
}
|
||||
// The countdown board mounts on the mast between the head and pole,
|
||||
// rather than protruding beyond the signal on the roadway side.
|
||||
const counterPosition = signalPanelPosition(headPosition, frame, countdownOffset, 0.05, 0);
|
||||
const counter = viewer.entities.add({
|
||||
position: counterPosition,
|
||||
orientation: frame.orientation,
|
||||
box: {
|
||||
dimensions: new Cesium.Cartesian3(0.82, 0.14, 0.56),
|
||||
material: Cesium.Color.fromCssColorString("#251f1c"),
|
||||
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 220),
|
||||
},
|
||||
});
|
||||
const countdown = createSevenSegmentCountdown(
|
||||
viewer,
|
||||
signal,
|
||||
start,
|
||||
headPosition,
|
||||
frame,
|
||||
countdownOffset,
|
||||
);
|
||||
entities.push(counter, ...countdown);
|
||||
function addTrafficSignals(viewer, signalData, start, assets) {
|
||||
const dynamic = assets.find((asset) => asset.category === "dynamic" && asset.model);
|
||||
const countdownModels = new Map(assets
|
||||
.filter((asset) => asset.category === "countdown" && asset.model)
|
||||
.map((asset) => [Number(asset.phaseGroup), asset.model]));
|
||||
if (dynamic && countdownModels.size === 2) {
|
||||
const signals = (signalData?.signals || []).filter((signal) => signal && signal.id);
|
||||
if (signals.length && !viewer.clock.shouldAnimate) viewer.clock.shouldAnimate = true;
|
||||
const visualStart = performance.now();
|
||||
const phaseTime = new Cesium.JulianDate();
|
||||
const state = { elapsedSeconds: 0, phase: "" };
|
||||
const entities = [];
|
||||
const nodes = new Map();
|
||||
const node = (name) => {
|
||||
if (nodes.has(name)) return nodes.get(name);
|
||||
let value = null;
|
||||
try {
|
||||
value = dynamic.model.getNode(name);
|
||||
} catch (error) {
|
||||
console.warn("Traffic signal node unavailable:", name, error);
|
||||
}
|
||||
// Do not cache a miss. Cesium can expose the Model before its node
|
||||
// lookup table is populated; a transient miss must be retried on the
|
||||
// next clock tick rather than freezing the initial visual state.
|
||||
if (value) nodes.set(name, value);
|
||||
return value;
|
||||
};
|
||||
const update = (elapsedSeconds) => {
|
||||
Cesium.JulianDate.addSeconds(start, elapsedSeconds, phaseTime);
|
||||
let changed = false;
|
||||
const groupPhases = new Map();
|
||||
for (const signal of signals) {
|
||||
const phase = signalPhase(signal.phaseGroup, phaseTime, start);
|
||||
groupPhases.set(signal.phaseGroup, phase.active);
|
||||
if (signal === signals[0]) state.phase = `${phase.active} ${String(phase.remaining).padStart(2, "0")}`;
|
||||
for (const state of ["red", "yellow", "green"]) {
|
||||
const value = node(`TrafficSignalDynamic_${signal.id}_${state}`);
|
||||
if (value && value.show !== (state === phase.active)) {
|
||||
value.show = state === phase.active;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const visibleCountdown = String(phase.remaining).padStart(2, "0");
|
||||
const countdownModel = countdownModels.get(Number(signal.phaseGroup));
|
||||
for (let value = 0; value < 20; value += 1) {
|
||||
const name = `TrafficSignalDynamic_${signal.id}_countdown_${String(value).padStart(2, "0")}`;
|
||||
let countdown = null;
|
||||
try { countdown = countdownModel.getNode(name); } catch (error) { /* model node table is still loading */ }
|
||||
if (countdown && countdown.show !== (String(value).padStart(2, "0") === visibleCountdown)) {
|
||||
countdown.show = String(value).padStart(2, "0") === visibleCountdown;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [group, active] of groupPhases) {
|
||||
const countdownModel = countdownModels.get(Number(group));
|
||||
countdownModel.color = signalBaseColor(active);
|
||||
countdownModel.colorBlendMode = Cesium.ColorBlendMode.REPLACE;
|
||||
countdownModel.colorBlendAmount = 1.0;
|
||||
}
|
||||
if (changed && viewer.scene.requestRender) viewer.scene.requestRender();
|
||||
};
|
||||
let lastSecond = -1;
|
||||
const render = () => {
|
||||
const elapsedSeconds = Math.floor((performance.now() - visualStart) / 1000);
|
||||
if (elapsedSeconds === lastSecond) return;
|
||||
lastSecond = elapsedSeconds;
|
||||
state.elapsedSeconds = elapsedSeconds;
|
||||
update(elapsedSeconds);
|
||||
};
|
||||
// Keep signal phases independent from the Cesium simulation clock. The
|
||||
// clock may be paused while a user inspects the scene, but the lights and
|
||||
// countdown must remain visibly periodic.
|
||||
const timer = setInterval(render, 250);
|
||||
render();
|
||||
return {
|
||||
entities, count: signals.length, dynamic, state, timer,
|
||||
set show(value) {
|
||||
dynamic.model.show = value;
|
||||
for (const model of countdownModels.values()) model.show = value;
|
||||
for (const entity of entities) entity.show = value;
|
||||
}
|
||||
};
|
||||
}
|
||||
return {
|
||||
entities,
|
||||
count: anchors.length,
|
||||
set show(value) { for (const entity of entities) entity.show = value; },
|
||||
};
|
||||
}
|
||||
|
||||
function signalPosition(signal, longitudinalMeters, lateralMeters, height) {
|
||||
const heading = Cesium.Math.toRadians(signal.headingDegrees);
|
||||
const latitude = signal.latitude + (longitudinalMeters * Math.cos(heading) - lateralMeters * Math.sin(heading)) / 110540;
|
||||
const longitude = signal.longitude + (longitudinalMeters * Math.sin(heading) + lateralMeters * Math.cos(heading)) /
|
||||
(111320 * Math.cos(Cesium.Math.toRadians(signal.latitude)));
|
||||
return Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
|
||||
}
|
||||
|
||||
function signalHeadFrame(signal, position) {
|
||||
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position);
|
||||
// headingDegrees is the approach's travel direction into the junction.
|
||||
// The signal's front must point back toward that approaching traffic.
|
||||
const heading = Cesium.Math.toRadians(signal.headingDegrees);
|
||||
const localFace = new Cesium.Cartesian3(-Math.sin(heading), -Math.cos(heading), 0);
|
||||
const face = Cesium.Matrix4.multiplyByPointAsVector(enu, localFace, new Cesium.Cartesian3());
|
||||
Cesium.Cartesian3.normalize(face, face);
|
||||
const up = Cesium.Cartesian3.normalize(position, new Cesium.Cartesian3());
|
||||
const across = Cesium.Cartesian3.cross(face, up, new Cesium.Cartesian3());
|
||||
Cesium.Cartesian3.normalize(across, across);
|
||||
const rotation = new Cesium.Matrix3(
|
||||
across.x, face.x, up.x,
|
||||
across.y, face.y, up.y,
|
||||
across.z, face.z, up.z,
|
||||
);
|
||||
return { across, face, up, orientation: Cesium.Quaternion.fromRotationMatrix(rotation, new Cesium.Quaternion()) };
|
||||
}
|
||||
|
||||
function signalLensPosition(headPosition, frame, faceOffset, verticalOffset) {
|
||||
const point = Cesium.Cartesian3.multiplyByScalar(frame.face, faceOffset, new Cesium.Cartesian3());
|
||||
Cesium.Cartesian3.add(headPosition, point, point);
|
||||
const vertical = Cesium.Cartesian3.multiplyByScalar(frame.up, verticalOffset, new Cesium.Cartesian3());
|
||||
return Cesium.Cartesian3.add(point, vertical, point);
|
||||
}
|
||||
|
||||
function signalPanelPosition(headPosition, frame, acrossOffset, faceOffset, verticalOffset) {
|
||||
const point = signalLensPosition(headPosition, frame, faceOffset, verticalOffset);
|
||||
const across = Cesium.Cartesian3.multiplyByScalar(frame.across, acrossOffset, new Cesium.Cartesian3());
|
||||
return Cesium.Cartesian3.add(point, across, point);
|
||||
}
|
||||
|
||||
function createSevenSegmentCountdown(viewer, signal, start, headPosition, frame, boardAcross) {
|
||||
const digitMap = { "0": "abcedf", "1": "bc", "2": "abged", "3": "abgcd", "4": "fgbc", "5": "afgcd", "6": "afgecd", "7": "abc", "8": "abcdefg", "9": "abfgcd" };
|
||||
const shape = {
|
||||
a: [0, 0.18, 0.20, 0.025, 0.035], b: [0.10, 0.085, 0.035, 0.025, 0.15],
|
||||
c: [0.10, -0.085, 0.035, 0.025, 0.15], d: [0, -0.18, 0.20, 0.025, 0.035],
|
||||
e: [-0.10, -0.085, 0.035, 0.025, 0.15], f: [-0.10, 0.085, 0.035, 0.025, 0.15],
|
||||
g: [0, 0, 0.20, 0.025, 0.035],
|
||||
};
|
||||
const result = [];
|
||||
for (const [digitIndex, digitAcross] of [-0.17, 0.17].entries()) {
|
||||
for (const [name, [x, z, width, depth, height]] of Object.entries(shape)) {
|
||||
result.push(viewer.entities.add({
|
||||
// The visible panel x-axis is the inverse of the signal frame's
|
||||
// across axis. Mirror the LED layout once here to keep digits normal.
|
||||
position: signalPanelPosition(headPosition, frame, boardAcross - digitAcross - x, 0.18, z),
|
||||
orientation: frame.orientation,
|
||||
box: {
|
||||
dimensions: new Cesium.Cartesian3(width, depth, height),
|
||||
material: new Cesium.ColorMaterialProperty(new Cesium.CallbackProperty((time) => signalActiveColor(signal.phaseGroup, time, start), false)),
|
||||
show: new Cesium.CallbackProperty((time) => {
|
||||
const value = String(signalPhase(signal.phaseGroup, time, start).remaining).padStart(2, "0")[digitIndex];
|
||||
return (digitMap[value] || "").includes(name);
|
||||
}, false),
|
||||
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 220),
|
||||
},
|
||||
}));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
return { entities: [], count: 0, set show(value) {} };
|
||||
}
|
||||
|
||||
function signalColor(group, state, time, start) {
|
||||
@@ -620,7 +566,11 @@
|
||||
}
|
||||
|
||||
function signalPhase(group, time, start) {
|
||||
const second = ((Cesium.JulianDate.secondsDifference(time, start) % 20) + 20) % 20;
|
||||
return signalPhaseAtElapsed(group, Cesium.JulianDate.secondsDifference(time, start));
|
||||
}
|
||||
|
||||
function signalPhaseAtElapsed(group, elapsed) {
|
||||
const second = ((elapsed % 20) + 20) % 20;
|
||||
if (group === 0) {
|
||||
if (second < 8) return { active: "green", remaining: Math.ceil(8 - second) };
|
||||
if (second < 10) return { active: "yellow", remaining: Math.ceil(10 - second) };
|
||||
|
||||
Reference in New Issue
Block a user