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
+1353 -92

No files matched your search

+57
View File
@@ -298,3 +298,60 @@ document byte-identical; warnings remain saveable. This prevents a client from
skipping preview and persisting a width, corner radius, crossing offset, or skipping preview and persisting a width, corner radius, crossing offset, or
stop-line value that the compiler rejects. Version conflicts are checked first stop-line value that the compiler rejects. Version conflicts are checked first
and continue to return HTTP 409 without invoking geometry validation writes. and continue to return HTTP 409 without invoking geometry validation writes.
## 16. Scoped complex junction identity
### Scope and signatures
Stage 1 establishes the read model consumed by later cluster editing. Use
`resolveComplexJunctionTopology(model, cluster, helpers)` in complex geometry,
then `structureFromTopology(topology, shape, center, features)`. Projection is
`projectJunctionStructure({ model, layers, trafficSignals, junctionRef })`.
### Contracts
- `junctionRef` is `{ type: 'node' | 'cluster', id }`. Explicit `null` means no
junction projection; unknown references return `null`, never the first core.
- `GET /api/state` returns `junctionStructures`, keyed by `node:<id>` and
`cluster:<id>`. The legacy singular field is null at this unscoped entry point.
- `GET /api/edit-state?junction=<node>` preserves the node selection contract;
`?cluster=<id>` selects a cluster. Preview uses the equivalent `selection`
object. Cluster handle manifests are empty until a future writable contract.
- Complex road-surface features carry `junction_key`, `object_key` and relevant
`arm_key`, `carriageway_key`, `corner_key`. Core (or the first remaining
approach when the core fails) carries `junction_structure` for persisted reads.
- Stable keys derive from cluster and sorted source node/segment/road IDs, with
corner keys derived from adjacent arms. Display indices and headings are not
object identities. `topologyFingerprint` detects source topology changes.
- Root provenance lists member nodes and external road/segment IDs. Arms point
to carriageways, corners to arms, facilities to feature IDs; normalizers must
preserve these fields and readonly capabilities across JSON round trips.
- Signal projection joins exact member `node_id` / `control_id`, retaining the
existing `signal_uid` as `geometryRef` and `provenance.featureIds`. It does not
rewrite the separately persisted signal document or guess from UID substrings.
### Validation matrix
| Input | Result |
| --- | --- |
| Multiple selection keys or repeated query keys | 400, no implicit priority |
| Empty/object-valued ID | 400 |
| Unknown node/cluster or missing compiled complex structure | null structure, empty diagnostics |
| Missing/ambiguous object source | readonly capability with reason |
| Explicit cluster selection | empty handles; never all-area or member-node handles |
### Cases and tests
Good: reorder member/road arrays and retain semantic IDs; delete a source and
change its identity/fingerprint. Base: legacy node editing still works. Bad:
opening cluster B while rendering cluster A's first core. Test the 3/4/offset/5+
arm matrix, two-cluster isolation, internal-link exclusion, grouped crossings,
scoped signals, JSON round trips, and persisted/preview projection equality.
```js
// Wrong: chooses an arbitrary junction and loses the selected scope.
projectJunctionStructure({ model, layers });
// Correct for a scoped editor:
projectJunctionStructure({ model, layers, trafficSignals,
junctionRef: { type: 'cluster', id: selectedClusterId } });
```
@@ -271,3 +271,28 @@ The same internal node layout can resolve to different external-arm topology.
If no summary exists, omit the shape row and retain normal cluster context; do If no summary exists, omit the shape row and retain normal cluster context; do
not show an inferred fallback. The compiler's safe fallback has no complex core not show an inferred fallback. The compiler's safe fallback has no complex core
and therefore no summary. and therefore no summary.
## 16. Scoped structure and semantic map selection
Use `structureForJunction(state, ref)` to read `state.junctionStructures`; do not
reuse the unscoped singular structure when its ref differs. A missing structure
stays unavailable. Use `junctionEditSelection(ref)` for edit-state and preview
requests so a cluster never falls back to the last selected road or node.
Compiler structure provenance supplies cluster hotspots and external road IDs.
`localJunctionState` and `localJunctionPreview` recognize explicit `junction_key`
(and legacy `cluster_id`) before testing node/road references. This keeps core
and corner features that do not carry member node IDs and excludes neighboring
clusters even if a connecting road is shared.
Map/list selection goes through `junctionObjectKeyForFeature` and
`junctionObjectFeatures`: compiler keys identify arms/corners/crossing groups;
signal UIDs resolve through scoped facility provenance. Display labels and row
indices are never parsed into IDs. Highlighting is a read-only overlay, allocated
when selecting an object; it must not mutate baseline features or rebuild the
map. On scope changes clear object selection and ignore obsolete manifest loads.
Map capability reason codes into user-facing Chinese descriptions.
Required checks: opposite node/cluster scopes with equal raw IDs, unknown scope,
list-to-feature grouping and feature-to-list identity, foreign-cluster exclusion,
raw signal UID selection, map identity preservation, and reload stability.
+114 -27
View File
@@ -1,6 +1,7 @@
'use strict'; 'use strict';
const fs = require('fs'); const fs = require('fs');
const { topologyIdentity, structureFromTopology } = require('./junction-topology');
const { convertGeoJson, boundsOf } = require('../reference/gaode'); const { convertGeoJson, boundsOf } = require('../reference/gaode');
const metricsCache = new WeakMap(); const metricsCache = new WeakMap();
const CORNER_FILLET_SEGMENTS = 12; 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. // past that end and let the two overlap rather than chase an exact seam.
const SIDEWALK_CORNER_OVERRUN_METERS = 6; 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) { function buildComplexJunctionGeometry(model, cluster, helpers) {
const nodeIds = new Set(cluster.nodeIds.map(String)); const nodeIds = new Set(cluster.nodeIds.map(String));
const nodes = cluster.nodeIds.map((id) => helpers.junctionPlans.get(String(id))?.node).filter(Boolean); 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], (sum, point) => [sum[0] + point[0] / nodes.length, sum[1] + point[1] / nodes.length],
[0, 0], [0, 0],
); );
const approaches = []; const topology = resolveComplexJunctionTopology(model, cluster, helpers);
const carriageways = []; const { carriageways, arms } = topology;
for (const [nodeId, plan] of helpers.junctionPlans) { const approaches = arms.map((arm) => arm.representative);
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 });
}
}
if (approaches.length < 3) if (approaches.length < 3)
return { return {
features: [], features: [],
@@ -62,18 +128,7 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
], ],
}; };
const { calibration, coreRadius } = complexJunctionMetrics(cluster); const { calibration, coreRadius } = complexJunctionMetrics(cluster);
const sorted = [...approaches].sort((a, b) => a.heading - b.heading); const sorted = approaches;
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 shape = classifyJunctionShape(arms, center, helpers); const shape = classifyJunctionShape(arms, center, helpers);
if (shape.kind === 'unsupported') if (shape.kind === 'unsupported')
return { return {
@@ -141,6 +196,9 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
type: 'Feature', type: 'Feature',
properties: { properties: {
native_id: `complex-stop-line:${cluster.id}:${item.approach.segmentId}`, 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, cluster_id: cluster.id,
kind: 'complex-stop-line', kind: 'complex-stop-line',
road_id: incomingRoad.id, road_id: incomingRoad.id,
@@ -223,6 +281,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
type: 'Feature', type: 'Feature',
properties: { properties: {
native_id: `complex-crosswalk:${cluster.id}:${item.nodeId}:${item.approach.segmentId}:${stripe + 1}`, 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, cluster_id: cluster.id,
kind: 'complex-crosswalk', kind: 'complex-crosswalk',
crossing_node_id: item.nodeId, crossing_node_id: item.nodeId,
@@ -290,6 +350,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
native_id: `complex-corner-island:${cluster.id}:${index + 1}`, native_id: `complex-corner-island:${cluster.id}:${index + 1}`,
cluster_id: cluster.id, cluster_id: cluster.id,
kind: 'complex-corner-island', kind: 'complex-corner-island',
object_key: `island:${first.cornerKey}`,
corner_key: first.cornerKey,
corner_index: index + 1, corner_index: index + 1,
from_heading: first.heading, from_heading: first.heading,
to_heading: second.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}`, native_id: `complex-corner-crosswalk:${cluster.id}:${index + 1}:${stripe + 1}`,
cluster_id: cluster.id, cluster_id: cluster.id,
kind: 'complex-corner-crosswalk', kind: 'complex-corner-crosswalk',
object_key: `crossing:${first.cornerKey}`,
corner_key: first.cornerKey,
corner_index: index + 1, corner_index: index + 1,
direction: bisector, direction: bisector,
radial_distance_m: stripeRadius, radial_distance_m: stripeRadius,
@@ -394,6 +458,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
native_id: `complex-corner-fillet:${cluster.id}:${index + 1}`, native_id: `complex-corner-fillet:${cluster.id}:${index + 1}`,
cluster_id: cluster.id, cluster_id: cluster.id,
kind: 'complex-corner-fillet', kind: 'complex-corner-fillet',
object_key: first.cornerKey,
corner_key: first.cornerKey,
complex_part: 'corner-fillet', complex_part: 'corner-fillet',
corner_index: index + 1, corner_index: index + 1,
from_heading: first.heading, from_heading: first.heading,
@@ -453,6 +519,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
native_id: `complex-sidewalk-corner:${cluster.id}:${index + 1}`, native_id: `complex-sidewalk-corner:${cluster.id}:${index + 1}`,
cluster_id: cluster.id, cluster_id: cluster.id,
kind: 'complex-sidewalk-corner', kind: 'complex-sidewalk-corner',
object_key: `sidewalk-turn:${first.cornerKey}`,
corner_key: first.cornerKey,
corner_index: index + 1, corner_index: index + 1,
from_heading: first.heading, from_heading: first.heading,
to_heading: second.heading, to_heading: second.heading,
@@ -530,6 +598,9 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
native_id: `complex-junction:${cluster.id}:carriageway:${item.approach.segmentId}`, native_id: `complex-junction:${cluster.id}:carriageway:${item.approach.segmentId}`,
cluster_id: cluster.id, cluster_id: cluster.id,
kind: 'complex-approach', kind: 'complex-approach',
object_key: item.key,
carriageway_key: item.key,
arm_key: item.armKey,
complex_part: 'carriageway', complex_part: 'carriageway',
heading_deg: item.heading, heading_deg: item.heading,
lane_count: item.approach.roadIds.reduce( 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 { return {
structure,
features, features,
islands: [...islands, ...sidewalkCorners], islands: [...islands, ...sidewalkCorners],
crosswalks, 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]; 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,
};
+2
View File
@@ -1093,6 +1093,8 @@ function makeJunctionHandles(model, junctionData, constraints) {
*/ */
function selectHandles(handles, model, selection) { function selectHandles(handles, model, selection) {
if (!selection || !selection.type) return handles; 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') { if (selection.type === 'segment') {
const segmentOf = new Map((model.roads || []).map((road) => [road.id, road.segmentId])); const segmentOf = new Map((model.roads || []).map((road) => [road.id, road.segmentId]));
const wanted = String(selection.id); const wanted = String(selection.id);
+73 -25
View File
@@ -11,30 +11,57 @@ function heading(from, to) {
return (Math.atan2(to[0] - from[0], to[1] - from[1]) * 180) / Math.PI; 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({ function projectJunctionStructure({
model = {}, model = {},
layers = {}, layers = {},
trafficSignals = null, trafficSignals = null,
shape = null, shape = null,
junctionKey = null, junctionKey = null,
junctionRef = undefined,
} = {}) { } = {}) {
if (junctionRef === null) return null;
const roads = Array.isArray(model.roads) ? model.roads : []; const roads = Array.isArray(model.roads) ? model.roads : [];
const endpoints = Array.isArray(model.endpoints) ? model.endpoints : []; const endpoints = Array.isArray(model.endpoints) ? model.endpoints : [];
const core = featureCollection(layers.intersectionSurface).find( if (junctionRef && !['node', 'cluster'].includes(junctionRef.type))
(feature) => feature.properties?.kind === 'complex-core', 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,
); );
const properties = core?.properties || {}; if (!carrier) return null;
const key = String(junctionKey || properties.cluster_id || endpoints[0]?.nodeId || 'junction:area'); const structure = buildJunctionStructure(carrier.properties.junction_structure);
const center = pointOf(core) || endpoints[0]?.coordinate || [0, 0]; const nodeIds = new Set(structure.provenance?.nodeIds || []);
const junctionNodeId = String(junctionKey || properties.cluster_id ? endpoints[0]?.nodeId || '' : key); 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(); const endpointByNode = new Map();
for (const endpoint of endpoints) endpointByNode.set(String(endpoint.nodeId), endpoint); for (const endpoint of endpoints) endpointByNode.set(String(endpoint.nodeId), endpoint);
const arms = roads const arms = roads
@@ -48,7 +75,13 @@ function projectJunctionStructure({
return { return {
key: `road-arm:${road.id || index + 1}`, key: `road-arm:${road.id || index + 1}`,
label: String(road.tags?.name || road.name || `道路 ${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: directionality:
road.direction === 'oneway' || road.direction === 'one-way' road.direction === 'oneway' || road.direction === 'one-way'
? 'one-way' ? 'one-way'
@@ -64,27 +97,37 @@ function projectJunctionStructure({
sourceRoadId: String(road.id || ''), sourceRoadId: String(road.id || ''),
}; };
}) })
.filter(Boolean); .filter(Boolean)
.sort((a, b) => a.heading - b.heading);
const corners = const corners =
arms.length > 1 arms.length > 1
? arms.map((arm, index) => { ? arms.map((arm, index) => {
const next = arms[(index + 1) % arms.length]; const next = arms[(index + 1) % arms.length];
return { return {
key: `corner:${index + 1}`, key: `corner:${arm.key}>${next.key}`,
label: `角部 ${index + 1}`, label: `角部 ${index + 1}`,
fromArmKey: arm.key, fromArmKey: arm.key,
toArmKey: next.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 facilities = [];
const crossingKeys = [];
for (const [kind, collection] of [ for (const [kind, collection] of [
['crossing', layers.crosswalks], ['crossing', layers.crosswalks],
['stop-line', layers.vehicleStopLines], ['stop-line', layers.vehicleStopLines],
]) { ]) {
featureCollection(collection).forEach((feature, index) => { featureCollection(collection)
.filter(inScope)
.forEach((feature, index) => {
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`; const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
facilities.push({ facilities.push({
key: String(id), key: String(id),
@@ -92,13 +135,15 @@ function projectJunctionStructure({
label: kind === 'crossing' ? `人行横道 ${index + 1}` : `停止线 ${index + 1}`, label: kind === 'crossing' ? `人行横道 ${index + 1}` : `停止线 ${index + 1}`,
geometryRef: String(id), 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 id = feature.properties?.signal_uid || feature.properties?.id || `signal:${index + 1}`;
const signalNode = feature.properties?.node_id || feature.properties?.control_id; 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({ facilities.push({
key: String(id), key: String(id),
kind: 'signal', kind: 'signal',
@@ -112,7 +157,9 @@ function projectJunctionStructure({
['median', layers.medians], ['median', layers.medians],
['sidewalk-turn', layers.sidewalkTurns], ['sidewalk-turn', layers.sidewalkTurns],
]) { ]) {
featureCollection(collection).forEach((feature, index) => { featureCollection(collection)
.filter(inScope)
.forEach((feature, index) => {
if (feature.properties?.kind !== kind) return; if (feature.properties?.kind !== kind) return;
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`; const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
facilities.push({ facilities.push({
@@ -134,6 +181,7 @@ function projectJunctionStructure({
(arms.length === 3 ? 't-junction' : arms.length >= 5 ? 'multi-arm' : arms.length === 4 ? 'cross' : 'unsupported'); (arms.length === 3 ? 't-junction' : arms.length >= 5 ? 'multi-arm' : arms.length === 4 ? 'cross' : 'unsupported');
return buildJunctionStructure({ return buildJunctionStructure({
junctionKey: key, junctionKey: key,
junctionRef: { type: 'node', id: junctionNodeId },
label: properties.shape_label || '路口', label: properties.shape_label || '路口',
center, center,
shape: { shape: {
@@ -151,7 +199,7 @@ function projectJunctionStructure({
function standardsDiagnostics(structure, profile = CN_URBAN_DEFAULT_PROFILE) { function standardsDiagnostics(structure, profile = CN_URBAN_DEFAULT_PROFILE) {
const diagnostics = []; 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 rule = profile.rules.find((item) => item.id === 'effective-carriageway-width');
const severity = evaluateRange(arm.carriageway.effectiveWidthMeters, rule); const severity = evaluateRange(arm.carriageway.effectiveWidthMeters, rule);
diagnostics.push({ diagnostics.push({
+55
View File
@@ -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) { function normalizeRoadArm(input, index) {
const key = objectKey(input.key, `road-arm:${index + 1}`); const key = objectKey(input.key, `road-arm:${index + 1}`);
const label = readableLabel(input.label, `道路 ${index + 1}`); const label = readableLabel(input.label, `道路 ${index + 1}`);
@@ -43,9 +71,22 @@ function normalizeRoadArm(input, index) {
const carriageway = input.carriageway || {}; const carriageway = input.carriageway || {};
const normalized = { const normalized = {
key, key,
...metadata(input),
label, label,
heading: finiteNumber(input.heading ?? 0, 'arm heading'), heading: finiteNumber(input.heading ?? 0, 'arm heading'),
directionality, 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: {
...(carriageway.laneCount === undefined ...(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`); if (fromArmKey === toArmKey) throw new Error(`Junction corner ${key} must connect two different road arms`);
return { return {
key, key,
...metadata(input),
label: readableLabel(input.label, `角部 ${index + 1}`), label: readableLabel(input.label, `角部 ${index + 1}`),
fromArmKey, fromArmKey,
toArmKey, toArmKey,
@@ -95,6 +137,7 @@ function normalizeFacility(input, index) {
const key = objectKey(input.key, `${kind}:${index + 1}`); const key = objectKey(input.key, `${kind}:${index + 1}`);
return { return {
key, key,
...metadata(input),
kind, kind,
label: readableLabel(input.label, kind === 'crossing' ? `人行横道 ${index + 1}` : `设施 ${index + 1}`), label: readableLabel(input.label, kind === 'crossing' ? `人行横道 ${index + 1}` : `设施 ${index + 1}`),
...(input.armKey ? { armKey: String(input.armKey) } : {}), ...(input.armKey ? { armKey: String(input.armKey) } : {}),
@@ -121,6 +164,10 @@ function buildJunctionStructure(input = {}) {
const kind = String(shape.kind || 'unsupported'); const kind = String(shape.kind || 'unsupported');
if (!SHAPE_KINDS.has(kind)) throw new Error(`Unsupported junction shape kind: ${kind}`); if (!SHAPE_KINDS.has(kind)) throw new Error(`Unsupported junction shape kind: ${kind}`);
const arms = (input.arms || []).map(normalizeRoadArm); const arms = (input.arms || []).map(normalizeRoadArm);
assertUniqueKeys(
arms.flatMap((arm) => arm.carriageways || []),
'carriageway',
);
const armKeys = assertUniqueKeys(arms, 'road arm'); const armKeys = assertUniqueKeys(arms, 'road arm');
const corners = (input.corners || []).map(normalizeCorner); const corners = (input.corners || []).map(normalizeCorner);
const cornerKeys = assertUniqueKeys(corners, 'corner'); const cornerKeys = assertUniqueKeys(corners, 'corner');
@@ -141,7 +188,15 @@ function buildJunctionStructure(input = {}) {
finiteNumber(effectiveArmCount, 'effective arm count', { integer: true, minimum: 0 }); finiteNumber(effectiveArmCount, 'effective arm count', { integer: true, minimum: 0 });
if (effectiveArmCount !== arms.length) if (effectiveArmCount !== arms.length)
throw new Error('Junction effective arm count must match the supplied road arms'); 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 { 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, schema: JUNCTION_STRUCTURE_SCHEMA,
junctionKey: objectKey(input.junctionKey, 'junction:unknown'), junctionKey: objectKey(input.junctionKey, 'junction:unknown'),
label: readableLabel(input.label, '未命名路口'), label: readableLabel(input.label, '未命名路口'),
+130
View File
@@ -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 };
+7 -1
View File
@@ -24,7 +24,13 @@ fs.writeFileSync(
fs.readFileSync(path.join(__dirname, '..', 'outputs', 'fengshu-er-road', 'native-traffic-signals.json')), fs.readFileSync(path.join(__dirname, '..', 'outputs', 'fengshu-er-road', 'native-traffic-signals.json')),
); );
const server = startWorkbench({ input, repoRoot: path.resolve(__dirname, '..'), dataRoot: root, port: 8899 }); const server = startWorkbench({
input,
repoRoot: path.resolve(__dirname, '..'),
dataRoot: root,
debug: true,
port: 8899,
});
const cleanup = () => { const cleanup = () => {
server.close(() => fs.rmSync(root, { recursive: true, force: true })); server.close(() => fs.rmSync(root, { recursive: true, force: true }));
}; };
+60
View File
@@ -1,6 +1,9 @@
import fs from 'node:fs'; import fs from 'node:fs';
import { expect, test } from '@playwright/test'; import { expect, test } from '@playwright/test';
import { strFromU8, unzipSync } from 'fflate'; import { strFromU8, unzipSync } from 'fflate';
import type OLMap from 'ol/Map';
import type VectorLayer from 'ol/layer/Vector';
import type VectorSource from 'ol/source/Vector';
test.describe('workbench editing shell', () => { test.describe('workbench editing shell', () => {
test.beforeEach(async ({ page }) => { test.beforeEach(async ({ page }) => {
@@ -194,4 +197,61 @@ test.describe('workbench editing shell', () => {
await page.getByRole('button', { name: '放弃草稿' }).click(); await page.getByRole('button', { name: '放弃草稿' }).click();
await expect(heading).toHaveValue(original); await expect(heading).toHaveValue(original);
}); });
test('keeps complex junction structure and map selection linked across reload', async ({ page }) => {
const initial = await page.request.get('/api/state').then((response) => response.json());
const candidate = initial.debug.junctionCandidates.find((item: { nodeIds: string[] }) => item.nodeIds.length >= 3);
expect(candidate).toBeTruthy();
const acceptedResponse = await page.request.post('/api/junction-clusters', {
data: { candidateId: candidate.id, nodeIds: candidate.nodeIds },
});
expect(acceptedResponse.ok()).toBe(true);
const accepted = await acceptedResponse.json();
const id = accepted.added.id;
const structure = accepted.junctionStructures[`cluster:${id}`];
expect(structure.arms.length).toBeGreaterThanOrEqual(3);
await page.goto(`/junction/cluster/${encodeURIComponent(id)}`);
const workspace = page.getByLabel('路口编辑工作区');
await expect(workspace).toBeVisible();
const armButtons = workspace.locator('.junction-workspace__object-list').first().getByRole('button');
await expect(armButtons).toHaveCount(structure.arms.length);
const map = await page
.getByLabel('道路地图')
.evaluateHandle((element) => (element as HTMLDivElement & { __roadWorkbenchMap: OLMap }).__roadWorkbenchMap);
await armButtons.first().click();
await expect(armButtons.first()).toHaveAttribute('aria-pressed', 'true');
await expect
.poll(async () =>
page.getByLabel('道路地图').evaluate((element) => {
const map = (element as HTMLDivElement & { __roadWorkbenchMap: OLMap }).__roadWorkbenchMap;
const layer = map
.getLayers()
.getArray()
.find((item) => item.getZIndex() === 89) as VectorLayer<VectorSource> | undefined;
return layer?.getSource()?.getFeatures().length || 0;
}),
)
.toBeGreaterThan(0);
const sameMap = await page
.getByLabel('道路地图')
.evaluate(
(element, original) =>
(element as HTMLDivElement & { __roadWorkbenchMap: OLMap }).__roadWorkbenchMap === original,
map,
);
expect(sameMap).toBe(true);
await expect(workspace.getByText('路口参数', { exact: true })).toHaveCount(0);
const scoped = await page.request
.get(`/api/edit-state?cluster=${encodeURIComponent(id)}`)
.then((response) => response.json());
expect(scoped.handles.handles).toEqual([]);
expect(scoped.junctionStructure.topologyFingerprint).toBe(structure.topologyFingerprint);
await page.reload();
await expect(armButtons).toHaveCount(structure.arms.length);
await expect(armButtons.first()).toHaveAttribute('aria-pressed', 'false');
const refreshed = await page.request.get('/api/state').then((response) => response.json());
expect(refreshed.junctionStructures[`cluster:${id}`].arms.map((arm: { key: string }) => arm.key)).toEqual(
structure.arms.map((arm: { key: string }) => arm.key),
);
});
}); });
+211
View File
@@ -93,3 +93,214 @@ assert.equal(diagnostics[1].severity, 'warning');
assert.equal(diagnostics[1].objectKey, 'road-arm:road:east'); assert.equal(diagnostics[1].objectKey, 'road-arm:road:east');
console.log('junction projection tests passed'); 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'),
);
}
+103 -1
View File
@@ -7,7 +7,14 @@ const path = require('path');
const { compileInput } = require('../src/compile/compiler'); const { compileInput } = require('../src/compile/compiler');
const { compileRoadModel, loadOverrides } = require('../src/compile/native-road'); const { compileRoadModel, loadOverrides } = require('../src/compile/native-road');
const { ensureRevisionStore } = require('../src/compile/road-revisions'); const { ensureRevisionStore } = require('../src/compile/road-revisions');
const { editPreview, editState, rebaseEdits, saveEdits } = require('../workbench/server'); const {
editPreview,
editState,
rebaseEdits,
saveEdits,
state: browseState,
selectionFrom,
} = require('../workbench/server');
const { snapshot: outputSnapshot } = require('./fixture-baseline'); const { snapshot: outputSnapshot } = require('./fixture-baseline');
const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'workbench-edit-api-')); const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'workbench-edit-api-'));
@@ -219,5 +226,100 @@ assert.notDeepEqual(
'a saved constraint must change the compiled output, or saving cannot survive a refresh', 'a saved constraint must change the compiled output, or saving cannot survive a refresh',
); );
// Typed scope must survive parsing and cannot silently choose the first key.
assert.deepEqual(selectionFrom(new URLSearchParams('cluster=fixture-five-arm')), {
type: 'cluster',
id: 'fixture-five-arm',
});
assert.deepEqual(selectionFrom({ junction: '8005332807' }), { type: 'junction', id: '8005332807' });
for (const invalid of [
{ cluster: 'one', junction: 'two' },
{ cluster: '' },
{ cluster: {} },
new URLSearchParams('cluster=one&cluster=two'),
]) {
assert.throws(() => selectionFrom(invalid), /selection/);
}
assert.throws(() => editPreview(area, { selection: { cluster: 'one', segment: 'two' } }), /selection/);
const cluster = {
id: 'fixture-five-arm',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
};
const complexInput = {
...input,
outDir: path.join(workspace, 'outputs', 'complex'),
stagingDir: path.join(workspace, 'outputs', '_complex'),
options: { edgeLines: false, junctionTemplates: { enabled: true, clusters: [cluster] } },
};
const complexArea = compileInput(complexInput).area;
const clusterState = editState(complexArea, selectionFrom({ cluster: cluster.id }));
assert.deepEqual(clusterState.handles.handles, [], 'cluster selection must never fall through to node handles');
assert.deepEqual(clusterState.junctionStructure.junctionRef, { type: 'cluster', id: cluster.id });
assert.equal(clusterState.junctionStructure.shape.effectiveArmCount, 5);
assert.equal(clusterState.junctionStructure.capability.editable, false);
const complexTracked = trackedFiles.map(({ file }) => ({
file,
bytes: fs.readFileSync(file),
mtimeMs: fs.statSync(file).mtimeMs,
}));
const emptyDocument = { ...clusterState.document, constraints: [], operations: [] };
const clusterPreview = editPreview(complexArea, { document: emptyDocument, selection: { cluster: cluster.id } });
assert.deepEqual(clusterPreview.handles.handles, []);
assert.deepEqual(
clusterPreview.junctionStructure,
clusterState.junctionStructure,
'preview and persisted compiler structure agree',
);
const browsing = browseState(complexArea);
const unavailableStructureState = browseState({
...complexArea,
nativeRoad: {
...complexArea.nativeRoad,
junctionTemplates: {
...complexArea.nativeRoad.junctionTemplates,
clusters: [
...complexArea.nativeRoad.junctionTemplates.clusters,
{ id: 'not-compiled', template: 'complex-junction-v1', nodeIds: ['missing-1', 'missing-2'] },
],
},
},
});
assert.equal(unavailableStructureState.junctionStructures['cluster:not-compiled'], undefined);
assert.ok(browsing.standardsDiagnostics.length, 'browse state retains structure diagnostics');
assert.equal(new Set(browsing.standardsDiagnostics.map((item) => item.id)).size, browsing.standardsDiagnostics.length);
assert.ok(
Object.values(browsing.junctionStructures).every(Boolean),
'the structure index contains only available structures',
);
assert.deepEqual(browsing.junctionStructures[`cluster:${cluster.id}`], clusterState.junctionStructure);
const simpleKey = Object.keys(browsing.junctionStructures).find(
(key) => key.startsWith('node:') && !cluster.nodeIds.includes(key.slice(5)),
);
assert.ok(simpleKey, 'fixture includes a simple junction outside the cluster');
const simpleState = editState(complexArea, selectionFrom({ junction: simpleKey.slice(5) }));
assert.deepEqual(simpleState.junctionStructure, browsing.junctionStructures[simpleKey]);
assert.equal(simpleState.junctionStructure.junctionRef.type, 'node');
for (const item of clusterState.standardsDiagnostics) {
assert.ok(browsing.standardsDiagnostics.some((candidate) => candidate.id === item.id));
}
assert.ok(simpleState.handles.handles.length);
for (const type of ['cluster', 'junction']) {
const missing = editState(complexArea, selectionFrom({ [type]: 'missing-junction' }));
assert.equal(missing.junctionStructure, null);
assert.deepEqual(missing.handles.handles, []);
assert.deepEqual(missing.standardsDiagnostics, []);
assert.equal(
editPreview(complexArea, { document: emptyDocument, selection: { [type]: 'missing-junction' } }).junctionStructure,
null,
);
}
for (const tracked of complexTracked) {
assert.deepEqual(fs.readFileSync(tracked.file), tracked.bytes, 'scoped reads and previews preserve active files');
assert.equal(fs.statSync(tracked.file).mtimeMs, tracked.mtimeMs);
}
fs.rmSync(workspace, { recursive: true, force: true }); fs.rmSync(workspace, { recursive: true, force: true });
console.log('workbench edit API tests passed'); console.log('workbench edit API tests passed');
+26 -6
View File
@@ -57,6 +57,12 @@ import type { JunctionRef } from './junction/hotspots';
import { candidateForJunction, junctionDescriptors, hotspotAt } from './junction/hotspots'; import { candidateForJunction, junctionDescriptors, hotspotAt } from './junction/hotspots';
import { JunctionWorkspace } from './junction/JunctionWorkspace'; import { JunctionWorkspace } from './junction/JunctionWorkspace';
import { localJunctionPreview, localJunctionState } from './junction/local-state'; import { localJunctionPreview, localJunctionState } from './junction/local-state';
import {
junctionEditSelection,
junctionObjectFeatures,
junctionObjectKeyForFeature,
structureForJunction,
} from './junction/structure';
import { import {
applyJunctionDraft, applyJunctionDraft,
cancelJunctionSession, cancelJunctionSession,
@@ -164,7 +170,7 @@ function App() {
editMode, editMode,
state, state,
selectedSegmentId: selected?.segmentId, selectedSegmentId: selected?.segmentId,
selectedJunctionId: junctionRoute?.type === 'node' ? junctionRoute.id : undefined, selectedJunction: junctionRoute,
setStatus, setStatus,
}); });
const { const {
@@ -206,6 +212,17 @@ function App() {
() => (state && junctionDescriptor && junctionRoute ? localJunctionState(state, junctionDescriptor) : state), () => (state && junctionDescriptor && junctionRoute ? localJunctionState(state, junctionDescriptor) : state),
[junctionDescriptor, junctionRoute, state], [junctionDescriptor, junctionRoute, state],
); );
const junctionStructure = useMemo(
() => (junctionRoute ? structureForJunction(state, junctionRoute) : null),
[junctionRoute, state],
);
const junctionSelectionFeatures = useMemo(
() => junctionObjectFeatures(state, junctionStructure, selectedObjectKey),
[state, junctionStructure, selectedObjectKey],
);
useEffect(() => {
setSelectedObjectKey(null);
}, [junctionRoute]);
const junctionMapPreview = useMemo( const junctionMapPreview = useMemo(
() => () =>
state && junctionDescriptor && junctionRoute state && junctionDescriptor && junctionRoute
@@ -417,9 +434,8 @@ function App() {
// fall back to the approach segment here: doing so makes an accepted preview // fall back to the approach segment here: doing so makes an accepted preview
// replace the junction manifest with a road-scoped one, which drops the // replace the junction manifest with a road-scoped one, which drops the
// width/cutback/radius rows immediately after the first edit. // width/cutback/radius rows immediately after the first edit.
selectionRef.current = selectionRef.current = junctionRoute
junctionRoute?.type === 'node' ? junctionEditSelection(junctionRoute)
? { junction: junctionRoute.id }
: selected?.segmentId : selected?.segmentId
? { segment: selected.segmentId } ? { segment: selected.segmentId }
: undefined; : undefined;
@@ -902,7 +918,9 @@ function App() {
}; };
const handleFeature = (properties: Record<string, unknown>) => { const handleFeature = (properties: Record<string, unknown>) => {
setMarking(properties); setMarking(properties);
const objectKey = properties.signal_uid const objectKey = junctionStructure
? junctionObjectKeyForFeature(junctionStructure, properties)
: properties.signal_uid
? `signal:${String(properties.signal_uid)}` ? `signal:${String(properties.signal_uid)}`
: properties.crossing_node_id : properties.crossing_node_id
? `${properties.provenance === 'stop-line' ? 'stop-line' : 'crossing'}:${String(properties.crossing_node_id)}` ? `${properties.provenance === 'stop-line' ? 'stop-line' : 'crossing'}:${String(properties.crossing_node_id)}`
@@ -1065,6 +1083,7 @@ function App() {
scene={scene} scene={scene}
junctionHotspots={junctionHotspots} junctionHotspots={junctionHotspots}
junctionNodeMarkers={junctionNodeMarkers} junctionNodeMarkers={junctionNodeMarkers}
junctionSelectionFeatures={junctionSelectionFeatures}
referenceOpacity={referenceOpacity} referenceOpacity={referenceOpacity}
onJunctionHotspot={(ref: JunctionRef, _coordinate, descriptor) => { onJunctionHotspot={(ref: JunctionRef, _coordinate, descriptor) => {
openJunction(ref); openJunction(ref);
@@ -1080,6 +1099,7 @@ function App() {
onBackground={() => { onBackground={() => {
setElement(null); setElement(null);
setMarking(null); setMarking(null);
setSelectedObjectKey(null);
}} }}
onSignalDrag={moveSignal} onSignalDrag={moveSignal}
onSignalDragEnd={finishSignalMove} onSignalDragEnd={finishSignalMove}
@@ -1178,7 +1198,7 @@ function App() {
descriptor={junctionDescriptor} descriptor={junctionDescriptor}
session={junctionSession} session={junctionSession}
dirty={Boolean(junctionSession.dirty || signalDirty)} dirty={Boolean(junctionSession.dirty || signalDirty)}
state={state} state={junctionMapState}
diagnostics={junctionDiagnostics} diagnostics={junctionDiagnostics}
selectedObjectKey={selectedObjectKey} selectedObjectKey={selectedObjectKey}
onSelectObject={(key) => setSelectedObjectKey(key)} onSelectObject={(key) => setSelectedObjectKey(key)}
@@ -1,5 +1,6 @@
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
import Feature from 'ol/Feature'; import Feature from 'ol/Feature';
import GeoJSON from 'ol/format/GeoJSON';
import LineString from 'ol/geom/LineString'; import LineString from 'ol/geom/LineString';
import Map from 'ol/Map'; import Map from 'ol/Map';
import Point from 'ol/geom/Point'; import Point from 'ol/geom/Point';
@@ -78,6 +79,8 @@ interface Props {
junctionHotspots?: boolean; junctionHotspots?: boolean;
onJunctionHotspot?: (ref: JunctionRef, coordinate: Coordinate, descriptor: JunctionDescriptor) => void; onJunctionHotspot?: (ref: JunctionRef, coordinate: Coordinate, descriptor: JunctionDescriptor) => void;
junctionNodeMarkers?: Array<{ coordinate: Coordinate; label: string; selected: boolean }>; junctionNodeMarkers?: Array<{ coordinate: Coordinate; label: string; selected: boolean }>;
/** Read-only semantic object selection from the compiler's stable object keys. */
junctionSelectionFeatures?: GeoJson['features'];
referenceOpacity?: number; referenceOpacity?: number;
} }
export function MapCanvas({ export function MapCanvas({
@@ -115,6 +118,7 @@ export function MapCanvas({
junctionHotspots = true, junctionHotspots = true,
onJunctionHotspot, onJunctionHotspot,
junctionNodeMarkers = [], junctionNodeMarkers = [],
junctionSelectionFeatures,
referenceOpacity = 0.55, referenceOpacity = 0.55,
}: Props) { }: Props) {
const target = useRef<HTMLDivElement>(null); const target = useRef<HTMLDivElement>(null);
@@ -129,6 +133,7 @@ export function MapCanvas({
const laneSelectionLayerRef = useRef<VectorLayer<VectorSource> | null>(null); const laneSelectionLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
const signalTransformSourceRef = useRef<VectorSource | null>(null); const signalTransformSourceRef = useRef<VectorSource | null>(null);
const signalTransformLayerRef = useRef<VectorLayer<VectorSource> | null>(null); const signalTransformLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
const junctionSelectionLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
const junctionNodeMarkerSourceRef = useRef<VectorSource | null>(null); const junctionNodeMarkerSourceRef = useRef<VectorSource | null>(null);
const laneSelectionFeaturesRef = useRef<Feature[]>([]); const laneSelectionFeaturesRef = useRef<Feature[]>([]);
const laneSelectionAnchorRef = useRef<Coordinate | null>(null); const laneSelectionAnchorRef = useRef<Coordinate | null>(null);
@@ -285,6 +290,7 @@ export function MapCanvas({
// road inspector, and dragging is owned by the edit interaction. // road inspector, and dragging is owned by the edit interaction.
layers: (layer) => layers: (layer) =>
layer !== layers.selectedRoad && layer !== layers.selectedRoad &&
layer !== junctionSelectionLayerRef.current &&
layer !== handleLayer?.layer && layer !== handleLayer?.layer &&
layer !== laneSelectionLayer && layer !== laneSelectionLayer &&
layer !== signalTransformLayer && layer !== signalTransformLayer &&
@@ -448,12 +454,40 @@ export function MapCanvas({
return () => { return () => {
select.un('select', listener); select.un('select', listener);
junctionNodeMarkerSourceRef.current = null; junctionNodeMarkerSourceRef.current = null;
junctionSelectionLayerRef.current = null;
map.setTarget(undefined); map.setTarget(undefined);
delete (target.current as HTMLDivElement & { __roadWorkbenchMap?: Map })?.__roadWorkbenchMap; delete (target.current as HTMLDivElement & { __roadWorkbenchMap?: Map })?.__roadWorkbenchMap;
}; };
// Map construction must be once per mounted canvas; state changes update sources below. // Map construction must be once per mounted canvas; state changes update sources below.
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
useEffect(() => {
const map = mapRef.current;
if (!map) return;
let layer = junctionSelectionLayerRef.current;
if (!layer && junctionSelectionFeatures?.length) {
layer = new VectorLayer({
source: new VectorSource(),
zIndex: 89,
style: new Style({
stroke: new Stroke({ color: '#0891b2', width: 3 }),
fill: new Fill({ color: 'rgba(8,145,178,0.16)' }),
image: new CircleStyle({ radius: 8, stroke: new Stroke({ color: '#0891b2', width: 3 }) }),
}),
});
junctionSelectionLayerRef.current = layer;
map.addLayer(layer);
}
const source = layer?.getSource();
if (!source) return;
source.clear();
source.addFeatures(
new GeoJSON().readFeatures(
{ type: 'FeatureCollection', features: junctionSelectionFeatures || [] },
{ dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' },
),
);
}, [junctionSelectionFeatures]);
useEffect(() => { useEffect(() => {
const source = junctionNodeMarkerSourceRef.current; const source = junctionNodeMarkerSourceRef.current;
if (!source) return; if (!source) return;
+1 -1
View File
@@ -214,7 +214,7 @@ export interface EditStateResponse {
* renders about six handles. Wire form matches the `?segment=` / `?junction=` * renders about six handles. Wire form matches the `?segment=` / `?junction=`
* query the GET route accepts. * query the GET route accepts.
*/ */
export type EditSelection = { segment: string } | { junction: string }; export type EditSelection = { segment: string } | { junction: string } | { cluster: string };
/** /**
* `POST /api/edit-preview`. Sending `constraints` alone lets the server merge * `POST /api/edit-preview`. Sending `constraints` alone lets the server merge
@@ -2,7 +2,8 @@ import { useEffect, useRef, useState } from 'react';
import { api } from '../lib/api'; import { api } from '../lib/api';
import { EditSession } from '../edit/session'; import { EditSession } from '../edit/session';
import type { EditDiagnostic, HandleManifest, PreviewLayerName } from '../edit/types'; import type { EditDiagnostic, HandleManifest, PreviewLayerName } from '../edit/types';
import type { GeoJson, WorkbenchState } from '../types/state'; import type { GeoJson, JunctionRef, WorkbenchState } from '../types/state';
import { junctionEditSelection } from '../junction/structure';
/** /**
* Owns the stable v2 session and the server state that surrounds it. Gesture * Owns the stable v2 session and the server state that surrounds it. Gesture
@@ -12,13 +13,13 @@ export function useDirectEditSession({
editMode, editMode,
state, state,
selectedSegmentId, selectedSegmentId,
selectedJunctionId, selectedJunction,
setStatus, setStatus,
}: { }: {
editMode: boolean; editMode: boolean;
state?: WorkbenchState; state?: WorkbenchState;
selectedSegmentId?: string; selectedSegmentId?: string;
selectedJunctionId?: string; selectedJunction?: JunctionRef | null;
setStatus: (status: string) => void; setStatus: (status: string) => void;
}) { }) {
const [manifest, setManifest] = useState<HandleManifest | null>(null); const [manifest, setManifest] = useState<HandleManifest | null>(null);
@@ -33,16 +34,18 @@ export function useDirectEditSession({
useEffect(() => { useEffect(() => {
// Flag off: no manifest request at all, so the network trace matches browse mode. // Flag off: no manifest request at all, so the network trace matches browse mode.
if (!editMode) return; if (!editMode) return;
let current = true;
setManifest(null);
api api
.editState( .editState(
selectedJunctionId selectedJunction
? { junction: selectedJunctionId } ? junctionEditSelection(selectedJunction)
: selectedSegmentId : selectedSegmentId
? { segment: selectedSegmentId } ? { segment: selectedSegmentId }
: undefined, : undefined,
) )
.then((value) => { .then((value) => {
if (!('handles' in value)) return; if (!current || !('handles' in value)) return;
setManifest(value.handles); setManifest(value.handles);
const key = `${value.areaId}:${value.documentVersion}`; const key = `${value.areaId}:${value.documentVersion}`;
if (loadedDocument.current === key) return; if (loadedDocument.current === key) return;
@@ -50,8 +53,13 @@ export function useDirectEditSession({
sessionRef.current?.load(value.document.constraints, value.document.operations, value.documentVersion); sessionRef.current?.load(value.document.constraints, value.document.operations, value.documentVersion);
touch(); touch();
}) })
.catch((error: Error) => setStatus(`直接编辑手柄不可用:${error.message}`)); .catch((error: Error) => {
}, [editMode, selectedJunctionId, selectedSegmentId, setStatus, state]); if (current) setStatus(`直接编辑手柄不可用:${error.message}`);
});
return () => {
current = false;
};
}, [editMode, selectedJunction, selectedSegmentId, setStatus, state]);
return { return {
session: sessionRef.current, session: sessionRef.current,
@@ -10,6 +10,7 @@ import type { WorkbenchState } from '../types/state';
import type { Coordinate } from '../edit/meters'; import type { Coordinate } from '../edit/meters';
import { junctionLabelForHandle, junctionRoadName } from './labels'; import { junctionLabelForHandle, junctionRoadName } from './labels';
import { junctionFacilities } from './facilities'; import { junctionFacilities } from './facilities';
import { junctionCapabilityReason, structureForJunction } from './structure';
import { SignalEditor } from '../components/ElementEditors'; import { SignalEditor } from '../components/ElementEditors';
interface Props { interface Props {
@@ -175,7 +176,7 @@ export function JunctionWorkspace({
() => (state ? junctionFacilities(state, descriptor.nodeIds, roads) : []), () => (state ? junctionFacilities(state, descriptor.nodeIds, roads) : []),
[descriptor.nodeIds, roads, state], [descriptor.nodeIds, roads, state],
); );
const structure = state?.junctionStructure; const structure = structureForJunction(state, descriptor.ref);
const standardDiagnostics = state?.standardsDiagnostics || []; const standardDiagnostics = state?.standardsDiagnostics || [];
return ( return (
<section className="junction-workspace" aria-label="路口编辑工作区"> <section className="junction-workspace" aria-label="路口编辑工作区">
@@ -237,6 +238,7 @@ export function JunctionWorkspace({
{state.junctionReference.source || '已加载参考文件'} {state.junctionReference.source || '已加载参考文件'}
</p> </p>
) : null} ) : null}
{structure.capability?.reason ? <p>{junctionCapabilityReason(structure.capability.reason)}</p> : null}
<dl> <dl>
<dt>道路臂</dt> <dt>道路臂</dt>
<dd> <dd>
@@ -248,6 +250,8 @@ export function JunctionWorkspace({
key={arm.key} key={arm.key}
className={selectedObjectKey === arm.key ? 'is-selected' : undefined} className={selectedObjectKey === arm.key ? 'is-selected' : undefined}
onClick={() => onSelectObject?.(arm.key)} onClick={() => onSelectObject?.(arm.key)}
aria-pressed={selectedObjectKey === arm.key}
title={junctionCapabilityReason(arm.capability?.reason)}
> >
{arm.label} {arm.label}
</button> </button>
@@ -258,7 +262,26 @@ export function JunctionWorkspace({
)} )}
</dd> </dd>
<dt>角部</dt> <dt>角部</dt>
<dd>{structure.corners.length ? structure.corners.map((corner) => corner.label).join('、') : '无'}</dd> <dd>
{structure.corners.length ? (
<span className="junction-workspace__object-list">
{structure.corners.map((corner) => (
<button
type="button"
key={corner.key}
className={selectedObjectKey === corner.key ? 'is-selected' : undefined}
aria-pressed={selectedObjectKey === corner.key}
title={junctionCapabilityReason(corner.capability?.reason)}
onClick={() => onSelectObject?.(corner.key)}
>
{corner.label}
</button>
))}
</span>
) : (
'无'
)}
</dd>
<dt>设施</dt> <dt>设施</dt>
<dd> <dd>
{structure.facilities.length ? ( {structure.facilities.length ? (
@@ -270,7 +293,16 @@ export function JunctionWorkspace({
<summary>已识别 {structure.facilities.length} 项设施</summary> <summary>已识别 {structure.facilities.length} 项设施</summary>
<ul> <ul>
{structure.facilities.map((facility) => ( {structure.facilities.map((facility) => (
<li key={facility.key}>{facility.label}</li> <li key={facility.key}>
<button
type="button"
aria-pressed={selectedObjectKey === facility.key}
title={junctionCapabilityReason(facility.capability?.reason)}
onClick={() => onSelectObject?.(facility.key)}
>
{facility.label}
</button>
</li>
))} ))}
</ul> </ul>
</details> </details>
+20 -1
View File
@@ -1,6 +1,7 @@
import type { Diagnostic, JunctionCandidate, Position, WorkbenchState, JunctionClusterConfig } from '../types/state'; import type { Diagnostic, JunctionCandidate, Position, WorkbenchState, JunctionClusterConfig } from '../types/state';
export type JunctionRef = { type: 'node' | 'cluster'; id: string }; export type { JunctionRef } from '../types/state';
import type { JunctionRef } from '../types/state';
export type JunctionHotspotStatus = 'editable' | 'readonly' | 'candidate'; export type JunctionHotspotStatus = 'editable' | 'readonly' | 'candidate';
export interface JunctionDescriptor { export interface JunctionDescriptor {
ref: JunctionRef; ref: JunctionRef;
@@ -158,6 +159,24 @@ export function junctionDescriptors(state: WorkbenchState): JunctionDescriptor[]
const descriptor = candidateDescriptor(candidate, diagnostic, configured); const descriptor = candidateDescriptor(candidate, diagnostic, configured);
if (descriptor) result.push(descriptor); if (descriptor) result.push(descriptor);
} }
// Compiler-owned topology replaces heuristic cluster footprints when available.
// This also works outside debug mode and excludes cluster-internal connections.
for (const structure of Object.values(state.junctionStructures || {})) {
if (structure.junctionRef?.type !== 'cluster' || !structure.center || !structure.provenance) continue;
const descriptor: JunctionDescriptor = {
ref: structure.junctionRef,
status: 'readonly',
coordinate: structure.center,
radiusMeters: 16,
nodeIds: structure.provenance.nodeIds,
approachRoadIds: structure.provenance.roadIds,
diagnosticIds: [],
source: 'cluster-config',
};
const existing = result.findIndex((item) => item.ref.type === 'cluster' && item.ref.id === descriptor.ref.id);
if (existing >= 0) result[existing] = descriptor;
else result.push(descriptor);
}
const unique = new Map<string, JunctionDescriptor>(); const unique = new Map<string, JunctionDescriptor>();
for (const descriptor of result) { for (const descriptor of result) {
const key = `${descriptor.ref.type}:${descriptor.ref.id}`; const key = `${descriptor.ref.type}:${descriptor.ref.id}`;
+19 -4
View File
@@ -1,6 +1,7 @@
import type { GeoFeature, GeoJson, Road, WorkbenchState } from '../types/state'; import type { GeoFeature, GeoJson, Road, WorkbenchState } from '../types/state';
import type { JunctionDescriptor } from './hotspots'; import type { JunctionDescriptor } from './hotspots';
import type { PreviewLayerName } from '../edit/types'; import type { PreviewLayerName } from '../edit/types';
import { structureForJunction } from './structure';
const empty: GeoJson = { type: 'FeatureCollection', features: [] }; const empty: GeoJson = { type: 'FeatureCollection', features: [] };
@@ -28,8 +29,16 @@ function text(value: unknown): string | null {
return typeof value === 'string' || typeof value === 'number' ? String(value) : null; return typeof value === 'string' || typeof value === 'number' ? String(value) : null;
} }
function related(feature: GeoFeature, nodeIds: Set<string>, roadIds: Set<string>, segmentIds: Set<string>): boolean { function related(
feature: GeoFeature,
nodeIds: Set<string>,
roadIds: Set<string>,
segmentIds: Set<string>,
descriptor?: JunctionDescriptor,
): boolean {
const props = feature.properties || {}; const props = feature.properties || {};
if (descriptor && props.junction_key) return props.junction_key === `${descriptor.ref.type}:${descriptor.ref.id}`;
if (descriptor?.ref.type === 'cluster' && props.cluster_id) return String(props.cluster_id) === descriptor.ref.id;
const nodeKeys = ['node_id', 'osm_node_id', 'control_id', 'crossing_node_id', 'junction_node_id']; const nodeKeys = ['node_id', 'osm_node_id', 'control_id', 'crossing_node_id', 'junction_node_id'];
if ( if (
nodeKeys.some((key) => { nodeKeys.some((key) => {
@@ -75,7 +84,7 @@ export function localJunctionPreview(
if (value === null || value === undefined) continue; if (value === null || value === undefined) continue;
scoped[name] = { scoped[name] = {
type: 'FeatureCollection', type: 'FeatureCollection',
features: value.features.filter((feature) => related(feature, nodeIds, roadIds, segmentIds)), features: value.features.filter((feature) => related(feature, nodeIds, roadIds, segmentIds, descriptor)),
}; };
} }
return scoped; return scoped;
@@ -92,7 +101,7 @@ export function localJunctionState(state: WorkbenchState, descriptor: JunctionDe
const segmentIds = new Set(roads.map((road) => road.segmentId)); const segmentIds = new Set(roads.map((road) => road.segmentId));
const keep = (value: GeoJson | null | undefined): GeoJson => ({ const keep = (value: GeoJson | null | undefined): GeoJson => ({
type: 'FeatureCollection', type: 'FeatureCollection',
features: (value?.features || []).filter((feature) => related(feature, nodeIds, roadIds, segmentIds)), features: (value?.features || []).filter((feature) => related(feature, nodeIds, roadIds, segmentIds, descriptor)),
}); });
const layerNames = [ const layerNames = [
'nativeRoadSurface', 'nativeRoadSurface',
@@ -113,10 +122,16 @@ export function localJunctionState(state: WorkbenchState, descriptor: JunctionDe
layers.nativeRoadSurface = keep(state.layers.nativeRoadSurface); layers.nativeRoadSurface = keep(state.layers.nativeRoadSurface);
layers.nativeIntersectionSurface = keep(state.layers.nativeIntersectionSurface); layers.nativeIntersectionSurface = keep(state.layers.nativeIntersectionSurface);
const signals = state.trafficSignals.assemblies.features.filter((feature) => const signals = state.trafficSignals.assemblies.features.filter((feature) =>
related(feature, nodeIds, roadIds, segmentIds), related(feature, nodeIds, roadIds, segmentIds, descriptor),
);
const structure = structureForJunction(state, descriptor.ref);
const objectKeys = new Set(
structure ? [...structure.arms, ...structure.corners, ...structure.facilities].map((object) => object.key) : [],
); );
return { return {
...state, ...state,
junctionStructure: structure,
standardsDiagnostics: state.standardsDiagnostics?.filter((item) => objectKeys.has(item.objectKey)),
compiled: { compiled: {
...state.compiled, ...state.compiled,
model: { model: {
@@ -0,0 +1,144 @@
import { describe, expect, it } from 'vitest';
import type { GeoFeature, JunctionStructure, WorkbenchState } from '../types/state';
import { junctionDescriptors } from './hotspots';
import { localJunctionPreview, localJunctionState } from './local-state';
import {
junctionEditSelection,
junctionObjectFeatures,
junctionObjectKeyForFeature,
structureForJunction,
} from './structure';
const structure: JunctionStructure = {
schema: 'junction-structure/v1',
junctionKey: 'cluster:a',
junctionRef: { type: 'cluster', id: 'a' },
label: '路口 A',
center: [120, 30],
provenance: { nodeIds: ['1', '2'], roadIds: ['external'], segmentIds: ['external-segment'] },
capability: { editable: false, reason: 'complex-geometry-editing-not-implemented' },
shape: { kind: 't-junction', label: 'T 字', effectiveArmCount: 3, throughPairCount: 1 },
arms: ['a', 'b', 'c'].map((id) => ({ key: `arm:${id}`, label: `道路 ${id}`, directionality: 'two-way' })),
corners: [{ key: 'corner:a', label: '角部 A', fromArmKey: 'arm:a', toArmKey: 'arm:b' }],
facilities: [{ key: 'crossing:a', label: '过街 A', kind: 'crossing' }],
};
const feature = (object: string, junction = 'cluster:a', arm?: string): GeoFeature => ({
type: 'Feature',
properties: { junction_key: junction, object_key: object, arm_key: arm },
geometry: {
type: 'Polygon',
coordinates: [
[
[120, 30],
[120.001, 30],
[120, 30.001],
[120, 30],
],
],
},
});
const road = (id: string, nodes: string[]) => ({
id,
sourceNodeIds: nodes,
segmentId: `${id}-segment`,
centerline: [],
osmWayIds: [],
tags: {},
highway: 'residential',
direction: 'forward',
widthMeters: 7,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
});
const state: WorkbenchState = {
areaId: 'test',
compiled: {
model: { roads: [road('external', ['1', '3']), road('internal', ['1', '2'])], endpoints: [], connections: [] },
diagnostics: [],
},
overrides: { schema: 'native-road-overrides/v1', overrides: [] },
trafficSignals: { provenance: 'empty', assemblies: { type: 'FeatureCollection', features: [] } },
trafficRuntime: { signals: [] },
comparison: {},
junctionStructures: { 'cluster:a': structure },
junctionStructure: structure,
layers: {
nativeRoadSurface: {
type: 'FeatureCollection',
features: [feature('carriageway:a', 'cluster:a', 'arm:a'), feature('carriageway:b', 'cluster:b', 'arm:a')],
},
crosswalks: {
type: 'FeatureCollection',
features: [feature('crossing:a'), feature('crossing:a'), feature('crossing:b', 'cluster:b')],
},
nativeIntersectionSurface: { type: 'FeatureCollection', features: [feature('corner:a')] },
},
};
describe('authoritative junction structures', () => {
it('uses typed scopes without leaking the legacy first structure', () => {
expect(junctionEditSelection({ type: 'cluster', id: 'a' })).toEqual({ cluster: 'a' });
expect(junctionEditSelection({ type: 'node', id: 'a' })).toEqual({ junction: 'a' });
expect(structureForJunction(state, { type: 'cluster', id: 'a' })).toBe(structure);
expect(structureForJunction(state, { type: 'node', id: 'a' })).toBeNull();
expect(structureForJunction(state, { type: 'cluster', id: 'missing' })).toBeNull();
});
it('makes map and list select the same arm, corner and crossing group', () => {
expect(junctionObjectKeyForFeature(structure, feature('carriageway:a', 'cluster:a', 'arm:a').properties!)).toBe(
'arm:a',
);
expect(junctionObjectKeyForFeature(structure, feature('corner:a').properties!)).toBe('corner:a');
expect(junctionObjectKeyForFeature(structure, feature('crossing:a').properties!)).toBe('crossing:a');
expect(junctionObjectKeyForFeature(structure, feature('crossing:a', 'cluster:b').properties!)).toBeNull();
expect(junctionObjectFeatures(state, structure, 'arm:a')).toHaveLength(1);
expect(junctionObjectFeatures(state, structure, 'crossing:a')).toHaveLength(2);
expect(junctionObjectFeatures(state, structure, 'corner:a')).toHaveLength(1);
expect(junctionObjectFeatures(state, structure, 'deleted')).toEqual([]);
});
it('scopes the canvas and preview using cluster ownership, retaining core features without node IDs', () => {
const descriptor = junctionDescriptors(state).find((item) => item.ref.type === 'cluster')!;
expect(descriptor.status).toBe('readonly');
expect(descriptor.approachRoadIds).toEqual(['external']);
const local = localJunctionState(state, descriptor);
expect(local.compiled.model.roads.map((item) => item.id)).toEqual(['external']);
expect(local.junctionStructure).toBe(structure);
expect(local.layers.nativeRoadSurface?.features).toHaveLength(1);
expect(local.layers.nativeIntersectionSurface?.features).toHaveLength(1);
const preview = localJunctionPreview(
{ roadSurface: state.layers.nativeRoadSurface },
descriptor,
state.compiled.model.roads,
);
expect(preview?.roadSurface?.features).toHaveLength(1);
});
it('resolves separately persisted signals through scoped provenance without parsing their IDs', () => {
const signal = { ...feature('unused'), properties: { signal_uid: 'raw:signal:uid' } };
const withSignal = {
...structure,
facilities: [
...structure.facilities,
{
key: 'cluster:a:signal:raw',
kind: 'signal',
label: '信号灯',
geometryRef: 'raw:signal:uid',
provenance: { featureIds: ['raw:signal:uid'] },
},
],
};
const signalState = {
...state,
trafficSignals: {
...state.trafficSignals,
assemblies: { ...state.trafficSignals.assemblies, features: [signal] },
},
};
expect(junctionObjectKeyForFeature(withSignal, signal.properties)).toBe('cluster:a:signal:raw');
expect(junctionObjectFeatures(signalState, withSignal, 'cluster:a:signal:raw')).toEqual([signal]);
expect(junctionObjectKeyForFeature(structure, signal.properties)).toBeNull();
});
});
@@ -0,0 +1,79 @@
import type { GeoFeature, JunctionRef, JunctionStructure, WorkbenchState } from '../types/state';
import type { EditSelection } from '../edit/types';
export function junctionEditSelection(ref: JunctionRef): EditSelection {
return ref.type === 'cluster' ? { cluster: ref.id } : { junction: ref.id };
}
/** A missing scoped structure must never show another junction's first result. */
export function structureForJunction(state: WorkbenchState | undefined, ref: JunctionRef): JunctionStructure | null {
const structure = state?.junctionStructures?.[`${ref.type}:${ref.id}`] ?? state?.junctionStructure;
if (!structure) return null;
return structure.junctionRef?.type === ref.type && structure.junctionRef.id === ref.id ? structure : null;
}
function objects(structure: JunctionStructure) {
return [...structure.arms, ...structure.corners, ...structure.facilities];
}
export function junctionCapabilityReason(reason: string | undefined): string | undefined {
if (!reason) return undefined;
switch (reason) {
case 'complex-geometry-editing-not-implemented':
return '当前可查看和选择,参数编辑将在后续阶段开放。';
case 'source-missing':
return '对象来源已缺失,暂不可编辑。';
case 'source-ambiguous':
return '对象来源存在歧义,暂不可编辑。';
default:
return '当前对象暂不可编辑。';
}
}
export function junctionObjectKeyForFeature(
structure: JunctionStructure | null,
properties: Record<string, unknown>,
): string | null {
if (!structure) return null;
if (properties.junction_key && properties.junction_key !== structure.junctionKey) return null;
const keys = [properties.object_key, properties.facility_key, properties.corner_key, properties.arm_key];
const candidates = objects(structure);
for (const key of keys) {
if (typeof key === 'string' && candidates.some((object) => object.key === key)) return key;
}
// Signals are a separate persisted layer. The server attaches their existing
// UID to the scoped structure without rewriting the signal document.
if (typeof properties.signal_uid === 'string') {
return (
structure.facilities.find(
(object) => object.kind === 'signal' && object.provenance?.featureIds?.includes(String(properties.signal_uid)),
)?.key ?? null
);
}
if (structure.junctionRef?.type === 'node') {
const ids = [properties.native_id, properties.signal_uid, properties.road_id];
return candidates.find((object) => object.geometryRef && ids.includes(object.geometryRef))?.key ?? null;
}
return null;
}
/** Resolve the selected semantic object to its published map features. */
export function junctionObjectFeatures(
state: WorkbenchState | undefined,
structure: JunctionStructure | null,
key: string | null,
): GeoFeature[] {
if (!state || !structure || !key || !objects(structure).some((object) => object.key === key)) return [];
const seen = new Set<GeoFeature>();
return [...Object.values(state.layers), state.trafficSignals.assemblies].flatMap((layer) =>
(layer?.features ?? []).filter((feature) => {
if (seen.has(feature)) return false;
seen.add(feature);
const properties = feature.properties || {};
if (typeof properties.signal_uid === 'string') return junctionObjectKeyForFeature(structure, properties) === key;
if (structure.junctionRef?.type === 'node') return junctionObjectKeyForFeature(structure, properties) === key;
if (properties.junction_key !== structure.junctionKey) return false;
return [properties.object_key, properties.arm_key, properties.corner_key, properties.facility_key].includes(key);
}),
);
}
+49 -5
View File
@@ -87,19 +87,62 @@ export interface Diagnostic {
geometry?: { type: string; coordinates: unknown }; geometry?: { type: string; coordinates: unknown };
manualCandidates?: Array<{ roadId: string; distanceMeters: number }>; manualCandidates?: Array<{ roadId: string; distanceMeters: number }>;
} }
export type JunctionRef = { type: 'node' | 'cluster'; id: string };
export interface JunctionProvenance {
nodeIds?: string[];
segmentIds?: string[];
roadIds?: string[];
osmWayIds?: string[];
carriagewayKeys?: string[];
armKeys?: string[];
featureIds?: string[];
}
export interface JunctionSource extends JunctionProvenance {
nodeIds: string[];
segmentIds: string[];
roadIds: string[];
}
export interface JunctionCapability {
editable: boolean;
reason?: string;
}
export interface JunctionObject {
key: string;
label: string;
geometryRef?: string;
geometryRefs?: string[];
provenance?: JunctionProvenance;
capability?: JunctionCapability;
}
export interface JunctionStructure { export interface JunctionStructure {
schema: string; schema: string;
junctionKey: string; junctionKey: string;
junctionRef?: JunctionRef;
topologyFingerprint?: string;
provenance?: JunctionSource;
capability?: JunctionCapability;
center?: Position;
label: string; label: string;
shape: { kind: string; label: string; effectiveArmCount: number; throughPairCount: number }; shape: { kind: string; label: string; effectiveArmCount: number; throughPairCount: number };
arms: Array<{ arms: Array<
key: string; JunctionObject & {
label: string; heading?: number;
directionality: string; directionality: string;
carriageway?: { laneCount?: number; effectiveWidthMeters?: number }; carriageway?: { laneCount?: number; effectiveWidthMeters?: number };
carriageways?: Array<{
key: string;
geometryRef: string;
laneCount: number;
effectiveWidthMeters: number;
provenance: JunctionSource;
capability: JunctionCapability;
}>; }>;
corners: Array<{ key: string; label: string; fromArmKey: string; toArmKey: string }>; }
facilities: Array<{ key: string; kind: string; label: string }>; >;
corners: Array<JunctionObject & { fromArmKey: string; toArmKey: string }>;
facilities: Array<
JunctionObject & { kind: string; armKey?: string; cornerKey?: string; relatedFacilityKey?: string }
>;
} }
export interface StandardsDiagnostic { export interface StandardsDiagnostic {
id: string; id: string;
@@ -133,6 +176,7 @@ export interface WorkbenchState {
junctionShapes?: JunctionShapeSummary[]; junctionShapes?: JunctionShapeSummary[];
} | null; } | null;
junctionStructure?: JunctionStructure | null; junctionStructure?: JunctionStructure | null;
junctionStructures?: Record<string, JunctionStructure>;
standardsProfile?: { id: string; label: string }; standardsProfile?: { id: string; label: string };
standardsDiagnostics?: StandardsDiagnostic[]; standardsDiagnostics?: StandardsDiagnostic[];
} }
+93 -10
View File
@@ -247,7 +247,38 @@ function state(area, junctionReference = null, debug = false) {
const trafficRuntime = runtime(trafficSignals); const trafficRuntime = runtime(trafficSignals);
const compiled = readCompiled(area); const compiled = readCompiled(area);
const layers = readWorkbenchLayers(nativeDir, osm2streetsRoadSurface); const layers = readWorkbenchLayers(nativeDir, osm2streetsRoadSurface);
const junctionStructure = projectJunctionStructure({ model: compiled.model, layers, trafficSignals }); const clusters = area.nativeRoad?.junctionTemplates?.clusters || [];
const nodeSegments = new Map();
const roadsById = new Map((compiled.model.roads || []).map((road) => [road.id, road]));
for (const endpoint of compiled.model.endpoints || []) {
const id = String(endpoint.nodeId);
if (!nodeSegments.has(id)) nodeSegments.set(id, new Set());
nodeSegments.get(id).add(roadsById.get(endpoint.roadId)?.segmentId || endpoint.roadId);
}
const refs = [
...[...nodeSegments].filter(([, segments]) => segments.size >= 2).map(([id]) => ({ type: 'node', id })),
...clusters.map((cluster) => ({ type: 'cluster', id: String(cluster.id) })),
];
const junctionStructures = Object.fromEntries(
refs
.map((junctionRef) => [
`${junctionRef.type}:${junctionRef.id}`,
projectJunctionStructure({
model: compiled.model,
layers: {
...layers,
roadSurface: layers.nativeRoadSurface,
intersectionSurface: layers.nativeIntersectionSurface,
sidewalkSurface: layers.nativeSidewalkSurface,
},
trafficSignals,
junctionRef,
clusters,
}),
])
.filter(([, structure]) => structure !== null),
);
const junctionStructure = null;
const junctionShapes = debug const junctionShapes = debug
? (readLayer(path.join(nativeDir, 'layers', 'road_surface.geojson')).features || []) ? (readLayer(path.join(nativeDir, 'layers', 'road_surface.geojson')).features || [])
.filter((feature) => feature.properties?.kind === 'complex-core' && feature.properties?.cluster_id) .filter((feature) => feature.properties?.kind === 'complex-core' && feature.properties?.cluster_id)
@@ -276,9 +307,16 @@ function state(area, junctionReference = null, debug = false) {
} }
: null, : null,
compiled, compiled,
junctionStructures,
junctionStructure, junctionStructure,
standardsProfile: { id: 'cn-urban-default', label: '中国城市道路(项目默认)' }, standardsProfile: { id: 'cn-urban-default', label: '中国城市道路(项目默认)' },
standardsDiagnostics: standardsDiagnostics(junctionStructure), standardsDiagnostics: [
...new Map(
Object.values(junctionStructures)
.flatMap((structure) => standardsDiagnostics(structure))
.map((item) => [item.id, item]),
).values(),
],
overrides: loadOverrides(area.outputs.nativeRoadOverrides), overrides: loadOverrides(area.outputs.nativeRoadOverrides),
trafficSignals, trafficSignals,
trafficRuntime, trafficRuntime,
@@ -323,11 +361,28 @@ function activeRevisionFields(area) {
// while the map renders about six handles. Omitting it keeps the full manifest for // while the map renders about six handles. Omitting it keeps the full manifest for
// callers that want it. // callers that want it.
function selectionFrom(source) { function selectionFrom(source) {
if (!source) return null; if (source == null) return null;
const segment = source.segment ?? source.get?.('segment'); if (typeof source !== 'object' || Array.isArray(source)) throw new Error('selection must be an object.');
if (segment) return { type: 'segment', id: String(segment) }; const keys = ['segment', 'junction', 'cluster'];
const junction = source.junction ?? source.get?.('junction'); const entries = keys.flatMap((key) => {
if (junction) return { type: 'junction', id: String(junction) }; if (typeof source.getAll === 'function') return source.getAll(key).map((value) => [key, value]);
return Object.hasOwn(source, key) ? [[key, source[key]]] : [];
});
if (entries.length > 1) throw new Error('selection must specify only one of segment, junction, or cluster.');
if (!entries.length) return null;
const [key, value] = entries[0];
if (
(typeof value !== 'string' && typeof value !== 'number') ||
!String(value).trim() ||
(typeof value === 'number' && !Number.isFinite(value))
)
throw new Error(`selection.${key} must be a non-empty ID.`);
return { type: key, id: String(value).trim() };
}
function junctionRefFromSelection(selection) {
if (selection?.type === 'junction') return { type: 'node', id: selection.id };
if (selection?.type === 'cluster') return { type: 'cluster', id: selection.id };
return null; return null;
} }
@@ -339,13 +394,21 @@ function editState(area, selection = null) {
const resolution = resolveDirectEditConstraints(model, directEdits, { const resolution = resolveDirectEditConstraints(model, directEdits, {
revisionId: initialized.active.activeRevisionId, revisionId: initialized.active.activeRevisionId,
compilerGeometryVersion: GEOMETRY_VERSION, compilerGeometryVersion: GEOMETRY_VERSION,
junctionTemplates: area.nativeRoad?.junctionTemplates,
selection, selection,
}); });
const compiled = readCompiled(area); const compiled = readCompiled(area);
const layers = readWorkbenchLayers(area.outputs.nativeRoadDir, null); const layers = readWorkbenchLayers(area.outputs.nativeRoadDir, null);
const junctionStructure = projectJunctionStructure({ const junctionStructure = projectJunctionStructure({
model: compiled.model, model: compiled.model,
layers, junctionRef: junctionRefFromSelection(selection),
clusters: area.nativeRoad?.junctionTemplates?.clusters || [],
layers: {
...layers,
roadSurface: layers.nativeRoadSurface,
intersectionSurface: layers.nativeIntersectionSurface,
sidewalkSurface: layers.nativeSidewalkSurface,
},
trafficSignals: readJson(area.outputs.nativeTrafficSignals), trafficSignals: readJson(area.outputs.nativeTrafficSignals),
}); });
return { return {
@@ -381,12 +444,14 @@ function editPreview(area, body = {}) {
const activeState = readJson(activeStateFile); const activeState = readJson(activeStateFile);
const persistedOverrides = loadOverrides(area.outputs.nativeRoadOverrides); const persistedOverrides = loadOverrides(area.outputs.nativeRoadOverrides);
const model = compileRoadModel(fs.readFileSync(area.input, 'utf8'), persistedOverrides); const model = compileRoadModel(fs.readFileSync(area.input, 'utf8'), persistedOverrides);
const selection = selectionFrom(body.selection);
const previewSeq = Number.isInteger(body.previewSeq) ? body.previewSeq : 0; const previewSeq = Number.isInteger(body.previewSeq) ? body.previewSeq : 0;
const resolution = resolveDirectEditConstraints(model, draft, { const resolution = resolveDirectEditConstraints(model, draft, {
revisionId: activeState.activeRevisionId, revisionId: activeState.activeRevisionId,
previewSeq, previewSeq,
compilerGeometryVersion: GEOMETRY_VERSION, compilerGeometryVersion: GEOMETRY_VERSION,
selection: selectionFrom(body.selection), junctionTemplates: area.nativeRoad?.junctionTemplates,
selection,
}); });
const compiled = compileGeometry(model, persistedOverrides, { const compiled = compileGeometry(model, persistedOverrides, {
edgeLines: area.nativeRoad.edgeLines, edgeLines: area.nativeRoad.edgeLines,
@@ -396,7 +461,14 @@ function editPreview(area, body = {}) {
const diagnostics = [...compiled.diagnostics, ...resolution.diagnostics]; const diagnostics = [...compiled.diagnostics, ...resolution.diagnostics];
const junctionStructure = projectJunctionStructure({ const junctionStructure = projectJunctionStructure({
model, model,
junctionRef: junctionRefFromSelection(selection),
clusters: area.nativeRoad?.junctionTemplates?.clusters || [],
layers: { layers: {
roadSurface: compiled.roadSurface,
sidewalkSurface: compiled.sidewalkSurface,
islands: compiled.intersectionSurface,
medians: compiled.intersectionSurface,
sidewalkTurns: compiled.sidewalkSurface,
crosswalks: compiled.crosswalks, crosswalks: compiled.crosswalks,
vehicleStopLines: compiled.vehicleStopLines, vehicleStopLines: compiled.vehicleStopLines,
intersectionSurface: compiled.intersectionSurface, intersectionSurface: compiled.intersectionSurface,
@@ -456,6 +528,7 @@ function saveEdits(area, body = {}) {
const resolution = resolveDirectEditConstraints(model, candidate, { const resolution = resolveDirectEditConstraints(model, candidate, {
revisionId: initialized.active.activeRevisionId, revisionId: initialized.active.activeRevisionId,
compilerGeometryVersion: GEOMETRY_VERSION, compilerGeometryVersion: GEOMETRY_VERSION,
junctionTemplates: area.nativeRoad?.junctionTemplates,
}); });
const blockingDiagnostic = resolution.diagnostics.find((item) => item.severity === 'error'); const blockingDiagnostic = resolution.diagnostics.find((item) => item.severity === 'error');
if (blockingDiagnostic) { if (blockingDiagnostic) {
@@ -484,6 +557,7 @@ function rebaseEdits(area, revisionId) {
const resolution = resolveDirectEditConstraints(model, revision.directEdits, { const resolution = resolveDirectEditConstraints(model, revision.directEdits, {
revisionId, revisionId,
compilerGeometryVersion: GEOMETRY_VERSION, compilerGeometryVersion: GEOMETRY_VERSION,
junctionTemplates: area.nativeRoad?.junctionTemplates,
replay: true, replay: true,
}); });
const counts = Object.fromEntries( const counts = Object.fromEntries(
@@ -750,4 +824,13 @@ function sendJson(response, status, value) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
response.end(`${JSON.stringify(value)}\n`); response.end(`${JSON.stringify(value)}\n`);
} }
module.exports = { startWorkbench, readMultipart, editState, editPreview, saveEdits, rebaseEdits }; module.exports = {
startWorkbench,
readMultipart,
state,
selectionFrom,
editState,
editPreview,
saveEdits,
rebaseEdits,
};