feat(junction): establish stable complex junction structure

This commit is contained in:
que01 committed 2026-09-08 11:25:57 +08:00
1 parent bd8b55e58b
commit 0a5a229ce3
22 files changed
+1386 -125

No files matched your search

+211
View File
@@ -93,3 +93,214 @@ assert.equal(diagnostics[1].severity, 'warning');
assert.equal(diagnostics[1].objectKey, 'road-arm:road:east');
console.log('junction projection tests passed');
// Real geographic topology survives input and persisted-layer ordering changes.
const fs = require('fs');
const path = require('path');
const { compileRoadModel, compileGeometry } = require('../src/compile/native-road');
const { buildJunctionStructure } = require('../src/compile/junction-structure');
const overrides = { schema: 'native-road-overrides/v1', overrides: [] };
const baseline = compileRoadModel(
fs.readFileSync(path.join(__dirname, 'fixtures/fengshu-er-road.osm'), 'utf8'),
overrides,
);
const cluster = {
id: 'identity',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
};
function compileCluster(input, config) {
return compileGeometry(input, overrides, {
edgeLines: false,
junctionTemplates: { enabled: true, clusters: [config] },
});
}
const layers = compileCluster(baseline, cluster);
const ref = { type: 'cluster', id: cluster.id };
const authoritative = projectJunctionStructure({ model: baseline, layers, junctionRef: ref });
assert.equal(authoritative.arms.length, 5);
assert.equal(authoritative.junctionRef.type, 'cluster');
assert.equal(authoritative.capability.editable, false);
assert.ok(authoritative.arms.every((arm) => arm.carriageways.length && arm.capability.reason));
assert.deepEqual(buildJunctionStructure(JSON.parse(JSON.stringify(authoritative))), authoritative);
assert.throws(
() => buildJunctionStructure({ ...authoritative, provenance: { nodeIds: 'invalid' } }),
/array of strings/,
);
assert.throws(
() => buildJunctionStructure({ ...authoritative, capability: { editable: false, reason: ' ' } }),
/requires a reason/,
);
const reversed = structuredClone(baseline);
reversed.roads.reverse();
reversed.endpoints.reverse();
const reorderedLayers = compileCluster(reversed, { ...cluster, nodeIds: [...cluster.nodeIds].reverse() });
reorderedLayers.roadSurface.features.reverse();
const reordered = projectJunctionStructure({ model: reversed, layers: reorderedLayers, junctionRef: ref });
for (const kind of ['arms', 'corners', 'facilities'])
assert.deepEqual(reordered[kind].map((item) => item.key).sort(), authoritative[kind].map((item) => item.key).sort());
assert.equal(reordered.topologyFingerprint, authoritative.topologyFingerprint);
function closeCoordinates(actual, expected) {
assert.equal(actual.length, expected.length);
actual.forEach((value, index) => {
if (Array.isArray(value)) closeCoordinates(value, expected[index]);
else assert.ok(Math.abs(value - expected[index]) < 1e-9, `${value} != ${expected[index]}`);
});
}
for (const [name, collection] of Object.entries(layers)) {
const originalFeatures = (collection?.features || []).filter((feature) => feature.properties?.object_key);
const recompiledFeatures = new Map(
(reorderedLayers[name]?.features || []).map((feature) => [feature.properties?.native_id, feature]),
);
for (const feature of originalFeatures) {
const recompiled = recompiledFeatures.get(feature.properties.native_id);
assert.ok(recompiled, feature.properties.native_id);
assert.equal(recompiled.properties.object_key, feature.properties.object_key);
closeCoordinates(recompiled.geometry.coordinates, feature.geometry.coordinates);
}
}
assert.equal(
projectJunctionStructure({ model: baseline, layers, junctionRef: { type: 'cluster', id: 'missing' } }),
null,
);
const otherLayers = compileCluster(baseline, { ...cluster, id: 'other' });
const combined = {
roadSurface: {
type: 'FeatureCollection',
features: [...otherLayers.roadSurface.features, ...layers.roadSurface.features],
},
};
assert.equal(projectJunctionStructure({ layers: combined, junctionRef: ref }).junctionKey, 'cluster:identity');
assert.equal(
projectJunctionStructure({ layers: combined, junctionRef: { type: 'cluster', id: 'other' } }).junctionKey,
'cluster:other',
);
const objectKeys = new Set(
[
...authoritative.arms,
...authoritative.corners,
...authoritative.facilities,
...authoritative.arms.flatMap((arm) => arm.carriageways),
].map((item) => item.key),
);
for (const collection of Object.values(layers)) {
for (const feature of collection?.features || []) {
if (feature.properties?.cluster_id !== cluster.id || !feature.properties.object_key) continue;
assert.ok(objectKeys.has(feature.properties.object_key), feature.properties.object_key);
}
}
const sources = authoritative.arms.flatMap((arm) => arm.carriageways).flatMap((item) => item.provenance.roadIds);
for (const id of sources) {
const road = baseline.roads.find((item) => item.id === id);
assert.ok(
!(
cluster.nodeIds.includes(String(road.sourceNodeIds[0])) &&
cluster.nodeIds.includes(String(road.sourceNodeIds.at(-1)))
),
);
}
const removedId = sources[0];
const removed = structuredClone(baseline);
removed.roads = removed.roads.filter((road) => road.id !== removedId);
removed.endpoints = removed.endpoints.filter((endpoint) => endpoint.roadId !== removedId);
const afterRemoval = projectJunctionStructure({ layers: compileCluster(removed, cluster), junctionRef: ref });
assert.notEqual(afterRemoval.topologyFingerprint, authoritative.topologyFingerprint);
assert.ok(
!afterRemoval.arms.flatMap((arm) => arm.carriageways).some((item) => item.provenance.roadIds.includes(removedId)),
);
assert.deepEqual(standardsDiagnostics(null), []);
console.log('complex junction identity and provenance tests passed');
const signalFeatures = [
{ properties: { signal_uid: 'signal:member', control_id: cluster.nodeIds[0] } },
{ properties: { signal_uid: 'signal:node', node_id: cluster.nodeIds[1] } },
{ properties: { signal_uid: `signal:${cluster.nodeIds[0]}`, control_id: 'elsewhere' } },
{ properties: { signal_uid: 'signal:unscoped' } },
];
const withSignals = (features) =>
projectJunctionStructure({ layers, junctionRef: ref, trafficSignals: { assemblies: { features } } });
const signalStructure = withSignals(signalFeatures);
const projectedSignals = signalStructure.facilities.filter((item) => item.kind === 'signal');
assert.equal(projectedSignals.length, 2);
assert.ok(projectedSignals.every((item) => !item.editable && !item.capability.editable));
assert.deepEqual(
projectedSignals.map((item) => item.provenance.featureIds),
[['signal:member'], ['signal:node']],
);
assert.deepEqual(withSignals([...signalFeatures].reverse()), signalStructure);
assert.deepEqual(buildJunctionStructure(JSON.parse(JSON.stringify(signalStructure))), signalStructure);
assert.equal(withSignals([]).facilities.filter((item) => item.kind === 'signal').length, 0);
assert.equal(
withSignals([...signalFeatures, signalFeatures[0]]).facilities.find((item) => item.geometryRef === 'signal:member')
.capability.reason,
'source-ambiguous',
);
const { resolveComplexJunctionTopology, classifyJunctionShape } = require('../src/compile/complex-junction');
const { structureFromTopology } = require('../src/compile/junction-topology');
for (const headings of [
[0, 90, 180],
[0, 90, 180, 270],
[0, 60, 120, 180, 240, 300],
]) {
const syntheticModel = {
roads: headings.map((angle) => ({ id: `road:${angle}`, sourceNodeIds: ['a', `outer:${angle}`], laneCount: 1 })),
};
const approaches = headings.map((angle) => ({
segmentId: `segment:${angle}`,
roadIds: [`road:${angle}`],
widthMeters: 3.5,
line: [
[0, 0],
[Math.sin((angle * Math.PI) / 180) * 30, Math.cos((angle * Math.PI) / 180) * 30],
],
}));
const plans = new Map([
['a', { node: [0, 0], approaches }],
['b', { node: [1, 1], approaches: [] }],
]);
const helpers = {
junctionPlans: plans,
headingAtEndpoint: (line) => (Math.atan2(line[1][0], line[1][1]) * 180) / Math.PI,
lineLengthMeters: () => 30,
distanceMeters: (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]),
};
const topology = resolveComplexJunctionTopology(syntheticModel, { id: 'synthetic', nodeIds: ['a', 'b'] }, helpers);
assert.equal(topology.arms.length, headings.length);
const shape = classifyJunctionShape(topology.arms, [0, 0], helpers);
assert.equal(structureFromTopology(topology, shape, [0, 0], []).shape.effectiveArmCount, headings.length);
if (headings.length === 4) {
approaches[0].line[1] = [0, 50];
const offset = resolveComplexJunctionTopology(syntheticModel, { id: 'synthetic', nodeIds: ['a', 'b'] }, helpers);
const offsetShape = classifyJunctionShape(offset.arms, [0, 0], helpers);
assert.equal(offsetShape.kind, 'offset-cross');
const offsetStructure = structureFromTopology(offset, offsetShape, [0, 0], []);
assert.equal(offsetStructure.arms.length, 4);
assert.deepEqual(
offsetStructure.arms.map((arm) => arm.key),
structureFromTopology(topology, shape, [0, 0], []).arms.map((arm) => arm.key),
);
}
// Duplicate provenance never invents another editable object.
approaches.push(approaches[0]);
const duplicate = resolveComplexJunctionTopology(syntheticModel, { id: 'synthetic', nodeIds: ['a', 'b'] }, helpers);
const duplicateStructure = structureFromTopology(duplicate, shape, [0, 0], []);
assert.equal(duplicateStructure.arms.length, headings.length);
assert.ok(
duplicateStructure.arms
.flatMap((arm) => arm.carriageways)
.some((item) => item.capability.reason === 'source-ambiguous'),
);
syntheticModel.roads[1].sourceNodeIds = [];
const missingSource = resolveComplexJunctionTopology(
syntheticModel,
{ id: 'synthetic', nodeIds: ['a', 'b'] },
helpers,
);
assert.ok(
structureFromTopology(missingSource, shape, [0, 0], [])
.arms.flatMap((arm) => arm.carriageways)
.some((item) => item.capability.reason === 'source-missing'),
);
}