카를라를 실행하고난 후에 TM을 초기화하고 도시 곳곳에 무작위로 분산된 트래픽을 생성합니다.
cd /opt/carla-simulator
./CarlaUE4.sh
import carla
import random
# Connect to the client and retrieve the world object
client = carla.Client('localhost', 2000)
world = client.get_world()
# Set up the simulator in synchronous mode
settings = world.get_settings()
settings.synchronous_mode = True # Enables synchronous mode
settings.fixed_delta_seconds = None
world.apply_settings(settings)
# Set up the TM in synchronous mode
traffic_manager = client.get_trafficmanager()
traffic_manager.set_synchronous_mode(True)
# Set a seed so behaviour can be repeated if necessary
traffic_manager.set_random_device_seed(0)
random.seed(0)
# We will aslo set up the spectator so we can see what we do
spectator = world.get_spectator()
그러나 위의 코드에서 오류가 발생하는 경우가 있습니다.
settings.synchronous_mode에서 발생하는 오류로 보입니다.
시뮬레이션과 현실의 시간을동기화 하는 과정이라고 합니다.
settings.synchronous_mode를 우선 주석처리하고 진행합니다. 이에 대한 문제는 후에 나타납니다.
import carla
import random
# Connect to the client and retrieve the world object
client = carla.Client('localhost', 2000)
world = client.get_world()
# Set up the simulator in synchronous mode
settings = world.get_settings()
#settings.synchronous_mode = True # Enables synchronous mode
settings.fixed_delta_seconds = None
world.apply_settings(settings)
# Set up the TM in synchronous mode
traffic_manager = client.get_trafficmanager()
traffic_manager.set_synchronous_mode(True)
# Set a seed so behaviour can be repeated if necessary
traffic_manager.set_random_device_seed(0)
random.seed(0)
# We will aslo set up the spectator so we can see what we do
spectator = world.get_spectator()
차량을 고루고루 분산시키기 위해서 산란할 지점이 미리 지정된 산란지점을 사용합니다.
spawn_points = world.get_map().get_spawn_points()
혹은 산란지점을 직접 선택하기위해 다음의 방법을 사용할 수 있습니다.
# Draw the spawn point locations as numbers in the map
for i, spawn_point in enumerate(spawn_points):
world.debug.draw_string(spawn_point.location, str(i), life_time=10)
# In synchronous mode, we need to run the simulation to fly the spectator
while True:
world.tick()
이제 차량을 스폰해봅시다.
# Select some models from the blueprint library
models = ['dodge', 'audi', 'model3', 'mini', 'mustang', 'lincoln', 'prius', 'nissan', 'crown', 'impala']
blueprints = []
for vehicle in world.get_blueprint_library().filter('*vehicle*'):
if any(model in vehicle.id for model in models):
blueprints.append(vehicle)
# Set a max number of vehicles and prepare a list for those we spawn
max_vehicles = 50
max_vehicles = min([max_vehicles, len(spawn_points)])
vehicles = []
# Take a random sample of the spawn points and spawn some vehicles
for i, spawn_point in enumerate(random.sample(spawn_points, max_vehicles)):
temp = world.try_spawn_actor(random.choice(blueprints), spawn_point)
if temp is not None:
vehicles.append(temp)
# Run the simulation so we can inspect the results with the spectator
while True:
world.tick()
그러면 이제 도로에 차량이 스폰되었으며, 아직 차량이 움직이거나 하지 않을 것입니다.
이제 트레픽을 직접제어해봅시다. 다음의 예제는 신호위반을 하도록 명령을 내립니다.
# Parse the list of spawned vehicles and give control to the TM through set_autopilot()
for vehicle in vehicles:
vehicle.set_autopilot(True)
# Randomly set the probability that a vehicle will ignore traffic lights
traffic_manager.ignore_lights_percentage(vehicle, random.randint(0,50))
while True:
world.tick()
차들이 움직이고, 신호를 위반하기도 합니다.
그리고, 다음으로는 몇몇곳에 트래픽을 집중시켜 정체를 유발하는 방법입니다.
# Draw the spawn point locations as numbers in the map
for i, spawn_point in enumerate(spawn_points):
world.debug.draw_string(spawn_point.location, str(i), life_time=10)
# In synchronous mode, we need to run the simulation to fly the spectator
while True:
world.tick()
spawn_points = world.get_map().get_spawn_points()
# Route 1
spawn_point_1 = spawn_points[32]
# Create route 1 from the chosen spawn points
route_1_indices = [129, 28, 124, 33, 97, 119, 58, 154, 147]
route_1 = []
for ind in route_1_indices:
route_1.append(spawn_points[ind].location)
# Route 2
spawn_point_2 = spawn_points[149]
# Create route 2 from the chosen spawn points
route_2_indices = [21, 76, 38, 34, 90, 3]
route_2 = []
for ind in route_2_indices:
route_2.append(spawn_points[ind].location)
# Now let's print them in the map so we can see our routes
world.debug.draw_string(spawn_point_1.location, 'Spawn point 1', life_time=30, color=carla.Color(255,0,0))
world.debug.draw_string(spawn_point_2.location, 'Spawn point 2', life_time=30, color=carla.Color(0,0,255))
for ind in route_1_indices:
spawn_points[ind].location
world.debug.draw_string(spawn_points[ind].location, str(ind), life_time=60, color=carla.Color(255,0,0))
for ind in route_2_indices:
spawn_points[ind].location
world.debug.draw_string(spawn_points[ind].location, str(ind), life_time=60, color=carla.Color(0,0,255))
while True:
world.tick()
이제 산란지점이랑 경유지점을 선택했으니, 경유지 목록을 따르도록 설정합니다.
# Set delay to create gap between spawn times
spawn_delay = 20
counter = spawn_delay
# Set max vehicles (set smaller for low hardward spec)
max_vehicles = 200
# Alternate between spawn points
alt = False
spawn_points = world.get_map().get_spawn_points()
while True:
world.tick()
n_vehicles = len(world.get_actors().filter('*vehicle*'))
vehicle_bp = random.choice(blueprints)
# Spawn vehicle only after delay
if counter == spawn_delay and n_vehicles < max_vehicles:
# Alternate spawn points
if alt:
vehicle = world.try_spawn_actor(vehicle_bp, spawn_point_1)
else:
vehicle = world.try_spawn_actor(vehicle_bp, spawn_point_2)
if vehicle: # IF vehicle is succesfully spawned
vehicle.set_autopilot(True) # Give TM control over vehicle
# Set parameters of TM vehicle control, we don't want lane changes
traffic_manager.update_vehicle_lights(vehicle, True)
traffic_manager.random_left_lanechange_percentage(vehicle, 0)
traffic_manager.random_right_lanechange_percentage(vehicle, 0)
traffic_manager.auto_lane_change(vehicle, False)
# Alternate between routes
if alt:
traffic_manager.set_path(vehicle, route_1)
alt = False
else:
traffic_manager.set_path(vehicle, route_2)
alt = True
vehicle = None
counter -= 1
elif counter > 0:
counter -= 1
elif counter == 0:
counter = spawn_delay
차량이 다음처럼 (우회전하는 차량)모이게 됩니다. 조금만 더 기다리면
길이 막히는 것을 볼 수 있습니다.
'공부#Robotics#자율주행 > carla' 카테고리의 다른 글
ROS-CARLA Bridge 사용해보기 (0) | 2023.04.30 |
---|---|
(CARLA) 3. segmentation 정보나 Bounding Box를 얻기 (0) | 2023.04.30 |
(CARLA) 1. PythonAPI를 이용해서 CARLA 사용하기 (0) | 2023.04.30 |
(Ubuntu) 우분투에 CARLA 설치하는 방법 및 활용법 (0) | 2023.04.30 |
(자율주행 시뮬레이터) 우분투 20.04에 Carla 를 설치하고, 객체를 소환시켜보자. (0) | 2023.03.13 |