feat(depth): observed_volume depth clearing as deployed 2026-10-14

Baseline commit of the working-tree refactor built on 2026-10-14 17:24 and
running on the KIT robot, recorded in one commit before further changes.

- VoxelLayer clearing looks up TF at the depth image stamp.
- ObservationBuffer: per-source cloud preparation at the measurement stamp,
  height/range gate before the PCL VoxelGrid.
- DepthFramePairer: pairs the marking cloud with the clearing image by
  source and stamp, bounded queue and age.
- DepthVisibilityChecker and the observed_volume clearing mode in VoxelLayer;
  the legacy frustum mode stays the default.
- Tests: depth_observation_buffer_test, depth_visibility_test.
This commit is contained in:
2026-10-15 11:37:56 +07:00
parent a63c084002
commit 2ca0bcc1c1
15 changed files with 1336 additions and 19 deletions

View File

@@ -23,6 +23,7 @@ find_package(Boost REQUIRED COMPONENTS system thread filesystem)
# still configure. The test block below requires it where it is actually used.
find_package(GTest QUIET)
find_package(yaml-cpp REQUIRED)
find_package(PCL REQUIRED COMPONENTS common filters)
if (NOT BUILDING_WITH_CATKIN)
@@ -107,12 +108,16 @@ add_library(robot_costmap_2d SHARED
src/array_parser.cpp
src/costmap_2d.cpp
src/observation_buffer.cpp
src/depth_visibility.cpp
src/layer.cpp
src/layered_costmap.cpp
src/costmap_math.cpp
src/footprint.cpp
src/costmap_layer.cpp
)
target_include_directories(robot_costmap_2d SYSTEM PRIVATE ${PCL_INCLUDE_DIRS})
target_compile_options(robot_costmap_2d PRIVATE ${PCL_DEFINITIONS})
target_link_libraries(robot_costmap_2d PRIVATE ${PCL_LIBRARIES})
if(BUILDING_WITH_CATKIN)
add_dependencies(robot_costmap_2d ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
@@ -281,6 +286,19 @@ endif()
option(BUILD_COSTMAP_TESTS "Build robot_costmap_2d test executables"
${BUILDING_WITH_CATKIN})
option(BUILD_DEPTH_MARKING_TESTS "Build depth observation buffer regression tests" OFF)
if(BUILD_DEPTH_MARKING_TESTS)
find_package(GTest REQUIRED)
add_executable(depth_observation_buffer_test test/depth_observation_buffer_test.cpp)
target_compile_definitions(depth_observation_buffer_test PRIVATE
DEPTH_MARKING_TEST_PLUGIN_PATH="$<TARGET_FILE:plugins>")
target_link_libraries(depth_observation_buffer_test PRIVATE
plugins robot_costmap_2d GTest::GTest GTest::Main)
add_executable(depth_visibility_test test/depth_visibility_test.cpp)
target_link_libraries(depth_visibility_test PRIVATE
plugins robot_costmap_2d GTest::GTest GTest::Main)
endif()
if(BUILD_COSTMAP_TESTS)
find_package(GTest REQUIRED)
find_package(Boost REQUIRED COMPONENTS system thread filesystem)

View File

@@ -0,0 +1,166 @@
#pragma once
#include <robot_costmap_2d/observation.h>
#include <boost/make_shared.hpp>
#include <chrono>
#include <map>
#include <mutex>
#include <cmath>
#include <stdexcept>
#include <algorithm>
namespace robot_costmap_2d
{
// A source pair owns immutable measurement messages; the update thread alone
// acknowledges applied frames. Queue timeout/freshness never expires occupancy.
class DepthFramePairer
{
public:
using Clock = std::chrono::steady_clock;
struct Candidate
{
uint64_t stamp{0};
robot_sensor_msgs::PointCloud2::ConstPtr cloud;
robot_sensor_msgs::DepthCameraData::ConstPtr depth;
};
struct Counts
{
uint64_t applied{0}, expired{0}, overflow{0}, stale{0}, duplicate{0}, invalid{0}, tf_wait{0};
};
explicit DepthFramePairer(const DepthFrustumConfig& config, double expected_period)
: config_(config), expected_period_(expected_period), started_(robot::Time::now()), last_clock_(started_)
{
if (!std::isfinite(expected_period_) || expected_period_ < 0 ||
!config_.pair_queue_size || !std::isfinite(config_.pair_max_wait_s) || config_.pair_max_wait_s <= 0 ||
!std::isfinite(config_.observation_max_age_s) || config_.observation_max_age_s <= 0)
throw std::invalid_argument("invalid depth pair queue/age configuration");
}
void addCloud(const robot_sensor_msgs::PointCloud2& cloud)
{
std::lock_guard<std::mutex> lock(mutex_);
observeClock();
if (cloud.header.stamp.isZero()) { ++counts_.invalid; return; }
const auto key = cloud.header.stamp.toNSec();
if (key <= applied_stamp_) { ++counts_.duplicate; return; }
auto& p = pending_[key];
if (p.cloud) { ++counts_.duplicate; return; }
if (!p.depth) p.arrival = Clock::now();
p.cloud = boost::make_shared<robot_sensor_msgs::PointCloud2>(cloud);
expire();
}
void addDepth(robot_sensor_msgs::DepthCameraData::ConstPtr depth)
{
std::lock_guard<std::mutex> lock(mutex_);
observeClock();
if (!depth || depth->depth.header.stamp.isZero()) { ++counts_.invalid; return; }
const auto key = depth->depth.header.stamp.toNSec();
if (key <= applied_stamp_) { ++counts_.duplicate; return; }
auto& p = pending_[key];
if (p.depth) { ++counts_.duplicate; return; }
if (!p.cloud) p.arrival = Clock::now();
p.depth = std::move(depth);
expire();
}
bool next(Candidate& out)
{
std::lock_guard<std::mutex> lock(mutex_);
observeClock(); expire();
for (auto it = pending_.begin(); it != pending_.end();)
{
auto& p = it->second;
if (!p.cloud || !p.depth) { ++it; continue; }
if (p.cloud->header.frame_id != p.depth->depth.header.frame_id ||
p.depth->depth.header.stamp != p.depth->camera_info.header.stamp ||
p.depth->depth.header.stamp != p.depth->header.stamp)
{
++counts_.invalid;
it = pending_.erase(it);
continue;
}
out = {it->first, p.cloud, p.depth};
return true;
}
return false;
}
void applied(uint64_t stamp)
{
std::lock_guard<std::mutex> lock(mutex_);
applied_stamp_ = std::max(applied_stamp_, stamp);
last_applied_ = robot::Time::now();
++counts_.applied;
for (auto it = pending_.begin(); it != pending_.end() && it->first <= applied_stamp_;)
it = pending_.erase(it);
}
void discard(uint64_t stamp)
{
std::lock_guard<std::mutex> lock(mutex_);
pending_.erase(stamp); ++counts_.invalid;
}
void noteTfWait()
{
std::lock_guard<std::mutex> lock(mutex_); ++counts_.tf_wait;
}
bool isCurrent()
{
std::lock_guard<std::mutex> lock(mutex_);
observeClock();
const auto last = last_applied_.isZero() ? started_ : last_applied_;
return expected_period_ <= 0 || (robot::Time::now() - last).toSec() <= expected_period_;
}
void reset()
{
std::lock_guard<std::mutex> lock(mutex_);
const auto watermark = applied_stamp_;
resetUnlocked(robot::Time::now());
applied_stamp_ = watermark; // map resets must not replay a cached old frame
}
Counts counts() const
{
std::lock_guard<std::mutex> lock(mutex_); return counts_;
}
private:
struct Pending
{
robot_sensor_msgs::PointCloud2::ConstPtr cloud;
robot_sensor_msgs::DepthCameraData::ConstPtr depth;
Clock::time_point arrival;
};
void resetUnlocked(const robot::Time& now)
{
pending_.clear(); applied_stamp_ = 0; last_applied_ = robot::Time();
started_ = now; last_clock_ = now;
}
void observeClock()
{
const auto now = robot::Time::now();
if (now < last_clock_) resetUnlocked(now);
last_clock_ = now;
}
void expire()
{
const auto now = Clock::now();
const double measurement_now = robot::Time::now().toSec();
for (auto it = pending_.begin(); it != pending_.end();)
{
const double age = measurement_now - static_cast<double>(it->first) * 1e-9;
if (age > config_.observation_max_age_s || age < -.05)
{ ++counts_.stale; it = pending_.erase(it); }
else if (std::chrono::duration<double>(now - it->second.arrival).count() > config_.pair_max_wait_s)
{ ++counts_.expired; it = pending_.erase(it); }
else ++it;
}
while (pending_.size() > config_.pair_queue_size)
{ pending_.erase(pending_.begin()); ++counts_.overflow; }
}
DepthFrustumConfig config_;
double expected_period_;
robot::Time started_, last_clock_, last_applied_;
uint64_t applied_stamp_{0};
std::map<uint64_t, Pending> pending_;
Counts counts_;
mutable std::mutex mutex_;
};
} // namespace robot_costmap_2d

View File

@@ -0,0 +1,35 @@
#pragma once
#include <robot_costmap_2d/observation.h>
#include <tf3/compat.h>
#include <Eigen/Geometry>
#include <vector>
namespace robot_costmap_2d
{
enum class DepthVisibility { Free, Unknown, Surface };
enum class DepthVisibilityReason { Free, OutsideView, InvalidDepth, Surface, EmptyRegion };
struct DepthVisibilityResult
{
DepthVisibility state{DepthVisibility::Unknown};
DepthVisibilityReason reason{DepthVisibilityReason::OutsideView};
};
// Pure geometry/measurement helper. It never mutates occupancy or queries TF.
class DepthVisibilityChecker
{
public:
bool prepare(robot_sensor_msgs::DepthCameraData::ConstPtr data,
const tf3::TransformStampedMsg& global_from_camera,
double min_height, double max_height, const DepthFrustumConfig& config);
DepthVisibilityResult classify(const Eigen::Vector3d& lower,
const Eigen::Vector3d& upper) const;
private:
robot_sensor_msgs::DepthCameraData::ConstPtr data_;
Eigen::Isometry3d camera_from_global_{Eigen::Isometry3d::Identity()};
double min_height_{0}, max_height_{0};
DepthFrustumConfig config_;
unsigned int bytes_per_pixel_{0};
};
} // namespace robot_costmap_2d

View File

@@ -81,6 +81,17 @@ struct DepthFrustumConfig
/// stereo no-disparity strip sits on the right instead of the left. Measured
/// from the last image column inward. 0 disables.
unsigned int clear_right_border_px = 0;
// Opt-in observed-volume mode. Legacy range/column keys are not used by it.
bool observed_volume_clearing = false;
double voxel_z_resolution_m = 0.0625; // depth-only grid: low objects must not occupy an entire 20 cm slab
std::string paired_marking_source;
unsigned int pair_queue_size = 4;
double pair_max_wait_s = 0.25;
double observation_max_age_s = 0.5;
double valid_min_z_m = 0.1;
double valid_max_z_m = 3.0;
double free_margin_m = 0.02;
unsigned int projection_margin_px = 1;
};
class DepthCameraObservation

