Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25cf82e7c7 | ||
|
|
bc845444bb | ||
|
|
bb2a1449ac | ||
|
|
1c2d091ad2 | ||
|
|
e997ece188 | ||
|
|
b7031f145a | ||
|
|
ee273c5cd6 | ||
|
|
71ba536c7c | ||
|
|
903b34b5ae | ||
|
|
f1f829c2c6 | ||
|
|
a16400ff96 | ||
|
|
8ecd794633 | ||
|
|
12aeda9a63 | ||
|
|
9a8dbc1a74 |
No files matched your search
@@ -4,3 +4,4 @@ outputs/
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
assets/models/speedtree/
|
assets/models/speedtree/
|
||||||
assets/models/lyrog/
|
assets/models/lyrog/
|
||||||
|
inputs/osm
|
||||||
@@ -54,6 +54,8 @@ cp config/examples/template.json config/areas/my-area.json
|
|||||||
| `turnLaneArrows` | | 见下 | 从 OSM `turn:lanes:*` 生成自定义车道箭头的发布开关 |
|
| `turnLaneArrows` | | 见下 | 从 OSM `turn:lanes:*` 生成自定义车道箭头的发布开关 |
|
||||||
| `osm2streets` | | 见下 | 透传给 osm2streets 的选项 |
|
| `osm2streets` | | 见下 | 透传给 osm2streets 的选项 |
|
||||||
| `blender` | | 见下 | Blender 侧选项 |
|
| `blender` | | 见下 | Blender 侧选项 |
|
||||||
|
| `nativeRoad` | | 见下 | 原生道路编译选项 |
|
||||||
|
| `v2xPreview` | | 见下 | 可选的 Cesium 预览实时 V2X 叠加设置 |
|
||||||
| `compress` | | 见下 | 默认交付压缩阶段的 GLB 压缩选项 |
|
| `compress` | | 见下 | 默认交付压缩阶段的 GLB 压缩选项 |
|
||||||
| `budget` | | 见下 | 区域 GLB 性能与体量预算 |
|
| `budget` | | 见下 | 区域 GLB 性能与体量预算 |
|
||||||
| `outputs` | | 从 `id` 推导 | 输出路径覆盖,逃生舱 |
|
| `outputs` | | 从 `id` 推导 | 输出路径覆盖,逃生舱 |
|
||||||
@@ -134,6 +136,35 @@ cp config/examples/template.json config/areas/my-area.json
|
|||||||
| `officeOverrides` | `""` | 旧名 `office_overrides` 仍被接受 |
|
| `officeOverrides` | `""` | 旧名 `office_overrides` 仍被接受 |
|
||||||
| `roadProvider` | `"native"` | Blender 道路来源。`"native"` 时仅使用 `native-road/` 的道路、路口和人行道面;`"osm2streets"` 仅用于显式 legacy/debug 构建。 |
|
| `roadProvider` | `"native"` | Blender 道路来源。`"native"` 时仅使用 `native-road/` 的道路、路口和人行道面;`"osm2streets"` 仅用于显式 legacy/debug 构建。 |
|
||||||
|
|
||||||
|
### `nativeRoad`
|
||||||
|
|
||||||
|
| 字段 | 默认 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `edgeLines` | `false` | 是否输出道路边缘线。 |
|
||||||
|
| `junctionTemplates.enabled` | `false` | 启用显式绑定的参数化路口模板。 |
|
||||||
|
| `junctionTemplates.references` | `[]` | 仅支持 `cross-v1`;每项必须给出 OSM `nodeId`,可带 GCJ-02 `referenceFile` 作校准与有效性检查。 |
|
||||||
|
| `junctionTemplates.clusters` | `[]` | `cross-cluster-v1` 的相邻 OSM 节点簇。输出各外部进口的参数化渐变道路面,簇内短段与节点级路口面保留;`approachWidthMultiplier` / `approachLengthMeters` 控制渐变。可选 `referenceFile` 记录 GCJ-02 校准来源,不合并节点级道路、connector、信号或停止线语义。 |
|
||||||
|
| `junctionTemplates.clusters[].cornerRadiusMeters` | `12`(4–25) | 仅 `complex-junction-v1`:相邻进口夹角处路缘圆角的半径。圆角切于两侧最外道路边缘,只补齐夹角处的路面,不改变 connector、信号或停止线。 |
|
||||||
|
| `junctionTemplates.clusters[].outerRadiusExtraMeters` | `18`(18–35) | 仅 `complex-junction-v1`:路口中心到外部进口交接边界的额外半径。用于让圆角包住角部斑马线;未配置时保持原有 18 m。 |
|
||||||
|
|
||||||
|
### `v2xPreview`
|
||||||
|
|
||||||
|
这是 Cesium 验证预览的可选实时叠加层,不进入发布的 `package/`。默认值:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"enabled": false,
|
||||||
|
"apiBaseUrl": "/api",
|
||||||
|
"wsBaseUrl": "/websocket",
|
||||||
|
"crossCode": ""
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`apiBaseUrl` 和 `wsBaseUrl` 应使用同源反向代理路径,不能写入私有上游主机、账号或令牌。
|
||||||
|
V2X 接口返回的地图数据是 GCJ-02;浏览器预览在创建 Cesium entity 前一次性转为 WGS84,
|
||||||
|
而 native package 的 WGS84/ENU 契约保持不变。详见
|
||||||
|
[`docs/v2x-cesium-preview.md`](../../../docs/v2x-cesium-preview.md)。
|
||||||
|
|
||||||
### `compress`
|
### `compress`
|
||||||
|
|
||||||
完整构建和显式 `--stages compress` 都使用此配置。默认压缩链是 texture resize + WebP
|
完整构建和显式 `--stages compress` 都使用此配置。默认压缩链是 texture resize + WebP
|
||||||
|
|||||||
@@ -815,6 +815,32 @@ area.outputs.trafficSignals
|
|||||||
- `layout.mastHeightMeters` 与 `layout.headCenterHeightMeters` 必须相等,表示横杆与灯壳的
|
- `layout.mastHeightMeters` 与 `layout.headCenterHeightMeters` 必须相等,表示横杆与灯壳的
|
||||||
中心对齐;`lensVerticalOffsetsMeters` 以灯壳中心为基准,正值向上、负值向下。当前倒计时牌
|
中心对齐;`lensVerticalOffsetsMeters` 以灯壳中心为基准,正值向上、负值向下。当前倒计时牌
|
||||||
垂直偏移为 `0`,必须贴在横杆上而非悬挂。
|
垂直偏移为 `0`,必须贴在横杆上而非悬挂。
|
||||||
|
- 复合路口中,具有相同 `cluster_id` 的停止线按道路轴线匹配 OSM control arm;轴线的两个
|
||||||
|
极性必须视为等价,但每条候选停止线仍只能消费一次。普通路口继续使用有向进口匹配,不能
|
||||||
|
用复合路口的无向规则覆盖普通路口。
|
||||||
|
- 复合路口的中心绿化带/中央分隔带不由 native 复合模板伪造;模板只生成 OSM 道路和路口
|
||||||
|
内必要的安全岛。每条生成的复合进口车道须在停止线外侧上游约 `8m` 生成一支与车道拓扑
|
||||||
|
一致的左转、直行或右转箭头;不得额外叠加一套固定直行箭头。
|
||||||
|
- **控制要素避让顺序**:`buildComplexJunctionGeometry` 在 `compileLaneCenterlines` 之前生成,
|
||||||
|
产出的 `complex-crosswalk` / `complex-corner-crosswalk` / `complex-stop-line` 必须以
|
||||||
|
`{ crosswalks, stopLines }` 参数传入 `compileLaneCenterlines`。车道中心线、车道分隔线、
|
||||||
|
中心虚线、导向箭头都在这一裁剪之后才落地。这里的裁剪对象包括两类车道几何:一是簇
|
||||||
|
边界上的 OSM 车道,二是模板自造的 `cluster-approach-lane` 预览车道。裁剪必须先按到
|
||||||
|
路口中心的距离把线定向为“外向内”,再复用 `trimLineBeforeFirstControl`:因为 OSM 车道
|
||||||
|
由簇边缘向外指、预览车道由外圈向核心指,两种朝向都存在,直接裁会裁反。裁剪后的几何
|
||||||
|
同时喂给车道标线源(`markingLanes[i].coordinates`),否则分隔线/箭头会画到斑马线之外
|
||||||
|
继续侵入核心区。拓扑几何 `coordinates`(供 connector 使用)不得裁剪,否则 turn path
|
||||||
|
会断。发布几何 vs 拓扑几何的双轨在 `compileLaneCenterlines` 内并存,别合并。
|
||||||
|
- **复合路口人行道转角**:直步行带被 `trimLineAtComplexCluster` 裁在簇外圈,两条相邻的
|
||||||
|
臂之间会留一个楔形无覆盖区。转角带由 `buildComplexJunctionGeometry` 与 `complex-corner-fillet`
|
||||||
|
共用同一 `curve` / `tangents` / `edges` / `apex` 复用生成,不重新拟合曲线;宽度
|
||||||
|
`SIDEWALK_WIDTH_METERS = 2` 必须与 `native-road.js:DEFAULT_SIDEWALK_WIDTH_METERS` 保持
|
||||||
|
一致,法线方向按“离簇中心更远”选取(路缘相对中心是星形的)。判定两侧臂是否都带步行带
|
||||||
|
时必须按臂的外向方向翻转 road 自身的 `sidewalkLeft/Right`,因为那是相对数字化方向的。
|
||||||
|
端头以 `SIDEWALK_CORNER_OVERRUN_METERS = 6` 冗余越过簇边界,让转角带和直条带自然重叠,
|
||||||
|
不追求精确缝合。自交(`ringSelfIntersects`)或任一坐标非有限时跳过并报
|
||||||
|
`complex-junction-sidewalk-corner-fallback`;不允许硬塞坏几何。产物经 `islands` 通道
|
||||||
|
与安全岛一同并入 `generatedComplexSidewalks`,最终落入 `sidewalk_surface.geojson`。
|
||||||
|
|
||||||
### 4. Validation & Error Matrix
|
### 4. Validation & Error Matrix
|
||||||
|
|
||||||
@@ -824,6 +850,9 @@ area.outputs.trafficSignals
|
|||||||
| 直接运行 `blender` / `preview` 但锚点不存在 | 在启动外部工具前报 `Traffic signal anchors not found` |
|
| 直接运行 `blender` / `preview` 但锚点不存在 | 在启动外部工具前报 `Traffic signal anchors not found` |
|
||||||
| `signal_uid` 缺失/重复、非空 `display_id` 重复、字段或 Point 无效 | 重导入在替换任何输出前失败 |
|
| `signal_uid` 缺失/重复、非空 `display_id` 重复、字段或 Point 无效 | 重导入在替换任何输出前失败 |
|
||||||
| 用户仅修改 QGIS 后运行 `reimport` | 重新生成锚点,不沿用旧坐标 |
|
| 用户仅修改 QGIS 后运行 `reimport` | 重新生成锚点,不沿用旧坐标 |
|
||||||
|
| 复合路口车道整体落在斑马线/停止线内 | 报 `lane-centerline-fully-inside-control`,回退为未裁剪发布几何,不写空 LineString |
|
||||||
|
| 复合路口人行道转角自交或坐标非有限 | 报 `complex-junction-sidewalk-corner-fallback`,跳过该角,两侧步行带保持断开 |
|
||||||
|
| 有 `referenceFile` 时同时配置 `coreRadiusMeters` | 校准值胜出,报 `complex-junction-configured-radius-ignored` 记录被忽略的配置值 |
|
||||||
|
|
||||||
### 5. Good/Base/Bad Cases
|
### 5. Good/Base/Bad Cases
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
| 加阶段、加 CLI 参数、改配置字段 | [CLI 与阶段](./cli-and-stages.md) |
|
| 加阶段、加 CLI 参数、改配置字段 | [CLI 与阶段](./cli-and-stages.md) |
|
||||||
| 改区域诊断/质量门命令或共享区域配置归一化 | [CLI 与阶段](./cli-and-stages.md#区域诊断命令) 和 [质量门](./cli-and-stages.md#区域质量门命令) |
|
| 改区域诊断/质量门命令或共享区域配置归一化 | [CLI 与阶段](./cli-and-stages.md#区域诊断命令) 和 [质量门](./cli-and-stages.md#区域质量门命令) |
|
||||||
| 改 stage manifest 写入、读取或 stale 判断 | [CLI 与阶段](./cli-and-stages.md#stage-manifest-契约) |
|
| 改 stage manifest 写入、读取或 stale 判断 | [CLI 与阶段](./cli-and-stages.md#stage-manifest-契约) |
|
||||||
|
| 改复合路口几何(`buildComplexJunctionGeometry`、车道控制避让、人行道转角) | [CLI 与阶段](./cli-and-stages.md#可编辑信号设施与运行时锚点的跨阶段消费) 的复合路口小节 |
|
||||||
| 改预览页生成 | [../preview/](../preview/index.md) |
|
| 改预览页生成 | [../preview/](../preview/index.md) |
|
||||||
| 声称"纯重构,产物不变" | [产物一致性指南](../guides/artifact-parity-guide.md) |
|
| 声称"纯重构,产物不变" | [产物一致性指南](../guides/artifact-parity-guide.md) |
|
||||||
|
|
||||||
|
|||||||
@@ -307,6 +307,105 @@ npm run build:area -- --config config/areas/<area>.json --stages cesium
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 实时 V2X 车辆仅数据源
|
||||||
|
|
||||||
|
### 1. Scope / Trigger
|
||||||
|
|
||||||
|
适用于开启 `v2xPreview.enabled` 的 Cesium 运营预览。触发:修改
|
||||||
|
`v2x-cesium-overlay.js`、preview descriptor 的 `routeName`、或实时车辆展示。
|
||||||
|
|
||||||
|
### 2. Signatures
|
||||||
|
|
||||||
|
```text
|
||||||
|
WS /network/ws/network/signal?authorization=<token>
|
||||||
|
WS /network/ws/network/obuPosition?authorization=<token>
|
||||||
|
WS /network/ws/network/targetPosition?authorization=<token>
|
||||||
|
```
|
||||||
|
|
||||||
|
OBU 消息使用 `carCode|obuCode`、`lon`、`lat`、`angle`、`speed`;目标识别消息使用
|
||||||
|
`data[deviceId][]` 内的 `id`、`longitude`、`latitude`、`type`、`subType`、`angle`、`speed`。
|
||||||
|
两类车辆消息的根部还带 `interval`(推送间隔,`0` 视为 `500`)。
|
||||||
|
信号灯消息使用 `lamps[]` 内的 `phaseNo`、`status`、`countDown`。
|
||||||
|
|
||||||
|
### 3. Contracts
|
||||||
|
|
||||||
|
- 两条车辆流均为 GCJ-02,必须在实体创建前恰好调用一次 `gcj02ToWgs84`。
|
||||||
|
- 本预览的 `routeName` 必须为 `null`,且不得生成 `trafficSimulation` 描述符。
|
||||||
|
真正的不变量是**不得有生成路线或交通仿真**,而不是「没有车模型」——
|
||||||
|
实时 V2X 车辆需要打包的车模型才能渲染,故 `vehicleModelNames` 由
|
||||||
|
`writeVehicleModel(area)` 正常写出(`build-area.js:writeCesiumPreview`),
|
||||||
|
`vehicleModelName` 取其首项。早期版本靠清空模型列表来阻止仿真车辆,
|
||||||
|
该机制已不适用,不要再用它作为约束手段。
|
||||||
|
- 每辆实时车保留最多 24 个已转换的位置作为实际轨迹;轨迹不是推测路径。
|
||||||
|
- **灯色码字典只有一份**,取自源看板 `HologramCross/components/utils.ts`:
|
||||||
|
`11=灭 21=红 22=黄 23=绿 31=其他`,未知码归入「其他」,**不得**落到红色。
|
||||||
|
overlay 归一化为 `{nodeKeys, color, countDown}` 后单向传给 `cesium-preview.js`;
|
||||||
|
预览层不得自带第二份字典。
|
||||||
|
- **三条 socket 必须发心跳** `{"heartBeat":"ping"}` / 30000ms,并在断线后退避重连,
|
||||||
|
且**重连后重放订阅帧**(signal 发 `junctionId`,obu 发 bounds,target 发 `deviceId`)。
|
||||||
|
缺心跳会被服务端断开,画面在一分钟后静默变空。
|
||||||
|
- **相位到原生灯头靠几何绑定**:`traffic-signals.json` 无 `phaseNo`,用 link 末段停止线点与
|
||||||
|
航向匹配原生 `stopLongitude/stopLatitude` 与行车方向;行车方向 =
|
||||||
|
`faceHeadingDegrees + 180`(生成侧 `scripts/lib/traffic-signals.js` 定义
|
||||||
|
`mast = travel - 90`、`face = travel + 180`)。
|
||||||
|
一相位可点亮多条进口道,一条 link 可点亮同进口道多个灯头,两侧都取并集。
|
||||||
|
未绑定相位须计数上报,可用 `v2xPreview.phaseSignalMap` 显式覆盖。
|
||||||
|
- **车辆生命周期**:超过 `interval * 1.5` 未更新即隐藏(不删除),隐藏项作为同模型的可复用槽位;
|
||||||
|
socket 断开清空车辆。OBU 数据 hook 标记为 `car_obu.glb`,但 dashboard 的最终
|
||||||
|
`CrossCars` 模板实际渲染 `11.glb`,预览必须以 `11.glb` 为准;目标车为
|
||||||
|
`${type}${subType}.glb`。`11/12/13/14/15/16/17/31/221/222.glb` 必须打入
|
||||||
|
`_preview/v2x-vehicles/`。
|
||||||
|
- **可见性是运行时契约**:有效推送创建的模型必须在路口概览下至少为 `28px`,并允许最大
|
||||||
|
`8x` 放大;位置高度须高于静态道路表面。首次有效车辆推送应聚焦到车群附近,标签须不受
|
||||||
|
静态 GLB 的深度遮挡。仅验证 WS 收包或 registry 条数不算通过。
|
||||||
|
- 车辆推送体解析必须容忍非严格 JSON(源看板用 `saferEval`),失败须计数并在面板可见,
|
||||||
|
**不得**静默丢弃;实现不得使用 `eval` / `new Function`。
|
||||||
|
- 周流量比 `FlowTravelRatio/queryListWeek` **不属于**实时路口范围。
|
||||||
|
|
||||||
|
### 4. Validation & Error Matrix
|
||||||
|
|
||||||
|
| 条件 | 结果 |
|
||||||
|
|---|---|
|
||||||
|
| 未登录、令牌失效、REST/WS 不可用 | 静态路口继续显示,车辆层为空,并显示实时数据不可用状态 |
|
||||||
|
| 消息不是 JSON、心跳、坐标无效 | 忽略该消息,不创建车辆;非心跳的解析失败须计数 |
|
||||||
|
| 收到有效车辆坐标 | 创建或更新真实车辆与实际轨迹 |
|
||||||
|
| 车辆超过 `interval * 1.5` 未更新 | 隐藏该车并保留槽位,不得堆积幽灵车 |
|
||||||
|
| 相机视野变化 | 节流后向 obu socket 发送 GCJ-02 四角 `bounds` |
|
||||||
|
| 视野矩形不可用 | 发空帧(等于不过滤),不得跳过发送导致空场景 |
|
||||||
|
| 相位一个都没绑定 | 面板显性提示并建议配置 `phaseSignalMap` |
|
||||||
|
|
||||||
|
### 5. Good / Base / Bad Cases
|
||||||
|
|
||||||
|
- Good:OBU 和感知目标连续推送,页面只显示对应车辆的实际行驶轨迹。
|
||||||
|
- Base:服务无数据,页面没有车辆或线路。
|
||||||
|
- Bad:将旧路线 JSON 或 `native-preview-traffic-simulation` 用作回退展示。
|
||||||
|
|
||||||
|
### 6. Tests Required
|
||||||
|
|
||||||
|
- `npm run test:v2x-cesium-preview`:校验灯色字典(含 `2`/`3` 不再是黄/绿的回归断言)、
|
||||||
|
宽松解析、几何相位绑定(对真实 `traffic-signals.json` 须达成精确一对一)、
|
||||||
|
同相位多进口道并集、车辆超时与槽位复用、心跳间隔与重连重放订阅帧、bounds 报文。
|
||||||
|
- `npm run test:preview-assets`:断言三条 WebSocket 存在,runtime 不调用
|
||||||
|
`addVehicleCruises`、不显示 simulation 诊断,且预览层**不再自带** `lampColorName`
|
||||||
|
或 `Number(status) === 3` 判断;断言实时车辆最小像素尺寸和诊断可见数量读数存在。
|
||||||
|
- 对目标区域运行 `npm run build:area -- --config config/areas/<area>.json --stages preview`,
|
||||||
|
检查 descriptor 中 `routeName` 为空、不存在 traffic-simulation 文件,
|
||||||
|
且 `vehicleModelNames` 已写出(实时车辆渲染需要)。
|
||||||
|
|
||||||
|
### 7. Wrong vs Correct
|
||||||
|
|
||||||
|
错误:接口不可用时恢复构造路线。
|
||||||
|
|
||||||
|
```js
|
||||||
|
const cruise = addVehicleCruises(viewer, routeData, signalData, start);
|
||||||
|
```
|
||||||
|
|
||||||
|
正确:保持空车辆层,等待真实流。
|
||||||
|
|
||||||
|
```js
|
||||||
|
const cruise = createLiveVehicleState();
|
||||||
|
```
|
||||||
|
|
||||||
## 本地预览必须走 HTTP
|
## 本地预览必须走 HTTP
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{"file": ".trellis/spec/preview/index.md", "reason": "校验改动未违反预览层约束:零依赖、无构建步骤、浏览器原生语法、IIFE。"}
|
||||||
|
{"file": "docs/v2x-cesium-preview.md", "reason": "校验文档与实现一致:接口清单、坐标契约、配置项、回滚说明。"}
|
||||||
|
{"file": ".trellis/tasks/08-24-v2x-realtime-cross-fidelity/prd.md", "reason": "AC1-AC10 是验收依据,逐条核对。"}
|
||||||
|
{"file": ".trellis/tasks/08-24-v2x-realtime-cross-fidelity/design.md", "reason": "核对灯色字典、相位映射算法、心跳与订阅帧是否与源项目逐项对齐。"}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
# Design — 还原 V2X 实时路口信号灯与车辆展示
|
||||||
|
|
||||||
|
## 1. 现状与根因
|
||||||
|
|
||||||
|
`scripts/lib/v2x-cesium-overlay.js`(418 行,单个 IIFE)承担了登录、REST、三个 WS、坐标转换、
|
||||||
|
实体渲染的全部职责。REST 路径与登录契约与源项目一致,失真集中在数据处理与渲染层。
|
||||||
|
|
||||||
|
逐项根因(对应 PRD 的 R1–R10):
|
||||||
|
|
||||||
|
| # | 现象 | 根因位置 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| R1 | 连接几十秒后静默中断 | `openSocket()` 无心跳、无重连 |
|
||||||
|
| R2 | 灯永远红 | `lampColor()` 判 `2`/`3`;真实码是 `21/22/23` |
|
||||||
|
| R3 | 原生信号灯模型从不亮 | `signalByPhase` 回退 `signal.id`,与 `phaseNo` 永不相等 |
|
||||||
|
| R4 | 同相位只亮一条进口道 | `state.linkPhases` 是 `Map<phase, entity>`,后写覆盖 |
|
||||||
|
| R5 | 无倒计时 | `updateSignalPhases()` 丢弃 `countDown` |
|
||||||
|
| R6 | OBU 可能一辆车都没有 | `connectObuSocket()` 的 `onOpen` 传 `null`,未发订阅帧 |
|
||||||
|
| R7 | 幽灵车堆积 | `state.vehicles` 只增不删,未用推送 `interval` |
|
||||||
|
| R8 | 车型错配 | 按数组下标取模型,非 `${type}${subType}` 语义 |
|
||||||
|
| R9 | 推送可能整条被丢 | `JSON.parse` + 静默 `catch`,源项目用 `saferEval` |
|
||||||
|
| R10 | 多余请求 | `FlowTravelRatio/queryListWeek` 不属实时路口 |
|
||||||
|
|
||||||
|
## 2. 边界与不变量
|
||||||
|
|
||||||
|
保持不变:
|
||||||
|
- overlay 仍是**单文件零依赖 IIFE**,由 `build-area.js:561` 原样拷入产物。不新增文件,避免改动
|
||||||
|
`area-preview.js` 的 HTML 装配与包契约。
|
||||||
|
- 纯逻辑继续通过 `createV2xCesiumOverlay.utils` 导出,供 `scripts/test-v2x-cesium-overlay.js`
|
||||||
|
的 `vm.runInNewContext` 沙箱直接测试(无 DOM、无 Cesium)。
|
||||||
|
- 坐标契约不变:GCJ-02 → WGS84 只在建实体前转一次。
|
||||||
|
- 令牌只进 `sessionStorage`,页面始终从登录门进入。
|
||||||
|
|
||||||
|
新增的可测试纯函数一律**不触碰 `window` / `Cesium` / `document`**,副作用留在薄薄的适配层。
|
||||||
|
|
||||||
|
## 3. 模块内部分层
|
||||||
|
|
||||||
|
文件内按四层组织,自下而上:
|
||||||
|
|
||||||
|
```
|
||||||
|
L1 纯工具 gcj02ToWgs84 / joinUrl / md5 / toWebSocketUrl / getAngle / haversine
|
||||||
|
L2 纯解析 lampColorName / parseLoosePayload / normalizeObuVehicle /
|
||||||
|
normalizeTargetVehicles / normalizeSignalLamps
|
||||||
|
L3 纯状态机 createVehicleRegistry / createPhaseBinding / buildPhaseSignalMap
|
||||||
|
L4 副作用层 createSocket(心跳/重连) / 实体渲染 / UI 面板
|
||||||
|
```
|
||||||
|
|
||||||
|
L1–L3 全部导出到 `.utils`,测试只打 L1–L3。
|
||||||
|
|
||||||
|
## 4. 关键设计决策
|
||||||
|
|
||||||
|
### 4.1 灯色状态字典(R2)
|
||||||
|
|
||||||
|
直接采用源项目 `HologramCross/components/utils.ts` 的字典,语义化返回而非直接返回颜色,
|
||||||
|
使 overlay 与 `cesium-preview.js` 共用同一套判定:
|
||||||
|
|
||||||
|
```
|
||||||
|
11 -> "off" 灭灯
|
||||||
|
21 -> "red"
|
||||||
|
22 -> "yellow"
|
||||||
|
23 -> "green"
|
||||||
|
31 -> "other"
|
||||||
|
其他 -> "other" // 不再落到 red
|
||||||
|
```
|
||||||
|
|
||||||
|
`lampColorName(status)` 放在 overlay 的 L2 并导出。`cesium-preview.js` 中重复的
|
||||||
|
`lampColorName()` 删除,改为消费 overlay 通过 `setSignalState` 回调传入的**已归一化**灯态
|
||||||
|
(`{nodeKeys, color, countDown}`),避免两处字典漂移。
|
||||||
|
|
||||||
|
> 取舍:也可以把字典抽到共享文件让两边 require,但 overlay 必须是浏览器端零依赖 IIFE,
|
||||||
|
> `cesium-preview.js` 同样是浏览器端脚本,两者无模块系统。让数据流单向(overlay → preview)
|
||||||
|
> 比共享常量更简单,也消除了双字典。
|
||||||
|
|
||||||
|
### 4.2 相位 → 原生信号灯映射(R3,本任务最难的一处)
|
||||||
|
|
||||||
|
`traffic-signals.json` 的信号灯项只有 `phaseGroup: 0`,**不含 V2X `phaseNo`**,两侧没有公共 ID。
|
||||||
|
唯一可靠的连接是**几何**。
|
||||||
|
|
||||||
|
源项目的做法给了线索:`CrossTrafficLights3D.vue:96-104` 对每条 link 取 `geom.coordinates` 的
|
||||||
|
最后两点,末点即停止线位置,两点连线的方位角即进口道航向。原生信号灯项恰好也有
|
||||||
|
`stopLongitude/stopLatitude` 与 `headingDegrees`。
|
||||||
|
|
||||||
|
因此定义纯函数:
|
||||||
|
|
||||||
|
```
|
||||||
|
buildPhaseSignalMap(links, nativeSignals, options) -> {
|
||||||
|
byPhase: Map<phaseNo, string[]>, // nodeKey 列表
|
||||||
|
bound: number,
|
||||||
|
unbound: Array<{phaseNo, reason}>,
|
||||||
|
diagnostics: Array<{linkId, matchedNodeKeys, distanceMeters, headingDeltaDegrees}>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
算法:
|
||||||
|
1. 对每条 link:解析 `geom`,取末两点,**先 GCJ-02 → WGS84**,再算 `stopPoint` 与
|
||||||
|
`approachHeading = getAngle(prePoint, lastPoint)`。
|
||||||
|
2. 对每个原生 signal:取 `(stopLongitude, stopLatitude)` 与**行车方向**。
|
||||||
|
|
||||||
|
行车方向的语义由生成侧 `scripts/lib/traffic-signals.js` 定死,不是猜的:
|
||||||
|
- `:54` `headingDegrees = atan2(axis)`,而 `axis = roadAxis(stopLineCenter → intersectionCenter)`,
|
||||||
|
即**停止线指向路口中心的行车方向**。
|
||||||
|
- `:82` `mast_heading_deg = heading - 90`
|
||||||
|
- `:83` `face_heading_deg = heading + 180`
|
||||||
|
|
||||||
|
运行时 `traffic-signals.json` 中 `headingDegrees === mastHeadingDegrees`(实测 7/7 相等,
|
||||||
|
如 `150.658`),即存的是 **mast 值**;`faceHeadingDegrees` 比它小 90(`60.658`)。因此:
|
||||||
|
|
||||||
|
```
|
||||||
|
travelHeading = (faceHeadingDegrees + 180) % 360 // 首选
|
||||||
|
= (mastHeadingDegrees + 90) % 360 // face 缺失时的等价回退
|
||||||
|
```
|
||||||
|
|
||||||
|
实测对全部 7 个信号自洽。
|
||||||
|
3. 候选条件:`haversine(stopPoint, signalStop) <= maxDistanceMeters`
|
||||||
|
且 `angleDelta(approachHeading, travelHeading) <= maxHeadingDeltaDegrees`。
|
||||||
|
4. 一条 link **可匹配多个** signal(同一进口道的多个灯头),满足 R4 的一半。
|
||||||
|
5. link 的 `phaseList` 中每个 `phase` → 该 link 匹配到的全部 nodeKey,**并集累加**
|
||||||
|
(`Map<phaseNo, Set<nodeKey>>`),满足 R4 的另一半(同相位多进口道)。
|
||||||
|
6. 默认容差:`maxDistanceMeters = 30`、`maxHeadingDeltaDegrees = 45`。
|
||||||
|
7. 未匹配上的相位进入 `unbound`,面板显示「N 已绑定 / M 未绑定」。
|
||||||
|
|
||||||
|
**实现期修正**:设计初稿认为朝向语义不可判定,打算用「三字段 ± 180 的候选集,任一命中即可」。
|
||||||
|
实测该方案在凤树二路路口产生**严重误匹配** —— 一条 link 同时命中 3 条不同 `approachId` 的进口道
|
||||||
|
(距离 1.57 / 13.01 / 17.56 m,角差 3.8 / 7.8 / 5.4°),因为 ±180 × 三字段几乎放行任意 90° 朝向。
|
||||||
|
改为上述单一确定式后,7 条 link 对 7 个信号达成 **7/7 精确一对一**,误匹配为 0。
|
||||||
|
候选集方案已废弃。
|
||||||
|
|
||||||
|
|
||||||
|
**配置覆盖**:`v2xPreview.phaseSignalMap = { "<phaseNo>": ["<nodeKey>", …] }` 存在时,
|
||||||
|
该 phaseNo 直接用配置值,跳过几何匹配。这是几何匹配失败时的逃生舱,也让映射可人工固化。
|
||||||
|
|
||||||
|
> 取舍:不用 `approachId` / `sourceWayId` 匹配,因为那是 OSM 侧标识,V2X link 不携带;
|
||||||
|
> 不用最近邻唯一指派(匈牙利算法),因为一进口道多灯头是正常情况,强制一对一会漏灯。
|
||||||
|
> 容差可配是因为不同路口的停止线标注精度差异较大。
|
||||||
|
|
||||||
|
### 4.3 WebSocket 连接层(R1、R6)
|
||||||
|
|
||||||
|
新增 `createSocket({url, onOpen, onMessage, onClose, heartbeatMs, reconnect})` 副作用封装:
|
||||||
|
|
||||||
|
- 心跳:`setInterval(() => send('{"heartBeat":"ping"}'), 30000)`,与源项目一致。
|
||||||
|
- 重连:指数退避 `1s, 2s, 4s, 8s`,上限 `8s`,**重连成功后重新执行 `onOpen`**,
|
||||||
|
确保订阅帧(`junctionId` / `deviceId` / `bounds`)被重放。这是源项目 `onConnected` 的语义。
|
||||||
|
- `close()` 主动关闭时不触发重连;`dispose()` 清心跳与退避计时器。
|
||||||
|
- 计时器通过参数注入(`setIntervalFn` / `setTimeoutFn`),使重连与心跳逻辑可在测试中用假时钟驱动。
|
||||||
|
|
||||||
|
订阅帧内容严格对齐源项目:
|
||||||
|
|
||||||
|
| socket | 连接后首帧 | 来源 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| signal | `{"junctionId":"<crossCode>"}` | `CrossTrafficLights3D.vue:129` |
|
||||||
|
| obu | `bounds \|\| ""`(dashboard 传 `null` → 空串) | `useObuCars.ts:31` |
|
||||||
|
| target | `{"deviceId":"<ids>"}` 或 `{"deviceId":null}` | `useTargetCars.ts:50-53` |
|
||||||
|
|
||||||
|
OBU 的 bounds:源项目取 AMap 视野四角。本项目用 Cesium `camera.computeViewRectangle()`
|
||||||
|
换算成同格式 `lng,lat;lng,lat;lng,lat;lng,lat`(**WGS84 → GCJ-02 反向转换**,因为服务端按 GCJ-02
|
||||||
|
过滤),在 `camera.moveEnd` 时节流发送 `{"bounds": "<…>"}`。视野不可用时退回空串,等价于不过滤。
|
||||||
|
|
||||||
|
> 取舍:Cesium 是倾斜视角,`computeViewRectangle()` 在极端俯仰下可能返回 `undefined`;
|
||||||
|
> 此时退回空串而非跳过发送,保证仍能收到全量推送——宁可多收也不要空场景。
|
||||||
|
|
||||||
|
### 4.4 车辆注册表(R7、R8)
|
||||||
|
|
||||||
|
纯状态机 `createVehicleRegistry({now})`:
|
||||||
|
|
||||||
|
```
|
||||||
|
registry.ingest(vehicles, interval) -> {added, updated, hidden}
|
||||||
|
registry.sweep(nowMs) -> hiddenKeys
|
||||||
|
registry.list() -> VehicleRecord[]
|
||||||
|
```
|
||||||
|
|
||||||
|
- 复刻源项目:`interval = Number(payload.interval) === 0 ? 500 : Number(payload.interval)`。
|
||||||
|
- `sweep()`:`Math.abs(now - timeStamp) >= interval * 1.5` 时 `visible = false`。
|
||||||
|
- 槽位复用:新车优先占用同模型的 `visible === false` 记录(源项目 `useTargetCars.ts:110`),
|
||||||
|
减少 Cesium 实体的增删抖动。
|
||||||
|
- `now` 注入,测试用假时钟推进。
|
||||||
|
- socket `onClose` 时 `registry.clear()`,对齐源项目 `onDisconnected: cars.value = []`。
|
||||||
|
|
||||||
|
渲染适配层据 `visible` 切 `entity.show`,**不删实体**,与槽位复用配套。
|
||||||
|
|
||||||
|
模型选择(R8):OBU 的数据 hook 虽标记 `car_obu.glb`,但最终的 `CrossCars/index.vue` 模板固定
|
||||||
|
传入 `11.glb`,因此 `modelNameFor(vehicle)` 对 OBU 返回 `11.glb`;目标车辆返回
|
||||||
|
`${type}${subType}.glb`。预览阶段把 dashboard 的 `11/12/13/14/15/16/17/31/221/222.glb`
|
||||||
|
复制到 `_preview/v2x-vehicles/`,并在 `vehicleModelNames` 中按文件名匹配;未知车型回退 `11.glb`
|
||||||
|
并累加 `missingModels` 计数供面板展示。
|
||||||
|
|
||||||
|
平滑:用 `Cesium.SampledPositionProperty` 按 `duration` 插值,替代当前的直接赋值跳变。
|
||||||
|
|
||||||
|
### 4.5 宽松解析(R9)
|
||||||
|
|
||||||
|
源项目用 `saferEval`。浏览器端零依赖不能引入该库,也不应引入 `eval`。改为
|
||||||
|
`parseLoosePayload(text)`:先 `JSON.parse`;失败则做一次受限规范化(单引号→双引号、
|
||||||
|
裸键补引号、去尾逗号、`NaN`/`Infinity` → `null`)后重试;仍失败返回 `null` 并
|
||||||
|
`state.parseFailures += 1`,面板显示失败计数(R9 要求可见)。
|
||||||
|
|
||||||
|
> 取舍:不用 `new Function` 还原 `saferEval` 的完整语义——那等于在预览页开一个任意代码执行面。
|
||||||
|
> 受限规范化覆盖实际会遇到的非严格 JSON 形态,且失败可观测,比静默丢弃安全得多。
|
||||||
|
|
||||||
|
### 4.6 移除范围外请求(R10)
|
||||||
|
|
||||||
|
`loadLiveData()` 的 `Promise.allSettled` 去掉 `FlowTravelRatio/queryListWeek`,
|
||||||
|
`state.metrics` 及面板中的 `flow metrics` 文案一并移除。
|
||||||
|
|
||||||
|
## 5. 数据流
|
||||||
|
|
||||||
|
```
|
||||||
|
登录 → resolveCrossCode()
|
||||||
|
→ queryCrossLinkInfo / queryPoles / findDeviceByCrossCode / crossDeviceConfig
|
||||||
|
→ buildPhaseSignalMap(links, nativeSignals) [纯]
|
||||||
|
→ connectLiveSockets()
|
||||||
|
signal → normalizeSignalLamps → lampColorName → setSignalState({nodeKeys,color,countDown})
|
||||||
|
→ cesium-preview 点亮原生灯头 + 倒计时
|
||||||
|
obu → parseLoosePayload → normalizeObuVehicle ┐
|
||||||
|
target → parseLoosePayload → normalizeTargetVehicles ┴→ registry.ingest → 渲染适配
|
||||||
|
registry.sweep → entity.show
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. 兼容性与回滚
|
||||||
|
|
||||||
|
- `v2xPreview.enabled=false` 时 `createV2xCesiumOverlay()` 仍返回 `null`,生成页不含面板,
|
||||||
|
包产物字节不变(AC10)。
|
||||||
|
- 原生信号灯在**无 V2X 灯态时**的行为保持现状(`hideUnconfirmedSignalAssets` 语义不变),
|
||||||
|
只有收到实时灯态才点亮,不会退回模拟相位。
|
||||||
|
- 回滚点:本任务对 `cesium-preview.js` 的改动限于删除重复的 `lampColorName` 与调整
|
||||||
|
`setSignalState` 入参形状,可单独 revert 而不影响 overlay。
|
||||||
|
- 新增 `phaseSignalMap`、`maxDistanceMeters`、`maxHeadingDeltaDegrees` 均为可选配置,
|
||||||
|
缺省即当前默认行为。
|
||||||
|
|
||||||
|
## 7. 风险
|
||||||
|
|
||||||
|
| 风险 | 影响 | 缓解 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 几何匹配在实际路口全部落空 | 灯仍不亮 | 面板显性报「0 已绑定」;`phaseSignalMap` 配置覆盖兜底 |
|
||||||
|
| `computeViewRectangle()` 返回 undefined | OBU 过滤异常 | 退回空串=不过滤 |
|
||||||
|
| 宽松解析未覆盖真实非法形态 | 丢消息 | `parseFailures` 计数可见,便于按真实样本补规则 |
|
||||||
|
| 服务端心跳格式与源项目不符 | 仍被断开 | 心跳报文与间隔取自源项目源码,AC1 用模拟服务端验证 |
|
||||||
|
| 真实推送 `interval` 缺失 | 车辆过早隐藏 | 缺失时回退 500ms,与源项目一致 |
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{"file": ".trellis/spec/preview/index.md", "reason": "预览层契约:无构建步骤、零依赖 IIFE、参数经 window.OSM_ASSET_PREVIEW_CONFIG 注入。overlay 与 cesium-preview.js 的所有改动都受这些约束。"}
|
||||||
|
{"file": ".trellis/spec/pipeline/index.md", "reason": "确认 build-area.js 如何把 v2x-cesium-overlay.js 拷入产物,避免误增文件破坏包契约。"}
|
||||||
|
{"file": ".trellis/spec/config/index.md", "reason": "新增可选配置 v2xPreview.phaseSignalMap / maxDistanceMeters / maxHeadingDeltaDegrees 需符合区域配置约定。"}
|
||||||
|
{"file": "docs/v2x-cesium-preview.md", "reason": "现有 V2X 预览文档:配置项、坐标契约、代理要求、回滚方式。移除 FlowTravelRatio 与新增配置后需同步更新。"}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
# Implement — 还原 V2X 实时路口信号灯与车辆展示
|
||||||
|
|
||||||
|
## 参照实现(只读)
|
||||||
|
|
||||||
|
`/Users/que01/Project/v2x_web/applications/dashboard/src/views/dashboard/components/Content/Map/HologramCross/`
|
||||||
|
|
||||||
|
改动前先读对应源文件,不要凭记忆写契约。
|
||||||
|
|
||||||
|
## 改动文件
|
||||||
|
|
||||||
|
| 文件 | 性质 |
|
||||||
|
| --- | --- |
|
||||||
|
| `scripts/lib/v2x-cesium-overlay.js` | 主要改动,L1–L4 分层重写 |
|
||||||
|
| `scripts/lib/cesium-preview.js` | 删除重复 `lampColorName`,调整 `setSignalState` 入参 |
|
||||||
|
| `scripts/test-v2x-cesium-overlay.js` | 扩充单测,覆盖 AC2–AC7 |
|
||||||
|
| `.trellis/tasks/.../prd.md` `design.md` | 如实现中发现偏差需回写 |
|
||||||
|
|
||||||
|
不改:`build-area.js`、`area-preview.js`、包产物生成逻辑。
|
||||||
|
|
||||||
|
## 执行顺序
|
||||||
|
|
||||||
|
每步结束跑一次 `npm run test:v2x-cesium-preview`,保持绿色再进下一步。
|
||||||
|
|
||||||
|
### 步骤 1 — L2 灯色字典 + 宽松解析(R2、R9)
|
||||||
|
|
||||||
|
1. 在 overlay 加 `LAMP_STATUS`(`11/21/22/23/31`)与 `lampColorName(status)`,未知返回 `"other"`。
|
||||||
|
2. 删除旧 `lampColor()` 中 `Number(status)===3 / ===2` 的判断。
|
||||||
|
3. 加 `parseLoosePayload(text)`:`JSON.parse` → 受限规范化重试 → `null`。
|
||||||
|
4. 心跳报文 `pong` 短路判定保留(与源项目一致)。
|
||||||
|
5. 二者导出到 `.utils`。
|
||||||
|
|
||||||
|
验证:`node scripts/test-v2x-cesium-overlay.js`
|
||||||
|
- `lampColorName(21)==="red"`, `(22)==="yellow"`, `(23)==="green"`, `(11)==="off"`, `(31)==="other"`
|
||||||
|
- **`lampColorName(2)!=="yellow"` 且 `lampColorName(3)!=="green"`**(防回归,AC2)
|
||||||
|
- `parseLoosePayload("{'a':1,}")` 解析成功;`parseLoosePayload("{bad")===null`(AC7)
|
||||||
|
|
||||||
|
**审查点 A**:灯色字典必须与 `HologramCross/components/utils.ts` 的
|
||||||
|
`lightStatusColorDict` 逐项一致,不得增删码值。
|
||||||
|
|
||||||
|
### 步骤 2 — L1 几何工具(支撑 R3)
|
||||||
|
|
||||||
|
1. 加 `getAngle(start, end)`:直接对齐源项目 `utils.ts` 的实现(返回 0–360)。
|
||||||
|
2. 加 `haversineMeters(a, b)`、`angleDeltaDegrees(a, b)`(后者处理 350° vs 10° 的环绕)。
|
||||||
|
3. 导出到 `.utils`。
|
||||||
|
|
||||||
|
验证:正北 `getAngle([0,0],[0,1])≈0`;正东 `≈90`;
|
||||||
|
`angleDeltaDegrees(350,10)===20`;`haversineMeters` 对已知两点误差 < 0.5m。
|
||||||
|
|
||||||
|
### 步骤 3 — 相位映射(R3、R4)
|
||||||
|
|
||||||
|
1. 实现 `buildPhaseSignalMap(links, nativeSignals, options)`,返回
|
||||||
|
`{byPhase, bound, unbound, diagnostics}`,算法见 `design.md` §4.2。
|
||||||
|
2. link 末两点**先 GCJ-02→WGS84 再算角度与距离**(原生信号是 WGS84)。
|
||||||
|
3. 一 link 匹配多 signal;`Map<phaseNo, Set<nodeKey>>` 并集累加。
|
||||||
|
4. 支持 `options.phaseSignalMap` 配置覆盖,命中则跳过几何匹配。
|
||||||
|
5. 默认 `maxDistanceMeters=30`、`maxHeadingDeltaDegrees=45`。
|
||||||
|
6. 导出到 `.utils`。
|
||||||
|
|
||||||
|
验证(AC3、AC4):
|
||||||
|
- 用 `outputs/fengshu-er-road/package/runtime/traffic-signals.json` 的真实 7 条信号做夹具,
|
||||||
|
配一组构造的 link(末点取自 `stopLongitude/stopLatitude` 反算 GCJ-02、
|
||||||
|
航向取自 `headingDegrees`),断言 `bound > 0`。
|
||||||
|
- 构造两条不同 link 共用同一 `phaseNo`,断言 `byPhase.get(phaseNo)` 含**两条 link 的全部 nodeKey**。
|
||||||
|
- 构造一条远离所有信号的 link,断言其相位进入 `unbound` 且带 `reason`。
|
||||||
|
- 配置覆盖生效:`phaseSignalMap` 指定的 phaseNo 取配置值。
|
||||||
|
|
||||||
|
**审查点 B**:这是全任务最易做错的一步。合入前必须用真实 `traffic-signals.json` 跑出
|
||||||
|
非零绑定数,若为 0 则说明容差或坐标方向反了,**不得靠放大容差蒙混过关**——先打印
|
||||||
|
`diagnostics` 的实际距离/角差,确认量级合理(距离应是米级而非千米级)。
|
||||||
|
|
||||||
|
### 步骤 4 — 车辆注册表(R7、R8)
|
||||||
|
|
||||||
|
1. 实现 `createVehicleRegistry({now})`,含 `ingest / sweep / list / clear`。
|
||||||
|
2. `interval` 取自推送体,`0` 或缺失回退 `500`。
|
||||||
|
3. `sweep`:`|now - timeStamp| >= interval*1.5` → `visible=false`。
|
||||||
|
4. 槽位复用:优先占用同 `model` 的不可见记录。
|
||||||
|
5. `modelNameFor(vehicle)`:OBU → dashboard 最终模板使用的 `11.glb`;target → `${type}${subType}.glb`。把 dashboard 车辆 GLB 复制到预览包。
|
||||||
|
6. `normalizeTargetVehicles` 补上源项目的 `type==1 && isNil(subType) → subType=1`。
|
||||||
|
7. 导出 `createVehicleRegistry`、`modelNameFor`。
|
||||||
|
|
||||||
|
验证(AC5):
|
||||||
|
- 注入一次推送 → `list()` 一条 `visible=true`。
|
||||||
|
- 假时钟推进 `interval*1.5` 后 `sweep()` → 该车 `visible=false`。
|
||||||
|
- 再注入同 key → 复用原槽位,`list().length` 不变。
|
||||||
|
- `clear()` 后为空。
|
||||||
|
- `modelNameFor({kind:"obu"})==="11.glb"`;`{kind:"target",type:1,subType:2}` → `"12.glb"`。
|
||||||
|
|
||||||
|
### 步骤 5 — WebSocket 连接层(R1、R6)
|
||||||
|
|
||||||
|
1. 实现 `createSocket({url, onOpen, onMessage, onClose, heartbeatMs, reconnect, socketFactory, setIntervalFn, setTimeoutFn})`。
|
||||||
|
2. 心跳 `{"heartBeat":"ping"}` / 30000ms。
|
||||||
|
3. 退避重连 `1s→2s→4s→8s` 封顶,**重连成功重放 `onOpen`**。
|
||||||
|
4. 主动 `close()` 不重连;`dispose()` 清所有计时器。
|
||||||
|
5. 三个 socket 的订阅帧按 `design.md` §4.3 的表格实现。
|
||||||
|
6. OBU bounds:`camera.computeViewRectangle()` → WGS84→GCJ-02 → `"lng,lat;…"` 四角,
|
||||||
|
`camera.moveEnd` 节流发送;不可用时发空串。
|
||||||
|
7. 导出 `createSocket`、`buildBoundsMessage`。
|
||||||
|
|
||||||
|
验证(AC1、AC6):
|
||||||
|
- 假 socket + 假时钟:推进 30s 断言收到一帧 `{"heartBeat":"ping"}`;推进 90s 断言三帧。
|
||||||
|
- 模拟 `onclose` 后推进退避时间,断言重新建连**且订阅帧被重放**。
|
||||||
|
- signal 首帧 `{"junctionId":"<code>"}`;target 无配置首帧 `{"deviceId":null}`,
|
||||||
|
有配置 `{"deviceId":"1,2"}`;obu 首帧为空串。
|
||||||
|
- `dispose()` 后推进时钟不再产生任何发送。
|
||||||
|
|
||||||
|
**审查点 C**:心跳报文与间隔必须逐字节对齐源项目
|
||||||
|
(`useObuCars.ts:28-31`、`useTargetCars.ts:27-30`、`CrossTrafficLights3D.vue:122-130`)。
|
||||||
|
|
||||||
|
### 步骤 6 — 接线与渲染适配(R4、R5、R10)
|
||||||
|
|
||||||
|
1. `loadLiveData()` 移除 `FlowTravelRatio/queryListWeek`,删 `state.metrics` 与面板 flow 文案。
|
||||||
|
2. 用 `buildPhaseSignalMap` 结果替换 `state.linkPhases`(`Map<phase, entity>` 整体删除)。
|
||||||
|
3. `updateSignalPhases` → 归一化为 `{nodeKeys, color, countDown}` 列表后调
|
||||||
|
`context.setSignalState(...)`,同时给 link polyline 上色(同相位多 link 全部上色)。
|
||||||
|
4. 车辆渲染改为消费 `registry`:`visible` 切 `entity.show`,位置用
|
||||||
|
`SampledPositionProperty` 按 `duration` 插值。
|
||||||
|
5. 面板状态行补:已绑定/未绑定相位数、缺失模型数、解析失败数。
|
||||||
|
6. `dispose()` 清 socket、计时器、实体、registry。
|
||||||
|
|
||||||
|
### 步骤 7 — `cesium-preview.js` 对接(R2、R5)
|
||||||
|
|
||||||
|
1. 删除 `cesium-preview.js` 中的 `lampColorName()`(与 overlay 重复且映射错误)。
|
||||||
|
2. `createLiveTrafficSignals().update(lamps)` 改签名为
|
||||||
|
`update(entries)`,`entries = [{nodeKeys:string[], color:"red"|"yellow"|"green"|"off"|"other", countDown:number}]`。
|
||||||
|
3. 按 `nodeKeys` 直接点亮 `TrafficSignalDynamic_<nodeKey>_<color>` 节点,
|
||||||
|
删除失效的 `signalByPhase` 回退逻辑。
|
||||||
|
4. `countDown` 驱动 `category === "countdown"` 资产显示。
|
||||||
|
5. `color === "off" | "other"` 时三色节点全灭。
|
||||||
|
|
||||||
|
验证:`npm run test:preview-assets`
|
||||||
|
|
||||||
|
### 步骤 8 — 全量校验
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run test:v2x-cesium-preview
|
||||||
|
npm run test:v2x-preview-server
|
||||||
|
npm run test:preview-assets
|
||||||
|
npm run test:traffic-signals
|
||||||
|
npm run test:native-preview-traffic
|
||||||
|
npm run test:package-contract
|
||||||
|
```
|
||||||
|
|
||||||
|
AC10 校验:将区域配置 `v2xPreview.enabled` 置 `false` 重新生成,
|
||||||
|
确认生成页无 V2X 面板且 `package/` 下产物字节不变。
|
||||||
|
|
||||||
|
## 人工验收(AC9,需真实上游)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
V2X_UPSTREAM=http://<host>:<port> \
|
||||||
|
npm run serve:v2x-preview -- --root outputs/fengshu-er-road --host 0.0.0.0 --port 7862
|
||||||
|
```
|
||||||
|
|
||||||
|
登录后逐项确认:
|
||||||
|
- [ ] 信号灯随相位变色,颜色与 dashboard 实时路口一致
|
||||||
|
- [ ] 倒计时数字走动
|
||||||
|
- [ ] 车辆出现、移动平滑、离开视野后消失(无幽灵车堆积)
|
||||||
|
- [ ] 连接持续 5 分钟以上不掉线
|
||||||
|
- [ ] 车辆与路口位置无明显偏移(坐标未二次转换)
|
||||||
|
- [ ] 面板绑定数、失败数符合预期
|
||||||
|
|
||||||
|
## 回滚点
|
||||||
|
|
||||||
|
- 步骤 7 独立可 revert(只动 `cesium-preview.js`)。
|
||||||
|
- 步骤 1–6 全在 overlay 单文件内,`git checkout scripts/lib/v2x-cesium-overlay.js` 即回到当前状态。
|
||||||
|
- `v2xPreview.enabled=false` 是运行时总开关。
|
||||||
|
|
||||||
|
## 不做(留待后续任务)
|
||||||
|
|
||||||
|
- AMap 底图 / 矢量瓦片图层
|
||||||
|
- `CrossDevices/Model3D.vue` 3D 杆件模型(设备维持点位)
|
||||||
|
- `useV2XEvents` 事件气泡
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
# 还原 V2X 实时路口信号灯与车辆展示
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
把 `v2x_web` dashboard「实时路口」(`HologramCross`) 的实时数据行为完整搬到本项目的 Cesium 预览中,使
|
||||||
|
`outputs/<area>/…-cesium-preview.html` 在登录后能持续、正确地显示 **信号灯相位灯色与倒计时** 和
|
||||||
|
**OBU / 目标识别车辆**。
|
||||||
|
|
||||||
|
当前实现(Codex 移植)接口地址是对的,但数据处理与渲染层基本失真,实际效果是:灯永远红、车可能一辆都不出现、
|
||||||
|
出现后也不消失、连接几十秒后被服务端断开。本任务修复这条链路。
|
||||||
|
|
||||||
|
## Source of Truth
|
||||||
|
|
||||||
|
参照实现(只读,不修改):
|
||||||
|
`/Users/que01/Project/v2x_web/applications/dashboard/src/views/dashboard/components/Content/Map/HologramCross/`
|
||||||
|
|
||||||
|
- `components/CrossTrafficLights3D.vue` — 信号灯:link 相位、WS 订阅、灯色/倒计时
|
||||||
|
- `components/utils.ts` — 灯色状态字典、航向角计算
|
||||||
|
- `components/CrossCars/hooks/useObuCars.ts` — OBU 车辆
|
||||||
|
- `components/CrossCars/hooks/useTargetCars.ts` — 目标识别车辆
|
||||||
|
- `components/CrossCars/type.ts` — 车辆数据结构
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### R1 WebSocket 连接层对齐
|
||||||
|
- 三个 socket(`signal` / `obuPosition` / `targetPosition`)均按源项目发送心跳
|
||||||
|
`{"heartBeat":"ping"}`,间隔 30000ms。
|
||||||
|
- 断线自动重连,重连后重新发送各自的订阅消息(signal 发 `junctionId`,target 发 `deviceId`,obu 发 bounds)。
|
||||||
|
- 页面 `visibilitychange` 回到可见时行为不得导致重复连接堆积;`dispose()` 必须清掉心跳与重连计时器。
|
||||||
|
|
||||||
|
### R2 信号灯灯色映射修正
|
||||||
|
- 采用源项目 `utils.ts` 的状态字典:`11=灭灯 21=红 22=黄 23=绿 31=其他`。
|
||||||
|
- 现有 `lampColor()`(overlay)与 `lampColorName()`(`cesium-preview.js`)中基于 `2`/`3` 的判断必须移除。
|
||||||
|
- 未知状态码按「其他/灭灯」处理,不得静默落到红色。
|
||||||
|
|
||||||
|
### R3 相位到原生信号灯的映射
|
||||||
|
- `traffic-signals.json` 中不存在 V2X `phaseNo`(只有 `phaseGroup: 0`),当前回退到 `signal.id` 导致永不匹配。
|
||||||
|
必须建立一条真实可用的 V2X `phaseNo` → 原生信号灯头的映射。
|
||||||
|
- 映射结果必须可诊断:面板要能显示「N 个相位已绑定 / M 个未绑定」。
|
||||||
|
- 允许区域配置提供显式覆盖映射。
|
||||||
|
|
||||||
|
### R4 一个相位可点亮多条进口道
|
||||||
|
- 同一 `phaseNo` 对应的所有 link / 信号灯头都要被点亮,当前 `Map<phase, entity>` 的覆盖行为必须消除。
|
||||||
|
|
||||||
|
### R5 倒计时
|
||||||
|
- 使用推送中的 `countDown` 字段(源项目 `phaseValue['time'] = signal.countDown`),驱动预览中已有的
|
||||||
|
countdown 资产或等效显示。
|
||||||
|
|
||||||
|
### R6 车辆订阅正确建立
|
||||||
|
- OBU socket 连接后必须发送订阅消息(源项目 `send(bounds || '')`),相机视野变化时发送
|
||||||
|
`{"bounds": "<lng,lat;…>"}`。
|
||||||
|
- target socket 连接后发送 `{"deviceId": "<ids joined by comma>"}`,无配置时发送 `{"deviceId": null}`。
|
||||||
|
|
||||||
|
### R7 车辆生命周期
|
||||||
|
- 按源项目实现超时隐藏:超过 `interval * 1.5` 未更新的车辆隐藏并可复用槽位;`interval` 取自推送体,
|
||||||
|
`0` 时回退 `500`。
|
||||||
|
- socket 断开时清空车辆列表。
|
||||||
|
- 车辆位置更新使用推送间隔做平滑插值,避免逐帧跳变。
|
||||||
|
|
||||||
|
### R8 车辆模型命名与资产对齐
|
||||||
|
- OBU 数据层标记为 `car_obu.glb`,但 dashboard 的实际 `CrossCars` 模板固定渲染 `11.glb`;预览必须遵从该最终渲染契约。目标识别车辆使用 `${type}${subType}.glb`。
|
||||||
|
- 预览包必须携带 dashboard 实际使用的车辆模型;包内缺少未知车型时回退到 `11.glb`,并在面板提示,不得静默显示错误车型。
|
||||||
|
|
||||||
|
### R9 推送体解析健壮性
|
||||||
|
- 源项目对两个车辆 socket 使用 `saferEval` 而非 `JSON.parse`,说明载荷不保证严格 JSON。
|
||||||
|
- 解析必须容忍非严格 JSON,且解析失败要计数并在面板可见,不得整条静默丢弃。
|
||||||
|
|
||||||
|
### R10 范围纠正
|
||||||
|
- `/facilities/api/FlowTravelRatio/queryListWeek`(周流量比)不属于「实时路口」,从实时加载链路移除。
|
||||||
|
|
||||||
|
## Non-Goals
|
||||||
|
|
||||||
|
- 不移植 AMap 底图 / 矢量瓦片图层(`linkVectorHdMapTileUrl`)。
|
||||||
|
- 不移植 `CrossDevices/Model3D.vue` 的 3D 杆件模型;设备维持点位显示(可后续独立任务)。
|
||||||
|
- 不移植 `useV2XEvents` 的 V2X 事件气泡。
|
||||||
|
- 不改变原生包产物(GLB / metadata / traffic-signals.json 的生成逻辑)。
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
|
||||||
|
- 不得提交上游地址、账号、令牌、AMap key;`v2xPreview` 配置保持非敏感。
|
||||||
|
- 令牌只存 `sessionStorage`,页面始终从登录门进入。
|
||||||
|
- 坐标契约不变:V2X 数据 GCJ-02,进 Cesium 前转一次 WGS84;原生数据不得二次转换。
|
||||||
|
- `v2xPreview.enabled` 默认 `false`,关闭时生成页不含 V2X 面板。
|
||||||
|
- 生成的预览为静态页,无构建步骤,overlay 保持零依赖 IIFE。
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] AC1 三个 socket 均可见 30s 心跳;模拟服务端在 60s+ 后连接仍存活。
|
||||||
|
- [ ] AC2 单测覆盖灯色映射:`21→红 22→黄 23→绿 11→灭 31→其他`,且 `2`/`3` 不再被当作黄/绿。
|
||||||
|
- [ ] AC3 单测覆盖相位映射:给定 V2X link 相位与 `traffic-signals.json`,输出的绑定数 > 0,
|
||||||
|
未绑定项被明确列出。
|
||||||
|
- [ ] AC4 单测覆盖同相位多进口道:一个 `phaseNo` 对应 2 条 link 时,两条都被点亮。
|
||||||
|
- [ ] AC5 单测覆盖车辆超时:注入两次推送并推进时间超过 `interval*1.5`,车辆转为不可见。
|
||||||
|
- [ ] AC6 单测覆盖 OBU/target 订阅消息:连接后发出的首帧内容与源项目一致。
|
||||||
|
- [ ] AC7 单测覆盖非严格 JSON 推送体能被解析,且失败计数可读。
|
||||||
|
- [ ] AC8 `npm run test:v2x-cesium-preview`、`test:v2x-preview-server`、`test:preview-assets` 全绿。
|
||||||
|
- [ ] AC9 真机(`npm run serve:v2x-preview` 接真实上游)登录后可见:信号灯随相位变色并显示倒计时、
|
||||||
|
车辆出现并移动、离开后消失。此项由开发者人工确认。
|
||||||
|
- [ ] AC10 `v2xPreview.enabled=false` 重新生成后,页面不含 V2X 面板,包产物字节不变。
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"id": "v2x-realtime-cross-fidelity",
|
||||||
|
"name": "v2x-realtime-cross-fidelity",
|
||||||
|
"title": "还原 V2X 实时路口信号灯与车辆展示",
|
||||||
|
"description": "",
|
||||||
|
"status": "in_progress",
|
||||||
|
"dev_type": null,
|
||||||
|
"scope": null,
|
||||||
|
"package": null,
|
||||||
|
"priority": "P2",
|
||||||
|
"creator": "dingkang",
|
||||||
|
"assignee": "dingkang",
|
||||||
|
"createdAt": "2026-08-24",
|
||||||
|
"completedAt": null,
|
||||||
|
"branch": null,
|
||||||
|
"base_branch": "main",
|
||||||
|
"worktree_path": null,
|
||||||
|
"commit": null,
|
||||||
|
"pr_url": null,
|
||||||
|
"subtasks": [],
|
||||||
|
"children": [],
|
||||||
|
"parent": null,
|
||||||
|
"relatedFiles": [],
|
||||||
|
"notes": "",
|
||||||
|
"meta": {}
|
||||||
|
}
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+2
-2
@@ -3,7 +3,7 @@
|
|||||||
"name": "native-preview-traffic-simulation",
|
"name": "native-preview-traffic-simulation",
|
||||||
"title": "Native preview traffic simulation and migration contract",
|
"title": "Native preview traffic simulation and migration contract",
|
||||||
"description": "",
|
"description": "",
|
||||||
"status": "in_progress",
|
"status": "completed",
|
||||||
"dev_type": null,
|
"dev_type": null,
|
||||||
"scope": null,
|
"scope": null,
|
||||||
"package": null,
|
"package": null,
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
"creator": "dingkang",
|
"creator": "dingkang",
|
||||||
"assignee": "dingkang",
|
"assignee": "dingkang",
|
||||||
"createdAt": "2026-08-18",
|
"createdAt": "2026-08-18",
|
||||||
"completedAt": null,
|
"completedAt": "2026-08-24",
|
||||||
"branch": null,
|
"branch": null,
|
||||||
"base_branch": "feature/native-road-compiler",
|
"base_branch": "feature/native-road-compiler",
|
||||||
"worktree_path": null,
|
"worktree_path": null,
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"_example": "Fill with {\"file\": \"<path>\", \"reason\": \"<why>\"}. Put spec/research files only — no code paths. Run `python3 .trellis/scripts/get_context.py --mode packages` to list available specs. Delete this line once real entries are added."}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# Technical Design
|
||||||
|
|
||||||
|
## Boundary
|
||||||
|
|
||||||
|
The native compiler remains authoritative for OSM road identity, directed lanes,
|
||||||
|
connections, traffic signals, stop lines, and preview routes. A reference layer is
|
||||||
|
an optional geometry-calibration input consumed before junction surface publication.
|
||||||
|
|
||||||
|
## Proposed Flow
|
||||||
|
|
||||||
|
```text
|
||||||
|
optional reference GeoJSON (GCJ-02)
|
||||||
|
-> validate schema and coordinate bounds
|
||||||
|
-> GCJ-02 to WGS84 conversion
|
||||||
|
-> associate reference footprint with an OSM junction node
|
||||||
|
-> classify geometry by observable shape, not opaque vendor type alone
|
||||||
|
-> derive bounded junction-shape parameters
|
||||||
|
-> native compiler creates surface/connectors as usual
|
||||||
|
-> diagnostics compare generated geometry with reference
|
||||||
|
```
|
||||||
|
|
||||||
|
The first production validation keeps the reference overlay/diagnostic, then enables a
|
||||||
|
bounded `cross` junction template for explicitly configured references. Connector
|
||||||
|
endpoints and movement enumeration still come from the native model. T and complex
|
||||||
|
junctions remain on the existing algorithm until their templates are separately validated.
|
||||||
|
|
||||||
|
## Input Contract
|
||||||
|
|
||||||
|
Use an optional area-level reference configuration rather than a hard-coded filename.
|
||||||
|
The sample points to `inputs/osm/珠山湖大道(枫树二路)口.geojson`, declares `GCJ-02`,
|
||||||
|
and identifies the target through OSM node `8005332807` or a stable spatial/name match.
|
||||||
|
The file is not assumed to contain a CRS member; the configured source CRS is required.
|
||||||
|
|
||||||
|
## Geometry Safety
|
||||||
|
|
||||||
|
- Convert all reference coordinates to WGS84 before distance/overlap tests.
|
||||||
|
- Reject malformed or non-finite coordinates and references outside the OSM bounds plus a
|
||||||
|
bounded tolerance.
|
||||||
|
- Never let a reference polygon create a movement, lane, signal, or stop-line record.
|
||||||
|
- Keep a fallback path to the current `compileGeometry()` junction algorithm.
|
||||||
|
|
||||||
|
## Compatibility And Rollback
|
||||||
|
|
||||||
|
No-reference configs and existing output schemas remain unchanged. The experiment can be
|
||||||
|
disabled by omitting the reference section or setting it disabled. Generated diagnostics
|
||||||
|
must record source file hash, conversion mode, matched OSM node, and whether fallback was used.
|
||||||
|
No source reference file is rewritten.
|
||||||
|
|
||||||
|
## Open Technical Work
|
||||||
|
|
||||||
|
1. Select the smallest reusable geometry parameter set from the sample (approach cutback,
|
||||||
|
corner radius/rounding, island/marking envelopes, and tolerances).
|
||||||
|
2. Implement and test GCJ-02 conversion independently from compiler logic.
|
||||||
|
3. Compare the sample against all native junctions near the converted footprint before any
|
||||||
|
production surface override is enabled.
|
||||||
|
4. Add topology classification and template dispatch; only cross is enabled in this validation.
|
||||||
|
5. Preserve native connectors and controls while replacing only the bounded junction surface geometry.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"_example": "Fill with {\"file\": \"<path>\", \"reason\": \"<why>\"}. Put spec/research files only — no code paths. Run `python3 .trellis/scripts/get_context.py --mode packages` to list available specs. Delete this line once real entries are added."}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# Validation Implementation Plan
|
||||||
|
|
||||||
|
进度标记于 2026-08-21。
|
||||||
|
|
||||||
|
1. [x] Add a read-only reference inspection utility or library helper that validates GeoJSON,
|
||||||
|
converts GCJ-02 to WGS84, computes bounds/center, and associates the sample with OSM node
|
||||||
|
`8005332807`. — `scripts/lib/gaode-junction-reference.js` + `scripts/inspect-junction-reference.js`
|
||||||
|
2. [x] Add focused tests for coordinate conversion, malformed input rejection, spatial association,
|
||||||
|
and the no-reference fallback. — `npm run test:gaode-junction-reference`
|
||||||
|
3. [x] Add a diagnostic comparison between the reference footprint and native
|
||||||
|
`intersection_surface.geojson`, including center offset, envelope overlap, and approach headings.
|
||||||
|
— 复杂路口的面写在 `road_surface.geojson`(`complex_part`)而非 `intersection_surface`,
|
||||||
|
原实现匹配不到、恒返回 `nativeIntersection: null`。已扩展为可回落到复杂路口簇
|
||||||
|
(新增 `--native-road-surface` / `--cluster-id`,schema 升至 v2)。
|
||||||
|
4. [x] Add a reference-backed, parameterized junction template and dispatch it only for
|
||||||
|
explicitly enabled samples. — 实际实现为 `complex-junction-v1`,非原计划的 cross 模板,
|
||||||
|
范围变更见 prd.md「Scope Drift」。
|
||||||
|
5. [x] Preserve connector, movement, signal, and stop-line generation; validate containment against
|
||||||
|
the new surface. — A/B 实测通过,数据见 prd.md「Verification Log」。
|
||||||
|
6. [x] Run native-road, preflight, preview-traffic, and package-contract tests, plus the sample
|
||||||
|
comparison. Inspect the generated overlay/diagnostic manually.
|
||||||
|
— 2026-08-21 全绿:`test:gaode-junction-reference`、`test:native-road`、`test:road-workbench`、
|
||||||
|
`test:preflight`、`test:native-preview-traffic`、`test:package-contract`、`test:traffic-signals`,
|
||||||
|
外加 `road:check` → `ok: true, errors: []`。人工视觉确认仍待用户。
|
||||||
|
7. [x] Stop at validation. Do not commit,
|
||||||
|
and do not modify the source OSM or reference GeoJSON. — 未 commit;参考 GeoJSON 未改;
|
||||||
|
源 OSM 有改动但来自人工 JOSM 编辑,非管线写入。
|
||||||
|
|
||||||
|
## 本次会话追加的修复(2026-08-21)
|
||||||
|
|
||||||
|
- 车道中心线与车道标线越过斑马线:`compileLaneCenterlines` 现接收模板已产出的斑马线/停止线,
|
||||||
|
新增 `trimLaneOutsideControls`(按到路口中心的半径定向后再裁剪,因为车道几何两种朝向都存在)。
|
||||||
|
拓扑几何 `coordinates` 保持完整,仅裁剪发布几何与标线源几何。
|
||||||
|
实测越线要素 20 → 0,分隔线越界 2 → 0,connector 356 / movement 370 前后一致。
|
||||||
|
- 新增诊断 `complex-junction-configured-radius-ignored`、`lane-centerline-fully-inside-control`。
|
||||||
|
- 删除死函数 `clusterApproachRing`。
|
||||||
|
- **复杂路口人行道转角**(`complex-junction.js`):直条带被裁在簇边界后,相邻两臂的步行带
|
||||||
|
各自留一个断头,中间整个楔形无覆盖。现沿圆角已定义的路缘补一条 2 m 宽转角带。
|
||||||
|
- 复用同一函数作用域内已算好的 `curve` / `tangents` / `edges` / `apex`,不重新拟合曲线
|
||||||
|
- 新增 `armCarriesSidewalk`(按臂的外向方向翻转道路自身的 `sidewalkLeft/Right`)、
|
||||||
|
`edgeRunToRadius`、`offsetPolylineAwayFromCenter`、`ringSelfIntersects`
|
||||||
|
- 经 `islands` 通道并入 `generatedComplexSidewalks`
|
||||||
|
- 自交或几何无效时跳过并报 `complex-junction-sidewalk-corner-fallback`,不硬塞坏几何
|
||||||
|
- 实测:人行道要素 7 → 8;生成角 1(平分线 286°,241°→331°,57 顶点);无自交;
|
||||||
|
与两侧条带均相接;面积采样 331 点中 0 点落在车行道内
|
||||||
|
- **限制**:全区 139 条路仅 3 条带人行道,4 个角中只有 286° 两侧齐备,
|
||||||
|
其余 3 个角当前不产出,缺少验证样本
|
||||||
|
|
||||||
|
## Rollback Points
|
||||||
|
|
||||||
|
- Delete/disable the optional reference configuration to restore the default native path.
|
||||||
|
- Remove only the reference diagnostic output; existing native-road outputs remain authoritative.
|
||||||
|
- Do not overwrite existing layers until the comparison is accepted.
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
# Parameterize junction geometry with optional Gaode reference
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
验证一种通用的、参数化的路口几何生成范式:借鉴高德路口 GeoJSON 的规整边界和标线组织方式,
|
||||||
|
但保持 OSM/native compiler 对道路身份、连接关系、车道可行驶性、信号和停止线的权威性。
|
||||||
|
当前阶段先做一个可回滚的生产几何验证,不提交代码或产物。
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- R1: native 路口在没有参考数据时行为不变,现有 OSM/native 输出仍是默认路径。
|
||||||
|
- R2: 支持可选的路口参考输入,至少记录输入路径、坐标来源(GCJ-02)和目标 OSM 路口关联方式。
|
||||||
|
- R3: 参考输入先转换为 WGS84;禁止将 GCJ-02 坐标直接与 OSM/native 几何叠加。
|
||||||
|
- R4: 参考数据只允许影响路口面的规整化参数、边界形态和标线布局;不得改变 OSM 道路、车道、connector、
|
||||||
|
signal_uid、停止线归属或车辆路线拓扑。
|
||||||
|
- R5: 不机械复制高德 feature 的 `type=1..5`;先建立可审计的几何类别映射或只使用其可验证的形态特征。
|
||||||
|
- R6: 以“珠山湖大道(枫树二路)”路口作为验证样本,输出参考前后对比、偏差诊断和可回滚结果。
|
||||||
|
- R6.1: 生成器按路口拓扑选择模板,至少区分 cross、T 和复杂/多臂路口;不能用一个固定几何参数机械覆盖所有路口。
|
||||||
|
- R6.2: 首个生产几何验证只启用 cross 模板,利用参考样本校准 cutback、圆角和进口过渡;T/复杂路口先保留现有 native 行为并记录诊断。
|
||||||
|
- R6.3: 模板生成的路口面必须由 OSM/native 道路宽度、方向和车道结构驱动;高德几何只用于校准参数或对比,不直接复制其 feature。
|
||||||
|
- R7: 参考文件缺失、坐标转换失败、无法关联 OSM 路口或几何越界时,构建必须回退默认 native 算法并给出诊断,
|
||||||
|
不得静默覆盖生产几何。
|
||||||
|
- R8: 保持当前阶段 manifest、GLB/package 契约和无参考区域的 parity 行为不变。
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
> 措辞修订说明见文末「Scope Drift」。勾选项均为 2026-08-21 实测,证据记录在「Verification Log」。
|
||||||
|
|
||||||
|
- [x] 不配置参考输入时,现有 native-road 测试和样本区域输出保持默认行为。
|
||||||
|
- [x] 配置枫树二路参考后,能稳定关联 OSM node `8005332807`,并生成 WGS84 参考诊断。
|
||||||
|
- [x] 参考几何与 native 路口的叠加结果可检查:路口中心、边界、进口方向有数值和 SVG 记录。
|
||||||
|
- [x] 参考模式不改变 OSM 衍生的 connector、车道连接、信号或停止线集合;模板只新增自有
|
||||||
|
`complex-*` 命名空间要素。(原措辞「不会新增或删除…停止线」严于 R4 本意,已修订)
|
||||||
|
- [x] 参考模式失败时有明确 warning,并成功回退默认 native 几何。
|
||||||
|
- [x] 模板生成的路口面视觉上接近高德参考。connector / 信号 / 停止线集合一致性已实测通过;
|
||||||
|
视觉接近度由用户 2026-08-21 在工作台确认(「基本 ok」),其间提出的人行道转角缺口已修复并复核通过。
|
||||||
|
- [x] 无参考路口继续走默认 native 几何,不被模板误套。
|
||||||
|
- [x] 验证产物写入区域输出目录,未执行 git commit。(源 OSM 有改动,但来自人工 JOSM 编辑,
|
||||||
|
非管线写入;原措辞未区分这两者,已修订)
|
||||||
|
|
||||||
|
## Scope Drift(2026-08-21 记录)
|
||||||
|
|
||||||
|
R6.2 原定「首个生产几何验证只启用 cross 模板;T/复杂路口先保留现有 native 行为」。
|
||||||
|
实际实现走的是 `complex-junction-v1`,对枫树二路 4 节点簇做整体路口面、斑马线、停止线、
|
||||||
|
角部安全岛和圆角生成。范围已越过 R6.2,本文档据实修订,R6.2 视为被本次决策取代。
|
||||||
|
cross 模板(`cross-v1` / `cross-cluster-v1`)代码路径仍在,未被删除。
|
||||||
|
|
||||||
|
## Verification Log(2026-08-21)
|
||||||
|
|
||||||
|
参考模式 A/B 对照(同一 OSM 输入,`junctionTemplates.enabled` 开/关,独立 outputRoot):
|
||||||
|
|
||||||
|
| 指标 | ON | OFF | 判定 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| connector 要素 | 356 | 356 | 集合逐一相同,无新增/缺失 |
|
||||||
|
| movement / published | 370 / 356 | 370 / 356 | 一致 |
|
||||||
|
| connection | 215 | 215 | 一致 |
|
||||||
|
| 信号 uid 集合 | 20 | 20 | 集合完全一致 |
|
||||||
|
| 普通斑马线 `native-road-crosswalk/v1` | 6 | 6 | 一致 |
|
||||||
|
| 模板新增 `complex-crosswalk` | 128 | 0 | 模板自有命名空间 |
|
||||||
|
| 模板新增 `complex-corner-crosswalk` | 24 | 0 | 同上 |
|
||||||
|
| 模板新增 `complex-stop-line` | 4 | 0 | 同上 |
|
||||||
|
| 预览车道 `cluster-approach-lane` | 24 | 0 | 同上 |
|
||||||
|
|
||||||
|
参考关联与叠加(`npm run reference:junction`):
|
||||||
|
|
||||||
|
- 匹配方式 `node-id`,命中 `8005332807`,参考中心到节点 **8.98 m**
|
||||||
|
- 匹配到 `complex-cluster` = `zhushanhu-fengshu-complex`,13 个要素
|
||||||
|
- native core 半径 **24 m**(配置 `coreRadiusMeters: 28`),进口 4 / 车行道 8,
|
||||||
|
进口朝向 `[-118.5, -28, 62.2, 151.9]`
|
||||||
|
- 已知口径差异:检查工具用参考文件**全部** feature 算 bounds(约 380×330 m,含长引道),
|
||||||
|
而 `readReferenceCalibration` 只取 `type ∈ [1,2,3,4]` 的子集。两者不同量级,
|
||||||
|
故 bbox IoU(0.070)当前**不是**可用的质量指标,仅中心偏差和朝向可比。
|
||||||
|
|
||||||
|
失败回退(`referenceFile` 指向不存在路径):
|
||||||
|
|
||||||
|
- 编译成功不抛错;诊断由 `complex-junction-reference-calibrated` 降级为 `complex-junction-generated`
|
||||||
|
- connector 356 / movement 370 不变
|
||||||
|
- 该路径下 `lane-centerline-fully-inside-control` 触发 10 次:无参考时 coreRadius 仅 14.56 m,
|
||||||
|
10 条车道整体落在控制带内,回退为未裁剪发布。非回归(改动前同样未裁剪),但属已知限制。
|
||||||
|
|
||||||
|
非簇路口未受模板影响(A/B `intersection_surface`):
|
||||||
|
|
||||||
|
| | ON | OFF |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 普通路口面总数 | 41 | 45 |
|
||||||
|
| 簇成员节点出现次数 | 0(预期 0) | 4(模板关闭时预期 4) |
|
||||||
|
| 非簇节点(41 个) | — | 与 ON 逐点几何完全一致,无增无缺 |
|
||||||
|
| 模板 `complex_part` 要素 | 13,全部归属唯一簇 `zhushanhu-fengshu-complex` | 0 |
|
||||||
|
|
||||||
|
结论:模板严格限定在 `nodeIds` 列表内,无外溢。
|
||||||
|
|
||||||
|
## Known Gaps(2026-08-21)
|
||||||
|
|
||||||
|
1. `way/858770823:segment/2`(长 19.2 m,远端为 service 路口 `8613058676`)被 `native-road.js`
|
||||||
|
的 cluster 丢弃判据误伤,整段无路面,该节点周边 25×25 m 内 25.8% 露底。
|
||||||
|
判据应从「远端在 outerRadius 内」改为「远端也是 cluster 成员节点」,实测该判据分界干净。
|
||||||
|
**用户 2026-08-21 明确暂缓,未修改。**
|
||||||
|
2. `coreRadiusMeters` 在有参考文件时不参与计算(被 calibration 覆盖并 clamp 到 24)。
|
||||||
|
已加诊断 `complex-junction-configured-radius-ignored` 使其可见,行为未改。
|
||||||
|
3. `approachLengthMeters` 对 `complex-junction-v1` 无效(仅 `cross-v1` / `cross-cluster-v1` 使用)。
|
||||||
|
死函数 `clusterApproachRing` 已删除。
|
||||||
|
4. 无参考路径下普通停止线为 0(`crossing-no-safe-stop-line` 告警 1 条),先于本任务存在。
|
||||||
|
|
||||||
|
|
||||||
|
## Constraints And Deferred Scope
|
||||||
|
|
||||||
|
- OSM WGS84 与 native 拓扑是交通语义的单一事实源。
|
||||||
|
- 高德参考暂不作为完整道路网络输入,也不直接替代 road surface 或 connector 几何。
|
||||||
|
- 暂不定义所有高德 `type` 值的业务语义;先验证几何范式和校准边界。
|
||||||
|
- 暂不提交代码、配置或生成产物;本阶段完成后由用户决定是否进入正式实现。
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"id": "gaode-junction-reference",
|
||||||
|
"name": "gaode-junction-reference",
|
||||||
|
"title": "Parameterize junction geometry with optional Gaode reference",
|
||||||
|
"description": "",
|
||||||
|
"status": "completed",
|
||||||
|
"dev_type": null,
|
||||||
|
"scope": null,
|
||||||
|
"package": null,
|
||||||
|
"priority": "P2",
|
||||||
|
"creator": "dingkang",
|
||||||
|
"assignee": "dingkang",
|
||||||
|
"createdAt": "2026-08-19",
|
||||||
|
"completedAt": "2026-08-21",
|
||||||
|
"branch": null,
|
||||||
|
"base_branch": "fengshu-er-road",
|
||||||
|
"worktree_path": null,
|
||||||
|
"commit": "12aeda9a63867ff659cec2310c3e4c586907d005",
|
||||||
|
"pr_url": null,
|
||||||
|
"subtasks": [],
|
||||||
|
"children": [],
|
||||||
|
"parent": null,
|
||||||
|
"relatedFiles": [],
|
||||||
|
"notes": "",
|
||||||
|
"meta": {}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"_example": "Fill with {\"file\": \"<path>\", \"reason\": \"<why>\"}. Put spec/research files only — no code paths. Run `python3 .trellis/scripts/get_context.py --mode packages` to list available specs. Delete this line once real entries are added."}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# Design: Live V2X Cesium Intersection View
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
The native pipeline remains the source of static scene geometry and package
|
||||||
|
placement. The existing Cesium preview gains an operations overlay and a compact
|
||||||
|
V2X sign-in gate. Vehicle entities and their trace lines exist only after the
|
||||||
|
authenticated V2X streams provide valid positions; no generated traffic route or
|
||||||
|
simulation is rendered. The implementation stays in the current generated static
|
||||||
|
preview architecture and does not import the source dashboard's Vue, AMap, or
|
||||||
|
Three dependencies.
|
||||||
|
|
||||||
|
The generated preview runtime is divided into four browser concerns:
|
||||||
|
|
||||||
|
1. `auth`: presents the V2X sign-in form, MD5-hashes the password to match the
|
||||||
|
source contract, stores a successful token in `sessionStorage`, and clears it
|
||||||
|
on sign-out or authorization failure.
|
||||||
|
2. `v2x-client`: owns configured REST/WS origins, adds the raw `Authorization`
|
||||||
|
request header, normalizes the source API envelope, and reports a capability
|
||||||
|
status rather than blanking the preview if an optional resource fails.
|
||||||
|
3. `coordinates`: labels external values as GCJ-02 and native values as WGS84 or
|
||||||
|
ENU. It converts V2X GCJ-02 positions to WGS84 exactly once before Cesium
|
||||||
|
entity creation; the existing native package placement contract is unchanged.
|
||||||
|
4. `cesium-v2x-overlay`: adds V2X links, devices, pole/configuration evidence,
|
||||||
|
metrics, and real signal phase updates to the existing Cesium viewer, with
|
||||||
|
independent visibility controls and diagnostics.
|
||||||
|
|
||||||
|
## Data Flow
|
||||||
|
|
||||||
|
```text
|
||||||
|
V2X sign-in -> session token
|
||||||
|
| |
|
||||||
|
| +--> Authorization header / WS query parameter
|
||||||
|
v
|
||||||
|
configured V2X REST + WS endpoints -> GCJ-02 V2X geometry, devices, metrics, lamps
|
||||||
|
|
|
||||||
|
v
|
||||||
|
GCJ-02-to-WGS84 adapter
|
||||||
|
|
|
||||||
|
native package + route/signal descriptors -> WGS84/ENU -> existing Cesium viewer
|
||||||
|
^
|
||||||
|
|
|
||||||
|
Cesium V2X operations overlay
|
||||||
|
```
|
||||||
|
|
||||||
|
## Endpoint Contract
|
||||||
|
|
||||||
|
The first delivery consumes `queryCrossLinkInfo`, `queryPoles`, bound-device,
|
||||||
|
cross-device-config, and weekly flow-ratio APIs. It subscribes to
|
||||||
|
`/network/ws/network/signal` only after link data establishes usable phases.
|
||||||
|
Endpoint host/prefixes and selected `crossCode` are deployment configuration. A
|
||||||
|
development proxy forwards REST and WebSocket traffic so the browser never needs
|
||||||
|
a hard-coded private origin.
|
||||||
|
|
||||||
|
## Coordinate Contract
|
||||||
|
|
||||||
|
| Producer | Source CRS | Consumer rule |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Native compiler package, traffic signals, route descriptor | WGS84 / local ENU | Preserve the existing Cesium package placement and WGS84 entity contracts. |
|
||||||
|
| V2X dashboard link, road, device, and pole data | GCJ-02 | Convert to WGS84 once before creating Cesium entities. |
|
||||||
|
| High德 reference GeoJSON | GCJ-02 | Calibration-only compiler input; no runtime map or SDK dependency. |
|
||||||
|
|
||||||
|
The existing `gaode-junction-reference` inverse conversion is an appropriate
|
||||||
|
source for the V2X adapter. It will be factored or safely reused only when doing
|
||||||
|
so preserves its compiler behavior and test coverage.
|
||||||
|
|
||||||
|
## Compatibility And Failure Handling
|
||||||
|
|
||||||
|
- Existing Cesium preview and its static-only workflow remain usable.
|
||||||
|
- The V2X overlay starts only after successful sign-in.
|
||||||
|
- An expired token returns the user to sign-in and removes live entities rather
|
||||||
|
than presenting stale data as current.
|
||||||
|
- A REST/WS capability failure is shown in diagnostics; native scene and signals
|
||||||
|
remain usable, while the vehicle layer stays empty rather than simulating data.
|
||||||
|
- Removing the optional overlay/support files restores current preview behavior
|
||||||
|
without changing static package contracts.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
`sessionStorage` limits the upstream token to the current tab session. Credentials
|
||||||
|
are never persisted. Configuration examples use placeholders, and deployment
|
||||||
|
documentation requires an HTTPS same-origin reverse proxy for V2X API/WS traffic.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"_example": "Fill with {\"file\": \"<path>\", \"reason\": \"<why>\"}. Put spec/research files only — no code paths. Run `python3 .trellis/scripts/get_context.py --mode packages` to list available specs. Delete this line once real entries are added."}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Implementation Plan: Live V2X Cesium Intersection View
|
||||||
|
|
||||||
|
1. Read preview and pipeline specifications, then add a focused V2X preview
|
||||||
|
configuration. Keep secrets and private origins out of defaults and tracked
|
||||||
|
area configuration.
|
||||||
|
2. Add browser-safe GCJ-02-to-WGS84 conversion and focused tests for source
|
||||||
|
coordinate labels and prevention of duplicate conversion. Preserve the current
|
||||||
|
compiler reference conversion behavior.
|
||||||
|
3. Implement the V2X browser client: login, session token lifecycle, REST
|
||||||
|
envelope handling, capability errors, and signal WebSocket lifecycle.
|
||||||
|
4. Extend the generated Cesium preview with V2X entities and operations controls
|
||||||
|
for links, devices, poles/configuration, metrics, live signal state, and the
|
||||||
|
OBU/target-vehicle streams. Do not load or generate simulated vehicle routes.
|
||||||
|
5. Add a local development/proxy configuration example and deployment
|
||||||
|
documentation for V2X REST/WS proxying. Do not add an AMap key, SDK, or page.
|
||||||
|
6. Add focused tests for HTML generation, configuration escaping, login/request
|
||||||
|
construction, coordinate conversion, source-layer diagnostics, and graceful
|
||||||
|
unavailable/auth states. Run existing preview and native-road regressions.
|
||||||
|
7. Validate in a browser with a real V2X account and configured proxy: sign in,
|
||||||
|
inspect aligned native/V2X features, verify REST panels and signal updates,
|
||||||
|
then verify sign-out/token expiry behavior.
|
||||||
|
|
||||||
|
## Validation Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node --check scripts/lib/area-preview.js
|
||||||
|
node --check scripts/lib/cesium-preview.js
|
||||||
|
npm run test:gaode-junction-reference
|
||||||
|
npm run test:preview-assets
|
||||||
|
npm run test:native-preview-traffic
|
||||||
|
npm run test:traffic-signals
|
||||||
|
npm run road:compile -- --config config/areas/fengshu-er-road.json
|
||||||
|
npm run build:area -- --config config/areas/fengshu-er-road.json --stages preview
|
||||||
|
```
|
||||||
|
|
||||||
|
## Review Gates
|
||||||
|
|
||||||
|
- Confirm no token, account, or private host is committed.
|
||||||
|
- Verify V2X GCJ-02 coordinates convert once before Cesium use.
|
||||||
|
- Verify the existing native WGS84/ENU scene contract remains unchanged.
|
||||||
|
- Verify the current Cesium preview works without V2X configuration or sign-in.
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# Integrate live V2X intersection data into Cesium preview
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Provide a Cesium-based operational view of the current complex intersection in
|
||||||
|
this repository. It must show live data from the existing V2X platform while
|
||||||
|
retaining the native road compiler's WGS84/ENU output as the geometry authority.
|
||||||
|
|
||||||
|
## Confirmed Facts
|
||||||
|
|
||||||
|
- The source dashboard's holographic-intersection view uses V2X REST resources for
|
||||||
|
road/link geometry, device bindings, poles, configuration, traffic metrics, and
|
||||||
|
a token-authenticated signal WebSocket.
|
||||||
|
- The dashboard development proxy targets `172.16.1.159:50400` under `/api`,
|
||||||
|
`/websocket`, and `/vectortile`; the application sends the upstream token as the
|
||||||
|
`Authorization` header.
|
||||||
|
- The source dashboard uses AMap and therefore its road/link data is GCJ-02. Its
|
||||||
|
road-network exporter converts that data from GCJ-02 to WGS84 before export.
|
||||||
|
- This repository's native road, signal, and simulation artifacts are WGS84/ENU.
|
||||||
|
- The target is the existing Cesium preview, not AMap. High德 data in this
|
||||||
|
repository is a calibration/reference GeoJSON only, not a target runtime map.
|
||||||
|
- The requested page has a simple login gate; V2X data must remain real live
|
||||||
|
interface data, not copied mock data.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- R1: Add a Cesium-based complex-intersection operations view to this repository, protected by
|
||||||
|
a simple application login.
|
||||||
|
- R2: Integrate the real V2X REST endpoints used by the source dashboard, including
|
||||||
|
current intersection/link geometry, devices, poles/configuration, traffic metrics,
|
||||||
|
and signal state where upstream authorization permits it.
|
||||||
|
- R3: Keep the V2X platform credentials separate from the simple application login;
|
||||||
|
do not put a reusable upstream credential into browser source or committed files.
|
||||||
|
- R4: Treat V2X map-facing coordinates as GCJ-02. Treat native compiler artifacts
|
||||||
|
as WGS84/ENU, and convert V2X GCJ-02 coordinates to WGS84 exactly once before
|
||||||
|
adding them to Cesium.
|
||||||
|
- R5: Surface a clear unavailable/authentication state when live data cannot be
|
||||||
|
loaded while leaving the native complex-intersection view usable.
|
||||||
|
- R6: Make endpoint origin, selected V2X intersection code, and authorization
|
||||||
|
mechanism deployment configuration rather than hard-coded source values.
|
||||||
|
- R7: Vehicle lines and moving vehicles must come only from the authenticated
|
||||||
|
V2X vehicle streams. Do not render or fall back to generated route/simulation
|
||||||
|
data when the service is unavailable.
|
||||||
|
|
||||||
|
## Candidate Upstream Resources
|
||||||
|
|
||||||
|
- `GET /network/api/link/network/queryCrossLinkInfo/{crossCode}`: intersection
|
||||||
|
link geometry and signal phase association.
|
||||||
|
- `GET /network/api/pole/network/queryPoles/{crossCode}`: pole and light placement
|
||||||
|
configuration.
|
||||||
|
- `GET /facilities/api/crossDevice/findDeviceByCrossCode/{crossCode}`: bound devices.
|
||||||
|
- `GET /facilities/api/crossDeviceConfig/{crossCode}`: target-device configuration.
|
||||||
|
- `GET /facilities/api/FlowTravelRatio/queryListWeek?code={crossCode}` and related
|
||||||
|
cross-monitor resources: operational metrics.
|
||||||
|
- `WS /network/ws/network/signal?authorization={token}`: live signal lamps.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] A user can pass the local login gate and open the current complex-intersection
|
||||||
|
Cesium view.
|
||||||
|
- [ ] The page retrieves and renders live V2X data for a configurable intersection
|
||||||
|
code without source-dashboard runtime dependencies.
|
||||||
|
- [ ] The page identifies the coordinate reference of each source and visually
|
||||||
|
aligns native WGS84 geometry with V2X data converted from GCJ-02.
|
||||||
|
- [ ] A missing/expired upstream credential or unavailable service is visible and
|
||||||
|
does not make the native intersection view unusable.
|
||||||
|
- [ ] Upstream URL, intersection code, and credentials/tokens are excluded from
|
||||||
|
tracked application source and documented for deployment.
|
||||||
|
|
||||||
|
## Out Of Scope
|
||||||
|
|
||||||
|
- Copying the source dashboard's Vue, AMap/Three, or proprietary UI component stack.
|
||||||
|
- Building a full user/role management service.
|
||||||
|
- Replacing native road geometry or traffic-signal contracts with V2X data.
|
||||||
|
- Generated vehicle-route or traffic-simulation fallback in the operations preview.
|
||||||
|
|
||||||
|
## Authentication Decision
|
||||||
|
|
||||||
|
- The page signs in to the upstream V2X service with the user-entered account,
|
||||||
|
posting `userName` and MD5-hashed `password` to
|
||||||
|
`/facilities/api/sys/login` through the configured API prefix.
|
||||||
|
- The returned token lives only in `sessionStorage`, is sent as the raw
|
||||||
|
`Authorization` header for REST requests, and is supplied as the
|
||||||
|
`authorization` WebSocket query parameter for the signal subscription.
|
||||||
|
- No default credentials, reusable token, or API secret may be committed.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"id": "v2x-amap-intersection-data",
|
||||||
|
"name": "v2x-amap-intersection-data",
|
||||||
|
"title": "Integrate live V2X intersection data into AMap preview",
|
||||||
|
"description": "",
|
||||||
|
"status": "completed",
|
||||||
|
"dev_type": null,
|
||||||
|
"scope": null,
|
||||||
|
"package": null,
|
||||||
|
"priority": "P2",
|
||||||
|
"creator": "dingkang",
|
||||||
|
"assignee": "dingkang",
|
||||||
|
"createdAt": "2026-08-24",
|
||||||
|
"completedAt": "2026-08-24",
|
||||||
|
"branch": null,
|
||||||
|
"base_branch": "fengshu-er-road",
|
||||||
|
"worktree_path": null,
|
||||||
|
"commit": null,
|
||||||
|
"pr_url": null,
|
||||||
|
"subtasks": [],
|
||||||
|
"children": [],
|
||||||
|
"parent": null,
|
||||||
|
"relatedFiles": [],
|
||||||
|
"notes": "",
|
||||||
|
"meta": {}
|
||||||
|
}
|
||||||
@@ -8,8 +8,8 @@
|
|||||||
|
|
||||||
<!-- @@@auto:current-status -->
|
<!-- @@@auto:current-status -->
|
||||||
- **Active File**: `journal-1.md`
|
- **Active File**: `journal-1.md`
|
||||||
- **Total Sessions**: 39
|
- **Total Sessions**: 41
|
||||||
- **Last Active**: 2026-08-18
|
- **Last Active**: 2026-08-24
|
||||||
<!-- @@@/auto:current-status -->
|
<!-- @@@/auto:current-status -->
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
<!-- @@@auto:active-documents -->
|
<!-- @@@auto:active-documents -->
|
||||||
| File | Lines | Status |
|
| File | Lines | Status |
|
||||||
|------|-------|--------|
|
|------|-------|--------|
|
||||||
| `journal-1.md` | ~845 | Active |
|
| `journal-1.md` | ~887 | Active |
|
||||||
<!-- @@@/auto:active-documents -->
|
<!-- @@@/auto:active-documents -->
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -29,6 +29,8 @@
|
|||||||
<!-- @@@auto:session-history -->
|
<!-- @@@auto:session-history -->
|
||||||
| # | Date | Title | Commits | Branch |
|
| # | Date | Title | Commits | Branch |
|
||||||
|---|------|-------|---------|--------|
|
|---|------|-------|---------|--------|
|
||||||
|
| 41 | 2026-08-24 | Use live V2X vehicle streams only | `b7031f1` | `fengshu-er-road` |
|
||||||
|
| 40 | 2026-08-24 | Stabilize Fengshu native road compilation | `f1f829c` | `fengshu-er-road` |
|
||||||
| 39 | 2026-08-18 | Complete native-only pipeline replacement | `9e0e25a` | `feature/native-road-compiler` |
|
| 39 | 2026-08-18 | Complete native-only pipeline replacement | `9e0e25a` | `feature/native-road-compiler` |
|
||||||
| 38 | 2026-08-18 | Complete native traffic signal workflow | `5accc0a` | `feature/native-road-compiler` |
|
| 38 | 2026-08-18 | Complete native traffic signal workflow | `5accc0a` | `feature/native-road-compiler` |
|
||||||
| 37 | 2026-08-18 | Complete rounded native junction verification | `e41bfd1`, `f7e71cf` | `feature/native-road-compiler` |
|
| 37 | 2026-08-18 | Complete rounded native junction verification | `e41bfd1`, `f7e71cf` | `feature/native-road-compiler` |
|
||||||
|
|||||||
@@ -843,3 +843,45 @@ Made native road compilation the default provider and full-build stage set; deco
|
|||||||
### Status
|
### Status
|
||||||
|
|
||||||
[OK] **Completed**
|
[OK] **Completed**
|
||||||
|
|
||||||
|
|
||||||
|
## Session 40: Stabilize Fengshu native road compilation
|
||||||
|
|
||||||
|
**Date**: 2026-08-24
|
||||||
|
**Task**: Stabilize Fengshu native road compilation
|
||||||
|
**Branch**: `fengshu-er-road`
|
||||||
|
|
||||||
|
### Summary
|
||||||
|
|
||||||
|
Validated and committed the Fengshu Er Road native compilation fixes, including stale override tolerance, corrected unreferenced complex-junction sizing, updated OSM input, and focused road/traffic preview regression coverage.
|
||||||
|
|
||||||
|
### Git Commits
|
||||||
|
|
||||||
|
| Hash | Message |
|
||||||
|
|------|---------|
|
||||||
|
| `f1f829c` | (see git log) |
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
[OK] **Completed**
|
||||||
|
|
||||||
|
|
||||||
|
## Session 41: Use live V2X vehicle streams only
|
||||||
|
|
||||||
|
**Date**: 2026-08-24
|
||||||
|
**Task**: Use live V2X vehicle streams only
|
||||||
|
**Branch**: `fengshu-er-road`
|
||||||
|
|
||||||
|
### Summary
|
||||||
|
|
||||||
|
Replaced the Cesium preview's simulated vehicle route with authenticated OBU and target-vehicle V2X streams, converting GCJ-02 coordinates to WGS84 exactly once. Removed native traffic-simulation output, regenerated Fengshu Er Road preview, documented the no-fallback contract, and verified focused preview, V2X, budget, native-road, and signal tests.
|
||||||
|
|
||||||
|
### Git Commits
|
||||||
|
|
||||||
|
| Hash | Message |
|
||||||
|
|------|---------|
|
||||||
|
| `b7031f1` | (see git log) |
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
[OK] **Completed**
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -55,6 +55,20 @@ npm run build:area -- --config config/areas/nantaizi-lake-innovation-valley.json
|
|||||||
|
|
||||||
## 导出为 Cesium GLB
|
## 导出为 Cesium GLB
|
||||||
|
|
||||||
|
导出脚本会优先使用 `tqdm` 显示固定在终端底部的进度条、速率和 ETA。它是可选依赖;未安装
|
||||||
|
时脚本自动回退为普通的 `CESIUM_EXPORT_PROGRESS` 日志,不会阻止导出。
|
||||||
|
|
||||||
|
macOS Blender 可用自带 Python 安装依赖:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
/Applications/Blender.app/Contents/Resources/4.5/python/bin/python3.11 \
|
||||||
|
-m pip install -r blender/requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
若 Blender 安装路径或版本不同,使用对应的 `Resources/<version>/python/bin/python3.*`。
|
||||||
|
安装后必须使用同一 Blender 安装启动导出脚本,系统 Python 中安装的 `tqdm` 不会自动被
|
||||||
|
Blender 发现。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
/Applications/Blender.app/Contents/MacOS/Blender \
|
/Applications/Blender.app/Contents/MacOS/Blender \
|
||||||
--background \
|
--background \
|
||||||
|
|||||||
+64
-12
@@ -16,6 +16,11 @@ import sys
|
|||||||
import bpy
|
import bpy
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
try:
|
||||||
|
from tqdm import tqdm
|
||||||
|
except ImportError:
|
||||||
|
tqdm = None
|
||||||
|
|
||||||
# --factory-startup does not put the script's own directory on sys.path, so the
|
# --factory-startup does not put the script's own directory on sys.path, so the
|
||||||
# osmassets package next to this file is not importable without this.
|
# osmassets package next to this file is not importable without this.
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
@@ -603,9 +608,39 @@ def semantic_asset_specs(glb_path, meshes):
|
|||||||
return specs
|
return specs
|
||||||
|
|
||||||
|
|
||||||
|
class ExportProgress:
|
||||||
|
"""Use tqdm when available, while keeping Blender builds dependency-free."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.percent = 0
|
||||||
|
self.bar = tqdm(total=100, desc="Cesium export", unit="%",
|
||||||
|
dynamic_ncols=True, mininterval=0.2,
|
||||||
|
disable=tqdm is None) if tqdm else None
|
||||||
|
|
||||||
|
def update(self, stage, percent, detail=""):
|
||||||
|
percent = max(self.percent, min(100, float(percent)))
|
||||||
|
delta = percent - self.percent
|
||||||
|
self.percent = percent
|
||||||
|
if self.bar:
|
||||||
|
self.bar.set_description("Cesium export | %s" % stage)
|
||||||
|
self.bar.set_postfix_str(detail, refresh=False)
|
||||||
|
if delta:
|
||||||
|
self.bar.update(delta)
|
||||||
|
self.bar.refresh()
|
||||||
|
return
|
||||||
|
suffix = " - " + detail if detail else ""
|
||||||
|
print("CESIUM_EXPORT_PROGRESS %3.0f%% [%s]%s" % (percent, stage, suffix), flush=True)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
if self.bar:
|
||||||
|
self.bar.close()
|
||||||
|
|
||||||
|
|
||||||
def export(args):
|
def export(args):
|
||||||
if not os.path.exists(args["blend"]):
|
if not os.path.exists(args["blend"]):
|
||||||
raise FileNotFoundError(args["blend"])
|
raise FileNotFoundError(args["blend"])
|
||||||
|
progress = ExportProgress()
|
||||||
|
progress.update("load scene", 1, os.path.basename(args["blend"]))
|
||||||
bpy.ops.wm.open_mainfile(filepath=args["blend"])
|
bpy.ops.wm.open_mainfile(filepath=args["blend"])
|
||||||
|
|
||||||
material_map = {}
|
material_map = {}
|
||||||
@@ -613,13 +648,13 @@ def export(args):
|
|||||||
dynamic_meshes = []
|
dynamic_meshes = []
|
||||||
countdown_meshes = {0: [], 1: []}
|
countdown_meshes = {0: [], 1: []}
|
||||||
unwrapped = set()
|
unwrapped = set()
|
||||||
for obj in bpy.context.scene.objects:
|
scene_objects = list(bpy.context.scene.objects)
|
||||||
if obj.type != "MESH":
|
candidates = [obj for obj in scene_objects
|
||||||
continue
|
if obj.type == "MESH" and obj.name != "Ground Plane"
|
||||||
if obj.name == "Ground Plane":
|
and not obj.hide_viewport and not obj.hide_render]
|
||||||
continue
|
total_candidates = max(1, len(candidates))
|
||||||
if obj.hide_viewport or obj.hide_render:
|
progress.update("prepare scene", 3, "%d mesh objects" % len(candidates))
|
||||||
continue
|
for index, obj in enumerate(candidates, 1):
|
||||||
if any(c.name == "06_TrafficSignalsDynamic" for c in obj.users_collection):
|
if any(c.name == "06_TrafficSignalsDynamic" for c in obj.users_collection):
|
||||||
groups = {slot.material.name for slot in obj.material_slots if slot.material}
|
groups = {slot.material.name for slot in obj.material_slots if slot.material}
|
||||||
group = (0 if any("Countdown Group 0" in name for name in groups)
|
group = (0 if any("Countdown Group 0" in name for name in groups)
|
||||||
@@ -650,21 +685,36 @@ def export(args):
|
|||||||
if source.name not in material_map:
|
if source.name not in material_map:
|
||||||
material_map[source.name] = make_export_material(source)
|
material_map[source.name] = make_export_material(source)
|
||||||
slot.material = material_map[source.name]
|
slot.material = material_map[source.name]
|
||||||
|
if index == total_candidates or index % max(1, total_candidates // 50) == 0:
|
||||||
|
progress.update("prepare scene", 3 + 42 * index / total_candidates,
|
||||||
|
"%d/%d objects, %d materials" % (index, total_candidates, len(material_map)))
|
||||||
|
|
||||||
export_glb(args["glb"], meshes)
|
semantic_assets = semantic_asset_specs(args["glb"], meshes)
|
||||||
|
exports = [(args["glb"], meshes, "main scene")]
|
||||||
if args.get("dynamic_glb"):
|
if args.get("dynamic_glb"):
|
||||||
if not dynamic_meshes:
|
if not dynamic_meshes:
|
||||||
raise RuntimeError("Dynamic traffic signal collection is empty")
|
raise RuntimeError("Dynamic traffic signal collection is empty")
|
||||||
export_glb(args["dynamic_glb"], dynamic_meshes)
|
exports.append((args["dynamic_glb"], dynamic_meshes, "dynamic signals"))
|
||||||
for group, key in ((0, "countdown_0_glb"), (1, "countdown_1_glb")):
|
for group, key in ((0, "countdown_0_glb"), (1, "countdown_1_glb")):
|
||||||
if not args.get(key):
|
if not args.get(key):
|
||||||
continue
|
continue
|
||||||
if not countdown_meshes[group]:
|
if not countdown_meshes[group]:
|
||||||
raise RuntimeError("Traffic countdown collection %d is empty" % group)
|
raise RuntimeError("Traffic countdown collection %d is empty" % group)
|
||||||
export_glb(args[key], countdown_meshes[group])
|
exports.append((args[key], countdown_meshes[group], "countdown group %d" % group))
|
||||||
semantic_assets = semantic_asset_specs(args["glb"], meshes)
|
|
||||||
for asset in semantic_assets:
|
for asset in semantic_assets:
|
||||||
export_glb(asset["path"], asset["meshes"])
|
exports.append((asset["path"], asset["meshes"], "%s layer" % asset["id"]))
|
||||||
|
|
||||||
|
total_export_objects = max(1, sum(len(objects) for _, objects, _ in exports))
|
||||||
|
completed_export_objects = 0
|
||||||
|
for filepath, objects, label in exports:
|
||||||
|
start_percent = 45 + 50 * completed_export_objects / total_export_objects
|
||||||
|
end_percent = 45 + 50 * (completed_export_objects + len(objects)) / total_export_objects
|
||||||
|
progress.update("export GLB", start_percent,
|
||||||
|
"%s (%d objects)" % (label, len(objects)))
|
||||||
|
export_glb(filepath, objects)
|
||||||
|
completed_export_objects += len(objects)
|
||||||
|
progress.update("export GLB", end_percent, "%s complete" % label)
|
||||||
|
progress.update("write metadata", 97)
|
||||||
|
|
||||||
scene = bpy.context.scene
|
scene = bpy.context.scene
|
||||||
try:
|
try:
|
||||||
@@ -711,6 +761,8 @@ def export(args):
|
|||||||
json.dump(metadata, handle, ensure_ascii=False, indent=2)
|
json.dump(metadata, handle, ensure_ascii=False, indent=2)
|
||||||
handle.write("\n")
|
handle.write("\n")
|
||||||
|
|
||||||
|
progress.update("complete", 100, "all assets exported")
|
||||||
|
progress.close()
|
||||||
print("CESIUM_EXPORT_DONE", json.dumps({
|
print("CESIUM_EXPORT_DONE", json.dumps({
|
||||||
"glb": args["glb"], "metadata": args["metadata"],
|
"glb": args["glb"], "metadata": args["metadata"],
|
||||||
"meshes": len(meshes), "materials": len(material_map),
|
"meshes": len(meshes), "materials": len(material_map),
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# Optional runtime helper for export_cesium.py progress display.
|
||||||
|
tqdm>=4.66,<5
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
{
|
||||||
|
"id": "fengshu-er-road",
|
||||||
|
"input": "/Users/que01/osm2streets-qgis-workflow/inputs/osm/枫树二路.osm",
|
||||||
|
"outputRoot": "/Users/que01/osm2streets-qgis-workflow/outputs",
|
||||||
|
"qgisApp": "/Applications/QGIS.app",
|
||||||
|
"blenderApp": "/Applications/Blender.app",
|
||||||
|
"stages": {
|
||||||
|
"intermediates": false,
|
||||||
|
"blender": true,
|
||||||
|
"cesium": true
|
||||||
|
},
|
||||||
|
"qgis": {
|
||||||
|
"arrowScale": 0.8,
|
||||||
|
"arrowMergeTriangles": true,
|
||||||
|
"arrowOutlineSimplifyMeters": 0.05,
|
||||||
|
"intersectionCornerSourceMaxDimensionMeters": 2.6,
|
||||||
|
"clipPad": 0.002,
|
||||||
|
"canvasPad": 0.001,
|
||||||
|
"previewPad": 0.0007,
|
||||||
|
"canvasExtent": null,
|
||||||
|
"previewExtent": null,
|
||||||
|
"layerPrefix": "osm2streets"
|
||||||
|
},
|
||||||
|
"turnLaneArrows": {
|
||||||
|
"enabled": false
|
||||||
|
},
|
||||||
|
"nativeRoad": {
|
||||||
|
"edgeLines": false,
|
||||||
|
"junctionTemplates": {
|
||||||
|
"enabled": true,
|
||||||
|
"references": [],
|
||||||
|
"clusters": [
|
||||||
|
{
|
||||||
|
"id": "zhushanhu-fengshu-complex",
|
||||||
|
"template": "complex-junction-v1",
|
||||||
|
"referenceFile": "/Users/que01/osm2streets-qgis-workflow/inputs/osm/珠山湖大道(枫树二路)口.geojson",
|
||||||
|
"approachWidthMultiplier": 1.45,
|
||||||
|
"approachLengthMeters": 32,
|
||||||
|
"coreRadiusMeters": 28,
|
||||||
|
"cornerRadiusMeters": 25,
|
||||||
|
"outerRadiusExtraMeters": 24,
|
||||||
|
"nodeIds": [
|
||||||
|
"8005332807",
|
||||||
|
"8024512135",
|
||||||
|
"8024512145",
|
||||||
|
"8024512147"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"osm2streets": {
|
||||||
|
"debug_each_step": false,
|
||||||
|
"dual_carriageway_experiment": false,
|
||||||
|
"sidepath_zipping_experiment": false,
|
||||||
|
"inferred_sidewalks": true,
|
||||||
|
"osm2lanes": true
|
||||||
|
},
|
||||||
|
"blender": {
|
||||||
|
"treeStyle": "natural",
|
||||||
|
"officeOverrides": "",
|
||||||
|
"roadProvider": "native"
|
||||||
|
},
|
||||||
|
"v2xPreview": {
|
||||||
|
"enabled": true,
|
||||||
|
"apiBaseUrl": "/api",
|
||||||
|
"wsBaseUrl": "/websocket",
|
||||||
|
"crossCode": ""
|
||||||
|
},
|
||||||
|
"compress": {
|
||||||
|
"textureSize": 768,
|
||||||
|
"quality": 82,
|
||||||
|
"effort": 80,
|
||||||
|
"meshopt": false
|
||||||
|
},
|
||||||
|
"budget": {
|
||||||
|
"glbSizeMb": 25,
|
||||||
|
"nodes": 1000,
|
||||||
|
"images": 24,
|
||||||
|
"triangles": 250000,
|
||||||
|
"embeddedImageBytesMb": 20,
|
||||||
|
"reason": ""
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,7 +25,12 @@
|
|||||||
"enabled": false
|
"enabled": false
|
||||||
},
|
},
|
||||||
"nativeRoad": {
|
"nativeRoad": {
|
||||||
"edgeLines": false
|
"edgeLines": false,
|
||||||
|
"junctionTemplates": {
|
||||||
|
"enabled": false,
|
||||||
|
"references": [],
|
||||||
|
"clusters": []
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"osm2streets": {
|
"osm2streets": {
|
||||||
"debug_each_step": false,
|
"debug_each_step": false,
|
||||||
@@ -39,6 +44,12 @@
|
|||||||
"officeOverrides": "",
|
"officeOverrides": "",
|
||||||
"roadProvider": "native"
|
"roadProvider": "native"
|
||||||
},
|
},
|
||||||
|
"v2xPreview": {
|
||||||
|
"enabled": false,
|
||||||
|
"apiBaseUrl": "/api",
|
||||||
|
"wsBaseUrl": "/websocket",
|
||||||
|
"crossCode": ""
|
||||||
|
},
|
||||||
"compress": {
|
"compress": {
|
||||||
"textureSize": 768,
|
"textureSize": 768,
|
||||||
"quality": 82,
|
"quality": 82,
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
# Live V2X Cesium Preview
|
||||||
|
|
||||||
|
The Cesium preview displays live V2X operational data on a compiled native
|
||||||
|
intersection. The package manifest, native road geometry, and traffic signals
|
||||||
|
remain independent of the service. Vehicle entities and their trace lines are
|
||||||
|
created only from authenticated V2X streams; generated routes and traffic
|
||||||
|
simulation are never rendered as a substitute.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Add a non-sensitive `v2xPreview` object to the area configuration:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"v2xPreview": {
|
||||||
|
"enabled": true,
|
||||||
|
"apiBaseUrl": "/api",
|
||||||
|
"wsBaseUrl": "/websocket",
|
||||||
|
"crossCode": "420100023333"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`apiBaseUrl` and `wsBaseUrl` should normally be relative, same-origin paths.
|
||||||
|
The deployment server proxies them to the V2X REST and WebSocket services. Do
|
||||||
|
not commit a private upstream address, an account, a token, or an AMap key.
|
||||||
|
`crossCode` is deployment configuration for the selected intersection. It is
|
||||||
|
never shown or editable in the browser login panel.
|
||||||
|
|
||||||
|
### Optional phase binding overrides
|
||||||
|
|
||||||
|
`traffic-signals.json` carries no V2X phase number, so live phases are bound to
|
||||||
|
native signal heads geometrically (see *Phase Binding* below). Three optional
|
||||||
|
keys tune or replace that binding:
|
||||||
|
|
||||||
|
| Key | Default | Purpose |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `maxDistanceMeters` | `30` | Stop-line proximity tolerance. |
|
||||||
|
| `maxHeadingDeltaDegrees` | `45` | Approach heading tolerance. |
|
||||||
|
| `phaseSignalMap` | none | Explicit `{"<phaseNo>": ["<nodeKey>", …]}`; bypasses geometry for the listed phases. |
|
||||||
|
|
||||||
|
Use `phaseSignalMap` when the V2X link geometry cannot be matched — the V2X
|
||||||
|
panel reports how many phases bound and how many did not.
|
||||||
|
|
||||||
|
The page always starts at the login gate. After authentication it resolves the
|
||||||
|
current intersection with the same source-dashboard rule: request the HD-map
|
||||||
|
cross list and cross-device configuration list, prefer a configured cross, then
|
||||||
|
use the first available HD-map cross. Only after that resolution succeeds does
|
||||||
|
it issue the operational REST requests or open signal, OBU, and target-vehicle
|
||||||
|
WebSockets.
|
||||||
|
|
||||||
|
The browser sends `POST {apiBaseUrl}/facilities/api/sys/login` with `userName`
|
||||||
|
and an MD5-hashed password, matching the source V2X dashboard. It holds the
|
||||||
|
returned token in `sessionStorage` only, sends it as the raw `Authorization`
|
||||||
|
header for REST calls, and uses it as the `authorization` parameter for the
|
||||||
|
signal WebSocket. Closing the tab clears the session token.
|
||||||
|
|
||||||
|
## Data Sources
|
||||||
|
|
||||||
|
After sign-in the preview reads the selected intersection's links, pole
|
||||||
|
configuration, bound devices, and device configuration, and subscribes to
|
||||||
|
`/network/ws/network/signal` for phase updates. It also subscribes to
|
||||||
|
`/network/ws/network/obuPosition` and `/network/ws/network/targetPosition` for
|
||||||
|
the only vehicle and vehicle-line sources. Failures are shown in the V2X panel;
|
||||||
|
the static Cesium scene stays available and the vehicle layer stays empty.
|
||||||
|
|
||||||
|
All three sockets mirror the source dashboard's connection behaviour: a
|
||||||
|
`{"heartBeat":"ping"}` frame every 30 s, automatic reconnect with backoff, and
|
||||||
|
the subscription frame replayed on every reconnect. Without the heartbeat the
|
||||||
|
service drops the connection and the scene silently empties after a minute.
|
||||||
|
|
||||||
|
Subscription frames match the dashboard exactly:
|
||||||
|
|
||||||
|
| Socket | Frame on every (re)connect |
|
||||||
|
| --- | --- |
|
||||||
|
| `signal` | `{"junctionId":"<crossCode>"}` |
|
||||||
|
| `obuPosition` | `{"bounds":"<four GCJ-02 corners>"}`, or an empty frame when the camera rectangle is unavailable (no viewport filter) |
|
||||||
|
| `targetPosition` | `{"deviceId":"<ids>"}`, or `{"deviceId":null}` when no targets are configured |
|
||||||
|
|
||||||
|
## Phase Binding
|
||||||
|
|
||||||
|
The runtime traffic-signal document has no V2X `phaseNo`, so phases are bound to
|
||||||
|
native signal heads by geometry: the V2X link's last segment ends at the stop
|
||||||
|
line, and each native signal records its own stop-line point and heading. The
|
||||||
|
generator in `scripts/lib/traffic-signals.js` derives `mast = travel - 90` and
|
||||||
|
`face = travel + 180` from the approach travel direction, so the travel heading
|
||||||
|
is recovered as `faceHeadingDegrees + 180`.
|
||||||
|
|
||||||
|
One link may bind several heads on the same approach, and several links may
|
||||||
|
share one phase; both are unions, so a phase lights every approach it drives.
|
||||||
|
Unbound phases are counted in the panel — override them with `phaseSignalMap`.
|
||||||
|
|
||||||
|
## Vehicle Lifecycle
|
||||||
|
|
||||||
|
Vehicles follow the dashboard's rules: the push `interval` (`0` falls back to
|
||||||
|
500 ms) sets the animation duration, a vehicle not updated within
|
||||||
|
`interval * 1.5` is hidden, and hidden entries stay as reusable slots rather
|
||||||
|
than being removed. The OBU data hook calls its model `car_obu.glb`, but the
|
||||||
|
dashboard's final `CrossCars` template renders `11.glb`; the preview uses that
|
||||||
|
final rendering contract. Targets use `${type}${subType}.glb`. The dashboard
|
||||||
|
vehicle assets are packaged under `_preview/v2x-vehicles/`. Valid live vehicles
|
||||||
|
are lifted clear of the road, remain at least 28 screen pixels in overview, and
|
||||||
|
the first live push focuses the camera near the vehicle group.
|
||||||
|
|
||||||
|
## Coordinate Contract
|
||||||
|
|
||||||
|
| Data | Coordinate system | Preview handling |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Native package placement and traffic signals | WGS84 and local ENU | Existing Cesium contract; unchanged. |
|
||||||
|
| V2X dashboard road/link/device data | GCJ-02 | Converted once to WGS84 immediately before Cesium entity creation. |
|
||||||
|
| High德 reference GeoJSON | GCJ-02 | Compiler calibration input only; never loaded by this preview. |
|
||||||
|
|
||||||
|
Do not convert native WGS84 data again, and do not pass V2X GCJ-02 coordinates
|
||||||
|
directly to Cesium. Either error produces a visible intersection offset.
|
||||||
|
|
||||||
|
## Proxy Requirements
|
||||||
|
|
||||||
|
Use an HTTPS reverse proxy which forwards the configured REST prefix and supports
|
||||||
|
WebSocket upgrade for the configured WS prefix. For development or a simple host
|
||||||
|
without Nginx, use the repository's proxy static server instead of
|
||||||
|
`python3 -m http.server`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
V2X_UPSTREAM=http://<v2x-api-host>:<port>/dashboardApi \
|
||||||
|
V2X_WS_UPSTREAM=http://<v2x-ws-host>:<port>/dashboardWebsocket \
|
||||||
|
npm run serve:v2x-preview -- --root outputs/fengshu-er-road --host 0.0.0.0 --port 7862
|
||||||
|
```
|
||||||
|
|
||||||
|
It rewrites `/api/*` and `/websocket/*` before proxying, matching the source
|
||||||
|
dashboard's Vite proxy. The upstream address stays an environment value, not a
|
||||||
|
browser configuration or committed area file. The generated preview is static,
|
||||||
|
so direct cross-origin calls are likely to fail CORS or expose an internal origin.
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
`v2xPreview.enabled` defaults to `false`; set it to `true` for a selected area.
|
||||||
|
Set it back to `false` and regenerate the preview. The generated
|
||||||
|
page omits the V2X panel; published package contents remain unchanged.
|
||||||
+11091
File diff suppressed because it is too large.
Load diff
@@ -12,10 +12,13 @@
|
|||||||
"diagnose:area": "node scripts/diagnose-area.js",
|
"diagnose:area": "node scripts/diagnose-area.js",
|
||||||
"preflight:area": "node scripts/preflight-area.js",
|
"preflight:area": "node scripts/preflight-area.js",
|
||||||
"road:compile": "node scripts/compile-native-roads.js",
|
"road:compile": "node scripts/compile-native-roads.js",
|
||||||
|
"reference:junction": "node scripts/inspect-junction-reference.js",
|
||||||
"road:check": "node scripts/check-native-roads.js",
|
"road:check": "node scripts/check-native-roads.js",
|
||||||
"road:workbench": "node scripts/road-workbench.js",
|
"road:workbench": "node scripts/road-workbench.js",
|
||||||
|
"serve:v2x-preview": "node scripts/v2x-preview-server.js",
|
||||||
"test:road-workbench": "node scripts/test-road-workbench.js",
|
"test:road-workbench": "node scripts/test-road-workbench.js",
|
||||||
"test:native-road": "node scripts/test-native-road.js",
|
"test:native-road": "node scripts/test-native-road.js",
|
||||||
|
"test:gaode-junction-reference": "node scripts/test-gaode-junction-reference.js",
|
||||||
"test:preflight": "node scripts/test-area-preflight.js",
|
"test:preflight": "node scripts/test-area-preflight.js",
|
||||||
"test:build-stages": "node scripts/test-build-stages.js",
|
"test:build-stages": "node scripts/test-build-stages.js",
|
||||||
"test:budgets": "node scripts/test-asset-budgets.js",
|
"test:budgets": "node scripts/test-asset-budgets.js",
|
||||||
@@ -26,6 +29,8 @@
|
|||||||
"test:turn-lane-arrows": "node scripts/test-turn-lane-arrows.js",
|
"test:turn-lane-arrows": "node scripts/test-turn-lane-arrows.js",
|
||||||
"test:traffic-signals": "node scripts/test-traffic-signals.js",
|
"test:traffic-signals": "node scripts/test-traffic-signals.js",
|
||||||
"test:native-preview-traffic": "node scripts/test-native-preview-traffic.js",
|
"test:native-preview-traffic": "node scripts/test-native-preview-traffic.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"
|
"render:turn-lane-arrow-samples": "node scripts/render-turn-lane-arrow-samples.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
+11
-12
@@ -16,8 +16,7 @@ const {
|
|||||||
} = require("./lib/scene-layers");
|
} = require("./lib/scene-layers");
|
||||||
const { digest: glbDigest } = require("./glb-digest");
|
const { digest: glbDigest } = require("./glb-digest");
|
||||||
const { buildVehicleRoute: buildPreviewVehicleRoute } = require("./lib/vehicle-route");
|
const { buildVehicleRoute: buildPreviewVehicleRoute } = require("./lib/vehicle-route");
|
||||||
const { buildNativeTrafficSimulation } = require("./lib/native-preview-traffic-simulation");
|
const { writePreviewVehicleLibrary, writePreviewV2xVehicleLibrary } = require("./lib/vehicle-library");
|
||||||
const { writePreviewVehicleLibrary } = require("./lib/vehicle-library");
|
|
||||||
const { readTrafficSignals } = require("./lib/traffic-signals");
|
const { readTrafficSignals } = require("./lib/traffic-signals");
|
||||||
const {
|
const {
|
||||||
cesiumPreviewHtml,
|
cesiumPreviewHtml,
|
||||||
@@ -559,6 +558,7 @@ function writeCesiumPreview(area, roadProvider) {
|
|||||||
osm: fileRecord(area.input),
|
osm: fileRecord(area.input),
|
||||||
previewCss: fileRecord(path.join(repoRoot, "scripts", "lib", "cesium-preview.css")),
|
previewCss: fileRecord(path.join(repoRoot, "scripts", "lib", "cesium-preview.css")),
|
||||||
previewJs: fileRecord(path.join(repoRoot, "scripts", "lib", "cesium-preview.js")),
|
previewJs: fileRecord(path.join(repoRoot, "scripts", "lib", "cesium-preview.js")),
|
||||||
|
v2xPreviewJs: fileRecord(path.join(repoRoot, "scripts", "lib", "v2x-cesium-overlay.js")),
|
||||||
};
|
};
|
||||||
if (roadProvider === "osm2streets") {
|
if (roadProvider === "osm2streets") {
|
||||||
const lanePolygons = path.join(area.outputs.geojsonDir, "lane_polygons.geojson");
|
const lanePolygons = path.join(area.outputs.geojsonDir, "lane_polygons.geojson");
|
||||||
@@ -575,11 +575,9 @@ function writeCesiumPreview(area, roadProvider) {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
Object.assign(previewInputs, nativeRoadRecords(area));
|
Object.assign(previewInputs, nativeRoadRecords(area));
|
||||||
const simulation = buildNativeTrafficSimulation(area);
|
// This operational preview intentionally has no synthetic vehicle source.
|
||||||
fs.mkdirSync(path.dirname(area.outputs.trafficSimulation), { recursive: true });
|
// A stale descriptor from an older build must not resurrect simulated routes.
|
||||||
fs.writeFileSync(area.outputs.trafficSimulation, `${JSON.stringify(simulation, null, 2)}\n`);
|
fs.rmSync(area.outputs.trafficSimulation, { force: true });
|
||||||
previewInputs.trafficSimulation = fileRecord(area.outputs.trafficSimulation);
|
|
||||||
routeArtifact = area.outputs.trafficSimulation;
|
|
||||||
}
|
}
|
||||||
const htmlPath = area.outputs.cesiumPreview;
|
const htmlPath = area.outputs.cesiumPreview;
|
||||||
const started = Date.now();
|
const started = Date.now();
|
||||||
@@ -598,11 +596,11 @@ function writeCesiumPreview(area, roadProvider) {
|
|||||||
const routeName = vehicleRoute || routeArtifact
|
const routeName = vehicleRoute || routeArtifact
|
||||||
? previewRelativePath(area.outputs.areaDir, vehicleRoute ? area.outputs.vehicleRoute : routeArtifact)
|
? previewRelativePath(area.outputs.areaDir, vehicleRoute ? area.outputs.vehicleRoute : routeArtifact)
|
||||||
: null;
|
: null;
|
||||||
const vehicleModelName = previewRelativePath(area.outputs.areaDir, area.outputs.vehicleModel);
|
const vehicleModelName = vehicleModelNames[0] ? `_preview/${vehicleModelNames[0]}` : null;
|
||||||
const descriptor = { routeName, vehicleModelName: previewRelativePath(area.outputs.areaDir, area.outputs.vehicleModel), vehicleModelNames: vehicleModelNames.map((name) => `_preview/${name}`), trafficSignalsName: "package/runtime/traffic-signals.json", assets: [] };
|
const descriptor = { routeName, vehicleModelName, vehicleModelNames: vehicleModelNames.map((name) => `_preview/${name}`), trafficSignalsName: "package/runtime/traffic-signals.json", assets: [] };
|
||||||
fs.mkdirSync(area.outputs.previewDir, { recursive: true });
|
fs.mkdirSync(area.outputs.previewDir, { recursive: true });
|
||||||
fs.writeFileSync(area.outputs.previewDescriptor, `${JSON.stringify(descriptor, null, 2)}\n`);
|
fs.writeFileSync(area.outputs.previewDescriptor, `${JSON.stringify(descriptor, null, 2)}\n`);
|
||||||
fs.writeFileSync(htmlPath, cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, area.id, vehicleModelNames.map((name) => `_preview/${name}`), "package/runtime/traffic-signals.json", "_preview/descriptor.json"));
|
fs.writeFileSync(htmlPath, cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, area.id, vehicleModelNames.map((name) => `_preview/${name}`), "package/runtime/traffic-signals.json", "_preview/descriptor.json", area.v2xPreview));
|
||||||
console.log(`Cesium preview: ${htmlPath}`);
|
console.log(`Cesium preview: ${htmlPath}`);
|
||||||
const finished = Date.now();
|
const finished = Date.now();
|
||||||
writeStageManifest(area, {
|
writeStageManifest(area, {
|
||||||
@@ -650,10 +648,11 @@ function writeVehicleModel(area) {
|
|||||||
const outDir = path.dirname(area.outputs.vehicleModel);
|
const outDir = path.dirname(area.outputs.vehicleModel);
|
||||||
const fileStem = path.basename(area.outputs.vehicleModel, ".gltf").replace(/-vehicle-car$/, "");
|
const fileStem = path.basename(area.outputs.vehicleModel, ".gltf").replace(/-vehicle-car$/, "");
|
||||||
const models = writePreviewVehicleLibrary(outDir, fileStem);
|
const models = writePreviewVehicleLibrary(outDir, fileStem);
|
||||||
|
const v2xModels = area.v2xPreview.enabled ? writePreviewV2xVehicleLibrary(outDir) : [];
|
||||||
// Preserve the existing output/manifest contract for old preview HTML.
|
// Preserve the existing output/manifest contract for old preview HTML.
|
||||||
fs.copyFileSync(path.join(outDir, models[0]), area.outputs.vehicleModel);
|
fs.copyFileSync(path.join(outDir, models[0]), area.outputs.vehicleModel);
|
||||||
console.log(`Vehicle models: ${models.length} candidates in ${path.dirname(area.outputs.vehicleModel)}`);
|
console.log(`Vehicle models: ${models.length + v2xModels.length} candidates in ${path.dirname(area.outputs.vehicleModel)}`);
|
||||||
return models;
|
return [...models, ...v2xModels];
|
||||||
}
|
}
|
||||||
|
|
||||||
function sceneGeojsonRecords(area) {
|
function sceneGeojsonRecords(area) {
|
||||||
|
|||||||
@@ -23,9 +23,23 @@ function compileArea(configPath) {
|
|||||||
const area = readAreaConfig(configPath, { repoRoot });
|
const area = readAreaConfig(configPath, { repoRoot });
|
||||||
const overrides = loadOverrides(area.outputs.nativeRoadOverrides);
|
const overrides = loadOverrides(area.outputs.nativeRoadOverrides);
|
||||||
const model = compileRoadModel(fs.readFileSync(area.input, "utf8"), overrides);
|
const model = compileRoadModel(fs.readFileSync(area.input, "utf8"), overrides);
|
||||||
validateOverrides(overrides, model);
|
// Editing the source OSM retires the ids some overrides point at. Those
|
||||||
|
// entries can no longer match anything, so drop them with a diagnostic rather
|
||||||
|
// than aborting the whole compile — otherwise every OSM edit blocks the
|
||||||
|
// pipeline until the file is hand-pruned, one error message at a time.
|
||||||
|
const validated = validateOverrides(overrides, model, { skipStaleTargets: true });
|
||||||
|
for (const item of validated.stale) console.warn(`[warning] 忽略失效的 override(目标已不存在):${item.id} -> ${item.target}`);
|
||||||
fs.mkdirSync(area.outputs.pipelineDir, { recursive: true });
|
fs.mkdirSync(area.outputs.pipelineDir, { recursive: true });
|
||||||
const compiled = compileGeometry(model, overrides, { edgeLines: area.nativeRoad.edgeLines });
|
const compiled = compileGeometry(model, overrides, { edgeLines: area.nativeRoad.edgeLines, junctionTemplates: area.nativeRoad.junctionTemplates });
|
||||||
|
compiled.diagnostics.push(...validated.stale.map((item) => ({
|
||||||
|
id: `diagnostic:stale-override:${item.id}`,
|
||||||
|
severity: "warning",
|
||||||
|
subjectId: item.id,
|
||||||
|
sourceIds: [],
|
||||||
|
rule: "stale-override-target",
|
||||||
|
message: `该设置指向的 ${item.kind} 目标 ${item.target} 已不存在(OSM 改动后 id 失效),本次编译已忽略。可在工作台重新设置,或从 native-road-overrides.json 中删除。`,
|
||||||
|
geometry: null,
|
||||||
|
})));
|
||||||
const signalDocument = loadOrGenerate(area.outputs.nativeTrafficSignals, fs.readFileSync(area.input, "utf8"), compiled.vehicleStopLines, compiled.intersectionSurface);
|
const signalDocument = loadOrGenerate(area.outputs.nativeTrafficSignals, fs.readFileSync(area.input, "utf8"), compiled.vehicleStopLines, compiled.intersectionSurface);
|
||||||
const signalRuntime = runtime(signalDocument);
|
const signalRuntime = runtime(signalDocument);
|
||||||
// Persist validation normalization, including one-time legacy heading migration.
|
// Persist validation normalization, including one-time legacy heading migration.
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const { inspectReference, localReferenceSvg } = require("./lib/gaode-junction-reference");
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const result = {};
|
||||||
|
for (let index = 0; index < argv.length; index += 1) {
|
||||||
|
if (!argv[index].startsWith("--")) continue;
|
||||||
|
const key = argv[index].slice(2).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
|
||||||
|
result[key] = argv[index + 1] && !argv[index + 1].startsWith("--") ? argv[++index] : "true";
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function required(args, key) {
|
||||||
|
if (!args[key]) throw new Error(`--${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)} is required`);
|
||||||
|
return path.resolve(args[key]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
const args = parseArgs(process.argv.slice(2));
|
||||||
|
const result = inspectReference({
|
||||||
|
referenceFile: required(args, "reference"),
|
||||||
|
osmFile: required(args, "osm"),
|
||||||
|
nativeIntersectionFile: required(args, "nativeIntersection"),
|
||||||
|
nativeRoadSurfaceFile: args.nativeRoadSurface ? path.resolve(args.nativeRoadSurface) : null,
|
||||||
|
nodeId: args.nodeId,
|
||||||
|
clusterId: args.clusterId,
|
||||||
|
});
|
||||||
|
const output = path.resolve(args.output || `${args.reference.replace(/\.geojson$/i, "")}-wgs84.geojson`);
|
||||||
|
const comparison = output.replace(/\.geojson$/i, "-comparison.json");
|
||||||
|
fs.mkdirSync(path.dirname(output), { recursive: true });
|
||||||
|
fs.writeFileSync(output, `${JSON.stringify(result.converted, null, 2)}\n`);
|
||||||
|
fs.writeFileSync(comparison, `${JSON.stringify({ ...result, converted: undefined, matchedFeatures: undefined }, null, 2)}\n`);
|
||||||
|
const svg = output.replace(/\.geojson$/i, "-overlay.svg");
|
||||||
|
// Draw whatever the comparison actually matched: a per-node junction surface
|
||||||
|
// for ordinary junctions, or the whole complex cluster for templated ones.
|
||||||
|
const matchingNative = { type: "FeatureCollection", features: result.matchedFeatures || [] };
|
||||||
|
fs.writeFileSync(svg, localReferenceSvg({ converted: result.converted, nativeIntersection: matchingNative, center: result.matchedOsmNode.coordinate }));
|
||||||
|
console.log(JSON.stringify({ output, comparison, svg, ...result, converted: undefined, matchedFeatures: undefined }, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) main();
|
||||||
@@ -113,6 +113,7 @@ function normalizeAreaConfig(raw, options = {}) {
|
|||||||
},
|
},
|
||||||
nativeRoad: {
|
nativeRoad: {
|
||||||
edgeLines: booleanOption(raw.nativeRoad?.edgeLines, false, "nativeRoad.edgeLines"),
|
edgeLines: booleanOption(raw.nativeRoad?.edgeLines, false, "nativeRoad.edgeLines"),
|
||||||
|
junctionTemplates: normalizeJunctionTemplates(raw.nativeRoad?.junctionTemplates, repoRoot),
|
||||||
},
|
},
|
||||||
osm2streets: raw.osm2streets || {
|
osm2streets: raw.osm2streets || {
|
||||||
debug_each_step: false,
|
debug_each_step: false,
|
||||||
@@ -126,12 +127,71 @@ function normalizeAreaConfig(raw, options = {}) {
|
|||||||
officeOverrides: raw.blender?.officeOverrides || raw.blender?.office_overrides || "",
|
officeOverrides: raw.blender?.officeOverrides || raw.blender?.office_overrides || "",
|
||||||
roadProvider: roadProviderOption(raw.blender?.roadProvider ?? "native"),
|
roadProvider: roadProviderOption(raw.blender?.roadProvider ?? "native"),
|
||||||
},
|
},
|
||||||
|
v2xPreview: normalizeV2xPreviewConfig(raw.v2xPreview),
|
||||||
compress,
|
compress,
|
||||||
budget,
|
budget,
|
||||||
outputs,
|
outputs,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeV2xPreviewConfig(raw) {
|
||||||
|
if (raw !== undefined && (raw === null || typeof raw !== "object" || Array.isArray(raw))) {
|
||||||
|
throw new Error("v2xPreview must be an object");
|
||||||
|
}
|
||||||
|
const value = raw || {};
|
||||||
|
const text = (name, fallback) => {
|
||||||
|
const item = value[name] ?? fallback;
|
||||||
|
if (typeof item !== "string") throw new Error(`v2xPreview.${name} must be a string`);
|
||||||
|
return item.trim();
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
enabled: booleanOption(value.enabled, false, "v2xPreview.enabled"),
|
||||||
|
// Relative defaults keep credentials and private service origins out of the
|
||||||
|
// generated preview. Production should reverse-proxy these prefixes.
|
||||||
|
apiBaseUrl: text("apiBaseUrl", "/api"),
|
||||||
|
wsBaseUrl: text("wsBaseUrl", "/websocket"),
|
||||||
|
crossCode: text("crossCode", ""),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeJunctionTemplates(raw, repoRoot) {
|
||||||
|
if (raw === undefined || raw === null) return { enabled: false, references: [] };
|
||||||
|
if (typeof raw !== "object" || Array.isArray(raw)) throw new Error("nativeRoad.junctionTemplates must be an object");
|
||||||
|
const enabled = booleanOption(raw.enabled, false, "nativeRoad.junctionTemplates.enabled");
|
||||||
|
if (raw.references !== undefined && !Array.isArray(raw.references)) throw new Error("nativeRoad.junctionTemplates.references must be an array");
|
||||||
|
const references = (raw.references || []).map((item, index) => {
|
||||||
|
if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error(`nativeRoad.junctionTemplates.references[${index}] must be an object`);
|
||||||
|
const nodeId = requireText(item.nodeId, `nativeRoad.junctionTemplates.references[${index}].nodeId`);
|
||||||
|
const template = item.template ?? "cross-v1";
|
||||||
|
if (template !== "cross-v1") throw new Error(`nativeRoad.junctionTemplates.references[${index}].template must be \"cross-v1\"`);
|
||||||
|
const referenceFile = item.referenceFile ? path.resolve(item.referenceFile) : null;
|
||||||
|
const coordinateSystem = item.coordinateSystem ?? "GCJ-02";
|
||||||
|
if (coordinateSystem !== "GCJ-02") throw new Error(`nativeRoad.junctionTemplates.references[${index}].coordinateSystem must be \"GCJ-02\"`);
|
||||||
|
const cornerRadiusMultiplier = numberOption(item.cornerRadiusMultiplier, 1, `nativeRoad.junctionTemplates.references[${index}].cornerRadiusMultiplier`, 0.75, 1.25);
|
||||||
|
const cutbackMultiplier = numberOption(item.cutbackMultiplier, 1, `nativeRoad.junctionTemplates.references[${index}].cutbackMultiplier`, 1, 1.35);
|
||||||
|
const approachWidthMultiplier = numberOption(item.approachWidthMultiplier, 1, `nativeRoad.junctionTemplates.references[${index}].approachWidthMultiplier`, 1, 1.8);
|
||||||
|
const approachLengthMeters = numberOption(item.approachLengthMeters, 24, `nativeRoad.junctionTemplates.references[${index}].approachLengthMeters`, 10, 50);
|
||||||
|
return { nodeId, template, referenceFile, coordinateSystem, cornerRadiusMultiplier, cutbackMultiplier, approachWidthMultiplier, approachLengthMeters };
|
||||||
|
});
|
||||||
|
if (raw.clusters !== undefined && !Array.isArray(raw.clusters)) throw new Error("nativeRoad.junctionTemplates.clusters must be an array");
|
||||||
|
const clusters = (raw.clusters || []).map((item, index) => {
|
||||||
|
if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error(`nativeRoad.junctionTemplates.clusters[${index}] must be an object`);
|
||||||
|
const id = requireText(item.id, `nativeRoad.junctionTemplates.clusters[${index}].id`);
|
||||||
|
const nodeIds = item.nodeIds;
|
||||||
|
if (!Array.isArray(nodeIds) || nodeIds.length < 2 || nodeIds.some((value) => typeof value !== "string" && typeof value !== "number")) throw new Error(`nativeRoad.junctionTemplates.clusters[${index}].nodeIds must contain at least two node ids`);
|
||||||
|
const template = item.template ?? "complex-junction-v1";
|
||||||
|
if (template !== "cross-cluster-v1" && template !== "complex-junction-v1") throw new Error(`nativeRoad.junctionTemplates.clusters[${index}].template must be \"cross-cluster-v1\" or \"complex-junction-v1\"`);
|
||||||
|
const referenceFile = item.referenceFile ? path.resolve(item.referenceFile) : null;
|
||||||
|
const approachWidthMultiplier = numberOption(item.approachWidthMultiplier, 1.45, `nativeRoad.junctionTemplates.clusters[${index}].approachWidthMultiplier`, 1, 1.8);
|
||||||
|
const approachLengthMeters = numberOption(item.approachLengthMeters, 32, `nativeRoad.junctionTemplates.clusters[${index}].approachLengthMeters`, 10, 50);
|
||||||
|
const coreRadiusMeters = numberOption(item.coreRadiusMeters, 28, `nativeRoad.junctionTemplates.clusters[${index}].coreRadiusMeters`, 12, 80);
|
||||||
|
const cornerRadiusMeters = numberOption(item.cornerRadiusMeters, 12, `nativeRoad.junctionTemplates.clusters[${index}].cornerRadiusMeters`, 4, 25);
|
||||||
|
const outerRadiusExtraMeters = numberOption(item.outerRadiusExtraMeters, 18, `nativeRoad.junctionTemplates.clusters[${index}].outerRadiusExtraMeters`, 18, 35);
|
||||||
|
return { id, nodeIds: nodeIds.map(String), template, referenceFile, approachWidthMultiplier, approachLengthMeters, coreRadiusMeters, cornerRadiusMeters, outerRadiusExtraMeters };
|
||||||
|
});
|
||||||
|
return { enabled, references, clusters };
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeBudgetConfig(raw) {
|
function normalizeBudgetConfig(raw) {
|
||||||
if (raw !== undefined && raw !== null && (typeof raw !== "object" || Array.isArray(raw))) {
|
if (raw !== undefined && raw !== null && (typeof raw !== "object" || Array.isArray(raw))) {
|
||||||
throw new Error("budget must be an object");
|
throw new Error("budget must be an object");
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ function writeCesiumPreviewSupportFiles(outDir) {
|
|||||||
const files = [
|
const files = [
|
||||||
[path.join(__dirname, "cesium-preview.css"), "cesium-preview.css"],
|
[path.join(__dirname, "cesium-preview.css"), "cesium-preview.css"],
|
||||||
[path.join(__dirname, "cesium-preview.js"), "cesium-preview.js"],
|
[path.join(__dirname, "cesium-preview.js"), "cesium-preview.js"],
|
||||||
|
[path.join(__dirname, "v2x-cesium-overlay.js"), "v2x-cesium-overlay.js"],
|
||||||
[path.join(__dirname, "..", "..", "assets", "preview", "vehicle-breakdown.png"), "vehicle-breakdown.png"],
|
[path.join(__dirname, "..", "..", "assets", "preview", "vehicle-breakdown.png"), "vehicle-breakdown.png"],
|
||||||
[path.join(__dirname, "..", "..", "assets", "preview", "vehicle-accident.png"), "vehicle-accident.png"],
|
[path.join(__dirname, "..", "..", "assets", "preview", "vehicle-accident.png"), "vehicle-accident.png"],
|
||||||
];
|
];
|
||||||
@@ -18,7 +19,7 @@ function writeCesiumPreviewSupportFiles(outDir) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, areaId, vehicleModelNames = [], trafficSignalsName = null, previewDescriptorName = null) {
|
function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, areaId, vehicleModelNames = [], trafficSignalsName = null, previewDescriptorName = null, v2xPreview = null) {
|
||||||
const previewConfig = {
|
const previewConfig = {
|
||||||
areaId,
|
areaId,
|
||||||
glbName,
|
glbName,
|
||||||
@@ -28,6 +29,7 @@ function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, a
|
|||||||
vehicleModelNames,
|
vehicleModelNames,
|
||||||
trafficSignalsName,
|
trafficSignalsName,
|
||||||
previewDescriptorName,
|
previewDescriptorName,
|
||||||
|
v2xPreview,
|
||||||
};
|
};
|
||||||
return `<!doctype html>
|
return `<!doctype html>
|
||||||
<html lang="zh-CN">
|
<html lang="zh-CN">
|
||||||
@@ -35,8 +37,8 @@ function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, a
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>${escapeHtml(areaId)} Cesium Preview</title>
|
<title>${escapeHtml(areaId)} Cesium Preview</title>
|
||||||
<script src="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Cesium.js"></script>
|
<link href="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Widgets/widgets.css" rel="stylesheet" onerror="this.onerror=null;this.href='https://unpkg.com/cesium@1.121.1/Build/Cesium/Widgets/widgets.css'">
|
||||||
<link href="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
|
<script src="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Cesium.js" onerror="this.onerror=null;this.src='https://unpkg.com/cesium@1.121.1/Build/Cesium/Cesium.js';"></script>
|
||||||
<link href="cesium-preview.css" rel="stylesheet">
|
<link href="cesium-preview.css" rel="stylesheet">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -100,6 +102,7 @@ function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, a
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script>window.OSM_ASSET_PREVIEW_CONFIG = ${escapeScriptJson(JSON.stringify(previewConfig))};</script>
|
<script>window.OSM_ASSET_PREVIEW_CONFIG = ${escapeScriptJson(JSON.stringify(previewConfig))};</script>
|
||||||
|
<script src="v2x-cesium-overlay.js"></script>
|
||||||
<script src="cesium-preview.js"></script>
|
<script src="cesium-preview.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -161,6 +161,74 @@ body.scene-error .loading-bar span {
|
|||||||
white-space: pre-line;
|
white-space: pre-line;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#v2xPanel {
|
||||||
|
position: absolute;
|
||||||
|
right: 12px;
|
||||||
|
bottom: 12px;
|
||||||
|
z-index: 2;
|
||||||
|
box-sizing: border-box;
|
||||||
|
width: min(300px, calc(100vw - 24px));
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: rgba(20, 24, 28, 0.88);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.45;
|
||||||
|
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
.v2x-heading {
|
||||||
|
display: grid;
|
||||||
|
gap: 2px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.v2x-heading span,
|
||||||
|
#v2xStatus {
|
||||||
|
color: rgba(255, 255, 255, 0.68);
|
||||||
|
}
|
||||||
|
|
||||||
|
#v2xLoginForm,
|
||||||
|
#v2xLiveControls {
|
||||||
|
display: grid;
|
||||||
|
gap: 7px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#v2xPanel label {
|
||||||
|
display: grid;
|
||||||
|
gap: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#v2xPanel input {
|
||||||
|
box-sizing: border-box;
|
||||||
|
width: 100%;
|
||||||
|
height: 27px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.28);
|
||||||
|
border-radius: 3px;
|
||||||
|
padding: 0 7px;
|
||||||
|
background: rgba(255, 255, 255, 0.12);
|
||||||
|
color: #fff;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
#v2xPanel button {
|
||||||
|
height: 27px;
|
||||||
|
margin-right: 6px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 3px;
|
||||||
|
padding: 0 8px;
|
||||||
|
background: #e9f3f5;
|
||||||
|
color: #112326;
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
#v2xStatus {
|
||||||
|
display: block;
|
||||||
|
margin-top: 8px;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
#vehicleInfoCard {
|
#vehicleInfoCard {
|
||||||
left: 0;
|
left: 0;
|
||||||
top: 0;
|
top: 0;
|
||||||
|
|||||||
+110
-15
@@ -48,22 +48,32 @@
|
|||||||
const metadata = await fetchJson(config.metadataName);
|
const metadata = await fetchJson(config.metadataName);
|
||||||
const descriptor = config.previewDescriptorName ? await fetchOptionalJson(config.previewDescriptorName) : null;
|
const descriptor = config.previewDescriptorName ? await fetchOptionalJson(config.previewDescriptorName) : null;
|
||||||
adaptPackageManifest(metadata, descriptor);
|
adaptPackageManifest(metadata, descriptor);
|
||||||
const routeData = await fetchOptionalJson(config.routeName);
|
|
||||||
const signalData = await fetchOptionalJson(config.trafficSignalsName);
|
const signalData = await fetchOptionalJson(config.trafficSignalsName);
|
||||||
const placement = scenePlacement(metadata);
|
const placement = scenePlacement(metadata);
|
||||||
const viewer = createViewer();
|
const viewer = createViewer();
|
||||||
setLoadingMessage("Loading model", config.glbName || "");
|
setLoadingMessage("Loading model", config.glbName || "");
|
||||||
const assets = await loadSceneAssets(viewer, metadata, placement);
|
const assets = await loadSceneAssets(viewer, metadata, placement);
|
||||||
const trafficStart = Cesium.JulianDate.now();
|
const trafficStart = Cesium.JulianDate.now();
|
||||||
const trafficSignals = addTrafficSignals(viewer, signalData, trafficStart, assets);
|
const trafficSignals = createLiveTrafficSignals(signalData, assets);
|
||||||
const cruise = addVehicleCruises(viewer, routeData, signalData, trafficStart, config.vehicleModelNames, config.vehicleModelName);
|
hideUnconfirmedSignalAssets(assets);
|
||||||
|
const cruise = createLiveVehicleState();
|
||||||
const cameras = createCameraPresets(viewer, metadata, placement, cruise);
|
const cameras = createCameraPresets(viewer, metadata, placement, cruise);
|
||||||
|
const v2xOverlay = typeof window.createV2xCesiumOverlay === "function"
|
||||||
|
? window.createV2xCesiumOverlay({
|
||||||
|
viewer,
|
||||||
|
metadata,
|
||||||
|
placement,
|
||||||
|
config,
|
||||||
|
nativeSignals: (signalData && signalData.signals) || [],
|
||||||
|
setSignalState: (entries) => trafficSignals.update(entries),
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
buildAssetToggles(assets);
|
buildAssetToggles(assets);
|
||||||
buildSemanticToggles(viewer, assets, placement);
|
buildSemanticToggles(viewer, assets, placement);
|
||||||
bindRuntimeControls(viewer, assets, cruise, cameras, placement, trafficSignals);
|
bindRuntimeControls(viewer, assets, cruise, cameras, placement, trafficSignals);
|
||||||
bindVehicleInfoCard(viewer, cruise);
|
bindVehicleInfoCard(viewer, cruise);
|
||||||
startDiagnostics(viewer, metadata, assets, cruise, placement, trafficSignals);
|
startDiagnostics(viewer, metadata, assets, cruise, placement, trafficSignals, v2xOverlay);
|
||||||
cameras.overview();
|
cameras.overview();
|
||||||
baseStatus = summaryText(metadata, assets, cruise);
|
baseStatus = summaryText(metadata, assets, cruise);
|
||||||
setStatus(baseStatus);
|
setStatus(baseStatus);
|
||||||
@@ -72,7 +82,7 @@
|
|||||||
document.body.classList.add("scene-ready");
|
document.body.classList.add("scene-ready");
|
||||||
// Handle for the browser console and for headless checks: everything else
|
// Handle for the browser console and for headless checks: everything else
|
||||||
// in here is closed over by the IIFE and unreachable from outside.
|
// in here is closed over by the IIFE and unreachable from outside.
|
||||||
window.osmPreview = { viewer, metadata, placement, assets, cruise, trafficSignals, cameras };
|
window.osmPreview = { viewer, metadata, placement, assets, cruise, trafficSignals, cameras, v2xOverlay };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchJson(url) {
|
async function fetchJson(url) {
|
||||||
@@ -587,6 +597,7 @@
|
|||||||
baseSpeed: speed,
|
baseSpeed: speed,
|
||||||
state: { selectedIndex: 0 },
|
state: { selectedIndex: 0 },
|
||||||
simulation,
|
simulation,
|
||||||
|
usingLiveData: false,
|
||||||
};
|
};
|
||||||
syncSelectedRouteVisibility(cruise);
|
syncSelectedRouteVisibility(cruise);
|
||||||
return cruise;
|
return cruise;
|
||||||
@@ -594,10 +605,92 @@
|
|||||||
|
|
||||||
function syncSelectedRouteVisibility(cruise) {
|
function syncSelectedRouteVisibility(cruise) {
|
||||||
for (let index = 0; index < cruise.vehicles.length; index += 1) {
|
for (let index = 0; index < cruise.vehicles.length; index += 1) {
|
||||||
cruise.vehicles[index].routeEntity.show = toggleRoutes.checked && index === cruise.state.selectedIndex;
|
cruise.vehicles[index].routeEntity.show = !cruise.usingLiveData && toggleRoutes.checked && index === cruise.state.selectedIndex;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createLiveVehicleState() {
|
||||||
|
return {
|
||||||
|
vehicles: [],
|
||||||
|
baseSpeed: 0,
|
||||||
|
state: { selectedIndex: 0 },
|
||||||
|
simulation: null,
|
||||||
|
usingLiveData: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideUnconfirmedSignalAssets(assets) {
|
||||||
|
assets.filter((asset) => asset.category === "dynamic" || asset.category === "countdown")
|
||||||
|
.forEach((asset) => { if (asset.model) asset.model.show = false; });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Driven entirely by live V2X lamp state. The overlay has already resolved
|
||||||
|
// phaseNo -> native node keys and normalized the lamp status, so this only
|
||||||
|
// paints; it never re-interprets status codes.
|
||||||
|
function createLiveTrafficSignals(signalData, assets) {
|
||||||
|
const dynamic = assets.find((asset) => asset.category === "dynamic" && asset.model);
|
||||||
|
const countdownModels = new Map(assets
|
||||||
|
.filter((asset) => asset.category === "countdown" && asset.model)
|
||||||
|
.map((asset) => [Number(asset.phaseGroup), asset.model]));
|
||||||
|
const signals = (signalData?.signals || []).filter((signal) => signal && signal.id);
|
||||||
|
const phaseGroupByNodeKey = new Map(signals.map((signal) => [String(signal.nodeKey || signal.id), Number(signal.phaseGroup)]));
|
||||||
|
const state = { live: false };
|
||||||
|
|
||||||
|
function paintLamp(nodeKey, color) {
|
||||||
|
let changed = false;
|
||||||
|
["red", "yellow", "green"].forEach((lamp) => {
|
||||||
|
let node = null;
|
||||||
|
try { node = dynamic.model.getNode(`TrafficSignalDynamic_${nodeKey}_${lamp}`); } catch (_) { return; }
|
||||||
|
if (node && node.show !== (lamp === color)) { node.show = lamp === color; changed = true; }
|
||||||
|
});
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
function paintCountdown(nodeKey, countDown, color) {
|
||||||
|
const model = countdownModels.get(phaseGroupByNodeKey.get(String(nodeKey)));
|
||||||
|
if (!model) return false;
|
||||||
|
// Only two digits are modelled; anything outside 00-19 shows nothing.
|
||||||
|
const visible = Number.isFinite(countDown) && countDown >= 0 && countDown < 20
|
||||||
|
? String(countDown).padStart(2, "0")
|
||||||
|
: null;
|
||||||
|
let changed = false;
|
||||||
|
for (let value = 0; value < 20; value += 1) {
|
||||||
|
const label = String(value).padStart(2, "0");
|
||||||
|
let node = null;
|
||||||
|
try { node = model.getNode(`TrafficSignalDynamic_${nodeKey}_countdown_${label}`); } catch (_) { continue; }
|
||||||
|
if (node && node.show !== (label === visible)) { node.show = label === visible; changed = true; }
|
||||||
|
}
|
||||||
|
if (visible !== null && typeof signalBaseColor === "function") {
|
||||||
|
model.color = signalBaseColor(color);
|
||||||
|
model.colorBlendMode = Cesium.ColorBlendMode.REPLACE;
|
||||||
|
model.colorBlendAmount = 1.0;
|
||||||
|
}
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
function update(entries) {
|
||||||
|
if (!dynamic?.model) return;
|
||||||
|
const list = Array.isArray(entries) ? entries : [];
|
||||||
|
let changed = false;
|
||||||
|
let painted = 0;
|
||||||
|
list.forEach((entry) => {
|
||||||
|
const nodeKeys = Array.isArray(entry?.nodeKeys) ? entry.nodeKeys : [];
|
||||||
|
nodeKeys.forEach((nodeKey) => {
|
||||||
|
painted += 1;
|
||||||
|
if (paintLamp(nodeKey, entry.color)) changed = true;
|
||||||
|
if (paintCountdown(nodeKey, entry.countDown, entry.color)) changed = true;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// Only show the dynamic assembly once a lamp actually resolved to a head.
|
||||||
|
state.live = painted > 0;
|
||||||
|
dynamic.model.show = state.live;
|
||||||
|
countdownModels.forEach((model) => { model.show = state.live; });
|
||||||
|
if (changed) dynamic.model.scene?.requestRender?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
const dynamic = assets.find((asset) => asset.category === "dynamic" && asset.model);
|
const dynamic = assets.find((asset) => asset.category === "dynamic" && asset.model);
|
||||||
const countdownModels = new Map(assets
|
const countdownModels = new Map(assets
|
||||||
@@ -1321,7 +1414,7 @@
|
|||||||
|
|
||||||
// Camera-dependent readouts have to track the camera, so refresh off the
|
// Camera-dependent readouts have to track the camera, so refresh off the
|
||||||
// render loop rather than a fixed timer, throttled to stay off the hot path.
|
// render loop rather than a fixed timer, throttled to stay off the hot path.
|
||||||
function startDiagnostics(viewer, metadata, assets, cruise, placement, trafficSignals) {
|
function startDiagnostics(viewer, metadata, assets, cruise, placement, trafficSignals, v2xOverlay) {
|
||||||
const center = placement.position;
|
const center = placement.position;
|
||||||
const stats = metadata.scene_stats || {};
|
const stats = metadata.scene_stats || {};
|
||||||
const failed = assets.filter((asset) => asset.error);
|
const failed = assets.filter((asset) => asset.error);
|
||||||
@@ -1342,11 +1435,12 @@
|
|||||||
"Trees: " + Number(stats.trees || 0),
|
"Trees: " + Number(stats.trees || 0),
|
||||||
"Road layer source: " + (metadata.source_geojson ? "osm2streets" : "OSM fallback")
|
"Road layer source: " + (metadata.source_geojson ? "osm2streets" : "OSM fallback")
|
||||||
];
|
];
|
||||||
if (cruise.simulation) {
|
if (v2xOverlay?.state) {
|
||||||
const simulation = cruise.simulation.diagnostics();
|
lines.push("Vehicle data: " + (v2xOverlay.state.vehicleSource === "live" ? "live V2X" : "waiting for live V2X"));
|
||||||
lines.push("Simulation: native-preview-traffic-simulation/v1");
|
lines.push("Live vehicles: " + (v2xOverlay.state?.registry?.visibleSize ?? 0));
|
||||||
lines.push("Stopped: " + simulation.stoppedVehicles);
|
lines.push("Target WS: " + (v2xOverlay.state?.targetMessages ?? 0) + " messages / " + (v2xOverlay.state?.targetLastCount ?? 0) + " parsed");
|
||||||
lines.push("Queue: " + simulation.queueLength);
|
lines.push("Target payload: " + (v2xOverlay.state?.targetPayloadShape || "waiting"));
|
||||||
|
if (v2xOverlay.state?.targetLastError) lines.push("Target error: " + v2xOverlay.state.targetLastError);
|
||||||
}
|
}
|
||||||
if (failed.length) {
|
if (failed.length) {
|
||||||
lines.push("Failed assets: " + failed.map((asset) => asset.url).join(", "));
|
lines.push("Failed assets: " + failed.map((asset) => asset.url).join(", "));
|
||||||
@@ -1368,7 +1462,7 @@
|
|||||||
return [
|
return [
|
||||||
config.areaId,
|
config.areaId,
|
||||||
liveAssets(assets).map((asset) => asset.url).join(", "),
|
liveAssets(assets).map((asset) => asset.url).join(", "),
|
||||||
cruise.vehicles.length ? "vehicles " + cruise.vehicles.length : "no drivable route",
|
"live V2X vehicles only",
|
||||||
"buildings " + Number(stats.buildings || 0),
|
"buildings " + Number(stats.buildings || 0),
|
||||||
"trees " + Number(stats.trees || 0)
|
"trees " + Number(stats.trees || 0)
|
||||||
].filter(Boolean).join(" | ");
|
].filter(Boolean).join(" | ");
|
||||||
@@ -1405,8 +1499,9 @@
|
|||||||
|
|
||||||
main().catch((error) => {
|
main().catch((error) => {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
setStatus("Failed to load Cesium preview: " + error.message);
|
const detail = error && error.message ? error.message : String(error);
|
||||||
|
setStatus("Failed to load Cesium preview: " + detail);
|
||||||
document.body.classList.add("scene-error");
|
document.body.classList.add("scene-error");
|
||||||
setLoadingMessage("Failed to load scene", error.message);
|
setLoadingMessage("Failed to load scene", detail + " (see Safari Develop > Show JavaScript Console)");
|
||||||
});
|
});
|
||||||
}());
|
}());
|
||||||
@@ -0,0 +1,474 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const { convertGeoJson, boundsOf } = require("./gaode-junction-reference");
|
||||||
|
const metricsCache = new WeakMap();
|
||||||
|
const CORNER_FILLET_SEGMENTS = 12;
|
||||||
|
// Must match DEFAULT_SIDEWALK_WIDTH_METERS in native-road.js so the corner band
|
||||||
|
// lines up with the straight strips it joins.
|
||||||
|
const SIDEWALK_WIDTH_METERS = 2;
|
||||||
|
// The straight strips are trimmed against the cluster boundary using the road
|
||||||
|
// centerline, so they stop a little beyond the carriageway end. Run the corner
|
||||||
|
// past that end and let the two overlap rather than chase an exact seam.
|
||||||
|
const SIDEWALK_CORNER_OVERRUN_METERS = 6;
|
||||||
|
|
||||||
|
function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||||
|
const nodeIds = new Set(cluster.nodeIds.map(String));
|
||||||
|
const nodes = cluster.nodeIds.map((id) => helpers.junctionPlans.get(String(id))?.node).filter(Boolean);
|
||||||
|
if (nodes.length < 2) return { features: [], diagnostics: [helpers.diagnostic("warning", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-insufficient-nodes", "复合路口至少需要两个有效节点。", null)] };
|
||||||
|
const center = nodes.reduce((sum, point) => [sum[0] + point[0] / nodes.length, sum[1] + point[1] / nodes.length], [0, 0]);
|
||||||
|
const approaches = [];
|
||||||
|
const carriageways = [];
|
||||||
|
for (const [nodeId, plan] of helpers.junctionPlans) {
|
||||||
|
if (!nodeIds.has(String(nodeId))) continue;
|
||||||
|
for (const approach of plan.approaches) {
|
||||||
|
const endpoint = approach.line.at(-1);
|
||||||
|
if (nodes.some((node) => node !== plan.node && helpers.distanceMeters(endpoint, node) < 4)) continue;
|
||||||
|
const heading = helpers.headingAtEndpoint(approach.line);
|
||||||
|
const length = helpers.lineLengthMeters(approach.line);
|
||||||
|
carriageways.push({ nodeId, approach, plan, heading, length });
|
||||||
|
if (approaches.some((item) => Math.abs(normalizeHeading(item.heading - heading)) < 20)) continue;
|
||||||
|
approaches.push({ nodeId, approach, plan, heading, length });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (approaches.length < 3) return { features: [], diagnostics: [helpers.diagnostic("warning", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-insufficient-approaches", "复合路口无法识别足够的外部进口。", center)] };
|
||||||
|
const { calibration, coreRadius } = complexJunctionMetrics(cluster);
|
||||||
|
const sorted = [...approaches].sort((a, b) => a.heading - b.heading);
|
||||||
|
const arms = sorted.map((representative) => ({
|
||||||
|
representative,
|
||||||
|
heading: averageHeading(carriageways.filter((candidate) => Math.abs(normalizeHeading(candidate.heading - representative.heading)) < 20).map((candidate) => candidate.heading)),
|
||||||
|
members: carriageways.filter((candidate) => Math.abs(normalizeHeading(candidate.heading - representative.heading)) < 20),
|
||||||
|
}));
|
||||||
|
const outerRadius = complexJunctionMetrics(cluster).approachOuterRadius;
|
||||||
|
const boundaryParts = [];
|
||||||
|
const crosswalks = [];
|
||||||
|
const stopLines = [];
|
||||||
|
const islands = [];
|
||||||
|
const armCrosswalkRadius = coreRadius * .68;
|
||||||
|
for (const item of carriageways) {
|
||||||
|
const outer = pointOnCarriagewayRadius(item, center, outerRadius, helpers);
|
||||||
|
const inner = pointOnCarriagewayRadius(item, center, coreRadius * .7, helpers);
|
||||||
|
const outerHalf = item.approach.widthMeters / 2;
|
||||||
|
const innerHalf = outerHalf;
|
||||||
|
boundaryParts.push({ item, outer, inner, outerHalf, innerHalf });
|
||||||
|
const incomingRoad = item.approach.roadIds.map((roadId) => model.roads.find((road) => road.id === roadId)).find((road) => String(road?.sourceNodeIds.at(-1)) === String(item.nodeId));
|
||||||
|
if (incomingRoad) {
|
||||||
|
// Keep the stop bar just outside the road crosswalk. The previous fixed
|
||||||
|
// core-radius offset placed it nearly ten metres beyond the crossing.
|
||||||
|
const stopCenter = pointOnCarriagewayRadius(item, center, armCrosswalkRadius + 3, helpers);
|
||||||
|
const ring = [
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, -outerHalf), item.heading, -.24),
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, outerHalf), item.heading, -.24),
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, outerHalf), item.heading, .24),
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, -outerHalf), item.heading, .24),
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, item.heading + 90, -outerHalf), item.heading, -.24),
|
||||||
|
];
|
||||||
|
stopLines.push({ type: "Feature", properties: { native_id: `complex-stop-line:${cluster.id}:${item.approach.segmentId}`, cluster_id: cluster.id, kind: "complex-stop-line", road_id: incomingRoad.id, node_id: item.nodeId, direction: item.heading, provenance: "native-road-complex-junction-stop-line/v1" }, geometry: { type: "Polygon", coordinates: [ring] } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The four support lines provide a common corner frame, but each long
|
||||||
|
// crossing remains clipped to its OSM-derived road envelope. Corner islands
|
||||||
|
// fill the remaining frame gaps; crossings must never do that job.
|
||||||
|
for (const arm of arms) {
|
||||||
|
const envelope = armEnvelopeAtRadius(arm, armCrosswalkRadius, center, helpers);
|
||||||
|
if (!envelope) continue;
|
||||||
|
arm.crosswalkFrame = {
|
||||||
|
center: envelope.center,
|
||||||
|
groupDepth: 3.4,
|
||||||
|
supportHeading: normalizeHeading(arm.heading + 90),
|
||||||
|
envelopeWidthMeters: envelope.widthMeters,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const frameCorners = arms.map((arm, index) => {
|
||||||
|
const next = arms[(index + 1) % arms.length];
|
||||||
|
const delta = positiveHeadingDelta(arm.heading, next.heading);
|
||||||
|
if (delta < 45 || delta > 135 || !arm.crosswalkFrame || !next.crosswalkFrame) return null;
|
||||||
|
return supportLineIntersection(arm.crosswalkFrame, next.crosswalkFrame, center);
|
||||||
|
});
|
||||||
|
for (let index = 0; index < arms.length; index += 1) {
|
||||||
|
const arm = arms[index];
|
||||||
|
if (!arm.crosswalkFrame) continue;
|
||||||
|
const item = arm.representative;
|
||||||
|
const roadEdgeInset = .35;
|
||||||
|
const usableSpan = Math.max(.42, arm.crosswalkFrame.envelopeWidthMeters - roadEdgeInset * 2);
|
||||||
|
const endpoints = [
|
||||||
|
helpers.offsetCoordinate(arm.crosswalkFrame.center, arm.heading + 90, -usableSpan / 2),
|
||||||
|
helpers.offsetCoordinate(arm.crosswalkFrame.center, arm.heading + 90, usableSpan / 2),
|
||||||
|
];
|
||||||
|
const groupDepth = arm.crosswalkFrame.groupDepth;
|
||||||
|
const stripeWidth = .42;
|
||||||
|
const stripeCount = Math.max(6, Math.floor((usableSpan - stripeWidth) / .82) + 1);
|
||||||
|
const stripeSpacing = stripeCount > 1 ? (usableSpan - stripeWidth) / (stripeCount - 1) : 0;
|
||||||
|
arm.crosswalkFrame.center = midpoint(...endpoints);
|
||||||
|
arm.crosswalkFrame.endpoints = endpoints;
|
||||||
|
arm.crosswalkFrame.spanMeters = usableSpan;
|
||||||
|
arm.crosswalkFrame.roadEdgeInsetMeters = roadEdgeInset;
|
||||||
|
for (let stripe = 0; stripe < stripeCount; stripe += 1) {
|
||||||
|
const along = stripeWidth / 2 + stripe * stripeSpacing;
|
||||||
|
const centerPoint = helpers.offsetCoordinate(endpoints[0], bearing(...endpoints), along);
|
||||||
|
const ring = [
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, -groupDepth / 2), arm.heading + 90, -stripeWidth / 2),
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, groupDepth / 2), arm.heading + 90, -stripeWidth / 2),
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, groupDepth / 2), arm.heading + 90, stripeWidth / 2),
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, -groupDepth / 2), arm.heading + 90, stripeWidth / 2),
|
||||||
|
helpers.offsetCoordinate(helpers.offsetCoordinate(centerPoint, arm.heading, -groupDepth / 2), arm.heading + 90, -stripeWidth / 2),
|
||||||
|
];
|
||||||
|
crosswalks.push({ type: "Feature", properties: { native_id: `complex-crosswalk:${cluster.id}:${item.nodeId}:${item.approach.segmentId}:${stripe + 1}`, cluster_id: cluster.id, kind: "complex-crosswalk", crossing_node_id: item.nodeId, road_id: item.approach.roadIds[0], direction: arm.heading, radial_distance_m: armCrosswalkRadius, span_m: usableSpan, road_envelope_span_m: arm.crosswalkFrame.envelopeWidthMeters, road_edge_inset_m: roadEdgeInset, group_depth_m: groupDepth, stripe_width_m: stripeWidth, stripe_spacing_m: stripeSpacing, frame_center: arm.crosswalkFrame.center, frame_support_heading: arm.crosswalkFrame.supportHeading, provenance: "native-road-complex-junction-crosswalk/v6-road-clipped" }, geometry: { type: "Polygon", coordinates: [ring] } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The four arm groups are the sides of one pedestrian frame. Each diagonal
|
||||||
|
// group is anchored at the intersection of its adjacent side support lines,
|
||||||
|
// so all eight groups stay one composition when the OSM arms are skewed.
|
||||||
|
for (let index = 0; index < arms.length; index += 1) {
|
||||||
|
const first = arms[index];
|
||||||
|
const second = arms[(index + 1) % arms.length];
|
||||||
|
const delta = positiveHeadingDelta(first.heading, second.heading);
|
||||||
|
if (delta < 45 || delta > 135) continue;
|
||||||
|
if (!first.crosswalkFrame || !second.crosswalkFrame) continue;
|
||||||
|
const bisector = normalizeHeading(first.heading + delta / 2);
|
||||||
|
const frameCorner = frameCorners[index];
|
||||||
|
if (!frameCorner) continue;
|
||||||
|
const cornerStripeSpacing = .62;
|
||||||
|
const cornerStripeWidth = .4;
|
||||||
|
const cornerGroupHalfDepth = (5 * cornerStripeSpacing + cornerStripeWidth) / 2;
|
||||||
|
const endpointForCorner = (arm) => [...arm.crosswalkFrame.endpoints].sort((a, b) => helpers.distanceMeters(a, frameCorner) - helpers.distanceMeters(b, frameCorner))[0];
|
||||||
|
const outerEdgeAtCorner = (arm) => {
|
||||||
|
const endpoint = endpointForCorner(arm);
|
||||||
|
return [arm.heading, arm.heading + 180]
|
||||||
|
.map((heading) => helpers.offsetCoordinate(endpoint, heading, arm.crosswalkFrame.groupDepth / 2))
|
||||||
|
.sort((a, b) => directionalProjectionMeters(center, b, bisector) - directionalProjectionMeters(center, a, bisector))[0];
|
||||||
|
};
|
||||||
|
const islandBaseGap = .05;
|
||||||
|
const islandApexOffset = 1.5;
|
||||||
|
const islandBase = [outerEdgeAtCorner(first), outerEdgeAtCorner(second)].map((point) => helpers.offsetCoordinate(point, bisector, islandBaseGap));
|
||||||
|
const islandApex = helpers.offsetCoordinate(frameCorner, bisector, islandApexOffset);
|
||||||
|
const islandCrossingClearance = .2;
|
||||||
|
const cornerCrossingOffset = islandApexOffset + islandCrossingClearance + cornerGroupHalfDepth;
|
||||||
|
const islandInnerRadius = Math.min(...islandBase.map((point) => directionalProjectionMeters(center, point, bisector)));
|
||||||
|
const islandOuterRadius = directionalProjectionMeters(center, islandApex, bisector);
|
||||||
|
const cornerCrossingCenter = helpers.offsetCoordinate(frameCorner, bisector, cornerCrossingOffset);
|
||||||
|
const islandRing = roundedPolygonRing([islandBase[0], islandApex, islandBase[1]], .24);
|
||||||
|
islands.push({ type: "Feature", properties: { native_id: `complex-corner-island:${cluster.id}:${index + 1}`, cluster_id: cluster.id, kind: "complex-corner-island", corner_index: index + 1, from_heading: first.heading, to_heading: second.heading, frame_corner: frameCorner, base_points: islandBase, apex_point: islandApex, inner_radius_m: islandInnerRadius, outer_radius_m: islandOuterRadius, base_width_m: helpers.distanceMeters(...islandBase), crossing_clearance_m: islandCrossingClearance, corner_rounding_ratio: .24, provenance: "native-road-complex-junction-corner/v7-road-gap-fill" }, geometry: { type: "Polygon", coordinates: [islandRing] } });
|
||||||
|
|
||||||
|
let cornerCrossingHalfSpan = .4;
|
||||||
|
for (let stripe = 0; stripe < 6; stripe += 1) {
|
||||||
|
const stripeOffset = (stripe - 2.5) * cornerStripeSpacing;
|
||||||
|
const stripeCenter = helpers.offsetCoordinate(cornerCrossingCenter, bisector, stripeOffset);
|
||||||
|
const stripeRadius = directionalProjectionMeters(center, stripeCenter, bisector);
|
||||||
|
const curbPair = limitedCornerPair(first, second, stripeRadius, bisector, center, 6.5, helpers);
|
||||||
|
if (!curbPair) continue;
|
||||||
|
const halfSpan = Math.max(.4, Math.min(6.5, helpers.distanceMeters(...curbPair)) / 2);
|
||||||
|
cornerCrossingHalfSpan = Math.max(cornerCrossingHalfSpan, halfSpan);
|
||||||
|
const stripePair = [
|
||||||
|
helpers.offsetCoordinate(stripeCenter, bisector - 90, halfSpan),
|
||||||
|
helpers.offsetCoordinate(stripeCenter, bisector + 90, halfSpan),
|
||||||
|
];
|
||||||
|
const ring = [
|
||||||
|
helpers.offsetCoordinate(stripePair[0], bisector, -cornerStripeWidth / 2),
|
||||||
|
helpers.offsetCoordinate(stripePair[1], bisector, -cornerStripeWidth / 2),
|
||||||
|
helpers.offsetCoordinate(stripePair[1], bisector, cornerStripeWidth / 2),
|
||||||
|
helpers.offsetCoordinate(stripePair[0], bisector, cornerStripeWidth / 2),
|
||||||
|
helpers.offsetCoordinate(stripePair[0], bisector, -cornerStripeWidth / 2),
|
||||||
|
];
|
||||||
|
crosswalks.push({ type: "Feature", properties: { native_id: `complex-corner-crosswalk:${cluster.id}:${index + 1}:${stripe + 1}`, cluster_id: cluster.id, kind: "complex-corner-crosswalk", corner_index: index + 1, direction: bisector, radial_distance_m: stripeRadius, frame_corner: frameCorner, from_heading: first.heading, to_heading: second.heading, provenance: "native-road-complex-junction-corner-crosswalk/v3" }, geometry: { type: "Polygon", coordinates: [ring] } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Each carriageway ends in its own rectangle, so adjacent arms meet at a
|
||||||
|
// sharp notch instead of a curb. A real corner is one tangent-continuous
|
||||||
|
// sweep between the two outermost road edges, so fit a fixed-radius fillet
|
||||||
|
// into the wedge those edges form and fill the sector behind it.
|
||||||
|
const cornerFills = [];
|
||||||
|
const sidewalkCorners = [];
|
||||||
|
const cornerDiagnostics = [];
|
||||||
|
const cornerRadius = Math.max(4, Math.min(25, Number(cluster.cornerRadiusMeters) || 12));
|
||||||
|
for (let index = 0; index < arms.length; index += 1) {
|
||||||
|
const first = arms[index];
|
||||||
|
const second = arms[(index + 1) % arms.length];
|
||||||
|
const delta = positiveHeadingDelta(first.heading, second.heading);
|
||||||
|
if (delta < 45 || delta > 135) continue;
|
||||||
|
const bisector = normalizeHeading(first.heading + delta / 2);
|
||||||
|
const edges = [first, second].map((arm) => cornerEdgeAt(arm, coreRadius + 6, bisector, center, helpers));
|
||||||
|
if (!edges.every(Boolean)) continue;
|
||||||
|
const apex = rayIntersection(edges[0], edges[1], center);
|
||||||
|
const apexReach = apex ? directionalProjectionMeters(center, apex, bisector) : null;
|
||||||
|
// The wedge apex has to sit ahead of the core and inside the arm handoff;
|
||||||
|
// outside that band the two edges are near parallel and any fillet fitted
|
||||||
|
// to them would sweep across the carriageways instead of the corner.
|
||||||
|
if (apexReach === null || apexReach < 1 || apexReach > outerRadius) {
|
||||||
|
cornerDiagnostics.push(helpers.diagnostic("warning", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-corner-fillet-fallback", "该夹角的道路边缘切线无法安全构造圆角,已保留直角过渡。", center));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Tangent distance for a circle of `cornerRadius` inscribed in a wedge of
|
||||||
|
// opening `delta`, clamped so the tangent points stay on the built arms.
|
||||||
|
const tangentDistance = Math.min(cornerRadius / Math.tan(delta * Math.PI / 360), Math.max(2, outerRadius - apexReach));
|
||||||
|
const tangents = edges.map((edge) => helpers.offsetCoordinate(apex, edge.heading, tangentDistance));
|
||||||
|
const curve = quadraticCurve(tangents[0], apex, tangents[1], CORNER_FILLET_SEGMENTS);
|
||||||
|
const ring = [...curve, center, curve[0]];
|
||||||
|
if (!ring.every((point) => point.every(Number.isFinite))) continue;
|
||||||
|
cornerFills.push({ type: "Feature", properties: { native_id: `complex-corner-fillet:${cluster.id}:${index + 1}`, cluster_id: cluster.id, kind: "complex-corner-fillet", complex_part: "corner-fillet", corner_index: index + 1, from_heading: first.heading, to_heading: second.heading, bisector_heading: bisector, corner_radius_m: cornerRadius, tangent_distance_m: Math.round(tangentDistance * 100) / 100, apex_reach_m: Math.round(apexReach * 100) / 100, provenance: "native-road-complex-junction-corner-fillet/v1" }, geometry: { type: "Polygon", coordinates: [ring] } });
|
||||||
|
|
||||||
|
// The straight pedestrian strips are trimmed at the cluster boundary, so
|
||||||
|
// two arms that both carry a footway still meet as two loose ends across
|
||||||
|
// an empty wedge. Bridge them along the curb the fillet already defines.
|
||||||
|
// The corner faces clockwise from `first` and counter-clockwise from
|
||||||
|
// `second`, so each arm must carry the footway on that facing side.
|
||||||
|
if (!armCarriesSidewalk(first, model, true) || !armCarriesSidewalk(second, model, false)) continue;
|
||||||
|
const curb = [
|
||||||
|
...edgeRunToRadius(apex, edges[0], tangentDistance, outerRadius + SIDEWALK_CORNER_OVERRUN_METERS, center, helpers).reverse(),
|
||||||
|
...curve.slice(1, -1),
|
||||||
|
...edgeRunToRadius(apex, edges[1], tangentDistance, outerRadius + SIDEWALK_CORNER_OVERRUN_METERS, center, helpers),
|
||||||
|
];
|
||||||
|
const outerEdge = offsetPolylineAwayFromCenter(curb, center, SIDEWALK_WIDTH_METERS, helpers);
|
||||||
|
const sidewalkRing = [...curb, ...outerEdge.slice().reverse(), curb[0]];
|
||||||
|
if (!sidewalkRing.every((point) => point.every(Number.isFinite)) || ringSelfIntersects(sidewalkRing)) {
|
||||||
|
cornerDiagnostics.push(helpers.diagnostic("warning", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-sidewalk-corner-fallback", "该夹角的人行道转角几何自交或无效,已跳过,两侧步行带保持断开。", center));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sidewalkCorners.push({ type: "Feature", properties: { native_id: `complex-sidewalk-corner:${cluster.id}:${index + 1}`, cluster_id: cluster.id, kind: "complex-sidewalk-corner", corner_index: index + 1, from_heading: first.heading, to_heading: second.heading, bisector_heading: bisector, width_m: SIDEWALK_WIDTH_METERS, overrun_m: SIDEWALK_CORNER_OVERRUN_METERS, provenance: "native-road-complex-junction-sidewalk-corner/v1" }, geometry: { type: "Polygon", coordinates: [sidewalkRing] } });
|
||||||
|
}
|
||||||
|
const corePoints = boundaryParts.flatMap(({ item, inner, innerHalf }) => [helpers.offsetCoordinate(inner, item.heading + 90, innerHalf), helpers.offsetCoordinate(inner, item.heading - 90, innerHalf)]).sort((first, second) => angleAround(center, first) - angleAround(center, second));
|
||||||
|
const coreRing = roundedPolygonRing(corePoints, .16);
|
||||||
|
const features = [{ type: "Feature", properties: { native_id: `complex-junction:${cluster.id}:core`, cluster_id: cluster.id, kind: "complex-core", complex_part: "core", center, radius_m: coreRadius, configured_radius_m: cluster.coreRadiusMeters, approach_count: approaches.length, carriageway_count: carriageways.length, approach_headings: sorted.map((item) => Math.round(item.heading * 10) / 10), corner_rounding_ratio: .16, provenance: "native-road-complex-junction/v6-rounded-core" }, geometry: { type: "Polygon", coordinates: [coreRing] } }];
|
||||||
|
for (const { item, outer, inner, outerHalf, innerHalf } of boundaryParts) {
|
||||||
|
const ring = [helpers.offsetCoordinate(outer, item.heading + 90, outerHalf), helpers.offsetCoordinate(inner, item.heading + 90, innerHalf), helpers.offsetCoordinate(inner, item.heading - 90, innerHalf), helpers.offsetCoordinate(outer, item.heading - 90, outerHalf), helpers.offsetCoordinate(outer, item.heading + 90, outerHalf)];
|
||||||
|
features.push({ type: "Feature", properties: { native_id: `complex-junction:${cluster.id}:carriageway:${item.approach.segmentId}`, cluster_id: cluster.id, kind: "complex-approach", complex_part: "carriageway", heading_deg: item.heading, lane_count: item.approach.roadIds.reduce((sum, roadId) => sum + (model.roads.find((road) => road.id === roadId)?.laneCount || 0), 0), width_m: item.approach.widthMeters, provenance: "native-road-complex-junction/v5" }, geometry: { type: "Polygon", coordinates: [ring] } });
|
||||||
|
}
|
||||||
|
// Corner fills come last so they overlay the rectangular carriageway ends
|
||||||
|
// they are smoothing; they never replace an OSM-derived road surface.
|
||||||
|
features.push(...cornerFills);
|
||||||
|
// `coreRadiusMeters` is only consulted when there is no reference geometry.
|
||||||
|
// Under calibration the radius comes from the reference span, so a configured
|
||||||
|
// value that silently does nothing has to be reported, not swallowed.
|
||||||
|
const configuredRadiusIgnored = calibration && Number.isFinite(cluster.coreRadiusMeters) && Math.abs(coreRadius - cluster.coreRadiusMeters) > .5;
|
||||||
|
const configurationDiagnostics = configuredRadiusIgnored
|
||||||
|
? [helpers.diagnostic("info", `junction-cluster:${cluster.id}`, [...nodeIds], "complex-junction-configured-radius-ignored", `已按参考几何校准核心半径为 ${Math.round(coreRadius * 10) / 10} 米,配置的 coreRadiusMeters=${cluster.coreRadiusMeters} 在有参考文件时不生效。`, center)]
|
||||||
|
: [];
|
||||||
|
return { features, islands: [...islands, ...sidewalkCorners], crosswalks, stopLines, center, approaches, diagnostics: [...cornerDiagnostics, ...configurationDiagnostics, helpers.diagnostic("info", `junction-cluster:${cluster.id}`, [...nodeIds], calibration ? "complex-junction-reference-calibrated" : "complex-junction-generated", calibration ? `已使用参考几何校准参数后,由 OSM/native 重新生成 ${approaches.length} 个进口、道路面、中央分隔带、斑马线和停止线。` : `已独立生成 ${approaches.length} 个进口、道路面、中央分隔带、斑马线和停止线。`, center)] };
|
||||||
|
}
|
||||||
|
|
||||||
|
function readReferenceCalibration(cluster) {
|
||||||
|
if (!cluster.referenceFile || !fs.existsSync(cluster.referenceFile)) return null;
|
||||||
|
try {
|
||||||
|
const converted = convertGeoJson(JSON.parse(fs.readFileSync(cluster.referenceFile, "utf8")));
|
||||||
|
const bounds = boundsOf({ features: converted.features.filter((feature) => [1, 2, 3, 4].includes(Number(feature.properties?.type))) });
|
||||||
|
const lonScale = 111320 * Math.cos(((bounds.minLat + bounds.maxLat) / 2) * Math.PI / 180);
|
||||||
|
return { longSpanMeters: (bounds.maxLon - bounds.minLon) * lonScale, shortSpanMeters: (bounds.maxLat - bounds.minLat) * 111320 };
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function complexJunctionMetrics(cluster) {
|
||||||
|
if (metricsCache.has(cluster)) return metricsCache.get(cluster);
|
||||||
|
const calibration = readReferenceCalibration(cluster);
|
||||||
|
// Without a reference geometry `coreRadiusMeters` is the only size input the
|
||||||
|
// template has, so honour it literally within the schema's own 12..80 range.
|
||||||
|
// It used to be scaled by .52 and clamped to 17, which silently capped every
|
||||||
|
// unreferenced junction at a core far smaller than its own approach envelope
|
||||||
|
// — a 24 m dual-carriageway arm was being fitted into a 16.6 m core no matter
|
||||||
|
// what the config asked for. The calibrated branch is unchanged.
|
||||||
|
const coreRadius = calibration
|
||||||
|
? Math.max(12, Math.min(24, calibration.shortSpanMeters * .14))
|
||||||
|
: Math.max(12, Math.min(80, Number(cluster.coreRadiusMeters) || 28));
|
||||||
|
const metrics = { calibration, coreRadius, approachOuterRadius: coreRadius + (Number(cluster.outerRadiusExtraMeters) || 18) };
|
||||||
|
metricsCache.set(cluster, metrics);
|
||||||
|
return metrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeHeading(value) { return ((value + 180) % 360 + 360) % 360 - 180; }
|
||||||
|
|
||||||
|
// `arm.heading` points outward from the junction, so the corner clockwise from
|
||||||
|
// it sits at heading+90 and the one counter-clockwise at heading-90. A road's
|
||||||
|
// own sidewalk flags are relative to its digitisation direction, so flip them
|
||||||
|
// whenever the arm runs against that direction.
|
||||||
|
function armCarriesSidewalk(arm, model, cornerIsClockwise) {
|
||||||
|
return arm.members.some((member) => member.approach.roadIds
|
||||||
|
.map((roadId) => model.roads.find((road) => road.id === roadId))
|
||||||
|
.filter(Boolean)
|
||||||
|
.some((road) => {
|
||||||
|
const outwardIsForward = String(road.sourceNodeIds[0]) === String(member.nodeId);
|
||||||
|
const onClockwiseSide = outwardIsForward ? road.sidewalkRight : road.sidewalkLeft;
|
||||||
|
const onCounterClockwiseSide = outwardIsForward ? road.sidewalkLeft : road.sidewalkRight;
|
||||||
|
return Boolean(cornerIsClockwise ? onClockwiseSide : onCounterClockwiseSide);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Walk outward along a wedge edge from its tangent point until the curb reaches
|
||||||
|
// `targetRadius`, so the corner band overlaps the straight strip it joins.
|
||||||
|
function edgeRunToRadius(apex, edge, tangentDistance, targetRadius, center, helpers) {
|
||||||
|
const points = [];
|
||||||
|
for (let extra = 0; extra <= 40; extra += 2) {
|
||||||
|
const point = helpers.offsetCoordinate(apex, edge.heading, tangentDistance + extra);
|
||||||
|
points.push(point);
|
||||||
|
if (helpers.distanceMeters(point, center) >= targetRadius) break;
|
||||||
|
}
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Offset each vertex along the polyline normal that increases distance from the
|
||||||
|
// junction centre. The curb is star-shaped around that centre, so "farther from
|
||||||
|
// the centre" is a reliable stand-in for "on the pedestrian side".
|
||||||
|
function offsetPolylineAwayFromCenter(points, center, meters, helpers) {
|
||||||
|
return points.map((point, index) => {
|
||||||
|
const previous = points[Math.max(0, index - 1)];
|
||||||
|
const next = points[Math.min(points.length - 1, index + 1)];
|
||||||
|
const tangent = previous === next ? 0 : bearing(previous, next);
|
||||||
|
return [tangent + 90, tangent - 90]
|
||||||
|
.map((heading) => helpers.offsetCoordinate(point, heading, meters))
|
||||||
|
.sort((first, second) => helpers.distanceMeters(second, center) - helpers.distanceMeters(first, center))[0];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function ringSelfIntersects(ring) {
|
||||||
|
const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
||||||
|
const straddles = (p1, p2, p3, p4) => {
|
||||||
|
const d1 = cross(p3, p4, p1); const d2 = cross(p3, p4, p2);
|
||||||
|
const d3 = cross(p1, p2, p3); const d4 = cross(p1, p2, p4);
|
||||||
|
return ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0));
|
||||||
|
};
|
||||||
|
for (let first = 0; first < ring.length - 1; first += 1) {
|
||||||
|
for (let second = first + 2; second < ring.length - 1; second += 1) {
|
||||||
|
if (first === 0 && second === ring.length - 2) continue;
|
||||||
|
if (straddles(ring[first], ring[first + 1], ring[second], ring[second + 1])) return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function angleAround(center, point) { return Math.atan2(point[1] - center[1], point[0] - center[0]); }
|
||||||
|
function signedLateralMeters(origin, point, heading) {
|
||||||
|
const east = (point[0] - origin[0]) * 111320 * Math.cos(origin[1] * Math.PI / 180);
|
||||||
|
const north = (point[1] - origin[1]) * 111320;
|
||||||
|
const radians = (heading + 90) * Math.PI / 180;
|
||||||
|
return east * Math.sin(radians) + north * Math.cos(radians);
|
||||||
|
}
|
||||||
|
function bearing(first, second) {
|
||||||
|
const east = (second[0] - first[0]) * Math.cos(first[1] * Math.PI / 180);
|
||||||
|
const north = second[1] - first[1];
|
||||||
|
return Math.atan2(east, north) * 180 / Math.PI;
|
||||||
|
}
|
||||||
|
function midpoint(first, second) { return [(first[0] + second[0]) / 2, (first[1] + second[1]) / 2]; }
|
||||||
|
function averageHeading(headings) {
|
||||||
|
const vector = headings.reduce((sum, heading) => {
|
||||||
|
const radians = heading * Math.PI / 180;
|
||||||
|
return [sum[0] + Math.sin(radians), sum[1] + Math.cos(radians)];
|
||||||
|
}, [0, 0]);
|
||||||
|
return Math.atan2(vector[0], vector[1]) * 180 / Math.PI;
|
||||||
|
}
|
||||||
|
function positiveHeadingDelta(first, second) { return ((second - first) % 360 + 360) % 360; }
|
||||||
|
function pointOnCarriagewayRadius(item, center, radius, helpers) {
|
||||||
|
const start = item.approach.line[0];
|
||||||
|
const startRadius = directionalProjectionMeters(center, start, item.heading);
|
||||||
|
return helpers.pointAlongLine(item.approach.line, Math.max(0, Math.min(item.length, radius - startRadius)));
|
||||||
|
}
|
||||||
|
function armEnvelopeAtRadius(arm, radius, center, helpers) {
|
||||||
|
if (!arm.members.length) return null;
|
||||||
|
const centers = arm.members.map((member) => pointOnCarriagewayRadius(member, center, radius, helpers));
|
||||||
|
const reference = centers[0];
|
||||||
|
let minimum = Infinity;
|
||||||
|
let maximum = -Infinity;
|
||||||
|
centers.forEach((point, index) => {
|
||||||
|
const lateral = signedLateralMeters(reference, point, arm.heading);
|
||||||
|
const halfWidth = arm.members[index].approach.widthMeters / 2;
|
||||||
|
minimum = Math.min(minimum, lateral - halfWidth);
|
||||||
|
maximum = Math.max(maximum, lateral + halfWidth);
|
||||||
|
});
|
||||||
|
if (!Number.isFinite(minimum) || maximum - minimum < 1) return null;
|
||||||
|
return { center: helpers.offsetCoordinate(reference, arm.heading + 90, (minimum + maximum) / 2), widthMeters: maximum - minimum };
|
||||||
|
}
|
||||||
|
function supportLineIntersection(first, second, origin) {
|
||||||
|
const lonScale = 111320 * Math.cos(origin[1] * Math.PI / 180);
|
||||||
|
const toLocal = (point) => [(point[0] - origin[0]) * lonScale, (point[1] - origin[1]) * 111320];
|
||||||
|
const firstPoint = toLocal(first.center);
|
||||||
|
const secondPoint = toLocal(second.center);
|
||||||
|
const direction = (heading) => {
|
||||||
|
const radians = heading * Math.PI / 180;
|
||||||
|
return [Math.sin(radians), Math.cos(radians)];
|
||||||
|
};
|
||||||
|
const firstDirection = direction(first.supportHeading);
|
||||||
|
const secondDirection = direction(second.supportHeading);
|
||||||
|
const denominator = firstDirection[0] * secondDirection[1] - firstDirection[1] * secondDirection[0];
|
||||||
|
if (Math.abs(denominator) < 1e-6) return null;
|
||||||
|
const delta = [secondPoint[0] - firstPoint[0], secondPoint[1] - firstPoint[1]];
|
||||||
|
const distanceAlongFirst = (delta[0] * secondDirection[1] - delta[1] * secondDirection[0]) / denominator;
|
||||||
|
const intersection = [firstPoint[0] + firstDirection[0] * distanceAlongFirst, firstPoint[1] + firstDirection[1] * distanceAlongFirst];
|
||||||
|
return [origin[0] + intersection[0] / lonScale, origin[1] + intersection[1] / 111320];
|
||||||
|
}
|
||||||
|
function limitedCornerPair(first, second, radius, bisector, center, maxWidth, helpers) {
|
||||||
|
const pair = [cornerEdgeAtRadius(first, radius, bisector, center, helpers), cornerEdgeAtRadius(second, radius, bisector, center, helpers)];
|
||||||
|
if (!pair.every(Boolean)) return null;
|
||||||
|
const width = helpers.distanceMeters(pair[0], pair[1]);
|
||||||
|
const middle = midpoint(pair[0], pair[1]);
|
||||||
|
const halfWidth = Math.max(.4, Math.min(width, maxWidth) / 2);
|
||||||
|
const acrossHeading = width > .1 ? bearing(pair[0], pair[1]) : bisector + 90;
|
||||||
|
return [helpers.offsetCoordinate(middle, acrossHeading + 180, halfWidth), helpers.offsetCoordinate(middle, acrossHeading, halfWidth)];
|
||||||
|
}
|
||||||
|
function cornerEdgeAtRadius(arm, radius, bisector, center, helpers) {
|
||||||
|
return cornerEdgeAt(arm, radius, bisector, center, helpers)?.point || null;
|
||||||
|
}
|
||||||
|
function cornerEdgeAt(arm, radius, bisector, center, helpers) {
|
||||||
|
const candidates = arm.members.flatMap((member) => {
|
||||||
|
const point = pointOnCarriagewayRadius(member, center, radius, helpers);
|
||||||
|
const halfWidth = member.approach.widthMeters / 2;
|
||||||
|
return [90, -90].map((side) => ({ point: helpers.offsetCoordinate(point, member.heading + side, halfWidth), heading: member.heading }));
|
||||||
|
});
|
||||||
|
return candidates.sort((first, second) => directionalProjectionMeters(center, second.point, bisector) - directionalProjectionMeters(center, first.point, bisector))[0] || null;
|
||||||
|
}
|
||||||
|
function rayIntersection(first, second, origin) {
|
||||||
|
const lonScale = 111320 * Math.cos(origin[1] * Math.PI / 180);
|
||||||
|
const toLocal = (point) => [(point[0] - origin[0]) * lonScale, (point[1] - origin[1]) * 111320];
|
||||||
|
const direction = (heading) => {
|
||||||
|
const radians = heading * Math.PI / 180;
|
||||||
|
return [Math.sin(radians), Math.cos(radians)];
|
||||||
|
};
|
||||||
|
const firstPoint = toLocal(first.point);
|
||||||
|
const secondPoint = toLocal(second.point);
|
||||||
|
const firstDirection = direction(first.heading);
|
||||||
|
const secondDirection = direction(second.heading);
|
||||||
|
const denominator = firstDirection[0] * secondDirection[1] - firstDirection[1] * secondDirection[0];
|
||||||
|
if (Math.abs(denominator) < 1e-4) return null;
|
||||||
|
const delta = [secondPoint[0] - firstPoint[0], secondPoint[1] - firstPoint[1]];
|
||||||
|
const distanceAlongFirst = (delta[0] * secondDirection[1] - delta[1] * secondDirection[0]) / denominator;
|
||||||
|
const local = [firstPoint[0] + firstDirection[0] * distanceAlongFirst, firstPoint[1] + firstDirection[1] * distanceAlongFirst];
|
||||||
|
if (!local.every(Number.isFinite)) return null;
|
||||||
|
return [origin[0] + local[0] / lonScale, origin[1] + local[1] / 111320];
|
||||||
|
}
|
||||||
|
function quadraticCurve(start, control, end, segments) {
|
||||||
|
const result = [];
|
||||||
|
for (let index = 0; index <= segments; index += 1) {
|
||||||
|
const t = index / segments;
|
||||||
|
const u = 1 - t;
|
||||||
|
result.push([u * u * start[0] + 2 * u * t * control[0] + t * t * end[0], u * u * start[1] + 2 * u * t * control[1] + t * t * end[1]]);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
function directionalProjectionMeters(origin, point, heading) {
|
||||||
|
const east = (point[0] - origin[0]) * 111320 * Math.cos(origin[1] * Math.PI / 180);
|
||||||
|
const north = (point[1] - origin[1]) * 111320;
|
||||||
|
const radians = heading * Math.PI / 180;
|
||||||
|
return east * Math.sin(radians) + north * Math.cos(radians);
|
||||||
|
}
|
||||||
|
function smoothClosedRing(vertices) {
|
||||||
|
// Curb-edge candidates can arrive in opposite winding orders when an OSM
|
||||||
|
// carriageway bends slightly. Sort this local corner only around its own
|
||||||
|
// centroid before rounding, avoiding a self-crossing safety island while
|
||||||
|
// keeping the global junction boundary fully OSM-driven.
|
||||||
|
const centroid = vertices.reduce((sum, point) => [sum[0] + point[0] / vertices.length, sum[1] + point[1] / vertices.length], [0, 0]);
|
||||||
|
const ordered = [...vertices].sort((first, second) => Math.atan2(first[1] - centroid[1], first[0] - centroid[0]) - Math.atan2(second[1] - centroid[1], second[0] - centroid[0]));
|
||||||
|
const points = ordered.flatMap((point, index) => {
|
||||||
|
const next = ordered[(index + 1) % ordered.length];
|
||||||
|
return [interpolateCoordinate(point, next, .18), interpolateCoordinate(point, next, .82)];
|
||||||
|
});
|
||||||
|
return [...points, points[0]];
|
||||||
|
}
|
||||||
|
function roundedPolygonRing(vertices, ratio) {
|
||||||
|
const points = vertices.flatMap((point, index) => {
|
||||||
|
const previous = vertices[(index - 1 + vertices.length) % vertices.length];
|
||||||
|
const next = vertices[(index + 1) % vertices.length];
|
||||||
|
return [interpolateCoordinate(previous, point, 1 - ratio), interpolateCoordinate(point, next, ratio)];
|
||||||
|
});
|
||||||
|
return [...points, points[0]];
|
||||||
|
}
|
||||||
|
function interpolateCoordinate(first, second, ratio) { return [first[0] + (second[0] - first[0]) * ratio, first[1] + (second[1] - first[1]) * ratio]; }
|
||||||
|
|
||||||
|
module.exports = { buildComplexJunctionGeometry, complexJunctionMetrics };
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
|
||||||
|
const PI = Math.PI;
|
||||||
|
const EARTH_A = 6378245.0;
|
||||||
|
const EARTH_EE = 0.00669342162296594323;
|
||||||
|
|
||||||
|
function transformLat(x, y) {
|
||||||
|
let value = -100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
|
||||||
|
value += (20 * Math.sin(6 * x * PI) + 20 * Math.sin(2 * x * PI)) * 2 / 3;
|
||||||
|
value += (20 * Math.sin(y * PI) + 40 * Math.sin(y / 3 * PI)) * 2 / 3;
|
||||||
|
value += (160 * Math.sin(y / 12 * PI) + 320 * Math.sin(y * PI / 30)) * 2 / 3;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function transformLon(x, y) {
|
||||||
|
let value = 300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
|
||||||
|
value += (20 * Math.sin(6 * x * PI) + 20 * Math.sin(2 * x * PI)) * 2 / 3;
|
||||||
|
value += (20 * Math.sin(x * PI) + 40 * Math.sin(x / 3 * PI)) * 2 / 3;
|
||||||
|
value += (150 * Math.sin(x / 12 * PI) + 300 * Math.sin(x / 30 * PI)) * 2 / 3;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is the standard local inverse approximation used for GCJ-02 reference
|
||||||
|
// data. It is intentionally kept separate from native road geometry, whose
|
||||||
|
// source coordinates remain WGS84.
|
||||||
|
function gcj02ToWgs84(coordinate) {
|
||||||
|
const [longitude, latitude] = coordinate;
|
||||||
|
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) throw new Error("Reference coordinate must be finite");
|
||||||
|
const dLat = transformLat(longitude - 105, latitude - 35);
|
||||||
|
const dLon = transformLon(longitude - 105, latitude - 35);
|
||||||
|
const radLat = latitude / 180 * PI;
|
||||||
|
const magic = 1 - EARTH_EE * Math.sin(radLat) ** 2;
|
||||||
|
const sqrtMagic = Math.sqrt(magic);
|
||||||
|
return [
|
||||||
|
longitude - dLon * 180 / (EARTH_A / sqrtMagic * Math.cos(radLat) * PI),
|
||||||
|
latitude - dLat * 180 / (EARTH_A * (1 - EARTH_EE) / (magic * sqrtMagic) * PI),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapCoordinates(coordinates, mapper) {
|
||||||
|
if (typeof coordinates[0] === "number") return mapper(coordinates);
|
||||||
|
return coordinates.map((value) => mapCoordinates(value, mapper));
|
||||||
|
}
|
||||||
|
|
||||||
|
function convertGeoJson(document) {
|
||||||
|
if (!document || document.type !== "FeatureCollection" || !Array.isArray(document.features)) {
|
||||||
|
throw new Error("Reference must be a GeoJSON FeatureCollection");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...document,
|
||||||
|
crs: undefined,
|
||||||
|
features: document.features.map((feature) => {
|
||||||
|
if (!feature || !feature.geometry || !feature.geometry.coordinates) throw new Error("Reference feature is missing geometry");
|
||||||
|
return { ...feature, geometry: { ...feature.geometry, coordinates: mapCoordinates(feature.geometry.coordinates, gcj02ToWgs84) } };
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function coordinatesOf(document) {
|
||||||
|
const points = [];
|
||||||
|
for (const feature of document.features || []) walkCoordinates(feature.geometry?.coordinates, points);
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
|
||||||
|
function walkCoordinates(value, points) {
|
||||||
|
if (!Array.isArray(value) || !value.length) return;
|
||||||
|
if (typeof value[0] === "number") {
|
||||||
|
points.push(value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const child of value) walkCoordinates(child, points);
|
||||||
|
}
|
||||||
|
|
||||||
|
function boundsOf(document) {
|
||||||
|
const points = coordinatesOf(document);
|
||||||
|
if (!points.length) throw new Error("Reference contains no coordinates");
|
||||||
|
return {
|
||||||
|
minLon: Math.min(...points.map((point) => point[0])),
|
||||||
|
minLat: Math.min(...points.map((point) => point[1])),
|
||||||
|
maxLon: Math.max(...points.map((point) => point[0])),
|
||||||
|
maxLat: Math.max(...points.map((point) => point[1])),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function centerOf(bounds) {
|
||||||
|
return [(bounds.minLon + bounds.maxLon) / 2, (bounds.minLat + bounds.maxLat) / 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
function distanceMeters(first, second) {
|
||||||
|
const lonScale = 111320 * Math.cos(first[1] * PI / 180);
|
||||||
|
return Math.hypot((second[0] - first[0]) * lonScale, (second[1] - first[1]) * 111320);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseOsmNodes(xml) {
|
||||||
|
const nodes = [];
|
||||||
|
for (const match of xml.matchAll(/<node\b([^>]*?)(?:\/>|>([\s\S]*?)<\/node>)/g)) {
|
||||||
|
const attrs = {};
|
||||||
|
for (const item of match[1].matchAll(/([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) attrs[item[1]] = item[2] ?? item[3];
|
||||||
|
if (!attrs.id || !Number.isFinite(Number(attrs.lon)) || !Number.isFinite(Number(attrs.lat))) continue;
|
||||||
|
const tags = {};
|
||||||
|
for (const item of (match[2] || "").matchAll(/<tag\b([^>]*)\/?\s*>/g)) {
|
||||||
|
const tag = {};
|
||||||
|
for (const attr of item[1].matchAll(/([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) tag[attr[1]] = attr[2] ?? attr[3];
|
||||||
|
if (tag.k) tags[tag.k] = tag.v || "";
|
||||||
|
}
|
||||||
|
nodes.push({ id: String(attrs.id), coordinate: [Number(attrs.lon), Number(attrs.lat)], tags });
|
||||||
|
}
|
||||||
|
return nodes;
|
||||||
|
}
|
||||||
|
|
||||||
|
function nearestNode(nodes, coordinate, nodeId) {
|
||||||
|
if (nodeId) {
|
||||||
|
const exact = nodes.find((node) => node.id === String(nodeId));
|
||||||
|
if (!exact) throw new Error(`OSM node not found: ${nodeId}`);
|
||||||
|
return { ...exact, distanceMeters: distanceMeters(exact.coordinate, coordinate), match: "node-id" };
|
||||||
|
}
|
||||||
|
const candidates = nodes.map((node) => ({ ...node, distanceMeters: distanceMeters(node.coordinate, coordinate) }));
|
||||||
|
candidates.sort((first, second) => first.distanceMeters - second.distanceMeters);
|
||||||
|
if (!candidates[0]) throw new Error("OSM contains no usable nodes");
|
||||||
|
return { ...candidates[0], match: "nearest-node" };
|
||||||
|
}
|
||||||
|
|
||||||
|
function bboxIntersectionRatio(first, second) {
|
||||||
|
const width = Math.max(0, Math.min(first.maxLon, second.maxLon) - Math.max(first.minLon, second.minLon));
|
||||||
|
const height = Math.max(0, Math.min(first.maxLat, second.maxLat) - Math.max(first.minLat, second.minLat));
|
||||||
|
const intersection = width * height;
|
||||||
|
const firstArea = Math.max(0, first.maxLon - first.minLon) * Math.max(0, first.maxLat - first.minLat);
|
||||||
|
const secondArea = Math.max(0, second.maxLon - second.minLon) * Math.max(0, second.maxLat - second.minLat);
|
||||||
|
return intersection / Math.max(firstArea + secondArea - intersection, Number.EPSILON);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A complex junction is compiled as one cluster of `complex_part` polygons in
|
||||||
|
// road_surface.geojson, not as a per-node feature in intersection_surface.
|
||||||
|
// Match it by cluster id, or by whichever cluster core sits nearest the node.
|
||||||
|
function complexClusterSurface(nativeRoadSurfaceFile, node, clusterId) {
|
||||||
|
if (!nativeRoadSurfaceFile || !fs.existsSync(nativeRoadSurfaceFile)) return null;
|
||||||
|
const surface = JSON.parse(fs.readFileSync(nativeRoadSurfaceFile, "utf8"));
|
||||||
|
const parts = (surface.features || []).filter((item) => item.properties?.cluster_id && item.properties?.complex_part);
|
||||||
|
const cores = parts.filter((item) => item.properties.complex_part === "core" && Array.isArray(item.properties.center));
|
||||||
|
if (!cores.length) return null;
|
||||||
|
const core = clusterId
|
||||||
|
? cores.find((item) => String(item.properties.cluster_id) === String(clusterId))
|
||||||
|
: [...cores].sort((first, second) => distanceMeters(first.properties.center, node.coordinate) - distanceMeters(second.properties.center, node.coordinate))[0];
|
||||||
|
if (!core) return null;
|
||||||
|
const features = parts.filter((item) => item.properties.cluster_id === core.properties.cluster_id);
|
||||||
|
return { clusterId: core.properties.cluster_id, core, features };
|
||||||
|
}
|
||||||
|
|
||||||
|
function inspectReference({ referenceFile, osmFile, nativeIntersectionFile, nativeRoadSurfaceFile, nodeId, clusterId }) {
|
||||||
|
const source = JSON.parse(fs.readFileSync(referenceFile, "utf8"));
|
||||||
|
const converted = convertGeoJson(source);
|
||||||
|
const referenceBounds = boundsOf(converted);
|
||||||
|
const referenceCenter = centerOf(referenceBounds);
|
||||||
|
const nodes = parseOsmNodes(fs.readFileSync(osmFile, "utf8"));
|
||||||
|
const matchedNode = nearestNode(nodes, referenceCenter, nodeId);
|
||||||
|
const native = JSON.parse(fs.readFileSync(nativeIntersectionFile, "utf8"));
|
||||||
|
const feature = (native.features || []).find((item) => item.properties?.osm_node_id === matchedNode.id);
|
||||||
|
const cluster = feature ? null : complexClusterSurface(nativeRoadSurfaceFile, matchedNode, clusterId);
|
||||||
|
const matchedFeatures = feature ? [feature] : cluster?.features || null;
|
||||||
|
const nativeBounds = matchedFeatures ? boundsOf({ features: matchedFeatures }) : null;
|
||||||
|
const diagnostics = [];
|
||||||
|
if (!matchedFeatures) diagnostics.push(nativeRoadSurfaceFile ? "No native intersection surface or complex cluster matched the OSM node" : "No native intersection surface matched the OSM node; pass --native-road-surface to also search complex junction clusters");
|
||||||
|
return {
|
||||||
|
schema: "gaode-junction-reference-comparison/v2",
|
||||||
|
source: { file: referenceFile, coordinateSystem: "GCJ-02", featureCount: converted.features.length },
|
||||||
|
conversion: { target: "WGS84", method: "gcj02-inverse-approximation" },
|
||||||
|
reference: { bounds: referenceBounds, center: referenceCenter },
|
||||||
|
matchedOsmNode: { id: matchedNode.id, coordinate: matchedNode.coordinate, tags: matchedNode.tags, match: matchedNode.match, centerDistanceMeters: matchedNode.distanceMeters },
|
||||||
|
nativeIntersection: nativeBounds ? {
|
||||||
|
kind: feature ? "junction-node" : "complex-cluster",
|
||||||
|
clusterId: cluster?.clusterId || null,
|
||||||
|
featureCount: matchedFeatures.length,
|
||||||
|
bounds: nativeBounds,
|
||||||
|
bboxIoU: bboxIntersectionRatio(referenceBounds, nativeBounds),
|
||||||
|
centerOffsetMeters: distanceMeters(referenceCenter, centerOf(nativeBounds)),
|
||||||
|
featureProperties: feature ? feature.properties : cluster.core.properties,
|
||||||
|
} : null,
|
||||||
|
diagnostics,
|
||||||
|
converted,
|
||||||
|
matchedFeatures,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function localReferenceSvg({ converted, nativeIntersection, center, radiusMeters = 180 }) {
|
||||||
|
const width = 1000;
|
||||||
|
const height = 1000;
|
||||||
|
const lonScale = 111320 * Math.cos(center[1] * PI / 180);
|
||||||
|
const project = (point) => [
|
||||||
|
width / 2 + (point[0] - center[0]) * lonScale * width / (radiusMeters * 2),
|
||||||
|
height / 2 - (point[1] - center[1]) * 111320 * height / (radiusMeters * 2),
|
||||||
|
];
|
||||||
|
const pathFor = (coordinates) => {
|
||||||
|
const parts = [];
|
||||||
|
const appendLine = (line, close) => {
|
||||||
|
if (!line?.length) return;
|
||||||
|
const [firstX, firstY] = project(line[0]);
|
||||||
|
parts.push(`M ${firstX.toFixed(1)} ${firstY.toFixed(1)}`);
|
||||||
|
for (const point of line.slice(1)) {
|
||||||
|
const [x, y] = project(point);
|
||||||
|
parts.push(`L ${x.toFixed(1)} ${y.toFixed(1)}`);
|
||||||
|
}
|
||||||
|
if (close) parts.push("Z");
|
||||||
|
};
|
||||||
|
const visit = (value) => {
|
||||||
|
if (!Array.isArray(value) || !value.length) return;
|
||||||
|
if (typeof value[0] === "number") return;
|
||||||
|
if (typeof value[0][0] === "number") appendLine(value, value.length > 2);
|
||||||
|
else value.forEach(visit);
|
||||||
|
};
|
||||||
|
visit(coordinates);
|
||||||
|
return parts.join(" ");
|
||||||
|
};
|
||||||
|
const color = { 1: "#2563eb", 2: "#0f766e", 3: "#7c3aed", 4: "#ea580c", 5: "#64748b" };
|
||||||
|
const references = converted.features.map((feature) => {
|
||||||
|
const type = feature.properties?.type || "unknown";
|
||||||
|
return `<path d="${pathFor(feature.geometry.coordinates)}" fill="${feature.geometry.type.includes("Polygon") ? `${color[type] || "#334155"}18` : "none"}" stroke="${color[type] || "#334155"}" stroke-width="1.2"/>`;
|
||||||
|
}).join("\n");
|
||||||
|
const nativePaths = (nativeIntersection?.features || []).map((feature) => `<path d="${pathFor(feature.geometry.coordinates)}" fill="#dc262655" stroke="#dc2626" stroke-width="3"/>`).join("\n");
|
||||||
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
|
||||||
|
<rect width="100%" height="100%" fill="#f8fafc"/>
|
||||||
|
${references}
|
||||||
|
${nativePaths}
|
||||||
|
<circle cx="${width / 2}" cy="${height / 2}" r="5" fill="#111827"/>
|
||||||
|
<text x="20" y="35" font-family="sans-serif" font-size="22" fill="#111827">Gaode reference (type colors) / native intersection (red)</text>
|
||||||
|
</svg>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { gcj02ToWgs84, convertGeoJson, boundsOf, parseOsmNodes, nearestNode, inspectReference, localReferenceSvg };
|
||||||
+698
-57
File diff suppressed because it is too large.
Load diff
@@ -12,10 +12,26 @@ const {
|
|||||||
const SCHEMA = "native-traffic-signals/v1";
|
const SCHEMA = "native-traffic-signals/v1";
|
||||||
|
|
||||||
function loadOrGenerate(file, osmText, stopLines, intersections) {
|
function loadOrGenerate(file, osmText, stopLines, intersections) {
|
||||||
if (fs.existsSync(file)) return validateDocument(JSON.parse(fs.readFileSync(file, "utf8")), osmText);
|
if (fs.existsSync(file)) {
|
||||||
|
const document = JSON.parse(fs.readFileSync(file, "utf8"));
|
||||||
|
try {
|
||||||
|
return validateDocument(document, osmText);
|
||||||
|
} catch (error) {
|
||||||
|
// OSM edits can invalidate the stable identities in a document that was
|
||||||
|
// itself generated from OSM. User-authored documents must remain strict.
|
||||||
|
if (document?.provenance === "generated:osm-controls" && isStaleSourceReferenceError(error)) {
|
||||||
|
return generate(osmText, stopLines, intersections);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
return generate(osmText, stopLines, intersections);
|
return generate(osmText, stopLines, intersections);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isStaleSourceReferenceError(error) {
|
||||||
|
return error instanceof Error && /^traffic signal feature \d+: (approach_id .* is not present on OSM control|control_id .* is not present in the current OSM)/.test(error.message);
|
||||||
|
}
|
||||||
|
|
||||||
function generate(osmText, stopLines, intersections) {
|
function generate(osmText, stopLines, intersections) {
|
||||||
const controls = parseOsm(osmText).trafficSignalControls;
|
const controls = parseOsm(osmText).trafficSignalControls;
|
||||||
return { schema: SCHEMA, provenance: "generated:osm-controls", assemblies: buildTrafficSignalFeatures(stopLines, intersections, controls) };
|
return { schema: SCHEMA, provenance: "generated:osm-controls", assemblies: buildTrafficSignalFeatures(stopLines, intersections, controls) };
|
||||||
|
|||||||
@@ -23,20 +23,38 @@ function buildTrafficSignalFeatures(stopLines, intersections, controls = []) {
|
|||||||
const point = polygonCenter(feature.geometry);
|
const point = polygonCenter(feature.geometry);
|
||||||
return { id: `intersection-${index + 1}`, point, radius: polygonRadius(feature.geometry, point) };
|
return { id: `intersection-${index + 1}`, point, radius: polygonRadius(feature.geometry, point) };
|
||||||
}).filter((entry) => entry.point);
|
}).filter((entry) => entry.point);
|
||||||
|
const clusteredStops = new Map();
|
||||||
|
for (const feature of stopLines.features || []) {
|
||||||
|
const clusterId = feature.properties?.cluster_id;
|
||||||
|
const point = polygonCenter(feature.geometry);
|
||||||
|
if (!clusterId || !point) continue;
|
||||||
|
if (!clusteredStops.has(clusterId)) clusteredStops.set(clusterId, []);
|
||||||
|
clusteredStops.get(clusterId).push(point);
|
||||||
|
}
|
||||||
|
for (const [clusterId, points] of clusteredStops) {
|
||||||
|
if (points.length < 3) continue;
|
||||||
|
const point = points.reduce((sum, item) => [sum[0] + item[0] / points.length, sum[1] + item[1] / points.length], [0, 0]);
|
||||||
|
centers.push({ id: `cluster-${clusterId}`, clusterId, point, radius: Math.max(...points.map((item) => metersBetween(point, item))) });
|
||||||
|
}
|
||||||
const candidates = [];
|
const candidates = [];
|
||||||
for (const feature of stopLines.features || []) {
|
for (const feature of stopLines.features || []) {
|
||||||
const center = polygonCenter(feature.geometry);
|
const center = polygonCenter(feature.geometry);
|
||||||
if (!center) continue;
|
if (!center) continue;
|
||||||
const intersection = nearestCenter(center, centers);
|
const clusterId = feature.properties?.cluster_id;
|
||||||
|
const intersection = clusterId ? centers.find((entry) => entry.clusterId === clusterId) : nearestCenter(center, centers);
|
||||||
if (!intersection || metersBetween(center, intersection.point) > 32) continue;
|
if (!intersection || metersBetween(center, intersection.point) > 32) continue;
|
||||||
const axis = roadAxis(feature.geometry, center, intersection.point);
|
const axis = roadAxis(feature.geometry, center, intersection.point);
|
||||||
if (!axis) continue;
|
if (!axis) continue;
|
||||||
const right = [axis[1], -axis[0]];
|
const right = [axis[1], -axis[0]];
|
||||||
const farSide = moveMeters(intersection.point, axis, intersection.radius + 3.2);
|
|
||||||
candidates.push({
|
candidates.push({
|
||||||
intersectionId: intersection.id, center, axis,
|
intersectionId: intersection.id, center, axis,
|
||||||
point: moveMeters(farSide, right, CURB_OFFSET_METERS),
|
point: intersection.clusterId
|
||||||
|
? moveMeters(center, right, CURB_OFFSET_METERS)
|
||||||
|
: moveMeters(moveMeters(intersection.point, axis, intersection.radius + 3.2), right, CURB_OFFSET_METERS),
|
||||||
headingDegrees: normalizeDegrees(Math.atan2(axis[0], axis[1]) * 180 / Math.PI),
|
headingDegrees: normalizeDegrees(Math.atan2(axis[0], axis[1]) * 180 / Math.PI),
|
||||||
|
matchHeadingDegrees: intersection.clusterId
|
||||||
|
? normalizeDegrees(Math.atan2(-axis[0], -axis[1]) * 180 / Math.PI)
|
||||||
|
: null,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const features = [];
|
const features = [];
|
||||||
@@ -180,25 +198,34 @@ function signalNodeKey(signalUid) {
|
|||||||
return `ts_${crypto.createHash("sha256").update(signalUid).digest("hex").slice(0, 16)}`;
|
return `ts_${crypto.createHash("sha256").update(signalUid).digest("hex").slice(0, 16)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateTrafficSignalSourceReferences(collection, controls) {
|
function reconcileTrafficSignalSourceReferences(collection, controls) {
|
||||||
const normalized = validateTrafficSignalFeatures(collection);
|
const normalized = validateTrafficSignalFeatures(collection);
|
||||||
const approachesByControl = new Map((controls || []).map((control) => [
|
const approachesByControl = new Map((controls || []).map((control) => [
|
||||||
String(control.id),
|
String(control.id),
|
||||||
new Set((control.arms || []).map((arm) => `${String(arm.wayId)}:${String(arm.neighborNodeId)}`)),
|
new Set((control.arms || []).map((arm) => `${String(arm.wayId)}:${String(arm.neighborNodeId)}`)),
|
||||||
]));
|
]));
|
||||||
|
const kept = [];
|
||||||
|
const dropped = [];
|
||||||
for (const [index, feature] of normalized.features.entries()) {
|
for (const [index, feature] of normalized.features.entries()) {
|
||||||
const { control_id: controlId, approach_id: approachId } = feature.properties;
|
const { control_id: controlId, approach_id: approachId, signal_uid: signalUid } = feature.properties;
|
||||||
const approaches = approachesByControl.get(controlId);
|
const approaches = approachesByControl.get(controlId);
|
||||||
if (!approaches) {
|
if (!approaches) {
|
||||||
throw new Error(`traffic signal feature ${index + 1}: control_id '${controlId}' is not present in the current OSM`);
|
dropped.push({ index: index + 1, signalUid, controlId, approachId, reason: "missing-control", message: `control_id '${controlId}' is not present in the current OSM` });
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
if (!approaches.has(approachId)) {
|
if (!approaches.has(approachId)) {
|
||||||
throw new Error(
|
dropped.push({ index: index + 1, signalUid, controlId, approachId, reason: "missing-approach", message: `approach_id '${approachId}' is not present on OSM control '${controlId}'` });
|
||||||
`traffic signal feature ${index + 1}: approach_id '${approachId}' is not present on OSM control '${controlId}'`,
|
continue;
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
kept.push(feature);
|
||||||
}
|
}
|
||||||
return normalized;
|
return { collection: { ...normalized, features: kept }, dropped };
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateTrafficSignalSourceReferences(collection, controls) {
|
||||||
|
const { collection: reconciled, dropped } = reconcileTrafficSignalSourceReferences(collection, controls);
|
||||||
|
if (dropped.length) throw new Error(`traffic signal feature ${dropped[0].index}: ${dropped[0].message}`);
|
||||||
|
return reconciled;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildTrafficSignals(stopLines, intersections, controls = []) {
|
function buildTrafficSignals(stopLines, intersections, controls = []) {
|
||||||
@@ -237,11 +264,20 @@ function uniqueApproachArms(candidates, controlPoint) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function matchOsmArms(candidates, controlPoint, osmArms) {
|
function matchOsmArms(candidates, controlPoint, osmArms) {
|
||||||
const remaining = candidates.map((candidate) => ({ ...candidate, armHeading: normalizeDegrees(headingBetween(controlPoint, candidate.center)) }));
|
const remaining = candidates.map((candidate) => ({ ...candidate, armHeading: candidate.matchHeadingDegrees ?? normalizeDegrees(headingBetween(controlPoint, candidate.center)) }));
|
||||||
if (!osmArms.length) return uniqueApproachArms(remaining, controlPoint);
|
if (!osmArms.length) return uniqueApproachArms(remaining, controlPoint);
|
||||||
return osmArms.map((osmArm) => {
|
return osmArms.map((osmArm) => {
|
||||||
let bestIndex = -1; let bestDistance = Infinity;
|
let bestIndex = -1; let bestDistance = Infinity;
|
||||||
remaining.forEach((item, index) => { const distance = angularDistance(item.armHeading, osmArm.headingDegrees); if (distance < bestDistance) { bestDistance = distance; bestIndex = index; } });
|
remaining.forEach((item, index) => {
|
||||||
|
const directedDistance = angularDistance(item.armHeading, osmArm.headingDegrees);
|
||||||
|
const distance = item.matchHeadingDegrees == null
|
||||||
|
? directedDistance
|
||||||
|
: Math.min(
|
||||||
|
angularDistance(item.matchHeadingDegrees, osmArm.headingDegrees),
|
||||||
|
angularDistance(item.matchHeadingDegrees + 180, osmArm.headingDegrees),
|
||||||
|
);
|
||||||
|
if (distance < bestDistance) { bestDistance = distance; bestIndex = index; }
|
||||||
|
});
|
||||||
const candidate = bestIndex >= 0 && bestDistance <= 45 ? remaining.splice(bestIndex, 1)[0] : fallbackCandidate(controlPoint, osmArm);
|
const candidate = bestIndex >= 0 && bestDistance <= 45 ? remaining.splice(bestIndex, 1)[0] : fallbackCandidate(controlPoint, osmArm);
|
||||||
return { ...candidate, osmArm };
|
return { ...candidate, osmArm };
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,978 @@
|
|||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const PI = Math.PI;
|
||||||
|
const EARTH_A = 6378245.0;
|
||||||
|
const EARTH_EE = 0.00669342162296594323;
|
||||||
|
const TOKEN_KEY = "osm-asset-preview-v2x-token";
|
||||||
|
const LIVE_VEHICLE_HEIGHT_METERS = 1.2;
|
||||||
|
const LIVE_VEHICLE_HEADING_OFFSET_DEGREES = 90;
|
||||||
|
|
||||||
|
function createV2xCesiumOverlay(context) {
|
||||||
|
const settings = context.config.v2xPreview || {};
|
||||||
|
if (!settings.enabled) return null;
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
token: "",
|
||||||
|
entities: [],
|
||||||
|
linkEntitiesByPhase: new Map(),
|
||||||
|
phaseSignals: new Map(),
|
||||||
|
phaseBinding: { bound: 0, unbound: [], diagnostics: [] },
|
||||||
|
sockets: [],
|
||||||
|
status: "Sign in to load live V2X data.",
|
||||||
|
crossCode: settings.crossCode || "",
|
||||||
|
vehicleSource: "waiting",
|
||||||
|
parseFailures: 0,
|
||||||
|
missingModels: new Set(),
|
||||||
|
targetMessages: 0,
|
||||||
|
targetVehiclesReceived: 0,
|
||||||
|
targetLastCount: 0,
|
||||||
|
targetLastError: "",
|
||||||
|
targetPayloadType: "",
|
||||||
|
targetPayloadSample: "",
|
||||||
|
targetPayloadShape: "",
|
||||||
|
};
|
||||||
|
// This preview intentionally starts at the login gate. Do not revive a
|
||||||
|
// previous tab's token and begin REST/WebSocket traffic before sign-in.
|
||||||
|
sessionStorage.removeItem(TOKEN_KEY);
|
||||||
|
const ui = buildUi(state);
|
||||||
|
state.vehicleModels = Array.isArray(context.config.vehicleModelNames) ? context.config.vehicleModelNames : [];
|
||||||
|
state.setSignalState = context.setSignalState;
|
||||||
|
state.nativeSignals = arrayValue(context.nativeSignals);
|
||||||
|
const registry = createVehicleRegistry({});
|
||||||
|
state.registry = registry;
|
||||||
|
let sweepTimer = null;
|
||||||
|
let boundsTimer = null;
|
||||||
|
let obuSend = null;
|
||||||
|
|
||||||
|
function setStatus(message) {
|
||||||
|
state.status = message;
|
||||||
|
ui.status.textContent = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusDetail() {
|
||||||
|
const parts = [];
|
||||||
|
parts.push(`${state.phaseBinding.bound} phases bound`);
|
||||||
|
if (state.phaseBinding.unbound.length) parts.push(`${state.phaseBinding.unbound.length} unbound`);
|
||||||
|
if (state.missingModels.size) parts.push(`${state.missingModels.size} models missing`);
|
||||||
|
if (state.parseFailures) parts.push(`${state.parseFailures} unparsed pushes`);
|
||||||
|
if (state.targetMessages) parts.push(`${state.targetVehiclesReceived} target vehicles`);
|
||||||
|
return parts.join(", ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearEntities() {
|
||||||
|
state.entities.forEach((entity) => context.viewer.entities.remove(entity));
|
||||||
|
state.entities = [];
|
||||||
|
registry.list().forEach((record) => {
|
||||||
|
if (record.entity) context.viewer.entities.remove(record.entity);
|
||||||
|
});
|
||||||
|
registry.clear();
|
||||||
|
state.linkEntitiesByPhase.clear();
|
||||||
|
state.phaseSignals.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
function disconnect() {
|
||||||
|
state.sockets.forEach((socket) => socket.dispose());
|
||||||
|
state.sockets = [];
|
||||||
|
if (sweepTimer !== null) { clearInterval(sweepTimer); sweepTimer = null; }
|
||||||
|
if (boundsTimer !== null) { clearTimeout(boundsTimer); boundsTimer = null; }
|
||||||
|
obuSend = null;
|
||||||
|
if (context.viewer?.camera?.moveEnd) {
|
||||||
|
try { context.viewer.camera.moveEnd.removeEventListener(onCameraMoveEnd); } catch (_) { /* not attached */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function useLiveVehicles() {
|
||||||
|
if (state.vehicleSource === "live") return;
|
||||||
|
state.vehicleSource = "live";
|
||||||
|
}
|
||||||
|
state.activateLiveVehicles = useLiveVehicles;
|
||||||
|
|
||||||
|
async function request(path) {
|
||||||
|
const response = await fetch(joinUrl(settings.apiBaseUrl || "/api", path), {
|
||||||
|
headers: state.token ? { Authorization: state.token } : {},
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
const body = await response.json().catch(() => null);
|
||||||
|
if (response.status === 401 || response.status === 403 || body?.code === 401 || body?.code === 403) {
|
||||||
|
signOut("V2X authorization expired. Sign in again.");
|
||||||
|
throw new Error("V2X authorization expired");
|
||||||
|
}
|
||||||
|
if (!response.ok) throw new Error(`V2X request failed (${response.status})`);
|
||||||
|
if (body && Object.prototype.hasOwnProperty.call(body, "code") && Number(body.code) !== 200) {
|
||||||
|
throw new Error(body.msg || body.message || "V2X request failed");
|
||||||
|
}
|
||||||
|
return body && Object.prototype.hasOwnProperty.call(body, "data") ? body.data : body;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signIn(userName, password) {
|
||||||
|
setStatus("Signing in to V2X...");
|
||||||
|
const response = await fetch(joinUrl(settings.apiBaseUrl || "/api", "/facilities/api/sys/login"), {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ userName, password: md5(password) }),
|
||||||
|
});
|
||||||
|
const body = await response.json().catch(() => null);
|
||||||
|
const payload = body?.data || body || {};
|
||||||
|
const token = payload.token || payload.accessToken || body?.token;
|
||||||
|
if (!response.ok || Number(body?.code) !== 200 || typeof token !== "string" || !token) {
|
||||||
|
throw new Error(body?.msg || body?.message || "V2X sign-in failed");
|
||||||
|
}
|
||||||
|
state.token = token;
|
||||||
|
ui.form.hidden = true;
|
||||||
|
ui.live.hidden = false;
|
||||||
|
await loadLiveData();
|
||||||
|
}
|
||||||
|
|
||||||
|
function signOut(message) {
|
||||||
|
disconnect();
|
||||||
|
clearEntities();
|
||||||
|
state.vehicleSource = "waiting";
|
||||||
|
state.token = "";
|
||||||
|
state.parseFailures = 0;
|
||||||
|
state.missingModels.clear();
|
||||||
|
state.phaseBinding = { bound: 0, unbound: [], diagnostics: [] };
|
||||||
|
sessionStorage.removeItem(TOKEN_KEY);
|
||||||
|
ui.form.hidden = false;
|
||||||
|
ui.live.hidden = true;
|
||||||
|
if (message) setStatus(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadLiveData() {
|
||||||
|
const crossCode = await resolveCrossCode();
|
||||||
|
if (!crossCode) {
|
||||||
|
setStatus("No V2X intersection is configured for this account.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clearEntities();
|
||||||
|
state.vehicleSource = "waiting";
|
||||||
|
setStatus("Loading live V2X intersection data...");
|
||||||
|
const results = await Promise.allSettled([
|
||||||
|
request(`/network/api/link/network/queryCrossLinkInfo/${encodeURIComponent(crossCode)}`),
|
||||||
|
request(`/network/api/pole/network/queryPoles/${encodeURIComponent(crossCode)}`),
|
||||||
|
request(`/facilities/api/crossDevice/findDeviceByCrossCode/${encodeURIComponent(crossCode)}`),
|
||||||
|
request(`/facilities/api/crossDeviceConfig/${encodeURIComponent(crossCode)}`),
|
||||||
|
]);
|
||||||
|
const [links, poles, devices, deviceConfig] = results;
|
||||||
|
const warnings = [];
|
||||||
|
const linkList = links.status === "fulfilled" ? arrayValue(links.value?.inLinkList) : [];
|
||||||
|
if (links.status === "fulfilled") addLinks(context.viewer, links.value, state);
|
||||||
|
else warnings.push("links unavailable");
|
||||||
|
if (devices.status === "fulfilled") addDevices(context.viewer, devices.value, state);
|
||||||
|
else warnings.push("devices unavailable");
|
||||||
|
|
||||||
|
state.phaseBinding = buildPhaseSignalMap(linkList, state.nativeSignals, {
|
||||||
|
phaseSignalMap: settings.phaseSignalMap,
|
||||||
|
maxDistanceMeters: settings.maxDistanceMeters,
|
||||||
|
maxHeadingDeltaDegrees: settings.maxHeadingDeltaDegrees,
|
||||||
|
});
|
||||||
|
state.phaseSignals = state.phaseBinding.byPhase;
|
||||||
|
if (!state.phaseBinding.bound && linkList.length) {
|
||||||
|
warnings.push("no phase bound to a native signal head; set v2xPreview.phaseSignalMap");
|
||||||
|
}
|
||||||
|
|
||||||
|
const poleCount = poles.status === "fulfilled" ? arrayValue(poles.value?.posConfig || poles.value).length : 0;
|
||||||
|
const deviceCount = devices.status === "fulfilled" ? arrayValue(devices.value).length : 0;
|
||||||
|
const targetCount = deviceConfig.status === "fulfilled" ? arrayValue(deviceConfig.value?.deviceConfig?.target).length : 0;
|
||||||
|
connectLiveSockets(deviceConfig.status === "fulfilled" ? deviceConfig.value : null);
|
||||||
|
setStatus(`Live V2X: ${linkList.length} links, ${deviceCount} devices, ${poleCount} poles, ${targetCount} configured targets. ${statusDetail()}. GCJ-02 -> WGS84 once.${warnings.length ? ` ${warnings.join(", ")}.` : ""}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveCrossCode() {
|
||||||
|
if (state.crossCode) return state.crossCode;
|
||||||
|
setStatus("Finding the configured V2X intersection...");
|
||||||
|
const [crosses, configurations] = await Promise.allSettled([
|
||||||
|
request("/cloud-display/api/search/crossList?hdMap=true"),
|
||||||
|
request("/facilities/api/crossDeviceConfig/queryList"),
|
||||||
|
]);
|
||||||
|
state.crossCode = selectCrossCode(
|
||||||
|
crosses.status === "fulfilled" ? crosses.value : null,
|
||||||
|
configurations.status === "fulfilled" ? configurations.value : null,
|
||||||
|
);
|
||||||
|
return state.crossCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectLiveSockets(deviceConfig) {
|
||||||
|
disconnect();
|
||||||
|
connectSignalSocket();
|
||||||
|
connectObuSocket();
|
||||||
|
connectTargetSocket(deviceConfig);
|
||||||
|
// Stale vehicles must disappear even while pushes keep arriving for
|
||||||
|
// others, so sweep on a timer as well as on each push.
|
||||||
|
sweepTimer = setInterval(() => {
|
||||||
|
if (registry.sweep().length) renderVehicles();
|
||||||
|
}, 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openSocket(path, onOpen, onMessage, unavailable) {
|
||||||
|
const socket = createSocket({
|
||||||
|
url: () => toWebSocketUrl(joinUrl(settings.wsBaseUrl || "/websocket", path), state.token),
|
||||||
|
onOpen,
|
||||||
|
onMessage,
|
||||||
|
onError: () => setStatus(`${state.status} ${unavailable}.`),
|
||||||
|
});
|
||||||
|
state.sockets.push(socket);
|
||||||
|
socket.open();
|
||||||
|
return socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectSignalSocket() {
|
||||||
|
openSocket("/network/ws/network/signal",
|
||||||
|
({ send }) => send(JSON.stringify({ junctionId: String(state.crossCode) })),
|
||||||
|
(value) => updateSignalPhases(value, state),
|
||||||
|
"Signal WebSocket unavailable");
|
||||||
|
}
|
||||||
|
|
||||||
|
function onCameraMoveEnd() {
|
||||||
|
if (boundsTimer !== null) clearTimeout(boundsTimer);
|
||||||
|
boundsTimer = setTimeout(() => {
|
||||||
|
boundsTimer = null;
|
||||||
|
const bounds = cameraBoundsMessage();
|
||||||
|
if (obuSend && bounds) obuSend(JSON.stringify({ bounds }));
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cameraBoundsMessage() {
|
||||||
|
try {
|
||||||
|
const rectangle = context.viewer?.camera?.computeViewRectangle?.();
|
||||||
|
if (!rectangle) return "";
|
||||||
|
return buildBoundsMessage({
|
||||||
|
west: Cesium.Math.toDegrees(rectangle.west),
|
||||||
|
south: Cesium.Math.toDegrees(rectangle.south),
|
||||||
|
east: Cesium.Math.toDegrees(rectangle.east),
|
||||||
|
north: Cesium.Math.toDegrees(rectangle.north),
|
||||||
|
});
|
||||||
|
} catch (_) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectObuSocket() {
|
||||||
|
const socket = openSocket("/network/ws/network/obuPosition", ({ send }) => {
|
||||||
|
obuSend = send;
|
||||||
|
// The dashboard sends `bounds || ''` on connect; an empty frame means
|
||||||
|
// "no viewport filter", which is the safe default for a tilted camera.
|
||||||
|
const bounds = cameraBoundsMessage();
|
||||||
|
send(bounds ? JSON.stringify({ bounds }) : "");
|
||||||
|
}, (value) => {
|
||||||
|
const push = normalizeObuPush(value);
|
||||||
|
if (!push.vehicle) { if (!isHeartbeat(value)) state.parseFailures += 1; return; }
|
||||||
|
useLiveVehicles();
|
||||||
|
registry.ingest([push.vehicle], push.interval);
|
||||||
|
registry.sweep();
|
||||||
|
renderVehicles();
|
||||||
|
}, "OBU vehicle WebSocket unavailable");
|
||||||
|
if (context.viewer?.camera?.moveEnd) {
|
||||||
|
try { context.viewer.camera.moveEnd.addEventListener(onCameraMoveEnd); } catch (_) { /* no camera events */ }
|
||||||
|
}
|
||||||
|
return socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectTargetSocket(deviceConfig) {
|
||||||
|
openSocket("/network/ws/network/targetPosition", ({ send }) => {
|
||||||
|
const targetIds = arrayValue(deviceConfig?.deviceConfig?.target);
|
||||||
|
send(JSON.stringify({ deviceId: targetIds.length ? targetIds.join(",") : null }));
|
||||||
|
}, (value) => {
|
||||||
|
if (isHeartbeat(value)) return;
|
||||||
|
state.targetMessages += 1;
|
||||||
|
try {
|
||||||
|
state.targetPayloadType = Object.prototype.toString.call(value);
|
||||||
|
state.targetPayloadSample = typeof value === "string" ? value.slice(0, 800) : String(value).slice(0, 800);
|
||||||
|
const payload = parseLoosePayload(value);
|
||||||
|
const data = payload?.data;
|
||||||
|
state.targetPayloadShape = data === null ? "data:null" : Array.isArray(data) ? `data:array(${data.length})` : typeof data === "object" ? `data:object(${Object.keys(data || {}).join(",")})` : `data:${typeof data}`;
|
||||||
|
const vehicles = targetVehiclesFrom(payload);
|
||||||
|
state.targetLastCount = vehicles.length;
|
||||||
|
if (!vehicles.length) {
|
||||||
|
if (payload === null) state.parseFailures += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.targetVehiclesReceived += vehicles.length;
|
||||||
|
useLiveVehicles();
|
||||||
|
registry.ingest(vehicles, payload?.interval);
|
||||||
|
registry.sweep();
|
||||||
|
renderVehicles();
|
||||||
|
} catch (error) {
|
||||||
|
state.targetLastError = String(error?.message || error);
|
||||||
|
state.parseFailures += 1;
|
||||||
|
}
|
||||||
|
}, "Target vehicle WebSocket unavailable");
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderVehicles() {
|
||||||
|
registry.list().forEach((record) => syncVehicleEntity(context.viewer, record, state));
|
||||||
|
}
|
||||||
|
|
||||||
|
ui.form.addEventListener("submit", async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
try {
|
||||||
|
await signIn(ui.userName.value.trim(), ui.password.value);
|
||||||
|
ui.password.value = "";
|
||||||
|
} catch (error) {
|
||||||
|
setStatus(error.message || "V2X sign-in failed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.reload.addEventListener("click", () => loadLiveData().catch((error) => setStatus(error.message || "Live V2X data unavailable")));
|
||||||
|
ui.signOut.addEventListener("click", () => signOut("Signed out. Native preview remains available."));
|
||||||
|
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
load: loadLiveData,
|
||||||
|
signOut,
|
||||||
|
dispose: () => { disconnect(); clearEntities(); state.vehicleSource = "waiting"; ui.root.remove(); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildUi(state) {
|
||||||
|
const root = document.createElement("aside");
|
||||||
|
root.id = "v2xPanel";
|
||||||
|
root.innerHTML = `<div class="v2x-heading"><strong>Live V2X Data</strong><span>Native: WGS84/ENU | V2X: GCJ-02</span></div>
|
||||||
|
<form id="v2xLoginForm"><label>Username<input name="userName" autocomplete="username" required></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button type="submit">Sign in</button></form>
|
||||||
|
<div id="v2xLiveControls" hidden><div><button type="button" data-action="reload">Refresh</button><button type="button" data-action="signout">Sign out</button></div></div>
|
||||||
|
<output id="v2xStatus"></output>`;
|
||||||
|
document.body.appendChild(root);
|
||||||
|
return {
|
||||||
|
root,
|
||||||
|
form: root.querySelector("#v2xLoginForm"),
|
||||||
|
live: root.querySelector("#v2xLiveControls"),
|
||||||
|
userName: root.querySelector("[name=userName]"),
|
||||||
|
password: root.querySelector("[name=password]"),
|
||||||
|
reload: root.querySelector("[data-action=reload]"),
|
||||||
|
signOut: root.querySelector("[data-action=signout]"),
|
||||||
|
status: root.querySelector("#v2xStatus"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function addLinks(viewer, document, state) {
|
||||||
|
arrayValue(document?.inLinkList).forEach((link) => {
|
||||||
|
let geometry;
|
||||||
|
try { geometry = typeof link.geom === "string" ? JSON.parse(link.geom) : link.geom; } catch (_) { return; }
|
||||||
|
const points = arrayValue(geometry?.coordinates).map(gcj02ToWgs84).flat();
|
||||||
|
if (points.length < 4) return;
|
||||||
|
const entity = viewer.entities.add({
|
||||||
|
name: link.name || `V2X link ${link.id}`,
|
||||||
|
polyline: { positions: Cesium.Cartesian3.fromDegreesArray(points), width: 5, material: Cesium.Color.CYAN.withAlpha(.78), clampToGround: false },
|
||||||
|
});
|
||||||
|
state.entities.push(entity);
|
||||||
|
// A phase can drive several approaches, so collect entities per phase
|
||||||
|
// instead of overwriting a single one.
|
||||||
|
arrayValue(link.phaseList).forEach((phase) => {
|
||||||
|
const key = String(phase.phase);
|
||||||
|
const existing = state.linkEntitiesByPhase.get(key) || [];
|
||||||
|
existing.push(entity);
|
||||||
|
state.linkEntitiesByPhase.set(key, existing);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function addDevices(viewer, devices, state) {
|
||||||
|
arrayValue(devices).forEach((device) => {
|
||||||
|
const longitude = Number(device.longitude ?? device.lon ?? device.position?.longitude);
|
||||||
|
const latitude = Number(device.latitude ?? device.lat ?? device.position?.latitude);
|
||||||
|
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return;
|
||||||
|
const [wgsLongitude, wgsLatitude] = gcj02ToWgs84([longitude, latitude]);
|
||||||
|
const entity = viewer.entities.add({
|
||||||
|
name: device.name || device.code || "V2X device",
|
||||||
|
position: Cesium.Cartesian3.fromDegrees(wgsLongitude, wgsLatitude, 3),
|
||||||
|
point: { pixelSize: 9, color: device.onlineStatus === 1 ? Cesium.Color.LIME : Cesium.Color.RED, outlineColor: Cesium.Color.BLACK, outlineWidth: 1 },
|
||||||
|
label: { text: device.code || device.name || "device", font: "11px sans-serif", fillColor: Cesium.Color.WHITE, outlineColor: Cesium.Color.BLACK, outlineWidth: 2, style: Cesium.LabelStyle.FILL_AND_OUTLINE, pixelOffset: new Cesium.Cartesian2(0, -16) },
|
||||||
|
});
|
||||||
|
state.entities.push(entity);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pick the packaged model whose file name matches the dashboard's naming
|
||||||
|
// (car_obu.glb / `${type}${subType}.glb`), falling back to the first model so
|
||||||
|
// a missing asset degrades to a visible vehicle rather than an invisible one.
|
||||||
|
function vehicleModelUri(record, state) {
|
||||||
|
const models = arrayValue(state.vehicleModels);
|
||||||
|
if (!models.length) return "";
|
||||||
|
const wanted = record.model;
|
||||||
|
const match = models.find((name) => String(name).split("/").pop() === wanted);
|
||||||
|
if (!match) state.missingModels.add(wanted);
|
||||||
|
return new URL(match || models[0], window.location.href).href;
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncVehicleEntity(viewer, record, state) {
|
||||||
|
const [longitude, latitude] = gcj02ToWgs84([record.longitude, record.latitude]);
|
||||||
|
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return;
|
||||||
|
const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, LIVE_VEHICLE_HEIGHT_METERS);
|
||||||
|
if (!record.entity) {
|
||||||
|
record.renderedPosition = position;
|
||||||
|
record.targetPosition = position;
|
||||||
|
record.sampleStart = Date.now();
|
||||||
|
// Interpolate between pushes so vehicles glide instead of teleporting.
|
||||||
|
const animated = new Cesium.CallbackProperty(() => {
|
||||||
|
const duration = Math.max(1, Number(record.duration) || 500);
|
||||||
|
const ratio = Math.min(1, (Date.now() - record.sampleStart) / duration);
|
||||||
|
return Cesium.Cartesian3.lerp(record.renderedPosition, record.targetPosition, ratio, new Cesium.Cartesian3());
|
||||||
|
}, false);
|
||||||
|
record.entity = viewer.entities.add({
|
||||||
|
name: record.label,
|
||||||
|
position: animated,
|
||||||
|
orientation: new Cesium.CallbackProperty(
|
||||||
|
() => vehicleOrientation(record.targetPosition, record.angle), false),
|
||||||
|
model: {
|
||||||
|
uri: vehicleModelUri(record, state),
|
||||||
|
// The full-intersection overview needs more than a couple of screen
|
||||||
|
// pixels for a car to remain distinguishable from road markings.
|
||||||
|
scale: 1.0,
|
||||||
|
minimumPixelSize: 28,
|
||||||
|
maximumScale: 8.0,
|
||||||
|
show: arrayValue(state.vehicleModels).length > 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
record.renderedPosition = record.targetPosition || position;
|
||||||
|
record.targetPosition = position;
|
||||||
|
record.sampleStart = Date.now();
|
||||||
|
}
|
||||||
|
// Stale vehicles are hidden, not removed, so the slot stays reusable.
|
||||||
|
record.entity.show = record.visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
function vehicleOrientation(position, angle) {
|
||||||
|
return Cesium.Transforms.headingPitchRollQuaternion(
|
||||||
|
position,
|
||||||
|
new Cesium.HeadingPitchRoll(Cesium.Math.toRadians((Number(angle) || 0) + LIVE_VEHICLE_HEADING_OFFSET_DEGREES), 0, 0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectCrossCode(crosses, configurations) {
|
||||||
|
const crossList = Array.isArray(crosses) ? crosses : Object.values(crosses || {}).flatMap(arrayValue);
|
||||||
|
const configuredCodes = new Set(arrayValue(configurations).map((item) => String(item.crossCode || "")).filter(Boolean));
|
||||||
|
const configuredCross = crossList.find((cross) => configuredCodes.has(String(cross?.code || cross?.crossCode || "")));
|
||||||
|
const selected = configuredCross || crossList[0];
|
||||||
|
return String(selected?.code || selected?.crossCode || arrayValue(configurations)[0]?.crossCode || "");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function isHeartbeat(value) {
|
||||||
|
return typeof value === "string" && value.includes('"heartBeat":"pong"');
|
||||||
|
}
|
||||||
|
|
||||||
|
// The dashboard parses vehicle pushes with saferEval, so the payload is not
|
||||||
|
// guaranteed to be strict JSON. Retry once through a narrow relaxation
|
||||||
|
// instead of eval, which would open arbitrary code execution in the preview.
|
||||||
|
function relaxJson(text) {
|
||||||
|
return text
|
||||||
|
.replace(/'/g, "\"")
|
||||||
|
.replace(/([{,]\s*)([A-Za-z_$][\w$]*|\d+)\s*:/g, "$1\"$2\":")
|
||||||
|
.replace(/,\s*([}\]])/g, "$1")
|
||||||
|
.replace(/:\s*(NaN|-?Infinity)\s*([,}\]])/g, ": null$2");
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseLoosePayload(value) {
|
||||||
|
if (typeof value !== "string" || isHeartbeat(value)) return null;
|
||||||
|
try { return JSON.parse(value); } catch (_) { /* retry relaxed */ }
|
||||||
|
try { return JSON.parse(relaxJson(value)); } catch (_) { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// traffic-signals.json carries no V2X phaseNo (only phaseGroup), so the two
|
||||||
|
// sides share no identifier. The only reliable join is geometry: the V2X link
|
||||||
|
// ends at the stop line (CrossTrafficLights3D.vue takes the last two points),
|
||||||
|
// and each native signal records its own stop-line point and heading.
|
||||||
|
//
|
||||||
|
// Heading semantics are fixed by the generator in scripts/lib/traffic-signals.js:
|
||||||
|
// the road axis points from the stop line into the intersection (the travel
|
||||||
|
// direction), and it emits mast = travel - 90 and face = travel + 180. The
|
||||||
|
// runtime document stores the mast value in both headingDegrees and
|
||||||
|
// mastHeadingDegrees, so the approach travel direction is recovered as
|
||||||
|
// face + 180, or equivalently heading + 90.
|
||||||
|
function signalTravelHeading(signal) {
|
||||||
|
const face = Number(signal.faceHeadingDegrees);
|
||||||
|
if (Number.isFinite(face)) return (face + 180) % 360;
|
||||||
|
const mast = Number(signal.mastHeadingDegrees ?? signal.headingDegrees);
|
||||||
|
if (Number.isFinite(mast)) return (mast + 90) % 360;
|
||||||
|
return NaN;
|
||||||
|
}
|
||||||
|
|
||||||
|
function linkStopGeometry(link) {
|
||||||
|
let geometry;
|
||||||
|
try { geometry = typeof link.geom === "string" ? JSON.parse(link.geom) : link.geom; } catch (_) { return null; }
|
||||||
|
const coordinates = arrayValue(geometry?.coordinates);
|
||||||
|
if (coordinates.length < 2) return null;
|
||||||
|
// Convert before measuring: native signals are WGS84, V2X links are GCJ-02.
|
||||||
|
const last = gcj02ToWgs84(coordinates[coordinates.length - 1]);
|
||||||
|
const previous = gcj02ToWgs84(coordinates[coordinates.length - 2]);
|
||||||
|
if (!Number.isFinite(last[0]) || !Number.isFinite(previous[0])) return null;
|
||||||
|
return { stopPoint: last, approachHeading: getAngle(previous, last) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPhaseSignalMap(links, nativeSignals, options) {
|
||||||
|
const settings = options || {};
|
||||||
|
const maxDistanceMeters = Number.isFinite(settings.maxDistanceMeters) ? settings.maxDistanceMeters : 30;
|
||||||
|
const maxHeadingDeltaDegrees = Number.isFinite(settings.maxHeadingDeltaDegrees) ? settings.maxHeadingDeltaDegrees : 45;
|
||||||
|
const override = settings.phaseSignalMap || null;
|
||||||
|
const signals = arrayValue(nativeSignals).filter((signal) => signal && signal.nodeKey);
|
||||||
|
const byPhase = new Map();
|
||||||
|
const diagnostics = [];
|
||||||
|
const unbound = [];
|
||||||
|
|
||||||
|
function addPhase(phaseNo, nodeKeys) {
|
||||||
|
const key = String(phaseNo);
|
||||||
|
const existing = byPhase.get(key) || new Set();
|
||||||
|
nodeKeys.forEach((nodeKey) => existing.add(nodeKey));
|
||||||
|
byPhase.set(key, existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
arrayValue(links).forEach((link) => {
|
||||||
|
const phases = arrayValue(link.phaseList)
|
||||||
|
.map((entry) => entry?.phase)
|
||||||
|
.filter((phase) => phase !== undefined && phase !== null);
|
||||||
|
if (!phases.length) return;
|
||||||
|
const geometry = linkStopGeometry(link);
|
||||||
|
if (!geometry) {
|
||||||
|
phases.forEach((phase) => unbound.push({ phaseNo: String(phase), linkId: link.id, reason: "link geometry unusable" }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const matches = [];
|
||||||
|
signals.forEach((signal) => {
|
||||||
|
const signalPoint = [Number(signal.stopLongitude ?? signal.longitude), Number(signal.stopLatitude ?? signal.latitude)];
|
||||||
|
if (!Number.isFinite(signalPoint[0]) || !Number.isFinite(signalPoint[1])) return;
|
||||||
|
const distanceMeters = haversineMeters(geometry.stopPoint, signalPoint);
|
||||||
|
if (distanceMeters > maxDistanceMeters) return;
|
||||||
|
const travelHeading = signalTravelHeading(signal);
|
||||||
|
const headingDeltaDegrees = angleDeltaDegrees(geometry.approachHeading, travelHeading);
|
||||||
|
if (!(headingDeltaDegrees <= maxHeadingDeltaDegrees)) return;
|
||||||
|
matches.push({ nodeKey: signal.nodeKey, distanceMeters, headingDeltaDegrees, travelHeading });
|
||||||
|
});
|
||||||
|
diagnostics.push({
|
||||||
|
linkId: link.id,
|
||||||
|
approachHeading: geometry.approachHeading,
|
||||||
|
matchedNodeKeys: matches.map((match) => match.nodeKey),
|
||||||
|
nearestDistanceMeters: matches.length ? Math.min(...matches.map((match) => match.distanceMeters)) : null,
|
||||||
|
matches,
|
||||||
|
});
|
||||||
|
// One link may light several heads on the same approach, and several
|
||||||
|
// links may share one phase; both unions are required.
|
||||||
|
if (matches.length) phases.forEach((phase) => addPhase(phase, matches.map((match) => match.nodeKey)));
|
||||||
|
else phases.forEach((phase) => unbound.push({ phaseNo: String(phase), linkId: link.id, reason: "no native signal within tolerance" }));
|
||||||
|
});
|
||||||
|
|
||||||
|
if (override && typeof override === "object") {
|
||||||
|
Object.keys(override).forEach((phaseNo) => {
|
||||||
|
const nodeKeys = arrayValue(override[phaseNo]).filter(Boolean).map(String);
|
||||||
|
if (!nodeKeys.length) return;
|
||||||
|
byPhase.set(String(phaseNo), new Set(nodeKeys));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const overridden = override ? new Set(Object.keys(override).map(String)) : new Set();
|
||||||
|
const resolved = new Map();
|
||||||
|
byPhase.forEach((nodeKeys, phaseNo) => resolved.set(phaseNo, Array.from(nodeKeys)));
|
||||||
|
return {
|
||||||
|
byPhase: resolved,
|
||||||
|
bound: resolved.size,
|
||||||
|
unbound: unbound.filter((entry) => !resolved.has(entry.phaseNo) && !overridden.has(entry.phaseNo)),
|
||||||
|
diagnostics,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseSocketJson(value) {
|
||||||
|
return parseLoosePayload(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const HEARTBEAT_MESSAGE = JSON.stringify({ heartBeat: "ping" });
|
||||||
|
const HEARTBEAT_INTERVAL_MS = 30000;
|
||||||
|
|
||||||
|
// The dashboard uses useWebSocket with a 30s {"heartBeat":"ping"} and
|
||||||
|
// autoReconnect on all three sockets. Without both, the service drops the
|
||||||
|
// connection and the scene silently goes empty after a minute.
|
||||||
|
function createSocket(options) {
|
||||||
|
const settings = options || {};
|
||||||
|
const resolveUrl = typeof settings.url === "function" ? settings.url : () => settings.url;
|
||||||
|
const factory = settings.socketFactory || ((url) => new WebSocket(url));
|
||||||
|
const setIntervalFn = settings.setIntervalFn || ((fn, ms) => setInterval(fn, ms));
|
||||||
|
const clearIntervalFn = settings.clearIntervalFn || ((handle) => clearInterval(handle));
|
||||||
|
const setTimeoutFn = settings.setTimeoutFn || ((fn, ms) => setTimeout(fn, ms));
|
||||||
|
const clearTimeoutFn = settings.clearTimeoutFn || ((handle) => clearTimeout(handle));
|
||||||
|
const heartbeatMs = Number.isFinite(settings.heartbeatMs) ? settings.heartbeatMs : HEARTBEAT_INTERVAL_MS;
|
||||||
|
const maxBackoffMs = Number.isFinite(settings.maxBackoffMs) ? settings.maxBackoffMs : 8000;
|
||||||
|
const reconnect = settings.reconnect !== false;
|
||||||
|
|
||||||
|
const state = { socket: null, heartbeat: null, retry: null, attempt: 0, disposed: false, closedByUs: false };
|
||||||
|
|
||||||
|
function stopHeartbeat() {
|
||||||
|
if (state.heartbeat === null) return;
|
||||||
|
clearIntervalFn(state.heartbeat);
|
||||||
|
state.heartbeat = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function startHeartbeat() {
|
||||||
|
stopHeartbeat();
|
||||||
|
if (!heartbeatMs) return;
|
||||||
|
state.heartbeat = setIntervalFn(() => send(HEARTBEAT_MESSAGE), heartbeatMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(data) {
|
||||||
|
const socket = state.socket;
|
||||||
|
if (!socket) return false;
|
||||||
|
if (typeof socket.readyState === "number" && socket.readyState !== 1) return false;
|
||||||
|
try { socket.send(data); return true; } catch (_) { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleReconnect() {
|
||||||
|
if (state.disposed || state.closedByUs || !reconnect) return;
|
||||||
|
const delay = Math.min(maxBackoffMs, 1000 * (2 ** state.attempt));
|
||||||
|
state.attempt += 1;
|
||||||
|
state.retry = setTimeoutFn(() => { state.retry = null; open(); }, delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
function open() {
|
||||||
|
if (state.disposed) return null;
|
||||||
|
state.closedByUs = false;
|
||||||
|
let socket;
|
||||||
|
try { socket = factory(resolveUrl()); } catch (error) {
|
||||||
|
settings.onError?.(error);
|
||||||
|
scheduleReconnect();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
state.socket = socket;
|
||||||
|
socket.onopen = () => {
|
||||||
|
state.attempt = 0;
|
||||||
|
startHeartbeat();
|
||||||
|
// Re-send the subscription frame on every (re)connect, matching the
|
||||||
|
// dashboard's onConnected. A reconnect without this receives nothing.
|
||||||
|
settings.onOpen?.({ send });
|
||||||
|
};
|
||||||
|
socket.onmessage = (event) => {
|
||||||
|
const payload = event?.data;
|
||||||
|
// The upstream sometimes marks UTF-8 JSON as a binary WS frame. DevTools
|
||||||
|
// renders that Blob as JSON, but JSON.parse cannot consume a Blob; decode
|
||||||
|
// it before applying the same dashboard payload parser.
|
||||||
|
if (typeof Blob !== "undefined" && payload instanceof Blob) {
|
||||||
|
payload.text().then((text) => settings.onMessage?.(text)).catch((error) => settings.onError?.(error));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (typeof ArrayBuffer !== "undefined" && payload instanceof ArrayBuffer) {
|
||||||
|
settings.onMessage?.(new TextDecoder().decode(payload));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
settings.onMessage?.(payload);
|
||||||
|
};
|
||||||
|
socket.onerror = (event) => settings.onError?.(event);
|
||||||
|
socket.onclose = (event) => {
|
||||||
|
stopHeartbeat();
|
||||||
|
settings.onClose?.(event);
|
||||||
|
scheduleReconnect();
|
||||||
|
};
|
||||||
|
return socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
state.closedByUs = true;
|
||||||
|
stopHeartbeat();
|
||||||
|
if (state.retry !== null) { clearTimeoutFn(state.retry); state.retry = null; }
|
||||||
|
try { state.socket?.close(); } catch (_) { /* already closed */ }
|
||||||
|
state.socket = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function dispose() {
|
||||||
|
state.disposed = true;
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
|
||||||
|
return { open, close, dispose, send, get attempt() { return state.attempt; }, get socket() { return state.socket; } };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Matches getMapBounds in CrossCars/index.vue: NW, NE, SE, SW joined by ';'.
|
||||||
|
// The camera reports WGS84 but the service filters GCJ-02, so convert.
|
||||||
|
function buildBoundsMessage(rectangle) {
|
||||||
|
if (!rectangle) return "";
|
||||||
|
const west = Number(rectangle.west);
|
||||||
|
const south = Number(rectangle.south);
|
||||||
|
const east = Number(rectangle.east);
|
||||||
|
const north = Number(rectangle.north);
|
||||||
|
if (![west, south, east, north].every(Number.isFinite)) return "";
|
||||||
|
const corners = [[west, north], [east, north], [east, south], [west, south]];
|
||||||
|
return corners
|
||||||
|
.map((corner) => wgs84ToGcj02(corner).map((value) => Number(value.toFixed(8))).join(","))
|
||||||
|
.join(";");
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeObuVehicle(value) {
|
||||||
|
const source = parseSocketJson(value);
|
||||||
|
return obuVehicleFrom(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
function obuVehicleFrom(source) {
|
||||||
|
const longitude = Number(source?.lon);
|
||||||
|
const latitude = Number(source?.lat);
|
||||||
|
const code = source?.carCode || source?.obuCode;
|
||||||
|
if (!code || !Number.isFinite(longitude) || !Number.isFinite(latitude)) return null;
|
||||||
|
return { id: `obu-${code}`, label: source.plateNumber || String(code), kind: "obu", longitude, latitude, angle: Number(source.angle) || 0, speed: Number(source.speed) || 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeObuPush(value) {
|
||||||
|
const source = parseSocketJson(value);
|
||||||
|
return { interval: source?.interval, vehicle: obuVehicleFrom(source) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTargetVehicles(value) {
|
||||||
|
return targetVehiclesFrom(parseSocketJson(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTargetPush(value) {
|
||||||
|
const source = parseSocketJson(value);
|
||||||
|
return { interval: source?.interval, vehicles: targetVehiclesFrom(source) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function targetVehiclesFrom(source) {
|
||||||
|
const devices = source?.data;
|
||||||
|
if (!devices || typeof devices !== "object" || Array.isArray(devices)) return [];
|
||||||
|
return Object.keys(devices).flatMap((deviceId) => arrayValue(devices[deviceId]).map((target) => {
|
||||||
|
const longitude = Number(target?.longitude);
|
||||||
|
const latitude = Number(target?.latitude);
|
||||||
|
if (!target?.id || !Number.isFinite(longitude) || !Number.isFinite(latitude)) return null;
|
||||||
|
// Mirrors useTargetCars.ts: a type 1 target with no subType is subType 1.
|
||||||
|
const type = target.type || 1;
|
||||||
|
const subType = target.subType || 1;
|
||||||
|
return { id: `${deviceId}-${target.id}-${type}${subType}`, label: target.plate || `${deviceId}-${target.id}`, kind: "target", longitude, latitude, angle: Number(target.angle) || 0, speed: Number(target.speed) || 0, type, subType };
|
||||||
|
}).filter(Boolean));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The dashboard's CrossCars template renders OBU with 11.glb, while target
|
||||||
|
// vehicles retain their `${type}${subType}.glb` model selection.
|
||||||
|
function modelNameFor(vehicle) {
|
||||||
|
if (!vehicle) return "";
|
||||||
|
if (vehicle.kind === "obu") return "11.glb";
|
||||||
|
return `${vehicle.type || 1}${vehicle.subType || 1}.glb`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolvePushInterval(value) {
|
||||||
|
const parsed = Number(value);
|
||||||
|
return !Number.isFinite(parsed) || parsed === 0 ? 500 : parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vehicles are hidden rather than removed once a push goes stale, and hidden
|
||||||
|
// slots are reused, matching hideTimeoutObuCars / hideTimeoutTargetCars.
|
||||||
|
function createVehicleRegistry(options) {
|
||||||
|
const settings = options || {};
|
||||||
|
const now = typeof settings.now === "function" ? settings.now : () => Date.now();
|
||||||
|
const records = [];
|
||||||
|
const index = new Map();
|
||||||
|
let interval = 1000;
|
||||||
|
|
||||||
|
function ingest(vehicles, pushInterval) {
|
||||||
|
interval = resolvePushInterval(pushInterval);
|
||||||
|
const timeStamp = now();
|
||||||
|
const summary = { added: 0, updated: 0, reused: 0 };
|
||||||
|
arrayValue(vehicles).forEach((vehicle) => {
|
||||||
|
if (!vehicle || !vehicle.id) return;
|
||||||
|
const model = modelNameFor(vehicle);
|
||||||
|
const next = { ...vehicle, model, visible: true, timeStamp, duration: interval };
|
||||||
|
const existing = index.get(vehicle.id);
|
||||||
|
if (existing) {
|
||||||
|
Object.assign(existing, next);
|
||||||
|
summary.updated += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const slot = records.find((record) => !record.visible && record.model === model);
|
||||||
|
if (slot) {
|
||||||
|
index.delete(slot.id);
|
||||||
|
Object.assign(slot, next);
|
||||||
|
index.set(vehicle.id, slot);
|
||||||
|
summary.reused += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const created = { ...next };
|
||||||
|
records.push(created);
|
||||||
|
index.set(vehicle.id, created);
|
||||||
|
summary.added += 1;
|
||||||
|
});
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sweep(atMs) {
|
||||||
|
const timeStamp = Number.isFinite(atMs) ? atMs : now();
|
||||||
|
const hidden = [];
|
||||||
|
records.forEach((record) => {
|
||||||
|
if (!record.visible) return;
|
||||||
|
if (Math.abs(timeStamp - record.timeStamp) >= interval * 1.5) {
|
||||||
|
record.visible = false;
|
||||||
|
hidden.push(record.id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clear() {
|
||||||
|
records.length = 0;
|
||||||
|
index.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ingest, sweep, clear,
|
||||||
|
list: () => records.slice(),
|
||||||
|
get interval() { return interval; },
|
||||||
|
get size() { return records.length; },
|
||||||
|
get visibleSize() { return records.filter((record) => record.visible).length; },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize the push into {nodeKeys, color, countDown} before handing it to
|
||||||
|
// the preview, so the lamp dictionary lives in exactly one place.
|
||||||
|
function signalEntriesFrom(lamps, phaseSignals) {
|
||||||
|
return arrayValue(lamps).map((lamp) => {
|
||||||
|
const phaseNo = String(lamp?.phaseNo ?? lamp?.phase ?? "");
|
||||||
|
return {
|
||||||
|
phaseNo,
|
||||||
|
nodeKeys: arrayValue(phaseSignals?.get?.(phaseNo)),
|
||||||
|
color: lampColorName(lamp?.status),
|
||||||
|
countDown: Number(lamp?.countDown),
|
||||||
|
};
|
||||||
|
}).filter((entry) => entry.phaseNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateSignalPhases(value, state) {
|
||||||
|
const payload = parseLoosePayload(value);
|
||||||
|
if (!payload) {
|
||||||
|
if (!isHeartbeat(value)) state.parseFailures += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const lamps = arrayValue(payload.lamps);
|
||||||
|
if (!lamps.length) return;
|
||||||
|
const entries = signalEntriesFrom(lamps, state.phaseSignals);
|
||||||
|
state.setSignalState?.(entries);
|
||||||
|
entries.forEach((entry) => {
|
||||||
|
// Every approach on this phase, not just the last one registered.
|
||||||
|
arrayValue(state.linkEntitiesByPhase.get(entry.phaseNo)).forEach((entity) => {
|
||||||
|
if (!entity?.polyline) return;
|
||||||
|
entity.polyline.material = lampCesiumColor(entry.color).withAlpha(.9);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lamp status codes come from the V2X dashboard's lightStatusColorDict
|
||||||
|
// (HologramCross/components/utils.ts). Do not reinterpret them as 1/2/3.
|
||||||
|
const LAMP_STATUS = { 11: "off", 21: "red", 22: "yellow", 23: "green", 31: "other" };
|
||||||
|
|
||||||
|
function lampColorName(status) {
|
||||||
|
return LAMP_STATUS[Number(status)] || "other";
|
||||||
|
}
|
||||||
|
|
||||||
|
function lampCesiumColor(color) {
|
||||||
|
switch (color) {
|
||||||
|
case "red": return Cesium.Color.fromCssColorString("#f45f5f");
|
||||||
|
case "yellow": return Cesium.Color.fromCssColorString("rgb(238, 166, 12)");
|
||||||
|
case "green": return Cesium.Color.fromCssColorString("rgb(8, 244, 8)");
|
||||||
|
case "off": return Cesium.Color.fromCssColorString("#eeeeee");
|
||||||
|
default: return Cesium.Color.GRAY;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function arrayValue(value) { return Array.isArray(value) ? value : []; }
|
||||||
|
function joinUrl(base, path) { return `${String(base || "").replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`; }
|
||||||
|
function toWebSocketUrl(url, token) {
|
||||||
|
const resolved = new URL(url, window.location.href);
|
||||||
|
resolved.protocol = resolved.protocol === "https:" ? "wss:" : "ws:";
|
||||||
|
resolved.searchParams.set("authorization", token);
|
||||||
|
return resolved.href;
|
||||||
|
}
|
||||||
|
|
||||||
|
function transformLat(x, y) { let value = -100 + 2 * x + 3 * y + .2 * y * y + .1 * x * y + .2 * Math.sqrt(Math.abs(x)); value += (20 * Math.sin(6 * x * PI) + 20 * Math.sin(2 * x * PI)) * 2 / 3; value += (20 * Math.sin(y * PI) + 40 * Math.sin(y / 3 * PI)) * 2 / 3; value += (160 * Math.sin(y / 12 * PI) + 320 * Math.sin(y * PI / 30)) * 2 / 3; return value; }
|
||||||
|
function transformLon(x, y) { let value = 300 + x + 2 * y + .1 * x * x + .1 * x * y + .1 * Math.sqrt(Math.abs(x)); value += (20 * Math.sin(6 * x * PI) + 20 * Math.sin(2 * x * PI)) * 2 / 3; value += (20 * Math.sin(x * PI) + 40 * Math.sin(x / 3 * PI)) * 2 / 3; value += (150 * Math.sin(x / 12 * PI) + 300 * Math.sin(x / 30 * PI)) * 2 / 3; return value; }
|
||||||
|
function gcj02ToWgs84(coordinate) { const longitude = Number(coordinate[0]); const latitude = Number(coordinate[1]); if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return [NaN, NaN]; const dLat = transformLat(longitude - 105, latitude - 35); const dLon = transformLon(longitude - 105, latitude - 35); const radLat = latitude / 180 * PI; const magic = 1 - EARTH_EE * Math.sin(radLat) ** 2; const sqrtMagic = Math.sqrt(magic); return [longitude - dLon * 180 / (EARTH_A / sqrtMagic * Math.cos(radLat) * PI), latitude - dLat * 180 / (EARTH_A * (1 - EARTH_EE) / (magic * sqrtMagic) * PI)]; }
|
||||||
|
|
||||||
|
// Forward transform, needed for the OBU bounds message: the service filters
|
||||||
|
// by GCJ-02, but the Cesium camera reports WGS84.
|
||||||
|
function wgs84ToGcj02(coordinate) {
|
||||||
|
const longitude = Number(coordinate[0]);
|
||||||
|
const latitude = Number(coordinate[1]);
|
||||||
|
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return [NaN, NaN];
|
||||||
|
const dLat = transformLat(longitude - 105, latitude - 35);
|
||||||
|
const dLon = transformLon(longitude - 105, latitude - 35);
|
||||||
|
const radLat = latitude / 180 * PI;
|
||||||
|
const magic = 1 - EARTH_EE * Math.sin(radLat) ** 2;
|
||||||
|
const sqrtMagic = Math.sqrt(magic);
|
||||||
|
return [
|
||||||
|
longitude + dLon * 180 / (EARTH_A / sqrtMagic * Math.cos(radLat) * PI),
|
||||||
|
latitude + dLat * 180 / (EARTH_A * (1 - EARTH_EE) / (magic * sqrtMagic) * PI),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bearing from north, 0-360. Mirrors HologramCross/components/utils.ts getAngle.
|
||||||
|
function getAngle(start, end) {
|
||||||
|
const rad = PI / 180;
|
||||||
|
const lat1 = Number(start[1]) * rad;
|
||||||
|
const lat2 = Number(end[1]) * rad;
|
||||||
|
const lon1 = Number(start[0]) * rad;
|
||||||
|
const lon2 = Number(end[0]) * rad;
|
||||||
|
const a = Math.sin(lon2 - lon1) * Math.cos(lat2);
|
||||||
|
const b = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
|
||||||
|
const degrees = (Math.atan2(a, b) % (2 * PI)) * 180 / PI;
|
||||||
|
return degrees > 0 ? degrees : degrees + 360;
|
||||||
|
}
|
||||||
|
|
||||||
|
function angleDeltaDegrees(a, b) {
|
||||||
|
const delta = Math.abs(((Number(a) - Number(b)) % 360 + 540) % 360 - 180);
|
||||||
|
return Number.isFinite(delta) ? delta : NaN;
|
||||||
|
}
|
||||||
|
|
||||||
|
function haversineMeters(a, b) {
|
||||||
|
const rad = PI / 180;
|
||||||
|
const lat1 = Number(a[1]) * rad;
|
||||||
|
const lat2 = Number(b[1]) * rad;
|
||||||
|
const dLat = lat2 - lat1;
|
||||||
|
const dLon = (Number(b[0]) - Number(a[0])) * rad;
|
||||||
|
const h = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
|
||||||
|
return 6371008.8 * 2 * Math.asin(Math.min(1, Math.sqrt(h)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The V2X login contract uses MD5. Keep the implementation local so the
|
||||||
|
// generated preview stays dependency-free and credentials are never sent plain.
|
||||||
|
function md5(value) {
|
||||||
|
const source = unescape(encodeURIComponent(String(value)));
|
||||||
|
const words = [];
|
||||||
|
for (let index = 0; index < source.length; index += 1) words[index >> 2] = (words[index >> 2] || 0) | (source.charCodeAt(index) << ((index % 4) * 8));
|
||||||
|
const bitLength = source.length * 8;
|
||||||
|
words[bitLength >> 5] = (words[bitLength >> 5] || 0) | (128 << (bitLength % 32));
|
||||||
|
words[(((bitLength + 64) >>> 9) << 4) + 14] = bitLength;
|
||||||
|
const shifts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];
|
||||||
|
let a0 = 1732584193;
|
||||||
|
let b0 = -271733879;
|
||||||
|
let c0 = -1732584194;
|
||||||
|
let d0 = 271733878;
|
||||||
|
for (let offset = 0; offset < words.length; offset += 16) {
|
||||||
|
let a = a0;
|
||||||
|
let b = b0;
|
||||||
|
let c = c0;
|
||||||
|
let d = d0;
|
||||||
|
for (let index = 0; index < 64; index += 1) {
|
||||||
|
let f;
|
||||||
|
let g;
|
||||||
|
if (index < 16) { f = (b & c) | (~b & d); g = index; }
|
||||||
|
else if (index < 32) { f = (d & b) | (~d & c); g = (5 * index + 1) % 16; }
|
||||||
|
else if (index < 48) { f = b ^ c ^ d; g = (3 * index + 5) % 16; }
|
||||||
|
else { f = c ^ (b | ~d); g = (7 * index) % 16; }
|
||||||
|
const nextD = d;
|
||||||
|
d = c;
|
||||||
|
c = b;
|
||||||
|
b = add(b, rotate(add(add(a, f), add(words[offset + g] || 0, Math.floor(Math.abs(Math.sin(index + 1)) * 4294967296))), shifts[index]));
|
||||||
|
a = nextD;
|
||||||
|
}
|
||||||
|
a0 = add(a0, a);
|
||||||
|
b0 = add(b0, b);
|
||||||
|
c0 = add(c0, c);
|
||||||
|
d0 = add(d0, d);
|
||||||
|
}
|
||||||
|
return [a0, b0, c0, d0].map(hex).join("");
|
||||||
|
}
|
||||||
|
function add(a, b) { return (a + b) & 0xFFFFFFFF; }
|
||||||
|
function rotate(value, count) { return (value << count) | (value >>> (32 - count)); }
|
||||||
|
function hex(value) { let output = ""; for (let index = 0; index < 4; index += 1) output += (`0${(value >>> (index * 8) & 255).toString(16)}`).slice(-2); return output; }
|
||||||
|
|
||||||
|
createV2xCesiumOverlay.utils = {
|
||||||
|
gcj02ToWgs84, wgs84ToGcj02, joinUrl, md5, toWebSocketUrl,
|
||||||
|
normalizeObuVehicle, normalizeObuPush, normalizeTargetVehicles, normalizeTargetPush,
|
||||||
|
selectCrossCode,
|
||||||
|
lampColorName, parseLoosePayload, isHeartbeat, signalEntriesFrom,
|
||||||
|
getAngle, angleDeltaDegrees, haversineMeters,
|
||||||
|
buildPhaseSignalMap, linkStopGeometry, signalTravelHeading,
|
||||||
|
createVehicleRegistry, modelNameFor, resolvePushInterval,
|
||||||
|
createSocket, buildBoundsMessage,
|
||||||
|
HEARTBEAT_MESSAGE, HEARTBEAT_INTERVAL_MS,
|
||||||
|
};
|
||||||
|
window.createV2xCesiumOverlay = createV2xCesiumOverlay;
|
||||||
|
}());
|
||||||
@@ -12,8 +12,12 @@ const VEHICLE_IDS = [
|
|||||||
"truck_a03_001",
|
"truck_a03_001",
|
||||||
];
|
];
|
||||||
const LIBRARY_ROOT = path.resolve(__dirname, "..", "..", "assets", "models", "custom", "lowpoly_cars");
|
const LIBRARY_ROOT = path.resolve(__dirname, "..", "..", "assets", "models", "custom", "lowpoly_cars");
|
||||||
|
const V2X_LIBRARY_ROOT = path.resolve(__dirname, "..", "..", "assets", "models", "v2x-vehicles");
|
||||||
const TEXTURE_NAME = "color_512x512.jpg";
|
const TEXTURE_NAME = "color_512x512.jpg";
|
||||||
const REVERSED_MODEL_IDS = new Set(["truck_a03_001"]);
|
const REVERSED_MODEL_IDS = new Set(["truck_a03_001"]);
|
||||||
|
// These are the dashboard's published vehicle assets. OBU rendering uses
|
||||||
|
// 11.glb in CrossCars/index.vue; target vehicles use `${type}${subType}.glb`.
|
||||||
|
const V2X_VEHICLE_MODEL_NAMES = ["11.glb", "12.glb", "13.glb", "14.glb", "15.glb", "16.glb", "17.glb", "31.glb", "221.glb", "222.glb"];
|
||||||
|
|
||||||
function writePreviewVehicleLibrary(outDir, fileStem) {
|
function writePreviewVehicleLibrary(outDir, fileStem) {
|
||||||
const textureOutput = `${fileStem}-vehicle-texture.jpg`;
|
const textureOutput = `${fileStem}-vehicle-texture.jpg`;
|
||||||
@@ -46,4 +50,21 @@ function writePreviewVehicleLibrary(outDir, fileStem) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { VEHICLE_IDS, REVERSED_MODEL_IDS, writePreviewVehicleLibrary };
|
function writePreviewV2xVehicleLibrary(outDir) {
|
||||||
|
const targetDir = path.join(outDir, "v2x-vehicles");
|
||||||
|
fs.mkdirSync(targetDir, { recursive: true });
|
||||||
|
for (const modelName of V2X_VEHICLE_MODEL_NAMES) {
|
||||||
|
const source = path.join(V2X_LIBRARY_ROOT, modelName);
|
||||||
|
if (!fs.existsSync(source)) throw new Error(`V2X vehicle model not found: ${source}`);
|
||||||
|
fs.copyFileSync(source, path.join(targetDir, modelName));
|
||||||
|
}
|
||||||
|
return V2X_VEHICLE_MODEL_NAMES.map((modelName) => `v2x-vehicles/${modelName}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
VEHICLE_IDS,
|
||||||
|
REVERSED_MODEL_IDS,
|
||||||
|
V2X_VEHICLE_MODEL_NAMES,
|
||||||
|
writePreviewVehicleLibrary,
|
||||||
|
writePreviewV2xVehicleLibrary,
|
||||||
|
};
|
||||||
@@ -4,10 +4,12 @@
|
|||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const http = require("http");
|
const http = require("http");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
|
const { execFileSync } = require("child_process");
|
||||||
const { readAreaConfig } = require("./lib/area-config");
|
const { readAreaConfig } = require("./lib/area-config");
|
||||||
const { loadOverrides, validateOverrides, writeJsonAtomic } = require("./lib/native-road");
|
const { loadOverrides, validateOverrides, writeJsonAtomic } = require("./lib/native-road");
|
||||||
const { generate, validateDocument, runtime } = require("./lib/native-traffic-signals");
|
const { generate, validateDocument, runtime } = require("./lib/native-traffic-signals");
|
||||||
const { compileArea, parseArgs } = require("./compile-native-roads");
|
const { compileArea, parseArgs } = require("./compile-native-roads");
|
||||||
|
const { convertGeoJson } = require("./lib/gaode-junction-reference");
|
||||||
|
|
||||||
const repoRoot = path.resolve(__dirname, "..");
|
const repoRoot = path.resolve(__dirname, "..");
|
||||||
|
|
||||||
@@ -16,23 +18,28 @@ function main() {
|
|||||||
const configPath = path.resolve(args.config || path.join(repoRoot, "config", "areas", "nantaizi-lake-innovation-valley.json"));
|
const configPath = path.resolve(args.config || path.join(repoRoot, "config", "areas", "nantaizi-lake-innovation-valley.json"));
|
||||||
if (args.noCompile !== "true") compileArea(configPath);
|
if (args.noCompile !== "true") compileArea(configPath);
|
||||||
const area = readAreaConfig(configPath, { repoRoot });
|
const area = readAreaConfig(configPath, { repoRoot });
|
||||||
|
const junctionReference = args.junctionReference ? readJunctionReference(path.resolve(args.junctionReference)) : null;
|
||||||
|
// `--debug` surfaces advisory compiler findings that have no geometry layer of
|
||||||
|
// their own — currently the complex-junction candidates. Off by default so the
|
||||||
|
// normal editing view stays uncluttered.
|
||||||
|
const debug = args.debug === "true";
|
||||||
const port = Number(args.port || 8787);
|
const port = Number(args.port || 8787);
|
||||||
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error("--port must be an integer in [1024, 65535].");
|
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error("--port must be an integer in [1024, 65535].");
|
||||||
const server = http.createServer((request, response) => handle(request, response, area, configPath));
|
const server = http.createServer((request, response) => handle(request, response, area, configPath, junctionReference, debug));
|
||||||
server.on("error", (error) => {
|
server.on("error", (error) => {
|
||||||
console.error(`Road Workbench failed to listen: ${error.message}`);
|
console.error(`Road Workbench failed to listen: ${error.message}`);
|
||||||
process.exitCode = 1;
|
process.exitCode = 1;
|
||||||
});
|
});
|
||||||
server.listen(port, "127.0.0.1", () => console.log(`Road Workbench: http://127.0.0.1:${port}/`));
|
server.listen(port, "127.0.0.1", () => console.log(`Road Workbench: http://127.0.0.1:${port}/${debug ? " (debug: 复杂路口候选已开启)" : ""}`));
|
||||||
}
|
}
|
||||||
|
|
||||||
function handle(request, response, area, configPath) {
|
function handle(request, response, area, configPath, junctionReference, debug = false) {
|
||||||
const url = new URL(request.url, "http://127.0.0.1");
|
const url = new URL(request.url, "http://127.0.0.1");
|
||||||
if (request.method === "GET" && url.pathname === "/") return sendFile(response, path.join(repoRoot, "scripts", "workbench", "index.html"), "text/html; charset=utf-8");
|
if (request.method === "GET" && url.pathname === "/") return sendFile(response, path.join(repoRoot, "scripts", "workbench", "index.html"), "text/html; charset=utf-8");
|
||||||
if (request.method === "GET" && url.pathname === "/app.js") return sendFile(response, path.join(repoRoot, "scripts", "workbench", "app.js"), "text/javascript; charset=utf-8");
|
if (request.method === "GET" && url.pathname === "/app.js") return sendFile(response, path.join(repoRoot, "scripts", "workbench", "app.js"), "text/javascript; charset=utf-8");
|
||||||
if (request.method === "GET" && url.pathname === "/app.css") return sendFile(response, path.join(repoRoot, "scripts", "workbench", "app.css"), "text/css; charset=utf-8");
|
if (request.method === "GET" && url.pathname === "/app.css") return sendFile(response, path.join(repoRoot, "scripts", "workbench", "app.css"), "text/css; charset=utf-8");
|
||||||
if (request.method === "GET" && url.pathname.startsWith("/vendor/")) return sendVendorFile(response, url.pathname);
|
if (request.method === "GET" && url.pathname.startsWith("/vendor/")) return sendVendorFile(response, url.pathname);
|
||||||
if (request.method === "GET" && url.pathname === "/api/state") return sendJson(response, 200, state(area));
|
if (request.method === "GET" && url.pathname === "/api/state") return sendJson(response, 200, state(area, junctionReference, debug));
|
||||||
if (request.method === "POST" && url.pathname === "/api/traffic-signals") return readBody(request).then((body) => {
|
if (request.method === "POST" && url.pathname === "/api/traffic-signals") return readBody(request).then((body) => {
|
||||||
const document = validateDocument(body, fs.readFileSync(area.input, "utf8"));
|
const document = validateDocument(body, fs.readFileSync(area.input, "utf8"));
|
||||||
writeJsonAtomic(area.outputs.nativeTrafficSignals, document);
|
writeJsonAtomic(area.outputs.nativeTrafficSignals, document);
|
||||||
@@ -53,21 +60,101 @@ function handle(request, response, area, configPath) {
|
|||||||
writeJsonAtomic(area.outputs.nativeRoadOverrides, overrides);
|
writeJsonAtomic(area.outputs.nativeRoadOverrides, overrides);
|
||||||
sendJson(response, 200, { ok: true, overrides });
|
sendJson(response, 200, { ok: true, overrides });
|
||||||
}).catch((error) => sendJson(response, 400, { ok: false, error: error.message }));
|
}).catch((error) => sendJson(response, 400, { ok: false, error: error.message }));
|
||||||
|
if (request.method === "POST" && url.pathname === "/api/junction-clusters") return readBody(request).then((body) => {
|
||||||
|
if (!debug) throw new Error("该接口仅在 --debug 模式下可用。");
|
||||||
|
const added = addJunctionCluster(configPath, body, readCompiled(area));
|
||||||
|
compileFresh(configPath);
|
||||||
|
const refreshed = readAreaConfig(configPath, { repoRoot });
|
||||||
|
sendJson(response, 200, { ok: true, added, ...state(refreshed, junctionReference, debug) });
|
||||||
|
}).catch((error) => sendJson(response, 400, { ok: false, error: error.message }));
|
||||||
if (request.method === "POST" && url.pathname === "/api/compile") return Promise.resolve().then(() => {
|
if (request.method === "POST" && url.pathname === "/api/compile") return Promise.resolve().then(() => {
|
||||||
compileArea(configPath);
|
compileFresh(configPath);
|
||||||
sendJson(response, 200, state(area));
|
sendJson(response, 200, state(area, junctionReference));
|
||||||
}).catch((error) => sendJson(response, 500, { ok: false, error: error.message }));
|
}).catch((error) => sendJson(response, 500, { ok: false, error: error.message }));
|
||||||
sendJson(response, 404, { error: "Not found" });
|
sendJson(response, 404, { error: "Not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
function state(area) {
|
function state(area, junctionReference = null, debug = false) {
|
||||||
const nativeDir = area.outputs.nativeRoadDir;
|
const nativeDir = area.outputs.nativeRoadDir;
|
||||||
const osm2streetsRoadSurface = path.join(area.outputs.geojsonDir, "road_surface.geojson");
|
const osm2streetsRoadSurface = path.join(area.outputs.geojsonDir, "road_surface.geojson");
|
||||||
const trafficSignals = fs.existsSync(area.outputs.nativeTrafficSignals)
|
const trafficSignals = fs.existsSync(area.outputs.nativeTrafficSignals)
|
||||||
? validateDocument(readJson(area.outputs.nativeTrafficSignals), fs.readFileSync(area.input, "utf8"))
|
? validateDocument(readJson(area.outputs.nativeTrafficSignals), fs.readFileSync(area.input, "utf8"))
|
||||||
: { schema: "native-traffic-signals/v1", provenance: "empty", assemblies: { type: "FeatureCollection", features: [] } };
|
: { schema: "native-traffic-signals/v1", provenance: "empty", assemblies: { type: "FeatureCollection", features: [] } };
|
||||||
const trafficRuntime = runtime(trafficSignals);
|
const trafficRuntime = runtime(trafficSignals);
|
||||||
return { areaId: area.id, compiled: readCompiled(area), overrides: loadOverrides(area.outputs.nativeRoadOverrides), trafficSignals, trafficRuntime, comparison: readJson(path.join(nativeDir, "comparison.json")), layers: { nativeRoadSurface: readLayer(path.join(nativeDir, "layers", "road_surface.geojson")), edgeLines: readLayer(path.join(nativeDir, "layers", "edge_lines.geojson")), nativeSidewalkSurface: readLayer(path.join(nativeDir, "layers", "sidewalk_surface.geojson")), nativeIntersectionSurface: readLayer(path.join(nativeDir, "layers", "intersection_surface.geojson")), laneCenterlines: readLayer(path.join(nativeDir, "layers", "lane_centerlines.geojson")), laneSeparators: readLayer(path.join(nativeDir, "layers", "lane_separators.geojson")), centerLines: readLayer(path.join(nativeDir, "layers", "center_lines.geojson")), directionArrows: readLayer(path.join(nativeDir, "layers", "direction_arrows.geojson")), turnArrows: readLayer(path.join(nativeDir, "layers", "turn_arrows.geojson")), crosswalks: readLayer(path.join(nativeDir, "layers", "crosswalks.geojson")), vehicleStopLines: readLayer(path.join(nativeDir, "layers", "vehicle_stop_lines.geojson")), connectors: readLayer(path.join(nativeDir, "layers", "connectors.geojson")), osm2streetsRoadSurface: fs.existsSync(osm2streetsRoadSurface) ? readLayer(osm2streetsRoadSurface) : null } };
|
const compiled = readCompiled(area);
|
||||||
|
return { areaId: area.id, debug: debug ? { junctionCandidates: junctionCandidates(compiled) } : null, compiled, overrides: loadOverrides(area.outputs.nativeRoadOverrides), trafficSignals, trafficRuntime, comparison: readJson(path.join(nativeDir, "comparison.json")), junctionReference, layers: { nativeRoadSurface: readLayer(path.join(nativeDir, "layers", "road_surface.geojson")), edgeLines: readLayer(path.join(nativeDir, "layers", "edge_lines.geojson")), nativeSidewalkSurface: readLayer(path.join(nativeDir, "layers", "sidewalk_surface.geojson")), nativeIntersectionSurface: readLayer(path.join(nativeDir, "layers", "intersection_surface.geojson")), laneCenterlines: readLayer(path.join(nativeDir, "layers", "lane_centerlines.geojson")), laneSeparators: readLayer(path.join(nativeDir, "layers", "lane_separators.geojson")), centerLines: readLayer(path.join(nativeDir, "layers", "center_lines.geojson")), directionArrows: readLayer(path.join(nativeDir, "layers", "direction_arrows.geojson")), turnArrows: readLayer(path.join(nativeDir, "layers", "turn_arrows.geojson")), crosswalks: readLayer(path.join(nativeDir, "layers", "crosswalks.geojson")), vehicleStopLines: readLayer(path.join(nativeDir, "layers", "vehicle_stop_lines.geojson")), connectors: readLayer(path.join(nativeDir, "layers", "connectors.geojson")), osm2streetsRoadSurface: fs.existsSync(osm2streetsRoadSurface) ? readLayer(osm2streetsRoadSurface) : null } };
|
||||||
|
}
|
||||||
|
// The compiler reports candidates as advisory diagnostics. Lift them into their
|
||||||
|
// own payload with a stable index so the map can label them "#1, #2, ..." and
|
||||||
|
// the inspector can offer a ready-to-paste cluster配置.
|
||||||
|
// Append one detected cluster to the hand-authored area config. The candidate
|
||||||
|
// must still be present in the latest compile, so a stale browser tab cannot
|
||||||
|
// write a cluster that no longer exists. The edited config is validated by the
|
||||||
|
// real loader before it replaces the file: an invalid write would break every
|
||||||
|
// later command, and the file is git-tracked so a bad accept stays revertible.
|
||||||
|
function addJunctionCluster(configPath, body, compiled) {
|
||||||
|
const index = Number(body?.index);
|
||||||
|
if (!Number.isInteger(index)) throw new Error("请求缺少候选编号 index。");
|
||||||
|
const candidate = junctionCandidates(compiled).find((item) => item.index === index);
|
||||||
|
if (!candidate) throw new Error(`候选 #${index} 不在最新一次编译结果里,请刷新页面后重试。`);
|
||||||
|
const raw = readJson(configPath);
|
||||||
|
const templates = raw.nativeRoad?.junctionTemplates;
|
||||||
|
if (!templates) throw new Error("区域配置缺少 nativeRoad.junctionTemplates,请先手工建立该节点。");
|
||||||
|
const clusters = Array.isArray(templates.clusters) ? templates.clusters : [];
|
||||||
|
const taken = new Set(clusters.flatMap((cluster) => (cluster.nodeIds || []).map(String)));
|
||||||
|
const clash = candidate.nodeIds.filter((nodeId) => taken.has(String(nodeId)));
|
||||||
|
if (clash.length) throw new Error(`节点 ${clash.join("、")} 已属于其他复杂路口配置。`);
|
||||||
|
const id = uniqueClusterId(`cluster-${candidate.nodeIds[0]}`, new Set(clusters.map((cluster) => cluster.id)));
|
||||||
|
const cluster = {
|
||||||
|
id,
|
||||||
|
template: candidate.template,
|
||||||
|
coreRadiusMeters: candidate.coreRadiusMeters,
|
||||||
|
cornerRadiusMeters: 12,
|
||||||
|
outerRadiusExtraMeters: 18,
|
||||||
|
nodeIds: candidate.nodeIds.map(String),
|
||||||
|
};
|
||||||
|
const next = { ...raw, nativeRoad: { ...raw.nativeRoad, junctionTemplates: { ...templates, enabled: true, clusters: [...clusters, cluster] } } };
|
||||||
|
const staging = `${configPath}.candidate-${process.pid}.json`;
|
||||||
|
fs.writeFileSync(staging, `${JSON.stringify(next, null, 2)}\n`);
|
||||||
|
try {
|
||||||
|
readAreaConfig(staging, { repoRoot });
|
||||||
|
} catch (error) {
|
||||||
|
fs.unlinkSync(staging);
|
||||||
|
throw new Error(`写入后的配置无法通过校验,已放弃:${error.message}`);
|
||||||
|
}
|
||||||
|
fs.unlinkSync(staging);
|
||||||
|
writeJsonAtomic(configPath, next);
|
||||||
|
return cluster;
|
||||||
|
}
|
||||||
|
function uniqueClusterId(base, taken) {
|
||||||
|
if (!taken.has(base)) return base;
|
||||||
|
for (let suffix = 2; suffix < 100; suffix += 1) if (!taken.has(`${base}-${suffix}`)) return `${base}-${suffix}`;
|
||||||
|
throw new Error("无法生成唯一的 cluster id。");
|
||||||
|
}
|
||||||
|
|
||||||
|
function junctionCandidates(compiled) {
|
||||||
|
return (compiled?.diagnostics || [])
|
||||||
|
.filter((item) => item.rule === "complex-junction-candidate" && item.suggestedCluster)
|
||||||
|
.sort((first, second) => second.suggestedCluster.nodeCount - first.suggestedCluster.nodeCount || first.suggestedCluster.diameterMeters - second.suggestedCluster.diameterMeters)
|
||||||
|
.map((item, index) => ({ index: index + 1, id: item.id, message: item.message, coordinate: item.geometry?.coordinates || null, ...item.suggestedCluster }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function compileFresh(configPath) {
|
||||||
|
try {
|
||||||
|
return execFileSync(process.execPath, [path.join(repoRoot, "scripts", "compile-native-roads.js"), "--config", configPath], {
|
||||||
|
cwd: repoRoot,
|
||||||
|
encoding: "utf8",
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const detail = String(error.stderr || error.stdout || error.message || "native compilation failed").trim();
|
||||||
|
throw new Error(`Native road compilation failed: ${detail}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function readJunctionReference(file) {
|
||||||
|
if (!fs.existsSync(file)) throw new Error(`Junction reference not found: ${file}`);
|
||||||
|
const converted = convertGeoJson(JSON.parse(fs.readFileSync(file, "utf8")));
|
||||||
|
return { source: file, coordinateSystem: "GCJ-02", converted };
|
||||||
}
|
}
|
||||||
function readCompiled(area) { return readJson(path.join(area.outputs.nativeRoadDir, "compiled.json")); }
|
function readCompiled(area) { return readJson(path.join(area.outputs.nativeRoadDir, "compiled.json")); }
|
||||||
function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
|
function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
|
||||||
|
|||||||
@@ -64,6 +64,22 @@ assert.equal(
|
|||||||
assert.equal(normalizeAreaConfig({ ...base, budget: { nodes: 800 } }).budget.glbNodes, 800);
|
assert.equal(normalizeAreaConfig({ ...base, budget: { nodes: 800 } }).budget.glbNodes, 800);
|
||||||
assert.equal(normalizeAreaConfig(base).stages.intermediates, false);
|
assert.equal(normalizeAreaConfig(base).stages.intermediates, false);
|
||||||
assert.equal(normalizeAreaConfig(base).blender.roadProvider, "native");
|
assert.equal(normalizeAreaConfig(base).blender.roadProvider, "native");
|
||||||
|
assert.deepEqual(normalizeAreaConfig(base).v2xPreview, {
|
||||||
|
enabled: false,
|
||||||
|
apiBaseUrl: "/api",
|
||||||
|
wsBaseUrl: "/websocket",
|
||||||
|
crossCode: "",
|
||||||
|
});
|
||||||
|
assert.deepEqual(normalizeAreaConfig({ ...base, v2xPreview: { enabled: false, apiBaseUrl: "/v2x-api/", wsBaseUrl: "/v2x-ws", crossCode: "420100023333" } }).v2xPreview, {
|
||||||
|
enabled: false,
|
||||||
|
apiBaseUrl: "/v2x-api/",
|
||||||
|
wsBaseUrl: "/v2x-ws",
|
||||||
|
crossCode: "420100023333",
|
||||||
|
});
|
||||||
|
assert.throws(
|
||||||
|
() => normalizeAreaConfig({ ...base, v2xPreview: "enabled" }),
|
||||||
|
/v2xPreview must be an object/,
|
||||||
|
);
|
||||||
assert.equal(normalizeAreaConfig({ ...base, blender: { roadProvider: "native" } }).blender.roadProvider, "native");
|
assert.equal(normalizeAreaConfig({ ...base, blender: { roadProvider: "native" } }).blender.roadProvider, "native");
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => normalizeAreaConfig({ ...base, blender: { roadProvider: "other" } }),
|
() => normalizeAreaConfig({ ...base, blender: { roadProvider: "other" } }),
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const assert = require("assert");
|
||||||
|
const fs = require("fs");
|
||||||
|
const os = require("os");
|
||||||
|
const path = require("path");
|
||||||
|
const { gcj02ToWgs84, convertGeoJson, inspectReference } = require("./lib/gaode-junction-reference");
|
||||||
|
|
||||||
|
const converted = gcj02ToWgs84([114.12864875054062, 30.460485279762146]);
|
||||||
|
assert.ok(Math.abs(converted[0] - 114.1229659) < 0.00001);
|
||||||
|
assert.ok(Math.abs(converted[1] - 30.4628266) < 0.00001);
|
||||||
|
assert.throws(() => gcj02ToWgs84([Infinity, 30]), /finite/);
|
||||||
|
assert.deepEqual(convertGeoJson({ type: "FeatureCollection", features: [{ type: "Feature", properties: {}, geometry: { type: "Point", coordinates: [114.12864875054062, 30.460485279762146] } }] }).features[0].geometry.coordinates.map((value) => Number(value.toFixed(6))), [114.122966, 30.462827]);
|
||||||
|
|
||||||
|
const temp = fs.mkdtempSync(path.join(os.tmpdir(), "gaode-junction-reference-"));
|
||||||
|
try {
|
||||||
|
const reference = path.join(temp, "reference.geojson");
|
||||||
|
const osm = path.join(temp, "input.osm");
|
||||||
|
const native = path.join(temp, "intersections.geojson");
|
||||||
|
fs.writeFileSync(reference, JSON.stringify({ type: "FeatureCollection", features: [{ type: "Feature", properties: { type: 1 }, geometry: { type: "Polygon", coordinates: [[[114.12860, 30.46040], [114.12870, 30.46040], [114.12870, 30.46050], [114.12860, 30.46040]]] } }] }));
|
||||||
|
fs.writeFileSync(osm, "<osm><node id='8005332807' lon='114.1229249' lat='30.462899'><tag k='highway' v='traffic_signals'/></node></osm>");
|
||||||
|
fs.writeFileSync(native, JSON.stringify({ type: "FeatureCollection", features: [{ type: "Feature", properties: { osm_node_id: "8005332807" }, geometry: { type: "Polygon", coordinates: [[[114.1228, 30.4627], [114.1231, 30.4627], [114.1231, 30.4630], [114.1228, 30.4627]]] } }] }));
|
||||||
|
const result = inspectReference({ referenceFile: reference, osmFile: osm, nativeIntersectionFile: native, nodeId: "8005332807" });
|
||||||
|
assert.equal(result.matchedOsmNode.id, "8005332807");
|
||||||
|
assert.equal(result.matchedOsmNode.match, "node-id");
|
||||||
|
assert.ok(result.matchedOsmNode.centerDistanceMeters < 20);
|
||||||
|
assert.ok(result.nativeIntersection.bboxIoU > 0);
|
||||||
|
assert.deepEqual(result.diagnostics, []);
|
||||||
|
fs.writeFileSync(native, JSON.stringify({ type: "FeatureCollection", features: [] }));
|
||||||
|
assert.match(inspectReference({ referenceFile: reference, osmFile: osm, nativeIntersectionFile: native, nodeId: "8005332807" }).diagnostics[0], /No native intersection/);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(temp, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Gaode junction reference tests passed.");
|
||||||
+268
-1
@@ -73,10 +73,28 @@ assert.ok(geometry.connectors.features.every((feature) => feature.properties.nod
|
|||||||
assert.ok(geometry.movements.length >= geometry.connectors.features.length);
|
assert.ok(geometry.movements.length >= geometry.connectors.features.length);
|
||||||
assert.ok(geometry.movements.every((movement) => movement.id.startsWith("movement:") && movement.connectorId.startsWith("connector:")));
|
assert.ok(geometry.movements.every((movement) => movement.id.startsWith("movement:") && movement.connectorId.startsWith("connector:")));
|
||||||
assert.ok(geometry.movements.every((movement) => ["connector", "continuous", "deferred-too-long"].includes(movement.geometryStatus)));
|
assert.ok(geometry.movements.every((movement) => ["connector", "continuous", "deferred-too-long"].includes(movement.geometryStatus)));
|
||||||
assert.ok(geometry.intersectionSurface.features.every((feature) => feature.properties.rule === "junction-shared-cutback/v3"));
|
assert.ok(geometry.intersectionSurface.features.every((feature) => feature.properties.rule === "junction-shared-cutback/v4-shared-node-split"));
|
||||||
assert.ok(geometry.intersectionSurface.features.every((feature) => ["approach-envelope", "rounded-approach-envelope", "connector-convex-fallback"].includes(feature.properties.boundary_mode)));
|
assert.ok(geometry.intersectionSurface.features.every((feature) => ["approach-envelope", "rounded-approach-envelope", "connector-convex-fallback"].includes(feature.properties.boundary_mode)));
|
||||||
assert.ok(geometry.intersectionSurface.features.every((feature) => feature.properties.approach_area_m2 > 0 && feature.properties.surface_area_m2 > 0 && feature.properties.expansion_ratio >= 1));
|
assert.ok(geometry.intersectionSurface.features.every((feature) => feature.properties.approach_area_m2 > 0 && feature.properties.surface_area_m2 > 0 && feature.properties.expansion_ratio >= 1));
|
||||||
for (const feature of geometry.intersectionSurface.features.filter((item) => item.properties.boundary_mode === "connector-convex-fallback")) assert.ok(geometry.diagnostics.some((item) => item.subjectId === feature.properties.native_id && item.rule === "junction-connector-envelope-fallback"));
|
for (const feature of geometry.intersectionSurface.features.filter((item) => item.properties.boundary_mode === "connector-convex-fallback")) assert.ok(geometry.diagnostics.some((item) => item.subjectId === feature.properties.native_id && item.rule === "junction-connector-envelope-fallback"));
|
||||||
|
// Complex-junction candidate detection: two junction nodes joined by a short
|
||||||
|
// link are one physical intersection; the same pair pushed far apart is a
|
||||||
|
// corridor and must not be reported. Detection is advisory only, so the
|
||||||
|
// geometry must be identical either way.
|
||||||
|
const candidateOsm = (lonB) => `<osm><node id="1" lon="113.999" lat="30"/><node id="2" lon="114" lat="30"/><node id="3" lon="${lonB}" lat="30"/><node id="4" lon="114.01" lat="30"/><node id="5" lon="114" lat="30.001"/><node id="6" lon="${lonB}" lat="29.999"/><way id="70"><nd ref="1"/><nd ref="2"/><tag k="highway" v="residential"/></way><way id="71"><nd ref="2"/><nd ref="3"/><tag k="highway" v="residential"/></way><way id="72"><nd ref="3"/><nd ref="4"/><tag k="highway" v="residential"/></way><way id="73"><nd ref="2"/><nd ref="5"/><tag k="highway" v="residential"/></way><way id="74"><nd ref="3"/><nd ref="6"/><tag k="highway" v="residential"/></way></osm>`;
|
||||||
|
const nearGeometry = compileGeometry(compileRoadModel(candidateOsm("114.0002"), empty));
|
||||||
|
const nearCandidates = nearGeometry.diagnostics.filter((item) => item.rule === "complex-junction-candidate");
|
||||||
|
assert.equal(nearCandidates.length, 1);
|
||||||
|
assert.deepEqual(nearCandidates[0].suggestedCluster.nodeIds, ["2", "3"]);
|
||||||
|
assert.equal(nearCandidates[0].suggestedCluster.template, "complex-junction-v1");
|
||||||
|
assert.equal(nearCandidates[0].severity, "info");
|
||||||
|
assert.ok(nearCandidates[0].suggestedCluster.diameterMeters > 0 && nearCandidates[0].suggestedCluster.coreRadiusMeters >= 12);
|
||||||
|
// Same topology, nodes 2 and 3 now ~965 m apart: no cluster, and no template.
|
||||||
|
const farGeometry = compileGeometry(compileRoadModel(candidateOsm("114.01"), empty));
|
||||||
|
assert.equal(farGeometry.diagnostics.filter((item) => item.rule === "complex-junction-candidate").length, 0);
|
||||||
|
assert.ok(nearGeometry.intersectionSurface.features.every((feature) => feature.properties.template === null));
|
||||||
|
assert.ok(nearGeometry.roadSurface.features.every((feature) => !feature.properties.cluster_id));
|
||||||
|
|
||||||
const controlOsm = `<osm><node id="1" lon="114" lat="30"/><node id="2" lon="114.00080" lat="30"><tag k="highway" v="crossing"/><tag k="crossing:markings" v="zebra"/></node><node id="3" lon="114.001" lat="30"/><node id="4" lon="114.002" lat="30"><tag k="highway" v="crossing"/><tag k="crossing:markings" v="unmarked"/></node><node id="5" lon="114.0035" lat="30"><tag k="highway" v="crossing"/></node><node id="6" lon="114.004" lat="30"/><node id="7" lon="114.001" lat="30.001"/><way id="60"><nd ref="1"/><nd ref="2"/><nd ref="3"/><nd ref="4"/><tag k="highway" v="residential"/></way><way id="61"><nd ref="5"/><nd ref="6"/><tag k="highway" v="footway"/></way><way id="62"><nd ref="3"/><nd ref="7"/><tag k="highway" v="residential"/></way></osm>`;
|
const controlOsm = `<osm><node id="1" lon="114" lat="30"/><node id="2" lon="114.00080" lat="30"><tag k="highway" v="crossing"/><tag k="crossing:markings" v="zebra"/></node><node id="3" lon="114.001" lat="30"/><node id="4" lon="114.002" lat="30"><tag k="highway" v="crossing"/><tag k="crossing:markings" v="unmarked"/></node><node id="5" lon="114.0035" lat="30"><tag k="highway" v="crossing"/></node><node id="6" lon="114.004" lat="30"/><node id="7" lon="114.001" lat="30.001"/><way id="60"><nd ref="1"/><nd ref="2"/><nd ref="3"/><nd ref="4"/><tag k="highway" v="residential"/></way><way id="61"><nd ref="5"/><nd ref="6"/><tag k="highway" v="footway"/></way><way id="62"><nd ref="3"/><nd ref="7"/><tag k="highway" v="residential"/></way></osm>`;
|
||||||
const controlGeometry = compileGeometry(compileRoadModel(controlOsm, empty));
|
const controlGeometry = compileGeometry(compileRoadModel(controlOsm, empty));
|
||||||
assert.equal(controlGeometry.crosswalks.features.length, 6);
|
assert.equal(controlGeometry.crosswalks.features.length, 6);
|
||||||
@@ -117,6 +135,180 @@ assert.ok(crossGeometry.directionArrows.features.every((feature) => feature.prop
|
|||||||
assert.ok(crossGeometry.roadSurface.features.every((feature) => Math.min(...feature.geometry.coordinates[0].map((point) => Math.hypot((point[0] - crossCenter[0]) * 96400, (point[1] - crossCenter[1]) * 111320))) > 4));
|
assert.ok(crossGeometry.roadSurface.features.every((feature) => Math.min(...feature.geometry.coordinates[0].map((point) => Math.hypot((point[0] - crossCenter[0]) * 96400, (point[1] - crossCenter[1]) * 111320))) > 4));
|
||||||
const exteriorRings = (geometry) => geometry.type === "Polygon" ? [geometry.coordinates[0]] : geometry.coordinates.map((polygon) => polygon[0]);
|
const exteriorRings = (geometry) => geometry.type === "Polygon" ? [geometry.coordinates[0]] : geometry.coordinates.map((polygon) => polygon[0]);
|
||||||
assert.ok(crossGeometry.sidewalkSurface.features.every((feature) => Math.min(...exteriorRings(feature.geometry).flat().map((point) => Math.hypot((point[0] - crossCenter[0]) * 96400, (point[1] - crossCenter[1]) * 111320))) > 5));
|
assert.ok(crossGeometry.sidewalkSurface.features.every((feature) => Math.min(...exteriorRings(feature.geometry).flat().map((point) => Math.hypot((point[0] - crossCenter[0]) * 96400, (point[1] - crossCenter[1]) * 111320))) > 5));
|
||||||
|
const crossTemplateGeometry = compileGeometry(compileRoadModel(crossOsm, empty), empty, {
|
||||||
|
junctionTemplates: { enabled: true, references: [{ nodeId: "2", template: "cross-v1", cornerRadiusMultiplier: 1.1 }] },
|
||||||
|
});
|
||||||
|
assert.equal(crossTemplateGeometry.intersectionSurface.features[0].properties.template, "cross-v1");
|
||||||
|
assert.equal(crossTemplateGeometry.intersectionSurface.features[0].properties.rule, "junction-cross-template/v1");
|
||||||
|
assert.ok(crossTemplateGeometry.diagnostics.some((item) => item.rule === "junction-template-applied"));
|
||||||
|
assert.notDeepEqual(crossTemplateGeometry.intersectionSurface.features[0].geometry.coordinates, crossGeometry.intersectionSurface.features[0].geometry.coordinates);
|
||||||
|
assert.deepEqual(crossTemplateGeometry.connectors, crossGeometry.connectors);
|
||||||
|
assert.deepEqual(crossTemplateGeometry.vehicleStopLines, crossGeometry.vehicleStopLines);
|
||||||
|
const crossCutbackTemplateGeometry = compileGeometry(compileRoadModel(crossOsm, empty), empty, {
|
||||||
|
junctionTemplates: { enabled: true, references: [{ nodeId: "2", template: "cross-v1", cornerRadiusMultiplier: 1.25, cutbackMultiplier: 1.25 }] },
|
||||||
|
});
|
||||||
|
const crossCutbackSurface = crossCutbackTemplateGeometry.intersectionSurface.features[0];
|
||||||
|
assert.ok(crossCutbackSurface.properties.cutback_m > crossGeometry.intersectionSurface.features[0].properties.cutback_m);
|
||||||
|
assert.ok(crossCutbackSurface.properties.surface_area_m2 > crossGeometry.intersectionSurface.features[0].properties.surface_area_m2);
|
||||||
|
const crossApproachTemplateGeometry = compileGeometry(compileRoadModel(crossOsm, empty), empty, {
|
||||||
|
junctionTemplates: { enabled: true, references: [{ nodeId: "2", template: "cross-v1", cornerRadiusMultiplier: 1.25, cutbackMultiplier: 1.25, approachWidthMultiplier: 1.45, approachLengthMeters: 24 }] },
|
||||||
|
});
|
||||||
|
const templateApproaches = crossApproachTemplateGeometry.roadSurface.features.filter((feature) => feature.properties.template === "cross-v1");
|
||||||
|
assert.equal(templateApproaches.length, 4);
|
||||||
|
assert.ok(templateApproaches.every((feature) => feature.properties.approach_width_m > feature.properties.width_m && feature.properties.approach_length_m === 24));
|
||||||
|
const clusterApproachGeometry = compileGeometry(compileRoadModel(crossOsm, empty), empty, {
|
||||||
|
junctionTemplates: { enabled: true, references: [], clusters: [{ id: "cross-cluster", nodeIds: ["2", "missing"], template: "complex-junction-v1", approachWidthMultiplier: 1.45, approachLengthMeters: 24, coreRadiusMeters: 18 }] },
|
||||||
|
});
|
||||||
|
const clusterApproaches = clusterApproachGeometry.roadSurface.features.filter((feature) => feature.properties.cluster_id === "cross-cluster");
|
||||||
|
assert.equal(clusterApproaches.filter((feature) => feature.properties.kind === "complex-reference-surface" || feature.properties.kind === "complex-composite").length, 0);
|
||||||
|
assert.ok(clusterApproachGeometry.diagnostics.some((item) => item.rule === "complex-junction-insufficient-nodes"));
|
||||||
|
assert.equal(clusterApproachGeometry.intersectionSurface.features.length, 0);
|
||||||
|
|
||||||
|
const fengshuOsm = fs.readFileSync(path.join(__dirname, "..", "inputs", "osm", "枫树二路.osm"), "utf8");
|
||||||
|
const fengshuModel = compileRoadModel(fengshuOsm, empty);
|
||||||
|
const fengshuCluster = {
|
||||||
|
id: "zhushanhu-fengshu-complex",
|
||||||
|
template: "complex-junction-v1",
|
||||||
|
referenceFile: path.join(__dirname, "..", "inputs", "osm", "珠山湖大道(枫树二路)口.geojson"),
|
||||||
|
approachWidthMultiplier: 1.45,
|
||||||
|
approachLengthMeters: 32,
|
||||||
|
coreRadiusMeters: 28,
|
||||||
|
outerRadiusExtraMeters: 18,
|
||||||
|
nodeIds: ["8005332807", "8024512135", "8024512145", "8024512147"],
|
||||||
|
};
|
||||||
|
const fengshuGeometry = compileGeometry(fengshuModel, empty, { edgeLines: false, junctionTemplates: { enabled: true, references: [], clusters: [fengshuCluster] } });
|
||||||
|
const fengshuSidewalkOverrides = { schema: "native-road-overrides/v1", overrides: [
|
||||||
|
{ id: "generic-complex-sidewalk-a", kind: "road", roadId: "road:way/99505317:forward", sidewalkRight: true },
|
||||||
|
{ id: "generic-complex-sidewalk-b", kind: "road", roadId: "road:way/858770821:segment/2:forward", sidewalkLeft: true },
|
||||||
|
] };
|
||||||
|
const fengshuSidewalkGeometry = compileGeometry(compileRoadModel(fengshuOsm, fengshuSidewalkOverrides), fengshuSidewalkOverrides, { edgeLines: false, junctionTemplates: { enabled: true, references: [], clusters: [fengshuCluster] } });
|
||||||
|
const fengshuConfiguredSidewalks = fengshuSidewalkGeometry.sidewalkSurface.features.filter((feature) => feature.properties.provenance === "native-road-sidewalk/v1" && feature.properties.cluster_id === fengshuCluster.id);
|
||||||
|
assert.equal(fengshuConfiguredSidewalks.length, 2, "sidewalk overrides on complex approaches remain road-side features");
|
||||||
|
const fengshuConfiguredCore = fengshuSidewalkGeometry.roadSurface.features.find((feature) => feature.properties.kind === "complex-core");
|
||||||
|
assert.ok(fengshuConfiguredSidewalks.every((feature) => !ringsOverlap(feature.geometry.coordinates[0], fengshuConfiguredCore.geometry.coordinates[0])), "configured sidewalks stop at the complex-junction handoff instead of entering its core");
|
||||||
|
assert.equal(fengshuSidewalkGeometry.sidewalkSurface.features.filter((feature) => feature.properties.provenance === "native-road-sidewalk-corner/v1" && fengshuCluster.nodeIds.includes(String(feature.properties.osm_node_id))).length, 0, "ordinary sidewalk corners are not generated at member nodes of a complex junction");
|
||||||
|
const genericComplexSource = fs.readFileSync(path.join(__dirname, "lib", "complex-junction.js"), "utf8");
|
||||||
|
assert.doesNotMatch(genericComplexSource, /8005332807|8024512135|8024512145|8024512147|858770823|珠山湖|枫树二路/, "complex junction generator must not contain sample-specific identifiers");
|
||||||
|
const renamedCluster = { ...fengshuCluster, id: "generic-complex-validation-cluster" };
|
||||||
|
const renamedGeometry = compileGeometry(fengshuModel, empty, { edgeLines: false, junctionTemplates: { enabled: true, references: [], clusters: [renamedCluster] } });
|
||||||
|
assert.equal(renamedGeometry.roadSurface.features.filter((feature) => feature.properties.cluster_id === renamedCluster.id && feature.properties.kind === "complex-core").length, 1, "complex geometry is selected by template and topology, not cluster name");
|
||||||
|
assert.equal(renamedGeometry.roadSurface.features.filter((feature) => feature.properties.cluster_id === renamedCluster.id && feature.properties.kind === "complex-approach").length, 8);
|
||||||
|
assert.equal(renamedGeometry.laneCenterlines.features.filter((feature) => feature.properties.cluster_id === renamedCluster.id && feature.properties.cluster_preview).length, 24);
|
||||||
|
assert.equal(renamedGeometry.connectors.features.length, fengshuGeometry.connectors.features.length, "renaming a complex cluster does not change native connector topology");
|
||||||
|
const fengshuRoadParts = fengshuGeometry.roadSurface.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.kind);
|
||||||
|
assert.equal(fengshuRoadParts.filter((feature) => feature.properties.kind === "complex-core").length, 1);
|
||||||
|
assert.equal(fengshuRoadParts.filter((feature) => feature.properties.kind === "complex-approach").length, 8);
|
||||||
|
const fengshuCore = fengshuRoadParts.find((feature) => feature.properties.kind === "complex-core");
|
||||||
|
assert.equal(fengshuCore.properties.corner_rounding_ratio, .16, "complex core rounds its four road-corner transitions without adding exterior sidewalk platforms");
|
||||||
|
assert.equal(fengshuCore.geometry.coordinates[0].length, 33, "complex core samples a rounded boundary at each of its approach-edge corners");
|
||||||
|
const fengshuApproachOuterExtents = fengshuRoadParts.filter((feature) => feature.properties.kind === "complex-approach").map((feature) => {
|
||||||
|
const extent = radialExtent(feature, fengshuCore.properties.center, feature.properties.heading_deg);
|
||||||
|
return extent[1];
|
||||||
|
});
|
||||||
|
assert.equal(fengshuApproachOuterExtents.filter((extent) => Math.abs(extent - (fengshuCore.properties.radius_m + 18)) < .15).length, 7, "all full-length complex approaches reach the same outer handoff radius");
|
||||||
|
assert.ok(fengshuApproachOuterExtents.every((extent) => extent <= fengshuCore.properties.radius_m + 18.15), "short OSM approaches stop at their continuation node instead of overshooting it");
|
||||||
|
const fengshuCornerFillets = fengshuRoadParts.filter((feature) => feature.properties.kind === "complex-corner-fillet");
|
||||||
|
assert.equal(fengshuCornerFillets.length, 4, "every adjacent-arm corner of a complex junction gets a curb fillet");
|
||||||
|
assert.deepEqual(fengshuCornerFillets.map((feature) => feature.properties.corner_index).sort(), [1, 2, 3, 4]);
|
||||||
|
assert.ok(fengshuCornerFillets.every((feature) => feature.properties.corner_radius_m === 12), "corner fillets use the configured curb radius");
|
||||||
|
// The fillet has to stay between the core it smooths and the handoff radius
|
||||||
|
// where the arms become ordinary road surface; a fillet reaching past either
|
||||||
|
// bound would cut the junction open or bridge across the carriageways.
|
||||||
|
assert.ok(fengshuCornerFillets.every((feature) => {
|
||||||
|
const extent = radialExtent(feature, fengshuCore.properties.center, feature.properties.bisector_heading);
|
||||||
|
return extent[1] > fengshuCore.properties.radius_m * .5 && extent[1] < fengshuCore.properties.radius_m + 18;
|
||||||
|
}), "corner fillets fill the wedge between the complex core and the approach handoff radius");
|
||||||
|
assert.ok(fengshuCornerFillets.every((feature) => !ringSelfIntersects(feature.geometry.coordinates[0])), "corner fillet rings are simple polygons");
|
||||||
|
const fengshuBoundaryRoadSurfaces = fengshuGeometry.roadSurface.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && !feature.properties.kind);
|
||||||
|
assert.equal(fengshuBoundaryRoadSurfaces.length, 7, "complex junction keeps its OSM-derived exterior road surfaces");
|
||||||
|
const fengshuPreviewLanes = fengshuGeometry.laneCenterlines.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.cluster_preview);
|
||||||
|
assert.equal(fengshuPreviewLanes.length, 24);
|
||||||
|
assert.equal(fengshuPreviewLanes.filter((feature) => feature.properties.incoming).length, 12);
|
||||||
|
assert.equal(fengshuPreviewLanes.filter((feature) => feature.properties.maneuver === "outbound").length, 12);
|
||||||
|
const fengshuBoundaryLanes = fengshuGeometry.laneCenterlines.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.cluster_boundary_clipped);
|
||||||
|
assert.equal(fengshuBoundaryLanes.length, 24, "eight exterior three-lane carriageways remain visible outside the complex junction boundary");
|
||||||
|
assert.ok(fengshuBoundaryLanes.every((feature) => !feature.properties.cluster_preview_hidden && !feature.properties.cluster_internal));
|
||||||
|
assert.ok(fengshuPreviewLanes.every((feature) => {
|
||||||
|
const road = fengshuModel.roads.find((candidate) => candidate.id === feature.properties.road_id);
|
||||||
|
const laneHeading = bearingDegrees(feature.geometry.coordinates[0], feature.geometry.coordinates.at(-1));
|
||||||
|
const roadHeading = bearingDegrees(road.centerline[0], road.centerline.at(-1));
|
||||||
|
return axialHeadingDifference(laneHeading, roadHeading) < 3;
|
||||||
|
}), "complex-junction lane centerlines remain parallel to their source OSM carriageways");
|
||||||
|
assert.equal(fengshuGeometry.laneSeparators.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.provenance === "native-road-complex-lane-separator/v1").length, 16);
|
||||||
|
const fengshuComplexControls = [
|
||||||
|
...fengshuGeometry.crosswalks.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id),
|
||||||
|
...fengshuGeometry.vehicleStopLines.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id),
|
||||||
|
];
|
||||||
|
assert.equal(fengshuGeometry.laneSeparators.features
|
||||||
|
.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.provenance === "native-road-complex-lane-separator/v1").length, 16, "complex lane separators remain present after control-line clipping");
|
||||||
|
const fengshuArmCrosswalks = fengshuGeometry.crosswalks.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.kind === "complex-crosswalk");
|
||||||
|
assert.ok(fengshuArmCrosswalks.length > 24);
|
||||||
|
assert.equal(new Set(fengshuArmCrosswalks.map((feature) => feature.properties.direction.toFixed(3))).size, 4, "four arm crosswalk groups define the central frame sides");
|
||||||
|
assert.ok(fengshuArmCrosswalks.every((feature) => {
|
||||||
|
const road = fengshuModel.roads.find((candidate) => candidate.id === feature.properties.road_id);
|
||||||
|
const stripe = feature.geometry.coordinates[0];
|
||||||
|
const stripeHeading = bearingDegrees(stripe[0], stripe[1]);
|
||||||
|
const roadHeading = bearingDegrees(road.centerline[0], road.centerline.at(-1));
|
||||||
|
return axialHeadingDifference(stripeHeading, roadHeading) < 3
|
||||||
|
&& distance(stripe[0], stripe[1]) > distance(stripe[1], stripe[2]) * 5;
|
||||||
|
}), "each arm crosswalk stripe is long and axially parallel to its source OSM carriageway");
|
||||||
|
assert.equal(fengshuGeometry.crosswalks.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.kind === "complex-corner-crosswalk").length, 24);
|
||||||
|
assert.equal(fengshuGeometry.vehicleStopLines.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id).length, 4);
|
||||||
|
const fengshuStopApproachArrows = fengshuGeometry.directionArrows.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.provenance === "native-road-complex-preview-arrow/v2-stop-anchored");
|
||||||
|
assert.equal(new Set(fengshuStopApproachArrows.map((feature) => feature.properties.lane_id)).size, 12, "each of the four complex approaches gets one maneuver arrow per generated lane");
|
||||||
|
assert.deepEqual([...new Set(fengshuStopApproachArrows.map((feature) => feature.properties.maneuver))].sort(), ["left", "right", "through"], "complex approach arrows preserve lane maneuver assignments");
|
||||||
|
assert.ok(fengshuStopApproachArrows.every((feature) => feature.properties.placement_distance_from_stop_meters === 8), "complex approach arrows are anchored upstream of their stop lines");
|
||||||
|
assert.ok(fengshuStopApproachArrows.every((feature) => {
|
||||||
|
const lane = fengshuGeometry.laneCenterlines.features.find((candidate) => candidate.properties.native_id === feature.properties.lane_id);
|
||||||
|
return lane && Math.abs(feature.properties.travel_heading_deg - bearingDegrees(lane.geometry.coordinates[0], lane.geometry.coordinates.at(-1))) < .01;
|
||||||
|
}), "complex stop-approach arrows retain the lane travel heading instead of the reversed placement axis");
|
||||||
|
assert.equal(fengshuGeometry.sidewalkSurface.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.kind === "complex-median").length, 0, "complex junctions do not add center green belts");
|
||||||
|
assert.equal(fengshuGeometry.sidewalkSurface.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.kind === "complex-corner-island").length, 4);
|
||||||
|
assert.equal(fengshuGeometry.sidewalkSurface.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id && feature.properties.kind === "complex-sidewalk-corner").length, 0, "complex junctions do not add center sidewalk/green-belt links");
|
||||||
|
assert.ok(fengshuGeometry.sidewalkSurface.features.filter((feature) => feature.properties.cluster_id === fengshuCluster.id).every((feature) => !ringSelfIntersects(feature.geometry.coordinates[0])));
|
||||||
|
const fengshuCenter = fengshuRoadParts.find((feature) => feature.properties.kind === "complex-core").properties.center;
|
||||||
|
for (let cornerIndex = 1; cornerIndex <= 4; cornerIndex += 1) {
|
||||||
|
const island = fengshuGeometry.sidewalkSurface.features.find((feature) => feature.properties.kind === "complex-corner-island" && feature.properties.corner_index === cornerIndex);
|
||||||
|
const crossing = fengshuGeometry.crosswalks.features.filter((feature) => feature.properties.kind === "complex-corner-crosswalk" && feature.properties.corner_index === cornerIndex);
|
||||||
|
const heading = crossing[0].properties.direction;
|
||||||
|
const firstArm = groupedArmCrosswalk(fengshuArmCrosswalks, crossing[0].properties.from_heading);
|
||||||
|
const secondArm = groupedArmCrosswalk(fengshuArmCrosswalks, crossing[0].properties.to_heading);
|
||||||
|
const expectedFrameCorner = supportLineIntersection(featureGroupCenter(firstArm), headingForArmGroup(firstArm) + 90, featureGroupCenter(secondArm), headingForArmGroup(secondArm) + 90, fengshuCenter);
|
||||||
|
assert.ok(expectedFrameCorner, `corner ${cornerIndex} adjacent arm frame supports intersect`);
|
||||||
|
assert.ok(distance(featureGroupCenter(crossing), expectedFrameCorner) > 3.1 && distance(featureGroupCenter(crossing), expectedFrameCorner) < 3.7, `corner ${cornerIndex} diagonal crossing leaves compact room for a safety island beyond the frame corner`);
|
||||||
|
assert.ok(distance(crossing[0].properties.frame_corner, expectedFrameCorner) < .15, `corner ${cornerIndex} records its derived frame corner`);
|
||||||
|
assert.ok(distance(island.properties.frame_corner, expectedFrameCorner) < .15, `corner ${cornerIndex} safety island occupies its derived frame corner`);
|
||||||
|
const islandExtent = radialExtent(island, fengshuCenter, heading);
|
||||||
|
const crossingExtent = radialExtent(crossing, fengshuCenter, heading);
|
||||||
|
assert.ok(crossing.every((feature) => axialHeadingDifference(bearingDegrees(feature.geometry.coordinates[0][0], feature.geometry.coordinates[0][1]), heading) > 75), `corner ${cornerIndex} stripes remain transverse to the pedestrian path`);
|
||||||
|
const armVertices = [...firstArm, ...secondArm].flatMap((feature) => feature.geometry.coordinates[0]);
|
||||||
|
assert.ok(island.properties.base_points.every((point) => Math.min(...armVertices.map((vertex) => distance(point, vertex))) < .4), `corner ${cornerIndex} safety island base follows both long-crosswalk endpoints`);
|
||||||
|
assert.ok(island.properties.base_width_m > 6 && island.properties.base_width_m < 12, `corner ${cornerIndex} safety island fills the space left between two road-clipped crosswalks`);
|
||||||
|
assert.ok(island.properties.crossing_clearance_m >= .15 && island.properties.crossing_clearance_m <= .25, `corner ${cornerIndex} safety island fills the gap without extending through the diagonal crossing`);
|
||||||
|
assert.equal(island.geometry.coordinates[0].length, 7, `corner ${cornerIndex} safety island rounds the existing gap boundary without adding an outer platform`);
|
||||||
|
assert.ok(islandExtent[1] + .25 < crossingExtent[0], `corner ${cornerIndex} crossing starts beyond its safety island`);
|
||||||
|
}
|
||||||
|
for (const heading of [...new Set(fengshuArmCrosswalks.map((feature) => feature.properties.direction))]) {
|
||||||
|
const crossing = fengshuGeometry.crosswalks.features.filter((feature) => feature.properties.kind === "complex-crosswalk" && Math.abs(feature.properties.direction - heading) < 1);
|
||||||
|
const stopLine = fengshuGeometry.vehicleStopLines.features.filter((feature) => Math.abs(feature.properties.direction - heading) < 2);
|
||||||
|
assert.ok(crossing.every((feature) => feature.properties.span_m > 20 && feature.properties.span_m <= feature.properties.road_envelope_span_m), "arm crosswalk spans the two three-lane carriageways without exceeding the OSM road envelope");
|
||||||
|
assert.ok(crossing.every((feature) => Math.abs(feature.properties.road_envelope_span_m - feature.properties.span_m - .7) < .05), "arm crosswalk keeps a curb inset on both road edges");
|
||||||
|
const lateralSpan = lateralExtent(crossing, fengshuCenter, heading);
|
||||||
|
assert.ok(lateralSpan[1] - lateralSpan[0] > crossing[0].properties.span_m - 1, "arm crosswalk geometry spans both three-lane carriageways and their median gap");
|
||||||
|
assert.ok(radialExtent(crossing, fengshuCenter, heading)[1] + .5 < radialExtent(stopLine, fengshuCenter, heading)[0], "incoming stop line is beyond the arm crosswalk");
|
||||||
|
assert.ok(radialExtent(stopLine, fengshuCenter, heading)[0] - radialExtent(crossing, fengshuCenter, heading)[1] < 1.2, "incoming stop line stays close to the arm crosswalk");
|
||||||
|
}
|
||||||
|
assert.deepEqual(crossCutbackTemplateGeometry.connectors.features.map((feature) => feature.properties.native_id).sort(), crossGeometry.connectors.features.map((feature) => feature.properties.native_id).sort());
|
||||||
|
assert.deepEqual(crossCutbackTemplateGeometry.movements.map((movement) => movement.id).sort(), crossGeometry.movements.map((movement) => movement.id).sort());
|
||||||
|
const missingReferenceGeometry = compileGeometry(compileRoadModel(crossOsm, empty), empty, {
|
||||||
|
junctionTemplates: { enabled: true, references: [{ nodeId: "2", template: "cross-v1", referenceFile: "/tmp/native-road-missing-junction-reference.geojson", cornerRadiusMultiplier: 1.1 }] },
|
||||||
|
});
|
||||||
|
assert.equal(missingReferenceGeometry.intersectionSurface.features[0].properties.template, null);
|
||||||
|
assert.ok(missingReferenceGeometry.diagnostics.some((item) => item.rule === "junction-template-reference-missing"));
|
||||||
|
const tTemplateGeometry = compileGeometry(compileRoadModel(osm, empty), empty, {
|
||||||
|
junctionTemplates: { enabled: true, references: [{ nodeId: "2", template: "cross-v1", cornerRadiusMultiplier: 1.1 }] },
|
||||||
|
});
|
||||||
|
assert.ok(tTemplateGeometry.intersectionSurface.features.every((feature) => feature.properties.template === null));
|
||||||
const crossSidewalkCorners = crossGeometry.sidewalkSurface.features.filter((feature) => feature.properties.kind === "corner");
|
const crossSidewalkCorners = crossGeometry.sidewalkSurface.features.filter((feature) => feature.properties.kind === "corner");
|
||||||
assert.equal(crossSidewalkCorners.length, 4);
|
assert.equal(crossSidewalkCorners.length, 4);
|
||||||
// A rounded sidewalk corner must sample both the curb and outer boundaries.
|
// A rounded sidewalk corner must sample both the curb and outer boundaries.
|
||||||
@@ -187,6 +379,20 @@ const laneOverrides = validateOverrides({ schema: "native-road-overrides/v1", ov
|
|||||||
assert.equal(compileGeometry(turnModel, laneOverrides).connectors.features.length, 0);
|
assert.equal(compileGeometry(turnModel, laneOverrides).connectors.features.length, 0);
|
||||||
assert.equal(compileGeometry(turnModel, laneOverrides).movements.length, 0);
|
assert.equal(compileGeometry(turnModel, laneOverrides).movements.length, 0);
|
||||||
assert.throws(() => validateOverrides({ schema: "native-road-overrides/v1", overrides: [{ id: "bad", kind: "road", roadId: "missing", widthMeters: 4 }] }, initial), /Unknown road/);
|
assert.throws(() => validateOverrides({ schema: "native-road-overrides/v1", overrides: [{ id: "bad", kind: "road", roadId: "missing", widthMeters: 4 }] }, initial), /Unknown road/);
|
||||||
|
// Editing OSM retires ids. Saving such a reference is still an error, but a
|
||||||
|
// consumer may ask to skip it so one stale entry cannot block the whole compile.
|
||||||
|
const staleDoc = { schema: "native-road-overrides/v1", overrides: [
|
||||||
|
{ id: "stale-road", kind: "road", roadId: "road:way/does-not-exist:forward", widthMeters: 4 },
|
||||||
|
{ id: "live-road", kind: "road", roadId: target.id, widthMeters: 9 },
|
||||||
|
] };
|
||||||
|
assert.throws(() => validateOverrides(staleDoc, initial), /Unknown road/);
|
||||||
|
const skipped = validateOverrides(staleDoc, initial, { skipStaleTargets: true });
|
||||||
|
assert.equal(skipped.overrides.length, 1);
|
||||||
|
assert.equal(skipped.overrides[0].id, "live-road");
|
||||||
|
assert.deepEqual(skipped.stale.map((item) => item.id), ["stale-road"]);
|
||||||
|
assert.equal(skipped.stale[0].target, "road:way/does-not-exist:forward");
|
||||||
|
// Skipping only forgives missing targets; a malformed entry still throws.
|
||||||
|
assert.throws(() => validateOverrides({ schema: "native-road-overrides/v1", overrides: [{ id: "bad-width", kind: "road", roadId: target.id, widthMeters: -1 }] }, initial, { skipStaleTargets: true }), /Invalid road override/);
|
||||||
const freshArea = fs.mkdtempSync(path.join(os.tmpdir(), "native-road-fresh-area-"));
|
const freshArea = fs.mkdtempSync(path.join(os.tmpdir(), "native-road-fresh-area-"));
|
||||||
try {
|
try {
|
||||||
const input = path.join(freshArea, "input.osm");
|
const input = path.join(freshArea, "input.osm");
|
||||||
@@ -217,6 +423,67 @@ try {
|
|||||||
function distance(a, b) {
|
function distance(a, b) {
|
||||||
return Math.hypot((b[0] - a[0]) * 111320 * Math.cos(a[1] * Math.PI / 180), (b[1] - a[1]) * 111320);
|
return Math.hypot((b[0] - a[0]) * 111320 * Math.cos(a[1] * Math.PI / 180), (b[1] - a[1]) * 111320);
|
||||||
}
|
}
|
||||||
|
function bearingDegrees(first, second) {
|
||||||
|
const east = (second[0] - first[0]) * Math.cos(first[1] * Math.PI / 180);
|
||||||
|
const north = second[1] - first[1];
|
||||||
|
return Math.atan2(east, north) * 180 / Math.PI;
|
||||||
|
}
|
||||||
|
function axialHeadingDifference(first, second) {
|
||||||
|
const difference = Math.abs(((first - second + 180) % 360 + 360) % 360 - 180);
|
||||||
|
return Math.min(difference, 180 - difference);
|
||||||
|
}
|
||||||
|
function ringSelfIntersects(ring) {
|
||||||
|
const orientation = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
||||||
|
for (let first = 0; first < ring.length - 1; first += 1) {
|
||||||
|
for (let second = first + 2; second < ring.length - 1; second += 1) {
|
||||||
|
if (first === 0 && second === ring.length - 2) continue;
|
||||||
|
if (orientation(ring[first], ring[first + 1], ring[second]) * orientation(ring[first], ring[first + 1], ring[second + 1]) < 0
|
||||||
|
&& orientation(ring[second], ring[second + 1], ring[first]) * orientation(ring[second], ring[second + 1], ring[first + 1]) < 0) return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
function radialExtent(features, center, heading) {
|
||||||
|
const list = Array.isArray(features) ? features : [features];
|
||||||
|
const radians = heading * Math.PI / 180;
|
||||||
|
const values = list.flatMap((feature) => feature.geometry.coordinates[0].map((point) => {
|
||||||
|
const east = (point[0] - center[0]) * 111320 * Math.cos(center[1] * Math.PI / 180);
|
||||||
|
const north = (point[1] - center[1]) * 111320;
|
||||||
|
return east * Math.sin(radians) + north * Math.cos(radians);
|
||||||
|
}));
|
||||||
|
return [Math.min(...values), Math.max(...values)];
|
||||||
|
}
|
||||||
|
function lateralExtent(features, center, heading) {
|
||||||
|
return radialExtent(features, center, heading + 90);
|
||||||
|
}
|
||||||
|
function groupedArmCrosswalk(features, heading) {
|
||||||
|
return features.filter((feature) => directedHeadingDifference(feature.properties.direction, heading) < 1);
|
||||||
|
}
|
||||||
|
function directedHeadingDifference(first, second) {
|
||||||
|
return Math.abs(((first - second + 180) % 360 + 360) % 360 - 180);
|
||||||
|
}
|
||||||
|
function headingForArmGroup(features) {
|
||||||
|
return features[0].properties.direction;
|
||||||
|
}
|
||||||
|
function featureGroupCenter(features) {
|
||||||
|
const centers = features.map((feature) => {
|
||||||
|
const ring = feature.geometry.coordinates[0].slice(0, -1);
|
||||||
|
return ring.reduce((sum, point) => [sum[0] + point[0] / ring.length, sum[1] + point[1] / ring.length], [0, 0]);
|
||||||
|
});
|
||||||
|
return centers.reduce((sum, point) => [sum[0] + point[0] / centers.length, sum[1] + point[1] / centers.length], [0, 0]);
|
||||||
|
}
|
||||||
|
function supportLineIntersection(firstPoint, firstHeading, secondPoint, secondHeading, origin) {
|
||||||
|
const lonScale = 111320 * Math.cos(origin[1] * Math.PI / 180);
|
||||||
|
const local = (point) => [(point[0] - origin[0]) * lonScale, (point[1] - origin[1]) * 111320];
|
||||||
|
const direction = (heading) => [Math.sin(heading * Math.PI / 180), Math.cos(heading * Math.PI / 180)];
|
||||||
|
const first = local(firstPoint); const second = local(secondPoint);
|
||||||
|
const a = direction(firstHeading); const b = direction(secondHeading);
|
||||||
|
const denominator = a[0] * b[1] - a[1] * b[0];
|
||||||
|
if (Math.abs(denominator) < 1e-6) return null;
|
||||||
|
const delta = [second[0] - first[0], second[1] - first[1]];
|
||||||
|
const along = (delta[0] * b[1] - delta[1] * b[0]) / denominator;
|
||||||
|
return [origin[0] + (first[0] + a[0] * along) / lonScale, origin[1] + (first[1] + a[1] * along) / 111320];
|
||||||
|
}
|
||||||
function ringsOverlap(first, second) {
|
function ringsOverlap(first, second) {
|
||||||
const bounds = (ring) => [Math.min(...ring.map((point) => point[0])), Math.min(...ring.map((point) => point[1])), Math.max(...ring.map((point) => point[0])), Math.max(...ring.map((point) => point[1]))];
|
const bounds = (ring) => [Math.min(...ring.map((point) => point[0])), Math.min(...ring.map((point) => point[1])), Math.max(...ring.map((point) => point[0])), Math.max(...ring.map((point) => point[1]))];
|
||||||
const a = bounds(first); const b = bounds(second);
|
const a = bounds(first); const b = bounds(second);
|
||||||
|
|||||||
@@ -7,7 +7,13 @@ const os = require("os");
|
|||||||
const path = require("path");
|
const path = require("path");
|
||||||
const { cesiumPreviewHtml } = require("./lib/area-preview");
|
const { cesiumPreviewHtml } = require("./lib/area-preview");
|
||||||
const { makeVehicleGltf } = require("./lib/vehicle-model");
|
const { makeVehicleGltf } = require("./lib/vehicle-model");
|
||||||
const { VEHICLE_IDS, REVERSED_MODEL_IDS, writePreviewVehicleLibrary } = require("./lib/vehicle-library");
|
const {
|
||||||
|
VEHICLE_IDS,
|
||||||
|
REVERSED_MODEL_IDS,
|
||||||
|
V2X_VEHICLE_MODEL_NAMES,
|
||||||
|
writePreviewVehicleLibrary,
|
||||||
|
writePreviewV2xVehicleLibrary,
|
||||||
|
} = require("./lib/vehicle-library");
|
||||||
const {
|
const {
|
||||||
allowedTurns,
|
allowedTurns,
|
||||||
buildVehicleRoute,
|
buildVehicleRoute,
|
||||||
@@ -235,6 +241,14 @@ if (fs.existsSync(vehicleLibraryRoot)) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const v2xVehicleLibraryRoot = path.join(__dirname, "..", "assets", "models", "v2x-vehicles");
|
||||||
|
if (fs.existsSync(v2xVehicleLibraryRoot)) {
|
||||||
|
const v2xLibraryDir = path.join(tempDir, "v2x-vehicle-library");
|
||||||
|
const models = writePreviewV2xVehicleLibrary(v2xLibraryDir);
|
||||||
|
assert.deepEqual(models, V2X_VEHICLE_MODEL_NAMES.map((name) => `v2x-vehicles/${name}`));
|
||||||
|
for (const model of models) assert.ok(fs.existsSync(path.join(v2xLibraryDir, model)));
|
||||||
|
}
|
||||||
|
|
||||||
const html = cesiumPreviewHtml(
|
const html = cesiumPreviewHtml(
|
||||||
"scene<&>.glb",
|
"scene<&>.glb",
|
||||||
"scene.json",
|
"scene.json",
|
||||||
@@ -243,6 +257,8 @@ const html = cesiumPreviewHtml(
|
|||||||
"north<&>\u2028valley",
|
"north<&>\u2028valley",
|
||||||
["car-a.gltf", "truck-a.gltf"],
|
["car-a.gltf", "truck-a.gltf"],
|
||||||
"traffic-signals.json",
|
"traffic-signals.json",
|
||||||
|
null,
|
||||||
|
{ enabled: true, apiBaseUrl: "/api", wsBaseUrl: "/websocket", crossCode: "420100023333" },
|
||||||
);
|
);
|
||||||
assert.match(html, /<title>north<&>\u2028valley Cesium Preview<\/title>/);
|
assert.match(html, /<title>north<&>\u2028valley Cesium Preview<\/title>/);
|
||||||
assert.match(html, /Loading scene<&>\.glb/);
|
assert.match(html, /Loading scene<&>\.glb/);
|
||||||
@@ -250,6 +266,8 @@ assert.match(html, /"areaId":"north\\u003c\\u0026\\u003e\\u2028valley"/);
|
|||||||
assert.match(html, /"glbName":"scene\\u003c\\u0026\\u003e\.glb"/);
|
assert.match(html, /"glbName":"scene\\u003c\\u0026\\u003e\.glb"/);
|
||||||
assert.match(html, /"vehicleModelNames":\["car-a\.gltf","truck-a\.gltf"\]/);
|
assert.match(html, /"vehicleModelNames":\["car-a\.gltf","truck-a\.gltf"\]/);
|
||||||
assert.match(html, /"trafficSignalsName":"traffic-signals\.json"/);
|
assert.match(html, /"trafficSignalsName":"traffic-signals\.json"/);
|
||||||
|
assert.match(html, /"v2xPreview":\{"enabled":true,"apiBaseUrl":"\/api","wsBaseUrl":"\/websocket","crossCode":"420100023333"\}/);
|
||||||
|
assert.match(html, /<script src="v2x-cesium-overlay\.js"><\/script>/);
|
||||||
assert.match(html, /id="toggleSignals"/);
|
assert.match(html, /id="toggleSignals"/);
|
||||||
assert.match(html, /id="vehicleInfoCard" class="hidden"/);
|
assert.match(html, /id="vehicleInfoCard" class="hidden"/);
|
||||||
assert.match(html, /id="vehicleIncidentNote"/);
|
assert.match(html, /id="vehicleIncidentNote"/);
|
||||||
@@ -261,13 +279,71 @@ assert.match(html, /data-view-mode="inspect"/);
|
|||||||
assert.match(html, /id="semanticToggles" class="control-subgroup hidden"/);
|
assert.match(html, /id="semanticToggles" class="control-subgroup hidden"/);
|
||||||
|
|
||||||
const previewRuntime = fs.readFileSync(path.join(__dirname, "lib", "cesium-preview.js"), "utf8");
|
const previewRuntime = fs.readFileSync(path.join(__dirname, "lib", "cesium-preview.js"), "utf8");
|
||||||
|
const v2xRuntime = fs.readFileSync(path.join(__dirname, "lib", "v2x-cesium-overlay.js"), "utf8");
|
||||||
const buildAreaSource = fs.readFileSync(path.join(__dirname, "build-area.js"), "utf8");
|
const buildAreaSource = fs.readFileSync(path.join(__dirname, "build-area.js"), "utf8");
|
||||||
assert.match(buildAreaSource, /vehicleModelNames\.map\(\(name\) => `_preview\/\$\{name\}`\)/);
|
assert.match(buildAreaSource, /const vehicleModelNames = writeVehicleModel\(area\);/);
|
||||||
|
assert.doesNotMatch(buildAreaSource, /buildNativeTrafficSimulation/);
|
||||||
const countdownFont = path.join(__dirname, "..", "assets", "fonts", "7LED-1.ttf");
|
const countdownFont = path.join(__dirname, "..", "assets", "fonts", "7LED-1.ttf");
|
||||||
assert.ok(fs.existsSync(countdownFont), "7LED countdown font must be versioned with the project");
|
assert.ok(fs.existsSync(countdownFont), "7LED countdown font must be versioned with the project");
|
||||||
assert.doesNotMatch(previewRuntime, /cylinder: \{ length: 6\.7/);
|
assert.doesNotMatch(previewRuntime, /cylinder: \{ length: 6\.7/);
|
||||||
assert.doesNotMatch(previewRuntime, /Traffic Signal Housing/);
|
assert.doesNotMatch(previewRuntime, /Traffic Signal Housing/);
|
||||||
assert.match(previewRuntime, /asset\.category === "dynamic"/);
|
assert.match(previewRuntime, /asset\.category === "dynamic"/);
|
||||||
|
assert.match(previewRuntime, /createV2xCesiumOverlay/);
|
||||||
|
assert.match(v2xRuntime, /\/facilities\/api\/sys\/login/);
|
||||||
|
assert.match(v2xRuntime, /sessionStorage/);
|
||||||
|
assert.match(v2xRuntime, /GCJ-02 -> WGS84 once/);
|
||||||
|
assert.match(v2xRuntime, /\/network\/ws\/network\/signal/);
|
||||||
|
assert.match(v2xRuntime, /\/network\/ws\/network\/obuPosition/);
|
||||||
|
assert.match(v2xRuntime, /\/network\/ws\/network\/targetPosition/);
|
||||||
|
assert.match(v2xRuntime, /headingPitchRollQuaternion/);
|
||||||
|
assert.match(v2xRuntime, /model:/);
|
||||||
|
assert.match(previewRuntime, /createLiveTrafficSignals\(/);
|
||||||
|
assert.doesNotMatch(previewRuntime, /const trafficSignals = addTrafficSignals\(/);
|
||||||
|
|
||||||
|
// The lamp dictionary lives only in the overlay, which hands the preview
|
||||||
|
// already-normalized {nodeKeys, color, countDown} entries. Two copies of the
|
||||||
|
// dictionary drifted apart once and made every phase render red.
|
||||||
|
assert.doesNotMatch(previewRuntime, /function lampColorName/,
|
||||||
|
"the preview must not keep its own lamp status dictionary");
|
||||||
|
assert.doesNotMatch(previewRuntime, /Number\(status\) === 3/,
|
||||||
|
"status 3 is not green; the real codes are 21/22/23");
|
||||||
|
assert.match(previewRuntime, /entry\.nodeKeys/,
|
||||||
|
"live signals are addressed by resolved native node keys");
|
||||||
|
assert.match(previewRuntime, /paintCountdown\(/, "countDown from the push drives the countdown assets");
|
||||||
|
assert.match(previewRuntime, /nativeSignals: \(signalData && signalData\.signals\) \|\| \[\]/,
|
||||||
|
"the overlay needs the native signal list to bind phases");
|
||||||
|
assert.match(previewRuntime, /registry\?\.visibleSize/,
|
||||||
|
"diagnostics must report the visible live-vehicle count");
|
||||||
|
assert.match(previewRuntime, /Target WS:/,
|
||||||
|
"diagnostics must expose target websocket receipt and parsing counts");
|
||||||
|
assert.match(previewRuntime, /Target payload:/,
|
||||||
|
"diagnostics must expose the payload shape when target pushes have no vehicles");
|
||||||
|
assert.match(v2xRuntime, /minimumPixelSize: 28/,
|
||||||
|
"live vehicles remain visible from the intersection overview");
|
||||||
|
assert.match(v2xRuntime, /LIVE_VEHICLE_HEIGHT_METERS = 1\.2/,
|
||||||
|
"live vehicles stay clear of the static road surface");
|
||||||
|
assert.match(v2xRuntime, /LIVE_VEHICLE_HEADING_OFFSET_DEGREES = 90/,
|
||||||
|
"live dashboard vehicle models receive their required clockwise heading correction");
|
||||||
|
|
||||||
|
// Overlay-side regressions: lamp codes, heartbeat, subscription frames,
|
||||||
|
// vehicle lifecycle and the removed out-of-scope request.
|
||||||
|
assert.match(v2xRuntime, /LAMP_STATUS = \{ 11: "off", 21: "red", 22: "yellow", 23: "green", 31: "other" \}/);
|
||||||
|
assert.doesNotMatch(v2xRuntime, /Number\(status\) === 3/);
|
||||||
|
assert.match(v2xRuntime, /heartBeat: "ping"/, "all sockets must heartbeat like the dashboard");
|
||||||
|
assert.match(v2xRuntime, /HEARTBEAT_INTERVAL_MS = 30000/);
|
||||||
|
assert.match(v2xRuntime, /scheduleReconnect/, "a dropped socket must reconnect");
|
||||||
|
assert.match(v2xRuntime, /buildBoundsMessage/, "the OBU socket must send a bounds frame");
|
||||||
|
assert.match(v2xRuntime, /createVehicleRegistry/, "stale vehicles must be swept");
|
||||||
|
assert.match(v2xRuntime, /linkEntitiesByPhase/, "one phase may light several approaches");
|
||||||
|
assert.doesNotMatch(v2xRuntime, /linkPhases/, "the phase -> single entity map overwrote approaches");
|
||||||
|
assert.doesNotMatch(v2xRuntime, /FlowTravelRatio/,
|
||||||
|
"weekly flow ratio is not part of the live intersection view");
|
||||||
|
assert.doesNotMatch(v2xRuntime, /Intersection code<input/);
|
||||||
|
assert.match(v2xRuntime, /Finding the configured V2X intersection/);
|
||||||
|
assert.match(v2xRuntime, /crossDeviceConfig\/queryList/);
|
||||||
|
assert.match(v2xRuntime, /gcj02ToWgs84/);
|
||||||
|
assert.match(previewRuntime, /createLiveVehicleState\(\)/);
|
||||||
|
assert.doesNotMatch(previewRuntime, /const cruise = addVehicleCruises\(/);
|
||||||
assert.match(previewRuntime, /new Cesium\.ScreenSpaceEventHandler/);
|
assert.match(previewRuntime, /new Cesium\.ScreenSpaceEventHandler/);
|
||||||
assert.match(previewRuntime, /vehicleId: record\.id/);
|
assert.match(previewRuntime, /vehicleId: record\.id/);
|
||||||
assert.match(previewRuntime, /status === "breakdown"\s+\? "vehicle-breakdown\.png"/);
|
assert.match(previewRuntime, /status === "breakdown"\s+\? "vehicle-breakdown\.png"/);
|
||||||
@@ -278,9 +354,7 @@ assert.match(previewRuntime, /\(\) => record\?\.status === "normal"/);
|
|||||||
assert.match(previewRuntime, /Cesium\.SceneTransforms\.worldToWindowCoordinates/);
|
assert.match(previewRuntime, /Cesium\.SceneTransforms\.worldToWindowCoordinates/);
|
||||||
assert.match(previewRuntime, /TrafficSignalDynamic_/);
|
assert.match(previewRuntime, /TrafficSignalDynamic_/);
|
||||||
assert.match(previewRuntime, /TrafficSignalDynamic_\$\{nodeKey\}_countdown_\$\{String\(value\)\.padStart\(2, "0"\)\}/);
|
assert.match(previewRuntime, /TrafficSignalDynamic_\$\{nodeKey\}_countdown_\$\{String\(value\)\.padStart\(2, "0"\)\}/);
|
||||||
assert.match(previewRuntime, /native-preview-traffic-simulation\/v1/);
|
assert.doesNotMatch(previewRuntime, /native-preview-traffic-simulation\/v1/);
|
||||||
assert.match(previewRuntime, /leader-gap/);
|
|
||||||
assert.match(previewRuntime, /stopReason = "traffic-signal"/);
|
|
||||||
assert.match(previewRuntime, /ColorBlendMode\.REPLACE/);
|
assert.match(previewRuntime, /ColorBlendMode\.REPLACE/);
|
||||||
assert.match(previewRuntime, /setBuildingGhost/);
|
assert.match(previewRuntime, /setBuildingGhost/);
|
||||||
assert.match(previewRuntime, /fetch\(url, \{ cache: "no-store" \}\)/);
|
assert.match(previewRuntime, /fetch\(url, \{ cache: "no-store" \}\)/);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ const path = require("path");
|
|||||||
const html = fs.readFileSync(path.join(__dirname, "workbench", "index.html"), "utf8");
|
const html = fs.readFileSync(path.join(__dirname, "workbench", "index.html"), "utf8");
|
||||||
assert.match(html, /id="width" type="number" min="1" step="0\.01"/);
|
assert.match(html, /id="width" type="number" min="1" step="0\.01"/);
|
||||||
assert.match(html, /data-layer="sidewalks" type="checkbox" checked> 路缘与步行带/);
|
assert.match(html, /data-layer="sidewalks" type="checkbox" checked> 路缘与步行带/);
|
||||||
|
assert.match(html, /data-layer="gaodeReference" type="checkbox" checked> 高德规整路口参考/);
|
||||||
assert.match(html, /id="scene-preview" type="checkbox"/);
|
assert.match(html, /id="scene-preview" type="checkbox"/);
|
||||||
assert.match(html, /id="selected-junction" hidden/);
|
assert.match(html, /id="selected-junction" hidden/);
|
||||||
const app = fs.readFileSync(path.join(__dirname, "workbench", "app.js"), "utf8");
|
const app = fs.readFileSync(path.join(__dirname, "workbench", "app.js"), "utf8");
|
||||||
@@ -18,7 +19,13 @@ assert.match(app, /road\.segmentId === selectedRoad\.segmentId/);
|
|||||||
assert.match(app, /sidewalkLeft: rightInput\.checked, sidewalkRight: leftInput\.checked/);
|
assert.match(app, /sidewalkLeft: rightInput\.checked, sidewalkRight: leftInput\.checked/);
|
||||||
assert.match(app, /function nativeSurfaceStyle\(feature\)/);
|
assert.match(app, /function nativeSurfaceStyle\(feature\)/);
|
||||||
assert.match(app, /reference: new VectorLayer\(\{ source: source\(\), visible: false/);
|
assert.match(app, /reference: new VectorLayer\(\{ source: source\(\), visible: false/);
|
||||||
|
assert.match(app, /gaodeReference: new VectorLayer/);
|
||||||
|
assert.match(app, /state\.junctionReference\?\.converted/);
|
||||||
|
assert.match(app, /gaodeReferenceColors/);
|
||||||
assert.match(app, /scene mode must render fills only/);
|
assert.match(app, /scene mode must render fills only/);
|
||||||
|
assert.match(app, /readFeatures\(state\.layers\.nativeRoadSurface\)/);
|
||||||
|
assert.doesNotMatch(app, /nativeRoadSurface, \(feature\) => !feature\.properties\?\.cluster_id/);
|
||||||
|
assert.doesNotMatch(app, /&& !feature\.properties\?\.cluster_preview\)/);
|
||||||
assert.match(app, /scenePreviewToggle\.onchange/);
|
assert.match(app, /scenePreviewToggle\.onchange/);
|
||||||
assert.match(app, /layers\.sidewalks\.setVisible\(document\.querySelector\('\[data-layer="sidewalks"\]'\)\.checked\)/);
|
assert.match(app, /layers\.sidewalks\.setVisible\(document\.querySelector\('\[data-layer="sidewalks"\]'\)\.checked\)/);
|
||||||
assert.match(app, /function selectJunction\(feature\)/);
|
assert.match(app, /function selectJunction\(feature\)/);
|
||||||
@@ -75,6 +82,8 @@ assert.match(app, /headFeatures\.push\(new Feature/);
|
|||||||
assert.match(app, /faceFeatures\.push\(new Feature/);
|
assert.match(app, /faceFeatures\.push\(new Feature/);
|
||||||
const server = fs.readFileSync(path.join(__dirname, "road-workbench.js"), "utf8");
|
const server = fs.readFileSync(path.join(__dirname, "road-workbench.js"), "utf8");
|
||||||
assert.match(server, /\/api\/traffic-signals\/generate/);
|
assert.match(server, /\/api\/traffic-signals\/generate/);
|
||||||
|
assert.match(server, /function compileFresh\(configPath\)/);
|
||||||
|
assert.match(server, /execFileSync\(process\.execPath, \[path\.join\(repoRoot, "scripts", "compile-native-roads\.js"\)/, "workbench regeneration must load the current compiler in a fresh process");
|
||||||
assert.doesNotMatch(app, /导入 QGIS|导出 QGIS/);
|
assert.doesNotMatch(app, /导入 QGIS|导出 QGIS/);
|
||||||
assert.doesNotMatch(server, /traffic-signals\/(?:import|export)-qgis/);
|
assert.doesNotMatch(server, /traffic-signals\/(?:import|export)-qgis/);
|
||||||
console.log("road workbench tests passed");
|
console.log("road workbench tests passed");
|
||||||
@@ -3,12 +3,16 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
const assert = require("assert");
|
const assert = require("assert");
|
||||||
|
const fs = require("fs");
|
||||||
|
const os = require("os");
|
||||||
|
const path = require("path");
|
||||||
const {
|
const {
|
||||||
buildTrafficSignalFeatures,
|
buildTrafficSignalFeatures,
|
||||||
buildTrafficSignalsFromFeatures,
|
buildTrafficSignalsFromFeatures,
|
||||||
validateTrafficSignalFeatures,
|
validateTrafficSignalFeatures,
|
||||||
validateTrafficSignalSourceReferences,
|
validateTrafficSignalSourceReferences,
|
||||||
} = require("./lib/traffic-signals");
|
} = require("./lib/traffic-signals");
|
||||||
|
const { SCHEMA, loadOrGenerate } = require("./lib/native-traffic-signals");
|
||||||
|
|
||||||
function rectangle(lon, lat, dx = 0.00003, dy = 0.000006) {
|
function rectangle(lon, lat, dx = 0.00003, dy = 0.000006) {
|
||||||
return { type: "Feature", geometry: { type: "Polygon", coordinates: [[
|
return { type: "Feature", geometry: { type: "Polygon", coordinates: [[
|
||||||
@@ -41,6 +45,28 @@ assert.deepEqual(
|
|||||||
"technical ids are deterministic",
|
"technical ids are deterministic",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const clusteredStops = { type: "FeatureCollection", features: [
|
||||||
|
rectangle(119.99995, 30.00005, 0.000006, 0.00003), rectangle(120.00010, 30.00025),
|
||||||
|
rectangle(120.00035, 30.00005, 0.000006, 0.00003), rectangle(120.00010, 29.99985),
|
||||||
|
].map((feature) => ({ ...feature, properties: { cluster_id: "generic-complex" } })) };
|
||||||
|
const polarityAgnosticControl = { ...control, arms: [{ ...arms[0], headingDegrees: 90 }, ...arms.slice(1)] };
|
||||||
|
const ordinaryWithReversedArm = buildTrafficSignalFeatures(stops, intersections, [polarityAgnosticControl]);
|
||||||
|
assert.ok(
|
||||||
|
!new Set(stops.features.map(stopCenterKey)).has(signalStopKey(ordinaryWithReversedArm.features.find((feature) => feature.properties.source_way_id === "east"))),
|
||||||
|
"ordinary candidates retain directed matching",
|
||||||
|
);
|
||||||
|
const clustered = buildTrafficSignalFeatures(clusteredStops, { type: "FeatureCollection", features: [] }, [polarityAgnosticControl]);
|
||||||
|
assert.equal(clustered.features.length, 4, "complex stop lines form a signal group without an ordinary intersection surface");
|
||||||
|
assert.deepEqual(
|
||||||
|
new Set(clustered.features.map(signalStopKey)),
|
||||||
|
new Set(clusteredStops.features.map(stopCenterKey)),
|
||||||
|
"complex OSM arms consume each stop-line candidate exactly once",
|
||||||
|
);
|
||||||
|
assert.ok(clustered.features.every((feature) => {
|
||||||
|
const stop = [feature.properties.stop_lon, feature.properties.stop_lat];
|
||||||
|
return metersBetweenForTest(feature.geometry.coordinates, stop) > 4.8 && metersBetweenForTest(feature.geometry.coordinates, stop) < 5.6;
|
||||||
|
}), "complex signal poles are positioned from their matched stop lines");
|
||||||
|
|
||||||
const edited = structuredClone(cross);
|
const edited = structuredClone(cross);
|
||||||
const first = edited.features[0];
|
const first = edited.features[0];
|
||||||
const originalStop = [first.properties.stop_lon, first.properties.stop_lat];
|
const originalStop = [first.properties.stop_lon, first.properties.stop_lat];
|
||||||
@@ -84,6 +110,19 @@ assert.equal(migrated.face_heading_deg, 222, "legacy heading preserves the histo
|
|||||||
edited.features[1].properties.enabled = "0";
|
edited.features[1].properties.enabled = "0";
|
||||||
assert.equal(buildTrafficSignalsFromFeatures(edited).signals.length, 3, "disabled assemblies are omitted");
|
assert.equal(buildTrafficSignalsFromFeatures(edited).signals.length, 3, "disabled assemblies are omitted");
|
||||||
|
|
||||||
|
function metersBetweenForTest(first, second) {
|
||||||
|
return Math.hypot((first[0] - second[0]) * 111320 * Math.cos(first[1] * Math.PI / 180), (first[1] - second[1]) * 111320);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopCenterKey(feature) {
|
||||||
|
const ring = feature.geometry.coordinates[0].slice(0, -1);
|
||||||
|
return `${ring.reduce((sum, point) => sum + point[0], 0) / ring.length},${ring.reduce((sum, point) => sum + point[1], 0) / ring.length}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function signalStopKey(feature) {
|
||||||
|
return `${feature.properties.stop_lon},${feature.properties.stop_lat}`;
|
||||||
|
}
|
||||||
|
|
||||||
const duplicateUid = structuredClone(cross);
|
const duplicateUid = structuredClone(cross);
|
||||||
duplicateUid.features[1].properties.signal_uid = duplicateUid.features[0].properties.signal_uid;
|
duplicateUid.features[1].properties.signal_uid = duplicateUid.features[0].properties.signal_uid;
|
||||||
assert.throws(() => validateTrafficSignalFeatures(duplicateUid), /Duplicate signal_uid/);
|
assert.throws(() => validateTrafficSignalFeatures(duplicateUid), /Duplicate signal_uid/);
|
||||||
@@ -129,4 +168,31 @@ const missingDirections = structuredClone(cross);
|
|||||||
for (const key of ["heading_deg", "mast_heading_deg", "face_heading_deg"]) missingDirections.features[0].properties[key] = null;
|
for (const key of ["heading_deg", "mast_heading_deg", "face_heading_deg"]) missingDirections.features[0].properties[key] = null;
|
||||||
assert.throws(() => validateTrafficSignalFeatures(missingDirections), /missing mast_heading_deg/);
|
assert.throws(() => validateTrafficSignalFeatures(missingDirections), /missing mast_heading_deg/);
|
||||||
|
|
||||||
|
const changedOsm = `
|
||||||
|
<osm>
|
||||||
|
<node id="control-1" lon="120.0001" lat="30.00005"><tag k="highway" v="traffic_signals" /></node>
|
||||||
|
<node id="w1" lon="119.9998" lat="30.00005" />
|
||||||
|
<node id="n1" lon="120.0001" lat="30.00035" />
|
||||||
|
<node id="e1" lon="120.0004" lat="30.00005" />
|
||||||
|
<way id="west"><nd ref="w1" /><nd ref="control-1" /><tag k="highway" v="primary" /></way>
|
||||||
|
<way id="north"><nd ref="control-1" /><nd ref="n1" /><tag k="highway" v="primary" /></way>
|
||||||
|
<way id="east"><nd ref="control-1" /><nd ref="e1" /><tag k="highway" v="primary" /></way>
|
||||||
|
</osm>`;
|
||||||
|
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "native-traffic-signals-"));
|
||||||
|
const generatedSignalPath = path.join(temporaryDirectory, "generated.json");
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(generatedSignalPath, JSON.stringify({ schema: SCHEMA, provenance: "generated:osm-controls", assemblies: cross }));
|
||||||
|
const regenerated = loadOrGenerate(generatedSignalPath, changedOsm, stops, intersections);
|
||||||
|
assert.equal(regenerated.assemblies.features.length, 3, "stale OSM-generated signals must refresh after OSM approaches change");
|
||||||
|
|
||||||
|
fs.writeFileSync(generatedSignalPath, JSON.stringify({ schema: SCHEMA, provenance: "edited:workbench", assemblies: cross }));
|
||||||
|
assert.throws(
|
||||||
|
() => loadOrGenerate(generatedSignalPath, changedOsm, stops, intersections),
|
||||||
|
/approach_id .* is not present on OSM control/,
|
||||||
|
"manually maintained signals must not be silently replaced",
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
console.log("Traffic signal tests passed.");
|
console.log("Traffic signal tests passed.");
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const assert = require("assert");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const vm = require("vm");
|
||||||
|
const { gcj02ToWgs84: referenceGcj02ToWgs84 } = require("./lib/gaode-junction-reference");
|
||||||
|
|
||||||
|
const source = fs.readFileSync(path.join(__dirname, "lib", "v2x-cesium-overlay.js"), "utf8");
|
||||||
|
const context = {
|
||||||
|
window: { location: new URL("https://preview.example.test/areas/fengshu/") },
|
||||||
|
URL,
|
||||||
|
Blob,
|
||||||
|
TextDecoder,
|
||||||
|
console,
|
||||||
|
};
|
||||||
|
vm.runInNewContext(source, context, { filename: "v2x-cesium-overlay.js" });
|
||||||
|
|
||||||
|
const {
|
||||||
|
gcj02ToWgs84, wgs84ToGcj02, joinUrl, md5, toWebSocketUrl,
|
||||||
|
normalizeObuVehicle, normalizeObuPush, normalizeTargetVehicles, normalizeTargetPush,
|
||||||
|
selectCrossCode, lampColorName, parseLoosePayload, isHeartbeat, signalEntriesFrom,
|
||||||
|
getAngle, angleDeltaDegrees, haversineMeters,
|
||||||
|
buildPhaseSignalMap, signalTravelHeading,
|
||||||
|
createVehicleRegistry, modelNameFor, resolvePushInterval,
|
||||||
|
createSocket, buildBoundsMessage, HEARTBEAT_MESSAGE, HEARTBEAT_INTERVAL_MS,
|
||||||
|
} = context.window.createV2xCesiumOverlay.utils;
|
||||||
|
|
||||||
|
// --- existing contracts -----------------------------------------------------
|
||||||
|
assert.equal(md5(""), "d41d8cd98f00b204e9800998ecf8427e");
|
||||||
|
assert.equal(md5("password"), "5f4dcc3b5aa765d61d8327deb882cf99");
|
||||||
|
assert.equal(joinUrl("/api/", "/facilities/api/sys/login"), "/api/facilities/api/sys/login");
|
||||||
|
assert.equal(joinUrl("/websocket", "network/ws/network/signal"), "/websocket/network/ws/network/signal");
|
||||||
|
assert.equal(toWebSocketUrl("/websocket/network/ws/network/signal", "opaque token"), "wss://preview.example.test/websocket/network/ws/network/signal?authorization=opaque+token");
|
||||||
|
|
||||||
|
const converted = gcj02ToWgs84([114.12864875054062, 30.460485279762146]);
|
||||||
|
const reference = referenceGcj02ToWgs84([114.12864875054062, 30.460485279762146]);
|
||||||
|
assert.ok(Math.abs(converted[0] - reference[0]) < 1e-12);
|
||||||
|
assert.ok(Math.abs(converted[1] - reference[1]) < 1e-12);
|
||||||
|
assert.deepEqual(gcj02ToWgs84([Infinity, 30]), [NaN, NaN]);
|
||||||
|
|
||||||
|
// wgs84ToGcj02 is the forward transform used for the OBU bounds frame. Both
|
||||||
|
// directions are single-step approximations, so the round trip is not exact:
|
||||||
|
// it closes to about 1.5 m. That is irrelevant for a viewport filter, and
|
||||||
|
// vehicle positions never use it -- they only ever go GCJ-02 -> WGS84 once.
|
||||||
|
const roundTrip = gcj02ToWgs84(wgs84ToGcj02([114.12864875054062, 30.460485279762146]));
|
||||||
|
assert.ok(haversineMeters([114.12864875054062, 30.460485279762146], roundTrip) < 2);
|
||||||
|
assert.deepEqual(wgs84ToGcj02([NaN, 30]), [NaN, NaN]);
|
||||||
|
|
||||||
|
assert.equal(selectCrossCode({ west: [{ code: "first" }, { code: "configured" }] }, [{ crossCode: "configured" }]), "configured");
|
||||||
|
assert.equal(selectCrossCode([{ code: "first" }], []), "first");
|
||||||
|
|
||||||
|
// --- AC2: lamp status dictionary -------------------------------------------
|
||||||
|
// Codes come from HologramCross/components/utils.ts lightStatusColorDict.
|
||||||
|
assert.equal(lampColorName(11), "off");
|
||||||
|
assert.equal(lampColorName(21), "red");
|
||||||
|
assert.equal(lampColorName(22), "yellow");
|
||||||
|
assert.equal(lampColorName(23), "green");
|
||||||
|
assert.equal(lampColorName(31), "other");
|
||||||
|
assert.equal(lampColorName("23"), "green", "string codes resolve too");
|
||||||
|
// Regression guard: the previous port read 2/3 as yellow/green, which made
|
||||||
|
// every real 21/22/23 push fall through to red.
|
||||||
|
assert.notEqual(lampColorName(2), "yellow");
|
||||||
|
assert.notEqual(lampColorName(3), "green");
|
||||||
|
assert.equal(lampColorName(2), "other");
|
||||||
|
assert.equal(lampColorName(3), "other");
|
||||||
|
assert.equal(lampColorName(undefined), "other", "unknown codes never default to red");
|
||||||
|
assert.equal(lampColorName(999), "other");
|
||||||
|
|
||||||
|
// --- AC7: loose payload parsing --------------------------------------------
|
||||||
|
assert.deepEqual(parseLoosePayload('{"a":1}'), { a: 1 });
|
||||||
|
assert.deepEqual(parseLoosePayload("{a:1,b:'x',}"), { a: 1, b: "x" });
|
||||||
|
assert.deepEqual(parseLoosePayload('{data:{1519:[{id:"53122",longitude:114.12871535072304,latitude:30.46061866463221}]}}'), {
|
||||||
|
data: { 1519: [{ id: "53122", longitude: 114.12871535072304, latitude: 30.46061866463221 }] },
|
||||||
|
}, "targetPosition uses unquoted numeric device-id keys");
|
||||||
|
assert.deepEqual(parseLoosePayload('{"a":NaN}'), { a: null });
|
||||||
|
assert.equal(parseLoosePayload("{bad"), null);
|
||||||
|
assert.equal(parseLoosePayload(null), null);
|
||||||
|
assert.ok(isHeartbeat('{"heartBeat":"pong"}'));
|
||||||
|
assert.equal(parseLoosePayload('{"heartBeat":"pong"}'), null, "heartbeats are not payloads");
|
||||||
|
|
||||||
|
// --- geometry helpers -------------------------------------------------------
|
||||||
|
assert.ok(Math.abs(angleDeltaDegrees(350, 10) - 20) < 1e-9);
|
||||||
|
assert.ok(Math.abs(angleDeltaDegrees(10, 350) - 20) < 1e-9);
|
||||||
|
assert.ok(Math.abs(angleDeltaDegrees(0, 180) - 180) < 1e-9);
|
||||||
|
assert.ok(Math.abs(getAngle([0, 0], [1, 0]) - 90) < 1e-6, "due east is 90");
|
||||||
|
assert.ok(Math.abs(haversineMeters([114, 30], [114, 30.001]) - 111.2) < 0.5);
|
||||||
|
assert.equal(haversineMeters([114, 30], [114, 30]), 0);
|
||||||
|
|
||||||
|
// --- AC3/AC4: phase to native signal mapping --------------------------------
|
||||||
|
const nativeSignals = JSON.parse(fs.readFileSync(
|
||||||
|
path.join(__dirname, "..", "outputs", "fengshu-er-road", "package", "runtime", "traffic-signals.json"), "utf8")).signals;
|
||||||
|
assert.ok(nativeSignals.length >= 4, "fixture needs several native signals");
|
||||||
|
|
||||||
|
// The generator emits mast = travel - 90 and face = travel + 180
|
||||||
|
// (scripts/lib/traffic-signals.js), so travel is recoverable from either.
|
||||||
|
nativeSignals.forEach((signal) => {
|
||||||
|
const fromFace = signalTravelHeading(signal);
|
||||||
|
const fromMast = signalTravelHeading({ mastHeadingDegrees: signal.mastHeadingDegrees });
|
||||||
|
assert.ok(angleDeltaDegrees(fromFace, fromMast) < 1e-6, "face and mast agree on travel heading");
|
||||||
|
});
|
||||||
|
|
||||||
|
// Build a V2X link whose last segment approaches the given native signal.
|
||||||
|
function linkForSignal(signal, id, phase) {
|
||||||
|
const stop = wgs84ToGcj02([signal.stopLongitude, signal.stopLatitude]);
|
||||||
|
const heading = signalTravelHeading(signal) * Math.PI / 180;
|
||||||
|
const step = 0.0002;
|
||||||
|
const previous = [stop[0] - Math.sin(heading) * step, stop[1] - Math.cos(heading) * step];
|
||||||
|
return { id, geom: JSON.stringify({ type: "LineString", coordinates: [previous, stop] }), phaseList: [{ phase }] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const oneToOne = buildPhaseSignalMap(nativeSignals.map((signal, index) => linkForSignal(signal, `L${index}`, index + 1)), nativeSignals, {});
|
||||||
|
assert.equal(oneToOne.bound, nativeSignals.length, "every phase binds");
|
||||||
|
assert.equal(oneToOne.unbound.length, 0);
|
||||||
|
oneToOne.diagnostics.forEach((entry, index) => {
|
||||||
|
assert.deepEqual(entry.matchedNodeKeys, [nativeSignals[index].nodeKey],
|
||||||
|
`link ${entry.linkId} must bind only its own approach, got ${entry.matchedNodeKeys.join()}`);
|
||||||
|
assert.ok(entry.nearestDistanceMeters < 5, "stop points are metres apart, not kilometres");
|
||||||
|
});
|
||||||
|
|
||||||
|
// AC4: one phase shared by two approaches lights both.
|
||||||
|
const shared = buildPhaseSignalMap([linkForSignal(nativeSignals[0], "A", 7), linkForSignal(nativeSignals[3], "B", 7)], nativeSignals, {});
|
||||||
|
assert.deepEqual(shared.byPhase.get("7").slice().sort(), [nativeSignals[0].nodeKey, nativeSignals[3].nodeKey].sort());
|
||||||
|
|
||||||
|
// A link nowhere near the intersection is reported, not silently dropped.
|
||||||
|
const stray = { id: "far", geom: JSON.stringify({ type: "LineString", coordinates: [[113, 29], [113.001, 29.001]] }), phaseList: [{ phase: 9 }] };
|
||||||
|
const strayResult = buildPhaseSignalMap([stray], nativeSignals, {});
|
||||||
|
assert.equal(strayResult.bound, 0);
|
||||||
|
assert.equal(strayResult.unbound.length, 1);
|
||||||
|
assert.equal(strayResult.unbound[0].phaseNo, "9");
|
||||||
|
assert.ok(strayResult.unbound[0].reason);
|
||||||
|
|
||||||
|
// Config override is the escape hatch when geometry cannot bind.
|
||||||
|
const overridden = buildPhaseSignalMap([stray], nativeSignals, { phaseSignalMap: { 9: ["ts_forced"] } });
|
||||||
|
assert.deepEqual(overridden.byPhase.get("9"), ["ts_forced"]);
|
||||||
|
assert.equal(overridden.unbound.length, 0);
|
||||||
|
|
||||||
|
// Unusable geometry is reported rather than throwing.
|
||||||
|
const brokenGeom = buildPhaseSignalMap([{ id: "x", geom: "{not json", phaseList: [{ phase: 5 }] }], nativeSignals, {});
|
||||||
|
assert.equal(brokenGeom.unbound[0].reason, "link geometry unusable");
|
||||||
|
|
||||||
|
// --- signal entries handed to the preview -----------------------------------
|
||||||
|
const entries = signalEntriesFrom(
|
||||||
|
[{ phaseNo: 1, status: 23, countDown: 12 }, { phaseNo: 2, status: 21, countDown: 4 }],
|
||||||
|
new Map([["1", ["nodeA", "nodeB"]], ["2", ["nodeC"]]]),
|
||||||
|
);
|
||||||
|
assert.deepEqual(entries, [
|
||||||
|
{ phaseNo: "1", nodeKeys: ["nodeA", "nodeB"], color: "green", countDown: 12 },
|
||||||
|
{ phaseNo: "2", nodeKeys: ["nodeC"], color: "red", countDown: 4 },
|
||||||
|
]);
|
||||||
|
assert.deepEqual(signalEntriesFrom([{ phaseNo: 8, status: 22 }], new Map()),
|
||||||
|
[{ phaseNo: "8", nodeKeys: [], color: "yellow", countDown: NaN }],
|
||||||
|
"an unbound phase still reports its colour");
|
||||||
|
|
||||||
|
// --- vehicle normalization --------------------------------------------------
|
||||||
|
assert.deepEqual(normalizeObuVehicle(JSON.stringify({ carCode: "car-7", plateNumber: "A12345", lon: 114.12865, lat: 30.46049, angle: 90, speed: 12 })), {
|
||||||
|
id: "obu-car-7", label: "A12345", kind: "obu", longitude: 114.12865, latitude: 30.46049, angle: 90, speed: 12,
|
||||||
|
});
|
||||||
|
assert.equal(normalizeObuVehicle("{bad json"), null);
|
||||||
|
const obuPush = normalizeObuPush(JSON.stringify({ carCode: "c1", lon: 114.1, lat: 30.4, interval: 800 }));
|
||||||
|
assert.equal(obuPush.interval, 800);
|
||||||
|
assert.equal(obuPush.vehicle.id, "obu-c1");
|
||||||
|
|
||||||
|
// type/subType survive normalization because the model name is built from them.
|
||||||
|
assert.deepEqual(normalizeTargetVehicles(JSON.stringify({ data: { 8: [{ id: 9, longitude: 114.12866, latitude: 30.4605, type: 1, subType: 2, angle: 180, speed: 5 }] } })), [{
|
||||||
|
id: "8-9-12", label: "8-9", kind: "target", longitude: 114.12866, latitude: 30.4605, angle: 180, speed: 5, type: 1, subType: 2,
|
||||||
|
}]);
|
||||||
|
assert.equal(normalizeTargetPush(JSON.stringify({ data: { 1519: [{ id: "50089", longitude: 114.12876415699589, latitude: 30.46060781353787, type: 1, subType: 1 }] }, interval: 1000 })).vehicles.length, 1,
|
||||||
|
"the live targetPosition payload uses numeric object keys and string target ids");
|
||||||
|
assert.equal(normalizeTargetPush('{data:{1519:[{id:"53122",longitude:114.12871535072304,latitude:30.46061866463221,type:1,subType:1}]},interval:1000}').vehicles.length, 1,
|
||||||
|
"unquoted numeric device-id keys are accepted from the live targetPosition stream");
|
||||||
|
const targetPush = normalizeTargetPush(JSON.stringify({ interval: 0, data: { 8: [{ id: 9, longitude: 114.1, latitude: 30.4, type: 1 }] } }));
|
||||||
|
assert.equal(targetPush.vehicles[0].subType, 1, "type 1 without subType defaults to subType 1");
|
||||||
|
assert.equal(resolvePushInterval(targetPush.interval), 500, "interval 0 falls back to 500");
|
||||||
|
assert.equal(resolvePushInterval(undefined), 500);
|
||||||
|
assert.equal(resolvePushInterval(900), 900);
|
||||||
|
|
||||||
|
// --- AC8: model naming matches the dashboard --------------------------------
|
||||||
|
assert.equal(modelNameFor({ kind: "obu" }), "11.glb");
|
||||||
|
assert.equal(modelNameFor({ kind: "target", type: 1, subType: 2 }), "12.glb");
|
||||||
|
assert.equal(modelNameFor({ kind: "target" }), "11.glb");
|
||||||
|
|
||||||
|
// --- AC5: vehicle lifecycle -------------------------------------------------
|
||||||
|
let clock = 1000;
|
||||||
|
const registry = createVehicleRegistry({ now: () => clock });
|
||||||
|
registry.ingest([{ id: "v1", kind: "target", type: 1, subType: 1 }], 1000);
|
||||||
|
assert.equal(registry.list().length, 1);
|
||||||
|
assert.equal(registry.list()[0].visible, true);
|
||||||
|
assert.equal(registry.visibleSize, 1);
|
||||||
|
assert.equal(registry.list()[0].duration, 1000);
|
||||||
|
assert.deepEqual(registry.sweep(clock + 1499), [], "still fresh below interval * 1.5");
|
||||||
|
assert.deepEqual(registry.sweep(clock + 1500), ["v1"], "hidden at interval * 1.5");
|
||||||
|
assert.equal(registry.list()[0].visible, false);
|
||||||
|
assert.equal(registry.visibleSize, 0);
|
||||||
|
assert.equal(registry.list().length, 1, "hidden vehicles are kept as reusable slots, not removed");
|
||||||
|
|
||||||
|
clock = 5000;
|
||||||
|
registry.ingest([{ id: "v2", kind: "target", type: 1, subType: 1 }], 1000);
|
||||||
|
assert.equal(registry.list().length, 1, "a hidden slot of the same model is reused");
|
||||||
|
assert.equal(registry.list()[0].id, "v2");
|
||||||
|
assert.equal(registry.list()[0].visible, true);
|
||||||
|
|
||||||
|
registry.ingest([{ id: "v3", kind: "obu" }], 1000);
|
||||||
|
assert.equal(registry.list().length, 2, "a different model never steals another model's slot");
|
||||||
|
registry.ingest([{ id: "v2", kind: "target", type: 1, subType: 1 }], 1000);
|
||||||
|
assert.equal(registry.list().length, 2, "re-ingesting a known id updates in place");
|
||||||
|
registry.clear();
|
||||||
|
assert.equal(registry.list().length, 0);
|
||||||
|
|
||||||
|
// --- AC1/AC6: socket heartbeat, subscription frames, reconnect --------------
|
||||||
|
assert.equal(HEARTBEAT_MESSAGE, '{"heartBeat":"ping"}');
|
||||||
|
assert.equal(HEARTBEAT_INTERVAL_MS, 30000);
|
||||||
|
|
||||||
|
function fakeClock() {
|
||||||
|
const intervals = [];
|
||||||
|
const timeouts = [];
|
||||||
|
return {
|
||||||
|
intervals, timeouts,
|
||||||
|
setIntervalFn: (fn, ms) => intervals.push({ fn, ms }) - 1,
|
||||||
|
clearIntervalFn: (handle) => { intervals[handle] = null; },
|
||||||
|
setTimeoutFn: (fn, ms) => timeouts.push({ fn, ms }) - 1,
|
||||||
|
clearTimeoutFn: (handle) => { timeouts[handle] = null; },
|
||||||
|
pendingIntervals: () => intervals.filter(Boolean),
|
||||||
|
pendingTimeouts: () => timeouts.filter(Boolean),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const clockStub = fakeClock();
|
||||||
|
const sent = [];
|
||||||
|
let built = 0;
|
||||||
|
let live = null;
|
||||||
|
const socket = createSocket({
|
||||||
|
url: () => "wss://preview.example.test/websocket/network/ws/network/signal",
|
||||||
|
setIntervalFn: clockStub.setIntervalFn,
|
||||||
|
clearIntervalFn: clockStub.clearIntervalFn,
|
||||||
|
setTimeoutFn: clockStub.setTimeoutFn,
|
||||||
|
clearTimeoutFn: clockStub.clearTimeoutFn,
|
||||||
|
socketFactory: () => { built += 1; live = { readyState: 1, send: (data) => sent.push(data), close() {} }; return live; },
|
||||||
|
onOpen: ({ send }) => send(JSON.stringify({ junctionId: "420100023333" })),
|
||||||
|
});
|
||||||
|
socket.open();
|
||||||
|
live.onopen();
|
||||||
|
assert.deepEqual(sent, ['{"junctionId":"420100023333"}'], "subscription frame is sent on connect");
|
||||||
|
assert.equal(clockStub.pendingIntervals()[0].ms, 30000, "heartbeat runs at the dashboard's 30s");
|
||||||
|
clockStub.pendingIntervals()[0].fn();
|
||||||
|
clockStub.pendingIntervals()[0].fn();
|
||||||
|
assert.deepEqual(sent.slice(1), [HEARTBEAT_MESSAGE, HEARTBEAT_MESSAGE]);
|
||||||
|
|
||||||
|
live.onclose({});
|
||||||
|
assert.equal(clockStub.pendingTimeouts().length, 1, "a drop schedules a reconnect");
|
||||||
|
assert.equal(clockStub.pendingTimeouts()[0].ms, 1000, "first backoff is 1s");
|
||||||
|
sent.length = 0;
|
||||||
|
clockStub.pendingTimeouts()[0].fn();
|
||||||
|
live.onopen();
|
||||||
|
assert.equal(built, 2, "the socket reconnected");
|
||||||
|
assert.deepEqual(sent, ['{"junctionId":"420100023333"}'], "the subscription is replayed after reconnect");
|
||||||
|
|
||||||
|
socket.dispose();
|
||||||
|
const timeoutsBeforeClose = clockStub.pendingTimeouts().length;
|
||||||
|
live.onclose({});
|
||||||
|
assert.equal(clockStub.pendingTimeouts().length, timeoutsBeforeClose, "a disposed socket never reconnects");
|
||||||
|
|
||||||
|
// Target subscription frames match useTargetCars.ts.
|
||||||
|
function subscriptionFrame(onOpen) {
|
||||||
|
const frames = [];
|
||||||
|
onOpen({ send: (data) => frames.push(data) });
|
||||||
|
return frames;
|
||||||
|
}
|
||||||
|
assert.deepEqual(subscriptionFrame(({ send }) => send(JSON.stringify({ deviceId: null }))), ['{"deviceId":null}']);
|
||||||
|
assert.deepEqual(subscriptionFrame(({ send }) => send(JSON.stringify({ deviceId: [1, 2].join(",") }))), ['{"deviceId":"1,2"}']);
|
||||||
|
|
||||||
|
// --- OBU bounds frame -------------------------------------------------------
|
||||||
|
const bounds = buildBoundsMessage({ west: 114.12, south: 30.46, east: 114.14, north: 30.47 });
|
||||||
|
const corners = bounds.split(";");
|
||||||
|
assert.equal(corners.length, 4, "NW, NE, SE, SW");
|
||||||
|
corners.forEach((corner) => assert.equal(corner.split(",").length, 2));
|
||||||
|
// Corners are converted to GCJ-02 because the service filters in that frame.
|
||||||
|
assert.notEqual(Number(corners[0].split(",")[0]), 114.12);
|
||||||
|
assert.equal(buildBoundsMessage(null), "");
|
||||||
|
assert.equal(buildBoundsMessage({ west: NaN, south: 30.46, east: 114.14, north: 30.47 }), "");
|
||||||
|
|
||||||
|
// --- the overlay stays opt-in ----------------------------------------------
|
||||||
|
assert.equal(context.window.createV2xCesiumOverlay({ config: {} }), null, "disabled by default");
|
||||||
|
assert.equal(context.window.createV2xCesiumOverlay({ config: { v2xPreview: { enabled: false } } }), null);
|
||||||
|
|
||||||
|
console.log("V2X Cesium overlay tests passed.");
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const assert = require("assert");
|
||||||
|
const http = require("http");
|
||||||
|
const path = require("path");
|
||||||
|
const { createV2xPreviewServer, isProxyPath, upstreamPath } = require("./v2x-preview-server");
|
||||||
|
|
||||||
|
async function listen(server) {
|
||||||
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||||
|
return server.address().port;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request(port, pathName, options = {}) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const request = http.request({ hostname: "127.0.0.1", port, path: pathName, method: options.method || "GET", headers: options.headers }, (response) => {
|
||||||
|
let body = "";
|
||||||
|
response.setEncoding("utf8");
|
||||||
|
response.on("data", (chunk) => { body += chunk; });
|
||||||
|
response.on("end", () => resolve({ status: response.statusCode, body, headers: response.headers }));
|
||||||
|
});
|
||||||
|
request.on("error", reject);
|
||||||
|
request.end(options.body);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
assert.equal(isProxyPath("/api/facilities/api/sys/login"), true);
|
||||||
|
assert.equal(isProxyPath("/websocket/network/ws/network/obuPosition"), true);
|
||||||
|
assert.equal(isProxyPath("/package/manifest.json"), false);
|
||||||
|
assert.equal(upstreamPath("/api/facilities/api/sys/login?x=1"), "/facilities/api/sys/login?x=1");
|
||||||
|
assert.equal(upstreamPath("/websocket/network/ws/network/signal"), "/network/ws/network/signal");
|
||||||
|
// An upstream base path (deployments front the API as /dashboardApi) is kept.
|
||||||
|
assert.equal(upstreamPath("/api/facilities/api/sys/login", "/dashboardApi"), "/dashboardApi/facilities/api/sys/login");
|
||||||
|
assert.equal(upstreamPath("/websocket/network/ws/x", "/dashboardWebsocket/"), "/dashboardWebsocket/network/ws/x");
|
||||||
|
assert.equal(upstreamPath("/api/x", "/"), "/x");
|
||||||
|
|
||||||
|
const upstream = http.createServer((req, res) => {
|
||||||
|
let body = "";
|
||||||
|
req.on("data", (chunk) => { body += chunk; });
|
||||||
|
req.on("end", () => {
|
||||||
|
res.setHeader("Content-Type", "application/json");
|
||||||
|
res.end(JSON.stringify({ method: req.method, path: req.url, body }));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const upstreamPort = await listen(upstream);
|
||||||
|
const preview = createV2xPreviewServer({
|
||||||
|
root: path.join(__dirname, "..", "outputs", "fengshu-er-road"),
|
||||||
|
upstream: `http://127.0.0.1:${upstreamPort}`,
|
||||||
|
});
|
||||||
|
const previewPort = await listen(preview);
|
||||||
|
try {
|
||||||
|
const proxied = await request(previewPort, "/api/facilities/api/sys/login", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: '{"userName":"test"}',
|
||||||
|
});
|
||||||
|
assert.equal(proxied.status, 200);
|
||||||
|
assert.deepEqual(JSON.parse(proxied.body), { method: "POST", path: "/facilities/api/sys/login", body: '{"userName":"test"}' });
|
||||||
|
const staticPage = await request(previewPort, "/fengshu-er-road-cesium-preview.html");
|
||||||
|
assert.equal(staticPage.status, 200);
|
||||||
|
assert.match(staticPage.body, /Cesium Preview/);
|
||||||
|
} finally {
|
||||||
|
await Promise.all([new Promise((resolve) => preview.close(resolve)), new Promise((resolve) => upstream.close(resolve))]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same upstream, but reached through a prefixed base path.
|
||||||
|
const prefixedUpstream = http.createServer((req, res) => {
|
||||||
|
res.setHeader("Content-Type", "application/json");
|
||||||
|
res.end(JSON.stringify({ path: req.url }));
|
||||||
|
});
|
||||||
|
const prefixedPort = await listen(prefixedUpstream);
|
||||||
|
const prefixedPreview = createV2xPreviewServer({
|
||||||
|
root: path.join(__dirname, "..", "outputs", "fengshu-er-road"),
|
||||||
|
upstream: `http://127.0.0.1:${prefixedPort}/dashboardApi`,
|
||||||
|
wsUpstream: `http://127.0.0.1:${prefixedPort}/dashboardWebsocket`,
|
||||||
|
});
|
||||||
|
const prefixedPreviewPort = await listen(prefixedPreview);
|
||||||
|
try {
|
||||||
|
const proxied = await request(prefixedPreviewPort, "/api/facilities/api/sys/login");
|
||||||
|
assert.deepEqual(JSON.parse(proxied.body), { path: "/dashboardApi/facilities/api/sys/login" });
|
||||||
|
} finally {
|
||||||
|
await Promise.all([
|
||||||
|
new Promise((resolve) => prefixedPreview.close(resolve)),
|
||||||
|
new Promise((resolve) => prefixedUpstream.close(resolve)),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
console.log("V2X preview server tests passed.");
|
||||||
|
})().catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const http = require("http");
|
||||||
|
const https = require("https");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
const MIME_TYPES = {
|
||||||
|
".css": "text/css; charset=utf-8",
|
||||||
|
".glb": "model/gltf-binary",
|
||||||
|
".gltf": "model/gltf+json",
|
||||||
|
".html": "text/html; charset=utf-8",
|
||||||
|
".js": "text/javascript; charset=utf-8",
|
||||||
|
".json": "application/json; charset=utf-8",
|
||||||
|
".png": "image/png",
|
||||||
|
".ttf": "font/ttf",
|
||||||
|
".wasm": "application/wasm",
|
||||||
|
".svg": "image/svg+xml",
|
||||||
|
".ico": "image/x-icon",
|
||||||
|
};
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const values = {};
|
||||||
|
for (let index = 0; index < argv.length; index += 1) {
|
||||||
|
const argument = argv[index];
|
||||||
|
if (!argument.startsWith("--")) continue;
|
||||||
|
const key = argument.slice(2).replace(/-([a-z])/g, (_, char) => char.toUpperCase());
|
||||||
|
const value = argv[index + 1];
|
||||||
|
if (!value || value.startsWith("--")) throw new Error(`Missing value for ${argument}`);
|
||||||
|
values[key] = value;
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createV2xPreviewServer({ root, upstream, wsUpstream }) {
|
||||||
|
const staticRoot = path.resolve(root);
|
||||||
|
const upstreamUrl = new URL(upstream);
|
||||||
|
// Deployments front the API and the WebSocket with different prefixes (e.g.
|
||||||
|
// /dashboardApi and /dashboardWebsocket), so the two targets are separate.
|
||||||
|
const wsUpstreamUrl = wsUpstream ? new URL(wsUpstream) : upstreamUrl;
|
||||||
|
if (!fs.statSync(staticRoot).isDirectory()) throw new Error(`Preview root is not a directory: ${staticRoot}`);
|
||||||
|
if (!/^https?:$/.test(upstreamUrl.protocol)) throw new Error("V2X upstream must use http or https");
|
||||||
|
if (!/^https?:$/.test(wsUpstreamUrl.protocol)) throw new Error("V2X websocket upstream must use http or https");
|
||||||
|
|
||||||
|
const server = http.createServer((request, response) => {
|
||||||
|
if (isProxyPath(request.url)) {
|
||||||
|
proxyHttpRequest(request, response, upstreamUrl);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
serveStaticFile(request, response, staticRoot);
|
||||||
|
});
|
||||||
|
|
||||||
|
server.on("upgrade", (request, socket, head) => {
|
||||||
|
if (!isProxyPath(request.url)) {
|
||||||
|
socket.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
proxyWebSocket(request, socket, head, wsUpstreamUrl);
|
||||||
|
});
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isProxyPath(url) {
|
||||||
|
const pathname = new URL(url, "http://preview.local").pathname;
|
||||||
|
return pathname === "/api" || pathname.startsWith("/api/") ||
|
||||||
|
pathname === "/websocket" || pathname.startsWith("/websocket/");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The browser calls /api/... and /websocket/...; the local prefix is dropped and
|
||||||
|
// whatever base path the upstream URL carries is prepended, so an upstream of
|
||||||
|
// http://host:7862/dashboardApi maps /api/facilities/... onto
|
||||||
|
// /dashboardApi/facilities/... instead of the bare backend path.
|
||||||
|
function upstreamPath(url, basePath) {
|
||||||
|
const parsed = new URL(url, "http://preview.local");
|
||||||
|
const pathname = parsed.pathname.replace(/^\/(api|websocket)(?=\/|$)/, "") || "/";
|
||||||
|
const base = String(basePath || "").replace(/\/+$/, "");
|
||||||
|
return `${base}${pathname}${parsed.search}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function upstreamRequestOptions(request, upstreamUrl) {
|
||||||
|
return {
|
||||||
|
protocol: upstreamUrl.protocol,
|
||||||
|
hostname: upstreamUrl.hostname,
|
||||||
|
port: upstreamUrl.port || undefined,
|
||||||
|
method: request.method,
|
||||||
|
path: upstreamPath(request.url, upstreamUrl.pathname),
|
||||||
|
headers: { ...request.headers, host: upstreamUrl.host },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function proxyHttpRequest(request, response, upstreamUrl) {
|
||||||
|
const client = upstreamUrl.protocol === "https:" ? https : http;
|
||||||
|
const proxyRequest = client.request(upstreamRequestOptions(request, upstreamUrl), (proxyResponse) => {
|
||||||
|
response.writeHead(proxyResponse.statusCode || 502, proxyResponse.headers);
|
||||||
|
proxyResponse.pipe(response);
|
||||||
|
});
|
||||||
|
proxyRequest.on("error", (error) => {
|
||||||
|
if (!response.headersSent) {
|
||||||
|
response.writeHead(502, { "Content-Type": "application/json; charset=utf-8" });
|
||||||
|
response.end(JSON.stringify({ error: "V2X upstream unavailable", detail: error.message }));
|
||||||
|
} else {
|
||||||
|
response.destroy(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
request.pipe(proxyRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
function proxyWebSocket(request, socket, head, upstreamUrl) {
|
||||||
|
const client = upstreamUrl.protocol === "https:" ? https : http;
|
||||||
|
const options = upstreamRequestOptions(request, upstreamUrl);
|
||||||
|
options.headers = {
|
||||||
|
...options.headers,
|
||||||
|
connection: "Upgrade",
|
||||||
|
upgrade: "websocket",
|
||||||
|
};
|
||||||
|
const proxyRequest = client.request(options);
|
||||||
|
proxyRequest.on("upgrade", (proxyResponse, upstreamSocket, upstreamHead) => {
|
||||||
|
socket.write(`HTTP/${proxyResponse.httpVersion} ${proxyResponse.statusCode} ${proxyResponse.statusMessage}\r\n`);
|
||||||
|
Object.entries(proxyResponse.headers).forEach(([name, value]) => {
|
||||||
|
socket.write(`${name}: ${Array.isArray(value) ? value.join(", ") : value}\r\n`);
|
||||||
|
});
|
||||||
|
socket.write("\r\n");
|
||||||
|
if (upstreamHead.length) socket.write(upstreamHead);
|
||||||
|
if (head.length) upstreamSocket.write(head);
|
||||||
|
socket.pipe(upstreamSocket).pipe(socket);
|
||||||
|
});
|
||||||
|
proxyRequest.on("response", (proxyResponse) => {
|
||||||
|
socket.write(`HTTP/${proxyResponse.httpVersion} ${proxyResponse.statusCode} ${proxyResponse.statusMessage}\r\n\r\n`);
|
||||||
|
socket.destroy();
|
||||||
|
});
|
||||||
|
proxyRequest.on("error", () => socket.destroy());
|
||||||
|
proxyRequest.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
function serveStaticFile(request, response, root) {
|
||||||
|
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||||
|
response.writeHead(405, { Allow: "GET, HEAD" });
|
||||||
|
response.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const pathname = decodeURIComponent(new URL(request.url, "http://preview.local").pathname);
|
||||||
|
const relativePath = pathname === "/" ? "" : pathname.slice(1);
|
||||||
|
const filename = path.resolve(root, relativePath || "fengshu-er-road-cesium-preview.html");
|
||||||
|
if (!filename.startsWith(`${root}${path.sep}`) && filename !== root) {
|
||||||
|
response.writeHead(403);
|
||||||
|
response.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fs.stat(filename, (error, stat) => {
|
||||||
|
if (error || !stat.isFile()) {
|
||||||
|
response.writeHead(404);
|
||||||
|
response.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
response.writeHead(200, { "Content-Type": MIME_TYPES[path.extname(filename).toLowerCase()] || "application/octet-stream", "Cache-Control": "no-store" });
|
||||||
|
if (request.method === "HEAD") response.end();
|
||||||
|
else fs.createReadStream(filename).pipe(response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
const args = parseArgs(process.argv.slice(2));
|
||||||
|
const root = args.root || process.cwd();
|
||||||
|
const upstream = args.upstream || process.env.V2X_UPSTREAM;
|
||||||
|
const wsUpstream = args.wsUpstream || process.env.V2X_WS_UPSTREAM;
|
||||||
|
const port = Number(args.port || process.env.PORT || 7862);
|
||||||
|
const host = args.host || process.env.HOST || "0.0.0.0";
|
||||||
|
if (!upstream) throw new Error("Set V2X_UPSTREAM or pass --upstream http://host:port");
|
||||||
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Port must be an integer between 1 and 65535");
|
||||||
|
const server = createV2xPreviewServer({ root, upstream, wsUpstream });
|
||||||
|
server.listen(port, host, () => console.log(`V2X preview server: http://${host}:${port} -> ${upstream} (ws -> ${wsUpstream || upstream})`));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createV2xPreviewServer, isProxyPath, upstreamPath };
|
||||||
+146
-14
@@ -10,6 +10,8 @@ import Style from "/vendor/ol/style/Style.js";
|
|||||||
import Fill from "/vendor/ol/style/Fill.js";
|
import Fill from "/vendor/ol/style/Fill.js";
|
||||||
import Stroke from "/vendor/ol/style/Stroke.js";
|
import Stroke from "/vendor/ol/style/Stroke.js";
|
||||||
import CircleStyle from "/vendor/ol/style/Circle.js";
|
import CircleStyle from "/vendor/ol/style/Circle.js";
|
||||||
|
import Text from "/vendor/ol/style/Text.js";
|
||||||
|
import Polygon from "/vendor/ol/geom/Polygon.js";
|
||||||
import RegularShape from "/vendor/ol/style/RegularShape.js";
|
import RegularShape from "/vendor/ol/style/RegularShape.js";
|
||||||
import Select from "/vendor/ol/interaction/Select.js";
|
import Select from "/vendor/ol/interaction/Select.js";
|
||||||
import { click } from "/vendor/ol/events/condition.js";
|
import { click } from "/vendor/ol/events/condition.js";
|
||||||
@@ -61,6 +63,15 @@ controlsToggle.innerHTML = '<input data-layer="controls" type="checkbox" checked
|
|||||||
const signalsToggle = document.createElement("label");
|
const signalsToggle = document.createElement("label");
|
||||||
signalsToggle.innerHTML = '<input data-layer="signals" type="checkbox" checked> 红绿灯设施';
|
signalsToggle.innerHTML = '<input data-layer="signals" type="checkbox" checked> 红绿灯设施';
|
||||||
document.querySelector('[data-layer="lanes"]').closest("label").after(directionArrowsToggle, markingsToggle, centerLinesToggle, edgeLinesToggle, controlsToggle, signalsToggle);
|
document.querySelector('[data-layer="lanes"]').closest("label").after(directionArrowsToggle, markingsToggle, centerLinesToggle, edgeLinesToggle, controlsToggle, signalsToggle);
|
||||||
|
// Only offered when the server was started with --debug; without it the state
|
||||||
|
// carries no candidates and an empty toggle would just be confusing.
|
||||||
|
const candidateAction = document.createElement("section");
|
||||||
|
document.querySelector(".inspector").insertBefore(candidateAction, document.querySelector(".inspector details"));
|
||||||
|
const candidatesToggle = document.createElement("label");
|
||||||
|
candidatesToggle.hidden = true;
|
||||||
|
candidatesToggle.innerHTML = '<input data-layer="junctionCandidates" type="checkbox" checked> 复杂路口候选(debug)';
|
||||||
|
signalsToggle.after(candidatesToggle);
|
||||||
|
const gaodeReferenceColors = { 1: "#2563eb", 2: "#0f766e", 3: "#7c3aed", 4: "#ea580c", 5: "#64748b" };
|
||||||
|
|
||||||
let state;
|
let state;
|
||||||
let selectedRoad = null;
|
let selectedRoad = null;
|
||||||
@@ -83,6 +94,7 @@ const signalPicker = signalPanel.querySelector('[name="signal-picker"]');
|
|||||||
const source = () => new VectorSource();
|
const source = () => new VectorSource();
|
||||||
const layers = {
|
const layers = {
|
||||||
reference: new VectorLayer({ source: source(), visible: false, style: new Style({ fill: new Fill({ color: "rgba(123, 140, 148, .28)" }), stroke: new Stroke({ color: "#8999a0", width: 1 }) }) }),
|
reference: new VectorLayer({ source: source(), visible: false, style: new Style({ fill: new Fill({ color: "rgba(123, 140, 148, .28)" }), stroke: new Stroke({ color: "#8999a0", width: 1 }) }) }),
|
||||||
|
gaodeReference: new VectorLayer({ source: source(), visible: true, zIndex: 1, style: (feature) => { const color = gaodeReferenceColors[feature.get("type")] || "#475569"; return new Style({ fill: new Fill({ color: `${color}26` }), stroke: new Stroke({ color, width: 1.5 }) }); } }),
|
||||||
native: new VectorLayer({ source: source(), style: nativeSurfaceStyle }),
|
native: new VectorLayer({ source: source(), style: nativeSurfaceStyle }),
|
||||||
edgeLines: new VectorLayer({ source: source(), visible: false, style: markingStyle }),
|
edgeLines: new VectorLayer({ source: source(), visible: false, style: markingStyle }),
|
||||||
sidewalks: new VectorLayer({ source: source(), style: sidewalkSurfaceStyle }),
|
sidewalks: new VectorLayer({ source: source(), style: sidewalkSurfaceStyle }),
|
||||||
@@ -95,16 +107,21 @@ const layers = {
|
|||||||
signals: new VectorLayer({ source: source(), style: signalAssemblyStyle, zIndex: 30 }),
|
signals: new VectorLayer({ source: source(), style: signalAssemblyStyle, zIndex: 30 }),
|
||||||
osmDirection: new VectorLayer({ source: source(), style: (feature) => new Style({ image: new RegularShape({ points: 3, radius: 9, rotation: feature.get("rotation"), fill: new Fill({ color: "#006e91" }), stroke: new Stroke({ color: "#fff", width: 1.5 }) }) }), zIndex: 11 }),
|
osmDirection: new VectorLayer({ source: source(), style: (feature) => new Style({ image: new RegularShape({ points: 3, radius: 9, rotation: feature.get("rotation"), fill: new Fill({ color: "#006e91" }), stroke: new Stroke({ color: "#fff", width: 1.5 }) }) }), zIndex: 11 }),
|
||||||
connectors: new VectorLayer({ source: source(), style: (feature) => effectiveConnectorEnabled(feature.getProperties()) ? new Style({ stroke: new Stroke({ color: roadIdFromLane(feature.get("from_lane_id")) === selectedRoad?.id ? "#d1226f" : "#ad3a76", width: roadIdFromLane(feature.get("from_lane_id")) === selectedRoad?.id ? 4 : 2, lineDash: [7, 5] }) }) : null }),
|
connectors: new VectorLayer({ source: source(), style: (feature) => effectiveConnectorEnabled(feature.getProperties()) ? new Style({ stroke: new Stroke({ color: roadIdFromLane(feature.get("from_lane_id")) === selectedRoad?.id ? "#d1226f" : "#ad3a76", width: roadIdFromLane(feature.get("from_lane_id")) === selectedRoad?.id ? 4 : 2, lineDash: [7, 5] }) }) : null }),
|
||||||
|
junctionCandidates: new VectorLayer({ source: source(), visible: true, zIndex: 25, style: (feature) => [
|
||||||
|
new Style({ fill: new Fill({ color: "rgba(219, 39, 119, .12)" }), stroke: new Stroke({ color: "#db2777", width: 2, lineDash: [8, 5] }) }),
|
||||||
|
new Style({ text: new Text({ text: `#${feature.get("index")} ${feature.get("nodeCount")}节点`, font: "bold 13px system-ui, sans-serif", fill: new Fill({ color: "#831843" }), stroke: new Stroke({ color: "#fff", width: 3 }), offsetY: -14 }) }),
|
||||||
|
] }),
|
||||||
diagnostics: new VectorLayer({ source: source(), style: (feature) => new Style({ image: new CircleStyle({ radius: 6, fill: new Fill({ color: feature.get("severity") === "error" ? "#bf3b2e" : "#d49318" }), stroke: new Stroke({ color: "#fff", width: 1 }) }) }) }),
|
diagnostics: new VectorLayer({ source: source(), style: (feature) => new Style({ image: new CircleStyle({ radius: 6, fill: new Fill({ color: feature.get("severity") === "error" ? "#bf3b2e" : "#d49318" }), stroke: new Stroke({ color: "#fff", width: 1 }) }) }) }),
|
||||||
selectedRoad: new VectorLayer({ source: source(), style: new Style({ stroke: new Stroke({ color: "#00a5cf", width: 8 }) }), zIndex: 10 }),
|
selectedRoad: new VectorLayer({ source: source(), style: new Style({ stroke: new Stroke({ color: "#00a5cf", width: 8 }) }), zIndex: 10 }),
|
||||||
selectedMovement: new VectorLayer({ source: source(), style: new Style({ stroke: new Stroke({ color: "#f0b323", width: 6 }) }), zIndex: 12 }),
|
selectedMovement: new VectorLayer({ source: source(), style: new Style({ stroke: new Stroke({ color: "#f0b323", width: 6 }) }), zIndex: 12 }),
|
||||||
};
|
};
|
||||||
const map = new Map({ target: "map", layers: [layers.reference, layers.native, layers.edgeLines, layers.sidewalks, layers.osm, layers.lanes, layers.directionArrows, layers.markings, layers.centerLines, layers.controls, layers.signals, layers.connectors, layers.diagnostics, layers.selectedRoad, layers.osmDirection, layers.selectedMovement], view: new View({ center: [0, 0], zoom: 2 }) });
|
const map = new Map({ target: "map", layers: [layers.gaodeReference, layers.reference, layers.native, layers.edgeLines, layers.sidewalks, layers.osm, layers.lanes, layers.directionArrows, layers.markings, layers.centerLines, layers.controls, layers.signals, layers.connectors, layers.junctionCandidates, layers.diagnostics, layers.selectedRoad, layers.osmDirection, layers.selectedMovement], view: new View({ center: [0, 0], zoom: 2 }) });
|
||||||
const select = new Select({ condition: click, layers: (layer) => manualFromEndpoint ? layer === layers.osm : [layers.osm, layers.lanes, layers.directionArrows, layers.markings, layers.centerLines, layers.edgeLines, layers.controls, layers.signals, layers.connectors, layers.native, layers.diagnostics].includes(layer), hitTolerance: 12, style: null });
|
const select = new Select({ condition: click, layers: (layer) => manualFromEndpoint ? layer === layers.osm : [layers.osm, layers.lanes, layers.directionArrows, layers.markings, layers.centerLines, layers.edgeLines, layers.controls, layers.signals, layers.connectors, layers.native, layers.junctionCandidates, layers.diagnostics].includes(layer), hitTolerance: 12, style: null });
|
||||||
map.addInteraction(select);
|
map.addInteraction(select);
|
||||||
select.on("select", ({ selected }) => {
|
select.on("select", ({ selected }) => {
|
||||||
const feature = selected[0];
|
const feature = selected[0];
|
||||||
if (!feature) return;
|
if (!feature) return;
|
||||||
|
if (feature.get("candidate_index")) return selectJunctionCandidate(feature);
|
||||||
if (feature.get("signal_uid")) return selectSignal(poleFeatureForSignal(feature.get("signal_uid")) || feature);
|
if (feature.get("signal_uid")) return selectSignal(poleFeatureForSignal(feature.get("signal_uid")) || feature);
|
||||||
if (manualFromEndpoint) return chooseManualTarget(roadForFeature(feature));
|
if (manualFromEndpoint) return chooseManualTarget(roadForFeature(feature));
|
||||||
const junction = junctionForFeature(feature);
|
const junction = junctionForFeature(feature);
|
||||||
@@ -155,7 +172,7 @@ function osmDirectionLabel(road) { return road?.direction === "forward" ? "沿 O
|
|||||||
function roadIdFromLane(laneId) { return typeof laneId === "string" ? laneId.slice(5, laneId.lastIndexOf(":")) : ""; }
|
function roadIdFromLane(laneId) { return typeof laneId === "string" ? laneId.slice(5, laneId.lastIndexOf(":")) : ""; }
|
||||||
function laneIndex(laneId) { return Number(String(laneId).split(":").at(-1)); }
|
function laneIndex(laneId) { return Number(String(laneId).split(":").at(-1)); }
|
||||||
function lanePositionLabel(road, index) { return road?.laneCount === 1 ? "唯一车道" : `左起第 ${index} 车道`; }
|
function lanePositionLabel(road, index) { return road?.laneCount === 1 ? "唯一车道" : `左起第 ${index} 车道`; }
|
||||||
function laneStyle(feature) { const selected = feature.get("road_id") === selectedRoad?.id; return new Style({ stroke: new Stroke({ color: selected ? "#006e91" : "#f5f6ee", width: selected ? 3 : 1.3, lineDash: [5, 4] }) }); }
|
function laneStyle(feature) { const roadId = feature.get("road_id"); const selected = Boolean(roadId && selectedRoad && roadId === selectedRoad.id); const composite = feature.get("cluster_preview"); return new Style({ stroke: new Stroke({ color: selected ? "#006e91" : "#f5f6ee", width: selected ? 3 : composite ? 1.6 : 1.3, lineDash: composite ? [7, 5] : [5, 4] }) }); }
|
||||||
function markingStyle(feature) { const yellow = feature?.get("color") === "yellow"; return new Style({ fill: new Fill({ color: yellow ? "#f5be2a" : "#f5f6ee" }), stroke: new Stroke({ color: yellow ? "#d29d16" : "#d9dacf", width: 1 }) }); }
|
function markingStyle(feature) { const yellow = feature?.get("color") === "yellow"; return new Style({ fill: new Fill({ color: yellow ? "#f5be2a" : "#f5f6ee" }), stroke: new Stroke({ color: yellow ? "#d29d16" : "#d9dacf", width: 1 }) }); }
|
||||||
function signalAssemblyStyle(feature) { const component = feature.get("signal_component"); if (component === "mast") return [new Style({ stroke: new Stroke({ color: "#fff", width: 9 }) }), new Style({ stroke: new Stroke({ color: "#007f99", width: 5 }) })]; if (component === "face") return [new Style({ stroke: new Stroke({ color: "#fff", width: 7 }) }), new Style({ stroke: new Stroke({ color: "#df2435", width: 3 }) })]; if (component === "head") { const heading = Number(feature.get("face_heading_deg")) || 0; return new Style({ image: new RegularShape({ points: 3, radius: 8, rotation: heading * Math.PI / 180, fill: new Fill({ color: "#df2435" }), stroke: new Stroke({ color: "#fff", width: 2 }) }) }); } return new Style({ image: new RegularShape({ points: 4, radius: 6, angle: Math.PI / 4, fill: new Fill({ color: "#263630" }), stroke: new Stroke({ color: "#fff", width: 2 }) }) }); }
|
function signalAssemblyStyle(feature) { const component = feature.get("signal_component"); if (component === "mast") return [new Style({ stroke: new Stroke({ color: "#fff", width: 9 }) }), new Style({ stroke: new Stroke({ color: "#007f99", width: 5 }) })]; if (component === "face") return [new Style({ stroke: new Stroke({ color: "#fff", width: 7 }) }), new Style({ stroke: new Stroke({ color: "#df2435", width: 3 }) })]; if (component === "head") { const heading = Number(feature.get("face_heading_deg")) || 0; return new Style({ image: new RegularShape({ points: 3, radius: 8, rotation: heading * Math.PI / 180, fill: new Fill({ color: "#df2435" }), stroke: new Stroke({ color: "#fff", width: 2 }) }) }); } return new Style({ image: new RegularShape({ points: 4, radius: 6, angle: Math.PI / 4, fill: new Fill({ color: "#263630" }), stroke: new Stroke({ color: "#fff", width: 2 }) }) }); }
|
||||||
function centerLineStyle(feature) { const white = feature.get("color") === "white"; const color = white ? "#faf9ee" : "#f5be2a"; return new Style({ fill: new Fill({ color }), stroke: new Stroke({ color: feature.get("pattern") === "solid" ? color : white ? "#aeb0aa" : "#d29d16", width: feature.get("pattern") === "solid" ? .25 : .8 }) }); }
|
function centerLineStyle(feature) { const white = feature.get("color") === "white"; const color = white ? "#faf9ee" : "#f5be2a"; return new Style({ fill: new Fill({ color }), stroke: new Stroke({ color: feature.get("pattern") === "solid" ? color : white ? "#aeb0aa" : "#d29d16", width: feature.get("pattern") === "solid" ? .25 : .8 }) }); }
|
||||||
@@ -163,6 +180,9 @@ function nativeSurfaceStyle(feature) {
|
|||||||
// Split road features meet at OSM junction nodes. Their per-feature outlines
|
// Split road features meet at OSM junction nodes. Their per-feature outlines
|
||||||
// are editing aids, not physical seams, so scene mode must render fills only.
|
// are editing aids, not physical seams, so scene mode must render fills only.
|
||||||
if (scenePreview) return new Style({ fill: new Fill({ color: "#3f4b50" }) });
|
if (scenePreview) return new Style({ fill: new Fill({ color: "#3f4b50" }) });
|
||||||
|
if (feature.get("cluster_id") && feature.get("complex_part")) return new Style({ fill: new Fill({ color: "#6f948a" }) });
|
||||||
|
if (feature.get("kind") === "cluster") return new Style({ fill: new Fill({ color: "rgba(20, 132, 112, .5)" }), stroke: new Stroke({ color: "#075e4f", width: 4, lineDash: [10, 5] }) });
|
||||||
|
if (feature.get("template")) return new Style({ fill: new Fill({ color: "rgba(20, 132, 112, .46)" }), stroke: new Stroke({ color: "#087c67", width: 3, lineDash: [7, 4] }) });
|
||||||
return feature.get("native_id")?.startsWith("junction:")
|
return feature.get("native_id")?.startsWith("junction:")
|
||||||
? new Style({ fill: new Fill({ color: "rgba(12, 116, 91, .38)" }), stroke: new Stroke({ color: "#0e785f", width: 1.5 }) })
|
? new Style({ fill: new Fill({ color: "rgba(12, 116, 91, .38)" }), stroke: new Stroke({ color: "#0e785f", width: 1.5 }) })
|
||||||
: new Style({ fill: new Fill({ color: "rgba(40, 105, 86, .35)" }), stroke: new Stroke({ color: "#296956", width: 1 }) });
|
: new Style({ fill: new Fill({ color: "rgba(40, 105, 86, .35)" }), stroke: new Stroke({ color: "#296956", width: 1 }) });
|
||||||
@@ -180,33 +200,127 @@ function roadForFeature(feature) {
|
|||||||
const roadId = properties.road_id || properties.subjectId || roadIdFromLane(properties.from_lane_id) || properties.directional_road_ids?.split(",")[0];
|
const roadId = properties.road_id || properties.subjectId || roadIdFromLane(properties.from_lane_id) || properties.directional_road_ids?.split(",")[0];
|
||||||
return state.compiled.model.roads.find((road) => road.id === roadId) || null;
|
return state.compiled.model.roads.find((road) => road.id === roadId) || null;
|
||||||
}
|
}
|
||||||
function junctionForFeature(feature) { const id = feature.get("native_id"); return id?.startsWith("junction:") ? layers.native.getSource().getFeatures().find((item) => item.get("native_id") === id) : null; }
|
function junctionForFeature(feature) { const id = feature.get("native_id"); return id?.startsWith("junction:") || id?.startsWith("junction-cluster:") ? layers.native.getSource().getFeatures().find((item) => item.get("native_id") === id) : null; }
|
||||||
function endpointFor(road, side) { return state.compiled.model.endpoints.find((endpoint) => endpoint.roadId === road?.id && endpoint.side === side) || null; }
|
function endpointFor(road, side) { return state.compiled.model.endpoints.find((endpoint) => endpoint.roadId === road?.id && endpoint.side === side) || null; }
|
||||||
function endpointsCompatible(from, to) { if (!from || !to || from.roadId === to.roadId || from.side !== "end" || to.side !== "start") return false; if (from.nodeId === to.nodeId) return true; const dx = (from.coordinate[0] - to.coordinate[0]) * 111320 * Math.cos(from.coordinate[1] * Math.PI / 180); const dy = (from.coordinate[1] - to.coordinate[1]) * 111320; return Math.hypot(dx, dy) <= 35; }
|
function endpointsCompatible(from, to) { if (!from || !to || from.roadId === to.roadId || from.side !== "end" || to.side !== "start") return false; if (from.nodeId === to.nodeId) return true; const dx = (from.coordinate[0] - to.coordinate[0]) * 111320 * Math.cos(from.coordinate[1] * Math.PI / 180); const dy = (from.coordinate[1] - to.coordinate[1]) * 111320; return Math.hypot(dx, dy) <= 35; }
|
||||||
function readFeatures(collection) { return geojson.readFeatures(collection || { type: "FeatureCollection", features: [] }, { dataProjection: "EPSG:4326", featureProjection: "EPSG:3857" }); }
|
function readFeatures(collection, predicate = null) { const source = collection || { type: "FeatureCollection", features: [] }; const filtered = predicate ? { ...source, features: (source.features || []).filter(predicate) } : source; return geojson.readFeatures(filtered, { dataProjection: "EPSG:4326", featureProjection: "EPSG:3857" }); }
|
||||||
function rawRoadFeatures() { return state.compiled.model.roads.map((road) => new Feature({ geometry: new LineString(road.centerline).transform("EPSG:4326", "EPSG:3857"), road_id: road.id })); }
|
function rawRoadFeatures() { return state.compiled.model.roads.map((road) => new Feature({ geometry: new LineString(road.centerline).transform("EPSG:4326", "EPSG:3857"), road_id: road.id })); }
|
||||||
function updateSources() {
|
function updateSources() {
|
||||||
layers.reference.getSource().clear(); layers.reference.getSource().addFeatures(readFeatures(state.layers.osm2streetsRoadSurface));
|
layers.reference.getSource().clear(); layers.reference.getSource().addFeatures(readFeatures(state.layers.osm2streetsRoadSurface));
|
||||||
|
layers.gaodeReference.getSource().clear(); layers.gaodeReference.getSource().addFeatures(readFeatures(state.junctionReference?.converted));
|
||||||
layers.native.getSource().clear(); layers.native.getSource().addFeatures([...readFeatures(state.layers.nativeRoadSurface), ...readFeatures(state.layers.nativeIntersectionSurface)]);
|
layers.native.getSource().clear(); layers.native.getSource().addFeatures([...readFeatures(state.layers.nativeRoadSurface), ...readFeatures(state.layers.nativeIntersectionSurface)]);
|
||||||
layers.sidewalks.getSource().clear(); layers.sidewalks.getSource().addFeatures(readFeatures(state.layers.nativeSidewalkSurface));
|
layers.sidewalks.getSource().clear(); layers.sidewalks.getSource().addFeatures(readFeatures(state.layers.nativeSidewalkSurface));
|
||||||
layers.osm.getSource().clear(); layers.osm.getSource().addFeatures(rawRoadFeatures());
|
layers.osm.getSource().clear(); layers.osm.getSource().addFeatures(rawRoadFeatures());
|
||||||
layers.lanes.getSource().clear(); layers.lanes.getSource().addFeatures(readFeatures(state.layers.laneCenterlines));
|
layers.lanes.getSource().clear(); layers.lanes.getSource().addFeatures(readFeatures(state.layers.laneCenterlines, (feature) => !feature.properties?.cluster_internal && !feature.properties?.cluster_preview_hidden));
|
||||||
layers.edgeLines.getSource().clear(); layers.edgeLines.getSource().addFeatures(readFeatures(state.layers.edgeLines));
|
layers.edgeLines.getSource().clear(); layers.edgeLines.getSource().addFeatures(readFeatures(state.layers.edgeLines));
|
||||||
layers.directionArrows.getSource().clear(); layers.directionArrows.getSource().addFeatures(readFeatures(state.layers.directionArrows));
|
layers.directionArrows.getSource().clear(); layers.directionArrows.getSource().addFeatures(readFeatures(state.layers.directionArrows, (feature) => !feature.properties?.cluster_preview_hidden));
|
||||||
layers.markings.getSource().clear(); layers.markings.getSource().addFeatures([...readFeatures(state.layers.laneSeparators), ...readFeatures(state.layers.turnArrows)]);
|
layers.markings.getSource().clear(); layers.markings.getSource().addFeatures([...readFeatures(state.layers.laneSeparators, (feature) => !feature.properties?.cluster_preview_hidden), ...readFeatures(state.layers.turnArrows, (feature) => !feature.properties?.cluster_preview_hidden)]);
|
||||||
layers.centerLines.getSource().clear(); layers.centerLines.getSource().addFeatures(readFeatures(state.layers.centerLines));
|
layers.centerLines.getSource().clear(); layers.centerLines.getSource().addFeatures(readFeatures(state.layers.centerLines, (feature) => !feature.properties?.cluster_preview_hidden));
|
||||||
layers.controls.getSource().clear(); layers.controls.getSource().addFeatures([...readFeatures(state.layers.crosswalks), ...readFeatures(state.layers.vehicleStopLines)]);
|
layers.controls.getSource().clear(); layers.controls.getSource().addFeatures([...readFeatures(state.layers.crosswalks), ...readFeatures(state.layers.vehicleStopLines)]);
|
||||||
const signalFeatures = readFeatures(state.trafficSignals?.assemblies || { type: "FeatureCollection", features: [] }); const armFeatures = []; const faceFeatures = []; const headFeatures = []; for (const signal of state.trafficRuntime?.signals || []) { const arm = signal.pose?.arm; const head = signal.pose?.head; if (!arm || !head) continue; const properties = { signal_uid: signal.id }; const headPoint = fromLonLat([head.longitude, head.latitude]); const radians = Number(head.faceHeadingDegrees) * Math.PI / 180; const faceEnd = [headPoint[0] + Math.sin(radians) * 2.5, headPoint[1] + Math.cos(radians) * 2.5]; armFeatures.push(new Feature({ geometry: new LineString([fromLonLat([arm.from.longitude, arm.from.latitude]), fromLonLat([arm.to.longitude, arm.to.latitude])]), signal_component: "mast", ...properties })); faceFeatures.push(new Feature({ geometry: new LineString([headPoint, faceEnd]), signal_component: "face", ...properties })); headFeatures.push(new Feature({ geometry: new Point(faceEnd), signal_component: "head", face_heading_deg: head.faceHeadingDegrees, ...properties })); } layers.signals.getSource().clear(); layers.signals.getSource().addFeatures([...armFeatures, ...faceFeatures, ...signalFeatures, ...headFeatures]); const pickerValue = signalPicker.value; signalPicker.replaceChildren(new Option("选择设施", "")); signalFeatures.forEach((feature) => signalPicker.add(new Option(feature.get("display_id") || feature.get("signal_uid"), feature.get("signal_uid")))); signalPicker.value = pickerValue;
|
const signalFeatures = readFeatures(state.trafficSignals?.assemblies || { type: "FeatureCollection", features: [] }); const armFeatures = []; const faceFeatures = []; const headFeatures = []; for (const signal of state.trafficRuntime?.signals || []) { const arm = signal.pose?.arm; const head = signal.pose?.head; if (!arm || !head) continue; const properties = { signal_uid: signal.id }; const headPoint = fromLonLat([head.longitude, head.latitude]); const radians = Number(head.faceHeadingDegrees) * Math.PI / 180; const faceEnd = [headPoint[0] + Math.sin(radians) * 2.5, headPoint[1] + Math.cos(radians) * 2.5]; armFeatures.push(new Feature({ geometry: new LineString([fromLonLat([arm.from.longitude, arm.from.latitude]), fromLonLat([arm.to.longitude, arm.to.latitude])]), signal_component: "mast", ...properties })); faceFeatures.push(new Feature({ geometry: new LineString([headPoint, faceEnd]), signal_component: "face", ...properties })); headFeatures.push(new Feature({ geometry: new Point(faceEnd), signal_component: "head", face_heading_deg: head.faceHeadingDegrees, ...properties })); } layers.signals.getSource().clear(); layers.signals.getSource().addFeatures([...armFeatures, ...faceFeatures, ...signalFeatures, ...headFeatures]); const pickerValue = signalPicker.value; signalPicker.replaceChildren(new Option("选择设施", "")); signalFeatures.forEach((feature) => signalPicker.add(new Option(feature.get("display_id") || feature.get("signal_uid"), feature.get("signal_uid")))); signalPicker.value = pickerValue;
|
||||||
layers.connectors.getSource().clear(); layers.connectors.getSource().addFeatures(readFeatures(state.layers.connectors));
|
layers.connectors.getSource().clear(); layers.connectors.getSource().addFeatures(readFeatures(state.layers.connectors, (feature) => !feature.properties?.cluster_internal));
|
||||||
|
candidatesToggle.hidden = !(state.debug?.junctionCandidates || []).length;
|
||||||
|
renderJunctionCandidates();
|
||||||
layers.diagnostics.getSource().clear(); layers.diagnostics.getSource().addFeatures(readFeatures({ type: "FeatureCollection", features: state.compiled.diagnostics.filter((item) => item.geometry).map(({ geometry, ...properties }) => ({ type: "Feature", properties, geometry })) }));
|
layers.diagnostics.getSource().clear(); layers.diagnostics.getSource().addFeatures(readFeatures({ type: "FeatureCollection", features: state.compiled.diagnostics.filter((item) => item.geometry).map(({ geometry, ...properties }) => ({ type: "Feature", properties, geometry })) }));
|
||||||
const extent = layers.osm.getSource().getExtent(); if (Number.isFinite(extent[0])) map.getView().fit(extent, { padding: [48, 48, 48, 48], maxZoom: 19 });
|
const extent = layers.osm.getSource().getExtent(); if (Number.isFinite(extent[0])) map.getView().fit(extent, { padding: [48, 48, 48, 48], maxZoom: 19 });
|
||||||
}
|
}
|
||||||
|
// Draw one convex-ish hull per candidate cluster so the whole intersection is
|
||||||
|
// outlined, not just its centre, and label it with the same index the inspector
|
||||||
|
// and the console listing use.
|
||||||
|
function renderJunctionCandidates() {
|
||||||
|
const source = layers.junctionCandidates.getSource();
|
||||||
|
source.clear();
|
||||||
|
const list = state.debug?.junctionCandidates || [];
|
||||||
|
if (!list.length) return;
|
||||||
|
for (const candidate of list) {
|
||||||
|
const nodes = candidate.nodeIds.map((nodeId) => nodeCoordinate(nodeId)).filter(Boolean);
|
||||||
|
if (!nodes.length) continue;
|
||||||
|
const ring = candidateRing(nodes, Math.max(12, candidate.coreRadiusMeters * .6));
|
||||||
|
source.addFeature(new Feature({ geometry: new Polygon([ring]), candidate_index: candidate.index, index: candidate.index, nodeCount: candidate.nodeCount, candidate_id: candidate.id }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function nodeCoordinate(nodeId) {
|
||||||
|
for (const road of state.compiled.model.roads) {
|
||||||
|
const at = road.sourceNodeIds.findIndex((item) => String(item) === String(nodeId));
|
||||||
|
if (at === 0) return road.centerline[0];
|
||||||
|
if (at === road.sourceNodeIds.length - 1) return road.centerline.at(-1);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// A rounded envelope around the member nodes: sample a circle of `padMeters`
|
||||||
|
// around each node and take the outer boundary by angle from the centroid.
|
||||||
|
function candidateRing(nodes, padMeters) {
|
||||||
|
const centre = nodes.reduce((sum, point) => [sum[0] + point[0] / nodes.length, sum[1] + point[1] / nodes.length], [0, 0]);
|
||||||
|
const metresPerLon = 111320 * Math.cos(centre[1] * Math.PI / 180);
|
||||||
|
const points = [];
|
||||||
|
for (let degrees = 0; degrees < 360; degrees += 12) {
|
||||||
|
const radians = degrees * Math.PI / 180;
|
||||||
|
let best = null;
|
||||||
|
for (const node of nodes) {
|
||||||
|
const point = [node[0] + Math.sin(radians) * padMeters / metresPerLon, node[1] + Math.cos(radians) * padMeters / 111320];
|
||||||
|
const reach = (point[0] - centre[0]) * metresPerLon * Math.sin(radians) + (point[1] - centre[1]) * 111320 * Math.cos(radians);
|
||||||
|
if (!best || reach > best.reach) best = { point, reach };
|
||||||
|
}
|
||||||
|
points.push(fromLonLat(best.point));
|
||||||
|
}
|
||||||
|
return [...points, points[0]];
|
||||||
|
}
|
||||||
|
function selectJunctionCandidate(feature) {
|
||||||
|
const candidate = (state.debug?.junctionCandidates || []).find((item) => item.index === feature.get("candidate_index"));
|
||||||
|
if (!candidate) return;
|
||||||
|
selectedRoad = null; selectedMovement = null; selectedJunction = null;
|
||||||
|
form.hidden = true; hint.hidden = false; selectedJunctionPanel.hidden = true;
|
||||||
|
hint.textContent = `复杂路口候选 #${candidate.index}:${candidate.nodeCount} 个节点,直径 ${candidate.diameterMeters} 米。下方是可直接粘贴到 config 的片段。`;
|
||||||
|
evidence.textContent = JSON.stringify({
|
||||||
|
说明: "复制到 config/areas/<区域>.json 的 nativeRoad.junctionTemplates.clusters 数组,然后重新编译",
|
||||||
|
片段: {
|
||||||
|
id: `cluster-${candidate.nodeIds[0]}`,
|
||||||
|
template: candidate.template,
|
||||||
|
nodeIds: candidate.nodeIds,
|
||||||
|
coreRadiusMeters: candidate.coreRadiusMeters,
|
||||||
|
cornerRadiusMeters: 12,
|
||||||
|
outerRadiusExtraMeters: 18,
|
||||||
|
},
|
||||||
|
实测: { 节点数: candidate.nodeCount, 直径米: candidate.diameterMeters, 最长内部连接米: candidate.longestLinkMeters, 最宽进口米: candidate.widestApproachMeters },
|
||||||
|
提示: "coreRadiusMeters 是按节点跨度估的起点,配好后按实际效果调整;有高德参考几何时它会被校准值覆盖。",
|
||||||
|
}, null, 2);
|
||||||
|
renderCandidateAction(candidate);
|
||||||
|
message(`已选中复杂路口候选 #${candidate.index}`);
|
||||||
|
}
|
||||||
|
// The accept button lives beside the snippet so the manual path stays available
|
||||||
|
// if the write is refused; both describe the same cluster.
|
||||||
|
function renderCandidateAction(candidate) {
|
||||||
|
candidateAction.replaceChildren();
|
||||||
|
const button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
button.textContent = `把候选 #${candidate.index} 加入配置并重新编译`;
|
||||||
|
button.onclick = async () => {
|
||||||
|
button.disabled = true;
|
||||||
|
message(`正在把候选 #${candidate.index} 写入区域配置...`);
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/junction-clusters", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ index: candidate.index }), cache: "no-store" });
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok || result.ok === false) throw new Error(result.error || `HTTP ${response.status}`);
|
||||||
|
state = result;
|
||||||
|
staged = [];
|
||||||
|
updateDirtyState(); updateSources(); renderDiagnostics(); renderSummary();
|
||||||
|
candidateAction.replaceChildren();
|
||||||
|
hint.textContent = `已加入复杂路口 ${result.added.id}(${result.added.nodeIds.length} 个节点),配置已更新并重新编译。`;
|
||||||
|
message(`已加入 ${result.added.id};如需撤销可 git checkout 区域配置`);
|
||||||
|
} catch (error) {
|
||||||
|
button.disabled = false;
|
||||||
|
message(`加入失败:${error.message}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
candidateAction.append(button);
|
||||||
|
}
|
||||||
function laneId(connection, side) { return connection[side === "from" ? "fromLaneId" : "toLaneId"] || connection[side === "from" ? "from_lane_id" : "to_lane_id"]; }
|
function laneId(connection, side) { return connection[side === "from" ? "fromLaneId" : "toLaneId"] || connection[side === "from" ? "from_lane_id" : "to_lane_id"]; }
|
||||||
function effectiveLaneEnabled(connector) { const id = `车道连接:${laneId(connector, "from")}->${laneId(connector, "to")}`; const override = [...staged, ...state.overrides.overrides].find((item) => item.id === id); return override ? override.enabled : connector.enabled !== false; }
|
function effectiveLaneEnabled(connector) { const id = `车道连接:${laneId(connector, "from")}->${laneId(connector, "to")}`; const override = [...staged, ...state.overrides.overrides].find((item) => item.id === id); return override ? override.enabled : connector.enabled !== false; }
|
||||||
function effectiveConnectionEnabled(connection) { const id = `连接:${connection.id}`; const override = [...staged, ...state.overrides.overrides].find((item) => item.id === id); return override ? override.enabled : connection.enabled; }
|
function effectiveConnectionEnabled(connection) { const id = `连接:${connection.id}`; const override = [...staged, ...state.overrides.overrides].find((item) => item.id === id); return override ? override.enabled : connection.enabled; }
|
||||||
function effectiveConnectorEnabled(connector) { const connection = state?.compiled.model.connections.find((item) => item.id === connector.connection_id); return effectiveLaneEnabled(connector) && (!connection || effectiveConnectionEnabled(connection)); }
|
function effectiveConnectorEnabled(connector) { const connection = state?.compiled.model.connections.find((item) => item.id === connector.connection_id); return effectiveLaneEnabled(connector) && (!connection || effectiveConnectionEnabled(connection)); }
|
||||||
|
|
||||||
function selectRoad(road, note, movement = null) {
|
function selectRoad(road, note, movement = null) {
|
||||||
|
candidateAction.replaceChildren();
|
||||||
selectedRoad = road; selectedMovement = movement; selectedJunction = null; selectedJunctionPanel.hidden = true; layers.osm.changed(); layers.lanes.changed(); layers.connectors.changed(); refreshOsmDirection(); refreshSelectedMovement();
|
selectedRoad = road; selectedMovement = movement; selectedJunction = null; selectedJunctionPanel.hidden = true; layers.osm.changed(); layers.lanes.changed(); layers.connectors.changed(); refreshOsmDirection(); refreshSelectedMovement();
|
||||||
layers.selectedRoad.getSource().clear(); if (road) layers.selectedRoad.getSource().addFeature(new Feature({ geometry: new LineString(road.centerline).transform("EPSG:4326", "EPSG:3857") }));
|
layers.selectedRoad.getSource().clear(); if (road) layers.selectedRoad.getSource().addFeature(new Feature({ geometry: new LineString(road.centerline).transform("EPSG:4326", "EPSG:3857") }));
|
||||||
form.hidden = !road; hint.hidden = Boolean(road); if (!road) return;
|
form.hidden = !road; hint.hidden = Boolean(road); if (!road) return;
|
||||||
@@ -217,11 +331,12 @@ function selectRoad(road, note, movement = null) {
|
|||||||
renderDirectionSwitch(road); renderMovementSummary(road); renderSelectedMovement(); renderConnections(road); message(note || (selectedMovement ? `已选中行驶动作:${turnLabel(selectedMovement.turn)}` : `已选中:${roadLabel(road)}`));
|
renderDirectionSwitch(road); renderMovementSummary(road); renderSelectedMovement(); renderConnections(road); message(note || (selectedMovement ? `已选中行驶动作:${turnLabel(selectedMovement.turn)}` : `已选中:${roadLabel(road)}`));
|
||||||
}
|
}
|
||||||
function selectJunction(feature) {
|
function selectJunction(feature) {
|
||||||
|
candidateAction.replaceChildren();
|
||||||
selectedJunction = feature; selectedRoad = null; selectedMovement = null; form.hidden = true; hint.hidden = true; selectedJunctionPanel.hidden = false;
|
selectedJunction = feature; selectedRoad = null; selectedMovement = null; form.hidden = true; hint.hidden = true; selectedJunctionPanel.hidden = false;
|
||||||
const properties = feature.getProperties(); const roadIds = String(properties.source_road_ids || "").split(",").filter(Boolean);
|
const properties = feature.getProperties(); const roadIds = String(properties.source_road_ids || "").split(",").filter(Boolean);
|
||||||
const roads = roadIds.map((id) => state.compiled.model.roads.find((road) => road.id === id)).filter(Boolean);
|
const roads = roadIds.map((id) => state.compiled.model.roads.find((road) => road.id === id)).filter(Boolean);
|
||||||
junctionDetail.textContent = JSON.stringify({ OSM节点: properties.osm_node_id, 类型: properties.kind === "t" ? "T字路口" : "十字路口", 参与方向道路: roads.map((road) => ({ 道路: roadLabel(road), OSM道路: road.osmWayIds, 节点顺序: road.sourceNodeIds })), 构面规则: properties.rule, 边界策略: properties.boundary_mode, 基础截面面积平方米: properties.approach_area_m2, 最终路口面积平方米: properties.surface_area_m2, 外缘扩张倍率: properties.expansion_ratio, 路口退让距离米: properties.cutback_m, 行驶动作数: properties.movement_count, 已绘制连接数: properties.connector_count }, null, 2);
|
junctionDetail.textContent = JSON.stringify({ OSM节点: properties.osm_node_id || properties.osm_node_ids, 类型: properties.kind === "cluster" ? "复合路口簇" : properties.kind === "t" ? "T字路口" : "十字路口", 参与方向道路: roads.map((road) => ({ 道路: roadLabel(road), OSM道路: road.osmWayIds, 节点顺序: road.sourceNodeIds })), 构面规则: properties.rule, 模板: properties.template, 边界策略: properties.boundary_mode, 基础截面面积平方米: properties.approach_area_m2, 最终路口面积平方米: properties.surface_area_m2, 外缘扩张倍率: properties.expansion_ratio, 路口退让距离米: properties.cutback_m, 行驶动作数: properties.movement_count, 已绘制连接数: properties.connector_count }, null, 2);
|
||||||
message(`已选中路口:OSM 节点 ${properties.osm_node_id}`);
|
message(`已选中路口:OSM 节点 ${properties.osm_node_id || properties.osm_node_ids}`);
|
||||||
}
|
}
|
||||||
function selectSignal(feature) {
|
function selectSignal(feature) {
|
||||||
selectedSignal = feature.get("signal_uid"); const p = feature.getProperties(); signalPicker.value = selectedSignal;
|
selectedSignal = feature.get("signal_uid"); const p = feature.getProperties(); signalPicker.value = selectedSignal;
|
||||||
@@ -304,13 +419,30 @@ centerLineForm.onsubmit = (event) => { event.preventDefault(); stageSelectedCent
|
|||||||
centerLineStyleInput.onchange = stageSelectedCenterLineStyle;
|
centerLineStyleInput.onchange = stageSelectedCenterLineStyle;
|
||||||
async function saveStagedChanges() { if (!staged.length) return true; const existing = state.overrides.overrides.filter((item) => !staged.some((change) => change.id === item.id)); const response = await fetch("/api/overrides", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ schema: "native-road-overrides/v1", overrides: [...existing, ...staged] }) }); const result = await response.json(); if (!result.ok) { message(result.error); return false; } state.overrides = result.overrides; staged = []; updateDirtyState(); return true; }
|
async function saveStagedChanges() { if (!staged.length) return true; const existing = state.overrides.overrides.filter((item) => !staged.some((change) => change.id === item.id)); const response = await fetch("/api/overrides", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ schema: "native-road-overrides/v1", overrides: [...existing, ...staged] }) }); const result = await response.json(); if (!result.ok) { message(result.error); return false; } state.overrides = result.overrides; staged = []; updateDirtyState(); return true; }
|
||||||
saveButton.onclick = async () => { if (await saveStagedChanges()) message("已保存,点击“保存并重新生成”写入几何"); };
|
saveButton.onclick = async () => { if (await saveStagedChanges()) message("已保存,点击“保存并重新生成”写入几何"); };
|
||||||
compileButton.onclick = async () => { if (!await saveStagedChanges()) return; message("正在保存修改并重新生成..."); const response = await fetch("/api/compile", { method: "POST" }); state = await response.json(); staged = []; updateDirtyState(); updateSources(); renderDiagnostics(); renderSummary(); selectRoad(selectedRoad ? state.compiled.model.roads.find((road) => road.id === selectedRoad.id) : null); message("已保存并重新生成"); };
|
compileButton.onclick = async () => {
|
||||||
|
if (!await saveStagedChanges()) return;
|
||||||
|
message("正在保存修改并重新生成...");
|
||||||
|
const response = await fetch("/api/compile", { method: "POST", cache: "no-store" });
|
||||||
|
const nextState = await response.json();
|
||||||
|
if (!response.ok || nextState.ok === false || !nextState.compiled?.model || !nextState.layers) {
|
||||||
|
message(`重新生成失败:${nextState.error || `HTTP ${response.status}`}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state = nextState;
|
||||||
|
staged = [];
|
||||||
|
updateDirtyState();
|
||||||
|
updateSources();
|
||||||
|
renderDiagnostics();
|
||||||
|
renderSummary();
|
||||||
|
selectRoad(selectedRoad ? state.compiled.model.roads.find((road) => road.id === selectedRoad.id) : null);
|
||||||
|
message("已保存并重新生成");
|
||||||
|
};
|
||||||
for (const input of document.querySelectorAll("[data-layer]")) input.onchange = () => { const visible = input.checked; layers[input.dataset.layer].setVisible(visible); if (input.dataset.layer === "osm") layers.osmDirection.setVisible(visible); };
|
for (const input of document.querySelectorAll("[data-layer]")) input.onchange = () => { const visible = input.checked; layers[input.dataset.layer].setVisible(visible); if (input.dataset.layer === "osm") layers.osmDirection.setVisible(visible); };
|
||||||
scenePreviewToggle.onchange = () => {
|
scenePreviewToggle.onchange = () => {
|
||||||
scenePreview = scenePreviewToggle.checked;
|
scenePreview = scenePreviewToggle.checked;
|
||||||
for (const input of document.querySelectorAll("[data-layer]")) {
|
for (const input of document.querySelectorAll("[data-layer]")) {
|
||||||
const layer = input.dataset.layer;
|
const layer = input.dataset.layer;
|
||||||
if (["osm", "lanes", "reference"].includes(layer)) layers[layer].setVisible(!scenePreview && input.checked);
|
if (["osm", "lanes", "reference", "gaodeReference"].includes(layer)) layers[layer].setVisible(!scenePreview && input.checked);
|
||||||
}
|
}
|
||||||
layers.osmDirection.setVisible(!scenePreview && document.querySelector('[data-layer="osm"]').checked);
|
layers.osmDirection.setVisible(!scenePreview && document.querySelector('[data-layer="osm"]').checked);
|
||||||
layers.connectors.setVisible(!scenePreview && document.querySelector('[data-layer="lanes"]').checked);
|
layers.connectors.setVisible(!scenePreview && document.querySelector('[data-layer="lanes"]').checked);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>道路编译工作台</title><link rel="stylesheet" href="/vendor/ol/ol.css"><link rel="stylesheet" href="/app.css"></head>
|
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>道路编译工作台</title><link rel="stylesheet" href="/vendor/ol/ol.css"><link rel="stylesheet" href="/app.css"></head>
|
||||||
<body><header><strong>道路编译工作台</strong><span id="area"></span><span id="status"></span><span id="dirty-state" aria-live="polite"></span><label style="display:inline;margin:0 0 0 auto;white-space:nowrap"><input id="scene-preview" type="checkbox"> 场景效果</label><button id="save">保存修改</button><button id="compile">保存并重新生成</button></header>
|
<body><header><strong>道路编译工作台</strong><span id="area"></span><span id="status"></span><span id="dirty-state" aria-live="polite"></span><label style="display:inline;margin:0 0 0 auto;white-space:nowrap"><input id="scene-preview" type="checkbox"> 场景效果</label><button id="save">保存修改</button><button id="compile">保存并重新生成</button></header>
|
||||||
<main><aside class="issues"><h1>图层</h1><label><input data-layer="osm" type="checkbox" checked> OSM 道路中心线</label><label><input data-layer="native" type="checkbox" checked> 自研道路与路口面</label><label><input data-layer="sidewalks" type="checkbox" checked> 路缘与步行带</label><label><input data-layer="lanes" type="checkbox" checked> 车道与转向路径</label><label><input data-layer="reference" type="checkbox"> osm2streets 参考面</label><hr><h1>当前编译概览</h1><dl id="summary"></dl><hr><h1>待检查问题</h1><div id="diagnostic-filters" class="segmented"><button data-diagnostic-filter="all" type="button">全部</button><button data-diagnostic-filter="candidates" type="button">可连接</button><button data-diagnostic-filter="other" type="button">其他</button></div><ul id="diagnostics"></ul></aside><section id="map" class="map"></section><aside class="inspector"><h1>当前道路设置</h1><p id="hint">点击道路、车道、转向路径或路口面以查看详情。</p><section id="selected-junction" hidden><h2>当前路口</h2><output id="junction-detail"></output></section><form id="road-form" hidden><label>道路</label><output id="road-name"></output><output id="movement-summary"></output><output id="lane-convention"></output><section id="selected-movement" hidden><h2>当前行驶动作</h2><output id="movement-detail"></output></section><div id="direction-switch"></div><label>本方向道路宽度(米)<input id="width" type="number" min="1" step="0.01"></label><label>本方向车道数<input id="lanes" type="number" min="1" step="1"></label><label><input id="left" type="checkbox"> 左侧有路缘与步行带</label><label><input id="right" type="checkbox"> 右侧有路缘与步行带</label><button type="submit">暂存本道路修改</button></form><form id="center-line-form" hidden><h2 id="marking-style-heading">道路中心线样式</h2><output id="center-line-segment"></output><label>样式<select id="center-line-style"><option value="yellow-dashed">黄色虚线(默认)</option><option value="white-dashed">白色虚线</option><option value="yellow-solid">黄色实线</option><option value="white-solid">白色实线</option></select></label><button type="submit">暂存标线样式</button></form><hr><h2>路口连接</h2><div id="connections">请选择一条道路。</div><button id="add-connection" type="button" hidden>手工新增驶出连接</button><details><summary>技术详情与来源</summary><pre id="evidence">无</pre></details></aside></main><script type="importmap">{"imports":{"rbush":"/vendor/rbush/index.js","quickselect":"/vendor/quickselect/index.js"}}</script><script type="module" src="/app.js"></script></body></html>
|
<main><aside class="issues"><h1>图层</h1><label><input data-layer="osm" type="checkbox" checked> OSM 道路中心线</label><label><input data-layer="native" type="checkbox" checked> 自研道路与路口面</label><label><input data-layer="sidewalks" type="checkbox" checked> 路缘与步行带</label><label><input data-layer="lanes" type="checkbox" checked> 车道与转向路径</label><label><input data-layer="gaodeReference" type="checkbox" checked> 高德规整路口参考</label><label><input data-layer="reference" type="checkbox"> osm2streets 参考面</label><hr><h1>当前编译概览</h1><dl id="summary"></dl><hr><h1>待检查问题</h1><div id="diagnostic-filters" class="segmented"><button data-diagnostic-filter="all" type="button">全部</button><button data-diagnostic-filter="candidates" type="button">可连接</button><button data-diagnostic-filter="other" type="button">其他</button></div><ul id="diagnostics"></ul></aside><section id="map" class="map"></section><aside class="inspector"><h1>当前道路设置</h1><p id="hint">点击道路、车道、转向路径或路口面以查看详情。</p><section id="selected-junction" hidden><h2>当前路口</h2><output id="junction-detail"></output></section><form id="road-form" hidden><label>道路</label><output id="road-name"></output><output id="movement-summary"></output><output id="lane-convention"></output><section id="selected-movement" hidden><h2>当前行驶动作</h2><output id="movement-detail"></output></section><div id="direction-switch"></div><label>本方向道路宽度(米)<input id="width" type="number" min="1" step="0.01"></label><label>本方向车道数<input id="lanes" type="number" min="1" step="1"></label><label><input id="left" type="checkbox"> 左侧有路缘与步行带</label><label><input id="right" type="checkbox"> 右侧有路缘与步行带</label><button type="submit">暂存本道路修改</button></form><form id="center-line-form" hidden><h2 id="marking-style-heading">道路中心线样式</h2><output id="center-line-segment"></output><label>样式<select id="center-line-style"><option value="yellow-dashed">黄色虚线(默认)</option><option value="white-dashed">白色虚线</option><option value="yellow-solid">黄色实线</option><option value="white-solid">白色实线</option></select></label><button type="submit">暂存标线样式</button></form><hr><h2>路口连接</h2><div id="connections">请选择一条道路。</div><button id="add-connection" type="button" hidden>手工新增驶出连接</button><details><summary>技术详情与来源</summary><pre id="evidence">无</pre></details></aside></main><script type="importmap">{"imports":{"rbush":"/vendor/rbush/index.js","quickselect":"/vendor/quickselect/index.js"}}</script><script type="module" src="/app.js"></script></body></html>
|
||||||
Reference in new issue
Block a user