-
Notifications
You must be signed in to change notification settings - Fork 377
/
Copy pathatomic_behaviors.py
2881 lines (2248 loc) · 109 KB
/
atomic_behaviors.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
#!/usr/bin/env python
# Copyright (c) 2018-2020 Intel Corporation
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
This module provides all atomic scenario behaviors required to realize
complex, realistic scenarios such as "follow a leading vehicle", "lane change",
etc.
The atomic behaviors are implemented with py_trees.
"""
from __future__ import print_function
import copy
import math
import operator
import os
import random
import time
import subprocess
import numpy as np
import py_trees
from py_trees.blackboard import Blackboard
import networkx
import carla
from agents.navigation.basic_agent import BasicAgent, LocalPlanner
from agents.navigation.local_planner import RoadOption
from agents.navigation.global_route_planner import GlobalRoutePlanner
from agents.navigation.global_route_planner_dao import GlobalRoutePlannerDAO
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
from srunner.scenariomanager.actorcontrols.actor_control import ActorControl
from srunner.scenariomanager.timer import GameTime
from srunner.tools.scenario_helper import detect_lane_obstacle
from srunner.tools.scenario_helper import generate_target_waypoint_list_multilane
import srunner.tools
EPSILON = 0.001
def calculate_distance(location, other_location, global_planner=None):
"""
Method to calculate the distance between to locations
Note: It uses the direct distance between the current location and the
target location to estimate the time to arrival.
To be accurate, it would have to use the distance along the
(shortest) route between the two locations.
"""
if global_planner:
distance = 0
# Get the route
route = global_planner.trace_route(location, other_location)
# Get the distance of the route
for i in range(1, len(route)):
curr_loc = route[i][0].transform.location
prev_loc = route[i - 1][0].transform.location
distance += curr_loc.distance(prev_loc)
return distance
return location.distance(other_location)
def get_actor_control(actor):
"""
Method to return the type of control to the actor.
"""
control = actor.get_control()
actor_type = actor.type_id.split('.')[0]
if not isinstance(actor, carla.Walker):
control.steering = 0
else:
control.speed = 0
return control, actor_type
class AtomicBehavior(py_trees.behaviour.Behaviour):
"""
Base class for all atomic behaviors used to setup a scenario
*All behaviors should use this class as parent*
Important parameters:
- name: Name of the atomic behavior
"""
def __init__(self, name, actor=None):
"""
Default init. Has to be called via super from derived class
"""
super(AtomicBehavior, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self.name = name
self._actor = actor
def setup(self, unused_timeout=15):
"""
Default setup
"""
self.logger.debug("%s.setup()" % (self.__class__.__name__))
return True
def initialise(self):
"""
Initialise setup terminates WaypointFollowers
Check whether WF for this actor is running and terminate all active WFs
"""
if self._actor is not None:
try:
check_attr = operator.attrgetter("running_WF_actor_{}".format(self._actor.id))
terminate_wf = copy.copy(check_attr(py_trees.blackboard.Blackboard()))
py_trees.blackboard.Blackboard().set(
"terminate_WF_actor_{}".format(self._actor.id), terminate_wf, overwrite=True)
except AttributeError:
# It is ok to continue, if the Blackboard variable does not exist
pass
self.logger.debug("%s.initialise()" % (self.__class__.__name__))
def terminate(self, new_status):
"""
Default terminate. Can be extended in derived class
"""
self.logger.debug("%s.terminate()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
class RunScript(AtomicBehavior):
"""
This is an atomic behavior to start execution of an additional script.
Args:
script (str): String containing the interpreter, scriptpath and arguments
Example: "python /path/to/script.py --arg1"
base_path (str): String containing the base path of for the script
Attributes:
_script (str): String containing the interpreter, scriptpath and arguments
Example: "python /path/to/script.py --arg1"
_base_path (str): String containing the base path of for the script
Example: "/path/to/"
Note:
This is intended for the use with OpenSCENARIO. Be aware of security side effects.
"""
def __init__(self, script, base_path=None, name="RunScript"):
"""
Setup parameters
"""
super(RunScript, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._script = script
self._base_path = base_path
def update(self):
"""
Start script
"""
path = None
script_components = self._script.split(' ')
if len(script_components) > 1:
path = script_components[1]
if not os.path.isfile(path):
path = os.path.join(self._base_path, path)
if not os.path.isfile(path):
new_status = py_trees.common.Status.FAILURE
print("Script file does not exists {}".format(path))
else:
subprocess.Popen(self._script, shell=True, cwd=self._base_path)
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class ChangeWeather(AtomicBehavior):
"""
Atomic to write a new weather configuration into the blackboard.
Used in combination with WeatherBehavior() to have a continuous weather simulation.
The behavior immediately terminates with SUCCESS after updating the blackboard.
Args:
weather (srunner.scenariomanager.weather_sim.Weather): New weather settings.
name (string): Name of the behavior.
Defaults to 'UpdateWeather'.
Attributes:
_weather (srunner.scenariomanager.weather_sim.Weather): Weather settings.
"""
def __init__(self, weather, name="ChangeWeather"):
"""
Setup parameters
"""
super(ChangeWeather, self).__init__(name)
self._weather = weather
def update(self):
"""
Write weather into blackboard and exit with success
returns:
py_trees.common.Status.SUCCESS
"""
py_trees.blackboard.Blackboard().set("CarlaWeather", self._weather, overwrite=True)
return py_trees.common.Status.SUCCESS
class ChangeRoadFriction(AtomicBehavior):
"""
Atomic to update the road friction in CARLA.
The behavior immediately terminates with SUCCESS after updating the friction.
Args:
friction (float): New friction coefficient.
name (string): Name of the behavior.
Defaults to 'UpdateRoadFriction'.
Attributes:
_friction (float): Friction coefficient.
"""
def __init__(self, friction, name="ChangeRoadFriction"):
"""
Setup parameters
"""
super(ChangeRoadFriction, self).__init__(name)
self._friction = friction
def update(self):
"""
Update road friction. Spawns new friction blueprint and removes the old one, if existing.
returns:
py_trees.common.Status.SUCCESS
"""
for actor in CarlaDataProvider.get_world().get_actors().filter('static.trigger.friction'):
actor.destroy()
friction_bp = CarlaDataProvider.get_world().get_blueprint_library().find('static.trigger.friction')
extent = carla.Location(1000000.0, 1000000.0, 1000000.0)
friction_bp.set_attribute('friction', str(self._friction))
friction_bp.set_attribute('extent_x', str(extent.x))
friction_bp.set_attribute('extent_y', str(extent.y))
friction_bp.set_attribute('extent_z', str(extent.z))
# Spawn Trigger Friction
transform = carla.Transform()
transform.location = carla.Location(-10000.0, -10000.0, 0.0)
CarlaDataProvider.get_world().spawn_actor(friction_bp, transform)
return py_trees.common.Status.SUCCESS
class ChangeActorControl(AtomicBehavior):
"""
Atomic to change the longitudinal/lateral control logic for an actor.
The (actor, controller) pair is stored inside the Blackboard.
The behavior immediately terminates with SUCCESS after the controller was changed.
Args:
actor (carla.Actor): Actor that should be controlled by the controller.
control_py_module (string): Name of the python module containing the implementation
of the controller.
args (dictionary): Additional arguments for the controller.
scenario_file_path (string): Additional path to controller implementation.
name (string): Name of the behavior.
Defaults to 'ChangeActorControl'.
Attributes:
_actor_control (ActorControl): Instance of the actor control.
"""
def __init__(self, actor, control_py_module, args, scenario_file_path=None, name="ChangeActorControl"):
"""
Setup actor controller.
"""
super(ChangeActorControl, self).__init__(name, actor)
self._actor_control = ActorControl(actor, control_py_module=control_py_module,
args=args, scenario_file_path=scenario_file_path)
def update(self):
"""
Write (actor, controler) pair to Blackboard, or update the controller
if actor already exists as a key.
returns:
py_trees.common.Status.SUCCESS
"""
actor_dict = {}
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if actor_dict:
if self._actor.id in actor_dict:
actor_dict[self._actor.id].reset()
actor_dict[self._actor.id] = self._actor_control
py_trees.blackboard.Blackboard().set("ActorsWithController", actor_dict, overwrite=True)
return py_trees.common.Status.SUCCESS
class DeActivateActorControlComponents(AtomicBehavior):
"""
Atomic to enable/disable the longitudinal/lateral control component of an actor controller.
The (actor, controller) pair is retrieved from the Blackboard.
The behavior immediately terminates with SUCCESS.
Args:
actor (carla.Actor): Actor that should be controlled by the controller.
control_py_module (string): Name of the python module containing the implementation
of the controller.
args (dictionary): Additional arguments for the controller.
scenario_file_path (string): Additional path to controller implementation.
name (string): Name of the behavior.
Defaults to 'ChangeActorControl'.
Attributes:
_actor_control (ActorControl): Instance of the actor control.
"""
def __init__(self, actor, lon_control=None, lat_control=None, name="ChangeActorControl"):
"""
Setup actor controller.
"""
super(DeActivateActorControlComponents, self).__init__(name, actor)
self._lon_control = lon_control
self._lat_control = lat_control
def update(self):
"""
Write (actor, controler) pair to Blackboard, or update the controller
if actor already exists as a key.
returns:
py_trees.common.Status.SUCCESS
"""
actor_dict = {}
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if self._actor.id in actor_dict:
if self._lon_control is not None:
actor_dict[self._actor.id].change_lon_control(self._lon_control)
if self._lat_control is not None:
actor_dict[self._actor.id].change_lat_control(self._lat_control)
else:
return py_trees.common.Status.FAILURE
return py_trees.common.Status.SUCCESS
class UpdateAllActorControls(AtomicBehavior):
"""
Atomic to update (run one control loop step) all actor controls.
The behavior is always in RUNNING state.
Args:
name (string): Name of the behavior.
Defaults to 'UpdateAllActorControls'.
"""
def __init__(self, name="UpdateAllActorControls"):
"""
Constructor
"""
super(UpdateAllActorControls, self).__init__(name)
def update(self):
"""
Execute one control loop step for all actor controls.
returns:
py_trees.common.Status.RUNNING
"""
actor_dict = {}
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
for actor_id in actor_dict:
actor_dict[actor_id].run_step()
return py_trees.common.Status.RUNNING
class ChangeActorTargetSpeed(AtomicBehavior):
"""
Atomic to change the target speed for an actor controller.
The behavior is in RUNNING state until the distance/duration
conditions are satisfied, or if a second ChangeActorTargetSpeed atomic
for the same actor is triggered.
Args:
actor (carla.Actor): Controlled actor.
target_speed (float): New target speed [m/s].
init_speed (boolean): Flag to indicate if the speed is the initial actor speed.
Defaults to False.
duration (float): Duration of the maneuver [s].
Defaults to None.
distance (float): Distance of the maneuver [m].
Defaults to None.
relative_actor (carla.Actor): If the target speed setting should be relative to another actor.
Defaults to None.
value (float): Offset, if the target speed setting should be relative to another actor.
Defaults to None.
value_type (string): Either 'Delta' or 'Factor' influencing how the offset to the reference actors
velocity is applied. Defaults to None.
continuous (boolean): If True, the atomic remains in RUNNING, independent of duration or distance.
Defaults to False.
name (string): Name of the behavior.
Defaults to 'ChangeActorTargetSpeed'.
Attributes:
_target_speed (float): New target speed [m/s].
_init_speed (boolean): Flag to indicate if the speed is the initial actor speed.
Defaults to False.
_start_time (float): Start time of the atomic [s].
Defaults to None.
_start_location (carla.Location): Start location of the atomic.
Defaults to None.
_duration (float): Duration of the maneuver [s].
Defaults to None.
_distance (float): Distance of the maneuver [m].
Defaults to None.
_relative_actor (carla.Actor): If the target speed setting should be relative to another actor.
Defaults to None.
_value (float): Offset, if the target speed setting should be relative to another actor.
Defaults to None.
_value_type (string): Either 'Delta' or 'Factor' influencing how the offset to the reference actors
velocity is applied. Defaults to None.
_continuous (boolean): If True, the atomic remains in RUNNING, independent of duration or distance.
Defaults to False.
"""
def __init__(self, actor, target_speed, init_speed=False,
duration=None, distance=None, relative_actor=None,
value=None, value_type=None, continuous=False, name="ChangeActorTargetSpeed"):
"""
Setup parameters
"""
super(ChangeActorTargetSpeed, self).__init__(name, actor)
self._target_speed = target_speed
self._init_speed = init_speed
self._start_time = None
self._start_location = None
self._relative_actor = relative_actor
self._value = value
self._value_type = value_type
self._continuous = continuous
self._duration = duration
self._distance = distance
def initialise(self):
"""
Set initial parameters such as _start_time and _start_location,
and get (actor, controller) pair from Blackboard.
May throw if actor is not available as key for the ActorsWithController
dictionary from Blackboard.
"""
actor_dict = {}
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if not actor_dict or not self._actor.id in actor_dict:
raise RuntimeError("Actor not found in ActorsWithController BlackBoard")
self._start_time = GameTime.get_time()
self._start_location = CarlaDataProvider.get_location(self._actor)
if self._relative_actor:
relative_velocity = CarlaDataProvider.get_velocity(self._relative_actor)
# get target velocity
if self._value_type == 'delta':
self._target_speed = relative_velocity + self._value
elif self._value_type == 'factor':
self._target_speed = relative_velocity * self._value
else:
print('self._value_type must be delta or factor')
actor_dict[self._actor.id].update_target_speed(self._target_speed, start_time=self._start_time)
if self._init_speed:
actor_dict[self._actor.id].set_init_speed()
super(ChangeActorTargetSpeed, self).initialise()
def update(self):
"""
Check the actor's current state and update target speed, if it is relative to another actor.
returns:
py_trees.common.Status.SUCCESS, if the duration or distance driven exceeded limits
if another ChangeActorTargetSpeed atomic for the same actor was triggered.
py_trees.common.Status.FAILURE, if the actor is not found in ActorsWithController Blackboard dictionary.
py_trees.common.Status.FAILURE, else.
"""
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if not actor_dict or not self._actor.id in actor_dict:
return py_trees.common.Status.FAILURE
if actor_dict[self._actor.id].get_last_longitudinal_command() != self._start_time:
return py_trees.common.Status.SUCCESS
new_status = py_trees.common.Status.RUNNING
if self._relative_actor:
relative_velocity = CarlaDataProvider.get_velocity(self._relative_actor)
# get target velocity
if self._value_type == 'delta':
actor_dict[self._actor.id].update_target_speed(relative_velocity + self._value)
elif self._value_type == 'factor':
actor_dict[self._actor.id].update_target_speed(relative_velocity * self._value)
else:
print('self._value_type must be delta or factor')
# check duration and driven_distance
if not self._continuous:
if (self._duration is not None) and (GameTime.get_time() - self._start_time > self._duration):
new_status = py_trees.common.Status.SUCCESS
driven_distance = CarlaDataProvider.get_location(self._actor).distance(self._start_location)
if (self._distance is not None) and (driven_distance > self._distance):
new_status = py_trees.common.Status.SUCCESS
if self._distance is None and self._duration is None:
new_status = py_trees.common.Status.SUCCESS
return new_status
class SyncArrivalOSC(AtomicBehavior):
"""
Atomic to make two actors arrive at their corresponding places at the same time
The behavior is in RUNNING state until the "main" actor has rezached its destination
Args:
actor (carla.Actor): Controlled actor.
master_actor (carla.Actor): Reference actor to sync up to.
actor_target (carla.Transform): Endpoint of the actor after the behavior finishes.
master_target (carla.Transform): Endpoint of the master_actor after the behavior finishes.
final_speed (float): Speed of the actor after the behavior ends.
relative_to_master (boolean): Whether or not the final speed is relative to master_actor.
Defaults to False.
relative_type (string): Type of relative speed. Either 'delta' or 'factor'.
Defaults to ''.
name (string): Name of the behavior.
Defaults to 'SyncArrivalOSC'.
"""
DISTANCE_THRESHOLD = 1
def __init__(self, actor, master_actor, actor_target, master_target, final_speed,
relative_to_master=False, relative_type='', name="SyncArrivalOSC"):
"""
Setup required parameters
"""
super(SyncArrivalOSC, self).__init__(name, actor)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._actor = actor
self._actor_target = actor_target
self._master_actor = master_actor
self._master_target = master_target
self._final_speed = final_speed
self._final_speed_set = False
self._relative_to_master = relative_to_master
self._relative_type = relative_type
self._start_time = None
def initialise(self):
"""
Set initial parameters and get (actor, controller) pair from Blackboard.
May throw if actor is not available as key for the ActorsWithController
dictionary from Blackboard.
"""
actor_dict = {}
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if not actor_dict or not self._actor.id in actor_dict:
raise RuntimeError("Actor not found in ActorsWithController BlackBoard")
self._start_time = GameTime.get_time()
# Get the distance of the actor to its endpoint
distance = calculate_distance(
CarlaDataProvider.get_location(self._actor), self._actor_target.location)
# Get the time to arrival of the reference to its endpoint
distance_reference = calculate_distance(
CarlaDataProvider.get_location(self._master_actor), self._master_target.location)
velocity_reference = CarlaDataProvider.get_velocity(self._master_actor)
if velocity_reference > 0:
time_reference = distance_reference / velocity_reference
else:
time_reference = float('inf')
# Get the required velocity of the actor
desired_velocity = distance / time_reference
actor_dict[self._actor.id].update_target_speed(desired_velocity, start_time=self._start_time)
def update(self):
"""
Dynamic control update for actor velocity to ensure that both actors reach their target
positions at the same time.
"""
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if not actor_dict or not self._actor.id in actor_dict:
return py_trees.common.Status.FAILURE
if actor_dict[self._actor.id].get_last_longitudinal_command() != self._start_time:
return py_trees.common.Status.SUCCESS
new_status = py_trees.common.Status.RUNNING
# Get the distance of the actor to its endpoint
distance = calculate_distance(
CarlaDataProvider.get_location(self._actor), self._actor_target.location)
if distance < self.DISTANCE_THRESHOLD:
return py_trees.common.Status.SUCCESS # Behaviour ends when the actor reaches its endpoint
# Get the time to arrival of the reference to its endpoint
distance_reference = calculate_distance(
CarlaDataProvider.get_location(self._master_actor), self._master_target.location)
velocity_reference = CarlaDataProvider.get_velocity(self._master_actor)
if velocity_reference > 0:
time_reference = distance_reference / velocity_reference
else:
time_reference = float('inf')
# Get the required velocity of the actor
desired_velocity = distance / time_reference
actor_dict[self._actor.id].update_target_speed(desired_velocity)
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
def terminate(self, new_status):
"""
On termination of this behavior, set the target speed to its desired one.
This function is called several times, so the use of self._final_speed_set
is needed to avoid interfering with other running behaviors
"""
if not self._final_speed_set:
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if actor_dict and self._actor.id in actor_dict:
if self._relative_to_master:
master_speed = CarlaDataProvider.get_velocity(self._master_actor)
if self._relative_type == 'delta':
final_speed = master_speed + self._final_speed
elif self._relative_type == 'factor':
final_speed = master_speed * self._final_speed
else:
print("'relative_type' must be delta or factor")
else:
final_speed = self._final_speed
actor_dict[self._actor.id].update_target_speed(final_speed)
self._final_speed_set = True
super(SyncArrivalOSC, self).terminate(new_status)
class ChangeActorWaypoints(AtomicBehavior):
"""
Atomic to change the waypoints for an actor controller.
The behavior is in RUNNING state until the last waypoint is reached, or if a
second waypoint related atomic for the same actor is triggered. These are:
- ChangeActorWaypoints
- ChangeActorLateralMotion
- ChangeActorLaneOffset
Args:
actor (carla.Actor): Controlled actor.
waypoints (List of (OSC position, OSC route option)): List of (Position, Route Option) as OpenScenario elements.
position will be converted to Carla transforms, considering the corresponding
route option (e.g. shortest, fastest)
name (string): Name of the behavior.
Defaults to 'ChangeActorWaypoints'.
Attributes:
_waypoints (List of (OSC position, OSC route option)): List of (Position, Route Option) as OpenScenario elements
_start_time (float): Start time of the atomic [s].
Defaults to None.
'''Note: When using routing options such as fastest or shortest, it is advisable to run
in synchronous mode
"""
def __init__(self, actor, waypoints, name="ChangeActorWaypoints"):
"""
Setup parameters
"""
super(ChangeActorWaypoints, self).__init__(name, actor)
self._waypoints = waypoints
self._start_time = None
def initialise(self):
"""
Set _start_time and get (actor, controller) pair from Blackboard.
Set waypoint list for actor controller.
May throw if actor is not available as key for the ActorsWithController
dictionary from Blackboard.
"""
actor_dict = {}
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if not actor_dict or not self._actor.id in actor_dict:
raise RuntimeError("Actor not found in ActorsWithController BlackBoard")
self._start_time = GameTime.get_time()
# Transforming OSC waypoints to Carla waypoints
carla_route_elements = []
for (osc_point, routing_option) in self._waypoints:
carla_transforms = srunner.tools.openscenario_parser.OpenScenarioParser.convert_position_to_transform(
osc_point)
carla_route_elements.append((carla_transforms, routing_option))
# Obtain final route, considering the routing option
# At the moment everything besides "shortest" will use the CARLA GlobalPlanner
dao = GlobalRoutePlannerDAO(CarlaDataProvider.get_world().get_map(), 2.0)
grp = GlobalRoutePlanner(dao)
grp.setup()
route = []
for i, _ in enumerate(carla_route_elements):
if carla_route_elements[i][1] == "shortest":
route.append(carla_route_elements[i][0])
else:
if i == 0:
mmap = CarlaDataProvider.get_map()
ego_location = CarlaDataProvider.get_location(self._actor)
ego_waypoint = mmap.get_waypoint(ego_location)
try:
ego_next_wp = ego_waypoint.next(1)[0]
except IndexError:
ego_next_wp = ego_waypoint
waypoint = ego_next_wp.transform.location
else:
waypoint = carla_route_elements[i - 1][0].location
waypoint_next = carla_route_elements[i][0].location
try:
interpolated_trace = grp.trace_route(waypoint, waypoint_next)
except networkx.NetworkXNoPath:
print("WARNING: No route from {} to {} - Using direct path instead".format(waypoint, waypoint_next))
route.append(carla_route_elements[i][0])
continue
for wp_tuple in interpolated_trace:
# The router sometimes produces points that go backward, or are almost identical
# We have to filter these, to avoid problems
if route and wp_tuple[0].transform.location.distance(route[-1].location) > 1.0:
new_heading_vec = wp_tuple[0].transform.location - route[-1].location
new_heading = np.arctan2(new_heading_vec.y, new_heading_vec.x)
if len(route) > 1:
last_heading_vec = route[-1].location - route[-2].location
else:
last_heading_vec = route[-1].location - ego_next_wp.transform.location
last_heading = np.arctan2(last_heading_vec.y, last_heading_vec.x)
heading_delta = math.fabs(new_heading - last_heading)
if math.fabs(heading_delta) < 0.5 or math.fabs(heading_delta) > 5.5:
route.append(wp_tuple[0].transform)
elif not route:
route.append(wp_tuple[0].transform)
actor_dict[self._actor.id].update_waypoints(route, start_time=self._start_time)
super(ChangeActorWaypoints, self).initialise()
def update(self):
"""
Check the actor's state along the waypoint route.
returns:
py_trees.common.Status.SUCCESS, if the final waypoint was reached, or
if another ChangeActorWaypoints atomic for the same actor was triggered.
py_trees.common.Status.FAILURE, if the actor is not found in ActorsWithController Blackboard dictionary.
py_trees.common.Status.FAILURE, else.
"""
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if not actor_dict or not self._actor.id in actor_dict:
return py_trees.common.Status.FAILURE
if actor_dict[self._actor.id].get_last_waypoint_command() != self._start_time:
return py_trees.common.Status.SUCCESS
new_status = py_trees.common.Status.RUNNING
if actor_dict[self._actor.id].check_reached_waypoint_goal():
new_status = py_trees.common.Status.SUCCESS
return new_status
class ChangeActorLateralMotion(AtomicBehavior):
"""
Atomic to change the waypoints for an actor controller.
The behavior is in RUNNING state until the last waypoint is reached, or if a
second waypoint related atomic for the same actor is triggered. These are:
- ChangeActorWaypoints
- ChangeActorLateralMotion
- ChangeActorLaneOffset
If an impossible lane change is asked for (due to the lack of lateral lanes,
next waypoints, continuous line, etc) the atomic will return a plan with the
waypoints until such impossibility is found.
Args:
actor (carla.Actor): Controlled actor.
direction (string): Lane change direction ('left' or 'right').
Defaults to 'left'.
distance_lane_change (float): Distance of the lance change [meters].
Defaults to 25.
distance_other_lane (float): Driven distance after the lange change [meters].
Defaults to 100.
name (string): Name of the behavior.
Defaults to 'ChangeActorLateralMotion'.
Attributes:
_waypoints (List of carla.Transform): List of waypoints representing the lane change (CARLA transforms).
_direction (string): Lane change direction ('left' or 'right').
_distance_same_lane (float): Distance on the same lane before the lane change starts [meters]
Constant to 5.
_distance_other_lane (float): Max. distance on the target lane after the lance change [meters]
Constant to 100.
_distance_lane_change (float): Max. total distance of the lane change [meters].
_pos_before_lane_change: carla.Location of the actor before the lane change.
Defaults to None.
_target_lane_id (int): Id of the target lane
Defaults to None.
_start_time (float): Start time of the atomic [s].
Defaults to None.
"""
def __init__(self, actor, direction='left', distance_lane_change=25, distance_other_lane=100,
lane_changes=1, name="ChangeActorLateralMotion"):
"""
Setup parameters
"""
super(ChangeActorLateralMotion, self).__init__(name, actor)
self._waypoints = []
self._direction = direction
self._distance_same_lane = 5
self._distance_other_lane = distance_other_lane
self._distance_lane_change = distance_lane_change
self._lane_changes = lane_changes
self._pos_before_lane_change = None
self._target_lane_id = None
self._plan = None
self._start_time = None
def initialise(self):
"""
Set _start_time and get (actor, controller) pair from Blackboard.
Generate a waypoint list (route) which representes the lane change. Set
this waypoint list for the actor controller.
May throw if actor is not available as key for the ActorsWithController
dictionary from Blackboard.
"""
actor_dict = {}
try:
check_actors = operator.attrgetter("ActorsWithController")
actor_dict = check_actors(py_trees.blackboard.Blackboard())
except AttributeError:
pass
if not actor_dict or not self._actor.id in actor_dict:
raise RuntimeError("Actor not found in ActorsWithController BlackBoard")
self._start_time = GameTime.get_time()
# get start position
position_actor = CarlaDataProvider.get_map().get_waypoint(CarlaDataProvider.get_location(self._actor))
# calculate plan with scenario_helper function
self._plan, self._target_lane_id = generate_target_waypoint_list_multilane(
position_actor, self._direction, self._distance_same_lane,
self._distance_other_lane, self._distance_lane_change, check=False, lane_changes=self._lane_changes)
if self._plan:
for elem in self._plan:
self._waypoints.append(elem[0].transform)
actor_dict[self._actor.id].update_waypoints(self._waypoints, start_time=self._start_time)
super(ChangeActorLateralMotion, self).initialise()
def update(self):
"""
Check the actor's current state and if the lane change was completed
returns: