Nav2 Navigation Stack - jazzy  jazzy
ROS 2 Navigation Stack
keepout_filter.cpp
1 /*********************************************************************
2  *
3  * Software License Agreement (BSD License)
4  *
5  * Copyright (c) 2020 Samsung Research Russia
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 the <ORGANIZATION> 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: Alexey Merzlyakov
36  *********************************************************************/
37 
38 #include <string>
39 #include <memory>
40 #include <algorithm>
41 #include "tf2/convert.h"
42 #include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
43 
44 #include "nav2_costmap_2d/costmap_filters/keepout_filter.hpp"
45 #include "nav2_costmap_2d/costmap_filters/filter_values.hpp"
46 
47 namespace nav2_costmap_2d
48 {
49 
51 : filter_info_sub_(nullptr), mask_sub_(nullptr), filter_mask_(nullptr),
52  global_frame_("")
53 {
54 }
55 
57  const std::string & filter_info_topic)
58 {
59  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
60 
61  rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
62  if (!node) {
63  throw std::runtime_error{"Failed to lock node"};
64  }
65 
66  filter_info_topic_ = filter_info_topic;
67  // Setting new costmap filter info subscriber
68  RCLCPP_INFO(
69  logger_,
70  "KeepoutFilter: Subscribing to \"%s\" topic for filter info...",
71  filter_info_topic_.c_str());
72  filter_info_sub_ = node->create_subscription<nav2_msgs::msg::CostmapFilterInfo>(
73  filter_info_topic_, rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
74  std::bind(&KeepoutFilter::filterInfoCallback, this, std::placeholders::_1));
75 
76  global_frame_ = layered_costmap_->getGlobalFrameID();
77 
78  declareParameter("override_lethal_cost", rclcpp::ParameterValue(false));
79  node->get_parameter(name_ + "." + "override_lethal_cost", override_lethal_cost_);
80  declareParameter("lethal_override_cost", rclcpp::ParameterValue(MAX_NON_OBSTACLE));
81  node->get_parameter(name_ + "." + "lethal_override_cost", lethal_override_cost_);
82 
83  // clamp lethal_override_cost_ in case if higher than MAX_NON_OBSTACLE is given
84  lethal_override_cost_ = \
85  std::clamp<unsigned int>(lethal_override_cost_, FREE_SPACE, MAX_NON_OBSTACLE);
86 }
87 
88 void KeepoutFilter::filterInfoCallback(
89  const nav2_msgs::msg::CostmapFilterInfo::SharedPtr msg)
90 {
91  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
92 
93  rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
94  if (!node) {
95  throw std::runtime_error{"Failed to lock node"};
96  }
97 
98  if (!mask_sub_) {
99  RCLCPP_INFO(
100  logger_,
101  "KeepoutFilter: Received filter info from %s topic.", filter_info_topic_.c_str());
102  } else {
103  RCLCPP_WARN(
104  logger_,
105  "KeepoutFilter: New costmap filter info arrived from %s topic. Updating old filter info.",
106  filter_info_topic_.c_str());
107  // Resetting previous subscriber each time when new costmap filter information arrives
108  mask_sub_.reset();
109  }
110 
111  // Checking that base and multiplier are set to their default values
112  if (msg->base != BASE_DEFAULT || msg->multiplier != MULTIPLIER_DEFAULT) {
113  RCLCPP_ERROR(
114  logger_,
115  "KeepoutFilter: For proper use of keepout filter base and multiplier"
116  " in CostmapFilterInfo message should be set to their default values (%f and %f)",
117  BASE_DEFAULT, MULTIPLIER_DEFAULT);
118  }
119 
120  mask_topic_ = msg->filter_mask_topic;
121 
122  // Setting new filter mask subscriber
123  RCLCPP_INFO(
124  logger_,
125  "KeepoutFilter: Subscribing to \"%s\" topic for filter mask...",
126  mask_topic_.c_str());
127  mask_sub_ = node->create_subscription<nav_msgs::msg::OccupancyGrid>(
128  mask_topic_, rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
129  std::bind(&KeepoutFilter::maskCallback, this, std::placeholders::_1));
130 }
131 
132 void KeepoutFilter::maskCallback(
133  const nav_msgs::msg::OccupancyGrid::SharedPtr msg)
134 {
135  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
136 
137  rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
138  if (!node) {
139  throw std::runtime_error{"Failed to lock node"};
140  }
141 
142  if (!filter_mask_) {
143  RCLCPP_INFO(
144  logger_,
145  "KeepoutFilter: Received filter mask from %s topic.", mask_topic_.c_str());
146  } else {
147  RCLCPP_WARN(
148  logger_,
149  "KeepoutFilter: New filter mask arrived from %s topic. Updating old filter mask.",
150  mask_topic_.c_str());
151  filter_mask_.reset();
152  }
153 
154  // Store filter_mask_
155  filter_mask_ = msg;
156  has_updated_data_ = true;
157  x_ = y_ = 0;
158  width_ = msg->info.width;
159  height_ = msg->info.height;
160 }
161 
163  double robot_x, double robot_y, double robot_yaw,
164  double * min_x, double * min_y, double * max_x, double * max_y)
165 {
166  if (!enabled_) {
167  return;
168  }
169 
170  CostmapFilter::updateBounds(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
171 
172  if(!has_updated_data_) {
173  return;
174  }
175 
176  double wx, wy;
177 
178  layered_costmap_->getCostmap()->mapToWorld(x_, y_, wx, wy);
179  *min_x = std::min(wx, *min_x);
180  *min_y = std::min(wy, *min_y);
181 
182  layered_costmap_->getCostmap()->mapToWorld(x_ + width_, y_ + height_, wx, wy);
183  *max_x = std::max(wx, *max_x);
184  *max_y = std::max(wy, *max_y);
185 
186  has_updated_data_ = false;
187 }
188 
190  nav2_costmap_2d::Costmap2D & master_grid,
191  int min_i, int min_j, int max_i, int max_j,
192  const geometry_msgs::msg::Pose2D & pose)
193 {
194  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
195 
196  if (!filter_mask_) {
197  // Show warning message every 2 seconds to not litter an output
198  RCLCPP_WARN_THROTTLE(
199  logger_, *(clock_), 2000,
200  "KeepoutFilter: Filter mask was not received");
201  return;
202  }
203 
204  tf2::Transform tf2_transform;
205  tf2_transform.setIdentity(); // initialize by identical transform
206  int mg_min_x, mg_min_y; // masger_grid indexes of bottom-left window corner
207  int mg_max_x, mg_max_y; // masger_grid indexes of top-right window corner
208 
209  const std::string mask_frame = filter_mask_->header.frame_id;
210 
211  if (mask_frame != global_frame_) {
212  // Filter mask and current layer are in different frames:
213  // prepare frame transformation if mask_frame != global_frame_
214  geometry_msgs::msg::TransformStamped transform;
215  try {
216  transform = tf_->lookupTransform(
217  mask_frame, global_frame_, tf2::TimePointZero,
219  } catch (tf2::TransformException & ex) {
220  RCLCPP_ERROR(
221  logger_,
222  "KeepoutFilter: Failed to get costmap frame (%s) "
223  "transformation to mask frame (%s) with error: %s",
224  global_frame_.c_str(), mask_frame.c_str(), ex.what());
225  return;
226  }
227  tf2::fromMsg(transform.transform, tf2_transform);
228 
229  mg_min_x = min_i;
230  mg_min_y = min_j;
231  mg_max_x = max_i;
232  mg_max_y = max_j;
233  } else {
234  // Filter mask and current layer are in the same frame:
235  // apply the following optimization - iterate only in overlapped
236  // (min_i, min_j)..(max_i, max_j) & filter_mask_ area.
237  //
238  // filter_mask_
239  // *----------------------------*
240  // | |
241  // | |
242  // | (2) |
243  // *-----+-------* |
244  // | |///////|<- overlapped area |
245  // | |///////| to iterate in |
246  // | *-------+--------------------*
247  // | (1) |
248  // | |
249  // *-------------*
250  // master_grid (min_i, min_j)..(max_i, max_j) window
251  //
252  // ToDo: after costmap rotation will be added, this should be re-worked.
253 
254  double wx, wy; // world coordinates
255 
256  // Calculating bounds corresponding to bottom-left overlapping (1) corner
257  // filter_mask_ -> master_grid indexes conversion
258  const double half_cell_size = 0.5 * filter_mask_->info.resolution;
259  wx = filter_mask_->info.origin.position.x + half_cell_size;
260  wy = filter_mask_->info.origin.position.y + half_cell_size;
261  master_grid.worldToMapNoBounds(wx, wy, mg_min_x, mg_min_y);
262  // Calculation of (1) corner bounds
263  if (mg_min_x >= max_i || mg_min_y >= max_j) {
264  // There is no overlapping. Do nothing.
265  return;
266  }
267  mg_min_x = std::max(min_i, mg_min_x);
268  mg_min_y = std::max(min_j, mg_min_y);
269 
270  // Calculating bounds corresponding to top-right window (2) corner
271  // filter_mask_ -> master_grid intexes conversion
272  wx = filter_mask_->info.origin.position.x +
273  filter_mask_->info.width * filter_mask_->info.resolution + half_cell_size;
274  wy = filter_mask_->info.origin.position.y +
275  filter_mask_->info.height * filter_mask_->info.resolution + half_cell_size;
276  master_grid.worldToMapNoBounds(wx, wy, mg_max_x, mg_max_y);
277  // Calculation of (2) corner bounds
278  if (mg_max_x <= min_i || mg_max_y <= min_j) {
279  // There is no overlapping. Do nothing.
280  return;
281  }
282  mg_max_x = std::min(max_i, mg_max_x);
283  mg_max_y = std::min(max_j, mg_max_y);
284  }
285 
286  // unsigned<-signed conversions.
287  unsigned int mg_min_x_u = static_cast<unsigned int>(mg_min_x);
288  unsigned int mg_min_y_u = static_cast<unsigned int>(mg_min_y);
289  unsigned int mg_max_x_u = static_cast<unsigned int>(mg_max_x);
290  unsigned int mg_max_y_u = static_cast<unsigned int>(mg_max_y);
291 
292  // Let's find the pose's cost if we are allowed to override the lethal cost
293  bool is_pose_lethal = false;
294  if (override_lethal_cost_) {
295  geometry_msgs::msg::Pose2D mask_pose;
296  if (transformPose(global_frame_, pose, filter_mask_->header.frame_id, mask_pose)) {
297  unsigned int mask_robot_i, mask_robot_j;
298  if (worldToMask(filter_mask_, mask_pose.x, mask_pose.y, mask_robot_i, mask_robot_j)) {
299  auto data = getMaskCost(filter_mask_, mask_robot_i, mask_robot_j);
300  is_pose_lethal = (data == INSCRIBED_INFLATED_OBSTACLE || data == LETHAL_OBSTACLE);
301  if (is_pose_lethal) {
302  RCLCPP_WARN_THROTTLE(
303  logger_, *(clock_), 2000,
304  "KeepoutFilter: Pose is in keepout zone, reducing cost override to navigate out.");
305  }
306  }
307  }
308 
309  // If in lethal space or just exited lethal space,
310  // we need to update all possible spaces touched during this state
311  if (is_pose_lethal || (last_pose_lethal_ && !is_pose_lethal)) {
312  lethal_state_update_min_x_ = std::min(mg_min_x_u, lethal_state_update_min_x_);
313  mg_min_x_u = lethal_state_update_min_x_;
314  lethal_state_update_min_y_ = std::min(mg_min_y_u, lethal_state_update_min_y_);
315  mg_min_y_u = lethal_state_update_min_y_;
316  lethal_state_update_max_x_ = std::max(mg_max_x_u, lethal_state_update_max_x_);
317  mg_max_x_u = lethal_state_update_max_x_;
318  lethal_state_update_max_y_ = std::max(mg_max_y_u, lethal_state_update_max_y_);
319  mg_max_y_u = lethal_state_update_max_y_;
320  } else {
321  // If out of lethal space, reset managed lethal state sizes
322  lethal_state_update_min_x_ = master_grid.getSizeInCellsX();
323  lethal_state_update_min_y_ = master_grid.getSizeInCellsY();
324  lethal_state_update_max_x_ = 0u;
325  lethal_state_update_max_y_ = 0u;
326  }
327  }
328 
329  unsigned int i, j; // master_grid iterators
330  unsigned int index; // corresponding index of master_grid
331  double gl_wx, gl_wy; // world coordinates in a global_frame_
332  double msk_wx, msk_wy; // world coordinates in a mask_frame
333  unsigned int mx, my; // filter_mask_ coordinates
334  unsigned char data, old_data; // master_grid element data
335 
336  // Main master_grid updating loop
337  // Iterate in costmap window by master_grid indexes
338  unsigned char * master_array = master_grid.getCharMap();
339  for (i = mg_min_x_u; i < mg_max_x_u; i++) {
340  for (j = mg_min_y_u; j < mg_max_y_u; j++) {
341  index = master_grid.getIndex(i, j);
342  old_data = master_array[index];
343  // Calculating corresponding to (i, j) point at filter_mask_:
344  // Get world coordinates in global_frame_
345  master_grid.mapToWorld(i, j, gl_wx, gl_wy);
346  if (mask_frame != global_frame_) {
347  // Transform (i, j) point from global_frame_ to mask_frame
348  tf2::Vector3 point(gl_wx, gl_wy, 0);
349  point = tf2_transform * point;
350  msk_wx = point.x();
351  msk_wy = point.y();
352  } else {
353  // In this case master_grid and filter-mask are in the same frame
354  msk_wx = gl_wx;
355  msk_wy = gl_wy;
356  }
357  // Get mask coordinates corresponding to (i, j) point at filter_mask_
358  if (worldToMask(filter_mask_, msk_wx, msk_wy, mx, my)) {
359  data = getMaskCost(filter_mask_, mx, my);
360  // Update if mask_ data is valid and greater than existing master_grid's one
361  if (data == NO_INFORMATION) {
362  continue;
363  }
364 
365  if (data > old_data || old_data == NO_INFORMATION) {
366  if (override_lethal_cost_ && is_pose_lethal) {
367  master_array[index] = lethal_override_cost_;
368  } else {
369  master_array[index] = data;
370  }
371  }
372  }
373  }
374  }
375 
376  last_pose_lethal_ = is_pose_lethal;
377 }
378 
380 {
381  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
382 
383  filter_info_sub_.reset();
384  mask_sub_.reset();
385 }
386 
388 {
389  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
390 
391  if (filter_mask_) {
392  return true;
393  }
394  return false;
395 }
396 
397 } // namespace nav2_costmap_2d
398 
399 #include "pluginlib/class_list_macros.hpp"
A 2D costmap provides a mapping between points in the world and their associated "costs".
Definition: costmap_2d.hpp:68
void mapToWorld(unsigned int mx, unsigned int my, double &wx, double &wy) const
Convert from map coordinates to world coordinates.
Definition: costmap_2d.cpp:279
unsigned int getIndex(unsigned int mx, unsigned int my) const
Given two map coordinates... compute the associated index.
Definition: costmap_2d.hpp:221
unsigned char * getCharMap() const
Will return a pointer to the underlying unsigned char array used as the costmap.
Definition: costmap_2d.cpp:259
void worldToMapNoBounds(double wx, double wy, int &mx, int &my) const
Convert from world coordinates to map coordinates without checking for legal bounds.
Definition: costmap_2d.cpp:315
unsigned int getSizeInCellsX() const
Accessor for the x size of the costmap in cells.
Definition: costmap_2d.cpp:514
unsigned int getSizeInCellsY() const
Accessor for the y size of the costmap in cells.
Definition: costmap_2d.cpp:519
bool worldToMask(nav_msgs::msg::OccupancyGrid::ConstSharedPtr filter_mask, double wx, double wy, unsigned int &mx, unsigned int &my) const
: Convert from world coordinates to mask coordinates. Similar to Costmap2D::worldToMap() method but w...
bool transformPose(const std::string global_frame, const geometry_msgs::msg::Pose2D &global_pose, const std::string mask_frame, geometry_msgs::msg::Pose2D &mask_pose) const
: Transforms robot pose from current layer frame to mask frame
std::string filter_info_topic_
: Name of costmap filter info topic
std::string mask_topic_
: Name of filter mask topic
tf2::Duration transform_tolerance_
: mask_frame->global_frame_ transform tolerance
unsigned char getMaskCost(nav_msgs::msg::OccupancyGrid::ConstSharedPtr filter_mask, const unsigned int mx, const unsigned int &my) const
Get the cost of a cell in the filter mask.
mutex_t * getMutex()
: returns pointer to a mutex
void updateBounds(double robot_x, double robot_y, double robot_yaw, double *min_x, double *min_y, double *max_x, double *max_y) override
Update the bounds of the master costmap by this layer's update dimensions.
Reads in a keepout mask and marks keepout regions in the map to prevent planning or control in restri...
void process(nav2_costmap_2d::Costmap2D &master_grid, int min_i, int min_j, int max_i, int max_j, const geometry_msgs::msg::Pose2D &pose)
Process the keepout layer at the current pose / bounds / grid.
void resetFilter()
Reset the costmap filter / topic / info.
void initializeFilter(const std::string &filter_info_topic)
Initialize the filter and subscribe to the info topic.
bool isActive()
If this filter is active.
void updateBounds(double robot_x, double robot_y, double robot_yaw, double *min_x, double *min_y, double *max_x, double *max_y) override
Update the bounds of the master costmap by this layer's update dimensions.
Abstract class for layered costmap plugin implementations.
Definition: layer.hpp:59
void declareParameter(const std::string &param_name, const rclcpp::ParameterValue &value)
Convenience functions for declaring ROS parameters.
Definition: layer.cpp:76
Costmap2D * getCostmap()
Get the costmap pointer to the master costmap.