feat(junction): establish stable complex junction structure
This commit is contained in:
1 parent
bd8b55e58b
commit
0a5a229ce3
22 files changed
+1386
-125
No files matched your search
+114
-27
@@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const { topologyIdentity, structureFromTopology } = require('./junction-topology');
|
||||
const { convertGeoJson, boundsOf } = require('../reference/gaode');
|
||||
const metricsCache = new WeakMap();
|
||||
const CORNER_FILLET_SEGMENTS = 12;
|
||||
@@ -12,6 +13,82 @@ const SIDEWALK_WIDTH_METERS = 2;
|
||||
// past that end and let the two overlap rather than chase an exact seam.
|
||||
const SIDEWALK_CORNER_OVERRUN_METERS = 6;
|
||||
|
||||
// Geometry and the durable structure use this single external topology.
|
||||
function resolveComplexJunctionTopology(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);
|
||||
// Source topology is authoritative; geometric proximity is only a fallback
|
||||
// for legacy plans with no source-node metadata.
|
||||
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),
|
||||
});
|
||||
}
|
||||
}
|
||||
// Stable source ordering makes heading grouping independent of plan/road order.
|
||||
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;
|
||||
}
|
||||
}
|
||||
for (let index = 0; index < arms.length; index += 1)
|
||||
arms[index].cornerKey = `corner:${arms[index].key}>${arms[(index + 1) % arms.length].key}`;
|
||||
return { cluster, nodeIds: [...nodeIds].sort(), carriageways, arms };
|
||||
}
|
||||
|
||||
function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
const nodeIds = new Set(cluster.nodeIds.map(String));
|
||||
const nodes = cluster.nodeIds.map((id) => helpers.junctionPlans.get(String(id))?.node).filter(Boolean);
|
||||
@@ -33,20 +110,9 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
(sum, point) => [sum[0] + point[0] / nodes.length, sum[1] + point[1] / nodes.length],
|
||||
[0, 0],
|
||||
);
|
||||
const approaches = [];
|
||||
const carriageways = [];
|
||||
for (const [nodeId, plan] of helpers.junctionPlans) {
|
||||
if (!nodeIds.has(String(nodeId))) continue;
|
||||
for (const approach of plan.approaches) {
|
||||
const endpoint = approach.line.at(-1);
|
||||
if (nodes.some((node) => node !== plan.node && helpers.distanceMeters(endpoint, node) < 4)) continue;
|
||||
const heading = helpers.headingAtEndpoint(approach.line);
|
||||
const length = helpers.lineLengthMeters(approach.line);
|
||||
carriageways.push({ nodeId, approach, plan, heading, length });
|
||||
if (approaches.some((item) => Math.abs(normalizeHeading(item.heading - heading)) < 20)) continue;
|
||||
approaches.push({ nodeId, approach, plan, heading, length });
|
||||
}
|
||||
}
|
||||
const topology = resolveComplexJunctionTopology(model, cluster, helpers);
|
||||
const { carriageways, arms } = topology;
|
||||
const approaches = arms.map((arm) => arm.representative);
|
||||
if (approaches.length < 3)
|
||||
return {
|
||||
features: [],
|
||||
@@ -62,18 +128,7 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
],
|
||||
};
|
||||
const { calibration, coreRadius } = complexJunctionMetrics(cluster);
|
||||
const sorted = [...approaches].sort((a, b) => a.heading - b.heading);
|
||||
const arms = sorted.map((representative) => ({
|
||||
representative,
|
||||
heading: averageHeading(
|
||||
carriageways
|
||||
.filter((candidate) => Math.abs(normalizeHeading(candidate.heading - representative.heading)) < 20)
|
||||
.map((candidate) => candidate.heading),
|
||||
),
|
||||
members: carriageways.filter(
|
||||
(candidate) => Math.abs(normalizeHeading(candidate.heading - representative.heading)) < 20,
|
||||
),
|
||||
}));
|
||||
const sorted = approaches;
|
||||
const shape = classifyJunctionShape(arms, center, helpers);
|
||||
if (shape.kind === 'unsupported')
|
||||
return {
|
||||
@@ -141,6 +196,9 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
type: 'Feature',
|
||||
properties: {
|
||||
native_id: `complex-stop-line:${cluster.id}:${item.approach.segmentId}`,
|
||||
object_key: `stop-line:${item.key}`,
|
||||
arm_key: item.armKey,
|
||||
carriageway_key: item.key,
|
||||
cluster_id: cluster.id,
|
||||
kind: 'complex-stop-line',
|
||||
road_id: incomingRoad.id,
|
||||
@@ -223,6 +281,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
type: 'Feature',
|
||||
properties: {
|
||||
native_id: `complex-crosswalk:${cluster.id}:${item.nodeId}:${item.approach.segmentId}:${stripe + 1}`,
|
||||
object_key: `crossing:${arm.key}`,
|
||||
arm_key: arm.key,
|
||||
cluster_id: cluster.id,
|
||||
kind: 'complex-crosswalk',
|
||||
crossing_node_id: item.nodeId,
|
||||
@@ -290,6 +350,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
native_id: `complex-corner-island:${cluster.id}:${index + 1}`,
|
||||
cluster_id: cluster.id,
|
||||
kind: 'complex-corner-island',
|
||||
object_key: `island:${first.cornerKey}`,
|
||||
corner_key: first.cornerKey,
|
||||
corner_index: index + 1,
|
||||
from_heading: first.heading,
|
||||
to_heading: second.heading,
|
||||
@@ -332,6 +394,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
native_id: `complex-corner-crosswalk:${cluster.id}:${index + 1}:${stripe + 1}`,
|
||||
cluster_id: cluster.id,
|
||||
kind: 'complex-corner-crosswalk',
|
||||
object_key: `crossing:${first.cornerKey}`,
|
||||
corner_key: first.cornerKey,
|
||||
corner_index: index + 1,
|
||||
direction: bisector,
|
||||
radial_distance_m: stripeRadius,
|
||||
@@ -394,6 +458,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
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,
|
||||
@@ -453,6 +519,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
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,
|
||||
@@ -530,6 +598,9 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
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(
|
||||
@@ -562,7 +633,18 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
|
||||
),
|
||||
]
|
||||
: [];
|
||||
const allFeatures = [...features, ...islands, ...sidewalkCorners, ...crosswalks, ...stopLines];
|
||||
const structure = structureFromTopology(topology, shape, center, allFeatures);
|
||||
for (const feature of allFeatures) {
|
||||
feature.properties.junction_key = structure.junctionKey;
|
||||
feature.properties.topology_fingerprint = structure.topologyFingerprint;
|
||||
}
|
||||
// Persist the compiler authority with a generated road surface, including the
|
||||
// supported-shape case where only the central polygon had to be skipped.
|
||||
const carrier = features.find((feature) => feature.properties.kind === 'complex-core') || features[0];
|
||||
if (carrier) carrier.properties.junction_structure = structure;
|
||||
return {
|
||||
structure,
|
||||
features,
|
||||
islands: [...islands, ...sidewalkCorners],
|
||||
crosswalks,
|
||||
@@ -907,4 +989,9 @@ function interpolateCoordinate(first, second, ratio) {
|
||||
return [first[0] + (second[0] - first[0]) * ratio, first[1] + (second[1] - first[1]) * ratio];
|
||||
}
|
||||
|
||||
module.exports = { buildComplexJunctionGeometry, classifyJunctionShape, complexJunctionMetrics };
|
||||
module.exports = {
|
||||
resolveComplexJunctionTopology,
|
||||
buildComplexJunctionGeometry,
|
||||
classifyJunctionShape,
|
||||
complexJunctionMetrics,
|
||||
};
|
||||
@@ -1093,6 +1093,8 @@ function makeJunctionHandles(model, junctionData, constraints) {
|
||||
*/
|
||||
function selectHandles(handles, model, selection) {
|
||||
if (!selection || !selection.type) return handles;
|
||||
// Cluster object identities are read-only until their geometry edit path exists.
|
||||
if (selection.type === 'cluster') return [];
|
||||
if (selection.type === 'segment') {
|
||||
const segmentOf = new Map((model.roads || []).map((road) => [road.id, road.segmentId]));
|
||||
const wanted = String(selection.id);
|
||||
|
||||
@@ -11,30 +11,57 @@ function heading(from, to) {
|
||||
return (Math.atan2(to[0] - from[0], to[1] - from[1]) * 180) / Math.PI;
|
||||
}
|
||||
|
||||
function pointOf(feature) {
|
||||
const coordinates = feature?.geometry?.coordinates;
|
||||
if (feature?.geometry?.type === 'Point' && Array.isArray(coordinates)) return coordinates;
|
||||
if (Array.isArray(coordinates?.[0]?.[0])) return coordinates[0][0];
|
||||
if (Array.isArray(coordinates?.[0])) return coordinates[0];
|
||||
return null;
|
||||
}
|
||||
|
||||
function projectJunctionStructure({
|
||||
model = {},
|
||||
layers = {},
|
||||
trafficSignals = null,
|
||||
shape = null,
|
||||
junctionKey = null,
|
||||
junctionRef = undefined,
|
||||
} = {}) {
|
||||
if (junctionRef === null) return null;
|
||||
const roads = Array.isArray(model.roads) ? model.roads : [];
|
||||
const endpoints = Array.isArray(model.endpoints) ? model.endpoints : [];
|
||||
const core = featureCollection(layers.intersectionSurface).find(
|
||||
(feature) => feature.properties?.kind === 'complex-core',
|
||||
);
|
||||
const properties = core?.properties || {};
|
||||
const key = String(junctionKey || properties.cluster_id || endpoints[0]?.nodeId || 'junction:area');
|
||||
const center = pointOf(core) || endpoints[0]?.coordinate || [0, 0];
|
||||
const junctionNodeId = String(junctionKey || properties.cluster_id ? endpoints[0]?.nodeId || '' : key);
|
||||
if (junctionRef && !['node', 'cluster'].includes(junctionRef.type))
|
||||
throw new Error('Invalid junction reference type');
|
||||
if (junctionRef?.type === 'cluster') {
|
||||
const carrier = featureCollection(layers.roadSurface || layers.nativeRoadSurface || layers.road_surface).find(
|
||||
(feature) =>
|
||||
String(feature.properties?.cluster_id) === String(junctionRef.id) && feature.properties?.junction_structure,
|
||||
);
|
||||
if (!carrier) return null;
|
||||
const structure = buildJunctionStructure(carrier.properties.junction_structure);
|
||||
const nodeIds = new Set(structure.provenance?.nodeIds || []);
|
||||
const signals = new Map();
|
||||
for (const feature of featureCollection(trafficSignals?.assemblies)) {
|
||||
const p = feature.properties || {};
|
||||
const nodeId = p.node_id ?? p.control_id;
|
||||
if (nodeId == null || !nodeIds.has(String(nodeId)) || !p.signal_uid) continue;
|
||||
const uid = String(p.signal_uid);
|
||||
if (signals.has(uid)) {
|
||||
signals.get(uid).capability.reason = 'source-ambiguous';
|
||||
continue;
|
||||
}
|
||||
signals.set(uid, {
|
||||
key: `cluster:${encodeURIComponent(junctionRef.id)}:signal:${encodeURIComponent(uid)}`,
|
||||
kind: 'signal',
|
||||
label: '信号灯',
|
||||
geometryRef: uid,
|
||||
editable: false,
|
||||
capability: { editable: false, reason: 'complex-geometry-editing-not-implemented' },
|
||||
provenance: { nodeIds: [String(nodeId)], featureIds: [uid] },
|
||||
});
|
||||
}
|
||||
return buildJunctionStructure({
|
||||
...structure,
|
||||
facilities: [...structure.facilities, ...signals.values()].sort((a, b) => a.key.localeCompare(b.key)),
|
||||
});
|
||||
}
|
||||
const properties = {};
|
||||
const key = String(junctionRef?.id || junctionKey || endpoints[0]?.nodeId || 'junction:area');
|
||||
const junctionNodeId = key;
|
||||
if ((junctionRef || junctionKey) && !endpoints.some((endpoint) => String(endpoint.nodeId) === key)) return null;
|
||||
const center = endpoints.find((endpoint) => String(endpoint.nodeId) === key)?.coordinate || [0, 0];
|
||||
const endpointByNode = new Map();
|
||||
for (const endpoint of endpoints) endpointByNode.set(String(endpoint.nodeId), endpoint);
|
||||
const arms = roads
|
||||
@@ -48,7 +75,13 @@ function projectJunctionStructure({
|
||||
return {
|
||||
key: `road-arm:${road.id || index + 1}`,
|
||||
label: String(road.tags?.name || road.name || `道路 ${index + 1}`),
|
||||
heading: heading(center, endpoint.coordinate),
|
||||
heading:
|
||||
road.centerline?.length > 1
|
||||
? heading(
|
||||
center,
|
||||
String(road.sourceNodeIds?.[0]) === junctionNodeId ? road.centerline[1] : road.centerline.at(-2),
|
||||
)
|
||||
: heading(center, endpoint.coordinate),
|
||||
directionality:
|
||||
road.direction === 'oneway' || road.direction === 'one-way'
|
||||
? 'one-way'
|
||||
@@ -64,41 +97,53 @@ function projectJunctionStructure({
|
||||
sourceRoadId: String(road.id || ''),
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => a.heading - b.heading);
|
||||
const corners =
|
||||
arms.length > 1
|
||||
? arms.map((arm, index) => {
|
||||
const next = arms[(index + 1) % arms.length];
|
||||
return {
|
||||
key: `corner:${index + 1}`,
|
||||
key: `corner:${arm.key}>${next.key}`,
|
||||
label: `角部 ${index + 1}`,
|
||||
fromArmKey: arm.key,
|
||||
toArmKey: next.key,
|
||||
geometryRef: `${key}:corner:${index + 1}`,
|
||||
geometryRef: `corner:${arm.key}>${next.key}`,
|
||||
};
|
||||
})
|
||||
: [];
|
||||
const inScope = (feature) => {
|
||||
if (!junctionRef && !junctionKey) return true;
|
||||
const p = feature.properties || {};
|
||||
if (p.cluster_id) return false;
|
||||
const node = p.node_id ?? p.osm_node_id ?? p.crossing_node_id;
|
||||
if (node !== undefined) return String(node) === junctionNodeId;
|
||||
return p.road_id && arms.some((arm) => arm.sourceRoadId === String(p.road_id));
|
||||
};
|
||||
const facilities = [];
|
||||
const crossingKeys = [];
|
||||
for (const [kind, collection] of [
|
||||
['crossing', layers.crosswalks],
|
||||
['stop-line', layers.vehicleStopLines],
|
||||
]) {
|
||||
featureCollection(collection).forEach((feature, index) => {
|
||||
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
|
||||
facilities.push({
|
||||
key: String(id),
|
||||
kind,
|
||||
label: kind === 'crossing' ? `人行横道 ${index + 1}` : `停止线 ${index + 1}`,
|
||||
geometryRef: String(id),
|
||||
featureCollection(collection)
|
||||
.filter(inScope)
|
||||
.forEach((feature, index) => {
|
||||
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
|
||||
facilities.push({
|
||||
key: String(id),
|
||||
kind,
|
||||
label: kind === 'crossing' ? `人行横道 ${index + 1}` : `停止线 ${index + 1}`,
|
||||
geometryRef: String(id),
|
||||
});
|
||||
});
|
||||
if (kind === 'crossing') crossingKeys.push(String(id));
|
||||
});
|
||||
}
|
||||
for (const [index, feature] of featureCollection(trafficSignals?.assemblies).entries()) {
|
||||
for (const [index, feature] of featureCollection(trafficSignals?.assemblies).filter(inScope).entries()) {
|
||||
const id = feature.properties?.signal_uid || feature.properties?.id || `signal:${index + 1}`;
|
||||
const signalNode = feature.properties?.node_id || feature.properties?.control_id;
|
||||
const related = crossingKeys.find((crossingKey) => String(crossingKey).includes(String(signalNode || '')));
|
||||
const related = featureCollection(layers.crosswalks)
|
||||
.filter(inScope)
|
||||
.find((crossing) => signalNode != null && String(crossing.properties?.crossing_node_id) === String(signalNode))
|
||||
?.properties?.native_id;
|
||||
facilities.push({
|
||||
key: String(id),
|
||||
kind: 'signal',
|
||||
@@ -112,21 +157,23 @@ function projectJunctionStructure({
|
||||
['median', layers.medians],
|
||||
['sidewalk-turn', layers.sidewalkTurns],
|
||||
]) {
|
||||
featureCollection(collection).forEach((feature, index) => {
|
||||
if (feature.properties?.kind !== kind) return;
|
||||
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
|
||||
facilities.push({
|
||||
key: String(id),
|
||||
kind,
|
||||
label:
|
||||
kind === 'island'
|
||||
? `导流岛 ${index + 1}`
|
||||
: kind === 'median'
|
||||
? `中央分隔 ${index + 1}`
|
||||
: `人行道转角 ${index + 1}`,
|
||||
geometryRef: String(id),
|
||||
featureCollection(collection)
|
||||
.filter(inScope)
|
||||
.forEach((feature, index) => {
|
||||
if (feature.properties?.kind !== kind) return;
|
||||
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
|
||||
facilities.push({
|
||||
key: String(id),
|
||||
kind,
|
||||
label:
|
||||
kind === 'island'
|
||||
? `导流岛 ${index + 1}`
|
||||
: kind === 'median'
|
||||
? `中央分隔 ${index + 1}`
|
||||
: `人行道转角 ${index + 1}`,
|
||||
geometryRef: String(id),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
const shapeKind =
|
||||
shape?.kind ||
|
||||
@@ -134,6 +181,7 @@ function projectJunctionStructure({
|
||||
(arms.length === 3 ? 't-junction' : arms.length >= 5 ? 'multi-arm' : arms.length === 4 ? 'cross' : 'unsupported');
|
||||
return buildJunctionStructure({
|
||||
junctionKey: key,
|
||||
junctionRef: { type: 'node', id: junctionNodeId },
|
||||
label: properties.shape_label || '路口',
|
||||
center,
|
||||
shape: {
|
||||
@@ -151,7 +199,7 @@ function projectJunctionStructure({
|
||||
|
||||
function standardsDiagnostics(structure, profile = CN_URBAN_DEFAULT_PROFILE) {
|
||||
const diagnostics = [];
|
||||
for (const arm of structure.arms) {
|
||||
for (const arm of structure?.arms || []) {
|
||||
const rule = profile.rules.find((item) => item.id === 'effective-carriageway-width');
|
||||
const severity = evaluateRange(arm.carriageway.effectiveWidthMeters, rule);
|
||||
diagnostics.push({
|
||||
|
||||
@@ -35,6 +35,34 @@ function overrideState(input = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function metadata(input) {
|
||||
const result = {};
|
||||
if (input.provenance !== undefined) {
|
||||
if (!input.provenance || typeof input.provenance !== 'object' || Array.isArray(input.provenance))
|
||||
throw new Error('Junction provenance must be an object');
|
||||
for (const field of ['nodeIds', 'segmentIds', 'roadIds', 'osmWayIds', 'carriagewayKeys', 'armKeys', 'featureIds']) {
|
||||
const values = input.provenance[field];
|
||||
if (values !== undefined && (!Array.isArray(values) || values.some((value) => typeof value !== 'string')))
|
||||
throw new Error(`Junction provenance.${field} must be an array of strings`);
|
||||
}
|
||||
result.provenance = JSON.parse(JSON.stringify(input.provenance));
|
||||
}
|
||||
if (input.capability !== undefined) {
|
||||
if (
|
||||
typeof input.capability?.editable !== 'boolean' ||
|
||||
(input.capability.reason !== undefined &&
|
||||
(typeof input.capability.reason !== 'string' || !input.capability.reason.trim())) ||
|
||||
(!input.capability.editable && !input.capability.reason)
|
||||
)
|
||||
throw new Error('Junction readonly capability requires a reason');
|
||||
result.capability = {
|
||||
editable: input.capability.editable,
|
||||
...(input.capability.reason ? { reason: String(input.capability.reason) } : {}),
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function normalizeRoadArm(input, index) {
|
||||
const key = objectKey(input.key, `road-arm:${index + 1}`);
|
||||
const label = readableLabel(input.label, `道路 ${index + 1}`);
|
||||
@@ -43,9 +71,22 @@ function normalizeRoadArm(input, index) {
|
||||
const carriageway = input.carriageway || {};
|
||||
const normalized = {
|
||||
key,
|
||||
...metadata(input),
|
||||
label,
|
||||
heading: finiteNumber(input.heading ?? 0, 'arm heading'),
|
||||
directionality,
|
||||
...(input.sourceRoadId ? { sourceRoadId: String(input.sourceRoadId) } : {}),
|
||||
...(input.carriageways
|
||||
? {
|
||||
carriageways: input.carriageways.map((item) => ({
|
||||
key: objectKey(item.key),
|
||||
geometryRef: objectKey(item.geometryRef, item.key),
|
||||
...metadata(item),
|
||||
laneCount: finiteNumber(item.laneCount, 'carriageway lane count', { integer: true, minimum: 0 }),
|
||||
effectiveWidthMeters: finiteNumber(item.effectiveWidthMeters, 'carriageway width', { minimum: 0 }),
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
carriageway: {
|
||||
...(carriageway.laneCount === undefined
|
||||
? {}
|
||||
@@ -77,6 +118,7 @@ function normalizeCorner(input, index) {
|
||||
if (fromArmKey === toArmKey) throw new Error(`Junction corner ${key} must connect two different road arms`);
|
||||
return {
|
||||
key,
|
||||
...metadata(input),
|
||||
label: readableLabel(input.label, `角部 ${index + 1}`),
|
||||
fromArmKey,
|
||||
toArmKey,
|
||||
@@ -95,6 +137,7 @@ function normalizeFacility(input, index) {
|
||||
const key = objectKey(input.key, `${kind}:${index + 1}`);
|
||||
return {
|
||||
key,
|
||||
...metadata(input),
|
||||
kind,
|
||||
label: readableLabel(input.label, kind === 'crossing' ? `人行横道 ${index + 1}` : `设施 ${index + 1}`),
|
||||
...(input.armKey ? { armKey: String(input.armKey) } : {}),
|
||||
@@ -121,6 +164,10 @@ function buildJunctionStructure(input = {}) {
|
||||
const kind = String(shape.kind || 'unsupported');
|
||||
if (!SHAPE_KINDS.has(kind)) throw new Error(`Unsupported junction shape kind: ${kind}`);
|
||||
const arms = (input.arms || []).map(normalizeRoadArm);
|
||||
assertUniqueKeys(
|
||||
arms.flatMap((arm) => arm.carriageways || []),
|
||||
'carriageway',
|
||||
);
|
||||
const armKeys = assertUniqueKeys(arms, 'road arm');
|
||||
const corners = (input.corners || []).map(normalizeCorner);
|
||||
const cornerKeys = assertUniqueKeys(corners, 'corner');
|
||||
@@ -141,7 +188,15 @@ function buildJunctionStructure(input = {}) {
|
||||
finiteNumber(effectiveArmCount, 'effective arm count', { integer: true, minimum: 0 });
|
||||
if (effectiveArmCount !== arms.length)
|
||||
throw new Error('Junction effective arm count must match the supplied road arms');
|
||||
if (
|
||||
input.junctionRef &&
|
||||
(!['node', 'cluster'].includes(input.junctionRef.type) || !String(input.junctionRef.id || '').trim())
|
||||
)
|
||||
throw new Error('Junction reference requires a node or cluster type and id');
|
||||
return {
|
||||
...metadata(input),
|
||||
...(input.junctionRef ? { junctionRef: { type: input.junctionRef.type, id: String(input.junctionRef.id) } } : {}),
|
||||
...(input.topologyFingerprint ? { topologyFingerprint: String(input.topologyFingerprint) } : {}),
|
||||
schema: JUNCTION_STRUCTURE_SCHEMA,
|
||||
junctionKey: objectKey(input.junctionKey, 'junction:unknown'),
|
||||
label: readableLabel(input.label, '未命名路口'),
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
'use strict';
|
||||
|
||||
const { createHash } = require('crypto');
|
||||
const { buildJunctionStructure } = require('./junction-structure');
|
||||
|
||||
function topologyIdentity(item) {
|
||||
return [item.nodeId, item.approach.segmentId || '', ...item.approach.roadIds.map(String).sort()]
|
||||
.map(encodeURIComponent)
|
||||
.join('/');
|
||||
}
|
||||
|
||||
function sourceOf(item) {
|
||||
return {
|
||||
nodeIds: [String(item.nodeId)],
|
||||
segmentIds: [String(item.approach.segmentId || '')],
|
||||
roadIds: item.approach.roadIds.map(String).sort(),
|
||||
osmWayIds: [...new Set(item.roads.flatMap((road) => (road.osmWayIds || []).map(String)))].sort(),
|
||||
};
|
||||
}
|
||||
|
||||
function capability(reason = 'complex-geometry-editing-not-implemented') {
|
||||
return { editable: false, reason };
|
||||
}
|
||||
|
||||
function structureFromTopology(topology, shape, center, features) {
|
||||
const { cluster } = topology;
|
||||
const arms = topology.arms.map((arm, index) => {
|
||||
const carriageways = arm.members.map((item) => ({
|
||||
key: item.key,
|
||||
geometryRef: item.key,
|
||||
provenance: sourceOf(item),
|
||||
capability: capability(
|
||||
item.ambiguousSource
|
||||
? 'source-ambiguous'
|
||||
: item.approach.segmentId &&
|
||||
item.roads.length > 0 &&
|
||||
item.roads.length === item.approach.roadIds.length &&
|
||||
item.roads.every((road) => road.sourceNodeIds?.length >= 2)
|
||||
? undefined
|
||||
: 'source-missing',
|
||||
),
|
||||
laneCount: item.roads.reduce((sum, road) => sum + (Number(road.laneCount) || 0), 0),
|
||||
effectiveWidthMeters: item.approach.widthMeters,
|
||||
}));
|
||||
return {
|
||||
key: arm.key,
|
||||
label: arm.members[0].roads[0]?.tags?.name || `道路 ${index + 1}`,
|
||||
heading: arm.heading,
|
||||
directionality: arm.members.some((item) => item.roads.length > 1) ? 'two-way' : 'one-way',
|
||||
carriageway: {
|
||||
laneCount: carriageways.reduce((sum, item) => sum + item.laneCount, 0),
|
||||
effectiveWidthMeters: carriageways.reduce((sum, item) => sum + item.effectiveWidthMeters, 0),
|
||||
},
|
||||
carriageways,
|
||||
geometryRef: arm.key,
|
||||
provenance: { carriagewayKeys: carriageways.map((item) => item.key) },
|
||||
capability: capability(),
|
||||
};
|
||||
});
|
||||
const corners =
|
||||
topology.arms.length > 1
|
||||
? topology.arms.map((arm, index) => ({
|
||||
key: arm.cornerKey,
|
||||
label: `角部 ${index + 1}`,
|
||||
fromArmKey: arm.key,
|
||||
toArmKey: topology.arms[(index + 1) % topology.arms.length].key,
|
||||
geometryRef: arm.cornerKey,
|
||||
provenance: { armKeys: [arm.key, topology.arms[(index + 1) % topology.arms.length].key] },
|
||||
capability: capability(),
|
||||
}))
|
||||
: [];
|
||||
const facilitiesByKey = new Map();
|
||||
for (const feature of features) {
|
||||
const p = feature.properties;
|
||||
const kind = {
|
||||
'complex-crosswalk': 'crossing',
|
||||
'complex-corner-crosswalk': 'crossing',
|
||||
'complex-stop-line': 'stop-line',
|
||||
'complex-corner-island': 'island',
|
||||
'complex-sidewalk-corner': 'sidewalk-turn',
|
||||
}[p.kind];
|
||||
if (!kind || !p.object_key) continue;
|
||||
if (!facilitiesByKey.has(p.object_key))
|
||||
facilitiesByKey.set(p.object_key, {
|
||||
key: p.object_key,
|
||||
kind,
|
||||
label: `${{ crossing: '人行横道', 'stop-line': '停止线', island: '导流岛', 'sidewalk-turn': '人行道转角' }[kind]}`,
|
||||
geometryRef: p.object_key,
|
||||
...(p.arm_key ? { armKey: p.arm_key } : {}),
|
||||
...(p.corner_key ? { cornerKey: p.corner_key } : {}),
|
||||
...(kind === 'stop-line' && features.some((f) => f.properties.object_key === `crossing:${p.arm_key}`)
|
||||
? { relatedFacilityKey: `crossing:${p.arm_key}` }
|
||||
: {}),
|
||||
editable: false,
|
||||
capability: capability(),
|
||||
provenance: { featureIds: [], ...(p.road_id ? { roadIds: [String(p.road_id)] } : {}) },
|
||||
});
|
||||
facilitiesByKey.get(p.object_key).provenance.featureIds.push(String(p.native_id));
|
||||
}
|
||||
const facilities = [...facilitiesByKey.values()].sort((a, b) => a.key.localeCompare(b.key));
|
||||
for (const facility of facilities) facility.provenance.featureIds.sort();
|
||||
const fingerprint = createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
nodeIds: topology.nodeIds,
|
||||
arms: arms.map((arm) => arm.key).sort(),
|
||||
corners: corners.map((corner) => corner.key).sort(),
|
||||
}),
|
||||
)
|
||||
.digest('hex');
|
||||
return buildJunctionStructure({
|
||||
junctionKey: `cluster:${cluster.id}`,
|
||||
junctionRef: { type: 'cluster', id: String(cluster.id) },
|
||||
label: shape.label,
|
||||
center,
|
||||
topologyFingerprint: fingerprint,
|
||||
provenance: {
|
||||
nodeIds: topology.nodeIds,
|
||||
roadIds: [...new Set(topology.carriageways.flatMap((item) => sourceOf(item).roadIds))].sort(),
|
||||
segmentIds: [...new Set(topology.carriageways.flatMap((item) => sourceOf(item).segmentIds))].sort(),
|
||||
},
|
||||
capability: capability(),
|
||||
shape: { ...shape, effectiveArmCount: arms.length },
|
||||
arms,
|
||||
corners,
|
||||
facilities,
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { topologyIdentity, structureFromTopology };
|
||||
Reference in new issue
Block a user