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

@@ -37,7 +37,6 @@
*********************************************************************/
#include <robot_costmap_2d/obstacle_layer.h>
#include <robot_costmap_2d/costmap_math.h>
#include <robot_costmap_2d/depth_evidence_store.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
@@ -123,25 +122,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
// now we need to split the topics based on whitespace which we can use a stringstream for
std::stringstream ss(topics_string);
struct CloudSourceDefinition
{
boost::shared_ptr<ObservationBuffer> buffer;
CloudProcessingConfig processing;
std::string topic, data_type;
double min_height, max_height, keep_time, expected_period;
bool marking, clearing;
};
struct DepthSourceDefinition
{
boost::shared_ptr<ObservationBuffer> buffer;
DepthFrustumConfig config;
std::string topic, data_type;
double expected_period;
};
std::map<std::string, CloudSourceDefinition> cloud_sources;
std::vector<DepthSourceDefinition> depth_sources;
paired_depth_sources_.clear();
std::string source;
callback_infos_.clear();
@@ -151,9 +131,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
double observation_keep_time = 0, expected_update_rate = 0, min_obstacle_height = 0, max_obstacle_height = 2;
std::string topic = "map", sensor_frame = "laser_frame", data_type = "PointCloud";
bool inf_is_valid = false, clearing=false, marking=true;
bool frustum_clearing_enabled = false;
int frustum_pixel_step = 8;
DepthFrustumConfig frustum_config;
robot::NodeHandle priv_nh(nh, source);
topic = loadParam(layer[source],"topic", topic);
@@ -166,34 +143,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
inf_is_valid = loadParam(layer[source],"inf_is_valid", false);
clearing = loadParam(layer[source],"clearing", false);
marking = loadParam(layer[source],"marking", true);
// frustum params are per-source; the layer-level key is kept as a
// fallback for older YAMLs
frustum_clearing_enabled = loadParam(layer[source], "frustum_clearing_enabled",
loadParam(layer, "frustum_clearing_enabled", false));
frustum_pixel_step = loadParam(layer[source], "frustum_clearing_pixel_step",
loadParam(layer, "frustum_clearing_pixel_step", 8));
frustum_config.min_range = loadParam(layer[source], "frustum_min_range",
loadParam(layer, "frustum_min_range", 0.2));
frustum_config.max_range = loadParam(layer[source], "frustum_max_range",
loadParam(layer, "frustum_max_range", 3.0));
frustum_config.skip_distance =
loadParam(layer[source], "frustum_skip_distance", frustum_config.skip_distance);
frustum_config.column_clearing =
loadParam(layer[source], "frustum_column_clearing", frustum_config.column_clearing);
frustum_config.column_min_height =
loadParam(layer[source], "column_clear_min_height", frustum_config.column_min_height);
frustum_config.column_max_height =
loadParam(layer[source], "column_clear_max_height", frustum_config.column_max_height);
frustum_config.column_skip_distance =
loadParam(layer[source], "column_skip_distance", frustum_config.column_skip_distance);
frustum_config.column_cover_distance =
loadParam(layer[source], "column_cover_distance", frustum_config.column_cover_distance);
int frustum_clear_left_border =
loadParam(layer[source], "frustum_clear_left_border_px",
loadParam(layer, "frustum_clear_left_border_px", 0));
int frustum_clear_right_border =
loadParam(layer[source], "frustum_clear_right_border_px",
loadParam(layer, "frustum_clear_right_border_px", 0));
if (priv_nh.hasParam("topic"))
priv_nh.getParam("topic", topic);
@@ -215,133 +164,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
priv_nh.getParam("clearing", clearing);
if (priv_nh.hasParam("marking"))
priv_nh.getParam("marking", marking);
if (priv_nh.hasParam("frustum_clearing_enabled"))
priv_nh.getParam("frustum_clearing_enabled", frustum_clearing_enabled);
if (priv_nh.hasParam("frustum_clearing_pixel_step"))
{
priv_nh.getParam("frustum_clearing_pixel_step", frustum_pixel_step);
frustum_pixel_step = std::max(1, frustum_pixel_step);
}
if (priv_nh.hasParam("frustum_min_range"))
priv_nh.getParam("frustum_min_range", frustum_config.min_range);
if (priv_nh.hasParam("frustum_max_range"))
priv_nh.getParam("frustum_max_range", frustum_config.max_range);
if (priv_nh.hasParam("frustum_skip_distance"))
priv_nh.getParam("frustum_skip_distance", frustum_config.skip_distance);
if (priv_nh.hasParam("frustum_column_clearing"))
priv_nh.getParam("frustum_column_clearing", frustum_config.column_clearing);
if (priv_nh.hasParam("column_clear_min_height"))
priv_nh.getParam("column_clear_min_height", frustum_config.column_min_height);
if (priv_nh.hasParam("column_clear_max_height"))
priv_nh.getParam("column_clear_max_height", frustum_config.column_max_height);
if (priv_nh.hasParam("column_skip_distance"))
priv_nh.getParam("column_skip_distance", frustum_config.column_skip_distance);
if (priv_nh.hasParam("column_cover_distance"))
priv_nh.getParam("column_cover_distance", frustum_config.column_cover_distance);
if (priv_nh.hasParam("frustum_clear_left_border_px"))
priv_nh.getParam("frustum_clear_left_border_px", frustum_clear_left_border);
if (priv_nh.hasParam("frustum_clear_right_border_px"))
priv_nh.getParam("frustum_clear_right_border_px", frustum_clear_right_border);
if (priv_nh.hasParam("frustum_depth_camera_topic"))
priv_nh.getParam("frustum_depth_camera_topic", depth_camera_data_topic_);
const auto read_depth_option = [&](const char* key, auto& value) {
value = loadParam(layer[source], key, value);
if (priv_nh.hasParam(key)) priv_nh.getParam(key, value);
};
std::string depth_mode = "legacy";
read_depth_option("depth_clearing_mode", depth_mode);
if (depth_mode != "legacy" && depth_mode != "observed_volume")
throw std::invalid_argument("unknown depth_clearing_mode: " + depth_mode);
frustum_config.observed_volume_clearing = depth_mode == "observed_volume";
read_depth_option("paired_marking_source", frustum_config.paired_marking_source);
int pair_queue = 4, projection_margin = 1;
read_depth_option("depth_pair_queue_size", pair_queue);
read_depth_option("depth_pair_max_wait_s", frustum_config.pair_max_wait_s);
read_depth_option("depth_observation_max_age_s", frustum_config.observation_max_age_s);
read_depth_option("depth_valid_min_z_m", frustum_config.valid_min_z_m);
read_depth_option("depth_valid_max_z_m", frustum_config.valid_max_z_m);
read_depth_option("depth_free_margin_m", frustum_config.free_margin_m);
read_depth_option("depth_projection_margin_px", projection_margin);
read_depth_option("depth_voxel_z_resolution_m", frustum_config.voxel_z_resolution_m);
if (pair_queue < 1 || pair_queue > 64 || projection_margin < 0 || projection_margin > 16)
throw std::invalid_argument("depth pair queue/projection margin out of bounds");
frustum_config.pair_queue_size = static_cast<unsigned int>(pair_queue);
frustum_config.projection_margin_px = static_cast<unsigned int>(projection_margin);
if (frustum_config.observed_volume_clearing &&
(!frustum_clearing_enabled || data_type != "DepthCameraData"))
throw std::invalid_argument("observed_volume requires a DepthCameraData frustum source");
if (frustum_config.observed_volume_clearing &&
(!std::isfinite(frustum_config.valid_min_z_m) || frustum_config.valid_min_z_m <= 0 ||
!std::isfinite(frustum_config.valid_max_z_m) || frustum_config.valid_max_z_m <= frustum_config.valid_min_z_m ||
!std::isfinite(frustum_config.free_margin_m) || frustum_config.free_margin_m < 0))
throw std::invalid_argument("observed_volume requires finite optical depth limits and free margin");
if (frustum_config.observed_volume_clearing &&
(!std::isfinite(frustum_config.voxel_z_resolution_m) || frustum_config.voxel_z_resolution_m <= 0))
throw std::invalid_argument("observed_volume requires finite positive voxel z resolution");
int evidence_points = static_cast<int>(frustum_config.evidence_points_per_voxel);
int marking_border = static_cast<int>(frustum_config.marking_border_px);
read_depth_option("depth_evidence_points_enabled", frustum_config.evidence_points_enabled);
read_depth_option("depth_evidence_points_per_voxel", evidence_points);
read_depth_option("depth_marking_border_px", marking_border);
if (evidence_points < static_cast<int>(DepthEvidenceStore::kExtremeSlots) ||
evidence_points > static_cast<int>(DepthEvidenceStore::kMaxPoints) ||
marking_border < 0 || marking_border > 64)
throw std::invalid_argument("depth_evidence_points_per_voxel must be 6..16 and "
"depth_marking_border_px 0..64");
frustum_config.evidence_points_per_voxel = static_cast<unsigned int>(evidence_points);
frustum_config.marking_border_px = static_cast<unsigned int>(marking_border);
if (frustum_config.evidence_points_enabled && !frustum_config.observed_volume_clearing)
throw std::invalid_argument("depth_evidence_points_enabled requires depth_clearing_mode: observed_volume");
read_depth_option("depth_far_return_is_behind", frustum_config.far_return_is_behind);
if (frustum_config.far_return_is_behind && !frustum_config.evidence_points_enabled)
throw std::invalid_argument("depth_far_return_is_behind requires depth_evidence_points_enabled");
int miss_frames = static_cast<int>(frustum_config.miss_frames);
int band_margin = static_cast<int>(frustum_config.stereo_band_margin_px);
read_depth_option("depth_reobserve_clearing", frustum_config.reobserve_clearing);
read_depth_option("depth_confirm_tolerance_m", frustum_config.confirm_tolerance_m);
read_depth_option("depth_miss_frames", miss_frames);
read_depth_option("depth_no_return_weight", frustum_config.no_return_weight);
read_depth_option("depth_stereo_baseline_m", frustum_config.stereo_baseline_m);
read_depth_option("depth_stereo_band_margin_px", band_margin);
if ((frustum_config.reobserve_clearing || frustum_config.stereo_baseline_m > 0) &&
!frustum_config.evidence_points_enabled)
throw std::invalid_argument("depth_reobserve_clearing and depth_stereo_baseline_m require "
"depth_evidence_points_enabled");
if (!std::isfinite(frustum_config.confirm_tolerance_m) || frustum_config.confirm_tolerance_m <= 0 ||
frustum_config.confirm_tolerance_m > 0.5 || miss_frames < 1 || miss_frames > 100 ||
!std::isfinite(frustum_config.no_return_weight) || frustum_config.no_return_weight < 0 ||
frustum_config.no_return_weight > 1 || !std::isfinite(frustum_config.stereo_baseline_m) ||
frustum_config.stereo_baseline_m < 0 || frustum_config.stereo_baseline_m > 1 ||
band_margin < 0 || band_margin > 200)
throw std::invalid_argument("depth_confirm_tolerance_m must be in (0, 0.5] m, depth_miss_frames 1..100, "
"depth_no_return_weight 0..1, depth_stereo_baseline_m 0..1 m and "
"depth_stereo_band_margin_px 0..200");
frustum_config.miss_frames = static_cast<unsigned int>(miss_frames);
frustum_config.stereo_band_margin_px = static_cast<unsigned int>(band_margin);
// One pixel more than the patch radius absorbs rounding of the stored float points,
// so every kept evidence point is re-checked with a full patch from its own pose.
if (frustum_config.evidence_points_enabled &&
frustum_config.marking_border_px <= frustum_config.projection_margin_px)
throw std::invalid_argument("depth_marking_border_px must be > depth_projection_margin_px "
"when depth_evidence_points_enabled is true");
frustum_config.pixel_step = static_cast<unsigned int>(std::max(1, frustum_pixel_step));
frustum_config.clear_left_border_px =
static_cast<unsigned int>(std::max(0, frustum_clear_left_border));
frustum_config.clear_right_border_px =
static_cast<unsigned int>(std::max(0, frustum_clear_right_border));
robot::log_info("source %s: frustum_clearing_enabled: %s, pixel_step: %u, range: [%.2f, %.2f] m, "
"skip: %.3f m, column_clearing: %s, column_band: [%.2f, %.2f] m, "
"column_skip: %.3f m, column_cover: %.2f m, clear_left_border_px: %u px, "
"clear_right_border_px: %u px\n",
source.c_str(), frustum_clearing_enabled ? "true" : "false",
frustum_config.pixel_step, frustum_config.min_range, frustum_config.max_range,
frustum_config.skip_distance, frustum_config.column_clearing ? "true" : "false",
frustum_config.column_min_height, frustum_config.column_max_height,
frustum_config.column_skip_distance, frustum_config.column_cover_distance,
frustum_config.clear_left_border_px, frustum_config.clear_right_border_px);
double obstacle_range = 2.5;
obstacle_range = loadParam(layer[source],"obstacle_range", obstacle_range);
@@ -353,133 +175,50 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
if (priv_nh.hasParam("raytrace_range"))
priv_nh.getParam("raytrace_range", raytrace_range);
CloudProcessingConfig cloud_processing;
cloud_processing.transform_at_stamp =
loadParam(layer[source], "cloud_transform_at_stamp", false);
const YAML::Node voxel_filter = layer[source]["marking_voxel_filter"];
if (voxel_filter && voxel_filter.IsMap())
// Depth images are handled by DepthCameraObstacleLayer; the frustum clearing that used to
// live here was removed. Fail at startup instead of silently dropping a camera.
if (data_type == "DepthCameraData" ||
loadParam(layer[source], "frustum_clearing_enabled", false))
{
cloud_processing.voxel_filter_enabled = loadParam(voxel_filter, "enabled", false);
cloud_processing.voxel_leaf_size = loadParam(voxel_filter, "leaf_size_m", 0.05);
robot::log_error("source %s: DepthCameraData / frustum_clearing_enabled are no longer supported by "
"ObstacleLayer/VoxelLayer, use a DepthCameraObstacleLayer plugin\n", source.c_str());
throw std::invalid_argument("source " + source + ": depth frustum clearing was removed from "
"ObstacleLayer/VoxelLayer, use DepthCameraObstacleLayer");
}
if (priv_nh.hasParam("cloud_transform_at_stamp"))
priv_nh.getParam("cloud_transform_at_stamp", cloud_processing.transform_at_stamp);
if (priv_nh.hasParam("marking_voxel_filter/enabled"))
priv_nh.getParam("marking_voxel_filter/enabled", cloud_processing.voxel_filter_enabled);
if (priv_nh.hasParam("marking_voxel_filter/leaf_size_m"))
priv_nh.getParam("marking_voxel_filter/leaf_size_m", cloud_processing.voxel_leaf_size);
if (cloud_processing.voxel_filter_enabled &&
(data_type != "PointCloud2" || !marking || clearing || frustum_clearing_enabled))
throw std::invalid_argument("marking_voxel_filter requires a marking-only PointCloud2 source");
if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan" || data_type == "DepthCameraData"))
if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan"))
{
robot::log_error("Only topics that use point clouds or laser scans are currently supported\n");
throw std::runtime_error("Only topics that use point clouds or laser scans are currently supported");
}
if(!frustum_clearing_enabled)
{
CallBackInfo info_tmp;
info_tmp.observation_source = source;
info_tmp.data_type = data_type;
info_tmp.topic = topic;
info_tmp.inf_is_valid = inf_is_valid;
callback_infos_.push_back(info_tmp);
CallBackInfo info_tmp;
info_tmp.observation_source = source;
info_tmp.data_type = data_type;
info_tmp.topic = topic;
info_tmp.inf_is_valid = inf_is_valid;
callback_infos_.push_back(info_tmp);
robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
priv_nh.getNamespace().c_str());
// enabled_ = enabled;
// create an observation buffer
observation_buffers_.push_back(
boost::shared_ptr < ObservationBuffer
> (new ObservationBuffer(topic, observation_keep_time, expected_update_rate, min_obstacle_height,
max_obstacle_height, obstacle_range, raytrace_range, *tf_, global_frame_,
sensor_frame, transform_tolerance)));
if (marking)
marking_buffers_.push_back(observation_buffers_.back());
robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
priv_nh.getNamespace().c_str());
// create an observation buffer
observation_buffers_.push_back(
boost::shared_ptr < ObservationBuffer
> (new ObservationBuffer(topic, observation_keep_time, expected_update_rate, min_obstacle_height,
max_obstacle_height, obstacle_range, raytrace_range, *tf_, global_frame_,
sensor_frame, transform_tolerance)));
observation_buffers_.back()->setCloudProcessingConfig(cloud_processing);
cloud_sources.emplace(source, CloudSourceDefinition{observation_buffers_.back(), cloud_processing,
topic, data_type, min_obstacle_height, max_obstacle_height, observation_keep_time,
expected_update_rate, marking, clearing});
robot::log_info("source %s: cloud_tf=%s height=[%.3f, %.3f] m range=%.3f m; "
"PCL_after_height_range=%s leaf=%.3f m\n", source.c_str(),
cloud_processing.transform_at_stamp ? "measurement_stamp" : "latest",
min_obstacle_height, max_obstacle_height, obstacle_range,
cloud_processing.voxel_filter_enabled ? "true" : "false",
cloud_processing.voxel_leaf_size);
if (marking)
marking_buffers_.push_back(observation_buffers_.back());
// check if we'll also add this buffer to our clearing observation buffers
if (clearing)
clearing_buffers_.push_back(observation_buffers_.back());
}
else
{
CallBackInfo info_tmp;
info_tmp.observation_source = source;
info_tmp.data_type = data_type;
info_tmp.topic = topic;
info_tmp.inf_is_valid = inf_is_valid;
callback_depth_infos_.push_back(info_tmp);
depth_observation_buffers_.push_back(
boost::shared_ptr < ObservationBuffer
> (new ObservationBuffer(topic, observation_keep_time, expected_update_rate, min_obstacle_height,
max_obstacle_height, obstacle_range, raytrace_range, frustum_config,
*tf_, global_frame_,
sensor_frame, transform_tolerance)));
depth_sources.push_back({depth_observation_buffers_.back(), frustum_config,
topic, data_type, expected_update_rate});
}
// check if we'll also add this buffer to our clearing observation buffers
if (clearing)
clearing_buffers_.push_back(observation_buffers_.back());
robot::log_info(
"Created an observation buffer for topic %s, global frame: %s, "
"expected update rate: %.2f, observation persistence: %.2f\n",
topic.c_str(), global_frame_.c_str(), expected_update_rate, observation_keep_time);
}
for (const auto& depth_source : depth_sources)
{
if (!depth_source.config.observed_volume_clearing) continue;
const auto marker = cloud_sources.find(depth_source.config.paired_marking_source);
if (marker == cloud_sources.end() || marker->second.data_type != "PointCloud2" ||
!marker->second.marking || marker->second.clearing || marker->second.keep_time != 0 ||
!marker->second.processing.transform_at_stamp || getType() != LayerType::VOXEL_LAYER)
throw std::invalid_argument("observed_volume needs a timestamped marking-only PointCloud2 pair with persistence=0");
for (const auto& other : cloud_sources)
if (other.first != marker->first && (other.second.marking || other.second.clearing))
throw std::invalid_argument("observed_volume depth must use its own VoxelLayer; mixed sensor ownership is unsupported");
if (!paired_depth_sources_.empty() || depth_sources.size() != 1)
throw std::invalid_argument("observed_volume supports one depth camera per VoxelLayer");
const auto& m = marker->second;
double period = m.expected_period;
if (period <= 0 || (depth_source.expected_period > 0 && depth_source.expected_period < period))
period = depth_source.expected_period;
auto paired = boost::make_shared<PairedDepthSource>(depth_source.config, period);
paired->cloud_topic = m.topic; paired->depth_topic = depth_source.topic;
paired->marking_buffer = m.buffer; paired->depth_buffer = depth_source.buffer;
paired->min_height = m.min_height; paired->max_height = m.max_height;
paired_depth_sources_.push_back(paired);
marking_buffers_.erase(std::remove(marking_buffers_.begin(), marking_buffers_.end(), m.buffer), marking_buffers_.end());
robot::log_info("depth clearing observed_volume: paired %s + %s, height=[%.3f, %.3f] m; "
"unknown/occluded/outside FOV retained; queue=%u age=%.3f s; rule=%s; "
"evidence_points=%s per_voxel=%u marking_border=%u px projection_margin=%u px "
"far_return_behind=%s; reobserve tolerance=%.3f m miss_frames=%u no_return_weight=%.2f; "
"stereo_baseline=%.3f m band_margin=%u px\n",
paired->cloud_topic.c_str(), paired->depth_topic.c_str(), m.min_height, m.max_height,
paired->config.pair_queue_size, paired->config.observation_max_age_s,
paired->config.reobserve_clearing ? "re-observe or clear" : "one valid free frame",
paired->config.evidence_points_enabled ? "true" : "false",
paired->config.evidence_points_per_voxel, paired->config.marking_border_px,
paired->config.projection_margin_px,
paired->config.far_return_is_behind ? "true" : "false",
paired->config.confirm_tolerance_m, paired->config.miss_frames,
paired->config.no_return_weight, paired->config.stereo_baseline_m,
paired->config.stereo_band_margin_px);
}
}
}
catch (const YAML::BadFile& e) {
robot::log_error("Cannot open YAML file: %s\n", e.what());
@@ -497,147 +236,60 @@ void ObstacleLayer::handleImpl(const void* data,
if (!enabled_ || stop_receiving_data_)
return;
if (type == typeid(robot_sensor_msgs::DepthCameraData::ConstPtr))
// DepthCameraData and other types are for other layers sharing this gateway; ignored here.
if (observation_buffers_.empty() || callback_infos_.empty())
return;
int size_callback = static_cast<int>(callback_infos_.size());
for (int i = 0; i < size_callback; i++)
{
const robot_sensor_msgs::DepthCameraData::ConstPtr& depth_camera_data_ptr =
*static_cast<const robot_sensor_msgs::DepthCameraData::ConstPtr*>(data);
if (!depth_camera_data_ptr)
return;
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[i];
const robot_sensor_msgs::DepthCameraData& depth_camera_data =
*depth_camera_data_ptr;
const robot_sensor_msgs::Image& depth = depth_camera_data.depth;
const robot_sensor_msgs::CameraInfo& camera_info = depth_camera_data.camera_info;
std::size_t bytes_per_pixel = 0;
if (depth.encoding == "16UC1" || depth.encoding == "mono16")
bytes_per_pixel = 2;
else if (depth.encoding == "32FC1")
bytes_per_pixel = 4;
else
{
robot::log_error("ObstacleLayer received unsupported depth encoding: %s\n", depth.encoding.c_str());
return;
}
const bool invalid_dimensions = depth.width == 0 || depth.height == 0 ||
depth.step < static_cast<std::size_t>(depth.width) * bytes_per_pixel ||
depth.data.size() < static_cast<std::size_t>(depth.step) * depth.height;
if (invalid_dimensions)
{
robot::log_error("ObstacleLayer received malformed DepthCameraData image\n");
return;
}
if (camera_info.K[0] <= 0.0 || camera_info.K[4] <= 0.0)
{
robot::log_error("ObstacleLayer received invalid camera intrinsics for depth clearing\n");
return;
}
if ((camera_info.width != 0 && camera_info.width != depth.width) ||
(camera_info.height != 0 && camera_info.height != depth.height))
{
robot::log_error("ObstacleLayer received mismatched depth image and camera info dimensions\n");
return;
}
const std::string& depth_frame = depth.header.frame_id;
const std::string& camera_frame = camera_info.header.frame_id;
if (!depth_frame.empty() && !camera_frame.empty() && depth_frame != camera_frame)
{
robot::log_error("ObstacleLayer received mismatched depth and camera-info frames: %s != %s\n",
depth_frame.c_str(), camera_frame.c_str());
return;
}
if (depth_camera_data.header.frame_id.empty() && depth_frame.empty() && camera_frame.empty())
{
robot::log_error("ObstacleLayer received DepthCameraData without an optical frame\n");
return;
}
// std::lock_guard<std::mutex> lock(depth_camera_data_mutex_);
// pending_depth_camera_data_ = depth_camera_data_ptr;
if (depth_observation_buffers_.empty() || callback_depth_infos_.empty())
return;
int size_callback_depth = static_cast<int>(callback_depth_infos_.size());
for(int i = 0; i < size_callback_depth; i++)
{
boost::shared_ptr<ObservationBuffer>& buffer = depth_observation_buffers_[i];
if (type == typeid(robot_sensor_msgs::DepthCameraData::ConstPtr) &&
topic == callback_depth_infos_[i].topic)
{
// robot::log_error_throttle(1.0,"TEST");
bool paired = false;
for (const auto& source : paired_depth_sources_)
if (source->depth_topic == topic)
{ source->pairer.addDepth(depth_camera_data_ptr); paired = true; break; }
if (!paired) depthImageCallback(depth_camera_data_ptr, buffer);
}
}
}
else
{
if (observation_buffers_.empty() || callback_infos_.empty())
return;
int size_callback = static_cast<int>(callback_infos_.size());
for (int i = 0; i < size_callback; i++)
if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
!callback_infos_[i].inf_is_valid)
{
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[i];
if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
!callback_infos_[i].inf_is_valid)
{
// if(topic == "/f_scan") robot::log_error("DATA front laser! %d",i);
// if(topic == "/b_scan") robot::log_error("DATA back laser! %d",i);
laserScanCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
callback_infos_[i].inf_is_valid)
{
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud) &&
callback_infos_[i].data_type == "PointCloud" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud2) &&
callback_infos_[i].data_type == "PointCloud2" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
bool paired = false;
for (const auto& source : paired_depth_sources_)
if (source->cloud_topic == topic)
{ source->pairer.addCloud(*static_cast<const robot_sensor_msgs::PointCloud2*>(data)); paired = true; break; }
if (!paired) pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
}
// else
// {
// std::cout << "obstacle_layer: check type: " << (type == typeid(robot_sensor_msgs::LaserScan)) << std::endl
// << "obstacle_layer: inf_is_valid: " << callback_infos_[i].inf_is_valid << std::endl
// << "data type: " << callback_infos_[i].data_type << std::endl
// << "topic: " << topic << std::endl
// << "topic check: " << callback_infos_[i].topic << std::endl << std::endl;
// }
// if(topic == "/f_scan") robot::log_error("DATA front laser! %d",i);
// if(topic == "/b_scan") robot::log_error("DATA back laser! %d",i);
laserScanCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
callback_infos_[i].inf_is_valid)
{
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud) &&
callback_infos_[i].data_type == "PointCloud" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud2) &&
callback_infos_[i].data_type == "PointCloud2" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
}
// else
// {
// std::cout << "obstacle_layer: check type: " << (type == typeid(robot_sensor_msgs::LaserScan)) << std::endl
// << "obstacle_layer: inf_is_valid: " << callback_infos_[i].inf_is_valid << std::endl
// << "data type: " << callback_infos_[i].data_type << std::endl
// << "topic: " << topic << std::endl
// << "topic check: " << callback_infos_[i].topic << std::endl << std::endl;
// }
}
}
@@ -739,14 +391,6 @@ void ObstacleLayer::pointCloud2Callback(const robot_sensor_msgs::PointCloud2& me
buffer->unlock();
}
void ObstacleLayer::depthImageCallback(robot_sensor_msgs::DepthCameraData::ConstPtr message,
const boost::shared_ptr<ObservationBuffer>& buffer)
{
buffer->lock();
buffer->bufferDepthCamera(std::move(message));
buffer->unlock();
}
void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y)
{
@@ -916,39 +560,6 @@ bool ObstacleLayer::getClearingObservations(std::vector<Observation>& clearing_o
return current;
}
bool ObstacleLayer::getFrustumClearingObservations(std::vector<DepthCameraObservation>& frustum_clearing_observations) const
{
bool current = true;
// DepthCameraObservation depth_obs;
for (const boost::shared_ptr<ObservationBuffer>& buffer : depth_observation_buffers_)
{
bool paired = false;
for (const auto& source : paired_depth_sources_)
if (source->depth_buffer == buffer) { paired = true; break; }
if (paired) continue;
buffer->lock();
buffer->getDepthObservations(frustum_clearing_observations);
current = buffer->isCurrent() && current;
buffer->unlock();
// frustum_clearing_observations.push_back(depth_obs);
}
return current;
}
bool ObstacleLayer::pairedDepthCurrent() const
{
bool current = true;
for (const auto& source : paired_depth_sources_) current = source->pairer.isCurrent() && current;
return current;
}
void ObstacleLayer::resetPairedDepth()
{
for (const auto& source : paired_depth_sources_) source->pairer.reset();
}
void ObstacleLayer::raytraceFreespace(const Observation& clearing_observation, double* min_x, double* min_y,
double* max_x, double* max_y)
{

View File

@@ -36,7 +36,6 @@
* David V. Lu!!
*********************************************************************/
#include <robot_costmap_2d/voxel_layer.h>
#include <robot_costmap_2d/depth_visibility.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
#include <robot_geometry_msgs/Vector3.h>
@@ -46,7 +45,6 @@
#include <cmath>
#include <cstdint>
#include <cstring>
#include <array>
#define VOXEL_BITS 16
@@ -73,18 +71,6 @@ void VoxelLayer::onInitialize()
VoxelLayer::~VoxelLayer()
{}
VoxelGrid VoxelLayer::voxelSnapshot()
{
VoxelGrid out;
out.header.frame_id = global_frame_;
out.header.stamp = robot::Time::now();
out.size_x = size_x_; out.size_y = size_y_; out.size_z = size_z_;
out.origin.x = origin_x_; out.origin.y = origin_y_; out.origin.z = origin_z_;
out.resolutions.x = out.resolutions.y = resolution_; out.resolutions.z = z_resolution_;
out.data.assign(robot_voxel_grid_.getData(), robot_voxel_grid_.getData() + size_x_ * size_y_);
return out;
}
bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandle &nh)
{
try
@@ -113,7 +99,7 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
mark_threshold_ = loadParam(layer, "mark_threshold", 0);
combination_method_ = loadParam(layer, "combination_method", 0.0);
int size_z, unknown_threshold, mark_threshold, frustum_pixel_step;
int size_z, unknown_threshold, mark_threshold;
if (nh.hasParam("enabled"))
nh.getParam("enabled", enabled_);
if (nh.hasParam("footprint_clearing_enabled"))
@@ -140,20 +126,6 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
if (nh.hasParam("combination_method"))
nh.getParam("combination_method", combination_method_);
if (!paired_depth_sources_.empty())
{
z_resolution_ = paired_depth_sources_.front()->config.voxel_z_resolution_m;
const auto& source = paired_depth_sources_.front();
if (!size_z_ || size_z_ > VOXEL_BITS || source->min_height < origin_z_ ||
source->max_height > origin_z_ + size_z_ * z_resolution_)
throw std::invalid_argument("observed_volume marking height band must fit its voxel grid");
robot::log_info("observed_volume grid: z_resolution=%.4f m bins=%u span=[%.3f, %.3f) m\n",
z_resolution_, size_z_, origin_z_, origin_z_ + size_z_ * z_resolution_);
depth_evidence_.setPointsPerVoxel(source->config.evidence_points_per_voxel);
robot::log_info("observed_volume evidence points: %s, points_per_voxel=%u, marking_border_px=%u px\n",
source->config.evidence_points_enabled ? "enabled" : "disabled (whole-voxel check)",
depth_evidence_.pointsPerVoxel(), source->config.marking_border_px);
}
this->matchSize();
}
catch (const YAML::BadFile& e) {
@@ -168,7 +140,6 @@ void VoxelLayer::matchSize()
{
ObstacleLayer::matchSize();
robot_voxel_grid_.resize(size_x_, size_y_, size_z_);
depth_evidence_.clear();
if (!(robot_voxel_grid_.sizeX() == size_x_ && robot_voxel_grid_.sizeY() == size_y_))
{
std::cerr << "[FATAL] Voxel grid size mismatch: "
@@ -188,10 +159,8 @@ void VoxelLayer::reset()
void VoxelLayer::resetMaps()
{
resetPairedDepth();
Costmap2D::resetMaps();
robot_voxel_grid_.reset();
depth_evidence_.clear();
}
void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
@@ -201,16 +170,8 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
useExtraBounds(min_x, min_y, max_x, max_y);
if (!paired_depth_sources_.empty() &&
(!static_marking_observations_.empty() || !static_clearing_observations_.empty()))
{
current_ = false;
robot::log_error_throttle(5.0, "observed_volume cannot share its voxel grid with static observations\n");
return;
}
bool current = true;
std::vector<Observation> observations, clearing_observations;
std::vector<DepthCameraObservation> depth_observations;
// get the marking observations
current = getMarkingObservations(observations) && current;
@@ -218,82 +179,19 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
// get the clearing observations
current = getClearingObservations(clearing_observations) && current;
current = getFrustumClearingObservations(depth_observations) && current;
// update the global current status
current_ = current;
for (const DepthCameraObservation& depth_observation : depth_observations)
{
raytraceDepthFrustum(depth_observation, min_x, min_y, max_x, max_y);
}
// raytrace freespace
for (unsigned int i = 0; i < clearing_observations.size(); ++i)
{
raytraceFreespace(clearing_observations[i], min_x, min_y, max_x, max_y);
}
for (const auto& observation : observations)
markObservation(observation, min_x, min_y, max_x, max_y);
processPairedDepth(min_x, min_y, max_x, max_y);
current_ = current_ && pairedDepthCurrent();
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
if (footprint_clearing_enabled_ && !paired_depth_sources_.empty())
clearFootprintVoxels();
}
void VoxelLayer::clearDepthColumn(unsigned int x, unsigned int y)
{
if (x >= size_x_ || y >= size_y_)
return;
const unsigned int index = getIndex(x, y);
if (robot_voxel_grid_.getData()[index] >> 16)
for (unsigned int z = 0; z < size_z_; ++z)
depth_evidence_.erase(evidenceKey(x, y, z));
robot_voxel_grid_.clearVoxelColumn(index);
}
void VoxelLayer::clearFootprintVoxels()
{
if (transformed_footprint_.size() < 3)
return;
std::vector<MapLocation> map_polygon;
for (const auto& point : transformed_footprint_)
// place the new obstacles into a priority queue... each with a priority of zero to begin with
for (std::vector<Observation>::const_iterator it = observations.begin(); it != observations.end(); ++it)
{
MapLocation location;
// Same rule as setConvexPolygonCost: a footprint partly outside the window clears nothing.
if (!worldToMap(point.x, point.y, location.x, location.y))
return;
map_polygon.push_back(location);
}
std::vector<MapLocation> cells;
convexFillCells(map_polygon, cells);
for (const auto& cell : cells)
{
clearDepthColumn(cell.x, cell.y);
costmap_[getIndex(cell.x, cell.y)] = FREE_SPACE;
}
}
void VoxelLayer::clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area)
{
// Same cell selection as CostmapLayer::clearArea, which then writes the 2D cells.
for (int x = 0; x < static_cast<int>(size_x_); ++x)
{
const bool xrange = x > start_x && x < end_x;
for (int y = 0; y < static_cast<int>(size_y_); ++y)
if ((xrange && y > start_y && y < end_y) == invert_area)
clearDepthColumn(static_cast<unsigned int>(x), static_cast<unsigned int>(y));
}
CostmapLayer::clearArea(start_x, start_y, end_x, end_y, invert_area);
}
void VoxelLayer::markObservation(const Observation& obs, double* min_x, double* min_y,
double* max_x, double* max_y, const PairedMarking* paired)
{
const bool record_evidence = paired != nullptr && paired->config->evidence_points_enabled;
const Observation& obs = *it;
const robot_sensor_msgs::PointCloud2& cloud = *(obs.cloud_);
@@ -330,21 +228,6 @@ void VoxelLayer::markObservation(const Observation& obs, double* min_x, double*
continue;
}
bool fresh_voxel = false;
if (record_evidence)
{
// A point at the image edge could never be re-checked with a full patch from the
// pose that saw it, and would leave a voxel that only the whole-box rule judges.
const Eigen::Vector3d point(*iter_x, *iter_y, *iter_z);
if ((paired->config->marking_border_px > 0 || paired->config->stereo_baseline_m > 0) &&
!paired->checker->projectsInside(point, paired->config->marking_border_px))
{
++visibility_counts_.border_dropped;
continue;
}
fresh_voxel = robot_voxel_grid_.getVoxel(mx, my, mz) != robot_voxel_grid::MARKED;
}
// mark the cell in the voxel grid and check if we should also mark it in the costmap
if (robot_voxel_grid_.markVoxelInMap(mx, my, mz, mark_threshold_))
{
@@ -353,184 +236,9 @@ void VoxelLayer::markObservation(const Observation& obs, double* min_x, double*
costmap_[index] = LETHAL_OBSTACLE;
touch(double(*iter_x), double(*iter_y), min_x, min_y, max_x, max_y);
}
if (record_evidence)
depth_evidence_.add(evidenceKey(mx, my, mz), Eigen::Vector3f(*iter_x, *iter_y, *iter_z), fresh_voxel);
}
}
void VoxelLayer::pruneDepthEvidence()
{
if (depth_evidence_.size() == 0)
return;
depth_evidence_.eraseIf([this](const DepthEvidenceStore::VoxelKey& key) {
const int x = key.x - evidence_offset_x_;
const int y = key.y - evidence_offset_y_;
return x < 0 || y < 0 || x >= static_cast<int>(size_x_) || y >= static_cast<int>(size_y_) ||
key.z >= size_z_ ||
robot_voxel_grid_.getVoxel(static_cast<unsigned int>(x), static_cast<unsigned int>(y), key.z) !=
robot_voxel_grid::MARKED;
});
}
bool VoxelLayer::reobserveFrees(DepthObservation observation, const DepthEvidenceStore::VoxelKey& key,
const DepthFrustumConfig& config)
{
float miss = 0.f;
switch (observation)
{
case DepthObservation::Confirmed:
++visibility_counts_.confirmed;
depth_evidence_.resetMiss(key);
return false;
case DepthObservation::Occluded:
++visibility_counts_.occluded;
return false;
case DepthObservation::OutOfView:
++visibility_counts_.out_of_view;
return false;
case DepthObservation::SeenThrough:
++visibility_counts_.seen_through;
miss = depth_evidence_.addMiss(key, 1.f);
break;
case DepthObservation::NoReturn:
++visibility_counts_.no_return;
if (config.no_return_weight <= 0)
return false;
miss = depth_evidence_.addMiss(key, static_cast<float>(config.no_return_weight));
break;
}
// The small slack absorbs float rounding when fractional no-return weights add up.
return miss >= static_cast<float>(config.miss_frames) - 1e-3f;
}
void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x, double* max_y)
{
for (const auto& source : paired_depth_sources_)
{
DepthFramePairer::Candidate pair;
while (source->pairer.next(pair))
{
tf3::TransformStampedMsg pose;
try
{
pose = tf_->lookupTransform(global_frame_, pair.cloud->header.frame_id,
data_convert::convertTime(pair.cloud->header.stamp));
}
catch (const tf3::TransformException& ex)
{
source->pairer.noteTfWait();
robot::log_error_throttle(5.0, "paired depth waiting for measurement TF: %s\n", ex.what());
break; // retain occupancy and bounded pending pair, never use latest TF
}
DepthVisibilityChecker checker;
if (!checker.prepare(pair.depth, pose, source->min_height,
std::min(source->max_height, max_obstacle_height_), source->config))
{
source->pairer.discard(pair.stamp);
robot::log_error_throttle(5.0, "paired depth rejected invalid image/model/pose\n");
continue;
}
std::vector<Observation> observations;
bool buffered;
{
std::lock_guard<ObservationBuffer> guard(*source->marking_buffer);
buffered = source->marking_buffer->tryBufferCloudWithTransform(*pair.cloud, pose);
if (buffered) source->marking_buffer->getObservations(observations);
}
if (!buffered || observations.size() != 1 ||
observations.front().cloud_->header.stamp.toNSec() != pair.stamp)
{
source->pairer.discard(pair.stamp);
continue; // no partial clear when marking branch cannot be prepared
}
// No occupied cache: the live voxel grid already contains rolling-window overlap.
// Plan all clears before applying this frame; both branches share exactly one pose.
// With evidence points a voxel is judged by the points that marked it; a voxel
// without evidence (marked before the mode was enabled) keeps the whole-box rule.
const bool use_evidence = source->config.evidence_points_enabled;
const bool reobserve = use_evidence && source->config.reobserve_clearing;
std::vector<Eigen::Vector3d> evidence;
std::vector<std::array<unsigned int, 3>> free_voxels;
for (unsigned int y = 0; y < size_y_; ++y)
for (unsigned int x = 0; x < size_x_; ++x)
{
if (!(robot_voxel_grid_.getData()[getIndex(x, y)] >> 16)) continue;
for (unsigned int z = 0; z < size_z_; ++z)
{
if (robot_voxel_grid_.getVoxel(x, y, z) != robot_voxel_grid::MARKED) continue;
DepthVisibilityResult visibility;
const auto key = evidenceKey(x, y, z);
if (use_evidence && depth_evidence_.points(key, evidence))
{
++visibility_counts_.by_evidence;
if (reobserve)
{
if (reobserveFrees(checker.observePoints(evidence), key, source->config))
{ free_voxels.push_back({x, y, z}); ++visibility_counts_.free; }
continue;
}
visibility = checker.classifyPoints(evidence);
}
else
{
const Eigen::Vector3d lower(origin_x_ + x * resolution_,
origin_y_ + y * resolution_, origin_z_ + z * z_resolution_);
const Eigen::Vector3d upper = lower + Eigen::Vector3d(resolution_, resolution_, z_resolution_);
visibility = checker.classify(lower, upper);
}
if (visibility.state == DepthVisibility::Free)
{ free_voxels.push_back({x, y, z}); ++visibility_counts_.free; }
else if (visibility.state == DepthVisibility::Surface) ++visibility_counts_.surface;
else ++visibility_counts_.unknown;
}
}
for (const auto& voxel : free_voxels)
{
const auto x = voxel[0], y = voxel[1], z = voxel[2];
robot_voxel_grid_.clearVoxel(x, y, z);
depth_evidence_.erase(evidenceKey(x, y, z));
const auto status = robot_voxel_grid_.getVoxelColumn(x, y, unknown_threshold_, mark_threshold_);
costmap_[getIndex(x, y)] = status == robot_voxel_grid::MARKED ? LETHAL_OBSTACLE :
status == robot_voxel_grid::FREE ? FREE_SPACE : NO_INFORMATION;
// Include whole cell so master/inflation can remove the former obstacle.
touch(origin_x_ + x * resolution_, origin_y_ + y * resolution_, min_x, min_y, max_x, max_y);
touch(origin_x_ + (x + 1) * resolution_, origin_y_ + (y + 1) * resolution_, min_x, min_y, max_x, max_y);
}
const PairedMarking paired_marking{&checker, &source->config};
markObservation(observations.front(), min_x, min_y, max_x, max_y, &paired_marking);
source->pairer.applied(pair.stamp);
++visibility_counts_.frames;
// Voxels cleared by other paths (footprint, recovery, legacy rays) leave stale
// evidence; a bounded sweep keeps the store at the size of the live occupancy.
constexpr uint64_t kEvidencePrunePeriodFrames = 50;
if (use_evidence && ++frames_since_evidence_prune_ >= kEvidencePrunePeriodFrames)
{
pruneDepthEvidence();
frames_since_evidence_prune_ = 0;
}
}
const auto counts = source->pairer.counts();
robot::log_info_throttle(5.0, "paired depth [%s]: applied=%llu tf_wait=%llu "
"invalid=%llu stale=%llu expired=%llu overflow=%llu duplicate=%llu; "
"voxel decisions free=%llu surface=%llu unknown=%llu by_evidence=%llu; "
"reobserve confirmed=%llu occluded=%llu seen_through=%llu no_return=%llu out_of_view=%llu; "
"border_dropped_points=%llu evidence_voxels=%zu (cumulative)\n",
name_.c_str(), static_cast<unsigned long long>(counts.applied),
static_cast<unsigned long long>(counts.tf_wait), static_cast<unsigned long long>(counts.invalid),
static_cast<unsigned long long>(counts.stale), static_cast<unsigned long long>(counts.expired),
static_cast<unsigned long long>(counts.overflow), static_cast<unsigned long long>(counts.duplicate),
static_cast<unsigned long long>(visibility_counts_.free),
static_cast<unsigned long long>(visibility_counts_.surface),
static_cast<unsigned long long>(visibility_counts_.unknown),
static_cast<unsigned long long>(visibility_counts_.by_evidence),
static_cast<unsigned long long>(visibility_counts_.confirmed),
static_cast<unsigned long long>(visibility_counts_.occluded),
static_cast<unsigned long long>(visibility_counts_.seen_through),
static_cast<unsigned long long>(visibility_counts_.no_return),
static_cast<unsigned long long>(visibility_counts_.out_of_view),
static_cast<unsigned long long>(visibility_counts_.border_dropped), depth_evidence_.size());
}
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
}
void VoxelLayer::clearNonLethal(double wx, double wy, double w_size_x, double w_size_y, bool clear_no_info)
@@ -681,545 +389,6 @@ void VoxelLayer::raytraceFreespace(const Observation& clearing_observation, doub
}
}
bool VoxelLayer::readDepthMeters(const robot_sensor_msgs::Image& depth, unsigned int u, unsigned int v,
double& depth_m, bool& is_valid) const
{
depth_m = 0.0;
is_valid = false;
if (u >= depth.width || v >= depth.height)
return false;
if (depth.encoding == "16UC1" || depth.encoding == "mono16")
{
const std::size_t offset = static_cast<std::size_t>(v) * depth.step + static_cast<std::size_t>(u) * 2;
if (offset + sizeof(std::uint16_t) > depth.data.size())
return false;
std::uint16_t raw = 0;
if (depth.is_bigendian)
raw = static_cast<std::uint16_t>((depth.data[offset] << 8) | depth.data[offset + 1]);
else
raw = static_cast<std::uint16_t>(depth.data[offset] | (depth.data[offset + 1] << 8));
if (raw == 0)
return true;
depth_m = static_cast<double>(raw) * 0.001;
is_valid = true;
return true;
}
if (depth.encoding == "32FC1")
{
const std::size_t offset = static_cast<std::size_t>(v) * depth.step + static_cast<std::size_t>(u) * 4;
if (offset + sizeof(float) > depth.data.size())
return false;
float raw = 0.0f;
if (depth.is_bigendian)
{
unsigned char bytes[sizeof(float)] = {
depth.data[offset + 3], depth.data[offset + 2], depth.data[offset + 1], depth.data[offset]};
std::memcpy(&raw, bytes, sizeof(float));
}
else
{
std::memcpy(&raw, &depth.data[offset], sizeof(float));
}
if (!std::isfinite(raw) || raw <= 0.0f)
return true;
depth_m = static_cast<double>(raw);
is_valid = true;
return true;
}
robot::log_error("VoxelLayer unsupported depth encoding for frustum clearing: %s\n", depth.encoding.c_str());
return false;
}
void VoxelLayer::updateDepthRayCache(unsigned int width, unsigned int height,
unsigned int pixel_step, double fx, double fy,
double cx, double cy)
{
if (cached_depth_width_ == width && cached_depth_height_ == height &&
cached_depth_pixel_step_ == pixel_step && cached_fx_ == fx && cached_fy_ == fy &&
cached_cx_ == cx && cached_cy_ == cy)
{
return;
}
cached_depth_width_ = width;
cached_depth_height_ = height;
cached_depth_pixel_step_ = pixel_step;
cached_fx_ = fx;
cached_fy_ = fy;
cached_cx_ = cx;
cached_cy_ = cy;
// Sample every pixel_step-th row/column and always include the last image
// row/column, so cells marked from border pixels stay inside the swept
// clearing fan.
std::vector<unsigned int> u_samples, v_samples;
u_samples.reserve(width / pixel_step + 2);
v_samples.reserve(height / pixel_step + 2);
for (unsigned int u = 0; u < width; u += pixel_step)
u_samples.push_back(u);
if (width > 0 && u_samples.back() != width - 1)
u_samples.push_back(width - 1);
for (unsigned int v = 0; v < height; v += pixel_step)
v_samples.push_back(v);
if (height > 0 && v_samples.back() != height - 1)
v_samples.push_back(height - 1);
cached_column_count_ = static_cast<unsigned int>(u_samples.size());
depth_ray_cache_.clear();
depth_ray_cache_.reserve(u_samples.size() * v_samples.size());
for (const unsigned int v : v_samples)
{
for (unsigned int col = 0; col < u_samples.size(); ++col)
{
const unsigned int u = u_samples[col];
const double x = (static_cast<double>(u) - cx) / fx;
const double y = (static_cast<double>(v) - cy) / fy;
const double inverse_norm = 1.0 / std::sqrt(x * x + y * y + 1.0);
depth_ray_cache_.push_back(
DepthRay{u, v, col, x * inverse_norm, y * inverse_norm, inverse_norm});
}
}
}
bool VoxelLayer::clipRaytraceEndpoint(double ox, double oy, double oz, double& wx, double& wy, double& wz)
{
double a = wx - ox;
double b = wy - oy;
double c = wz - oz;
double t = 1.0;
constexpr double kEpsilon = 1e-9;
if (std::fabs(a) < kEpsilon && std::fabs(b) < kEpsilon && std::fabs(c) < kEpsilon)
return false;
if (wz > max_obstacle_height_ && std::fabs(c) > kEpsilon)
t = std::max(0.0, std::min(t, (max_obstacle_height_ - 0.01 - oz) / c));
else if (wz < origin_z_ && std::fabs(c) > kEpsilon)
t = std::min(t, (origin_z_ - oz) / c);
const double map_end_x = origin_x_ + getSizeInMetersX();
const double map_end_y = origin_y_ + getSizeInMetersY();
if (wx < origin_x_ && std::fabs(a) > kEpsilon)
t = std::min(t, (origin_x_ - ox) / a);
if (wy < origin_y_ && std::fabs(b) > kEpsilon)
t = std::min(t, (origin_y_ - oy) / b);
if (wx > map_end_x && std::fabs(a) > kEpsilon)
t = std::min(t, (map_end_x - ox) / a);
if (wy > map_end_y && std::fabs(b) > kEpsilon)
t = std::min(t, (map_end_y - oy) / b);
if (!std::isfinite(t) || t <= 0.0)
return false;
wx = ox + a * t;
wy = oy + b * t;
wz = oz + c * t;
return true;
}
bool VoxelLayer::clearVoxelRay(double ox, double oy, double oz, double wx, double wy, double wz,
double raytrace_range, unsigned int cell_raytrace_range,
double* min_x, double* min_y, double* max_x, double* max_y)
{
double sensor_x, sensor_y, sensor_z;
if (!worldToMap3DFloat(ox, oy, oz, sensor_x, sensor_y, sensor_z))
return false;
if (!clipRaytraceEndpoint(ox, oy, oz, wx, wy, wz))
return false;
double point_x, point_y, point_z;
if (!worldToMap3DFloat(wx, wy, wz, point_x, point_y, point_z))
return false;
robot_voxel_grid_.clearVoxelLineInMap(sensor_x, sensor_y, sensor_z, point_x, point_y, point_z, costmap_,
unknown_threshold_, mark_threshold_, FREE_SPACE, NO_INFORMATION,
cell_raytrace_range);
updateRaytraceBounds(ox, oy, wx, wy, raytrace_range, min_x, min_y, max_x, max_y);
return true;
}
bool VoxelLayer::raytraceDepthFrustum(const DepthCameraObservation& observation,
double* min_x, double* min_y, double* max_x, double* max_y)
{
if (!observation.data_)
return false;
const robot_sensor_msgs::DepthCameraData& depth_camera_data = *observation.data_;
const robot_sensor_msgs::Image& depth = depth_camera_data.depth;
const robot_sensor_msgs::CameraInfo& camera_info = depth_camera_data.camera_info;
if (depth.width == 0 || depth.height == 0 || depth.data.empty())
return false;
const double fx = camera_info.K[0];
const double fy = camera_info.K[4];
const double cx = camera_info.K[2];
const double cy = camera_info.K[5];
if (fx <= 0.0 || fy <= 0.0)
return false;
std::string depth_frame = depth.header.frame_id.empty() ? depth_camera_data.header.frame_id : depth.header.frame_id;
if (depth_frame.empty())
depth_frame = camera_info.header.frame_id;
if (depth_frame.empty() || tf_ == nullptr)
return false;
robot_geometry_msgs::PointStamped local_origin;
local_origin.header = depth.header;
local_origin.header.frame_id = depth_frame;
if (local_origin.header.stamp.isZero())
local_origin.header.stamp = depth_camera_data.header.stamp;
local_origin.point.x = 0.0;
local_origin.point.y = 0.0;
local_origin.point.z = 0.0;
robot_geometry_msgs::PointStamped global_origin;
tf3::TransformStampedMsg tfm;
try
{
const robot::Time& depth_stamp = local_origin.header.stamp;
const tf3::Time query_time =
depth_stamp.isZero()
? tf3::Time()
: tf3::Time(depth_stamp.sec, depth_stamp.nsec);
tfm = tf_->lookupTransform(global_frame_, depth_frame, query_time);
tf3::doTransform(local_origin, global_origin, tfm);
}
catch (tf3::TransformException& ex)
{
robot::log_error_throttle(
5.0, "VoxelLayer depth topic [%s] TF exception from %s to %s: %s\n",
observation.topic_.c_str(), depth_frame.c_str(), global_frame_.c_str(), ex.what());
return false;
}
const double ox = global_origin.point.x;
const double oy = global_origin.point.y;
const double oz = global_origin.point.z;
double sensor_x, sensor_y, sensor_z;
if (!worldToMap3DFloat(ox, oy, oz, sensor_x, sensor_y, sensor_z))
{
robot::log_error_throttle(
5.0, "VoxelLayer depth topic [%s] origin at (%.2f, %.2f, %.2f) is outside the voxel map\n",
observation.topic_.c_str(), ox, oy, oz);
return false;
}
const DepthFrustumConfig& frustum = observation.frustum_;
const unsigned int step = std::max(1u, frustum.pixel_step);
const double min_range = frustum.min_range;
const double max_range = frustum.max_range;
const double skip_dist =
frustum.skip_distance >= 0.0 ? frustum.skip_distance : 2.0 * resolution_;
const unsigned int width = std::min(depth.width, camera_info.width == 0 ? depth.width : camera_info.width);
const unsigned int height = std::min(depth.height, camera_info.height == 0 ? depth.height : camera_info.height);
updateDepthRayCache(width, height, step, fx, fy, cx, cy);
double qx = tfm.transform.rotation.x;
double qy = tfm.transform.rotation.y;
double qz = tfm.transform.rotation.z;
double qw = tfm.transform.rotation.w;
const double quaternion_norm = std::sqrt(qx * qx + qy * qy + qz * qz + qw * qw);
if (quaternion_norm <= 0.0)
return false;
qx /= quaternion_norm;
qy /= quaternion_norm;
qz /= quaternion_norm;
qw /= quaternion_norm;
const double r00 = 1.0 - 2.0 * (qy * qy + qz * qz);
const double r01 = 2.0 * (qx * qy - qz * qw);
const double r02 = 2.0 * (qx * qz + qy * qw);
const double r10 = 2.0 * (qx * qy + qz * qw);
const double r11 = 1.0 - 2.0 * (qx * qx + qz * qz);
const double r12 = 2.0 * (qy * qz - qx * qw);
const double r20 = 2.0 * (qx * qz - qy * qw);
const double r21 = 2.0 * (qy * qz + qx * qw);
const double r22 = 1.0 - 2.0 * (qx * qx + qy * qy);
const unsigned int cell_raytrace_range = cellDistance(max_range);
bool cleared_any = false;
// Column clearing: certify the beam length per pixel column and the distance
// window [cover, far] where the vertical FOV spans the whole height band.
// Outside that window a real obstacle could sit above/below the FOV, so only
// the per-pixel 3D rays may clear there.
const double band_min_h = frustum.column_min_height;
const double band_max_h =
frustum.column_max_height >= 0.0 ? frustum.column_max_height : max_obstacle_height_;
double cover_dist = frustum.column_cover_distance;
double far_dist = std::numeric_limits<double>::infinity();
bool column_pass = frustum.column_clearing && band_max_h > band_min_h;
if (column_pass && cover_dist < 0.0)
{
const double up_half = std::atan2(cy, fy);
const double down_half = std::atan2(static_cast<double>(height) - 1.0 - cy, fy);
const double axis_elev = std::atan2(r22, std::hypot(r02, r12));
const double alpha_top = axis_elev + up_half;
const double alpha_bot = axis_elev - down_half;
const double band_top = band_max_h - oz;
const double band_bot = band_min_h - oz;
constexpr double kMinSlope = 1e-3;
cover_dist = 0.0;
if (band_top > 0.0)
{
if (alpha_top <= kMinSlope)
column_pass = false; // camera can never look up to the band top
else
cover_dist = std::max(cover_dist, band_top / std::tan(alpha_top));
}
else if (alpha_top < -kMinSlope)
{
far_dist = std::min(far_dist, band_top / std::tan(alpha_top));
}
if (band_bot < 0.0)
{
if (alpha_bot >= -kMinSlope)
column_pass = false; // camera can never look down to the band bottom
else
cover_dist = std::max(cover_dist, band_bot / std::tan(alpha_bot));
}
else if (alpha_bot > kMinSlope)
{
far_dist = std::min(far_dist, band_bot / std::tan(alpha_bot));
}
if (!column_pass)
{
robot::log_warning_throttle(
10.0, "VoxelLayer column clearing disabled: vertical FOV [%.1f, %.1f] deg at camera "
"height %.2f m never covers band [%.2f, %.2f] m\n",
alpha_bot * 180.0 / M_PI, alpha_top * 180.0 / M_PI, oz, band_min_h, band_max_h);
}
}
if (column_pass)
depth_column_stats_.assign(cached_column_count_, DepthColumnStat());
for (const DepthRay& local_ray : depth_ray_cache_)
{
double depth_m = 0.0;
bool valid = false;
if (!readDepthMeters(depth, local_ray.u, local_ray.v, depth_m, valid))
continue;
// Edge stereo no-disparity strips (left and/or right, depending on the
// camera). An INVALID pixel in such a strip is structurally invalid (carries
// no free-space evidence), so clearing it out to max_range erases obstacles
// rotating out of the FOV on that side (the turn bug) — skip only those. A
// VALID return there is a real measured surface, so it must still clear
// normally; otherwise the border becomes a clearing dead zone and obstacles
// there never get cleared. Invalid pixels OUTSIDE the strips still clear to
// max_range (ghost removal). Right edge measured inward from the last column;
// the unsigned test avoids underflow when the border exceeds the width.
const bool in_left_border = local_ray.u < frustum.clear_left_border_px;
const bool in_right_border =
frustum.clear_right_border_px > 0 &&
local_ray.u + frustum.clear_right_border_px >= width;
const bool in_border = in_left_border || in_right_border;
if (in_border && !valid)
continue;
// depth images store z-depth; local_ray.z is the unit ray's optical axis
// component, so depth / z is the Euclidean range
const double euclid_range = valid ? depth_m / local_ray.z : 0.0;
robot_geometry_msgs::Vector3 global_ray;
global_ray.x = r00 * local_ray.x + r01 * local_ray.y + r02 * local_ray.z;
global_ray.y = r10 * local_ray.x + r11 * local_ray.y + r12 * local_ray.z;
global_ray.z = r20 * local_ray.x + r21 * local_ray.y + r22 * local_ray.z;
if (column_pass && local_ray.col < depth_column_stats_.size())
{
const double horiz_norm = std::hypot(global_ray.x, global_ray.y);
if (horiz_norm > 1e-6)
{
DepthColumnStat& stat = depth_column_stats_[local_ray.col];
const double row_delta = std::fabs(static_cast<double>(local_ray.v) - cy);
if (stat.min_band_dist < 0.0 && row_delta < stat.best_row_delta)
{
// no in-band return yet: aim the beam along the ray nearest the
// principal row
stat.azimuth = std::atan2(global_ray.y, global_ray.x);
stat.best_row_delta = row_delta;
}
stat.has_ray = true;
if (in_border)
stat.in_border = true;
if (valid)
{
const double pz = oz + global_ray.z * euclid_range;
if (pz >= band_min_h && pz <= band_max_h)
{
const double dist_h = horiz_norm * euclid_range;
if (stat.min_band_dist < 0.0 || dist_h < stat.min_band_dist)
{
stat.min_band_dist = dist_h;
stat.azimuth = std::atan2(global_ray.y, global_ray.x);
}
}
}
}
}
double ray_len = max_range;
if (valid && euclid_range < max_range)
ray_len = std::max(0.0, euclid_range - skip_dist);
if (ray_len <= min_range)
continue;
const double sx = ox + global_ray.x * min_range;
const double sy = oy + global_ray.y * min_range;
const double sz = oz + global_ray.z * min_range;
const double wx = ox + global_ray.x * ray_len;
const double wy = oy + global_ray.y * ray_len;
const double wz = oz + global_ray.z * ray_len;
cleared_any = clearVoxelRay(sx, sy, sz, wx, wy, wz, ray_len, cell_raytrace_range,
min_x, min_y, max_x, max_y) || cleared_any;
}
if (column_pass)
{
cleared_any = clearDepthColumns(ox, oy, cover_dist, far_dist, min_range, max_range,
std::max(0.0, frustum.column_skip_distance),
min_x, min_y, max_x, max_y) ||
cleared_any;
}
return cleared_any;
}
namespace
{
/// raytraceLine action: frees the 2D cell and wipes its whole voxel column.
class ClearFullColumn
{
public:
ClearFullColumn(unsigned char* costmap, robot_voxel_grid::VoxelGrid& voxel_grid)
: costmap_(costmap), voxel_grid_(voxel_grid)
{
}
inline void operator()(unsigned int offset)
{
costmap_[offset] = FREE_SPACE;
voxel_grid_.clearVoxelColumn(offset);
}
private:
unsigned char* costmap_;
robot_voxel_grid::VoxelGrid& voxel_grid_;
};
} // namespace
bool VoxelLayer::clipColumnSegment(double& sx, double& sy, double& ex, double& ey) const
{
// Liang-Barsky clip against the map interior; the half-resolution margin
// keeps clipped endpoints valid for worldToMap.
const double min_wx = origin_x_;
const double min_wy = origin_y_;
const double max_wx = origin_x_ + getSizeInMetersX() - 0.5 * resolution_;
const double max_wy = origin_y_ + getSizeInMetersY() - 0.5 * resolution_;
const double dx = ex - sx;
const double dy = ey - sy;
const double p[4] = {-dx, dx, -dy, dy};
const double q[4] = {sx - min_wx, max_wx - sx, sy - min_wy, max_wy - sy};
double t0 = 0.0;
double t1 = 1.0;
for (int i = 0; i < 4; ++i)
{
if (std::fabs(p[i]) < 1e-12)
{
if (q[i] < 0.0)
return false;
continue;
}
const double r = q[i] / p[i];
if (p[i] < 0.0)
t0 = std::max(t0, r);
else
t1 = std::min(t1, r);
}
if (t0 > t1)
return false;
const double bx = sx;
const double by = sy;
sx = bx + t0 * dx;
sy = by + t0 * dy;
ex = bx + t1 * dx;
ey = by + t1 * dy;
return true;
}
bool VoxelLayer::clearDepthColumns(double ox, double oy, double cover_distance,
double far_distance, double min_range, double max_range,
double skip_dist, double* min_x, double* min_y,
double* max_x, double* max_y)
{
const double start_dist = std::max(cover_distance, min_range);
bool cleared_any = false;
for (const DepthColumnStat& stat : depth_column_stats_)
{
if (!stat.has_ray)
continue;
// In an edge stereo strip, never clear a whole column out to max_range on a
// missing in-band return: that is exactly the no-free-space-evidence case that
// erases obstacles turning out of view. Only an in-band measured surface may
// shorten (and thus clear) a border column.
if (stat.in_border && stat.min_band_dist < 0.0)
continue;
double end_dist = stat.min_band_dist >= 0.0 ? stat.min_band_dist - skip_dist : max_range;
end_dist = std::min(std::min(end_dist, max_range), far_distance);
if (end_dist <= start_dist)
continue;
const double cos_az = std::cos(stat.azimuth);
const double sin_az = std::sin(stat.azimuth);
double sx = ox + cos_az * start_dist;
double sy = oy + sin_az * start_dist;
double ex = ox + cos_az * end_dist;
double ey = oy + sin_az * end_dist;
if (!clipColumnSegment(sx, sy, ex, ey))
continue;
unsigned int sx_m, sy_m, ex_m, ey_m;
if (!worldToMap(sx, sy, sx_m, sy_m) || !worldToMap(ex, ey, ex_m, ey_m))
continue;
ClearFullColumn clearer(costmap_, robot_voxel_grid_);
raytraceLine(clearer, sx_m, sy_m, ex_m, ey_m);
touch(sx, sy, min_x, min_y, max_x, max_y);
touch(ex, ey, min_x, min_y, max_x, max_y);
cleared_any = true;
}
return cleared_any;
}
void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
{
// project the new origin into the grid
@@ -1267,10 +436,8 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
cell_size_x, cell_size_x, cell_size_y);
}
// Shift storage without resetting the paired input queue. A newly received
// measurement must still apply after the rolling origin moves this cycle.
Costmap2D::resetMaps();
robot_voxel_grid_.reset();
// we'll reset our maps to unknown space if appropriate
resetMaps();
// update the origin with the appropriate world coordinates
origin_x_ = new_grid_ox;
@@ -1289,10 +456,6 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
size_x_, cell_size_x, cell_size_y);
}
// Evidence keys are window-independent: track the shift, then drop what left the window.
evidence_offset_x_ += cell_ox;
evidence_offset_y_ += cell_oy;
pruneDepthEvidence();
}
// Export factory function