Carla自带样例:automatic_control.py解析

文章目录

find_weather_presets()

这个函数的目的是:

从 Carla 的 WeatherParameters 中找出所有天气预设

将预设的驼峰命名转换为更可读的格式

返回预设的实际值和可读名称列表

例如,对于 "ClearNoon",函数会返回对应的天气预设值和 "Clear Noon" 这样可读的名称。

python 复制代码
def find_weather_presets():
    """Method to find weather presets"""
    rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
    def name(x): return ' '.join(m.group(0) for m in rgx.finditer(x))
    presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)]
    return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets]

get_actor_display_name

函数的主要目的是:

用于获取(Actor)显示名称的函数

从演员的类型ID中提取一个更友好、可读的显示名称

如果名称过长,进行截断并添加省略号

如果 actor.type_id 是 "vehicle_car_tesla",最终 name 会是 "Car Tesla"

python 复制代码
def get_actor_display_name(actor, truncate=250):
    """Method to get actor display name"""
    name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])
    return (name[:truncate - 1] + u'\u2026') if len(name) > truncate else name

get_actor_blueprints()

函数的主要目的是:

根据传入的过滤器(filter)筛选蓝图

根据代际(generation)进一步筛选蓝图

处理各种特殊情况,如全部、单一蓝图、无效代际等

这个函数在自动驾驶模拟器(如Carla)中用于精确选择要生成的车辆或演员蓝图,提供了灵活的筛选机制

例子:获取第2代特定类型的蓝图

gen2_blueprints = get_actor_blueprints(world, "vehicle.tesla", "2")

python 复制代码
def get_actor_blueprints(world, filter, generation):
    bps = world.get_blueprint_library().filter(filter)

    if generation.lower() == "all":
        return bps

    # If the filter returns only one bp, we assume that this one needed
    # and therefore, we ignore the generation
    if len(bps) == 1:
        return bps

    try:
        int_generation = int(generation)
        # Check if generation is in available generations
        if int_generation in [1, 2, 3]:
            bps = [x for x in bps if int(x.get_attribute('generation')) == int_generation]
            return bps
        else:
            print("   Warning! Actor Generation is not valid. No actor will be spawned.")
            return []
    except:
        print("   Warning! Actor Generation is not valid. No actor will be spawned.")
        return []

restart()

python 复制代码
    def restart(self, args):
        """Restart the world"""
        # Keep same camera config if the camera manager exists.
        #保存当前相机的索引和变换索引
        #如果相机管理器不存在,则使用默认值0
        cam_index = self.camera_manager.index if self.camera_manager is not None else 0
        cam_pos_id = self.camera_manager.transform_index if self.camera_manager is not None else 0

        # Get a random blueprint.
        # get_actor_blueprints() 获取可用的蓝图列表
        blueprint_list = get_actor_blueprints(self.world, self._actor_filter, self._actor_generation)
        if not blueprint_list:
            raise ValueError("Couldn't find any blueprints with the specified filters")
        blueprint = random.choice(blueprint_list)
        # 设置角色名为 'hero',随机选择一个推荐颜色
        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. 将已存在的车辆更换位置重新生成
        if self.player is not None:
            spawn_point = self.player.get_transform()
            spawn_point.location.z += 2.0
            spawn_point.rotation.roll = 0.0
            spawn_point.rotation.pitch = 0.0
            self.destroy()
            self.player = self.world.try_spawn_actor(blueprint, spawn_point)
            self.modify_vehicle_physics(self.player)
        while self.player is None:
            if not self.map.get_spawn_points():
                print('There are no spawn points available in your map/town.')
                print('Please add some Vehicle Spawn Point to your UE4 scene.')
                sys.exit(1)
            # 获取当前地图中所有预定义的生成点
            spawn_points = self.map.get_spawn_points()
            # 随机选择一个生成点
            spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform()
            # 尝试在选定的生成点生成一个演员(车辆)
            self.player = self.world.try_spawn_actor(blueprint, spawn_point)
            # 对新生成的车辆调用物理特性修改方法
            self.modify_vehicle_physics(self.player)
        # 根据同步参数,更新世界状态
        if self._args.sync:
            self.world.tick()
        else:
            self.world.wait_for_tick()

        # Set up the sensors.
        # 碰撞传感器
        self.collision_sensor = CollisionSensor(self.player, self.hud)
        # 车道入侵传感器
        self.lane_invasion_sensor = LaneInvasionSensor(self.player, self.hud)
        # GNSS传感器
        self.gnss_sensor = GnssSensor(self.player)
        # 相机管理器
        # 1.创建一个摄像机管理器实例 2.设置摄像机的变换索引 3.设置具体的摄像机传感器
        # 这段代码确保了在重新生成车辆后,摄像机能够保持之前的配置,提供连续的模拟体验
        self.camera_manager = CameraManager(self.player, self.hud)
        self.camera_manager.transform_index = cam_pos_id
        self.camera_manager.set_sensor(cam_index, notify=False)
        # 获取车辆显示名称
        actor_type = get_actor_display_name(self.player)
        # 在抬头显示(HUD)上通知
        self.hud.notification(actor_type)

next_weather

相关推荐
chushiyunen5 小时前
欧洲地理笔记
笔记
吃着火锅x唱着歌5 小时前
Effective C++ 学习笔记 条款43 学习处理模板化基类内的名称
c++·笔记·学习
GGMM78912 小时前
VX4B600100 控制板全解析:施耐德 ATV630 变频器核心控制单元详解
笔记·变频器·变频器维修
kdxiaojie13 小时前
Linux USB驱动阅读笔记(1)
linux·笔记·学习·usb
半生过往14 小时前
前端学 Java 课程笔记
java·前端·笔记
九硕智慧建筑一体化厂家14 小时前
楼宇自控|智慧建筑核心引擎!楼宇自控系统,赋能建筑高效低碳运维
运维·人工智能·笔记·智慧城市
GGMM78915 小时前
施耐德 VX5A1HC90110(VX5A1HD9011)ATV61/ATV71 90‑110KW 电源驱动板详解
笔记·变频器·变频器维修
Wang's Blog16 小时前
PostgreSQL笔记48: 全文检索与向量检索的对比与混合检索实践
笔记·postgresql·全文检索
liuyicenysabel16 小时前
Flask 个人站 iProfile 上线笔记(k3s + Nginx + Let‘s Encrypt)
笔记·nginx·flask
深蓝海拓16 小时前
基于QtPy (PySide6) 的PLC-HMI工程项目(十五)后续完善和改进:PLC端数据解析的防粘包、残包、废包、拆包
笔记·学习·plc