View File

@@ -50,6 +50,14 @@
namespace robot_costmap_2d
{
// Opt-in per source: legacy callers keep their TF and cloud policy.
struct CloudProcessingConfig
{
bool transform_at_stamp{false};
bool voxel_filter_enabled{false};
double voxel_leaf_size{0.05}; // [m], applied after height/range gates
};
/**
* @class ObservationBuffer
* @brief Takes in point clouds from sensors, transforms them to the desired frame, and stores them
@@ -104,6 +112,14 @@ public:
*/
void bufferCloud(const robot_sensor_msgs::PointCloud2& cloud);
// Configure before receiving samples. Empty valid clouds return true;
// missing TF/malformed observations return false and do not refresh the buffer.
void setCloudProcessingConfig(const CloudProcessingConfig& config);
bool tryBufferCloud(const robot_sensor_msgs::PointCloud2& cloud);
bool tryBufferCloudWithTransform(const robot_sensor_msgs::PointCloud2& cloud,
const tf3::TransformStampedMsg& transform);
const std::string& sensorFrame() const { return sensor_frame_; }
/**
* @brief Store the newest depth frame without converting it to PointCloud2.
*/
@@ -156,6 +172,8 @@ private:
void purgeStaleObservations();
void purgeStaleDepthObservations();
bool tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2& cloud,
const tf3::TransformStampedMsg* prepared_transform);
tf3::BufferCore& tf3_buffer_;
const robot::Duration observation_keep_time_;
@@ -172,6 +190,7 @@ private:
double obstacle_range_, raytrace_range_;
double tf_tolerance_;
DepthFrustumConfig frustum_config_;
CloudProcessingConfig cloud_processing_config_;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_

