Stations like "WEINFELDEN Kreisel West - Umfahrung" have directions such as "zur Umfahrung" or "von Egelseestrasse" that cannot be geocoded, so their dots were drawn on a nearby side road or around the roundabout ring. - Derive the roundabout centre from all stations sharing the name before " - " and point each arm outward from it - Prefer road segments named like the station's address when following an arm; reject arms that don't get away from the centre - Parse "zur", "zum", "Richtung" and "vom" direction prefixes - Treat only swissTLM3D object kinds 12-19 as non-roads; kind 20 is a regular road (e.g. Dunantstrasse in Weinfelden) - Bump the geometry cache to v7 so all stations are rebuilt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
302 lines
11 KiB
C#
302 lines
11 KiB
C#
using System.Numerics;
|
|
using Schaad.OpenData.Traffic.Models;
|
|
|
|
namespace Schaad.OpenData.Traffic.Geometry;
|
|
|
|
public static class RoadPathBuilder
|
|
{
|
|
private const float JoinToleranceMeters = 2f;
|
|
private const double MaxTurnDegrees = 60;
|
|
private const double MinimumSideLengthMeters = 60;
|
|
private const double MainRoadSnapMeters = 60;
|
|
private const double RoadClassChangePenaltyDegrees = 25;
|
|
|
|
private const double ArmSearchMeters = 80;
|
|
private const float ArmDistancePenalty = 2f;
|
|
private const float MinimumArmProgressMeters = 30f;
|
|
|
|
private sealed record RoadLine(List<Vector2> Points, bool IsMainRoad, string? Name);
|
|
|
|
private static List<RoadLine> ToLines(IReadOnlyList<RoadSegment> segments, LocalProjection projection)
|
|
{
|
|
var usable = segments.Where(s => s.Points.Count >= 2).ToList();
|
|
var drivable = usable.Where(s => s.IsDrivable).ToList();
|
|
return (drivable.Count > 0 ? drivable : usable)
|
|
.Select(s => new RoadLine(s.Points.Select(projection.ToLocal).ToList(), s.IsMainRoad, s.Name))
|
|
.ToList();
|
|
}
|
|
|
|
public static IReadOnlyList<GeoPoint>? BuildRoadPath(GeoPoint station, IReadOnlyList<RoadSegment> segments, double halfLengthMeters)
|
|
{
|
|
var projection = new LocalProjection(station);
|
|
var lines = ToLines(segments, projection);
|
|
if (lines.Count == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var distances = lines.Select(l => DistanceToPolyline(Vector2.Zero, l.Points)).ToList();
|
|
var nearestMain = Enumerable.Range(0, lines.Count)
|
|
.Where(i => lines[i].IsMainRoad && distances[i] <= MainRoadSnapMeters)
|
|
.OrderBy(i => distances[i])
|
|
.Select(i => (int?)i)
|
|
.FirstOrDefault();
|
|
var start = nearestMain ?? Enumerable.Range(0, lines.Count).MinBy(i => distances[i]);
|
|
|
|
var chain = new List<Vector2>(lines[start].Points);
|
|
var used = new HashSet<int> { start };
|
|
var preferMain = lines[start].IsMainRoad;
|
|
ExtendAtEnd(chain, lines, used, preferMain, halfLengthMeters);
|
|
chain.Reverse();
|
|
ExtendAtEnd(chain, lines, used, preferMain, halfLengthMeters);
|
|
chain.Reverse();
|
|
|
|
var trimmed = Trim(chain, ArcPositionOf(Vector2.Zero, chain), halfLengthMeters);
|
|
return trimmed.Count >= 2 ? trimmed.Select(projection.ToGeo).ToList() : null;
|
|
}
|
|
|
|
public static IReadOnlyList<GeoPoint>? BuildArmPath(
|
|
GeoPoint station,
|
|
IReadOnlyList<RoadSegment> segments,
|
|
GeoPoint target,
|
|
double lengthMeters,
|
|
string? roadName = null)
|
|
{
|
|
var projection = new LocalProjection(station);
|
|
var toward = projection.ToLocal(target);
|
|
if (toward.LengthSquared() < 1e-6f)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
toward = Vector2.Normalize(toward);
|
|
var lines = ToLines(segments, projection);
|
|
var nearby = lines
|
|
.Select((line, index) => (Index: index, Distance: DistanceToPolyline(Vector2.Zero, line.Points), line.Name))
|
|
.Where(c => c.Distance <= ArmSearchMeters)
|
|
.ToList();
|
|
var named = nearby
|
|
.Where(c => !string.IsNullOrEmpty(roadName) && string.Equals(c.Name, roadName, StringComparison.OrdinalIgnoreCase))
|
|
.Select(c => (c.Index, c.Distance))
|
|
.ToList();
|
|
var all = nearby.Select(c => (c.Index, c.Distance)).ToList();
|
|
|
|
var arm = BestArm(lines, named, toward, lengthMeters) ?? BestArm(lines, all, toward, lengthMeters);
|
|
return arm?.Select(projection.ToGeo).ToList();
|
|
}
|
|
|
|
private static List<Vector2>? BestArm(List<RoadLine> lines, List<(int Index, double Distance)> candidates, Vector2 toward, double lengthMeters) =>
|
|
candidates
|
|
.Select(c =>
|
|
{
|
|
var arm = FollowArm(lines, c.Index, toward, lengthMeters);
|
|
var isValid = arm.Count >= 2 && Length(arm) >= MinimumSideLengthMeters && Vector2.Dot(arm[^1], toward) >= MinimumArmProgressMeters;
|
|
return (Arm: arm, IsValid: isValid, Score: Vector2.Dot(arm.Count > 0 ? arm[^1] : Vector2.Zero, toward) - ArmDistancePenalty * c.Distance);
|
|
})
|
|
.Where(c => c.IsValid)
|
|
.OrderByDescending(c => c.Score)
|
|
.Select(c => c.Arm)
|
|
.FirstOrDefault();
|
|
|
|
private static List<Vector2> FollowArm(List<RoadLine> lines, int start, Vector2 toward, double lengthMeters)
|
|
{
|
|
var chain = new List<Vector2>(lines[start].Points);
|
|
if (Vector2.Dot(chain[^1] - chain[0], toward) < 0)
|
|
{
|
|
chain.Reverse();
|
|
}
|
|
|
|
ExtendAtEnd(chain, lines, [start], lines[start].IsMainRoad, lengthMeters);
|
|
var position = ArcPositionOf(Vector2.Zero, chain);
|
|
return Trim(chain, position + lengthMeters / 2, lengthMeters / 2);
|
|
}
|
|
|
|
public static IReadOnlyList<GeoPoint> BuildStraightPath(GeoPoint station, GeoPoint? toward, double halfLengthMeters)
|
|
{
|
|
var projection = new LocalProjection(station);
|
|
var direction = toward is { } target ? projection.ToLocal(target) : Vector2.UnitX;
|
|
direction = direction.LengthSquared() < 1e-6 ? Vector2.UnitX : Vector2.Normalize(direction);
|
|
var offset = direction * (float)halfLengthMeters;
|
|
return [projection.ToGeo(-offset), projection.ToGeo(offset)];
|
|
}
|
|
|
|
public static IReadOnlyList<DirectionGeometry> Orient(GeoPoint station, IReadOnlyList<GeoPoint> path, IReadOnlyList<ResolvedDirection> directions)
|
|
{
|
|
var projection = new LocalProjection(station);
|
|
var pathVector = projection.ToLocal(path[^1]) - projection.ToLocal(path[0]);
|
|
|
|
var forward = directions
|
|
.Select(d => d.TargetLocation is { } location
|
|
? (bool?)((Vector2.Dot(pathVector, projection.ToLocal(location)) > 0) == d.Target.IsDestination)
|
|
: null)
|
|
.ToList();
|
|
|
|
if (forward.Count == 2)
|
|
{
|
|
forward = (forward[0], forward[1]) switch
|
|
{
|
|
(null, null) => [true, false],
|
|
({ } first, null) => [first, !first],
|
|
(null, { } second) => [!second, second],
|
|
({ } first, { } second) when first == second => [first, !first],
|
|
_ => forward,
|
|
};
|
|
}
|
|
|
|
var reversed = path.Reverse().ToList();
|
|
return directions
|
|
.Select((d, i) => new DirectionGeometry(d.Direction, (forward[i] ?? i % 2 == 0) ? path : reversed))
|
|
.ToList();
|
|
}
|
|
|
|
private static void ExtendAtEnd(List<Vector2> chain, List<RoadLine> lines, HashSet<int> used, bool preferMain, double halfLengthMeters)
|
|
{
|
|
while (Length(chain) - ArcPositionOf(Vector2.Zero, chain) < halfLengthMeters)
|
|
{
|
|
var end = chain[^1];
|
|
var heading = Heading(chain[^2], end);
|
|
var best = -1;
|
|
var bestAngle = double.MaxValue;
|
|
List<Vector2>? bestLine = null;
|
|
|
|
for (var i = 0; i < lines.Count; i++)
|
|
{
|
|
if (used.Contains(i))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var line = lines[i].Points;
|
|
List<Vector2>? oriented = null;
|
|
if (Vector2.Distance(line[0], end) <= JoinToleranceMeters)
|
|
{
|
|
oriented = line;
|
|
}
|
|
else if (Vector2.Distance(line[^1], end) <= JoinToleranceMeters)
|
|
{
|
|
oriented = Enumerable.Reverse(line).ToList();
|
|
}
|
|
|
|
if (oriented is null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var next = oriented.FirstOrDefault(p => Vector2.Distance(p, oriented[0]) > 0.5f, oriented[^1]);
|
|
var angle = Math.Acos(Math.Clamp(Vector2.Dot(heading, Heading(oriented[0], next)), -1f, 1f)) * 180 / Math.PI;
|
|
var score = angle + (lines[i].IsMainRoad == preferMain ? 0 : RoadClassChangePenaltyDegrees);
|
|
if (angle <= MaxTurnDegrees && score < bestAngle)
|
|
{
|
|
best = i;
|
|
bestAngle = score;
|
|
bestLine = oriented;
|
|
}
|
|
}
|
|
|
|
if (bestLine is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
used.Add(best);
|
|
chain.AddRange(bestLine.Skip(1));
|
|
}
|
|
}
|
|
|
|
private static List<Vector2> Trim(List<Vector2> chain, double center, double halfLengthMeters)
|
|
{
|
|
var from = center - halfLengthMeters;
|
|
var to = center + halfLengthMeters;
|
|
var result = new List<Vector2>();
|
|
var position = 0d;
|
|
|
|
for (var i = 0; i < chain.Count - 1; i++)
|
|
{
|
|
var a = chain[i];
|
|
var b = chain[i + 1];
|
|
var length = Vector2.Distance(a, b);
|
|
var start = position;
|
|
var end = position + length;
|
|
position = end;
|
|
|
|
if (end < from || start > to || length <= 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (result.Count == 0)
|
|
{
|
|
result.Add(start >= from ? a : Vector2.Lerp(a, b, (float)((from - start) / length)));
|
|
}
|
|
|
|
if (end <= to)
|
|
{
|
|
result.Add(b);
|
|
}
|
|
else
|
|
{
|
|
result.Add(Vector2.Lerp(a, b, (float)((to - start) / length)));
|
|
break;
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private static double ArcPositionOf(Vector2 point, List<Vector2> chain)
|
|
{
|
|
var bestDistance = double.MaxValue;
|
|
var bestPosition = 0d;
|
|
var position = 0d;
|
|
|
|
for (var i = 0; i < chain.Count - 1; i++)
|
|
{
|
|
var a = chain[i];
|
|
var b = chain[i + 1];
|
|
var length = Vector2.Distance(a, b);
|
|
var t = length > 0 ? Math.Clamp(Vector2.Dot(point - a, b - a) / (length * length), 0, 1) : 0;
|
|
var distance = Vector2.Distance(point, Vector2.Lerp(a, b, t));
|
|
if (distance < bestDistance)
|
|
{
|
|
bestDistance = distance;
|
|
bestPosition = position + t * length;
|
|
}
|
|
|
|
position += length;
|
|
}
|
|
|
|
return bestPosition;
|
|
}
|
|
|
|
private static double DistanceToPolyline(Vector2 point, List<Vector2> line)
|
|
{
|
|
var best = double.MaxValue;
|
|
for (var i = 0; i < line.Count - 1; i++)
|
|
{
|
|
var a = line[i];
|
|
var b = line[i + 1];
|
|
var lengthSquared = Vector2.DistanceSquared(a, b);
|
|
var t = lengthSquared > 0 ? Math.Clamp(Vector2.Dot(point - a, b - a) / lengthSquared, 0, 1) : 0;
|
|
best = Math.Min(best, Vector2.Distance(point, Vector2.Lerp(a, b, t)));
|
|
}
|
|
|
|
return best;
|
|
}
|
|
|
|
private static double Length(List<Vector2> chain)
|
|
{
|
|
var length = 0d;
|
|
for (var i = 0; i < chain.Count - 1; i++)
|
|
{
|
|
length += Vector2.Distance(chain[i], chain[i + 1]);
|
|
}
|
|
|
|
return length;
|
|
}
|
|
|
|
private static Vector2 Heading(Vector2 from, Vector2 to)
|
|
{
|
|
var delta = to - from;
|
|
return delta.LengthSquared() < 1e-6f ? Vector2.UnitX : Vector2.Normalize(delta);
|
|
}
|
|
}
|