-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathxodr_parser.py
1910 lines (1745 loc) · 79.6 KB
/
xodr_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Parser for OpenDRIVE (.xodr) files."""
import abc
from collections import defaultdict
import itertools
import math
import warnings
import xml.etree.ElementTree as ET
import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.optimize import brentq
from shapely.geometry import GeometryCollection, MultiPoint, MultiPolygon, Point, Polygon
from shapely.ops import snap, unary_union
from scenic.core.geometry import (
averageVectors,
cleanChain,
cleanPolygon,
plotPolygon,
polygonUnion,
removeHoles,
)
from scenic.core.regions import PolygonalRegion, PolylineRegion
from scenic.core.vectors import Vector
from scenic.domains.driving import roads as roadDomain
class OpenDriveWarning(UserWarning):
pass
def warn(message):
warnings.warn(message, OpenDriveWarning, stacklevel=2)
def buffer_union(polys, tolerance=0.01):
return polygonUnion(polys, buf=tolerance, tolerance=tolerance)
class Poly3:
"""Cubic polynomial."""
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def eval_at(self, x):
return self.a + self.b * x + self.c * x**2 + self.d * x**3
def grad_at(self, x):
return self.b + 2 * self.c * x + 3 * self.d * x**2
class Curve:
"""Geometric elements which compose road reference lines.
See the OpenDRIVE Format Specification for coordinate system details."""
def __init__(self, x0, y0, hdg, length):
self.x0 = x0
self.y0 = y0
self.hdg = hdg # In radians counterclockwise, 0 at positive x-axis.
self.cos_hdg, self.sin_hdg = math.cos(hdg), math.sin(hdg)
self.length = length
def to_points(self, num, extra_points=[]):
"""Sample NUM evenly-spaced points from curve.
Points are tuples of (x, y, s) with (x, y) absolute coordinates
and s the arc length along the curve. Additional points at s values in
extra_points are included if they are contained in the curve (unless
they are extremely close to one of the equally-spaced points).
"""
s_vals = []
extras = itertools.chain(extra_points, itertools.repeat(float("inf")))
next_extra = next(extras)
last_s = 0
for s in np.linspace(0, self.length, num=num):
while next_extra <= s:
if last_s + 1e-6 < next_extra < s - 1e-6:
s_vals.append(next_extra)
next_extra = next(extras)
s_vals.append(s)
last_s = s
return [self.point_at(s) for s in s_vals]
@abc.abstractmethod
def point_at(self, s):
"""Get an (x, y, s) point along the curve at the given s coordinate."""
return
def rel_to_abs(self, point):
"""Convert from relative coordinates of curve to absolute coordinates.
I.e. rotate counterclockwise by self.hdg and translate by (x0, x1)."""
x, y, s = point
return (
self.x0 + self.cos_hdg * x - self.sin_hdg * y,
self.y0 + self.sin_hdg * x + self.cos_hdg * y,
s,
)
class Cubic(Curve):
"""A curve defined by the cubic polynomial a + bu + cu^2 + du^3.
The curve starts at (X0, Y0) in direction HDG, with length LENGTH."""
def __init__(self, x0, y0, hdg, length, a, b, c, d):
super().__init__(x0, y0, hdg, length)
self.poly = Poly3(a, b, c, d)
# Crude upper bound for u (used to bracket u for a given s in point_at)
if d != 0:
self.ubound = max(
2 * abs(c / d), abs(b / d) ** 0.5, (3 * length / abs(d)) ** (1 / 3)
)
elif c != 0:
self.ubound = max(abs(b / c), (2 * length / abs(c)) ** 0.5)
else:
self.ubound = length / abs(b)
def arclength(self, u):
d_arc = lambda x: np.sqrt(1 + self.poly.grad_at(x) ** 2)
return quad(d_arc, 0, u)[0]
def point_at(self, s):
# Use Brent's method to find parameter u corresponding to arclength s;
# (N.B. Brent's method proved to be faster than Newton's and has no potential
# convergence issues.)
root_func = lambda x: self.arclength(x) - s
u = float(brentq(root_func, 0, self.ubound))
pt = (s, self.poly.eval_at(u), s)
return self.rel_to_abs(pt)
class ParamCubic(Curve):
"""A curve defined by the parametric equations
u = a_u + b_up + c_up^2 + d_up^3,
v = a_v + b_vp + c_vp^2 + d_up^3,
with p in [0, p_range].
The curve starts at (X0, Y0) in direction HDG, with length LENGTH."""
def __init__(self, x0, y0, hdg, length, au, bu, cu, du, av, bv, cv, dv, p_range=1):
super().__init__(x0, y0, hdg, length)
self.u_poly = Poly3(au, bu, cu, du)
self.v_poly = Poly3(av, bv, cv, dv)
self.p_range = p_range if p_range else 1
def arclength(self, p):
d_arc = lambda x: math.hypot(self.u_poly.grad_at(x), self.v_poly.grad_at(x))
return quad(d_arc, 0, p)[0]
def point_at(self, s):
root_func = lambda x: self.arclength(x) - s
p = float(brentq(root_func, 0, self.p_range))
pt = (self.u_poly.eval_at(p), self.v_poly.eval_at(p), s)
return self.rel_to_abs(pt)
class Clothoid(Curve):
"""An Euler spiral with curvature varying linearly between CURV0 and CURV1.
The spiral starts at (X0, Y0) in direction HDG, with length LENGTH."""
def __init__(self, x0, y0, hdg, length, curv0, curv1):
super().__init__(x0, y0, hdg, length)
# Initial and final curvature.
self.curv0 = curv0
self.curv1 = curv1
self.curve_rate = (curv1 - curv0) / length
self.a = abs(curv0)
self.r = 1 / self.a if curv0 != 0 else 1 # value not used if curv0 == 0
self.ode_init = np.array([x0, y0, hdg])
def point_at(self, s):
# Generate a origin-centered clothoid with zero curvature at origin,
# then translate/rotate the relevant segment.
# Arcs are just a degenerate clothoid:
if self.curv0 == self.curv1:
if self.curv0 == 0:
pt = (s, 0, s)
else:
r = self.r
th = s * self.a
if self.curv0 > 0:
pt = (r * math.sin(th), r - r * math.cos(th), s)
else:
pt = (r * math.sin(th), -r + r * math.cos(th), s)
return self.rel_to_abs(pt)
else:
def clothoid_ode(s, state):
x, y, theta = state
return np.array(
[math.cos(theta), math.sin(theta), self.curv0 + (self.curve_rate * s)]
)
sol = solve_ivp(clothoid_ode, (0, s), self.ode_init)
x, y, hdg = sol.y[:, -1]
return (x, y, s)
class Line(Curve):
"""A line segment between (x0, y0) and (x1, y1)."""
def __init__(self, x0, y0, hdg, length):
super().__init__(x0, y0, hdg, length)
# Endpoints of line.
self.x1 = x0 + length * math.cos(hdg)
self.y1 = y0 + length * math.sin(hdg)
def point_at(self, s):
return self.rel_to_abs((s, 0, s))
class Lane:
def __init__(self, id_, type_, pred=None, succ=None):
self.id_ = id_
self.width = [] # List of tuples (Poly3, int) for width and s-offset.
self.type_ = type_
self.pred = pred
self.succ = succ
self.left_bounds = [] # to be filled in later
self.right_bounds = []
self.centerline = []
self.parent_lane_poly = None
def width_at(self, s):
# S here is relative to start of LaneSection this lane is in.
ind = 0
while ind + 1 < len(self.width) and self.width[ind + 1][1] <= s:
ind += 1
assert self.width[ind][1] <= s, "No matching width entry found."
w_poly, s_off = self.width[ind]
w = w_poly.eval_at(s - s_off)
if w < -1e-6: # allow for numerical error
raise RuntimeError("OpenDRIVE lane has negative width")
return max(w, 0)
class LaneSection:
def __init__(self, s0, left_lanes={}, right_lanes={}):
self.s0 = s0
self.left_lanes = left_lanes
self.right_lanes = right_lanes
self.left_lane_ids = sorted(self.left_lanes.keys())
self.right_lane_ids = sorted(self.right_lanes.keys(), reverse=True)
self.lanes = dict(list(left_lanes.items()) + list(right_lanes.items()))
def get_lane(self, id_):
if id_ in self.left_lanes:
return self.left_lanes[id_]
elif id_ in self.right_lanes:
return self.right_lanes[id_]
elif id_ == 0:
return Lane(0, "none")
else:
raise RuntimeError("Lane with id", id_, "not found")
def get_offsets(self, s):
"""Returns dict of lane id and offset from
reference line of lane boundary at coordinate S along line.
By convention, left lanes have positive width offset and right lanes
have negative."""
assert s >= self.s0, "Input s is before lane start position."
offsets = {}
for lane_id in self.left_lane_ids:
if lane_id - 1 in self.left_lane_ids:
offsets[lane_id] = offsets[lane_id - 1] + self.left_lanes[
lane_id
].width_at(s - self.s0)
else:
offsets[lane_id] = self.left_lanes[lane_id].width_at(s - self.s0)
for lane_id in self.right_lane_ids:
if lane_id + 1 in self.right_lane_ids:
offsets[lane_id] = offsets[lane_id + 1] - self.right_lanes[
lane_id
].width_at(s - self.s0)
else:
offsets[lane_id] = -self.right_lanes[lane_id].width_at(s - self.s0)
return offsets
class RoadLink:
"""Indicates Roads a and b, with ids id_a and id_b respectively, are connected."""
def __init__(self, id_a, id_b, contact_a, contact_b):
self.id_a = id_a
self.id_b = id_b
# contact_a and contact_b should be of value "start" or "end"
# and indicate which end of each road is connected to the other.
self.contact_a = contact_a
self.contact_b = contact_b
class Junction:
class Connection:
def __init__(self, incoming_id, connecting_id, connecting_contact, lane_links):
self.incoming_id = incoming_id
# id of connecting road
self.connecting_id = connecting_id
# contact point ('start' or 'end') on connecting road
self.connecting_contact = connecting_contact
# dict mapping incoming to connecting lane ids (empty = identity mapping)
self.lane_links = lane_links
def __init__(self, id_, name):
self.id_ = id_
self.name = name
self.connections = []
# Ids of roads that are paths within junction:
self.paths = []
self.poly = None
def add_connection(self, incoming_id, connecting_id, connecting_contact, lane_links):
conn = Junction.Connection(
incoming_id, connecting_id, connecting_contact, lane_links
)
self.connections.append(conn)
class Road:
def __init__(self, name, id_, length, junction, drive_on_right=True):
self.name = name
self.id_ = id_
self.length = length
self.junction = junction if junction != "-1" else None
self.predecessor = None
self.successor = None
self.signals = [] # List of Signal objects.
self.lane_secs = [] # List of LaneSection objects.
self.ref_line = [] # List of Curve objects defining reference line.
# NOTE: sec_points, sec_polys, sec_lane_polys should be ordered according to lane_secs.
self.sec_points = [] # List of lists of points, one for each LaneSection.
self.sec_polys = [] # List of Polygons, one for each LaneSections.
# List of dict of lane id to Polygon for each LaneSection.
self.sec_lane_polys = []
# List of lane polygons. Not a dict b/c lane id is not unique along road.
self.lane_polys = []
# Each polygon in lane_polys is the union of connected lane section polygons.
# lane_polys is currently not used.
# Reference line offset:
self.offset = [] # List of tuple (Poly3, s-coordinate).
self.drive_on_right = drive_on_right
# Used to fill in gaps between roads:
self.start_bounds_left = {}
self.start_bounds_right = {}
self.end_bounds_left = {}
self.end_bounds_right = {}
self.remappedStartLanes = None # hack for handling spurious initial lane sections
def get_ref_line_offset(self, s):
if not self.offset:
return 0
ind = 0
while ind + 1 < len(self.offset) and self.offset[ind + 1][1] <= s:
ind += 1
poly, s0 = self.offset[ind]
assert s >= s0
return poly.eval_at(s - s0)
def get_ref_points(self, num):
"""Returns list of list of points for each piece of ref_line.
List of list structure necessary because each piece needs to be
constructed into Polygon separately then unioned afterwards to avoid
self-intersecting lines."""
ref_points = []
transition_points = [sec.s0 for sec in self.lane_secs[1:]]
last_s = 0
for piece in self.ref_line:
piece_points = piece.to_points(num, extra_points=transition_points)
assert piece_points, "Failed to get piece points"
if ref_points:
last_s = ref_points[-1][-1][2]
piece_points = [(p[0], p[1], p[2] + last_s) for p in piece_points]
ref_points.append(piece_points)
transition_points = [s - last_s for s in transition_points if s > last_s]
return ref_points
def heading_at(self, point):
# Convert point to shapely Point.
point = Point(point.x, point.y)
for i in range(len(self.lane_secs)):
ref_points = self.sec_points[i]
poly = self.sec_polys[i]
if point.within(poly.buffer(1)):
lane_id = None
for id_ in self.sec_lane_polys[i].keys():
if point.within(self.sec_lane_polys[i][id_].buffer(1)):
lane_id = id_
break
assert lane_id is not None, "Point not found in sec_lane_polys."
min_dist = float("inf")
for i in range(len(ref_points)):
cur_point = Point(ref_points[i][0], ref_points[i][1])
if point.distance(cur_point) < min_dist:
closest_idx = i
if closest_idx >= len(ref_points) - 1:
closest_idx = len(ref_points) - 2
dy = ref_points[closest_idx + 1][1] - ref_points[closest_idx][1]
dx = ref_points[closest_idx + 1][0] - ref_points[closest_idx][0]
heading = math.atan2(dy, dx)
# Right lanes have negative lane_id.
# Flip heading if drive_on_right XOR right lane.
if self.drive_on_right != (lane_id < 0):
heading += math.pi
# Heading 0 is defined differently between OpenDrive and Scenic(?)
heading -= math.pi / 2
return (heading + math.pi) % (2 * math.pi) - math.pi
raise RuntimeError("Point not found in piece_polys")
def calc_geometry_for_type(self, lane_types, num, tolerance, calc_gap=False):
"""Given a list of lane types, returns a tuple of:
- List of lists of points along the reference line, with same indexing as self.lane_secs
- List of region polygons, with same indexing as self.lane_secs
- List of dictionary of lane id to polygon, with same indexing as self.lane_secs
- List of polygons for each lane (not necessarily by id, but respecting lane successor/predecessor)
- Polygon for entire region.
If calc_gap=True, fills in gaps between connected roads. This is fairly expensive.
"""
road_polygons = []
ref_points = self.get_ref_points(num)
self.ref_line_points = list(itertools.chain.from_iterable(ref_points))
cur_lane_polys = {}
sec_points = []
sec_polys = []
sec_lane_polys = []
lane_polys = []
last_lefts = None
last_rights = None
cur_p = None
for i in range(len(self.lane_secs)):
cur_sec = self.lane_secs[i]
cur_sec_points = []
if i < len(self.lane_secs) - 1:
next_sec = self.lane_secs[i + 1]
s_stop = next_sec.s0
else:
s_stop = float("inf")
left_bounds = defaultdict(list)
right_bounds = defaultdict(list)
cur_sec_lane_polys = defaultdict(list)
cur_sec_polys = []
end_of_sec = False
while ref_points and not end_of_sec:
if not ref_points[0]:
ref_points.pop(0)
if not ref_points or (cur_p and cur_p[2] >= s_stop):
# Case 1: We have processed the entire reference line.
# Case 2: The s-coordinate has exceeded s_stop, so we should move
# onto the next LaneSection.
# Either way, we collect all the bound points so far into polygons.
end_of_sec = True
cur_last_lefts = {}
cur_last_rights = {}
for id_ in left_bounds:
# Polygon for piece of lane:
left = left_bounds[id_]
right = right_bounds[id_][::-1]
bounds = left + right
if len(bounds) < 3:
continue
poly = cleanPolygon(Polygon(bounds), tolerance)
if not poly.is_empty:
if poly.geom_type == "MultiPolygon":
poly = MultiPolygon(
[
p
for p in poly.geoms
if not p.is_empty and p.exterior
]
)
cur_sec_polys.extend(poly.geoms)
else:
cur_sec_polys.append(poly)
cur_sec_lane_polys[id_].append(poly)
cur_last_lefts[id_] = left_bounds[id_][-1]
cur_last_rights[id_] = right_bounds[id_][-1]
if i == 0 or not self.start_bounds_left:
self.start_bounds_left[id_] = left_bounds[id_][0]
self.start_bounds_right[id_] = right_bounds[id_][0]
left_bounds = defaultdict(list)
right_bounds = defaultdict(list)
if cur_last_lefts and cur_last_rights:
last_lefts = cur_last_lefts
last_rights = cur_last_rights
else:
cur_p = ref_points[0][0]
cur_sec_points.append(cur_p)
s = min(max(cur_p[2], cur_sec.s0), s_stop - 1e-6)
offsets = cur_sec.get_offsets(s)
offsets[0] = 0
for id_ in offsets:
offsets[id_] += self.get_ref_line_offset(s)
if len(ref_points[0]) > 1:
next_p = ref_points[0][1]
tan_vec = (next_p[0] - cur_p[0], next_p[1] - cur_p[1])
else:
if len(cur_sec_points) >= 2:
prev_p = cur_sec_points[-2]
else:
assert len(sec_points) > 0
if sec_points[-1]:
assert sec_points[-1][-1] == cur_p
prev_p = sec_points[-1][-2]
else:
prev_p = sec_points[-2][-2]
tan_vec = (cur_p[0] - prev_p[0], cur_p[1] - prev_p[1])
tan_norm = math.hypot(tan_vec[0], tan_vec[1])
assert tan_norm > 1e-10
normal_vec = (-tan_vec[1] / tan_norm, tan_vec[0] / tan_norm)
if cur_p[2] < s_stop:
# if at end of section, keep current point to be included in
# the next section as well; otherwise remove it
ref_points[0].pop(0)
elif len(ref_points[0]) == 1 and len(ref_points) > 1:
# also get rid of point if this is the last point of the current geometry and
# and there is another geometry following
ref_points[0].pop(0)
for id_ in offsets:
lane = cur_sec.get_lane(id_)
if lane.type_ in lane_types:
if id_ > 0:
prev_id = id_ - 1
else:
prev_id = id_ + 1
left_bound = [
cur_p[0] + normal_vec[0] * offsets[id_],
cur_p[1] + normal_vec[1] * offsets[id_],
]
right_bound = [
cur_p[0] + normal_vec[0] * offsets[prev_id],
cur_p[1] + normal_vec[1] * offsets[prev_id],
]
if id_ < 0:
left_bound, right_bound = right_bound, left_bound
halfway = (offsets[id_] + offsets[prev_id]) / 2
centerline = [
cur_p[0] + normal_vec[0] * halfway,
cur_p[1] + normal_vec[1] * halfway,
]
left_bounds[id_].append(left_bound)
right_bounds[id_].append(right_bound)
lane.left_bounds.append(left_bound)
lane.right_bounds.append(right_bound)
lane.centerline.append(centerline)
assert len(cur_sec_points) >= 2, i
sec_points.append(cur_sec_points)
sec_polys.append(buffer_union(cur_sec_polys, tolerance=tolerance))
for id_ in cur_sec_lane_polys:
poly = buffer_union(cur_sec_lane_polys[id_], tolerance=tolerance)
cur_sec_lane_polys[id_] = poly
cur_sec.get_lane(id_).poly = poly
sec_lane_polys.append(dict(cur_sec_lane_polys))
next_lane_polys = {}
for id_ in cur_sec_lane_polys:
pred_id = cur_sec.get_lane(id_).pred
if pred_id and pred_id in cur_lane_polys:
next_lane_polys[id_] = cur_lane_polys.pop(pred_id) + [
cur_sec_lane_polys[id_]
]
else:
next_lane_polys[id_] = [cur_sec_lane_polys[id_]]
for id_ in cur_lane_polys:
poly = buffer_union(cur_lane_polys[id_], tolerance=tolerance)
lane_polys.append(poly)
self.lane_secs[i - 1].get_lane(id_).parent_lane_poly = poly
cur_lane_polys = next_lane_polys
for id_ in cur_lane_polys:
poly = buffer_union(cur_lane_polys[id_], tolerance=tolerance)
lane_polys.append(poly)
cur_sec.get_lane(id_).parent_lane_poly = poly
union_poly = buffer_union(sec_polys, tolerance=tolerance)
if last_lefts and last_rights:
self.end_bounds_left.update(last_lefts)
self.end_bounds_right.update(last_rights)
# Difference and slightly erode all overlapping polygons
for i in range(len(sec_polys) - 1):
if sec_polys[i].overlaps(sec_polys[i + 1]):
sec_polys[i] = sec_polys[i].difference(sec_polys[i + 1]).buffer(-1e-6)
assert not sec_polys[i].overlaps(sec_polys[i + 1])
for polys in sec_lane_polys:
ids = sorted(polys) # order adjacent lanes consecutively
for i in range(len(ids) - 1):
polyA, polyB = polys[ids[i]], polys[ids[i + 1]]
if polyA.overlaps(polyB):
polys[ids[i]] = polyA.difference(polyB).buffer(-1e-6)
assert not polys[ids[i]].overlaps(polyB)
for i in range(len(lane_polys) - 1):
if lane_polys[i].overlaps(lane_polys[i + 1]):
lane_polys[i] = lane_polys[i].difference(lane_polys[i + 1]).buffer(-1e-6)
assert not lane_polys[i].overlaps(lane_polys[i + 1])
return (sec_points, sec_polys, sec_lane_polys, lane_polys, union_poly)
def calculate_geometry(
self,
num,
tolerance,
calc_gap,
drivable_lane_types,
sidewalk_lane_types,
shoulder_lane_types,
):
# Note: this also calculates self.start_bounds_left, self.start_bounds_right,
# self.end_bounds_left, self.end_bounds_right
(
self.sec_points,
self.sec_polys,
self.sec_lane_polys,
self.lane_polys,
self.drivable_region,
) = self.calc_geometry_for_type(
drivable_lane_types, num, tolerance, calc_gap=calc_gap
)
for i, sec in enumerate(self.lane_secs):
sec.drivable_lanes = {}
sec.sidewalk_lanes = {}
sec.shoulder_lanes = {}
for id_, lane in sec.lanes.items():
ty = lane.type_
if ty in drivable_lane_types:
sec.drivable_lanes[id_] = lane
elif ty in sidewalk_lane_types:
sec.sidewalk_lanes[id_] = lane
elif ty in shoulder_lane_types:
sec.shoulder_lanes[id_] = lane
if not sec.drivable_lanes:
continue
rightmost = None
for id_ in itertools.chain(reversed(sec.right_lane_ids), sec.left_lane_ids):
if id_ in sec.drivable_lanes:
rightmost = sec.lanes[id_]
break
assert rightmost is not None, i
leftmost = None
for id_ in itertools.chain(reversed(sec.left_lane_ids), sec.right_lane_ids):
if id_ in sec.drivable_lanes:
leftmost = sec.lanes[id_]
break
assert leftmost is not None, i
sec.left_edge = leftmost.left_bounds
assert len(sec.left_edge) >= 2
sec.right_edge = rightmost.right_bounds
assert len(sec.right_edge) >= 2
_, _, _, _, self.sidewalk_region = self.calc_geometry_for_type(
sidewalk_lane_types, num, tolerance, calc_gap=calc_gap
)
_, _, _, _, self.shoulder_region = self.calc_geometry_for_type(
shoulder_lane_types, num, tolerance, calc_gap=calc_gap
)
def toScenicRoad(self, tolerance):
assert self.sec_points
allElements = []
# Create lane and road sections
roadSections = []
last_section = None
sidewalkSections = defaultdict(list)
shoulderSections = defaultdict(list)
for sec, pts, sec_poly, lane_polys in zip(
self.lane_secs, self.sec_points, self.sec_polys, self.sec_lane_polys
):
pts = [pt[:2] for pt in pts] # drop s coordinate
assert sec.drivable_lanes
laneSections = {}
for id_, lane in sec.drivable_lanes.items():
succ = None # will set this later
if last_section and lane.pred:
if lane.pred in last_section.lanesByOpenDriveID:
pred = last_section.lanesByOpenDriveID[lane.pred]
else:
warn(
f"road {self.id_} section {len(roadSections)} "
f"lane {id_} has a non-drivable predecessor"
)
pred = None
else:
pred = lane.pred # will correct inter-road links later
left, center, right = lane.left_bounds, lane.centerline, lane.right_bounds
if id_ > 0: # backward lane
left, center, right = right[::-1], center[::-1], left[::-1]
succ, pred = pred, succ
section = roadDomain.LaneSection(
id=f"road{self.id_}_sec{len(roadSections)}_lane{id_}",
polygon=lane_polys[id_],
centerline=PolylineRegion(cleanChain(center)),
leftEdge=PolylineRegion(cleanChain(left)),
rightEdge=PolylineRegion(cleanChain(right)),
successor=succ,
predecessor=pred,
lane=None, # will set these later
group=None,
road=None,
openDriveID=id_,
isForward=id_ < 0,
)
section._original_lane = lane
laneSections[id_] = section
allElements.append(section)
section = roadDomain.RoadSection(
id=f"road{self.id_}_sec{len(roadSections)}",
polygon=sec_poly,
centerline=PolylineRegion(cleanChain(pts)),
leftEdge=PolylineRegion(cleanChain(sec.left_edge)),
rightEdge=PolylineRegion(cleanChain(sec.right_edge)),
successor=None,
predecessor=last_section,
road=None, # will set later
lanesByOpenDriveID=laneSections,
)
roadSections.append(section)
allElements.append(section)
last_section = section
for id_, lane in sec.sidewalk_lanes.items():
sidewalkSections[id_].append(lane)
for id_, lane in sec.shoulder_lanes.items():
shoulderSections[id_].append(lane)
# Build sidewalks and shoulders
# TODO improve this!
forwardSidewalks, backwardSidewalks = [], []
forwardShoulders, backwardShoulders = [], []
for id_ in sidewalkSections:
(forwardSidewalks if id_ < 0 else backwardSidewalks).append(id_)
for id_ in shoulderSections:
(forwardShoulders if id_ < 0 else backwardShoulders).append(id_)
def combineSections(laneIDs, sections, name):
leftmost, rightmost = max(laneIDs), min(laneIDs)
if len(laneIDs) != leftmost - rightmost + 1:
warn(f"ignoring {name} in the middle of road {self.id_}")
leftPoints, rightPoints = [], []
if leftmost < 0:
leftmost = rightmost
while leftmost + 1 in laneIDs:
leftmost = leftmost + 1
leftSecs, rightSecs = sections[leftmost], sections[rightmost]
for leftSec, rightSec in zip(leftSecs, rightSecs):
leftPoints.extend(leftSec.left_bounds)
rightPoints.extend(rightSec.right_bounds)
else:
rightmost = leftmost
while rightmost - 1 in laneIDs:
rightmost = rightmost - 1
leftSecs = reversed(sections[leftmost])
rightSecs = reversed(sections[rightmost])
for leftSec, rightSec in zip(leftSecs, rightSecs):
leftPoints.extend(reversed(rightSec.right_bounds))
rightPoints.extend(reversed(leftSec.left_bounds))
leftEdge = PolylineRegion(cleanChain(leftPoints))
rightEdge = PolylineRegion(cleanChain(rightPoints))
# Heuristically create some kind of reasonable centerline
if len(leftPoints) == len(rightPoints):
centerPoints = list(
averageVectors(l, r) for l, r in zip(leftPoints, rightPoints)
)
else:
num = max(len(leftPoints), len(rightPoints))
centerPoints = []
for d in np.linspace(0, 1, num):
l = leftEdge.lineString.interpolate(d, normalized=True)
r = rightEdge.lineString.interpolate(d, normalized=True)
centerPoints.append(averageVectors(l.coords[0], r.coords[0]))
centerline = PolylineRegion(cleanChain(centerPoints))
allPolys = (
sec.poly
for id_ in range(rightmost, leftmost + 1)
for sec in sections[id_]
)
union = buffer_union(allPolys, tolerance=tolerance)
id_ = f"road{self.id_}_{name}({leftmost},{rightmost})"
return id_, union, centerline, leftEdge, rightEdge
def makeSidewalk(laneIDs):
if not laneIDs:
return None
id_, union, centerline, leftEdge, rightEdge = combineSections(
laneIDs, sidewalkSections, "sidewalk"
)
sidewalk = roadDomain.Sidewalk(
id=id_,
polygon=union,
centerline=centerline,
leftEdge=leftEdge,
rightEdge=rightEdge,
road=None,
crossings=(), # TODO add crosswalks
)
allElements.append(sidewalk)
return sidewalk
forwardSidewalk = makeSidewalk(forwardSidewalks)
backwardSidewalk = makeSidewalk(backwardSidewalks)
def makeShoulder(laneIDs):
if not laneIDs:
return None
id_, union, centerline, leftEdge, rightEdge = combineSections(
laneIDs, shoulderSections, "shoulder"
)
shoulder = roadDomain.Shoulder(
id=id_,
polygon=union,
centerline=centerline,
leftEdge=leftEdge,
rightEdge=rightEdge,
road=None,
)
allElements.append(shoulder)
return shoulder
forwardShoulder = makeShoulder(forwardShoulders)
backwardShoulder = makeShoulder(backwardShoulders)
# Connect sections to their successors
next_section = None
for sec, section in reversed(list(zip(self.lane_secs, roadSections))):
if next_section is None:
next_section = section
for id_, lane in sec.drivable_lanes.items():
newLane = section.lanesByOpenDriveID[id_]
if newLane.isForward:
# will correct inter-road links later
newLane._successor = lane.succ
else:
newLane._predecessor = lane.succ
continue
section._successor = next_section
for id_, lane in sec.drivable_lanes.items():
newLane = section.lanesByOpenDriveID[id_]
if newLane.isForward:
newLane._successor = next_section.lanesByOpenDriveID.get(lane.succ)
else:
newLane._predecessor = next_section.lanesByOpenDriveID.get(lane.succ)
next_section = section
# Connect lane sections to adjacent lane sections
for section in roadSections:
lanes = section.lanesByOpenDriveID
for id_, lane in lanes.items():
if id_ < -1:
leftID = id_ + 1
elif id_ == -1:
leftID = 1
elif id_ == 1:
leftID = -1
else:
leftID = id_ - 1
rightID = id_ - 1 if id_ < 0 else id_ + 1
lane._laneToLeft = lanes.get(leftID)
lane._laneToRight = lanes.get(rightID)
if self.drive_on_right:
lane._fasterLane = lane._laneToLeft
lane._slowerLane = lane._laneToRight
else:
lane._slowerLane = lane._laneToLeft
lane._fasterLane = lane._laneToRight
if lane._fasterLane and lane._fasterLane.isForward != lane.isForward:
lane._fasterLane = None
if lane._slowerLane and lane._slowerLane.isForward != lane.isForward:
lane._slowerLane = None
adj = []
if lane._laneToLeft:
adj.append(lane._laneToLeft)
if lane._laneToRight:
adj.append(lane._laneToRight)
lane.adjacentLanes = tuple(adj)
# Gather lane sections into lanes
nextID = 0
forwardLanes, backwardLanes = [], []
for roadSection in roadSections:
for laneSection in roadSection.lanes:
laneSection._visited = False
for roadSection, sec in zip(roadSections, self.lane_secs):
for laneSection in roadSection.lanes:
if not laneSection._visited: # start of new lane
forward = laneSection.isForward
sections = []
successorLane = None # lane this one will merge into
while True:
sections.append(laneSection)
laneSection._visited = True
assert laneSection.isForward == forward
if forward:
nextSection = laneSection._successor
else:
nextSection = laneSection._predecessor
if not nextSection or not isinstance(
nextSection, roadDomain.LaneSection
):
break
elif nextSection._visited:
successorLane = nextSection.lane
break
laneSection = nextSection
ls = laneSection._original_lane
assert ls.parent_lane_poly
if not forward:
sections = tuple(reversed(sections))
leftPoints, rightPoints, centerPoints = [], [], []
for section in sections:
leftPoints.extend(section.leftEdge.points)
rightPoints.extend(section.rightEdge.points)
centerPoints.extend(section.centerline.points)
leftEdge = PolylineRegion(cleanChain(leftPoints))
rightEdge = PolylineRegion(cleanChain(rightPoints))
centerline = PolylineRegion(cleanChain(centerPoints))
lane = roadDomain.Lane(
id=f"road{self.id_}_lane{nextID}",
polygon=ls.parent_lane_poly,
centerline=centerline,
leftEdge=leftEdge,
rightEdge=rightEdge,
group=None,
road=None,
sections=tuple(sections),
successor=successorLane, # will correct inter-road links later
)
nextID += 1
for section in sections:
section.lane = lane
(forwardLanes if forward else backwardLanes).append(lane)
allElements.append(lane)
lanes = forwardLanes + backwardLanes
assert lanes
# Compute lane adjacencies
for lane in lanes:
adj = []
for section in lane.sections:
adj.extend(sec.lane for sec in section.adjacentLanes)
lane.adjacentLanes = tuple(adj)
# Create lane groups
def getEdges(forward):
if forward:
sec = roadSections[0]
startLanes = sec.forwardLanes
else:
sec = roadSections[-1]
startLanes = sec.backwardLanes
leftPoints = []
current = startLanes[-1] # get leftmost lane of the first section
while current and isinstance(current, roadDomain.LaneSection):
if current._laneToLeft and current._laneToLeft.isForward == forward:
current = current._laneToLeft
leftPoints.extend(current.leftEdge.points)
current = current._successor
leftEdge = PolylineRegion(cleanChain(leftPoints))
rightPoints = []
current = startLanes[0] # get rightmost lane of the first section
while current and isinstance(current, roadDomain.LaneSection):
if current._laneToRight and current._laneToRight.isForward == forward:
current = current._laneToRight
rightPoints.extend(current.rightEdge.points)
current = current._successor
rightEdge = PolylineRegion(cleanChain(rightPoints))
middleLane = startLanes[len(startLanes) // 2].lane # rather arbitrary
return leftEdge, middleLane.centerline, rightEdge
if forwardLanes:
leftEdge, centerline, rightEdge = getEdges(forward=True)
forwardGroup = roadDomain.LaneGroup(
id=f"road{self.id_}_forward",
polygon=buffer_union(
(lane.polygon for lane in forwardLanes), tolerance=tolerance
),
centerline=centerline,
leftEdge=leftEdge,
rightEdge=rightEdge,
road=None,
lanes=tuple(forwardLanes),
curb=(forwardShoulder.rightEdge if forwardShoulder else rightEdge),
sidewalk=forwardSidewalk,
bikeLane=None,
shoulder=forwardShoulder,
opposite=None,
)
allElements.append(forwardGroup)
else:
forwardGroup = None
if backwardLanes: