def walker_collision_creator(self, vehicle):

        vehicle_transform = vehicle.get_transform()
        v = vehicle.get_velocity()
        mps = math.sqrt(v.x**2 + v.y**2 + v.z**2)
        vehicle_loc = vehicle_transform.location
        yaw = self.yaw
        vehicle_xyz = np.array([vehicle_loc.x, vehicle_loc.y, vehicle_loc.z])
        i = 0
        for walker in self.walkers:

            if not self.finished_control[0, i]:

                loc = walker.get_location()
                pedestrian_xyz = np.array([loc.x, loc.y, loc.z])
                R = transforms3d.euler.euler2mat(0, 0, yaw).T
                ped_loc_relative = np.dot(R, pedestrian_xyz - vehicle_xyz)
                x_to_car = ped_loc_relative[0]
                y_to_car = ped_loc_relative[1]

                if not self.applied_control[0, i]:
                    start_walking_distance = self.start_walking_distances[i]
                    if x_to_car < start_walking_distance + random.uniform(
                            5, 20) and x_to_car > 1:
                        control = carla.WalkerControl()
                        control.direction.y = self.ped_velocity_relative[1]
                        control.direction.x = self.ped_velocity_relative[0]
                        control.direction.z = 0
                        control.speed = random.uniform(3, 12) / 3.6
                        walker.apply_control(control)
                        self.applied_control[0, i] = True

                if y_to_car < 0.5 and self.clock_counts[0,
                                                        i] < self.wait_time[i]:
                    control = carla.WalkerControl()
                    control.direction.y = 0
                    control.direction.x = 1
                    control.direction.z = 0
                    control.speed = 0
                    walker.apply_control(control)
                    self.clock_counts[0, i] = self.clock_counts[0, i] + 1

                elif self.clock_counts[0, i] >= self.wait_time[i]:
                    control = carla.WalkerControl()
                    control.direction.y = self.ped_velocity_relative[1]
                    control.direction.x = self.ped_velocity_relative[0]
                    control.direction.z = 0
                    control.speed = 5 / 3.6
                    walker.apply_control(control)
                    self.finished_control[0, i] = True

            i = i + 1
示例#2
0
def spawn_pedestrians():
    client = carla.Client('localhost', 2000)
    client.set_timeout(2.0)
    world = client.get_world()
    blueprint_library = world.get_blueprint_library()
    bp = random.choice(blueprint_library.filter('walker'))

    # n=0
    # while n<20:
    transform = random.choice(world.get_map().get_spawn_points())

    transform = carla.Transform(carla.Location(x=180, y=220, z=10),
                                carla.Rotation(pitch=0, yaw=0, roll=0))

    print(transform)
    pedestrian = world.spawn_actor(bp, transform)
    print('created %s' % pedestrian.type_id)

    while True:
        control = carla.WalkerControl()
        control.speed = 0.1
        control.direction.y = 10
        control.direction.x = 0
        control.direction.z = 0
        pedestrian.apply_control(control)
        time.sleep(2)
        control = carla.WalkerControl()
        control.speed = 0.1
        control.direction.y = 0
        control.direction.x = 10
        control.direction.z = 0
        pedestrian.apply_control(control)
        time.sleep(2)
        control = carla.WalkerControl()
        control.speed = 0.1
        control.direction.y = -10
        control.direction.x = 0
        control.direction.z = 0
        pedestrian.apply_control(control)
        time.sleep(2)
        control = carla.WalkerControl()
        control.speed = 0.1
        control.direction.y = 0
        control.direction.x = -10
        control.direction.z = 0
        pedestrian.apply_control(control)
        time.sleep(2)

    time.sleep(5)
    n += 1
示例#3
0
    def __init__(self, world, carla_setting: CarlaConfig):
        self.logger = logging.getLogger(__name__)
        if carla_setting.print_keyboard_hint:
            print(__doc__)
            print()
        if isinstance(world.player, carla.Vehicle):
            self._control = carla.VehicleControl()
            self._lights = carla.VehicleLightState.NONE
            world.player.set_light_state(self._lights)
        elif isinstance(world.player, carla.Walker):
            self._control = carla.WalkerControl()
            self._rotation = world.player.get_transform().rotation
        else:
            raise NotImplementedError("Actor type not supported")
        self._steer_cache = 0.0
        self.use_joystick = False
        try:
            pygame.joystick.init()
            self.joystick = pygame.joystick.Joystick(0)
            self.joystick.init()
            self.logger.info(
                f"Joystick [{self.joystick.get_name()}] detected, Using Joytick"
            )
            self.use_joystick = True
        except Exception as e:
            self.logger.info(
                "No joystick detected. Plz use your keyboard instead")

        self.logger.debug("Keyboard Control initiated")
示例#4
0
    def __init__(self, world, start_in_autopilot, control_mode):
        self.world = world
        self._autopilot_enabled = start_in_autopilot

        self._manual_input = False
        self._control_mode = control_mode
        self._start_transition = None
        self._transition_prev_time = None
        self._conditions_satisfied = False
        self._request_sent = False
        self._allow_switch = False
        self._start_request_period = None

        self._lane_change = None
        self._old_lane_id = None


        if isinstance(world.player, carla.Vehicle):
            self._control = carla.VehicleControl()
            world.player.set_autopilot(self._autopilot_enabled)
        elif isinstance(world.player, carla.Walker):
            self._control = carla.WalkerControl()
            self._autopilot_enabled = False
            self._rotation = world.player.get_transform().rotation
        else:
            raise NotImplementedError("Actor type not supported")
        self._steer_cache = 0.0
        world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
示例#5
0
    def _initialize_actors(self, config):
        """
        Custom initialization
        """

        # Create a pedestrian.  From CARLA tutorial code:
        # https://github.com/carla-simulator/carla/blob/master/Docs/python_api_tutorial.md
        # and https://github.com/carla-simulator/carla/issues/1229
        blueprintsWalkers = self._world.get_blueprint_library().filter(
            "walker.pedestrian.*")

        # Pedestrians can only spawn at WalkerSpawnPoints.  The UnrealEditor
        # can be used to open a town and locate spawn points.
        ped_location = carla.Location(126.970, 229.260, 1.840)
        spawn_point = carla.Transform(ped_location, carla.Rotation(0))

        self._pedestrian = self._world.try_spawn_actor(
            random.choice(blueprintsWalkers), spawn_point)
        if (self._pedestrian != None):
            player_control = carla.WalkerControl()
            player_control.speed = 2
            if (self._variant == 'Rss_Ext_PASSPED_c'):
                pedestrian_heading = 170
            else:
                pedestrian_heading = 90
            player_rotation = carla.Rotation(0, pedestrian_heading, 0)
            player_control.direction = player_rotation.get_forward_vector()
            self._pedestrian.apply_control(player_control)

        # wait for a tick to ensure client receives the last transform of the walkers we have just created
        self._world.wait_for_tick()
示例#6
0
 def callback(my_world, timestep):
     control = carla.WalkerControl()
     control.speed = 1
     control.direction.x = -1
     control.direction.y = 0
     control.direction.z = 0
     world.get_actor(results[1].actor_id).apply_control(control)
示例#7
0
def control_pedestrian(pedestrian, speed=1, x=0, y=0, z=0, jump=0):
    control = carla.WalkerControl()
    control.speed = speed
    control.direction.x = x
    control.direction.y = y
    control.direction.z = z
    return control
示例#8
0
    def createObjectInSimulator(self, obj):
        # Extract blueprint
        blueprint = self.blueprintLib.find(obj.blueprint)

        # Set up transform
        loc = utils.scenicToCarlaLocation(obj.position,
                                          z=obj.elevation,
                                          world=self.world)
        rot = utils.scenicToCarlaRotation(obj.heading)
        transform = carla.Transform(loc, rot)

        # Create Carla actor
        carlaActor = self.world.try_spawn_actor(blueprint, transform)
        if carlaActor is None:
            raise SimulationCreationError(f'Unable to spawn object {obj}')

        if isinstance(carlaActor, carla.Vehicle):
            # TODO manual gear shift issue? (see above)
            carlaActor.apply_control(
                carla.VehicleControl(manual_gear_shift=False, gear=1))
        elif isinstance(carlaActor, carla.Walker):
            carlaActor.apply_control(carla.WalkerControl())

        obj.carlaActor = carlaActor
        return carlaActor
示例#9
0
    def __init__(self, world, start_in_autopilot):
        self._autopilot_enabled = start_in_autopilot
        if isinstance(world.player, carla.Vehicle):
            self._control = carla.VehicleControl()
            world.player.set_autopilot(self._autopilot_enabled)
        elif isinstance(world.player, carla.Walker):
            self._control = carla.WalkerControl()
            self._autopilot_enabled = False
            self._rotation = world.player.get_transform().rotation
        else:
            raise NotImplementedError("Actor type not supported")
        self._steer_cache = 0.0
        world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)

        # initialize steering wheel
        pygame.joystick.init()

        joystick_count = pygame.joystick.get_count()
        if joystick_count > 1:
            raise ValueError("Please Connect Just One Joystick")

        self._joystick = pygame.joystick.Joystick(0)
        self._joystick.init()

        self._parser = ConfigParser()
        self._parser.read('wheel_config.ini')
        self._steer_idx = int(
            self._parser.get('G29 Racing Wheel', 'steering_wheel'))
        self._throttle_idx = int(
            self._parser.get('G29 Racing Wheel', 'throttle'))
        self._brake_idx = int(self._parser.get('G29 Racing Wheel', 'brake'))
        self._reverse_idx = int(self._parser.get('G29 Racing Wheel',
                                                 'reverse'))
        self._handbrake_idx = int(
            self._parser.get('G29 Racing Wheel', 'handbrake'))
示例#10
0
    def __init__(self, world, start_in_autopilot, db):
        """

        :param world: Oggetto che contiene informazioni sul mondo di gioco
        :type world: Carla_Classes.World
        :param start_in_autopilot: Valore booleano che indica se nel veicolo è abilitato o meno l'autopilota
        :type start_in_autopilot: bool
        :param db: Contiene tutte le informazioni presenti nel database di messaggi CAN
        :type db: cantools.database.can.database.Database db
        """
        pygame.joystick.init()
        self._reverse_idx = 4
        self._autopilot_enabled = start_in_autopilot
        self.db = db

        if isinstance(world.player, carla.Vehicle):
            self.control = carla.VehicleControl()
            world.player.set_autopilot(self._autopilot_enabled)
        elif isinstance(world.player, carla.Walker):
            self.control = carla.WalkerControl()
            self._autopilot_enabled = False
            self._rotation = world.player.get_transform().rotation
        else:
            raise NotImplementedError("Actor type not supported")

        world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)

        self.normal_control = True  # Il veicolo funziona normalmente
        self.fault_control = carla.VehicleControl()
