refactor: split complex junction stages

This commit is contained in:
que01 committed 2026-09-16 17:45:57 +08:00
1 parent 1679d1bfc1
commit 55888e8d91
8 files changed
+1644 -1121

No files matched your search

@@ -54,3 +54,25 @@ Wrong: move a stripe until it touches an arc at one point and declare success
because overlap area is zero. Correct: share the complete crossing short-edge
segment with the island boundary, then derive the green polygon from those
same endpoints and verify non-contact curves separately.
## Generator stage ordering
`src/compile/complex-junction.js` keeps `buildComplexJunctionGeometry` as the
orchestrator. Its private stages own approach selection/stop lines, arm crossing
layout, corner composition, crossing displacement, pavement assembly and
publication. Keep the existing local solvers in their geometry modules.
- `buildArmCrossings` writes the arm's `crosswalkFrame`, `crosswalkRadius` and
evidence before `buildCornerCompositions` consumes them.
- Corner contact solutions collect both endpoint offsets for each shared arm.
Call `applyCrossingDisplacements` once after all corners, before pavement
assembly. It updates stripes, stop lines and the full swept crossing regions;
moving only the visible stripes leaves pavement gaps.
- Preserve the current failure dependency during structural refactors: a failed
corner contact solve also skips that corner's sidewalk. Changing this is a
behavior change requiring a dedicated regression, not a helper extraction.
- Core `approach_headings` uses `arm.representative.heading`, not `arm.heading`:
the representative heading and grouped arm heading can differ.
- Validate refactors against complete generator results, including feature
order, metadata and diagnostics. Run `test/junction-island-offset.js` explicitly
alongside `npm test`; it covers the shared-endpoint displacement path.
@@ -1,5 +1,13 @@
# 实施计划与阶段出口
## 2026-09-16 生成器结构重构
用户确认梳理 `buildComplexJunctionGeometry`,已将千行入口缩为约 159 行阶段编排,按进口、过街、角部、位移、铺装和发布拆出私有函数。45 次完整新旧返回值深比较一致;几何/编辑/API/导入回归、191 项客户端单测、类型检查和 12 项 E2E 通过。`npm test` 最后仍有重构前已复现的 fixture 快照差异;全仓格式检查仍有未修改文件的既有问题,本次源文件格式通过。独立复核未发现行为变化。详细边界、可重跑差分脚本及证据见 `research/geometry-refactor.md`。未提交,父任务其余验收保持原状态。
后续评估已先迁出无状态局部几何工具至 `complex-junction-geometry.js`;`complex-junction.js` 从 1685 行降至 1472 行。设施阶段应以整体迁移的方式进入单独模块,避免将共享 arm frame 和角部失败依赖拆散。完整评估与本轮针对性验证见同一 research 文档。
该模块拆分已完成:`complex-junction-surfaces.js` 承担核心/进口/铺装,`complex-junction-facilities.js` 承担进口停止线、过街、角部和位移;入口文件现为 367 行。保持公开导出与构建顺序,差分和针对性回归通过;仍需按任务既有质量门在提交前重跑全量检查。
当前为 in_progress;任务已收敛为分阶段推进。第一个新阶段是“复杂路口区域模型”:先统一中心通行区、角部可行域和安全岛边界,再恢复设施与视觉验收。实验性固定安全岛修改已保存至 `/private/tmp/junction-island-experiment.patch`,不作为正式方案。
## 0. 契约与最小反例
@@ -0,0 +1,47 @@
'use strict';
// Run from the repo root with node --require <this file> test/<suite>.js.
// This one-off comparison retains the pre-refactor generator as its oracle.
const assert = require('node:assert/strict');
const path = require('node:path');
const Module = require('node:module');
const { execFileSync } = require('node:child_process');
const root = path.resolve(__dirname, '../../../..');
const filename = path.join(root, 'src/compile/complex-junction.js');
const baseline = new Module(filename, module);
baseline.filename = filename;
baseline.paths = Module._nodeModulePaths(path.dirname(filename));
baseline._compile(
execFileSync('git', ['show', '1679d1b:src/compile/complex-junction.js'], { cwd: root, encoding: 'utf8' }),
filename,
);
const current = require(filename);
const build = current.buildComplexJunctionGeometry;
let comparisons = 0;
const shapes = new Set();
const diagnostics = new Set();
let shifted = 0;
let crossingEdits = 0;
current.buildComplexJunctionGeometry = function (model, cluster, helpers) {
const values = {};
const functions = {};
for (const [key, value] of Object.entries(helpers)) {
(typeof value === 'function' ? functions : values)[key] = value;
}
const copied = structuredClone({ model, cluster, values });
const expected = baseline.exports.buildComplexJunctionGeometry(copied.model, copied.cluster, {
...copied.values,
...functions,
});
const actual = build(model, cluster, helpers);
assert.deepStrictEqual(actual, expected, `generator output changed for ${cluster.id}`);
comparisons++;
shapes.add(actual.shape?.kind || 'early-return');
for (const item of actual.diagnostics) diagnostics.add(item.rule);
if (helpers.clusterIslandOffsetMeters) shifted++;
if (helpers.clusterCrossingControls?.size) crossingEdits++;
return actual;
};
process.on('exit', () => {
console.log('Generator parity:', { comparisons, shapes: [...shapes], shifted, crossingEdits, diagnostics: [...diagnostics] });
});
@@ -0,0 +1,47 @@
# 复杂路口生成器结构整理
用户于 2026-09-16 确认实施代码审阅提出的结构重构。
## 边界与设计
现有 buildComplexJunctionGeometry 超过千行,阶段之间依赖 arm 上的可变字段和共享集合。本轮将入口整理为可读的阶段编排,抽取进口、过街布局、角部组合、位移联动和结果装配;角部组合继续拆出有明确职责的局部函数。阶段输入输出显式传递,避免通用可变 context。
实现范围为 src/compile/complex-junction.js 及必要的同目录内部模块。保留公开导出、运算顺序、坐标、Feature 顺序、ID、诊断和失败路径。清理本轮相关的无用变量、导入和过时注释;诊断内容不在此次改变。复用既有几何求解模块,不引入框架或新的配置机制,不改 UI 或几何算法。
## 验证计划
1. 保存重构前生成器,对实际测试输入逐次深比较完整返回值。
2. 运行现有几何、编辑及完整 npm test 回归;既有失败需与基线区分,禁止刷新快照隐藏差异。
3. 运行格式、客户端类型及 git diff --check;审阅阶段依赖和失败路径。
4. 记录重构结果与验证证据,不关闭父任务的其他未完成验收。
## 实现与差分结果
生产修改仅位于 `src/compile/complex-junction.js`。主函数从 1021 行缩为约 159 行;同文件私有函数分别承担阶段编排及单个设施构建,最大新函数约 115 行。没有新增公开导出或依赖。删除两个无用导入和两项无用坐标计算;保留历史诊断并注明其兼容性原因。
差分工具最初位于 `/private/tmp/complex-junction-refactor-parity.cjs`,现保留在同目录 `geometry-refactor-parity.cjs`。用 Node Module 加载基线提交 `1679d1b` 的生成器,将每次实际调用的输入复制后交给旧函数,再对完整返回值执行 `assert.deepStrictEqual`。45 次比较全部一致:主测试流 41 次,单独 island-offset 测试 4 次(其中 3 次非零外移)。覆盖正交、偏置十字、T 形、多臂和节点不足返回,以及无效断面、短过渡、排除区、岛体求解失败、核心闭合失败、过街编辑等诊断路径。
检查结果:
- `npm test` 的代码、几何、编辑、API、工作台导入检查通过,最后 `test/fixtures.js` 失败。该快照差异在重构前已单独复现,重构后输出哈希相同;未刷新基线。
- `node --require /private/tmp/complex-junction-refactor-parity.cjs test/junction-island-offset.js` 通过。
- 客户端类型检查、191 项客户端单测通过。
- 本次源文件格式和 `git diff --check` 通过。全仓 `format:check` 在未修改的 `junction-facility-composition.js` 失败;对 HEAD 原文运行 Prettier 同样失败。
- `npm run test:e2e` 通过:生产构建及 12 项浏览器回归,包含三臂复杂路口控制编辑、保存和刷新。保留既有 bundle 大小提示。
- 独立代码复核通过,无新增修复:核对角部失败依赖、Feature/诊断顺序、共享过街位移和停止线联动。
本轮未提交,父任务保持进行中。历史“角部设施已省略”诊断与实际默认生成行为的矛盾保留为单独行为修正事项。
## 后续模块边界评估(2026-09-16)
阶段编排已经从入口函数中抽出,但 `complex-junction.js` 仍保留了局部米制计算、道路臂包络、圆角相交、人行道接缝和环验证等无状态几何代码,导致文件仍有 1685 行。它们不依赖构建阶段、Feature 发布或诊断顺序,已迁入 `complex-junction-geometry.js`,入口文件降为 1472 行。
下一条清晰边界是 `complex-junction-facilities.js`:进口/停止线、道路臂过街、角部组合和位移联动共用可变的 arm frame,必须作为一个整体迁移;把它们逐个拆成更多小模块会掩盖阶段依赖。核心/入口面/统一铺装可作为之后的 `complex-junction-surfaces.js`。建议在当前功能任务结束并提交现有工作后,以完整输出差分为保护再实施这两次迁移,避免在仍频繁调整的设施算法中扩大冲突面。
本次几何模块提取保持输出:两组设施测试与 island-offset 测试通过,差分脚本对 5 次复杂路口完整返回值比较一致;铺装、落面和拓扑反例测试通过,变更文件 Prettier 与 `git diff --check` 通过。
随后迁出 `complex-junction-surfaces.js`:核心面、进口面与统一铺装区域现在作为一组独立的 surface 阶段。入口文件从 1473 行降至 1301 行。铺装、落面、拓扑反例与 island-offset 回归通过;差分脚本对 9 次复杂路口完整返回值比较一致,包含无效入口、T 形、圆角降级及非零岛体外移。
最后迁出 `complex-junction-facilities.js`:进口与停止线、道路臂过街、角部组合及共享位移共同拥有 arm frame 的写入、消费和最终应用,因此保持为单个模块。入口文件从 1301 行降至 367 行,只保留拓扑/指标/边界图、阶段编排和发布。迁移中补回形态分类所需的 `normalizeHeading` 与 `positiveHeadingDelta` 纯几何导入。设施组合、岛体外移、铺装、落面和拓扑反例通过;差分脚本对 5 次完整返回值比较一致,包含非零岛体外移。
完整 `npm test` 通过全部代码、几何、编辑 API 和工作台导入检查,最后仍在已有 `test/fixtures.js` 快照差异退出;该差异与重构前记录一致,未更新基线。首次完整回归暴露 facilities 模块遗漏 `ringsOverlap` 依赖,已补入并重跑。客户端类型检查和变更文件格式检查通过。
+955
View File
@@ -0,0 +1,955 @@
'use strict';
const { COMPLEX_CROSSWALK_DEPTH_METERS } = require('./junction-metrics');
const { ringsOverlap } = require('./junction-boundary-graph');
const { rectangle } = require('./junction-pavement-region');
const { orthogonalCrossingHeadings, stripeLayout, solveIslandContacts } = require('./junction-facility-composition');
const { radialShift } = require('./junction-island-offset');
const {
armCarriesSidewalk,
armEnvelopeAtRadius,
bearing,
cornerEdgeAt,
crossingEvidenceForArm,
directionalProjectionMeters,
exteriorSidewalkSeam,
midpoint,
normalizeHeading,
offsetPolylineAwayFromCenter,
polygonCenter,
positiveHeadingDelta,
pointOnCarriagewayRadius,
projectionRatio,
quadraticCurve,
rayIntersection,
ringSelfIntersects,
signedLateralMeters,
} = require('./complex-junction-geometry');
const CORNER_FILLET_SEGMENTS = 12;
const SIDEWALK_WIDTH_METERS = 2;
function planArmCrossings(model, arms, center, coreRadius, crossingControls, helpers) {
const crossingPlans = new Map(
arms.map((arm) => {
const inferredRadius = Math.max(1, coreRadius * 0.68);
const inferredEnvelope = armEnvelopeAtRadius(arm, inferredRadius, center, helpers);
const evidence = inferredEnvelope
? crossingEvidenceForArm(model, arm, inferredEnvelope.center, helpers)
: { kind: 'unknown-no-crossing-source', crossingNodeIds: [], crossing: null };
return [
arm.key,
{
evidence,
baseRadius: evidence.crossing ? helpers.distanceMeters(center, evidence.crossing.coordinate) : inferredRadius,
},
];
}),
);
const armCrosswalkRadiusFor = (arm) =>
Math.max(
1,
(crossingPlans.get(arm.key)?.baseRadius || coreRadius * 0.68) +
(crossingControls.get(`crossing:${arm.key}`)?.crosswalkInsetMeters || 0),
);
return { crossingPlans, armCrosswalkRadiusFor };
}
function buildApproachSurfacesAndStops({
model,
cluster,
helpers,
center,
arms,
carriageways,
boundaryGraph,
crossingControls,
crossingPlans,
armCrosswalkRadiusFor,
}) {
const boundaryParts = [];
const stopLines = [];
const transitionDiagnostics = [];
for (const section of boundaryGraph.sections) {
const item = carriageways.find((candidate) => candidate.key === section.carriagewayKey);
if (!item) continue;
// The approach plan owns the editable handoff distance. It shifts only this
// carriageway's outer transition, leaving neighboring arms untouched. A
// collapsed handoff is reported and omitted rather than publishing a
// zero-area trapezoid that downstream layers could mistake for pavement.
if (section.ringStatus !== 'supported') {
transitionDiagnostics.push(
helpers.diagnostic(
'warning',
`carriageway:${item.key}`,
item.approach.roadIds.map(String),
'complex-junction-entry-ring-invalid',
'该进口边界无法形成有效道路面,已省略退化或自交几何。',
section.inner.point,
),
);
continue;
}
if (section.exclusionStatus !== 'clear') {
transitionDiagnostics.push(
helpers.diagnostic(
'warning',
`carriageway:${item.key}`,
item.approach.roadIds.map(String),
'complex-junction-entry-overlaps-known-region',
'该进口过渡区域侵入已知排除区域,已省略该进口面以保留来源区域。',
section.inner.point,
),
);
continue;
}
if (section.transitionStatus !== 'supported') {
transitionDiagnostics.push(
helpers.diagnostic(
'warning',
`carriageway:${item.key}`,
item.approach.roadIds.map(String),
'complex-junction-entry-transition-unsupported',
'该进口在当前来源长度内无法形成外部断面到核心断面的连续过渡,已省略退化进口面。',
section.inner.point,
),
);
continue;
}
boundaryParts.push({ item, section });
const stopLine = buildApproachStopLine({
model,
cluster,
helpers,
center,
item,
arms,
crossingControls,
crossingPlans,
armCrosswalkRadiusFor,
});
if (stopLine) stopLines.push(stopLine);
}
return { boundaryParts, stopLines, diagnostics: transitionDiagnostics };
}
function buildApproachStopLine({
model,
cluster,
helpers,
center,
item,
arms,
crossingControls,
crossingPlans,
armCrosswalkRadiusFor,
}) {
const outerHalf = item.approach.widthMeters / 2;
const incomingRoad = item.approach.roadIds
.map((roadId) => model.roads.find((road) => road.id === roadId))
.find((road) => String(road?.sourceNodeIds.at(-1)) === String(item.nodeId));
if (incomingRoad) {
// Offset is clear space beyond the relocated crossing outer edge; include
// half the stop bar thickness so the minimum offset cannot cut into it.
const arm = arms.find((candidate) => candidate.members.includes(item));
const crossingKey = `crossing:${arm.key}`;
const crossingRadius = armCrosswalkRadiusFor(arm);
const stopOffset = crossingControls.get(crossingKey)?.stopLineOffsetMeters || 3;
const stopHeading = orthogonalCrossingHeadings(arms.map((candidate) => candidate.heading))[arms.indexOf(arm)];
const envelope = armEnvelopeAtRadius(arm, crossingRadius, center, helpers);
const basePoint = pointOnCarriagewayRadius(item, center, crossingRadius, helpers);
const lateral = signedLateralMeters(envelope.center, basePoint, stopHeading);
const stopCenter = helpers.offsetCoordinate(
helpers.offsetCoordinate(envelope.center, stopHeading + 90, lateral),
stopHeading,
COMPLEX_CROSSWALK_DEPTH_METERS * 1.5 + 0.24 + stopOffset,
);
const crossingEvidence = crossingPlans.get(arm.key)?.evidence || {
kind: 'unknown-no-crossing-source',
crossingNodeIds: [],
};
const ring = [
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, stopHeading + 90, -outerHalf), stopHeading, -0.24),
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, stopHeading + 90, outerHalf), stopHeading, -0.24),
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, stopHeading + 90, outerHalf), stopHeading, 0.24),
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, stopHeading + 90, -outerHalf), stopHeading, 0.24),
helpers.offsetCoordinate(helpers.offsetCoordinate(stopCenter, stopHeading + 90, -outerHalf), stopHeading, -0.24),
];
return {
type: 'Feature',
properties: {
native_id: `complex-stop-line:${cluster.id}:${item.approach.segmentId}`,
object_key: `stop-line:${item.key}`,
crossing_key: crossingKey,
arm_key: item.armKey,
carriageway_key: item.key,
cluster_id: cluster.id,
kind: 'complex-stop-line',
road_id: incomingRoad.id,
node_id: item.nodeId,
direction: item.heading,
facility_evidence: crossingEvidence.kind,
...(crossingEvidence.crossingNodeIds.length
? { source_crossing_node_ids: crossingEvidence.crossingNodeIds }
: {}),
provenance: 'native-road-complex-junction-stop-line/v1',
},
geometry: { type: 'Polygon', coordinates: [ring] },
};
}
}
function buildArmCrossings({
arms,
center,
cluster,
helpers,
publishedCarriageways,
crossingPlans,
armCrosswalkRadiusFor,
}) {
const transitionDiagnostics = [];
// Frames belong to these local topology arms. Complete their layout before
// corner contacts consume the endpoints; displacement is applied only later.
// The four support lines provide a common corner frame, but each long
// crossing remains clipped to its OSM-derived road envelope. Corner islands
// fill the remaining frame gaps; crossings must never do that job.
for (const arm of arms) {
if (!arm.members.every((item) => publishedCarriageways.has(item.key))) {
transitionDiagnostics.push(
helpers.diagnostic(
'warning',
`crossing:${arm.key}`,
arm.members.flatMap((item) => item.approach.roadIds.map(String)),
'complex-junction-crosswalk-pavement-unavailable',
'该过街缺少完整可发布的车行道过渡面,已省略标线,避免跨越无效进口。',
center,
),
);
continue;
}
const armCrosswalkRadius = armCrosswalkRadiusFor(arm);
arm.crosswalkRadius = armCrosswalkRadius;
const envelope = armEnvelopeAtRadius(arm, armCrosswalkRadius, center, helpers);
if (!envelope) continue;
const evidence = crossingPlans.get(arm.key)?.evidence || {
kind: 'unknown-no-crossing-source',
crossingNodeIds: [],
};
if (evidence.kind !== 'source-crossing-node') {
transitionDiagnostics.push(
helpers.diagnostic(
'info',
`crossing:${arm.key}`,
arm.members.flatMap((item) => item.approach.roadIds.map(String)),
'complex-junction-crossing-source-missing',
'该进口未找到匹配的 OSM 过街节点,过街来源未知,按复杂路口默认生成斑马线。',
envelope.center,
),
);
}
arm.crosswalkFrame = {
center: envelope.center,
groupDepth: COMPLEX_CROSSWALK_DEPTH_METERS,
supportHeading: normalizeHeading(arm.heading + 90),
envelopeWidthMeters: envelope.widthMeters,
};
arm.crosswalkEvidence = evidence;
}
const crossingHeadings = orthogonalCrossingHeadings(arms.map((arm) => arm.heading));
arms.forEach((arm, index) => {
if (arm.crosswalkFrame) {
arm.crosswalkFrame.heading = crossingHeadings[index];
arm.crosswalkFrame.supportHeading = normalizeHeading(crossingHeadings[index] + 90);
}
});
const crossingSpanTrim = coordinatedCrossingSpanTrim(arms, center, helpers);
const crosswalks = [];
const crossingRegions = [];
for (const arm of arms) {
if (!arm.crosswalkFrame) continue;
const crossing = buildArmCrossing(arm, crossingSpanTrim, cluster, helpers);
crosswalks.push(...crossing.crosswalks);
crossingRegions.push(crossing.region);
}
return { crosswalks, crossingRegions, diagnostics: transitionDiagnostics };
}
function coordinatedCrossingSpanTrim(arms, center, helpers) {
// Coordinate all four landing pairs before publishing stripes. Trim whole
// stripe pitches symmetrically so stripe size and spacing stay unchanged.
let crossingSpanTrim = 0;
if (arms.length === 4 && arms.every((arm) => arm.crosswalkFrame)) {
for (let attempt = 0; attempt < 12; attempt++) {
const trialTrim = attempt * 1.64;
const candidates = arms.map((arm) => {
const f = arm.crosswalkFrame;
const span = f.envelopeWidthMeters - 0.7 - trialTrim;
if (span < f.groupDepth) return null;
const shifted = helpers.offsetCoordinate(f.center, f.heading, f.groupDepth);
const layout = stripeLayout(span);
const half = span / 2 - (layout.centers[0] - layout.width / 2);
return [-1, 1].map((sign) => helpers.offsetCoordinate(shifted, f.heading + 90, sign * half));
});
if (candidates.some((candidate) => !candidate)) break;
const valid = arms.every((arm, i) => {
const j = (i + 1) % arms.length;
const pair = candidates[i]
.flatMap((a) => candidates[j].map((b) => ({ a, b, distance: helpers.distanceMeters(a, b) })))
.sort((a, b) => a.distance - b.distance)[0];
const origin = rayIntersection(
{ point: pair.a, heading: arm.crosswalkFrame.heading },
{ point: pair.b, heading: arms[j].crosswalkFrame.heading },
center,
);
return (
origin &&
[
[arm, pair.a],
[arms[j], pair.b],
].every(
([side, point]) =>
directionalProjectionMeters(origin, point, side.crosswalkFrame.heading) >
side.crosswalkFrame.groupDepth / 2 + 0.2,
)
);
});
if (valid) {
crossingSpanTrim = trialTrim;
break;
}
}
}
return crossingSpanTrim;
}
function buildArmCrossing(arm, crossingSpanTrim, cluster, helpers) {
const crosswalks = [];
const item = arm.representative;
const crossingHeading = arm.crosswalkFrame.heading;
const roadEdgeInset = 0.35;
const usableSpan = Math.max(0.42, arm.crosswalkFrame.envelopeWidthMeters - roadEdgeInset * 2 - crossingSpanTrim);
const groupDepth = arm.crosswalkFrame.groupDepth;
arm.crosswalkFrame.center = helpers.offsetCoordinate(arm.crosswalkFrame.center, crossingHeading, groupDepth);
arm.crosswalkRadius += groupDepth;
const endpoints = [
helpers.offsetCoordinate(arm.crosswalkFrame.center, crossingHeading + 90, -usableSpan / 2),
helpers.offsetCoordinate(arm.crosswalkFrame.center, crossingHeading + 90, usableSpan / 2),
];
const stripeWidth = 0.42;
const layout = stripeLayout(usableSpan);
const stripeCount = layout.centers.length;
const stripeSpacing = layout.pitch;
arm.crosswalkFrame.center = midpoint(...endpoints);
arm.crosswalkFrame.endpoints = endpoints;
arm.crosswalkFrame.spanMeters = usableSpan;
arm.crosswalkFrame.contactEndpointRatio = (layout.centers[0] - layout.width / 2) / usableSpan;
arm.crosswalkFrame.roadEdgeInsetMeters = roadEdgeInset;
const region = rectangle(arm.crosswalkFrame.center, crossingHeading, groupDepth, usableSpan);
for (let stripe = 0; stripe < stripeCount; stripe += 1) {
const along = layout.centers[stripe];
const centerPoint = helpers.offsetCoordinate(endpoints[0], bearing(...endpoints), along);
const ring = [
helpers.offsetCoordinate(
helpers.offsetCoordinate(centerPoint, crossingHeading, -groupDepth / 2),
crossingHeading + 90,
-stripeWidth / 2,
),
helpers.offsetCoordinate(
helpers.offsetCoordinate(centerPoint, crossingHeading, groupDepth / 2),
crossingHeading + 90,
-stripeWidth / 2,
),
helpers.offsetCoordinate(
helpers.offsetCoordinate(centerPoint, crossingHeading, groupDepth / 2),
crossingHeading + 90,
stripeWidth / 2,
),
helpers.offsetCoordinate(
helpers.offsetCoordinate(centerPoint, crossingHeading, -groupDepth / 2),
crossingHeading + 90,
stripeWidth / 2,
),
helpers.offsetCoordinate(
helpers.offsetCoordinate(centerPoint, crossingHeading, -groupDepth / 2),
crossingHeading + 90,
-stripeWidth / 2,
),
];
crosswalks.push({
type: 'Feature',
properties: {
native_id: `complex-crosswalk:${cluster.id}:${item.nodeId}:${item.approach.segmentId}:${stripe + 1}`,
object_key: `crossing:${arm.key}`,
crossing_key: `crossing:${arm.key}`,
arm_key: arm.key,
cluster_id: cluster.id,
kind: 'complex-crosswalk',
crossing_node_id: item.nodeId,
road_id: item.approach.roadIds[0],
direction: crossingHeading,
radial_distance_m: arm.crosswalkRadius,
span_m: usableSpan,
road_envelope_span_m: arm.crosswalkFrame.envelopeWidthMeters,
road_edge_inset_m: roadEdgeInset,
group_depth_m: groupDepth,
stripe_width_m: stripeWidth,
stripe_spacing_m: stripeSpacing,
frame_center: arm.crosswalkFrame.center,
frame_support_heading: arm.crosswalkFrame.supportHeading,
facility_evidence: arm.crosswalkEvidence.kind,
...(arm.crosswalkEvidence.crossingNodeIds.length
? { source_crossing_node_ids: arm.crosswalkEvidence.crossingNodeIds }
: {}),
provenance: 'native-road-complex-junction-crosswalk/v6-road-clipped',
},
geometry: { type: 'Polygon', coordinates: [ring] },
});
}
return { crosswalks, region };
}
function buildCornerCompositions({
model,
cluster,
helpers,
center,
nodeIds,
arms,
boundaryGraph,
publishedCarriageways,
coreRadius,
outerRadius,
}) {
const cornerFills = [];
const sidewalkCorners = [];
const cornerDiagnostics = [];
const islands = [];
const crosswalks = [];
// Two neighbouring corners contribute offsets to each shared arm crossing.
const armEndpointOffsets = new Map();
const islandOffsetMeters = Number(helpers.clusterIslandOffsetMeters) || 0;
const cornerOverlapsExclusion = (ring, cornerKey, part) => {
const region = boundaryGraph.exclusionRegions.find((region) => ringsOverlap(region.ring, ring));
if (!region) return false;
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`corner:${cornerKey}`,
[String(region.id)],
'complex-junction-corner-exclusion-overlap',
`该角部${part}侵入已知排除区域 ${region.id},已省略,避免覆盖已知不可通行空间。`,
center,
),
);
return true;
};
const omittedCornerFacilityCount = arms.filter((arm, index) => {
const next = arms[(index + 1) % arms.length];
const delta = positiveHeadingDelta(arm.heading, next.heading);
return delta >= 45 && delta <= 135;
}).length;
// Retain the legacy diagnostic for output compatibility. Default inferred
// corner facilities below are still governed by their geometric checks.
if (omittedCornerFacilityCount)
cornerDiagnostics.push(
helpers.diagnostic(
'info',
`junction-cluster:${cluster.id}`,
[...nodeIds],
'complex-junction-corner-facilities-omitted',
`已省略 ${omittedCornerFacilityCount} 组缺少岛体或步行连接来源的角部导流岛和斑马线。`,
center,
),
);
const defaultCornerRadius = Math.max(4, Math.min(25, Number(cluster.cornerRadiusMeters) || 12));
for (let index = 0; index < arms.length; index += 1) {
const first = arms[index];
const second = arms[(index + 1) % arms.length];
if (!publishedCarriageways.size) continue;
const cornerRadius = helpers.clusterCornerRadii?.get(first.cornerKey) ?? defaultCornerRadius;
const fillet = buildCornerFillet({
first,
second,
index,
cornerRadius,
coreRadius,
outerRadius,
center,
cluster,
nodeIds,
helpers,
cornerOverlapsExclusion,
cornerDiagnostics,
});
if (!fillet) continue;
cornerFills.push(fillet.feature);
const contacts = solveCornerContacts({
first,
second,
center,
outerRadius,
islandOffsetMeters,
nodeIds,
helpers,
cornerDiagnostics,
armEndpointOffsets,
});
if (!contacts) continue;
islands.push(...buildCornerIslands(first, index, cluster, contacts, cornerOverlapsExclusion));
if (
!first.members.every((item) => publishedCarriageways.has(item.key)) ||
!second.members.every((item) => publishedCarriageways.has(item.key))
)
continue;
crosswalks.push(...buildDiagonalCrossing(first, index, cluster, contacts, helpers));
// Preserve the composition's failure dependency: sidewalks are only built
// after the corner contact solve and the carriageway publication checks.
const sidewalk = buildCornerSidewalk({
first,
second,
index,
model,
cluster,
center,
nodeIds,
boundaryGraph,
helpers,
fillet,
cornerOverlapsExclusion,
cornerDiagnostics,
});
if (sidewalk) sidewalkCorners.push(sidewalk);
}
return { cornerFills, sidewalkCorners, islands, crosswalks, armEndpointOffsets, diagnostics: cornerDiagnostics };
}
function buildCornerFillet({
first,
second,
index,
cornerRadius,
coreRadius,
outerRadius,
center,
cluster,
nodeIds,
helpers,
cornerOverlapsExclusion,
cornerDiagnostics,
}) {
const delta = positiveHeadingDelta(first.heading, second.heading);
if (delta < 45 || delta > 135) return null;
const bisector = normalizeHeading(first.heading + delta / 2);
const edges = [first, second].map((arm) => cornerEdgeAt(arm, coreRadius + 6, bisector, center, helpers));
if (!edges.every(Boolean)) return null;
const apex = rayIntersection(edges[0], edges[1], center);
const apexReach = apex ? directionalProjectionMeters(center, apex, bisector) : null;
// The wedge apex has to sit ahead of the core and inside the arm handoff;
// outside that band the two edges are near parallel and any fillet fitted
// to them would sweep across the carriageways instead of the corner.
if (apexReach === null || apexReach < 1 || apexReach > outerRadius) {
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`junction-cluster:${cluster.id}`,
[...nodeIds],
'complex-junction-corner-fillet-fallback',
'该夹角的道路边缘切线无法安全构造圆角,已保留直角过渡。',
center,
),
);
return null;
}
// Tangent distance for a circle of `cornerRadius` inscribed in a wedge of
// opening `delta`.
// Keep the radius control continuous. The previous handoff cap made a
// sizeable part of the advertised 1..25 m range geometry-inert: once the
// tangent distance hit the cap, pressing Enter only changed metadata.
// The solver's radius bounds and the generated arm envelope provide the
// validity boundary; this value must remain the direct geometric response.
const tangentDistance = cornerRadius / Math.tan((delta * Math.PI) / 360);
const tangents = edges.map((edge) => helpers.offsetCoordinate(apex, edge.heading, tangentDistance));
const curve = quadraticCurve(tangents[0], apex, tangents[1], CORNER_FILLET_SEGMENTS);
const ring = [...curve, center, curve[0]];
if (!ring.every((point) => point.every(Number.isFinite))) return null;
if (cornerOverlapsExclusion(ring, first.cornerKey, '道路补面')) return null;
const feature = {
type: 'Feature',
properties: {
native_id: `complex-corner-fillet:${cluster.id}:${index + 1}`,
cluster_id: cluster.id,
kind: 'complex-corner-fillet',
object_key: first.cornerKey,
corner_key: first.cornerKey,
complex_part: 'corner-fillet',
corner_index: index + 1,
from_heading: first.heading,
to_heading: second.heading,
bisector_heading: bisector,
corner_radius_m: cornerRadius,
tangent_distance_m: Math.round(tangentDistance * 100) / 100,
apex_reach_m: Math.round(apexReach * 100) / 100,
provenance: 'native-road-complex-junction-corner-fillet/v1',
},
geometry: { type: 'Polygon', coordinates: [ring] },
};
return { feature, edges, curve, bisector };
}
function solveCornerContacts({
first,
second,
center,
outerRadius,
islandOffsetMeters,
nodeIds,
helpers,
cornerDiagnostics,
armEndpointOffsets,
}) {
if (!first.crosswalkFrame?.endpoints || !second.crosswalkFrame?.endpoints) return null;
const endpointPairs = first.crosswalkFrame.endpoints.flatMap((a, firstEndpointIndex) =>
second.crosswalkFrame.endpoints.map((b, secondEndpointIndex) => ({
a,
b,
firstEndpointIndex,
secondEndpointIndex,
distance: helpers.distanceMeters(a, b),
})),
);
const pair = endpointPairs.sort((a, b) => a.distance - b.distance)[0];
const crossingCorner = rayIntersection(
{ point: pair.a, heading: first.crosswalkFrame.heading },
{ point: pair.b, heading: second.crosswalkFrame.heading },
center,
);
if (!crossingCorner) return null;
const lonScale = 111320 * Math.cos((crossingCorner[1] * Math.PI) / 180);
const toLocal = (point) => [(point[0] - crossingCorner[0]) * lonScale, (point[1] - crossingCorner[1]) * 111320];
const fromLocal = (point) => [crossingCorner[0] + point[0] / lonScale, crossingCorner[1] + point[1] / 111320];
const landing = (arm, endpoint) => {
const frame = arm.crosswalkFrame;
const layout = stripeLayout(frame.spanMeters);
const margin = layout.centers[0] - layout.width / 2;
const edgeCenter = helpers.offsetCoordinate(endpoint, bearing(endpoint, frame.center), margin);
return [-1, 1].map((sign) =>
toLocal(helpers.offsetCoordinate(edgeCenter, frame.heading, (sign * frame.groupDepth) / 2)),
);
};
let contactSolution = solveIslandContacts(
landing(first, pair.a),
landing(second, pair.b),
COMPLEX_CROSSWALK_DEPTH_METERS,
{ maxLegLength: outerRadius },
);
if (contactSolution.status !== 'solved') {
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`corner:${first.cornerKey}`,
[...nodeIds],
'complex-junction-island-infeasible',
contactSolution.reason,
crossingCorner,
),
);
return null;
}
// Dragging moves the whole pedestrian composition away from the cluster
// centre. Re-solve from the translated landing segments so the island,
// its green contact hexagon and all three complete contacts retain the same
// source coordinates instead of merely translating a detached island.
let islandShift = [0, 0];
if (islandOffsetMeters > 0) {
const provisionalRing = contactSolution.ring.map(fromLocal);
const provisionalCenter = polygonCenter(provisionalRing);
islandShift = radialShift(center, provisionalCenter, islandOffsetMeters);
const localShift = toLocal([crossingCorner[0] + islandShift[0], crossingCorner[1] + islandShift[1]]);
const translateSegment = (segment) => segment.map((point) => [point[0] + localShift[0], point[1] + localShift[1]]);
const shifted = solveIslandContacts(
translateSegment(landing(first, pair.a)),
translateSegment(landing(second, pair.b)),
COMPLEX_CROSSWALK_DEPTH_METERS,
{ maxLegLength: outerRadius },
);
if (shifted.status !== 'solved') {
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`corner:${first.cornerKey}`,
[...nodeIds],
'complex-junction-island-offset-infeasible',
shifted.reason,
crossingCorner,
),
);
return null;
}
contactSolution = shifted;
const rememberOffset = (arm, endpointIndex) => {
const offsets = armEndpointOffsets.get(arm.key) || [
[0, 0],
[0, 0],
];
offsets[endpointIndex] = islandShift;
armEndpointOffsets.set(arm.key, offsets);
};
rememberOffset(first, pair.firstEndpointIndex);
rememberOffset(second, pair.secondEndpointIndex);
}
return { contactSolution, fromLocal };
}
function buildCornerIslands(first, index, cluster, { contactSolution, fromLocal }, cornerOverlapsExclusion) {
const islands = [];
const publishedIslandRing = contactSolution.ring.map(fromLocal);
const greenRing = contactSolution.greenRing.map(fromLocal);
if (!cornerOverlapsExclusion(publishedIslandRing, first.cornerKey, '安全岛'))
islands.push({
type: 'Feature',
properties: {
native_id: `complex-corner-island:${cluster.id}:${index + 1}`,
object_key: `island:inferred/${first.cornerKey}`,
cluster_id: cluster.id,
kind: 'island',
corner_key: first.cornerKey,
facility_evidence: 'inferred-complex-junction-corner',
provenance: 'native-road-complex-junction-inferred-island/v1',
island_leg_lengths_m: contactSolution.legLengths,
contact_points: greenRing.slice(0, -1),
},
geometry: { type: 'Polygon', coordinates: [publishedIslandRing] },
});
if (!cornerOverlapsExclusion(greenRing, first.cornerKey, '安全岛绿色接触区'))
islands.push({
type: 'Feature',
properties: {
native_id: `complex-corner-island-green:${cluster.id}:${index + 1}`,
object_key: `island:inferred/${first.cornerKey}`,
cluster_id: cluster.id,
corner_key: first.cornerKey,
kind: 'island-green',
island_key: `island:inferred/${first.cornerKey}`,
provenance: 'native-road-complex-junction-island-contact-hexagon/v1',
},
geometry: { type: 'Polygon', coordinates: [greenRing] },
});
return islands;
}
function buildDiagonalCrossing(first, index, cluster, { contactSolution, fromLocal }, helpers) {
const crosswalks = [];
const stripeWidth = 0.42;
// Complex junctions carry a default diagonal crossing across each safe
// corner. Source crossing nodes refine provenance/inset values, but are
// not required for the default visual treatment.
const outerMidpoint = fromLocal(contactSolution.thirdCenter);
const diagonalDepth = COMPLEX_CROSSWALK_DEPTH_METERS;
const outwardHeading = (Math.atan2(contactSolution.outward[0], contactSolution.outward[1]) * 180) / Math.PI;
const diagonalHeading = outwardHeading;
const diagonalCenter = helpers.offsetCoordinate(outerMidpoint, outwardHeading, diagonalDepth / 2);
const diagonalSpan = COMPLEX_CROSSWALK_DEPTH_METERS;
const layout = stripeLayout(diagonalDepth);
const stripeCount = layout.centers.length;
const stripeSpacing = layout.pitch;
for (let stripe = 0; stripe < stripeCount; stripe += 1) {
const along = -diagonalDepth / 2 + layout.centers[stripe] - (layout.centers[0] - stripeWidth / 2);
const stripeCenter = helpers.offsetCoordinate(diagonalCenter, diagonalHeading, along);
const ring = [
helpers.offsetCoordinate(
helpers.offsetCoordinate(stripeCenter, diagonalHeading + 90, -diagonalSpan / 2),
diagonalHeading,
-stripeWidth / 2,
),
helpers.offsetCoordinate(
helpers.offsetCoordinate(stripeCenter, diagonalHeading + 90, diagonalSpan / 2),
diagonalHeading,
-stripeWidth / 2,
),
helpers.offsetCoordinate(
helpers.offsetCoordinate(stripeCenter, diagonalHeading + 90, diagonalSpan / 2),
diagonalHeading,
stripeWidth / 2,
),
helpers.offsetCoordinate(
helpers.offsetCoordinate(stripeCenter, diagonalHeading + 90, -diagonalSpan / 2),
diagonalHeading,
stripeWidth / 2,
),
helpers.offsetCoordinate(
helpers.offsetCoordinate(stripeCenter, diagonalHeading + 90, -diagonalSpan / 2),
diagonalHeading,
-stripeWidth / 2,
),
];
crosswalks.push({
type: 'Feature',
properties: {
native_id: `complex-corner-crosswalk:${cluster.id}:${index + 1}:${stripe + 1}`,
object_key: `crossing:corner:${first.cornerKey}`,
crossing_key: `crossing:corner:${first.cornerKey}`,
island_key: `island:inferred/${first.cornerKey}`,
from_boundary: `sidewalk:${first.cornerKey}:from`,
to_boundary: `island:inferred/${first.cornerKey}`,
cluster_id: cluster.id,
kind: 'complex-corner-crosswalk',
stripe_width_m: stripeWidth,
stripe_spacing_m: stripeSpacing,
group_depth_m: COMPLEX_CROSSWALK_DEPTH_METERS,
corner_key: first.cornerKey,
facility_evidence: 'default-complex-junction',
provenance: 'native-road-complex-junction-corner-crosswalk/v1',
},
geometry: { type: 'Polygon', coordinates: [ring] },
});
}
return crosswalks;
}
function buildCornerSidewalk({
first,
second,
index,
model,
cluster,
center,
nodeIds,
boundaryGraph,
helpers,
fillet,
cornerOverlapsExclusion,
cornerDiagnostics,
}) {
const { edges, curve, bisector } = fillet;
// The straight pedestrian strips are trimmed at the cluster boundary, so
// two arms that both carry a footway still meet as two loose ends across
// an empty wedge. Bridge them along the curb the fillet already defines.
// The corner faces clockwise from `first` and counter-clockwise from
// `second`, so each arm must carry the footway on that facing side.
if (!armCarriesSidewalk(first, model, true) || !armCarriesSidewalk(second, model, false)) return null;
const seams = edges.map((edge) => exteriorSidewalkSeam(edge, boundaryGraph, helpers));
if (!seams.every(Boolean)) {
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`corner:${first.cornerKey}`,
edges.flatMap((edge) => edge.roadIds),
'complex-junction-sidewalk-seam-unavailable',
'该角部缺少两侧可验证的人行道接缝,已省略连接,避免生成悬空步行带。',
center,
),
);
return null;
}
const curb = [seams[0].curb, ...curve, seams[1].curb];
const outerEdge = offsetPolylineAwayFromCenter(curb, center, SIDEWALK_WIDTH_METERS, helpers);
outerEdge[0] = seams[0].outer;
outerEdge[outerEdge.length - 1] = seams[1].outer;
const sidewalkRing = [...curb, ...outerEdge.slice().reverse(), curb[0]];
if (!sidewalkRing.every((point) => point.every(Number.isFinite)) || ringSelfIntersects(sidewalkRing)) {
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`junction-cluster:${cluster.id}`,
[...nodeIds],
'complex-junction-sidewalk-corner-fallback',
'该夹角的人行道转角几何自交或无效,已跳过,两侧步行带保持断开。',
center,
),
);
return null;
}
if (cornerOverlapsExclusion(sidewalkRing, first.cornerKey, '人行道')) return null;
return {
type: 'Feature',
properties: {
native_id: `complex-sidewalk-corner:${cluster.id}:${index + 1}`,
cluster_id: cluster.id,
kind: 'complex-sidewalk-corner',
object_key: `sidewalk-turn:${first.cornerKey}`,
corner_key: first.cornerKey,
corner_index: index + 1,
from_heading: first.heading,
to_heading: second.heading,
bisector_heading: bisector,
width_m: SIDEWALK_WIDTH_METERS,
seam_source: 'published-exterior-sidewalk',
provenance: 'native-road-complex-junction-sidewalk-corner/v1',
},
geometry: { type: 'Polygon', coordinates: [sidewalkRing] },
};
}
function applyCrossingDisplacements(arms, armEndpointOffsets, crosswalks, crossingRegions, stopLines) {
// Rebuild each shared arm crossing from its two endpoint displacement values.
// Interpolation occurs along its declared support axis, preserving every
// stripe's width and spacing while allowing the two neighbouring islands to
// move in different radial directions.
if (armEndpointOffsets.size) {
for (const arm of arms) {
const offsets = armEndpointOffsets.get(arm.key);
if (!offsets || !arm.crosswalkFrame?.endpoints) continue;
const [start, end] = arm.crosswalkFrame.endpoints;
const movedRing = (ring) =>
ring.map((point) => {
const rawRatio = projectionRatio(point, start, end);
const contactRatio = arm.crosswalkFrame.contactEndpointRatio || 0;
const ratio = Math.max(0, Math.min(1, (rawRatio - contactRatio) / (1 - contactRatio * 2)));
const shift = [
offsets[0][0] * (1 - ratio) + offsets[1][0] * ratio,
offsets[0][1] * (1 - ratio) + offsets[1][1] * ratio,
];
return [point[0] + shift[0], point[1] + shift[1]];
});
for (const crossing of crosswalks) {
if (crossing.properties.arm_key === arm.key)
crossing.geometry.coordinates[0] = movedRing(crossing.geometry.coordinates[0]);
}
// Preserve the original full crossing footprint and pave the swept
// connection to its new position, including the gaps between white bars.
const frame = arm.crosswalkFrame;
const corners = rectangle(frame.center, frame.heading, frame.groupDepth, frame.spanMeters);
const originalRegion = [];
// Split at the same endpoint clamps used by movedRing. A four-vertex
// rectangle would interpolate across those clamps and cut off the bars.
const contactRatio = frame.contactEndpointRatio || 0;
for (let edge = 0; edge < 4; edge++) {
const ratios = edge % 2 === 0 ? [0, contactRatio, 1 - contactRatio] : [0];
for (const ratio of ratios) {
originalRegion.push(corners[edge].map((value, axis) => value + (corners[edge + 1][axis] - value) * ratio));
}
}
originalRegion.push(originalRegion[0]);
const movedRegion = movedRing(originalRegion);
crossingRegions.push(movedRegion);
for (let edge = 0; edge < originalRegion.length - 1; edge++) {
crossingRegions.push([
originalRegion[edge],
originalRegion[edge + 1],
movedRegion[edge + 1],
movedRegion[edge],
originalRegion[edge],
]);
}
const averageShift = [(offsets[0][0] + offsets[1][0]) / 2, (offsets[0][1] + offsets[1][1]) / 2];
for (const stopLine of stopLines) {
if (stopLine.properties.arm_key !== arm.key) continue;
stopLine.geometry.coordinates[0] = stopLine.geometry.coordinates[0].map((point) => [
point[0] + averageShift[0],
point[1] + averageShift[1],
]);
}
}
}
}
module.exports = {
applyCrossingDisplacements,
buildApproachSurfacesAndStops,
buildArmCrossings,
buildCornerCompositions,
planArmCrossings,
};
+262
View File
@@ -0,0 +1,262 @@
'use strict';
const { stationAtDistanceFrom } = require('./junction-build-plan');
function normalizeHeading(value) {
return ((((value + 180) % 360) + 360) % 360) - 180;
}
function armCarriesSidewalk(arm, model, cornerIsClockwise) {
return arm.members.some((member) =>
member.approach.roadIds
.map((roadId) => model.roads.find((road) => road.id === roadId))
.filter(Boolean)
.some((road) => {
const outwardIsForward = String(road.sourceNodeIds[0]) === String(member.nodeId);
const onClockwiseSide = outwardIsForward ? road.sidewalkRight : road.sidewalkLeft;
const onCounterClockwiseSide = outwardIsForward ? road.sidewalkLeft : road.sidewalkRight;
return Boolean(cornerIsClockwise ? onClockwiseSide : onCounterClockwiseSide);
}),
);
}
function exteriorSidewalkSeam(edge, graph, helpers) {
const section = graph.sections.find((item) => item.carriagewayKey === edge.carriagewayKey);
if (
!section ||
section.ringStatus !== 'supported' ||
section.transitionStatus !== 'supported' ||
section.exclusionStatus !== 'clear'
)
return null;
const target = edge.side === 90 ? section.outer.right : section.outer.left;
for (const feature of helpers.exteriorSidewalks || []) {
const ids = String(feature.properties.directional_road_ids || '').split(',');
if (!edge.roadIds.some((id) => ids.includes(String(id)))) continue;
const ring = feature.geometry.coordinates[0];
const half = (ring.length - 1) / 2;
for (const [curb, outer] of [
[ring[0], ring[ring.length - 2]],
[ring[half - 1], ring[half]],
]) {
if (helpers.distanceMeters(curb, target) <= 0.01) return { curb, outer };
}
}
return null;
}
function offsetPolylineAwayFromCenter(points, center, meters, helpers) {
return points.map((point, index) => {
const previous = points[Math.max(0, index - 1)];
const next = points[Math.min(points.length - 1, index + 1)];
const tangent = previous === next ? 0 : bearing(previous, next);
return [tangent + 90, tangent - 90]
.map((heading) => helpers.offsetCoordinate(point, heading, meters))
.sort((first, second) => helpers.distanceMeters(second, center) - helpers.distanceMeters(first, center))[0];
});
}
function ringSelfIntersects(ring) {
const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
const straddles = (p1, p2, p3, p4) => {
const d1 = cross(p3, p4, p1);
const d2 = cross(p3, p4, p2);
const d3 = cross(p1, p2, p3);
const d4 = cross(p1, p2, p4);
return ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0));
};
for (let first = 0; first < ring.length - 1; first += 1) {
for (let second = first + 2; second < ring.length - 1; second += 1) {
if (first === 0 && second === ring.length - 2) continue;
if (straddles(ring[first], ring[first + 1], ring[second], ring[second + 1])) return true;
}
}
return false;
}
function angleAround(center, point) {
return Math.atan2(point[1] - center[1], point[0] - center[0]);
}
function signedLateralMeters(origin, point, heading) {
const east = (point[0] - origin[0]) * 111320 * Math.cos((origin[1] * Math.PI) / 180);
const north = (point[1] - origin[1]) * 111320;
const radians = ((heading + 90) * Math.PI) / 180;
return east * Math.sin(radians) + north * Math.cos(radians);
}
function bearing(first, second) {
const east = (second[0] - first[0]) * Math.cos((first[1] * Math.PI) / 180);
const north = second[1] - first[1];
return (Math.atan2(east, north) * 180) / Math.PI;
}
function midpoint(first, second) {
return [(first[0] + second[0]) / 2, (first[1] + second[1]) / 2];
}
function averageHeading(headings) {
const vector = headings.reduce(
(sum, heading) => {
const radians = (heading * Math.PI) / 180;
return [sum[0] + Math.sin(radians), sum[1] + Math.cos(radians)];
},
[0, 0],
);
return (Math.atan2(vector[0], vector[1]) * 180) / Math.PI;
}
function positiveHeadingDelta(first, second) {
return (((second - first) % 360) + 360) % 360;
}
function pointOnCarriagewayRadius(item, center, radius, helpers) {
const station = stationAtDistanceFrom(item.approach.line, center, radius, helpers);
return helpers.pointAlongLine(item.approach.line, Math.max(0, Math.min(item.length, station)));
}
function armEnvelopeAtRadius(arm, radius, center, helpers) {
if (!arm.members.length) return null;
const centers = arm.members.map((member) => pointOnCarriagewayRadius(member, center, radius, helpers));
const reference = centers[0];
let minimum = Infinity;
let maximum = -Infinity;
centers.forEach((point, index) => {
const lateral = signedLateralMeters(reference, point, arm.heading);
const halfWidth = arm.members[index].approach.widthMeters / 2;
minimum = Math.min(minimum, lateral - halfWidth);
maximum = Math.max(maximum, lateral + halfWidth);
});
if (!Number.isFinite(minimum) || maximum - minimum < 1) return null;
return {
center: helpers.offsetCoordinate(reference, arm.heading + 90, (minimum + maximum) / 2),
widthMeters: maximum - minimum,
};
}
function crossingEvidenceForArm(model, arm, center, helpers) {
const osmWayIds = new Set(
arm.members.flatMap((member) => member.roads.flatMap((road) => (road.osmWayIds || []).map(String))),
);
const maximumDistance = Math.max(
8,
arm.members.reduce((width, member) => width + member.approach.widthMeters, 0) / 2 + 3,
);
const crossings = (model.crossings || [])
.filter(
(crossing) =>
(crossing.osmWayIds || []).some((wayId) => osmWayIds.has(String(wayId))) &&
helpers.distanceMeters(crossing.coordinate, center) <= maximumDistance,
)
.sort(
(first, second) =>
helpers.distanceMeters(first.coordinate, center) - helpers.distanceMeters(second.coordinate, center) ||
String(first.id).localeCompare(String(second.id)),
);
const crossingNodeIds = crossings.map((crossing) => String(crossing.id));
return {
kind: crossingNodeIds.length ? 'source-crossing-node' : 'unknown-no-crossing-source',
crossingNodeIds,
crossing: crossings[0] || null,
};
}
function cornerEdgeAt(arm, radius, bisector, center, helpers) {
const candidates = arm.members.flatMap((member) => {
const point = pointOnCarriagewayRadius(member, center, radius, helpers);
const halfWidth = member.approach.widthMeters / 2;
return [90, -90].map((side) => ({
point: helpers.offsetCoordinate(point, member.heading + side, halfWidth),
heading: member.heading,
carriagewayKey: member.key,
roadIds: member.approach.roadIds,
side,
}));
});
return (
candidates.sort(
(first, second) =>
directionalProjectionMeters(center, second.point, bisector) -
directionalProjectionMeters(center, first.point, bisector),
)[0] || null
);
}
function rayIntersection(first, second, origin) {
const lonScale = 111320 * Math.cos((origin[1] * Math.PI) / 180);
const toLocal = (point) => [(point[0] - origin[0]) * lonScale, (point[1] - origin[1]) * 111320];
const direction = (heading) => {
const radians = (heading * Math.PI) / 180;
return [Math.sin(radians), Math.cos(radians)];
};
const firstPoint = toLocal(first.point);
const secondPoint = toLocal(second.point);
const firstDirection = direction(first.heading);
const secondDirection = direction(second.heading);
const denominator = firstDirection[0] * secondDirection[1] - firstDirection[1] * secondDirection[0];
if (Math.abs(denominator) < 1e-4) return null;
const delta = [secondPoint[0] - firstPoint[0], secondPoint[1] - firstPoint[1]];
const distanceAlongFirst = (delta[0] * secondDirection[1] - delta[1] * secondDirection[0]) / denominator;
const local = [
firstPoint[0] + firstDirection[0] * distanceAlongFirst,
firstPoint[1] + firstDirection[1] * distanceAlongFirst,
];
if (!local.every(Number.isFinite)) return null;
return [origin[0] + local[0] / lonScale, origin[1] + local[1] / 111320];
}
function quadraticCurve(start, control, end, segments) {
const result = [];
for (let index = 0; index <= segments; index += 1) {
const t = index / segments;
const u = 1 - t;
result.push([
u * u * start[0] + 2 * u * t * control[0] + t * t * end[0],
u * u * start[1] + 2 * u * t * control[1] + t * t * end[1],
]);
}
return result;
}
function directionalProjectionMeters(origin, point, heading) {
const east = (point[0] - origin[0]) * 111320 * Math.cos((origin[1] * Math.PI) / 180);
const north = (point[1] - origin[1]) * 111320;
const radians = (heading * Math.PI) / 180;
return east * Math.sin(radians) + north * Math.cos(radians);
}
function polygonCenter(ring) {
const points = ring.slice(0, -1);
return points.reduce((sum, point) => [sum[0] + point[0] / points.length, sum[1] + point[1] / points.length], [0, 0]);
}
function projectionRatio(point, start, end) {
const lonScale = 111320 * Math.cos((start[1] * Math.PI) / 180);
const vector = [(end[0] - start[0]) * lonScale, (end[1] - start[1]) * 111320];
const relative = [(point[0] - start[0]) * lonScale, (point[1] - start[1]) * 111320];
const lengthSquared = vector[0] * vector[0] + vector[1] * vector[1];
if (lengthSquared < 1e-12) return 0;
return Math.max(0, Math.min(1, (relative[0] * vector[0] + relative[1] * vector[1]) / lengthSquared));
}
module.exports = {
angleAround,
armCarriesSidewalk,
armEnvelopeAtRadius,
bearing,
cornerEdgeAt,
crossingEvidenceForArm,
directionalProjectionMeters,
exteriorSidewalkSeam,
midpoint,
normalizeHeading,
offsetPolylineAwayFromCenter,
polygonCenter,
positiveHeadingDelta,
pointOnCarriagewayRadius,
projectionRatio,
quadraticCurve,
rayIntersection,
ringSelfIntersects,
signedLateralMeters,
};
+178
View File
@@ -0,0 +1,178 @@
'use strict';
const { solveComplexPavementRegion } = require('./junction-pavement-region');
function buildCoreSurface({ cluster, helpers, center, nodeIds, arms, carriageways, shape, coreRadius, coreClosure }) {
const coreRing = coreClosure.status === 'supported' ? coreClosure.ring : null;
const cornerDiagnostics = [];
let coreFeature = null;
if (coreRing)
coreFeature = {
type: 'Feature',
properties: {
native_id: `complex-junction:${cluster.id}:core`,
cluster_id: cluster.id,
kind: 'complex-core',
complex_part: 'core',
center,
radius_m: coreRadius,
configured_radius_m: cluster.coreRadiusMeters,
approach_count: arms.length,
carriageway_count: carriageways.length,
shape_kind: shape.kind,
shape_label: shape.label,
arm_count: arms.length,
through_pair_count: shape.throughPairCount,
approach_headings: arms.map((arm) => Math.round(arm.representative.heading * 10) / 10),
boundary_refs: coreClosure.sharedEdgeRefs,
closure_count: coreClosure.closureCount,
shared_seam_error_m: coreClosure.maxSharedSeamErrorMeters,
shared_seam_errors: coreClosure.sharedSeamErrors,
connected_entry_count: coreClosure.connectedEntryCount,
required_pavement_connected: coreClosure.requiredPavementConnected,
core_ring_area: coreClosure.ringArea,
core_ring_self_intersects: coreClosure.ringSelfIntersects,
exclusion_hole_count: (coreClosure.holes || []).length,
region_status: coreClosure.holes?.length ? 'supported-with-holes' : 'supported',
provenance: 'native-road-complex-junction/v7-shared-entry-core',
},
geometry: { type: 'Polygon', coordinates: [coreRing, ...(coreClosure.holes || [])] },
};
if (coreRing && coreClosure.maxSharedSeamErrorMeters > 0.01) {
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`junction-cluster:${cluster.id}`,
[...nodeIds],
'complex-junction-shared-seam-exceeds-tolerance',
`核心区域与入口断面的最大接缝误差为 ${coreClosure.maxSharedSeamErrorMeters.toFixed(3)} 米,超过 1 厘米验收阈值。`,
center,
),
);
} else if (!coreRing) {
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`junction-cluster:${cluster.id}`,
[...nodeIds],
'complex-junction-core-closure-unsupported',
`路口中心区域缺少可验证的闭合边(${coreClosure.reason}),已保留各进口道路面。`,
center,
),
);
}
return { feature: coreFeature, diagnostics: cornerDiagnostics };
}
function buildApproachSurfaceFeatures(boundaryParts, model, cluster) {
const features = [];
for (const { item, section } of boundaryParts) {
const ring = section.ring;
features.push({
type: 'Feature',
properties: {
native_id: `complex-junction:${cluster.id}:carriageway:${item.approach.segmentId}`,
cluster_id: cluster.id,
kind: 'complex-approach',
object_key: item.key,
carriageway_key: item.key,
arm_key: item.armKey,
complex_part: 'carriageway',
heading_deg: item.heading,
lane_count: item.approach.roadIds.reduce(
(sum, roadId) => sum + (model.roads.find((road) => road.id === roadId)?.laneCount || 0),
0,
),
width_m: item.approach.widthMeters,
outer_width_m: section.outerWidthMeters,
inner_width_m: section.innerWidthMeters,
transition_length_m: Math.round(section.transitionMeters * 10) / 10,
transition_status: section.transitionStatus,
ring_status: section.ringStatus,
exclusion_status: section.exclusionStatus,
...(section.exclusionRegionId ? { exclusion_region_id: section.exclusionRegionId } : {}),
boundary_refs: section.edgeRefs,
provenance: 'native-road-complex-junction/v6-shared-transition-sections',
},
geometry: { type: 'Polygon', coordinates: [ring] },
});
}
return features;
}
function appendPavementRegion(features, crossingRegions, cluster, center, nodeIds, helpers) {
const cornerDiagnostics = [];
// Publish a single canonical pavement region last. The individual approach,
// core and corner polygons above remain structural inputs for editing and
// diagnostics; they are no longer the visible authority at the junction.
const basePavement = features.map((feature) => feature.geometry.coordinates[0]);
const pavementRegion = solveComplexPavementRegion(basePavement, crossingRegions);
if (pavementRegion.status === 'supported') {
for (const feature of features) feature.properties.pavement_input = true;
features.push({
type: 'Feature',
properties: {
native_id: `complex-junction:${cluster.id}:pavement-region`,
cluster_id: cluster.id,
kind: 'complex-pavement-region',
complex_part: 'pavement-region',
center,
region_status: 'supported',
region_input_count: pavementRegion.inputCount,
crossing_connector_count: 0,
provenance: 'native-road-complex-junction-pavement-region/v1',
},
geometry: { type: 'MultiPolygon', coordinates: pavementRegion.regions },
});
} else
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`junction-cluster:${cluster.id}`,
[...nodeIds],
pavementRegion.status === 'unsupported'
? 'complex-junction-pavement-region-assembly-failed'
: 'complex-junction-pavement-region-disconnected',
pavementRegion.status === 'unsupported'
? '统一铺装区域无法可靠装配,保留结构输入面并拒绝发布统一铺装面。'
: '过街与入口无法组成连续铺装区域,保留结构输入面并拒绝发布统一铺装面。',
center,
),
);
return cornerDiagnostics;
}
function assemblePavementSurfaces({
model,
cluster,
helpers,
center,
nodeIds,
topology,
shape,
coreRadius,
coreClosure,
boundaryParts,
cornerFills,
crossingRegions,
}) {
const { feature: coreFeature, diagnostics } = buildCoreSurface({
cluster,
helpers,
center,
nodeIds,
arms: topology.arms,
carriageways: topology.carriageways,
shape,
coreRadius,
coreClosure,
});
const features = buildApproachSurfaceFeatures(boundaryParts, model, cluster);
// Preserve the structural surface order before publishing canonical pavement.
features.push(...cornerFills);
if (coreFeature) features.push(coreFeature);
diagnostics.push(...appendPavementRegion(features, crossingRegions, cluster, center, nodeIds, helpers));
return { features, diagnostics };
}
module.exports = { assemblePavementSurfaces };
File diff suppressed because it is too large. Load diff