costmap_2d详解5:static_layer.cpp分析

本文详细解析了ROS中Costmap2D的静态地图层工作原理,包括关键变量的作用,初始化过程,地图数据的接收与处理,以及如何更新成本地图和边界。介绍了如何通过配置参数调整地图的致命成本阈值、未知区域的成本值等。

关键变量

  std::string global_frame_;  //global_costmap时为map, local_costmap时为odom_combined
  std::string map_frame_; 
  bool subscribe_to_updates_;
  bool map_received_;
  bool has_updated_data_;

/*
*在接收到地图时,x_, y_被置为0,width_, height_ 被设为地图宽高
*/
  unsigned int x_, y_, width_, height_;
  bool track_unknown_space_; //默认没有配置,使用true
  bool use_maximum_;  //false
  bool first_map_only_;      //false
  bool trinary_costmap_; //true
  ros::Subscriber map_sub_, map_update_sub_;
  unsigned char* costmap_; //这个变量是从Costmap2D 类中继承来的,是一个指针
   //致命cost 阈值,使用默认的为100,未知的区域,cost 值为255
  unsigned char lethal_threshold_, unknown_cost_value_;
  dynamic_reconfigure::Server<costmap_2d::GenericPluginConfig> *dsrv_;

关键代码

/*该函数是虚函数,是从Layer 类中继承来的,是在costmap_2d_ros.cpp 中

*plugin->initialize(layered_costmap_, name + "/" + pname, &tf_); 调用的

*/

