feat(workbench): add traffic signal rotation handle

This commit is contained in:
que01 committed 2026-09-02 11:38:30 +08:00
1 parent 9b7c3d59bd
commit caa3cb843f
4 files changed
+234 -23

No files matched your search

+10 -2
View File
@@ -6,6 +6,7 @@ const { parseOsm } = require('./osm');
const EARTH_RADIUS = 6371008.8;
const CURB_OFFSET_METERS = 5.2;
const MAX_SIGNAL_POLE_DISTANCE_FROM_STOP_METERS = 40;
const MAST_REACH_METERS = 4.5;
const SIGNAL_LAYOUT = Object.freeze({
poleHeightMeters: 6.7,
@@ -195,6 +196,13 @@ function validateTrafficSignalFeatures(collection) {
input.face_heading_deg == null || input.face_heading_deg === ''
? normalizeDegrees((legacyHeading == null ? 0 : legacyHeading) + 180)
: normalizeDegrees(number('face_heading_deg'));
const stopLon = number('stop_lon', { min: -180, max: 180 });
const stopLat = number('stop_lat', { min: -90, max: 90 });
const poleDistance = metersBetween(feature.geometry.coordinates, [stopLon, stopLat]);
if (poleDistance > MAX_SIGNAL_POLE_DISTANCE_FROM_STOP_METERS)
throw new Error(
`${label}: signal pole is ${Math.round(poleDistance)}m from its stop line (maximum ${MAX_SIGNAL_POLE_DISTANCE_FROM_STOP_METERS}m)`,
);
return {
type: 'Feature',
geometry: { type: 'Point', coordinates: feature.geometry.coordinates.slice(0, 2).map(Number) },
@@ -212,8 +220,8 @@ function validateTrafficSignalFeatures(collection) {
face_heading_deg: faceHeading,
phase_group: phaseGroup,
mast_reach_m: number('mast_reach_m', { min: 0.1, max: 30 }),
stop_lon: number('stop_lon', { min: -180, max: 180 }),
stop_lat: number('stop_lat', { min: -90, max: 90 }),
stop_lon: stopLon,
stop_lat: stopLat,
enabled,
z_offset_m: number('z_offset_m', { min: -20, max: 100 }),
},
+103 -16
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Download, RefreshCw, Save, Upload } from 'lucide-react';
import { Download, RefreshCw, Upload } from 'lucide-react';
import { api, isVersionConflict } from './lib/api';
import { MapCanvas } from './components/MapCanvas';
import { ParameterPanel, type ParameterPanelHandle } from './components/ParameterPanel';
@@ -19,6 +19,7 @@ import type { ElementOutline } from './edit/handle-layer';
import {
azimuthBetween,
coordinateAtStation,
haversineMeters,
metersAlongPolyline,
polylineLengthMeters,
toLonLat,
@@ -116,6 +117,7 @@ function App() {
const signalRedoRef = useRef<GeoFeature[][]>([]);
const signalSavedRef = useRef<GeoFeature[] | null>(null);
const signalMoveActiveRef = useRef(false);
const signalRotateActiveRef = useRef(false);
const [layers, setLayers] = useState(defaultLayers);
const [scene, setScene] = useState(false);
const [status, setStatus] = useState('正在加载工作台...');
@@ -739,6 +741,20 @@ function App() {
signalRedoRef.current = [];
signalMoveActiveRef.current = true;
}
const currentFeature = current.trafficSignals.assemblies.features.find(
(feature) => feature.properties?.signal_uid === uid,
);
const stop: Coordinate | null = currentFeature
? [Number(currentFeature.properties?.stop_lon), Number(currentFeature.properties?.stop_lat)]
: null;
let nextCoordinate = coordinate;
if (stop && stop.every(Number.isFinite)) {
const distance = haversineMeters(stop, coordinate);
if (distance > 40) {
const ratio = 40 / distance;
nextCoordinate = [stop[0] + (coordinate[0] - stop[0]) * ratio, stop[1] + (coordinate[1] - stop[1]) * ratio];
}
}
return {
...current,
trafficSignals: {
@@ -747,7 +763,7 @@ function App() {
...current.trafficSignals.assemblies,
features: current.trafficSignals.assemblies.features.map((feature) =>
feature.properties?.signal_uid === uid
? { ...feature, geometry: { type: 'Point', coordinates: coordinate } }
? { ...feature, geometry: { type: 'Point', coordinates: nextCoordinate } }
: feature,
),
},
@@ -759,15 +775,80 @@ function App() {
const finishSignalMove = (uid: string, coordinate: Coordinate) => {
const current = state;
if (!current) return;
const source = current.trafficSignals.assemblies.features.find((feature) => feature.properties?.signal_uid === uid);
const stop: Coordinate | null = source
? [Number(source.properties?.stop_lon), Number(source.properties?.stop_lat)]
: null;
let nextCoordinate = coordinate;
if (stop && stop.every(Number.isFinite)) {
const distance = haversineMeters(stop, coordinate);
if (distance > 40) {
const ratio = 40 / distance;
nextCoordinate = [stop[0] + (coordinate[0] - stop[0]) * ratio, stop[1] + (coordinate[1] - stop[1]) * ratio];
}
}
const features = current.trafficSignals.assemblies.features.map((feature) =>
feature.properties?.signal_uid === uid
? { ...feature, geometry: { type: 'Point', coordinates: coordinate } }
? { ...feature, geometry: { type: 'Point', coordinates: nextCoordinate } }
: feature,
);
signalDraftRef.current = features;
signalMoveActiveRef.current = false;
setSignalDirty(true);
};
const rotateSignal = (uid: string, mastHeading: number) => {
const heading = ((mastHeading % 360) + 360) % 360;
setState((current) => {
if (!current) return current;
if (!signalRotateActiveRef.current) {
signalUndoRef.current.push(current.trafficSignals.assemblies.features);
signalRedoRef.current = [];
signalRotateActiveRef.current = true;
}
return {
...current,
trafficSignals: {
...current.trafficSignals,
assemblies: {
...current.trafficSignals.assemblies,
features: current.trafficSignals.assemblies.features.map((feature) =>
feature.properties?.signal_uid === uid
? {
...feature,
properties: {
...feature.properties,
mast_heading_deg: heading,
face_heading_deg: (((heading - 90) % 360) + 360) % 360,
},
}
: feature,
),
},
},
};
});
setSignalDirty(true);
};
const finishSignalRotate = (uid: string, mastHeading: number) => {
const current = state;
if (!current) return;
const heading = ((mastHeading % 360) + 360) % 360;
const features = current.trafficSignals.assemblies.features.map((feature) =>
feature.properties?.signal_uid === uid
? {
...feature,
properties: {
...feature.properties,
mast_heading_deg: heading,
face_heading_deg: (((heading - 90) % 360) + 360) % 360,
},
}
: feature,
);
signalDraftRef.current = features;
signalRotateActiveRef.current = false;
setSignalDirty(true);
};
return (
<>
<header>
@@ -809,17 +890,11 @@ function App() {
<a className="button" href="/api/export.zip" download>
<Download size={15} /> 导出道路包
</a>
<Button onClick={() => void save()} disabled={!staged.length}>
<Save size={15} /> 保存修改
</Button>
<Button onClick={() => void compile()}>
<RefreshCw size={15} /> 保存并重新生成
</Button>
{editMode ? (
<>
<Button onClick={() => void saveDirectEdits()} disabled={!session?.dirty}>
<Save size={15} /> 保存直接编辑
</Button>
<Button onClick={undoEdit} disabled={!session?.canUndo && !signalUndoRef.current.length}>
撤销
</Button>
@@ -898,9 +973,15 @@ function App() {
scene={scene}
onSelectRoad={setSelected}
onFeature={handleFeature}
onBackground={() => setElement(null)}
signalSelectionUid={typeof marking?.signal_uid === 'string' ? marking.signal_uid : null}
onBackground={() => {
setElement(null);
setMarking(null);
}}
onSignalDrag={moveSignal}
onSignalDragEnd={finishSignalMove}
onSignalRotate={rotateSignal}
onSignalRotateEnd={finishSignalRotate}
handles={editHandles}
ranges={editRanges}
element={elementOutline}
@@ -1435,9 +1516,19 @@ function SignalEditor({
: null;
const saveField = (key: string, value: unknown) => {
if (!feature) return;
const mastHeading = key === 'mast_heading_deg' ? ((Number(value) % 360) + 360) % 360 : null;
void update(
state.trafficSignals.assemblies.features.map((item) =>
item === feature ? { ...item, properties: { ...item.properties, [key]: value } } : item,
item === feature
? {
...item,
properties: {
...item.properties,
[key]: mastHeading ?? value,
...(mastHeading === null ? {} : { face_heading_deg: (((mastHeading - 90) % 360) + 360) % 360 }),
},
}
: item,
),
);
};
@@ -1505,11 +1596,7 @@ function SignalEditor({
</label>
<label>
灯面朝向(度)
<input
type="number"
value={Number(feature.properties?.face_heading_deg || 0)}
onChange={(event) => saveField('face_heading_deg', Number(event.target.value))}
/>
<input type="number" value={Number(feature.properties?.face_heading_deg || 0)} readOnly />
</label>
<label>
相位组
+120 -4
View File
@@ -1,12 +1,15 @@
import { useEffect, useRef } from 'react';
import Feature from 'ol/Feature';
import LineString from 'ol/geom/LineString';
import Map from 'ol/Map';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import View from 'ol/View';
import Select from 'ol/interaction/Select';
import PointerInteraction from 'ol/interaction/Pointer';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import CircleStyle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
@@ -18,6 +21,7 @@ import { EditGhostLayer } from '../edit/ghost-layer';
import { EditHandleLayer, type ElementOutline } from '../edit/handle-layer';
import { EditPreviewLayer } from '../edit/preview-layer';
import { fromLonLat, offsetCoordinate, signedMetersAlongAxis, toLonLat, type Coordinate } from '../edit/meters';
import { azimuthBetween } from '../edit/meters';
import type { IntervalRangeHandle } from '../edit/selection';
import type { EditHandle, PreviewLayerName, RoadIntervalAnchor } from '../edit/types';
@@ -49,6 +53,10 @@ interface Props {
onLaneSelectionDragEnd?: (from: Coordinate, to: Coordinate) => void;
onSignalDrag?: (signalUid: string, coordinate: Coordinate) => void;
onSignalDragEnd?: (signalUid: string, coordinate: Coordinate) => void;
/** The selected signal gets a temporary pivot marker and rotate handle. */
signalSelectionUid?: string | null;
onSignalRotate?: (signalUid: string, mastHeading: number) => void;
onSignalRotateEnd?: (signalUid: string, mastHeading: number) => void;
/** Authoritative preview geometry; null returns the map to the baseline. */
preview?: Partial<Record<PreviewLayerName, GeoJson | null>> | null;
/** Live value during a drag — the caller debounces the preview request. */
@@ -83,6 +91,9 @@ export function MapCanvas({
onLaneSelectionDragEnd,
onSignalDrag,
onSignalDragEnd,
signalSelectionUid,
onSignalRotate,
onSignalRotateEnd,
preview,
onHandleDrag,
onHandleDragEnd,
@@ -102,6 +113,8 @@ export function MapCanvas({
const fittedAreaIdRef = useRef<string | null>(null);
const laneSelectionSourceRef = useRef<VectorSource | null>(null);
const laneSelectionLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
const signalTransformSourceRef = useRef<VectorSource | null>(null);
const signalTransformLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
const laneSelectionFeaturesRef = useRef<Feature[]>([]);
const laneSelectionAnchorRef = useRef<Coordinate | null>(null);
const hiddenMarkingIdsRef = useRef<ReadonlySet<string>>(new Set());
@@ -122,6 +135,8 @@ export function MapCanvas({
onLaneSelectionDrag,
onSignalDrag,
onSignalDragEnd,
onSignalRotate,
onSignalRotateEnd,
laneSelectionAxisAzimuth,
ghostPending,
});
@@ -135,6 +150,8 @@ export function MapCanvas({
onLaneSelectionDrag,
onSignalDrag,
onSignalDragEnd,
onSignalRotate,
onSignalRotateEnd,
laneSelectionAxisAzimuth,
ghostPending,
};
@@ -177,6 +194,26 @@ export function MapCanvas({
});
laneSelectionSourceRef.current = laneSelectionSource;
laneSelectionLayerRef.current = laneSelectionLayer;
const signalTransformSource = new VectorSource();
const signalTransformLayer = new VectorLayer({
source: signalTransformSource,
zIndex: 95,
style: (feature) => {
const component = feature.get('signal_transform');
if (component === 'crosshair') return new Style({ stroke: new Stroke({ color: '#0e7490', width: 2 }) });
if (component === 'rotate-leader')
return new Style({ stroke: new Stroke({ color: '#2563eb', width: 1.5, lineDash: [4, 3] }) });
return new Style({
image: new CircleStyle({
radius: 8,
fill: new Fill({ color: '#2563eb' }),
stroke: new Stroke({ color: '#ffffff', width: 2 }),
}),
});
},
});
signalTransformSourceRef.current = signalTransformSource;
signalTransformLayerRef.current = signalTransformLayer;
// Direct-edit sources are always installed; visibility and hit testing follow
// the in-page browser/edit switch.
const handleLayer = new EditHandleLayer();
@@ -194,6 +231,7 @@ export function MapCanvas({
...Object.values(layers),
...(previewLayer ? previewLayer.all() : []),
laneSelectionLayer,
signalTransformLayer,
...(handleLayer ? [handleLayer.layer] : []),
...(ghost ? [ghost.layer] : []),
],
@@ -204,31 +242,62 @@ export function MapCanvas({
condition: click,
// Handles are not selectable features: clicking one must not re-target the
// road inspector, and dragging is owned by the edit interaction.
layers: (layer) => layer !== layers.selectedRoad && layer !== handleLayer?.layer && layer !== laneSelectionLayer,
layers: (layer) =>
layer !== layers.selectedRoad &&
layer !== handleLayer?.layer &&
layer !== laneSelectionLayer &&
layer !== signalTransformLayer,
hitTolerance: 12,
style: null,
});
map.addInteraction(select);
let signalUid: string | null = null;
let rotatePivot: Coordinate | null = null;
map.addInteraction(
new PointerInteraction({
handleDownEvent: (event) => {
if (!editModeRef.current) return false;
const rotateHit = event.map.forEachFeatureAtPixel(event.pixel, (feature) => feature, {
layerFilter: (layer) => layer === signalTransformLayer,
hitTolerance: 12,
});
if (rotateHit?.get('signal_transform') === 'rotate-handle') {
const uid = rotateHit.get('signal_uid');
const pivot = rotateHit.get('signal_pivot');
if (typeof uid === 'string' && Array.isArray(pivot) && pivot.length === 2) {
signalUid = uid;
rotatePivot = pivot as Coordinate;
event.map.getViewport().style.cursor = 'grabbing';
return true;
}
}
const hit = event.map.forEachFeatureAtPixel(event.pixel, (feature) => feature, {
layerFilter: (layer) => layer === layers.signals,
hitTolerance: 10,
});
const uid = hit?.get('signal_uid');
if (typeof uid !== 'string' || hit?.get('signal_component')) return false;
if (!hit || typeof uid !== 'string' || hit.get('signal_component')) return false;
signalUid = uid;
selectRef.current.onFeature(hit.getProperties());
event.map.getViewport().style.cursor = 'grabbing';
return true;
},
handleDragEvent: (event) => {
if (signalUid) dragRef.current.onSignalDrag?.(signalUid, toLonLat(event.coordinate as Coordinate));
if (signalUid) {
const target = toLonLat(event.coordinate as Coordinate);
if (rotatePivot) dragRef.current.onSignalRotate?.(signalUid, azimuthBetween(rotatePivot, target));
else dragRef.current.onSignalDrag?.(signalUid, target);
}
},
handleUpEvent: (event) => {
if (signalUid) dragRef.current.onSignalDragEnd?.(signalUid, toLonLat(event.coordinate as Coordinate));
if (signalUid) {
const target = toLonLat(event.coordinate as Coordinate);
if (rotatePivot) dragRef.current.onSignalRotateEnd?.(signalUid, azimuthBetween(rotatePivot, target));
else dragRef.current.onSignalDragEnd?.(signalUid, target);
}
signalUid = null;
rotatePivot = null;
event.map.getViewport().style.cursor = '';
return false;
},
}),
@@ -372,6 +441,53 @@ export function MapCanvas({
);
laneSelectionFeaturesRef.current = parts;
}, [laneSelectionBounds, laneSelectionFeatures]);
useEffect(() => {
const source = signalTransformSourceRef.current;
const layer = signalTransformLayerRef.current;
if (!source || !layer) return;
source.clear();
layer.setVisible(Boolean(editMode && signalSelectionUid));
if (!editMode || !signalSelectionUid) return;
const signal = state.trafficSignals.assemblies.features.find(
(feature) => feature.properties?.signal_uid === signalSelectionUid,
);
const pivot =
signal?.geometry?.type === 'Point' && Array.isArray(signal.geometry.coordinates)
? (signal.geometry.coordinates as Coordinate)
: null;
const mastHeading = Number(signal?.properties?.mast_heading_deg);
const reach = Number(signal?.properties?.mast_reach_m);
if (!pivot || !Number.isFinite(mastHeading) || !Number.isFinite(reach)) return;
const mastEnd = offsetCoordinate(pivot, mastHeading, reach);
const rotateHandle = offsetCoordinate(pivot, mastHeading, reach + 1.2);
const crosshairRadius = 0.45;
source.addFeatures([
new Feature({
geometry: new LineString([
fromLonLat(offsetCoordinate(pivot, 270, crosshairRadius)),
fromLonLat(offsetCoordinate(pivot, 90, crosshairRadius)),
]),
signal_transform: 'crosshair',
}),
new Feature({
geometry: new LineString([
fromLonLat(offsetCoordinate(pivot, 180, crosshairRadius)),
fromLonLat(offsetCoordinate(pivot, 0, crosshairRadius)),
]),
signal_transform: 'crosshair',
}),
new Feature({
geometry: new LineString([fromLonLat(mastEnd), fromLonLat(rotateHandle)]),
signal_transform: 'rotate-leader',
}),
new Feature({
geometry: new Point(fromLonLat(rotateHandle)),
signal_transform: 'rotate-handle',
signal_uid: signalSelectionUid,
signal_pivot: pivot,
}),
]);
}, [editMode, signalSelectionUid, state.trafficSignals.assemblies.features]);
useEffect(() => {
// Selection changes only affect presentation; compiler GeoJSON stays untouched.
layersRef.current?.markings.changed();
+1 -1
View File
@@ -198,7 +198,7 @@ export function updateLayers(layers: ReturnType<typeof createLayers>, state: Wor
{
type: 'Feature' as const,
geometry: { type: 'Point', coordinates: faceEnd },
properties: { ...properties, signal_component: 'face-tip', signal_heading: faceHeading },
properties: { ...properties, signal_component: 'face-tip', signal_heading: faceHeading, signal_origin: point },
},
];
});