refactor(depth): keep DepthCameraObstacleLayer, drop the legacy depth clearing

Two depth-image clearing designs lived in this package: the frustum ray
clearing inherited from dev_cam_intel (DepthCameraData sources of
ObstacleLayer/VoxelLayer, frustum_* and column_* keys) and the observed_volume
evidence clearing (ROC) on top of it. Both are replaced on the robot by
DepthCameraObstacleLayer, a port of costmap_depth_camera that takes the
filtered PointCloud2 directly, so both are removed and the tree is rebuilt
from main (a63c084) plus the plugin.

- observation.h / observation_buffer: DepthFrustumConfig, DepthCameraObservation
  and the depth buffering API are gone; buffers hold point clouds only.
- ObstacleLayer/VoxelLayer: no frustum ray casting, column clearing or depth
  ray cache. A DepthCameraData source or frustum_clearing_enabled: true now
  fails at startup with a message pointing to DepthCameraObstacleLayer
  instead of silently dropping the camera; DepthCameraData reaching the layer
  through the gateway is ignored.
- copyParentParameters no longer forwards the frustum_* / column_* keys.
- ROC files (depth_evidence_store, depth_visibility, depth_frame_pairer) and
  their tests are not carried over; CloudProcessingConfig goes with them.
- PCL is needed by the plugin library only. The plugin test moves under
  BUILD_COSTMAP_TESTS; BUILD_DEPTH_MARKING_TESTS is gone.
- README documents DepthCameraObstacleLayer and its known limits.

The plugin code is unchanged from the version running on the KIT robot.
This commit is contained in:
2026-10-20 09:47:25 +07:00
parent 9a67eee148
commit b23ff27a3c
20 changed files with 222 additions and 3768 deletions

View File

@@ -414,21 +414,6 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
double max_obstacle_height;
double obstacle_range;
double raytrace_range;
bool cloud_transform_at_stamp = false;
bool marking_voxel_enabled = false;
double marking_voxel_leaf_size = 0.05;
bool frustum_clearing_enabled = false;
int frustum_clearing_pixel_step = 8;
double frustum_min_range = 0.2;
double frustum_max_range = 3.0;
double frustum_skip_distance = -1.0;
bool frustum_column_clearing = false;
double column_clear_min_height = 0.10;
double column_clear_max_height = -1.0;
double column_skip_distance = 0.02;
double column_cover_distance = -1.0;
int frustum_clear_left_border_px = 0;
int frustum_clear_right_border_px = 0;
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "topic", topic);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "sensor_frame", sensor_frame);
@@ -442,38 +427,7 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "max_obstacle_height", max_obstacle_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "obstacle_range", obstacle_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "raytrace_range", raytrace_range);
// These source options must reach local/global plugin namespaces too;
// loading the common YAML alone does not scope them to the layer.
move_parameter(plugin_nh_element, costmap_plugin_nh_element,
"cloud_transform_at_stamp", cloud_transform_at_stamp);
move_parameter(plugin_nh_element, costmap_plugin_nh_element,
"marking_voxel_filter/enabled", marking_voxel_enabled);
move_parameter(plugin_nh_element, costmap_plugin_nh_element,
"marking_voxel_filter/leaf_size_m", marking_voxel_leaf_size);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_enabled", frustum_clearing_enabled);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_pixel_step", frustum_clearing_pixel_step);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_min_range", frustum_min_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_max_range", frustum_max_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_skip_distance", frustum_skip_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_column_clearing", frustum_column_clearing);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_clear_min_height", column_clear_min_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_clear_max_height", column_clear_max_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_skip_distance", column_skip_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_cover_distance", column_cover_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clear_left_border_px", frustum_clear_left_border_px);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clear_right_border_px", frustum_clear_right_border_px);
for (const char* key : {"depth_clearing_mode", "paired_marking_source", "depth_pair_queue_size",
"depth_pair_max_wait_s", "depth_observation_max_age_s", "depth_valid_min_z_m",
"depth_valid_max_z_m", "depth_free_margin_m", "depth_projection_margin_px",
"depth_voxel_z_resolution_m", "depth_evidence_points_enabled",
"depth_evidence_points_per_voxel", "depth_marking_border_px",
"depth_far_return_is_behind", "depth_reobserve_clearing",
"depth_confirm_tolerance_m", "depth_miss_frames", "depth_no_return_weight",
"depth_stereo_baseline_m", "depth_stereo_band_margin_px"})
if (plugin_nh_element.hasParam(key))
costmap_plugin_nh_element.setParam(key, YAML::Clone(plugin_nh_element.getParamValue(key)));
robot::log_info("topic: %s data_type: %s clearing: %d marking: %d inf_is_valid: %d min_obstacle_height: %f max_obstacle_height: %f", topic.c_str(), data_type.c_str(), clearing, marking, inf_is_valid, min_obstacle_height, max_obstacle_height);
robot::log_info("frustum_clearing_enabled: %s, frustum_clearing_pixel_step: %d, frustum_min_range: %f, frustum_max_range: %f, frustum_clear_left_border_px: %d, frustum_clear_right_border_px: %d", frustum_clearing_enabled ? "true" : "false", frustum_clearing_pixel_step, frustum_min_range, frustum_max_range, frustum_clear_left_border_px, frustum_clear_right_border_px);
}
}
}
@@ -510,18 +464,6 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
double max_obstacle_height;
double obstacle_range;
double raytrace_range;
bool frustum_clearing_enabled = false;
int frustum_clearing_pixel_step = 8;
double frustum_min_range = 0.2;
double frustum_max_range = 3.0;
double frustum_skip_distance = -1.0;
bool frustum_column_clearing = false;
double column_clear_min_height = 0.10;
double column_clear_max_height = -1.0;
double column_skip_distance = 0.02;
double column_cover_distance = -1.0;
int frustum_clear_left_border_px = 0;
int frustum_clear_right_border_px = 0;
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "topic", topic);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "sensor_frame", sensor_frame);
@@ -535,20 +477,7 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "max_obstacle_height", max_obstacle_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "obstacle_range", obstacle_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "raytrace_range", raytrace_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_enabled", frustum_clearing_enabled);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_pixel_step", frustum_clearing_pixel_step);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_min_range", frustum_min_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_max_range", frustum_max_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_skip_distance", frustum_skip_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_column_clearing", frustum_column_clearing);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_clear_min_height", column_clear_min_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_clear_max_height", column_clear_max_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_skip_distance", column_skip_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_cover_distance", column_cover_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clear_left_border_px", frustum_clear_left_border_px);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clear_right_border_px", frustum_clear_right_border_px);
robot::log_info("topic: %s data_type: %s clearing: %d marking: %d inf_is_valid: %d min_obstacle_height: %f max_obstacle_height: %f", topic.c_str(), data_type.c_str(), clearing, marking, inf_is_valid, min_obstacle_height, max_obstacle_height);
robot::log_info("frustum_clearing_enabled: %s, frustum_clearing_pixel_step: %d, frustum_min_range: %f, frustum_max_range: %f, frustum_clear_left_border_px: %d, frustum_clear_right_border_px: %d", frustum_clearing_enabled ? "true" : "false", frustum_clearing_pixel_step, frustum_min_range, frustum_max_range, frustum_clear_left_border_px, frustum_clear_right_border_px);
}
}
}

