fix: verify and align complex junction layer seams

This commit is contained in:
que01 committed 2026-09-17 10:07:26 +08:00
1 parent 79590d3d0f
commit cfb3593a0b
15 files changed
+1122 -57

No files matched your search

+478
View File
@@ -0,0 +1,478 @@
'use strict';
// Independent measurements of published geometry. Do not call the boundary or
// marking builders here: a shared bug must not manufacture its own expectation.
const TOLERANCE_METERS = 0.01;
const LAYERS = [
'roadSurface',
'coreApproach',
'edgeLines',
'centerLines',
'laneCenterlines',
'laneSeparators',
'sidewalkSurface',
];
const mix = (a, b, t = 0.5) => a.map((v, i) => v + (b[i] - v) * t);
const ids = (value) =>
String(value || '')
.split(',')
.filter(Boolean);
const id = (feature) => feature?.properties?.native_id;
const xy = (point, origin) => [
(point[0] - origin[0]) * 111320 * Math.cos((origin[1] * Math.PI) / 180),
(point[1] - origin[1]) * 111320,
];
const distance = (a, b) => Math.hypot(...xy(a, b));
const dot = (a, b) => a[0] * b[0] + a[1] * b[1];
const cross = (a, b) => a[0] * b[1] - a[1] * b[0];
const subtract = (a, b) => a.map((v, i) => v - b[i]);
function pointSegmentDistance(point, a, b) {
const p = xy(a, point),
q = xy(b, point),
v = subtract(q, p);
const t = Math.max(0, Math.min(1, -dot(p, v) / (dot(v, v) || 1)));
return Math.hypot(...mix(p, q, t));
}
function lineDistance(point, line) {
return Math.min(...line.slice(1).map((q, i) => pointSegmentDistance(point, line[i], q)));
}
function ringsOf(feature) {
if (feature?.geometry?.type === 'Polygon') return feature.geometry.coordinates;
if (feature?.geometry?.type === 'MultiPolygon') return feature.geometry.coordinates.flat();
return [];
}
function inside(point, ring) {
let result = false;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const a = ring[i],
b = ring[j];
if (a[1] > point[1] !== b[1] > point[1] && point[0] < ((b[0] - a[0]) * (point[1] - a[1])) / (b[1] - a[1]) + a[0])
result = !result;
}
return result;
}
// Partition at every edge crossing. A narrow interior notch cannot hide
// between probes, unlike endpoint-only or fixed quarter-point measurements.
function measureSegment(a, b, feature, boundaryOnly = true) {
const rings = ringsOf(feature).map((ring) => ring.map((p) => xy(p, a)));
const end = xy(b, a),
length = Math.hypot(...end),
length2 = dot(end, end);
if (!rings.length || !length) return { errorMeters: null, uncoveredMeters: length, missing: true };
const partitions = [0, 1],
intervals = [];
for (const ring of rings)
for (let i = 1; i < ring.length; i++) {
const p = ring[i - 1],
q = ring[i],
v = subtract(q, p),
denominator = cross(end, v);
if (Math.abs(denominator) > 1e-12) {
const t = cross(p, v) / denominator,
u = cross(p, end) / denominator;
if (t > 0 && t < 1 && u >= 0 && u <= 1) partitions.push(t);
}
// Project only edges parallel and numerically coincident with the seam.
// Tolerance is a permitted geometric error, not permission to bridge gaps.
if (
Math.abs(cross(end, p)) / length <= TOLERANCE_METERS &&
Math.abs(cross(end, q)) / length <= TOLERANCE_METERS
) {
const first = Math.max(0, Math.min(dot(p, end), dot(q, end)) / length2);
const last = Math.min(1, Math.max(dot(p, end), dot(q, end)) / length2);
if (last > first) {
intervals.push([first, last]);
partitions.push(first, last);
}
}
}
partitions.sort((x, y) => x - y);
let uncoveredMeters = 0;
const polygons = feature.geometry.type === 'Polygon' ? [feature.geometry.coordinates] : feature.geometry.coordinates;
const inPolygon = (p) =>
polygons.some((polygon) => inside(p, polygon[0]) && !polygon.slice(1).some((hole) => inside(p, hole)));
for (let i = 1; i < partitions.length; i++) {
const first = partitions[i - 1],
last = partitions[i],
t = (first + last) / 2;
if (!intervals.some(([lo, hi]) => t >= lo && t <= hi) && (boundaryOnly || !inPolygon(mix(a, b, t))))
uncoveredMeters += (last - first) * length;
}
const endpointError = Math.max(
...[a, b].map((p) =>
!boundaryOnly && inPolygon(p) ? 0 : Math.min(...ringsOf(feature).map((ring) => lineDistance(p, ring))),
),
);
return { errorMeters: endpointError, uncoveredMeters };
}
function caps(feature) {
const ring = ringsOf(feature)[0] || [],
half = (ring.length - 1) / 2;
if (!Number.isInteger(half) || half < 2) return [];
return [
[ring[0], ring[ring.length - 2]],
[ring[half - 1], ring[half]],
];
}
function auditJunctionSeams(model, geometry, structures) {
const report = Object.fromEntries(
LAYERS.map((layer) => [layer, { checked: 0, failed: 0, notApplicable: 0, records: [] }]),
);
const features = (layer) => geometry[layer]?.features || [];
function record(layer, identity, measurement, featureIds = []) {
const missing = Boolean(measurement.missing);
const failed =
missing ||
!Number.isFinite(measurement.errorMeters) ||
measurement.errorMeters > TOLERANCE_METERS ||
(measurement.uncoveredMeters || 0) > TOLERANCE_METERS;
report[layer].checked++;
if (failed) report[layer].failed++;
report[layer].records.push({
...identity,
featureIds: featureIds.filter(Boolean),
...measurement,
status: failed ? 'failed' : 'passed',
});
}
function na(layer, identity, reason) {
report[layer].notApplicable++;
report[layer].records.push({ ...identity, status: 'not-applicable', reason });
}
function point(layer, identity, expected, candidates, points) {
const actual = candidates.flatMap(points);
record(
layer,
identity,
{
errorMeters: actual.length ? Math.min(...actual.map((p) => distance(expected, p))) : null,
missing: !actual.length,
},
candidates.map(id),
);
}
for (const structure of structures) {
const clusterId = structure.junctionRef.id;
const core = features('roadSurface').find(
(f) => f.properties.cluster_id === clusterId && f.properties.kind === 'complex-core',
);
for (const arm of structure.arms)
for (const carriageway of arm.carriageways) {
const roadIds = carriageway.provenance.roadIds;
const identity = { clusterId, carriagewayKey: carriageway.key, roadIds };
const approach = features('roadSurface').find((f) => f.properties.carriageway_key === carriageway.key);
if (!approach) {
for (const layer of LAYERS.filter((name) => name !== 'sidewalkSurface'))
record(layer, identity, { missing: true, errorMeters: null, reason: 'Required approach is missing.' });
continue;
}
const ring = approach.geometry.coordinates[0],
seam = [ring[0], ring[3]];
const exterior = features('roadSurface').filter(
(f) =>
roadIds.length === ids(f.properties.directional_road_ids).length &&
roadIds.every((roadId) => ids(f.properties.directional_road_ids).includes(roadId)),
);
record('roadSurface', { ...identity, join: 'exterior-approach' }, measureSegment(...seam, exterior[0]), [
id(approach),
id(exterior[0]),
]);
record('coreApproach', { ...identity, join: 'approach-core' }, measureSegment(ring[1], ring[2], core, false), [
id(approach),
id(core),
]);
const pavement = features('roadSurface').find(
(f) => f.properties.cluster_id === clusterId && f.properties.kind === 'complex-pavement-region',
);
record(
'roadSurface',
{ ...identity, join: 'exterior-published-pavement' },
measureSegment(...seam, pavement, false),
[id(pavement)],
);
const road = model.roads.find((r) => r.id === roadIds[0]);
// Preview indices run right-to-left in the outward arm frame; native
// lanes run left-to-right in each road's travel frame. Derive the mapping
// from source direction, never from whichever geometry happens to be near.
const incoming = (r) => carriageway.provenance.nodeIds.includes(String(r.sourceNodeIds.at(-1)));
const sourceRoads = roadIds.map((roadId) => model.roads.find((r) => r.id === roadId));
const bindings = [...sourceRoads.filter((r) => !incoming(r)), ...sourceRoads.filter(incoming)].flatMap((r) =>
Array.from({ length: r.laneCount }, (_, i) => ({
roadId: r.id,
laneIndex: incoming(r) ? i + 1 : r.laneCount - i,
})),
);
const previews = features('laneCenterlines').filter(
(f) =>
f.properties.carriageway_key === carriageway.key &&
f.properties.cluster_preview &&
roadIds.includes(f.properties.road_id),
);
for (let index = 1; index <= carriageway.laneCount; index++) {
const laneIdentity = { ...identity, laneIndex: index };
const preview = previews.find((f) => f.properties.lane_index === index);
const binding = bindings[index - 1];
const external = features('laneCenterlines').filter(
(f) =>
!f.properties.cluster_preview &&
f.properties.road_id === binding.roadId &&
f.properties.lane_index === binding.laneIndex,
);
const expected = mix(...seam, (index - 0.5) / carriageway.laneCount);
point(
'laneCenterlines',
{ ...laneIdentity, join: 'transition-seam' },
expected,
preview ? [preview] : [],
(f) => [f.geometry.coordinates[0]],
);
point('laneCenterlines', { ...laneIdentity, join: 'external-transition' }, expected, external, (f) => [
f.geometry.coordinates[0],
f.geometry.coordinates.at(-1),
]);
}
// Edges terminate at the outer pavement edge; there is no separately
// published internal edge continuation. Match the same source road only.
const directions = model.roads.filter((r) => r.segmentId === road.segmentId);
for (const sourceRoad of sourceRoads)
for (const side of directions.length > 1 ? ['right'] : ['left', 'right']) {
const edges = features('edgeLines').filter(
(f) => f.properties.road_id === sourceRoad.id && f.properties.side === side,
);
const expected = seam[(side === 'right') === incoming(sourceRoad) ? 1 : 0];
if (edges.some((f) => f.properties.pattern !== 'solid')) {
const surfaceRing = ringsOf(exterior[0])[0] || [];
const half = (surfaceRing.length - 1) / 2;
const supports = [surfaceRing.slice(0, half), surfaceRing.slice(half, -1)];
const support = supports.sort((a, b) => lineDistance(expected, a) - lineDistance(expected, b))[0];
const nearest = edges
.map((f) => ({ f, ends: caps(f).map((cap) => mix(...cap)) }))
.sort(
(a, b) =>
Math.min(...a.ends.map((p) => distance(p, expected))) -
Math.min(...b.ends.map((p) => distance(p, expected))),
)[0];
const gap = Math.min(...nearest.ends.map((p) => distance(p, expected)));
record(
'edgeLines',
{ ...identity, roadId: sourceRoad.id, side, join: 'dash-support' },
{
errorMeters: Math.max(...nearest.ends.map((p) => lineDistance(p, support))),
gapMeters: gap,
uncoveredMeters: Math.max(0, gap - (incoming(sourceRoad) ? 4 : 0)),
},
[id(nearest.f)],
);
na(
'edgeLines',
{ ...identity, side },
'Two-metre dashes with two-metre spacing need not end at the seam.',
);
continue;
}
const actual = edges.flatMap((f) => caps(f).map((cap) => mix(...cap)));
record(
'edgeLines',
{ ...identity, roadId: sourceRoad.id, side },
{
missing: !actual.length,
errorMeters: actual.length ? Math.min(...actual.map((p) => distance(p, expected))) : null,
},
edges.map(id),
);
}
for (let index = 1; index < carriageway.laneCount; index++) {
const separatorIdentity = { ...identity, leftLaneIndex: index, rightLaneIndex: index + 1 };
const expected = mix(...seam, index / carriageway.laneCount);
const separators = features('laneSeparators').filter(
(f) =>
f.properties.cluster_id === clusterId &&
roadIds.includes(f.properties.road_id) &&
f.properties.left_lane_index === index &&
f.properties.provenance === 'native-road-complex-lane-separator/v1',
);
point('laneSeparators', { ...separatorIdentity, join: 'transition-seam' }, expected, separators, (f) =>
caps(f).map((cap) => mix(...cap)),
);
const firstBinding = bindings[index - 1],
secondBinding = bindings[index];
if (firstBinding.roadId !== secondBinding.roadId) {
na(
'laneSeparators',
separatorIdentity,
'Opposite directions meet at the road centre marking, not an exterior lane separator.',
);
continue;
}
const exteriorIndex = Math.min(firstBinding.laneIndex, secondBinding.laneIndex);
const exteriorSeparators = features('laneSeparators').filter(
(f) =>
f.properties.road_id === firstBinding.roadId &&
f.properties.left_lane_index === exteriorIndex &&
f.properties.provenance === 'native-road-lane-separator/v1',
);
if (!exteriorSeparators.length)
record('laneSeparators', separatorIdentity, { missing: true, errorMeters: null });
else {
// The final dash need not end at the seam. Its centre must lie on the
// same lane pair's support, near this interface rather than another arm.
const lanes = [exteriorIndex, exteriorIndex + 1].map((laneIndex) =>
features('laneCenterlines').find(
(f) =>
!f.properties.cluster_preview &&
f.properties.road_id === firstBinding.roadId &&
f.properties.lane_index === laneIndex,
),
);
const nearest = exteriorSeparators
.map((f) => ({ f, point: mix(...caps(f).map((cap) => mix(...cap))) }))
.sort((a, b) => distance(a.point, expected) - distance(b.point, expected))[0];
const first = lanes[0]?.geometry.coordinates,
second = lanes[1]?.geometry.coordinates;
const support = first && first.length === second?.length ? first.map((p, i) => mix(p, second[i])) : [];
const gap = Math.min(...caps(nearest.f).map((cap) => distance(mix(...cap), expected)));
record(
'laneSeparators',
{ ...separatorIdentity, join: 'external-dash-support' },
{
missing: !support.length,
errorMeters: support.length
? Math.max(...caps(nearest.f).map((cap) => lineDistance(mix(...cap), support)))
: null,
gapMeters: gap,
uncoveredMeters: Math.max(
0,
gap -
(nearest.f.properties.pattern === 'solid' ||
!incoming(sourceRoads.find((r) => r.id === firstBinding.roadId))
? 0
: 4),
),
},
[id(nearest.f), ...lanes.map(id)],
);
na(
'laneSeparators',
separatorIdentity,
'Dash spacing and stop-line clipping do not require white paint across the seam.',
);
}
}
if (carriageway.laneCount < 2) na('laneSeparators', identity, 'Single lane has no lane separator.');
if (directions.length < 2 || road.highway === 'service')
na('centerLines', identity, 'No bidirectional road centre marking is published.');
else {
const markings = features('centerLines').filter(
(f) =>
roadIds.includes(f.properties.road_id) &&
roadIds.length === ids(f.properties.directional_road_ids).length &&
roadIds.every((roadId) => ids(f.properties.directional_road_ids).includes(roadId)),
);
const nearest = markings
.map((f) => ({ f, point: mix(...caps(f).map((cap) => mix(...cap))) }))
.sort((a, b) => distance(a.point, mix(...seam)) - distance(b.point, mix(...seam)))[0];
const supportPoints = nearest ? caps(nearest.f).map((cap) => mix(...cap)) : [];
const gap = supportPoints.length ? Math.min(...supportPoints.map((p) => distance(p, mix(...seam)))) : null;
record(
'centerLines',
identity,
{
missing: !nearest,
errorMeters: nearest
? Math.max(
...supportPoints.map((p) =>
Math.abs(lineDistance(p, road.centerline) - (nearest.f.properties.double ? 0.16 : 0)),
),
)
: null,
gapMeters: gap,
uncoveredMeters:
gap === null
? 0
: Math.max(
0,
gap -
(incoming(sourceRoads.find((r) => r.id === nearest.f.properties.road_id))
? nearest.f.properties.dash_length_m + nearest.f.properties.dash_gap_m
: 0),
),
},
[id(nearest?.f)],
);
na(
'centerLines',
identity,
'Road centre dashes terminate outside the cluster; no interior centre marking is published.',
);
}
}
for (const corner of structure.corners) {
const arms = [corner.fromArmKey, corner.toArmKey].map((key) => structure.arms.find((arm) => arm.key === key));
const roadGroups = arms.map((arm) => arm.carriageways.flatMap((c) => c.provenance.roadIds));
const strips = roadGroups.map((roadIds) =>
features('sidewalkSurface').filter(
(f) =>
f.properties.provenance === 'native-road-sidewalk/v1' &&
ids(f.properties.directional_road_ids).some((roadId) => roadIds.includes(roadId)),
),
);
const identity = { clusterId, cornerKey: corner.key, roadIds: roadGroups.flat() };
if (strips.some((group) => !group.length)) {
const enabled = roadGroups.every((group) =>
group.some((roadId) => {
const road = model.roads.find((r) => r.id === roadId);
return road?.sidewalkLeft || road?.sidewalkRight;
}),
);
if (enabled) record('sidewalkSurface', identity, { missing: true, errorMeters: null });
else na('sidewalkSurface', identity, 'Source arms do not both carry sidewalks.');
continue;
}
const join = features('sidewalkSurface').find(
(f) => f.properties.kind === 'complex-sidewalk-corner' && f.properties.corner_key === corner.key,
);
if (!join) {
const omitted = (geometry.diagnostics || []).find(
(d) =>
d.subjectId === `corner:${corner.key}` &&
[
'complex-junction-sidewalk-corner-fallback',
'complex-junction-island-infeasible',
'complex-junction-corner-exclusion-overlap',
].includes(d.rule),
);
if (omitted) na('sidewalkSurface', identity, `Explicitly rejected corner: ${omitted.rule}. ${omitted.message}`);
else record('sidewalkSurface', identity, { missing: true, errorMeters: null });
continue;
}
if (caps(join).length !== 2) {
record('sidewalkSurface', identity, { missing: true, errorMeters: null, reason: 'Invalid corner end edges.' });
continue;
}
for (const [index, cap] of caps(join).entries()) {
const candidates = strips[index]
.map((f) => ({ f, measurement: measureSegment(...cap, f) }))
.sort(
(a, b) =>
a.measurement.errorMeters +
a.measurement.uncoveredMeters -
(b.measurement.errorMeters + b.measurement.uncoveredMeters),
);
record('sidewalkSurface', { ...identity, end: index }, candidates[0].measurement, [
id(join),
id(candidates[0].f),
]);
}
}
}
return report;
}
module.exports = { TOLERANCE_METERS, LAYERS, auditJunctionSeams, measureSegment, distance };
+343
View File
@@ -0,0 +1,343 @@
'use strict';
const assert = require('assert/strict');
const fs = require('fs');
const path = require('path');
const { compileRoadModel, compileGeometry } = require('../src/compile/native-road');
const { auditJunctionSeams, LAYERS, measureSegment } = require('./helpers/junction-seams');
const overrides = { overrides: [] };
function compile(name, model, clusters, extra = {}, styles = overrides) {
const geometry = compileGeometry(model, styles, { junctionTemplates: { enabled: true, clusters }, ...extra });
const structures = geometry.roadSurface.features.map((f) => f.properties.junction_structure).filter(Boolean);
assert.equal(structures.length, clusters.length, `${name}: missing junction structure`);
const report = auditJunctionSeams(model, geometry, structures);
return { name, model, clusters, geometry, structures, report };
}
function synthetic(curved = false, twoWay = false, adjacent = false) {
const nodes = [
[-5, 0],
[240, 0],
[5, 240],
[-240, 0],
[-5, -240],
[100, curved ? 12 : 0],
[5, 0],
];
if (adjacent) nodes.push([250, 0], [240, 240], [500, 0], [250, -240]);
const ways = [2, 3, 4, 5].map((n) => [n, [n <= 3 ? 7 : 1, ...(n === 2 ? [6] : []), n]]);
if (adjacent) ways.push([9, [2, 9]], [10, [8, 10]], [11, [8, 11]]);
const internal = [[1, 7], ...(adjacent ? [[2, 8]] : [])];
const osm = `<osm>${nodes.map(([x, y], i) => `<node id="${i + 1}" lon="${120 + x / (111320 * Math.cos(Math.PI / 6))}" lat="${30 + y / 111320}"/>`).join('')}${ways.map(([id, refs]) => `<way id="${id}">${refs.map((ref) => `<nd ref="${ref}"/>`).join('')}<tag k="highway" v="primary"/><tag k="lanes" v="${twoWay ? 4 : 3}"/>${twoWay ? '' : '<tag k="oneway" v="yes"/>'}<tag k="sidewalk" v="both"/></way>`).join('')}${internal.map((refs, i) => `<way id="internal${i}">${refs.map((ref) => `<nd ref="${ref}"/>`).join('')}<tag k="highway" v="primary"/></way>`).join('')}</osm>`;
return compileRoadModel(osm, overrides);
}
const cluster = { id: 'synthetic', template: 'complex-junction-v1', coreRadiusMeters: 21, nodeIds: ['1', '7'] };
const realModel = compileRoadModel(
fs.readFileSync(path.join(__dirname, '../inputs/osm/枫树二路.osm'), 'utf8'),
overrides,
);
const west = {
id: 'west',
template: 'complex-junction-v1',
coreRadiusMeters: 21,
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147'],
};
const east = {
id: 'east',
template: 'complex-junction-v1',
coreRadiusMeters: 18,
nodeIds: ['1590698046', '6538106539'],
};
const scenarios = [
compile('straight', synthetic(), [cluster]),
compile('curved', synthetic(true), [cluster]),
compile('two-way', synthetic(false, true), [cluster]),
compile('two-way-curved', synthetic(true, true), [cluster]),
compile('real-osm', realModel, [west]),
compile('adjacent', realModel, [west, east]),
compile(
'sidewalks',
{ ...realModel, roads: realModel.roads.map((r) => ({ ...r, sidewalkLeft: true, sidewalkRight: true })) },
[west],
),
];
scenarios.push(
compile('two-way-adjacent', synthetic(true, true, true), [
cluster,
{ ...cluster, id: 'synthetic-east', nodeIds: ['2', '8'] },
]),
);
const curvedTwoWay = scenarios.find((s) => s.name === 'two-way-curved');
const twoWayApproach = curvedTwoWay.geometry.roadSurface.features.find((f) => f.properties.kind === 'complex-approach');
scenarios.push(
compile('two-way-width-edit', curvedTwoWay.model, [cluster], {
directEdit: {
clusterPlans: new Map([
[cluster.id, new Map([[twoWayApproach.properties.carriageway_key, twoWayApproach.properties.width_m * 1.2]])],
]),
},
}),
);
const curved = scenarios[1];
const approach = curved.geometry.roadSurface.features.find((f) => f.properties.kind === 'complex-approach');
scenarios.push(
compile('width-edit', curved.model, [cluster], {
directEdit: {
clusterPlans: new Map([
[cluster.id, new Map([[approach.properties.carriageway_key, approach.properties.width_m * 1.2]])],
]),
},
}),
);
scenarios.push(
compile('island-edit', realModel, [west], { directEdit: { clusterIslandOffsets: new Map([[west.id, 3.3]]) } }),
);
scenarios.push(compile('adjacent-reordered', { ...realModel, roads: [...realModel.roads].reverse() }, [east, west]));
scenarios.push(
compile(
'dashed-edges',
synthetic(true, true),
[cluster],
{},
{
overrides: synthetic(true, true).roads.flatMap((r) =>
['left', 'right'].map((side) => ({
kind: 'edge-line-style',
roadId: r.id,
side,
color: 'white',
pattern: 'dashed',
})),
),
},
),
);
const expectedCoverage = {
straight: [8, 4, 8, 0, 24, 16, 4],
curved: [8, 4, 8, 0, 24, 16, 4],
'two-way': [8, 4, 8, 4, 32, 20, 8],
'two-way-curved': [8, 4, 8, 4, 32, 20, 8],
'real-osm': [16, 8, 16, 0, 48, 32, 0],
adjacent: [26, 13, 26, 1, 76, 49, 0],
sidewalks: [16, 8, 16, 0, 48, 32, 8],
'width-edit': [8, 4, 8, 0, 24, 16, 4],
'island-edit': [16, 8, 16, 0, 48, 32, 0],
'adjacent-reordered': [26, 13, 26, 1, 76, 49, 0],
'dashed-edges': [8, 4, 8, 4, 32, 20, 8],
'two-way-adjacent': [16, 8, 16, 8, 64, 40, 16],
'two-way-width-edit': [8, 4, 8, 4, 32, 20, 8],
};
for (const { name, report } of scenarios) {
assert.deepEqual(
LAYERS.map((layer) => report[layer].checked),
expectedCoverage[name],
`${name}: coverage changed`,
);
for (const layer of LAYERS) {
assert.equal(
report[layer].failed,
0,
`${name}/${layer}: ${JSON.stringify(report[layer].records.filter((r) => r.status === 'failed'))}`,
);
assert.ok(report[layer].records.every((r) => r.status !== 'not-applicable' || r.reason));
}
}
for (const layer of LAYERS)
assert.ok(
scenarios.some((s) => s.report[layer].checked > 0),
`${layer}: empty audit`,
);
// Reordering must preserve expected source identities, not just pass counts.
function identities(report) {
return Object.fromEntries(
LAYERS.map((layer) => [
layer,
report[layer].records
.map((r) =>
JSON.stringify({
...r,
featureIds: undefined,
errorMeters: undefined,
uncoveredMeters: undefined,
gapMeters: undefined,
roadIds: [...r.roadIds].sort(),
}),
)
.sort(),
]),
);
}
assert.deepEqual(
identities(scenarios.find((s) => s.name === 'adjacent').report),
identities(scenarios.find((s) => s.name === 'adjacent-reordered').report),
);
// Corrupt published outputs while retaining the independent expected topology.
const base = scenarios.find((s) => s.name === 'two-way');
function detects(name, layer, mutate, scenario = base) {
const geometry = structuredClone(scenario.geometry);
mutate(geometry);
const result = auditJunctionSeams(scenario.model, geometry, scenario.structures);
assert.ok(result[layer].failed > 0, `${name}: audit silently accepted damaged ${layer}`);
}
const shift = (coordinates, dx, dy) =>
typeof coordinates[0] === 'number'
? [coordinates[0] + dx / (111320 * Math.cos((coordinates[1] * Math.PI) / 180)), coordinates[1] + dy / 111320]
: coordinates.map((value) => shift(value, dx, dy));
const move = (feature) => {
feature.geometry.coordinates = shift(feature.geometry.coordinates, 0.02, 0);
};
for (const [layer, predicate, auditLayer = layer] of [
['roadSurface', (f) => Boolean(f.properties.directional_road_ids)],
['roadSurface', (f) => f.properties.kind === 'complex-core', 'coreApproach'],
['roadSurface', (f) => f.properties.kind === 'complex-approach'],
['edgeLines', () => true],
['centerLines', () => true],
['laneCenterlines', (f) => !f.properties.cluster_preview],
['laneSeparators', (f) => f.properties.provenance === 'native-road-complex-lane-separator/v1'],
['sidewalkSurface', (f) => f.properties.kind === 'complex-sidewalk-corner'],
]) {
detects('missing counterpart', auditLayer, (g) => {
g[layer].features = g[layer].features.filter((f) => !predicate(f));
});
detects('one missing counterpart', auditLayer, (g) => {
const index = g[layer].features.findIndex(predicate);
assert.ok(index >= 0);
g[layer].features.splice(index, 1);
});
detects('2 cm displacement', auditLayer, (g) => g[layer].features.filter(predicate).forEach(move));
}
detects('wrong preview source', 'laneCenterlines', (g) => {
g.laneCenterlines.features.find((f) => f.properties.cluster_preview).properties.road_id = 'wrong-road';
});
detects('wrong centre primary source', 'centerLines', (g) => {
for (const f of g.centerLines.features) f.properties.road_id = 'wrong-road';
});
detects('partial centre source match', 'centerLines', (g) => {
for (const f of g.centerLines.features) f.properties.directional_road_ids = `${f.properties.road_id},wrong-road`;
});
for (const layer of ['edgeLines', 'centerLines', 'laneCenterlines', 'laneSeparators']) {
detects('wrong source', layer, (g) => {
for (const f of g[layer].features) {
f.properties.road_id = 'wrong-road';
if (f.properties.directional_road_ids) f.properties.directional_road_ids = 'wrong-road';
}
});
}
detects('swapped lane indices', 'laneCenterlines', (g) => {
for (const f of g.laneCenterlines.features.filter((f) => !f.properties.cluster_preview))
f.properties.lane_index = 3 - f.properties.lane_index;
});
detects('wrong surface source', 'roadSurface', (g) => {
for (const f of g.roadSurface.features.filter((f) => f.properties.directional_road_ids))
f.properties.directional_road_ids = 'wrong-road';
});
detects('missing sidewalk strip', 'sidewalkSurface', (g) => {
g.sidewalkSurface.features = g.sidewalkSurface.features.filter(
(f) => f.properties.provenance !== 'native-road-sidewalk/v1',
);
});
detects('wrong sidewalk source', 'sidewalkSurface', (g) => {
for (const f of g.sidewalkSurface.features.filter((f) => f.properties.provenance === 'native-road-sidewalk/v1'))
f.properties.directional_road_ids = 'wrong-road';
});
detects(
'displaced edge dashes',
'edgeLines',
(g) => g.edgeLines.features.forEach(move),
scenarios.find((s) => s.name === 'dashed-edges'),
);
detects(
'missing anchored edge dash',
'edgeLines',
(g) => g.edgeLines.features.shift(),
scenarios.find((s) => s.name === 'dashed-edges'),
);
detects('missing exterior separators', 'laneSeparators', (g) => {
g.laneSeparators.features = g.laneSeparators.features.filter(
(f) => f.properties.provenance !== 'native-road-lane-separator/v1',
);
});
detects('displaced exterior separators', 'laneSeparators', (g) =>
g.laneSeparators.features.filter((f) => f.properties.provenance === 'native-road-lane-separator/v1').forEach(move),
);
// A 2 cm notch away from all endpoint/quarter/midpoint probes must fail.
const metric = ([x, y]) => [120 + x / (111320 * Math.cos(Math.PI / 6)), 30 + y / 111320];
const polygon = (ring) => ({ geometry: { type: 'Polygon', coordinates: [ring.map(metric)] } });
const full = polygon([
[0, 0],
[10, 0],
[10, 2],
[0, 2],
[0, 0],
]);
const notch = polygon([
[0, 0],
[3.11, 0],
[3.11, 0.1],
[3.13, 0.1],
[3.13, 0],
[10, 0],
[10, 2],
[0, 2],
[0, 0],
]);
for (const boundaryOnly of [true, false]) {
assert.ok(measureSegment(metric([0, 0]), metric([10, 0]), full, boundaryOnly).uncoveredMeters < 0.01);
assert.ok(measureSegment(metric([0, 0]), metric([10, 0]), notch, boundaryOnly).uncoveredMeters > 0.019);
}
const holed = polygon([
[0, -1],
[10, -1],
[10, 2],
[0, 2],
[0, -1],
]);
holed.geometry.coordinates.push(
[
[3.11, -0.1],
[3.13, -0.1],
[3.13, 0.1],
[3.11, 0.1],
[3.11, -0.1],
].map(metric),
);
assert.ok(measureSegment(metric([0, 0]), metric([10, 0]), holed, false).uncoveredMeters > 0.019);
const summary = scenarios.map(({ name, report }) => ({
name,
layers: Object.fromEntries(
LAYERS.map((layer) => {
const { checked, failed, notApplicable, records } = report[layer];
return [
layer,
{
checked,
failed,
notApplicable,
maxErrorMeters: Math.max(0, ...records.map((r) => r.errorMeters || 0)),
maxUncoveredMeters: Math.max(0, ...records.map((r) => r.uncoveredMeters || 0)),
},
];
}),
),
}));
const reportIndex = process.argv.indexOf('--report');
if (reportIndex >= 0)
fs.writeFileSync(
process.argv[reportIndex + 1],
JSON.stringify(
{ toleranceMeters: 0.01, summary, scenarios: scenarios.map(({ name, report }) => ({ name, report })) },
null,
2,
) + '\n',
);
console.log(
`junction layer seam tests passed (${scenarios.length} scenarios, ${summary.reduce((sum, s) => sum + Object.values(s.layers).reduce((n, l) => n + l.checked, 0), 0)} measured joins)`,
);