371 lines
16 KiB
JavaScript
371 lines
16 KiB
JavaScript
'use strict';
|
|
|
|
const { union } = require('./junction-polygon-ops');
|
|
|
|
const { solvePavedRegion } = require('./junction-region-solver');
|
|
|
|
const { stationAtDistanceFrom } = require('./junction-build-plan');
|
|
|
|
const { offsetCoordinate, metersAt } = require('../geometry/metric');
|
|
|
|
function pointAtStation(line, station, helpers) {
|
|
let remaining = Math.max(0, station);
|
|
for (let index = 1; index < line.length; index += 1) {
|
|
const length = helpers.distanceMeters(line[index - 1], line[index]);
|
|
if (remaining <= length) {
|
|
const ratio = length ? remaining / length : 0;
|
|
return [
|
|
line[index - 1][0] + (line[index][0] - line[index - 1][0]) * ratio,
|
|
line[index - 1][1] + (line[index][1] - line[index - 1][1]) * ratio,
|
|
];
|
|
}
|
|
remaining -= length;
|
|
}
|
|
return line.at(-1) || null;
|
|
}
|
|
|
|
function tangentAtStation(line, station, helpers) {
|
|
let walked = 0;
|
|
for (let index = 1; index < line.length; index += 1) {
|
|
const length = helpers.distanceMeters(line[index - 1], line[index]);
|
|
if (station <= walked + length || index === line.length - 1)
|
|
return helpers.headingAtEndpoint([line[index - 1], line[index]]);
|
|
walked += length;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function sectionAt(item, radius, center, widthMeters, helpers, explicitStation, edgeOffsets = null) {
|
|
const station = Math.max(
|
|
0,
|
|
Math.min(item.length, explicitStation ?? stationAtDistanceFrom(item.approach.line, center, radius, helpers)),
|
|
);
|
|
const point = pointAtStation(item.approach.line, station, helpers);
|
|
const tangent = tangentAtStation(item.approach.line, station, helpers) + (Number(edgeOffsets?.direction) || 0);
|
|
const halfWidth = Math.max(0, Number(widthMeters) || 0) / 2;
|
|
const leftOffset = Number(edgeOffsets?.left) || 0;
|
|
const rightOffset = Number(edgeOffsets?.right) || 0;
|
|
return {
|
|
stationMeters: station,
|
|
point,
|
|
tangent,
|
|
left: offsetCoordinate(point, tangent - 90, halfWidth + leftOffset),
|
|
right: offsetCoordinate(point, tangent + 90, halfWidth + rightOffset),
|
|
};
|
|
}
|
|
|
|
// The graph currently owns only source-derived entry edges. Core closure is
|
|
// deliberately unresolved until a later stage can distinguish paved links,
|
|
// medians, and exclusion regions from topology alone.
|
|
function buildJunctionBoundaryGraph(topology, center, radii, helpers, exclusionRegions = []) {
|
|
const sections = topology.carriageways.map((item) => {
|
|
const outerRadius = radii.outerRadiusFor(item);
|
|
const innerRadius = radii.innerRadiusFor(item);
|
|
const outerWidthMeters = Number(item.approach.sourceWidthMeters) || item.approach.widthMeters;
|
|
const innerWidthMeters = item.approach.widthMeters;
|
|
const positionOffset = Number(item.approach.positionOffsetMeters) || 0;
|
|
const outer = sectionAt(item, outerRadius, center, outerWidthMeters, helpers, undefined);
|
|
const requestedTransition = Number.isFinite(item.approach.transitionLengthMeters)
|
|
? Math.max(0, item.approach.transitionLengthMeters)
|
|
: null;
|
|
const edgeOffsets = {
|
|
left: item.approach.leftEdgeOffsetMeters,
|
|
right: item.approach.rightEdgeOffsetMeters,
|
|
direction: item.approach.directionOffsetDegrees,
|
|
};
|
|
const baseInnerStation =
|
|
requestedTransition === null
|
|
? stationAtDistanceFrom(item.approach.line, center, innerRadius, helpers)
|
|
: outer.stationMeters - requestedTransition;
|
|
const inner = sectionAt(
|
|
item,
|
|
innerRadius,
|
|
center,
|
|
innerWidthMeters,
|
|
helpers,
|
|
baseInnerStation + positionOffset,
|
|
edgeOffsets,
|
|
);
|
|
const key = `boundary:${item.key}`;
|
|
const sectionRing = [outer.right, inner.right, inner.left, outer.left, outer.right];
|
|
const exclusion = exclusionRegions.find((region) => ringsOverlap(region.ring, sectionRing));
|
|
const ringFinite = sectionRing.every((coordinate) => coordinate?.every(Number.isFinite));
|
|
const ringArea = ringFinite ? Math.abs(signedArea(sectionRing)) : 0;
|
|
const ringStatus = !ringFinite || ringArea < 1e-14 || ringSelfIntersects(sectionRing) ? 'invalid' : 'supported';
|
|
return {
|
|
key,
|
|
carriagewayKey: item.key,
|
|
exclusionStatus: exclusion ? 'overlaps-known-region' : 'clear',
|
|
...(exclusion ? { exclusionRegionId: String(exclusion.id ?? '') } : {}),
|
|
armKey: item.armKey,
|
|
outerWidthMeters,
|
|
innerWidthMeters,
|
|
transitionMeters: Math.max(0, outer.stationMeters - inner.stationMeters),
|
|
transitionStatus:
|
|
Math.abs(baseInnerStation + positionOffset - inner.stationMeters) > 1e-6
|
|
? 'insufficient-source-length'
|
|
: outer.stationMeters - inner.stationMeters > 1e-6
|
|
? 'supported'
|
|
: 'insufficient-source-length',
|
|
outer,
|
|
inner,
|
|
ring: sectionRing,
|
|
ringStatus,
|
|
edgeRefs: {
|
|
left: `${key}:left`,
|
|
right: `${key}:right`,
|
|
outer: `${key}:outer`,
|
|
inner: `${key}:inner`,
|
|
},
|
|
};
|
|
});
|
|
const edges = sections.flatMap((section) => [
|
|
{ key: section.edgeRefs.left, from: section.outer.left, to: section.inner.left, owner: section.carriagewayKey },
|
|
{ key: section.edgeRefs.right, from: section.inner.right, to: section.outer.right, owner: section.carriagewayKey },
|
|
{ key: section.edgeRefs.outer, from: section.outer.right, to: section.outer.left, owner: section.carriagewayKey },
|
|
{ key: section.edgeRefs.inner, from: section.inner.left, to: section.inner.right, owner: section.carriagewayKey },
|
|
]);
|
|
return {
|
|
schema: 'junction-boundary-graph/v1',
|
|
status: 'entry-sections-only',
|
|
sections,
|
|
edges,
|
|
exclusionRegions: exclusionRegions.filter((region) => Array.isArray(region.ring) && region.ring.length >= 4),
|
|
unresolvedClosures: topology.arms.map((arm) => arm.cornerKey),
|
|
};
|
|
}
|
|
|
|
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 signedArea(ring) {
|
|
return ring.slice(1).reduce((area, point, index) => area + ring[index][0] * point[1] - point[0] * ring[index][1], 0);
|
|
}
|
|
|
|
function pointInRing(point, ring) {
|
|
return ring.slice(1).reduce((inside, candidate, index) => {
|
|
const previous = ring[index];
|
|
const crosses = previous[1] > point[1] !== candidate[1] > point[1];
|
|
return crosses &&
|
|
point[0] < ((candidate[0] - previous[0]) * (point[1] - previous[1])) / (candidate[1] - previous[1]) + previous[0]
|
|
? !inside
|
|
: inside;
|
|
}, false);
|
|
}
|
|
|
|
function segmentsIntersect(first, second, third, fourth) {
|
|
// Orientation alone treats all collinear segments as intersecting, even
|
|
// when their finite extents are disjoint.
|
|
if (
|
|
Math.max(first[0], second[0]) < Math.min(third[0], fourth[0]) ||
|
|
Math.max(third[0], fourth[0]) < Math.min(first[0], second[0]) ||
|
|
Math.max(first[1], second[1]) < Math.min(third[1], fourth[1]) ||
|
|
Math.max(third[1], fourth[1]) < Math.min(first[1], second[1])
|
|
)
|
|
return false;
|
|
const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
|
const firstSide = cross(first, second, third);
|
|
const secondSide = cross(first, second, fourth);
|
|
const thirdSide = cross(third, fourth, first);
|
|
const fourthSide = cross(third, fourth, second);
|
|
return (
|
|
((firstSide >= 0 && secondSide <= 0) || (firstSide <= 0 && secondSide >= 0)) &&
|
|
((thirdSide >= 0 && fourthSide <= 0) || (thirdSide <= 0 && fourthSide >= 0))
|
|
);
|
|
}
|
|
|
|
function ringsOverlap(first, second) {
|
|
return (
|
|
first.slice(0, -1).some((point) => pointInRing(point, second)) ||
|
|
second.slice(0, -1).some((point) => pointInRing(point, first)) ||
|
|
first
|
|
.slice(1)
|
|
.some((point, index) =>
|
|
second.slice(1).some((other, otherIndex) => segmentsIntersect(first[index], point, second[otherIndex], other)),
|
|
)
|
|
);
|
|
}
|
|
|
|
function coordinateDistanceMeters(first, second) {
|
|
if (!first?.every(Number.isFinite) || !second?.every(Number.isFinite)) return Infinity;
|
|
const { lon, lat } = metersAt((first[1] + second[1]) / 2);
|
|
const east = (second[0] - first[0]) * lon;
|
|
const north = (second[1] - first[1]) * lat;
|
|
return Math.hypot(east, north);
|
|
}
|
|
|
|
// 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.
|
|
// Split at boundary crossings to check complete seam intervals, not samples.
|
|
function segmentCoveredByRing(start, end, ring) {
|
|
const { lon, lat } = metersAt(start[1]);
|
|
const xy = (p) => [(p[0] - start[0]) * lon, (p[1] - start[1]) * lat];
|
|
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);
|
|
}
|
|
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' };
|
|
if (topology.arms.length === 3 && topology.arms.some((arm) => arm.members.length !== 1)) {
|
|
// A short source link between clustered junction nodes can split one
|
|
// physical T arm into parallel carriageways while still describing one
|
|
// continuous paved core. Keep rejecting arbitrary divided T junctions;
|
|
// only a configured cluster with a link that fits inside its core may use
|
|
// the constrained entry-cell union below.
|
|
const coreRadius = Number(topology.cluster?.coreRadiusMeters);
|
|
const shortInternalLink =
|
|
Number.isFinite(coreRadius) &&
|
|
topology.internalRoadIds?.length > 0 &&
|
|
topology.internalLinkLengths?.some((length) => length <= coreRadius * 2) &&
|
|
topology.arms.some(
|
|
(arm) =>
|
|
arm.members.length > 1 &&
|
|
arm.members.every((member) => Number.isFinite(member.length) && member.length > coreRadius * 2),
|
|
);
|
|
if (!shortInternalLink) 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),
|
|
);
|
|
if (!pavedRegion.length) return { status: 'unsupported', reason: 'known-exclusion-region' };
|
|
const hasZeroLengthEdge = ring.slice(1).some((point, index) => {
|
|
const previous = ring[index];
|
|
const dx = point[0] - previous[0];
|
|
const dy = point[1] - previous[1];
|
|
return dx * dx + dy * dy <= 1e-24;
|
|
});
|
|
const pairedEdges = new Map();
|
|
points.forEach((item, index) => {
|
|
if (!pairedEdges.has(item.edgeRef)) pairedEdges.set(item.edgeRef, []);
|
|
pairedEdges.get(item.edgeRef).push(index);
|
|
});
|
|
const paired = [...pairedEdges.values()].every((indexes) => {
|
|
if (indexes.length !== 2) return false;
|
|
return Math.abs(indexes[0] - indexes[1]) === 1 || (indexes[0] === 0 && indexes[1] === points.length - 1);
|
|
});
|
|
if (ring.length < 7 || hasZeroLengthEdge || !paired || Math.abs(signedArea(ring)) < 1e-14 || ringSelfIntersects(ring))
|
|
return { status: 'unsupported', reason: 'core-closure-invalid' };
|
|
const holes = graph.exclusionRegions
|
|
.filter((region) => {
|
|
const boundaryIntersects = ringSelfIntersects([...region.ring]);
|
|
const contained = region.ring.slice(0, -1).every((point) => pointInRing(point, ring));
|
|
const clearOfEntries = graph.sections.every((section) => !ringsOverlap(region.ring, section.ring));
|
|
return region.isHole === true && !boundaryIntersects && contained && clearOfEntries;
|
|
})
|
|
.map((region) => region.ring);
|
|
if (graph.exclusionRegions.some((region) => ringsOverlap(region.ring, ring) && !holes.includes(region.ring)))
|
|
return { status: 'unsupported', reason: 'known-exclusion-region' };
|
|
const seamErrors = graph.sections.map((section) => {
|
|
const leftIndex = ring.findIndex(
|
|
(point) => point[0] === section.inner.left[0] && point[1] === section.inner.left[1],
|
|
);
|
|
const rightIndex = ring.findIndex(
|
|
(point) => point[0] === section.inner.right[0] && point[1] === section.inner.right[1],
|
|
);
|
|
const contiguous =
|
|
leftIndex >= 0 &&
|
|
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);
|
|
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),
|
|
);
|
|
const reverse = Math.max(
|
|
coordinateDistanceMeters(ringLeft, edge.to),
|
|
coordinateDistanceMeters(ringRight, edge.from),
|
|
);
|
|
return { carriagewayKey: section.carriagewayKey, errorMeters: Math.min(forward, reverse) };
|
|
});
|
|
const seamErrorMeters = seamErrors.reduce((maximum, item) => Math.max(maximum, item.errorMeters), 0);
|
|
const connectedEntryCount = seamErrors.filter((item) => Number.isFinite(item.errorMeters)).length;
|
|
return {
|
|
status: 'supported',
|
|
ring,
|
|
holes,
|
|
ringArea: Math.abs(signedArea(ring)) / 2,
|
|
ringSelfIntersects: false,
|
|
sharedEdgeRefs: [...pairedEdges.keys()].sort(),
|
|
closureCount: graph.sections.length,
|
|
connectedEntryCount,
|
|
requiredPavementConnected: connectedEntryCount === graph.sections.length,
|
|
maxSharedSeamErrorMeters: seamErrorMeters,
|
|
sharedSeamErrors: seamErrors,
|
|
};
|
|
}
|
|
|
|
module.exports = { buildJunctionBoundaryGraph, buildCoreClosure, ringsOverlap, segmentCoveredByRing };
|