diff --git a/CMakeLists.txt b/CMakeLists.txt index 646cad5..efd7628 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,7 +23,8 @@ find_package(Boost REQUIRED COMPONENTS system thread filesystem) # still configure. The test block below requires it where it is actually used. find_package(GTest QUIET) find_package(yaml-cpp REQUIRED) -find_package(PCL REQUIRED COMPONENTS common filters) +# kdtree/search/segmentation: DepthCameraObstacleLayer (kd-tree clearing, Euclidean clustering). +find_package(PCL REQUIRED COMPONENTS common filters kdtree search segmentation) if (NOT BUILDING_WITH_CATKIN) @@ -181,7 +182,12 @@ add_library(plugins SHARED plugins/directional_layer.cpp plugins/preferred_layer.cpp plugins/unpreferred_layer.cpp + plugins/depth_camera_obstacle_layer.cpp ) +# PCL stays private to the plugin library, like robot_costmap_2d: no PCL type in public headers. +target_include_directories(plugins SYSTEM PRIVATE ${PCL_INCLUDE_DIRS}) +target_compile_options(plugins PRIVATE ${PCL_DEFINITIONS}) +target_link_libraries(plugins PRIVATE ${PCL_LIBRARIES}) if(BUILDING_WITH_CATKIN) add_dependencies(plugins ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) @@ -301,6 +307,9 @@ if(BUILD_DEPTH_MARKING_TESTS) add_executable(depth_evidence_store_test test/depth_evidence_store_test.cpp) target_link_libraries(depth_evidence_store_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main) + add_executable(depth_camera_obstacle_layer_test test/depth_camera_obstacle_layer_test.cpp) + target_link_libraries(depth_camera_obstacle_layer_test PRIVATE + plugins robot_costmap_2d GTest::GTest GTest::Main) endif() if(BUILD_COSTMAP_TESTS) diff --git a/include/robot_costmap_2d/depth_camera_obstacle_layer.h b/include/robot_costmap_2d/depth_camera_obstacle_layer.h new file mode 100644 index 0000000..38bdb5a --- /dev/null +++ b/include/robot_costmap_2d/depth_camera_obstacle_layer.h @@ -0,0 +1,221 @@ +/********************************************************************* + * Port of costmap_depth_camera::DepthCameraObstacleLayer (BSD, Apola), + * 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. + *********************************************************************/ +#ifndef ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_ +#define ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace robot_costmap_2d +{ + +/** + * @brief Truncated pyramid of one depth camera observation, in the global frame. + * + * Same construction as costmap_depth_camera::Observation: 8 vertices from the configured + * FOV and detect range in the sensor frame, transformed to the global frame, then 6 inward + * normals (inside test) and 6 plane equations (12 cm "attach" band test). + */ +struct DepthCameraFrustum +{ + Eigen::Vector3f origin = Eigen::Vector3f::Zero(); ///< sensor origin, global frame [m] + std::array vertices; ///< TLNear TRNear BLNear BRNear TLFar TRFar BLFar BRFar + std::array normals; ///< near right bottom left far top + std::array planes; ///< a, b, c, d of each face + double max_detect_distance = 2.5; ///< [m] + + /** + * @brief Build the frustum. + * @param T_global_sensor pose of the sensor frame in the global frame + * @param fov_w, fov_v full horizontal / vertical field of view [rad] + * @param min_d, max_d near / far plane distance along the viewing axis [m] + * @param optical true: sensor frame is Z forward, X right, Y down (REP 103 optical); + * false: X forward, Y left, Z up (camera_link), as the source assumes + */ + void build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, double min_d, + double max_d, bool optical); + + /// Inside all 6 faces (FrustumUtils::isInsideFRUSTUMwoAttach without the band test). + bool inside(const Eigen::Vector3f& p) const; + + /// Within 0.12 m of a face plane and within max_detect_distance + 0.5 m of the origin in XY. + bool nearFace(const Eigen::Vector3f& p) const; +}; + +/// FrustumUtils::isInsideFRUSTUMs: inside at least one frustum. +bool insideAnyFrustum(const std::vector& frustums, const Eigen::Vector3f& p); + +/// FrustumUtils::isAttachFRUSTUMs: near a face of one frustum and not well inside another. +bool attachedToFrustums(const std::vector& frustums, const Eigen::Vector3f& p); + +class DepthCameraObstacleLayer : public CostmapLayer +{ +public: + DepthCameraObstacleLayer(); + ~DepthCameraObstacleLayer() override; + + void onInitialize() override; + void updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y, + double* max_x, double* max_y) override; + void updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) override; + void activate() override; + void deactivate() override; + void reset() override; + + /// SensorGateway only delivers obstacle data to VOXEL_LAYER plugins. + LayerType getType() const override + { + return LayerType::VOXEL_LAYER; + } + + /// Number of stored (column, height) points, for tests and the stats log. + std::size_t storedPoints() const; + +protected: + void handleImpl(const void* data, const std::type_info& type, const std::string& topic) override; + +private: + /// One observation: cloud after TF and the height gate, plus its frustum (both global frame). + struct Observation + { + robot::Time stamp; + std::vector points; + DepthCameraFrustum frustum; + }; + + /// ObservationBuffer of the source, one per entry of observation_sources. + struct Source + { + std::string name; + std::string topic; + std::string sensor_frame; + bool sensor_frame_is_optical = false; + double observation_keep_time = 0.0; ///< [s] 0 keeps only the newest observation + double expected_update_rate = 0.0; ///< [s] 0 disables the staleness check + double min_obstacle_height = 0.0; ///< [m] global-frame z gate + double max_obstacle_height = 2.0; ///< [m] + double fov_w = 1.5; ///< [rad] + double fov_v = 1.0; ///< [rad] + double min_detect_distance = 0.15; ///< [m] + double max_detect_distance = 2.5; ///< [m] + bool marking = true; + + std::list observations; ///< newest first + robot::Time last_updated; + + std::mutex pending_mutex; ///< guards pending: handleImpl runs on the producer thread + std::shared_ptr pending; + }; + + void loadParameters(); + bool processPending(Source& source); + bool bufferCloud(Source& source, const robot_sensor_msgs::PointCloud2& cloud); + void purgeStale(Source& source) const; + bool sourceIsCurrent(const Source& source) const; + + void clearMarkingByKdtree(const std::vector& cloud, + const std::vector& frustums, double robot_x, + double robot_y, double* min_x, double* min_y, double* max_x, + double* max_y); + void processCluster(const std::vector& frustums, + const std::vector& cluster, double* min_x, double* min_y, + double* max_x, double* max_y); + 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; + void logStats(); + + // (int)(x / res) toward zero and back to the cell corner, exactly as the source stores points. + void worldToIntIndex(double wx, double wy, int& mx, int& my, double resolution) const + { + mx = static_cast(wx / resolution); + my = static_cast(wy / resolution); + } + void intIndexToWorld(double& wx, double& wy, int mx, int my, double resolution) const + { + wx = mx * resolution; + wy = my * resolution; + } + + std::string global_frame_; + bool rolling_window_ = false; + std::vector> sources_; + + // Parameters, names and defaults as in the source. + bool footprint_clearing_enabled_ = true; + int combination_method_ = 1; ///< 0 overwrite, 1 maximum, other: nothing + bool enable_near_blocked_protection_ = true; + int number_points_considered_as_blocked_ = 5; + double forced_clearing_distance_ = 0.1; ///< [m] from robot_base_frame + double ec_seg_distance_ = 0.2; ///< [m] Euclidean cluster tolerance + int ec_cluster_min_size_ = 5; + int size_of_cluster_rejection_ = 5; ///< clusters with <= this many points are not marked + double voxel_resolution_ = 0.01; ///< [m] height quantization of stored points + double check_radius_ = 0.1; ///< [m] kd-tree radius of the "seen again" test + int number_clearing_threshold_ = 2; ///< fewer neighbours than this clears the point + bool use_voxelized_observation_ = true; ///< VoxelGrid 5 cm on the combined cloud + double transform_tolerance_ = 0.2; ///< [s] how long a cloud may wait for its TF + double marking_height_under_ground_ = 100.0; + 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] + + /// (ix, iy) of the cell corner -> {height index -> label}, global frame (use_global_frame_to_mark). + std::map, std::map> pc_3d_map_global_; + std::vector transformed_footprint_; + + struct Stats + { + std::size_t cycles = 0; + std::size_t cloud_points = 0; + std::size_t marked = 0; + std::size_t cleared = 0; + std::size_t cleared_all_frames = 0; + std::size_t bypassed_frames = 0; + std::size_t tf_waits = 0; + std::size_t tf_drops = 0; + std::size_t dropped_out_of_window = 0; + double bounds_ms_sum = 0.0; + double bounds_ms_max = 0.0; + } stats_; + robot::Time last_stats_log_; +}; + +} // namespace robot_costmap_2d + +#endif // ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_ diff --git a/include/robot_costmap_2d/depth_evidence_store.h b/include/robot_costmap_2d/depth_evidence_store.h index a0ab3e7..0426070 100644 --- a/include/robot_costmap_2d/depth_evidence_store.h +++ b/include/robot_costmap_2d/depth_evidence_store.h @@ -48,8 +48,13 @@ public: unsigned int pointsPerVoxel() const { return points_per_voxel_; } /// Records a marking point [global frame, m]. fresh = true drops points left over from - /// an earlier occupancy of the voxel (it was not MARKED before this point). + /// an earlier occupancy of the voxel (it was not MARKED before this point). A marking + /// point also restarts the voxel's re-observe miss count. void add(const VoxelKey& key, const Eigen::Vector3f& point, bool fresh); + /// Re-observe-or-clear: adds weight to the voxel's miss count and returns the new count; + /// 0 when the voxel has no evidence. + float addMiss(const VoxelKey& key, float weight); + void resetMiss(const VoxelKey& key); /// Distinct evidence points of one voxel. Returns false when the voxel has none. bool points(const VoxelKey& key, std::vector& out) const; @@ -75,6 +80,7 @@ private: std::array points; unsigned char count = 0; ///< valid slots, extremes included unsigned char next_recent = 0; ///< ring position among the recent slots + float miss = 0.f; ///< re-observe misses since last marked or confirmed }; unsigned int points_per_voxel_; diff --git a/include/robot_costmap_2d/depth_visibility.h b/include/robot_costmap_2d/depth_visibility.h index f61cc7c..c4f57e2 100644 --- a/include/robot_costmap_2d/depth_visibility.h +++ b/include/robot_costmap_2d/depth_visibility.h @@ -9,6 +9,8 @@ namespace robot_costmap_2d { enum class DepthVisibility { Free, Unknown, Surface }; enum class DepthVisibilityReason { Free, OutsideView, InvalidDepth, Surface, EmptyRegion }; +/// What one frame says about a marked voxel under the re-observe-or-clear rule, weakest first. +enum class DepthObservation { OutOfView, NoReturn, SeenThrough, Occluded, Confirmed }; struct DepthVisibilityResult { DepthVisibility state{DepthVisibility::Unknown}; @@ -35,13 +37,27 @@ public: */ DepthVisibilityResult classifyPoints(const std::vector& points) const; + /** + * @brief Re-observes the measured evidence points of one voxel [global frame, m]. + * + * Per point, its projection_margin_px patch decides: a valid pixel within confirm_tolerance_m + * of the point is Confirmed; otherwise a valid pixel in front is Occluded; otherwise one + * behind is SeenThrough; otherwise NoReturn. A point outside the trusted depth range, the + * usable image or the stereo band is OutOfView. The voxel takes its strongest point result. + */ + DepthObservation observePoints(const std::vector& points) const; + /// True when a global-frame point projects at least border_px inside the usable image - /// (the clear_left/right border strips are not usable). Used to gate evidence marking. + /// (the clear_left/right border strips and the stereo band are not usable). Used to gate + /// evidence marking, so every marked point can be re-checked later. bool projectsInside(const Eigen::Vector3d& point, unsigned int border_px) const; private: /// Raw depth at a pixel [m]; NaN for an unsupported encoding. Caller checks bounds. double depthAt(int u, int v) const; + /// First usable image column for a point at depth z [m] > 0: the left border strip or the + /// stereo no-disparity band, whichever is wider. + int usableLeft(double z) const; robot_sensor_msgs::DepthCameraData::ConstPtr data_; Eigen::Isometry3d camera_from_global_{Eigen::Isometry3d::Identity()}; diff --git a/include/robot_costmap_2d/observation.h b/include/robot_costmap_2d/observation.h index f75b5c2..34d2336 100755 --- a/include/robot_costmap_2d/observation.h +++ b/include/robot_costmap_2d/observation.h @@ -104,6 +104,25 @@ struct DepthFrustumConfig /// 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; + /// Re-observe-or-clear rule (needs evidence points). A marked voxel in view must be measured + /// again at one of its points each frame; seen through for miss_frames frames in a row frees + /// it. Occluded, out-of-view and no-return frames keep it, so nothing expires out of the FOV. + /// false: a voxel is freed only when every pixel of every point proves free space. + bool reobserve_clearing = false; + /// [m] Re-observe: |measured - point depth| within this means the surface is still there. + /// Nearer than that is an occluder, deeper is free space seen through. Replaces free_margin_m. + double confirm_tolerance_m = 0.05; + /// [frames] Re-observe: seen-through frames in a row that free a voxel. + unsigned int miss_frames = 3; + /// [0..1] Re-observe: miss added by a frame whose patch pixels are all invalid. 0 keeps invalid + /// depth as unknown; > 0 lets voxels in view expire where the camera returns nothing. + double no_return_weight = 0.0; + /// [m] Stereo baseline of the left no-disparity band, fx * baseline / z + stereo_band_margin_px + /// wide at depth z. Points inside it cannot be re-checked: they are out of view and are not + /// marked. 0 disables (only clear_left_border_px applies). + double stereo_baseline_m = 0.0; + /// [px] Added to the stereo band width. + unsigned int stereo_band_margin_px = 10; }; class DepthCameraObservation diff --git a/include/robot_costmap_2d/voxel_layer.h b/include/robot_costmap_2d/voxel_layer.h index be61027..324747a 100755 --- a/include/robot_costmap_2d/voxel_layer.h +++ b/include/robot_costmap_2d/voxel_layer.h @@ -59,6 +59,7 @@ namespace robot_costmap_2d { class DepthVisibilityChecker; +enum class DepthObservation; class VoxelLayer : public ObstacleLayer { @@ -132,7 +133,13 @@ private: uint64_t free{0}, unknown{0}, surface{0}, frames{0}; uint64_t by_evidence{0}; ///< decisions made from evidence points uint64_t border_dropped{0}; ///< marking points dropped at the image border + /// re-observe-or-clear outcomes per voxel and frame + uint64_t confirmed{0}, occluded{0}, seen_through{0}, no_return{0}, out_of_view{0}; } visibility_counts_; + /// Re-observe-or-clear: applies one frame's observation to the voxel's miss count. + /// Returns true when the voxel is to be freed. + bool reobserveFrees(DepthObservation observation, const DepthEvidenceStore::VoxelKey& key, + const DepthFrustumConfig& config); /// Window-independent key: local cell index plus the cells the rolling origin moved. DepthEvidenceStore::VoxelKey evidenceKey(unsigned int x, unsigned int y, unsigned int z) const diff --git a/plugins/depth_camera_obstacle_layer.cpp b/plugins/depth_camera_obstacle_layer.cpp new file mode 100644 index 0000000..23515c8 --- /dev/null +++ b/plugins/depth_camera_obstacle_layer.cpp @@ -0,0 +1,834 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2008, 2013, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Willow Garage, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * Author: Apola (costmap_depth_camera); port to robot_costmap_2d. + *********************************************************************/ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace robot_costmap_2d +{ +namespace +{ +// Distance of the "attach" band around each frustum face, hard-coded in the source [m]. +constexpr float kAttachDistance = 0.12f; +// Stored columns farther than this from the robot are not tested for clearing [m]. +constexpr double kClearingSkipDistance = 10.0; +// VoxelGrid leaf of the combined observation, hard-coded in the source [m]. +constexpr float kObservationLeaf = 0.05f; + +Eigen::Isometry3d toIsometry(const tf3::TransformStampedMsg& t) +{ + const auto& q = t.transform.rotation; + const auto& p = t.transform.translation; + Eigen::Isometry3d iso = Eigen::Isometry3d::Identity(); + iso.linear() = Eigen::Quaterniond(q.w, q.x, q.y, q.z).normalized().toRotationMatrix(); + iso.translation() << p.x, p.y, p.z; + return iso; +} + +// The source keeps parameters in the plugin namespace. Costmap2DROBOT only copies the keys of +// known layer types from the shared namespace into "/", so read the scoped +// value first and fall back to the shared block with the plugin's own name. +class ParamReader +{ +public: + ParamReader(const robot::NodeHandle& scoped, const robot::NodeHandle& shared) + : scoped_(scoped), shared_(shared) + { + } + + ParamReader child(const std::string& ns) const + { + return ParamReader(robot::NodeHandle(scoped_, ns), robot::NodeHandle(shared_, ns)); + } + + bool has(const std::string& key) const + { + return scoped_.hasParam(key) || shared_.hasParam(key); + } + + template + T get(const std::string& key, const T& default_value) const + { + T value = default_value; + if (scoped_.hasParam(key)) + scoped_.getParam(key, value, default_value); + else if (shared_.hasParam(key)) + shared_.getParam(key, value, default_value); + return value; + } + +private: + robot::NodeHandle scoped_; + robot::NodeHandle shared_; +}; + +void requireRange(bool ok, const std::string& what) +{ + if (!ok) + throw std::invalid_argument("DepthCameraObstacleLayer: " + what); +} +} // namespace + +// --------------------------------------------------------------------------------------------- +// Frustum (costmap_depth_camera::Observation::findFrustum* and FrustumUtils) +// --------------------------------------------------------------------------------------------- + +void DepthCameraFrustum::build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, + double min_d, double max_d, bool optical) +{ + max_detect_distance = max_d; + const double tw = std::tan(fov_w / 2.0); + const double tv = std::tan(fov_v / 2.0); + // findFrustumVertex(): X forward, +Y left, +Z up. TL = +Y +Z, BR = -Y -Z. + const std::array local = { + Eigen::Vector3d(min_d, min_d * tw, min_d * tv), Eigen::Vector3d(min_d, -min_d * tw, min_d * tv), + Eigen::Vector3d(min_d, min_d * tw, -min_d * tv), Eigen::Vector3d(min_d, -min_d * tw, -min_d * tv), + Eigen::Vector3d(max_d, max_d * tw, max_d * tv), Eigen::Vector3d(max_d, -max_d * tw, max_d * tv), + Eigen::Vector3d(max_d, max_d * tw, -max_d * tv), Eigen::Vector3d(max_d, -max_d * tw, -max_d * tv)}; + for (std::size_t i = 0; i < local.size(); ++i) + { + Eigen::Vector3d v = local[i]; + // Same pyramid expressed in an optical frame: forward = +Z, left = -X, up = -Y. + if (optical) + v = Eigen::Vector3d(-local[i].y(), -local[i].z(), local[i].x()); + vertices[i] = (T_global_sensor * v).cast(); + } + origin = T_global_sensor.translation().cast(); + + const Eigen::Vector3f& TLNear = vertices[0]; + const Eigen::Vector3f& TRNear = vertices[1]; + const Eigen::Vector3f& BLNear = vertices[2]; + const Eigen::Vector3f& BRNear = vertices[3]; + const Eigen::Vector3f& TLFar = vertices[4]; + const Eigen::Vector3f& TRFar = vertices[5]; + const Eigen::Vector3f& BLFar = vertices[6]; + const Eigen::Vector3f& BRFar = vertices[7]; + + // findFrustumNormal(): getVec(a, b) = b - a, inward normals in this order. + normals[0] = (TRNear - TLNear).cross(BRNear - TRNear); // near + normals[1] = (TRFar - TRNear).cross(BRFar - TRFar); // right + normals[2] = (BRFar - BRNear).cross(BLFar - BRFar); // bottom + normals[3] = (BLFar - BLNear).cross(TLFar - BLFar); // left + normals[4] = (TRFar - BRFar).cross(TLFar - TRFar); // far + normals[5] = (TRFar - TLFar).cross(TRNear - TRFar); // top + + // findFrustumPlane(): getPlaneN(p1, p2, p3) = cross(p2 - p1, p3 - p1), d = -n . p1. + const auto plane = [](const Eigen::Vector3f& p1, const Eigen::Vector3f& p2, const Eigen::Vector3f& p3) { + const Eigen::Vector3f n = (p2 - p1).cross(p3 - p1); + return Eigen::Vector4f(n.x(), n.y(), n.z(), -n.dot(p1)); + }; + planes[0] = plane(TLNear, TLFar, BLNear); + planes[1] = plane(BLNear, BRNear, BLFar); + planes[2] = plane(TRNear, BRNear, BRFar); + planes[3] = plane(TLNear, TRNear, TLFar); + planes[4] = plane(TLNear, BLNear, BRNear); + planes[5] = plane(TLFar, TRFar, BRFar); +} + +bool DepthCameraFrustum::inside(const Eigen::Vector3f& p) const +{ + // Faces 0..2 pass through BRNear, faces 3..5 through TLFar. + for (int i = 0; i < 6; ++i) + { + const Eigen::Vector3f& corner = i < 3 ? vertices[3] : vertices[4]; + if ((p - corner).dot(normals[i]) < 0.f) + return false; + } + return true; +} + +bool DepthCameraFrustum::nearFace(const Eigen::Vector3f& p) const +{ + for (const Eigen::Vector4f& pl : planes) + { + const float dis = std::fabs(pl[0] * p.x() + pl[1] * p.y() + pl[2] * p.z() + pl[3]) / + std::sqrt(pl[0] * pl[0] + pl[1] * pl[1] + pl[2] * pl[2]); + if (dis <= kAttachDistance && + std::hypot(p.x() - origin.x(), p.y() - origin.y()) < max_detect_distance + 0.5) + return true; + } + return false; +} + +bool insideAnyFrustum(const std::vector& frustums, const Eigen::Vector3f& p) +{ + for (const DepthCameraFrustum& f : frustums) + if (f.inside(p)) + return true; + return false; +} + +bool attachedToFrustums(const std::vector& frustums, const Eigen::Vector3f& p) +{ + for (std::size_t i = 0; i < frustums.size(); ++i) + { + if (!frustums[i].nearFace(p)) + continue; + // Attached to this one; not attached overall if it lies well inside another camera's frustum. + for (std::size_t j = 0; j < frustums.size(); ++j) + if (j != i && !frustums[j].nearFace(p) && frustums[j].inside(p)) + return false; + return true; + } + return false; +} + +// --------------------------------------------------------------------------------------------- +// Layer +// --------------------------------------------------------------------------------------------- + +DepthCameraObstacleLayer::DepthCameraObstacleLayer() +{ + costmap_ = NULL; // the unsigned char* of the parent Costmap2D +} + +DepthCameraObstacleLayer::~DepthCameraObstacleLayer() = default; + +void DepthCameraObstacleLayer::onInitialize() +{ + rolling_window_ = layered_costmap_->isRolling(); + global_frame_ = layered_costmap_->getGlobalFrameID(); + loadParameters(); + matchSize(); + current_ = true; + last_stats_log_ = robot::Time::now(); +} + +void DepthCameraObstacleLayer::loadParameters() +{ + robot::NodeHandle nh("~"); + const std::string short_name = name_.substr(name_.find_last_of('/') + 1); + const ParamReader p(robot::NodeHandle(nh, name_), robot::NodeHandle(nh, short_name)); + + const bool track_unknown_space = p.get("track_unknown_space", layered_costmap_->isTrackingUnknown()); + default_value_ = track_unknown_space ? NO_INFORMATION : FREE_SPACE; + + enabled_ = p.get("enabled", true); + footprint_clearing_enabled_ = p.get("footprint_clearing_enabled", true); + combination_method_ = p.get("combination_method", 1); + enable_near_blocked_protection_ = p.get("enable_near_blocked_protection", true); + number_points_considered_as_blocked_ = p.get("number_points_considered_as_blocked", 5); + forced_clearing_distance_ = p.get("forced_clearing_distance", 0.1); + ec_seg_distance_ = p.get("ec_seg_distance", 0.2); + ec_cluster_min_size_ = p.get("ec_cluster_min_size", 5); + size_of_cluster_rejection_ = p.get("size_of_cluster_rejection", 5); + voxel_resolution_ = p.get("voxel_resolution", 0.01); + check_radius_ = p.get("check_radius", 0.1); + number_clearing_threshold_ = p.get("number_clearing_threshold", 2); + 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); + debug_stats_ = p.get("debug/stats", true); + debug_stats_period_ = p.get("debug/stats_period", 5.0); + + // The source's local mode keys points by costmap index, so markings move with a rolling + // window (its README shows it). Only the global mode is ported. + requireRange(use_global_frame_to_mark, "use_global_frame_to_mark: false is not ported"); + requireRange(voxel_resolution_ > 0.0 && std::isfinite(voxel_resolution_), "voxel_resolution must be > 0"); + requireRange(check_radius_ > 0.0 && std::isfinite(check_radius_), "check_radius must be > 0"); + requireRange(ec_seg_distance_ > 0.0 && std::isfinite(ec_seg_distance_), "ec_seg_distance must be > 0"); + requireRange(ec_cluster_min_size_ >= 1, "ec_cluster_min_size must be >= 1"); + requireRange(size_of_cluster_rejection_ >= 0, "size_of_cluster_rejection must be >= 0"); + requireRange(number_clearing_threshold_ >= 1, "number_clearing_threshold must be >= 1"); + requireRange(number_points_considered_as_blocked_ >= 0, "number_points_considered_as_blocked must be >= 0"); + requireRange(forced_clearing_distance_ >= 0.0, "forced_clearing_distance must be >= 0"); + requireRange(transform_tolerance_ >= 0.0 && std::isfinite(transform_tolerance_), "transform_tolerance must be >= 0"); + requireRange(debug_stats_period_ > 0.0, "debug/stats_period must be > 0"); + + marking_height_under_ground_ = 100.0; + marking_height_above_ground_ = -100.0; + + std::stringstream ss(p.get("observation_sources", std::string(""))); + std::string name; + while (ss >> name) + { + const ParamReader s = p.child(name); + std::unique_ptr src(new Source()); + src->name = name; + src->topic = s.get("topic", name); + src->sensor_frame = s.get("sensor_frame", std::string("")); + src->sensor_frame_is_optical = s.get("sensor_frame_is_optical", false); + src->observation_keep_time = s.get("observation_persistence", 0.0); + src->expected_update_rate = s.get("expected_update_rate", 0.0); + src->min_obstacle_height = s.get("min_obstacle_height", 0.0); + src->max_obstacle_height = s.get("max_obstacle_height", 2.0); + src->marking = s.get("marking", true); + src->fov_v = s.get("FOV_V", 1.0); + src->fov_w = s.get("FOV_W", 1.5); + src->min_detect_distance = s.get("min_detect_distance", 0.15); + src->max_detect_distance = s.get("max_detect_distance", 2.5); + if (s.get("inf_is_valid", false)) + robot::log_warning("DepthCameraObstacleLayer: inf_is_valid is not applicable to PointCloud observations\n"); + + const std::string what = "source " + name + ": "; + requireRange(src->fov_w > 0.0 && src->fov_w < M_PI, what + "FOV_W must be in (0, pi) [rad]"); + requireRange(src->fov_v > 0.0 && src->fov_v < M_PI, what + "FOV_V must be in (0, pi) [rad]"); + requireRange(src->min_detect_distance >= 0.0 && src->max_detect_distance > src->min_detect_distance, + what + "need 0 <= min_detect_distance < max_detect_distance [m]"); + requireRange(src->min_obstacle_height <= src->max_obstacle_height, + what + "min_obstacle_height must be <= max_obstacle_height [m]"); + requireRange(src->observation_keep_time >= 0.0 && src->expected_update_rate >= 0.0, + what + "observation_persistence and expected_update_rate must be >= 0 [s]"); + + // Update minimum height and maximum height for overall marking. + marking_height_above_ground_ = std::max(marking_height_above_ground_, src->max_obstacle_height); + marking_height_under_ground_ = std::min(marking_height_under_ground_, src->min_obstacle_height); + src->last_updated = robot::Time::now(); + + robot::log_info("DepthCameraObstacleLayer %s: source %s topic=%s sensor_frame=%s optical=%s " + "FOV_W=%.3f FOV_V=%.3f rad detect=[%.2f, %.2f] m height=[%.2f, %.2f] m " + "persistence=%.2f s expected_update_rate=%.2f s marking=%s\n", + name_.c_str(), name.c_str(), src->topic.c_str(), + src->sensor_frame.empty() ? "(cloud frame)" : src->sensor_frame.c_str(), + src->sensor_frame_is_optical ? "true" : "false", src->fov_w, src->fov_v, + src->min_detect_distance, src->max_detect_distance, src->min_obstacle_height, + src->max_obstacle_height, src->observation_keep_time, src->expected_update_rate, + src->marking ? "true" : "false"); + sources_.push_back(std::move(src)); + } + if (sources_.empty()) + robot::log_warning("DepthCameraObstacleLayer %s: observation_sources is empty, the layer marks nothing\n", + name_.c_str()); + + robot::log_info("DepthCameraObstacleLayer %s: global_frame=%s rolling=%s track_unknown=%s " + "voxel_resolution=%.3f m check_radius=%.3f m number_clearing_threshold=%d " + "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", + 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", + marking_height_under_ground_, marking_height_above_ground_, debug_stats_ ? "on" : "off"); +} + +void DepthCameraObstacleLayer::handleImpl(const void* data, const std::type_info& type, + const std::string& topic) +{ + // DepthCameraData, LaserScan, ... are meant for other layers of the same type. + if (type != typeid(robot_sensor_msgs::PointCloud2)) + return; + const auto& cloud = *static_cast(data); + std::shared_ptr copy; + for (const auto& source : sources_) + { + if (source->topic != topic) + continue; + if (!copy) + copy = std::make_shared(cloud); + // Newest only: the source buffer keeps one observation, and a cloud still waiting for its + // TF is superseded by a newer one, like a full tf2_ros::MessageFilter queue. + std::lock_guard lock(source->pending_mutex); + source->pending = copy; + } +} + +bool DepthCameraObstacleLayer::processPending(Source& source) +{ + std::shared_ptr cloud; + { + std::lock_guard lock(source.pending_mutex); + cloud = source.pending; + } + if (!cloud) + return false; + + bool done = true; + try + { + bufferCloud(source, *cloud); + } + catch (const tf3::TransformException& ex) + { + // Measurement TF only, never the latest TF. Wait while the cloud is younger than the + // tolerance, then drop it. + const double age = (robot::Time::now() - cloud->header.stamp).toSec(); + if (age <= transform_tolerance_) + { + ++stats_.tf_waits; + done = false; + } + else + { + ++stats_.tf_drops; + robot::log_error_throttle(5.0, "DepthCameraObstacleLayer %s: no TF %s <- %s at the cloud stamp " + "(%.3f s old), cloud dropped: %s\n", name_.c_str(), global_frame_.c_str(), + cloud->header.frame_id.c_str(), age, ex.what()); + } + } + catch (const std::exception& ex) + { + robot::log_error_throttle(5.0, "DepthCameraObstacleLayer %s: malformed cloud on %s dropped: %s\n", + name_.c_str(), source.topic.c_str(), ex.what()); + } + + if (done) + { + std::lock_guard lock(source.pending_mutex); + if (source.pending == cloud) + source.pending.reset(); + } + return done; +} + +bool DepthCameraObstacleLayer::bufferCloud(Source& source, const robot_sensor_msgs::PointCloud2& cloud) +{ + if (cloud.header.frame_id.empty()) + throw std::invalid_argument("cloud has no frame_id"); + const std::string origin_frame = source.sensor_frame.empty() ? cloud.header.frame_id : source.sensor_frame; + const tf3::Time stamp = data_convert::convertTime(cloud.header.stamp); + + const Eigen::Isometry3d T_cloud = toIsometry(tf_->lookupTransform(global_frame_, cloud.header.frame_id, stamp)); + const Eigen::Isometry3d T_origin = origin_frame == cloud.header.frame_id + ? T_cloud : toIsometry(tf_->lookupTransform(global_frame_, origin_frame, stamp)); + + Observation obs; + obs.stamp = cloud.header.stamp; + // Frustum vertices are given in the sensor frame, then everything is in the global frame. + obs.frustum.build(T_origin, source.fov_w, source.fov_v, source.min_detect_distance, + source.max_detect_distance, source.sensor_frame_is_optical); + + const std::size_t size = static_cast(cloud.width) * cloud.height; + obs.points.reserve(size); + robot_sensor_msgs::PointCloud2ConstIterator iter_x(cloud, "x"); + robot_sensor_msgs::PointCloud2ConstIterator iter_y(cloud, "y"); + robot_sensor_msgs::PointCloud2ConstIterator iter_z(cloud, "z"); + for (std::size_t i = 0; i < size; ++i, ++iter_x, ++iter_y, ++iter_z) + { + // The source relies on dense clouds; NaN would only disappear later in PCL. Drop it here. + if (!std::isfinite(*iter_x) || !std::isfinite(*iter_y) || !std::isfinite(*iter_z)) + continue; + const Eigen::Vector3d g = T_cloud * Eigen::Vector3d(*iter_x, *iter_y, *iter_z); + if (g.z() <= source.max_obstacle_height && g.z() >= source.min_obstacle_height) + obs.points.push_back(g.cast()); + } + + source.observations.push_front(std::move(obs)); + source.last_updated = robot::Time::now(); + purgeStale(source); + return true; +} + +void DepthCameraObstacleLayer::purgeStale(Source& source) const +{ + if (source.observations.empty()) + return; + // Keeping observations for no time keeps exactly one. + if (source.observation_keep_time == 0.0) + { + source.observations.erase(std::next(source.observations.begin()), source.observations.end()); + return; + } + for (auto it = source.observations.begin(); it != source.observations.end(); ++it) + { + if ((source.last_updated - it->stamp).toSec() > source.observation_keep_time) + { + source.observations.erase(it, source.observations.end()); + return; + } + } +} + +bool DepthCameraObstacleLayer::sourceIsCurrent(const Source& source) const +{ + if (source.expected_update_rate == 0.0) + return true; + const double since = (robot::Time::now() - source.last_updated).toSec(); + const bool current = since <= source.expected_update_rate; + if (!current) + robot::log_warning_throttle(5.0, "DepthCameraObstacleLayer %s: source %s not updated for %.2f s, expected " + "every %.2f s\n", name_.c_str(), source.name.c_str(), since, + source.expected_update_rate); + return current; +} + +void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, + double* min_y, double* max_x, double* max_y) +{ + 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); + + bool current = true; + std::vector frustums; + std::vector combined; + for (const auto& source : sources_) + { + if (!source->marking) + continue; // the source marks and clears with marking observations only + processPending(*source); + purgeStale(*source); + for (const Observation& obs : source->observations) + { + frustums.push_back(obs.frustum); + combined.insert(combined.end(), obs.points.begin(), obs.points.end()); + } + current = sourceIsCurrent(*source) && current; + } + current_ = current; + + pcl::PointCloud::Ptr cloud(new pcl::PointCloud); + cloud->points.reserve(combined.size()); + for (const Eigen::Vector3f& q : combined) + { + pcl::PointXYZI pt; + pt.x = q.x(); + pt.y = q.y(); + pt.z = q.z(); + pt.intensity = 0.f; + cloud->points.push_back(pt); + } + cloud->width = static_cast(cloud->points.size()); + cloud->height = 1; + cloud->is_dense = true; + + // Voxelized combined observation to save computation. + if (use_voxelized_observation_ && !cloud->points.empty()) + { + pcl::VoxelGrid voxel; + voxel.setLeafSize(kObservationLeaf, kObservationLeaf, kObservationLeaf); + voxel.setInputCloud(cloud); + pcl::PointCloud::Ptr filtered(new pcl::PointCloud); + voxel.filter(*filtered); + cloud = filtered; + } + std::vector points; + points.reserve(cloud->points.size()); + for (const auto& pt : cloud->points) + points.emplace_back(pt.x, pt.y, pt.z); + stats_.cloud_points += points.size(); + + clearMarkingByKdtree(points, frustums, robot_x, robot_y, min_x, min_y, max_x, max_y); + + if (cloud->points.size() > 5) + { + pcl::search::KdTree::Ptr tree(new pcl::search::KdTree); + tree->setInputCloud(cloud); + std::vector clusters; + pcl::EuclideanClusterExtraction ec; + ec.setClusterTolerance(ec_seg_distance_); + ec.setMinClusterSize(ec_cluster_min_size_); + ec.setMaxClusterSize(static_cast(cloud->points.size())); + ec.setSearchMethod(tree); + ec.setInputCloud(cloud); + ec.extract(clusters); + std::vector cluster; + for (const pcl::PointIndices& indices : clusters) + { + // PCL can still output clusters below ec_cluster_min_size; the source rejects them here. + if (static_cast(indices.indices.size()) <= size_of_cluster_rejection_) + continue; + cluster.clear(); + for (int idx : indices.indices) + cluster.push_back(points[idx]); + processCluster(frustums, cluster, min_x, min_y, max_x, max_y); + } + } + updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y); + + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + ++stats_.cycles; + stats_.bounds_ms_sum += ms; + stats_.bounds_ms_max = std::max(stats_.bounds_ms_max, ms); + logStats(); +} + +void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vector& cloud, + const std::vector& frustums, + double robot_x, double robot_y, double* min_x, + double* min_y, double* max_x, double* max_y) +{ + bool bypass_clearing = false; + if (enable_near_blocked_protection_ && + static_cast(cloud.size()) < number_points_considered_as_blocked_) + { + robot::log_warning_throttle(30.0, "DepthCameraObstacleLayer %s: blocked by something, clearing is skipped\n", + name_.c_str()); + bypass_clearing = true; + } + + bool clear_all_marking_in_this_frame = false; + pcl::KdTreeFLANN kdtree; + if (cloud.size() > 5) + { + pcl::PointCloud::Ptr input(new pcl::PointCloud); + input->points.reserve(cloud.size()); + for (const Eigen::Vector3f& q : cloud) + { + pcl::PointXYZI pt; + pt.x = q.x(); + pt.y = q.y(); + pt.z = q.z(); + pt.intensity = 0.f; + input->points.push_back(pt); + } + input->width = static_cast(input->points.size()); + input->height = 1; + kdtree.setInputCloud(input); + } + else if (!enable_near_blocked_protection_) + clear_all_marking_in_this_frame = true; // we really see nothing in the space + else + bypass_clearing = true; + if (clear_all_marking_in_this_frame) + ++stats_.cleared_all_frames; + else if (bypass_clearing) + ++stats_.bypassed_frames; + + const double resolution = layered_costmap_->getCostmap()->getResolution(); + std::vector indices; + std::vector sq_distances; + for (auto& column : pc_3d_map_global_) + { + double wx, wy; + 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) + continue; + + auto& heights = column.second; + for (auto it = heights.begin(), next_it = it; it != heights.end(); it = next_it) + { + ++next_it; + // Clearing tests the stored cell-corner position; the attach band is cleared too. + const Eigen::Vector3f search(static_cast(wx), static_cast(wy), + static_cast(it->first * voxel_resolution_)); + if (!insideAnyFrustum(frustums, search)) + continue; + bool erase = false; + if (clear_all_marking_in_this_frame) + erase = true; + else if (!bypass_clearing && pc_dis <= forced_clearing_distance_) + erase = true; + else if (!bypass_clearing) + { + pcl::PointXYZI q; + q.x = search.x(); + q.y = search.y(); + q.z = search.z(); + erase = kdtree.radiusSearch(q, check_radius_, indices, sq_distances) < number_clearing_threshold_; + } + if (!erase) + continue; + heights.erase(it); + ++stats_.cleared; + if (clear_touches_bounds_) + touch(wx, wy, min_x, min_y, max_x, max_y); + } + } +} + +void DepthCameraObstacleLayer::processCluster(const std::vector& frustums, + const std::vector& cluster, double* min_x, + double* min_y, double* max_x, double* max_y) +{ + const double resolution = layered_costmap_->getCostmap()->getResolution(); + const int h_max = static_cast(marking_height_above_ground_ / voxel_resolution_); + const int h_min = static_cast(marking_height_under_ground_ / voxel_resolution_); + for (const Eigen::Vector3f& p : cluster) + { + // Robust marking condition: the raw point, inside a frustum and away from its faces. + if (!insideAnyFrustum(frustums, p) || attachedToFrustums(frustums, p)) + continue; + int mmx, mmy; + worldToIntIndex(p.x(), p.y(), mmx, mmy, resolution); + const int h_ind = static_cast(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)]; + 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); + } +} + +void DepthCameraObstacleLayer::updateFootprint(double robot_x, double robot_y, double robot_yaw, double* min_x, + double* min_y, double* max_x, double* max_y) +{ + if (!footprint_clearing_enabled_) + return; + 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); +} + +bool DepthCameraObstacleLayer::isValid(int mx, int my) const +{ + // Same result as the source's unsigned test: mx - 1 of cell 0 is out of range. + return mx >= 0 && my >= 0 && mx <= static_cast(getSizeInCellsX()) && + my <= static_cast(getSizeInCellsY()); +} + +void DepthCameraObstacleLayer::updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) +{ + 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. + if (footprint_clearing_enabled_) + setConvexPolygonCost(transformed_footprint_, FREE_SPACE); + + switch (combination_method_) + { + case 0: // Overwrite + updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j); + break; + case 1: // Maximum + updateWithMax(master_grid, min_i, min_j, max_i, max_j); + break; + default: // Nothing + break; + } +} + +std::size_t DepthCameraObstacleLayer::storedPoints() const +{ + std::size_t n = 0; + for (const auto& column : pc_3d_map_global_) + n += column.second.size(); + return n; +} + +void DepthCameraObstacleLayer::logStats() +{ + const robot::Time now = robot::Time::now(); + const double since = (now - last_stats_log_).toSec(); + if (since < debug_stats_period_ && since >= 0.0) + return; + 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", + name_.c_str(), stats_.cycles, static_cast(stats_.cloud_points) / stats_.cycles, + storedPoints(), pc_3d_map_global_.size(), stats_.marked, stats_.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(); +} + +void DepthCameraObstacleLayer::activate() +{ + for (const auto& source : sources_) + source->last_updated = robot::Time::now(); +} + +void DepthCameraObstacleLayer::deactivate() +{ + // The source unsubscribes and clears its local-mode map only; the global-mode map stays. + for (const auto& source : sources_) + { + std::lock_guard lock(source->pending_mutex); + source->pending.reset(); + } +} + +void DepthCameraObstacleLayer::reset() +{ + deactivate(); + resetMaps(); + current_ = true; + activate(); +} + +// Export factory function +static boost::shared_ptr create_depth_camera_obstacle_plugin() +{ + return boost::make_shared(); +} + +BOOST_DLL_ALIAS(create_depth_camera_obstacle_plugin, DepthCameraObstacleLayer) + +} // namespace robot_costmap_2d diff --git a/plugins/obstacle_layer.cpp b/plugins/obstacle_layer.cpp index 54cd840..401e159 100755 --- a/plugins/obstacle_layer.cpp +++ b/plugins/obstacle_layer.cpp @@ -296,6 +296,29 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa 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"); + int miss_frames = static_cast(frustum_config.miss_frames); + int band_margin = static_cast(frustum_config.stereo_band_margin_px); + read_depth_option("depth_reobserve_clearing", frustum_config.reobserve_clearing); + read_depth_option("depth_confirm_tolerance_m", frustum_config.confirm_tolerance_m); + read_depth_option("depth_miss_frames", miss_frames); + read_depth_option("depth_no_return_weight", frustum_config.no_return_weight); + read_depth_option("depth_stereo_baseline_m", frustum_config.stereo_baseline_m); + read_depth_option("depth_stereo_band_margin_px", band_margin); + if ((frustum_config.reobserve_clearing || frustum_config.stereo_baseline_m > 0) && + !frustum_config.evidence_points_enabled) + throw std::invalid_argument("depth_reobserve_clearing and depth_stereo_baseline_m require " + "depth_evidence_points_enabled"); + if (!std::isfinite(frustum_config.confirm_tolerance_m) || frustum_config.confirm_tolerance_m <= 0 || + frustum_config.confirm_tolerance_m > 0.5 || miss_frames < 1 || miss_frames > 100 || + !std::isfinite(frustum_config.no_return_weight) || frustum_config.no_return_weight < 0 || + frustum_config.no_return_weight > 1 || !std::isfinite(frustum_config.stereo_baseline_m) || + frustum_config.stereo_baseline_m < 0 || frustum_config.stereo_baseline_m > 1 || + band_margin < 0 || band_margin > 200) + throw std::invalid_argument("depth_confirm_tolerance_m must be in (0, 0.5] m, depth_miss_frames 1..100, " + "depth_no_return_weight 0..1, depth_stereo_baseline_m 0..1 m and " + "depth_stereo_band_margin_px 0..200"); + frustum_config.miss_frames = static_cast(miss_frames); + frustum_config.stereo_band_margin_px = static_cast(band_margin); // 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 && @@ -442,15 +465,20 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa paired_depth_sources_.push_back(paired); 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; " + "unknown/occluded/outside FOV retained; queue=%u age=%.3f s; rule=%s; " "evidence_points=%s per_voxel=%u marking_border=%u px projection_margin=%u px " - "far_return_behind=%s\n", + "far_return_behind=%s; reobserve tolerance=%.3f m miss_frames=%u no_return_weight=%.2f; " + "stereo_baseline=%.3f m band_margin=%u px\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.reobserve_clearing ? "re-observe or clear" : "one valid free frame", 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.far_return_is_behind ? "true" : "false"); + paired->config.far_return_is_behind ? "true" : "false", + paired->config.confirm_tolerance_m, paired->config.miss_frames, + paired->config.no_return_weight, paired->config.stereo_baseline_m, + paired->config.stereo_band_margin_px); } } catch (const YAML::BadFile& e) { diff --git a/plugins/voxel_layer.cpp b/plugins/voxel_layer.cpp index 2dd9088..f70312d 100755 --- a/plugins/voxel_layer.cpp +++ b/plugins/voxel_layer.cpp @@ -336,7 +336,7 @@ void VoxelLayer::markObservation(const Observation& obs, double* min_x, double* // A point at the image edge could never be re-checked with a full patch from the // pose that saw it, and would leave a voxel that only the whole-box rule judges. const Eigen::Vector3d point(*iter_x, *iter_y, *iter_z); - if (paired->config->marking_border_px > 0 && + if ((paired->config->marking_border_px > 0 || paired->config->stereo_baseline_m > 0) && !paired->checker->projectsInside(point, paired->config->marking_border_px)) { ++visibility_counts_.border_dropped; @@ -372,6 +372,37 @@ void VoxelLayer::pruneDepthEvidence() }); } +bool VoxelLayer::reobserveFrees(DepthObservation observation, const DepthEvidenceStore::VoxelKey& key, + const DepthFrustumConfig& config) +{ + float miss = 0.f; + switch (observation) + { + case DepthObservation::Confirmed: + ++visibility_counts_.confirmed; + depth_evidence_.resetMiss(key); + return false; + case DepthObservation::Occluded: + ++visibility_counts_.occluded; + return false; + case DepthObservation::OutOfView: + ++visibility_counts_.out_of_view; + return false; + case DepthObservation::SeenThrough: + ++visibility_counts_.seen_through; + miss = depth_evidence_.addMiss(key, 1.f); + break; + case DepthObservation::NoReturn: + ++visibility_counts_.no_return; + if (config.no_return_weight <= 0) + return false; + miss = depth_evidence_.addMiss(key, static_cast(config.no_return_weight)); + break; + } + // The small slack absorbs float rounding when fractional no-return weights add up. + return miss >= static_cast(config.miss_frames) - 1e-3f; +} + void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x, double* max_y) { for (const auto& source : paired_depth_sources_) @@ -418,6 +449,7 @@ void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x, // With evidence points a voxel is judged by the points that marked it; a voxel // without evidence (marked before the mode was enabled) keeps the whole-box rule. const bool use_evidence = source->config.evidence_points_enabled; + const bool reobserve = use_evidence && source->config.reobserve_clearing; std::vector evidence; std::vector> free_voxels; for (unsigned int y = 0; y < size_y_; ++y) @@ -428,10 +460,17 @@ void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x, { if (robot_voxel_grid_.getVoxel(x, y, z) != robot_voxel_grid::MARKED) continue; DepthVisibilityResult visibility; - if (use_evidence && depth_evidence_.points(evidenceKey(x, y, z), evidence)) + const auto key = evidenceKey(x, y, z); + if (use_evidence && depth_evidence_.points(key, evidence)) { - visibility = checker.classifyPoints(evidence); ++visibility_counts_.by_evidence; + if (reobserve) + { + if (reobserveFrees(checker.observePoints(evidence), key, source->config)) + { free_voxels.push_back({x, y, z}); ++visibility_counts_.free; } + continue; + } + visibility = checker.classifyPoints(evidence); } else { @@ -475,6 +514,7 @@ void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x, robot::log_info_throttle(5.0, "paired depth [%s]: applied=%llu tf_wait=%llu " "invalid=%llu stale=%llu expired=%llu overflow=%llu duplicate=%llu; " "voxel decisions free=%llu surface=%llu unknown=%llu by_evidence=%llu; " + "reobserve confirmed=%llu occluded=%llu seen_through=%llu no_return=%llu out_of_view=%llu; " "border_dropped_points=%llu evidence_voxels=%zu (cumulative)\n", name_.c_str(), static_cast(counts.applied), static_cast(counts.tf_wait), static_cast(counts.invalid), @@ -484,6 +524,11 @@ void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x, static_cast(visibility_counts_.surface), static_cast(visibility_counts_.unknown), static_cast(visibility_counts_.by_evidence), + static_cast(visibility_counts_.confirmed), + static_cast(visibility_counts_.occluded), + static_cast(visibility_counts_.seen_through), + static_cast(visibility_counts_.no_return), + static_cast(visibility_counts_.out_of_view), static_cast(visibility_counts_.border_dropped), depth_evidence_.size()); } } diff --git a/src/costmap_2d_robot.cpp b/src/costmap_2d_robot.cpp index a043de3..6ee7016 100644 --- a/src/costmap_2d_robot.cpp +++ b/src/costmap_2d_robot.cpp @@ -467,7 +467,9 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name, "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_far_return_is_behind"}) + "depth_far_return_is_behind", "depth_reobserve_clearing", + "depth_confirm_tolerance_m", "depth_miss_frames", "depth_no_return_weight", + "depth_stereo_baseline_m", "depth_stereo_band_margin_px"}) 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_evidence_store.cpp b/src/depth_evidence_store.cpp index 7b6b3dc..5396802 100644 --- a/src/depth_evidence_store.cpp +++ b/src/depth_evidence_store.cpp @@ -21,6 +21,7 @@ void DepthEvidenceStore::add(const VoxelKey& key, const Eigen::Vector3f& point, if (!point.allFinite()) return; Entry& entry = entries_[key]; + entry.miss = 0.f; if (fresh || entry.count == 0) { // Slots 0..5 hold min/max of x, y, z; the first point is every extreme. @@ -65,6 +66,22 @@ bool DepthEvidenceStore::points(const VoxelKey& key, std::vectorsecond.miss += weight; + return it->second.miss; +} + +void DepthEvidenceStore::resetMiss(const VoxelKey& key) +{ + const auto it = entries_.find(key); + if (it != entries_.end()) + it->second.miss = 0.f; +} + void DepthEvidenceStore::erase(const VoxelKey& key) { entries_.erase(key); diff --git a/src/depth_visibility.cpp b/src/depth_visibility.cpp index fe52086..8df0ffa 100644 --- a/src/depth_visibility.cpp +++ b/src/depth_visibility.cpp @@ -200,6 +200,16 @@ bool projectToPixel(const Eigen::Vector3d& camera_point, const robot_sensor_msgs } } // namespace +int DepthVisibilityChecker::usableLeft(double z) const +{ + int left = static_cast(config_.clear_left_border_px); + // The right imager cannot see the leftmost fx * B / z columns at depth z: no disparity there. + if (config_.stereo_baseline_m > 0) + left = std::max(left, static_cast(std::ceil(data_->camera_info.K[0] * config_.stereo_baseline_m / z)) + + static_cast(config_.stereo_band_margin_px)); + return left; +} + bool DepthVisibilityChecker::projectsInside(const Eigen::Vector3d& point, unsigned int border_px) const { if (!data_ || !point.allFinite()) @@ -210,12 +220,55 @@ bool DepthVisibilityChecker::projectsInside(const Eigen::Vector3d& point, unsign return false; const int border = static_cast(border_px); int u, v; - return projectToPixel(p, data_->camera_info, - static_cast(config_.clear_left_border_px) + border, + return projectToPixel(p, data_->camera_info, usableLeft(p.z()) + border, static_cast(image.width) - 1 - static_cast(config_.clear_right_border_px) - border, border, static_cast(image.height) - 1 - border, u, v); } +DepthObservation DepthVisibilityChecker::observePoints(const std::vector& points) const +{ + DepthObservation best = DepthObservation::OutOfView; + if (!data_) + return best; + const auto& image = data_->depth; + const int r = static_cast(config_.projection_margin_px); + const double tolerance = config_.confirm_tolerance_m; + for (const auto& point : points) + { + if (!point.allFinite()) + continue; + const Eigen::Vector3d p = camera_from_global_ * point; + if (!p.allFinite() || p.z() < config_.valid_min_z_m || p.z() > config_.valid_max_z_m) + continue; + int u, v; + if (!projectToPixel(p, data_->camera_info, usableLeft(p.z()) + r, + static_cast(image.width) - 1 - static_cast(config_.clear_right_border_px) - r, + r, static_cast(image.height) - 1 - r, u, v)) + continue; + // A return beyond the trusted range only proves free space for a point well inside it. + const bool far_is_behind = config_.far_return_is_behind && p.z() + tolerance < config_.valid_max_z_m; + bool in_front = false, behind = false; + for (int dv = -r; dv <= r; ++dv) + for (int du = -r; du <= r; ++du) + { + const double measured_z = depthAt(u + du, v + dv); + if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m || + (measured_z > config_.valid_max_z_m && !far_is_behind)) + continue; // no return: says nothing about this point + if (std::abs(measured_z - p.z()) <= tolerance) + return DepthObservation::Confirmed; + if (measured_z < p.z()) + in_front = true; + else + behind = true; + } + const DepthObservation seen = in_front ? DepthObservation::Occluded : + behind ? DepthObservation::SeenThrough : DepthObservation::NoReturn; + best = std::max(best, seen); + } + return best; +} + DepthVisibilityResult DepthVisibilityChecker::classifyPoints(const std::vector& points) const { if (!data_ || points.empty()) diff --git a/test/depth_camera_obstacle_layer_test.cpp b/test/depth_camera_obstacle_layer_test.cpp new file mode 100644 index 0000000..f986ce9 --- /dev/null +++ b/test/depth_camera_obstacle_layer_test.cpp @@ -0,0 +1,385 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace robot_costmap_2d; + +namespace +{ +constexpr double kFovW = 1.23; // D410 at 424x240, fx = 300 [rad] +constexpr double kFovV = 0.76; +constexpr char kTopic[] = "/camera/depth/points_proc"; + +// Optical frame "camera" 0.19 m above odom, looking along +x of odom (rotated by yaw). +tf3::TransformStampedMsg pose(robot::Time stamp, double yaw = 0) +{ + tf3::TransformStampedMsg p; + p.header.frame_id = "odom"; + p.child_frame_id = "camera"; + p.header.stamp = tf3::Time(stamp.sec, stamp.nsec); + Eigen::Matrix3d optical; + optical << 0, 0, 1, -1, 0, 0, 0, -1, 0; + Eigen::Quaterniond q(Eigen::AngleAxisd(yaw, Eigen::Vector3d::UnitZ()) * optical); + p.transform.rotation.x = q.x(); + p.transform.rotation.y = q.y(); + p.transform.rotation.z = q.z(); + p.transform.rotation.w = q.w(); + p.transform.translation.z = .19; + return p; +} + +// Points given in odom for a camera at yaw 0; stored in the optical frame of the cloud. +robot_sensor_msgs::PointCloud2 cloud(robot::Time stamp, const std::vector& odom_points) +{ + robot_sensor_msgs::PointCloud2 c; + c.header.stamp = stamp; + c.header.frame_id = "camera"; + c.height = 1; + robot_sensor_msgs::PointCloud2Modifier m(c); + m.setPointCloud2FieldsByString(1, "xyz"); + m.resize(odom_points.size()); + robot_sensor_msgs::PointCloud2Iterator x(c, "x"), y(c, "y"), z(c, "z"); + for (const auto& p : odom_points) + { + *x = -p.y(); + *y = .19 - p.z(); + *z = p.x(); + ++x; + ++y; + ++z; + } + return c; +} + +// 3 x 3 points, 6 cm apart (one per 5 cm voxel), one Euclidean cluster. Kept away from cell +// boundaries: the source stores (int)(x / 0.05), so y = .07 .13 .19 are columns 1 2 3. +std::vector object(double x = 1.02, double y = .13, double z = .30) +{ + std::vector pts; + for (double dy : {-.06, 0., .06}) + for (double dz : {-.06, 0., .06}) + pts.emplace_back(x, y + dy, z + dz); + return pts; +} + +// 11 points in a row 0.6 m behind the object: keeps the cloud above 5 points, own cluster. +std::vector wall() +{ + std::vector pts; + for (int i = -5; i <= 5; ++i) + pts.emplace_back(1.62, i * .06 + .13, .30); + return pts; +} + +std::vector join(std::vector a, const std::vector& b) +{ + a.insert(a.end(), b.begin(), b.end()); + return a; +} + +YAML::Node baseConfig() +{ + YAML::Node cfg; + cfg["enabled"] = true; + cfg["footprint_clearing_enabled"] = false; + cfg["use_global_frame_to_mark"] = true; + cfg["enable_near_blocked_protection"] = false; + cfg["observation_sources"] = "depth_cam"; + cfg["debug"]["stats"] = false; + cfg["depth_cam"]["topic"] = kTopic; + cfg["depth_cam"]["sensor_frame_is_optical"] = true; + cfg["depth_cam"]["FOV_W"] = kFovW; + cfg["depth_cam"]["FOV_V"] = kFovV; + cfg["depth_cam"]["min_detect_distance"] = .15; + cfg["depth_cam"]["max_detect_distance"] = 2.5; + cfg["depth_cam"]["min_obstacle_height"] = .05; + cfg["depth_cam"]["max_obstacle_height"] = 1.0; + return cfg; +} +} // namespace + +// --------------------------------------------------------------------------------------------- +// Frustum geometry +// --------------------------------------------------------------------------------------------- + +TEST(DepthCameraFrustum, InsideFollowsTheConfiguredPyramid) +{ + DepthCameraFrustum f; + f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false); // X forward + const float half_w = std::tan(kFovW / 2), half_v = std::tan(kFovV / 2); + EXPECT_TRUE(f.inside(Eigen::Vector3f(1, 0, 0))); + EXPECT_FALSE(f.inside(Eigen::Vector3f(.1f, 0, 0))); // before the near plane + EXPECT_FALSE(f.inside(Eigen::Vector3f(2.6f, 0, 0))); // beyond the far plane + EXPECT_FALSE(f.inside(Eigen::Vector3f(-1, 0, 0))); + EXPECT_TRUE(f.inside(Eigen::Vector3f(1, .98f * half_w, 0))); + EXPECT_FALSE(f.inside(Eigen::Vector3f(1, 1.02f * half_w, 0))); + EXPECT_FALSE(f.inside(Eigen::Vector3f(1, -1.02f * half_w, 0))); + EXPECT_TRUE(f.inside(Eigen::Vector3f(1, 0, -.98f * half_v))); + EXPECT_FALSE(f.inside(Eigen::Vector3f(1, 0, 1.02f * half_v))); +} + +TEST(DepthCameraFrustum, AttachBandIsTwelveCentimetresFromEveryFace) +{ + DepthCameraFrustum f; + f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false); + EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, 0, 0))); + EXPECT_TRUE(f.nearFace(Eigen::Vector3f(.25f, 0, 0))); // 10 cm past the near plane + EXPECT_TRUE(f.nearFace(Eigen::Vector3f(2.4f, 0, 0))); // 10 cm before the far plane + const float half_w = std::tan(kFovW / 2); + EXPECT_TRUE(f.nearFace(Eigen::Vector3f(1, half_w - .05f, 0))); + EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, half_w - .3f, 0))); +} + +TEST(DepthCameraFrustum, OpticalFrameGivesTheSamePyramid) +{ + DepthCameraFrustum link, optical; + link.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false); + Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); + T.linear() << 0, 0, 1, -1, 0, 0, 0, -1, 0; // optical axes expressed in camera_link + optical.build(T, kFovW, kFovV, .15, 2.5, true); + for (int i = 0; i < 8; ++i) + EXPECT_LT((link.vertices[i] - optical.vertices[i]).norm(), 1e-5f) << "vertex " << i; + EXPECT_TRUE(optical.inside(Eigen::Vector3f(1, 0, 0))); +} + +TEST(DepthCameraFrustum, AttachedUnlessWellInsideAnotherFrustum) +{ + DepthCameraFrustum a, b; + a.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false); + Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); + T.translation() << 0, .3, 0; // second camera 30 cm to the left + b.build(T, kFovW, kFovV, .15, 2.5, false); + const Eigen::Vector3f near_left_face_of_a(1, std::tan(kFovW / 2) - .05f, 0); + EXPECT_TRUE(attachedToFrustums({a}, near_left_face_of_a)); + EXPECT_FALSE(attachedToFrustums({a, b}, near_left_face_of_a)); + EXPECT_FALSE(attachedToFrustums({a}, Eigen::Vector3f(1, 0, 0))); +} + +// --------------------------------------------------------------------------------------------- +// Layer +// --------------------------------------------------------------------------------------------- + +class DepthCameraLayerTest : public ::testing::Test +{ +protected: + tf3::BufferCore tf; + LayeredCostmap parent{"odom", false, false}; + DepthCameraObstacleLayer layer; + uint32_t tick = 0; + double min_x = 0, min_y = 0, max_x = 0, max_y = 0; + + void SetUp() override + { + robot::Time::setNow(robot::Time(100, 0)); + YAML::Node cfg = baseConfig(); + configure(cfg); + robot::NodeHandle nh("~"); + nh.setParam("dcam_test", cfg); + parent.getCostmap()->resizeMap(80, 80, .05, -2, -2); + layer.initialize(&parent, "dcam_test", &tf); + ASSERT_TRUE(layer.isEnabled()); + } + virtual void configure(YAML::Node&) {} + + robot::Time next() + { + return robot::Time(100, ++tick * 10000000); + } + void update() + { + min_x = min_y = 1e9; + max_x = max_y = -1e9; + layer.updateBounds(0, 0, 0, &min_x, &min_y, &max_x, &max_y); + } + void frame(const std::vector& pts, double yaw = 0, bool has_tf = true) + { + const robot::Time stamp = next(); + robot::Time::setNow(stamp); + if (has_tf) + ASSERT_TRUE(tf.setTransform(pose(stamp, yaw), "test")); + layer.dataCallBack(cloud(stamp, pts), kTopic); + update(); + } + unsigned char master(double x = 1.01, double y = .11) + { + Costmap2D& m = *parent.getCostmap(); + m.resetMap(0, 0, m.getSizeInCellsX(), m.getSizeInCellsY()); + layer.updateCosts(m, 0, 0, m.getSizeInCellsX(), m.getSizeInCellsY()); + unsigned int a, b; + EXPECT_TRUE(m.worldToMap(x, y, a, b)); + return m.getCost(a, b); + } +}; + +TEST_F(DepthCameraLayerTest, MarksAClusterInsideTheFrustum) +{ + frame(object()); + EXPECT_EQ(layer.storedPoints(), 9u); + EXPECT_EQ(master(), LETHAL_OBSTACLE); + EXPECT_TRUE(layer.isCurrent()); +} + +TEST_F(DepthCameraLayerTest, SmallClusterAndOutOfHeightPointsAreNotMarked) +{ + std::vector five = object(); + five.resize(5); // <= size_of_cluster_rejection + frame(join(five, wall())); + EXPECT_NE(master(), LETHAL_OBSTACLE); + frame(join(object(1.02, .13, 1.5), wall())); // above max_obstacle_height + EXPECT_NE(master(), LETHAL_OBSTACLE); +} + +TEST_F(DepthCameraLayerTest, KeptWhileSeenAgainAndClearedWhenGone) +{ + frame(join(object(), wall())); + ASSERT_EQ(master(), LETHAL_OBSTACLE); + for (int i = 0; i < 5; ++i) + frame(join(object(), wall())); + EXPECT_EQ(master(), LETHAL_OBSTACLE); + frame(wall()); // no cloud point within check_radius of the stored points + EXPECT_NE(master(), LETHAL_OBSTACLE); + EXPECT_EQ(master(1.61, .11), LETHAL_OBSTACLE); +} + +TEST_F(DepthCameraLayerTest, OutsideTheFrustumIsKept) +{ + frame(object()); + ASSERT_EQ(master(), LETHAL_OBSTACLE); + for (int i = 0; i < 5; ++i) + frame({}, 1.57); // camera turned away, sees nothing + EXPECT_EQ(master(), LETHAL_OBSTACLE); +} + +TEST_F(DepthCameraLayerTest, NearlyEmptyCloudClearsEverythingInViewWithoutProtection) +{ + frame(object()); + ASSERT_EQ(master(), LETHAL_OBSTACLE); + frame({}); + EXPECT_NE(master(), LETHAL_OBSTACLE); +} + +class DepthCameraBlockedTest : public DepthCameraLayerTest +{ +protected: + void configure(YAML::Node& cfg) override + { + cfg["enable_near_blocked_protection"] = true; + } +}; + +TEST_F(DepthCameraBlockedTest, NearlyEmptyCloudSkipsClearingWithProtection) +{ + frame(object()); + ASSERT_EQ(master(), LETHAL_OBSTACLE); + for (int i = 0; i < 5; ++i) + frame({}); + EXPECT_EQ(master(), LETHAL_OBSTACLE); + frame(wall()); + EXPECT_NE(master(), LETHAL_OBSTACLE); +} + +TEST_F(DepthCameraLayerTest, AttachBandIsNotMarked) +{ + // 10 cm past the near plane (0.15 m) of a camera at x = 0: inside, but attached. + frame(wall()); + const std::size_t wall_points = layer.storedPoints(); + ASSERT_GT(wall_points, 0u); + frame(join(object(.25, .10, .19), wall())); + EXPECT_EQ(layer.storedPoints(), wall_points); +} + +TEST_F(DepthCameraLayerTest, WaitsForTheMeasurementTfThenDropsAfterTheTolerance) +{ + frame(object(), 0, false); // no TF at this stamp yet + EXPECT_EQ(layer.storedPoints(), 0u); + const robot::Time stamp(100, tick * 10000000); + ASSERT_TRUE(tf.setTransform(pose(stamp), "late_tf")); + update(); + EXPECT_EQ(layer.storedPoints(), 9u); + + frame(object(1.32, -.47, .3), 0, false); + const robot::Time late(100, tick * 10000000); + robot::Time::setNow(robot::Time(101, 0)); // older than transform_tolerance (0.2 s) + update(); + ASSERT_TRUE(tf.setTransform(pose(late), "too_late_tf")); + update(); + EXPECT_NE(master(1.31, -.44), LETHAL_OBSTACLE); // the waiting cloud was dropped + EXPECT_EQ(layer.storedPoints(), 9u); +} + +TEST_F(DepthCameraLayerTest, OtherTopicsAndDepthImagesAreIgnored) +{ + const robot::Time stamp = next(); + robot::Time::setNow(stamp); + ASSERT_TRUE(tf.setTransform(pose(stamp), "test")); + layer.dataCallBack(cloud(stamp, object()), "/other/points"); + robot_sensor_msgs::DepthCameraData::ConstPtr depth = boost::make_shared(); + layer.dataCallBack(depth, kTopic); + update(); + EXPECT_EQ(layer.storedPoints(), 0u); +} + +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()); + EXPECT_EQ(layer.storedPoints(), 0u); +} + +TEST_F(DepthCameraLayerTest, ClearedPointsDoNotTouchTheBoundsByDefault) +{ + frame(join(object(), wall())); + frame(wall()); + EXPECT_GT(min_x, 1.5); // only the wall marking touched the bounds +} + +class DepthCameraTouchTest : public DepthCameraLayerTest +{ +protected: + void configure(YAML::Node& cfg) override + { + cfg["clear_touches_bounds"] = true; + } +}; + +TEST_F(DepthCameraTouchTest, ClearedPointsTouchTheBoundsWhenEnabled) +{ + frame(join(object(), wall())); + frame(wall()); + EXPECT_LT(min_x, 1.05); // the cleared object cell is reset in the master too +} + +TEST(DepthCameraLayerConfig, RejectsUnportedModeAndOutOfRangeValues) +{ + tf3::BufferCore tf; + LayeredCostmap parent{"odom", false, false}; + parent.getCostmap()->resizeMap(80, 80, .05, -2, -2); + robot::NodeHandle nh("~"); + const auto expectThrow = [&](const YAML::Node& cfg) { + nh.setParam("dcam_bad", cfg); + DepthCameraObstacleLayer layer; + EXPECT_THROW(layer.initialize(&parent, "dcam_bad", &tf), std::invalid_argument); + }; + YAML::Node cfg = baseConfig(); + cfg["use_global_frame_to_mark"] = false; + expectThrow(cfg); + cfg = baseConfig(); + cfg["depth_cam"]["FOV_W"] = 3.5; + expectThrow(cfg); + cfg = baseConfig(); + cfg["depth_cam"]["min_detect_distance"] = 3.0; + expectThrow(cfg); + cfg = baseConfig(); + cfg["voxel_resolution"] = 0.0; + expectThrow(cfg); +} diff --git a/test/depth_evidence_store_test.cpp b/test/depth_evidence_store_test.cpp index a7e7dcd..2c80656 100644 --- a/test/depth_evidence_store_test.cpp +++ b/test/depth_evidence_store_test.cpp @@ -87,6 +87,22 @@ TEST(DepthEvidenceStore, EraseEraseIfClearAndNonFinite) EXPECT_EQ(store.size(), 0u); } +TEST(DepthEvidenceStore, MissCountRestartsOnMarkingAndLeavesWithTheVoxel) +{ + DepthEvidenceStore store(8); + const DepthEvidenceStore::VoxelKey key{1, 2, 3}; + EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 0.f); // no evidence, nothing to count + store.add(key, Eigen::Vector3f(1.f, 2.f, .3f), false); + EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 1.f); + EXPECT_FLOAT_EQ(store.addMiss(key, .5f), 1.5f); + store.add(key, Eigen::Vector3f(1.01f, 2.f, .3f), false); // marked again + EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 1.f); + store.resetMiss(key); + EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 1.f); + store.erase(key); + EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 0.f); +} + TEST(DepthEvidenceStore, CapacityIsClamped) { EXPECT_EQ(DepthEvidenceStore(2).pointsPerVoxel(), DepthEvidenceStore::kExtremeSlots); diff --git a/test/depth_observation_buffer_test.cpp b/test/depth_observation_buffer_test.cpp index c53887f..5aa5ea9 100644 --- a/test/depth_observation_buffer_test.cpp +++ b/test/depth_observation_buffer_test.cpp @@ -247,7 +247,9 @@ TEST(DepthBuffer, RuntimeFactoryForwardsObservedVolumeModeAndPairsSources) 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_far_return_is_behind"}) + "depth_far_return_is_behind", "depth_reobserve_clearing", "depth_confirm_tolerance_m", + "depth_miss_frames", "depth_no_return_weight", "depth_stereo_baseline_m", + "depth_stereo_band_margin_px"}) { 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 44d95f9..e0fc686 100644 --- a/test/depth_visibility_test.cpp +++ b/test/depth_visibility_test.cpp @@ -133,6 +133,77 @@ TEST(DepthVisibility, ProjectsInsideHonoursBorderAndUsableStrips) { EXPECT_FALSE(c.projectsInside(Eigen::Vector3d(-.89,0,1),2)); // u = 11, inside the left strip + 2 EXPECT_FALSE(c.projectsInside(Eigen::Vector3d(0,0,.05),2)); // nearer than valid_min_z } +// Re-observe-or-clear checker. Camera frame == global frame; (0,0,1) projects to u = 100, v = 80. +void setPixel(robot_sensor_msgs::DepthCameraData::Ptr& d,unsigned u,unsigned v,double meters) { + uint16_t value=static_cast(meters*1000);std::memcpy(&d->depth.data[v*400+u*2],&value,2); +} +tf3::TransformStampedMsg identity() { + 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;return p; +} +TEST(DepthReobserve, FourOutcomesOfOnePoint) { + DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity(); + const std::vector point{Eigen::Vector3d(0,0,1)}; + auto d=depth(1.03);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints(point),DepthObservation::Confirmed); // within 5 cm + d=depth(.9);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints(point),DepthObservation::Occluded); + d=depth(1.2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints(point),DepthObservation::SeenThrough); + d=depth(0);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints(point),DepthObservation::NoReturn); +} +TEST(DepthReobserve, OutOfViewWhenNotProjectableOrOutsideTheTrustedRange) { + DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity(); + auto d=depth(2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints({}),DepthObservation::OutOfView); + EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,-1)}),DepthObservation::OutOfView); // behind the camera + EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,3.5)}),DepthObservation::OutOfView); // beyond valid_max_z_m + EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,-.80,1)}),DepthObservation::OutOfView); // v = 0: no full patch + EXPECT_EQ(c.observePoints({Eigen::Vector3d(5,0,1)}),DepthObservation::OutOfView); // right of the image +} +TEST(DepthReobserve, InvalidPixelsDoNotBlockSeeingThrough) { + DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity(); + const std::vector point{Eigen::Vector3d(0,0,1)}; + auto d=depth(0);setPixel(d,101,81,2); // one valid pixel behind, eight with no return + ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints(point),DepthObservation::SeenThrough); +} +TEST(DepthReobserve, OccluderInThePatchBeatsSeenThroughAndConfirmBeatsBoth) { + DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity(); + const std::vector point{Eigen::Vector3d(0,0,1)}; + auto d=depth(2);setPixel(d,99,79,.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints(point),DepthObservation::Occluded); + setPixel(d,101,81,1.02);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints(point),DepthObservation::Confirmed); + // The voxel takes its strongest point: one point still on a surface keeps it. + d=depth(1.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,1),Eigen::Vector3d(0,0,1.5)}),DepthObservation::Confirmed); + d=depth(1.2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,1),Eigen::Vector3d(0,0,1.5)}),DepthObservation::Occluded); +} +TEST(DepthReobserve, FarReturnIsBehindOnlyWhenEnabledAndInsideTheRange) { + DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity(); + auto d=depth(4);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,1)}),DepthObservation::NoReturn); + cfg.far_return_is_behind=true;ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,1)}),DepthObservation::SeenThrough); + EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,2.99)}),DepthObservation::NoReturn); // 2.99 + 0.05 >= 3 +} +// fx = 100: the band at depth z is ceil(100 * 0.1 / z) + 10 px. Column u = 30 is in it at 0.5 m +// (30 + 1 px patch > 30) and clear of it at 2.5 m (14 + 1 px). +TEST(DepthReobserve, StereoBandIsOutOfViewNearAndUsableFar) { + DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity(); + const Eigen::Vector3d near(-.35,0,.5), far(-1.75,0,2.5); // both u = 30 + auto d=depth(.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints({near}),DepthObservation::Confirmed); // band disabled + cfg.stereo_baseline_m=.1;cfg.stereo_band_margin_px=10;ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints({near}),DepthObservation::OutOfView); + EXPECT_FALSE(c.projectsInside(near,2)); + d=depth(2.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg)); + EXPECT_EQ(c.observePoints({far}),DepthObservation::Confirmed); + EXPECT_TRUE(c.projectsInside(far,2)); +} TEST(DepthPairer, MissingHalfExactPairAndDeduplication) { robot::Time::setNow(robot::Time(100,0));DepthFrustumConfig cfg;DepthFramePairer p(cfg,.5); auto c=cloud(robot::Time(100,0));p.addCloud(c);DepthFramePairer::Candidate next; @@ -175,6 +246,8 @@ protected: // 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; + cfg["pc_clearing"]["depth_reobserve_clearing"]=false; + cfg["pc_clearing"]["depth_stereo_baseline_m"]=0.0; configure(cfg); robot::NodeHandle nh("~");nh.setParam("depth_test",cfg); parent.getCostmap()->resizeMap(80,80,.05,-2,-2);layer.initialize(&parent,"depth_test",&tf); @@ -394,6 +467,76 @@ TEST_F(DepthFarReturnLayerTest, FarReturnClearsWhenEnabledButNoDataStillKeeps) { frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); frame(0);EXPECT_EQ(at(),LETHAL_OBSTACLE); } +// Re-observe-or-clear on the layer. The marked point (0.62, 0.01, 0.08) projects to (98, 98); +// frame(m) shows depth m everywhere: .62 re-observes it, 2 sees through, .4 occludes, 0 is no return. +class DepthReobserveLayerTest:public DepthEvidenceLayerTest { +protected: + void configure(YAML::Node& cfg) override { + DepthEvidenceLayerTest::configure(cfg); + cfg["pc_clearing"]["depth_reobserve_clearing"]=true; + cfg["pc_clearing"]["depth_confirm_tolerance_m"]=.05; + cfg["pc_clearing"]["depth_miss_frames"]=3; + cfg["pc_clearing"]["depth_no_return_weight"]=noReturnWeight(); + cfg["pc_clearing"]["depth_stereo_baseline_m"]=stereoBaseline(); + cfg["pc_clearing"]["depth_stereo_band_margin_px"]=10; + } + virtual double noReturnWeight() const {return 0.;} + virtual double stereoBaseline() const {return 0.;} +}; +TEST_F(DepthReobserveLayerTest, SeenThroughFreesOnlyAfterMissFrames) { + frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); + frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE); + frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE); + frame(2);EXPECT_EQ(at(),FREE_SPACE); +} +TEST_F(DepthReobserveLayerTest, ConfirmRestartsTheMissCount) { + frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); + frame(2);frame(2);frame(.62); // surface measured again, no marking point + frame(2);frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE); + frame(2);EXPECT_EQ(at(),FREE_SPACE); +} +TEST_F(DepthReobserveLayerTest, RemarkedVoxelStartsANewMissCount) { + frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); + frame(2); + frameCloud(2,-.01f,.11f,.62f); // seen through (2nd miss), then marked again in the same frame + frame(2);frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE); + frame(2);EXPECT_EQ(at(),FREE_SPACE); +} +TEST_F(DepthReobserveLayerTest, OccludedOutOfViewAndNoReturnNeverExpire) { + frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); + for(int i=0;i<20;++i) frame(.4); + EXPECT_EQ(at(),LETHAL_OBSTACLE); + for(int i=0;i<20;++i) frame(2,false,1.57); // camera turned away + EXPECT_EQ(at(),LETHAL_OBSTACLE); + for(int i=0;i<20;++i) frame(0); + EXPECT_EQ(at(),LETHAL_OBSTACLE); + frame(2);frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE); // none of the above counted as a miss + frame(2);EXPECT_EQ(at(),FREE_SPACE); +} +TEST_F(DepthReobserveLayerTest, StillVisibleObjectIsKept) { + frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); + for(int i=0;i<20;++i) frame(i%2?.64:.60); // depth noise inside the 5 cm tolerance + EXPECT_EQ(at(),LETHAL_OBSTACLE); +} +class DepthReobserveNoReturnTest:public DepthReobserveLayerTest { +protected: + double noReturnWeight() const override {return .5;} +}; +TEST_F(DepthReobserveNoReturnTest, NoReturnFreesWhenWeighted) { + frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE); + for(int i=0;i<5;++i) frame(0); + EXPECT_EQ(at(),LETHAL_OBSTACLE); // 2.5 misses + frame(0);EXPECT_EQ(at(),FREE_SPACE); +} +// Band at 0.62 m: ceil(100 * 0.1 / 0.62) + 10 = 27 px, plus the 2 px marking border. +class DepthReobserveStereoBandTest:public DepthReobserveLayerTest { +protected: + double stereoBaseline() const override {return .1;} +}; +TEST_F(DepthReobserveStereoBandTest, MarkingSkipsTheStereoBand) { + frameCloud(.62,-.496f,.11f,.62f);EXPECT_NE(at(.62,.496),LETHAL_OBSTACLE); // u = 20 + frameCloud(.62,-.248f,.11f,.62f);EXPECT_EQ(at(.62,.248),LETHAL_OBSTACLE); // u = 60 +} } int main(int argc,char**argv) {robot::Time::init();testing::InitGoogleTest(&argc,argv);return RUN_ALL_TESTS();}