Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
obstacle_layer.cpp
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  * Steve Macenski
38  *********************************************************************/
39 #include "nav2_costmap_2d/obstacle_layer.hpp"
40 
41 #include <algorithm>
42 #include <memory>
43 #include <string>
44 #include <vector>
45 
46 #include "pluginlib/class_list_macros.hpp"
47 #include "sensor_msgs/point_cloud2_iterator.hpp"
48 #include "nav2_costmap_2d/costmap_math.hpp"
49 #include "rclcpp/version.h"
50 
52 
53 using nav2_costmap_2d::NO_INFORMATION;
54 using nav2_costmap_2d::LETHAL_OBSTACLE;
55 using nav2_costmap_2d::FREE_SPACE;
56 
59 using rcl_interfaces::msg::ParameterType;
60 
61 namespace nav2_costmap_2d
62 {
63 
65 {
66  auto node = node_.lock();
67  if (dyn_params_handler_ && node) {
68  node->remove_on_set_parameters_callback(dyn_params_handler_.get());
69  }
70  dyn_params_handler_.reset();
71  for (auto & notifier : observation_notifiers_) {
72  notifier.reset();
73  }
74 }
75 
77 {
78  bool track_unknown_space;
79  double transform_tolerance;
80 
81  // The topics that we'll subscribe to from the parameter server
82  std::string topics_string;
83 
84  declareParameter("enabled", rclcpp::ParameterValue(true));
85  declareParameter("footprint_clearing_enabled", rclcpp::ParameterValue(true));
86  declareParameter("min_obstacle_height", rclcpp::ParameterValue(0.0));
87  declareParameter("max_obstacle_height", rclcpp::ParameterValue(2.0));
88  declareParameter("combination_method", rclcpp::ParameterValue(1));
89  declareParameter("observation_sources", rclcpp::ParameterValue(std::string("")));
90 
91  auto node = node_.lock();
92  if (!node) {
93  throw std::runtime_error{"Failed to lock node"};
94  }
95 
96  node->get_parameter(name_ + "." + "enabled", enabled_);
97  node->get_parameter(name_ + "." + "footprint_clearing_enabled", footprint_clearing_enabled_);
98  node->get_parameter(name_ + "." + "min_obstacle_height", min_obstacle_height_);
99  node->get_parameter(name_ + "." + "max_obstacle_height", max_obstacle_height_);
100  node->get_parameter("track_unknown_space", track_unknown_space);
101  node->get_parameter("transform_tolerance", transform_tolerance);
102  node->get_parameter(name_ + "." + "observation_sources", topics_string);
103  double tf_filter_tolerance = nav2::declare_or_get_parameter(node, name_ + "." +
104  "tf_filter_tolerance", 0.05);
105 
106  int combination_method_param{};
107  node->get_parameter(name_ + "." + "combination_method", combination_method_param);
108  combination_method_ = combination_method_from_int(combination_method_param);
109 
110  dyn_params_handler_ = node->add_on_set_parameters_callback(
111  std::bind(
113  this,
114  std::placeholders::_1));
115 
116  RCLCPP_INFO(
117  logger_,
118  "Subscribed to Topics: %s", topics_string.c_str());
119 
120  rolling_window_ = layered_costmap_->isRolling();
121 
122  if (track_unknown_space) {
123  default_value_ = NO_INFORMATION;
124  } else {
125  default_value_ = FREE_SPACE;
126  }
127 
129  current_ = true;
130  was_reset_ = false;
131 
132  global_frame_ = layered_costmap_->getGlobalFrameID();
133 
134  auto sub_opt = rclcpp::SubscriptionOptions();
135  sub_opt.callback_group = callback_group_;
136 
137  // now we need to split the topics based on whitespace which we can use a stringstream for
138  std::stringstream ss(topics_string);
139 
140  std::string source;
141  while (ss >> source) {
142  // get the parameters for the specific topic
143  double observation_keep_time, expected_update_rate, min_obstacle_height, max_obstacle_height;
144  std::string topic, sensor_frame, data_type;
145  bool inf_is_valid, clearing, marking;
146 
147  declareParameter(source + "." + "topic", rclcpp::ParameterValue(source));
148  declareParameter(source + "." + "sensor_frame", rclcpp::ParameterValue(std::string("")));
149  declareParameter(source + "." + "observation_persistence", rclcpp::ParameterValue(0.0));
150  declareParameter(source + "." + "expected_update_rate", rclcpp::ParameterValue(0.0));
151  declareParameter(source + "." + "data_type", rclcpp::ParameterValue(std::string("LaserScan")));
152  declareParameter(source + "." + "min_obstacle_height", rclcpp::ParameterValue(0.0));
153  declareParameter(source + "." + "max_obstacle_height", rclcpp::ParameterValue(0.0));
154  declareParameter(source + "." + "inf_is_valid", rclcpp::ParameterValue(false));
155  declareParameter(source + "." + "marking", rclcpp::ParameterValue(true));
156  declareParameter(source + "." + "clearing", rclcpp::ParameterValue(false));
157  declareParameter(source + "." + "obstacle_max_range", rclcpp::ParameterValue(2.5));
158  declareParameter(source + "." + "obstacle_min_range", rclcpp::ParameterValue(0.0));
159  declareParameter(source + "." + "raytrace_max_range", rclcpp::ParameterValue(3.0));
160  declareParameter(source + "." + "raytrace_min_range", rclcpp::ParameterValue(0.0));
161 
162  node->get_parameter(name_ + "." + source + "." + "topic", topic);
163  node->get_parameter(name_ + "." + source + "." + "sensor_frame", sensor_frame);
164  node->get_parameter(
165  name_ + "." + source + "." + "observation_persistence",
166  observation_keep_time);
167  node->get_parameter(
168  name_ + "." + source + "." + "expected_update_rate",
169  expected_update_rate);
170  node->get_parameter(name_ + "." + source + "." + "data_type", data_type);
171  node->get_parameter(name_ + "." + source + "." + "min_obstacle_height", min_obstacle_height);
172  node->get_parameter(name_ + "." + source + "." + "max_obstacle_height", max_obstacle_height);
173  node->get_parameter(name_ + "." + source + "." + "inf_is_valid", inf_is_valid);
174  node->get_parameter(name_ + "." + source + "." + "marking", marking);
175  node->get_parameter(name_ + "." + source + "." + "clearing", clearing);
176 
177  if (!(data_type == "PointCloud2" || data_type == "LaserScan")) {
178  RCLCPP_FATAL(
179  logger_,
180  "Only topics that use point cloud2s or laser scans are currently supported");
181  throw std::runtime_error(
182  "Only topics that use point cloud2s or laser scans are currently supported");
183  }
184 
185  // get the obstacle range for the sensor
186  double obstacle_max_range, obstacle_min_range;
187  node->get_parameter(name_ + "." + source + "." + "obstacle_max_range", obstacle_max_range);
188  node->get_parameter(name_ + "." + source + "." + "obstacle_min_range", obstacle_min_range);
189 
190  // get the raytrace ranges for the sensor
191  double raytrace_max_range, raytrace_min_range;
192  node->get_parameter(name_ + "." + source + "." + "raytrace_min_range", raytrace_min_range);
193  node->get_parameter(name_ + "." + source + "." + "raytrace_max_range", raytrace_max_range);
194 
195  topic = joinWithParentNamespace(topic);
196 
197  RCLCPP_DEBUG(
198  logger_,
199  "Creating an observation buffer for source %s, topic %s, frame %s",
200  source.c_str(), topic.c_str(),
201  sensor_frame.c_str());
202 
203  // create an observation buffer
204  observation_buffers_.push_back(
205  std::shared_ptr<ObservationBuffer
206  >(
207  new ObservationBuffer(
208  node, topic, observation_keep_time, expected_update_rate,
209  min_obstacle_height,
210  max_obstacle_height, obstacle_max_range, obstacle_min_range, raytrace_max_range,
211  raytrace_min_range, *tf_,
213  sensor_frame, tf2::durationFromSec(transform_tolerance))));
214 
215  // check if we'll add this buffer to our marking observation buffers
216  if (marking) {
217  marking_buffers_.push_back(observation_buffers_.back());
218  }
219 
220  // check if we'll also add this buffer to our clearing observation buffers
221  if (clearing) {
222  clearing_buffers_.push_back(observation_buffers_.back());
223  }
224 
225  RCLCPP_DEBUG(
226  logger_,
227  "Created an observation buffer for source %s, topic %s, global frame: %s, "
228  "expected update rate: %.2f, observation persistence: %.2f",
229  source.c_str(), topic.c_str(),
230  global_frame_.c_str(), expected_update_rate, observation_keep_time);
231 
232  const auto custom_qos_profile = nav2::qos::SensorDataQoS(50);
233 
234  // create a callback for the topic
235  if (data_type == "LaserScan") {
236  // For Kilted and Older Support from Message Filters API change
237  #if RCLCPP_VERSION_GTE(29, 6, 0)
238  std::shared_ptr<message_filters::Subscriber<sensor_msgs::msg::LaserScan>> sub;
239  #else
240  std::shared_ptr<message_filters::Subscriber<sensor_msgs::msg::LaserScan,
241  rclcpp_lifecycle::LifecycleNode>> sub;
242  #endif
243 
244  // For Kilted compatibility in Message Filters API change
245  #if RCLCPP_VERSION_GTE(29, 6, 0)
246  sub = std::make_shared<message_filters::Subscriber<sensor_msgs::msg::LaserScan>>(
247  node, topic, custom_qos_profile, sub_opt);
248  // For Jazzy compatibility in Message Filters API change
249  #elif RCLCPP_VERSION_GTE(29, 0, 0)
250  sub = std::make_shared<message_filters::Subscriber<sensor_msgs::msg::LaserScan,
251  rclcpp_lifecycle::LifecycleNode>>(
252  std::static_pointer_cast<rclcpp_lifecycle::LifecycleNode>(node),
253  topic, custom_qos_profile, sub_opt);
254  // For Humble and Older compatibility in Message Filters API change
255  #else
256  sub = std::make_shared<message_filters::Subscriber<sensor_msgs::msg::LaserScan,
257  rclcpp_lifecycle::LifecycleNode>>(
258  std::static_pointer_cast<rclcpp_lifecycle::LifecycleNode>(node),
259  topic, custom_qos_profile.get_rmw_qos_profile(), sub_opt);
260  #endif
261 
262  sub->unsubscribe();
263 
264  auto filter = std::make_shared<tf2_ros::MessageFilter<sensor_msgs::msg::LaserScan>>(
265  *sub, *tf_, global_frame_, 50,
266  node->get_node_logging_interface(),
267  node->get_node_clock_interface(),
268  tf2::durationFromSec(transform_tolerance));
269 
270  if (inf_is_valid) {
271  filter->registerCallback(
272  std::bind(
273  &ObstacleLayer::laserScanValidInfCallback, this, std::placeholders::_1,
274  observation_buffers_.back()));
275 
276  } else {
277  filter->registerCallback(
278  std::bind(
279  &ObstacleLayer::laserScanCallback, this, std::placeholders::_1,
280  observation_buffers_.back()));
281  }
282 
283  observation_subscribers_.push_back(sub);
284 
285  observation_notifiers_.push_back(filter);
286  observation_notifiers_.back()->setTolerance(rclcpp::Duration::from_seconds(
287  tf_filter_tolerance));
288 
289  } else {
290  // For Kilted and Older Support from Message Filters API change
291  #if RCLCPP_VERSION_GTE(29, 6, 0)
292  std::shared_ptr<message_filters::Subscriber<sensor_msgs::msg::PointCloud2>> sub;
293  #else
294  std::shared_ptr<message_filters::Subscriber<sensor_msgs::msg::PointCloud2,
295  rclcpp_lifecycle::LifecycleNode>> sub;
296  #endif
297 
298  // For Kilted compatibility in Message Filters API change
299  #if RCLCPP_VERSION_GTE(29, 6, 0)
300  sub = std::make_shared<message_filters::Subscriber<sensor_msgs::msg::PointCloud2>>(
301  node, topic, custom_qos_profile, sub_opt);
302  // For Jazzy compatibility in Message Filters API change
303  #elif RCLCPP_VERSION_GTE(29, 0, 0)
304  sub = std::make_shared<message_filters::Subscriber<sensor_msgs::msg::PointCloud2,
305  rclcpp_lifecycle::LifecycleNode>>(
306  std::static_pointer_cast<rclcpp_lifecycle::LifecycleNode>(node),
307  topic, custom_qos_profile, sub_opt);
308  // For Humble and Older compatibility in Message Filters API change
309  #else
310  sub = std::make_shared<message_filters::Subscriber<sensor_msgs::msg::PointCloud2,
311  rclcpp_lifecycle::LifecycleNode>>(
312  std::static_pointer_cast<rclcpp_lifecycle::LifecycleNode>(node),
313  topic, custom_qos_profile.get_rmw_qos_profile(), sub_opt);
314  #endif
315 
316  sub->unsubscribe();
317 
318  if (inf_is_valid) {
319  RCLCPP_WARN(
320  logger_,
321  "obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.");
322  }
323 
324  auto filter = std::make_shared<tf2_ros::MessageFilter<sensor_msgs::msg::PointCloud2>>(
325  *sub, *tf_, global_frame_, 50,
326  node->get_node_logging_interface(),
327  node->get_node_clock_interface(),
328  tf2::durationFromSec(transform_tolerance));
329 
330  filter->registerCallback(
331  std::bind(
332  &ObstacleLayer::pointCloud2Callback, this, std::placeholders::_1,
333  observation_buffers_.back()));
334 
335  observation_subscribers_.push_back(sub);
336  observation_notifiers_.push_back(filter);
337  }
338 
339  if (sensor_frame != "") {
340  std::vector<std::string> target_frames;
341  target_frames.push_back(global_frame_);
342  target_frames.push_back(sensor_frame);
343  observation_notifiers_.back()->setTargetFrames(target_frames);
344  }
345  }
346 }
347 
348 rcl_interfaces::msg::SetParametersResult
350  std::vector<rclcpp::Parameter> parameters)
351 {
352  std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
353  rcl_interfaces::msg::SetParametersResult result;
354 
355  for (auto parameter : parameters) {
356  const auto & param_type = parameter.get_type();
357  const auto & param_name = parameter.get_name();
358  if (param_name.find(name_ + ".") != 0) {
359  continue;
360  }
361 
362  if (param_type == ParameterType::PARAMETER_DOUBLE) {
363  if (param_name == name_ + "." + "min_obstacle_height") {
364  min_obstacle_height_ = parameter.as_double();
365  } else if (param_name == name_ + "." + "max_obstacle_height") {
366  max_obstacle_height_ = parameter.as_double();
367  }
368  } else if (param_type == ParameterType::PARAMETER_BOOL) {
369  if (param_name == name_ + "." + "enabled" && enabled_ != parameter.as_bool()) {
370  enabled_ = parameter.as_bool();
371  if (enabled_) {
372  current_ = false;
373  }
374  } else if (param_name == name_ + "." + "footprint_clearing_enabled") {
375  footprint_clearing_enabled_ = parameter.as_bool();
376  }
377  } else if (param_type == ParameterType::PARAMETER_INTEGER) {
378  if (param_name == name_ + "." + "combination_method") {
379  combination_method_ = combination_method_from_int(parameter.as_int());
380  }
381  }
382  }
383 
384  result.successful = true;
385  return result;
386 }
387 
388 void
390  sensor_msgs::msg::LaserScan::ConstSharedPtr message,
391  const std::shared_ptr<nav2_costmap_2d::ObservationBuffer> & buffer)
392 {
393  // project the laser into a point cloud
394  sensor_msgs::msg::PointCloud2 cloud;
395  cloud.header = message->header;
396 
397  // project the scan into a point cloud
398  try {
399  projector_.transformLaserScanToPointCloud(message->header.frame_id, *message, cloud, *tf_);
400  } catch (tf2::TransformException & ex) {
401  RCLCPP_WARN(
402  logger_,
403  "High fidelity enabled, but TF returned a transform exception to frame %s: %s",
404  global_frame_.c_str(),
405  ex.what());
406  projector_.projectLaser(*message, cloud);
407  } catch (std::runtime_error & ex) {
408  RCLCPP_WARN(
409  logger_,
410  "transformLaserScanToPointCloud error, it seems the message from laser is malformed."
411  " Ignore this message. what(): %s",
412  ex.what());
413  return;
414  }
415 
416  // buffer the point cloud
417  buffer->lock();
418  buffer->bufferCloud(cloud);
419  buffer->unlock();
420 }
421 
422 void
424  sensor_msgs::msg::LaserScan::ConstSharedPtr raw_message,
425  const std::shared_ptr<nav2_costmap_2d::ObservationBuffer> & buffer)
426 {
427  // Filter positive infinities ("Inf"s) to max_range.
428  float epsilon = 0.0001; // a tenth of a millimeter
429  sensor_msgs::msg::LaserScan message = *raw_message;
430  for (size_t i = 0; i < message.ranges.size(); i++) {
431  float range = message.ranges[i];
432  if (!std::isfinite(range) && range > 0) {
433  message.ranges[i] = message.range_max - epsilon;
434  }
435  }
436 
437  // project the laser into a point cloud
438  sensor_msgs::msg::PointCloud2 cloud;
439  cloud.header = message.header;
440 
441  // project the scan into a point cloud
442  try {
443  projector_.transformLaserScanToPointCloud(message.header.frame_id, message, cloud, *tf_);
444  } catch (tf2::TransformException & ex) {
445  RCLCPP_WARN(
446  logger_,
447  "High fidelity enabled, but TF returned a transform exception to frame %s: %s",
448  global_frame_.c_str(), ex.what());
449  projector_.projectLaser(message, cloud);
450  } catch (std::runtime_error & ex) {
451  RCLCPP_WARN(
452  logger_,
453  "transformLaserScanToPointCloud error, it seems the message from laser is malformed."
454  " Ignore this message. what(): %s",
455  ex.what());
456  return;
457  }
458 
459  // buffer the point cloud
460  buffer->lock();
461  buffer->bufferCloud(cloud);
462  buffer->unlock();
463 }
464 
465 void
467  sensor_msgs::msg::PointCloud2::ConstSharedPtr message,
468  const std::shared_ptr<ObservationBuffer> & buffer)
469 {
470  // buffer the point cloud
471  buffer->lock();
472  buffer->bufferCloud(*message);
473  buffer->unlock();
474 }
475 
476 void
478  double robot_x, double robot_y, double robot_yaw, double * min_x,
479  double * min_y, double * max_x, double * max_y)
480 {
481  std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
482  if (rolling_window_) {
483  updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
484  }
485  if (!enabled_) {
486  return;
487  }
488  useExtraBounds(min_x, min_y, max_x, max_y);
489 
490  bool current = true;
491  std::vector<Observation> observations, clearing_observations;
492 
493  // get the marking observations
494  current = current && getMarkingObservations(observations);
495 
496  // get the clearing observations
497  current = current && getClearingObservations(clearing_observations);
498 
499  // update the global current status
500  current_ = current;
501 
502  // raytrace freespace
503  for (unsigned int i = 0; i < clearing_observations.size(); ++i) {
504  raytraceFreespace(clearing_observations[i], min_x, min_y, max_x, max_y);
505  }
506 
507  // place the new obstacles into a priority queue... each with a priority of zero to begin with
508  for (std::vector<Observation>::const_iterator it = observations.begin();
509  it != observations.end(); ++it)
510  {
511  const Observation & obs = *it;
512 
513  const sensor_msgs::msg::PointCloud2 & cloud = *(obs.cloud_);
514 
515  double sq_obstacle_max_range = obs.obstacle_max_range_ * obs.obstacle_max_range_;
516  double sq_obstacle_min_range = obs.obstacle_min_range_ * obs.obstacle_min_range_;
517 
518  sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
519  sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
520  sensor_msgs::PointCloud2ConstIterator<float> iter_z(cloud, "z");
521 
522  for (; iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z) {
523  double px = *iter_x, py = *iter_y, pz = *iter_z;
524 
525  // if the obstacle is too low, we won't add it
526  if (pz < min_obstacle_height_) {
527  RCLCPP_DEBUG(logger_, "The point is too low");
528  continue;
529  }
530 
531  // if the obstacle is too high or too far away from the robot we won't add it
532  if (pz > max_obstacle_height_) {
533  RCLCPP_DEBUG(logger_, "The point is too high");
534  continue;
535  }
536 
537  // compute the squared distance from the hitpoint to the pointcloud's origin
538  double sq_dist =
539  (px -
540  obs.origin_.x) * (px - obs.origin_.x) + (py - obs.origin_.y) * (py - obs.origin_.y) +
541  (pz - obs.origin_.z) * (pz - obs.origin_.z);
542 
543  // if the point is far enough away... we won't consider it
544  if (sq_dist >= sq_obstacle_max_range) {
545  RCLCPP_DEBUG(logger_, "The point is too far away");
546  continue;
547  }
548 
549  // if the point is too close, do not conisder it
550  if (sq_dist < sq_obstacle_min_range) {
551  RCLCPP_DEBUG(logger_, "The point is too close");
552  continue;
553  }
554 
555  // now we need to compute the map coordinates for the observation
556  unsigned int mx, my;
557  if (!worldToMap(px, py, mx, my)) {
558  RCLCPP_DEBUG(logger_, "Computing map coords failed");
559  continue;
560  }
561 
562  unsigned int index = getIndex(mx, my);
563  costmap_[index] = LETHAL_OBSTACLE;
564  touch(px, py, min_x, min_y, max_x, max_y);
565  }
566  }
567 
568  updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
569 }
570 
571 void
573  double robot_x, double robot_y, double robot_yaw,
574  double * min_x, double * min_y,
575  double * max_x,
576  double * max_y)
577 {
578  if (!footprint_clearing_enabled_) {return;}
579  transformFootprint(robot_x, robot_y, robot_yaw, getFootprint(), transformed_footprint_);
580 
581  for (unsigned int i = 0; i < transformed_footprint_.size(); i++) {
582  touch(transformed_footprint_[i].x, transformed_footprint_[i].y, min_x, min_y, max_x, max_y);
583  }
584 }
585 
586 void
588  nav2_costmap_2d::Costmap2D & master_grid, int min_i, int min_j,
589  int max_i,
590  int max_j)
591 {
592  std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
593  if (!enabled_) {
594  return;
595  }
596 
597  // if not current due to reset, set current now after clearing
598  if (!current_ && was_reset_) {
599  was_reset_ = false;
600  current_ = true;
601  }
602 
603  if (footprint_clearing_enabled_) {
604  setConvexPolygonCost(transformed_footprint_, nav2_costmap_2d::FREE_SPACE);
605  }
606 
607  switch (combination_method_) {
609  updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j);
610  break;
612  updateWithMax(master_grid, min_i, min_j, max_i, max_j);
613  break;
615  updateWithMaxWithoutUnknownOverwrite(master_grid, min_i, min_j, max_i, max_j);
616  break;
617  default: // Nothing
618  break;
619  }
620 }
621 
622 void
623 ObstacleLayer::addStaticObservation(
625  bool marking, bool clearing)
626 {
627  if (marking) {
628  static_marking_observations_.push_back(obs);
629  }
630  if (clearing) {
631  static_clearing_observations_.push_back(obs);
632  }
633 }
634 
635 void
636 ObstacleLayer::clearStaticObservations(bool marking, bool clearing)
637 {
638  if (marking) {
639  static_marking_observations_.clear();
640  }
641  if (clearing) {
642  static_clearing_observations_.clear();
643  }
644 }
645 
646 bool
647 ObstacleLayer::getMarkingObservations(std::vector<Observation> & marking_observations) const
648 {
649  bool current = true;
650  // get the marking observations
651  for (unsigned int i = 0; i < marking_buffers_.size(); ++i) {
652  marking_buffers_[i]->lock();
653  marking_buffers_[i]->getObservations(marking_observations);
654  current = marking_buffers_[i]->isCurrent() && current;
655  marking_buffers_[i]->unlock();
656  }
657  marking_observations.insert(
658  marking_observations.end(),
659  static_marking_observations_.begin(), static_marking_observations_.end());
660  return current;
661 }
662 
663 bool
664 ObstacleLayer::getClearingObservations(std::vector<Observation> & clearing_observations) const
665 {
666  bool current = true;
667  // get the clearing observations
668  for (unsigned int i = 0; i < clearing_buffers_.size(); ++i) {
669  clearing_buffers_[i]->lock();
670  clearing_buffers_[i]->getObservations(clearing_observations);
671  current = clearing_buffers_[i]->isCurrent() && current;
672  clearing_buffers_[i]->unlock();
673  }
674  clearing_observations.insert(
675  clearing_observations.end(),
676  static_clearing_observations_.begin(), static_clearing_observations_.end());
677  return current;
678 }
679 
680 void
682  const Observation & clearing_observation, double * min_x,
683  double * min_y,
684  double * max_x,
685  double * max_y)
686 {
687  double ox = clearing_observation.origin_.x;
688  double oy = clearing_observation.origin_.y;
689  const sensor_msgs::msg::PointCloud2 & cloud = *(clearing_observation.cloud_);
690 
691  // get the map coordinates of the origin of the sensor
692  unsigned int x0, y0;
693  if (!worldToMap(ox, oy, x0, y0)) {
694  RCLCPP_WARN(
695  logger_,
696  "Sensor origin at (%.2f, %.2f) is out of map bounds (%.2f, %.2f) to (%.2f, %.2f). "
697  "The costmap cannot raytrace for it.",
698  ox, oy,
699  origin_x_, origin_y_,
700  origin_x_ + getSizeInMetersX(), origin_y_ + getSizeInMetersY());
701  return;
702  }
703 
704  // we can pre-compute the endpoints of the map outside of the inner loop... we'll need these later
705  double origin_x = origin_x_, origin_y = origin_y_;
706  double map_end_x = origin_x + size_x_ * resolution_;
707  double map_end_y = origin_y + size_y_ * resolution_;
708 
709 
710  touch(ox, oy, min_x, min_y, max_x, max_y);
711 
712  // for each point in the cloud, we want to trace a line from the origin
713  // and clear obstacles along it
714  sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
715  sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
716 
717  for (; iter_x != iter_x.end(); ++iter_x, ++iter_y) {
718  double wx = *iter_x;
719  double wy = *iter_y;
720 
721  // now we also need to make sure that the endpoint we're raytracing
722  // to isn't off the costmap and scale if necessary
723  double a = wx - ox;
724  double b = wy - oy;
725 
726  // the minimum value to raytrace from is the origin
727  if (wx < origin_x) {
728  double t = (origin_x - ox) / a;
729  wx = origin_x;
730  wy = oy + b * t;
731  }
732  if (wy < origin_y) {
733  double t = (origin_y - oy) / b;
734  wx = ox + a * t;
735  wy = origin_y;
736  }
737 
738  // the maximum value to raytrace to is the end of the map
739  if (wx > map_end_x) {
740  double t = (map_end_x - ox) / a;
741  wx = map_end_x - .001;
742  wy = oy + b * t;
743  }
744  if (wy > map_end_y) {
745  double t = (map_end_y - oy) / b;
746  wx = ox + a * t;
747  wy = map_end_y - .001;
748  }
749 
750  // now that the vector is scaled correctly... we'll get the map coordinates of its endpoint
751  unsigned int x1, y1;
752 
753  // check for legality just in case
754  if (!worldToMap(wx, wy, x1, y1)) {
755  continue;
756  }
757 
758  unsigned int cell_raytrace_max_range = cellDistance(clearing_observation.raytrace_max_range_);
759  unsigned int cell_raytrace_min_range = cellDistance(clearing_observation.raytrace_min_range_);
760  MarkCell marker(costmap_, FREE_SPACE);
761  // and finally... we can execute our trace to clear obstacles along that line
762  raytraceLine(marker, x0, y0, x1, y1, cell_raytrace_max_range, cell_raytrace_min_range);
763 
765  ox, oy, wx, wy, clearing_observation.raytrace_max_range_,
766  clearing_observation.raytrace_min_range_, min_x, min_y, max_x,
767  max_y);
768  }
769 }
770 
771 void
773 {
774  for (auto & notifier : observation_notifiers_) {
775  notifier->clear();
776  }
777 
778  // if we're stopped we need to re-subscribe to topics
779  for (unsigned int i = 0; i < observation_subscribers_.size(); ++i) {
780  if (observation_subscribers_[i] != NULL) {
781  observation_subscribers_[i]->subscribe();
782  }
783  }
785 }
786 
787 void
789 {
790  for (unsigned int i = 0; i < observation_subscribers_.size(); ++i) {
791  if (observation_subscribers_[i] != NULL) {
792  observation_subscribers_[i]->unsubscribe();
793  }
794  }
795 }
796 
797 void
799  double ox, double oy, double wx, double wy, double max_range, double min_range,
800  double * min_x, double * min_y, double * max_x, double * max_y)
801 {
802  double dx = wx - ox, dy = wy - oy;
803  double full_distance = hypot(dx, dy);
804  if (full_distance < min_range) {
805  return;
806  }
807  double scale = std::min(1.0, max_range / full_distance);
808  double ex = ox + dx * scale, ey = oy + dy * scale;
809  touch(ex, ey, min_x, min_y, max_x, max_y);
810 }
811 
812 void
814 {
815  resetMaps();
817  current_ = false;
818  was_reset_ = true;
819 }
820 
821 void
823 {
824  for (unsigned int i = 0; i < observation_buffers_.size(); ++i) {
825  if (observation_buffers_[i]) {
826  observation_buffers_[i]->resetLastUpdated();
827  }
828  }
829 }
830 
831 } // namespace nav2_costmap_2d
A QoS profile for best-effort sensor data with a history of 10 messages.
A 2D costmap provides a mapping between points in the world and their associated "costs".
Definition: costmap_2d.hpp:69
unsigned int getIndex(unsigned int mx, unsigned int my) const
Given two map coordinates... compute the associated index.
Definition: costmap_2d.hpp:231
void raytraceLine(ActionType at, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, unsigned int max_length=UINT_MAX, unsigned int min_length=0)
Raytrace a line and apply some action at each step.
Definition: costmap_2d.hpp:476
bool worldToMap(double wx, double wy, unsigned int &mx, unsigned int &my) const
Convert from world coordinates to map coordinates.
Definition: costmap_2d.cpp:291
virtual void updateOrigin(double new_origin_x, double new_origin_y)
Move the origin of the costmap to a new location.... keeping data when it can.
Definition: costmap_2d.cpp:349
bool setConvexPolygonCost(const std::vector< geometry_msgs::msg::Point > &polygon, unsigned char cost_value)
Sets the cost of a convex polygon to a desired value.
Definition: costmap_2d.cpp:405
double getSizeInMetersY() const
Accessor for the y size of the costmap in meters.
Definition: costmap_2d.cpp:561
double getSizeInMetersX() const
Accessor for the x size of the costmap in meters.
Definition: costmap_2d.cpp:556
virtual void resetMaps()
Resets the costmap and static_map to be unknown space.
Definition: costmap_2d.cpp:124
unsigned int cellDistance(double world_dist)
Given distance in the world... convert it to cells.
Definition: costmap_2d.cpp:253
void touch(double x, double y, double *min_x, double *min_y, double *max_x, double *max_y)
virtual void matchSize()
Match the size of the master costmap.
CombinationMethod combination_method_from_int(const int value)
Converts an integer to a CombinationMethod enum and logs on failure.
Abstract class for layered costmap plugin implementations.
Definition: layer.hpp:59
std::string joinWithParentNamespace(const std::string &topic)
Definition: layer.cpp:121
void declareParameter(const std::string &param_name, const rclcpp::ParameterValue &value)
Convenience functions for declaring ROS parameters.
Definition: layer.cpp:76
const std::vector< geometry_msgs::msg::Point > & getFootprint() const
Convenience function for layered_costmap_->getFootprint().
Definition: layer.cpp:70
bool isRolling()
If this costmap is rolling or not.
Takes in point clouds from sensors, transforms them to the desired frame, and stores them.
Stores an observation in terms of a point cloud and the origin of the source.
Definition: observation.hpp:47
Takes in laser and pointcloud data to populate into 2D costmap.
void pointCloud2Callback(sensor_msgs::msg::PointCloud2::ConstSharedPtr message, const std::shared_ptr< nav2_costmap_2d::ObservationBuffer > &buffer)
A callback to handle buffering PointCloud2 messages.
std::vector< std::shared_ptr< nav2_costmap_2d::ObservationBuffer > > marking_buffers_
Used to store observation buffers used for marking obstacles.
virtual void activate()
Activate the layer.
std::vector< std::shared_ptr< tf2_ros::MessageFilterBase > > observation_notifiers_
Used to make sure that transforms are available for each sensor.
bool getMarkingObservations(std::vector< nav2_costmap_2d::Observation > &marking_observations) const
Get the observations used to mark space.
std::string global_frame_
The global frame for the costmap.
bool getClearingObservations(std::vector< nav2_costmap_2d::Observation > &clearing_observations) const
Get the observations used to clear space.
void updateRaytraceBounds(double ox, double oy, double wx, double wy, double max_range, double min_range, double *min_x, double *min_y, double *max_x, double *max_y)
Process update costmap with raytracing the window bounds.
rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr dyn_params_handler_
Dynamic parameters handler.
void laserScanCallback(sensor_msgs::msg::LaserScan::ConstSharedPtr message, const std::shared_ptr< nav2_costmap_2d::ObservationBuffer > &buffer)
A callback to handle buffering LaserScan messages.
void resetBuffersLastUpdated()
triggers the update of observations buffer
std::vector< std::shared_ptr< nav2_costmap_2d::ObservationBuffer > > clearing_buffers_
Used to store observation buffers used for clearing obstacles.
void laserScanValidInfCallback(sensor_msgs::msg::LaserScan::ConstSharedPtr message, const std::shared_ptr< nav2_costmap_2d::ObservationBuffer > &buffer)
A callback to handle buffering LaserScan messages which need filtering to turn Inf values into range_...
std::vector< std::shared_ptr< message_filters::SubscriberBase< rclcpp_lifecycle::LifecycleNode > > > observation_subscribers_
Used for the observation message filters.
void updateFootprint(double robot_x, double robot_y, double robot_yaw, double *min_x, double *min_y, double *max_x, double *max_y)
Clear costmap layer info below the robot's footprint.
virtual void deactivate()
Deactivate the layer.
virtual void updateCosts(nav2_costmap_2d::Costmap2D &master_grid, int min_i, int min_j, int max_i, int max_j)
Update the costs in the master costmap in the window.
rcl_interfaces::msg::SetParametersResult dynamicParametersCallback(std::vector< rclcpp::Parameter > parameters)
Callback executed when a parameter change is detected.
virtual ~ObstacleLayer()
A destructor.
std::vector< std::shared_ptr< nav2_costmap_2d::ObservationBuffer > > observation_buffers_
Used to store observations from various sensors.
virtual void onInitialize()
Initialization process of layer on startup.
double min_obstacle_height_
Max Obstacle Height.
laser_geometry::LaserProjection projector_
Used to project laser scans into point clouds.
double max_obstacle_height_
Max Obstacle Height.
virtual void reset()
Reset this costmap.
virtual void raytraceFreespace(const nav2_costmap_2d::Observation &clearing_observation, double *min_x, double *min_y, double *max_x, double *max_y)
Clear freespace based on one observation.
virtual void updateBounds(double robot_x, double robot_y, double robot_yaw, double *min_x, double *min_y, double *max_x, double *max_y)
Update the bounds of the master costmap by this layer's update dimensions.
void transformFootprint(double x, double y, double theta, const std::vector< geometry_msgs::msg::Point > &footprint_spec, std::vector< geometry_msgs::msg::Point > &oriented_footprint)
Given a pose and base footprint, build the oriented footprint of the robot (list of Points)
Definition: footprint.cpp:112