Python carla.Transform() Examples

The following are 30 code examples of carla.Transform(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module carla , or try the search function .
Example #1
Source File: misc.py    From gym-carla with MIT License 6 votes vote down vote up
def get_pixel_info(local_info, d_behind, obs_range, image_size):
  """
  Transform local vehicle info to pixel info, with ego placed at lower center of image.
  Here the ego local coordinate is left-handed, the pixel coordinate is also left-handed,
  with its origin at the left bottom.
  :param local_info: local vehicle info in ego coordinate
  :param d_behind: distance from ego to bottom of FOV
  :param obs_range: length of edge of FOV
  :param image_size: size of edge of image
  :return: tuple of pixel level info, including (x, y, yaw, l, w) all in pixels
  """
  x, y, yaw, l, w = local_info
  x_pixel = (x + d_behind) / obs_range * image_size
  y_pixel = y / obs_range * image_size + image_size / 2
  yaw_pixel = yaw
  l_pixel = l / obs_range * image_size
  w_pixel = w / obs_range * image_size
  pixel_tuple = (x_pixel, y_pixel, yaw_pixel, l_pixel, w_pixel)
  return pixel_tuple 
Example #2
Source File: cut_in.py    From scenario_runner with MIT License 6 votes vote down vote up
def _initialize_actors(self, config):

        # direction of lane, on which other_actor is driving before lane change
        if 'LEFT' in self._config.name.upper():
            self._direction = 'left'

        if 'RIGHT' in self._config.name.upper():
            self._direction = 'right'

        # add actors from xml file
        for actor in config.other_actors:
            vehicle = CarlaDataProvider.request_new_actor(actor.model, actor.transform)
            self.other_actors.append(vehicle)
            vehicle.set_simulate_physics(enabled=False)

        # transform visible
        other_actor_transform = self.other_actors[0].get_transform()
        self._transform_visible = carla.Transform(
            carla.Location(other_actor_transform.location.x,
                           other_actor_transform.location.y,
                           other_actor_transform.location.z + 105),
            other_actor_transform.rotation) 
Example #3
Source File: vehicle_manager.py    From macad-gym with MIT License 6 votes vote down vote up
def set_vehicle(self, transform):
        """Spawn vehicle.

        Args:
            transform (carla.Transform): start location and rotation.

        Returns:
            N/A.
        """
        # Initialize blueprints and vehicle properties.
        bps = self._world.get_blueprint_library().filter('vehicle')
        bp = random.choice(bps)
        print('spawning vehicle %r with %d wheels' %
              (bp.id, bp.get_attribute('number_of_wheels')))

        # Spawn vehicle.
        vehicle = self._world.try_spawn_actor(bp, transform)
        print('vehicle at ',
              vehicle.get_location().x,
              vehicle.get_location().y,
              vehicle.get_location().z)
        self._vehicle = vehicle

        # Set sensors to the vehicle
        self._set_sensors() 
Example #4
Source File: other_leading_vehicle.py    From scenario_runner with MIT License 6 votes vote down vote up
def _initialize_actors(self, config):
        """
        Custom initialization
        """
        first_vehicle_waypoint, _ = get_waypoint_in_distance(self._reference_waypoint, self._first_vehicle_location)
        second_vehicle_waypoint, _ = get_waypoint_in_distance(self._reference_waypoint, self._second_vehicle_location)
        second_vehicle_waypoint = second_vehicle_waypoint.get_left_lane()

        first_vehicle_transform = carla.Transform(first_vehicle_waypoint.transform.location,
                                                  first_vehicle_waypoint.transform.rotation)
        second_vehicle_transform = carla.Transform(second_vehicle_waypoint.transform.location,
                                                   second_vehicle_waypoint.transform.rotation)

        first_vehicle = CarlaDataProvider.request_new_actor('vehicle.nissan.patrol', first_vehicle_transform)
        second_vehicle = CarlaDataProvider.request_new_actor('vehicle.audi.tt', second_vehicle_transform)

        self.other_actors.append(first_vehicle)
        self.other_actors.append(second_vehicle)

        self._first_actor_transform = first_vehicle_transform
        self._second_actor_transform = second_vehicle_transform 
Example #5
Source File: spawn_control.py    From macad-gym with MIT License 6 votes vote down vote up
def __init__(self, parent_actor, hud):
        self.sensor = None
        self._parent = parent_actor
        self._hud = hud
        world = self._parent.get_world()
        bp = world.get_blueprint_library().find('sensor.other.lane_detector')
        self.sensor = world.spawn_actor(bp,
                                        carla.Transform(),
                                        attach_to=self._parent)
        # We need to pass the lambda a weak reference to self to avoid circular
        # reference.
        weak_self = weakref.ref(self)
        self._offlane = 0
        self._off_lane_percentage = 0
        self.sensor.listen(
            lambda event: LaneInvasionSensor._on_invasion(weak_self, event)) 
Example #6
Source File: map_explore.py    From macad-gym with MIT License 6 votes vote down vote up
def start_scenario():
    car_bp = random.choice(world.get_blueprint_library().filter('vehicle'))
    car_bp.set_attribute("role_name", "hero")
    car1_loc_s = carla.Location(*spawn_locs["car1"]["S"])
    car2_loc_s = carla.Location(*spawn_locs["car2"]["S"])
    ped1_loc_s = carla.Location(*spawn_locs["ped1"]["S"])

    car1 = world.spawn_actor(
        car_bp, carla.Transform(car1_loc_s, carla.Rotation(yaw=0)))
    car1.set_autopilot(True)
    car2 = world.spawn_actor(
        car_bp, carla.Transform(car2_loc_s, carla.Rotation(yaw=-90)))
    car2.set_autopilot(True)

    ped_bp = random.choice(world.get_blueprint_library().filter('walker'))
    ped1 = world.spawn_actor(
        ped_bp, carla.Transform(ped1_loc_s, carla.Rotation(yaw=0)))
    start_walker(ped1) 
Example #7
Source File: atomic_behaviors.py    From scenario_runner with MIT License 6 votes vote down vote up
def update(self):
        """
        Transform actor
        """
        new_status = py_trees.common.Status.RUNNING

        # calculate transform with method in openscenario_parser.py
        self._osc_transform = srunner.tools.openscenario_parser.OpenScenarioParser.convert_position_to_transform(
            self._osc_position)
        self._actor.set_transform(self._osc_transform)

        if not self._actor.is_alive:
            new_status = py_trees.common.Status.FAILURE

        if calculate_distance(self._actor.get_location(), self._osc_transform.location) < 1.0:
            if self._physics:
                self._actor.set_simulate_physics(enabled=True)
            new_status = py_trees.common.Status.SUCCESS

        return new_status 
Example #8
Source File: derived_sensors.py    From macad-gym with MIT License 6 votes vote down vote up
def __init__(self, parent_actor, hud):
        self.sensor = None
        self._history = []
        self._parent = parent_actor
        self._hud = hud
        self.offlane = 0  # count of off lane
        self.offroad = 0  # count of off road
        world = self._parent.get_world()
        bp = world.get_blueprint_library().find('sensor.other.lane_detector')
        self.sensor = world.spawn_actor(
            bp, carla.Transform(), attach_to=self._parent)
        # We need to pass the lambda a weak reference to self to avoid circular
        # reference.
        weak_self = weakref.ref(self)
        self.sensor.listen(
            lambda event: LaneInvasionSensor._on_invasion(weak_self, event)) 
Example #9
Source File: atomic_criteria.py    From scenario_runner with MIT License 6 votes vote down vote up
def __init__(self, actor, other_actor=None, other_actor_type=None,
                 optional=False, name="CollisionTest", terminate_on_failure=False):
        """
        Construction with sensor setup
        """
        super(CollisionTest, self).__init__(name, actor, 0, None, optional, terminate_on_failure)
        self.logger.debug("%s.__init__()" % (self.__class__.__name__))

        world = self.actor.get_world()
        blueprint = world.get_blueprint_library().find('sensor.other.collision')
        self._collision_sensor = world.spawn_actor(blueprint, carla.Transform(), attach_to=self.actor)
        self._collision_sensor.listen(lambda event: self._count_collisions(weakref.ref(self), event))

        self.other_actor = other_actor
        self.other_actor_type = other_actor_type
        self.registered_collisions = []
        self.last_id = None
        self.collision_time = None 
Example #10
Source File: carla_lane_invasion_sensor_operator.py    From pylot with Apache License 2.0 6 votes vote down vote up
def run(self):
        # Read the vehicle ID from the vehicle ID stream.
        vehicle_id_msg = self._vehicle_id_stream.read()
        vehicle_id = vehicle_id_msg.data
        self._logger.debug("@{}: Received Vehicle ID: {}".format(
            vehicle_id_msg.timestamp, vehicle_id))

        # Connect to the world.
        _, world = get_world(self._flags.carla_host, self._flags.carla_port,
                             self._flags.carla_timeout)

        self._vehicle = get_vehicle_handle(world, vehicle_id)
        self._map = world.get_map()

        # Install the lane-invasion sensor.
        lane_invasion_blueprint = world.get_blueprint_library().find(
            'sensor.other.lane_invasion')

        self._logger.debug("Spawning a lane invasion sensor.")
        self._lane_invasion_sensor = world.spawn_actor(lane_invasion_blueprint,
                                                       carla.Transform(),
                                                       attach_to=self._vehicle)

        # Register the callback on the lane-invasion sensor.
        self._lane_invasion_sensor.listen(self.process_lane_invasion) 
Example #11
Source File: spawn_control.py    From macad-gym with MIT License 6 votes vote down vote up
def __init__(self, parent_actor, hud):
        self.sensor = None
        self._history = []
        self._parent = parent_actor
        self._hud = hud
        self.collision_vehicles = 0
        self.collision_pedestrains = 0
        self.collision_other = 0
        self.collision_id_set = set()
        self.collision_type_id_set = set()
        world = self._parent.get_world()
        bp = world.get_blueprint_library().find('sensor.other.collision')
        self.sensor = world.spawn_actor(bp,
                                        carla.Transform(),
                                        attach_to=self._parent)
        # We need to pass the lambda a weak reference to self to avoid circular
        # reference.
        weak_self = weakref.ref(self)
        self.sensor.listen(
            lambda event: CollisionSensor._on_collision(weak_self, event)) 
Example #12
Source File: change_lane.py    From scenario_runner with MIT License 6 votes vote down vote up
def _initialize_actors(self, config):

        # add actors from xml file
        for actor in config.other_actors:
            vehicle = CarlaDataProvider.request_new_actor(actor.model, actor.transform)
            self.other_actors.append(vehicle)
            vehicle.set_simulate_physics(enabled=False)

        # fast vehicle, tesla
        # transform visible
        fast_car_waypoint, _ = get_waypoint_in_distance(self._reference_waypoint, self._fast_vehicle_distance)
        self.fast_car_visible = carla.Transform(
            carla.Location(fast_car_waypoint.transform.location.x,
                           fast_car_waypoint.transform.location.y,
                           fast_car_waypoint.transform.location.z + 1),
            fast_car_waypoint.transform.rotation)

        # slow vehicle, vw
        # transform visible
        slow_car_waypoint, _ = get_waypoint_in_distance(self._reference_waypoint, self._slow_vehicle_distance)
        self.slow_car_visible = carla.Transform(
            carla.Location(slow_car_waypoint.transform.location.x,
                           slow_car_waypoint.transform.location.y,
                           slow_car_waypoint.transform.location.z),
            slow_car_waypoint.transform.rotation) 
Example #13
Source File: object_crash_intersection.py    From scenario_runner with MIT License 6 votes vote down vote up
def get_opponent_transform(added_dist, waypoint, trigger_location):
    """
    Calculate the transform of the adversary
    """
    lane_width = waypoint.lane_width

    offset = {"orientation": 270, "position": 90, "k": 1.0}
    _wp = waypoint.next(added_dist)
    if _wp:
        _wp = _wp[-1]
    else:
        raise RuntimeError("Cannot get next waypoint !")

    location = _wp.transform.location
    orientation_yaw = _wp.transform.rotation.yaw + offset["orientation"]
    position_yaw = _wp.transform.rotation.yaw + offset["position"]

    offset_location = carla.Location(
        offset['k'] * lane_width * math.cos(math.radians(position_yaw)),
        offset['k'] * lane_width * math.sin(math.radians(position_yaw)))
    location += offset_location
    location.z = trigger_location.z
    transform = carla.Transform(location, carla.Rotation(yaw=orientation_yaw))

    return transform 
Example #14
Source File: sensors.py    From tensorforce with Apache License 2.0 6 votes vote down vote up
def __init__(self, parent_actor: carla.Actor, transform=carla.Transform(), attachment_type=None,
                 attributes: dict = None):
        self.parent = parent_actor
        self.world = self.parent.get_world()
        self.attributes = attributes or dict()
        self.event_callbacks = []

        # Look for callback(s)
        if 'callback' in self.attributes:
            self.event_callbacks.append(self.attributes.pop('callback'))

        elif 'callbacks' in self.attributes:
            for callback in self.attributes.pop('callbacks'):
                self.event_callbacks.append(callback)

        # detector-sensors retrieve data only when triggered (not at each tick!)
        self.sensor, self.is_detector = self._spawn(transform, attachment_type) 
Example #15
Source File: background_activity.py    From scenario_runner with MIT License 6 votes vote down vote up
def _initialize_actors(self, config):

        town_name = config.town
        if town_name in self.town_amount:
            amount = self.town_amount[town_name]
        else:
            amount = 0

        new_actors = CarlaDataProvider.request_new_batch_actors('vehicle.*',
                                                                amount,
                                                                carla.Transform(),
                                                                autopilot=True,
                                                                random_location=True,
                                                                rolename='background')

        if new_actors is None:
            raise Exception("Error: Unable to add the background activity, all spawn points were occupied")

        for _actor in new_actors:
            self.other_actors.append(_actor) 
Example #16
Source File: object_crash_vehicle.py    From scenario_runner with MIT License 6 votes vote down vote up
def _spawn_blocker(self, transform, orientation_yaw):
        """
        Spawn the blocker prop that blocks the vision from the egovehicle of the jaywalker
        :return:
        """
        # static object transform
        shift = 0.9
        x_ego = self._reference_waypoint.transform.location.x
        y_ego = self._reference_waypoint.transform.location.y
        x_cycle = transform.location.x
        y_cycle = transform.location.y
        x_static = x_ego + shift * (x_cycle - x_ego)
        y_static = y_ego + shift * (y_cycle - y_ego)

        spawn_point_wp = self.ego_vehicles[0].get_world().get_map().get_waypoint(transform.location)

        self.transform2 = carla.Transform(carla.Location(x_static, y_static,
                                                         spawn_point_wp.transform.location.z + 0.3),
                                          carla.Rotation(yaw=orientation_yaw + 180))

        static = CarlaDataProvider.request_new_actor('static.prop.vendingmachine', self.transform2)
        static.set_simulate_physics(enabled=False)

        return static 
Example #17
Source File: object_crash_vehicle.py    From scenario_runner with MIT License 6 votes vote down vote up
def _initialize_actors(self, config):
        """
        Custom initialization
        """
        _start_distance = 40
        lane_width = self._reference_waypoint.lane_width
        location, _ = get_location_in_distance_from_wp(self._reference_waypoint, _start_distance)
        waypoint = self._wmap.get_waypoint(location)
        offset = {"orientation": 270, "position": 90, "z": 0.4, "k": 0.2}
        position_yaw = waypoint.transform.rotation.yaw + offset['position']
        orientation_yaw = waypoint.transform.rotation.yaw + offset['orientation']
        offset_location = carla.Location(
            offset['k'] * lane_width * math.cos(math.radians(position_yaw)),
            offset['k'] * lane_width * math.sin(math.radians(position_yaw)))
        location += offset_location
        location.z += offset['z']
        self.transform = carla.Transform(location, carla.Rotation(yaw=orientation_yaw))
        static = CarlaDataProvider.request_new_actor('static.prop.container', self.transform)
        static.set_simulate_physics(True)
        self.other_actors.append(static) 
Example #18
Source File: no_rendering_mode.py    From scenario_runner with MIT License 6 votes vote down vote up
def _spawn_hero(self):
        # Get a random blueprint.
        blueprint = random.choice(self.world.get_blueprint_library().filter(self.args.filter))
        blueprint.set_attribute('role_name', 'hero')
        if blueprint.has_attribute('color'):
            color = random.choice(blueprint.get_attribute('color').recommended_values)
            blueprint.set_attribute('color', color)
        # Spawn the player.
        while self.hero_actor is None:
            spawn_points = self.world.get_map().get_spawn_points()
            spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform()
            self.hero_actor = self.world.try_spawn_actor(blueprint, spawn_point)
        self.hero_transform = self.hero_actor.get_transform()

        # Save it in order to destroy it when closing program
        self.spawned_hero = self.hero_actor 
Example #19
Source File: follow_leading_vehicle.py    From scenario_runner with MIT License 6 votes vote down vote up
def _initialize_actors(self, config):
        """
        Custom initialization
        """

        first_vehicle_waypoint, _ = get_waypoint_in_distance(self._reference_waypoint, self._first_vehicle_location)
        self._other_actor_transform = carla.Transform(
            carla.Location(first_vehicle_waypoint.transform.location.x,
                           first_vehicle_waypoint.transform.location.y,
                           first_vehicle_waypoint.transform.location.z + 1),
            first_vehicle_waypoint.transform.rotation)
        first_vehicle_transform = carla.Transform(
            carla.Location(self._other_actor_transform.location.x,
                           self._other_actor_transform.location.y,
                           self._other_actor_transform.location.z - 500),
            self._other_actor_transform.rotation)
        first_vehicle = CarlaDataProvider.request_new_actor('vehicle.nissan.patrol', first_vehicle_transform)
        first_vehicle.set_simulate_physics(enabled=False)
        self.other_actors.append(first_vehicle) 
Example #20
Source File: env_utils.py    From tensorforce with Apache License 2.0 6 votes vote down vote up
def random_spawn_point(world_map: carla.Map, different_from: carla.Location = None) -> carla.Transform:
    """Returns a random spawning location.
        :param world_map: a carla.Map instance obtained by calling world.get_map()
        :param different_from: ensures that the location of the random spawn point is different from the one specified here.
        :return: a carla.Transform instance.
    """
    available_spawn_points = world_map.get_spawn_points()

    if different_from is not None:
        while True:
            spawn_point = random.choice(available_spawn_points)

            if spawn_point.location != different_from:
                return spawn_point
    else:
        return random.choice(available_spawn_points) 
Example #21
Source File: test_transform.py    From macad-gym with MIT License 6 votes vote down vote up
def test_values(self):
        t = carla.Transform()
        self.assertEqual(t.location.x, 0.0)
        self.assertEqual(t.location.y, 0.0)
        self.assertEqual(t.location.z, 0.0)
        self.assertEqual(t.rotation.pitch, 0.0)
        self.assertEqual(t.rotation.yaw, 0.0)
        self.assertEqual(t.rotation.roll, 0.0)
        t = carla.Transform(carla.Location(y=42.0))
        self.assertEqual(t.location.x, 0.0)
        self.assertEqual(t.location.y, 42.0)
        self.assertEqual(t.location.z, 0.0)
        self.assertEqual(t.rotation.pitch, 0.0)
        self.assertEqual(t.rotation.yaw, 0.0)
        self.assertEqual(t.rotation.roll, 0.0)
        t = carla.Transform(rotation=carla.Rotation(yaw=42.0))
        self.assertEqual(t.location.x, 0.0)
        self.assertEqual(t.location.y, 0.0)
        self.assertEqual(t.location.z, 0.0)
        self.assertEqual(t.rotation.pitch, 0.0)
        self.assertEqual(t.rotation.yaw, 42.0)
        self.assertEqual(t.rotation.roll, 0.0) 
Example #22
Source File: env_utils.py    From tensorforce with Apache License 2.0 6 votes vote down vote up
def spawn_actor(world: carla.World, blueprint: carla.ActorBlueprint, spawn_point: carla.Transform,
                attach_to: carla.Actor = None, attachment_type=carla.AttachmentType.Rigid) -> carla.Actor:
    """Tries to spawn an actor in a CARLA simulator.
        :param world: a carla.World instance.
        :param blueprint: specifies which actor has to be spawned.
        :param spawn_point: where to spawn the actor. A transform specifies the location and rotation.
        :param attach_to: whether the spawned actor has to be attached (linked) to another one.
        :param attachment_type: the kind of the attachment. Can be 'Rigid' or 'SpringArm'.
        :return: a carla.Actor instance.
    """
    actor = world.try_spawn_actor(blueprint, spawn_point, attach_to, attachment_type)

    if actor is None:
        raise ValueError(f'Cannot spawn actor. Try changing the spawn_point ({spawn_point}) to something else.')

    return actor 
Example #23
Source File: basic_scenario.py    From scenario_runner with MIT License 6 votes vote down vote up
def _initialize_environment(self, world):
        """
        Default initialization of weather and road friction.
        Override this method in child class to provide custom initialization.
        """

        # Set the appropriate weather conditions
        world.set_weather(self.config.weather)

        # Set the appropriate road friction
        if self.config.friction is not None:
            friction_bp = world.get_blueprint_library().find('static.trigger.friction')
            extent = carla.Location(1000000.0, 1000000.0, 1000000.0)
            friction_bp.set_attribute('friction', str(self.config.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)
            world.spawn_actor(friction_bp, transform) 
Example #24
Source File: sensors.py    From tensorforce with Apache License 2.0 5 votes vote down vote up
def lane_detector(transform: carla.Transform = None, position: str = None, attachment_type='Rigid', **kwargs):
        return SensorSpecs.detector('lane_invasion', transform, position, attachment_type, **kwargs) 
Example #25
Source File: sensors.py    From tensorforce with Apache License 2.0 5 votes vote down vote up
def radar(transform: carla.Transform = None, position: str = None, attachment_type='Rigid', **kwargs):
        return SensorSpecs.other('radar', transform, position, attachment_type, **kwargs) 
Example #26
Source File: sensors.py    From tensorforce with Apache License 2.0 5 votes vote down vote up
def lidar(transform: carla.Transform = None, position: str = None, attachment_type=None, **kwargs) -> dict:
        return dict(type='sensor.lidar.ray_cast',
                    transform=transform or SensorSpecs.get_position(position),
                    attachment_type=SensorSpecs.ATTACHMENT_TYPE[attachment_type],
                    attributes=kwargs) 
Example #27
Source File: sensors.py    From tensorforce with Apache License 2.0 5 votes vote down vote up
def other(kind: str, transform: carla.Transform = None, position: str = None, attachment_type=None, **kwargs) -> dict:
        assert kind in ['imu', 'gnss', 'radar']
        return dict(type='sensor.other.' + kind,
                    transform=transform or SensorSpecs.get_position(position),
                    attachment_type=SensorSpecs.ATTACHMENT_TYPE[attachment_type],
                    attributes=kwargs) 
Example #28
Source File: sensors.py    From tensorforce with Apache License 2.0 5 votes vote down vote up
def obstacle_detector(transform: carla.Transform = None, position: str = None, attachment_type='Rigid', **kwargs):
        return SensorSpecs.detector('obstacle', transform, position, attachment_type, **kwargs) 
Example #29
Source File: sensors.py    From tensorforce with Apache License 2.0 5 votes vote down vote up
def detector(kind: str, transform: carla.Transform = None, position: str = None, attachment_type=None,
                 **kwargs) -> dict:
        assert kind in ['collision', 'lane_invasion', 'obstacle']
        return dict(type='sensor.other.' + kind,
                    transform=transform or SensorSpecs.get_position(position),
                    attachment_type=SensorSpecs.ATTACHMENT_TYPE[attachment_type],
                    attributes=kwargs) 
Example #30
Source File: sensors.py    From tensorforce with Apache License 2.0 5 votes vote down vote up
def depth_camera(transform: carla.Transform = None, position: str = None, attachment_type='SpringArm',
                     color_converter='LogarithmicDepth', **kwargs):
        return SensorSpecs.camera('depth', transform, position, attachment_type, color_converter, **kwargs)