View File

@@ -42,6 +42,7 @@
#include <robot_costmap_2d/costmap_layer.h>
#include <robot_costmap_2d/layered_costmap.h>
#include <robot_costmap_2d/observation_buffer.h>
#include <robot_costmap_2d/depth_frame_pairer.h>
#include <robot_costmap_2d/footprint.h>
#include <robot_nav_msgs/OccupancyGrid.h>
@@ -202,6 +203,20 @@ protected:
mutable std::mutex depth_camera_data_mutex_;
robot_sensor_msgs::DepthCameraData::ConstPtr pending_depth_camera_data_;
struct PairedDepthSource
{
PairedDepthSource(const DepthFrustumConfig& config, double expected_period)
: config(config), pairer(config, expected_period) {}
std::string cloud_topic, depth_topic;
boost::shared_ptr<ObservationBuffer> marking_buffer, depth_buffer;
double min_height{0}, max_height{0};
DepthFrustumConfig config;
DepthFramePairer pairer;
};
std::vector<boost::shared_ptr<PairedDepthSource>> paired_depth_sources_;
bool pairedDepthCurrent() const;
void resetPairedDepth();
private:
bool getParams(const std::string& config_file_name, robot::NodeHandle &nh);
};

View File

@@ -73,6 +73,8 @@ public:
double* max_x, double* max_y);
void updateOrigin(double new_origin_x, double new_origin_y);
// Diagnostic snapshot; caller must hold the layer/update lock, as with getCharMap().
VoxelGrid voxelSnapshot();
bool isDiscretized()
{
return true;
@@ -109,6 +111,13 @@ private:
double min_range, double max_range, double skip_dist,
double* min_x, double* min_y, double* max_x, double* max_y);
bool clipColumnSegment(double& sx, double& sy, double& ex, double& ey) const;
void markObservation(const Observation& observation, double* min_x, double* min_y,
double* max_x, double* max_y);
void processPairedDepth(double* min_x, double* min_y, double* max_x, double* max_y);
struct VisibilityCounts
{
uint64_t free{0}, unknown{0}, surface{0}, frames{0};
} visibility_counts_;
bool publish_voxel_;

View File

@@ -20,6 +20,8 @@
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>libconsole-bridge-dev</build_depend>
<build_depend>libpcl-all-dev</build_depend>
<run_depend>libpcl-all</run_depend>
<run_depend>libconsole-bridge-dev</run_depend>
<build_depend>robot_std_msgs</build_depend>
@@ -64,4 +66,4 @@
<build_depend>robot_time</build_depend>
<run_depend>robot_time</run_depend>
</package>
</package>

View File

@@ -122,6 +122,25 @@ 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();
@@ -225,6 +244,41 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
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");
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));
@@ -252,6 +306,25 @@ 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())
{
cloud_processing.voxel_filter_enabled = loadParam(voxel_filter, "enabled", false);
cloud_processing.voxel_leaf_size = loadParam(voxel_filter, "leaf_size_m", 0.05);
}
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"))
{
robot::log_error("Only topics that use point clouds or laser scans are currently supported\n");
@@ -279,6 +352,16 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
> (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());
@@ -301,6 +384,8 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
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});
}
robot::log_info(
@@ -308,7 +393,35 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
"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; one valid free frame\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);
}
}
catch (const YAML::BadFile& e) {
robot::log_error("Cannot open YAML file: %s\n", e.what());
@@ -399,7 +512,11 @@ void ObstacleLayer::handleImpl(const void* data,
topic == callback_depth_infos_[i].topic)
{
// robot::log_error_throttle(1.0,"TEST");
depthImageCallback(depth_camera_data_ptr, buffer);
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);
}
}
}
@@ -448,7 +565,11 @@ void ObstacleLayer::handleImpl(const void* data,
{
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);
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
// {
@@ -744,6 +865,10 @@ bool ObstacleLayer::getFrustumClearingObservations(std::vector<DepthCameraObserv
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;
@@ -754,6 +879,18 @@ bool ObstacleLayer::getFrustumClearingObservations(std::vector<DepthCameraObserv
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,6 +36,7 @@
* 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>
@@ -45,6 +46,7 @@
#include <cmath>
#include <cstdint>
#include <cstring>
#include <array>
#define VOXEL_BITS 16
@@ -71,6 +73,18 @@ 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
@@ -126,6 +140,16 @@ 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_);
}
this->matchSize();
}
catch (const YAML::BadFile& e) {
@@ -159,6 +183,7 @@ void VoxelLayer::reset()
void VoxelLayer::resetMaps()
{
resetPairedDepth();
Costmap2D::resetMaps();
robot_voxel_grid_.reset();
}
@@ -170,6 +195,13 @@ 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;
@@ -196,10 +228,17 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
raytraceFreespace(clearing_observations[i], min_x, min_y, max_x, max_y);
}
// 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)
{
const Observation& obs = *it;
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);
}
void VoxelLayer::markObservation(const Observation& obs, double* min_x, double* min_y,
double* max_x, double* max_y)
{
const robot_sensor_msgs::PointCloud2& cloud = *(obs.cloud_);
@@ -245,8 +284,96 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
touch(double(*iter_x), double(*iter_y), min_x, min_y, max_x, max_y);
}
}
}
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.
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;
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_);
const auto 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);
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);
}
markObservation(observations.front(), min_x, min_y, max_x, max_y);
source->pairer.applied(pair.stamp);
++visibility_counts_.frames;
}
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 (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));
}
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)
@@ -606,7 +733,13 @@ bool VoxelLayer::raytraceDepthFrustum(const DepthCameraObservation& observation,
tf3::TransformStampedMsg tfm;
try
{
tfm = tf_->lookupTransform(global_frame_, depth_frame, tf3::Time());
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)
@@ -977,8 +1110,10 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
cell_size_x, cell_size_x, cell_size_y);
}
// we'll reset our maps to unknown space if appropriate
resetMaps();
// 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();
// update the origin with the appropriate world coordinates
origin_x_ = new_grid_ox;

