Files
road-compiler/test/index.js
T

601 lines
24 KiB
JavaScript

'use strict';
const assert = require('assert/strict');
const fs = require('fs');
const path = require('path');
const compiler = require('../src');
assert.equal(typeof compiler.laneGeometry.laneCenterline, 'function');
assert.equal(typeof compiler.gaodeReference.convertGeoJson, 'function');
assert.equal(typeof compiler.turnLaneArrows.buildCustomTurnLaneArrows, 'function');
assert.equal(typeof compiler.complexJunction.buildComplexJunctionGeometry, 'function');
assert.equal(typeof compiler.complexJunction.classifyJunctionShape, 'function');
assert.equal(typeof compiler.junctionStructure.buildJunctionStructure, 'function');
assert.equal(typeof compiler.junctionStandards.validateStandardsProfile, 'function');
assert.equal(typeof compiler.junctionProjection.projectJunctionStructure, 'function');
const shapeHelpers = { distanceMeters: (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]) };
const arm = (heading, distance = 20) => ({
heading,
members: [
{
approach: {
line: [
[0, 0],
[0, distance],
],
},
},
],
});
assert.equal(
compiler.complexJunction.classifyJunctionShape([arm(0), arm(90), arm(180), arm(270)], [0, 0], shapeHelpers).kind,
'cross',
);
assert.equal(
compiler.complexJunction.classifyJunctionShape([arm(0), arm(120), arm(180)], [0, 0], shapeHelpers).kind,
't-junction',
);
assert.equal(
compiler.complexJunction.classifyJunctionShape([arm(0), arm(80), arm(140)], [0, 0], shapeHelpers).kind,
'multi-arm',
);
assert.equal(
compiler.complexJunction.classifyJunctionShape([arm(0), arm(90), arm(180), arm(270)], [0, 0], shapeHelpers).label,
'4 臂十字路口',
);
assert.equal(
compiler.complexJunction.classifyJunctionShape([arm(0), arm(90)], [0, 0], shapeHelpers).kind,
'unsupported',
);
assert.equal(typeof compiler.nativeRoad.compileRoadModel, 'function');
assert.equal(typeof compiler.check.checkOutput, 'function');
assert.equal(typeof compiler.layerManifest.manifestForArea, 'function');
const manifest = compiler.layerManifest.manifestForArea('fixture');
assert.equal(manifest.contract, 'native-road-package/v1.1');
assert.equal(manifest.layers.length, 12);
assert.deepEqual(
manifest.layers.filter((layer) => layer.role === 'semantic').map((layer) => layer.source),
['lane_centerlines', 'connectors'],
);
assert.equal(manifest.layers.find((layer) => layer.source === 'center_lines').splitBy.cases[0].match, 'white');
const fixture = path.join(__dirname, 'fixtures', 'fengshu-er-road.osm');
assert.ok(fs.existsSync(fixture));
assert.throws(() => compiler.compiler.validateInput({ id: 'area' }), /RoadCompilerInput/);
const model = compiler.nativeRoad.compileRoadModel(fs.readFileSync(fixture, 'utf8'), {
schema: 'native-road-overrides/v1',
overrides: [],
});
assert.equal(model.roads.length, 24);
const islandModel = compiler.nativeRoad.compileRoadModel(
`<osm>
<node id="1" lon="120" lat="30"/><node id="2" lon="120.0001" lat="30"/>
<node id="3" lon="120.0001" lat="30.0001"/><node id="4" lon="120" lat="30.0001"/>
<way id="island"><nd ref="1"/><nd ref="2"/><nd ref="3"/><nd ref="4"/><nd ref="1"/><tag k="highway" v="traffic_island"/></way>
</osm>`,
{ schema: 'native-road-overrides/v1', overrides: [] },
);
assert.deepEqual(
islandModel.exclusionRegions.map((region) => [region.id, region.source]),
[['island', 'osm-traffic-island']],
);
const islandGeometry = compiler.nativeRoad.compileGeometry(islandModel, {
schema: 'native-road-overrides/v1',
overrides: [],
});
assert.equal(
islandGeometry.intersectionSurface.features.find(
(feature) => feature.properties?.native_id === 'osm-traffic-island:island',
)?.properties?.object_key,
'island:osm/island',
);
const complexModel = compiler.nativeRoad.compileRoadModel(fs.readFileSync(fixture, 'utf8'), {
schema: 'native-road-overrides/v1',
overrides: [],
});
const complexGeometry = compiler.nativeRoad.compileGeometry(
complexModel,
{ schema: 'native-road-overrides/v1', overrides: [] },
{
edgeLines: false,
junctionTemplates: {
enabled: true,
clusters: [
{
id: 'fixture-five-arm',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
},
],
},
},
);
const complexCore = complexGeometry.roadSurface.features.find(
(feature) => feature.properties?.kind === 'complex-core' && feature.properties?.cluster_id === 'fixture-five-arm',
);
// This fixture contains multiple source carriageways within several arms. The
// compiler must retain those independent sections rather than filling their
// unknown interstitial areas with a synthetic core.
assert.equal(complexCore, undefined);
assert.ok(
complexGeometry.diagnostics.some(
(item) =>
item.rule === 'complex-junction-core-closure-unsupported' &&
item.subjectId === 'junction-cluster:fixture-five-arm',
),
);
assert.ok(complexGeometry.roadSurface.features.some((feature) => feature.properties?.kind === 'complex-approach'));
const compiledApproach = complexGeometry.roadSurface.features.find(
(feature) => feature.properties?.kind === 'complex-approach',
);
assert.equal(compiledApproach.properties.transition_status, 'supported');
assert.equal(compiledApproach.properties.ring_status, 'supported');
assert.equal(compiledApproach.properties.exclusion_status, 'clear');
assert.ok(compiledApproach.properties.transition_length_m > 0);
const complexApproachFeatures = complexGeometry.roadSurface.features.filter(
(feature) => feature.properties?.kind === 'complex-approach',
);
for (const feature of complexApproachFeatures) {
const ring = feature.geometry?.coordinates?.[0] || [];
assert.ok(ring.length >= 4 && ring[0][0] === ring.at(-1)[0] && ring[0][1] === ring.at(-1)[1]);
assert.ok(ring.every((coordinate) => coordinate.every(Number.isFinite)));
const area = Math.abs(
ring
.slice(1)
.reduce((sum, coordinate, index) => sum + ring[index][0] * coordinate[1] - coordinate[0] * ring[index][1], 0) / 2,
);
assert.ok(area > 0, 'compiled complex approach surface must have positive area');
}
// Published transition lanes share the fixed source seam, including when the
// inner width is edited. Their outer endpoints must remain inside that seam.
const previewLanes = complexGeometry.laneCenterlines.features.filter((feature) => feature.properties.cluster_preview);
assert.ok(previewLanes.length > 0);
for (const lane of previewLanes) {
const approach = complexApproachFeatures.find(
(feature) => feature.properties.carriageway_key === lane.properties.carriageway_key,
);
assert.ok(approach, 'a transition lane must have a supported approach surface');
const ring = approach.geometry.coordinates[0];
const ratio = (lane.properties.lane_index - 0.5) / approach.properties.lane_count;
const expected = ring[0].map((value, axis) => value + (ring[3][axis] - value) * ratio);
assert.ok(
Math.hypot(...expected.map((value, axis) => value - lane.geometry.coordinates[0][axis])) < 1e-9,
'transition lane starts on its actual outer seam',
);
}
const boundaryEditOptions = {
junctionTemplates: {
enabled: true,
clusters: [
{
id: 'fixture-five-arm',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
},
],
},
directEdit: {
clusterPlans: new Map([
[
'fixture-five-arm',
new Map([[compiledApproach.properties.carriageway_key, compiledApproach.properties.width_m * 1.2]]),
],
]),
},
};
const widenedGeometry = compiler.nativeRoad.compileGeometry(complexModel, { overrides: [] }, boundaryEditOptions);
const exteriorBaseline = compiler.nativeRoad.compileGeometry(
complexModel,
{ overrides: [] },
{ junctionTemplates: boundaryEditOptions.junctionTemplates },
);
// External pavement and all linear consumers retain the same geometry when
// only the internal width changes; measure the pavement seam in metres too.
for (const layerName of ['roadSurface', 'edgeLines', 'sidewalkSurface', 'centerLines', 'laneCenterlines']) {
const external = (geometry) =>
geometry[layerName].features.filter((feature) =>
layerName === 'roadSurface'
? Boolean(feature.properties.directional_road_ids)
: layerName === 'sidewalkSurface'
? feature.properties.provenance === 'native-road-sidewalk/v1'
: !feature.properties.cluster_preview,
);
assert.deepEqual(
external(widenedGeometry),
external(exteriorBaseline),
`${layerName} must keep the fixed exterior geometry during local widening`,
);
}
let checkedExteriorSeams = 0;
for (const approach of complexApproachFeatures) {
const lane = previewLanes.find(
(candidate) => candidate.properties.carriageway_key === approach.properties.carriageway_key,
);
const surface = complexGeometry.roadSurface.features.find((candidate) =>
String(candidate.properties.directional_road_ids || '')
.split(',')
.includes(lane?.properties.road_id),
);
if (!surface) continue;
const ring = approach.geometry.coordinates[0];
for (const endpoint of [ring[0], ring[3]]) {
const error = Math.min(
...surface.geometry.coordinates[0].map((coordinate) =>
Math.hypot(
(coordinate[0] - endpoint[0]) * 111320 * Math.cos((endpoint[1] * Math.PI) / 180),
(coordinate[1] - endpoint[1]) * 111320,
),
),
);
assert.ok(error <= 0.01, `external pavement seam error ${error} exceeds one centimetre`);
}
checkedExteriorSeams++;
}
assert.ok(checkedExteriorSeams > 0);
const widenedLanes = widenedGeometry.laneCenterlines.features.filter(
(feature) =>
feature.properties.cluster_preview &&
feature.properties.carriageway_key === compiledApproach.properties.carriageway_key,
);
assert.ok(widenedLanes.length > 0);
for (const lane of widenedLanes) {
const before = previewLanes.find((candidate) => candidate.properties.native_id === lane.properties.native_id);
assert.deepEqual(
lane.geometry.coordinates[0],
before.geometry.coordinates[0],
'local widening preserves the outer lane seam',
);
}
const rejectedGeometry = compiler.nativeRoad.compileGeometry(
complexModel,
{ overrides: [] },
{
...boundaryEditOptions,
directEdit: {
clusterTransitions: new Map([
['fixture-five-arm', new Map([[compiledApproach.properties.carriageway_key, 10000]])],
]),
},
},
);
assert.equal(
rejectedGeometry.laneCenterlines.features.some(
(feature) =>
feature.properties.cluster_preview &&
feature.properties.carriageway_key === compiledApproach.properties.carriageway_key,
),
false,
'an unsupported transition must not publish floating lanes',
);
// External attachments must follow actual pavement publication, even when a
// short source road is swallowed by a cluster. Internal solver lanes remain private.
const surfacedIds = new Set(
exteriorBaseline.roadSurface.features
.flatMap((feature) => String(feature.properties.directional_road_ids || '').split(','))
.filter(Boolean),
);
assert.ok(
complexModel.roads.some((road) => !surfacedIds.has(road.id)),
'fixture exercises omitted roads',
);
for (const name of ['edgeLines', 'centerLines', 'laneCenterlines', 'laneSeparators', 'directionArrows', 'turnArrows']) {
for (const feature of exteriorBaseline[name].features) {
if (feature.properties.cluster_preview || String(feature.properties.native_id).startsWith('complex-')) continue;
assert.ok(
surfacedIds.has(feature.properties.road_id),
`${name} must not publish an attachment without external pavement`,
);
}
}
const sidewalkModel = {
...complexModel,
roads: complexModel.roads.map((road) => ({ ...road, sidewalkLeft: true, sidewalkRight: true })),
};
const sidewalkGeometry = compiler.nativeRoad.compileGeometry(
sidewalkModel,
{ overrides: [] },
{ junctionTemplates: boundaryEditOptions.junctionTemplates },
);
const strips = sidewalkGeometry.sidewalkSurface.features.filter(
(feature) => feature.properties.provenance === 'native-road-sidewalk/v1',
);
for (const strip of strips)
assert.ok(
String(strip.properties.directional_road_ids)
.split(',')
.every((id) => surfacedIds.has(id)),
);
const corners = sidewalkGeometry.sidewalkSurface.features.filter(
(feature) => feature.properties.kind === 'complex-sidewalk-corner',
);
assert.ok(corners.length > 0, 'fixture must exercise joined corner sidewalks');
for (const corner of corners) {
const ring = corner.geometry.coordinates[0];
const half = (ring.length - 1) / 2;
for (const [curb, outer] of [
[ring[0], ring[ring.length - 2]],
[ring[half - 1], ring[half]],
]) {
assert.ok(
strips.some((strip) => {
const points = strip.geometry.coordinates[0];
const middle = (points.length - 1) / 2;
return [
[points[0], points[points.length - 2]],
[points[middle - 1], points[middle]],
].some(([first, second]) => JSON.stringify([first, second]) === JSON.stringify([curb, outer]));
}),
'both ends of each corner must share the complete published sidewalk seam',
);
}
}
// Every generated corner surface must respect the same known exclusion regions
// as the core and entry surfaces, including containment without edge crossings.
for (const target of [
sidewalkGeometry.roadSurface.features.find((feature) => feature.properties.kind === 'complex-corner-fillet'),
corners[0],
]) {
assert.ok(target, 'fixture exercises both corner pavement and sidewalk');
const protectedRing = target.geometry.coordinates[0];
const excludedGeometry = compiler.nativeRoad.compileGeometry(
{ ...sidewalkModel, exclusionRegions: [{ id: 'corner-protection', ring: protectedRing }] },
{ overrides: [] },
{ junctionTemplates: boundaryEditOptions.junctionTemplates },
);
const { ringsOverlap } = require('../src/compile/junction-boundary-graph');
const publishedCorners = [
...excludedGeometry.roadSurface.features,
...excludedGeometry.sidewalkSurface.features,
].filter((feature) => ['complex-corner-fillet', 'complex-sidewalk-corner'].includes(feature.properties.kind));
assert.ok(publishedCorners.every((feature) => !ringsOverlap(protectedRing, feature.geometry.coordinates[0])));
assert.ok(
excludedGeometry.diagnostics.some((item) => item.rule === 'complex-junction-corner-exclusion-overlap'),
'omitted corner surfaces report their exclusion conflict',
);
}
// Empty pavement is a real result, not a signal to disable attachment checks.
const shortPoints = [
[1, -1, 0],
[2, 1, 0],
[3, -8, 8],
[4, -8, -8],
[5, 8, 8],
[6, 8, -8],
];
const shortWays = [
[1, 2],
[1, 3],
[1, 4],
[2, 5],
[2, 6],
];
const shortXml = `<osm>${shortPoints.map(([id, x, y]) => `<node id="${id}" lon="${x / 111320}" lat="${y / 111320}"/>`).join('')}${shortWays.map(([from, to], index) => `<way id="${index + 1}"><nd ref="${from}"/><nd ref="${to}"/><tag k="highway" v="residential"/><tag k="sidewalk" v="both"/></way>`).join('')}</osm>`;
const shortModel = compiler.nativeRoad.compileRoadModel(shortXml, { overrides: [] });
const shortGeometry = compiler.nativeRoad.compileGeometry(
shortModel,
{ overrides: [] },
{
junctionTemplates: {
enabled: true,
clusters: [{ id: 'short', nodeIds: ['1', '2'], template: 'complex-junction-v1', coreRadiusMeters: 24 }],
},
},
);
assert.equal(
shortGeometry.roadSurface.features.some((feature) => feature.properties.directional_road_ids),
false,
);
for (const name of [
'edgeLines',
'centerLines',
'laneCenterlines',
'laneSeparators',
'directionArrows',
'turnArrows',
'sidewalkSurface',
'crosswalks',
'vehicleStopLines',
])
assert.equal(shortGeometry[name].features.length, 0, `${name} must remain empty when all source roads are swallowed`);
assert.ok(
shortGeometry.diagnostics.some((item) => item.rule === 'complex-junction-crosswalk-pavement-unavailable'),
'unsupported crossings explain their missing pavement',
);
const missingSidewalkSeams = shortGeometry.diagnostics.filter(
(item) => item.rule === 'complex-junction-sidewalk-seam-unavailable',
);
assert.ok(
missingSidewalkSeams.length >= 0,
'corner sidewalk diagnostics are optional when no corner can be constructed',
);
for (const item of missingSidewalkSeams) {
assert.equal(item.severity, 'warning');
assert.ok(item.subjectId.startsWith('corner:'), 'missing seams must identify the affected corner');
assert.ok(item.sourceIds.length > 0);
assert.ok(item.sourceIds.every((id) => shortModel.roads.some((road) => road.id === id)));
}
const complexFeatures = Object.values(complexGeometry).flatMap((layer) => layer?.features || []);
assert.equal(
complexFeatures.some((feature) => feature.properties?.kind === 'complex-corner-island'),
false,
);
assert.equal(
complexFeatures.some((feature) => feature.properties?.kind === 'complex-corner-crosswalk'),
true,
);
assert.ok(complexGeometry.diagnostics.some((item) => item.rule === 'complex-junction-corner-facilities-omitted'));
assert.equal(
complexGeometry.crosswalks.features.some((feature) => feature.properties?.kind === 'complex-crosswalk'),
true,
'complex approaches default to zebra crossings when pavement is available',
);
assert.ok(complexGeometry.diagnostics.some((item) => item.rule === 'complex-junction-crossing-source-missing'));
assert.match(complexGeometry.diagnostics.find((item) => item.rule === 'complex-junction-generated').message, /斑马线/);
const inferredStopLine = complexGeometry.vehicleStopLines.features.find(
(feature) => feature.properties?.kind === 'complex-stop-line',
);
assert.equal(inferredStopLine.properties.facility_evidence, 'unknown-no-crossing-source');
const sourceCrossingModel = structuredClone(complexModel);
const sourceRoad = sourceCrossingModel.roads.find((road) => road.id === inferredStopLine.properties.road_id);
sourceCrossingModel.crossings = [
{
id: 'known-complex-crossing',
coordinate: inferredStopLine.geometry.coordinates[0]
.slice(0, -1)
.reduce((center, point) => [center[0] + point[0] / 4, center[1] + point[1] / 4], [0, 0]),
osmWayIds: sourceRoad.osmWayIds,
},
];
const sourceCrossingGeometry = compiler.nativeRoad.compileGeometry(
sourceCrossingModel,
{ schema: 'native-road-overrides/v1', overrides: [] },
{
edgeLines: false,
junctionTemplates: {
enabled: true,
clusters: [
{
id: 'fixture-five-arm',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
},
],
},
},
);
const sourcedComplexCrosswalk = sourceCrossingGeometry.crosswalks.features.find(
(feature) => feature.properties?.crossing_key === inferredStopLine.properties.crossing_key,
);
assert.ok(sourcedComplexCrosswalk, 'an OSM crossing node enables the matching arm crosswalk');
assert.equal(sourcedComplexCrosswalk.properties.facility_evidence, 'source-crossing-node');
assert.deepEqual(sourcedComplexCrosswalk.properties.source_crossing_node_ids, ['known-complex-crossing']);
const sourceCenter = sourceCrossingGeometry.roadSurface.features.find(
(feature) => feature.properties?.junction_structure,
)?.properties.junction_structure.center;
const sourceLatitudeScale = 111320 * Math.cos((sourceCenter[1] * Math.PI) / 180);
const sourceCrossingRadius = Math.hypot(
(sourceCrossingModel.crossings[0].coordinate[0] - sourceCenter[0]) * sourceLatitudeScale,
(sourceCrossingModel.crossings[0].coordinate[1] - sourceCenter[1]) * 111320,
);
assert.ok(
Math.abs(
sourcedComplexCrosswalk.properties.radial_distance_m -
sourceCrossingRadius -
sourcedComplexCrosswalk.properties.group_depth_m,
) < 0.1,
'complex crossing retreats by its full rectangle depth from its source station',
);
const sourcedStopLine = sourceCrossingGeometry.vehicleStopLines.features.find(
(feature) => feature.properties?.crossing_key === inferredStopLine.properties.crossing_key,
);
if (sourcedStopLine) assert.equal(sourcedStopLine.properties.facility_evidence, 'source-crossing-node');
const sourceStructure = sourceCrossingGeometry.roadSurface.features.find(
(feature) => feature.properties?.junction_structure,
)?.properties.junction_structure;
assert.equal(
sourceStructure.facilities.find((facility) => facility.key === sourcedComplexCrosswalk.properties.object_key)
.provenance.facilityEvidence,
'source-crossing-node',
);
const knownIsland = {
id: 'known-structure-island',
source: 'osm-traffic-island',
ring: [
[sourceCenter[0] - 0.00001, sourceCenter[1] - 0.00001],
[sourceCenter[0] + 0.00001, sourceCenter[1] - 0.00001],
[sourceCenter[0] + 0.00001, sourceCenter[1] + 0.00001],
[sourceCenter[0] - 0.00001, sourceCenter[1] + 0.00001],
[sourceCenter[0] - 0.00001, sourceCenter[1] - 0.00001],
],
};
const islandStructureModel = structuredClone(sourceCrossingModel);
islandStructureModel.exclusionRegions = [knownIsland];
const islandStructureGeometry = compiler.nativeRoad.compileGeometry(
islandStructureModel,
{ schema: 'native-road-overrides/v1', overrides: [] },
{
edgeLines: false,
junctionTemplates: {
enabled: true,
clusters: [
{
id: 'fixture-five-arm',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
},
],
},
},
);
const islandStructure = islandStructureGeometry.roadSurface.features.find(
(feature) => feature.properties?.junction_structure,
)?.properties.junction_structure;
assert.equal(
islandStructure.facilities.find((facility) => facility.key === 'island:osm/known-structure-island').provenance
.facilityEvidence,
'source-osm-region',
);
console.log('road compiler package tests passed');
// Stop lines must remain outside the relocated matching crossing stripes.
const polygonClipping = require('polygon-clipping');
for (const stop of sourceCrossingGeometry.vehicleStopLines.features) {
if (stop.properties.kind !== 'complex-stop-line') continue;
for (const stripe of sourceCrossingGeometry.crosswalks.features) {
if (stripe.properties.crossing_key !== stop.properties.crossing_key) continue;
assert.deepEqual(
polygonClipping.intersection(stop.geometry.coordinates, stripe.geometry.coordinates),
[],
'stop line does not intersect its crosswalk after default retreat',
);
}
}
const minimumStopGeometry = compiler.nativeRoad.compileGeometry(
sourceCrossingModel,
{ schema: 'native-road-overrides/v1', overrides: [] },
{
edgeLines: false,
junctionTemplates: {
enabled: true,
clusters: [
{
id: 'fixture-five-arm',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
},
],
},
directEdit: {
clusterCrossings: new Map([
[
'fixture-five-arm',
new Map(
sourceCrossingGeometry.vehicleStopLines.features
.filter((f) => f.properties.kind === 'complex-stop-line')
.map((f) => [f.properties.crossing_key, { stopLineOffsetMeters: 0.5 }]),
),
],
]),
},
},
);
const minimumStops = minimumStopGeometry.vehicleStopLines.features.filter(
(f) => f.properties.kind === 'complex-stop-line',
);
assert.ok(minimumStops.length > 0);
for (const stop of minimumStops) {
for (const stripe of minimumStopGeometry.crosswalks.features) {
if (stripe.properties.crossing_key !== stop.properties.crossing_key) continue;
assert.deepEqual(
polygonClipping.intersection(stop.geometry.coordinates, stripe.geometry.coordinates),
[],
'minimum stop offset must not overlap its matching crossing',
);
}
}