示例#11
0
    def spawn_walker(self, walker_params):
        # spawn the walker
        world = self.client.get_world()
        walker_bp = world.get_blueprint_library().filter(
            "walker.pedestrian.*")[0]
        walker_bp.set_attribute('is_invincible', 'false')
        walker_sp = carla.Transform()
        walker_sp.location.x = walker_params[0]
        walker_sp.location.y = walker_params[1]
        walker_sp.location.z = walker_params[2]
        walker_sp.rotation.pitch = walker_params[3]
        walker_sp.rotation.yaw = walker_params[4]
        walker_sp.rotation.roll = walker_params[5]

        self.walker = world.spawn_actor(walker_bp, walker_sp)
        self.walker_vel.linear.x = walker_params[6] * walker_params[9]
        self.walker_vel.linear.y = walker_params[7] * walker_params[9]

        time.sleep(5)

        #spawn the walker control
        walker_control = carla.WalkerControl(
            carla.Vector3D(walker_params[6], walker_params[7],
                           walker_params[8]), walker_params[9], False)
        self.walker.apply_control(walker_control)
        world.wait_for_tick()
    def cross_road(self):
        if (WALKER_SAMPLE_SPEED):
            self.speed = np.random.uniform(0.5, 1) * self.max_speed
        else:
            self.speed = self.max_speed

        walk = carla.WalkerControl(self.direction,
                                   speed=self.speed,
                                   jump=False)

        self.actor.apply_control(walk)
示例#13
0
 def __init__(self, world, start_in_autopilot):
     self._autopilot_enabled = start_in_autopilot
     if isinstance(world.player, carla.Vehicle):
         self._control = carla.VehicleControl()
         world.player.set_autopilot(self._autopilot_enabled)
     elif isinstance(world.player, carla.Walker):
         self._control = carla.WalkerControl()
         self._autopilot_enabled = False
         self._rotation = world.player.get_transform().rotation
     else:
         raise NotImplementedError("Actor type not supported")
     self._steer_cache = 0.0
 def __init__(self, world, start_in_autopilot):
     self._autopilot_enabled = start_in_autopilot
     if isinstance(world.player, carla.Vehicle):
         self._control = carla.VehicleControl()
         world.player.set_autopilot(self._autopilot_enabled)
     elif isinstance(world.player, carla.Walker):
         self._control = carla.WalkerControl()
         self._autopilot_enabled = False
         self._rotation = world.player.get_transform().rotation
     else:
         raise NotImplementedError("Actor type not supported")
     world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
示例#15
0
def main():
    client = carla.Client('localhost', 2000)
    client.set_timeout(3.0)

    world = client.get_world()

    spawn_points = world.get_map().get_spawn_points()

    vehicle_bp = random.choice(
        world.get_blueprint_library().filter('vehicle.bmw.*'))

    vehicle = world.spawn_actor(vehicle_bp, spawn_points[1])

    ped_bp = random.choice(world.get_blueprint_library().filter('walker'))

    ped = world.spawn_actor(
        ped_bp,
        carla.Transform(carla.Location(75.5166, 12.80842, 0.8431),
                        carla.Rotation(0.0, 270.0, 0.0)))

    control = carla.WalkerControl()

    rgb = sensors.cameras.create_camera(vehicle,
                                        sensors.cameras.SensorTypeEnum.RGB)
    rgb.listen(lambda image: image.save_to_disk('output/veh1_rgb_%06d' % image.
                                                frame_number))
    depth = sensors.cameras.create_camera(vehicle,
                                          sensors.cameras.SensorTypeEnum.DEPTH)
    depth.listen(lambda image: image.save_to_disk(
        'output/veh1_dep_%06d' % image.frame_number, carla.libcarla.
        ColorConverter.LogarithmicDepth))
    seg = sensors.cameras.create_camera(
        vehicle, sensors.cameras.SensorTypeEnum.SEGMENTATION)
    seg.listen(lambda image: image.save_to_disk(
        'output/veh1_seg_%06d' % image.frame_number, carla.libcarla.
        ColorConverter.CityScapesPalette))

    start_time = time.time()
    timeout = 10.0  # seconds

    while time.time() <= start_time + timeout:
        control.speed = 2.0
        control.direction.x = 0.5
        control.direction.y = -0.5
        control.direction.z = 0
        ped.apply_control(control)

    rgb.destroy()
    depth.destroy()
    seg.destroy()
    vehicle.destroy()
    ped.destroy()