View File

@@ -414,6 +414,9 @@ 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;
@@ -439,6 +442,14 @@ 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);
@@ -451,6 +462,12 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
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"})
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);
}

167
src/depth_visibility.cpp Normal file
View File

@@ -0,0 +1,167 @@
#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;
double measured_z;
const auto* pixel = image.data.data() + static_cast<size_t>(v) * image.step + u * bytes_per_pixel_;
if (bytes_per_pixel_ == 2) { uint16_t z; std::memcpy(&z, pixel, 2); measured_z = z * .001; }
else { float z; std::memcpy(&z, pixel, 4); measured_z = z; }
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{};
}
} // namespace robot_costmap_2d

View File

@@ -41,12 +41,41 @@
#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,
@@ -143,6 +172,43 @@ 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;
@@ -150,6 +216,13 @@ void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
// 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
@@ -160,14 +233,16 @@ void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
local_origin.point.y = 0;
local_origin.point.z = 0;
// tf3_buffer_.transform(local_origin, global_origin, global_frame_);
const tf3::TransformStampedMsg cloud_transform = tf3_buffer_.lookupTransform(
global_frame_, cloud.header.frame_id, tf3::Time());
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);
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, tf3::Time()));
tf3_buffer_.lookupTransform(global_frame_, origin_frame, query_time));
tf3::convert(global_origin.point, observation.origin_);
observation.raytrace_range_ = raytrace_range_;
@@ -182,11 +257,24 @@ void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
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_z)
for (std::size_t read_index = 0; read_index < cloud_size;
++read_index, ++iter_x, ++iter_y, ++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;
@@ -204,12 +292,36 @@ void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
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("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;
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;
}
if (observation_keep_time_ == robot::Duration(0.0) && !observation_list_.empty())
@@ -227,6 +339,7 @@ void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
// we'll also remove any stale observations from the list
purgeStaleObservations();
return true;
}
void ObservationBuffer::bufferDepthCamera(const robot_sensor_msgs::DepthCameraData& depth_camera_data)

View File

