From 63707c968ca4d997c4c82af214ed775c67ceb472 Mon Sep 17 00:00:00 2001 From: duongtd Date: Thu, 15 Oct 2026 16:58:23 +0700 Subject: [PATCH] fix(depth): free voxels on clearArea/footprint, accept far returns as behind clearArea and footprint clearing only wrote the 2D cells, so the voxels and evidence points stayed MARKED and the next column update brought the phantom back. VoxelLayer now frees the voxel column and its evidence in both paths (footprint only for observed_volume; legacy unchanged). A valid return deeper than depth_valid_max_z_m kept every evidence point unknown, so phantoms with nothing within 3 m behind never cleared. New key depth_far_return_is_behind (default false) counts such a return as behind a point that lies at least free_margin_m inside the trusted range. Replay of the 2026-10-15 bags: real phantoms 62 -> 53, static-cell dropouts unchanged, object kept on 10/11 FOV exits as before. --- include/robot_costmap_2d/observation.h | 3 + include/robot_costmap_2d/voxel_layer.h | 7 ++ plugins/obstacle_layer.cpp | 9 ++- plugins/voxel_layer.cpp | 48 +++++++++++++ src/costmap_2d_robot.cpp | 3 +- src/depth_visibility.cpp | 3 + test/depth_observation_buffer_test.cpp | 3 +- test/depth_visibility_test.cpp | 97 ++++++++++++++++++++++++++ 8 files changed, 169 insertions(+), 4 deletions(-) diff --git a/include/robot_costmap_2d/observation.h b/include/robot_costmap_2d/observation.h index 1deca18..f75b5c2 100755 --- a/include/robot_costmap_2d/observation.h +++ b/include/robot_costmap_2d/observation.h @@ -101,6 +101,9 @@ struct DepthFrustumConfig /// [px] with evidence points, marking drops points that project closer than this to /// the usable image edge, so each kept point has a full projection patch in view. unsigned int marking_border_px = 0; + /// With evidence points, a valid return deeper than valid_max_z_m counts as behind a point + /// that lies at least free_margin_m inside the trusted range: the ray passed the point. + bool far_return_is_behind = false; }; class DepthCameraObservation diff --git a/include/robot_costmap_2d/voxel_layer.h b/include/robot_costmap_2d/voxel_layer.h index a50cdd0..be61027 100755 --- a/include/robot_costmap_2d/voxel_layer.h +++ b/include/robot_costmap_2d/voxel_layer.h @@ -84,6 +84,9 @@ public: } virtual void matchSize(); virtual void reset(); + /// Recovery clear. Also drops the voxels and evidence points of the cleared cells: the + /// base class only writes the 2D cells, and the next column update re-derived the obstacle. + void clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area = false) override; LayerType getType() const override { @@ -138,6 +141,10 @@ private: } /// Drops evidence of voxels that left the window or are no longer MARKED. void pruneDepthEvidence(); + /// Frees every voxel of the column and its evidence points; the 2D cell is left to the caller. + void clearDepthColumn(unsigned int x, unsigned int y); + /// Paired depth only: the voxels under the footprint, which ObstacleLayer frees in 2D only. + void clearFootprintVoxels(); DepthEvidenceStore depth_evidence_; int evidence_offset_x_ = 0; int evidence_offset_y_ = 0; diff --git a/plugins/obstacle_layer.cpp b/plugins/obstacle_layer.cpp index c1b330b..54cd840 100755 --- a/plugins/obstacle_layer.cpp +++ b/plugins/obstacle_layer.cpp @@ -293,6 +293,9 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa frustum_config.marking_border_px = static_cast(marking_border); if (frustum_config.evidence_points_enabled && !frustum_config.observed_volume_clearing) throw std::invalid_argument("depth_evidence_points_enabled requires depth_clearing_mode: observed_volume"); + read_depth_option("depth_far_return_is_behind", frustum_config.far_return_is_behind); + if (frustum_config.far_return_is_behind && !frustum_config.evidence_points_enabled) + throw std::invalid_argument("depth_far_return_is_behind requires depth_evidence_points_enabled"); // One pixel more than the patch radius absorbs rounding of the stored float points, // so every kept evidence point is re-checked with a full patch from its own pose. if (frustum_config.evidence_points_enabled && @@ -440,12 +443,14 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa marking_buffers_.erase(std::remove(marking_buffers_.begin(), marking_buffers_.end(), m.buffer), marking_buffers_.end()); robot::log_info("depth clearing observed_volume: paired %s + %s, height=[%.3f, %.3f] m; " "unknown/occluded/outside FOV retained; queue=%u age=%.3f s; one valid free frame; " - "evidence_points=%s per_voxel=%u marking_border=%u px projection_margin=%u px\n", + "evidence_points=%s per_voxel=%u marking_border=%u px projection_margin=%u px " + "far_return_behind=%s\n", paired->cloud_topic.c_str(), paired->depth_topic.c_str(), m.min_height, m.max_height, paired->config.pair_queue_size, paired->config.observation_max_age_s, paired->config.evidence_points_enabled ? "true" : "false", paired->config.evidence_points_per_voxel, paired->config.marking_border_px, - paired->config.projection_margin_px); + paired->config.projection_margin_px, + paired->config.far_return_is_behind ? "true" : "false"); } } catch (const YAML::BadFile& e) { diff --git a/plugins/voxel_layer.cpp b/plugins/voxel_layer.cpp index 605dec6..2dd9088 100755 --- a/plugins/voxel_layer.cpp +++ b/plugins/voxel_layer.cpp @@ -240,6 +240,54 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, processPairedDepth(min_x, min_y, max_x, max_y); current_ = current_ && pairedDepthCurrent(); updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y); + if (footprint_clearing_enabled_ && !paired_depth_sources_.empty()) + clearFootprintVoxels(); +} + +void VoxelLayer::clearDepthColumn(unsigned int x, unsigned int y) +{ + if (x >= size_x_ || y >= size_y_) + return; + const unsigned int index = getIndex(x, y); + if (robot_voxel_grid_.getData()[index] >> 16) + for (unsigned int z = 0; z < size_z_; ++z) + depth_evidence_.erase(evidenceKey(x, y, z)); + robot_voxel_grid_.clearVoxelColumn(index); +} + +void VoxelLayer::clearFootprintVoxels() +{ + if (transformed_footprint_.size() < 3) + return; + std::vector map_polygon; + for (const auto& point : transformed_footprint_) + { + MapLocation location; + // Same rule as setConvexPolygonCost: a footprint partly outside the window clears nothing. + if (!worldToMap(point.x, point.y, location.x, location.y)) + return; + map_polygon.push_back(location); + } + std::vector cells; + convexFillCells(map_polygon, cells); + for (const auto& cell : cells) + { + clearDepthColumn(cell.x, cell.y); + costmap_[getIndex(cell.x, cell.y)] = FREE_SPACE; + } +} + +void VoxelLayer::clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area) +{ + // Same cell selection as CostmapLayer::clearArea, which then writes the 2D cells. + for (int x = 0; x < static_cast(size_x_); ++x) + { + const bool xrange = x > start_x && x < end_x; + for (int y = 0; y < static_cast(size_y_); ++y) + if ((xrange && y > start_y && y < end_y) == invert_area) + clearDepthColumn(static_cast(x), static_cast(y)); + } + CostmapLayer::clearArea(start_x, start_y, end_x, end_y, invert_area); } void VoxelLayer::markObservation(const Observation& obs, double* min_x, double* min_y, diff --git a/src/costmap_2d_robot.cpp b/src/costmap_2d_robot.cpp index 16f40ba..a043de3 100644 --- a/src/costmap_2d_robot.cpp +++ b/src/costmap_2d_robot.cpp @@ -466,7 +466,8 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name, "depth_pair_max_wait_s", "depth_observation_max_age_s", "depth_valid_min_z_m", "depth_valid_max_z_m", "depth_free_margin_m", "depth_projection_margin_px", "depth_voxel_z_resolution_m", "depth_evidence_points_enabled", - "depth_evidence_points_per_voxel", "depth_marking_border_px"}) + "depth_evidence_points_per_voxel", "depth_marking_border_px", + "depth_far_return_is_behind"}) if (plugin_nh_element.hasParam(key)) costmap_plugin_nh_element.setParam(key, YAML::Clone(plugin_nh_element.getParamValue(key))); robot::log_info("topic: %s data_type: %s clearing: %d marking: %d inf_is_valid: %d min_obstacle_height: %f max_obstacle_height: %f", topic.c_str(), data_type.c_str(), clearing, marking, inf_is_valid, min_obstacle_height, max_obstacle_height); diff --git a/src/depth_visibility.cpp b/src/depth_visibility.cpp index 66a2e3e..fe52086 100644 --- a/src/depth_visibility.cpp +++ b/src/depth_visibility.cpp @@ -240,6 +240,9 @@ DepthVisibilityResult DepthVisibilityChecker::classifyPoints(const std::vector config_.valid_max_z_m && p.z() + config_.free_margin_m < config_.valid_max_z_m) + continue; if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m || measured_z > config_.valid_max_z_m) return {DepthVisibility::Unknown, DepthVisibilityReason::InvalidDepth}; diff --git a/test/depth_observation_buffer_test.cpp b/test/depth_observation_buffer_test.cpp index 9dee46f..c53887f 100644 --- a/test/depth_observation_buffer_test.cpp +++ b/test/depth_observation_buffer_test.cpp @@ -246,7 +246,8 @@ TEST(DepthBuffer, RuntimeFactoryForwardsObservedVolumeModeAndPairsSources) const YAML::Node runtime_clearing = YAML::LoadFile((runtime / "costmap_common_params.yaml").string())["obstacles"]["pc_clearing"]; for (const char* key : {"depth_evidence_points_enabled", "depth_evidence_points_per_voxel", - "depth_marking_border_px", "depth_projection_margin_px", "depth_valid_max_z_m"}) + "depth_marking_border_px", "depth_projection_margin_px", "depth_valid_max_z_m", + "depth_far_return_is_behind"}) { ASSERT_TRUE(runtime_clearing[key].IsDefined()) << key; ASSERT_TRUE(settings.hasParam(key)) << key; diff --git a/test/depth_visibility_test.cpp b/test/depth_visibility_test.cpp index c7d5a38..44d95f9 100644 --- a/test/depth_visibility_test.cpp +++ b/test/depth_visibility_test.cpp @@ -104,6 +104,24 @@ TEST(DepthVisibility, EvidencePointsCertifyAVoxelCutByTheImageTop) { d=depth(1.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); EXPECT_EQ(c.classifyPoints({Eigen::Vector3d(0,0,1),Eigen::Vector3d(0,0,1.6)}).state,DepthVisibility::Surface); } +// A return beyond valid_max_z_m (3 m) proves the ray passed a point well inside the range. +TEST(DepthVisibility, FarReturnCountsAsBehindOnlyWhenEnabled) { + DepthVisibilityChecker c; DepthFrustumConfig cfg; + tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera"; + p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1; + const std::vector point{Eigen::Vector3d(0,0,1)}; // u = 100, v = 80 + auto d=depth(4);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.classifyPoints(point).state,DepthVisibility::Unknown); // default: not proof + cfg.far_return_is_behind=true;ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.classifyPoints(point).state,DepthVisibility::Free); + // point + margin reaches the range limit: a far return proves nothing about it + EXPECT_EQ(c.classifyPoints({Eigen::Vector3d(0,0,2.99)}).state,DepthVisibility::Unknown); + d=depth(4);uint16_t zero=0;std::memcpy(&d->depth.data[80*400+101*2],&zero,2); // no-data in the patch + ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.classifyPoints(point).state,DepthVisibility::Unknown); + d=depth(.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.classifyPoints(point).state,DepthVisibility::Surface); // a nearer surface still keeps it +} TEST(DepthVisibility, ProjectsInsideHonoursBorderAndUsableStrips) { DepthVisibilityChecker c; DepthFrustumConfig cfg;cfg.clear_left_border_px=10; tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera"; @@ -156,6 +174,7 @@ protected: cfg["observation_sources"]="pc_marking pc_clearing";cfg["footprint_clearing_enabled"]=false;cfg["enabled"]=true; // Explicit, so the result does not depend on what the runtime YAML currently enables. cfg["pc_clearing"]["depth_evidence_points_enabled"]=false; + cfg["pc_clearing"]["depth_far_return_is_behind"]=false; configure(cfg); robot::NodeHandle nh("~");nh.setParam("depth_test",cfg); parent.getCostmap()->resizeMap(80,80,.05,-2,-2);layer.initialize(&parent,"depth_test",&tf); @@ -297,6 +316,84 @@ TEST_F(DepthEvidenceLayerTest, AStillVisibleObjectIsNeverCertifiedFree) { for(int i=0;i<3;++i) {frameCloud(.62,-.01f,-.45f,.62f);EXPECT_EQ(at(),LETHAL_OBSTACLE);} frame(.62);EXPECT_EQ(at(),LETHAL_OBSTACLE); // no marking this frame, surface still seen } +// Two voxels in the column of (0.62, 0.01): z 0.08 m (seen by image rows below 65) and +// z 0.48 m (rows above 65). The partial frame frees the low one and keeps the high one +// occluded, so a column update would re-derive the cell from any voxel left behind. +class DepthColumnClearTest:public DepthEvidenceLayerTest { +protected: + void configure(YAML::Node& cfg) override { + DepthEvidenceLayerTest::configure(cfg); + cfg["footprint_clearing_enabled"]=true; + } + void markTwoVoxels() { + auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test")); + auto c=cloud(stamp);robot_sensor_msgs::PointCloud2Modifier m(c);m.resize(2); + robot_sensor_msgs::PointCloud2Iterator x(c,"x"),y(c,"y"),z(c,"z"); + *x=-.01;*y=.11;*z=.62;++x;++y;++z;*x=-.01;*y=-.29;*z=.62; + layer.dataCallBack(c,"/camera/depth/points_proc"); + robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(.62,stamp);layer.dataCallBack(d,"/camera/depth/data");update(); + } + void partialFrame() { + auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test")); + auto partial=depth(2,stamp);uint16_t blocked=400; + for(unsigned v=0;v<65;++v) for(unsigned u=0;u<200;++u) + std::memcpy(&partial->depth.data[v*400+u*2],&blocked,2); + layer.dataCallBack(cloud(stamp,false),"/camera/depth/points_proc"); + robot_sensor_msgs::DepthCameraData::ConstPtr d=partial;layer.dataCallBack(d,"/camera/depth/data");update(); + } + void setFootprint(double x0,double x1,double y0,double y1) { + std::vector footprint(4); + footprint[0].x=footprint[1].x=x0;footprint[2].x=footprint[3].x=x1; + footprint[0].y=footprint[3].y=y0;footprint[1].y=footprint[2].y=y1; + parent.setFootprint(footprint); + } + uint32_t markedBits(double x=.62,double y=.01) { + unsigned a,b;EXPECT_TRUE(layer.worldToMap(x,y,a,b)); + return layer.voxelSnapshot().data[b*layer.getSizeInCellsX()+a]>>16; + } +}; +TEST_F(DepthColumnClearTest, FootprintClearingAlsoFreesTheVoxelColumn) { + setFootprint(-1.9,-1.8,-1.9,-1.8); // far corner of the window + markTwoVoxels();ASSERT_EQ(at(),LETHAL_OBSTACLE);ASSERT_NE(markedBits(),0u); + setFootprint(.50,.75,-.10,.10);update(); // robot body now covers the cell + EXPECT_EQ(at(),FREE_SPACE);EXPECT_EQ(markedBits(),0u); + setFootprint(-1.9,-1.8,-1.9,-1.8);partialFrame(); + EXPECT_EQ(at(),FREE_SPACE); // nothing left in the column to re-derive the cell +} +TEST_F(DepthColumnClearTest, ClearAreaAlsoFreesTheVoxelColumn) { + setFootprint(-1.9,-1.8,-1.9,-1.8); + markTwoVoxels();ASSERT_EQ(at(),LETHAL_OBSTACLE); + layer.clearArea(0,0,0,0,false); // empty kept window: clear the whole layer + EXPECT_EQ(at(),NO_INFORMATION);EXPECT_EQ(markedBits(),0u); + partialFrame();EXPECT_NE(at(),LETHAL_OBSTACLE); +} +TEST_F(DepthColumnClearTest, ClearAreaFollowsTheBaseWindowSelection) { + setFootprint(-1.9,-1.8,-1.9,-1.8); + markTwoVoxels();ASSERT_EQ(at(),LETHAL_OBSTACLE); + unsigned ux,uy;ASSERT_TRUE(layer.worldToMap(.62,.01,ux,uy)); + const int x=static_cast(ux),y=static_cast(uy); + layer.clearArea(x-3,y-3,x+3,y+3,false); // default recovery: keep the window, clear outside it + EXPECT_EQ(at(),LETHAL_OBSTACLE);EXPECT_NE(markedBits(),0u); + layer.clearArea(x-3,y-3,x+3,y+3,true); // inverted: clear inside the window + EXPECT_EQ(at(),NO_INFORMATION);EXPECT_EQ(markedBits(),0u); +} +class DepthFarReturnLayerTest:public DepthEvidenceLayerTest { +protected: + void configure(YAML::Node& cfg) override { + DepthEvidenceLayerTest::configure(cfg); + cfg["pc_clearing"]["depth_far_return_is_behind"]=true; + } +}; +TEST_F(DepthEvidenceLayerTest, FarReturnKeepsTheVoxelByDefault) { + frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); + frame(4);EXPECT_EQ(at(),LETHAL_OBSTACLE); +} +TEST_F(DepthFarReturnLayerTest, FarReturnClearsWhenEnabledButNoDataStillKeeps) { + frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); + frame(4);EXPECT_EQ(at(),FREE_SPACE); + frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); + frame(0);EXPECT_EQ(at(),LETHAL_OBSTACLE); +} } int main(int argc,char**argv) {robot::Time::init();testing::InitGoogleTest(&argc,argv);return RUN_ALL_TESTS();}