def get_actor_control(actor):
    """
    Method to return the type of control to the actor.
    """
    control = None
    actor_type = actor.type_id.split('.')[0]
    if actor.type_id.split('.')[0] == 'vehicle':
        control = carla.VehicleControl()
        control.steering = 0
    elif actor.type_id.split('.')[0] == 'walker':
        control = carla.WalkerControl()

    return control, actor_type
示例#17
0
def main():
    client = carla.Client('localhost', 2000)
    world = client.get_world()
    ped_blueprints = world.get_blueprint_library().filter("walker.*")
    spawn_points = list(world.get_map().get_spawn_points())
    for i in range(1, len(spawn_points), 1):
        player = world.try_spawn_actor(random.choice(ped_blueprints),
                                       spawn_points[i])
        player_control = carla.WalkerControl()
        player_control.speed = 3.
        player_rotation = carla.Rotation(0, 90, 0)
        player_control.direction = player_rotation.get_forward_vector()
        player.apply_control(player_control)
        logging.debug("spawned pedestrian at {}".format(str(spawn_points[i])))
    def ApplyControl(self):

        #while True:
        control = carla.WalkerControl()

        control.speed = 0.9
        control.direction.y = self.ped_velocity_relative[1]
        control.direction.x = self.ped_velocity_relative[0]
        control.direction.z = 0
        #print("here")
        # 3. we spawn the walker controller

        for i in range(len(self.walkers)):
            control.speed = random.uniform(3, 6) / 3.6
            self.walkers[i].apply_control(control)
示例#19
0
 def __init__(self, world, carla_setting: CarlaConfig):
     self.logger = logging.getLogger(__name__)
     if carla_setting.print_keyboard_hint:
         print(__doc__)
         print()
     if isinstance(world.player, carla.Vehicle):
         self._control = carla.VehicleControl()
         self._lights = carla.VehicleLightState.NONE
         world.player.set_light_state(self._lights)
     elif isinstance(world.player, carla.Walker):
         self._control = carla.WalkerControl()
         self._rotation = world.player.get_transform().rotation
     else:
         raise NotImplementedError("Actor type not supported")
     self._steer_cache = 0.0
     self.logger.debug("Keyboard Control initiated")
示例#20
0
 def __init__(self, world, args):
     self._autopilot_enabled = args.autopilot
     self._world = world
     self._restrictor = None
     if isinstance(world.player, carla.Vehicle):
         self._control = carla.VehicleControl()
         world.player.set_autopilot(self._autopilot_enabled)
         self._restrictor = carla.RssRestrictor()
     elif isinstance(world.player, carla.Walker):
         self._control = carla.WalkerControl()
         self._autopilot_enabled = False
         self._rotation = world.player.get_transform().rotation
     else:
         raise NotImplementedError("Actor type not supported")
     self._steer_cache = 0.0
     world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
 def __init__(self, world, start_in_autopilot):
     self._autopilot_enabled = start_in_autopilot
     self.event_ind = 0
     self.seq = seq()
     self.pro = None
     if isinstance(world.player, carla.Vehicle):
         self._control = carla.VehicleControl()
         self._lights = carla.VehicleLightState.NONE
         world.player.set_autopilot(self._autopilot_enabled)
         world.player.set_light_state(self._lights)
     elif isinstance(world.player, carla.Walker):
         self._control = carla.WalkerControl()
         self._autopilot_enabled = False
         self._rotation = world.player.get_transform().rotation
     else:
         raise NotImplementedError("Actor type not supported")
     self._steer_cache = 0.0
     world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
