fix: verify and align complex junction layer seams

This commit is contained in:
que01 committed 2026-09-17 10:07:26 +08:00
1 parent 79590d3d0f
commit cfb3593a0b
15 files changed
+1122 -57

No files matched your search

+1
View File
@@ -6,3 +6,4 @@
- [Direct Edit Solver And API](./direct-edit-api.md) -- pure constraint solving, preview/save endpoints, version protection, and rebase behavior.
- [Junction Island Contact](./junction-island-contact.md) -- confirmed target contract for full crossing-edge contact, dynamic island legs and the six-point green region (implementation pending).
- [Junction Layer Seams](./junction-layer-seams.md) -- metric seam audit, source identity mapping, and both-end corridor trims.
@@ -0,0 +1,81 @@
# Junction layer seams
## Scope and source contracts
Complex-junction seams use a **0.01 m** numerical tolerance in local metric
coordinates. This is internal stitching precision, not OSM survey accuracy.
`test/helpers/junction-seams.js` audits published features against source
identities in `junction_structure`; it does not call the geometry builders to
manufacture expected geometry.
- Exterior surfaces match the complete `directional_road_ids` set of a
carriageway. Core and pavement match `cluster_id`; approaches match
`carriageway_key`.
- Native lanes use `road_id` and travel-direction `lane_index`. Preview lanes
use a combined cross-section index running from `outer.right` to `outer.left`.
Map outgoing lanes in reverse order, followed by incoming lanes in forward
order. Do not equate these two index spaces or choose a nearest lane globally.
- Edge lines match the source road and `side`. Separators match the lane pair;
the boundary between opposite directions belongs to the road centre marking.
Centre markings match the complete `directional_road_ids` set and a primary
`road_id` belonging to that set; a partial source match is not sufficient.
- Sidewalk corners match `corner_key` and strips from their two source arms.
Absence is acceptable only for disabled source sidewalks or an explicit
rejection identifying that exact corner. A cluster-wide fallback diagnostic
must not excuse a missing corner elsewhere.
## Both ends of a corridor
`trimRoadAtComplexClusters(road, junctionPlans, clusters, boundaries)` in
`native-road.js` calculates **both** endpoint cutbacks from the original source
polyline and each cluster's `outer.stationMeters`, then calls `trimLineRange`
once. Road surfaces, sidewalks, edges, centre lines and native lanes share it.
Wrong: select `startCluster || endCluster` as the only trim owner, or trim
sequentially using the second station on the shortened line. Correct: resolve
each endpoint independently and preserve intermediate source bends.
The first bug leaves the far approach covered by exterior pavement and its
edge/lane endpoints tens of metres past the seam. Vertex-to-boundary checks can
miss it because the long side edges still touch both seam endpoints.
## Measurements and failures
`auditJunctionSeams(model, geometry, structures)` returns each layer's `checked`,
`failed`, `notApplicable` and identity-bearing `records`.
| Interface | Required measurement |
| --- | --- |
| Exterior surface / approach | Endpoint error and complete boundary segment coverage |
| Approach / core and published pavement | Complete segment containment, respecting holes |
| Native / preview lanes and solid edges | Corresponding endpoint or paint-cap midpoint |
| Dashed edges, centre lines, separators | Support alignment and bounded terminal gap |
| Corner / sidewalk strip | Both full end edges, with source-arm matching |
Missing expected objects fail; never iterate only detected objects and report an
empty set as success. Segment coverage partitions at all boundary crossings, so
interior notches cannot hide between fixed probes. Polygon holes remain holes.
Dashes do not need white paint across every seam. An outward road starts its
dash sequence at the seam, so its first cap must coincide; the other end can
leave a residual dash cycle. Current edge/separator cycles are 2 m paint + 2 m
gap. Centre markings publish `dash_length_m` and `dash_gap_m`. Report these gaps
separately from the 1 cm transverse alignment tolerance. The audit does not
certify every individual dash, every double-line component, or interior paint
continuity through a complex core where centre markings are not published.
## Required regression
Run `node test/junction-layer-seams.js` (also in `npm test`). To inspect every
identity and measurement, run:
```sh
node test/junction-layer-seams.js --report /private/tmp/junction-layer-seams.json
```
Keep nonempty per-layer counts for straight/curved, one-way/two-way, local width
and island edits, two-ended corridors, reordered input, current real OSM and
explicitly sidewalk-enabled real OSM. Required negative controls: exactly 2 cm
displacement, missing single/whole counterparts, wrong source identities,
swapped lane indices, absent first anchored dash, a 2 cm interior notch and a
hole. Do not loosen the tolerance or refresh unrelated fixture snapshots.
@@ -0,0 +1,2 @@
{"file": ".trellis/spec/backend/junction-island-contact.md", "reason": "检查接缝与诊断"}
{"file": ".trellis/spec/backend/junction-layer-seams.md", "reason": "接缝矩阵、来源映射、两端裁切及负向验证"}
@@ -0,0 +1,23 @@
# Phase 3.4 提交批次(用户已确认)
2026-09-17:用户回复“可以”,授权以下两笔提交及接缝专项归档。
1. `fix: verify and align complex junction layer seams`
- `src/compile/native-road.js`
- `src/compile/complex-junction-facilities.js`
- `test/helpers/junction-seams.js`
- `test/junction-layer-seams.js`
- `package.json`
- `.trellis/spec/backend/index.md`
- `.trellis/spec/backend/junction-layer-seams.md`
- `.trellis/tasks/09-17-junction-layer-seams/`(需求、设计、实施、验收及上下文)
2. `docs: scope junction exclusion routing follow-up`
- `.trellis/tasks/09-17-junction-exclusion-routing/`(规划与只读初审,无产品代码)
没有未识别的脏文件;没有 fixture 快照更新;不推送远端。
确认后按上述顺序提交,再归档接缝专项并记录会话。
排除区专项保持 planning,父任务保持已归档。
确认要求来源:`.trellis/workflow.md` Phase 3.4 第 5 步
“Present the plan once, ask for one-shot confirmation”。
@@ -0,0 +1,11 @@
# 接缝审计设计
审计发布几何与来源身份,复用已有 BoundaryGraph/structure 中的接入关系。先在 test/helpers/junction-seams.js 建立独立测量,再由 test/junction-layer-seams.js 编译合成和真实场景。报告以 JSON 可序列化对象输出,各层记录身份、测量值、判定和覆盖数量;不新增产品 API。
面积接边测量两端及整段覆盖,不只检查顶点最近距离。线图层按方向与 lane_index 对应外部车道和 transition lane。对条纹/虚线按其连续支撑线或合法裁切终点评估,不要求白条填满所有空间。需先审计生成代码确定每层有效接缝契约,不能将所有图层强行套用道路面边界。
局部米制坐标以当前接缝作为原点,避免绝对经纬度距离与面积数值误差。几何辅助优先复用既有 polygon/segment 工具,但测试期望不能调用被测生成器重建同一结果。
修改范围:新增测量测试与 helper、package.json 测试入口;如发现局部构建缺陷,仅修改拥有实际接缝的 native-road/complex-junction 模块,并补独立反例。新规划器不纳入本专项。
风险:缺失对象容易导致空集通过;虚线和控制标线本来有间隙;曲线法线可能让端点不一致。用覆盖计数、明确不适用原因及人工损坏反例验证审计器。若需改变设施语义,先记录独立专项。
@@ -0,0 +1,89 @@
# 接缝专项验收证据
2026-09-17。实现与专项验收完成,用户已确认 Phase 3.4 提交及归档;父任务
`junction-reference-fidelity` 保持归档。本次没有实施复杂绕障规划。
## 实际修复
真实 OSM 的两条相邻路口连接道路只选取一个端点所属 cluster 进行裁切。
另一端的面边界没有真正形成接边,边线与车道线端点偏离约 28.9 / 34.4 m。
旧顶点检查仍能通过,因为道路两条长边经过了应有接缝的两个端点。
`native-road.js` 现在从原始道路分别计算两端 station,一次裁切;道路面、
边线、中心线、车道中心线和人行道共同使用这一规则,保留中间弯折。
角部人行道的自交拒绝诊断改为具体 corner 身份,避免一个角部的拒绝
掩盖另一个角部的意外缺失。设施省略规则没有更改。
## 测量矩阵与结果
完整契约见 `.trellis/spec/backend/junction-layer-seams.md`。
| 图层/接口 | checked | failed | notApplicable | 最大位置误差 m | 最大未覆盖长度 m |
| --- | ---: | ---: | ---: | ---: | ---: |
| 道路面 / 进口 / 最终铺装 | 172 | 0 | 0 | 0.003285 | 0.000262 |
| 核心 / 进口 | 86 | 0 | 0 | 0 | < 0.000001 |
| 道路边线 | 172 | 0 | 8 | 0.006183 | < 0.000001 |
| 道路中心线 | 26 | 0 | 86 | 0.000005 | < 0.000001 |
| 车道中心线 | 560 | 0 | 0 | 0.006149 | 0 |
| 车道分隔线 | 362 | 0 | 194 | 0.000004 | 0.000002 |
| 人行道 | 68 | 0 | 28 | 0 | 0 |
以上最大值向上取整。共 **13 个场景、1,446 个测量记录**,阈值始终
为 0.01 m。`checked` 是接口记录数,包含同一图层不同接口及多场景,
不是互不重复的道路数量。`notApplicable` 可与同一对象的有效测量并存,
用于说明不要求连续白漆或不发布中心标线的接口。
场景包含单向直线/曲线、双向直线/曲线、真实 OSM 单路口/相邻路口、
真实道路显式开启人行道、双向曲线相邻路口、单向/双向局部展宽、
岛体位移、道路与 cluster 输入重排、虚线边线。
测试锁定每个场景各图层的 checked 数量,所有应连续接口须通过。
每个图层有非空覆盖;源数据没有人行道的真实场景明确标记不适用,
由显式开启人行道的真实场景提供角部接边验证。
负向测试验证:精确向东平移 2 cm、删除单个/整组必需对象、错误道路
来源、交换车道序号、缺失外部人行道/分隔线、缺失起始锚定虚线、
接边中部 2 cm 缺口及穿过接边的孔洞。原实现子代理中断留下的审计器
还存在双向/驶出车道序号误配及缺失车道时异常,这些问题均已修正。
## 可复现命令
```sh
node test/junction-layer-seams.js --report /private/tmp/junction-layer-seams.json
node test/junction-island-offset.js
npm test
npm run test:client
npx prettier --check src/compile/native-road.js src/compile/complex-junction-facilities.js test/helpers/junction-seams.js test/junction-layer-seams.js package.json
git diff --check
```
报告按场景和图层保存 checked/failed/notApplicable、对象身份、feature IDs、
位置误差、未覆盖长度、虚线端部间隙及省略原因;临时报告可随时重建,
不把大型机器报告作为仓库快照。
## 质量检查
- 专项最终 13 场景 / 1,446 接口通过;已加入 `npm test`。
- `npm test` 中编译、结构、轨迹、投影、反例、设施、铺装、标线、
接缝、编辑文档、修订存储、编辑 solver、Workbench API 和导入测试通过。
最终 `test/fixtures.js:18` 仍因既有当前 OSM / 旧基线差异失败。
全量运行时为 11 场景,后续新增的 2 场景及强化反例已单独完整重跑通过;
此后没有修改生产几何代码。
- TypeScript 检查、独立岛体位移回归、变更文件 Prettier、diff 检查通过。
- 全仓 `format:check` 仅报告既有未改动的
`src/compile/junction-facility-composition.js` 格式问题。
- 独立 `trellis-check` 已复核裁切、来源匹配、面积完整接边、缺对象、
车道映射及明确省略契约;未发现阻断问题。
## 明确限制
不把每个角部都能生成设施作为接缝验收条件。两个单向合成角部因自交被
生成器明确拒绝;这些记录携带对应 corner 的拒绝原因,其他已发布角部
仍必须完整接边。未实现新的角部设施语义。
虚线按接缝附近支撑线及合法端部间隙测量,起始锚点不能丢失;不声称
验证整条道路的每根白条、双实/虚线每一组成部分或复杂核心内不存在的
中心标线。路口外的所有内部标线连续性不是本审计的对象。
排除区最终铺装孔洞保留风险仅完成代码初审,尚未运行最终发布面的反例;
保留在 `09-17-junction-exclusion-routing/research.md`,不能当成已修复。
@@ -0,0 +1,2 @@
{"file": ".trellis/spec/backend/junction-island-contact.md", "reason": "共享坐标与精度约定"}
{"file": ".trellis/spec/backend/junction-layer-seams.md", "reason": "实施产生的共享接缝与两端裁切契约"}
@@ -0,0 +1,13 @@
# 实施步骤
- [x] 审计现有接缝与落面断言,编写 PRD 和设计。
- [x] 审计每个发布层的身份、裁切和连续性契约,写测量矩阵。
- [x] 实现独立米制测量和报告,加入 2 cm 偏移、缺对象、错接和中段缺口反例。
- [x] 建立直线、曲线、编辑、相邻路口、真实 OSM 场景,保证各层非空覆盖。
- [x] 修复被测量定位的局部接缝错误;超出局部修复范围的项目列入独立专项。
- [x] 接入 npm test,运行针对性回归、全量回归、变更文件格式及 git diff --check。
- [x] 记录各层结果、误差、覆盖数量及明确限制;更新规范。
- [x] 按 Phase 3.4 确认提交批次。
- [ ] 提交并归档。
已知基线问题:npm test 的 test/fixtures.js 快照与当前 OSM 不符;全仓 format:check 曾在 junction-facility-composition.js 失败。不得把这两项写成通过,也不得为本任务直接重置快照。
@@ -0,0 +1,26 @@
# 复杂路口全图层接缝精度验证
## Goal
以自动测量验证复杂路口各发布图层在应连续接口处的接缝精度,定位并修复支持范围内的局部缺陷。承接已归档 junction-reference-fidelity 的验证遗留。
## Requirements
- 检查道路面、核心/进口面、道路边线、道路中心线、车道中心线、车道分隔线及人行道。
- 由 road/carriageway/lane 来源身份匹配相邻对象,以米制测量完整接边或对应线端位置,不通过全图最近点掩盖错接。
- 接缝位置误差上限 0.01 m。明确区分停止线裁切、虚线间隔与本来不发布的设施,这些正常断开不能算接缝失败。
- 缺少应存在的相邻对象必须报错,不能跳过。各图层报告 checked/failed/not-applicable 数量、对象身份、误差与不适用原因。
- 测量发现的局部构建错误应修复;新绕障规划和设施规则变更作为独立专项。
## Acceptance Criteria
- [x] 每个图层有非空的应连续样本,覆盖直线、曲线、宽度变化、局部编辑、相邻路口与当前真实 OSM。
- [x] 人为移动接缝 2 cm、删除必需邻接对象、错接不同道路均被检测;面积接边中间缺口不能只凭两端接触通过。
- [x] 输入重排保持身份匹配稳定。支持场景满足 1 cm,不放宽阈值或减少覆盖使测试通过。
- [x] 回归纳入 npm test,记录已有 fixture 差异,不刷新基线掩盖变化。
## 范围边界和现有证据
不涉及复杂排除区绕障、多通行区路径规划、车辆扫掠、UI 新控件或人工视觉验收。1 cm 为内部拼接精度,不是 OSM 测绘精度。
test/index.js:148 已验证 transition lane 与进口断面;:193 验证展宽保持外部图层;:230 仅验证道路面接缝端点;:324 的 0.3 m 落面容差不等同于接缝;:379 验证角部人行道完整端边。test/junction-build-plan-counterexamples.js:718 有核心整段覆盖反例。
@@ -0,0 +1,26 @@
{
"id": "junction-layer-seams",
"name": "junction-layer-seams",
"title": "复杂路口全图层接缝精度验证",
"description": "",
"status": "in_progress",
"dev_type": null,
"scope": null,
"package": null,
"priority": "P2",
"creator": "dingkang",
"assignee": "dingkang",
"createdAt": "2026-09-17",
"completedAt": null,
"branch": null,
"base_branch": "main",
"worktree_path": null,
"commit": null,
"pr_url": null,
"subtasks": [],
"children": [],
"parent": null,
"relatedFiles": ["src/compile/native-road.js", "src/compile/complex-junction-facilities.js", "test/helpers/junction-seams.js", "test/junction-layer-seams.js", "package.json"],
"notes": "实现及专项验收完成:13 场景、1446 接口;详情见 evidence.md。全量回归保留既有 fixture / format 基线问题。用户已确认 Phase 3.4 提交及归档。",
"meta": {}
}
+1 -1
View File
@@ -8,7 +8,7 @@
"road-compiler": "bin/road-compiler.js"
},
"scripts": {
"test": "node test/index.js && node test/junction-structure.js && node test/connector-trajectories.js && node test/junction-projection.js && node test/junction-build-plan-counterexamples.js && node test/junction-polygon-ops.js && node test/junction-region-solver.js && node test/junction-facility-composition.js && node test/junction-pavement-region.js && node test/junction-marking-containment.js && node test/junction-corridor-markings.js && node test/native-road-edits.js && node test/road-revisions.js && node test/direct-edit-solver.js && node test/workbench-edit-api.js && node test/workbench-import-compile.js && node test/fixtures.js",
"test": "node test/index.js && node test/junction-structure.js && node test/connector-trajectories.js && node test/junction-projection.js && node test/junction-build-plan-counterexamples.js && node test/junction-polygon-ops.js && node test/junction-region-solver.js && node test/junction-facility-composition.js && node test/junction-pavement-region.js && node test/junction-marking-containment.js && node test/junction-corridor-markings.js && node test/junction-layer-seams.js && node test/native-road-edits.js && node test/road-revisions.js && node test/direct-edit-solver.js && node test/workbench-edit-api.js && node test/workbench-import-compile.js && node test/fixtures.js",
"test:fixtures:update-baseline": "node test/update-fixture-baselines.js",
"road:workbench": "node bin/road-workbench.js",
"road:export": "node bin/road-compiler.js",
+1 -1
View File
@@ -853,7 +853,7 @@ function buildCornerSidewalk({
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`junction-cluster:${cluster.id}`,
`corner:${first.cornerKey}`,
[...nodeIds],
'complex-junction-sidewalk-corner-fallback',
'该夹角的人行道转角几何自交或无效,已跳过,两侧步行带保持断开。',
+25 -55
View File
@@ -708,14 +708,7 @@ function compileGeometry(model, overrides = { overrides: [] }, options = {}) {
}
const line =
cluster?.template === 'complex-junction-v1'
? trimLineAtComplexCluster(
road.centerline,
road.sourceNodeIds,
junctionPlans,
cluster,
complexClusterCenters.get(cluster.id),
complexApproachBoundaries.get(cluster.id)?.get(road.id),
)
? trimRoadAtComplexClusters(road, junctionPlans, activeClusters, complexApproachBoundaries)
: trimLineAtJunctions(road.centerline, road.sourceNodeIds, junctionPlans);
const ring = roadRing(line, totalWidth);
if (!ring) {
@@ -1237,7 +1230,6 @@ function compileEdgeLines(
const clusterByNode = new Map(
clusters.flatMap((cluster) => cluster.nodeIds.map((nodeId) => [String(nodeId), cluster])),
);
const clusterCenters = new Map(clusters.map((cluster) => [cluster.id, clusterCenter(cluster, junctionPlans)]));
// Roads swallowed by a complex cluster never get a surface. Deriving their
// edge from the centerline anyway paints a curb across bare ground, so take
// the surfaces actually emitted as the authority on what can be outlined.
@@ -1261,14 +1253,7 @@ function compileEdgeLines(
clusterByNode.get(String(road.sourceNodeIds[0])) || clusterByNode.get(String(road.sourceNodeIds.at(-1)));
const line =
cluster?.template === 'complex-junction-v1'
? trimLineAtComplexCluster(
road.centerline,
road.sourceNodeIds,
junctionPlans,
cluster,
clusterCenters.get(cluster.id),
complexBoundaries.get(cluster.id)?.get(road.id),
)
? trimRoadAtComplexClusters(road, junctionPlans, clusters, complexBoundaries)
: trimLineAtJunctions(road.centerline, road.sourceNodeIds, junctionPlans);
// On a two-way segment, the inner edge is the road centre boundary and is
// owned by center_lines. Emit only each directional carriageway's outer
@@ -1345,14 +1330,7 @@ function compileCenterLines(
const cluster = clusterForRoad(forward, options) || clusterForRoad(backward, options);
const internalCluster = cluster && roadInternalToCluster(forward, cluster);
const line = cluster
? trimLineAtComplexCluster(
forward.centerline,
forward.sourceNodeIds,
junctionPlans,
cluster,
clusterCenter(cluster, junctionPlans),
complexBoundaries.get(cluster.id)?.get(forward.id),
)
? trimRoadAtComplexClusters(forward, junctionPlans, options.junctionTemplates.clusters, complexBoundaries)
: trimLineAtJunctions(forward.centerline, forward.sourceNodeIds, junctionPlans);
const length = lineLengthMeters(line);
if (line.length < 2 || !Number.isFinite(length)) {
@@ -2030,20 +2008,12 @@ function compileSidewalkSurfaces(
['right', forward.sidewalkRight || Boolean(backward?.sidewalkLeft)],
];
const cluster = clusterForRoad(forward, options) || (backward ? clusterForRoad(backward, options) : null);
const center = cluster ? clusterCenter(cluster, junctionPlans) : null;
for (const [side, enabled] of sides) {
const profile = forward.directEditProfile;
const sidewalkWidth = profile?.sidewalkWidths?.[side] ?? DEFAULT_SIDEWALK_WIDTH_METERS;
if (!enabled || sidewalkWidth <= 0) continue;
const centerline = cluster
? trimLineAtComplexCluster(
forward.centerline,
forward.sourceNodeIds,
junctionPlans,
cluster,
center,
complexBoundaries.get(cluster.id)?.get(forward.id),
)
? trimRoadAtComplexClusters(forward, junctionPlans, options.junctionTemplates.clusters, complexBoundaries)
: trimLineAtJunctions(forward.centerline, forward.sourceNodeIds, junctionPlans);
const ring = sidewalkRing(centerline, totalWidth / 2, totalWidth / 2 + sidewalkWidth, side === 'left' ? 1 : -1);
if (!ring) {
@@ -2310,14 +2280,7 @@ function compileLaneCenterlines(
const internalCluster = boundaryCluster && roadInternalToCluster(road, boundaryCluster);
const clippedRoadLine =
boundaryCluster?.template === 'complex-junction-v1'
? trimLineAtComplexCluster(
road.centerline,
road.sourceNodeIds,
junctionPlans,
boundaryCluster,
clusterCenters.get(boundaryCluster.id),
complexBoundaries.get(boundaryCluster.id)?.get(road.id),
)
? trimRoadAtComplexClusters(road, junctionPlans, clusters, complexBoundaries)
: trimLineAtJunctions(road.centerline, road.sourceNodeIds, junctionPlans);
// OSM centerline is the shared carriageway center. On a two-way road,
// offset each directed carriageway to its own side before placing lanes.
@@ -3642,20 +3605,27 @@ function trimLineAtJunctions(line, sourceNodeIds, junctionPlans) {
return result;
}
function trimLineAtComplexCluster(line, sourceNodeIds, junctionPlans, cluster, center, boundarySection) {
if (!center || line.length < 2) return trimLineAtJunctions(line, sourceNodeIds, junctionPlans);
const radius = complexJunctionMetrics(cluster).approachOuterRadius;
const startInCluster = cluster.nodeIds.map(String).includes(String(sourceNodeIds[0]));
const endInCluster = cluster.nodeIds.map(String).includes(String(sourceNodeIds.at(-1)));
function trimRoadAtComplexClusters(road, junctionPlans, clusters, boundaries) {
const { centerline: line, sourceNodeIds } = road;
if (line.length < 2) return line;
const available = lineLengthMeters(line);
const startDistance = startInCluster
? (boundarySection?.outer.stationMeters ?? distanceAlongLineToRadius(line, center, radius))
: 0;
const endDistance = endInCluster
? (boundarySection?.outer.stationMeters ?? distanceAlongLineToRadius([...line].reverse(), center, radius))
: 0;
const startCutback = startDistance > 0 && available > startDistance + 1 ? startDistance : 0;
const endCutback = endDistance > 0 && available > endDistance + 1 ? endDistance : 0;
// Both stations refer to the original source line. Trimming sequentially
// would shift the second station and choosing one cluster leaves a corridor
// extending through the other junction's approach.
const cutback = (nodeId, oriented) => {
const cluster = clusters.find(
(item) => item.template === 'complex-junction-v1' && item.nodeIds.map(String).includes(String(nodeId)),
);
if (!cluster) return 0;
const center = clusterCenter(cluster, junctionPlans);
if (!center) return 0;
const station =
boundaries.get(cluster.id)?.get(road.id)?.outer.stationMeters ??
distanceAlongLineToRadius(oriented, center, complexJunctionMetrics(cluster).approachOuterRadius);
return station > 0 && available > station + 1 ? station : 0;
};
const startCutback = cutback(sourceNodeIds[0], line);
const endCutback = cutback(sourceNodeIds.at(-1), [...line].reverse());
if (!startCutback && !endCutback) return line;
return trimLineRange(line, startCutback, endCutback);
}
+478
View File
@@ -0,0 +1,478 @@
'use strict';
// Independent measurements of published geometry. Do not call the boundary or
// marking builders here: a shared bug must not manufacture its own expectation.
const TOLERANCE_METERS = 0.01;
const LAYERS = [
'roadSurface',
'coreApproach',
'edgeLines',
'centerLines',
'laneCenterlines',
'laneSeparators',
'sidewalkSurface',
];
const mix = (a, b, t = 0.5) => a.map((v, i) => v + (b[i] - v) * t);
const ids = (value) =>
String(value || '')
.split(',')
.filter(Boolean);
const id = (feature) => feature?.properties?.native_id;
const xy = (point, origin) => [
(point[0] - origin[0]) * 111320 * Math.cos((origin[1] * Math.PI) / 180),
(point[1] - origin[1]) * 111320,
];
const distance = (a, b) => Math.hypot(...xy(a, b));
const dot = (a, b) => a[0] * b[0] + a[1] * b[1];
const cross = (a, b) => a[0] * b[1] - a[1] * b[0];
const subtract = (a, b) => a.map((v, i) => v - b[i]);
function pointSegmentDistance(point, a, b) {
const p = xy(a, point),
q = xy(b, point),
v = subtract(q, p);
const t = Math.max(0, Math.min(1, -dot(p, v) / (dot(v, v) || 1)));
return Math.hypot(...mix(p, q, t));
}
function lineDistance(point, line) {
return Math.min(...line.slice(1).map((q, i) => pointSegmentDistance(point, line[i], q)));
}
function ringsOf(feature) {
if (feature?.geometry?.type === 'Polygon') return feature.geometry.coordinates;
if (feature?.geometry?.type === 'MultiPolygon') return feature.geometry.coordinates.flat();
return [];
}
function inside(point, ring) {
let result = false;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const a = ring[i],
b = ring[j];
if (a[1] > point[1] !== b[1] > point[1] && point[0] < ((b[0] - a[0]) * (point[1] - a[1])) / (b[1] - a[1]) + a[0])
result = !result;
}
return result;
}
// Partition at every edge crossing. A narrow interior notch cannot hide
// between probes, unlike endpoint-only or fixed quarter-point measurements.
function measureSegment(a, b, feature, boundaryOnly = true) {
const rings = ringsOf(feature).map((ring) => ring.map((p) => xy(p, a)));
const end = xy(b, a),
length = Math.hypot(...end),
length2 = dot(end, end);
if (!rings.length || !length) return { errorMeters: null, uncoveredMeters: length, missing: true };
const partitions = [0, 1],
intervals = [];
for (const ring of rings)
for (let i = 1; i < ring.length; i++) {
const p = ring[i - 1],
q = ring[i],
v = subtract(q, p),
denominator = cross(end, v);
if (Math.abs(denominator) > 1e-12) {
const t = cross(p, v) / denominator,
u = cross(p, end) / denominator;
if (t > 0 && t < 1 && u >= 0 && u <= 1) partitions.push(t);
}
// Project only edges parallel and numerically coincident with the seam.
// Tolerance is a permitted geometric error, not permission to bridge gaps.
if (
Math.abs(cross(end, p)) / length <= TOLERANCE_METERS &&
Math.abs(cross(end, q)) / length <= TOLERANCE_METERS
) {
const first = Math.max(0, Math.min(dot(p, end), dot(q, end)) / length2);
const last = Math.min(1, Math.max(dot(p, end), dot(q, end)) / length2);
if (last > first) {
intervals.push([first, last]);
partitions.push(first, last);
}
}
}
partitions.sort((x, y) => x - y);
let uncoveredMeters = 0;
const polygons = feature.geometry.type === 'Polygon' ? [feature.geometry.coordinates] : feature.geometry.coordinates;
const inPolygon = (p) =>
polygons.some((polygon) => inside(p, polygon[0]) && !polygon.slice(1).some((hole) => inside(p, hole)));
for (let i = 1; i < partitions.length; i++) {
const first = partitions[i - 1],
last = partitions[i],
t = (first + last) / 2;
if (!intervals.some(([lo, hi]) => t >= lo && t <= hi) && (boundaryOnly || !inPolygon(mix(a, b, t))))
uncoveredMeters += (last - first) * length;
}
const endpointError = Math.max(
...[a, b].map((p) =>
!boundaryOnly && inPolygon(p) ? 0 : Math.min(...ringsOf(feature).map((ring) => lineDistance(p, ring))),
),
);
return { errorMeters: endpointError, uncoveredMeters };
}
function caps(feature) {
const ring = ringsOf(feature)[0] || [],
half = (ring.length - 1) / 2;
if (!Number.isInteger(half) || half < 2) return [];
return [
[ring[0], ring[ring.length - 2]],
[ring[half - 1], ring[half]],
];
}
function auditJunctionSeams(model, geometry, structures) {
const report = Object.fromEntries(
LAYERS.map((layer) => [layer, { checked: 0, failed: 0, notApplicable: 0, records: [] }]),
);
const features = (layer) => geometry[layer]?.features || [];
function record(layer, identity, measurement, featureIds = []) {
const missing = Boolean(measurement.missing);
const failed =
missing ||
!Number.isFinite(measurement.errorMeters) ||
measurement.errorMeters > TOLERANCE_METERS ||
(measurement.uncoveredMeters || 0) > TOLERANCE_METERS;
report[layer].checked++;
if (failed) report[layer].failed++;
report[layer].records.push({
...identity,
featureIds: featureIds.filter(Boolean),
...measurement,
status: failed ? 'failed' : 'passed',
});
}
function na(layer, identity, reason) {
report[layer].notApplicable++;
report[layer].records.push({ ...identity, status: 'not-applicable', reason });
}
function point(layer, identity, expected, candidates, points) {
const actual = candidates.flatMap(points);
record(
layer,
identity,
{
errorMeters: actual.length ? Math.min(...actual.map((p) => distance(expected, p))) : null,
missing: !actual.length,
},
candidates.map(id),
);
}
for (const structure of structures) {
const clusterId = structure.junctionRef.id;
const core = features('roadSurface').find(
(f) => f.properties.cluster_id === clusterId && f.properties.kind === 'complex-core',
);
for (const arm of structure.arms)
for (const carriageway of arm.carriageways) {
const roadIds = carriageway.provenance.roadIds;
const identity = { clusterId, carriagewayKey: carriageway.key, roadIds };
const approach = features('roadSurface').find((f) => f.properties.carriageway_key === carriageway.key);
if (!approach) {
for (const layer of LAYERS.filter((name) => name !== 'sidewalkSurface'))
record(layer, identity, { missing: true, errorMeters: null, reason: 'Required approach is missing.' });
continue;
}
const ring = approach.geometry.coordinates[0],
seam = [ring[0], ring[3]];
const exterior = features('roadSurface').filter(
(f) =>
roadIds.length === ids(f.properties.directional_road_ids).length &&
roadIds.every((roadId) => ids(f.properties.directional_road_ids).includes(roadId)),
);
record('roadSurface', { ...identity, join: 'exterior-approach' }, measureSegment(...seam, exterior[0]), [
id(approach),
id(exterior[0]),
]);
record('coreApproach', { ...identity, join: 'approach-core' }, measureSegment(ring[1], ring[2], core, false), [
id(approach),
id(core),
]);
const pavement = features('roadSurface').find(
(f) => f.properties.cluster_id === clusterId && f.properties.kind === 'complex-pavement-region',
);
record(
'roadSurface',
{ ...identity, join: 'exterior-published-pavement' },
measureSegment(...seam, pavement, false),
[id(pavement)],
);
const road = model.roads.find((r) => r.id === roadIds[0]);
// Preview indices run right-to-left in the outward arm frame; native
// lanes run left-to-right in each road's travel frame. Derive the mapping
// from source direction, never from whichever geometry happens to be near.
const incoming = (r) => carriageway.provenance.nodeIds.includes(String(r.sourceNodeIds.at(-1)));
const sourceRoads = roadIds.map((roadId) => model.roads.find((r) => r.id === roadId));
const bindings = [...sourceRoads.filter((r) => !incoming(r)), ...sourceRoads.filter(incoming)].flatMap((r) =>
Array.from({ length: r.laneCount }, (_, i) => ({
roadId: r.id,
laneIndex: incoming(r) ? i + 1 : r.laneCount - i,
})),
);
const previews = features('laneCenterlines').filter(
(f) =>
f.properties.carriageway_key === carriageway.key &&
f.properties.cluster_preview &&
roadIds.includes(f.properties.road_id),
);
for (let index = 1; index <= carriageway.laneCount; index++) {
const laneIdentity = { ...identity, laneIndex: index };
const preview = previews.find((f) => f.properties.lane_index === index);
const binding = bindings[index - 1];
const external = features('laneCenterlines').filter(
(f) =>
!f.properties.cluster_preview &&
f.properties.road_id === binding.roadId &&
f.properties.lane_index === binding.laneIndex,
);
const expected = mix(...seam, (index - 0.5) / carriageway.laneCount);
point(
'laneCenterlines',
{ ...laneIdentity, join: 'transition-seam' },
expected,
preview ? [preview] : [],
(f) => [f.geometry.coordinates[0]],
);
point('laneCenterlines', { ...laneIdentity, join: 'external-transition' }, expected, external, (f) => [
f.geometry.coordinates[0],
f.geometry.coordinates.at(-1),
]);
}
// Edges terminate at the outer pavement edge; there is no separately
// published internal edge continuation. Match the same source road only.
const directions = model.roads.filter((r) => r.segmentId === road.segmentId);
for (const sourceRoad of sourceRoads)
for (const side of directions.length > 1 ? ['right'] : ['left', 'right']) {
const edges = features('edgeLines').filter(
(f) => f.properties.road_id === sourceRoad.id && f.properties.side === side,
);
const expected = seam[(side === 'right') === incoming(sourceRoad) ? 1 : 0];
if (edges.some((f) => f.properties.pattern !== 'solid')) {
const surfaceRing = ringsOf(exterior[0])[0] || [];
const half = (surfaceRing.length - 1) / 2;
const supports = [surfaceRing.slice(0, half), surfaceRing.slice(half, -1)];
const support = supports.sort((a, b) => lineDistance(expected, a) - lineDistance(expected, b))[0];
const nearest = edges
.map((f) => ({ f, ends: caps(f).map((cap) => mix(...cap)) }))
.sort(
(a, b) =>
Math.min(...a.ends.map((p) => distance(p, expected))) -
Math.min(...b.ends.map((p) => distance(p, expected))),
)[0];
const gap = Math.min(...nearest.ends.map((p) => distance(p, expected)));
record(
'edgeLines',
{ ...identity, roadId: sourceRoad.id, side, join: 'dash-support' },
{
errorMeters: Math.max(...nearest.ends.map((p) => lineDistance(p, support))),
gapMeters: gap,
uncoveredMeters: Math.max(0, gap - (incoming(sourceRoad) ? 4 : 0)),
},
[id(nearest.f)],
);
na(
'edgeLines',
{ ...identity, side },
'Two-metre dashes with two-metre spacing need not end at the seam.',
);
continue;
}
const actual = edges.flatMap((f) => caps(f).map((cap) => mix(...cap)));
record(
'edgeLines',
{ ...identity, roadId: sourceRoad.id, side },
{
missing: !actual.length,
errorMeters: actual.length ? Math.min(...actual.map((p) => distance(p, expected))) : null,
},
edges.map(id),
);
}
for (let index = 1; index < carriageway.laneCount; index++) {
const separatorIdentity = { ...identity, leftLaneIndex: index, rightLaneIndex: index + 1 };
const expected = mix(...seam, index / carriageway.laneCount);
const separators = features('laneSeparators').filter(
(f) =>
f.properties.cluster_id === clusterId &&
roadIds.includes(f.properties.road_id) &&
f.properties.left_lane_index === index &&
f.properties.provenance === 'native-road-complex-lane-separator/v1',
);
point('laneSeparators', { ...separatorIdentity, join: 'transition-seam' }, expected, separators, (f) =>
caps(f).map((cap) => mix(...cap)),
);
const firstBinding = bindings[index - 1],
secondBinding = bindings[index];
if (firstBinding.roadId !== secondBinding.roadId) {
na(
'laneSeparators',
separatorIdentity,
'Opposite directions meet at the road centre marking, not an exterior lane separator.',
);
continue;
}
const exteriorIndex = Math.min(firstBinding.laneIndex, secondBinding.laneIndex);
const exteriorSeparators = features('laneSeparators').filter(
(f) =>
f.properties.road_id === firstBinding.roadId &&
f.properties.left_lane_index === exteriorIndex &&
f.properties.provenance === 'native-road-lane-separator/v1',
);
if (!exteriorSeparators.length)
record('laneSeparators', separatorIdentity, { missing: true, errorMeters: null });
else {
// The final dash need not end at the seam. Its centre must lie on the
// same lane pair's support, near this interface rather than another arm.
const lanes = [exteriorIndex, exteriorIndex + 1].map((laneIndex) =>
features('laneCenterlines').find(
(f) =>
!f.properties.cluster_preview &&
f.properties.road_id === firstBinding.roadId &&
f.properties.lane_index === laneIndex,
),
);
const nearest = exteriorSeparators
.map((f) => ({ f, point: mix(...caps(f).map((cap) => mix(...cap))) }))
.sort((a, b) => distance(a.point, expected) - distance(b.point, expected))[0];
const first = lanes[0]?.geometry.coordinates,
second = lanes[1]?.geometry.coordinates;
const support = first && first.length === second?.length ? first.map((p, i) => mix(p, second[i])) : [];
const gap = Math.min(...caps(nearest.f).map((cap) => distance(mix(...cap), expected)));
record(
'laneSeparators',
{ ...separatorIdentity, join: 'external-dash-support' },
{
missing: !support.length,
errorMeters: support.length
? Math.max(...caps(nearest.f).map((cap) => lineDistance(mix(...cap), support)))
: null,
gapMeters: gap,
uncoveredMeters: Math.max(
0,
gap -
(nearest.f.properties.pattern === 'solid' ||
!incoming(sourceRoads.find((r) => r.id === firstBinding.roadId))
? 0
: 4),
),
},
[id(nearest.f), ...lanes.map(id)],
);
na(
'laneSeparators',
separatorIdentity,
'Dash spacing and stop-line clipping do not require white paint across the seam.',
);
}
}
if (carriageway.laneCount < 2) na('laneSeparators', identity, 'Single lane has no lane separator.');
if (directions.length < 2 || road.highway === 'service')
na('centerLines', identity, 'No bidirectional road centre marking is published.');
else {
const markings = features('centerLines').filter(
(f) =>
roadIds.includes(f.properties.road_id) &&
roadIds.length === ids(f.properties.directional_road_ids).length &&
roadIds.every((roadId) => ids(f.properties.directional_road_ids).includes(roadId)),
);
const nearest = markings
.map((f) => ({ f, point: mix(...caps(f).map((cap) => mix(...cap))) }))
.sort((a, b) => distance(a.point, mix(...seam)) - distance(b.point, mix(...seam)))[0];
const supportPoints = nearest ? caps(nearest.f).map((cap) => mix(...cap)) : [];
const gap = supportPoints.length ? Math.min(...supportPoints.map((p) => distance(p, mix(...seam)))) : null;
record(
'centerLines',
identity,
{
missing: !nearest,
errorMeters: nearest
? Math.max(
...supportPoints.map((p) =>
Math.abs(lineDistance(p, road.centerline) - (nearest.f.properties.double ? 0.16 : 0)),
),
)
: null,
gapMeters: gap,
uncoveredMeters:
gap === null
? 0
: Math.max(
0,
gap -
(incoming(sourceRoads.find((r) => r.id === nearest.f.properties.road_id))
? nearest.f.properties.dash_length_m + nearest.f.properties.dash_gap_m
: 0),
),
},
[id(nearest?.f)],
);
na(
'centerLines',
identity,
'Road centre dashes terminate outside the cluster; no interior centre marking is published.',
);
}
}
for (const corner of structure.corners) {
const arms = [corner.fromArmKey, corner.toArmKey].map((key) => structure.arms.find((arm) => arm.key === key));
const roadGroups = arms.map((arm) => arm.carriageways.flatMap((c) => c.provenance.roadIds));
const strips = roadGroups.map((roadIds) =>
features('sidewalkSurface').filter(
(f) =>
f.properties.provenance === 'native-road-sidewalk/v1' &&
ids(f.properties.directional_road_ids).some((roadId) => roadIds.includes(roadId)),
),
);
const identity = { clusterId, cornerKey: corner.key, roadIds: roadGroups.flat() };
if (strips.some((group) => !group.length)) {
const enabled = roadGroups.every((group) =>
group.some((roadId) => {
const road = model.roads.find((r) => r.id === roadId);
return road?.sidewalkLeft || road?.sidewalkRight;
}),
);
if (enabled) record('sidewalkSurface', identity, { missing: true, errorMeters: null });
else na('sidewalkSurface', identity, 'Source arms do not both carry sidewalks.');
continue;
}
const join = features('sidewalkSurface').find(
(f) => f.properties.kind === 'complex-sidewalk-corner' && f.properties.corner_key === corner.key,
);
if (!join) {
const omitted = (geometry.diagnostics || []).find(
(d) =>
d.subjectId === `corner:${corner.key}` &&
[
'complex-junction-sidewalk-corner-fallback',
'complex-junction-island-infeasible',
'complex-junction-corner-exclusion-overlap',
].includes(d.rule),
);
if (omitted) na('sidewalkSurface', identity, `Explicitly rejected corner: ${omitted.rule}. ${omitted.message}`);
else record('sidewalkSurface', identity, { missing: true, errorMeters: null });
continue;
}
if (caps(join).length !== 2) {
record('sidewalkSurface', identity, { missing: true, errorMeters: null, reason: 'Invalid corner end edges.' });
continue;
}
for (const [index, cap] of caps(join).entries()) {
const candidates = strips[index]
.map((f) => ({ f, measurement: measureSegment(...cap, f) }))
.sort(
(a, b) =>
a.measurement.errorMeters +
a.measurement.uncoveredMeters -
(b.measurement.errorMeters + b.measurement.uncoveredMeters),
);
record('sidewalkSurface', { ...identity, end: index }, candidates[0].measurement, [
id(join),
id(candidates[0].f),
]);
}
}
}
return report;
}
module.exports = { TOLERANCE_METERS, LAYERS, auditJunctionSeams, measureSegment, distance };
+343
View File
@@ -0,0 +1,343 @@
'use strict';
const assert = require('assert/strict');
const fs = require('fs');
const path = require('path');
const { compileRoadModel, compileGeometry } = require('../src/compile/native-road');
const { auditJunctionSeams, LAYERS, measureSegment } = require('./helpers/junction-seams');
const overrides = { overrides: [] };
function compile(name, model, clusters, extra = {}, styles = overrides) {
const geometry = compileGeometry(model, styles, { junctionTemplates: { enabled: true, clusters }, ...extra });
const structures = geometry.roadSurface.features.map((f) => f.properties.junction_structure).filter(Boolean);
assert.equal(structures.length, clusters.length, `${name}: missing junction structure`);
const report = auditJunctionSeams(model, geometry, structures);
return { name, model, clusters, geometry, structures, report };
}
function synthetic(curved = false, twoWay = false, adjacent = false) {
const nodes = [
[-5, 0],
[240, 0],
[5, 240],
[-240, 0],
[-5, -240],
[100, curved ? 12 : 0],
[5, 0],
];
if (adjacent) nodes.push([250, 0], [240, 240], [500, 0], [250, -240]);
const ways = [2, 3, 4, 5].map((n) => [n, [n <= 3 ? 7 : 1, ...(n === 2 ? [6] : []), n]]);
if (adjacent) ways.push([9, [2, 9]], [10, [8, 10]], [11, [8, 11]]);
const internal = [[1, 7], ...(adjacent ? [[2, 8]] : [])];
const osm = `<osm>${nodes.map(([x, y], i) => `<node id="${i + 1}" lon="${120 + x / (111320 * Math.cos(Math.PI / 6))}" lat="${30 + y / 111320}"/>`).join('')}${ways.map(([id, refs]) => `<way id="${id}">${refs.map((ref) => `<nd ref="${ref}"/>`).join('')}<tag k="highway" v="primary"/><tag k="lanes" v="${twoWay ? 4 : 3}"/>${twoWay ? '' : '<tag k="oneway" v="yes"/>'}<tag k="sidewalk" v="both"/></way>`).join('')}${internal.map((refs, i) => `<way id="internal${i}">${refs.map((ref) => `<nd ref="${ref}"/>`).join('')}<tag k="highway" v="primary"/></way>`).join('')}</osm>`;
return compileRoadModel(osm, overrides);
}
const cluster = { id: 'synthetic', template: 'complex-junction-v1', coreRadiusMeters: 21, nodeIds: ['1', '7'] };
const realModel = compileRoadModel(
fs.readFileSync(path.join(__dirname, '../inputs/osm/枫树二路.osm'), 'utf8'),
overrides,
);
const west = {
id: 'west',
template: 'complex-junction-v1',
coreRadiusMeters: 21,
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147'],
};
const east = {
id: 'east',
template: 'complex-junction-v1',
coreRadiusMeters: 18,
nodeIds: ['1590698046', '6538106539'],
};
const scenarios = [
compile('straight', synthetic(), [cluster]),
compile('curved', synthetic(true), [cluster]),
compile('two-way', synthetic(false, true), [cluster]),
compile('two-way-curved', synthetic(true, true), [cluster]),
compile('real-osm', realModel, [west]),
compile('adjacent', realModel, [west, east]),
compile(
'sidewalks',
{ ...realModel, roads: realModel.roads.map((r) => ({ ...r, sidewalkLeft: true, sidewalkRight: true })) },
[west],
),
];
scenarios.push(
compile('two-way-adjacent', synthetic(true, true, true), [
cluster,
{ ...cluster, id: 'synthetic-east', nodeIds: ['2', '8'] },
]),
);
const curvedTwoWay = scenarios.find((s) => s.name === 'two-way-curved');
const twoWayApproach = curvedTwoWay.geometry.roadSurface.features.find((f) => f.properties.kind === 'complex-approach');
scenarios.push(
compile('two-way-width-edit', curvedTwoWay.model, [cluster], {
directEdit: {
clusterPlans: new Map([
[cluster.id, new Map([[twoWayApproach.properties.carriageway_key, twoWayApproach.properties.width_m * 1.2]])],
]),
},
}),
);
const curved = scenarios[1];
const approach = curved.geometry.roadSurface.features.find((f) => f.properties.kind === 'complex-approach');
scenarios.push(
compile('width-edit', curved.model, [cluster], {
directEdit: {
clusterPlans: new Map([
[cluster.id, new Map([[approach.properties.carriageway_key, approach.properties.width_m * 1.2]])],
]),
},
}),
);
scenarios.push(
compile('island-edit', realModel, [west], { directEdit: { clusterIslandOffsets: new Map([[west.id, 3.3]]) } }),
);
scenarios.push(compile('adjacent-reordered', { ...realModel, roads: [...realModel.roads].reverse() }, [east, west]));
scenarios.push(
compile(
'dashed-edges',
synthetic(true, true),
[cluster],
{},
{
overrides: synthetic(true, true).roads.flatMap((r) =>
['left', 'right'].map((side) => ({
kind: 'edge-line-style',
roadId: r.id,
side,
color: 'white',
pattern: 'dashed',
})),
),
},
),
);
const expectedCoverage = {
straight: [8, 4, 8, 0, 24, 16, 4],
curved: [8, 4, 8, 0, 24, 16, 4],
'two-way': [8, 4, 8, 4, 32, 20, 8],
'two-way-curved': [8, 4, 8, 4, 32, 20, 8],
'real-osm': [16, 8, 16, 0, 48, 32, 0],
adjacent: [26, 13, 26, 1, 76, 49, 0],
sidewalks: [16, 8, 16, 0, 48, 32, 8],
'width-edit': [8, 4, 8, 0, 24, 16, 4],
'island-edit': [16, 8, 16, 0, 48, 32, 0],
'adjacent-reordered': [26, 13, 26, 1, 76, 49, 0],
'dashed-edges': [8, 4, 8, 4, 32, 20, 8],
'two-way-adjacent': [16, 8, 16, 8, 64, 40, 16],
'two-way-width-edit': [8, 4, 8, 4, 32, 20, 8],
};
for (const { name, report } of scenarios) {
assert.deepEqual(
LAYERS.map((layer) => report[layer].checked),
expectedCoverage[name],
`${name}: coverage changed`,
);
for (const layer of LAYERS) {
assert.equal(
report[layer].failed,
0,
`${name}/${layer}: ${JSON.stringify(report[layer].records.filter((r) => r.status === 'failed'))}`,
);
assert.ok(report[layer].records.every((r) => r.status !== 'not-applicable' || r.reason));
}
}
for (const layer of LAYERS)
assert.ok(
scenarios.some((s) => s.report[layer].checked > 0),
`${layer}: empty audit`,
);
// Reordering must preserve expected source identities, not just pass counts.
function identities(report) {
return Object.fromEntries(
LAYERS.map((layer) => [
layer,
report[layer].records
.map((r) =>
JSON.stringify({
...r,
featureIds: undefined,
errorMeters: undefined,
uncoveredMeters: undefined,
gapMeters: undefined,
roadIds: [...r.roadIds].sort(),
}),
)
.sort(),
]),
);
}
assert.deepEqual(
identities(scenarios.find((s) => s.name === 'adjacent').report),
identities(scenarios.find((s) => s.name === 'adjacent-reordered').report),
);
// Corrupt published outputs while retaining the independent expected topology.
const base = scenarios.find((s) => s.name === 'two-way');
function detects(name, layer, mutate, scenario = base) {
const geometry = structuredClone(scenario.geometry);
mutate(geometry);
const result = auditJunctionSeams(scenario.model, geometry, scenario.structures);
assert.ok(result[layer].failed > 0, `${name}: audit silently accepted damaged ${layer}`);
}
const shift = (coordinates, dx, dy) =>
typeof coordinates[0] === 'number'
? [coordinates[0] + dx / (111320 * Math.cos((coordinates[1] * Math.PI) / 180)), coordinates[1] + dy / 111320]
: coordinates.map((value) => shift(value, dx, dy));
const move = (feature) => {
feature.geometry.coordinates = shift(feature.geometry.coordinates, 0.02, 0);
};
for (const [layer, predicate, auditLayer = layer] of [
['roadSurface', (f) => Boolean(f.properties.directional_road_ids)],
['roadSurface', (f) => f.properties.kind === 'complex-core', 'coreApproach'],
['roadSurface', (f) => f.properties.kind === 'complex-approach'],
['edgeLines', () => true],
['centerLines', () => true],
['laneCenterlines', (f) => !f.properties.cluster_preview],
['laneSeparators', (f) => f.properties.provenance === 'native-road-complex-lane-separator/v1'],
['sidewalkSurface', (f) => f.properties.kind === 'complex-sidewalk-corner'],
]) {
detects('missing counterpart', auditLayer, (g) => {
g[layer].features = g[layer].features.filter((f) => !predicate(f));
});
detects('one missing counterpart', auditLayer, (g) => {
const index = g[layer].features.findIndex(predicate);
assert.ok(index >= 0);
g[layer].features.splice(index, 1);
});
detects('2 cm displacement', auditLayer, (g) => g[layer].features.filter(predicate).forEach(move));
}
detects('wrong preview source', 'laneCenterlines', (g) => {
g.laneCenterlines.features.find((f) => f.properties.cluster_preview).properties.road_id = 'wrong-road';
});
detects('wrong centre primary source', 'centerLines', (g) => {
for (const f of g.centerLines.features) f.properties.road_id = 'wrong-road';
});
detects('partial centre source match', 'centerLines', (g) => {
for (const f of g.centerLines.features) f.properties.directional_road_ids = `${f.properties.road_id},wrong-road`;
});
for (const layer of ['edgeLines', 'centerLines', 'laneCenterlines', 'laneSeparators']) {
detects('wrong source', layer, (g) => {
for (const f of g[layer].features) {
f.properties.road_id = 'wrong-road';
if (f.properties.directional_road_ids) f.properties.directional_road_ids = 'wrong-road';
}
});
}
detects('swapped lane indices', 'laneCenterlines', (g) => {
for (const f of g.laneCenterlines.features.filter((f) => !f.properties.cluster_preview))
f.properties.lane_index = 3 - f.properties.lane_index;
});
detects('wrong surface source', 'roadSurface', (g) => {
for (const f of g.roadSurface.features.filter((f) => f.properties.directional_road_ids))
f.properties.directional_road_ids = 'wrong-road';
});
detects('missing sidewalk strip', 'sidewalkSurface', (g) => {
g.sidewalkSurface.features = g.sidewalkSurface.features.filter(
(f) => f.properties.provenance !== 'native-road-sidewalk/v1',
);
});
detects('wrong sidewalk source', 'sidewalkSurface', (g) => {
for (const f of g.sidewalkSurface.features.filter((f) => f.properties.provenance === 'native-road-sidewalk/v1'))
f.properties.directional_road_ids = 'wrong-road';
});
detects(
'displaced edge dashes',
'edgeLines',
(g) => g.edgeLines.features.forEach(move),
scenarios.find((s) => s.name === 'dashed-edges'),
);
detects(
'missing anchored edge dash',
'edgeLines',
(g) => g.edgeLines.features.shift(),
scenarios.find((s) => s.name === 'dashed-edges'),
);
detects('missing exterior separators', 'laneSeparators', (g) => {
g.laneSeparators.features = g.laneSeparators.features.filter(
(f) => f.properties.provenance !== 'native-road-lane-separator/v1',
);
});
detects('displaced exterior separators', 'laneSeparators', (g) =>
g.laneSeparators.features.filter((f) => f.properties.provenance === 'native-road-lane-separator/v1').forEach(move),
);
// A 2 cm notch away from all endpoint/quarter/midpoint probes must fail.
const metric = ([x, y]) => [120 + x / (111320 * Math.cos(Math.PI / 6)), 30 + y / 111320];
const polygon = (ring) => ({ geometry: { type: 'Polygon', coordinates: [ring.map(metric)] } });
const full = polygon([
[0, 0],
[10, 0],
[10, 2],
[0, 2],
[0, 0],
]);
const notch = polygon([
[0, 0],
[3.11, 0],
[3.11, 0.1],
[3.13, 0.1],
[3.13, 0],
[10, 0],
[10, 2],
[0, 2],
[0, 0],
]);
for (const boundaryOnly of [true, false]) {
assert.ok(measureSegment(metric([0, 0]), metric([10, 0]), full, boundaryOnly).uncoveredMeters < 0.01);
assert.ok(measureSegment(metric([0, 0]), metric([10, 0]), notch, boundaryOnly).uncoveredMeters > 0.019);
}
const holed = polygon([
[0, -1],
[10, -1],
[10, 2],
[0, 2],
[0, -1],
]);
holed.geometry.coordinates.push(
[
[3.11, -0.1],
[3.13, -0.1],
[3.13, 0.1],
[3.11, 0.1],
[3.11, -0.1],
].map(metric),
);
assert.ok(measureSegment(metric([0, 0]), metric([10, 0]), holed, false).uncoveredMeters > 0.019);
const summary = scenarios.map(({ name, report }) => ({
name,
layers: Object.fromEntries(
LAYERS.map((layer) => {
const { checked, failed, notApplicable, records } = report[layer];
return [
layer,
{
checked,
failed,
notApplicable,
maxErrorMeters: Math.max(0, ...records.map((r) => r.errorMeters || 0)),
maxUncoveredMeters: Math.max(0, ...records.map((r) => r.uncoveredMeters || 0)),
},
];
}),
),
}));
const reportIndex = process.argv.indexOf('--report');
if (reportIndex >= 0)
fs.writeFileSync(
process.argv[reportIndex + 1],
JSON.stringify(
{ toleranceMeters: 0.01, summary, scenarios: scenarios.map(({ name, report }) => ({ name, report })) },
null,
2,
) + '\n',
);
console.log(
`junction layer seam tests passed (${scenarios.length} scenarios, ${summary.reduce((sum, s) => sum + Object.values(s.layers).reduce((n, l) => n + l.checked, 0), 0)} measured joins)`,
);