@@ -0,0 +1,263 @@
#include <robot_costmap_2d/observation_buffer.h>
#include <robot_costmap_2d/voxel_layer.h>
#include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <gtest/gtest.h>
#include <array>
#include <limits>
#include <filesystem>
#include <cstdlib>
namespace
{
using robot_costmap_2d::CloudProcessingConfig;
using robot_costmap_2d::Observation;
using robot_costmap_2d::ObservationBuffer;
using Points = std::vector<std::array<float, 3>>;
robot_sensor_msgs::PointCloud2 cloud(const Points &points)
{
robot_sensor_msgs::PointCloud2 out;
out.height = 1;
out.header.frame_id = "camera";
out.header.stamp = robot::Time(10, 123456789);
out.header.seq = 9;
robot_sensor_msgs::PointCloud2Modifier m(out);
m.setPointCloud2FieldsByString(1, "xyz");
m.resize(points.size());
robot_sensor_msgs::PointCloud2Iterator<float> x(out, "x"), y(out, "y"), z(out, "z");
for (const auto &p : points)
{
*x = p[0]; *y = p[1]; *z = p[2];
++x; ++y; ++z;
}
return out;
}
void transform(tf3::BufferCore &tf, const std::string &child, double x, double z,
uint32_t sec = 10, bool fixed = true)
{
tf3::TransformStampedMsg t;
t.header.frame_id = "odom";
t.header.stamp = tf3::Time(sec, 123456789);
t.child_frame_id = child;
t.transform.translation.x = x;
t.transform.translation.z = z;
ASSERT_TRUE(tf.setTransform(t, "test", fixed));
}
CloudProcessingConfig config(bool voxel = true)
{
CloudProcessingConfig c;
c.transform_at_stamp = true;
c.voxel_filter_enabled = voxel;
return c;
}
Points output(ObservationBuffer &buffer, Observation *observation = nullptr)
{
std::vector<Observation> observations;
buffer.getObservations(observations);
if (observations.empty()) return {};
if (observation) *observation = observations.front();
const auto &c = *observations.front().cloud_;
Points points;
robot_sensor_msgs::PointCloud2ConstIterator<float> x(c, "x"), y(c, "y"), z(c, "z");
for (size_t i = 0; i < c.width * c.height; ++i, ++x, ++y, ++z)
points.push_back({*x, *y, *z});
return points;
}
TEST(DepthBuffer, HeightGatePrecedesCentroidAndKeepsExactHeader)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0.04);
ObservationBuffer b("depth", 0, 0, 0.05, 1, 2.5, 3, tf, "odom", "", 0.2);
b.setCloudProcessingConfig(config());
// Two floor points + a 6 cm obstacle share a camera-frame leaf before TF.
// Their premature centroid would be below the 5 cm height threshold.
ASSERT_TRUE(b.tryBufferCloud(cloud({{0.011f, 0.011f, 0.001f},
{0.013f, 0.011f, 0.001f},
{0.019f, 0.011f, 0.020f}})));
Observation obs;
const auto pts = output(b, &obs);
ASSERT_EQ(pts.size(), 1u);
EXPECT_NEAR(pts[0][2], 0.06, 1e-6);
EXPECT_EQ(obs.cloud_->header.frame_id, "odom");
EXPECT_EQ(obs.cloud_->header.stamp.nsec, 123456789u);
EXPECT_EQ(obs.cloud_->header.seq, 9u);
EXPECT_DOUBLE_EQ(obs.origin_.z, 0.04);
}
TEST(DepthBuffer, VoxelCentroidsArePerSourceOptIn)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0);
const auto c = cloud({{.011f, .011f, .11f}, {.019f, .011f, .11f}});
ObservationBuffer filtered("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
filtered.setCloudProcessingConfig(config());
ASSERT_TRUE(filtered.tryBufferCloud(c));
ASSERT_EQ(output(filtered).size(), 1u);
EXPECT_NEAR(output(filtered)[0][0], .015, 1e-6);
ObservationBuffer legacy("other", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
ASSERT_TRUE(legacy.tryBufferCloud(c));
EXPECT_EQ(output(legacy).size(), 2u);
}
TEST(DepthBuffer, UsesMeasurementTransformForCloudAndDifferentOriginFrame)
{
tf3::BufferCore tf;
transform(tf, "camera", 1, 0, 10, false);
transform(tf, "camera", 4, 0, 11, false);
transform(tf, "sensor_origin", .5, 0, 10, false);
transform(tf, "sensor_origin", 3.5, 0, 11, false);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "sensor_origin", .2);
b.setCloudProcessingConfig(config(false));
ASSERT_TRUE(b.tryBufferCloud(cloud({{0, 0, .1f}})));
Observation obs;
ASSERT_EQ(output(b, &obs).size(), 1u);
EXPECT_NEAR(output(b)[0][0], 1, 1e-6);
EXPECT_DOUBLE_EQ(obs.origin_.x, .5);
}
TEST(DepthBuffer, EmptyCloudIsValidAndMissingTfDoesNotReplaceIt)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0, 10, false);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
b.setCloudProcessingConfig(config());
ASSERT_TRUE(b.tryBufferCloud(cloud({})));
auto late = cloud({{0, 0, .1f}});
late.header.stamp.sec = 20;
EXPECT_FALSE(b.tryBufferCloud(late));
std::vector<Observation> obs;
b.getObservations(obs);
ASSERT_EQ(obs.size(), 1u);
EXPECT_EQ(obs[0].cloud_->header.stamp.sec, 10u);
EXPECT_EQ(obs[0].cloud_->width, 0u);
EXPECT_FALSE(obs[0].cloud_->fields.empty());
}
TEST(DepthBuffer, FiniteHeightAndRangeGatesPrecedePcl)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
b.setCloudProcessingConfig(config(false));
const float nan = std::numeric_limits<float>::quiet_NaN();
ASSERT_TRUE(b.tryBufferCloud(cloud({{nan, 0, .1f}, {0, 0, nan},
{3, 0, .1f}, {0, 0, .049f},
{.1f, 0, .05f}, {.2f, 0, 1.f}, {.3f, 0, 1.01f}})));
EXPECT_EQ(output(b).size(), 2u);
}
TEST(DepthBuffer, RejectsZeroStampAndInvalidFilterConfig)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
b.setCloudProcessingConfig(config());
auto c = cloud({}); c.header.stamp = robot::Time();
EXPECT_FALSE(b.tryBufferCloud(c));
auto bad = config();
for (double leaf : {0., -1., std::numeric_limits<double>::infinity()})
{
bad.voxel_leaf_size = leaf;
EXPECT_THROW(b.setCloudProcessingConfig(bad), std::invalid_argument);
}
bad = config(); bad.transform_at_stamp = false;
EXPECT_THROW(b.setCloudProcessingConfig(bad), std::invalid_argument);
}
TEST(DepthBuffer, RejectsMalformedXyzFieldsBeforeReadingOrTransforming)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
b.setCloudProcessingConfig(config());
auto c = cloud({{0, 0, .1f}});
c.fields[0].offset = c.point_step;
EXPECT_FALSE(b.tryBufferCloud(c));
c = cloud({}); c.fields.pop_back();
EXPECT_FALSE(b.tryBufferCloud(c));
c = cloud({}); c.is_bigendian = true;
EXPECT_FALSE(b.tryBufferCloud(c));
}
class InspectVoxelLayer : public robot_costmap_2d::VoxelLayer
{
public:
using robot_costmap_2d::ObstacleLayer::getMarkingObservations;
size_t pairedSources() const { return paired_depth_sources_.size(); }
};
TEST(DepthBuffer, RuntimeYamlActuallyEnablesTimestampAndPclOnDepthSource)
{
const auto runtime = std::filesystem::path(ROBOT_COSTMAP_2D_DIR)
.parent_path().parent_path().parent_path() / "config/runtime";
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", runtime.c_str(), 1), 0);
tf3::BufferCore tf;
transform(tf, "camera", 1, 0, 10, false);
transform(tf, "camera", 4, 0, 11, false);
transform(tf, "base_link", 0, 0);
tf3::TransformStampedMsg map_odom;
map_odom.header.frame_id = "map";
map_odom.child_frame_id = "odom";
ASSERT_TRUE(tf.setTransform(map_odom, "test", true));
// Run the real costmap factory so copyParentParameters(), not test-only
// manual parameter injection, forwards common source options to this layer.
// Select the camera observation profile in memory; the default runtime may
// intentionally use f_scan. No config file or ROS parameter server is written.
robot::NodeHandle root("~");
root.setParam("obstacles/observation_sources", std::string("pc_marking"));
root.setParam("local_costmap/library_path", std::string(DEPTH_MARKING_TEST_PLUGIN_PATH));
robot_costmap_2d::Costmap2DROBOT configured("local_costmap", tf);
configured.pause();
robot::NodeHandle settings("local_costmap/obstacles/pc_marking");
bool stamp_tf = false, pcl_enabled = false;
ASSERT_TRUE(settings.getParam("cloud_transform_at_stamp", stamp_tf));
ASSERT_TRUE(settings.getParam("marking_voxel_filter/enabled", pcl_enabled));
EXPECT_TRUE(stamp_tf);
EXPECT_TRUE(pcl_enabled);
robot_costmap_2d::LayeredCostmap parent("odom", true, false);
parent.getCostmap()->resizeMap(40, 40, .05, -1, -1);
InspectVoxelLayer layer;
ASSERT_NO_THROW(layer.initialize(&parent, "local_costmap/obstacles", &tf));
ASSERT_TRUE(layer.isEnabled());
layer.dataCallBack(cloud({{.011f, .011f, .11f}, {.019f, .011f, .11f}}),
"/camera/depth/points_proc");
std::vector<Observation> observations;
EXPECT_TRUE(layer.getMarkingObservations(observations));
ASSERT_EQ(observations.size(), 1u);
const auto &c = *observations.front().cloud_;
ASSERT_EQ(c.width, 1u);
robot_sensor_msgs::PointCloud2ConstIterator<float> x(c, "x");
EXPECT_NEAR(*x, 1.015, 1e-6);
EXPECT_EQ(c.header.stamp.nsec, 123456789u);
}
TEST(DepthBuffer, RuntimeFactoryForwardsObservedVolumeModeAndPairsSources)
{
const auto runtime = std::filesystem::path(ROBOT_COSTMAP_2D_DIR)
.parent_path().parent_path().parent_path() / "config/runtime";
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", runtime.c_str(), 1), 0);
tf3::BufferCore tf;
transform(tf, "base_link", 0, 0);
tf3::TransformStampedMsg map_odom;
map_odom.header.frame_id = "map"; map_odom.child_frame_id = "odom";
ASSERT_TRUE(tf.setTransform(map_odom, "test", true));
robot::NodeHandle root("~");
root.setParam("obstacles/observation_sources", std::string("pc_marking pc_clearing"));
root.setParam("local_costmap/library_path", std::string(DEPTH_MARKING_TEST_PLUGIN_PATH));
robot_costmap_2d::Costmap2DROBOT configured("local_costmap", tf);
configured.pause();
robot::NodeHandle settings("local_costmap/obstacles/pc_clearing");
std::string mode;
ASSERT_TRUE(settings.getParam("depth_clearing_mode", mode));
EXPECT_EQ(mode,"observed_volume");
// Instantiate with the factory's scoped parameters, then verify the paired
// owner exists and a marking-only half does not enter legacy observations.
robot_costmap_2d::LayeredCostmap parent("odom", true, false);
parent.getCostmap()->resizeMap(40,40,.05,-1,-1);
InspectVoxelLayer layer;
ASSERT_NO_THROW(layer.initialize(&parent,"local_costmap/obstacles",&tf));
ASSERT_EQ(layer.pairedSources(),1u);
layer.dataCallBack(cloud({{.1f,0,.1f}}),"/camera/depth/points_proc");
std::vector<Observation> observations;
EXPECT_TRUE(layer.getMarkingObservations(observations));
EXPECT_TRUE(observations.empty());
}
} // namespace
int main(int argc, char **argv)
{
robot::Time::init();
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,210 @@
#include <robot_costmap_2d/depth_visibility.h>
#include <robot_costmap_2d/depth_frame_pairer.h>
#include <robot_costmap_2d/voxel_layer.h>
#include <robot_costmap_2d/inflation_layer.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <boost/make_shared.hpp>
#include <gtest/gtest.h>
#include <filesystem>
#include <cstring>
#include <thread>
using namespace robot_costmap_2d;
namespace {
robot_sensor_msgs::DepthCameraData::Ptr depth(double meters, robot::Time stamp = robot::Time(100,0)) {
auto d = boost::make_shared<robot_sensor_msgs::DepthCameraData>();
d->header.stamp=stamp; d->header.frame_id="camera";
d->depth.header=d->header; d->camera_info.header=d->header;
d->depth.width=d->camera_info.width=200; d->depth.height=d->camera_info.height=160;
d->depth.step=400; d->depth.encoding="16UC1"; d->depth.data.resize(64000);
uint16_t value=static_cast<uint16_t>(meters*1000);
for(size_t i=0;i<d->depth.data.size();i+=2) std::memcpy(&d->depth.data[i], &value, 2);
d->camera_info.K={100,0,100,0,100,80,0,0,1};
d->camera_info.P={100,0,100,0,0,100,80,0,0,0,1,0};
return d;
}
robot_sensor_msgs::PointCloud2 cloud(robot::Time stamp, bool point=true) {
robot_sensor_msgs::PointCloud2 c; c.header.stamp=stamp; c.header.frame_id="camera"; c.height=1;
robot_sensor_msgs::PointCloud2Modifier m(c); m.setPointCloud2FieldsByString(1,"xyz"); m.resize(point?1:0);
if(point) { robot_sensor_msgs::PointCloud2Iterator<float> x(c,"x"), y(c,"y"), z(c,"z");
*x=-.01;*y=.11;*z=.62; }
return c;
}
tf3::TransformStampedMsg pose(robot::Time stamp, double yaw=0) {
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(stamp.sec,stamp.nsec);
Eigen::Matrix3d optical; optical << 0,0,1, -1,0,0, 0,-1,0;
Eigen::Quaterniond q(Eigen::AngleAxisd(yaw,Eigen::Vector3d::UnitZ())*optical);
p.transform.rotation.x=q.x();p.transform.rotation.y=q.y();
p.transform.rotation.z=q.z();p.transform.rotation.w=q.w();p.transform.translation.z=.19;
return p;
}
TEST(DepthVisibility, FullRegionFreeInvalidOccludedAndOutsideView) {
DepthVisibilityChecker c; DepthFrustumConfig cfg;
auto d=depth(2);
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;
Eigen::Vector3d lo(-.02,-.02,1),hi(.02,.02,1.05);
ASSERT_TRUE(c.prepare(d,p,0,3,cfg));
EXPECT_EQ(c.classify(lo,hi).state,DepthVisibility::Free);
uint16_t zero=0;std::memcpy(&d->depth.data[80*400+100*2],&zero,2);
ASSERT_TRUE(c.prepare(d,p,0,3,cfg));EXPECT_EQ(c.classify(lo,hi).state,DepthVisibility::Unknown);
d=depth(.8);ASSERT_TRUE(c.prepare(d,p,0,3,cfg));
EXPECT_EQ(c.classify(lo,hi).state,DepthVisibility::Surface);
d=depth(2);ASSERT_TRUE(c.prepare(d,p,0,3,cfg));
EXPECT_EQ(c.classify(Eigen::Vector3d(1,-.02,1),Eigen::Vector3d(1.05,.02,1.05)).state,DepthVisibility::Unknown);
EXPECT_EQ(c.classify(Eigen::Vector3d(-.02,-.02,.05),hi).state,DepthVisibility::Unknown);
EXPECT_EQ(c.classify(Eigen::Vector3d(1e30,-.02,1),Eigen::Vector3d(2e30,.02,1.05)).state,DepthVisibility::Unknown);
}
TEST(DepthVisibility, InvalidPixelAtProjectedEdgeAlsoBlocksClear) {
auto d=depth(2); DepthVisibilityChecker c;DepthFrustumConfig cfg;
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;
uint16_t zero=0;std::memcpy(&d->depth.data[80*400+97*2],&zero,2);
ASSERT_TRUE(c.prepare(d,p,0,3,cfg));
EXPECT_EQ(c.classify(Eigen::Vector3d(-.02,-.02,1),Eigen::Vector3d(.02,.02,1.05)).state,DepthVisibility::Unknown);
}
TEST(DepthVisibility, RejectsWrongStampModelAndMalformedImage) {
auto d=depth(2);DepthVisibilityChecker c;DepthFrustumConfig cfg;
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(101,0);p.transform.rotation.w=1;
EXPECT_FALSE(c.prepare(d,p,0,3,cfg));p.header.stamp=tf3::Time(100,0);
d->camera_info.P[0]=90;EXPECT_FALSE(c.prepare(d,p,0,3,cfg));
d=depth(2);d->depth.data.pop_back();EXPECT_FALSE(c.prepare(d,p,0,3,cfg));
d=depth(2);d->depth.is_bigendian=true;EXPECT_FALSE(c.prepare(d,p,0,3,cfg));
}
TEST(DepthPairer, MissingHalfExactPairAndDeduplication) {
robot::Time::setNow(robot::Time(100,0));DepthFrustumConfig cfg;DepthFramePairer p(cfg,.5);
auto c=cloud(robot::Time(100,0));p.addCloud(c);DepthFramePairer::Candidate next;
EXPECT_FALSE(p.next(next));p.addDepth(depth(2));ASSERT_TRUE(p.next(next));
EXPECT_EQ(next.stamp,c.header.stamp.toNSec());p.applied(next.stamp);
p.addCloud(c);p.addDepth(depth(2));EXPECT_FALSE(p.next(next));
EXPECT_EQ(p.counts().applied,1u);EXPECT_EQ(p.counts().duplicate,2u);
}
TEST(DepthPairer, NewerAppliedFrameCannotBeResurrectedByDelayedOlderCloud) {
robot::Time::setNow(robot::Time(100,0));DepthFrustumConfig cfg;DepthFramePairer p(cfg,.5);
p.addCloud(cloud(robot::Time(100,0)));robot::Time::setNow(robot::Time(100,100000000));
p.addCloud(cloud(robot::Time(100,100000000)));p.addDepth(depth(2,robot::Time(100,100000000)));
DepthFramePairer::Candidate n;ASSERT_TRUE(p.next(n));p.applied(n.stamp);
p.addDepth(depth(2));EXPECT_FALSE(p.next(n));p.reset();
p.addCloud(cloud(robot::Time(100,0)));p.addDepth(depth(2));EXPECT_FALSE(p.next(n));
}
TEST(DepthPairer, BoundTimeoutAgeAndClockReset) {
robot::Time::setNow(robot::Time(100,0));DepthFrustumConfig cfg;cfg.pair_queue_size=2;cfg.pair_max_wait_s=.005;
DepthFramePairer p(cfg,.5);
for(int i=0;i<3;++i) {robot::Time::setNow(robot::Time(100,i*10000000));p.addCloud(cloud(robot::Time(100,i*10000000)));}
EXPECT_EQ(p.counts().overflow,1u);std::this_thread::sleep_for(std::chrono::milliseconds(10));
DepthFramePairer::Candidate n;EXPECT_FALSE(p.next(n));EXPECT_EQ(p.counts().expired,2u);
p.addCloud(cloud(robot::Time(99,0)));EXPECT_EQ(p.counts().stale,1u);
p.applied(robot::Time(100,20000000).toNSec());
robot::Time::setNow(robot::Time(10,0));p.addCloud(cloud(robot::Time(10,0)));p.addDepth(depth(2,robot::Time(10,0)));
EXPECT_TRUE(p.next(n));
}
class DepthLayerTest:public ::testing::Test {
protected:
tf3::BufferCore tf;
LayeredCostmap parent{"odom",false,false};
VoxelLayer layer;
uint32_t tick=0;
void SetUp() override {
robot::Time::setNow(robot::Time(100,0));
auto runtime=std::filesystem::path(ROBOT_COSTMAP_2D_DIR).parent_path().parent_path().parent_path()/"config/runtime";
setenv("PNKX_NAV_CORE_CONFIG_DIR",runtime.c_str(),1);
YAML::Node cfg=YAML::Clone(YAML::LoadFile((runtime/"costmap_common_params.yaml").string())["obstacles"]);
cfg["observation_sources"]="pc_marking pc_clearing";cfg["footprint_clearing_enabled"]=false;cfg["enabled"]=true;
robot::NodeHandle nh("~");nh.setParam("depth_test",cfg);
parent.getCostmap()->resizeMap(80,80,.05,-2,-2);layer.initialize(&parent,"depth_test",&tf);
ASSERT_TRUE(layer.isEnabled());
}
robot::Time now() {return robot::Time(100,++tick*10000000);}
void update() {double a=1e9,b=1e9,c=-1e9,d=-1e9;layer.updateBounds(0,0,0,&a,&b,&c,&d);}
void frame(double measurement,bool point=false,double yaw=0,bool hasTf=true,bool hasCloud=true,bool hasDepth=true) {
auto stamp=now();robot::Time::setNow(stamp);
if(hasTf) ASSERT_TRUE(tf.setTransform(pose(stamp,yaw),"test"));
if(hasCloud) layer.dataCallBack(cloud(stamp,point),"/camera/depth/points_proc");
if(hasDepth) {robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(measurement,stamp);
layer.dataCallBack(d,"/camera/depth/data");}
update();
}
unsigned char at(double x=.62,double y=.01) {unsigned a,b;EXPECT_TRUE(layer.worldToMap(x,y,a,b));return layer.getCost(a,b);}
};
TEST_F(DepthLayerTest, RetainsOutsideInvalidOccludedAndClearsOnFirstValidFrame) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,1.57);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(0);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(.4);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE); // one valid frame; no free-frame delay
}
TEST_F(DepthLayerTest, MissingCloudDepthOrTfCannotClearAndNoTtl) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,0,true,false,true);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,0,true,true,false);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,0,false,true,true);EXPECT_EQ(at(),LETHAL_OBSTACLE);
robot::Time::setNow(robot::Time(110,0));update();EXPECT_EQ(at(),LETHAL_OBSTACLE);
EXPECT_FALSE(layer.isCurrent());
}
TEST_F(DepthLayerTest, ClearingFrameDoesNotRepeatOldMarkingCloud) {
frame(.62,true);frame(2);ASSERT_EQ(at(),FREE_SPACE);
layer.dataCallBack(cloud(robot::Time(100,10000000)),"/camera/depth/points_proc");
update();EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthLayerTest, RollingOriginPreservesOverlapAndDropsExitedCells) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
layer.updateOrigin(-1.5,-2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
layer.updateOrigin(1,-2);layer.updateOrigin(-2,-2);EXPECT_NE(at(),LETHAL_OBSTACLE);
}
TEST_F(DepthLayerTest, WaitingPairAppliesWhenItsExactTfArrives) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,0,false);EXPECT_EQ(at(),LETHAL_OBSTACLE);
auto stamp=robot::Time(100,tick*10000000);
ASSERT_TRUE(tf.setTransform(pose(stamp),"late_tf"));
update();EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthLayerTest, PendingFrameSurvivesRollingStorageShift) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
layer.dataCallBack(cloud(stamp,false),"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(2,stamp);layer.dataCallBack(d,"/camera/depth/data");
layer.updateOrigin(-1.5,-2);update();EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthLayerTest, MasterAndInflationRemoveTheClearedObstacle) {
parent.addPlugin(boost::shared_ptr<Layer>(&layer,[](Layer*){}));
auto inflation=boost::make_shared<InflationLayer>();
robot::NodeHandle nh("~");nh.setParam("depth_inflation/inflation_radius",.3);
nh.setParam("depth_inflation/cost_scaling_factor",10.);
parent.addPlugin(inflation);inflation->initialize(&parent,"depth_inflation",&tf);
std::vector<robot_geometry_msgs::Point> footprint(4);
footprint[0].x=footprint[1].x=-.1;footprint[2].x=footprint[3].x=.1;
footprint[0].y=footprint[3].y=-.1;footprint[1].y=footprint[2].y=.1;
parent.setFootprint(footprint);
for(bool occupied : {true,false}) {
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
layer.dataCallBack(cloud(stamp,occupied),"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(occupied?.62:2,stamp);
layer.dataCallBack(d,"/camera/depth/data");parent.updateMap(0,0,0);
unsigned x,y;ASSERT_TRUE(parent.getCostmap()->worldToMap(.62,.01,x,y));
EXPECT_EQ(parent.getCostmap()->getCost(x,y),occupied?LETHAL_OBSTACLE:FREE_SPACE);
ASSERT_TRUE(parent.getCostmap()->worldToMap(.72,.01,x,y));
if(occupied) EXPECT_GT(parent.getCostmap()->getCost(x,y),FREE_SPACE);
else EXPECT_EQ(parent.getCostmap()->getCost(x,y),FREE_SPACE);
}
}
TEST_F(DepthLayerTest, AStillOccludedVoxelKeepsItsColumnLethal) {
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
auto c=cloud(stamp);robot_sensor_msgs::PointCloud2Modifier m(c);m.resize(2);
robot_sensor_msgs::PointCloud2Iterator<float> x(c,"x"),y(c,"y"),z(c,"z");
*x=-.01;*y=.11;*z=.62;++x;++y;++z;*x=-.01;*y=-.29;*z=.62;
layer.dataCallBack(c,"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(.62,stamp);layer.dataCallBack(d,"/camera/depth/data");update();
ASSERT_EQ(at(),LETHAL_OBSTACLE);
stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
auto partial=depth(2,stamp);uint16_t blocked=400;
for(unsigned v=0;v<65;++v) for(unsigned u=0;u<200;++u)
std::memcpy(&partial->depth.data[v*400+u*2],&blocked,2);
layer.dataCallBack(cloud(stamp,false),"/camera/depth/points_proc");
d=partial;layer.dataCallBack(d,"/camera/depth/data");update();EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
}
int main(int argc,char**argv) {robot::Time::init();testing::InitGoogleTest(&argc,argv);return RUN_ALL_TESTS();}