示例#22
0
    def __init__(self, world, target_speed, initial_state):
        self._autopilot_enabled = False
        self._targe_speed = target_speed
        self.initial_state = initial_state

        self.NX = 4
        self.NU = 2
        self.T = 5

        self.R = np.diag([0.01, 0.01]) # input cost function
        self.Rd = np.diag([0.01, 1]) # input different cost matrix
        self.Q = np.diag([1.0, 1.0, 0.5, 0.5]) #stage cost function
        self.Qf = self.Q #stage final matrix

        # iterative parameter
        self.MAX_ITER = 3 
        self.DU_TH = 1
        self.DT = 0.2 #s
        self.WB = 2.5 #m
        self.N_IND_SEARCH = 200 # Search index number
        self.dl = 0.2 # course tick
        self.MAX_TIME = 5

        # CONSTRAINTS
        self.MAX_STEER = 1.0
        self.MAX_DSTEER = 0.1
        self.MAX_SPEED = 100  #km/h
        self.MIN_SPEED = 0 # km/h
        self.MAX_ACCEL = 0.9

        if isinstance(world.player, carla.Vehicle):
            self._control = carla.VehicleControl()
            self._lights = carla.VehicleLightState.NONE
            world.player.set_autopilot(self._autopilot_enabled)
            world.player.set_light_state(self._lights)
        elif isinstance(world.player, carla.Walker):
            self._control = carla.WalkerControl()
            self._autopilot_enabled = False
            self._rotation = world.player.get_transform().rotation
        else:
            raise NotImplementedError("Actor type not supported")
        self._steer_cache = 0.0
        world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
    def step(self, action):

        constant_speed = 0.8
        # action = [-90,90]
        self._rotation.yaw += action
        next_orientation = self._rotation.get_forward_vector()
        control = carla.WalkerControl(direction=next_orientation,
                                      speed=constant_speed)
        self.pedestrian.apply_control(control)

        done = False
        if len(self.collision_hist) != 0:
            done = True  # terminal condition
            reward = -200

        if self.episode_start + SECONDS_PER_EPISODE < time.time():
            done = True
        reward = -1
        return self.main_cam.front_camera, reward, done, None  # obs, reward, done, extra_info
示例#24
0
def spawn_pedestrians(
    world: carla.World,  # pylint: disable=no-member
    num_pedestrians: int,
    speeds: Sequence[float] = (1.0, 1.5, 2.0),
) -> Sequence[carla.Vehicle]:  # pylint: disable=no-member
    """Spawns `pedestrians` in random locations.

  Args:
    world: The world object associated with the simulation.
    num_pedestrians: The number of pedestrians to spawn.
    speeds: The valid set of speeds for the pedestrians.

  Returns:
    The list of pedestrians actors.
  """
    # Blueprints library.
    bl = world.get_blueprint_library()
    # Output container
    actors = list()
    for n in range(num_pedestrians):
        # Fetch random blueprint.
        pedestrian_bp = random.choice(bl.filter("walker.pedestrian.*"))
        # Make pedestrian invicible.
        pedestrian_bp.set_attribute("is_invincible", "true")
        while len(actors) != n:
            # Get random location.
            spawn_point = carla.Transform()  # pylint: disable=no-member
            spawn_point.location = world.get_random_location_from_navigation()
            if spawn_point.location is None:
                continue
            # Attempt to spawn vehicle in random location.
            actor = world.try_spawn_actor(pedestrian_bp, spawn_point)
            player_control = carla.WalkerControl()
            player_control.speed = 3
            pedestrian_heading = 90
            player_rotation = carla.Rotation(0, pedestrian_heading, 0)
            player_control.direction = player_rotation.get_forward_vector()
            if actor is not None:
                actor.apply_control(player_control)
                actors.append(actor)
    logging.debug("Spawned {} pedestrians".format(len(actors)))
    return actors
