-
Notifications
You must be signed in to change notification settings - Fork 0
/
automatic_control_custom.py
222 lines (179 loc) · 6.65 KB
/
automatic_control_custom.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
import argparse
import logging
import random
import carla
import pygame
import time
from examples.manual_control import World, KeyboardControl, HUD, CollisionSensor, LaneInvasionSensor, GnssSensor, IMUSensor, CameraManager
from agents.navigation.behavior_agent import BehaviorAgent
from agents.navigation.basic_agent import BasicAgent
def get_actor_display_name(actor, truncate=250):
name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])
return (name[:truncate - 1] + u'\u2026') if len(name) > truncate else name
class WorldSR(World):
restarted = False
def restart(self):
if self.restarted:
return
self.restarted = True
self.player_max_speed = 1.589
self.player_max_speed_fast = 3.713
# Keep same camera config if the camera manager exists.
cam_index = self.camera_manager.index if self.camera_manager is not None else 0
cam_pos_index = self.camera_manager.transform_index if self.camera_manager is not None else 0
# Get the ego vehicle
while self.player is None:
print("Waiting for the ego vehicle...")
time.sleep(1)
possible_vehicles = self.world.get_actors().filter('vehicle.*')
for vehicle in possible_vehicles:
if vehicle.attributes['role_name'] == self.actor_role_name:
print("Ego vehicle found")
self.player = vehicle
break
self.player_name = self.player.type_id
# Set up the sensors.
self.collision_sensor = CollisionSensor(self.player, self.hud)
self.lane_invasion_sensor = LaneInvasionSensor(self.player, self.hud)
self.gnss_sensor = GnssSensor(self.player)
self.imu_sensor = IMUSensor(self.player)
self.camera_manager = CameraManager(self.player, self.hud, self._gamma)
self.camera_manager.transform_index = cam_pos_index
self.camera_manager.set_sensor(cam_index, notify=False)
actor_type = get_actor_display_name(self.player)
self.hud.notification(actor_type)
if self.sync:
print("Is sync")
self.world.tick()
else:
print("Is not sync")
self.world.wait_for_tick()
def tick(self, clock):
if len(self.world.get_actors().filter(self.player_name)) < 1:
return False
self.hud.tick(self, clock)
return True
def game_loop(args):
"""
Main loop of the simulation. It handles updating all the HUD information,
ticking the agent and, if needed, the world.
"""
pygame.init()
pygame.font.init()
world = None
try:
if args.seed:
random.seed(args.seed)
client = carla.Client(args.host, args.port)
client.set_timeout(4.0)
traffic_manager = client.get_trafficmanager()
hud = HUD(args.width, args.height)
world = WorldSR(client.get_world(), hud, args)
display = pygame.display.set_mode(
(args.width, args.height),
pygame.HWSURFACE | pygame.DOUBLEBUF)
# if args.agent == "Basic":
agent = BasicAgent(world.player, target_speed=50)
# else:
# print("Creating a behavior agent")
agent = BehaviorAgent(world.player, behavior="aggressive")
# Set the agent destination
spawn_points = world.map.get_spawn_points()
destination = spawn_points[0].location
agent.set_destination(destination)
# clock = pygame.time.Clock()
# world.player.set_autopilot(True)
while True:
# clock.tick_busy_loop(60)
if not world.tick(clock):
return
world.render(display)
pygame.display.flip()
control = agent.run_step()
world.player.apply_control(control)
finally:
if world and world.recording_enabled:
client.stop_recorder()
if world is not None:
world.destroy()
pygame.quit()
def main():
argparser = argparse.ArgumentParser(
description='CARLA Automatic Control Client')
argparser.add_argument(
'-v', '--verbose',
action='store_true',
dest='debug',
help='Print debug information')
argparser.add_argument(
'--host',
metavar='H',
default='127.0.0.1',
help='IP of the host server (default: 127.0.0.1)')
argparser.add_argument(
'-p', '--port',
metavar='P',
default=2000,
type=int,
help='TCP port to listen to (default: 2000)')
argparser.add_argument(
'--res',
metavar='WIDTHxHEIGHT',
default='1280x720',
help='Window resolution (default: 1280x720)')
argparser.add_argument(
'--sync',
action='store_true',
help='Synchronous mode execution')
argparser.add_argument(
'--filter',
metavar='PATTERN',
default='vehicle.*',
help='Actor filter (default: "vehicle.*")')
argparser.add_argument(
'-l', '--loop',
action='store_true',
dest='loop',
help='Sets a new random destination upon reaching the previous one (default: False)')
argparser.add_argument(
"-a", "--agent", type=str,
choices=["Behavior", "Basic"],
help="select which agent to run",
default="Behavior")
argparser.add_argument(
'-b', '--behavior', type=str,
choices=["cautious", "normal", "aggressive"],
help='Choose one of the possible agent behaviors (default: normal) ',
default='normal')
argparser.add_argument(
'-s', '--seed',
help='Set seed for repeating executions (default: None)',
default=None,
type=int)
argparser.add_argument(
'--rolename',
metavar='NAME',
default='hero',
help='role name of ego vehicle to control (default: "hero")')
argparser.add_argument(
'--generation',
metavar='G',
default='2',
help='restrict to certain actor generation (values: "1","2","All" - default: "2")')
argparser.add_argument(
'--gamma',
default=2.2,
type=float,
help='Gamma correction of the camera (default: 2.2)')
args = argparser.parse_args()
args.width, args.height = [int(x) for x in args.res.split('x')]
log_level = logging.DEBUG if args.debug else logging.INFO
logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)
logging.info('listening to server %s:%s', args.host, args.port)
print(__doc__)
try:
game_loop(args)
except KeyboardInterrupt:
print('\nCancelled by user. Bye!')
if __name__ == '__main__':
main()