View File

@@ -1,106 +0,0 @@
#include <robot_costmap_2d/depth_evidence_store.h>
#include <algorithm>
namespace robot_costmap_2d
{
DepthEvidenceStore::DepthEvidenceStore(unsigned int points_per_voxel)
: points_per_voxel_(std::clamp(points_per_voxel, kExtremeSlots, kMaxPoints)), entries_()
{
}
void DepthEvidenceStore::setPointsPerVoxel(unsigned int points_per_voxel)
{
points_per_voxel_ = std::clamp(points_per_voxel, kExtremeSlots, kMaxPoints);
entries_.clear();
}
void DepthEvidenceStore::add(const VoxelKey& key, const Eigen::Vector3f& point, bool fresh)
{
if (!point.allFinite())
return;
Entry& entry = entries_[key];
entry.miss = 0.f;
if (fresh || entry.count == 0)
{
// Slots 0..5 hold min/max of x, y, z; the first point is every extreme.
entry.points.fill(point);
entry.count = kExtremeSlots;
entry.next_recent = 0;
return;
}
for (int axis = 0; axis < 3; ++axis)
{
if (point[axis] < entry.points[2 * axis][axis])
entry.points[2 * axis] = point;
if (point[axis] > entry.points[2 * axis + 1][axis])
entry.points[2 * axis + 1] = point;
}
const unsigned int recent_slots = points_per_voxel_ - kExtremeSlots;
if (recent_slots == 0)
return;
if (entry.count < points_per_voxel_)
{
entry.points[entry.count++] = point;
return;
}
entry.points[kExtremeSlots + entry.next_recent] = point;
entry.next_recent = static_cast<unsigned char>((entry.next_recent + 1) % recent_slots);
}
bool DepthEvidenceStore::points(const VoxelKey& key, std::vector<Eigen::Vector3d>& out) const
{
out.clear();
const auto it = entries_.find(key);
if (it == entries_.end() || it->second.count == 0)
return false;
const Entry& entry = it->second;
for (unsigned int i = 0; i < entry.count; ++i)
{
const Eigen::Vector3d point = entry.points[i].cast<double>();
// Extreme slots often repeat the same point; checking it twice adds nothing.
if (std::find(out.begin(), out.end(), point) == out.end())
out.push_back(point);
}
return true;
}
float DepthEvidenceStore::addMiss(const VoxelKey& key, float weight)
{
const auto it = entries_.find(key);
if (it == entries_.end())
return 0.f;
it->second.miss += weight;
return it->second.miss;
}
void DepthEvidenceStore::resetMiss(const VoxelKey& key)
{
const auto it = entries_.find(key);
if (it != entries_.end())
it->second.miss = 0.f;
}
void DepthEvidenceStore::erase(const VoxelKey& key)
{
entries_.erase(key);
}
void DepthEvidenceStore::eraseIf(const std::function<bool(const VoxelKey&)>& predicate)
{
for (auto it = entries_.begin(); it != entries_.end();)
{
if (predicate(it->first))
it = entries_.erase(it);
else
++it;
}
}
void DepthEvidenceStore::clear()
{
entries_.clear();
}
} // namespace robot_costmap_2d