示例#25
0
 def __init__(self, world, start_in_autopilot):
     self._autopilot_enabled = start_in_autopilot
     #carla.Vehicle.set_velocity(carla.Vehicle,10.0) #36km/s
     if isinstance(world.player, carla.Vehicle):
         #world.player.apply_control(carla.VehicleControl(throttle=0, brake=0, manual_gear_shift=True, gear=0))
         #while True:
         #vehicle.set_velocity(carla.Vector3D(x,y,z))
         #time.sleep(0.01)
         #print(world.player.get_velocity().x, world.player.get_velocity().y)
         self._control = carla.VehicleControl(
         )  ###############################################################################################################
         world.player.set_autopilot(self._autopilot_enabled)
     elif isinstance(world.player, carla.Walker):
         self._control = carla.WalkerControl()
         self._autopilot_enabled = False
         self._rotation = world.player.get_transform().rotation
     else:
         raise NotImplementedError("Actor type not supported")
     self._steer_cache = 0.0
     #world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
     """
示例#26
0
 def blind_point_setting(self, control):
     leading_transform = self._leading_vehicle.get_transform()
     trigger = False
     if control == "StraightAndWalker":
         walker_location = leading_transform.location
         walker_location.x += -5
         walker_location.z += 1
         walker_rotation = leading_transform.rotation
         walker_rotation.yaw = walker_rotation.yaw - 90
         dangerous_walker = Scenario._carla_env.spawn_new_actor(
             bp_str='walker.pedestrian.0001',
             location=walker_location,
             rotation=walker_rotation)
         self.tmp_actor.append(dangerous_walker)
     # self.tmp_actor.append(ai_controller)
     while True:
         if self._scenario_done:
             break
         if self._level_done:
             break
         distance = self.get_distance(self._physical_vehicle,
                                      self._leading_vehicle)
         if not trigger:
             if control == "StraightAndWalker":
                 if distance <= 27:
                     # ai walker start to walk
                     if dangerous_walker is not None:
                         direction_vec = carla.Vector3D(y=1, x=0, z=0)
                         walker_control = carla.WalkerControl(
                             direction=direction_vec, speed=1)
                         dangerous_walker.apply_control(walker_control)
                     # walker_destination = dangerous_walker.get_transform().location
                     # walker_destination.y = 205
                     # ai_controller.start()
                     # ai_controller.go_to_location(walker_destination)
                     # trigger = True
     # dangerous_walker.destroy()
     self.release_tmp_actor()
     self._leading_vehicle = None
    def spawn_npcs(self):
        # blueprints = self.world.get_blueprint_library().filter('vehicle.*')
        spawn_points = self.world.get_map().get_spawn_points()
        vehicle_spawn_points = spawn_points[:NUM_OF_VEHICLE_SPAWN_POINTS]
        walker_spawn_points = spawn_points[-NUM_OF_WALKER_SPAWN_POINTS:]
        number_of_spawn_points = len(walker_spawn_points)

        if self.number_of_pedestrians < number_of_spawn_points:
            random.shuffle(spawn_points)
        elif self.number_of_pedestrians > number_of_spawn_points:
            msg = 'requested %d pedestrians, but could only find %d spawn points for pedestrians'
            logging.warning(msg, self.number_of_pedestrians, number_of_spawn_points)
            self.number_of_pedestrians = number_of_spawn_points

        for n, transform in enumerate(spawn_points):
            if n >= self.number_of_pedestrians:
                break
            blueprint = random.choice(self.world.get_blueprint_library().filter('walker.*'))
            if blueprint.has_attribute('color'):
                color = random.choice(blueprint.get_attribute('color').recommended_values)
                blueprint.set_attribute('color', color)
            if blueprint.has_attribute('is_invincible'):
                blueprint.set_attribute('is_invincible', 'false')

            player = self.world.try_spawn_actor(blueprint, transform)
            player_control = carla.WalkerControl()
            player_control.speed = 3
            player_control.jump = False
            pedestrian_heading = 90
            player_rotation = carla.Rotation(0, pedestrian_heading, 0)
            direction = player_rotation.get_forward_vector()
            player_control.direction.x = direction.x
            player_control.direction.y = -direction.y
            player_control.direction.z = direction.z
            player.apply_control(player_control)
            self.actor_list.append(player)

        print('spawned %d pedestrians, press Ctrl+C to exit.' % len(self.actor_list))
示例#28
0
文件: simulator.py 项目: t27/Scenic
	def createObjectInSimulator(self, obj):
		# Extract blueprint
		blueprint = self.blueprintLib.find(obj.blueprint)
		if obj.rolename is not None:
			blueprint.set_attribute('role_name', obj.rolename)

		# set walker as not invincible
		if blueprint.has_attribute('is_invincible'):
			blueprint.set_attribute('is_invincible', 'False')

		# Set up transform
		loc = utils.scenicToCarlaLocation(obj.position, world=self.world, blueprint=obj.blueprint)
		rot = utils.scenicToCarlaRotation(obj.heading)
		transform = carla.Transform(loc, rot)

		# Create Carla actor
		carlaActor = self.world.try_spawn_actor(blueprint, transform)
		if carlaActor is None:
			self.destroy()
			raise SimulationCreationError(f'Unable to spawn object {obj}')
		obj.carlaActor = carlaActor

		carlaActor.set_simulate_physics(obj.physics)

		if isinstance(carlaActor, carla.Vehicle):
			carlaActor.apply_control(carla.VehicleControl(manual_gear_shift=True, gear=1))
		elif isinstance(carlaActor, carla.Walker):
			carlaActor.apply_control(carla.WalkerControl())
			# spawn walker controller
			controller_bp = self.blueprintLib.find('controller.ai.walker')
			controller = self.world.try_spawn_actor(controller_bp, carla.Transform(), carlaActor)
			if controller is None:
				self.destroy()
				raise SimulationCreationError(f'Unable to spawn carla controller for object {obj}')
			obj.carlaController = controller
		return carlaActor
示例#29
0
        # END HACK

        camera_yaw = math.atan2(R[1, 0], R[0, 0])
        camera_pitch = math.atan2(-R[2, 0], np.sqrt(R[2, 1]**2 + (R[2, 2]**2)))
        camera_roll = math.atan2(R[2, 1], R[2, 2])

        actor_list = []
        car_list = {}
        pygame.init()

        client = carla.Client('localhost', 2000)
        client.set_timeout(100000.0)

        world = client.get_world()
        print(("initial speed: " + str(np.linalg.norm(directions) * 10)))
        control = carla.WalkerControl()
        control.speed = np.linalg.norm(directions) * 10

        print('enabling synchronous mode.')
        settings = world.get_settings()
        settings.synchronous_mode = True
        world.apply_settings(settings)

        cur_yaw = 0
        name_movie = ""
        name_movie_main = ""
        try:
            m = world.get_map()
            print("starting ")
            poses = m.get_spawn_points()
示例#30
0
    bp = blueprint_library.filter('model3')[0]
    print(bp)

    spawn_point = random.choice(world.get_map().get_spawn_points())

    vehicle = world.spawn_actor(bp, spawn_point)
    vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=0.0))
    # vehicle.set_autopilot(True)  # if you just wanted some NPCs to drive.

    actor_list.append(vehicle)

    # Spawn pedestrians
    ped_blueprints = blueprint_library.filter("walker.*")
    spawn_point = random.choice(world.get_map().get_spawn_points())
    player = world.spawn_actor(random.choice(ped_blueprints), spawn_point)
    player_control = carla.WalkerControl()
    player_control.speed = 3
    player_rotation = carla.Rotation(0, 90, 0)
    player_control.direction = player_rotation.get_forward_vector()
    player.apply_control(player_control)

    actor_list.append(player)

    # https://carla.readthedocs.io/en/latest/cameras_and_sensors
    # get the blueprint for this sensor
    blueprint = blueprint_library.find('sensor.camera.rgb')
    # change the dimensions of the image
    blueprint.set_attribute('image_size_x', f'{IM_WIDTH}')
    blueprint.set_attribute('image_size_y', f'{IM_HEIGHT}')
    blueprint.set_attribute('fov', '110')