void StaticLayer::onInitialize()
{
  ros::NodeHandle nh("~/" + name_), g_nh;
  current_ = true;
  //global_costmap时为map, local_costmap时为odom_combined
  global_frame_ = layered_costmap_->getGlobalFrameID();

  std::string map_topic;
  nh.param("map_topic", map_topic, std::string("map"));
  nh.param("first_map_only", first_map_only_, false);
  nh.param("subscribe_to_updates", subscribe_to_updates_, false);

  //静态地图层中没有配置,使用默认的
  nh.param("track_unknown_space", track_unknown_space_, true);
  nh.param("use_maximum", use_maximum_, false);

  int temp_lethal_threshold, temp_unknown_cost_value;

  //致命cost 阈值,使用默认的为100
  nh.param("lethal_cost_threshold", temp_lethal_threshold, int(100));

  //未知的区域,cost 值为255
  nh.param("unknown_cost_value", temp_unknown_cost_value, int(-1));

 //三倍的costmap??默认没有配置,为true
  nh.param("trinary_costmap", trinary_costmap_, true);

  lethal_threshold_ = std::max(std::min(temp_lethal_threshold, 100), 0);
  unknown_cost_value_ = temp_unknown_cost_value;

  // Only resubscribe if topic has changed
  if (map_sub_.getTopic() != ros::names::resolve(map_topic))
  {
//从/map中订阅地图数据,并在回调函数中使用
    map_sub_ = g_nh.subscribe(map_topic, 1, &StaticLayer::incomingMap, this);
    map_received_ = false;
    has_updated_data_ = false;


  dsrv_ = new dynamic_reconfigure::Server<costmap_2d::GenericPluginConfig>(nh);
  dynamic_reconfigure::Server<costmap_2d::GenericPluginConfig>::CallbackType cb = boost::bind(&StaticLayer::reconfigureCB, this, _1, _2);
  dsrv_->setCallback(cb);

}

void StaticLayer::incomingMap(const nav_msgs::OccupancyGridConstPtr& new_map)
{
//从地图消息中获取地图的宽和高
  unsigned int size_x = new_map->info.width, size_y = new_map->info.height;

  //判断master costmap地图是否发生变化
  Costmap2D* master = layered_costmap_->getCostmap();
  if (!layered_costmap_->isRolling() && (master->getSizeInCellsX() != size_x ||
      master->getSizeInCellsY() != size_y ||
      master->getResolution() != new_map->info.resolution ||
      master->getOriginX() != new_map->info.origin.position.x ||
      master->getOriginY() != new_map->info.origin.position.y ||
      !layered_costmap_->isSizeLocked()))
  {

// 如果master costmap 层发生变化,就更新master costmap 范围
    layered_costmap_->resizeMap(size_x, size_y, new_map->info.resolution, new_map->info.origin.position.x,new_map->info.origin.position.y, true);

  }
 //一开始size_x_为0,所以会进入并仅仅更新static costmap 层
  else if (size_x_ != size_x || size_y_ != size_y ||
           resolution_ != new_map->info.resolution ||
           origin_x_ != new_map->info.origin.position.x ||
           origin_y_ != new_map->info.origin.position.y)
  {
   //仅更新static costmap 层信息
    resizeMap(size_x, size_y, new_map->info.resolution,
              new_map->info.origin.position.x, new_map->info.origin.position.y);
  }
  /*size_x_,size_y_是从Costmap2D类中继承过来的
  * 此时size_x_,size_y_,resolution_,origin_x_,origin_y_
  * 都已经变成map 的地图的范围等信息了
  */
  unsigned int index = 0;

  //根据新地图中的数据来更新costmap 的值,
  //将图片的像素值转换成代价值了,具体转换可以看interpretValue函数
  for (unsigned int i = 0; i < size_y; ++i)
  {
    for (unsigned int j = 0; j < size_x; ++j)
    {
      //地图传来的值为-1(即255),0 和100
      unsigned char value = new_map->data[index];
      //这个变量是从Costmap2D 类中继承来的,是一个指针,具体指向哪里呢?
      costmap_[index] = interpretValue(value);
      ++index;
    }
  }
  map_frame_ = new_map->header.frame_id;
  x_ = y_ = 0;
  width_ = size_x_;  //这个是以像素坐标系(地图左下角)为参考的坐标,是int类型
  height_ = size_y_;
  map_received_ = true;
  has_updated_data_ = true;

  // shutdown the map subscrber if firt_map_only_ flag is on
  if (first_map_only_)
  {
    ROS_INFO("Shutting down the map subscriber. first_map_only flag is on");
    map_sub_.shutdown();
  }
}


 

unsigned char StaticLayer::interpretValue(unsigned char value)
{
  // check if the static value is above the unknown or lethal thresholds
  // 实际上就是高于一个阈值lethal_threshold那么就认为是障碍物
  // 没有信息的就认为是未探测的区域
  // 否则为自由空间,true, -1,
  if (track_unknown_space_ && value == unknown_cost_value_)
  {
    //map数据为-1 时会进入这里
    return NO_INFORMATION;
  }
  else if (!track_unknown_space_ && value == unknown_cost_value_)
    return FREE_SPACE;
  // map数据为100 时,>=100 就是致命的障碍物,会进入这里
  else if (value >= lethal_threshold_)
    return LETHAL_OBSTACLE;
  else if (trinary_costmap_)
    return FREE_SPACE;
  // map数据为0 时进入这里
  double scale = (double) value / lethal_threshold_;
  return scale * LETHAL_OBSTACLE;
}

 

/*作用:

 * 参数: robot_x, robot_y, robot_yaw

*min_x, min_y,max_x, max_y 初始值min_x=min_y=1e30,max_x=max_y=-1e30

*返回:min_x, min_y,max_x, max_y为地图的范围,是以世界坐标系(map)为参考的坐标,double类型

*/

void StaticLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,double* max_x, double* max_y)
{
  //传过来的参数 min_x=min_y=1e30,max_x=max_y=-1e30
  if( !layered_costmap_->isRolling() ){
    if (!map_received_ || !(has_updated_data_ || has_extra_bounds_))
      return;
  }
  //初始化边界
  useExtraBounds(min_x, min_y, max_x, max_y);
  double wx, wy;

  /*计算静态costmap地图左下角像素的坐标*/
  mapToWorld(x_, y_, wx, wy);
  *min_x = std::min(wx, *min_x);
  *min_y = std::min(wy, *min_y);

  /*计算静态costmap地图右上角像素的坐标*/
  mapToWorld(x_ + width_, y_ + height_, wx, wy);
  *max_x = std::max(wx, *max_x);
  *max_y = std::max(wy, *max_y);

  has_updated_data_ = false;

}

