diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/check.jsonl b/.trellis/tasks/09-08-junction-reference-fidelity/check.jsonl new file mode 100644 index 0000000..8812b1e --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/check.jsonl @@ -0,0 +1,3 @@ +{"file": ".trellis/spec/backend/direct-edit-api.md", "reason": "纯求解、几何可行域、稳定身份与预览保存合约"} +{"file": ".trellis/spec/frontend/direct-edit-client.md", "reason": "共享编辑会话、预览隔离与输入约定"} +{"file": ".trellis/tasks/09-08-junction-reference-fidelity/research/current-state.md", "reason": "现有表达限制和跨层风险"} diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/design.md b/.trellis/tasks/09-08-junction-reference-fidelity/design.md new file mode 100644 index 0000000..f6b9033 --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/design.md @@ -0,0 +1,45 @@ +# 技术设计:共享结构驱动的复杂路口构建 + +## 核心选择 + +采用“来源拓扑 → 有效结构与接入断面 → 共享边界 → 道路区域 → 设施与连接”的分层管线。不增加按 T/十字等标签分派的独立绘图模板,也不首期引入不可解释的全局非线性自动优化器。 + +自动推断提供初稿,显式结构校正与几何校正处理源数据不足。支持范围有限且可检测;无法求解时输出对象级原因,不制造假连通。 + +## 模型与边界 + +新增内部纯数据 JunctionBuildPlan(内部版本独立于展示结构): + +- SourceTopology:有向车行道及来源 ID、外部接入/内部连接、道路臂归组、已知分隔关系、允许通行关系和推断来源。臂不是一个实心总宽矩形。 +- EntrySection:所属 carriageway、接入中心/方向、左右边界端点、远端固定截面、可用过渡范围。边界按朝路口外侧的局部坐标定义,与 forward/backward 显式换算。 +- BoundaryGraph:接入边、路缘曲线、共享接缝、闭合环、已知排除区域;每条共享边只有一个几何所有者,由相邻面引用。内部允许凹形区域、孔洞及多个通行区域,不能用“全部端点凸包”抹去分隔关系。 +- Dependency:参数到接入断面、边界、面、设施的依赖。修改局部只重新求值必要对象;不承诺相邻角部完全不变,但必须保持约束外的固定锚点和不相关路口不变。 + +junction-structure/v1 保持前端投影,按需扩展展示字段;不在客户端生成第二份几何模型。稳定键由来源和显式关系决定,不随坐标调整或角度排序变化。归组改变属于拓扑编辑,改变 fingerprint 并触发受影响约束重检。 + +## 构建步骤 + +1. 服务层预加载参考配置,纯拓扑解析统一 compiler 与 resolver 当前重复逻辑。先区分进出车行道、分隔关系与内部通路,再形成道路臂;方向相近只作候选依据。 +2. 按各车行道真实中心线和可用长度定义固定远端与可编辑接入断面。不能将“沿线距离”与“到平均中心的半径”混用。允许偏移/方向/左右展宽通过过渡接回固定远端。 +3. 邻接边界先求交和安全连接,局部选择直线/受约束曲线。圆角切点限制来自两侧可用边界;不可行则拒绝该编辑或给出明确降级,不用孤立补面遮盖。 +4. 从闭合边界图构造铺装区域,保留已知不可通行区域;验证连通、相交与孔洞。几何布尔运算只是实现工具,不能决定哪个区域“应当是岛”。共享语义键不依赖布尔运算输出顺序。 +5. 所有道路面、路缘/步行带、边线和车道标线使用同一有效接入与裁切计划。设施定位消费最终可行区域;交通连接是有向运动关系,与平面面邻接分开。允许机动车路径相交,不将其误判成边界自交。 +6. 编译几何验证与 solver 诊断合并,经同一 compileEditCandidate 供预览与保存使用。 + +## 编辑协议 + +复用 native-road-edits/v2 约束与操作历史。新增语义约束建议为 carriageway 接入位姿、左右横向边界与过渡长度;schema 的名称及单位在阶段 1 契约落地时固定。位姿以源断面为基准的局部米制偏移/角度定义,避免绝对坐标缺乏来源;分量标量输入也必须落到完整同一约束。归组覆盖使用稳定源 carriageway 集合,禁止保存界面序号。 + +优先级:显式局部覆盖 > 已保存路口默认 > 自动基线;批量操作先确定目标集合,再合成约束,不能把后一次草稿的基线覆盖前一次修改。重置沿现有禁用约束语义,保存版本冲突遵循 409 合约。 + +## 数据不足和设施范围 + +仅根据夹角不能证明存在导流岛或独立右转道路。已知设施使用显式来源/区域;推断对象标明推断原因,缺少通行区域或步行端点证据时不输出伪造有效设施。未知与不存在分开表达。本期不提供岛体自由编辑器,但 BoundaryGraph 可表达其排除区域与相邻通道,避免下一期推翻基础模型。 + +## 兼容、性能与风险 + +- 新管线先在显式 geometry version 下验证;旧复杂文档不能直接换默认值或静默裁剪。缺省构建应确定性;迁移报告逐约束列出可重放、需重检、失效及原因。普通路口输出回归保持不变。 +- 半径和收口既有语义不等同于新接入位姿,不能凭名称强行映射;保留兼容适配,冲突显式处理。 +- 不为性能让浏览器复制几何算法。记录相同输入的冷/热预览耗时与 payload;300 ms 是既有预算提示,不是无需实测的完成承诺。pending 从排队到最新结果完成持续有效。 +- 局部米制计算与 GeoJSON 经纬度输出分离;方向绕回、曲线进口、短路段、多区域、来源不完整均为失败风险。 +- 回滚按管线/能力关闭;保留新文档的可读性和不支持诊断,禁止旧管线忽略新约束却显示成功。 diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/implement.jsonl b/.trellis/tasks/09-08-junction-reference-fidelity/implement.jsonl new file mode 100644 index 0000000..8812b1e --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/implement.jsonl @@ -0,0 +1,3 @@ +{"file": ".trellis/spec/backend/direct-edit-api.md", "reason": "纯求解、几何可行域、稳定身份与预览保存合约"} +{"file": ".trellis/spec/frontend/direct-edit-client.md", "reason": "共享编辑会话、预览隔离与输入约定"} +{"file": ".trellis/tasks/09-08-junction-reference-fidelity/research/current-state.md", "reason": "现有表达限制和跨层风险"} diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/implement.md b/.trellis/tasks/09-08-junction-reference-fidelity/implement.md new file mode 100644 index 0000000..7533ef8 --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/implement.md @@ -0,0 +1,60 @@ +# 实施计划与阶段出口 + +当前为 planning;用户正在审阅通用方向。创建任务不等于实施批准。单一任务按串行里程碑交付;每阶段必须提交证据,不能以接口有返回代替效果验收。 + +## 0. 契约与最小反例 + +- [x] 审计 compiler/resolver 的归组、方向、沿线距离/半径、共享边与各图层裁切;核实 research/current-state.md 风险。 +- [x] 写出 JunctionBuildPlan 字段、单位、引用完整性、歧义策略和兼容矩阵;确认现有 polygon 工具能力,必要时小型验证,不先扩展 UI。 +- [x] 构造无需图片的反例:分隔双向进口、T 形闭合侧、偏置且不等宽交叉、曲线短进口;在旧实现上记录问题。 +- [x] 出口:每个反例都有结构预期与几何不变量;任何样本 ID 专用分支均不接受。 + +## 1. 共享纯拓扑与接入计划 + +- [x] 统一重复归组;保存车行道和内部通路,不将不同通道按接近角度无条件合并。 +- [x] 引入 EntrySection 契约、来源/推断信息和稳定键;BoundaryGraph 留待连续边界阶段实现。 +- [ ] 分离参考文件加载和纯 resolver;补输入重排、角度绕回、歧义、两路口隔离测试。 +- [ ] 出口 A1/A2 基础:3~6 臂和分隔组合均能产生可解释结构或明确不支持原因。 + +## 2. 连续边界与区域求解(最高风险) + +- [ ] 实现接入断面到固定远端过渡;以共享边界构建中心/进口/角部,取消独立半径拼接作为权威。 +- [ ] 支持凹形与已知排除区域,检查环、自交、接缝、必要连接;设计边界可行域并由 solver/manifest 共用。 +- [ ] 审计 roadSurface、sidewalkSurface、edgeLines、lane/center markings 的每个裁切入口,确保消费同一计划。 +- [ ] 出口 A3:接缝≤1 cm,必要区域连通,无自交与排除区侵占;自动测试验证实际几何,不只是参数回显。 +- [ ] 此阶段不通过,不开启新几何控件。 + +## 3. 通用局部校正闭环 + +- [ ] 贯通接入位置、方向、左右边界、过渡长度与归组覆盖的 validator/replay/solver/manifest/客户端。 +- [ ] 保留已有宽度/收口/圆角语义兼容,超出可行域明确重检,不发布 current 超出自身范围的正常可编辑手柄。 +- [ ] 输入和拖拽复用 EditSession;验证批量编辑已有约束、预览早于 Enter、请求乱序、切换路口、撤销重做、重置和 pending。 +- [ ] 出口 A4/A5/A7:两类结构在浏览器完成预览→保存→编译→刷新,并验证最终地图 source/几何与服务端一致。 + +## 4. 现有设施联动与缺失信息治理 + +- [ ] 现有过街/停止线依附最终车行道;区分未知、已知存在、不支持。 +- [ ] 清理没有区域/连接依据的自动角部设施;对旧结果变化提供来源和诊断说明。 +- [ ] 验证已知排除区和独立通道未被核心铺装吞并,未知岛体不臆造。 +- [ ] 出口 A6;导流岛自由编辑与新右转通道创建留后续任务。 + +## 5. 通用性验收与发布 + +- [ ] 测试矩阵:3/4/5/6 臂,正交/斜交/偏置,不等宽,单/双向和分隔,曲线/短进口,邻接多个路口,缺失/矛盾数据;至少覆盖组合交互,不只各单变量。 +- [ ] 变形测试:重排、平移、旋转(含跨 0°),允许范围内微调;对象身份稳定,几何无跳变。 +- [ ] 保留未参与调参的真实 OSM 用作外部验证;若仓库不具备则记录数据需求,不冒称真实泛化通过。 +- [ ] 生成纯效果/调试效果、几何指标、支持/拒绝情况、耗时及兼容报告;三组截图仅复核暴露的问题是否被通用机制处理。 +- [ ] 用户视觉验收合理初稿与局部校正结果;技术指标通过不能替代该验收。 +- [ ] 更新 spec,记录迁移和剩余能力;按当前用户提交授权执行提交,不假定授权发布或合并。 + +## 验证命令 + +按阶段运行针对性测试:node test/direct-edit-solver.js;node test/junction-structure.js;node test/junction-projection.js;node test/workbench-edit-api.js;新增纯拓扑/区域不变量测试纳入 npm test。 + +最终质量门:npm test、npm run test:client、npm run test:client:unit、npm run test:e2e、npm run format:check、git diff --check。需要本地端口的测试串行执行,避免 8899 冲突。命令失败时后续未执行的子测试不得报告通过。 + +## 关键文件与回滚点 + +complex-junction.js / native-road.js:构建与全部消费者;direct-edit-solver.js / native-road-edits.js:纯求解与兼容;junction-structure.js / junction-topology.js / junction-projection.js:身份及投影;server.js:预览保存一致性;App.tsx / ParameterPanel.tsx / MapCanvas.tsx / edit/*:输入和状态。 + +每个阶段独立可回滚。几何更换前保存原始文档和输出比较,禁止先更新 fixture baseline 掩盖差异。任何大幅缩减支持范围或迁移语义变更先更新规划供用户审阅。 diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/prd.md b/.trellis/tasks/09-08-junction-reference-fidelity/prd.md new file mode 100644 index 0000000..285da30 --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/prd.md @@ -0,0 +1,56 @@ +# 复杂路口通用构建:结构约束与连续边界 + +## 目标与价值 + +让复杂路口由可解释、可组合、可局部校正的结构生成连续道路几何。不同进口数量、方向、宽度和分隔方式应自然得到不同形态,而不是依靠针对具体路口的模板补丁。用户可从 OSM 得到合理初稿,在数据不足时用有限的结构/边界编辑修正,并可靠地预览、撤销、保存和重建。 + +“相对理想”的交付定义:支持范围内结构正确、必要接缝连续、编辑真实有效、无依据设施不被伪造、失败可定位;不是从不完整 OSM 自动还原卫星图的全部细节。 + +## 已确认背景 + +- 用户提供三组真实/生成截图以暴露问题,明确反对专门适配这三个样本。图片保存在 references/,仅作定性观察;尚未配准,遮挡处和尺寸不是事实输入。 +- 现有编辑已覆盖复杂车行道宽度、收口、角部圆角、过街退让、停止线偏移;继续复用编辑与存储闭环。 +- 当前构建仍分别生成中心包络、车行道矩形、圆角和角部设施。问题证据与代码入口见 research/current-state.md。 +- 用户已要求暂缓导流岛编辑;本阶段不以实现岛体编辑为完成条件,但通用结构不能把岛体误当作普通角部填充。 + +## 范围与要求 + +R1 通用结构:显式表达外部车行道、进出方向、接入断面、相邻边界、通行区域、已知排除区域及必要连接。道路臂是组合视图,不因方向近似便抹掉分隔车行道、辅路或独立通道的差异。分类标签用于说明,不控制是否采用同一矩形模板。 + +R2 连续构建:进口、中心、路缘和过渡以同一有效几何计划为依据。外部道路与进口共享接缝;进口与核心的必要连接可验证。支持不等宽、非正交、非对称和错位接入,调整局部参数不得制造断面或侵占已知排除区域。 + +R3 有限校正:支持选定车行道的接入位置、方向、左右边界及过渡长度校正;保留角部控制。道路远端锚定,改动通过过渡传播;控件明确展示作用对象。源拓扑有歧义时允许显式纠正道路臂归组,不能靠改几何角度隐式改变身份。每种控件必须贯通求解、图形、保存再编译后才开放。 + +R4 数据诚实:每个推断保留来源和原因;缺失的岛体、独立右转或过街连接不能被假定存在。已知但暂不支持的复杂结构应给对象级诊断,不能悄悄简化成正确外观。现有设施必须消费有效道路边界;无支撑的自动角部岛体/小斑马线应可识别并停止伪生成,同时报告原因。 + +R5 兼容与交互:保留稳定来源身份、普通路口行为及编辑文档的可读性。输入与拖拽共用会话、预览、撤销、保存协议;慢请求持续显示 pending,旧响应不能覆盖新编辑;无效参数保留最后有效几何并显示原因。 + +## 首期支持边界 + +- 同层平面交叉:3~6 个外部道路臂,含单向/双向及分隔车行道组合、T/斜交/十字/偏置/不等宽进口。 +- 已知分隔空间作为区域约束保留;已识别独立通道不被错误吞并。复杂渠化结构若不能安全构建,明确标记局部不支持。 +- 不承诺任意路网完全自动建模,不涉及立交、环岛专用设计、交通配时优化、卫星图自动识别、完整车道级交通仿真。 +- 导流岛自由编辑、独立右转通道创建、全套过街设施新编辑器作为后续阶段;本期仅完成结构预留、现有设施联动与错误自动生成治理。 + +## 验收标准 + +| ID | 可观察结果与验证 | 对应需求 | +| --- | --- | --- | +| A1 | 单一构建路径覆盖上述 3~6 臂组合;不得以图片编号、OSM ID、地名或固定坐标选分支 | R1、R2 | +| A2 | 同一输入反复编译确定性一致;输入顺序重排不改变来源身份;平移/旋转后的拓扑和相对几何等价;调整一侧方向/宽度能连续响应 | R1、R2 | +| A3 | 局部米制坐标下共享接缝端点偏差 ≤1 cm;环闭合、面积为正且无自交;必要铺装区域连通;已知排除区域不被侵入。逐项报告,不能仅靠截图或 GeoJSON 有变化通过 | R2 | +| A4 | 至少两类不同结构验证接入位置、方向、左右边界、过渡长度的输入/拖拽、撤销/重做、重置、保存/重编译/刷新;目标区域变化且远端锚点保持;真实拓扑改变时旧约束明确重检/失效 | R3、R5 | +| A5 | 每项参数边界可接受且有几何效果;超过边界返回明确诊断。旧文档超出新可行域时不静默截断;歧义归组可解释并可纠正 | R3、R5 | +| A6 | 现有斑马线位于实际车行道范围;已知步行连接可追溯;未知连接标记不确定。无依据的孤立角部设施不作为有效结果输出 | R4 | +| A7 | 预览与正式编译对同文档输出一致;预览不写盘;保存失败/409 不覆盖文档;跨路口、连续编辑和慢响应不串状态 | R5 | +| A8 | 合成组合测试之外,用未参与调参的真实 OSM 验证;三张图仅为定性复核之一。纯效果与调试效果并列提供,用户确认整体达到合理初稿且可局部修正 | 全部 | + +A3 的 1 cm 是内部拼接精度,不代表影像测绘精度。视觉相似度不设置虚假的百分比分数。真实图与源数据无法对应时,记录缺失信息,不猜测完成 A8。 + +## 交付物 + +通用结构/几何契约、构建实现、可用校正界面、兼容策略、结构组合与几何不变量测试、真实数据验证报告、前后纯效果/调试效果对照、遗留问题列表。 + +## 待验证技术问题 + +这些问题由实施阶段证据解决,不要求用户猜实现:现有 polygon 运算是否足以完成区域验证;车道线/步行带全部裁切调用是否统一;现有 OSM 数据能支持哪些歧义归组纠正;校正与旧半径/收口约束的兼容边界。若答案导致缩减上述支持范围,须修订规划后再实施该缩减。 diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/references/manifest.json b/.trellis/tasks/09-08-junction-reference-fidelity/references/manifest.json new file mode 100644 index 0000000..7dc90cc --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/references/manifest.json @@ -0,0 +1,36 @@ +{ + "source": "/tmp/路口对应", + "images": [ + { + "file": "路口1-生成.png", + "sha256": "6cd1ceae55223e1480af858e65cdd128d34286349d28f8b64316937b24b4794a", + "role": "问题观察资料;非几何真值或专用适配目标" + }, + { + "file": "路口1-真实.png", + "sha256": "aa9601801660ab7874042609c9408ebf33a8488e5f521bc710c65914a914ce9b", + "role": "问题观察资料;非几何真值或专用适配目标" + }, + { + "file": "路口2-生成.png", + "sha256": "0bebf0124f06f92cfec4f14944557dc3d5529b7237317af5a98a4cc1595f18d1", + "role": "问题观察资料;非几何真值或专用适配目标" + }, + { + "file": "路口2-真实.png", + "sha256": "256c8c8f133f26ddd986f7cf9f2772f952a232e6d95cb4fc04e873ecbc36fd1c", + "role": "问题观察资料;非几何真值或专用适配目标" + }, + { + "file": "路口3-生成.png", + "sha256": "ca74fffb839601dbc2a2b2e4ee1e83d06b0cfbb648fa1132d4a73c236905890a", + "role": "问题观察资料;非几何真值或专用适配目标" + }, + { + "file": "路口3-真实.png", + "sha256": "53852c16d62dd52202fc12cdd9c1864c73f76236d06da66cd7bf8485846cbc58", + "role": "问题观察资料;非几何真值或专用适配目标" + } + ], + "registration": "未配准,无统一比例尺;不得据此确定米级尺寸或遮挡处拓扑" +} diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/references/路口1-生成.png b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口1-生成.png new file mode 100644 index 0000000..5e2807c Binary files /dev/null and b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口1-生成.png differ diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/references/路口1-真实.png b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口1-真实.png new file mode 100644 index 0000000..768460d Binary files /dev/null and b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口1-真实.png differ diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/references/路口2-生成.png b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口2-生成.png new file mode 100644 index 0000000..18ab524 Binary files /dev/null and b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口2-生成.png differ diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/references/路口2-真实.png b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口2-真实.png new file mode 100644 index 0000000..782bb65 Binary files /dev/null and b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口2-真实.png differ diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/references/路口3-生成.png b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口3-生成.png new file mode 100644 index 0000000..54e609b Binary files /dev/null and b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口3-生成.png differ diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/references/路口3-真实.png b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口3-真实.png new file mode 100644 index 0000000..de313cb Binary files /dev/null and b/.trellis/tasks/09-08-junction-reference-fidelity/references/路口3-真实.png differ diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/research/current-state.md b/.trellis/tasks/09-08-junction-reference-fidelity/research/current-state.md new file mode 100644 index 0000000..756ed85 --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/research/current-state.md @@ -0,0 +1,20 @@ +# 当前证据与通用问题 + +## 图像观察 + +三组图显示角部设施离散、形态趋同和内部空间组织不足。紫色连接线/节点等属于调试显示,不能据此断定铺装或实际标线错误。路口 2 的 T 形判断、图像与 OSM 对应关系均待核实;禁止将截图观察硬编码成拓扑真值。 + +## 代码入口(规划时) + +- src/compile/complex-junction.js:17 resolveComplexJunctionTopology:以来源和方向归组;独立通道/分隔关系需要显式保留。 +- src/compile/complex-junction.js:150 boundaryParts;约 325 行按夹角与过街框架生成岛体/小斑马线;约 550 行由进口端点排序生成核心;约 603 行生成独立进口矩形。彼此缺少统一边界所有权。 +- src/compile/complex-junction.js:698 classifyJunctionShape:有形态分类,但主要生成规则仍共用包络。 +- src/compile/junction-topology.js:29 structureFromTopology 和 junction-structure.js:已有来源、臂、角部、设施稳定键,但结构主要是输出读模型;不宜直接把展示 schema 当可求解计划。 +- src/compile/direct-edit-solver.js:276 clusterArms 再次归组,可能与几何生成器方向采样/来源判断漂移;规划需统一纯拓扑解析。 +- src/compile/native-road.js:3198 trimLineAtComplexCluster 及所有调用:最近修复只为道路面传 per-road 半径,其他裁切消费者仍可能使用默认半径,需跨图层审计。 +- src/compile/direct-edit-solver.js:17 引入 complexJunctionMetrics,而其所在模块读取参考文件。后端规范要求 resolver 无 IO,应将预加载参数与纯计算分离。 +- workbench/client/src/components/ParameterPanel.tsx 和 App.tsx:复用现有编辑通道;要验证预览先于 Enter 返回、批量修改已有约束、取消与旧响应等场景,避免只证明请求发生。 + +## 设计约束 + +遵守 .trellis/spec/backend/direct-edit-api.md、frontend/direct-edit-client.md;既有实现与规范不一致处需显式记录修正。数据中没有路缘/岛体精确形状时,只能推断或人工校正,不能宣称全自动真实还原。 diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/research/phase-0-audit.md b/.trellis/tasks/09-08-junction-reference-fidelity/research/phase-0-audit.md new file mode 100644 index 0000000..183208f --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/research/phase-0-audit.md @@ -0,0 +1,142 @@ +# Phase 0 Audit: Current Complex-Junction Construction + +Date: 2026-09-08 + +## Scope and evidence + +This audit uses source-independent synthetic fixtures in +`test/junction-build-plan-counterexamples.js`. They deliberately do not contain +the reference image names, OSM object IDs, place names, or fixed real-world +coordinates. The file records the old behaviour as a baseline; phase 1 must +replace its absence assertions with positive `JunctionBuildPlan` assertions. + +## Findings + +### 1. Source identity survives, but grouping and geometry have separate rules + +- `src/compile/native-road.js:2823-2841` groups ordinary junction approaches by + `segmentId`, sums both directions into one width, and selects the first road + for the approach line. +- `src/compile/complex-junction.js:17-89` creates one complex carriageway per + existing approach, then groups them into an arm when heading differs by less + than 20 degrees (`:60-71`). The direct-edit solver repeats that independently + in `src/compile/direct-edit-solver.js:210-297`, including its own line and + tangent sampling (`:254-258`, `:277-296`). +- Stable keys use source identity (`complex-junction.js:47-88` and + `junction-topology.js:3-9`), which is reusable. But an arm becomes the + operative geometry unit: the core uses one envelope per arm + (`complex-junction.js:551-566`), and arm crossings start from the + representative (`:244-247`). That does not provide a distinct EntrySection + or shared curb for each separated carriageway. + +Result: directional/source identity is a good starting point, but no single +pure structure resolver is authoritative for compiler and solver. Do not make +the 20-degree threshold the `JunctionBuildPlan` grouping rule. + +### 2. Distance semantics mix along-line and radial projection + +- Ordinary cutback uses `pointAlongLine()` and a tangent at that cutback + (`native-road.js:2844-2859`, `:2900-2918`), which is the correct local basis + for a bent ordinary approach. +- Complex geometry takes the first-segment heading at the node + (`complex-junction.js:42-44`) and maps a radius to an along-line station by a + scalar projection (`:857-861`). For a curve, that is not the intersection of + the centre-radius boundary and the line. `armEnvelopeAtRadius()` and corner + calculations reuse it (`:862-878`, `:919-934`). +- External road surface has a late per-road radial correction + (`native-road.js:656-699`, `:3215-3236`), but the other consumers do not all + receive that same per-road radius. + +Result: `EntrySection` must name a fixed far section and a station measured on +the source polyline. It may derive a boundary intersection from the actual +polyline, but may not equate that with a centre projection. + +### 3. Existing surfaces have no shared-boundary authority + +- Complex geometry independently emits a core polygon (`complex-junction.js:551-602`), one rectangular polygon per carriageway (`:603-631`), corner fills + (`:450-490`), pedestrian corner bands (`:492-549`), and automatic corner + islands/crossings (`:319-449`). Their overlap is intentional in places; it is + not a referenced seam contract. +- Ordinary boundaries merge parallel approaches into a single face + (`native-road.js:2861-2897`) and then independently round corners + (`:2900-2955`). This avoids one failure mode but loses separate-corridor + semantics. +- `roadRing()` and `sidewalkRing()` only offset independent centre lines + (`native-road.js:3364-3396`); neither receives a shared boundary reference. +- Validation is local: complex pedestrian corners check self-intersection + (`complex-junction.js:519-530`) and the core checks one ring (`:565-566`). + There is no validation of road/core seams, connected required pavement, holes, + or exclusion zones. + +Result: phase 2 needs `BoundaryGraph` ownership before adding more controls. +Core, approach, corner, sidewalk, marking, and facility producers must consume +edge references rather than reconstructing offset rectangles. + +### 4. Layer trimming is inconsistent + +| Consumer | Complex-cluster trim path | Per-carriageway boundary radius | +| --- | --- | --- | +| Road surface | `native-road.js:688-699` | Yes, from `complexApproachBoundaryRadii()` | +| Edge lines | `native-road.js:1098-1120` | No | +| Centre/lane separators | `native-road.js:1171-1192` | No | +| Sidewalk strips | `native-road.js:1850-1855` | No | +| Lane centre lines | `native-road.js:2109-2140` | No | +| Complex carriageway, core, corners, facilities | `complex-junction.js:149-667` | Separate radial/core rules | + +The shared helper falls back to `approachOuterRadius` when no radius is passed +(`native-road.js:3201-3212`). Thus the earlier road-surface continuity repair +does not establish a cross-layer contract. Every listed consumer must eventually +take its termination from the same `EntrySection`/BoundaryGraph plan. + +### 5. Solver purity is currently violated indirectly + +`direct-edit-solver.js:17` imports `complexJunctionMetrics()`. That function +calls `readReferenceCalibration()` (`complex-junction.js:740-757`), which uses +`fs.existsSync` and `fs.readFileSync` (`:723-737`). This conflicts with the +direct-edit resolver purity requirement in `.trellis/spec/backend/direct-edit-api.md`. +Preload reference-derived metrics in the compile/service boundary, then pass +plain values into a pure topology/plan resolver. + +## Minimal counterexamples and required future invariants + +| Fixture | Current baseline | Required plan invariant | +| --- | --- | --- | +| `divided` | Two 10 m-separated, same-heading carriageways become one 20-degree arm. | Two stable carriageways and EntrySections remain distinct; an arm may group them for presentation only. Their boundaries cannot collapse into a single solid approach unless an explicit traversable connection says so. | +| `tee` | Shape is `t-junction`; no closure or boundary object exists. | The blocked side is represented by explicit boundary edges, with no invented through pavement or facility. | +| `offset-unequal` | Label is `offset-cross`; widths remain approach metadata without boundary references. | Each section keeps its own position, tangent, left/right edge, and far anchor; generated rings have shared seams within 1 cm. | +| `curved-short` | Heading samples the first segment and core/radius code uses a projection-derived station; length is below the minimum core radius. | Resolve against actual polyline length and local tangent. Return an object-scoped unsupported diagnostic when a required transition cannot fit; never extend or silently disconnect geometry. | + +## Recommended first implementation slice + +Implement a pure `junction-build-plan` module before touching rendering or UI. +It should receive already-loaded model/config data and return either: + +1. `JunctionBuildPlan` with version, source topology, stable carriageway keys, + `EntrySection`s (source polyline, far station, entry station, tangent, + left/right boundary endpoints), grouping provenance, and diagnostics; or +2. an object-scoped unsupported/ambiguous result with no geometry claim. + +The module must be the sole source for both `resolveComplexJunctionTopology()` +and solver cluster handle anchors. First tests should make all four fixtures +positive: input order and rotation stable, separated carriageways retained, +curved stations bounded by actual length, and T closure explicit. Do not add a +new user control until phase 2 verifies shared seams and all layer consumers use +the plan. + +## Compatibility matrix for the first slice + +| Existing concept | First-slice treatment | +| --- | --- | +| Stable carriageway/arm/corner keys | Preserve source-derived keys; add plan-local keys without coordinate ordering. | +| `cluster-carriageway-width` and cutback | Read existing constraints through an adapter; retain values only when the resolved EntrySection has a feasible range, otherwise mark recheck/stale. | +| Corner radius | Preserve as a compatibility request, but do not derive a final curve until BoundaryGraph feasibility exists. | +| Crossing and stop-line offsets | Keep document readability; mark as dependent on an arm/section plan and do not create a facility from angle alone. | +| Ordinary junction output | No behavior change in the first slice. | +| Reference-file calibration | Move I/O outside the pure resolver and inject resolved metrics. | + +## Checks run + +`node test/junction-build-plan-counterexamples.js` + +This is a planning-stage baseline and is intentionally not added to `npm test` +until phase 1 replaces its current-state assertions with the new plan contract. diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/task.json b/.trellis/tasks/09-08-junction-reference-fidelity/task.json new file mode 100644 index 0000000..c9a1c42 --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/task.json @@ -0,0 +1,26 @@ +{ + "id": "junction-reference-fidelity", + "name": "junction-reference-fidelity", + "title": "复杂路口通用构建:结构约束与连续边界", + "description": "以三组对照暴露的结构表达问题为线索,建立共享拓扑、接入断面与边界的通用复杂路口构建方案;禁止针对样本专用适配。", + "status": "in_progress", + "dev_type": null, + "scope": "junction", + "package": null, + "priority": "P1", + "creator": "dingkang", + "assignee": "dingkang", + "createdAt": "2026-09-08", + "completedAt": null, + "branch": null, + "base_branch": "main", + "worktree_path": null, + "commit": null, + "pr_url": null, + "subtasks": [], + "children": [], + "parent": null, + "relatedFiles": [], + "notes": "用户修正方向:三组图片用于发现问题,不是适配目标。保持 planning,待最新方案审阅后再实施。", + "meta": {} +} \ No newline at end of file diff --git a/package.json b/package.json index af90796..0beb263 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "road-compiler": "bin/road-compiler.js" }, "scripts": { - "test": "node test/index.js && node test/junction-structure.js && node test/junction-projection.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/junction-projection.js && node test/junction-build-plan-counterexamples.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", diff --git a/src/compile/complex-junction.js b/src/compile/complex-junction.js index 91a0f24..727cf2d 100644 --- a/src/compile/complex-junction.js +++ b/src/compile/complex-junction.js @@ -1,7 +1,8 @@ 'use strict'; const fs = require('fs'); -const { topologyIdentity, structureFromTopology } = require('./junction-topology'); +const { structureFromTopology } = require('./junction-topology'); +const { resolveJunctionBuildPlan } = require('./junction-build-plan'); const { convertGeoJson, boundsOf } = require('../reference/gaode'); const metricsCache = new WeakMap(); const CORNER_FILLET_SEGMENTS = 12; @@ -13,81 +14,9 @@ const SIDEWALK_WIDTH_METERS = 2; // past that end and let the two overlap rather than chase an exact seam. const SIDEWALK_CORNER_OVERRUN_METERS = 6; -// Geometry and the durable structure use this single external topology. -function resolveComplexJunctionTopology(model, cluster, helpers) { - const nodeIds = new Set(cluster.nodeIds.map(String)); - const nodes = [...nodeIds] - .sort() - .map((id) => helpers.junctionPlans.get(id)?.node) - .filter(Boolean); - const carriageways = []; - for (const [nodeId, plan] of helpers.junctionPlans) { - if (!nodeIds.has(String(nodeId))) continue; - for (const approach of plan.approaches) { - const roads = approach.roadIds.map((id) => model.roads.find((road) => road.id === id)).filter(Boolean); - // Source topology is authoritative; geometric proximity is only a fallback - // for legacy plans with no source-node metadata. - const sourced = roads.filter((road) => road.sourceNodeIds?.length >= 2); - const internal = sourced.length - ? sourced.every( - (road) => nodeIds.has(String(road.sourceNodeIds[0])) && nodeIds.has(String(road.sourceNodeIds.at(-1))), - ) - : nodes.some((node) => node !== plan.node && helpers.distanceMeters(approach.line.at(-1), node) < 4); - if (internal) continue; - carriageways.push({ - nodeId: String(nodeId), - approach, - plan, - roads, - heading: helpers.headingAtEndpoint(approach.line), - length: helpers.lineLengthMeters(approach.line), - }); - } - } - // Stable source ordering makes heading grouping independent of plan/road order. - carriageways.sort((a, b) => topologyIdentity(a).localeCompare(topologyIdentity(b))); - const duplicateSources = new Set(); - const seenSources = new Set(); - for (const item of carriageways) { - const identity = topologyIdentity(item); - if (seenSources.has(identity)) duplicateSources.add(identity); - seenSources.add(identity); - } - for (let index = carriageways.length - 1; index > 0; index -= 1) - if (topologyIdentity(carriageways[index]) === topologyIdentity(carriageways[index - 1])) - carriageways.splice(index, 1); - const arms = []; - for (const item of carriageways) { - item.ambiguousSource = duplicateSources.has(topologyIdentity(item)); - let arm = arms.find( - (candidate) => Math.abs(normalizeHeading(candidate.representative.heading - item.heading)) < 20, - ); - if (!arm) { - arm = { representative: item, members: [] }; - arms.push(arm); - } - arm.members.push(item); - } - for (const arm of arms) arm.heading = averageHeading(arm.members.map((item) => item.heading)); - for (const item of carriageways) - if (arms.filter((arm) => Math.abs(normalizeHeading(arm.representative.heading - item.heading)) < 20).length > 1) - item.ambiguousSource = true; - arms.sort( - (a, b) => - a.heading - b.heading || topologyIdentity(a.representative).localeCompare(topologyIdentity(b.representative)), - ); - const scope = `cluster:${encodeURIComponent(cluster.id)}`; - for (const arm of arms) { - arm.key = `${scope}:arm:${arm.members.map(topologyIdentity).sort().join('|')}`; - for (const item of arm.members) { - item.key = `${scope}:carriageway:${topologyIdentity(item)}`; - item.armKey = arm.key; - } - } - for (let index = 0; index < arms.length; index += 1) - arms[index].cornerKey = `corner:${arms[index].key}>${arms[(index + 1) % arms.length].key}`; - return { cluster, nodeIds: [...nodeIds].sort(), carriageways, arms }; -} +// Compatibility export for current compiler consumers. The build-plan module is +// pure and is the shared authority for geometry and direct-edit identity. +const resolveComplexJunctionTopology = resolveJunctionBuildPlan; function buildComplexJunctionGeometry(model, cluster, helpers) { const nodeIds = new Set(cluster.nodeIds.map(String)); diff --git a/src/compile/direct-edit-solver.js b/src/compile/direct-edit-solver.js index 76c0406..81d3706 100644 --- a/src/compile/direct-edit-solver.js +++ b/src/compile/direct-edit-solver.js @@ -13,8 +13,8 @@ const { junctionSurfaceId, connectionConnectorId, } = require('./native-ids'); -const { topologyIdentity } = require('./junction-topology'); const { complexJunctionMetrics } = require('./complex-junction'); +const { resolveJunctionBuildPlan } = require('./junction-build-plan'); const RESOLUTION_SCHEMA = 'road-edit-resolution/v1'; const HANDLE_MANIFEST_SCHEMA = 'road-edit-handles/v1'; @@ -211,89 +211,60 @@ function clusterCarriageways(model, junctionData, clusters) { const result = new Map(); for (const cluster of Array.isArray(clusters) ? clusters : []) { if (!cluster?.id || !Array.isArray(cluster.nodeIds)) continue; - const nodeIds = new Set(cluster.nodeIds.map(String)); - const items = []; - for (const nodeId of nodeIds) { - for (const approach of junctionData.approaches.get(nodeId) || []) { - const roads = approach.items.map((item) => item.road); - const sourced = roads.filter((road) => road.sourceNodeIds?.length >= 2); - const internal = - sourced.length && - sourced.every( - (road) => nodeIds.has(String(road.sourceNodeIds[0])) && nodeIds.has(String(road.sourceNodeIds.at(-1))), - ); - if (internal || !roads.length) continue; - const source = { - nodeId: String(nodeId), - approach: { segmentId: approach.segmentId, roadIds: roads.map((road) => road.id) }, - roads, + const plans = new Map(); + for (const nodeId of cluster.nodeIds.map(String)) { + const approaches = (junctionData.approaches.get(nodeId) || []).map((source) => { + const roads = source.items.map((item) => item.road); + const first = source.items[0]; + const line = first?.endpoint.side === 'end' ? [...roads[0].centerline].reverse() : roads[0]?.centerline || []; + return { + ...source, + roadIds: roads.map((road) => road.id), + widthMeters: source.items.reduce((sum, item) => sum + item.road.widthMeters, 0), + line, }; - items.push({ - clusterId: String(cluster.id), - nodeId: String(nodeId), - approach, - roads, - identity: topologyIdentity(source), - key: `cluster:${encodeURIComponent(cluster.id)}:carriageway:${topologyIdentity(source)}`, - sourceNodeIds: [...new Set(roads.flatMap((road) => (road.sourceNodeIds || []).map(String)))].sort(), - sourceRoadIds: roads.map((road) => String(road.id)).sort(), - widthMeters: approach.items.reduce((sum, item) => sum + item.road.widthMeters, 0), - laneCount: roads.reduce((sum, road) => sum + (Number(road.laneCount) || 0), 0), - }); - } + }); + const node = approaches[0]?.line?.[0] || [0, 0]; + plans.set(nodeId, { node, approaches }); } - const seen = new Set(); + const topology = resolveJunctionBuildPlan(model, cluster, { + junctionPlans: plans, + distanceMeters: haversineMeters, + lineLengthMeters: polylineLength, + headingAtEndpoint: (line) => tangentAzimuth(line, 0), + }); + const armByKey = new Map(topology.arms.flatMap((arm) => arm.members.map((member) => [member.key, arm]))); result.set( String(cluster.id), - items.filter((item) => !seen.has(item.key) && seen.add(item.key)), + topology.carriageways.map((item) => ({ + ...item, + clusterId: String(cluster.id), + identity: item.key.split(':carriageway:').at(-1), + sourceNodeIds: [...new Set(item.roads.flatMap((road) => (road.sourceNodeIds || []).map(String)))].sort(), + sourceRoadIds: item.roads.map((road) => String(road.id)).sort(), + widthMeters: item.approach.widthMeters, + laneCount: item.roads.reduce((sum, road) => sum + (Number(road.laneCount) || 0), 0), + arm: armByKey.get(item.key), + })), ); } return result; } function clusterApproachLine(item) { - const road = item.approach.items[0]?.road; - if (!road) return []; - return item.approach.endpoint.side === 'end' ? [...road.centerline].reverse() : road.centerline; + return item.approach.line || []; } -function headingDifference(first, second) { - return Math.abs(((first - second + 540) % 360) - 180); -} - -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 + 360) % 360; -} - -// Mirrors resolveComplexJunctionTopology(): corner identity belongs to adjacent -// external arms, not whichever individual carriageways happened to be listed. function clusterArms(clusterId, items) { - const arms = []; - for (const item of [...items].sort((a, b) => a.identity.localeCompare(b.identity))) { - item.heading = tangentAzimuth(clusterApproachLine(item), 0.05); - let arm = arms.find((candidate) => headingDifference(candidate.representative.heading, item.heading) < 20); - if (!arm) { - arm = { representative: item, members: [] }; - arms.push(arm); - } - arm.members.push(item); + const byArm = new Map(); + for (const item of items) { + if (!item.arm || byArm.has(item.arm.key)) continue; + byArm.set(item.arm.key, { + ...item.arm, + members: item.arm.members.map((member) => items.find((candidate) => candidate.key === member.key) || member), + }); } - for (const arm of arms) { - arm.heading = averageHeading(arm.members.map((member) => member.heading)); - arm.key = `cluster:${encodeURIComponent(clusterId)}:arm:${arm.members - .map((member) => member.identity) - .sort() - .join('|')}`; - } - arms.sort((a, b) => a.heading - b.heading || a.representative.identity.localeCompare(b.representative.identity)); - return arms; + return [...byArm.values()]; } function numericValue(constraint, key, fallback) { diff --git a/src/compile/junction-build-plan.js b/src/compile/junction-build-plan.js new file mode 100644 index 0000000..8ef6a7f --- /dev/null +++ b/src/compile/junction-build-plan.js @@ -0,0 +1,151 @@ +'use strict'; + +const { topologyIdentity } = require('./junction-topology'); + +const MIN_ENTRY_SECTION_METERS = 12; + +function normalizeHeading(value) { + return ((((value + 180) % 360) + 360) % 360) - 180; +} + +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 + 360) % 360; +} + +function tangentAt(line, station, length, helpers) { + if (!Array.isArray(line) || line.length < 2 || !Number.isFinite(length) || length <= 0) return null; + let walked = 0; + for (let index = 1; index < line.length; index += 1) { + const segmentLength = helpers.distanceMeters(line[index - 1], line[index]); + if (station <= walked + segmentLength || index === line.length - 1) + return helpers.headingAtEndpoint([line[index - 1], line[index]]); + walked += segmentLength; + } + return null; +} + +function offsetCoordinate(point, heading, meters) { + if (!point || !Number.isFinite(heading)) return null; + const radians = (heading * Math.PI) / 180; + const lonMeters = 111320 * Math.cos((point[1] * Math.PI) / 180); + return [ + point[0] + (Math.sin(radians) * meters) / Math.max(lonMeters, 1e-9), + point[1] + (Math.cos(radians) * meters) / 111320, + ]; +} + +function boundaryAt(point, tangent, widthMeters) { + const halfWidth = Math.max(0, Number(widthMeters) || 0) / 2; + return { + left: offsetCoordinate(point, tangent - 90, halfWidth), + right: offsetCoordinate(point, tangent + 90, halfWidth), + }; +} + +function entrySectionFor(item, helpers) { + const length = item.length; + const line = item.approach.line; + const nearTangent = tangentAt(line, 0, length, helpers); + const farTangent = tangentAt(line, length, length, helpers); + const feasible = Number.isFinite(length) && length >= MIN_ENTRY_SECTION_METERS; + return { + carriagewayKey: item.key, + sourceLine: line, + nearStationMeters: 0, + farStationMeters: length, + entryStationMeters: 0, + nearTangent, + farTangent, + boundaryEndpoints: { + near: boundaryAt(line?.[0] || null, nearTangent, item.approach.widthMeters), + far: boundaryAt(line?.at(-1) || null, farTangent, item.approach.widthMeters), + }, + feasibility: feasible ? 'supported' : 'short-approach', + ...(feasible ? {} : { reason: 'entry-section-too-short' }), + }; +} + +// This plan is deliberately limited to source topology and source-polyline +// sections. It is shared by geometry and edit identity, while later work can +// add computed shared boundaries without making either layer guess arm order. +function resolveJunctionBuildPlan(model, cluster, helpers) { + const nodeIds = new Set(cluster.nodeIds.map(String)); + const nodes = [...nodeIds] + .sort() + .map((id) => helpers.junctionPlans.get(id)?.node) + .filter(Boolean); + const carriageways = []; + for (const [nodeId, plan] of helpers.junctionPlans) { + if (!nodeIds.has(String(nodeId))) continue; + for (const approach of plan.approaches || []) { + const roads = approach.roadIds.map((id) => model.roads.find((road) => road.id === id)).filter(Boolean); + const sourced = roads.filter((road) => road.sourceNodeIds?.length >= 2); + const internal = sourced.length + ? sourced.every( + (road) => nodeIds.has(String(road.sourceNodeIds[0])) && nodeIds.has(String(road.sourceNodeIds.at(-1))), + ) + : nodes.some((node) => node !== plan.node && helpers.distanceMeters(approach.line.at(-1), node) < 4); + if (internal) continue; + carriageways.push({ + nodeId: String(nodeId), + approach, + plan, + roads, + heading: helpers.headingAtEndpoint(approach.line), + length: helpers.lineLengthMeters(approach.line), + }); + } + } + carriageways.sort((a, b) => topologyIdentity(a).localeCompare(topologyIdentity(b))); + const duplicateSources = new Set(); + const seenSources = new Set(); + for (const item of carriageways) { + const identity = topologyIdentity(item); + if (seenSources.has(identity)) duplicateSources.add(identity); + seenSources.add(identity); + } + for (let index = carriageways.length - 1; index > 0; index -= 1) + if (topologyIdentity(carriageways[index]) === topologyIdentity(carriageways[index - 1])) + carriageways.splice(index, 1); + const arms = []; + for (const item of carriageways) { + item.ambiguousSource = duplicateSources.has(topologyIdentity(item)); + let arm = arms.find( + (candidate) => Math.abs(normalizeHeading(candidate.representative.heading - item.heading)) < 20, + ); + if (!arm) { + arm = { representative: item, members: [] }; + arms.push(arm); + } + arm.members.push(item); + } + for (const arm of arms) arm.heading = averageHeading(arm.members.map((item) => item.heading)); + for (const item of carriageways) + if (arms.filter((arm) => Math.abs(normalizeHeading(arm.representative.heading - item.heading)) < 20).length > 1) + item.ambiguousSource = true; + arms.sort( + (a, b) => + a.heading - b.heading || topologyIdentity(a.representative).localeCompare(topologyIdentity(b.representative)), + ); + const scope = `cluster:${encodeURIComponent(cluster.id)}`; + for (const arm of arms) { + arm.key = `${scope}:arm:${arm.members.map(topologyIdentity).sort().join('|')}`; + for (const item of arm.members) { + item.key = `${scope}:carriageway:${topologyIdentity(item)}`; + item.armKey = arm.key; + item.entrySection = entrySectionFor(item, helpers); + } + } + for (let index = 0; index < arms.length; index += 1) + arms[index].cornerKey = `corner:${arms[index].key}>${arms[(index + 1) % arms.length].key}`; + return { schema: 'junction-build-plan/v1', cluster, nodeIds: [...nodeIds].sort(), carriageways, arms }; +} + +module.exports = { MIN_ENTRY_SECTION_METERS, resolveJunctionBuildPlan }; diff --git a/test/junction-build-plan-counterexamples.js b/test/junction-build-plan-counterexamples.js new file mode 100644 index 0000000..c72cd84 --- /dev/null +++ b/test/junction-build-plan-counterexamples.js @@ -0,0 +1,123 @@ +'use strict'; + +// Source-independent counterexamples for the JunctionBuildPlan contract. + +const assert = require('assert/strict'); +const { resolveJunctionBuildPlan } = require('../src/compile/junction-build-plan'); +const { classifyJunctionShape } = require('../src/compile/complex-junction'); + +const metersPerDegree = 111320; +const point = (east, north) => [east / metersPerDegree, north / metersPerDegree]; + +function heading(line) { + const [from, to] = line; + return (Math.atan2(to[0] - from[0], to[1] - from[1]) * 180) / Math.PI; +} + +function distance(first, second) { + return Math.hypot((first[0] - second[0]) * metersPerDegree, (first[1] - second[1]) * metersPerDegree); +} + +function length(line) { + return line.slice(1).reduce((total, item, index) => total + distance(line[index], item), 0); +} + +function fixture(name, entries) { + const nodeId = `${name}:node`; + const approaches = entries.map((entry, index) => ({ + segmentId: `${name}:segment:${index + 1}`, + roadIds: [`${name}:road:${index + 1}`], + widthMeters: entry.widthMeters, + line: entry.line, + })); + return { + model: { + roads: entries.map((entry, index) => ({ + id: `${name}:road:${index + 1}`, + segmentId: `${name}:segment:${index + 1}`, + sourceNodeIds: [nodeId, `${name}:outer:${index + 1}`], + laneCount: 1, + })), + }, + cluster: { id: name, nodeIds: [nodeId, `${name}:internal`] }, + helpers: { + junctionPlans: new Map([ + [nodeId, { node: point(0, 0), approaches }], + [`${name}:internal`, { node: point(1, 1), approaches: [] }], + ]), + headingAtEndpoint: heading, + lineLengthMeters: length, + distanceMeters: distance, + }, + }; +} + +function topology(name, entries) { + const input = fixture(name, entries); + return { ...input, topology: resolveJunctionBuildPlan(input.model, input.cluster, input.helpers) }; +} + +// A divided approach keeps independently addressable entry sections even when +// both carriageways share an arm. +const divided = topology('divided', [ + { widthMeters: 4, line: [point(-5, 0), point(-5, 50)] }, + { widthMeters: 5, line: [point(5, 0), point(5, 50)] }, + { widthMeters: 7, line: [point(0, 0), point(50, 0)] }, + { widthMeters: 7, line: [point(0, 0), point(0, -50)] }, +]); +assert.equal(divided.topology.carriageways.length, 4); +assert.equal(divided.topology.arms.length, 3); +assert.equal(divided.topology.arms.find((arm) => arm.members.length === 2)?.members.length, 2); +assert.equal(new Set(divided.topology.carriageways.map((item) => item.entrySection.carriagewayKey)).size, 4); +assert.ok( + divided.topology.carriageways.every( + (item) => item.entrySection.boundaryEndpoints.near.left[0] !== item.entrySection.boundaryEndpoints.near.right[0], + ), +); + +// A T junction has explicit, source-stable entry sections. Closure edges are a +// later BoundaryGraph concern and must not be fabricated by topology parsing. +const tee = topology('tee', [ + { widthMeters: 8, line: [point(0, 0), point(0, 45)] }, + { widthMeters: 4, line: [point(0, 0), point(45, 0)] }, + { widthMeters: 4, line: [point(0, 0), point(-45, 0)] }, +]); +assert.equal(tee.topology.arms.length, 3); +assert.equal(classifyJunctionShape(tee.topology.arms, point(0, 0), tee.helpers).kind, 't-junction'); +assert.ok(tee.topology.carriageways.every((item) => item.entrySection.feasibility === 'supported')); + +// Offset and unequal-width approaches preserve individual source sections and +// local section tangents rather than a single arm envelope. +const offsetUnequal = topology('offset-unequal', [ + { widthMeters: 12, line: [point(-8, 0), point(-8, 48)] }, + { widthMeters: 4, line: [point(0, 18), point(48, 18)] }, + { widthMeters: 6, line: [point(9, 0), point(9, -28)] }, + { widthMeters: 9, line: [point(0, -12), point(-48, -12)] }, +]); +assert.equal(offsetUnequal.topology.arms.length, 4); +assert.equal( + classifyJunctionShape(offsetUnequal.topology.arms, point(0, 0), offsetUnequal.helpers).kind, + 'offset-cross', +); +assert.deepEqual( + offsetUnequal.topology.carriageways.map((item) => item.entrySection.farStationMeters), + offsetUnequal.topology.carriageways.map((item) => item.length), +); + +// A short curved approach reports bounded feasibility while retaining distinct +// local tangents at each end of its source polyline. +const curvedShort = topology('curved-short', [ + { widthMeters: 6, line: [point(0, 0), point(0, 3), point(7, 7)] }, + { widthMeters: 6, line: [point(0, 0), point(35, 0)] }, + { widthMeters: 6, line: [point(0, 0), point(0, -35)] }, +]); +assert.equal(curvedShort.topology.carriageways[0].heading, 0, 'current heading samples only the first segment'); +assert.ok(curvedShort.topology.carriageways[0].length < 12, 'fixture is shorter than the minimum complex core radius'); +assert.equal(curvedShort.topology.carriageways[0].entrySection.feasibility, 'short-approach'); +assert.equal(curvedShort.topology.carriageways[0].entrySection.reason, 'entry-section-too-short'); +assert.notEqual( + curvedShort.topology.carriageways[0].entrySection.nearTangent, + curvedShort.topology.carriageways[0].entrySection.farTangent, +); + +console.log('junction build-plan counterexample tests passed');