/********************************************************************* * 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 #include #include #include #include #include namespace robot_costmap_2d { namespace { // 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; // Occlusion guard. The values were checked on 10 KIT robot bags (22-23/10/2026) with an offline // replay of this layer; change them only with a new replay. // Ray bin in tangent units: 0.01 is ~0.57 deg, ~1.7 px of the D410 at fx = 300. constexpr float kRangeBin = 0.01f; // Returns and stored points closer than this along the viewing axis carry no evidence [m]. constexpr float kRangeMinDepth = 0.1f; // Depth noise band around a stored point at range r: kRangeMargin + kRangeMarginPerSqM * r^2 [m]. // Stereo depth error grows with r^2. constexpr float kRangeMargin = 0.05f; constexpr float kRangeMarginPerSqM = 0.02f; // Of the 3 x 3 bins around the ray: this many nearer bins hide the point... constexpr int kOccludingBins = 2; // ...and this many farther bins, the centre one among them, show that the camera sees past it. constexpr int kSeeThroughBins = 6; 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; } 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, double attach_d) { max_detect_distance = max_d; attach_distance = static_cast(attach_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 <= attach_distance && 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; } // --------------------------------------------------------------------------------------------- // Range image (occlusion guard, an addition of this port) // --------------------------------------------------------------------------------------------- void DepthCameraRangeImage::reset(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, bool optical) { sensor_from_global_ = T_global_sensor.inverse().cast(); optical_ = optical; // One spare bin on each side: a ray on the frustum edge still has all its 3 x 3 neighbours. half_u_ = static_cast(std::ceil(std::tan(fov_w / 2.0) / kRangeBin)) + 1; half_v_ = static_cast(std::ceil(std::tan(fov_v / 2.0) / kRangeBin)) + 1; min_range_.assign(static_cast(2 * half_u_ + 1) * static_cast(2 * half_v_ + 1), std::numeric_limits::infinity()); } Eigen::Vector3f DepthCameraRangeImage::toOptical(const Eigen::Vector3f& p) const { // Same axes as DepthCameraFrustum::build: camera_link X forward, Y left, Z up. return optical_ ? p : Eigen::Vector3f(-p.y(), -p.z(), p.x()); } bool DepthCameraRangeImage::bin(const Eigen::Vector3f& q, int& u, int& v) const { if (min_range_.empty() || !(q.z() > kRangeMinDepth)) return false; const float fu = q.x() / q.z() / kRangeBin; const float fv = q.y() / q.z() / kRangeBin; if (!(std::fabs(fu) <= half_u_ + 0.5f) || !(std::fabs(fv) <= half_v_ + 0.5f)) return false; u = static_cast(std::lround(fu)); v = static_cast(std::lround(fv)); return std::abs(u) <= half_u_ && std::abs(v) <= half_v_; } void DepthCameraRangeImage::addSensorPoint(const Eigen::Vector3f& p) { const Eigen::Vector3f q = toOptical(p); int u, v; if (!bin(q, u, v)) return; float& slot = min_range_[index(u, v)]; slot = std::min(slot, q.norm()); } DepthCameraRangeImage::Evidence DepthCameraRangeImage::test(const Eigen::Vector3f& p_global) const { const Eigen::Vector3f q = toOptical(sensor_from_global_ * p_global); int u, v; if (!bin(q, u, v)) return Evidence::kNone; const float r = q.norm(); const float margin = kRangeMargin + kRangeMarginPerSqM * r * r; int nearer = 0, farther = 0; for (int du = -1; du <= 1; ++du) { for (int dv = -1; dv <= 1; ++dv) { const int a = u + du, b = v + dv; if (std::abs(a) > half_u_ || std::abs(b) > half_v_) continue; // Only the nearest return of a bin counts: a bin that grazes the floor spans tens of // centimetres of range, so its farthest return says nothing. +inf (no return) counts for neither. const float m = min_range_[index(a, b)]; if (m < r - margin) ++nearer; else if (std::isfinite(m) && m > r + margin) ++farther; } } const float centre = min_range_[index(u, v)]; if (nearer >= kOccludingBins || centre < r - margin) return Evidence::kOccluded; if (farther >= kSeeThroughBins && std::isfinite(centre) && centre > r + margin) return Evidence::kSeenThrough; return Evidence::kNone; } // --------------------------------------------------------------------------------------------- // 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() { // Step 1 of the config flow: the default file, like the other layers. A missing file or block // stops the costmap from being built instead of running on C++ defaults. const std::string config_file_name = "depth_camera_obstacle_layer_params.yaml"; const char* env_config = std::getenv("PNKX_NAV_CORE_CONFIG_DIR"); const std::string folder = (env_config && std::filesystem::exists(env_config)) ? env_config : ""; YAML::Node config; try { config = YAML::LoadFile(getSourceFile(folder, config_file_name)); } catch (const YAML::BadFile&) { throw std::runtime_error("DepthCameraObstacleLayer " + name_ + ": cannot open the default file " + config_file_name); } YAML::Node layer = config["depth_camera_obstacle_layer"]; if (!layer.IsMap()) throw std::runtime_error("DepthCameraObstacleLayer " + name_ + ": " + config_file_name + " has no depth_camera_obstacle_layer: block"); // ===== 1. Defaults from the layer's file ===== // track_unknown_space is not in the file on purpose: unset, the layer follows the costmap. bool track_unknown_space = loadParam(layer, "track_unknown_space", layered_costmap_->isTrackingUnknown()); enabled_ = loadParam(layer, "enabled", true); footprint_clearing_enabled_ = loadParam(layer, "footprint_clearing_enabled", true); combination_method_ = loadParam(layer, "combination_method", 1); enable_near_blocked_protection_ = loadParam(layer, "enable_near_blocked_protection", true); number_points_considered_as_blocked_ = loadParam(layer, "number_points_considered_as_blocked", 5); forced_clearing_distance_ = loadParam(layer, "forced_clearing_distance", 0.1); ec_seg_distance_ = loadParam(layer, "ec_seg_distance", 0.2); ec_cluster_min_size_ = loadParam(layer, "ec_cluster_min_size", 5); size_of_cluster_rejection_ = loadParam(layer, "size_of_cluster_rejection", 5); voxel_resolution_ = loadParam(layer, "voxel_resolution", 0.01); check_radius_ = loadParam(layer, "check_radius", 0.1); number_clearing_threshold_ = loadParam(layer, "number_clearing_threshold", 2); use_voxelized_observation_ = loadParam(layer, "use_voxelized_observation", true); transform_tolerance_ = loadParam(layer, "transform_tolerance", 0.2); bool use_global_frame_to_mark = loadParam(layer, "use_global_frame_to_mark", true); std::string topics_string = loadParam(layer, "observation_sources", std::string("")); debug_stats_ = loadParam(layer["debug"], "stats", true); debug_stats_period_ = loadParam(layer["debug"], "stats_period", 5.0); occlusion_guard_ = loadParam(layer, "occlusion_guard", false); // ===== 2. Override from "/", which copyParentParameters() filled from the // shared ":" block (only when the key exists) ===== // getParam() gets the current value as its default: a value of the wrong type then keeps the // file default instead of becoming 0/false/"". A wrong type in the shared block already stopped // copyParentParameters(). robot::NodeHandle nh("~"); robot::NodeHandle priv_nh(nh, name_); if (priv_nh.hasParam("track_unknown_space")) priv_nh.getParam("track_unknown_space", track_unknown_space, track_unknown_space); if (priv_nh.hasParam("enabled")) priv_nh.getParam("enabled", enabled_, enabled_); if (priv_nh.hasParam("footprint_clearing_enabled")) priv_nh.getParam("footprint_clearing_enabled", footprint_clearing_enabled_, footprint_clearing_enabled_); if (priv_nh.hasParam("combination_method")) priv_nh.getParam("combination_method", combination_method_, combination_method_); if (priv_nh.hasParam("enable_near_blocked_protection")) priv_nh.getParam("enable_near_blocked_protection", enable_near_blocked_protection_, enable_near_blocked_protection_); if (priv_nh.hasParam("number_points_considered_as_blocked")) priv_nh.getParam("number_points_considered_as_blocked", number_points_considered_as_blocked_, number_points_considered_as_blocked_); if (priv_nh.hasParam("forced_clearing_distance")) priv_nh.getParam("forced_clearing_distance", forced_clearing_distance_, forced_clearing_distance_); if (priv_nh.hasParam("ec_seg_distance")) priv_nh.getParam("ec_seg_distance", ec_seg_distance_, ec_seg_distance_); if (priv_nh.hasParam("ec_cluster_min_size")) priv_nh.getParam("ec_cluster_min_size", ec_cluster_min_size_, ec_cluster_min_size_); if (priv_nh.hasParam("size_of_cluster_rejection")) priv_nh.getParam("size_of_cluster_rejection", size_of_cluster_rejection_, size_of_cluster_rejection_); if (priv_nh.hasParam("voxel_resolution")) priv_nh.getParam("voxel_resolution", voxel_resolution_, voxel_resolution_); if (priv_nh.hasParam("check_radius")) priv_nh.getParam("check_radius", check_radius_, check_radius_); if (priv_nh.hasParam("number_clearing_threshold")) priv_nh.getParam("number_clearing_threshold", number_clearing_threshold_, number_clearing_threshold_); if (priv_nh.hasParam("use_voxelized_observation")) priv_nh.getParam("use_voxelized_observation", use_voxelized_observation_, use_voxelized_observation_); if (priv_nh.hasParam("transform_tolerance")) priv_nh.getParam("transform_tolerance", transform_tolerance_, transform_tolerance_); if (priv_nh.hasParam("use_global_frame_to_mark")) priv_nh.getParam("use_global_frame_to_mark", use_global_frame_to_mark, use_global_frame_to_mark); if (priv_nh.hasParam("observation_sources")) priv_nh.getParam("observation_sources", topics_string, topics_string); if (priv_nh.hasParam("debug/stats")) priv_nh.getParam("debug/stats", debug_stats_, debug_stats_); if (priv_nh.hasParam("debug/stats_period")) priv_nh.getParam("debug/stats_period", debug_stats_period_, debug_stats_period_); if (priv_nh.hasParam("occlusion_guard")) priv_nh.getParam("occlusion_guard", occlusion_guard_, occlusion_guard_); default_value_ = track_unknown_space ? NO_INFORMATION : FREE_SPACE; if (layer["clear_touches_bounds"] || priv_nh.hasParam("clear_touches_bounds")) robot::log_warning("DepthCameraObstacleLayer %s: clear_touches_bounds is obsolete and ignored: a cleared " "cell now always resets its master cell\n", name_.c_str()); // 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(topics_string); std::string name; while (ss >> name) { std::unique_ptr src(new Source()); src->name = name; // ===== 1. Defaults. Like obstacle_layer_params.yaml, the file has no block per source, so // these are the C++ defaults unless the file gains one ===== src->topic = loadParam(layer[name], "topic", name); src->sensor_frame = loadParam(layer[name], "sensor_frame", std::string("")); src->sensor_frame_is_optical = loadParam(layer[name], "sensor_frame_is_optical", false); src->observation_keep_time = loadParam(layer[name], "observation_persistence", 0.0); src->expected_update_rate = loadParam(layer[name], "expected_update_rate", 0.0); src->min_obstacle_height = loadParam(layer[name], "min_obstacle_height", 0.0); src->max_obstacle_height = loadParam(layer[name], "max_obstacle_height", 2.0); src->marking = loadParam(layer[name], "marking", true); src->fov_v = loadParam(layer[name], "FOV_V", 1.0); src->fov_w = loadParam(layer[name], "FOV_W", 1.5); src->min_detect_distance = loadParam(layer[name], "min_detect_distance", 0.15); src->max_detect_distance = loadParam(layer[name], "max_detect_distance", 2.5); src->attach_distance = loadParam(layer[name], "attach_distance", 0.12); bool inf_is_valid = loadParam(layer[name], "inf_is_valid", false); // ===== 2. Override from "//" ===== robot::NodeHandle source_nh(priv_nh, name); if (source_nh.hasParam("topic")) source_nh.getParam("topic", src->topic, src->topic); if (source_nh.hasParam("sensor_frame")) source_nh.getParam("sensor_frame", src->sensor_frame, src->sensor_frame); if (source_nh.hasParam("sensor_frame_is_optical")) source_nh.getParam("sensor_frame_is_optical", src->sensor_frame_is_optical, src->sensor_frame_is_optical); if (source_nh.hasParam("observation_persistence")) source_nh.getParam("observation_persistence", src->observation_keep_time, src->observation_keep_time); if (source_nh.hasParam("expected_update_rate")) source_nh.getParam("expected_update_rate", src->expected_update_rate, src->expected_update_rate); if (source_nh.hasParam("min_obstacle_height")) source_nh.getParam("min_obstacle_height", src->min_obstacle_height, src->min_obstacle_height); if (source_nh.hasParam("max_obstacle_height")) source_nh.getParam("max_obstacle_height", src->max_obstacle_height, src->max_obstacle_height); if (source_nh.hasParam("marking")) source_nh.getParam("marking", src->marking, src->marking); if (source_nh.hasParam("FOV_V")) source_nh.getParam("FOV_V", src->fov_v, src->fov_v); if (source_nh.hasParam("FOV_W")) source_nh.getParam("FOV_W", src->fov_w, src->fov_w); if (source_nh.hasParam("min_detect_distance")) source_nh.getParam("min_detect_distance", src->min_detect_distance, src->min_detect_distance); if (source_nh.hasParam("max_detect_distance")) source_nh.getParam("max_detect_distance", src->max_detect_distance, src->max_detect_distance); if (source_nh.hasParam("attach_distance")) source_nh.getParam("attach_distance", src->attach_distance, src->attach_distance); if (source_nh.hasParam("inf_is_valid")) source_nh.getParam("inf_is_valid", inf_is_valid, inf_is_valid); if (inf_is_valid) 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]"); // At half the frustum depth the near and far bands meet and nothing along the axis is marked. requireRange(src->attach_distance >= 0.0 && src->attach_distance < (src->max_detect_distance - src->min_detect_distance) / 2.0, what + "attach_distance must be in [0, (max_detect_distance - min_detect_distance) / 2) [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 attach=%.3f 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->attach_distance, 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 marking_height=[%.2f, %.2f] m occlusion_guard=%s 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", marking_height_under_ground_, marking_height_above_ground_, occlusion_guard_ ? "true" : "false", 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, source.attach_distance); // Occlusion guard: nearest return per ray from every point, before the height gate below. Eigen::Isometry3f T_sensor_cloud = Eigen::Isometry3f::Identity(); if (occlusion_guard_) { obs.range.reset(T_origin, source.fov_w, source.fov_v, source.sensor_frame_is_optical); T_sensor_cloud = (T_origin.inverse() * T_cloud).cast(); } 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; if (occlusion_guard_) obs.range.addSensorPoint(T_sensor_cloud * Eigen::Vector3f(*iter_x, *iter_y, *iter_z)); 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) { // ClearCostmapRecovery and resetLayers() reach the stored points from other threads. boost::unique_lock lock(*getMutex()); if (rolling_window_) updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2); if (!enabled_) return; const auto start = std::chrono::steady_clock::now(); useExtraBounds(min_x, min_y, max_x, max_y); dropColumnsOutsideWindow(min_x, min_y, max_x, max_y); bool current = true; std::vector frustums; // Points into source->observations, which nothing changes until the end of this cycle. std::vector range_images; 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); range_images.push_back(obs.range.empty() ? nullptr : &obs.range); 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, range_images, 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, const std::vector& range_images, 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_.begin(); column != pc_3d_map_global_.end();) { 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) { ++column; 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_; } // The kd-tree test cannot tell "gone" from "hidden by something nearer": a person walking in // front of a box cleared the box. With the guard, the depth rays decide where they can. if (occlusion_guard_ && !bypass_clearing) { // The middle of the cell, not its corner: indices are truncated toward zero, so the corner // can lie outside a small object and its ray would see the floor behind it. const Eigen::Vector3f centre(static_cast(wx + std::copysign(0.5 * resolution, wx)), static_cast(wy + std::copysign(0.5 * resolution, wy)), search.z()); bool occluded = false, seen_through = false; for (std::size_t i = 0; i < frustums.size() && i < range_images.size(); ++i) { if (range_images[i] == nullptr || !frustums[i].inside(search)) continue; const DepthCameraRangeImage::Evidence evidence = range_images[i]->test(centre); occluded = occluded || evidence == DepthCameraRangeImage::Evidence::kOccluded; seen_through = seen_through || evidence == DepthCameraRangeImage::Evidence::kSeenThrough; } if (erase && occluded) { erase = false; ++stats_.kept_occluded; } else if (!erase && seen_through && !occluded) { erase = true; ++stats_.cleared_seen_through; } } if (!erase) continue; heights.erase(it); ++stats_.cleared; } // The last point of the column is gone: the cell is free again, in the own grid and, // through the bounds, in the master this cycle. column = heights.empty() ? eraseColumn(column, min_x, min_y, max_x, max_y) : std::next(column); } } 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; const std::pair key(mmx, mmy); unsigned int cx, cy; if (!columnCell(key, cx, cy)) continue; // would be dropped as out of the window anyway auto& slot = pc_3d_map_global_[key]; auto inserted = slot.insert(std::make_pair(h_ind, 0.f)); if (inserted.second) ++stats_.marked; setCost(cx, cy, LETHAL_OBSTACLE); double wx, wy; intIndexToWorld(wx, wy, mmx, mmy, resolution); touch(wx, wy, min_x, min_y, max_x, max_y); } } 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); // updateCosts() frees the footprint in the own grid like ObstacleLayer; the stored points under // it must go too, or the next marking pass would not bring them back but nothing would ever // remove them either. std::vector polygon, cells; for (const auto& pt : transformed_footprint_) { MapLocation loc; if (!worldToMap(pt.x, pt.y, loc.x, loc.y)) return; // footprint leaves the window: same give-up as setConvexPolygonCost polygon.push_back(loc); } if (polygon.size() < 3) return; convexFillCells(polygon, cells); std::unordered_set under; for (const MapLocation& c : cells) under.insert(getIndex(c.x, c.y)); for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();) { unsigned int mx, my; if (columnCell(it->first, mx, my) && under.count(getIndex(mx, my))) { ++stats_.footprint_cleared; it = eraseColumn(it, min_x, min_y, max_x, max_y); } else ++it; } } bool DepthCameraObstacleLayer::isValid(int mx, int my) const { // 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()); } bool DepthCameraObstacleLayer::columnCell(const std::pair& column, unsigned int& mx, unsigned int& my) const { double wx, wy; intIndexToWorld(wx, wy, column.first, column.second, getResolution()); if (!worldToMap(wx, wy, mx, my)) return false; // The +-1 cells guard the rounding of the stored corner, as in the source. const int x = static_cast(mx), y = static_cast(my); return isValid(x - 1, y - 1) && isValid(x - 1, y + 1) && isValid(x + 1, y - 1) && isValid(x + 1, y + 1); } std::map, std::map>::iterator DepthCameraObstacleLayer::eraseColumn( std::map, std::map>::iterator it, double* min_x, double* min_y, double* max_x, double* max_y) { unsigned int mx, my; if (columnCell(it->first, mx, my)) { setCost(mx, my, FREE_SPACE); double wx, wy; intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution()); touch(wx, wy, min_x, min_y, max_x, max_y); } return pc_3d_map_global_.erase(it); } void DepthCameraObstacleLayer::dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x, double* max_y) { for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();) { unsigned int mx, my; if (columnCell(it->first, mx, my)) { // Keep the own grid in step with the points even after matchSize() or a cleared area // wiped the cell: one O(columns) pass that writes only when something is missing. if (getCost(mx, my) != LETHAL_OBSTACLE) { setCost(mx, my, LETHAL_OBSTACLE); double wx, wy; intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution()); touch(wx, wy, min_x, min_y, max_x, max_y); } ++it; continue; } // B6: the source keeps such points forever, so the map and every loop over it grow. ++stats_.dropped_out_of_window; double wx, wy; intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution()); if (worldToMap(wx, wy, mx, my)) { // Still inside the window, on its edge row/column: free that cell as well. setCost(mx, my, FREE_SPACE); touch(wx, wy, min_x, min_y, max_x, max_y); } it = pc_3d_map_global_.erase(it); } } void DepthCameraObstacleLayer::updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) { boost::unique_lock lock(*getMutex()); if (!enabled_) return; // The own grid mirrors the stored points (see updateBounds), so the layer merges like // ObstacleLayer and the master is only changed inside the update bounds. if (footprint_clearing_enabled_) setConvexPolygonCost(transformed_footprint_, FREE_SPACE); 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 footprint_cleared=%zu clear_all_cycles=%zu bypass_cycles=%zu " "tf_wait=%zu tf_drop=%zu out_of_window=%zu kept_occluded=%zu cleared_seen_through=%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_.footprint_cleared, stats_.cleared_all_frames, stats_.bypassed_frames, stats_.tf_waits, stats_.tf_drops, stats_.dropped_out_of_window, stats_.kept_occluded, stats_.cleared_seen_through, 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() { boost::unique_lock lock(*getMutex()); deactivate(); resetMaps(); // The source keeps its global-mode points here (B9), so a reset changed nothing on the master. pc_3d_map_global_.clear(); for (const auto& source : sources_) source->observations.clear(); current_ = true; activate(); } void DepthCameraObstacleLayer::matchSize() { // The master was resized (or this is onInitialize): CostmapLayer::matchSize() rebuilds the own // grid with default_value_, so put the stored columns back now instead of waiting a cycle, and // ask the next update to merge the whole layer. boost::unique_lock lock(*getMutex()); CostmapLayer::matchSize(); for (const auto& column : pc_3d_map_global_) { unsigned int mx, my; if (columnCell(column.first, mx, my)) setCost(mx, my, LETHAL_OBSTACLE); } if (!pc_3d_map_global_.empty()) addExtraBounds(getOriginX(), getOriginY(), getOriginX() + getSizeInMetersX(), getOriginY() + getSizeInMetersY()); } void DepthCameraObstacleLayer::clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area) { boost::unique_lock lock(*getMutex()); CostmapLayer::clearArea(start_x, start_y, end_x, end_y, invert_area); for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();) { unsigned int mx, my; if (columnCell(it->first, mx, my)) { // Same test as CostmapLayer::clearArea: keep what it keeps. const int x = static_cast(mx), y = static_cast(my); const bool inside = x > start_x && x < end_x && y > start_y && y < end_y; if (inside != invert_area) { ++it; continue; } } // The own grid cell is already NO_INFORMATION from CostmapLayer::clearArea. it = pc_3d_map_global_.erase(it); } } // Export factory function static boost::shared_ptr create_depth_camera_obstacle_plugin() { return boost::make_shared(); } BOOST_DLL_ALIAS(create_depth_camera_obstacle_plugin, DepthCameraObstacleLayer) } // namespace robot_costmap_2d