/*作用:用static costmap 的值更新master costmap 的值

*参数:master_grid: 是master costmap 地图

* min_i,min_j,max_i,max_j 是该master costmap 地图的范围,以像素坐标表示

*/
 

void StaticLayer::updateCosts(costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j)
{

  if (!layered_costmap_->isRolling())
  {
    if (!use_maximum_)
/*
 *静态costmap 会进入这里面,会获取static costmap 的cost 值,然后更新master costmap
 *static costmap 的cost 值是在incomingMap函数中处理初始化的,该函数在costmap_2d 中实现
*/
      updateWithTrueOverwrite(master_grid, min_i, min_j, max_i, max_j);
    else
      updateWithMax(master_grid, min_i, min_j, max_i, max_j);

  }

}

 

<think>我们正在解决编译时找不到`nav2_costmap_2d/costmap_layer.hpp`文件的问题。根据错误信息,这通常是由以下原因引起的: 1. **缺少依赖安装**:可能没有安装`nav2_costmap_2d`包或其依赖。 2. **头文件路径未包含**:在编译时,CMakeLists.txt中未正确包含`nav2_costmap_2d`的头文件路径。 3. **工作空间未正确配置**:可能未正确source工作空间或者未正确构建工作空间。 ### 解决方案步骤: #### 步骤1:确保已安装`nav2_costmap_2d`包 在ROS2中,`nav2_costmap_2d`是Navigation2的一部分。如果你是通过源码安装的Navigation2,请确保已正确编译。如果是通过二进制包安装,请检查是否已安装。 对于二进制安装(以Foxy为例): ```bash sudo apt install ros-foxy-nav2-costmap-2d ``` 对于源码安装,请确保在克隆Navigation2源码后,已经构建并安装了`nav2_costmap_2d`。 #### 步骤2:在`CMakeLists.txt`中添加依赖和头文件路径 在需要使用`nav2_costmap_2d`的包的`CMakeLists.txt`中,确保已经添加了以下内容: 1. 在`find_package`中添加`nav2_costmap_2d`: ```cmake find_package(ament_cmake REQUIRED) find_package(nav2_costmap_2d REQUIRED) ``` 2. 包含头文件目录: ```cmake include_directories( include ${nav2_costmap_2d_INCLUDE_DIRS} ) ``` 3. 在链接库时,将`nav2_costmap_2d`添加到`ament_target_dependencies`或`target_link_libraries`: ```cmake ament_target_dependencies(your_target nav2_costmap_2d ) ``` 或者 ```cmake target_link_libraries(your_target ${nav2_costmap_2d_LIBRARIES} ) ``` #### 步骤3:重新编译工作空间 在修改`CMakeLists.txt`后,需要重新编译工作空间: ```bash colcon build --symlink-install source install/setup.bash ``` #### 步骤4:检查头文件实际路径 如果问题仍然存在,可以检查`nav2_costmap_2d`包的头文件是否实际存在于你的工作空间中。例如,在安装目录中查找: ```bash find install/ -name "costmap_layer.hpp" ``` 如果该文件存在,请确保在`CMakeLists.txt`中正确包含了其所在路径。通常,通过`find_package`后,使用`include_directories(${nav2_costmap_2d_INCLUDE_DIRS})`即可。 #### 步骤5:环境变量设置 确保你的工作空间已经正确source。在每次打开新终端时,需要运行: ```bash source /opt/ros/foxy/setup.bash # 根据你的ROS2发行版调整 source ~/your_ws/install/setup.bash ``` ### 相关问题 1. 如何在ROS2中正确设置CMakeLists.txt以包含外部包的头文件? 2. 如何检查ROS2包的头文件路径? 3. 在ROS2中,如何安装Navigation2的二进制包? 4. 如何通过源码构建Navigation2? </think>### 解决找不到 `nav2_costmap_2d/costmap_layer.hpp` 文件的完整指南 #### 🔍 问题原因分析 该错误表明编译器无法定位 `nav2_costmap_2d` 包的头文件,主要原因包括: 1. **依赖缺失**:未安装 `nav2_costmap_2d` 包或其依赖项[^1] 2. **路径配置错误**:CMakeLists.txt 中未正确包含头文件路径 3. **编译顺序问题**:未优先编译Navigation2核心组件 4. **ROS版本不匹配**:代码与当前ROS2发行版兼容性问题 --- ### 📝 逐步解决方案 #### 步骤1:安装必要依赖包 ```bash # 安装Navigation2核心组件 sudo apt install ros-$ROS_DISTRO-navigation2 ros-$ROS_DISTRO-nav2-bringup # 安装costmap_2d专用包 sudo apt install ros-$ROS_DISTRO-nav2-costmap-2d ros-$ROS_DISTRO-nav2-common # 验证安装 apt list --installed | grep nav2-costmap-2d ``` #### 步骤2:修复CMakeLists.txt配置 在您的 `CMakeLists.txt` 中添加以下关键配置: ```cmake # 添加find_package依赖 find_package(ament_cmake REQUIRED) find_package(nav2_costmap_2d REQUIRED) # 关键声明 # 包含头文件路径 include_directories( include ${nav2_costmap_2d_INCLUDE_DIRS} # 引用包的头文件路径 ) # 链接库文件 target_link_libraries(your_node ${nav2_costmap_2d_LIBRARIES} ) ``` #### 步骤3:更新package.xml 在包的 `package.xml` 中添加: ```xml <depend>nav2_costmap_2d</depend> <depend>nav2_common</depend> ``` #### 步骤4:清理并重建工作空间 ```bash # 清理旧编译文件 rm -rf build install log # 重建工作空间(关键参数) colcon build --symlink-install --packages-up-to your_package # 更新环境 source install/local_setup.bash ``` #### 步骤5:验证头文件位置 检查头文件是否存在于标准路径: ```bash find /opt/ros/$ROS_DISTRO -name costmap_layer.hpp # 预期输出:/opt/ros/foxy/include/nav2_costmap_2d/costmap_layer.hpp ``` --- ### ⚠️ 常见问题处理 **场景1**:使用源码编译Navigation2时 ```bash # 在colcon工作空间中克隆源码 git clone https://github.com/ros-planning/navigation2.git src/navigation2 # 优先编译navigation2核心 colcon build --symlink-install --packages-select nav2_costmap_2d ``` **场景2**:ROS版本兼容性问题 - Galactic/Humble用户需使用: ```cpp #include "nav2_costmap_2d/costmap_layer.hpp" // 正确路径 ``` - 替代旧版ROS中的: ```cpp #include "costmap_2d/costmap_layer.hpp" // 已废弃路径 ``` --- ### 📚 技术原理 `costmap_layer.hpp` 定义了分层代价地图的核心接口: ```cpp class CostmapLayer : public Layer { public: virtual void updateBounds(double robot_x, double robot_y, ...) = 0; virtual void updateCosts(nav2_costmap_2d::Costmap2D& master_grid, ...) = 0; }; ``` 该类实现了代价地图的层叠更新机制[^1],通过 `updateBounds()` 定义图层影响范围,`updateCosts()` 合并到主代价地图中[^2]。 --- ### 🔧 高级调试 若仍失败,手动指定头文件路径: ```cmake # 在CMakeLists.txt中添加 include_directories(/opt/ros/$ROS_DISTRO/include) ``` 使用编译日志调试: ```bash colcon build --cmake-args -DCMAKE_VERBOSE_MAKEFILE=ON ``` --- ### 📊 相关文件结构 ``` /opt/ros/foxy/ ├── include/ │ └── nav2_costmap_2d/ │ ├── costmap_layer.hpp # 缺失的头文件 │ ├── costmap_2d.hpp │ └── layer.hpp └── lib/ └── libnav2_costmap_2d.so # 链接库 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值