obstacle_layer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. /*********************************************************************
  2. *
  3. * Software License Agreement (BSD License)
  4. *
  5. * Copyright (c) 2008, 2013, Willow Garage, Inc.
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * * Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. * * Redistributions in binary form must reproduce the above
  15. * copyright notice, this list of conditions and the following
  16. * disclaimer in the documentation and/or other materials provided
  17. * with the distribution.
  18. * * Neither the name of Willow Garage, Inc. nor the names of its
  19. * contributors may be used to endorse or promote products derived
  20. * from this software without specific prior written permission.
  21. *
  22. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  25. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  26. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  27. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  28. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  29. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  30. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  31. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  32. * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. * POSSIBILITY OF SUCH DAMAGE.
  34. *
  35. * Author: Eitan Marder-Eppstein
  36. * David V. Lu!!
  37. *********************************************************************/
  38. #include <costmap_2d/obstacle_layer.h>
  39. #include <costmap_2d/costmap_math.h>
  40. #include <tf2_ros/message_filter.h>
  41. #include <pluginlib/class_list_macros.hpp>
  42. #include <sensor_msgs/point_cloud2_iterator.h>
  43. PLUGINLIB_EXPORT_CLASS(costmap_2d::ObstacleLayer, costmap_2d::Layer)
  44. using costmap_2d::FREE_SPACE;
  45. using costmap_2d::LETHAL_OBSTACLE;
  46. using costmap_2d::NO_INFORMATION;
  47. using costmap_2d::Observation;
  48. using costmap_2d::ObservationBuffer;
  49. namespace costmap_2d
  50. {
  51. // 初始化时被调用,用于设置参数、订阅传感器话题、创建观察缓冲区等
  52. void ObstacleLayer::onInitialize()
  53. {
  54. ros::NodeHandle nh("~/" + name_), g_nh;
  55. rolling_window_ = layered_costmap_->isRolling();
  56. // 未知空间的代价值设置
  57. bool track_unknown_space;
  58. nh.param("track_unknown_space", track_unknown_space, layered_costmap_->isTrackingUnknown());
  59. if (track_unknown_space)
  60. default_value_ = NO_INFORMATION; // no information 的代价值是 255
  61. else
  62. default_value_ = FREE_SPACE; // 空闲代价 0
  63. ObstacleLayer::matchSize(); // 调整障碍层的大小以匹配代价地图的大小
  64. current_ = true; // 设置当前状态为真,表示层是最新的
  65. global_frame_ = layered_costmap_->getGlobalFrameID(); // 获取全局坐标ID
  66. double transform_tolerance;
  67. nh.param("transform_tolerance", transform_tolerance, 0.2);
  68. std::string topics_string;
  69. // get the topics that we'll subscribe to from the parameter server
  70. nh.param("observation_sources", topics_string, std::string("")); // 这里就一个雷达数据的话题
  71. ROS_INFO(" Subscribed to Topics: %s", topics_string.c_str());
  72. // now we need to split the topics based on whitespace which we can use a stringstream for
  73. // 现在我们需要根据空格分割主题,我们可以使用字符串流
  74. std::stringstream ss(topics_string); // 使用std::stringstream分割话题字符串,为每个话题创建观察缓冲区和订阅器
  75. std::string source;
  76. while (ss >> source)
  77. {
  78. std::cout << "======================== while (ss >> source) ==========================" << std::endl;
  79. ros::NodeHandle source_node(nh, source);
  80. // get the parameters for the specific topic 获得具体话题的一些参数
  81. double observation_keep_time, expected_update_rate, min_obstacle_height, max_obstacle_height;
  82. std::string topic, sensor_frame, data_type;
  83. bool inf_is_valid, clearing, marking;
  84. source_node.param("topic", topic, source);
  85. source_node.param("sensor_frame", sensor_frame, std::string(""));
  86. source_node.param("observation_persistence", observation_keep_time, 0.0); // 这个是干嘛用的?
  87. source_node.param("expected_update_rate", expected_update_rate, 0.0);
  88. source_node.param("data_type", data_type, std::string("PointCloud"));
  89. source_node.param("min_obstacle_height", min_obstacle_height, 0.0);
  90. source_node.param("max_obstacle_height", max_obstacle_height, 2.0);
  91. source_node.param("inf_is_valid", inf_is_valid, false);
  92. source_node.param("clearing", clearing, true);
  93. source_node.param("marking", marking, true);
  94. if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan"))
  95. {
  96. ROS_FATAL("Only topics that use point clouds or laser scans are currently supported");
  97. throw std::runtime_error("Only topics that use point clouds or laser scans are currently supported");
  98. }
  99. std::string raytrace_range_param_name, obstacle_range_param_name;
  100. // get the obstacle range for the sensor 获取传感器的障碍物范围
  101. double obstacle_range = 2.5;
  102. if (source_node.searchParam("obstacle_range", obstacle_range_param_name))
  103. {
  104. source_node.getParam(obstacle_range_param_name, obstacle_range);
  105. }
  106. // get the raytrace range for the sensor 获取传感器的光线追踪范围
  107. double raytrace_range = 3.0;
  108. if (source_node.searchParam("raytrace_range", raytrace_range_param_name))
  109. {
  110. source_node.getParam(raytrace_range_param_name, raytrace_range);
  111. }
  112. ROS_DEBUG("Creating an observation buffer for source %s, topic %s, frame %s", source.c_str(), topic.c_str(), sensor_frame.c_str());
  113. // create an observation buffer 创建观察缓冲区
  114. observation_buffers_.push_back(
  115. boost::shared_ptr<ObservationBuffer>(new ObservationBuffer(topic, observation_keep_time, expected_update_rate, min_obstacle_height,
  116. max_obstacle_height, obstacle_range, raytrace_range, *tf_, global_frame_,
  117. sensor_frame, transform_tolerance)));
  118. // check if we'll add this buffer to our marking observation buffers
  119. // 检查我们是否要将此缓冲区添加到标记观察缓冲区中
  120. if (marking)
  121. marking_buffers_.push_back(observation_buffers_.back());
  122. // check if we'll also add this buffer to our clearing observation buffers
  123. std::cout << "clearing = " << clearing << std::endl;
  124. if (clearing)
  125. clearing_buffers_.push_back(observation_buffers_.back());
  126. ROS_DEBUG(
  127. "Created an observation buffer for source %s, topic %s, global frame: %s, "
  128. "expected update rate: %.2f, observation persistence: %.2f",
  129. source.c_str(), topic.c_str(), global_frame_.c_str(), expected_update_rate, observation_keep_time);
  130. // create a callback for the topic 根据话题创建回调函数
  131. if (data_type == "LaserScan")
  132. {
  133. boost::shared_ptr<message_filters::Subscriber<sensor_msgs::LaserScan>> sub(new message_filters::Subscriber<sensor_msgs::LaserScan>(g_nh, topic, 50));
  134. boost::shared_ptr<tf2_ros::MessageFilter<sensor_msgs::LaserScan>> filter(
  135. new tf2_ros::MessageFilter<sensor_msgs::LaserScan>(*sub, *tf_, global_frame_, 50, g_nh));
  136. if (inf_is_valid)
  137. {
  138. filter->registerCallback([this, buffer = observation_buffers_.back()](auto &msg)
  139. { laserScanValidInfCallback(msg, buffer); });
  140. // 当有新的LaserScan消息到达并且时间戳检查通过时,会自动调用laserScanValidInfCallback函数,并将消息和最后一个ObservationBuffer对象的引用作为参数传递
  141. }
  142. else
  143. {
  144. filter->registerCallback([this, buffer = observation_buffers_.back()](auto &msg)
  145. { laserScanCallback(msg, buffer); });
  146. }
  147. observation_subscribers_.push_back(sub);
  148. observation_notifiers_.push_back(filter);
  149. observation_notifiers_.back()->setTolerance(ros::Duration(0.05));
  150. }
  151. else if (data_type == "PointCloud")
  152. {
  153. boost::shared_ptr<message_filters::Subscriber<sensor_msgs::PointCloud>> sub(new message_filters::Subscriber<sensor_msgs::PointCloud>(g_nh, topic, 50));
  154. if (inf_is_valid)
  155. {
  156. ROS_WARN("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.");
  157. }
  158. boost::shared_ptr<tf2_ros::MessageFilter<sensor_msgs::PointCloud>> filter(new tf2_ros::MessageFilter<sensor_msgs::PointCloud>(*sub, *tf_, global_frame_, 50, g_nh));
  159. filter->registerCallback([this, buffer = observation_buffers_.back()](auto &msg)
  160. { pointCloudCallback(msg, buffer); });
  161. observation_subscribers_.push_back(sub);
  162. observation_notifiers_.push_back(filter);
  163. }
  164. else
  165. {
  166. boost::shared_ptr<message_filters::Subscriber<sensor_msgs::PointCloud2>> sub(new message_filters::Subscriber<sensor_msgs::PointCloud2>(g_nh, topic, 50));
  167. if (inf_is_valid)
  168. {
  169. ROS_WARN("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.");
  170. }
  171. boost::shared_ptr<tf2_ros::MessageFilter<sensor_msgs::PointCloud2>> filter(new tf2_ros::MessageFilter<sensor_msgs::PointCloud2>(*sub, *tf_, global_frame_, 50, g_nh));
  172. filter->registerCallback([this, buffer = observation_buffers_.back()](auto &msg)
  173. { pointCloud2Callback(msg, buffer); });
  174. observation_subscribers_.push_back(sub);
  175. observation_notifiers_.push_back(filter);
  176. }
  177. if (sensor_frame != "")
  178. {
  179. std::vector<std::string> target_frames;
  180. target_frames.push_back(global_frame_);
  181. target_frames.push_back(sensor_frame);
  182. observation_notifiers_.back()->setTargetFrames(target_frames);
  183. }
  184. }
  185. dsrv_ = NULL;
  186. setupDynamicReconfigure(nh); // 动态重配置的设置
  187. }
  188. // 设置动态重配置,允许在运行时修改配置参数
  189. void ObstacleLayer::setupDynamicReconfigure(ros::NodeHandle &nh)
  190. {
  191. dsrv_ = new dynamic_reconfigure::Server<costmap_2d::ObstaclePluginConfig>(nh);
  192. dynamic_reconfigure::Server<costmap_2d::ObstaclePluginConfig>::CallbackType cb =
  193. [this](auto &config, auto level)
  194. { reconfigureCB(config, level); };
  195. dsrv_->setCallback(cb);
  196. }
  197. // 析构函数
  198. ObstacleLayer::~ObstacleLayer()
  199. {
  200. if (dsrv_)
  201. delete dsrv_;
  202. }
  203. // 动态重配置的回调函数,用于更新配置参数
  204. void ObstacleLayer::reconfigureCB(costmap_2d::ObstaclePluginConfig &config, uint32_t level)
  205. {
  206. enabled_ = config.enabled;
  207. footprint_clearing_enabled_ = config.footprint_clearing_enabled;
  208. max_obstacle_height_ = config.max_obstacle_height;
  209. combination_method_ = config.combination_method;
  210. }
  211. // 处理激光扫描(LaserScan)消息的回调函数,将激光扫描转换为点云并存储在观察缓冲区中
  212. void ObstacleLayer::laserScanCallback(const sensor_msgs::LaserScanConstPtr &message,
  213. const boost::shared_ptr<ObservationBuffer> &buffer)
  214. {
  215. // project the laser into a point cloud
  216. sensor_msgs::PointCloud2 cloud;
  217. cloud.header = message->header;
  218. // project the scan into a point cloud 将扫描投影到点云中
  219. try
  220. {
  221. projector_.transformLaserScanToPointCloud(message->header.frame_id, *message, cloud, *tf_);
  222. }
  223. catch (tf2::TransformException &ex)
  224. {
  225. ROS_WARN("High fidelity enabled, but TF returned a transform exception to frame %s: %s", global_frame_.c_str(), ex.what());
  226. projector_.projectLaser(*message, cloud);
  227. }
  228. catch (std::runtime_error &ex)
  229. {
  230. ROS_WARN("transformLaserScanToPointCloud error, it seems the message from laser sensor is malformed. Ignore this laser scan. what(): %s", ex.what());
  231. return; // ignore this message
  232. }
  233. // buffer the point cloud 缓冲点云
  234. buffer->lock();
  235. buffer->bufferCloud(cloud);
  236. buffer->unlock();
  237. }
  238. // 处理激光扫描消息的回调函数,与laserScanCallback类似,但会将正无穷大的距离替换为最大范围值
  239. void ObstacleLayer::laserScanValidInfCallback(const sensor_msgs::LaserScanConstPtr &raw_message,
  240. const boost::shared_ptr<ObservationBuffer> &buffer)
  241. {
  242. // Filter positive infinities ("Inf"s) to max_range.
  243. float epsilon = 0.0001; // a tenth of a millimeter
  244. sensor_msgs::LaserScan message = *raw_message;
  245. for (size_t i = 0; i < message.ranges.size(); i++)
  246. {
  247. float range = message.ranges[i];
  248. if (!std::isfinite(range) && range > 0)
  249. {
  250. message.ranges[i] = message.range_max - epsilon;
  251. }
  252. }
  253. // project the laser into a point cloud
  254. sensor_msgs::PointCloud2 cloud;
  255. cloud.header = message.header;
  256. // project the scan into a point cloud
  257. try
  258. {
  259. projector_.transformLaserScanToPointCloud(message.header.frame_id, message, cloud, *tf_);
  260. }
  261. catch (tf2::TransformException &ex)
  262. {
  263. ROS_WARN("High fidelity enabled, but TF returned a transform exception to frame %s: %s",
  264. global_frame_.c_str(), ex.what());
  265. projector_.projectLaser(message, cloud);
  266. }
  267. catch (std::runtime_error &ex)
  268. {
  269. ROS_WARN("transformLaserScanToPointCloud error, it seems the message from laser sensor is malformed. Ignore this laser scan. what(): %s", ex.what());
  270. return; // ignore this message
  271. }
  272. // buffer the point cloud
  273. buffer->lock();
  274. buffer->bufferCloud(cloud);
  275. buffer->unlock();
  276. }
  277. // 处理点云(PointCloud)消息的回调函数,将PointCloud转换为PointCloud2并存储在观察缓冲区中
  278. void ObstacleLayer::pointCloudCallback(const sensor_msgs::PointCloudConstPtr &message,
  279. const boost::shared_ptr<ObservationBuffer> &buffer)
  280. {
  281. sensor_msgs::PointCloud2 cloud2;
  282. if (!sensor_msgs::convertPointCloudToPointCloud2(*message, cloud2))
  283. {
  284. ROS_ERROR("Failed to convert a PointCloud to a PointCloud2, dropping message");
  285. return;
  286. }
  287. // buffer the point cloud
  288. buffer->lock();
  289. buffer->bufferCloud(cloud2);
  290. buffer->unlock();
  291. }
  292. // 处理点云2(PointCloud2)消息的回调函数,直接将PointCloud2存储在观察缓冲区中
  293. void ObstacleLayer::pointCloud2Callback(const sensor_msgs::PointCloud2ConstPtr &message,
  294. const boost::shared_ptr<ObservationBuffer> &buffer)
  295. {
  296. // buffer the point cloud
  297. buffer->lock();
  298. buffer->bufferCloud(*message);
  299. buffer->unlock();
  300. }
  301. // 更新障碍层的边界,处理观察数据,并将障碍物添加到代价地图中
  302. void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double *min_x,
  303. double *min_y, double *max_x, double *max_y)
  304. {
  305. // std::cout << "get in updateBounds========================================" << std::endl;
  306. if (rolling_window_)
  307. updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
  308. useExtraBounds(min_x, min_y, max_x, max_y);
  309. bool current = true;
  310. std::vector<Observation> observations, clearing_observations;
  311. // get the marking observations
  312. current = current && getMarkingObservations(observations);
  313. // get the clearing observations
  314. current = current && getClearingObservations(clearing_observations);
  315. // update the global current status
  316. current_ = current;
  317. // raytrace freespace
  318. for (unsigned int i = 0; i < clearing_observations.size(); ++i)
  319. {
  320. raytraceFreespace(clearing_observations[i], min_x, min_y, max_x, max_y);
  321. }
  322. // place the new obstacles into a priority queue... each with a priority of zero to begin with
  323. for (std::vector<Observation>::const_iterator it = observations.begin(); it != observations.end(); ++it)
  324. {
  325. const Observation &obs = *it;
  326. const sensor_msgs::PointCloud2 &cloud = *(obs.cloud_);
  327. double sq_obstacle_range = obs.obstacle_range_ * obs.obstacle_range_;
  328. sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
  329. sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
  330. sensor_msgs::PointCloud2ConstIterator<float> iter_z(cloud, "z");
  331. for (; iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z)
  332. {
  333. double px = *iter_x, py = *iter_y, pz = *iter_z;
  334. // if the obstacle is too high or too far away from the robot we won't add it
  335. if (pz > max_obstacle_height_)
  336. {
  337. ROS_DEBUG("The point is too high");
  338. continue;
  339. }
  340. // compute the squared distance from the hitpoint to the pointcloud's origin
  341. double sq_dist = (px - obs.origin_.x) * (px - obs.origin_.x) + (py - obs.origin_.y) * (py - obs.origin_.y) + (pz - obs.origin_.z) * (pz - obs.origin_.z);
  342. // if the point is far enough away... we won't consider it
  343. if (sq_dist >= sq_obstacle_range)
  344. {
  345. ROS_DEBUG("The point is too far away");
  346. continue;
  347. }
  348. // now we need to compute the map coordinates for the observation
  349. unsigned int mx, my;
  350. if (!worldToMap(px, py, mx, my))
  351. {
  352. ROS_DEBUG("Computing map coords failed");
  353. continue;
  354. }
  355. unsigned int index = getIndex(mx, my);
  356. costmap_[index] = LETHAL_OBSTACLE;
  357. touch(px, py, min_x, min_y, max_x, max_y);
  358. }
  359. }
  360. updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
  361. }
  362. // 更新机器人足印(footprint)在代价地图中的表示
  363. void ObstacleLayer::updateFootprint(double robot_x, double robot_y, double robot_yaw, double *min_x, double *min_y,
  364. double *max_x, double *max_y)
  365. {
  366. if (!footprint_clearing_enabled_)
  367. return;
  368. transformFootprint(robot_x, robot_y, robot_yaw, getFootprint(), transformed_footprint_);
  369. for (unsigned int i = 0; i < transformed_footprint_.size(); i++)
  370. {
  371. touch(transformed_footprint_[i].x, transformed_footprint_[i].y, min_x, min_y, max_x, max_y);
  372. }
  373. }
  374. // 更新代价地图的成本值
  375. void ObstacleLayer::updateCosts(costmap_2d::Costmap2D &master_grid, int min_i, int min_j, int max_i, int max_j)
  376. {
  377. // std::vector<Observation> clearing_observations;
  378. // // get the clearing observations
  379. // getClearingObservations(clearing_observations);
  380. // // double *min_x, *min_y, *max_x, *max_y;
  381. // double *min_x = new double(1e30);
  382. // double *min_y = new double(1e30);
  383. // double *max_x = new double(-1e30);
  384. // double *max_y = new double(-1e30);
  385. // // raytrace freespace
  386. // // std::cout << clearing_observations.size() << std::endl;
  387. // for (unsigned int i = 0; i < clearing_observations.size(); ++i)
  388. // {
  389. // raytraceFreespace(clearing_observations[i], min_x, min_y, max_x, max_y);
  390. // }
  391. // std::cout << "get in updateCosts" << std::endl;
  392. if (footprint_clearing_enabled_)
  393. {
  394. setConvexPolygonCost(transformed_footprint_, costmap_2d::FREE_SPACE);
  395. // 如果启用了足印清除,调用setConvexPolygonCost函数,将机器人的当前区域设置为 FREE_SPACE
  396. }
  397. switch (combination_method_)
  398. {
  399. case 0: // Overwrite 覆盖
  400. updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j); // 这个的效果有点类似是: 移动机器人附近的障碍物才会膨胀,膨胀后的不会消除
  401. break;
  402. case 1: // Maximum 最大值
  403. updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j); // 一般是调用这个 updateWithMax updateWithAddition updateWithTrueOverwrite
  404. break;
  405. default: // Nothing
  406. break;
  407. }
  408. }
  409. // 添加静态观察数据,可以是标记障碍物或清除障碍物
  410. void ObstacleLayer::addStaticObservation(costmap_2d::Observation &obs, bool marking, bool clearing)
  411. {
  412. if (marking)
  413. static_marking_observations_.push_back(obs);
  414. if (clearing)
  415. static_clearing_observations_.push_back(obs);
  416. }
  417. // 清除静态观察数据
  418. void ObstacleLayer::clearStaticObservations(bool marking, bool clearing)
  419. {
  420. if (marking)
  421. static_marking_observations_.clear();
  422. if (clearing)
  423. static_clearing_observations_.clear();
  424. }
  425. // 获取标记障碍物的观察数据
  426. bool ObstacleLayer::getMarkingObservations(std::vector<Observation> &marking_observations) const
  427. {
  428. bool current = true;
  429. // get the marking observations
  430. for (unsigned int i = 0; i < marking_buffers_.size(); ++i)
  431. {
  432. marking_buffers_[i]->lock();
  433. marking_buffers_[i]->getObservations(marking_observations);
  434. current = marking_buffers_[i]->isCurrent() && current;
  435. marking_buffers_[i]->unlock();
  436. }
  437. marking_observations.insert(marking_observations.end(),
  438. static_marking_observations_.begin(), static_marking_observations_.end());
  439. return current;
  440. }
  441. // 获取清除障碍物的观察数据
  442. bool ObstacleLayer::getClearingObservations(std::vector<Observation> &clearing_observations) const
  443. {
  444. bool current = true;
  445. // get the clearing observations
  446. // std::cout << "clearing_buffers_.size() = " << clearing_buffers_.size() << std::endl;
  447. for (unsigned int i = 0; i < clearing_buffers_.size(); ++i)
  448. {
  449. clearing_buffers_[i]->lock();
  450. clearing_buffers_[i]->getObservations(clearing_observations);
  451. current = clearing_buffers_[i]->isCurrent() && current;
  452. clearing_buffers_[i]->unlock();
  453. }
  454. clearing_observations.insert(clearing_observations.end(),
  455. static_clearing_observations_.begin(), static_clearing_observations_.end());
  456. return current;
  457. }
  458. // 执行射线追踪以清除代价地图中的障碍物
  459. void ObstacleLayer::raytraceFreespace(const Observation &clearing_observation, double *min_x, double *min_y, double *max_x, double *max_y)
  460. {
  461. std::cout << "raytraceFreespace ==================================" << std::endl;
  462. double ox = clearing_observation.origin_.x;
  463. double oy = clearing_observation.origin_.y;
  464. const sensor_msgs::PointCloud2 &cloud = *(clearing_observation.cloud_);
  465. // get the map coordinates of the origin of the sensor
  466. unsigned int x0, y0;
  467. if (!worldToMap(ox, oy, x0, y0))
  468. {
  469. ROS_WARN_THROTTLE(
  470. 1.0, "The origin for the sensor at (%.2f, %.2f) is out of map bounds. So, the costmap cannot raytrace for it.",
  471. ox, oy);
  472. return;
  473. }
  474. // we can pre-compute the enpoints of the map outside of the inner loop... we'll need these later
  475. double origin_x = origin_x_, origin_y = origin_y_;
  476. double map_end_x = origin_x + size_x_ * resolution_;
  477. double map_end_y = origin_y + size_y_ * resolution_;
  478. touch(ox, oy, min_x, min_y, max_x, max_y);
  479. // for each point in the cloud, we want to trace a line from the origin and clear obstacles along it
  480. sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
  481. sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
  482. for (; iter_x != iter_x.end(); ++iter_x, ++iter_y)
  483. {
  484. double wx = *iter_x;
  485. double wy = *iter_y;
  486. // now we also need to make sure that the enpoint we're raytracing
  487. // to isn't off the costmap and scale if necessary
  488. double a = wx - ox;
  489. double b = wy - oy;
  490. // the minimum value to raytrace from is the origin
  491. if (wx < origin_x)
  492. {
  493. double t = (origin_x - ox) / a;
  494. wx = origin_x;
  495. wy = oy + b * t;
  496. }
  497. if (wy < origin_y)
  498. {
  499. double t = (origin_y - oy) / b;
  500. wx = ox + a * t;
  501. wy = origin_y;
  502. }
  503. // the maximum value to raytrace to is the end of the map
  504. if (wx > map_end_x)
  505. {
  506. double t = (map_end_x - ox) / a;
  507. wx = map_end_x - .001;
  508. wy = oy + b * t;
  509. }
  510. if (wy > map_end_y)
  511. {
  512. double t = (map_end_y - oy) / b;
  513. wx = ox + a * t;
  514. wy = map_end_y - .001;
  515. }
  516. // now that the vector is scaled correctly... we'll get the map coordinates of its endpoint
  517. unsigned int x1, y1;
  518. // check for legality just in case
  519. if (!worldToMap(wx, wy, x1, y1))
  520. continue;
  521. unsigned int cell_raytrace_range = cellDistance(clearing_observation.raytrace_range_);
  522. MarkCell marker(costmap_, FREE_SPACE);
  523. // and finally... we can execute our trace to clear obstacles along that line
  524. raytraceLine(marker, x0, y0, x1, y1, cell_raytrace_range);
  525. updateRaytraceBounds(ox, oy, wx, wy, clearing_observation.raytrace_range_, min_x, min_y, max_x, max_y);
  526. }
  527. }
  528. // 激活障碍层,重新订阅话题
  529. void ObstacleLayer::activate()
  530. {
  531. // if we're stopped we need to re-subscribe to topics
  532. for (unsigned int i = 0; i < observation_subscribers_.size(); ++i)
  533. {
  534. if (observation_subscribers_[i] != NULL)
  535. observation_subscribers_[i]->subscribe();
  536. }
  537. for (unsigned int i = 0; i < observation_buffers_.size(); ++i)
  538. {
  539. if (observation_buffers_[i])
  540. observation_buffers_[i]->resetLastUpdated();
  541. }
  542. }
  543. // 禁用障碍层,取消订阅话题
  544. void ObstacleLayer::deactivate()
  545. {
  546. for (unsigned int i = 0; i < observation_subscribers_.size(); ++i)
  547. {
  548. if (observation_subscribers_[i] != NULL)
  549. observation_subscribers_[i]->unsubscribe();
  550. }
  551. }
  552. // 更新射线追踪的边界
  553. void ObstacleLayer::updateRaytraceBounds(double ox, double oy, double wx, double wy, double range,
  554. double *min_x, double *min_y, double *max_x, double *max_y)
  555. {
  556. double dx = wx - ox, dy = wy - oy;
  557. double full_distance = hypot(dx, dy);
  558. double scale = std::min(1.0, range / full_distance);
  559. double ex = ox + dx * scale, ey = oy + dy * scale;
  560. touch(ex, ey, min_x, min_y, max_x, max_y);
  561. }
  562. void ObstacleLayer::reset()
  563. {
  564. deactivate();
  565. resetMaps();
  566. current_ = true;
  567. activate();
  568. }
  569. } // namespace costmap_2d