View File

@@ -1,308 +0,0 @@
#include <robot_costmap_2d/depth_visibility.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <limits>
namespace robot_costmap_2d
{
namespace
{
double cross(const Eigen::Vector2d& a, const Eigen::Vector2d& b, const Eigen::Vector2d& c)
{
const auto x = b - a, y = c - a;
return x.x() * y.y() - x.y() * y.x();
}
std::vector<Eigen::Vector2d> convexHull(std::vector<Eigen::Vector2d> points)
{
std::sort(points.begin(), points.end(), [](const auto& a, const auto& b) {
return a.x() < b.x() || (a.x() == b.x() && a.y() < b.y());
});
points.erase(std::unique(points.begin(), points.end(), [](const auto& a, const auto& b) {
return a.x() == b.x() && a.y() == b.y();
}), points.end());
std::vector<Eigen::Vector2d> hull;
for (const auto& p : points)
{
while (hull.size() >= 2 && cross(hull[hull.size()-2], hull.back(), p) <= 0) hull.pop_back();
hull.push_back(p);
}
const size_t lower_size = hull.size();
for (auto it = points.rbegin() + (points.empty() ? 0 : 1); it != points.rend(); ++it)
{
while (hull.size() > lower_size && cross(hull[hull.size()-2], hull.back(), *it) <= 0) hull.pop_back();
hull.push_back(*it);
}
if (!hull.empty()) hull.pop_back();
return hull;
}
// SAT tests the full pixel cell expanded by calibration margin, not only its center.
bool intersectsPixel(const std::vector<Eigen::Vector2d>& polygon, int u, int v, double half)
{
const Eigen::Vector2d center(u, v);
for (int dimension = 0; dimension < 2; ++dimension)
{
double lo = std::numeric_limits<double>::infinity(), hi = -lo;
for (const auto& p : polygon) { lo = std::min(lo, p[dimension]); hi = std::max(hi, p[dimension]); }
if (center[dimension] + half < lo - 1e-9 || center[dimension] - half > hi + 1e-9) return false;
}
for (size_t i = 0; i < polygon.size(); ++i)
{
const auto edge = polygon[(i+1) % polygon.size()] - polygon[i];
const Eigen::Vector2d axis(-edge.y(), edge.x());
double lo = std::numeric_limits<double>::infinity(), hi = -lo;
for (const auto& p : polygon) { const double d = axis.dot(p); lo = std::min(lo, d); hi = std::max(hi, d); }
const double c = axis.dot(center), r = half * (std::abs(axis.x()) + std::abs(axis.y()));
if (c + r < lo - 1e-9 || c - r > hi + 1e-9) return false;
}
return true;
}
} // namespace
bool DepthVisibilityChecker::prepare(robot_sensor_msgs::DepthCameraData::ConstPtr data,
const tf3::TransformStampedMsg& pose, double min_height, double max_height,
const DepthFrustumConfig& config)
{
data_.reset();
if (!data || !std::isfinite(min_height) || !std::isfinite(max_height) || min_height > max_height ||
!std::isfinite(config.valid_min_z_m) || !std::isfinite(config.valid_max_z_m) ||
config.valid_min_z_m <= 0 || config.valid_max_z_m <= config.valid_min_z_m ||
!std::isfinite(config.free_margin_m) || config.free_margin_m < 0)
return false;
const auto& image = data->depth;
const auto& ci = data->camera_info;
bytes_per_pixel_ = image.encoding == "16UC1" || image.encoding == "mono16" ? 2u : image.encoding == "32FC1" ? 4u : 0u;
if (!bytes_per_pixel_ || image.is_bigendian || !image.width || !image.height ||
image.width > static_cast<unsigned>(std::numeric_limits<int>::max()) ||
image.height > static_cast<unsigned>(std::numeric_limits<int>::max()) ||
image.step < static_cast<size_t>(image.width) * bytes_per_pixel_ ||
image.data.size() < static_cast<size_t>(image.step) * image.height ||
ci.width != image.width || ci.height != image.height || image.header.stamp.isZero() ||
image.header.stamp != ci.header.stamp || image.header.stamp != data->header.stamp ||
pose.header.stamp != tf3::Time(image.header.stamp.sec, image.header.stamp.nsec) ||
image.header.frame_id.empty() || image.header.frame_id != ci.header.frame_id ||
image.header.frame_id != data->header.frame_id || image.header.frame_id != pose.child_frame_id ||
pose.header.frame_id.empty() || ci.binning_x > 1 || ci.binning_y > 1 ||
ci.roi.x_offset || ci.roi.y_offset || ci.roi.width || ci.roi.height)
return false;
for (double value : ci.K) if (!std::isfinite(value)) return false;
for (double value : ci.P) if (!std::isfinite(value)) return false;
if (ci.K[0] <= 0 || ci.K[4] <= 0 || std::abs(ci.K[1]) > 1e-6 ||
std::abs(ci.K[3]) > 1e-6 || std::abs(ci.K[6]) > 1e-6 ||
std::abs(ci.K[7]) > 1e-6 || std::abs(ci.K[8] - 1) > 1e-6 ||
std::abs(ci.P[0] - ci.K[0]) > 1e-6 || std::abs(ci.P[5] - ci.K[4]) > 1e-6 ||
std::abs(ci.P[2] - ci.K[2]) > 1e-6 || std::abs(ci.P[6] - ci.K[5]) > 1e-6 ||
std::abs(ci.P[3]) > 1e-6 || std::abs(ci.P[7]) > 1e-6) return false;
const auto& q = pose.transform.rotation;
const auto& t = pose.transform.translation;
Eigen::Quaterniond rotation(q.w, q.x, q.y, q.z);
if (!rotation.coeffs().allFinite() || std::abs(rotation.norm() - 1.0) > .01 ||
!std::isfinite(t.x) || !std::isfinite(t.y) || !std::isfinite(t.z)) return false;
Eigen::Isometry3d global_from_camera = Eigen::Isometry3d::Identity();
global_from_camera.linear() = rotation.normalized().toRotationMatrix();
global_from_camera.translation() = Eigen::Vector3d(t.x, t.y, t.z);
camera_from_global_ = global_from_camera.inverse();
min_height_ = min_height; max_height_ = max_height; config_ = config;
data_ = std::move(data);
return true;
}
DepthVisibilityResult DepthVisibilityChecker::classify(const Eigen::Vector3d& box_lower,
const Eigen::Vector3d& box_upper) const
{
if (!data_ || !box_lower.allFinite() || !box_upper.allFinite()) return {};
Eigen::Vector3d lower = box_lower, upper = box_upper;
lower.z() = std::max(lower.z(), min_height_); upper.z() = std::min(upper.z(), max_height_);
if (upper.z() < lower.z() || upper.x() <= lower.x() || upper.y() <= lower.y())
return {DepthVisibility::Unknown, DepthVisibilityReason::EmptyRegion};
const auto& image = data_->depth;
const auto& ci = data_->camera_info;
std::vector<Eigen::Vector2d> corners;
double far_z = 0;
for (int i = 0; i < 8; ++i)
{
const Eigen::Vector3d world(i & 1 ? upper.x() : lower.x(), i & 2 ? upper.y() : lower.y(), i & 4 ? upper.z() : lower.z());
const auto p = camera_from_global_ * world;
if (!p.allFinite() || p.z() < config_.valid_min_z_m || p.z() > config_.valid_max_z_m) return {};
far_z = std::max(far_z, p.z());
corners.emplace_back(ci.K[0] * p.x() / p.z() + ci.K[2], ci.K[4] * p.y() / p.z() + ci.K[5]);
}
const auto hull = convexHull(corners);
if (hull.size() < 3) return {};
double min_u = image.width, max_u = -1, min_v = image.height, max_v = -1;
for (const auto& p : hull)
{
min_u = std::min(min_u, p.x()); max_u = std::max(max_u, p.x());
min_v = std::min(min_v, p.y()); max_v = std::max(max_v, p.y());
}
const double margin = config_.projection_margin_px;
// Reject unbounded projections before converting to signed pixel indices.
if (!std::isfinite(min_u) || !std::isfinite(max_u) || !std::isfinite(min_v) || !std::isfinite(max_v) ||
min_u - margin - .5 < 0 || max_u + margin + .5 >= image.width ||
min_v - margin - .5 < 0 || max_v + margin + .5 >= image.height) return {};
const int left = static_cast<int>(std::floor(min_u - margin - .5));
const int right = static_cast<int>(std::ceil(max_u + margin + .5));
const int top = static_cast<int>(std::floor(min_v - margin - .5));
const int bottom = static_cast<int>(std::ceil(max_v + margin + .5));
if (left < static_cast<int>(config_.clear_left_border_px) ||
right >= static_cast<int>(image.width) - static_cast<int>(config_.clear_right_border_px) ||
top < 0 || bottom >= static_cast<int>(image.height)) return {};
bool any_pixel = false;
for (int v = top; v <= bottom; ++v)
for (int u = left; u <= right; ++u)
{
if (!intersectsPixel(hull, u, v, margin + .5)) continue;
any_pixel = true;
const double measured_z = depthAt(u, v);
if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m || measured_z > config_.valid_max_z_m)
return {DepthVisibility::Unknown, DepthVisibilityReason::InvalidDepth};
if (measured_z <= far_z + config_.free_margin_m)
return {DepthVisibility::Surface, DepthVisibilityReason::Surface};
}
return any_pixel ? DepthVisibilityResult{DepthVisibility::Free, DepthVisibilityReason::Free} : DepthVisibilityResult{};
}
double DepthVisibilityChecker::depthAt(int u, int v) const
{
const auto& image = data_->depth;
const auto* pixel = image.data.data() + static_cast<size_t>(v) * image.step +
static_cast<size_t>(u) * bytes_per_pixel_;
if (bytes_per_pixel_ == 2)
{
uint16_t millimeters;
std::memcpy(&millimeters, pixel, 2);
return millimeters * .001;
}
if (bytes_per_pixel_ == 4)
{
float meters;
std::memcpy(&meters, pixel, 4);
return meters;
}
return std::numeric_limits<double>::quiet_NaN();
}
namespace
{
// Pixel index of a projection; the bounds test keeps lround() away from huge values.
bool projectToPixel(const Eigen::Vector3d& camera_point, const robot_sensor_msgs::CameraInfo& ci,
int left, int right, int top, int bottom, int& u, int& v)
{
const double pu = ci.K[0] * camera_point.x() / camera_point.z() + ci.K[2];
const double pv = ci.K[4] * camera_point.y() / camera_point.z() + ci.K[5];
// round(p) in [lo, hi] <=> p in [lo - 0.5, hi + 0.5)
if (!std::isfinite(pu) || !std::isfinite(pv) || pu < left - .5 || pu >= right + .5 ||
pv < top - .5 || pv >= bottom + .5)
return false;
u = static_cast<int>(std::lround(pu));
v = static_cast<int>(std::lround(pv));
return true;
}
} // namespace
int DepthVisibilityChecker::usableLeft(double z) const
{
int left = static_cast<int>(config_.clear_left_border_px);
// The right imager cannot see the leftmost fx * B / z columns at depth z: no disparity there.
if (config_.stereo_baseline_m > 0)
left = std::max(left, static_cast<int>(std::ceil(data_->camera_info.K[0] * config_.stereo_baseline_m / z)) +
static_cast<int>(config_.stereo_band_margin_px));
return left;
}
bool DepthVisibilityChecker::projectsInside(const Eigen::Vector3d& point, unsigned int border_px) const
{
if (!data_ || !point.allFinite())
return false;
const auto& image = data_->depth;
const Eigen::Vector3d p = camera_from_global_ * point;
if (!p.allFinite() || p.z() < config_.valid_min_z_m)
return false;
const int border = static_cast<int>(border_px);
int u, v;
return projectToPixel(p, data_->camera_info, usableLeft(p.z()) + border,
static_cast<int>(image.width) - 1 - static_cast<int>(config_.clear_right_border_px) - border,
border, static_cast<int>(image.height) - 1 - border, u, v);
}
DepthObservation DepthVisibilityChecker::observePoints(const std::vector<Eigen::Vector3d>& points) const
{
DepthObservation best = DepthObservation::OutOfView;
if (!data_)
return best;
const auto& image = data_->depth;
const int r = static_cast<int>(config_.projection_margin_px);
const double tolerance = config_.confirm_tolerance_m;
for (const auto& point : points)
{
if (!point.allFinite())
continue;
const Eigen::Vector3d p = camera_from_global_ * point;
if (!p.allFinite() || p.z() < config_.valid_min_z_m || p.z() > config_.valid_max_z_m)
continue;
int u, v;
if (!projectToPixel(p, data_->camera_info, usableLeft(p.z()) + r,
static_cast<int>(image.width) - 1 - static_cast<int>(config_.clear_right_border_px) - r,
r, static_cast<int>(image.height) - 1 - r, u, v))
continue;
// A return beyond the trusted range only proves free space for a point well inside it.
const bool far_is_behind = config_.far_return_is_behind && p.z() + tolerance < config_.valid_max_z_m;
bool in_front = false, behind = false;
for (int dv = -r; dv <= r; ++dv)
for (int du = -r; du <= r; ++du)
{
const double measured_z = depthAt(u + du, v + dv);
if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m ||
(measured_z > config_.valid_max_z_m && !far_is_behind))
continue; // no return: says nothing about this point
if (std::abs(measured_z - p.z()) <= tolerance)
return DepthObservation::Confirmed;
if (measured_z < p.z())
in_front = true;
else
behind = true;
}
const DepthObservation seen = in_front ? DepthObservation::Occluded :
behind ? DepthObservation::SeenThrough : DepthObservation::NoReturn;
best = std::max(best, seen);
}
return best;
}
DepthVisibilityResult DepthVisibilityChecker::classifyPoints(const std::vector<Eigen::Vector3d>& points) const
{
if (!data_ || points.empty())
return {};
const auto& image = data_->depth;
const int r = static_cast<int>(config_.projection_margin_px);
for (const auto& point : points)
{
if (!point.allFinite())
return {};
const Eigen::Vector3d p = camera_from_global_ * point;
// Same view limits as classify(): out of the trusted optical range is not seen.
if (!p.allFinite() || p.z() < config_.valid_min_z_m || p.z() > config_.valid_max_z_m)
return {};
int u, v;
if (!projectToPixel(p, data_->camera_info,
static_cast<int>(config_.clear_left_border_px) + r,
static_cast<int>(image.width) - 1 - static_cast<int>(config_.clear_right_border_px) - r,
r, static_cast<int>(image.height) - 1 - r, u, v))
return {};
for (int dv = -r; dv <= r; ++dv)
for (int du = -r; du <= r; ++du)
{
const double measured_z = depthAt(u + du, v + dv);
if (config_.far_return_is_behind && std::isfinite(measured_z) &&
measured_z > config_.valid_max_z_m && p.z() + config_.free_margin_m < config_.valid_max_z_m)
continue;
if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m ||
measured_z > config_.valid_max_z_m)
return {DepthVisibility::Unknown, DepthVisibilityReason::InvalidDepth};
if (measured_z <= p.z() + config_.free_margin_m)
return {DepthVisibility::Surface, DepthVisibilityReason::Surface};
}
}
return {DepthVisibility::Free, DepthVisibilityReason::Free};
}
} // namespace robot_costmap_2d

