/********************************************************************* * 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 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); if (p.has("clear_touches_bounds")) robot::log_warning("DepthCameraObstacleLayer %s: clear_touches_bounds is obsolete and ignored: a cleared " "cell now always resets its master cell\n", name_.c_str()); debug_stats_ = p.get("debug/stats", true); debug_stats_period_ = p.get("debug/stats_period", 5.0); // 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 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", 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) { // 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; 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_.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_; } 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 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_.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::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