From 7ce412e52e03c33e280b5c24e8671be25e93d6f0 Mon Sep 17 00:00:00 2001 From: que01 Date: Sat, 10 Oct 2026 16:07:00 +0800 Subject: [PATCH] feat: add participant runtime simulation with traffic signal scheduling - Implement deterministic participant simulation in cesium-preview.js with fixed-seed arrival, IDM car-following, stop-line constraints, and geometric conflict occupancy detection - Build native traffic simulation participants from road package data including signal phase mapping, crosswalk centerlines, and lane routing - Add participant runtime regression test covering 600 s simulation, green-only releases, and 2D bounding box overlap checks - Update model URI prefix to _preview/ so simulation JSON resolves assets relative to area output directory - Sync Trellis spec and task docs for participant scheduling contract --- .trellis/spec/preview/vehicle-routes.md | 11 + .../design.md | 4 + .../08-24-v2x-realtime-cross-fidelity/prd.md | 2 +- package.json | 1 + scripts/build-area.js | 5 +- scripts/lib/cesium-preview.js | 600 +++++++++++++- .../lib/native-preview-traffic-simulation.js | 750 +++++++++++++++++- scripts/test-native-preview-traffic.js | 57 +- scripts/test-participant-runtime.js | 176 ++++ scripts/test-preview-assets.js | 24 +- 10 files changed, 1587 insertions(+), 43 deletions(-) create mode 100644 scripts/test-participant-runtime.js diff --git a/.trellis/spec/preview/vehicle-routes.md b/.trellis/spec/preview/vehicle-routes.md index d5eb522..8fceea6 100644 --- a/.trellis/spec/preview/vehicle-routes.md +++ b/.trellis/spec/preview/vehicle-routes.md @@ -100,6 +100,17 @@ if (oneway !== "-1") edges.push(makeEdge(way, refs, coords, "forward")); if (!isOneWay(oneway)) edges.push(makeEdge(way, [...refs].reverse(), [...coords].reverse(), "backward")); ``` +## 本地参与者调度校验 + +`scripts/lib/cesium-preview.js:createParticipantSimulation()` 使用固定种子的间隔到达、IDM 跟驰、 +进口停止线约束和几何冲突占用。排队及占用检测仅包含已到达且仍活动的参与者;首次放行必须 +同时更新路程和 committed 状态。进入路口后不再服从出口方向的信号灯,但仍让行前方过街者。 +行人及自行车仅在配对方向红灯且剩余时间足够完成过街时进入,启动全红不放行过街者。 + +回归命令:`npm run test:participant-runtime`。可传真实生成数据进行 600 秒的放行、通行完成 +及二维包围盒重叠检查:`node scripts/test-participant-runtime.js outputs/fengshu-er-road/_preview/fengshu-er-road-traffic-simulation.json`。 +这是展示级调度校验,不代替 GLB 模型实际外形、车身原点和浏览器渲染的检查。 + ## 信号动态 GLB 契约 `traffic_signals.json` 的 `pose.*` 是 Blender 静态设施、动态灯珠和倒计时共享的锚点。Blender diff --git a/.trellis/tasks/08-24-v2x-realtime-cross-fidelity/design.md b/.trellis/tasks/08-24-v2x-realtime-cross-fidelity/design.md index 2fbaef6..cfd07f9 100644 --- a/.trellis/tasks/08-24-v2x-realtime-cross-fidelity/design.md +++ b/.trellis/tasks/08-24-v2x-realtime-cross-fidelity/design.md @@ -184,6 +184,10 @@ registry.list() -> VehicleRecord[] 平滑:用 `Cesium.SampledPositionProperty` 按 `duration` 插值,替代当前的直接赋值跳变。 +模型资产闭包:dashboard 的车辆模型已复制到本项目 `assets/models/v2x-vehicles/`,由 +`scripts/lib/vehicle-library.js` 构建时复制到输出预览目录。运行时不访问 +`/Users/que01/Project/wbza_web`;外部 dashboard 仅作为模型来源与契约参考。 + ### 4.5 宽松解析(R9) 源项目用 `saferEval`。浏览器端零依赖不能引入该库,也不应引入 `eval`。改为 diff --git a/.trellis/tasks/08-24-v2x-realtime-cross-fidelity/prd.md b/.trellis/tasks/08-24-v2x-realtime-cross-fidelity/prd.md index 3c7faf5..342d77d 100644 --- a/.trellis/tasks/08-24-v2x-realtime-cross-fidelity/prd.md +++ b/.trellis/tasks/08-24-v2x-realtime-cross-fidelity/prd.md @@ -59,7 +59,7 @@ ### R8 车辆模型命名与资产对齐 - OBU 数据层标记为 `car_obu.glb`,但 dashboard 的实际 `CrossCars` 模板固定渲染 `11.glb`;预览必须遵从该最终渲染契约。目标识别车辆使用 `${type}${subType}.glb`。 -- 预览包必须携带 dashboard 实际使用的车辆模型;包内缺少未知车型时回退到 `11.glb`,并在面板提示,不得静默显示错误车型。 +- 预览包必须携带已复制到本项目 `assets/models/v2x-vehicles/` 的 dashboard 实际使用车辆模型;构建和运行时不得读取 dashboard 外部路径。包内缺少未知车型时回退到 `11.glb`,并在面板提示,不得静默显示错误车型。 ### R9 推送体解析健壮性 - 源项目对两个车辆 socket 使用 `saferEval` 而非 `JSON.parse`,说明载荷不保证严格 JSON。 diff --git a/package.json b/package.json index 88bfaab..913f4c2 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "test:turn-lane-arrows": "node scripts/test-turn-lane-arrows.js", "test:traffic-signals": "node scripts/test-traffic-signals.js", "test:native-preview-traffic": "node scripts/test-native-preview-traffic.js", + "test:participant-runtime": "node scripts/test-participant-runtime.js", "test:v2x-preview-server": "node scripts/test-v2x-preview-server.js", "test:v2x-cesium-preview": "node scripts/test-v2x-cesium-overlay.js", "render:turn-lane-arrow-samples": "node scripts/render-turn-lane-arrow-samples.js" diff --git a/scripts/build-area.js b/scripts/build-area.js index 48458d7..52d53a3 100755 --- a/scripts/build-area.js +++ b/scripts/build-area.js @@ -571,7 +571,10 @@ function writeCesiumPreview(area, roadProvider) { } else { const nativePackage = importNativeRoadPackage(area); Object.assign(previewInputs, nativeRoadRecords(nativePackage)); - const simulation = buildNativeTrafficSimulation(area, { nativePackage }); + // The simulation JSON is loaded by the preview HTML, so model URIs must + // be relative to the area output (where `_preview/` is the asset root), + // not relative to the repository's source asset directory. + const simulation = buildNativeTrafficSimulation(area, { nativePackage, modelPrefix: "_preview/" }); fs.mkdirSync(path.dirname(area.outputs.trafficSimulation), { recursive: true }); fs.writeFileSync(area.outputs.trafficSimulation, `${JSON.stringify(simulation, null, 2)}\n`); routeArtifact = area.outputs.trafficSimulation; diff --git a/scripts/lib/cesium-preview.js b/scripts/lib/cesium-preview.js index f454e24..a06d3bb 100644 --- a/scripts/lib/cesium-preview.js +++ b/scripts/lib/cesium-preview.js @@ -39,7 +39,7 @@ // from a control the user just touched. Keep the summary so the transient // note can be replaced instead of destroying it. let baseStatus = ""; - const PREVIEW_BACKGROUND = "#d9e0e2"; + const PREVIEW_BACKGROUND = "#02050A"; Cesium.Ion.defaultAccessToken = ""; @@ -55,14 +55,16 @@ setLoadingMessage("Loading model", config.glbName || ""); const assets = await loadSceneAssets(viewer, metadata, placement); const trafficStart = Cesium.JulianDate.now(); + const trafficEpochMs = performance.now(); const useLiveV2x = Boolean(config.v2xPreview?.enabled); - const trafficSignals = useLiveV2x - ? createLiveTrafficSignals(signalData, assets) - : addTrafficSignals(viewer, signalData, trafficStart, assets); - if (useLiveV2x) hideUnconfirmedSignalAssets(assets); - const cruise = useLiveV2x - ? createLiveVehicleState() - : addVehicleCruises(viewer, routeData, signalData, trafficStart, config.vehicleModelNames, config.vehicleModelName); + // The native signal cycle is the local fallback and must remain visible + // when the optional V2X overlay has no websocket connection. + const trafficSignals = addTrafficSignals(viewer, signalData, trafficStart, assets, routeData?.signalPlan, trafficEpochMs); + // Keep the deterministic native intersection simulation visible even when + // the optional V2X overlay is enabled. The overlay may add live entities, + // but an unavailable websocket must not replace the local traffic layer + // with an empty state. + const cruise = addVehicleCruises(viewer, routeData, signalData, trafficStart, config.vehicleModelNames, config.vehicleModelName, trafficEpochMs); const cameras = createCameraPresets(viewer, metadata, placement, cruise); const v2xOverlay = typeof window.createV2xCesiumOverlay === "function" ? window.createV2xCesiumOverlay({ @@ -81,6 +83,7 @@ bindVehicleInfoCard(viewer, cruise); startDiagnostics(viewer, metadata, assets, cruise, placement, trafficSignals, v2xOverlay); cameras.overview(); + cameras.startAutoOrbit(); baseStatus = summaryText(metadata, assets, cruise); setStatus(baseStatus); setLoadingMessage("Preparing view", "finalizing materials"); @@ -121,8 +124,8 @@ geocoder: false, navigationHelpButton: false, sceneModePicker: false, - homeButton: true, - fullscreenButton: true, + homeButton: false, + fullscreenButton: false, infoBox: false, selectionIndicator: false, baseLayer: false @@ -135,6 +138,12 @@ viewer.scene.sun.show = false; viewer.scene.moon.show = false; viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString(PREVIEW_BACKGROUND); + viewer.scene.screenSpaceCameraController.enableTranslate = false; + viewer.scene.screenSpaceCameraController.maximumTranslateFactor = 0.0; + viewer.canvas.addEventListener("mousedown", (event) => { + if (event.button === 1 || event.shiftKey) event.preventDefault(); + }); + viewer.canvas.addEventListener("contextmenu", (event) => event.preventDefault()); return viewer; } @@ -436,6 +445,10 @@ !semanticAssets(assets).some((asset) => asset.id === "vegetation")) { toggleBuildingGhost.disabled = true; } + // Keep the intersection readable by default: the building shell is + // translucent while roads, signals and participants remain visible. + toggleBuildingGhost.checked = !toggleBuildingGhost.disabled; + if (toggleBuildingGhost.checked) void setBuildingGhost(true); async function setViewMode(nextMode) { if (nextMode === viewMode) return; @@ -565,7 +578,10 @@ return stopFollow; } - function addVehicleCruises(viewer, routeData, signalData, trafficStart, vehicleModelNames, fallbackVehicleModelName) { + function addVehicleCruises(viewer, routeData, signalData, trafficStart, vehicleModelNames, fallbackVehicleModelName, trafficEpochMs) { + if (routeData && Array.isArray(routeData.participants) && routeData.participants.length) { + return addParticipantCruises(viewer, routeData, signalData, trafficStart, trafficEpochMs); + } const segments = ((routeData && (routeData.routes || routeData.segments)) || []) .filter((segment) => segment.coordinates && segment.coordinates.length >= 2) .slice(0, 5); @@ -615,6 +631,492 @@ } } + // --------------------------------------------------------------------------- + // Intersection participants (descriptor v2) + // + // Open routes: agents enter at the approach end, cross the junction, and + // despawn past the exit end, then respawn after a short delay. Vehicles stop + // at their own approach's red signal and follow the leader on the same + // template; pedestrians cross while their paired approach phase is red. + // --------------------------------------------------------------------------- + + function addParticipantCruises(viewer, routeData, signalData, trafficStart, trafficEpochMs) { + const templates = routeData.participants.filter((template) => template.coordinates && template.coordinates.length >= 2); + const speed = Number(routeData.speedMetersPerSecond) || 8; + const start = trafficStart; + const simulation = createParticipantSimulation(viewer, templates, start, speed, routeData.settings || {}, routeData.signalPlan, trafficEpochMs); + + viewer.clock.startTime = start.clone(); + viewer.clock.currentTime = start.clone(); + viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED; + viewer.clock.multiplier = 1; + viewer.clock.shouldAnimate = templates.length > 0; + + const vehicles = simulation.agents.map((agent, index) => { + const template = agent.template; + const routeEntity = viewer.entities.add({ + name: "Participant route " + (index + 1), + polyline: { + positions: Cesium.Cartesian3.fromDegreesArrayHeights( + template.coordinates.flatMap((coord) => [coord[0], coord[1], ROUTE_LINE_HEIGHT_METERS]) + ), + width: 2, + material: participantRouteColor(index), + arcType: Cesium.ArcType.NONE, + clampToGround: false + } + }); + routeEntity.show = false; + const entity = viewer.entities.add({ + name: "Participant " + (index + 1), + position: agent.positions, + orientation: openRouteOrientationFromState(agent.route, agent.state, agent.speed, template.headingOffsetDegrees || 0), + model: { + uri: template.modelName, + scale: Number(template.modelScale) || 1.0, + minimumPixelSize: 0 + }, + show: false + }); + agent.entity = entity; + const record = { + id: "participant-" + (index + 1), + entity, + routeEntity, + positions: agent.positions, + route: agent.route, + segment: { lengthMeters: template.lengthMeters, maneuvers: template.turn ? [template.turn] : [] }, + label: participantLabel(template, index), + modelName: template.modelName.split("/").pop(), + status: "normal", + incidentNote: "", + motion: agent, + routeColor: participantRouteColor(index), + markerEntity: null, + }; + entity.properties = new Cesium.PropertyBag({ vehicleId: record.id }); + record.markerEntity = viewer.entities.add({ + name: "Participant incident marker " + (index + 1), + position: agent.positions, + billboard: { + image: "", + show: false, + width: 36, + height: 44, + pixelOffset: new Cesium.Cartesian2(0, -40), + verticalOrigin: Cesium.VerticalOrigin.BOTTOM, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); + const option = document.createElement("option"); + option.value = String(index); + option.textContent = record.label; + vehicleSelect.appendChild(option); + return record; + }); + const cruise = { + vehicles, + baseSpeed: speed, + state: { selectedIndex: 0 }, + simulation, + usingLiveData: false, + }; + syncSelectedRouteVisibility(cruise); + return cruise; + } + + function participantRouteColor(index) { + return [ + Cesium.Color.CYAN, + Cesium.Color.LIME, + Cesium.Color.YELLOW, + Cesium.Color.ORANGE, + Cesium.Color.DEEPSKYBLUE + ][index % 5]; + } + + function participantLabel(template, index) { + const kindLabel = { vehicle: "", motorcycle: "摩托 · ", bicycle: "骑行 · ", pedestrian: "行人 · " }[template.kind] || ""; + const turn = { left: "左转", right: "右转", through: "直行" }[template.turn]; + return "#" + (index + 1) + " · " + kindLabel + (turn ? turn + " · " : "") + Math.round(template.lengthMeters || 0) + " m"; + } + + function participantRoute(template, reversed) { + const coordinates = reversed ? [...template.coordinates].reverse() : template.coordinates; + const distances = [0.0]; + for (let i = 1; i < coordinates.length; i += 1) { + distances.push(distances[i - 1] + distanceMeters(coordinates[i - 1], coordinates[i])); + } + return { + coordinates, + distances, + length: Math.max(1.0, distances[distances.length - 1]), + // Stops are pre-attached to the template by the generator; reversing a + // route is only used for pedestrians, which carry none. + stops: reversed ? [] : (template.stops || []).map((stop) => ({ + distance: stop.distance, + stopReason: stop.stopReason || "traffic-signal", + signal: { id: stop.signalId, phaseGroup: stop.phaseGroup }, + })), + }; + } + + function createParticipantSimulation(viewer, templates, start, baseSpeed, settings = {}, signalPlan, trafficEpochMs) { + const isCrossing = (agent) => agent.template.kind === "pedestrian" || agent.template.kind === "bicycle"; + const entryDistance = (agent) => isCrossing(agent) ? -agent.length - minimumGapMeters : -120 - agent.length; + const exitDistance = (agent) => agent.route.length + (isCrossing(agent) ? agent.length : 120 + agent.length); + let randomState = 27092026; + function random() { + randomState = (Math.imul(randomState, 1664525) + 1013904223) >>> 0; + return (randomState + 0.5) / 4294967296; + } + function arrivalDelay(agent) { + return (isCrossing(agent) ? 12 : 4) - Math.log(1 - random()) * (isCrossing(agent) ? 18 : 7); + } + const reactionTimeSeconds = Number(settings.reactionTimeSeconds) || 0.8; + const minimumGapMeters = Number(settings.minimumGapMeters) || 6; + const agents = templates.flatMap((template, templateIndex) => { + const count = Math.max(1, Math.round(Number(template.fleet) || 1)) * (template.kind === "vehicle" ? 3 : 1); + return Array.from({ length: count }, (_, index) => { + // Crossing users share the same ordered crosswalk queue. Keeping one + // travel direction avoids head-on overlap between pedestrians and bikes. + const reversed = false; + const route = participantRoute(template, reversed); + const jitter = 0.9 + 0.2 * random(); + const speed = Math.max(0.8, Math.min(14, (Number(template.speedMetersPerSecond) || baseSpeed) * jitter)); + const length = Number(template.vehicleLengthMeters) || (template.kind === "pedestrian" ? 0.8 : 4.6); + const height = Number(template.heightMeters) || 0.4; + const state = { + distance: (template.kind === "pedestrian" || template.kind === "bicycle") ? -length - minimumGapMeters : -120 - length, + // Vehicles must enter the simulation from rest. Starting them at + // cruising speed made the first rendered frame look like a red-light + // violation before the controller had a chance to brake. + speed: 0, + targetSpeed: speed, + stopReason: null, + active: true, + // Stagger entries by a realistic headway so the whole fleet does + // not appear at the stop line in the same simulation second. + spawnDelay: 1 + templateIndex * 0.7 + index * (6 + random() * 5), + committed: false, + respawnDelay: 0, + lastTime: start.clone(), + }; + return { + template, + route, + speed, + length, + height, + headway: 1.2 + random() * 0.6, + state, + positions: new Cesium.CallbackProperty((time, result) => + openRoutePositionAtDistance(route, state.distance, height, result), false), + }; + }); + }); + agents.forEach((agent, index) => { agent.agentIndex = index; }); + const byTemplate = new Map(); + const crossingUsersById = new Map(); + agents.forEach((agent) => { + const queueKey = (agent.template.kind === "pedestrian" || agent.template.kind === "bicycle") + ? (agent.template.crossingId || agent.template) + : (agent.template.approachLaneId || agent.template.id); + if (!byTemplate.has(queueKey)) byTemplate.set(queueKey, []); + byTemplate.get(queueKey).push(agent); + if (agent.template.kind === "pedestrian" || agent.template.kind === "bicycle") { + const crossingId = agent.template.crossingId; + if (!crossingUsersById.has(crossingId)) crossingUsersById.set(crossingId, []); + crossingUsersById.get(crossingId).push(agent); + } + }); + // Queue outside the scene; no participant starts inside a crossing. + for (const [queueKey, peers] of byTemplate) { + if (typeof queueKey !== "string" || peers.length < 2) continue; + peers.sort((a, b) => a.agentIndex - b.agentIndex); + // Crossing users enter from the near edge. Seeding them at the far end + // would mark the whole zebra crossing occupied before the first signal + // phase and make every approach yield indefinitely. + let occupied = 0; + for (const agent of peers) { + agent.state.distance = entryDistance(agent) - occupied; + occupied += agent.length + minimumGapMeters; + } + } + + // Cache geometric conflicts once. Reservations cover only the junction, + // not distant approach lanes. A released movement retains priority until + // its rear clears the shared trajectory. + const movementConflicts = new Map(); + for (const agent of agents.filter((candidate) => !isCrossing(candidate))) { + const entries = []; + for (const other of agents.filter((candidate) => !isCrossing(candidate))) { + if (agent === other || agent.template.approachLaneId === other.template.approachLaneId) continue; + let conflict = null; + for (let i = 0; i < agent.route.coordinates.length; i += 1) { + if (agent.route.distances[i] < (agent.route.stops[0]?.distance || 0) + agent.length + 3) continue; + for (let j = 0; j < other.route.coordinates.length; j += 1) { + if (other.route.distances[j] < (other.route.stops[0]?.distance || 0) + other.length + 3) continue; + if (distanceMeters(agent.route.coordinates[i], other.route.coordinates[j]) < 3.5) { + conflict = { other, distance: agent.route.distances[i], otherDistance: other.route.distances[j] }; + } + } + } + if (conflict) entries.push(conflict); + } + movementConflicts.set(agent, entries); + } + + const update = (clock) => { + const elapsed = Cesium.JulianDate.secondsDifference(clock.currentTime, agents[0]?.state.lastTime || start); + if (!(elapsed > 0) || elapsed > 2) { + for (const agent of agents) Cesium.JulianDate.clone(clock.currentTime, agent.state.lastTime); + return; + } + for (const peers of byTemplate.values()) { + peers.sort((a, b) => a.state.distance - b.state.distance); + } + const trafficElapsed = Math.max(0, (performance.now() - trafficEpochMs) / 1000); + const elapsedFromStart = Cesium.JulianDate.secondsDifference(clock.currentTime, start); + const present = (agent) => agent.state.active && elapsedFromStart >= agent.state.spawnDelay; + const ordered = [...agents].sort((a, b) => b.state.distance - a.state.distance); + for (const agent of ordered) { + const state = agent.state; + Cesium.JulianDate.clone(clock.currentTime, state.lastTime); + const ready = elapsedFromStart >= state.spawnDelay; + if (agent.entity) agent.entity.show = state.active && ready && toggleVehicles.checked; + if (!ready) continue; + if (state.isMoving && !state.isMoving()) { + state.speed = 0; + state.stopReason = "incident"; + continue; + } + if (!state.active) { + state.respawnDelay -= elapsed; + if (state.respawnDelay <= 0) { + const entryBlocked = agents.some((other) => other !== agent && present(other) + && (other.template.approachLaneId || other.template.crossingId) === (agent.template.approachLaneId || agent.template.crossingId) + && other.state.distance < entryDistance(agent) + agent.length + other.length + minimumGapMeters); + if (entryBlocked) continue; + state.active = true; + state.committed = false; + state.distance = entryDistance(agent); + state.speed = 0; + } + continue; + } + const route = agent.route; + const controlStop = route.stops[0] || null; + let target = agent.speed; + let stopReason = null; + let crossingOccupied = false; + let crossingYieldDistance = null; + let boundary = Infinity; + + if (agent.template.kind === "pedestrian" || agent.template.kind === "bicycle") { + // Walk only while the paired approach phase is red; once started, + // finish the crossing regardless of the phase clock. + const group = Number(agent.template.phaseGroup); + const phaseState = Number.isFinite(group) ? signalPhaseAtElapsed(group, trafficElapsed, signalPlan) : null; + const clearanceSeconds = agent.route.length / agent.speed + agent.speed / 1.4 + 3; + const occupiedByVehicle = agents.some((other) => !isCrossing(other) && present(other) + && other.state.committed && (other.template.crossingConflicts || []).some((conflict) => + conflict.crossingId === agent.template.crossingId + // Permission to enter is a reservation until the vehicle's rear + // clears this crossing, including the whole turning movement. + && other.state.distance < conflict.distance + other.length + 3)); + if (!state.committed && (!phaseState || phaseState.active !== "red" || phaseState.initialClearance + || phaseState.remaining < clearanceSeconds || occupiedByVehicle)) { + boundary = -0.5; + stopReason = "pedestrian-signal"; + } + } else { + const conflicts = agent.template.crossingConflicts || []; + for (const conflict of conflicts) { + // A crossing that is already behind the vehicle cannot make it + // stop again. This matters for left turns: after clearing the + // first zebra, a phase change must not freeze the vehicle on the + // downstream approach. + if (!(Number.isFinite(conflict.distance) && conflict.distance > state.distance + 0.25)) continue; + const crossingUsers = crossingUsersById.get(conflict.crossingId) || []; + const occupied = crossingUsers.some((candidate) => present(candidate) && candidate.state.committed + && candidate.state.distance >= 0 + && candidate.state.distance < candidate.route.length + candidate.length); + if (occupied && (crossingYieldDistance === null || conflict.distance < crossingYieldDistance)) { + crossingYieldDistance = conflict.distance; + } + } + crossingOccupied = crossingYieldDistance !== null; + if (crossingOccupied) { + boundary = Math.min(boundary, crossingYieldDistance - agent.length / 2 - 2); + const remaining = crossingYieldDistance - state.distance - 1.0; + const decel = Number(agent.template.decelerationMetersPerSecondSquared) || 3.5; + target = Math.min(target, Math.sqrt(Math.max(0, 2 * decel * Math.max(0, remaining)))); + stopReason = "pedestrian-crossing"; + // Even a vehicle already committed to the junction must yield to + // an occupied zebra crossing; it stops in place, never teleports. + } + if (controlStop && !state.committed) { + const phase = signalPhaseAtElapsed(controlStop.signal.phaseGroup, trafficElapsed, signalPlan).active; + const junctionBlocked = (movementConflicts.get(agent) || []).some((conflict) => present(conflict.other) + && conflict.other.state.committed + && conflict.other.state.distance < conflict.otherDistance + conflict.other.length + 3); + const exitBlocked = agents.some((other) => other !== agent && !isCrossing(other) && present(other) + && other.state.committed && agent.template.exitRoadId && other.template.exitRoadId === agent.template.exitRoadId + && other.state.speed < 0.5 && other.state.distance < other.route.length + other.length + minimumGapMeters); + if (phase !== "green" || crossingOccupied || junctionBlocked || exitBlocked) { + boundary = Math.min(boundary, controlStop.distance); + // Keep the same controlling stop active at and before the line. + // Do not search only for a stop ahead: that made it disappear + // exactly when the vehicle reached it, allowing red-light runs. + const remaining = Math.max(0, controlStop.distance - state.distance); + const decel = Number(agent.template.decelerationMetersPerSecondSquared) || 3.5; + const stoppingSpeed = Math.sqrt(Math.max(0, 2 * decel * Math.max(0, remaining - 0.8))); + target = Math.min(target, stoppingSpeed); + stopReason = junctionBlocked || exitBlocked ? "junction-clearance" : crossingOccupied ? "pedestrian-crossing" : "traffic-signal"; + } + } + if (agent.template.turn && agent.template.turn !== "through" + && state.distance > (controlStop?.distance || 0) && state.distance < route.length * 0.85) { + target = Math.min(target, agent.template.turn === "left" ? 4.5 : 3.5); + } + } + + const queueKey = (agent.template.kind === "pedestrian" || agent.template.kind === "bicycle") + ? (agent.template.crossingId || agent.template) + : (agent.template.approachLaneId || agent.template.id); + const peers = byTemplate.get(queueKey) || []; + let leaderAgent = null; + const leader = peers.filter((candidate) => candidate !== agent && present(candidate) + && candidate.state.distance > state.distance).sort((a, b) => a.state.distance - b.state.distance)[0]; + if (leader) { + leaderAgent = leader; + const centerGap = leader.state.distance - state.distance; + const crossingAgent = agent.template.kind === "pedestrian" || agent.template.kind === "bicycle"; + const gapBuffer = crossingAgent ? 1.5 : minimumGapMeters; + const requiredGap = (leader.length + agent.length) / 2 + gapBuffer + state.speed * reactionTimeSeconds; + if (centerGap < requiredGap + 10) { + target = Math.min(target, Math.max(0, (centerGap - (leader.length + agent.length) / 2 - gapBuffer) / Math.max(reactionTimeSeconds, 0.1))); + if (target < 0.2) stopReason = stopReason || "leader-gap"; + } + } + + state.targetSpeed = target; + const accel = Number(agent.template.accelerationMetersPerSecondSquared) || 1.8; + const decel = Number(agent.template.decelerationMetersPerSecondSquared) || 3.5; + // Intelligent Driver Model: free acceleration plus a speed-dependent + // desired gap. Treat a waiting boundary as a stationary virtual leader. + let gap = boundary - state.distance; + let leaderSpeed = 0; + if (leaderAgent && leaderAgent.state.distance - state.distance - (leaderAgent.length + agent.length) / 2 < gap) { + gap = leaderAgent.state.distance - state.distance - (leaderAgent.length + agent.length) / 2; + leaderSpeed = leaderAgent.state.speed; + } + const desiredGap = (isCrossing(agent) ? 0.5 : 2.5) + Math.max(0, + state.speed * agent.headway + state.speed * (state.speed - leaderSpeed) / (2 * Math.sqrt(accel * decel))); + const acceleration = accel * (1 - (state.speed / Math.max(0.1, target)) ** 4 + - (Number.isFinite(gap) ? (desiredGap / Math.max(0.1, gap)) ** 2 : 0)); + state.speed = Math.max(0, state.speed + Math.max(-decel, Math.min(accel, acceleration)) * elapsed); + let nextDistance = state.distance + Math.max(0, state.speed) * elapsed; + if (leaderAgent) { + const crossingAgent = agent.template.kind === "pedestrian" || agent.template.kind === "bicycle"; + const physicalGap = (leaderAgent.length + agent.length) / 2 + (crossingAgent ? 1.5 : minimumGapMeters); + nextDistance = Math.min(nextDistance, Math.max(state.distance, leaderAgent.state.distance - physicalGap)); + } + if (Number.isFinite(boundary)) { + nextDistance = Math.min(nextDistance, Math.max(state.distance, boundary)); + if (nextDistance >= boundary - 0.05) state.speed = 0; + } + state.distance = nextDistance; + if (controlStop && !state.committed) { + const phase = signalPhaseAtElapsed(controlStop.signal.phaseGroup, trafficElapsed, signalPlan).active; + if (phase === "green" && nextDistance > controlStop.distance) { + state.committed = true; + } + } + if (isCrossing(agent) && state.distance >= 0) state.committed = true; + state.stopReason = state.speed < 0.25 ? stopReason : null; + if (state.distance >= exitDistance(agent)) { + state.active = false; + state.speed = 0; + // Crossing users are occasional arrivals, not a continuous stream. + // Keep the route reusable while leaving a realistic gap between + // successive pedestrians/cyclists. + state.respawnDelay = arrivalDelay(agent); + } + } + }; + viewer.clock.onTick.addEventListener(update); + return { + agents, + settings: { reactionTimeSeconds, minimumGapMeters }, + diagnostics() { + const live = agents.filter((agent) => agent.state.active); + return { + stoppedVehicles: live.filter((agent) => agent.state.stopReason).length, + queueLength: live.filter((agent) => agent.state.stopReason === "leader-gap").length, + activeVehicles: live.length, + pedestrians: live.filter((agent) => agent.template.kind === "pedestrian").length, + }; + }, + }; + } + + // Open-route variant of routePositionAtDistance: no wraparound; distances + // outside [0, length] extrapolate along the first/last segment, and the + // model height comes from the participant template. + function openRoutePositionAtDistance(route, distance, heightMeters, result) { + let index = 1; + while (index < route.distances.length - 1 && route.distances[index] < distance) { + index += 1; + } + const prevDist = route.distances[index - 1]; + const nextDist = route.distances[index]; + const t = nextDist > prevDist ? (distance - prevDist) / (nextDist - prevDist) : 0; + const a = route.coordinates[index - 1]; + const b = route.coordinates[index]; + const lon = a[0] + (b[0] - a[0]) * t; + const lat = a[1] + (b[1] - a[1]) * t; + return Cesium.Cartesian3.fromDegrees(lon, lat, heightMeters, Cesium.Ellipsoid.WGS84, result); + } + + function openRouteOrientationFromState(route, state, speed, yawDegrees) { + const correction = Cesium.Quaternion.fromAxisAngle( + Cesium.Cartesian3.UNIT_Z, + Cesium.Math.toRadians(yawDegrees) + ); + const current = new Cesium.Cartesian3(); + const ahead = new Cesium.Cartesian3(); + const direction = new Cesium.Cartesian3(); + const up = new Cesium.Cartesian3(); + const east = new Cesium.Cartesian3(); + const north = new Cesium.Cartesian3(); + const hpr = new Cesium.HeadingPitchRoll(0.0, 0.0, 0.0); + const base = new Cesium.Quaternion(); + return new Cesium.CallbackProperty((time, result) => { + openRoutePositionAtDistance(route, state.distance, 0, current); + const lookAhead = Math.max(0.8, speed * 0.8); + // Position and heading share the open route's endpoint extrapolation. + // Clamping only the forward sample points behind an exiting vehicle. + openRoutePositionAtDistance(route, state.distance + lookAhead, 0, ahead); + Cesium.Cartesian3.subtract(ahead, current, direction); + if (Cesium.Cartesian3.magnitudeSquared(direction) < 1e-9) return result; + Cesium.Cartesian3.normalize(direction, direction); + Cesium.Cartesian3.normalize(current, up); + Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, up, east); + if (Cesium.Cartesian3.magnitudeSquared(east) < 1e-9) { + Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, east); + } else { + Cesium.Cartesian3.normalize(east, east); + } + Cesium.Cartesian3.cross(up, east, north); + Cesium.Cartesian3.normalize(north, north); + hpr.heading = Math.atan2(Cesium.Cartesian3.dot(direction, east), Cesium.Cartesian3.dot(direction, north)); + Cesium.Transforms.headingPitchRollQuaternion(current, hpr, undefined, undefined, base); + return Cesium.Quaternion.multiply(base, correction, result || new Cesium.Quaternion()); + }, false); + } + function createLiveVehicleState() { return { vehicles: [], @@ -697,7 +1199,7 @@ return { count: signals.length, state, update, set show(value) { if (dynamic?.model) dynamic.model.show = Boolean(value && state.live); } }; } - function addTrafficSignals(viewer, signalData, start, assets) { + function addTrafficSignals(viewer, signalData, start, assets, signalPlan, trafficEpochMs) { const dynamic = assets.find((asset) => asset.category === "dynamic" && asset.model); const countdownModels = new Map(assets .filter((asset) => asset.category === "countdown" && asset.model) @@ -705,7 +1207,6 @@ 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 = []; @@ -743,7 +1244,7 @@ const groupPhases = new Map(); for (const signal of signals) { const nodeKey = signal.nodeKey || signal.id; - const phase = signalPhase(signal.phaseGroup, phaseTime, start); + const phase = signalPhaseAtElapsed(signal.phaseGroup, elapsedSeconds, signalPlan); 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"]) { @@ -775,7 +1276,7 @@ }; let lastSecond = -1; const render = () => { - const elapsedSeconds = Math.floor((performance.now() - visualStart) / 1000); + const elapsedSeconds = Math.floor(Math.max(0, performance.now() - trafficEpochMs) / 1000); if (elapsedSeconds === lastSecond) return; lastSecond = elapsedSeconds; state.elapsedSeconds = elapsedSeconds; @@ -823,16 +1324,25 @@ 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) }; - return { active: "red", remaining: Math.ceil(20 - second) }; - } - if (second < 10) return { active: "red", remaining: Math.ceil(10 - second) }; - if (second < 18) return { active: "green", remaining: Math.ceil(18 - second) }; - return { active: "yellow", remaining: Math.ceil(20 - second) }; + function signalPhaseAtElapsed(group, elapsed, signalPlan) { + const plan = signalPlan || { + cycleSeconds: 60, + initialAllRedSeconds: 5, + groups: { + 0: [{ from: 0, to: 25, state: "green" }, { from: 25, to: 28, state: "yellow" }, { from: 28, to: 60, state: "red" }], + 1: [{ from: 0, to: 32, state: "red" }, { from: 32, to: 57, state: "green" }, { from: 57, to: 60, state: "yellow" }], + }, + }; + const initialAllRedSeconds = Math.max(0, Number(plan.initialAllRedSeconds) || 0); + if (elapsed < initialAllRedSeconds) return { active: "red", remaining: Math.ceil(initialAllRedSeconds - elapsed), initialClearance: true }; + const cycleSeconds = Number(plan.cycleSeconds) || 20; + const intervals = plan.groups?.[String(Number(group))] || plan.groups?.[Number(group)]; + if (!Array.isArray(intervals) || !intervals.length) return { active: "red", remaining: 0 }; + const cycleElapsed = elapsed - initialAllRedSeconds; + const second = ((cycleElapsed % cycleSeconds) + cycleSeconds) % cycleSeconds; + const interval = intervals.find((candidate) => second >= candidate.from && second < candidate.to); + if (!interval) return { active: "red", remaining: 0 }; + return { active: interval.state, remaining: Math.ceil(interval.to - second) }; } function selectedVehicleModelName(modelNames, fallbackModelName) { @@ -1374,8 +1884,14 @@ } function createCameraPresets(viewer, metadata, placement, cruise) { - const radius = Math.max(220.0, boundsRadiusMeters(metadata.bounds) || 900.0); - const center = placement.position; + const configuredCenter = Array.isArray(config.simulationCenter) && config.simulationCenter.length >= 2 + ? config.simulationCenter.map(Number) + : null; + const center = configuredCenter && configuredCenter.every(Number.isFinite) + ? Cesium.Cartesian3.fromDegrees(configuredCenter[0], configuredCenter[1], placement.height) + : placement.position; + const radius = Math.max(40.0, Number(config.cameraRadiusMeters) || 105.0); + let autoOrbit = null; function lookAt(range, headingDegrees, pitchDegrees) { viewer.camera.lookAt( center, @@ -1385,15 +1901,13 @@ range ) ); - // lookAt locks the camera into the target's reference frame; release it - // so orbit and pan keep working from the new vantage point. + // Release the temporary target frame after positioning the camera so + // Cesium's normal orbit and zoom controls remain available. viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); } return { overview() { - viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(center, radius), { - duration: 0.0 - }); + lookAt(radius, 135.0, -32.0); }, oblique() { lookAt(radius * 0.92, 135.0, -28.0); @@ -1414,6 +1928,28 @@ }, duration: 0.0 }); + }, + startAutoOrbit() { + if (autoOrbit) return; + let headingDegrees = 135.0; + let lastTime = performance.now(); + const onPointerDown = () => { + if (!autoOrbit) return; + viewer.scene.preRender.removeEventListener(autoOrbit); + viewer.canvas.removeEventListener("pointerdown", onPointerDown); + autoOrbit = null; + viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); + }; + autoOrbit = () => { + const now = performance.now(); + const elapsed = Math.min(0.1, Math.max(0, (now - lastTime) / 1000)); + lastTime = now; + headingDegrees = (headingDegrees + elapsed * 4.0) % 360.0; + lookAt(radius, headingDegrees, -32.0); + }; + viewer.scene.preRender.addEventListener(autoOrbit); + viewer.canvas.addEventListener("pointerdown", onPointerDown, { once: true }); + autoOrbit(); } }; } diff --git a/scripts/lib/native-preview-traffic-simulation.js b/scripts/lib/native-preview-traffic-simulation.js index 47b76a7..9787637 100644 --- a/scripts/lib/native-preview-traffic-simulation.js +++ b/scripts/lib/native-preview-traffic-simulation.js @@ -4,7 +4,20 @@ const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); -const SCHEMA = "native-preview-traffic-simulation/v1"; +const SCHEMA = "native-preview-traffic-simulation/v2"; +// Local preview signal plan. Each green is preceded by a 2 s all-red clearance +// so the previous movement can leave the junction before conflicting traffic. +const DEFAULT_SIGNAL_PLAN = { + cycleSeconds: 60, + // Start with every approach red so the first rendered frame is a controlled + // queue, not a vehicle released into a phase before the scene is visible. + initialAllRedSeconds: 5, + groups: { + 0: [{ from: 0, to: 25, state: "green" }, { from: 25, to: 28, state: "yellow" }, { from: 28, to: 60, state: "red" }], + 1: [{ from: 0, to: 32, state: "red" }, { from: 32, to: 57, state: "green" }, { from: 57, to: 60, state: "yellow" }], + }, + pedestrianRule: "cross only while the paired approach group is red; finish crossing after the phase changes", +}; const MAX_ROUTES = 5; const MIN_ROAD_COUNT = 3; const MAX_ROAD_COUNT = 7; @@ -17,6 +30,49 @@ const DEFAULT_SETTINGS = { vehicleLengthMeters: 4.6, minimumGapMeters: 7, }; +const DEFAULT_FLEET = { + vehiclesPerThroughRoute: 1, + vehiclesPerTurnRoute: 1, + motorcycles: 1, + bicyclesPerRoute: 1, + pedestriansPerCrossing: 1, +}; +// Dashboard cross-model catalog (`${type}${subType}.glb`): type 1 motor +// vehicles with subType 1 small / 2 bus / 3 special / 5 mid / 6 large / +// 7 oversize, 4 motorcycle, 21/22 bicycles, 31 pedestrian. +const VEHICLE_MODEL_CATALOG = [ + { modelName: "v2x-vehicles/11.glb", vehicleLengthMeters: 4.6, weight: 5 }, + { modelName: "v2x-vehicles/15.glb", vehicleLengthMeters: 6.5, weight: 2 }, + { modelName: "v2x-vehicles/16.glb", vehicleLengthMeters: 8.5, weight: 1.5 }, + { modelName: "v2x-vehicles/17.glb", vehicleLengthMeters: 10.5, weight: 0.75 }, + { modelName: "v2x-vehicles/12.glb", vehicleLengthMeters: 11.5, weight: 0.75 }, + { modelName: "v2x-vehicles/13.glb", vehicleLengthMeters: 5.8, weight: 0.5 }, +]; +const MOTORCYCLE_MODEL = { modelName: "v2x-vehicles/14.glb", vehicleLengthMeters: 2.0 }; +const BICYCLE_MODELS = ["v2x-vehicles/221.glb", "v2x-vehicles/222.glb"]; +const PEDESTRIAN_MODEL = "v2x-vehicles/31.glb"; +const KIND_DYNAMICS = { + vehicle: { desiredSpeedMetersPerSecond: 8, accelerationMetersPerSecondSquared: 1.8, decelerationMetersPerSecondSquared: 3.5 }, + motorcycle: { desiredSpeedMetersPerSecond: 9, accelerationMetersPerSecondSquared: 2.4, decelerationMetersPerSecondSquared: 3.8 }, + bicycle: { desiredSpeedMetersPerSecond: 5.0, accelerationMetersPerSecondSquared: 1.8, decelerationMetersPerSecondSquared: 2.8 }, + pedestrian: { desiredSpeedMetersPerSecond: 2.0, accelerationMetersPerSecondSquared: 1.4, decelerationMetersPerSecondSquared: 2.4 }, +}; +const KIND_PLACEMENT = { + vehicle: { modelScale: 1.0, heightMeters: 0.4 }, + motorcycle: { modelScale: 1.0, heightMeters: 0.4 }, + bicycle: { modelScale: 1.0, heightMeters: 0.05 }, + pedestrian: { modelScale: 1.0, heightMeters: 0.05 }, +}; +// The dashboard glb set models face +X (AMap three.js applies a 90° heading +// offset); keep the same correction so models face along the route. +const MODEL_HEADING_OFFSET_DEGREES = -90; +// Lane indices run 1 (median) -> 3 (curb) on the modelled travel direction. +const CANONICAL_LANE_BY_TURN = { right: 3, through: 2, left: 1 }; +const CROSSWALK_PAD_METERS = 2.5; +// Participant routes may extend up to this far into the upstream/downstream +// corridor roads so vehicles enter and leave the scene instead of popping in +// beside the stop line. +const PARTICIPANT_CORRIDOR_CAP_METERS = 250; function buildNativeTrafficSimulation(area, options = {}) { const root = options.nativePackage?.rootDir; @@ -34,29 +90,56 @@ function buildNativeTrafficSimulation(area, options = {}) { const connectors = readFeatureCollection(connectorPath, "native connectors"); const laneCenterlines = fs.existsSync(laneCenterlinePath) ? readFeatureCollection(laneCenterlinePath, "native lane centerlines") : null; const stopLines = readFeatureCollection(stopLinePath, "native stop lines"); + const crosswalkPath = path.join(root, "layers", "crosswalks.geojson"); + const crosswalks = fs.existsSync(crosswalkPath) ? readFeatureCollection(crosswalkPath, "native crosswalks") : null; const settings = { ...DEFAULT_SETTINGS, ...(options.settings || {}) }; validateSettings(settings); + const fleet = { ...DEFAULT_FLEET, ...(options.fleet || {}) }; + const modelPrefix = options.modelPrefix || ""; const routeBuild = buildRoutes(compiled, connectors, signals.signals || [], stopLines.features, laneCenterlines); + const participantBuild = buildParticipants({ + compiled, + connectorCollection: connectors, + laneCenterlines, + stopLineFeatures: stopLines.features, + crosswalks, + signals: signals.signals || [], + fleet, + modelPrefix, + }); + const participants = participantBuild.participants; return { schema: SCHEMA, areaId: area.id, coordinateSystem: { route: "WGS84", model: "ENU", units: "meters", axes: "X east / Y north / Z up" }, generatedAt: new Date().toISOString(), speedMetersPerSecond: settings.desiredSpeedMetersPerSecond, - source: sourceRecords(area, [compiledPath, signalPath, connectorPath, stopLinePath, ...(laneCenterlines ? [laneCenterlinePath] : [])]), + source: sourceRecords(area, [ + compiledPath, + signalPath, + connectorPath, + stopLinePath, + ...(laneCenterlines ? [laneCenterlinePath] : []), + ...(crosswalks ? [crosswalkPath] : []), + ]), settings, + fleet, + signalPlan: DEFAULT_SIGNAL_PLAN, routes: routeBuild.routes, + participants, signals: (signals.signals || []).filter((signal) => signal && signal.id).map(signalDescriptor), diagnostics: [ ...routeBuild.diagnostics, - ...(routeBuild.routes.length ? [] : [{ severity: "warning", reason: "no_native_cruise_route", message: "No deterministic native route crossed three or more directional roads." }]), + ...participantBuild.diagnostics, + ...(routeBuild.routes.length || participants.length ? [] : [{ severity: "warning", reason: "no_native_cruise_route", message: "No deterministic native route or open intersection participant was generated." }]), ], rejectedRoutes: routeBuild.rejectedRoutes, migration: { schema: SCHEMA, - updateLoop: "advance route distance using settings, stop before red/yellow signal, then apply leader minimum gap", + updateLoop: "advance route distance using settings, stop before red/yellow signal, then apply leader minimum gap; pedestrians advance only while their crossing phase is red", signalIdentity: "signals[].id is the existing traffic runtime signal_uid", - coordinates: "routes[].coordinates are WGS84; static package remains local ENU placed by package manifest", + coordinates: "routes[]/participants[] coordinates are WGS84; static package remains local ENU placed by package manifest", + participants: "participants[] are open route templates (approach to exit, or crosswalk spans) with per-kind models and fleet counts", legacyDependency: false, }, }; @@ -102,6 +185,661 @@ function buildRoutes(compiled, connectorCollection, signals, stopLineFeatures, l return { routes, diagnostics, rejectedRoutes }; } +// --------------------------------------------------------------------------- +// Intersection participants (v2) +// +// A single-intersection clip has no closed loop, so cruise routes stay empty. +// Instead the descriptor carries open route templates ("participants"): each +// runs from an approach entry, through one movement connector, onto an exit +// (vehicles, motorcycles, bicycles), or across a crosswalk span (pedestrians). +// Signal phases come from pairing signal stop points with native stop lines, +// so no way id is hardcoded. +// --------------------------------------------------------------------------- + +function buildParticipants({ compiled, connectorCollection, laneCenterlines, stopLineFeatures, crosswalks, signals, fleet, modelPrefix }) { + const diagnostics = []; + const roads = new Map((compiled.model?.roads || []).map((road) => [road.id, road])); + const allMovements = (compiled.movements || []).filter((movement) => movement.geometryPublished !== false && roads.has(movement.fromRoadId) && roads.has(movement.toRoadId)); + const connectorByMovement = new Map(connectorCollection.features.map((feature) => [feature.properties?.movement_id, feature.geometry?.coordinates || []])); + const movementHasConnector = (movement) => (connectorByMovement.get(movement.id) || []).length >= 2; + // Intersection movements are the cluster lane-paths; endpoint-connection + // movements are corridor continuations used only to extend participant + // routes toward the clip boundary. Fall back to all movements when the + // package predates cluster naming. + let movements = allMovements.filter((movement) => String(movement.id).includes(":cluster:") && movementHasConnector(movement)); + if (!movements.length) movements = allMovements.filter(movementHasConnector); + const laneCenterlineById = indexLaneCenterlines(laneCenterlines); + const context = { + roads, + connectorByMovement, + laneCenterlineById, + movements: allMovements, + diagnostics, + }; + const crossings = collectMainCrosswalks(crosswalks, stopLineFeatures, diagnostics); + const crossingByRoad = new Map(crossings.map((crossing) => [crossing.roadId, crossing])); + const participants = []; + + const movementsByApproach = new Map(); + for (const movement of movements) { + if (!movementsByApproach.has(movement.fromRoadId)) movementsByApproach.set(movement.fromRoadId, []); + movementsByApproach.get(movement.fromRoadId).push(movement); + } + const { phaseByRoad, signalIdByRoad } = mapApproachPhases(signals, movementsByApproach, context, diagnostics); + + let vehicleTemplateIndex = 0; + const throughApproaches = []; + let approachIndex = 0; + for (const approachRoadId of [...movementsByApproach.keys()].sort()) { + const byTurn = groupByTurn(movementsByApproach.get(approachRoadId)); + // Keep one through stream on every arm. Add a single alternating turn + // stream so the intersection remains readable and does not spawn three + // vehicles into the same stop line at once. + const allowedTurns = approachIndex % 2 === 0 ? ["through", "left"] : ["through"]; + for (const turn of allowedTurns) { + const movement = pickMovementByCanonicalLane(byTurn[turn] || [], CANONICAL_LANE_BY_TURN[turn]); + if (!movement) continue; + const path = buildMovementPath(movement, context); + if (!path) continue; + const isThrough = turn === "through"; + const fleetCount = isThrough ? fleet.vehiclesPerThroughRoute : fleet.vehiclesPerTurnRoute; + const model = VEHICLE_MODEL_CATALOG[vehicleTemplateIndex % VEHICLE_MODEL_CATALOG.length]; + vehicleTemplateIndex += 1; + participants.push(makeParticipantTemplate({ + id: `participant:vehicle:${shortRoadId(approachRoadId)}:${turn}`, + kind: "vehicle", + movement, + path, + fleetCount, + modelPrefix, + model: model.modelName, + vehicleLengthMeters: model.vehicleLengthMeters, + approachRoadId, + signalIdByRoad, + signals, + stopLineFeatures, + crossing: crossingByRoad.get(approachRoadId) || null, + crossings, + })); + if (isThrough) throughApproaches.push({ approachRoadId, movement, path }); + } + approachIndex += 1; + } + + if (fleet.motorcycles > 0 && throughApproaches.length) { + // Deterministic: ride the alphabetically first through corridor. + const template = throughApproaches[0]; + participants.push(makeParticipantTemplate({ + id: `participant:motorcycle:${shortRoadId(template.approachRoadId)}:through`, + kind: "motorcycle", + movement: template.movement, + path: template.path, + fleetCount: fleet.motorcycles, + modelPrefix, + model: MOTORCYCLE_MODEL.modelName, + vehicleLengthMeters: MOTORCYCLE_MODEL.vehicleLengthMeters, + approachRoadId: template.approachRoadId, + signalIdByRoad, + signals, + stopLineFeatures, + crossing: crossingByRoad.get(template.approachRoadId) || null, + crossings, + })); + } + + if (fleet.pedestriansPerCrossing > 0) { + for (const crossing of crossings) { + const phaseGroup = phaseByRoad.get(crossing.roadId); + if (!Number.isFinite(phaseGroup)) { + diagnostics.push({ severity: "warning", reason: "crosswalk_phase_unresolved", message: `Crosswalk ${crossing.id} has no paired approach signal; pedestrians omitted.`, crosswalkId: crossing.id }); + continue; + } + const coordinates = crossing.coordinates; + const distances = cumulativeDistances(coordinates); + const dynamics = KIND_DYNAMICS.pedestrian; + participants.push({ + id: `participant:pedestrian:${crossing.id}`, + kind: "pedestrian", + crossingId: crossing.id, + fleet: fleet.pedestriansPerCrossing, + modelName: `${modelPrefix}${PEDESTRIAN_MODEL}`, + modelScale: KIND_PLACEMENT.pedestrian.modelScale, + headingOffsetDegrees: MODEL_HEADING_OFFSET_DEGREES, + heightMeters: KIND_PLACEMENT.pedestrian.heightMeters, + phaseGroup, + coordinates, + distances, + lengthMeters: round(distances.at(-1)), + speedMetersPerSecond: dynamics.desiredSpeedMetersPerSecond, + accelerationMetersPerSecondSquared: dynamics.accelerationMetersPerSecondSquared, + decelerationMetersPerSecondSquared: dynamics.decelerationMetersPerSecondSquared, + stops: [], + }); + if (fleet.bicyclesPerRoute > 0) { + participants.push({ + id: `participant:bicycle:${crossing.id}`, + kind: "bicycle", + fleet: fleet.bicyclesPerRoute, + modelName: `${modelPrefix}${BICYCLE_MODELS[crossings.indexOf(crossing) % BICYCLE_MODELS.length]}`, + modelScale: KIND_PLACEMENT.bicycle.modelScale, + headingOffsetDegrees: MODEL_HEADING_OFFSET_DEGREES, + heightMeters: KIND_PLACEMENT.bicycle.heightMeters, + phaseGroup, + crossingId: crossing.id, + coordinates, + distances, + lengthMeters: round(distances.at(-1)), + speedMetersPerSecond: KIND_DYNAMICS.bicycle.desiredSpeedMetersPerSecond, + accelerationMetersPerSecondSquared: KIND_DYNAMICS.bicycle.accelerationMetersPerSecondSquared, + decelerationMetersPerSecondSquared: KIND_DYNAMICS.bicycle.decelerationMetersPerSecondSquared, + vehicleLengthMeters: 1.8, + stops: [], + }); + } + } + } + + const withFleet = participants.filter((participant) => participant.fleet > 0 && participant.lengthMeters > 5); + return { participants: withFleet, diagnostics }; +} + +function makeParticipantTemplate({ id, kind, movement, path, fleetCount, modelPrefix, model, vehicleLengthMeters, approachRoadId, signalIdByRoad, signals, crossing, crossings }) { + const coordinates = path.coordinates; + const distances = cumulativeDistances(coordinates); + const crossingConflicts = kind === "vehicle" || kind === "motorcycle" + ? (crossings || []).map((candidate) => { + let best = { distance: Infinity, routeDistance: 0 }; + for (let index = 0; index < coordinates.length; index += 1) { + for (const point of candidate.coordinates || []) { + const distance = haversine(coordinates[index], point); + if (distance < best.distance) best = { distance, routeDistance: distances[index] }; + } + } + return best.distance <= 7 ? { crossingId: candidate.id, distance: round(best.routeDistance), matchDistanceMeters: round(best.distance) } : null; + }).filter(Boolean) + : []; + const dynamics = KIND_DYNAMICS[kind]; + // Attach the paired approach signal directly by projecting its stop point + // onto the route: raw proximity matching grabs neighbouring signals in this + // compact intersection, and the curb lane can sit outside their tolerance. + const ownSignal = signals.find((signal) => signal && signal.id === (signalIdByRoad.get(approachRoadId) || null)); + const stops = []; + if (ownSignal && Number.isFinite(ownSignal.stopLongitude) && Number.isFinite(ownSignal.stopLatitude)) { + let best = { distance: Infinity, routeDistance: 0 }; + // The controlling zebra is on the approach arm. Never match a nearby + // crossing after the turn connector, otherwise a turning vehicle receives + // a stop point inside the junction. + const approachLimit = distances.at(-1) * 0.48; + for (let index = 0; index < coordinates.length && distances[index] <= approachLimit; index += 1) { + const distance = haversine(coordinates[index], [ownSignal.stopLongitude, ownSignal.stopLatitude]); + if (distance < best.distance) best = { distance, routeDistance: distances[index] }; + } + if (best.distance <= 30) { + // Route distance tracks the model origin, while the legal stop line is + // constrained by the front bumper. Keep half a vehicle length plus a + // small safety margin behind the signal's stop-line point. + const centerStopDistance = Math.max(0, best.routeDistance - vehicleLengthMeters / 2 - 1.0); + stops.push({ signalId: ownSignal.id, phaseGroup: ownSignal.phaseGroup, distance: round(centerStopDistance), stopLineDistance: round(best.routeDistance), matchDistanceMeters: round(best.distance), stopReason: "traffic-signal" }); + } + } + let crossingStopDistance = null; + if (crossing?.coordinates?.length) { + let nearest = { distance: Infinity, routeDistance: null }; + const approachLimit = distances.at(-1) * 0.48; + for (let index = 0; index < coordinates.length && distances[index] <= approachLimit; index += 1) { + for (const point of crossing.coordinates) { + const distance = haversine(coordinates[index], point); + if (distance < nearest.distance) nearest = { distance, routeDistance: distances[index] }; + } + } + if (Number.isFinite(nearest.routeDistance) && nearest.distance <= 20) { + // GLB origins are not guaranteed to be geometric centers. Keep the + // complete vehicle length plus a buffer behind the zebra so long buses + // and trucks cannot nose over the stop line. + crossingStopDistance = Math.max(0, nearest.routeDistance - (vehicleLengthMeters + 4.0)); + if (ownSignal) { + const existing = stops[0]; + if (!existing || crossingStopDistance < existing.distance) { + stops.splice(0, 1, { signalId: ownSignal.id, phaseGroup: ownSignal.phaseGroup, distance: round(crossingStopDistance), matchDistanceMeters: round(nearest.distance), stopReason: "crosswalk-control" }); + } + } + } + } + return { + id, + kind, + fleet: fleetCount, + modelName: `${modelPrefix}${model}`, + modelScale: KIND_PLACEMENT[kind].modelScale, + headingOffsetDegrees: MODEL_HEADING_OFFSET_DEGREES, + heightMeters: KIND_PLACEMENT[kind].heightMeters, + movementId: movement.id, + approachRoadId, + approachLaneId: movement.fromLaneId || null, + turn: movement.turn, + exitRoadId: movement.toRoadId, + coordinates, + distances, + lengthMeters: round(distances.at(-1)), + speedMetersPerSecond: dynamics.desiredSpeedMetersPerSecond, + accelerationMetersPerSecondSquared: dynamics.accelerationMetersPerSecondSquared, + decelerationMetersPerSecondSquared: dynamics.decelerationMetersPerSecondSquared, + vehicleLengthMeters, + crossingId: crossing?.id || null, + crossingConflicts, + crossingStopDistance: crossingStopDistance === null ? null : round(crossingStopDistance), + stops, + }; +} + +// Bind each approach to the signal whose *facing direction* controls its +// inbound movement. approachId/node equality and nearest-stop-point matching +// are not sufficient here: this junction's identifiers pair several signals +// with perpendicular stop lines, which releases cars on the cross street's +// green. The route tangent is the vehicle's actual inbound heading. +function mapApproachPhases(signals, movementsByApproach, context, diagnostics) { + const phaseByRoad = new Map(); + const signalIdByRoad = new Map(); + const unmatched = []; + for (const [roadId, movements] of movementsByApproach) { + let best = null; + for (const movement of movements) { + const path = buildMovementPath(movement, context); + if (!path || path.coordinates.length < 2) continue; + const heading = bearingDegrees(path.coordinates[0], path.coordinates[1]); + let nearestSignal = null; + for (const signal of signals) { + if (!Number.isFinite(signal.stopLongitude) || !Number.isFinite(signal.stopLatitude)) continue; + const travelHeading = signalTravelHeading(signal); + if (!Number.isFinite(travelHeading)) continue; + const headingDelta = angleDeltaDegrees(heading, travelHeading); + if (headingDelta > 45) continue; + let distance = Infinity; + for (const point of path.coordinates) { + distance = Math.min(distance, haversine(point, [signal.stopLongitude, signal.stopLatitude])); + } + if (distance > 55) continue; + const score = headingDelta * 2 + distance; + if (!nearestSignal || score < nearestSignal.score) nearestSignal = { signal, distance, headingDelta, score }; + } + if (nearestSignal && (!best || nearestSignal.score < best.score)) best = nearestSignal; + } + if (best) { + phaseByRoad.set(roadId, best.signal.phaseGroup); + signalIdByRoad.set(roadId, best.signal.id); + } else unmatched.push(roadId); + } + if (!phaseByRoad.size) { + diagnostics.push({ severity: "warning", reason: "signal_approach_heading_pairing_failed", message: "No signal could be paired to an inbound route by travel heading; participants remain controlled only where a signal match exists." }); + } + for (const roadId of unmatched) diagnostics.push({ severity: "warning", reason: "signal_approach_unmatched", message: `No direction-compatible signal was found for approach ${roadId}.`, approachRoadId: roadId }); + return { phaseByRoad, signalIdByRoad }; +} + +function signalTravelHeading(signal) { + const face = Number(signal.faceHeadingDegrees); + if (Number.isFinite(face)) return (face + 180) % 360; + const mast = Number(signal.mastHeadingDegrees ?? signal.headingDegrees); + return Number.isFinite(mast) ? (mast + 90 + 360) % 360 : NaN; +} + +function bearingDegrees(a, b) { + const radians = Math.PI / 180; + const dLon = (b[0] - a[0]) * radians; + const lat1 = a[1] * radians; + const lat2 = b[1] * radians; + const y = Math.sin(dLon) * Math.cos(lat2); + const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon); + return (Math.atan2(y, x) / radians + 360) % 360; +} + +function angleDeltaDegrees(a, b) { + const delta = Math.abs((a - b) % 360); + return Math.min(delta, 360 - delta); +} + +function groupByTurn(movements) { + const byTurn = {}; + for (const movement of movements) { + const turn = movement.turn || "through"; + (byTurn[turn] = byTurn[turn] || []).push(movement); + } + for (const list of Object.values(byTurn)) list.sort((a, b) => String(a.id).localeCompare(String(b.id))); + return byTurn; +} + +function movementLaneIndex(movement, side) { + const laneId = side === "from" ? movement.fromLaneId : movement.toLaneId; + const match = /:(\d+)$/.exec(String(laneId || "")); + return match ? Number(match[1]) : null; +} + +function pickMovementByCanonicalLane(movements, canonicalLane) { + if (!movements.length) return null; + if (Number.isFinite(canonicalLane)) { + const preferred = movements.find((movement) => movementLaneIndex(movement, "from") === canonicalLane); + if (preferred) return preferred; + } + return movements[0]; +} + +function pickCurbLaneMovement(movements) { + if (!movements.length) return null; + const withLanes = movements.filter((movement) => Number.isFinite(movementLaneIndex(movement, "from"))); + if (withLanes.length) { + // Highest-numbered approach lane rides nearest the curb. + withLanes.sort((a, b) => movementLaneIndex(b, "from") - movementLaneIndex(a, "from")); + return withLanes[0]; + } + return movements[0]; +} + +// Assemble approach lane -> connector -> exit lane with travel-direction +// continuity: each lane line is oriented so it flows into/out of its +// connector, then trimmed to a cap so vehicles spawn near the junction +// instead of at the far clip boundary. +function buildMovementPath(movement, context) { + const { roads, connectorByMovement, laneCenterlineById, diagnostics } = context; + const connector = cleanLine(connectorByMovement.get(movement.id)); + if (!connector || connector.length < 2) return null; + const approachRoad = roads.get(movement.fromRoadId); + const exitRoad = roads.get(movement.toRoadId); + const approachLine = laneLineForRoad(laneCenterlineById, approachRoad, movementLaneIndex(movement, "from")); + const exitLine = laneLineForRoad(laneCenterlineById, exitRoad, movementLaneIndex(movement, "to")); + if (!approachLine || !exitLine) return null; + + const elements = [ + { type: "line", role: "approach", coords: approachLine }, + { type: "connector", coords: connector }, + { type: "line", role: "exit", coords: exitLine }, + ]; + const coordinates = []; + let anchored = false; + for (let index = 0; index < elements.length; index += 1) { + const element = elements[index]; + const anchor = coordinates.at(-1) || null; + if (element.type === "line") { + const nextConnector = elements[index + 1]?.type === "connector" ? elements[index + 1] : null; + const previousConnector = elements[index - 1]?.type === "connector" ? elements[index - 1] : null; + let oriented; + if (!anchored) { + // Head of the route: align the line end with the first connector. + const direction = nextConnector ? segmentDirection(nextConnector.coords, 0) : segmentDirection(element.coords, element.coords.length - 2); + oriented = orientLine(element.coords, nextConnector?.coords[0] || element.coords.at(-1), direction, true); + } else { + // Continue out of the previous connector. + const direction = previousConnector ? segmentDirection(previousConnector.coords, previousConnector.coords.length - 2) : segmentDirection(element.coords, 0); + oriented = orientLine(element.coords, anchor, direction, false); + } + if (!oriented) { + diagnostics.push({ severity: "warning", reason: "participant_path_orientation_failed", message: `Movement ${movement.id} lane geometry could not be oriented against its connector.`, movementId: movement.id }); + return null; + } + const startGap = anchor ? distanceMeters(anchor, oriented[0]) : 0; + if (anchored && startGap > MAX_CONNECTION_GAP_METERS) { + diagnostics.push({ severity: "warning", reason: "participant_path_gap", message: `Movement ${movement.id} path gap ${round(startGap)}m exceeds ${MAX_CONNECTION_GAP_METERS}m at element ${index}.`, movementId: movement.id, elementIndex: index }); + return null; + } + append(coordinates, trimLine(oriented, PARTICIPANT_CORRIDOR_CAP_METERS, element.role === "approach" ? "end" : "start")); + } else { + const startGap = anchor ? distanceMeters(anchor, element.coords[0]) : 0; + if (anchored && startGap > MAX_CONNECTION_GAP_METERS) { + diagnostics.push({ severity: "warning", reason: "participant_path_gap", message: `Movement ${movement.id} path gap ${round(startGap)}m exceeds ${MAX_CONNECTION_GAP_METERS}m at element ${index}.`, movementId: movement.id, elementIndex: index }); + return null; + } + append(coordinates, element.coords); + } + anchored = true; + } + if (coordinates.length < 4) return null; + return { coordinates }; +} + +function laneLineForRoad(laneCenterlineById, road, laneIndex) { + if (!road) return null; + if (Number.isFinite(laneIndex)) { + const lane = laneCenterlineById.get(`${road.id}:${laneIndex}`); + if (lane) return lane; + } + return laneCenterlineById.get(`${road.id}:1`) || road.centerline || null; +} + +// Keep only the corridor portion within `capMeters` of the junction end. +function trimLine(line, capMeters, attachEnd) { + const cleaned = cleanLine(line); + if (!cleaned || cleaned.length < 2) return cleaned; + const distances = cumulativeDistances(cleaned); + const total = distances.at(-1); + if (total <= capMeters) return cleaned; + const kept = []; + if (attachEnd === "end") { + const cut = total - capMeters; + for (let index = 0; index < cleaned.length; index += 1) { + if (distances[index] >= cut) kept.push(cleaned[index]); + } + } else { + for (let index = 0; index < cleaned.length; index += 1) { + if (distances[index] <= capMeters) kept.push(cleaned[index]); + } + } + return kept.length >= 2 ? kept : cleaned; +} + +function cleanLine(line) { + if (!Array.isArray(line)) return null; + const cleaned = line.map((point) => [Number(point[0]), Number(point[1])]).filter((point) => point.every(Number.isFinite)); + return cleaned.length >= 2 ? cleaned : null; +} + +// Orient `line` so the end that should meet `attachPoint` does, preferring the +// orientation whose initial travel direction continues `directionSample`. +function orientLine(line, attachPoint, directionSample, attachAtEnd) { + const forward = line.map((point) => point.slice(0, 2).map(Number)).filter((point) => point.every(Number.isFinite)); + if (forward.length < 2) return null; + const reverse = [...forward].reverse(); + const candidates = attachAtEnd + ? [ + { line: forward, attach: forward.at(-1), direction: segmentDirection(forward, forward.length - 2) }, + { line: reverse, attach: reverse.at(-1), direction: segmentDirection(reverse, reverse.length - 2) }, + ] + : [ + { line: forward, attach: forward[0], direction: segmentDirection(forward, 0) }, + { line: reverse, attach: reverse[0], direction: segmentDirection(reverse, 0) }, + ]; + const desired = Math.atan2(directionSample[1], directionSample[0]); + let best = null; + let bestScore = Infinity; + for (const candidate of candidates) { + const proximity = distanceMeters(candidate.attach, attachPoint); + if (!Number.isFinite(proximity)) continue; + const actual = Math.atan2(candidate.direction[1], candidate.direction[0]); + let turn = Math.abs(actual - desired); + while (turn > Math.PI) turn = 2 * Math.PI - turn; + // Direction continuity dominates; proximity only breaks near-ties. + const score = turn * 1000 + proximity; + if (score < bestScore) { + bestScore = score; + best = candidate.line; + } + } + return best; +} + +function segmentDirection(points, index) { + const a = points[index]; + const b = points[index + 1] || a; + const metersPerDegreeLatitude = 111320; + const metersPerDegreeLongitude = Math.max(1, Math.cos(((a[1] + b[1]) / 2) * Math.PI / 180) * metersPerDegreeLatitude); + return [(b[0] - a[0]) * metersPerDegreeLongitude, (b[1] - a[1]) * metersPerDegreeLatitude]; +} + +function indexLaneCenterlines(laneCenterlineCollection) { + const byId = new Map(); + for (const feature of laneCenterlineCollection?.features || []) { + const properties = feature.properties || {}; + const coordinates = feature.geometry?.coordinates || []; + if (properties.native_id) byId.set(properties.native_id, coordinates); + if (properties.road_id && Number.isFinite(Number(properties.lane_index))) byId.set(`${properties.road_id}:${properties.lane_index}`, coordinates); + } + return byId; +} + +// Main crosswalk spans: one band per intersection arm. Zebra stripes are +// grouped by crossing_key; the band phase comes from the paired stop line on +// the same arm (nearest stop line wins as a geometry-level fallback). +function collectMainCrosswalks(crosswalks, stopLineFeatures, diagnostics) { + if (!crosswalks?.features?.length) return []; + const groups = new Map(); + for (const feature of crosswalks.features) { + const properties = feature.properties || {}; + const crossingKey = properties.crossing_key || ""; + if (!crossingKey || crossingKey.includes(":corner:")) continue; + if (!groups.has(crossingKey)) groups.set(crossingKey, []); + groups.get(crossingKey).push(feature); + } + const stopLines = stopLineFeatures.map((feature) => ({ + roadId: feature.properties?.road_id, + armKey: feature.properties?.arm_key || "", + points: flattenCoordinates(feature.geometry), + })).filter((entry) => entry.roadId && entry.points.length); + const crossings = []; + for (const [crossingKey, features] of groups) { + const centroids = features.map((feature) => ringCentroid(feature.geometry)).filter(Boolean); + if (centroids.length < 2) continue; + const roadId = resolveCrosswalkRoad(crossingKey, features, stopLines); + if (!roadId) { + diagnostics.push({ severity: "warning", reason: "crosswalk_road_unresolved", message: `Crosswalk ${crossingKey} could not be tied to a stop line.`, crosswalkId: crossingKey }); + continue; + } + crossings.push({ + id: crossingIdFromKey(crossingKey), + roadId, + coordinates: crosswalkCenterline(centroids), + }); + } + return crossings.sort((a, b) => a.id.localeCompare(b.id)); +} + +function resolveCrosswalkRoad(crossingKey, features, stopLines) { + const decodedArm = safeDecode(crossingKey); + const armPrefix = decodedArm.split("|")[0]; + for (const stopLine of stopLines) { + const decodedStopArm = safeDecode(stopLine.armKey); + if (decodedStopArm.split("|").some((part) => part === armPrefix)) return stopLine.roadId; + } + // Geometry fallback: the stop line nearest the band centroid. + const centroid = features.map((feature) => ringCentroid(feature.geometry)).filter(Boolean)[0]; + if (!centroid) return null; + let best = null; + let bestDistance = Infinity; + for (const stopLine of stopLines) { + for (const point of stopLine.points) { + const distance = haversine(centroid, point); + if (distance < bestDistance) { + bestDistance = distance; + best = stopLine.roadId; + } + } + } + return best; +} + +function crosswalkCenterline(centroids) { + const meanLon = centroids.reduce((sum, point) => sum + point[0], 0) / centroids.length; + const meanLat = centroids.reduce((sum, point) => sum + point[1], 0) / centroids.length; + const metersPerDegreeLongitude = Math.max(1, Math.cos(meanLat * Math.PI / 180) * 111320); + // Local meter frame centred on the cloud mean. + const points = centroids.map((point) => [(point[0] - meanLon) * metersPerDegreeLongitude, (point[1] - meanLat) * 111320]); + let sxx = 0; + let syy = 0; + let sxy = 0; + for (const [x, y] of points) { + sxx += x * x; + syy += y * y; + sxy += x * y; + } + // Zebra stripes repeat along the walking direction, so the centroid cloud's + // major axis IS the walking line (its long side spans the road width). + const theta = 0.5 * Math.atan2(2 * sxy, sxx - syy); + const axis = [Math.cos(theta), Math.sin(theta)]; + let minProjection = Infinity; + let maxProjection = -Infinity; + let minPoint = null; + let maxPoint = null; + for (const [x, y] of points) { + const projection = x * axis[0] + y * axis[1]; + if (projection < minProjection) { + minProjection = projection; + minPoint = [x, y]; + } + if (projection > maxProjection) { + maxProjection = projection; + maxPoint = [x, y]; + } + } + // Extend past the outermost stripes onto the sidewalk ramps. + const start = [minPoint[0] - axis[0] * CROSSWALK_PAD_METERS, minPoint[1] - axis[1] * CROSSWALK_PAD_METERS]; + const end = [maxPoint[0] + axis[0] * CROSSWALK_PAD_METERS, maxPoint[1] + axis[1] * CROSSWALK_PAD_METERS]; + const toDegrees = ([x, y]) => [meanLon + x / metersPerDegreeLongitude, meanLat + y / 111320]; + return [ + toDegrees(start), + toDegrees(end), + ]; +} + +function ringCentroid(geometry) { + const rings = geometry?.type === "Polygon" ? geometry.coordinates : null; + if (!rings?.length || !rings[0]?.length) return null; + const ring = rings[0]; + let lon = 0; + let lat = 0; + for (const point of ring) { + lon += point[0]; + lat += point[1]; + } + return [lon / ring.length, lat / ring.length]; +} + +function flattenCoordinates(geometry) { + const points = []; + const walk = (value) => { + if (!Array.isArray(value)) return; + if (value.every((item) => typeof item === "number")) { + points.push([value[0], value[1]]); + return; + } + for (const item of value) walk(item); + }; + walk(geometry?.coordinates); + return points.filter((point) => point.every(Number.isFinite)); +} + +function crossingIdFromKey(crossingKey) { + const decoded = safeDecode(crossingKey); + const match = /segment:way\/(\d+)\/(\d+)/.exec(decoded); + return match ? `crossing-${match[1]}-${match[2]}` : `crossing-${Math.abs(hashString(decoded)) % 100000}`; +} + +function shortRoadId(roadId) { + return String(roadId || "").replace(/^road:way\//, "").replace(/:forward$/, ""); +} + +function safeDecode(value) { + try { + return decodeURIComponent(String(value || "")); + } catch (error) { + return String(value || ""); + } +} + +function hashString(value) { + let hash = 0; + for (let index = 0; index < value.length; index += 1) { + hash = (hash * 31 + value.charCodeAt(index)) | 0; + } + return hash; +} + function findCycles(start, current, roadIds, movements, outgoing, seen, candidates) { const nextRoadIds = [...roadIds, current]; if (nextRoadIds.length > MAX_ROAD_COUNT) return; @@ -257,4 +995,4 @@ function validateSettings(settings) { function sha256(file) { return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); } function round(value) { return Math.round(value * 100) / 100; } -module.exports = { SCHEMA, DEFAULT_SETTINGS, buildNativeTrafficSimulation }; +module.exports = { SCHEMA, DEFAULT_SETTINGS, DEFAULT_SIGNAL_PLAN, buildNativeTrafficSimulation }; diff --git a/scripts/test-native-preview-traffic.js b/scripts/test-native-preview-traffic.js index 3941500..31291a3 100644 --- a/scripts/test-native-preview-traffic.js +++ b/scripts/test-native-preview-traffic.js @@ -18,9 +18,22 @@ const roads = [ ]; const movements = [ ["road:a", "road:b", "left"], ["road:b", "road:c", "through"], ["road:c", "road:a", "right"], -].map(([fromRoadId, toRoadId, turn], index) => ({ id: `movement:${index}`, connectorId: `connector:${index}`, fromRoadId, toRoadId, turn, geometryPublished: true })); +].map(([fromRoadId, toRoadId, turn], index) => ({ + id: `movement:cluster:test:${index}`, + connectorId: `connector:${index}`, + fromRoadId, + toRoadId, + fromLaneId: `lane:${fromRoadId}:1`, + toLaneId: `lane:${toRoadId}:1`, + turn, + geometryPublished: true, +})); fs.writeFileSync(path.join(nativeRoadDir, "compiled.json"), JSON.stringify({ model: { roads }, movements })); -fs.writeFileSync(path.join(nativeRoadDir, "traffic-signals.json"), JSON.stringify({ signals: [{ id: "osm-signal-1", phaseGroup: 0, approachId: "way:a", sourceWayId: "a", stopLongitude: 120.0009, stopLatitude: 30, enabled: true }] })); +fs.writeFileSync(path.join(nativeRoadDir, "traffic-signals.json"), JSON.stringify({ signals: [ + { id: "osm-signal-1", phaseGroup: 0, approachId: "way:a", sourceWayId: "a", stopLongitude: 120.0009, stopLatitude: 30, faceHeadingDegrees: 270, enabled: true }, + // A closer but perpendicular signal must not win over the direction match. + { id: "perpendicular-signal", phaseGroup: 1, approachId: "way:wrong", sourceWayId: "wrong", stopLongitude: 120.0009, stopLatitude: 30, faceHeadingDegrees: 0, enabled: true }, +] })); fs.writeFileSync(path.join(layersDir, "connectors.geojson"), JSON.stringify({ type: "FeatureCollection", features: movements.map((movement, index) => ({ type: "Feature", properties: { movement_id: movement.id }, geometry: { type: "LineString", coordinates: [[[120.001, 30], [120.001, 30.0001]], [[120.001, 30.001], [120.0009, 30.001]], [[120, 30.001], [120, 30.0009]]][index] } })) })); fs.writeFileSync(path.join(layersDir, "vehicle_stop_lines.geojson"), JSON.stringify({ type: "FeatureCollection", features: [{ type: "Feature", properties: { road_id: "road:a" }, geometry: { type: "Polygon", coordinates: [] } }] })); fs.writeFileSync(path.join(layersDir, "lane_centerlines.geojson"), JSON.stringify({ type: "FeatureCollection", features: roads.map((road) => ({ type: "Feature", properties: { road_id: road.id, lane_index: 1 }, geometry: { type: "LineString", coordinates: road.centerline } })) })); @@ -28,9 +41,49 @@ fs.writeFileSync(path.join(layersDir, "lane_centerlines.geojson"), JSON.stringif const descriptor = buildNativeTrafficSimulation({ id: "fixture", outputs: { areaDir } }, { nativePackage: { rootDir: nativeRoadDir } }); assert.equal(descriptor.schema, SCHEMA); assert.equal(descriptor.coordinateSystem.route, "WGS84"); +assert.equal(descriptor.signalPlan.cycleSeconds, 60); +assert.equal(descriptor.signalPlan.initialAllRedSeconds, 5, "all movements start red while the preview initializes"); +assert.deepEqual(descriptor.signalPlan.groups[0], [ + { from: 0, to: 25, state: "green" }, + { from: 25, to: 28, state: "yellow" }, + { from: 28, to: 60, state: "red" }, +]); +assert.deepEqual(descriptor.signalPlan.groups[1], [ + { from: 0, to: 32, state: "red" }, + { from: 32, to: 57, state: "green" }, + { from: 57, to: 60, state: "yellow" }, +]); assert.ok(descriptor.routes.length >= 1); assert.ok(descriptor.routes.some((route) => route.connectors.length === 3)); assert.ok(descriptor.routes.some((route) => route.stops.some((stop) => stop.signalId === "osm-signal-1"))); +assert.ok(descriptor.participants.some((participant) => participant.kind === "vehicle")); +assert.ok( + descriptor.participants.every((participant) => participant.stops.every((stop) => stop.signalId !== "perpendicular-signal")), + "a perpendicular signal must never control a route, even when it shares the stop point", +); +for (const participant of descriptor.participants.filter((entry) => entry.kind === "vehicle" || entry.kind === "motorcycle")) { + const signalStop = participant.stops.find((stop) => stop.stopReason === "traffic-signal"); + if (!signalStop) continue; + assert.ok(Number.isFinite(signalStop.stopLineDistance), "signal-controlled stops retain their geometric stop-line distance"); + assert.ok( + Math.abs(signalStop.stopLineDistance - signalStop.distance - (participant.vehicleLengthMeters / 2 + 1)) < 0.02, + "the model origin stops half a vehicle length plus a safety margin before the line", + ); +} +assert.ok(descriptor.participants.some((participant) => participant.kind === "motorcycle")); +assert.ok(descriptor.participants.filter((participant) => participant.kind === "vehicle").every((participant) => participant.approachLaneId), + "vehicle queues need stable lane identities so adjacent lanes do not become one queue"); +assert.ok(descriptor.participants.filter((participant) => participant.kind === "pedestrian").every((participant) => participant.crossingId), + "crossing participants need a shared crossing identity for vehicle yield checks"); +assert.ok(descriptor.participants.filter((participant) => participant.kind === "vehicle").every((participant) => Array.isArray(participant.crossingConflicts)), + "vehicles must carry geometry-based crossing conflict points for turn yielding"); +assert.ok(descriptor.participants.every((participant) => participant.modelName.startsWith("v2x-vehicles/"))); +const previewDescriptor = buildNativeTrafficSimulation( + { id: "fixture", outputs: { areaDir } }, + { nativePackage: { rootDir: nativeRoadDir }, modelPrefix: "_preview/" }, +); +assert.ok(previewDescriptor.participants.every((participant) => participant.modelName.startsWith("_preview/v2x-vehicles/"))); +assert.ok(!descriptor.diagnostics.some((entry) => entry.reason === "no_native_cruise_route")); assert.equal(descriptor.migration.legacyDependency, false); assert.equal(descriptor.source.length, 5); fs.rmSync(areaDir, { recursive: true, force: true }); diff --git a/scripts/test-participant-runtime.js b/scripts/test-participant-runtime.js new file mode 100644 index 0000000..3559683 --- /dev/null +++ b/scripts/test-participant-runtime.js @@ -0,0 +1,176 @@ +#!/usr/bin/env node +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); + +const source = fs.readFileSync(path.join(__dirname, "lib/cesium-preview.js"), "utf8"); +function functionSource(name) { + const start = source.indexOf(" function " + name + "("); + assert.ok(start >= 0, name); + const end = source.indexOf("\n function ", start + 1); + return source.slice(start, end < 0 ? source.length : end); +} +let seconds = 0; +class Time { + constructor(value = 0) { this.value = value; } + clone() { return new Time(this.value); } +} +const context = vm.createContext({ + performance: { now: () => seconds * 1000 }, + toggleVehicles: { checked: true }, + Cesium: { + JulianDate: { + secondsDifference: (a, b) => a.value - b.value, + clone: (a, b) => { b.value = a.value; return b; }, + }, + CallbackProperty: class { constructor(callback) { this.callback = callback; } }, + }, + distanceMeters: (a, b) => Math.hypot((a[0] - b[0]) * 100000, (a[1] - b[1]) * 100000), +}); +vm.runInContext(["participantRoute", "createParticipantSimulation", "signalPhaseAtElapsed"].map(functionSource).join("\n"), context); +const plan = { cycleSeconds: 60, initialAllRedSeconds: 5, groups: { + 0: [{ from: 0, to: 25, state: "green" }, { from: 25, to: 28, state: "yellow" }, { from: 28, to: 60, state: "red" }], + 1: [{ from: 0, to: 32, state: "red" }, { from: 32, to: 57, state: "green" }, { from: 57, to: 60, state: "yellow" }], +} }; +const templates = [ + { id: "cars", kind: "vehicle", fleet: 1, approachLaneId: "lane", speedMetersPerSecond: 8, + vehicleLengthMeters: 4.6, coordinates: [[0, 0], [0.0002, 0], [0.0008, 0]], + stops: [{ distance: 20, phaseGroup: 0 }], crossingConflicts: [] }, + { id: "walk", kind: "pedestrian", fleet: 1, crossingId: "zebra", phaseGroup: 0, + speedMetersPerSecond: 2, coordinates: [[0, 0.001], [0.0003, 0.001]], stops: [] }, +]; +let tick; +const simulation = context.createParticipantSimulation({ clock: { onTick: { addEventListener: (fn) => { tick = fn; } } } }, + templates, new Time(), 8, {}, plan, 0); +let releases = 0; +let completedCrossings = 0; +for (let frame = 1; frame <= 12000; frame += 1) { + seconds = frame * 0.05; + const previous = simulation.agents.map((agent) => ({ ...agent.state })); + tick({ currentTime: new Time(seconds) }); + simulation.agents.forEach((agent, index) => { + const before = previous[index]; + const state = agent.state; + assert.ok(Number.isFinite(state.distance) && Number.isFinite(state.speed)); + if (before.active && state.active && before.committed === state.committed) { + assert.ok(state.distance >= before.distance - 1e-8, "no reversing or teleporting"); + } + if (agent.template.kind === "vehicle" && !before.committed && state.committed) { + assert.equal(context.signalPhaseAtElapsed(0, seconds, plan).active, "green", "release only on green"); + assert.ok(state.distance > before.distance, "release advances position"); + releases += 1; + } + if (agent.template.kind === "pedestrian" && before.active && !state.active) completedCrossings += 1; + }); + const cars = simulation.agents.filter((agent) => agent.template.kind === "vehicle" + && agent.state.active && seconds >= agent.state.spawnDelay).sort((a, b) => a.state.distance - b.state.distance); + for (let i = 1; i < cars.length; i += 1) { + assert.ok(cars[i].state.distance - cars[i - 1].state.distance >= 4.6 - 0.01, "car bodies never overlap"); + } +} +assert.ok(releases > 15, "traffic keeps releasing across ten cycles"); +assert.ok(completedCrossings >= 5, "pedestrians complete crossings instead of freezing"); +console.log(`Participant runtime: 600 s passed, ${releases} green releases, ${completedCrossings} completed crossings.`); + +// Exercise the actual orientation callback at and beyond the open-route end. +// Stop after its position samples so this check does not require WebGL/Cesium. +const sampledDistances = []; +const samplesComplete = new Error("position samples complete"); +const orientationContext = vm.createContext({ + Cesium: { + Cartesian3: class {}, + Quaternion: class { static fromAxisAngle() { return {}; } }, + Math: { toRadians: (degrees) => degrees * Math.PI / 180 }, + HeadingPitchRoll: class {}, + CallbackProperty: class { constructor(callback) { this.callback = callback; } }, + }, + openRoutePositionAtDistance: (route, distance) => { + sampledDistances.push(distance); + if (sampledDistances.length === 2) throw samplesComplete; + }, +}); +vm.runInContext(functionSource("openRouteOrientationFromState"), orientationContext); +for (const distance of [79.5, 80, 81, 200]) { + sampledDistances.length = 0; + const orientation = orientationContext.openRouteOrientationFromState({ length: 80 }, { distance }, 8, -90); + assert.throws(() => orientation.callback(), (error) => error === samplesComplete); + assert.ok(sampledDistances[1] > sampledDistances[0], "heading sample remains ahead after exiting the route"); +} + +if (process.argv[2]) { + const descriptor = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); + context.Cesium.Math = { toRadians: (degrees) => degrees * Math.PI / 180 }; + vm.runInContext(functionSource("distanceMeters"), context); + seconds = 0; + const real = context.createParticipantSimulation({ clock: { onTick: { addEventListener: (fn) => { tick = fn; } } } }, + descriptor.participants, new Time(), 8, descriptor.settings, descriptor.signalPlan, 0); + const completed = new Map(); + function footprint(agent) { + const route = agent.route; + const distance = agent.state.distance; + let index = 1; + while (index < route.distances.length - 1 && route.distances[index] < distance) index += 1; + const a = route.coordinates[index - 1]; + const b = route.coordinates[index]; + const fraction = (distance - route.distances[index - 1]) / (route.distances[index] - route.distances[index - 1]); + const scaleX = 111195 * Math.cos(30.46288 * Math.PI / 180); + const delta = [(b[0] - a[0]) * scaleX, (b[1] - a[1]) * 111195]; + const length = Math.hypot(...delta); + const forward = delta.map((value) => value / length); + return { center: [(a[0] - 114) * scaleX + delta[0] * fraction, (a[1] - 30) * 111195 + delta[1] * fraction], + axes: [forward, [-forward[1], forward[0]]], half: [agent.length / 2, agent.template.kind === "vehicle" ? 1 : 0.3] }; + } + function overlaps(a, b) { + const delta = a.center.map((value, index) => value - b.center[index]); + const dot = (x, y) => x[0] * y[0] + x[1] * y[1]; + return [...a.axes, ...b.axes].every((axis) => { + const radius = (box) => box.half.reduce((sum, half, index) => sum + half * Math.abs(dot(box.axes[index], axis)), 0); + return Math.abs(dot(delta, axis)) < radius(a) + radius(b) - 0.05; + }); + } + for (let frame = 1; frame <= 12000; frame += 1) { + seconds = frame * 0.05; + const previous = real.agents.map((agent) => ({ ...agent.state })); + tick({ currentTime: new Time(seconds) }); + real.agents.forEach((agent, index) => { + const before = previous[index]; + if (agent.template.kind === "vehicle" && !before.committed && agent.state.committed) { + assert.equal(context.signalPhaseAtElapsed(agent.route.stops[0].signal.phaseGroup, + seconds, descriptor.signalPlan).active, "green", "real junction releases only on green"); + } + if ((agent.template.kind === "pedestrian" || agent.template.kind === "bicycle") + && !before.committed && agent.state.committed) { + const phase = context.signalPhaseAtElapsed(agent.template.phaseGroup, seconds, descriptor.signalPlan); + assert.equal(phase.active, "red", "crossing entries follow the paired vehicle red phase"); + assert.ok(!phase.initialClearance, "startup all-red does not release crossing users"); + assert.ok(!real.agents.some((other) => other.template.kind === "vehicle" && other.state.active + && other.state.committed && (other.template.crossingConflicts || []).some((conflict) => + conflict.crossingId === agent.template.crossingId + && other.state.distance < conflict.distance + other.length + 3)), + "crossing entry cannot interrupt a reserved vehicle movement"); + } + if (agent.template.kind === "vehicle" && before.active && !agent.state.active) { + assert.ok(agent.state.distance >= agent.route.length + 120, + "vehicles leave only beyond the visible route, not at its short endpoint"); + } + if (before.active && !agent.state.active) completed.set(agent.template.id, (completed.get(agent.template.id) || 0) + 1); + }); + if (frame % 5 === 0) { + const visible = real.agents.filter((agent) => agent.state.active && seconds >= agent.state.spawnDelay + && agent.state.distance >= 0 && agent.state.distance < agent.route.length); + for (let i = 0; i < visible.length; i += 1) { + for (let j = i + 1; j < visible.length; j += 1) { + assert.ok(!overlaps(footprint(visible[i]), footprint(visible[j])), + `body overlap at ${seconds}s: ${visible[i].template.id} / ${visible[j].template.id}`); + } + } + } + } + for (const template of descriptor.participants) { + assert.ok(completed.get(template.id) > 0, `${template.id} must clear the junction within 600 s`); + } + console.log("Real junction: 600 s passed, every movement and crossing completed:", Object.fromEntries(completed)); +} diff --git a/scripts/test-preview-assets.js b/scripts/test-preview-assets.js index 9330955..ac23c4f 100644 --- a/scripts/test-preview-assets.js +++ b/scripts/test-preview-assets.js @@ -297,7 +297,29 @@ assert.match(v2xRuntime, /\/network\/ws\/network\/targetPosition/); assert.match(v2xRuntime, /headingPitchRollQuaternion/); assert.match(v2xRuntime, /model:/); assert.match(previewRuntime, /createLiveTrafficSignals\(/); -assert.match(previewRuntime, /addTrafficSignals\(viewer, signalData, trafficStart, assets\)/); +assert.match(previewRuntime, /addTrafficSignals\(viewer, signalData, trafficStart, assets, routeData\?\.signalPlan, trafficEpochMs\)/, + "native lamps must use the same route signal plan and epoch as the local participant simulation"); +assert.match(previewRuntime, /createParticipantSimulation\(viewer, templates, start, speed, routeData\.settings \|\| \{\}, routeData\.signalPlan, trafficEpochMs\)/, + "local participant decisions must use the plan that drives the lamps"); +assert.match(previewRuntime, /elapsed < initialAllRedSeconds/, + "the startup clearance must hold every signal group and participant before release"); +assert.match(previewRuntime, /phaseState\.initialClearance/, + "pedestrians and bicycles must not treat the startup all-red clearance as a walk phase"); +assert.match(previewRuntime, /crossingUsersById/, "vehicles must yield while a pedestrian or bicycle occupies a conflicting zebra crossing"); +assert.match(previewRuntime, /if \(isCrossing\(agent\) && state\.distance >= 0\) state\.committed = true/, + "crossing users retain permission once physically entering the zebra"); +assert.match(previewRuntime, /const gapBuffer = crossingAgent \? 1\.5 : minimumGapMeters/, + "pedestrian and bicycle queues use a short physical gap"); +assert.match(previewRuntime, /const requiredGap = \(leader\.length \+ agent\.length\) \/ 2 \+ gapBuffer/, + "queue spacing must account for both vehicles' physical lengths"); +assert.match(previewRuntime, /leaderAgent\.state\.distance - physicalGap/, + "a following vehicle must be hard-clamped before its leader's physical envelope"); +assert.match(previewRuntime, /crossingYieldDistance - agent\.length \/ 2 - 2/, + "crossing yield includes the front bumper and a safety margin"); +assert.match(previewRuntime, /state\.respawnDelay = arrivalDelay\(agent\)/, + "participants return according to their arrival headway"); +assert.match(previewRuntime, /stopReason: stop\.stopReason \|\| "traffic-signal"/, + "participant control must preserve the type of its controlling stop point"); // The lamp dictionary lives only in the overlay, which hands the preview // already-normalized {nodeKeys, color, countDown} entries. Two copies of the