当前位置:   article > 正文

carla学习笔记(二)_world.wait_for_tick

world.wait_for_tick

主要是学习自带的example中的spawn_npc.py的源码.

发现前一天学的很多代码都可以在这里找到原型,觉得还是要先把example代码学习完,在读一下doc才能更深入的了解carla.

  1. #!/usr/bin/env python
  2. # Copyright (c) 2019 Computer Vision Center (CVC) at the Universitat Autonoma de
  3. # Barcelona (UAB).
  4. #
  5. # This work is licensed under the terms of the MIT license.
  6. # For a copy, see <https://opensource.org/licenses/MIT>.
  7. """Spawn NPCs into the simulation"""
  8. import glob
  9. """
  10. glob()函数是python的glob模块中的方法,是种文件通配符,glob()函数可以查找符合自己要求的文件,
  11. glob模块中的函数,有三个:glob.glob(pathname,*,recursive=False)
  12. """
  13. import os
  14. import sys
  15. import time
  16. try:
  17. sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
  18. sys.version_info.major,
  19. sys.version_info.minor,
  20. 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
  21. except IndexError:
  22. pass
  23. """
  24. os.name该变量返回当前操作系统的类型,当前只注册了3个值:分别是posix , nt , java, 对应linux/windows/java虚拟机
  25. """
  26. import carla
  27. from carla import VehicleLightState as vls
  28. import argparse
  29. # argparse 是一种类似于python字典的数据结构
  30. # 我们可以用args.参数名来获取参数
  31. import logging
  32. from numpy import random
  33. def main():
  34. argparser = argparse.ArgumentParser(
  35. description=__doc__)
  36. argparser.add_argument(
  37. '--host',
  38. # 主机127.0.0.1
  39. metavar='H',
  40. default='127.0.0.1',
  41. help='IP of the host server (default: 127.0.0.1)')
  42. argparser.add_argument(
  43. '-p', '--port',
  44. # 端口2000
  45. metavar='P',
  46. default=2000,
  47. type=int,
  48. help='TCP port to listen to (default: 2000)')
  49. argparser.add_argument(
  50. '-n', '--number-of-vehicles',
  51. # 默认车辆个数
  52. metavar='N',
  53. default=10,
  54. type=int,
  55. help='number of vehicles (default: 10)')
  56. argparser.add_argument(
  57. '-w', '--number-of-walkers',
  58. # 默认行人数
  59. metavar='W',
  60. default=50,
  61. type=int,
  62. help='number of walkers (default: 50)')
  63. argparser.add_argument(
  64. '--safe',
  65. # 大概是安全系数?
  66. action='store_true',
  67. help='avoid spawning vehicles prone to accidents')
  68. argparser.add_argument(
  69. '--filterv',
  70. # 选择车辆的某种参数
  71. metavar='PATTERN',
  72. default='vehicle.*',
  73. help='vehicles filter (default: "vehicle.*")')
  74. argparser.add_argument(
  75. '--filterw',
  76. # 选择行人的某种参数
  77. metavar='PATTERN',
  78. default='walker.pedestrian.*',
  79. help='pedestrians filter (default: "walker.pedestrian.*")')
  80. argparser.add_argument(
  81. '--tm-port',
  82. # traffic_manager的参数
  83. metavar='P',
  84. default=8000,
  85. type=int,
  86. help='port to communicate with TM (default: 8000)')
  87. argparser.add_argument(
  88. '--sync',
  89. # 同步模式
  90. action='store_true',
  91. help='Synchronous mode execution')
  92. argparser.add_argument(
  93. '--hybrid',
  94. # 异步模式
  95. action='store_true',
  96. help='Enanble')
  97. argparser.add_argument(
  98. '-s', '--seed',
  99. # 生成设备的种子??
  100. metavar='S',
  101. type=int,
  102. help='Random device seed')
  103. argparser.add_argument(
  104. '--car-lights-on',
  105. # 车灯开启
  106. action='store_true',
  107. default=False,
  108. help='Enanble car lights')
  109. # 封装到了args里面
  110. args = argparser.parse_args()
  111. # 日志,先可以不用过多了解
  112. logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
  113. # 生成的车辆list
  114. vehicles_list = []
  115. # 生成的行人的list
  116. walkers_list = []
  117. # 所有的ID
  118. all_id = []
  119. # 获取客户端
  120. client = carla.Client(args.host, args.port)
  121. # 设定时序?
  122. client.set_timeout(10.0)
  123. # 现将同步模式关闭
  124. synchronous_master = False
  125. # 随机数种子,返回时间戳?
  126. random.seed(args.seed if args.seed is not None else int(time.time()))
  127. try:
  128. # 获取仿真世界
  129. world = client.get_world()
  130. # 设置tm相关的参数,要管理大量的车辆必须使用tm
  131. # 先设置tm的端口
  132. traffic_manager = client.get_trafficmanager(args.tm_port)
  133. # 设置tm的安全距离为1米
  134. traffic_manager.set_global_distance_to_leading_vehicle(1.0)
  135. # 将物理引擎打开
  136. if args.hybrid:
  137. traffic_manager.set_hybrid_physics_mode(True)
  138. # 生成随机数相关?
  139. if args.seed is not None:
  140. traffic_manager.set_random_device_seed(args.seed)
  141. # 把同步模式打开
  142. if args.sync:
  143. settings = world.get_settings()
  144. traffic_manager.set_synchronous_mode(True)
  145. if not settings.synchronous_mode:
  146. synchronous_master = True
  147. settings.synchronous_mode = True
  148. # 设置0.05秒一帧?
  149. settings.fixed_delta_seconds = 0.05
  150. # 将相关的设置应用到仿真世界中去
  151. world.apply_settings(settings)
  152. else:
  153. synchronous_master = False
  154. # 获取仿真世界里面的蓝图,主要用filter获取所有的车辆
  155. blueprints = world.get_blueprint_library().filter(args.filterv)
  156. # 获取仿真世界里面的蓝图,主要用filter获取所有的行人模型
  157. blueprintsWalkers = world.get_blueprint_library().filter(args.filterw)
  158. # 保证安全,避免产生的车辆容易发生故障?
  159. if args.safe:
  160. blueprints = [x for x in blueprints if int(x.get_attribute('number_of_wheels')) == 4]
  161. blueprints = [x for x in blueprints if not x.id.endswith('isetta')]
  162. blueprints = [x for x in blueprints if not x.id.endswith('carlacola')]
  163. blueprints = [x for x in blueprints if not x.id.endswith('cybertruck')]
  164. blueprints = [x for x in blueprints if not x.id.endswith('t2')]
  165. # 将车辆以id来排序
  166. blueprints = sorted(blueprints, key=lambda bp: bp.id)
  167. # 获取world中可以生成车辆的点
  168. spawn_points = world.get_map().get_spawn_points()
  169. # 生成点的个数
  170. number_of_spawn_points = len(spawn_points)
  171. # 如果车辆的个数少于点的个数,那么打乱点的顺序,否则就会报错,先忽略报错
  172. if args.number_of_vehicles < number_of_spawn_points:
  173. random.shuffle(spawn_points)
  174. elif args.number_of_vehicles > number_of_spawn_points:
  175. msg = 'requested %d vehicles, but could only find %d spawn points'
  176. logging.warning(msg, args.number_of_vehicles, number_of_spawn_points)
  177. args.number_of_vehicles = number_of_spawn_points
  178. # 这部分主要是carla中的命令,可能是为了方便?
  179. # @todo cannot import these directly.
  180. # 控制所有生成actor
  181. SpawnActor = carla.command.SpawnActor
  182. # 控制车辆的自动驾驶开关
  183. SetAutopilot = carla.command.SetAutopilot
  184. # 控制车的灯
  185. SetVehicleLightState = carla.command.SetVehicleLightState
  186. # 控制某种属性,默认值是0
  187. FutureActor = carla.command.FutureActor
  188. # --------------
  189. # Spawn vehicles
  190. # --------------
  191. batch = []
  192. # 给spawn_points加上序号0,1,2,3...
  193. for n, transform in enumerate(spawn_points):
  194. # 若n大于要求的数量就报错
  195. if n >= args.number_of_vehicles:
  196. break
  197. # 随机选择一辆车的蓝图,下面全是随机选择并设置车的相关属性
  198. blueprint = random.choice(blueprints)
  199. if blueprint.has_attribute('color'):
  200. color = random.choice(blueprint.get_attribute('color').recommended_values)
  201. blueprint.set_attribute('color', color)
  202. if blueprint.has_attribute('driver_id'):
  203. driver_id = random.choice(blueprint.get_attribute('driver_id').recommended_values)
  204. blueprint.set_attribute('driver_id', driver_id)
  205. blueprint.set_attribute('role_name', 'autopilot')
  206. # 设置车灯的一些属性
  207. # prepare the light state of the cars to spawn
  208. light_state = vls.NONE
  209. if args.car_lights_on:
  210. light_state = vls.Position | vls.LowBeam | vls.LowBeam
  211. # 将随机好的车辆生成并设置驾驶模式和车灯开启相关
  212. # spawn the cars and set their autopilot and light state all together
  213. batch.append(SpawnActor(blueprint, transform)
  214. .then(SetAutopilot(FutureActor, True, traffic_manager.get_port()))
  215. .then(SetVehicleLightState(FutureActor, light_state)))
  216. # 生成同步模式相关
  217. for response in client.apply_batch_sync(batch, synchronous_master):
  218. if response.error:
  219. logging.error(response.error)
  220. else:
  221. vehicles_list.append(response.actor_id)
  222. # -------------
  223. # Spawn Walkers
  224. # -------------
  225. # some settings
  226. percentagePedestriansRunning = 0.0 # how many pedestrians will run
  227. percentagePedestriansCrossing = 0.0 # how many pedestrians will walk through the road
  228. # 1. take all the random locations to spawn
  229. # 主要是将carla的transform的数据格式放入spawn_point中
  230. spawn_points = []
  231. for i in range(args.number_of_walkers):
  232. spawn_point = carla.Transform()
  233. # 只能针对walks使用,在sidewalk上使用
  234. loc = world.get_random_location_from_navigation()
  235. if (loc != None):
  236. spawn_point.location = loc
  237. spawn_points.append(spawn_point)
  238. # 2. we spawn the walker object
  239. # 设置行人的速度
  240. batch = []
  241. walker_speed = []
  242. for spawn_point in spawn_points:
  243. walker_bp = random.choice(blueprintsWalkers)
  244. # set as not invincible
  245. # 设置无敌?
  246. if walker_bp.has_attribute('is_invincible'):
  247. walker_bp.set_attribute('is_invincible', 'false')
  248. # set the max speed
  249. if walker_bp.has_attribute('speed'):
  250. if (random.random() > percentagePedestriansRunning):
  251. # walking
  252. walker_speed.append(walker_bp.get_attribute('speed').recommended_values[1])
  253. else:
  254. # running
  255. walker_speed.append(walker_bp.get_attribute('speed').recommended_values[2])
  256. else:
  257. print("Walker has no speed")
  258. walker_speed.append(0.0)
  259. batch.append(SpawnActor(walker_bp, spawn_point))
  260. results = client.apply_batch_sync(batch, True)
  261. walker_speed2 = []
  262. for i in range(len(results)):
  263. if results[i].error:
  264. logging.error(results[i].error)
  265. else:
  266. walkers_list.append({"id": results[i].actor_id})
  267. walker_speed2.append(walker_speed[i])
  268. walker_speed = walker_speed2
  269. # 3. we spawn the walker controller
  270. # 设置一个行人的控制器
  271. batch = []
  272. # 在蓝图库中找到行人ai控制器
  273. walker_controller_bp = world.get_blueprint_library().find('controller.ai.walker')
  274. for i in range(len(walkers_list)):
  275. batch.append(SpawnActor(walker_controller_bp, carla.Transform(), walkers_list[i]["id"]))
  276. results = client.apply_batch_sync(batch, True)
  277. for i in range(len(results)):
  278. if results[i].error:
  279. logging.error(results[i].error)
  280. else:
  281. walkers_list[i]["con"] = results[i].actor_id
  282. # 4. we put altogether the walkers and controllers id to get the objects from their id
  283. for i in range(len(walkers_list)):
  284. all_id.append(walkers_list[i]["con"])
  285. all_id.append(walkers_list[i]["id"])
  286. all_actors = world.get_actors(all_id)
  287. # wait for a tick to ensure client receives the last transform of the walkers we have just created
  288. if not args.sync or not synchronous_master:
  289. world.wait_for_tick()
  290. else:
  291. world.tick()
  292. # 5. initialize each controller and set target to walk to (list is [controler, actor, controller, actor ...])
  293. # set how many pedestrians can cross the road
  294. # 设置行人的控制相关
  295. world.set_pedestrians_cross_factor(percentagePedestriansCrossing)
  296. for i in range(0, len(all_id), 2):
  297. # start walker
  298. all_actors[i].start()
  299. # set walk to random point
  300. all_actors[i].go_to_location(world.get_random_location_from_navigation())
  301. # max speed
  302. all_actors[i].set_max_speed(float(walker_speed[int(i/2)]))
  303. print('spawned %d vehicles and %d walkers, press Ctrl+C to exit.' % (len(vehicles_list), len(walkers_list)))
  304. # example of how to use parameters
  305. traffic_manager.global_percentage_speed_difference(30.0)
  306. while True:
  307. if args.sync and synchronous_master:
  308. world.tick()
  309. else:
  310. world.wait_for_tick()
  311. finally:
  312. # 主要是恢复初始化
  313. if args.sync and synchronous_master:
  314. settings = world.get_settings()
  315. settings.synchronous_mode = False
  316. settings.fixed_delta_seconds = None
  317. world.apply_settings(settings)
  318. print('\ndestroying %d vehicles' % len(vehicles_list))
  319. client.apply_batch([carla.command.DestroyActor(x) for x in vehicles_list])
  320. # stop walker controllers (list is [controller, actor, controller, actor ...])
  321. for i in range(0, len(all_id), 2):
  322. all_actors[i].stop()
  323. print('\ndestroying %d walkers' % len(walkers_list))
  324. client.apply_batch([carla.command.DestroyActor(x) for x in all_id])
  325. time.sleep(0.5)
  326. if __name__ == '__main__':
  327. try:
  328. main()
  329. except KeyboardInterrupt:
  330. pass
  331. finally:
  332. print('\ndone.')

在学习的过程中,想到了昨天调用cv2的包,突发奇想,想把spectator的视角用imshow独立的窗口展示出来,但自己上手后没有成功,可能是imshow的格式属性不对,也可能是别的问题.需要在后续的学习中可以实现.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/110638
推荐阅读
相关标签
  

闽ICP备14008679号