From a5f548f0d7b537bb5ee5aeb7b18ec76b0aaeeb5e Mon Sep 17 00:00:00 2001 From: duongtd Date: Tue, 20 Oct 2026 13:33:51 +0700 Subject: [PATCH] refactor(depth): DepthCameraObstacleLayer follows the CostmapLayer contract The port wrote LETHAL straight into the master from its stored 3D points and left its own grid empty, as costmap_depth_camera does. Everything CostmapLayer offers on top of the own grid therefore missed the layer: clearArea() (the ClearCostmapRecovery path), reset() (Costmap2DROBOT::resetLayers()), footprint clearing and combination_method all acted on an empty grid, and the next cycle wrote the ghosts back. Cleared cells also stayed on the master until another layer's bounds covered them (the source's B7). The stored points stay the source of truth; the clearing and marking algorithm is unchanged. The own grid now mirrors them cell by cell, the way VoxelLayer keeps a voxel grid next to its 2D grid: - marking sets the column's cell LETHAL, the last point of a column leaving sets it FREE_SPACE, and both touch the bounds, so a cleared cell leaves the master in the same cycle (clear_touches_bounds is gone, always on); - updateCosts() only merges the own grid with combination_method, like ObstacleLayer; combination_method other than 0/1 now means "no effect"; - reset() drops the stored points and buffered observations; - clearArea() follows CostmapLayer::clearArea(): invert_area false clears outside the box and keeps the inside, true clears the inside; - footprint clearing erases the stored columns under the robot; - markings that leave the window are dropped in updateBounds() (B6), and a column whose cell went missing is re-marked; - the layer mutex guards the point map, since ClearCostmapRecovery and resetLayers() reach it from other threads (recursive mutex, held by the recovery around clearArea()). Tests: the two clear_touches_bounds cases become one bounded-update case, and clearArea (both directions), reset and footprint clearing get their own. --- README.md | 21 +- .../depth_camera_obstacle_layer.h | 48 +++-- plugins/depth_camera_obstacle_layer.cpp | 196 ++++++++++++++---- test/depth_camera_obstacle_layer_test.cpp | 67 +++++- 4 files changed, 258 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index bcea5b3..092ed6d 100644 --- a/README.md +++ b/README.md @@ -461,9 +461,10 @@ cần quan sát. Không tăng `max_obstacle_height` vượt khỏi voxel grid m ### 5.6. DepthCameraObstacleLayer -Port của `costmap_depth_camera` (noetic). Layer nhận `PointCloud2` đã lọc của từng depth -camera, giữ các điểm vật cản 3D trong frame global của costmap và ghi `LETHAL` trực tiếp -lên master costmap. Mỗi chu kỳ: +Port thuật toán của `costmap_depth_camera` (noetic). Layer nhận `PointCloud2` đã lọc của từng +depth camera và giữ các điểm vật cản 3D trong frame global của costmap. Lưới riêng của layer +phản chiếu các điểm đó theo từng ô (cột có điểm là `LETHAL`, cột mất điểm cuối cùng thành +`FREE_SPACE`), rồi được gộp lên master như `ObstacleLayer` (`combination_method`). Mỗi chu kỳ: 1. Cloud mới nhất của từng source được biến đổi sang frame global bằng TF **tại đúng stamp của cloud** (chờ tối đa `transform_tolerance`, quá hạn thì bỏ cloud và log lỗi), @@ -476,7 +477,14 @@ lên master costmap. Mỗi chu kỳ: 3. **Đánh dấu:** gom cụm Euclidean (`ec_seg_distance`); cụm có `<= size_of_cluster_rejection` điểm bị bỏ; điểm của cụm còn lại nằm trong khối nhìn và cách mọi mặt khối nhìn hơn 12 cm thì được lưu. -4. Điểm ra ngoài cửa sổ costmap (rolling window) bị bỏ. +4. Điểm ra ngoài cửa sổ costmap (rolling window) bị bỏ; điểm dưới footprint robot bị xóa khi + bật `footprint_clearing_enabled`. + +Mọi ô đổi trạng thái (đánh dấu hoặc xóa) đều được đưa vào vùng cập nhật, nên ô vừa xóa biến +khỏi master ngay trong chu kỳ đó. `reset()` (dùng bởi `Costmap2DROBOT::resetLayers()`) xóa toàn +bộ điểm đã lưu; `clearArea()` (dùng bởi `ClearCostmapRecovery`) xóa điểm theo đúng ngữ nghĩa +của `CostmapLayer::clearArea()`: `invert_area: false` xóa các ô **ngoài** hình chữ nhật và giữ +các ô bên trong, `true` xóa các ô **bên trong**. Tham số chung của layer: @@ -495,10 +503,9 @@ Tham số chung của layer: | `voxel_resolution` | `0.01 m` | Bước lượng tử độ cao của điểm lưu. | | `use_voxelized_observation` | `true` | Gộp voxel 5 cm trước khi xử lý. | | `transform_tolerance` | `0.2 s` | Thời gian chờ TF tại stamp của cloud. | -| `footprint_clearing_enabled` | `true` | Như các layer khác (xem ghi chú bên dưới). | +| `footprint_clearing_enabled` | `true` | Xóa ô và điểm đã lưu nằm dưới footprint robot. | | `combination_method` | `1` | Như các layer khác. | | `use_global_frame_to_mark` | `true` | Chỉ hỗ trợ `true`; `false` báo lỗi. | -| `clear_touches_bounds` | `false` | `true`: điểm bị xóa cũng mở rộng vùng cập nhật để master được reset ngay. | | `debug/stats` | `true` | Log `[debug/stats]` định kỳ: số điểm, số điểm đánh dấu/xóa, TF chờ/bỏ, thời gian. | | `debug/stats_period` | `5.0 s` | Chu kỳ log trên. | @@ -524,8 +531,6 @@ Giới hạn đã biết: hai. - Khối nhìn đối xứng và trùng mép ảnh; dải mép ảnh không có depth (lọc mép, dải stereo bên trái) vẫn được coi là "nhìn thấy trống". -- `reset()`, `clearArea()` và footprint clearing không xóa các điểm đã lưu; layer ghi lại - chúng ở chu kỳ sau. - `DepthCameraData` (ảnh depth) đi tới layer này bị bỏ qua. ### 5.7. InflationLayer diff --git a/include/robot_costmap_2d/depth_camera_obstacle_layer.h b/include/robot_costmap_2d/depth_camera_obstacle_layer.h index 38bdb5a..e989f4d 100644 --- a/include/robot_costmap_2d/depth_camera_obstacle_layer.h +++ b/include/robot_costmap_2d/depth_camera_obstacle_layer.h @@ -3,17 +3,23 @@ * https://github.com/tsengapola/costmap_depth_camera, noetic branch 59b7737, * onto robot_costmap_2d (boost::dll, robot::NodeHandle, tf3). * - * The algorithm is kept as in the source on purpose, so that it can be compared - * A/B against VoxelLayer on the same robot. Only what the host forces is changed: - * - data arrives through handleImpl() instead of a ROS subscriber, and the cloud - * is processed in updateBounds() once TF at its stamp exists (the role of the - * tf2_ros::MessageFilter in the source); - * - getType() is VOXEL_LAYER, the only type SensorGateway feeds sensor data to; - * - no debug publishers and no dynamic_reconfigure (no ROS inside the core); - * - `sensor_frame_is_optical` builds the frustum in a Z-forward optical frame, - * because this robot's TF has no X-forward camera_link; - * - B6: markings that left the rolling window are dropped instead of kept forever. - * `clear_touches_bounds` (B7) is an optional fix, off by default as in the source. + * The clearing and marking algorithm is the source's (kd-tree "seen again" test inside the + * frustums, Euclidean clusters away from the frustum faces). How the result reaches the costmap + * follows the CostmapLayer contract of ObstacleLayer/VoxelLayer instead of the source, which + * wrote LETHAL straight into the master and left its own grid empty: + * - the stored 3D points (pc_3d_map_global_) stay the source of truth, and this layer's own + * grid mirrors them cell by cell: a column with points is LETHAL, a column that loses its + * last point becomes FREE_SPACE, and every such change touches the update bounds, so a + * cleared cell leaves the master in the same cycle (the source's B7); + * - updateCosts() only merges the own grid (combination_method), like ObstacleLayer; + * - reset(), clearArea() and footprint clearing also erase the stored points, so + * Costmap2DROBOT::resetLayers() and ClearCostmapRecovery work on this layer (the source's + * reset() kept its global-mode points, B9). + * Host adaptations: data arrives through handleImpl() and a cloud is processed in + * updateBounds() once TF at its stamp exists (the role of the tf2_ros::MessageFilter); + * getType() is VOXEL_LAYER, the only type SensorGateway feeds sensor data to; no ROS + * publishers or dynamic_reconfigure; `sensor_frame_is_optical` builds the frustum in a Z-forward + * optical frame; markings that leave the rolling window are dropped (B6). *********************************************************************/ #ifndef ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_ #define ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_ @@ -92,8 +98,18 @@ public: void updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) override; void activate() override; void deactivate() override; + /// Drops the stored points and the buffered observations as well as the own grid. void reset() override; + /** + * @brief Same contract as CostmapLayer::clearArea(), applied to the stored points too. + * + * Cells strictly inside (start, end) are kept and the rest is cleared when invert_area is + * false; invert_area true clears the inside instead. Called by ClearCostmapRecovery with the + * layer mutex held (recursive). + */ + void clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area = false) override; + /// SensorGateway only delivers obstacle data to VOXEL_LAYER plugins. LayerType getType() const override { @@ -155,6 +171,14 @@ private: void updateFootprint(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y, double* max_x, double* max_y); bool isValid(int mx, int my) const; + /// Own-grid cell of a stored column; false when it is outside the window or on its edge. + bool columnCell(const std::pair& column, unsigned int& mx, unsigned int& my) const; + /// Drops columns that left the window (B6), frees edge cells, re-marks cells a column lost. + void dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x, double* max_y); + /// The column became empty: erase it, free its own-grid cell and touch the bounds. + std::map, std::map>::iterator eraseColumn( + std::map, std::map>::iterator it, double* min_x, double* min_y, + double* max_x, double* max_y); void logStats(); // (int)(x / res) toward zero and back to the cell corner, exactly as the source stores points. @@ -191,7 +215,6 @@ private: double marking_height_above_ground_ = -100.0; // Additions of this port. - bool clear_touches_bounds_ = false; ///< B7 fix: a cleared point also resets its master cell bool debug_stats_ = true; ///< debug/stats: periodic counters log double debug_stats_period_ = 5.0; ///< [s] @@ -205,6 +228,7 @@ private: std::size_t cloud_points = 0; std::size_t marked = 0; std::size_t cleared = 0; + std::size_t footprint_cleared = 0; ///< columns erased under the robot footprint std::size_t cleared_all_frames = 0; std::size_t bypassed_frames = 0; std::size_t tf_waits = 0; diff --git a/plugins/depth_camera_obstacle_layer.cpp b/plugins/depth_camera_obstacle_layer.cpp index 23515c8..27f6730 100644 --- a/plugins/depth_camera_obstacle_layer.cpp +++ b/plugins/depth_camera_obstacle_layer.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include @@ -55,6 +56,7 @@ #include #include #include +#include namespace robot_costmap_2d { @@ -270,7 +272,9 @@ void DepthCameraObstacleLayer::loadParameters() use_voxelized_observation_ = p.get("use_voxelized_observation", true); transform_tolerance_ = p.get("transform_tolerance", 0.2); const bool use_global_frame_to_mark = p.get("use_global_frame_to_mark", true); - clear_touches_bounds_ = p.get("clear_touches_bounds", false); + if (p.has("clear_touches_bounds")) + robot::log_warning("DepthCameraObstacleLayer %s: clear_touches_bounds is obsolete and ignored: a cleared " + "cell now always resets its master cell\n", name_.c_str()); debug_stats_ = p.get("debug/stats", true); debug_stats_period_ = p.get("debug/stats_period", 5.0); @@ -348,14 +352,14 @@ void DepthCameraObstacleLayer::loadParameters() "ec_seg_distance=%.2f m ec_cluster_min_size=%d size_of_cluster_rejection=%d " "forced_clearing_distance=%.2f m near_blocked_protection=%s (%d pts) " "voxelized_observation=%s transform_tolerance=%.2f s combination_method=%d " - "footprint_clearing=%s clear_touches_bounds=%s marking_height=[%.2f, %.2f] m debug/stats=%s\n", + "footprint_clearing=%s marking_height=[%.2f, %.2f] m debug/stats=%s\n", name_.c_str(), global_frame_.c_str(), rolling_window_ ? "true" : "false", track_unknown_space ? "true" : "false", voxel_resolution_, check_radius_, number_clearing_threshold_, ec_seg_distance_, ec_cluster_min_size_, size_of_cluster_rejection_, forced_clearing_distance_, enable_near_blocked_protection_ ? "true" : "false", number_points_considered_as_blocked_, use_voxelized_observation_ ? "true" : "false", transform_tolerance_, combination_method_, - footprint_clearing_enabled_ ? "true" : "false", clear_touches_bounds_ ? "true" : "false", + footprint_clearing_enabled_ ? "true" : "false", marking_height_under_ground_, marking_height_above_ground_, debug_stats_ ? "on" : "off"); } @@ -502,12 +506,15 @@ bool DepthCameraObstacleLayer::sourceIsCurrent(const Source& source) const void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y, double* max_x, double* max_y) { + // ClearCostmapRecovery and resetLayers() reach the stored points from other threads. + boost::unique_lock lock(*getMutex()); if (rolling_window_) updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2); if (!enabled_) return; const auto start = std::chrono::steady_clock::now(); useExtraBounds(min_x, min_y, max_x, max_y); + dropColumnsOutsideWindow(min_x, min_y, max_x, max_y); bool current = true; std::vector frustums; @@ -638,16 +645,19 @@ void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vectorgetCostmap()->getResolution(); std::vector indices; std::vector sq_distances; - for (auto& column : pc_3d_map_global_) + for (auto column = pc_3d_map_global_.begin(); column != pc_3d_map_global_.end();) { double wx, wy; - intIndexToWorld(wx, wy, column.first.first, column.first.second, resolution); + intIndexToWorld(wx, wy, column->first.first, column->first.second, resolution); // Marked points this far from the robot are out of every frustum. const double pc_dis = std::hypot(wx - robot_x, wy - robot_y); if (pc_dis > kClearingSkipDistance) + { + ++column; continue; + } - auto& heights = column.second; + auto& heights = column->second; for (auto it = heights.begin(), next_it = it; it != heights.end(); it = next_it) { ++next_it; @@ -673,9 +683,10 @@ void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vector(std::round(p.z() * (1 / voxel_resolution_))); if (h_ind > h_max || h_ind < h_min) continue; - auto& slot = pc_3d_map_global_[std::make_pair(mmx, mmy)]; + const std::pair key(mmx, mmy); + unsigned int cx, cy; + if (!columnCell(key, cx, cy)) + continue; // would be dropped as out of the window anyway + auto& slot = pc_3d_map_global_[key]; auto inserted = slot.insert(std::make_pair(h_ind, 0.f)); if (inserted.second) ++stats_.marked; - touch(p.x(), p.y(), min_x, min_y, max_x, max_y); + setCost(cx, cy, LETHAL_OBSTACLE); + double wx, wy; + intIndexToWorld(wx, wy, mmx, mmy, resolution); + touch(wx, wy, min_x, min_y, max_x, max_y); } } @@ -712,6 +730,35 @@ void DepthCameraObstacleLayer::updateFootprint(double robot_x, double robot_y, d transformFootprint(robot_x, robot_y, robot_yaw, getFootprint(), transformed_footprint_); for (const auto& pt : transformed_footprint_) touch(pt.x, pt.y, min_x, min_y, max_x, max_y); + + // updateCosts() frees the footprint in the own grid like ObstacleLayer; the stored points under + // it must go too, or the next marking pass would not bring them back but nothing would ever + // remove them either. + std::vector polygon, cells; + for (const auto& pt : transformed_footprint_) + { + MapLocation loc; + if (!worldToMap(pt.x, pt.y, loc.x, loc.y)) + return; // footprint leaves the window: same give-up as setConvexPolygonCost + polygon.push_back(loc); + } + if (polygon.size() < 3) + return; + convexFillCells(polygon, cells); + std::unordered_set under; + for (const MapLocation& c : cells) + under.insert(getIndex(c.x, c.y)); + for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();) + { + unsigned int mx, my; + if (columnCell(it->first, mx, my) && under.count(getIndex(mx, my))) + { + ++stats_.footprint_cleared; + it = eraseColumn(it, min_x, min_y, max_x, max_y); + } + else + ++it; + } } bool DepthCameraObstacleLayer::isValid(int mx, int my) const @@ -721,42 +768,75 @@ bool DepthCameraObstacleLayer::isValid(int mx, int my) const my <= static_cast(getSizeInCellsY()); } +bool DepthCameraObstacleLayer::columnCell(const std::pair& column, unsigned int& mx, + unsigned int& my) const +{ + double wx, wy; + intIndexToWorld(wx, wy, column.first, column.second, getResolution()); + if (!worldToMap(wx, wy, mx, my)) + return false; + // The +-1 cells guard the rounding of the stored corner, as in the source. + const int x = static_cast(mx), y = static_cast(my); + return isValid(x - 1, y - 1) && isValid(x - 1, y + 1) && isValid(x + 1, y - 1) && isValid(x + 1, y + 1); +} + +std::map, std::map>::iterator DepthCameraObstacleLayer::eraseColumn( + std::map, std::map>::iterator it, double* min_x, double* min_y, + double* max_x, double* max_y) +{ + unsigned int mx, my; + if (columnCell(it->first, mx, my)) + { + setCost(mx, my, FREE_SPACE); + double wx, wy; + intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution()); + touch(wx, wy, min_x, min_y, max_x, max_y); + } + return pc_3d_map_global_.erase(it); +} + +void DepthCameraObstacleLayer::dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x, + double* max_y) +{ + for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();) + { + unsigned int mx, my; + if (columnCell(it->first, mx, my)) + { + // Keep the own grid in step with the points even after matchSize() or a cleared area + // wiped the cell: one O(columns) pass that writes only when something is missing. + if (getCost(mx, my) != LETHAL_OBSTACLE) + { + setCost(mx, my, LETHAL_OBSTACLE); + double wx, wy; + intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution()); + touch(wx, wy, min_x, min_y, max_x, max_y); + } + ++it; + continue; + } + // B6: the source keeps such points forever, so the map and every loop over it grow. + ++stats_.dropped_out_of_window; + double wx, wy; + intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution()); + if (worldToMap(wx, wy, mx, my)) + { + // Still inside the window, on its edge row/column: free that cell as well. + setCost(mx, my, FREE_SPACE); + touch(wx, wy, min_x, min_y, max_x, max_y); + } + it = pc_3d_map_global_.erase(it); + } +} + void DepthCameraObstacleLayer::updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) { + boost::unique_lock lock(*getMutex()); if (!enabled_) return; - unsigned char* master_array = master_grid.getCharMap(); - const double resolution = layered_costmap_->getCostmap()->getResolution(); - for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();) - { - double wx, wy; - intIndexToWorld(wx, wy, it->first.first, it->first.second, resolution); - unsigned int mx, my; - if (!worldToMap(wx, wy, mx, my)) - { - // B6: the source keeps such points forever, so the map and this loop grow all shift. - ++stats_.dropped_out_of_window; - it = pc_3d_map_global_.erase(it); - continue; - } - // The +-1 cells guard the rounding of the stored corner, as in the source. - const int x = static_cast(mx), y = static_cast(my); - if (isValid(x - 1, y - 1) && isValid(x - 1, y + 1) && isValid(x + 1, y - 1) && isValid(x + 1, y + 1) && - !it->second.empty()) - { - const unsigned int index = getIndex(mx, my); - master_array[index] = std::max(LETHAL_OBSTACLE, master_array[index]); - ++it; - } - else - { - it = pc_3d_map_global_.erase(it); - } - } - - // Footprint and combination act on this layer's own grid, which holds no markings: as in the - // source, they do not remove LETHAL already written to the master above. + // The own grid mirrors the stored points (see updateBounds), so the layer merges like + // ObstacleLayer and the master is only changed inside the update bounds. if (footprint_clearing_enabled_) setConvexPolygonCost(transformed_footprint_, FREE_SPACE); @@ -790,10 +870,10 @@ void DepthCameraObstacleLayer::logStats() last_stats_log_ = now; if (debug_stats_ && stats_.cycles > 0) robot::log_info("[debug/stats] DepthCameraObstacleLayer %s: cycles=%zu cloud_pts/cycle=%.0f stored=%zu " - "columns=%zu marked=%zu cleared=%zu clear_all_cycles=%zu bypass_cycles=%zu tf_wait=%zu " - "tf_drop=%zu out_of_window=%zu bounds_ms avg=%.1f max=%.1f\n", + "columns=%zu marked=%zu cleared=%zu footprint_cleared=%zu clear_all_cycles=%zu bypass_cycles=%zu " + "tf_wait=%zu tf_drop=%zu out_of_window=%zu bounds_ms avg=%.1f max=%.1f\n", name_.c_str(), stats_.cycles, static_cast(stats_.cloud_points) / stats_.cycles, - storedPoints(), pc_3d_map_global_.size(), stats_.marked, stats_.cleared, + storedPoints(), pc_3d_map_global_.size(), stats_.marked, stats_.cleared, stats_.footprint_cleared, stats_.cleared_all_frames, stats_.bypassed_frames, stats_.tf_waits, stats_.tf_drops, stats_.dropped_out_of_window, stats_.bounds_ms_sum / stats_.cycles, stats_.bounds_ms_max); stats_ = Stats(); @@ -817,12 +897,40 @@ void DepthCameraObstacleLayer::deactivate() void DepthCameraObstacleLayer::reset() { + boost::unique_lock lock(*getMutex()); deactivate(); resetMaps(); + // The source keeps its global-mode points here (B9), so a reset changed nothing on the master. + pc_3d_map_global_.clear(); + for (const auto& source : sources_) + source->observations.clear(); current_ = true; activate(); } +void DepthCameraObstacleLayer::clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area) +{ + boost::unique_lock lock(*getMutex()); + CostmapLayer::clearArea(start_x, start_y, end_x, end_y, invert_area); + for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();) + { + unsigned int mx, my; + if (columnCell(it->first, mx, my)) + { + // Same test as CostmapLayer::clearArea: keep what it keeps. + const int x = static_cast(mx), y = static_cast(my); + const bool inside = x > start_x && x < end_x && y > start_y && y < end_y; + if (inside != invert_area) + { + ++it; + continue; + } + } + // The own grid cell is already NO_INFORMATION from CostmapLayer::clearArea. + it = pc_3d_map_global_.erase(it); + } +} + // Export factory function static boost::shared_ptr create_depth_camera_obstacle_plugin() { diff --git a/test/depth_camera_obstacle_layer_test.cpp b/test/depth_camera_obstacle_layer_test.cpp index f986ce9..27114aa 100644 --- a/test/depth_camera_obstacle_layer_test.cpp +++ b/test/depth_camera_obstacle_layer_test.cpp @@ -331,32 +331,79 @@ TEST_F(DepthCameraLayerTest, MarkingsThatLeaveTheWindowAreDropped) frame(object()); ASSERT_EQ(layer.storedPoints(), 9u); layer.updateOrigin(10, 10); // the stored cells are outside the layer now - Costmap2D& m = *parent.getCostmap(); - layer.updateCosts(m, 0, 0, m.getSizeInCellsX(), m.getSizeInCellsY()); + update(); EXPECT_EQ(layer.storedPoints(), 0u); } -TEST_F(DepthCameraLayerTest, ClearedPointsDoNotTouchTheBoundsByDefault) +TEST_F(DepthCameraLayerTest, ClearedCellLeavesTheMasterInsideTheBounds) { frame(join(object(), wall())); + ASSERT_EQ(master(), LETHAL_OBSTACLE); // master now holds the object cell frame(wall()); - EXPECT_GT(min_x, 1.5); // only the wall marking touched the bounds + EXPECT_LT(min_x, 1.05); // the cleared object cell is part of this cycle's bounds + // What LayeredCostmap does: reset the master inside the bounds only, then merge the layer there. + Costmap2D& m = *parent.getCostmap(); + int i0, j0, i1, j1; + m.worldToMapEnforceBounds(min_x, min_y, i0, j0); + m.worldToMapEnforceBounds(max_x, max_y, i1, j1); + m.resetMap(i0, j0, i1 + 1, j1 + 1); + layer.updateCosts(m, i0, j0, i1 + 1, j1 + 1); + unsigned int a, b; + ASSERT_TRUE(m.worldToMap(1.01, .11, a, b)); + EXPECT_NE(m.getCost(a, b), LETHAL_OBSTACLE); + ASSERT_TRUE(m.worldToMap(1.61, .11, a, b)); + EXPECT_EQ(m.getCost(a, b), LETHAL_OBSTACLE); } -class DepthCameraTouchTest : public DepthCameraLayerTest +TEST_F(DepthCameraLayerTest, ClearAreaKeepsTheInsideByDefaultAndClearsItWhenInverted) +{ + frame(join(object(), wall())); + ASSERT_EQ(master(), LETHAL_OBSTACLE); + ASSERT_EQ(master(1.61, .11), LETHAL_OBSTACLE); + // Cells strictly inside (55, 35)-(65, 50) hold the object (cell x 60); the wall is at cell x 72. + layer.clearArea(55, 35, 65, 50, false); // CostmapLayer contract: clears OUTSIDE the box + EXPECT_EQ(layer.storedPoints(), 9u); + EXPECT_EQ(master(), LETHAL_OBSTACLE); + EXPECT_NE(master(1.61, .11), LETHAL_OBSTACLE); + layer.clearArea(55, 35, 65, 50, true); // inverted: clears the inside + EXPECT_EQ(layer.storedPoints(), 0u); + EXPECT_NE(master(), LETHAL_OBSTACLE); +} + +TEST_F(DepthCameraLayerTest, ResetDropsTheStoredPointsAndObservations) +{ + frame(join(object(), wall())); + ASSERT_GT(layer.storedPoints(), 0u); + layer.reset(); + EXPECT_EQ(layer.storedPoints(), 0u); + EXPECT_NE(master(), LETHAL_OBSTACLE); + update(); // no new cloud: the buffered observation is gone too, nothing comes back + EXPECT_EQ(layer.storedPoints(), 0u); +} + +class DepthCameraFootprintTest : public DepthCameraLayerTest { protected: void configure(YAML::Node& cfg) override { - cfg["clear_touches_bounds"] = true; + cfg["footprint_clearing_enabled"] = true; + cfg["enable_near_blocked_protection"] = true; // an empty cycle must not clear by itself } }; -TEST_F(DepthCameraTouchTest, ClearedPointsTouchTheBoundsWhenEnabled) +TEST_F(DepthCameraFootprintTest, FootprintClearingErasesThePointsUnderTheRobot) { - frame(join(object(), wall())); - frame(wall()); - EXPECT_LT(min_x, 1.05); // the cleared object cell is reset in the master too + std::vector square(4); + square[0].x = -.3; square[0].y = -.3; + square[1].x = .3; square[1].y = -.3; + square[2].x = .3; square[2].y = .3; + square[3].x = -.3; square[3].y = .3; + parent.setFootprint(square); + frame(object()); + ASSERT_EQ(layer.storedPoints(), 9u); + layer.updateBounds(1.02, .13, 0, &min_x, &min_y, &max_x, &max_y); // robot drives onto it + EXPECT_EQ(layer.storedPoints(), 0u); + EXPECT_NE(master(), LETHAL_OBSTACLE); } TEST(DepthCameraLayerConfig, RejectsUnportedModeAndOutOfRangeValues)