Files
road-compiler/src/compile/junction-build-plan.js
T

186 lines
7.2 KiB
JavaScript

'use strict';
const { topologyIdentity } = require('./junction-topology');
const MIN_ENTRY_SECTION_METERS = 12;
function normalizeHeading(value) {
return ((((value + 180) % 360) + 360) % 360) - 180;
}
function averageHeading(headings) {
const vector = headings.reduce(
(sum, heading) => {
const radians = (heading * Math.PI) / 180;
return [sum[0] + Math.sin(radians), sum[1] + Math.cos(radians)];
},
[0, 0],
);
return ((Math.atan2(vector[0], vector[1]) * 180) / Math.PI + 360) % 360;
}
function tangentAt(line, station, length, helpers) {
if (!Array.isArray(line) || line.length < 2 || !Number.isFinite(length) || length <= 0) return null;
let walked = 0;
for (let index = 1; index < line.length; index += 1) {
const segmentLength = helpers.distanceMeters(line[index - 1], line[index]);
if (station <= walked + segmentLength || index === line.length - 1)
return helpers.headingAtEndpoint([line[index - 1], line[index]]);
walked += segmentLength;
}
return null;
}
function offsetCoordinate(point, heading, meters) {
if (!point || !Number.isFinite(heading)) return null;
const radians = (heading * Math.PI) / 180;
const lonMeters = 111320 * Math.cos((point[1] * Math.PI) / 180);
return [
point[0] + (Math.sin(radians) * meters) / Math.max(lonMeters, 1e-9),
point[1] + (Math.cos(radians) * meters) / 111320,
];
}
function boundaryAt(point, tangent, widthMeters) {
const halfWidth = Math.max(0, Number(widthMeters) || 0) / 2;
return {
left: offsetCoordinate(point, tangent - 90, halfWidth),
right: offsetCoordinate(point, tangent + 90, halfWidth),
};
}
function interpolate(first, second, ratio) {
return [first[0] + (second[0] - first[0]) * ratio, first[1] + (second[1] - first[1]) * ratio];
}
// Return the first source-polyline station whose actual distance to `center`
// reaches the requested boundary. This intentionally does not project a fixed
// initial heading: curved approaches must terminate where their own geometry
// meets the boundary.
function stationAtDistanceFrom(line, center, radius, helpers) {
if (!center || !Array.isArray(line) || line.length < 2 || !Number.isFinite(radius)) return 0;
let station = 0;
let previousDistance = helpers.distanceMeters(line[0], center);
if (previousDistance >= radius) return 0;
for (let index = 1; index < line.length; index += 1) {
const start = line[index - 1];
const end = line[index];
const segmentLength = helpers.distanceMeters(start, end);
const endDistance = helpers.distanceMeters(end, center);
if (previousDistance < radius && endDistance >= radius) {
let low = 0;
let high = 1;
for (let iteration = 0; iteration < 32; iteration += 1) {
const middle = (low + high) / 2;
if (helpers.distanceMeters(interpolate(start, end, middle), center) < radius) low = middle;
else high = middle;
}
return station + segmentLength * ((low + high) / 2);
}
station += segmentLength;
previousDistance = endDistance;
}
return station;
}
function entrySectionFor(item, helpers) {
const length = item.length;
const line = item.approach.line;
const nearTangent = tangentAt(line, 0, length, helpers);
const farTangent = tangentAt(line, length, length, helpers);
const feasible = Number.isFinite(length) && length >= MIN_ENTRY_SECTION_METERS;
return {
carriagewayKey: item.key,
sourceLine: line,
nearStationMeters: 0,
farStationMeters: length,
entryStationMeters: 0,
nearTangent,
farTangent,
boundaryEndpoints: {
near: boundaryAt(line?.[0] || null, nearTangent, item.approach.widthMeters),
far: boundaryAt(line?.at(-1) || null, farTangent, item.approach.widthMeters),
},
feasibility: feasible ? 'supported' : 'short-approach',
...(feasible ? {} : { reason: 'entry-section-too-short' }),
};
}
// This plan is deliberately limited to source topology and source-polyline
// sections. It is shared by geometry and edit identity, while later work can
// add computed shared boundaries without making either layer guess arm order.
function resolveJunctionBuildPlan(model, cluster, helpers) {
const nodeIds = new Set(cluster.nodeIds.map(String));
const nodes = [...nodeIds]
.sort()
.map((id) => helpers.junctionPlans.get(id)?.node)
.filter(Boolean);
const carriageways = [];
for (const [nodeId, plan] of helpers.junctionPlans) {
if (!nodeIds.has(String(nodeId))) continue;
for (const approach of plan.approaches || []) {
const roads = approach.roadIds.map((id) => model.roads.find((road) => road.id === id)).filter(Boolean);
const sourced = roads.filter((road) => road.sourceNodeIds?.length >= 2);
const internal = sourced.length
? sourced.every(
(road) => nodeIds.has(String(road.sourceNodeIds[0])) && nodeIds.has(String(road.sourceNodeIds.at(-1))),
)
: nodes.some((node) => node !== plan.node && helpers.distanceMeters(approach.line.at(-1), node) < 4);
if (internal) continue;
carriageways.push({
nodeId: String(nodeId),
approach,
plan,
roads,
heading: helpers.headingAtEndpoint(approach.line),
length: helpers.lineLengthMeters(approach.line),
});
}
}
carriageways.sort((a, b) => topologyIdentity(a).localeCompare(topologyIdentity(b)));
const duplicateSources = new Set();
const seenSources = new Set();
for (const item of carriageways) {
const identity = topologyIdentity(item);
if (seenSources.has(identity)) duplicateSources.add(identity);
seenSources.add(identity);
}
for (let index = carriageways.length - 1; index > 0; index -= 1)
if (topologyIdentity(carriageways[index]) === topologyIdentity(carriageways[index - 1]))
carriageways.splice(index, 1);
const arms = [];
for (const item of carriageways) {
item.ambiguousSource = duplicateSources.has(topologyIdentity(item));
let arm = arms.find(
(candidate) => Math.abs(normalizeHeading(candidate.representative.heading - item.heading)) < 20,
);
if (!arm) {
arm = { representative: item, members: [] };
arms.push(arm);
}
arm.members.push(item);
}
for (const arm of arms) arm.heading = averageHeading(arm.members.map((item) => item.heading));
for (const item of carriageways)
if (arms.filter((arm) => Math.abs(normalizeHeading(arm.representative.heading - item.heading)) < 20).length > 1)
item.ambiguousSource = true;
arms.sort(
(a, b) =>
a.heading - b.heading || topologyIdentity(a.representative).localeCompare(topologyIdentity(b.representative)),
);
const scope = `cluster:${encodeURIComponent(cluster.id)}`;
for (const arm of arms) {
arm.key = `${scope}:arm:${arm.members.map(topologyIdentity).sort().join('|')}`;
for (const item of arm.members) {
item.key = `${scope}:carriageway:${topologyIdentity(item)}`;
item.armKey = arm.key;
item.entrySection = entrySectionFor(item, helpers);
}
}
for (let index = 0; index < arms.length; index += 1)
arms[index].cornerKey = `corner:${arms[index].key}>${arms[(index + 1) % arms.length].key}`;
return { schema: 'junction-build-plan/v1', cluster, nodeIds: [...nodeIds].sort(), carriageways, arms };
}
module.exports = { MIN_ENTRY_SECTION_METERS, resolveJunctionBuildPlan, stationAtDistanceFrom };