View File

@@ -41,41 +41,12 @@
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <cstring>
#include <cmath>
#include <stdexcept>
#include <pcl/filters/voxel_grid.h>
#include <pcl/point_types.h>
#include <data_convert/pcl_convert.h>
using namespace std;
using namespace tf3;
namespace robot_costmap_2d
{
namespace
{
bool validTimestampCloud(const robot_sensor_msgs::PointCloud2& cloud)
{
if (cloud.header.stamp.isZero() || cloud.header.frame_id.empty() ||
cloud.is_bigendian || cloud.point_step == 0 || cloud.height != 1 ||
cloud.row_step != static_cast<size_t>(cloud.width) * cloud.point_step ||
cloud.data.size() != cloud.row_step)
return false;
unsigned int fields = 0;
for (const auto& field : cloud.fields)
{
const unsigned int bit = field.name == "x" ? 1u : field.name == "y" ? 2u : field.name == "z" ? 4u : 0u;
if (!bit) continue;
if ((fields & bit) || field.count != 1 ||
field.datatype != robot_sensor_msgs::PointField::FLOAT32 ||
static_cast<size_t>(field.offset) + sizeof(float) > cloud.point_step)
return false;
fields |= bit;
}
return fields == 7u;
}
} // namespace
ObservationBuffer::ObservationBuffer(string topic_name, double observation_keep_time, double expected_update_rate,
double min_obstacle_height, double max_obstacle_height, double obstacle_range,
double raytrace_range, tf3::BufferCore& tf3_buffer, string global_frame,
@@ -87,23 +58,6 @@ ObservationBuffer::ObservationBuffer(string topic_name, double observation_keep_
{
}
ObservationBuffer::ObservationBuffer(string topic_name, double observation_keep_time, double expected_update_rate,
double min_obstacle_height, double max_obstacle_height, double obstacle_range,
double raytrace_range, const DepthFrustumConfig& frustum_config,
tf3::BufferCore& tf3_buffer, string global_frame,
string sensor_frame, double tf_tolerance) :
tf3_buffer_(tf3_buffer), observation_keep_time_(observation_keep_time), expected_update_rate_(expected_update_rate),
last_updated_(robot::Time::now()), global_frame_(global_frame), sensor_frame_(sensor_frame), topic_name_(topic_name),
min_obstacle_height_(min_obstacle_height), max_obstacle_height_(max_obstacle_height),
obstacle_range_(obstacle_range), raytrace_range_(raytrace_range),
tf_tolerance_(tf_tolerance),
frustum_config_(frustum_config)
{
frustum_config_.pixel_step = std::max(1u, frustum_config_.pixel_step);
frustum_config_.min_range = std::max(0.0, frustum_config_.min_range);
frustum_config_.max_range = std::max(frustum_config_.max_range, frustum_config_.min_range);
}
ObservationBuffer::~ObservationBuffer()
{
}
@@ -172,43 +126,6 @@ bool ObservationBuffer::setGlobalFrame(const std::string new_global_frame)
}
void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
{
(void)tryBufferCloud(cloud);
}
void ObservationBuffer::setCloudProcessingConfig(const CloudProcessingConfig& config)
{
const float leaf = static_cast<float>(config.voxel_leaf_size);
if (config.voxel_filter_enabled &&
(!config.transform_at_stamp || !std::isfinite(leaf) || leaf <= 0.0f ||
!std::isfinite(config.voxel_leaf_size)))
throw std::invalid_argument("cloud voxel filter requires timestamp TF and a finite positive leaf [m]");
if (config.transform_at_stamp &&
(!std::isfinite(min_obstacle_height_) || !std::isfinite(max_obstacle_height_) ||
min_obstacle_height_ > max_obstacle_height_ ||
!std::isfinite(obstacle_range_) || obstacle_range_ <= 0.0))
throw std::invalid_argument("timestamp cloud processing requires finite height/range limits");
cloud_processing_config_ = config;
}
bool ObservationBuffer::tryBufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
{
return tryBufferCloudImpl(cloud, nullptr);
}
bool ObservationBuffer::tryBufferCloudWithTransform(const robot_sensor_msgs::PointCloud2& cloud,
const tf3::TransformStampedMsg& transform)
{
if (!cloud_processing_config_.transform_at_stamp || transform.header.frame_id != global_frame_ ||
transform.header.stamp != data_convert::convertTime(cloud.header.stamp) ||
transform.child_frame_id != cloud.header.frame_id ||
(!sensor_frame_.empty() && sensor_frame_ != cloud.header.frame_id))
return false;
return tryBufferCloudImpl(cloud, &transform);
}
bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2& cloud,
const tf3::TransformStampedMsg* prepared_transform)
{
robot_geometry_msgs::PointStamped global_origin;
Observation observation;
@@ -216,13 +133,6 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
// check whether the origin frame has been set explicitly or whether we should get it from the cloud
string origin_frame = sensor_frame_ == "" ? cloud.header.frame_id : sensor_frame_;
if (cloud_processing_config_.transform_at_stamp && !validTimestampCloud(cloud))
{
robot::log_error_throttle(5.0, "ObservationBuffer [%s]: invalid timestamp cloud layout/header\n",
topic_name_.c_str());
return false;
}
try
{
// given these observations come from sensors... we'll need to store the origin pt of the sensor
@@ -233,16 +143,14 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
local_origin.point.y = 0;
local_origin.point.z = 0;
// tf3_buffer_.transform(local_origin, global_origin, global_frame_);
const tf3::Time query_time = cloud_processing_config_.transform_at_stamp
? tf3::Time(cloud.header.stamp.sec, cloud.header.stamp.nsec) : tf3::Time();
const tf3::TransformStampedMsg cloud_transform = prepared_transform ? *prepared_transform
: tf3_buffer_.lookupTransform(global_frame_, cloud.header.frame_id, query_time);
const tf3::TransformStampedMsg cloud_transform = tf3_buffer_.lookupTransform(
global_frame_, cloud.header.frame_id, tf3::Time());
if (origin_frame == cloud.header.frame_id)
tf3::doTransform(local_origin, global_origin, cloud_transform);
else
tf3::doTransform(
local_origin, global_origin,
tf3_buffer_.lookupTransform(global_frame_, origin_frame, query_time));
tf3_buffer_.lookupTransform(global_frame_, origin_frame, tf3::Time()));
tf3::convert(global_origin.point, observation.origin_);
observation.raytrace_range_ = raytrace_range_;
@@ -257,24 +165,11 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
const std::size_t point_step = observation_cloud.point_step;
std::size_t point_count = 0;
robot_sensor_msgs::PointCloud2Iterator<float> iter_z(observation_cloud, "z");
robot_sensor_msgs::PointCloud2Iterator<float> iter_x(observation_cloud, "x");
robot_sensor_msgs::PointCloud2Iterator<float> iter_y(observation_cloud, "y");
const double sq_range = obstacle_range_ * obstacle_range_;
// Compact accepted points in-place. This avoids allocating and copying a
// second full-size filtered cloud after the TF transform.
for (std::size_t read_index = 0; read_index < cloud_size;
++read_index, ++iter_x, ++iter_y, ++iter_z)
for (std::size_t read_index = 0; read_index < cloud_size; ++read_index, ++iter_z)
{
if (cloud_processing_config_.transform_at_stamp)
{
const double dx = *iter_x - observation.origin_.x;
const double dy = *iter_y - observation.origin_.y;
const double dz = *iter_z - observation.origin_.z;
if (!std::isfinite(*iter_x) || !std::isfinite(*iter_y) || !std::isfinite(*iter_z) ||
dx * dx + dy * dy + dz * dz >= sq_range)
continue;
}
if ((*iter_z) > max_obstacle_height_ || (*iter_z) < min_obstacle_height_)
continue;
@@ -292,36 +187,12 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
robot_sensor_msgs::PointCloud2Modifier modifier(observation_cloud);
modifier.resize(point_count);
}
// Floor/out-of-band points cannot pull a small obstacle's centroid below
// its marking threshold. Only this source's opted-in cloud is downsampled.
if (cloud_processing_config_.voxel_filter_enabled && point_count != 0)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr input(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromROBOTMsg(observation_cloud, *input);
pcl::VoxelGrid<pcl::PointXYZ> voxel;
const float leaf = static_cast<float>(cloud_processing_config_.voxel_leaf_size);
voxel.setLeafSize(leaf, leaf, leaf);
voxel.setInputCloud(input);
pcl::PointCloud<pcl::PointXYZ> output;
voxel.filter(output);
const robot_std_msgs::Header header = observation_cloud.header;
pcl::toROBOTMsg(output, observation_cloud);
observation_cloud.header = header; // PCL timestamps only have microseconds.
}
}
catch (TransformException& ex)
{
robot::log_error_throttle(5.0, "ObservationBuffer [%s] missing TF for frame %s at %u.%09u: %s\n",
topic_name_.c_str(), cloud.header.frame_id.c_str(),
cloud.header.stamp.sec, cloud.header.stamp.nsec, ex.what());
return false;
}
catch (const std::exception& ex)
{
robot::log_error_throttle(5.0, "ObservationBuffer [%s] rejected cloud: %s\n",
topic_name_.c_str(), ex.what());
return false;
robot::log_error("TF Exception that should never happen for sensor frame: %s, cloud frame: %s, %s\n", sensor_frame_.c_str(),
cloud.header.frame_id.c_str(), ex.what());
return;
}
if (observation_keep_time_ == robot::Duration(0.0) && !observation_list_.empty())
@@ -339,37 +210,6 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
// we'll also remove any stale observations from the list
purgeStaleObservations();
return true;
}
void ObservationBuffer::bufferDepthCamera(const robot_sensor_msgs::DepthCameraData& depth_camera_data)
{
bufferDepthCamera(boost::make_shared<robot_sensor_msgs::DepthCameraData>(depth_camera_data));
}
void ObservationBuffer::bufferDepthCamera(robot_sensor_msgs::DepthCameraData::ConstPtr depth_camera_data)
{
if (!depth_camera_data)
return;
DepthCameraObservation observation(
std::move(depth_camera_data), topic_name_, robot::Time::now(), frustum_config_);
if (observation_keep_time_ == robot::Duration(0.0) && !depth_observation_list_.empty())
{
depth_observation_list_.front() = std::move(observation);
depth_observation_list_.erase(++depth_observation_list_.begin(), depth_observation_list_.end());
}
else
{
depth_observation_list_.push_front(std::move(observation));
}
// if the update was successful, we want to update the last updated time
last_updated_ = robot::Time::now();
// first... let's make sure that we don't have any stale observations
purgeStaleDepthObservations();
}
// returns a copy of the observations
@@ -386,26 +226,6 @@ void ObservationBuffer::getObservations(vector<Observation>& observations)
}
}
void ObservationBuffer::getDepthObservations(vector<DepthCameraObservation>& observations)
{
// first... let's make sure that we don't have any stale observations
purgeStaleDepthObservations();
// now we'll just copy the observations for the caller
if (observation_keep_time_ == robot::Duration(0.0))
{
if (!depth_observation_list_.empty())
{
observations.push_back(std::move(depth_observation_list_.front()));
depth_observation_list_.clear();
}
return;
}
observations.insert(
observations.end(), depth_observation_list_.begin(), depth_observation_list_.end());
}
void ObservationBuffer::purgeStaleObservations()
{
if (!observation_list_.empty())
@@ -432,30 +252,6 @@ void ObservationBuffer::purgeStaleObservations()
}
}
void ObservationBuffer::purgeStaleDepthObservations()
{
if (depth_observation_list_.empty())
return;
if (observation_keep_time_ == robot::Duration(0.0))
{
auto observation = depth_observation_list_.begin();
depth_observation_list_.erase(++observation, depth_observation_list_.end());
return;
}
const robot::Time now = robot::Time::now();
for (auto observation = depth_observation_list_.begin(); observation != depth_observation_list_.end(); ++observation)
{
DepthCameraObservation& obs = *observation;
if ((last_updated_ - obs.data_->header.stamp) > observation_keep_time_)
{
depth_observation_list_.erase(observation, depth_observation_list_.end());
return;
}
}
}
bool ObservationBuffer::isCurrent() const
{
if (expected_update_rate_ == robot::Duration(0.0))