diff --git a/.trellis/spec/backend/direct-edit-api.md b/.trellis/spec/backend/direct-edit-api.md index 2b3f445..b56733d 100644 --- a/.trellis/spec/backend/direct-edit-api.md +++ b/.trellis/spec/backend/direct-edit-api.md @@ -452,10 +452,15 @@ constraints and legacy constraints containing both offsets must be evaluated with both effective offsets present. Boundary closure reports `sharedSeamErrors` per carriageway and -`maxSharedSeamErrorMeters` as the maximum endpoint distance in local metres -between the core ring edge and its BoundaryGraph `inner` edge. Missing or -non-contiguous edges remain `Infinity`; the value is not a boolean adjacency -placeholder. Explicit transition stations are clamped to the source polyline +`maxSharedSeamErrorMeters` against the authoritative BoundaryGraph inner +section. For a simple closure the section is an exact ring edge. For overlapping +multi-carriageway entries, the center is the union of center-to-entry cells; +a complete inner seam may then lie inside that union. Such a seam is accepted +only after splitting it at every polygon boundary intersection and checking +all resulting intervals (0.1 mm numerical boundary tolerance), then measuring +its endpoint mismatch against its authoritative graph edge. Missing or +uncovered seams remain `Infinity`; valid overlap must not discard carriageways +or falsify the connected-entry count. Explicit transition stations are clamped to the source polyline range for legacy/direct compiler inputs and marked `insufficient-source-length` when the requested length cannot fit. The solver rejects such values before they can be saved. @@ -472,3 +477,23 @@ and inner section edges, preserving the fixed source width when the inner width changes. Unsupported, invalid or excluded transitions do not publish preview lanes or their derived markings. This contract does not yet replace the separate corner sidewalk overrun geometry or validate all short-road suppression paths. + + +## Complex cluster vehicle paths + +Cluster connectors trace enabled lane movements through internal roads to +external lane ports. Use breadth-first traversal per incoming lane; avoid +cycling through internal lanes. Preserve source movement IDs and existing lane +restrictions. A published whole-cluster path references visible approach lanes +and their travel-oriented endpoints (outbound preview polylines are stored in +reverse travel order). Do not retain per-node connector fragments as if they +were whole-cluster trajectories. + +Curves preserve endpoint tangents and use adaptive sampling (2 cm chord error, +2 m maximum segment length, 1 degree tangent/chord error). These are geometric +sampling tolerances, not proof of curvature continuity or vehicle turning +radius. Published cluster paths must be non-self-intersecting, fully inside the +published pavement region and avoid island edges/interiors. Failed candidate +paths remain diagnostic/deferred movements, never fake safe curves. Current +implementation explores a bounded set of cubic control lengths; it is not a +complete motion planner and does not prove vehicle swept-envelope clearance. diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/implement.md b/.trellis/tasks/09-08-junction-reference-fidelity/implement.md index 1de7809..4d6acb3 100644 --- a/.trellis/tasks/09-08-junction-reference-fidelity/implement.md +++ b/.trellis/tasks/09-08-junction-reference-fidelity/implement.md @@ -168,3 +168,13 @@ complex-junction.js / native-road.js:构建与全部消费者;direct-edit-so 实际最新导入工作区 import-fE8XI7 使用四节点、coreRadius=21;此前验证脚本硬编码五节点、24,漏掉真实失败。已复现两个 contact-crosses-corner 导致两岛省略。四臂过街现在在发布前共同检查相邻接触短边;必要时对称缩短所有过街跨度,以完整白条节距进行裁减,保留白条长度/宽度/间隔。找不到满足最小过街跨度的方案时不应用试探裁减,保留不可行诊断。未改保存配置或用户编辑。 实际配置现在发布四岛、四绿色六边形,各六个唯一点,面积约 19.49–28.70m²。新增真实 OSM 四节点 21m 回归检查四角对象、六点及岛体引用。references/four-islands-coordinated.png 为编译几何整图(黄色停止线用于辨识),非浏览器截图。接触交集约 4.2e-5m²、中心铺装缺口仍待解决;不能声称严格共享边界或整体验收完成。前序“六点数量通过即完整接触完成”的说法不成立。 + +## 2026-09-14 中心铺装与集群车辆轨迹(未提交) + +按 research/core-and-trajectories-audit.md 实施。中心闭合改为每条有效车行道保留完整断面,按断面而非散点排序;多车行道内断面交叠产生自交时,对中心与边界形成的局部铺装单元做区域并集,不使用凸包,也不删除某条车行道。内接缝可成为并集内部线段,需逐边界交点拆分验证整段覆盖,随后与权威 BoundaryGraph 断面测量位置误差。原“必须缺失 core”断言改为连续区域验收;已有 T/五/六臂和排除区域反例仍通过。实际四节点、21m 配置生成中心面,8/8 入口接通,接缝误差0,四岛和绿色区域保持。 + +车辆轨迹先统一为端点切向 cubic 与自适应采样,随后实际叠加图证明原节点 connector 仍是局部碎片。因此继续增加集群级拼接:在原有允许的 lane movement 图上逐入口 BFS,追溯内部车道到外部出口,保留来源 movement IDs,遵守车道方向和默认目标车道对应关系。端口引用实际可见 approach lane(出口预览线按行驶方向反转)。用有限控制柄候选求曲线;检查整条发布折线的自交、与安全岛边相交、是否逐段落在真实铺装区域内。替代原四节点碎片;不可行候选明确诊断 deferred-region-conflict,不伪造可行轨迹。尚未提供车辆扫掠包络或曲率连续性保证。 + +实测与测试:中心8个入口全连通;集群28条发布完整路径,8条区域冲突暂缓。28条全部匹配可见车道端点,0条因端点缺失而跳过;最大端点切向误差0.9898度。合成T/四臂最大误差0.9807度。新 test/connector-trajectories.js 纳入 npm test。references/core-and-trajectories.png/svg 为实际配置编译几何叠加图(蓝线轨迹,黄色停止线),非浏览器截图。 + +npm test 中代码、投影、边界反例、设施、编辑与工作台导入检查通过;最后 test/fixtures.js 快照仍失败(当前 OSM 与旧基线不同,且本次轨迹几何也会改变输出),未刷新基线,因此不得写为全量测试通过。格式与diff检查通过。8条暂缓路径、车辆尺度转弯半径/扫掠、全图层接缝及已有岛/斑马线约4.2e-5m²微小面积交集尚未关闭。未提交、未归档。 diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/references/core-and-trajectories.png b/.trellis/tasks/09-08-junction-reference-fidelity/references/core-and-trajectories.png new file mode 100644 index 0000000..f0c2634 Binary files /dev/null and b/.trellis/tasks/09-08-junction-reference-fidelity/references/core-and-trajectories.png differ diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/references/core-and-trajectories.svg b/.trellis/tasks/09-08-junction-reference-fidelity/references/core-and-trajectories.svg new file mode 100644 index 0000000..8211c5f --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/references/core-and-trajectories.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/research/core-and-trajectories-audit.md b/.trellis/tasks/09-08-junction-reference-fidelity/research/core-and-trajectories-audit.md new file mode 100644 index 0000000..1683ddc --- /dev/null +++ b/.trellis/tasks/09-08-junction-reference-fidelity/research/core-and-trajectories-audit.md @@ -0,0 +1,23 @@ +# Center pavement and vehicle trajectory audit — 2026-09-14 + +Scope: investigation and implementation plan only; no implementation changes. + +Reproduced with workbench-data/import-fE8XI7/source.osm and its active area-config.snapshot.json: four nodes (8005332807, 8024512135, 8024512145, 8024512147), core radius 21 m. Do not substitute the older five-node/24 m script. + +## Confirmed findings + +- Actual compilation publishes no complex-core. Diagnostic: complex-junction-core-closure-unsupported / core-closure-invalid. Eight complex-approach surfaces and four complex-corner-fillet surfaces remain. +- complex-junction.js constructs each corner fill as [...curve, center, curve[0]]. With the core absent, these center-directed fans explain the triangular gaps. This is not evidence of a triangulation-rendering defect. +- buildCoreClosure in junction-boundary-graph.js selects one section per arm when arms contain multiple carriageways, discarding other entry seams from the candidate core. It then sorts endpoints by angle and rejects zero edges, unpaired edges, insufficient area or self-intersection with the same generic reason. Which individual predicate fails must be instrumented before changing construction. +- compileConnectors in native-road.js works on enabled model.connections by node. Four-segment nodes use a quadratic curve through an endpoint node as control; other through movements use a straight chord; other turns use cubic curves with lane endpoint tangents. Fixed sampling is 12 segments. Existing tangent-based construction therefore does exist, but is not used consistently. +- validateConnectorContainment checks samples against one junction exterior ring and skips kind=cluster; it does not establish swept vehicle clearance from island holes or authoritative complex pavement. No claim yet that a particular observed connector joins the wrong lane; that requires source/destination tracing and measured evidence. + +## Implementation sequence + +1. Establish reproducible metrics for this saved configuration: all entry section IDs, core failure predicate, pavement connected components and unexplained gap regions; each movement's source/destination lane and endpoint/tangent errors. Export pavement and trajectory overlays separately and together. Preserve current four islands as a regression invariant. +2. Repair core closure using every valid carriageway entry seam and explicit connecting boundary edges. Reuse BoundaryGraph and polygon-clipping; validate a simple closed boundary, union with approach/turn pavement, and subtract justified non-drivable islands/exclusions. Crosswalks are markings on pavement, not holes. Do not force-fill a convex hull or disable closure validation. +3. Trace cluster movements across internal source connections to external lane ports, preserving turn restrictions and source provenance. Determine whether current node-level connectors duplicate or omit these movements before replacing them. Lane endpoints/tangents and pavement must consume the same entry sections. +4. Use lane endpoint positions and tangent directions for all connector shapes, including offset through movements. Begin with existing cubic machinery; constrain/control curvature and adapt sampling by geometric error. A cubic with tangent continuity does not automatically give curvature continuity across road joins. Add curvature limits or curvature-transition construction where required. Validate the full path and, with an explicit vehicle envelope, swept clearance against final drivable region and islands. Crossings between different traffic streams are not automatically errors. +5. Acceptance: all expected external entries connect to continuous pavement; no unexplained holes; four islands/green polygons retained; movement IDs and permitted lane pairings correct; endpoint error <= 1 cm, measured endpoint tangent error <= 1 degree; no self-return/cusp or island penetration. Establish vehicle-specific minimum radius before declaring trajectories physically drivable. Include T/Y/oblique/multi-carriageway and short-source counterexamples. + +Deliver as one reviewed change across pavement and trajectories after real-workbench visual verification. Do not archive parent task from local facility tests. Remaining uncertainty: exact closure rejection predicate, abnormal connector IDs, whether those displayed lines include lane separators as well as connectors, and necessary vehicle curvature assumptions. diff --git a/package.json b/package.json index 5e5bf76..474f513 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/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/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/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/junction-boundary-graph.js b/src/compile/junction-boundary-graph.js index 3914e58..0145731 100644 --- a/src/compile/junction-boundary-graph.js +++ b/src/compile/junction-boundary-graph.js @@ -1,5 +1,7 @@ 'use strict'; +const { union } = require('./junction-polygon-ops'); + const { solvePavedRegion } = require('./junction-region-solver'); const { stationAtDistanceFrom } = require('./junction-build-plan'); @@ -219,41 +221,70 @@ function coordinateDistanceMeters(first, second) { // A central paved region is safe to infer only when every arm has exactly one // source carriageway. Its shared entry seams are the sections' `inner` edges; // every remaining edge is an explicit closure between adjacent arms. -function buildCoreClosure(topology, graph, center) { - let coreSections = graph.sections; - if (topology.arms.some((arm) => arm.members.length !== 1)) { - if (topology.arms.length < 4 || topology.arms.length > 6) - return { status: 'unsupported', reason: 'parallel-carriageway-closure-unresolved' }; - coreSections = topology.arms.map( - (arm) => - graph.sections - .filter((section) => section.armKey === arm.key && section.ringStatus === 'supported') - .sort((a, b) => { - const distance = (section) => { - const x = (section.inner.left[0] + section.inner.right[0]) / 2 - center[0]; - const y = (section.inner.left[1] + section.inner.right[1]) / 2 - center[1]; - return x * x + y * y; - }; - return distance(a) - distance(b) || a.carriagewayKey.localeCompare(b.carriagewayKey); - })[0], - ); - if (coreSections.some((section) => !section)) - return { status: 'unsupported', reason: 'parallel-carriageway-closure-unresolved' }; +// Split at boundary crossings to check complete seam intervals, not samples. +function segmentCoveredByRing(start, end, ring) { + const scale = Math.cos((start[1] * Math.PI) / 180); + const xy = (p) => [(p[0] - start[0]) * 111320 * scale, (p[1] - start[1]) * 111320]; + const d = xy(end), + boundary = ring.map(xy); + const cross = (a, b) => a[0] * b[1] - a[1] * b[0]; + const parameters = [0, 1]; + for (let i = 1; i < boundary.length; i++) { + const a = boundary[i - 1], + b = boundary[i], + edge = [b[0] - a[0], b[1] - a[1]]; + const denominator = cross(d, edge); + if (Math.abs(denominator) < 1e-10) continue; + const t = cross(a, edge) / denominator, + u = cross(a, d) / denominator; + if (t > 0 && t < 1 && u >= 0 && u <= 1) parameters.push(t); } - if (coreSections.length < 3 || coreSections.length > 6) + parameters.sort((a, b) => a - b); + const covered = (t) => { + const p = d.map((v) => v * t); + if (pointInRing(p, boundary)) return true; + return boundary.slice(1).some((b, i) => { + const a = boundary[i], + dx = b[0] - a[0], + dy = b[1] - a[1]; + const length = dx * dx + dy * dy; + const q = length ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / length)) : 0; + return Math.hypot(p[0] - a[0] - q * dx, p[1] - a[1] - q * dy) <= 0.0001; + }); + }; + return parameters.every(covered) && parameters.slice(1).every((t, i) => covered((t + parameters[i]) / 2)); +} + +function buildCoreClosure(topology, graph, center) { + const coreSections = graph.sections.filter((section) => section.ringStatus === 'supported'); + if (topology.arms.length < 3 || topology.arms.length > 6) return { status: 'unsupported', reason: 'unsupported-arm-count' }; - const points = coreSections - .flatMap((section) => [ - { point: section.inner.left, edgeRef: section.edgeRefs.inner }, - { point: section.inner.right, edgeRef: section.edgeRefs.inner }, - ]) - .filter((item) => item.point?.every(Number.isFinite)) - .sort( - (first, second) => - Math.atan2(first.point[1] - center[1], first.point[0] - center[0]) - - Math.atan2(second.point[1] - center[1], second.point[0] - center[0]), - ); - const ring = [...points.map((item) => item.point), points[0]?.point].filter(Boolean); + if (topology.arms.length === 3 && topology.arms.some((arm) => arm.members.length !== 1)) + return { status: 'unsupported', reason: 'parallel-carriageway-closure-unresolved' }; + // Sort whole entry edges, never their individual endpoints. Each valid + // carriageway contributes its full inner seam, including divided arms. + const angle = (point) => Math.atan2(point[1] - center[1], point[0] - center[0]); + const points = [...coreSections] + .sort((a, b) => { + const middle = (section) => section.inner.left.map((v, i) => (v + section.inner.right[i]) / 2); + return angle(middle(a)) - angle(middle(b)); + }) + .flatMap((section) => { + const ends = [section.inner.left, section.inner.right]; + const delta = Math.atan2(Math.sin(angle(ends[1]) - angle(ends[0])), Math.cos(angle(ends[1]) - angle(ends[0]))); + if (delta < 0) ends.reverse(); + return ends.map((point) => ({ point, edgeRef: section.edgeRefs.inner })); + }); + let ring = [...points.map((item) => item.point), points[0]?.point].filter(Boolean); + let mergedEntryCells = false; + if (topology.arms.some((arm) => arm.members.length > 1) && ring.length >= 7 && ringSelfIntersects(ring)) { + const cells = ring.slice(1).map((point, index) => [[center, ring[index], point, center]]); + const region = union(...cells); + if (region.length === 1 && region[0].length === 1) { + ring = region[0][0]; + mergedEntryCells = true; + } + } const pavedRegion = solvePavedRegion( ring, graph.exclusionRegions.filter((region) => !region.isHole).map((region) => region.ring), @@ -298,9 +329,10 @@ function buildCoreClosure(topology, graph, center) { rightIndex >= 0 && (Math.abs(leftIndex - rightIndex) === 1 || Math.abs(leftIndex - rightIndex) === ring.length - 2); const edge = graph.edges.find((candidate) => candidate.key === section.edgeRefs.inner); - if (!contiguous || !edge) return { carriagewayKey: section.carriagewayKey, errorMeters: Infinity }; - const ringLeft = ring[leftIndex]; - const ringRight = ring[rightIndex]; + const covered = mergedEntryCells && segmentCoveredByRing(section.inner.left, section.inner.right, ring); + if ((!contiguous && !covered) || !edge) return { carriagewayKey: section.carriagewayKey, errorMeters: Infinity }; + const ringLeft = contiguous ? ring[leftIndex] : section.inner.left; + const ringRight = contiguous ? ring[rightIndex] : section.inner.right; const forward = Math.max( coordinateDistanceMeters(ringLeft, edge.from), coordinateDistanceMeters(ringRight, edge.to), @@ -328,4 +360,4 @@ function buildCoreClosure(topology, graph, center) { }; } -module.exports = { buildJunctionBoundaryGraph, buildCoreClosure, ringsOverlap }; +module.exports = { buildJunctionBoundaryGraph, buildCoreClosure, ringsOverlap, segmentCoveredByRing }; diff --git a/src/compile/native-road.js b/src/compile/native-road.js index cdbf41c..2cbc950 100644 --- a/src/compile/native-road.js +++ b/src/compile/native-road.js @@ -1,6 +1,8 @@ 'use strict'; const fs = require('fs'); +const { union: unionPolygons } = require('./junction-polygon-ops'); +const { segmentCoveredByRing } = require('./junction-boundary-graph'); const path = require('path'); const { arrowRingsAt, normalizeManeuver } = require('./turn-lane-arrows'); const { @@ -860,7 +862,16 @@ function compileGeometry(model, overrides = { overrides: [] }, options = {}) { // Complex crosswalks are generated from native approach tangents; do not // synthesize side strips that can be mistaken for crosswalks. sidewalks.push(...generatedComplexSidewalks); - const connectorResult = compileConnectors(model, lanes, diagnostics, overrides, junctionPlans); + const connectorResult = compileConnectors( + model, + lanes, + diagnostics, + overrides, + junctionPlans, + options, + generatedComplexSidewalks, + features, + ); const junctionFeatures = compileJunctionSurfaces( model, junctionPlans, @@ -2488,7 +2499,7 @@ function cubicTurnCurve(start, end, startHeading, endHeading, radius, turn, cent return points.every((point) => point.every(Number.isFinite)) ? points : [start, center, end]; } -function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans) { +function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans, options, islands, pavementFeatures) { const features = []; const movements = []; for (const connection of model.connections.filter((item) => item.enabled)) { @@ -2518,14 +2529,10 @@ function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans) if ((!laneAllowsTurn(fromRoad, index, turn) && override?.enabled !== true) || override?.enabled === false) continue; const from = defaultFromLane.coordinates.at(-1); - const to = defaultToLane.coordinates[0]; const plan = junctionPlans.get(connection.nodeId); - // Cross intersections retain the earlier center-node curve while T junctions - // use lane tangents so their through movement does not bow toward the stem. - const coordinates = - plan?.segmentIds.size === 4 - ? quadraticCurve(from, endpointCoordinate(model, connection.fromEndpointId), to, 12) - : connectorCurve(defaultFromLane.coordinates, defaultToLane.coordinates, turn); + // Every maneuver shares the actual lane endpoint tangents, including + // four-arm nodes and laterally offset through movements. + const coordinates = connectorCurve(defaultFromLane.coordinates, defaultToLane.coordinates); const length = lineLengthMeters(coordinates); const id = `movement:${connection.id}:${defaultFromLane.id}->${defaultToLane.id}`; const provenance = override ? `override:${override.id}` : connection.provenance; @@ -2584,6 +2591,184 @@ function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans) movements.push(movement); } } + for (const cluster of options.junctionTemplates?.enabled ? options.junctionTemplates.clusters || [] : []) { + if (cluster.template !== 'complex-junction-v1') continue; + const nodes = new Set(cluster.nodeIds.map(String)); + const roads = new Map(model.roads.map((road) => [road.id, road])); + const internal = (road) => nodes.has(String(road.sourceNodeIds[0])) && nodes.has(String(road.sourceNodeIds.at(-1))); + const local = movements.filter((m) => nodes.has(String(m.nodeId))); + const outgoing = new Map(); + for (const movement of local) { + if (!outgoing.has(movement.fromLaneId)) outgoing.set(movement.fromLaneId, []); + outgoing.get(movement.fromLaneId).push(movement); + } + const routes = new Map(); + for (const startLane of outgoing.keys()) { + const initial = outgoing.get(startLane); + if (internal(roads.get(initial[0].fromRoadId))) continue; + const queue = initial.map((movement) => [movement]); + const seen = new Set([startLane]); + for (let cursor = 0; cursor < queue.length; cursor++) { + const path = queue[cursor], + last = path.at(-1), + road = roads.get(last.toRoadId); + if (!internal(road)) { + if (path[0].fromRoadId !== last.toRoadId) { + const key = startLane + '>' + last.toLaneId; + if (!routes.has(key)) routes.set(key, path); + } + continue; + } + if (seen.has(last.toLaneId)) continue; + seen.add(last.toLaneId); + for (const next of outgoing.get(last.toLaneId) || []) queue.push([...path, next]); + } + } + const publishedLane = (roadId, laneIdValue, arriving) => { + const original = (lanes.byRoadId.get(roadId) || []).find((lane) => lane.id === laneIdValue); + if (!original) return null; + const previews = lanes.features.filter( + (f) => + f.properties.cluster_id === cluster.id && + f.properties.cluster_preview && + f.properties.road_id === roadId && + f.properties.lane_index === original.index && + f.properties.incoming === arriving, + ); + const feature = + previews.length === 1 ? previews[0] : lanes.features.find((f) => f.properties.native_id === laneIdValue); + if (!feature) return null; + const coordinates = + previews.length === 1 && !arriving ? [...feature.geometry.coordinates].reverse() : feature.geometry.coordinates; + return { id: feature.properties.native_id, coordinates }; + }; + const replacements = [], + replacementMovements = []; + const pavement = unionPolygons( + ...pavementFeatures.filter((f) => f.properties.cluster_id === cluster.id).map((f) => f.geometry.coordinates), + ); + + for (const route of routes.values()) { + const first = route[0], + last = route.at(-1); + const from = publishedLane(first.fromRoadId, first.fromLaneId, true); + const to = publishedLane(last.toRoadId, last.toLaneId, false); + if (!from || !to) continue; + const turn = connectionTurn(roads.get(first.fromRoadId), roads.get(last.toRoadId)); + const sourceLanes = lanes.byRoadId.get(first.fromRoadId) || []; + const targetLanes = lanes.byRoadId.get(last.toRoadId) || []; + const sourceIndex = sourceLanes.findIndex((lane) => lane.id === first.fromLaneId); + const targetIndex = targetLanes.findIndex((lane) => lane.id === last.toLaneId); + const explicit = laneOverride(overrides, first.fromLaneId, last.toLaneId); + if (explicit?.enabled === false) continue; + if ( + explicit?.enabled !== true && + (turn === 'uturn' || + !laneAllowsTurn(roads.get(first.fromRoadId), sourceIndex, turn) || + targetIndex !== targetLaneIndex(turn, sourceIndex, sourceLanes.length, targetLanes.length)) + ) + continue; + + const a = from.coordinates.at(-1), + b = to.coordinates[0]; + const incoming = headingDegrees(from.coordinates.at(-2), a), + leaving = headingDegrees(b, to.coordinates[1]); + const masks = islands.filter((f) => f.properties.kind === 'island' && f.properties.cluster_id === cluster.id); + const chord = distanceMeters(a, b); + let coordinates = null; + const handlePairs = [0.42, 0.65, 0.85, 1.1, 0.2, 0.1].flatMap((first) => + [0.42, 0.65, 0.85, 1.1, 0.2, 0.1].map((second) => [first, second]), + ); + for (const [firstFactor, secondFactor] of handlePairs) { + const candidate = cubicBezier( + a, + offsetCoordinate(a, incoming, chord * firstFactor), + offsetCoordinate(b, leaving + 180, chord * secondFactor), + b, + ); + const islandConflict = masks.some((f) => { + const ring = f.geometry.coordinates[0]; + return ( + candidate.some((p) => pointInPolygon(p, ring)) || + candidate + .slice(1) + .some((b, i) => ring.slice(1).some((d, j) => segmentsIntersect(candidate[i], b, ring[j], d))) + ); + }); + if (islandConflict || hasSelfIntersection(candidate, false)) continue; + if ( + !candidate + .slice(1) + .every((end, index) => + pavement.some( + (polygon) => + segmentCoveredByRing(candidate[index], end, polygon[0]) && + !polygon + .slice(1) + .some( + (hole) => + pointInPolygon(end, hole) || + hole.slice(1).some((p, j) => segmentsIntersect(candidate[index], end, hole[j], p)), + ), + ), + ) + ) + continue; + coordinates = candidate; + break; + } + const id = `movement:cluster:${cluster.id}:${first.fromLaneId}->${last.toLaneId}`; + const movement = { + ...first, + id, + connectorId: id, + connectionId: id, + toRoadId: last.toRoadId, + fromLaneId: from.id, + toLaneId: to.id, + turn, + geometryPublished: Boolean(coordinates), + geometryStatus: coordinates ? 'connector' : 'deferred-region-conflict', + sourceMovementIds: route.map((m) => m.id), + }; + replacementMovements.push(movement); + if (!coordinates) { + diagnostics.push( + diagnostic( + 'warning', + id, + [...nodes], + 'cluster-connector-region-conflict', + '完整转向路径无法满足铺装区域或安全岛避让约束,未发布。', + a, + ), + ); + continue; + } + replacements.push({ + type: 'Feature', + properties: { + native_id: id, + movement_id: id, + connection_id: id, + node_id: first.nodeId, + cluster_id: cluster.id, + cluster_internal: false, + from_lane_id: from.id, + to_lane_id: to.id, + turn, + source_movement_ids: route.map((m) => m.id), + provenance: 'native-road-cluster-lane-path/v1', + }, + geometry: { type: 'LineString', coordinates }, + }); + } + for (let i = features.length - 1; i >= 0; i--) + if (nodes.has(String(features[i].properties.node_id))) features.splice(i, 1); + for (let i = movements.length - 1; i >= 0; i--) if (nodes.has(String(movements[i].nodeId))) movements.splice(i, 1); + features.push(...replacements); + movements.push(...replacementMovements); + } return { features, movements }; } /** The maneuver an override sets for a lane, or `undefined` when none applies. */ @@ -2653,10 +2838,9 @@ function targetLaneIndex(turn, sourceIndex, sourceCount, targetCount) { Math.round((sourceIndex / Math.max(1, sourceCount - 1)) * Math.max(0, targetCount - 1)), ); } -function connectorCurve(incoming, outgoing, turn) { +function connectorCurve(incoming, outgoing) { const start = incoming.at(-1); const end = outgoing[0]; - if (turn === 'through') return lineCurve(start, end, 12); const incomingHeading = headingDegrees(incoming.at(-2), start); const outgoingHeading = headingDegrees(end, outgoing[1]); const chord = distanceMeters(start, end); @@ -2672,9 +2856,11 @@ function connectorCurve(incoming, outgoing, turn) { tangentIntersection && tangentIntersection.outgoing >= 0 ? Math.min(tangentIntersection.outgoing, Math.min(8, Math.max(0.75, outgoingSpan * 2.4))) / 3 : fallbackDistance; - const firstControl = offsetCoordinate(start, incomingHeading, firstDistance); - const secondControl = offsetCoordinate(end, outgoingHeading + 180, secondDistance); - return cubicBezier(start, firstControl, secondControl, end, 12); + // A zero handle loses the endpoint tangent even when its ray intersection + // is valid. Keep a positive handle before adaptive sampling. + const firstControl = offsetCoordinate(start, incomingHeading, Math.max(0.1, firstDistance)); + const secondControl = offsetCoordinate(end, outgoingHeading + 180, Math.max(0.1, secondDistance)); + return cubicBezier(start, firstControl, secondControl, end); } function intersectTangentRays(start, end, incomingHeading, outgoingHeading) { @@ -2689,20 +2875,46 @@ function intersectTangentRays(start, end, incomingHeading, outgoingHeading) { }; } -function lineCurve(start, end, segments) { - return Array.from({ length: segments + 1 }, (_, index) => interpolate(start, end, index / segments)); -} - -function cubicBezier(a, firstControl, secondControl, b, segments) { - const result = []; - for (let index = 0; index <= segments; index += 1) { - const t = index / segments; - const u = 1 - t; - result.push([ - u ** 3 * a[0] + 3 * u * u * t * firstControl[0] + 3 * u * t * t * secondControl[0] + t ** 3 * b[0], - u ** 3 * a[1] + 3 * u * u * t * firstControl[1] + 3 * u * t * t * secondControl[1] + t ** 3 * b[1], - ]); - } +// Subdivide in local metres until chord/tangent error is small. A fixed +// sample count hides tight bends and creates visible kinks at lane joins. +function cubicBezier(a, firstControl, secondControl, b) { + const result = [a]; + const angle = (u, v) => { + const denominator = Math.hypot(...u) * Math.hypot(...v); + if (denominator < 1e-12) return 0; + return Math.acos(Math.max(-1, Math.min(1, (u[0] * v[0] + u[1] * v[1]) / denominator))); + }; + const visit = (p, q, r, s, depth) => { + const chord = project(s, p); + const first = project(q, p); + const last = project(s, r); + const length = Math.hypot(...chord); + const flatness = + length > 1e-9 + ? Math.max( + ...[q, r].map((point) => { + const v = project(point, p); + return Math.abs(v[0] * chord[1] - v[1] * chord[0]) / length; + }), + ) + : Math.max(distanceMeters(p, q), distanceMeters(p, r)); + if ( + depth >= 14 || + (length <= 2 && flatness <= 0.02 && angle(first, chord) <= Math.PI / 180 && angle(chord, last) <= Math.PI / 180) + ) { + result.push(s); + return; + } + const pq = interpolate(p, q, 0.5); + const qr = interpolate(q, r, 0.5); + const rs = interpolate(r, s, 0.5); + const left = interpolate(pq, qr, 0.5); + const right = interpolate(qr, rs, 0.5); + const middle = interpolate(left, right, 0.5); + visit(p, pq, left, middle, depth + 1); + visit(middle, right, rs, s, depth + 1); + }; + visit(a, firstControl, secondControl, b, 0); return result; } @@ -3487,10 +3699,10 @@ function distanceMeters(a, b) { const dy = (b[1] - a[1]) * 111320; return Math.hypot(dx, dy); } -function hasSelfIntersection(ring) { +function hasSelfIntersection(ring, closed = true) { for (let first = 0; first < ring.length - 1; first += 1) for (let second = first + 1; second < ring.length - 1; second += 1) { - if (Math.abs(first - second) <= 1 || (first === 0 && second === ring.length - 2)) continue; + if (Math.abs(first - second) <= 1 || (closed && first === 0 && second === ring.length - 2)) continue; if (segmentsIntersect(ring[first], ring[first + 1], ring[second], ring[second + 1])) return true; } return false; diff --git a/test/connector-trajectories.js b/test/connector-trajectories.js new file mode 100644 index 0000000..c556ea0 --- /dev/null +++ b/test/connector-trajectories.js @@ -0,0 +1,122 @@ +'use strict'; +const assert = require('assert/strict'); +const fs = require('fs'); +const { compileRoadModel, compileGeometry } = require('../src/compile/native-road'); + +function vector(a, b) { + return [(b[0] - a[0]) * Math.cos((a[1] * Math.PI) / 180), b[1] - a[1]]; +} +function angle(a, b) { + return ( + (Math.acos(Math.max(-1, Math.min(1, (a[0] * b[0] + a[1] * b[1]) / (Math.hypot(...a) * Math.hypot(...b))))) * 180) / + Math.PI + ); +} +function check(geometry, label, clipped = false) { + const lanes = new Map( + geometry.laneCenterlines.features.map((f) => [ + f.properties.native_id, + f.properties.cluster_preview && f.properties.incoming === false + ? [...f.geometry.coordinates].reverse() + : f.geometry.coordinates, + ]), + ); + let maximum = 0; + let checked = 0; + let unavailable = 0; + for (const feature of geometry.connectors.features) { + const line = feature.geometry.coordinates; + const incoming = lanes.get(feature.properties.from_lane_id); + const outgoing = lanes.get(feature.properties.to_lane_id); + if (clipped && (!incoming || !outgoing)) { + unavailable += 1; + continue; + } + if ( + clipped && + (JSON.stringify(line[0]) !== JSON.stringify(incoming.at(-1)) || + JSON.stringify(line.at(-1)) !== JSON.stringify(outgoing[0])) + ) { + unavailable += 1; + continue; + } + checked += 1; + assert.deepEqual(line[0], incoming.at(-1)); + assert.deepEqual(line.at(-1), outgoing[0]); + const error = Math.max( + angle(vector(incoming.at(-2), incoming.at(-1)), vector(line[0], line[1])), + angle(vector(outgoing[0], outgoing[1]), vector(line.at(-2), line.at(-1))), + ); + maximum = Math.max(maximum, error); + assert.ok(error <= 1.01, `${label} ${feature.properties.native_id}: tangent error ${error}`); + assert.ok(line.every((p) => p.every(Number.isFinite))); + } + assert.ok(checked > 0); + console.log( + `${label}: ${checked} checked, ${unavailable} clipped/missing endpoint references, max tangent error ${maximum.toFixed(4)} deg`, + ); +} +// Oblique four-arm and T nodes exercise the former quadratic and straight +// special cases using public compilation, not a duplicate curve implementation. +for (const count of [3, 4]) { + const coords = [ + [0, 0], + [0, 0.001], + [0.001, 0.0001], + [0, -0.001], + [-0.001, 0], + ]; + const osm = `${coords.map((p, i) => ``).join('')}${coords + .slice(1, count + 1) + .map( + (_, i) => + ``, + ) + .join('')}`; + check(compileGeometry(compileRoadModel(osm, { overrides: [] }), { overrides: [] }), `${count}-arm`); +} +if (process.argv[2]) { + const root = process.argv[2]; + const overrides = JSON.parse(fs.readFileSync(`${root}/native-road-overrides.json`)); + const options = JSON.parse(fs.readFileSync(`${root}/active/area-config.snapshot.json`)).options; + check( + compileGeometry(compileRoadModel(fs.readFileSync(`${root}/source.osm`, 'utf8'), overrides), overrides, options), + 'saved workbench', + true, + ); +} + +// The four-node configuration must publish whole cluster movements whose +// endpoints refer to visible approach lanes, not invisible internal OSM lanes. +{ + const model = compileRoadModel( + fs.readFileSync(require('path').join(__dirname, '../inputs/osm/枫树二路.osm'), 'utf8'), + { overrides: [] }, + ); + const geometry = compileGeometry( + model, + { overrides: [] }, + { + edgeLines: false, + junctionTemplates: { + enabled: true, + clusters: [ + { + id: 'cluster-path-regression', + template: 'complex-junction-v1', + coreRadiusMeters: 21, + nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147'], + }, + ], + }, + }, + ); + const paths = geometry.connectors.features.filter((f) => f.properties.cluster_id === 'cluster-path-regression'); + assert.ok(paths.length > 0); + check({ ...geometry, connectors: { ...geometry.connectors, features: paths } }, 'whole cluster'); + for (const path of paths) { + assert.equal(path.properties.cluster_internal, false); + assert.ok(path.properties.source_movement_ids.length > 0); + assert.ok(!path.properties.from_lane_id.includes('undefined')); + } +} diff --git a/test/index.js b/test/index.js index 1b7da90..0df76a0 100644 --- a/test/index.js +++ b/test/index.js @@ -113,17 +113,11 @@ const complexGeometry = compiler.nativeRoad.compileGeometry( const complexCore = complexGeometry.roadSurface.features.find( (feature) => feature.properties?.kind === 'complex-core' && feature.properties?.cluster_id === 'fixture-five-arm', ); -// This fixture contains multiple source carriageways within several arms. The -// compiler must retain those independent sections rather than filling their -// unknown interstitial areas with a synthetic core. -assert.equal(complexCore, undefined); -assert.ok( - complexGeometry.diagnostics.some( - (item) => - item.rule === 'complex-junction-core-closure-unsupported' && - item.subjectId === 'junction-cluster:fixture-five-arm', - ), -); +// Every valid carriageway must participate in the continuous center region. +assert.ok(complexCore); +assert.equal(complexCore.properties.required_pavement_connected, true); +assert.equal(complexCore.properties.shared_seam_error_m, 0); +assert.equal(complexCore.properties.core_ring_self_intersects, false); assert.ok(complexGeometry.roadSurface.features.some((feature) => feature.properties?.kind === 'complex-approach')); const compiledApproach = complexGeometry.roadSurface.features.find( (feature) => feature.properties?.kind === 'complex-approach', diff --git a/test/junction-build-plan-counterexamples.js b/test/junction-build-plan-counterexamples.js index 440060d..bd660a6 100644 --- a/test/junction-build-plan-counterexamples.js +++ b/test/junction-build-plan-counterexamples.js @@ -692,3 +692,22 @@ const editedCurvedGraph = buildJunctionBoundaryGraph( assert.deepEqual(editedCurvedGraph.sections[0].outer, originalCurvedGraph.sections[0].outer); assert.ok(Math.abs(editedCurvedGraph.sections[0].transitionMeters - 16) < 1e-9); assert.notDeepEqual(editedCurvedGraph.sections[0].inner, originalCurvedGraph.sections[0].inner); + +// An internal seam must be covered along its full length, including between +// sample positions. The narrow notch below would escape quarter-point probes. +{ + const { segmentCoveredByRing } = require('../src/compile/junction-boundary-graph'); + const notch = [ + [0, 0], + [1, 0], + [1, 1], + [0.15, 1], + [0.15, 0.4], + [0.1, 0.4], + [0.1, 1], + [0, 1], + [0, 0], + ]; + assert.equal(segmentCoveredByRing([0, 0.5], [1, 0.5], notch), false); + assert.equal(segmentCoveredByRing([0, 0], [1, 0], notch), true); +} diff --git a/test/junction-facility-composition.js b/test/junction-facility-composition.js index 6a4ab5e..ef8a459 100644 --- a/test/junction-facility-composition.js +++ b/test/junction-facility-composition.js @@ -155,6 +155,12 @@ assert.equal(new Set(solvedContacts.greenRing.slice(0, -1).map((p) => p.join(',' ); const outer = geometry.sidewalkSurface.features.filter((f) => f.properties.kind === 'island'); const green = geometry.sidewalkSurface.features.filter((f) => f.properties.kind === 'island-green'); + const core = geometry.roadSurface.features.find((f) => f.properties.kind === 'complex-core'); + assert.ok(core, 'saved four-node 21m configuration must publish center pavement'); + assert.equal(core.properties.connected_entry_count, 8); + assert.equal(core.properties.required_pavement_connected, true); + assert.equal(core.properties.shared_seam_error_m, 0); + assert.equal(core.properties.core_ring_self_intersects, false); assert.equal(outer.length, 4, 'all four corners must publish islands'); assert.equal(green.length, 4, 'all four islands must publish green contact polygons'); assert.equal(new Set(green.map((f) => f.properties.corner_key)).size, 4);