/********************************************************************* * 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 clearing and marking algorithm is the source's (kd-tree "seen again" test inside the * frustums, Euclidean clusters away from the frustum faces). How the result reaches the costmap * follows the CostmapLayer contract of ObstacleLayer/VoxelLayer instead of the source, which * wrote LETHAL straight into the master and left its own grid empty: * - the stored 3D points (pc_3d_map_global_) stay the source of truth, and this layer's own * grid mirrors them cell by cell: a column with points is LETHAL, a column that loses its * last point becomes FREE_SPACE, and every such change touches the update bounds, so a * cleared cell leaves the master in the same cycle (the source's B7); * - updateCosts() only merges the own grid (combination_method), like ObstacleLayer; * - reset(), clearArea() and footprint clearing also erase the stored points, so * Costmap2DROBOT::resetLayers() and ClearCostmapRecovery work on this layer (the source's * reset() kept its global-mode points, B9). * Host adaptations: data arrives through handleImpl() and a cloud is processed in * updateBounds() once TF at its stamp exists (the role of the tf2_ros::MessageFilter); * getType() is its own DEPTH_CAMERA_LAYER, which SensorGateway feeds PointCloud2 and * DepthCameraData; no ROS publishers or dynamic_reconfigure; `sensor_frame_is_optical` builds the frustum in a Z-forward * optical frame; markings that leave the rolling window are dropped (B6). * Additions over the source, both off by default so the source behaviour stays the default: * the attach band width is a per-source parameter (`attach_distance`, the source hard-codes * 0.12 m), and `occlusion_guard` adds depth-ray evidence to the clearing (keep a stored point a * nearer return hides, clear one the camera sees past). *********************************************************************/ #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 ("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] /// [m] Points this close to a face are not marked: an object cut by the image edge or the /// noisy image border. 0.12 in the source; a wide band hides low objects near the lower FOV edge. float attach_distance = 0.12f; /** * @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 * @param attach_d width of the attach band [m], see attach_distance */ void build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, double min_d, double max_d, bool optical, double attach_d = 0.12); /// Inside all 6 faces (FrustumUtils::isInsideFRUSTUMwoAttach without the band test). bool inside(const Eigen::Vector3f& p) const; /// Within attach_distance of a face plane and within max_detect_distance + 0.5 m of the origin in XY. bool nearFace(const Eigen::Vector3f& p) const; }; /** * @brief Nearest depth return per viewing ray of one observation, for the occlusion guard. * * Rays are binned by their tangent (x / z and y / z in the optical frame); each bin keeps the * smallest range it saw. It is built from the whole cloud before the height gate: the floor the * gate drops is exactly what shows that a stored point is no longer there. */ struct DepthCameraRangeImage { /// What the returns around the ray to a stored point say about it. enum class Evidence { kNone, ///< no usable return around the ray, or a return at the point itself kOccluded, ///< something nearer hides the point: clearing must keep it kSeenThrough, ///< the camera sees past the point: it is gone }; /// Empty image covering the frustum of a sensor at T_global_sensor. void reset(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, bool optical); /// Adds one return given in the sensor frame. void addSensorPoint(const Eigen::Vector3f& p); /// Evidence about a point given in the global frame; kNone while the image is empty. Evidence test(const Eigen::Vector3f& p_global) const; bool empty() const { return min_range_.empty(); } private: Eigen::Vector3f toOptical(const Eigen::Vector3f& p) const; /// Bin of a point in optical coordinates; false when it is too close or outside the image. bool bin(const Eigen::Vector3f& q, int& u, int& v) const; std::size_t index(int u, int v) const { return static_cast(v + half_v_) * (2 * half_u_ + 1) + static_cast(u + half_u_); } Eigen::Isometry3f sensor_from_global_ = Eigen::Isometry3f::Identity(); bool optical_ = true; int half_u_ = 0; int half_v_ = 0; std::vector min_range_; ///< [m] (2 half_u + 1) x (2 half_v + 1), +inf where nothing returned }; /// 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; /// Drops the stored points and the buffered observations as well as the own grid. void reset() override; /** * @brief Same contract as CostmapLayer::clearArea(), applied to the stored points too. * * Cells strictly inside (start, end) are kept and the rest is cleared when invert_area is * false; invert_area true clears the inside instead. Called by ClearCostmapRecovery with the * layer mutex held (recursive). */ void clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area = false) override; /// Own type: SensorGateway delivers PointCloud2 and DepthCameraData to it, not LaserScan. LayerType getType() const override { return LayerType::DEPTH_CAMERA_LAYER; } /// Resizes the own grid to the master and re-marks the stored columns right away. void matchSize() override; /// 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; DepthCameraRangeImage range; ///< whole cloud before the gate; empty unless occlusion_guard }; /// 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] double attach_distance = 0.12; ///< [m] marking-free band near each frustum face 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; /// range_images[i] belongs to frustums[i]; null when that observation has no range image. void clearMarkingByKdtree(const std::vector& cloud, const std::vector& frustums, const std::vector& range_images, 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; /// Own-grid cell of a stored column; false when it is outside the window or on its edge. bool columnCell(const std::pair& column, unsigned int& mx, unsigned int& my) const; /// Drops columns that left the window (B6), frees edge cells, re-marks cells a column lost. void dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x, double* max_y); /// The column became empty: erase it, free its own-grid cell and touch the bounds. std::map, std::map>::iterator eraseColumn( std::map, std::map>::iterator it, double* min_x, double* min_y, double* max_x, double* max_y); void logStats(); // (int)(x / res) toward zero and back to the cell corner, exactly as the source stores points. 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 debug_stats_ = true; ///< debug/stats: periodic counters log double debug_stats_period_ = 5.0; ///< [s] bool occlusion_guard_ = false; ///< depth-ray evidence in the clearing, see clearMarkingByKdtree /// (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 footprint_cleared = 0; ///< columns erased under the robot footprint std::size_t cleared_all_frames = 0; std::size_t bypassed_frames = 0; std::size_t tf_waits = 0; std::size_t tf_drops = 0; std::size_t dropped_out_of_window = 0; std::size_t kept_occluded = 0; ///< points the kd-tree test would clear, kept as hidden std::size_t cleared_seen_through = 0; ///< points the kd-tree test would keep, cleared as seen past 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_