carla/PythonAPI/spawn_npc.py

128 lines
3.5 KiB
Python
Raw Normal View History

2018-10-29 00:46:37 +08:00
#!/usr/bin/env python
# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""Spawn NPCs into the simulation"""
import glob
import os
import sys
try:
sys.path.append(glob.glob('**/*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
import argparse
import random
import time
def main():
argparser = argparse.ArgumentParser(
description=__doc__)
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(
2018-10-30 19:00:00 +08:00
'-n', '--number-of-vehicles',
2018-10-29 00:46:37 +08:00
metavar='N',
default=10,
type=int,
help='number of vehicles (default: 10)')
argparser.add_argument(
'-d', '--delay',
metavar='D',
default=2.0,
type=float,
help='delay in seconds between spawns (default: 2.0)')
2018-11-03 19:28:14 +08:00
argparser.add_argument(
'--safe',
action='store_true',
help='avoid spawning vehicles prone to accidents')
2018-10-29 00:46:37 +08:00
args = argparser.parse_args()
actor_list = []
try:
client = carla.Client(args.host, args.port)
client.set_timeout(2.0)
world = client.get_world()
blueprints = world.get_blueprint_library().filter('vehicle.*')
2018-11-03 19:28:14 +08:00
if args.safe:
blueprints = [x for x in blueprints if int(x.get_attribute('number_of_wheels')) == 4]
blueprints = [x for x in blueprints if not x.id.endswith('isetta')]
2018-10-29 22:00:46 +08:00
def try_spawn_random_vehicle_at(transform):
2018-10-29 00:46:37 +08:00
blueprint = random.choice(blueprints)
if blueprint.has_attribute('color'):
color = random.choice(blueprint.get_attribute('color').recommended_values)
blueprint.set_attribute('color', color)
Provide parent/attribute content of Actors via python interface While creating the new carla ros bridge some extensions became necessary within CARLA: The parent property of an actor via python interface is not yet filled. Therefore, the parent_id of Actors has to be transferred from the CARLA server via rpc interface. In addition, actor attributes are published via python interface. Changes in detail: carla/rpc/Actor.h: - add parent_id field to the Actor class for rpc transport TheNewCarlaServer.cpp: - fill the parent_id field with the appropriate value client/ActorList: - added GetActor() function to get an actor by id client/ActorVariant: - added actor_list optional parameter to Get() and MakeActor() function which allows to query for the parent actor in case the actor_list is available client/ActorAttribute: - solved problem of independent rpc::ActorAttribute* classes by introduction of ActorAttributeValueAccess class, to be able to reuse most of the functions for both ActorAttribueValues and ActorAttributes ActorBlueprintFunctionLibrary: - extended actor attributes by attribute 'role_name' having {autopilot, scenario, ego_vehicle} as recommended values for vehicles or {front,back,...} for sensors to be able to distiguish the different actors in a meaningful way when transferring to ROS topic names - extended vehicle attributes by not-modifiable attribute 'object_type' to be defined at blueprint creation time to provide ground truth object classification type PythonAPI: - libcarla: provide the actor attributes within python as dictionary - make use of role_name attribute to provide information required for ROS bridge to distinguish ego vehicle from others
2018-11-30 23:05:30 +08:00
blueprint.set_attribute('role_name', 'autopilot')
2018-10-29 00:46:37 +08:00
vehicle = world.try_spawn_actor(blueprint, transform)
if vehicle is not None:
actor_list.append(vehicle)
vehicle.set_autopilot()
print('spawned %r at %s' % (vehicle.type_id, transform.location))
2018-10-29 22:00:46 +08:00
return True
return False
# @todo Needs to be converted to list to be shuffled.
spawn_points = list(world.get_map().get_spawn_points())
random.shuffle(spawn_points)
2018-10-29 00:46:37 +08:00
2018-10-29 22:00:46 +08:00
print('found %d spawn points.' % len(spawn_points))
count = args.number_of_vehicles
for spawn_point in spawn_points:
if try_spawn_random_vehicle_at(spawn_point):
count -= 1
if count <= 0:
break
while count > 0:
2018-10-29 00:46:37 +08:00
time.sleep(args.delay)
2018-10-29 22:00:46 +08:00
if try_spawn_random_vehicle_at(random.choice(spawn_points)):
count -= 1
2018-10-29 00:46:37 +08:00
print('spawned %d vehicles, press Ctrl+C to exit.' % args.number_of_vehicles)
2018-10-30 19:00:00 +08:00
while True:
time.sleep(10)
2018-10-29 00:46:37 +08:00
finally:
2018-10-30 19:00:00 +08:00
print('\ndestroying %d actors' % len(actor_list))
2018-10-29 00:46:37 +08:00
for actor in actor_list:
actor.destroy()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
print('\ndone.')