fix: fill junction core and connect cluster lane trajectories

This commit is contained in:
que01 committed 2026-09-14 10:47:25 +08:00
1 parent 695bf21a84
commit 6a8f026d12
12 files changed
+527 -83

No files matched your search

+69 -37
View File
@@ -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 };
+242 -30
View File
@@ -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;