23#include <tf2/LinearMath/Transform.h>
25#include <tracetools/tracetools.h>
26#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
27#include <tf2_sensor_msgs/tf2_sensor_msgs.hpp>
29#include <rmw/qos_profiles.h>
30#include <rclcpp_components/register_node_macro.hpp>
49inline bool pointWithinRange(
50 float x,
float y,
float z,
float x_min,
float x_max,
float y_min,
float y_max,
float z_min,
float z_max) {
51 return x >= x_min && x <= x_max && y >= y_min && y <= y_max && z >= z_min && z <= z_max;
62template <
typename Byte>
63inline Byte* byteOffset(Byte* data, std::size_t offset) {
64 return std::next(data,
static_cast<std::ptrdiff_t
>(offset));
74inline float loadFloat(
const uint8_t* data, std::size_t offset) {
76 std::memcpy(&value, byteOffset(data, offset),
sizeof(value));
81inline float loadObjectVelocity(
const uint8_t* data,
int datatype,
bool bigendian) {
82 const uint16_t endian_check = 1;
84 std::memcpy(&first_byte, &endian_check,
sizeof(first_byte));
85 if (bigendian != (first_byte == 0)) {
86 float value = std::numeric_limits<float>::quiet_NaN();
90 if (datatype == sensor_msgs::msg::PointField::FLOAT32)
return loadFloat(data, 0);
92 std::memcpy(&value, data,
sizeof(value));
93 return std::abs(value) <= std::numeric_limits<float>::max() ?
static_cast<float>(value)
94 : std::numeric_limits<float>::quiet_NaN();
97inline uint32_t loadUint32(
const uint8_t* data, std::size_t offset) {
99 std::memcpy(&value, byteOffset(data, offset),
sizeof(value));
103inline void storeUint32(uint8_t* data, std::size_t offset, uint32_t value) {
104 std::memcpy(byteOffset(data, offset), &value,
sizeof(value));
107inline int64_t stampDeltaInTimeUnits(
const builtin_interfaces::msg::Time& input_stamp,
108 const rclcpp::Time& output_stamp,
109 double time_scale_sec) {
110 return std::llround((rclcpp::Time(input_stamp) - output_stamp).seconds() / time_scale_sec);
113inline uint32_t rebasedTimeOffset(uint32_t input_offset,
114 const builtin_interfaces::msg::Time& input_stamp,
115 const rclcpp::Time& output_stamp,
116 double time_scale_sec) {
117 const int64_t rebased = stampDeltaInTimeUnits(input_stamp, output_stamp, time_scale_sec) +
static_cast<int64_t
>(input_offset);
118 return static_cast<uint32_t
>(std::clamp<int64_t>(rebased, 0, std::numeric_limits<uint32_t>::max()));
122template <
typename Lookup>
123auto lookupWithWallTimeout(
double timeout_sec,
const Lookup& lookup) {
124 const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration<double>(timeout_sec);
128 }
catch (
const tf2::TransformException&) {
129 if (!rclcpp::ok() || std::chrono::steady_clock::now() >= deadline)
throw;
130 std::this_thread::sleep_for(std::chrono::milliseconds(1));
142inline void storeFloat(uint8_t* data, std::size_t offset,
float value) {
143 std::memcpy(byteOffset(data, offset), &value,
sizeof(value));
147inline void copyConvertedFields(
const uint8_t* source,
148 uint8_t* destination,
150 bool source_bigendian,
151 bool destination_bigendian) {
155 source_bigendian, value);
157 if (!std::isfinite(value) && conversion.destination_datatype != sensor_msgs::msg::PointField::FLOAT32 &&
158 conversion.destination_datatype != sensor_msgs::msg::PointField::FLOAT64) {
162 destination_bigendian, value);
173 "Frame into which all input point clouds are transformed before fusion",
177 std::nullopt, std::nullopt, std::nullopt,
180 "Point-cloud topics to fuse",
184 std::nullopt, std::nullopt, std::nullopt,
185 "Must configure between 1 and " + std::to_string(
kMaxInputTopics) +
" topics");
188 "Transport hint for each input topic; unspecified entries use raw",
192 std::nullopt, std::nullopt, std::nullopt,
193 "Length must be zero or match input_topics; unspecified entries default to '" +
196 "Queue depth for approximate-time synchronization",
205 "Queue depth for the fused output publisher",
215 "Fields retained in the fused output; an empty list retains all input fields",
219 std::nullopt, std::nullopt, std::nullopt,
220 "Typical fields include: x, y, z, intensity, t, reflectivity, ring, ambient, range.");
223 "Missing-field overrides as field=value entries; defaults are NaN for floats and zero for integers",
229 "Fused timestamp selection: earliest, latest, mean, or input0",
233 std::nullopt, std::nullopt, std::nullopt,
237 "Runtime-reconfigurable maximum valid point count per input cloud; 0 disables the limit",
244 "0 = disabled; reasonable range is 0 to 10,000,000 points per input cloud");
246 "Runtime-reconfigurable backend selection; true uses CUDA and false uses CPU",
250 std::nullopt, std::nullopt, std::nullopt,
251 "Runtime changes apply between fusion batches.");
253 "Compensate inter-sensor capture skew and motion during each scan",
257 std::nullopt, std::nullopt, std::nullopt,
258 "Requires a connected TF trajectory through motion_compensation.fixed_frame; "
259 "the per-point time field is optional.");
261 "World-fixed TF frame used to compare sensor poses at different times",
265 std::nullopt, std::nullopt, std::nullopt,
266 "Typically map or odom; must connect target_frame and every input frame.");
268 "UINT32 point field containing an offset from the cloud header stamp",
272 std::nullopt, std::nullopt, std::nullopt,
273 "If absent, capture-time compensation remains active but scan deskewing is skipped.");
275 "Seconds represented by one unit of the per-point time field",
282 "Use 1e-9 for Ouster nanosecond offsets.");
284 "Per input_topics entry: true if its driver already deskewed the points to header.stamp. "
285 "Must match the drivers; a wrong entry deskews twice or not at all",
289 std::nullopt, std::nullopt, std::nullopt,
290 "Length must be zero (no input deskewed) or match input_topics. A wrong entry "
291 "silently deskews twice or not at all.");
293 throw std::invalid_argument(
"motion_compensation.deskewed_inputs must match input_topics length");
297 RCLCPP_INFO(this->get_logger(),
"Input '%s' is configured as already deskewed; motion compensation skips its scan deskewing",
302 "Timeout for the first motion-compensation TF failure [s]",
309 "The entire batch falls back to rigid transforms; recovery probes do not wait.");
311 "Advance points to the output timestamp using absolute radial velocity",
316 "Scalar FLOAT32/FLOAT64 absolute radial velocity field in m/s",
321 "Optional velocity field per input_topics entry; empty entries disable correction",
326 "1 for increasing-range-positive velocity, -1 for approaching-positive",
331 "Maximum absolute point extrapolation duration [s]",
338 "Maximum accepted absolute radial speed [m/s]",
345 "Optional UINT32 field containing invalid-velocity flag bits",
350 "Skip object correction when any masked flag is set; zero disables the mask",
359 "Enable XYZ range filtering after transformation into target_frame",
363 std::nullopt, std::nullopt, std::nullopt,
364 "When false, no range filtering is applied.");
366 "Minimum x coordinate in target_frame to keep [m]",
373 "Must be less than range_limits.x_max.");
375 "Maximum x coordinate in target_frame to keep [m]",
382 "Must be greater than range_limits.x_min.");
384 "Minimum y coordinate in target_frame to keep [m]",
391 "Must be less than range_limits.y_max.");
393 "Maximum y coordinate in target_frame to keep [m]",
400 "Must be greater than range_limits.y_min.");
402 "Minimum z coordinate in target_frame to keep [m]",
409 "Must be less than range_limits.z_max.");
411 "Maximum z coordinate in target_frame to keep [m]",
418 "Must be greater than range_limits.z_min.");
421 "Maximum timestamp spread across a synchronized input batch in seconds",
425 0.0, std::nullopt, std::nullopt,
426 "Must be non-negative");
428 "Age penalty used by the approximate-time synchronizer",
435 "Valid range is [0, 100].");
437 "feature_calibration.enable",
439 "Continuously map follower feature distributions to the pooled, unchanged "
440 "leader distribution",
445 "feature_calibration.mode",
447 "Calibration algorithm; currently only continuous distribution mapping is "
452 std::nullopt, std::nullopt, std::nullopt,
453 "Currently supported value: distribution");
455 "feature_calibration.field",
457 "Scalar field to calibrate, typically reflectivity or intensity",
462 "feature_calibration.leading_inputs",
464 "Input topics that form the unchanged reference distribution",
469 "feature_calibration.follower_inputs",
471 "Input topics whose values are remapped to the reference distribution",
476 "feature_calibration.samples_per_cloud",
478 "Maximum rotating stratified samples collected per selected cloud by the "
479 "asynchronous worker",
487 "feature_calibration.window_samples",
489 "Rolling sample capacity maintained separately for each selected input",
497 "feature_calibration.minimum_samples",
499 "Samples required for a leader pool and follower before calibration "
508 "feature_calibration.quantiles",
510 "Number of tail-dense piecewise-linear quantile intervals used by the "
511 "distribution mapping",
519 "feature_calibration.update_interval_sec",
521 "Minimum interval between continuous background mapping updates",
534 cuda_context_ = std::make_unique<cuda::CudaTransformContext>();
536 RCLCPP_INFO(this->get_logger(),
"CUDA acceleration enabled");
538 RCLCPP_INFO(this->get_logger(),
"CUDA context initialized; using CPU backend by parameter");
540 }
catch (
const std::exception& e) {
541 RCLCPP_ERROR(this->get_logger(),
"Failed to initialize CUDA context: %s", e.what());
542 RCLCPP_WARN(this->get_logger(),
"Falling back to CPU-only implementation");
543 cuda_context_.reset();
545 this->set_parameter(rclcpp::Parameter(
"use_cuda",
false));
548 RCLCPP_INFO(this->get_logger(),
"CUDA support not compiled, using CPU-only implementation");
550 this->set_parameter(rclcpp::Parameter(
"use_cuda",
false));
554 setup_timer_ = this->create_wall_timer(std::chrono::milliseconds(1), [
this]() {
566 const std::string& description,
567 const bool add_to_auto_reconfigurable_params,
568 const bool is_required,
569 const bool read_only,
570 const std::optional<double>& from_value,
571 const std::optional<double>& to_value,
572 const std::optional<double>& step_value,
573 const std::string& additional_constraints) {
574 rcl_interfaces::msg::ParameterDescriptor param_desc;
575 param_desc.description = description;
576 param_desc.additional_constraints = additional_constraints;
577 param_desc.read_only = read_only;
579 auto type = rclcpp::ParameterValue(param).get_type();
581 if (from_value.has_value() && to_value.has_value()) {
582 if constexpr (std::is_integral_v<T>) {
583 rcl_interfaces::msg::IntegerRange range;
584 range.set__from_value(
static_cast<T
>(from_value.value())).set__to_value(
static_cast<T
>(to_value.value()));
585 if (step_value.has_value()) range.set__step(
static_cast<T
>(step_value.value()));
586 param_desc.integer_range = {range};
587 }
else if constexpr (std::is_floating_point_v<T>) {
588 rcl_interfaces::msg::FloatingPointRange range;
589 range.set__from_value(
static_cast<T
>(from_value.value())).set__to_value(
static_cast<T
>(to_value.value()));
590 if (step_value.has_value()) range.set__step(
static_cast<T
>(step_value.value()));
591 param_desc.floating_point_range = {range};
593 RCLCPP_WARN(this->get_logger(),
594 "Parameter type of parameter '%s' does not support "
595 "specifying a range",
600 this->declare_parameter(name, type, param_desc);
603 param = this->get_parameter(name).get_value<T>();
604 std::stringstream ss;
605 ss <<
"Loaded parameter '" << name <<
"': ";
608 for (std::size_t i = 0; i < param.size(); ++i) ss << (i > 0 ?
", " :
"") << param[i];
613 RCLCPP_INFO_STREAM(this->get_logger(), ss.str());
614 }
catch (rclcpp::exceptions::ParameterUninitializedException&) {
616 RCLCPP_FATAL_STREAM(this->get_logger(),
"Missing required parameter '" << name <<
"', exiting");
619 std::stringstream ss;
620 ss <<
"Missing parameter '" << name <<
"', using default value: ";
623 for (std::size_t i = 0; i < param.size(); ++i) ss << (i > 0 ?
", " :
"") << param[i];
628 RCLCPP_WARN_STREAM(this->get_logger(), ss.str());
629 this->set_parameters({rclcpp::Parameter(name, rclcpp::ParameterValue(param))});
633 if (add_to_auto_reconfigurable_params) {
634 std::function<void(
const rclcpp::Parameter&)> setter = [¶m](
const rclcpp::Parameter& p) { param = p.get_value<T>(); };
640 std::unique_lock<std::shared_mutex> config_lock(
config_mutex_);
645 std::optional<detail::MissingFieldFillValues> prospective_fills;
648 bool any_range_param =
false;
658 for (
const auto& param : parameters) {
659 const auto& name = param.get_name();
660 if (name ==
"missing_field_fill_values") {
663 }
catch (
const std::exception& error) {
664 rcl_interfaces::msg::SetParametersResult result;
665 result.successful =
false;
666 result.reason = error.what();
669 }
else if (name ==
"object_motion_compensation.enable") {
670 prospective_object_motion = param.as_bool();
671 }
else if (name ==
"motion_compensation.enable") {
672 prospective_ego_motion = param.as_bool();
673 }
else if (name ==
"fixed_points_per_input_cloud") {
674 prospective_fixed_points_per_input_cloud = param.as_int();
675 }
else if (name ==
"use_cuda") {
676 prospective_use_cuda = param.as_bool();
677 }
else if (name ==
"range_limits.x_min") {
678 prospective_x_min = param.as_double();
679 any_range_param =
true;
680 }
else if (name ==
"range_limits.x_max") {
681 prospective_x_max = param.as_double();
682 any_range_param =
true;
683 }
else if (name ==
"range_limits.y_min") {
684 prospective_y_min = param.as_double();
685 any_range_param =
true;
686 }
else if (name ==
"range_limits.y_max") {
687 prospective_y_max = param.as_double();
688 any_range_param =
true;
689 }
else if (name ==
"range_limits.z_min") {
690 prospective_z_min = param.as_double();
691 any_range_param =
true;
692 }
else if (name ==
"range_limits.z_max") {
693 prospective_z_max = param.as_double();
694 any_range_param =
true;
698 if (prospective_object_motion && !prospective_ego_motion) {
699 rcl_interfaces::msg::SetParametersResult result;
700 result.successful =
false;
701 result.reason =
"object_motion_compensation.enable requires motion_compensation.enable";
707 rcl_interfaces::msg::SetParametersResult result;
708 result.successful =
false;
711 RCLCPP_ERROR(this->get_logger(),
"Rejecting parameter update: %s", result.reason.c_str());
715 if (prospective_use_cuda) {
717 if (!cuda_context_) {
718 rcl_interfaces::msg::SetParametersResult result;
719 result.successful =
false;
721 "CUDA backend is unavailable because CUDA context "
722 "initialization failed";
723 RCLCPP_ERROR(this->get_logger(),
"Rejecting parameter update: %s", result.reason.c_str());
727 rcl_interfaces::msg::SetParametersResult result;
728 result.successful =
false;
729 result.reason =
"CUDA backend is unavailable because CUDA support was not compiled";
730 RCLCPP_ERROR(this->get_logger(),
"Rejecting parameter update: %s", result.reason.c_str());
735 if (any_range_param) {
736 rcl_interfaces::msg::SetParametersResult result;
738 if (prospective_x_min >= prospective_x_max) {
739 reason +=
"range_limits.x_min (" + std::to_string(prospective_x_min) +
") must be less than range_limits.x_max (" +
740 std::to_string(prospective_x_max) +
"). ";
742 if (prospective_y_min >= prospective_y_max) {
743 reason +=
"range_limits.y_min (" + std::to_string(prospective_y_min) +
") must be less than range_limits.y_max (" +
744 std::to_string(prospective_y_max) +
"). ";
746 if (prospective_z_min >= prospective_z_max) {
747 reason +=
"range_limits.z_min (" + std::to_string(prospective_z_min) +
") must be less than range_limits.z_max (" +
748 std::to_string(prospective_z_max) +
"). ";
750 if (!reason.empty()) {
751 result.successful =
false;
752 result.reason = reason;
753 RCLCPP_ERROR(this->get_logger(),
"Rejecting range_limits parameter update: %s", reason.c_str());
759 const bool previous_use_cuda =
use_cuda_;
760 for (
const auto& param : parameters) {
762 if (param.get_name() == std::get<0>(auto_reconfigurable_param)) {
763 std::get<1>(auto_reconfigurable_param)(param);
764 RCLCPP_INFO(this->get_logger(),
"Reconfigured parameter '%s' to: %s", param.get_name().c_str(),
765 param.value_to_string().c_str());
772 RCLCPP_INFO(this->get_logger(),
"Fusion backend switched to %s",
use_cuda_ ?
"CUDA" :
"CPU");
775 rcl_interfaces::msg::SetParametersResult result;
776 result.successful =
true;
783template <std::
size_t N>
788 using Policy = message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2>;
793 using Policy = message_filters::sync_policies::
794 ApproximateTime<sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2>;
799 using Policy = message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::PointCloud2,
800 sensor_msgs::msg::PointCloud2,
801 sensor_msgs::msg::PointCloud2,
802 sensor_msgs::msg::PointCloud2>;
807 using Policy = message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::PointCloud2,
808 sensor_msgs::msg::PointCloud2,
809 sensor_msgs::msg::PointCloud2,
810 sensor_msgs::msg::PointCloud2,
811 sensor_msgs::msg::PointCloud2>;
816 using Policy = message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::PointCloud2,
817 sensor_msgs::msg::PointCloud2,
818 sensor_msgs::msg::PointCloud2,
819 sensor_msgs::msg::PointCloud2,
820 sensor_msgs::msg::PointCloud2,
821 sensor_msgs::msg::PointCloud2>;
826 using Policy = message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::PointCloud2,
827 sensor_msgs::msg::PointCloud2,
828 sensor_msgs::msg::PointCloud2,
829 sensor_msgs::msg::PointCloud2,
830 sensor_msgs::msg::PointCloud2,
831 sensor_msgs::msg::PointCloud2,
832 sensor_msgs::msg::PointCloud2>;
837 using Policy = message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::PointCloud2,
838 sensor_msgs::msg::PointCloud2,
839 sensor_msgs::msg::PointCloud2,
840 sensor_msgs::msg::PointCloud2,
841 sensor_msgs::msg::PointCloud2,
842 sensor_msgs::msg::PointCloud2,
843 sensor_msgs::msg::PointCloud2,
844 sensor_msgs::msg::PointCloud2>;
849 using Policy = message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::PointCloud2,
850 sensor_msgs::msg::PointCloud2,
851 sensor_msgs::msg::PointCloud2,
852 sensor_msgs::msg::PointCloud2,
853 sensor_msgs::msg::PointCloud2,
854 sensor_msgs::msg::PointCloud2,
855 sensor_msgs::msg::PointCloud2,
856 sensor_msgs::msg::PointCloud2,
857 sensor_msgs::msg::PointCloud2>;
860template <std::
size_t N>
863template <std::
size_t N>
864using SyncType = message_filters::Synchronizer<SyncPolicy<N>>;
875template <std::size_t N, std::size_t... Is>
877 const std::vector<std::shared_ptr<point_cloud_transport::SubscriberFilter>>& subs,
878 std::index_sequence<Is...> ) {
880 sync.connectInput(*subs[Is]...);
890template <std::
size_t N>
903 tf_buffer_ = std::make_shared<tf2_ros::Buffer>(this->get_clock());
908 RCLCPP_WARN(this->get_logger(),
909 "'input_transport_hints' length (%zu) does not match "
910 "'input_topics' (%zu). Missing hints default to "
922 const std::string resolved = this->get_node_topics_interface()->resolve_topic_name(configured);
927 auto callback_group = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive);
928 rclcpp::SubscriptionOptions subscription_options;
929 subscription_options.callback_group = callback_group;
931 auto subscriber = std::make_shared<point_cloud_transport::SubscriberFilter>();
936 subscriber->subscribe(this->shared_from_this(), resolved, hint, rmw_qos_profile_sensor_data, subscription_options);
937 RCLCPP_INFO(this->get_logger(),
"Subscribed to '%s' (hint=%s)", subscriber->getTopic().c_str(), hint.c_str());
942 RCLCPP_INFO(this->get_logger(),
"Configured %zu input subscriber callback groups for %zu input topics",
949 cloud_subscribers_.front()->registerCallback([
this](
const PointCloudMsg::ConstSharedPtr msg) {
950 std::vector<PointCloudMsg::ConstSharedPtr> batch;
952 batch.emplace_back(msg);
955 RCLCPP_INFO(this->get_logger(),
"Configured single-input mode for topic '%s'",
984 RCLCPP_FATAL(this->get_logger(),
"Unsupported number of input topics: %zu",
cloud_subscribers_.size());
990 point_cloud_transport::PointCloudTransport pct(this->shared_from_this());
991 std::string point_cloud_topic_name = this->get_node_topics_interface()->resolve_topic_name(
"~/point_cloud");
994 RCLCPP_INFO(this->get_logger(),
"Publishing to '%s'",
cloud_publisher_->getTopic().c_str());
998 std::vector<const void*> link_subs;
999 std::vector<const void*> link_pubs;
1001 auto sub_base = sub_filter->getSubscriber().getSubscription();
1003 link_subs.push_back(
static_cast<const void*
>(sub_base->get_subscription_handle().get()));
1007 std::map<std::string, rclcpp::PublisherBase::SharedPtr> pubs_base =
cloud_publisher_->getPublishers();
1008 for (
const auto& [transport, pub_base] : pubs_base) {
1009 link_pubs.push_back(
static_cast<const void*
>(pub_base->get_publisher_handle().get()));
1012 TRACETOOLS_TRACEPOINT(message_link_partial_sync, link_subs.data(), link_subs.size(), link_pubs.data(), link_pubs.size());
1015template <std::
size_t N>
1017 static_assert(N >= 2 && N <= 9,
"Supported synchronizer size is between 2 and 9");
1023 auto sync = std::make_shared<Sync>(Policy(
static_cast<size_t>(
sync_queue_size_)));
1030 sync->registerCallback([
this](
auto&&... msgs) {
1031 std::vector<PointCloudMsg::ConstSharedPtr> batch;
1032 batch.reserve(
sizeof...(msgs));
1034 auto append = [&batch](
auto&& msg) {
1035 using ArgT = std::decay_t<
decltype(msg)>;
1036 if constexpr (std::is_same_v<ArgT, PointCloudMsg::ConstSharedPtr>) {
1038 batch.emplace_back(std::forward<
decltype(msg)>(msg));
1042 (append(std::forward<
decltype(msgs)>(msgs)), ...);
1043 if (!batch.empty()) {
1046 RCLCPP_WARN(this->get_logger(),
1047 "ApproximateTime synchronizer yielded no "
1048 "valid point clouds; skipping fusion.");
1054 RCLCPP_INFO(this->get_logger(),
1055 "Configured approximate time synchronizer for %zu inputs "
1056 "(queue=%zu, max_dt=%.3f s, age_penalty=%.6f)",
1069 std::shared_lock<std::shared_mutex> config_lock(
config_mutex_);
1071 const auto callback_start = std::chrono::steady_clock::now();
1079 std::size_t cuda_valid_count = 0;
1080 auto processing_start = std::chrono::steady_clock::time_point{};
1081 auto processing_end = std::chrono::steady_clock::time_point{};
1082 PointCloudMsg::UniquePtr cuda_result;
1083 bool used_cuda =
false;
1087 std::lock_guard<std::mutex> cuda_lock(cuda_context_mutex_);
1091 processing_start = std::chrono::steady_clock::now();
1092 cuda_result = fusePointCloudBatchCUDA(msgs, timing, cuda_valid_count);
1093 processing_end = std::chrono::steady_clock::now();
1099 publishFusedCloud(std::move(cuda_result), timing, msgs.size(), cuda_valid_count, callback_start, processing_start,
1100 processing_end,
"cuda_fusion_complete");
1102 RCLCPP_WARN(this->get_logger(),
"CUDA processing failed");
1109 std::size_t valid_count = 0;
1110 const auto cpu_processing_start = std::chrono::steady_clock::now();
1113 if (!fused_point_cloud) {
1114 RCLCPP_WARN(this->get_logger(),
"All points are invalid, skipping fusion");
1118 const auto cpu_processing_end = std::chrono::steady_clock::now();
1119 publishFusedCloud(std::move(fused_point_cloud), timing, msgs.size(), valid_count, callback_start, cpu_processing_start,
1120 cpu_processing_end,
"cpu_fusion_complete");
1128 const auto input0_stamp = rclcpp::Time(msgs.front()->header.stamp);
1129 bool first_stamp =
true;
1130 double max_dt_from_input0_sec = 0.0;
1131 rclcpp::Time earliest_stamp;
1132 rclcpp::Time latest_stamp;
1136 for (
const auto& pc_msg : msgs) {
1138 RCLCPP_WARN(this->get_logger(),
1139 "Received null point cloud pointer in "
1140 "synchronized batch, skipping fusion");
1144 const rclcpp::Time current_stamp(pc_msg->header.stamp);
1146 earliest_stamp = current_stamp;
1147 latest_stamp = current_stamp;
1148 first_stamp =
false;
1150 if (current_stamp < earliest_stamp) earliest_stamp = current_stamp;
1151 if (current_stamp > latest_stamp) latest_stamp = current_stamp;
1154 const double dt_sec = std::fabs((current_stamp - input0_stamp).seconds());
1155 if (dt_sec > max_dt_from_input0_sec) {
1156 max_dt_from_input0_sec = dt_sec;
1173 return timing.
earliest_stamp + rclcpp::Duration::from_nanoseconds(delta.nanoseconds() / 2);
1184 const rclcpp::Time& reference_stamp,
1185 int time_field_offset,
1190 const std::size_t total_points =
static_cast<std::size_t
>(msg.width) *
static_cast<std::size_t
>(msg.height);
1191 if (time_field_offset >= 0 && total_points > 0) {
1192 const auto offset =
static_cast<std::size_t
>(time_field_offset);
1193 if (offset +
sizeof(uint32_t) <= msg.point_step && msg.data.size() >= total_points * msg.point_step) {
1194 const auto* data = msg.data.data();
1195 uint32_t max_time_offset = 0;
1196 for (std::size_t idx = 0; idx < total_points; ++idx) {
1197 max_time_offset = std::max(max_time_offset, loadUint32(byteOffset(data, idx * msg.point_step), offset));
1207 const rclcpp::Time scan_start(msg.header.stamp);
1208 const auto scan_duration =
1210 const rclcpp::Time scan_end = scan_start + scan_duration;
1211 auto lookup_at = [&](
const rclcpp::Time& source_stamp) {
1212 return lookupWithWallTimeout(timeout_sec, [&] {
1218 geometry_msgs::msg::TransformStamped start_stamped;
1219 geometry_msgs::msg::TransformStamped end_stamped;
1221 start_stamped = lookup_at(scan_start);
1222 end_stamped = transform.
max_time_offset > 0 ? lookup_at(scan_end) : start_stamped;
1223 }
catch (
const tf2::TransformException& ex) {
1224 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
1225 "Motion compensation unavailable for '%s' through "
1226 "fixed frame '%s': %s; "
1227 "falling back to rigid transforms for this batch",
1232 auto copy_transform = [](
const geometry_msgs::msg::Transform& source, std::array<float, 3>& translation,
1233 std::array<float, 4>& quaternion) {
1234 translation[0] =
static_cast<float>(source.translation.x);
1235 translation[1] =
static_cast<float>(source.translation.y);
1236 translation[2] =
static_cast<float>(source.translation.z);
1237 quaternion[0] =
static_cast<float>(source.rotation.x);
1238 quaternion[1] =
static_cast<float>(source.rotation.y);
1239 quaternion[2] =
static_cast<float>(source.rotation.z);
1240 quaternion[3] =
static_cast<float>(source.rotation.w);
1245 const float quaternion_dot =
1248 if (quaternion_dot < 0.0F) {
1250 component = -component;
1257 const rclcpp::Time& reference_stamp,
1258 const std::vector<int>& time_field_offsets,
1259 std::vector<MotionTransform>& transforms)
const {
1261 transforms.resize(msgs.size());
1266 if (time_field_offsets.size() != msgs.size())
return false;
1270 bool prepared_any =
false;
1271 for (std::size_t i = 0; i < msgs.size(); ++i) {
1272 if (!msgs[i] || time_field_offsets[i] == -2) {
1275 prepared_any =
true;
1279 const bool needs_ray_origin =
1281 const int deskew_time_offset = deskewed && !needs_ray_origin ? -1 : time_field_offsets[i];
1282 if (!
prepareMotionTransform(*msgs[i], reference_stamp, deskew_time_offset, timeout_sec, transforms[i])) {
1290 RCLCPP_INFO(this->get_logger(),
1291 "Motion-compensation TF is available "
1292 "again; resuming compensated fusion");
1294 return prepared_any;
1299 throw std::invalid_argument(
"object_motion_compensation.enable requires motion_compensation.enable");
1302 throw std::invalid_argument(
"object_motion_compensation.velocity_fields must match input_topics length");
1305 throw std::invalid_argument(
"object_motion_compensation.doppler_sign must be 1 or -1");
1309 throw std::invalid_argument(
"object motion limits must be finite and positive");
1312 throw std::invalid_argument(
"object_motion_compensation.invalid_flags_mask requires invalid_flags_field");
1317 std::size_t input_index,
1318 const rclcpp::Time& reference_stamp)
const {
1323 if (name.empty())
return motion;
1325 if (velocity ==
nullptr)
return motion;
1327 (velocity->datatype != sensor_msgs::msg::PointField::FLOAT32 &&
1328 velocity->datatype != sensor_msgs::msg::PointField::FLOAT64)) {
1329 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
1330 "Object motion: '%s' must be a scalar FLOAT32/FLOAT64 measurement; skipping correction", name.c_str());
1335 if (flags ==
nullptr || flags->count != 1 || flags->datatype != sensor_msgs::msg::PointField::UINT32 ||
1337 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
1338 "Object motion: configured invalid_flags_field is unavailable; skipping correction");
1347 motion.
reference_offset_sec =
static_cast<float>((reference_stamp - rclcpp::Time(cloud.header.stamp)).seconds());
1356 if (
fields.empty())
return;
1357 std::ostringstream names;
1358 for (std::size_t i = 0; i <
fields.size(); ++i) {
1359 if (i != 0U) names <<
", ";
1362 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
1363 "Ignoring unused missing_field_fill_values entries for this batch: %s (no selected field needs filling)",
1364 names.str().c_str());
1368 const std::vector<PointCloudMsg::ConstSharedPtr>& msgs)
const {
1372 const auto index =
static_cast<std::size_t
>(it -
input_topics_.begin());
1373 if (index >= msgs.size() || !msgs[index])
continue;
1374 const auto& cloud = *msgs[index];
1376 if (field !=
nullptr && field->count == 1 &&
detail::validField(*field, cloud.point_step) &&
1383 return std::nullopt;
1387 const std::vector<PointCloudMsg::ConstSharedPtr>& msgs,
const FusionTiming& timing, std::size_t& valid_point_count)
const {
1388 valid_point_count = 0;
1389 if (msgs.empty())
return nullptr;
1394 calibration_field ? &*calibration_field :
nullptr);
1396 RCLCPP_ERROR_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
"%s; skipping batch", layout.
fill_error.c_str());
1401 RCLCPP_WARN(this->get_logger(),
"No input cloud has valid FLOAT32 x/y/z fields; skipping batch");
1408 std::ostringstream names;
1410 if (i != 0U) names <<
", ";
1413 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
1414 "Omitting same-name fields with incompatible datatype/count: %s", names.str().c_str());
1417 std::size_t max_capacity = 0;
1418 std::vector<int> time_offsets(msgs.size(), -2);
1419 for (std::size_t i = 0; i < msgs.size(); ++i) {
1420 if (!layout.
inputs[i].valid || !msgs[i]) {
1424 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
1425 "Skipping cloud from '%s': %s (missing_xyz_total=%llu, "
1426 "skipped_total=%llu)",
1427 msgs[i]->header.frame_id.c_str(), layout.
inputs[i].rejection_reason.c_str(),
1433 time_offsets[i] = layout.
inputs[i].time_offset;
1434 std::size_t count =
static_cast<std::size_t
>(msgs[i]->width) * msgs[i]->height;
1435 count = std::min(count, msgs[i]->
point_step == 0 ? std::size_t{0} : msgs[i]->data.size() / msgs[i]->
point_step);
1439 max_capacity += count;
1440 if (!layout.
inputs[i].zero_filled_fields.empty()) {
1442 RCLCPP_DEBUG(this->get_logger(),
"Cloud from '%s' zero-fills %zu output fields (total=%llu)",
1443 msgs[i]->header.frame_id.c_str(), layout.
inputs[i].zero_filled_fields.size(),
1447 if (max_capacity == 0)
return nullptr;
1449 const auto calibration_mappings =
1451 const auto output_calibration_field = std::find_if(layout.
fields.begin(), layout.
fields.end(), [
this](
const auto& field) {
1452 return field.name == feature_calibration_field_ && field.count == 1;
1455 auto output = std::make_unique<PointCloudMsg>();
1457 const rclcpp::Time chosen_stamp =
outputStamp(timing);
1458 output->header.stamp = chosen_stamp;
1462 output->fields = layout.
fields;
1463 output->is_dense = layout.
is_dense;
1464 output->data.resize(max_capacity * layout.
point_step);
1474 std::vector<MotionTransform> motion_transforms;
1476 int output_time_offset = -1;
1477 for (
const auto& field : layout.
fields) {
1480 output_time_offset =
static_cast<int>(field.offset);
1484 uint8_t* destination = output->data.data();
1486 for (std::size_t input_index = 0; input_index < msgs.size(); ++input_index) {
1487 const auto& msg = msgs[input_index];
1488 const auto& input = layout.
inputs[input_index];
1489 if (!msg || !input.
valid || msg->point_step == 0)
continue;
1490 const auto mapping = input_index < calibration_mappings.size() ? calibration_mappings[input_index] :
nullptr;
1492 const bool calibrate = mapping && input_calibration_field !=
nullptr && input_calibration_field->count == 1 &&
1494 output_calibration_field != layout.
fields.end();
1496 const bool apply_transform = batch_motion || msg->header.frame_id !=
target_frame_;
1499 object_motion.end_ray_origin = motion_transforms[input_index].end_ray_origin;
1500 tf2::Vector3 translation(0.0, 0.0, 0.0);
1501 tf2::Matrix3x3 rotation = tf2::Matrix3x3::getIdentity();
1502 if (!batch_motion && apply_transform) {
1504 const auto stamped = lookupWithWallTimeout(0.1, [&] {
1506 rclcpp::Duration::from_seconds(0.0));
1508 tf2::Transform transform;
1509 tf2::fromMsg(stamped.transform, transform);
1510 translation = transform.getOrigin();
1511 rotation = transform.getBasis();
1512 }
catch (
const tf2::TransformException& exception) {
1514 RCLCPP_ERROR(this->get_logger(),
1515 "Cannot transform point cloud from %s to %s: %s "
1516 "(skipped_total=%llu)",
1517 msg->header.frame_id.c_str(),
target_frame_.c_str(), exception.what(),
1523 const std::size_t declared_points =
static_cast<std::size_t
>(msg->width) * msg->height;
1524 const std::size_t total_points = std::min(declared_points, msg->data.size() / msg->point_step);
1528 if (samples == 0)
continue;
1529 const double stride =
static_cast<double>(total_points) /
static_cast<double>(samples);
1531 for (std::size_t sample = 0; sample < samples; ++sample) {
1532 const std::size_t point_index =
1533 samples == total_points ? sample
1534 : std::min(
static_cast<std::size_t
>(
static_cast<double>(sample) * stride), total_points - 1);
1535 const uint8_t* source = byteOffset(msg->data.data(), point_index * msg->point_step);
1536 float x = loadFloat(source, input.
x_offset);
1537 float y = loadFloat(source, input.
y_offset);
1538 float z = loadFloat(source, input.
z_offset);
1539 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
continue;
1541 const uint32_t point_time =
1542 batch_motion && input.
time_offset >= 0 ? loadUint32(source,
static_cast<std::size_t
>(input.
time_offset)) : 0U;
1543 if (object_motion.velocity_offset >= 0 &&
1544 (object_motion.invalid_flags_offset < 0 ||
1545 (loadUint32(source,
static_cast<std::size_t
>(object_motion.invalid_flags_offset)) &
1546 object_motion.invalid_flags_mask) == 0U)) {
1547 const float velocity = loadObjectVelocity(byteOffset(source,
static_cast<std::size_t
>(object_motion.velocity_offset)),
1548 object_motion.velocity_datatype, msg->is_bigendian);
1552 float transformed_x = x;
1553 float transformed_y = y;
1554 float transformed_z = z;
1558 }
else if (apply_transform) {
1559 const tf2::Vector3 transformed = rotation * tf2::Vector3(x, y, z) + translation;
1560 transformed_x =
static_cast<float>(transformed.x());
1561 transformed_y =
static_cast<float>(transformed.y());
1562 transformed_z =
static_cast<float>(transformed.z());
1565 !pointWithinRange(transformed_x, transformed_y, transformed_z, x_min, x_max, y_min, y_max, z_min, z_max)) {
1570 std::memcpy(destination, source, layout.
point_step);
1572 std::memset(destination, 0, layout.
point_step);
1574 for (
const auto& copy : input.
copies) {
1575 std::memcpy(byteOffset(destination, copy.destination_offset), byteOffset(source, copy.source_offset), copy.byte_length);
1577 copyConvertedFields(source, destination, input, msg->is_bigendian, layout.
is_bigendian);
1579 storeFloat(destination, layout.
x_offset, transformed_x);
1580 storeFloat(destination, layout.
y_offset, transformed_y);
1581 storeFloat(destination, layout.
z_offset, transformed_z);
1582 if (output_time_offset >= 0 && input.
time_offset >= 0) {
1583 const uint32_t output_time =
1585 : rebasedTimeOffset(loadUint32(source,
static_cast<std::size_t
>(input.
time_offset)), msg->header.stamp,
1587 storeUint32(destination,
static_cast<std::size_t
>(output_time_offset), output_time);
1591 if (
readScalarField(byteOffset(source, input_calibration_field->offset), input_calibration_field->datatype,
1592 msg->is_bigendian, value)) {
1593 writeScalarField(byteOffset(destination, output_calibration_field->offset), output_calibration_field->datatype,
1594 output->is_bigendian, mapping->apply(value));
1597 destination = byteOffset(destination, layout.
point_step);
1598 ++valid_point_count;
1602 if (valid_point_count == 0)
return nullptr;
1603 output->width = valid_point_count;
1604 output->row_step = output->point_step * output->width;
1605 output->data.resize(valid_point_count * output->point_step);
1611 std::size_t input_count,
1612 std::size_t total_points,
1613 std::chrono::steady_clock::time_point callback_start,
1614 std::chrono::steady_clock::time_point processing_start,
1615 std::chrono::steady_clock::time_point processing_end,
1616 const char* event_name) {
1620 const auto publish_end = std::chrono::steady_clock::now();
1622 const double prep_duration_ms = std::chrono::duration<double, std::milli>(processing_start - callback_start).count();
1623 const double processing_duration_ms = std::chrono::duration<double, std::milli>(processing_end - processing_start).count();
1624 const double publish_duration_ms = std::chrono::duration<double, std::milli>(publish_end - processing_end).count();
1625 const double e2e_duration_ms = prep_duration_ms + processing_duration_ms + publish_duration_ms;
1628 RCLCPP_DEBUG(this->get_logger(),
1629 "%s inputs=%zu points=%zu e2e_ms=%.3f prep_ms=%.3f "
1630 "process_ms=%.3f publish_ms=%.3f batch_dt_ms=%.3f "
1632 event_name, input_count, total_points, e2e_duration_ms, prep_duration_ms, processing_duration_ms,
1637 std::string lowered = mode;
1638 std::transform(lowered.begin(), lowered.end(), lowered.begin(),
1639 [](
unsigned char c) { return static_cast<char>(std::tolower(c)); });
1641 if (lowered ==
"earliest") {
1643 }
else if (lowered ==
"mean" || lowered ==
"mid" || lowered ==
"midpoint") {
1645 }
else if (lowered ==
"input0") {
1647 }
else if (lowered ==
"latest") {
1650 RCLCPP_WARN(this->get_logger(),
"Invalid output_stamp_mode '%s'; defaulting to 'earliest'.", mode.c_str());
1658 std::transform(mode.begin(), mode.end(), mode.begin(),
1659 [](
unsigned char character) { return static_cast<char>(std::tolower(character)); });
1660 if (mode !=
"distribution") {
1661 throw std::invalid_argument(
"feature_calibration.mode must be 'distribution'");
1664 throw std::invalid_argument(
"feature_calibration.field must be included in output_fields");
1666 const auto indices = [
this](
const std::vector<std::string>& topics,
const char* role) {
1667 std::vector<std::size_t> result;
1668 for (
const auto& topic : topics) {
1671 RCLCPP_FATAL(this->get_logger(),
"Feature-calibration %s topic '%s' is not present in input_topics", role, topic.c_str());
1672 throw std::invalid_argument(
"feature calibration topic is not an input");
1674 result.push_back(
static_cast<std::size_t
>(it -
input_topics_.begin()));
1681 throw std::invalid_argument(
"enabled feature calibration requires a field, leading_inputs, and follower_inputs");
1683 for (
const auto follower : followers) {
1684 if (std::find(leaders.begin(), leaders.end(), follower) != leaders.end()) {
1685 throw std::invalid_argument(
"an input cannot be both a feature-calibration leader and follower");
1689 throw std::invalid_argument(
"feature_calibration.minimum_samples must not exceed window_samples");
1693 config.
leaders = std::move(leaders);
1694 config.
followers = std::move(followers);
1702 std::move(config), [
this](
const std::string& message) { RCLCPP_INFO(this->get_logger(),
"%s", message.c_str()); });
1703 RCLCPP_INFO(this->get_logger(),
"Asynchronous distribution calibration enabled for field '%s' (%zu leaders, %zu followers)",
1710 RCLCPP_FATAL(this->get_logger(),
"No input topics configured (parameter 'input_topics'). Exiting");
1714 RCLCPP_FATAL(this->get_logger(),
1715 "Configured with %zu input topics, but only up to %zu inputs "
1725 RCLCPP_ERROR(this->get_logger(),
1726 "range_limits.x_min (%.3f) must be less than "
1727 "range_limits.x_max (%.3f); disabling range filtering",
1732 RCLCPP_ERROR(this->get_logger(),
1733 "range_limits.y_min (%.3f) must be less than "
1734 "range_limits.y_max (%.3f); disabling range filtering",
1739 RCLCPP_ERROR(this->get_logger(),
1740 "range_limits.z_min (%.3f) must be less than "
1741 "range_limits.z_max (%.3f); disabling range filtering",
1752PointCloudFusion::PointCloudMsg::UniquePtr PointCloudFusion::fusePointCloudBatchCUDA(
1753 const std::vector<PointCloudMsg::ConstSharedPtr>& msgs,
const FusionTiming& timing, std::size_t& valid_point_count)
const {
1754 valid_point_count = 0;
1755 if (msgs.empty() || !cuda_context_)
return nullptr;
1757 const rclcpp::Time chosen_stamp =
outputStamp(timing);
1760 const auto processing_fields =
1767 const auto* calibration_descriptor = calibration_field ? &*calibration_field :
nullptr;
1769 processing_fills, calibration_descriptor);
1776 RCLCPP_ERROR_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
"CUDA: %s; skipping batch", error.c_str());
1780 RCLCPP_WARN(this->get_logger(),
"CUDA: no input cloud has valid FLOAT32 x/y/z fields; skipping batch");
1786 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
"CUDA: omitting incompatible same-name field '%s'",
1789 const auto calibration_mappings =
1791 const auto output_calibration_field =
1792 std::find_if(output_layout.
fields.begin(), output_layout.
fields.end(),
1793 [
this](
const auto& field) { return field.name == feature_calibration_field_ && field.count == 1; });
1794 const bool has_active_calibration = output_calibration_field != output_layout.
fields.end() &&
1795 std::any_of(calibration_mappings.begin(), calibration_mappings.end(),
1796 [](
const auto& mapping) { return mapping != nullptr; });
1797 std::vector<ObjectMotion> source_objects(msgs.size());
1798 std::vector<ObjectMotion> packed_objects(msgs.size());
1799 bool private_velocity =
false;
1800 bool private_flags =
false;
1802 for (std::size_t i = 0; i < msgs.size(); ++i) {
1803 if (!msgs[i] || !processing_layout.
inputs[i].valid)
continue;
1805 packed_objects[i] = source_objects[i];
1806 if (source_objects[i].velocity_offset < 0)
continue;
1807 const auto packed_offset = [&](
int offset,
int datatype) {
1808 for (
const auto& source : msgs[i]->
fields) {
1809 if (source.offset !=
static_cast<uint32_t
>(offset) || source.datatype != datatype || source.count != 1)
continue;
1810 for (
const auto& destination : processing_layout.
fields) {
1811 if (source.name == destination.name &&
detail::sameType(source, destination)) {
1812 return static_cast<int>(destination.offset);
1818 packed_objects[i].velocity_offset = packed_offset(source_objects[i].velocity_offset, source_objects[i].velocity_datatype);
1819 private_velocity = private_velocity || packed_objects[i].velocity_offset < 0;
1820 if (source_objects[i].invalid_flags_offset >= 0) {
1821 packed_objects[i].invalid_flags_offset =
1822 packed_offset(source_objects[i].invalid_flags_offset, sensor_msgs::msg::PointField::UINT32);
1823 private_flags = private_flags || packed_objects[i].invalid_flags_offset < 0;
1831 const std::size_t calibration_scratch_offset = processing_layout.
point_step;
1832 const std::size_t velocity_scratch_offset = calibration_scratch_offset + (has_active_calibration ?
sizeof(float) : 0U);
1833 const std::size_t flags_scratch_offset = velocity_scratch_offset + (private_velocity ?
sizeof(float) : 0U);
1834 const std::size_t time_scratch_offset = flags_scratch_offset + (private_flags ?
sizeof(uint32_t) : 0U);
1835 int packed_time_offset = -1;
1836 for (
const auto& field : processing_layout.
fields) {
1839 packed_time_offset =
static_cast<int>(field.offset);
1846 std::any_of(processing_layout.
inputs.begin(), processing_layout.
inputs.end(),
1847 [](
const auto& input) { return input.valid && input.time_offset >= 0; });
1848 if (private_time) packed_time_offset =
static_cast<int>(time_scratch_offset);
1849 const std::size_t processing_point_step = time_scratch_offset + (private_time ?
sizeof(uint32_t) : 0U);
1850 for (std::size_t i = 0; i < msgs.size(); ++i) {
1851 if (source_objects[i].velocity_offset < 0)
continue;
1852 if (packed_objects[i].velocity_offset < 0) {
1853 packed_objects[i].velocity_offset =
static_cast<int>(velocity_scratch_offset);
1854 packed_objects[i].velocity_datatype = sensor_msgs::msg::PointField::FLOAT32;
1856 if (source_objects[i].invalid_flags_offset >= 0 && packed_objects[i].invalid_flags_offset < 0) {
1857 packed_objects[i].invalid_flags_offset =
static_cast<int>(flags_scratch_offset);
1865 std::vector<std::vector<uint8_t>> packed(msgs.size());
1866 std::vector<const uint8_t*> input_data(msgs.size(),
nullptr);
1867 std::vector<std::size_t> point_counts(msgs.size(), 0);
1868 std::vector<int> source_time_offsets(msgs.size(), -2);
1869 std::size_t max_points = 0;
1870 for (std::size_t i = 0; i < msgs.size(); ++i) {
1871 const auto& msg = msgs[i];
1872 const auto& input = processing_layout.
inputs[i];
1873 if (!msg || !input.
valid || msg->point_step == 0) {
1877 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
"CUDA: skipping cloud from '%s': %s",
1883 point_counts[i] = std::min(
static_cast<std::size_t
>(msg->width) * msg->height, msg->data.size() / msg->point_step);
1884 max_points = std::max(max_points, point_counts[i]);
1886 input_data[i] = msg->data.data();
1889 packed[i].assign(point_counts[i] * processing_point_step, 0);
1890 const auto mapping = i < calibration_mappings.size() ? calibration_mappings[i] :
nullptr;
1892 const bool pack_calibration =
1893 calibration_field !=
nullptr && calibration_field->count == 1 &&
detail::validField(*calibration_field, msg->point_step);
1894 const auto object = source_objects[i];
1895 const bool pack_velocity =
object.velocity_offset >= 0 && private_velocity &&
1896 packed_objects[i].velocity_offset ==
static_cast<int>(velocity_scratch_offset);
1897 const bool pack_flags =
object.invalid_flags_offset >= 0 && private_flags &&
1898 packed_objects[i].invalid_flags_offset ==
static_cast<int>(flags_scratch_offset);
1899 const bool pack_time = private_time && input.
time_offset >= 0;
1900 for (std::size_t point = 0; point < point_counts[i]; ++point) {
1901 const uint8_t* source = byteOffset(msg->data.data(), point * msg->point_step);
1902 uint8_t* destination = byteOffset(packed[i].data(), point * processing_point_step);
1904 std::memcpy(destination, source, processing_layout.
point_step);
1907 for (
const auto& copy : input.
copies) {
1908 std::memcpy(byteOffset(destination, copy.destination_offset), byteOffset(source, copy.source_offset), copy.byte_length);
1910 copyConvertedFields(source, destination, input, msg->is_bigendian, processing_layout.
is_bigendian);
1912 if (pack_calibration) {
1914 if (!
readScalarField(source + calibration_field->offset, calibration_field->datatype, msg->is_bigendian, value)) {
1915 value = std::numeric_limits<float>::quiet_NaN();
1918 std::memcpy(byteOffset(destination, calibration_scratch_offset), &value,
sizeof(value));
1920 if (pack_velocity) {
1921 const float velocity = loadObjectVelocity(byteOffset(source,
static_cast<std::size_t
>(
object.velocity_offset)),
1922 object.velocity_datatype, msg->is_bigendian);
1923 std::memcpy(byteOffset(destination, velocity_scratch_offset), &velocity,
sizeof(velocity));
1926 const uint32_t flags = loadUint32(source,
static_cast<std::size_t
>(
object.invalid_flags_offset));
1927 std::memcpy(byteOffset(destination, flags_scratch_offset), &flags,
sizeof(flags));
1930 const uint32_t time = loadUint32(source,
static_cast<std::size_t
>(input.
time_offset));
1931 std::memcpy(byteOffset(destination, time_scratch_offset), &time,
sizeof(time));
1934 input_data[i] = packed[i].data();
1939 if (max_points == 0)
return nullptr;
1941 std::vector<MotionTransform> motion_transforms;
1943 const std::size_t total_capacity = max_points * msgs.size();
1944 int output_time_offset = -1;
1945 std::vector<cuda::CudaFieldCopy> copy_plan;
1946 copy_plan.reserve(output_layout.
fields.size());
1947 for (
const auto& output_field : output_layout.
fields) {
1948 const auto source = std::find_if(
1949 processing_layout.
fields.begin(), processing_layout.
fields.end(),
1950 [&output_field](
const auto& field) { return field.name == output_field.name && detail::sameType(field, output_field); });
1951 if (source == processing_layout.
fields.end()) {
1952 RCLCPP_ERROR(this->get_logger(),
"CUDA: output field '%s' is absent from processing layout", output_field.name.c_str());
1955 copy_plan.push_back({
static_cast<int>(source->offset),
static_cast<int>(output_field.offset),
1958 output_field.count == 1) {
1959 output_time_offset =
static_cast<int>(output_field.offset);
1962 if (!cuda_context_->resetBatch(total_capacity, max_points, processing_point_step, output_layout.
point_step,
1963 static_cast<int>(processing_layout.
x_offset),
static_cast<int>(processing_layout.
y_offset),
1964 static_cast<int>(processing_layout.
z_offset),
static_cast<int>(output_layout.
x_offset),
1965 static_cast<int>(output_layout.
y_offset),
static_cast<int>(output_layout.
z_offset),
1970 RCLCPP_ERROR(this->get_logger(),
"CUDA resetBatch failed for heterogeneous layout");
1974 for (std::size_t i = 0; i < msgs.size(); ++i) {
1975 if (!input_data[i] || point_counts[i] == 0)
continue;
1976 const auto& msg = msgs[i];
1977 const bool apply_transform = batch_motion || msg->header.frame_id !=
target_frame_;
1978 float rotation[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
1979 float translation[3] = {0, 0, 0};
1980 if (!batch_motion && apply_transform) {
1982 const auto stamped = lookupWithWallTimeout(0.1, [&] {
1984 rclcpp::Duration::from_seconds(0.0));
1986 tf2::Transform transform;
1987 tf2::fromMsg(stamped.transform, transform);
1988 const auto basis = transform.getBasis();
1989 const auto origin = transform.getOrigin();
1990 for (
int row = 0; row < 3; ++row) {
1991 for (
int column = 0; column < 3; ++column) rotation[row * 3 + column] = basis[row][column];
1993 translation[0] = origin.x();
1994 translation[1] = origin.y();
1995 translation[2] = origin.z();
1996 }
catch (
const tf2::TransformException& exception) {
1998 RCLCPP_ERROR(this->get_logger(),
"CUDA: cannot transform %s to %s: %s", msg->header.frame_id.c_str(),
2004 const auto& motion = motion_transforms[i];
2005 packed_objects[i].ray_origin_max_time_offset = motion.ray_origin_max_time_offset;
2006 packed_objects[i].end_ray_origin = motion.end_ray_origin;
2007 const int cuda_time_offset = source_time_offsets[i] >= 0 ? packed_time_offset : -1;
2009 const auto mapping = i < calibration_mappings.size() ? calibration_mappings[i] :
nullptr;
2011 const bool calibrate = has_active_calibration && mapping && input_calibration_field !=
nullptr &&
2012 input_calibration_field->count == 1 &&
detail::validField(*input_calibration_field, msg->point_step);
2013 if (!cuda_context_->addCloud(input_data[i], point_counts[i], rotation, translation, apply_transform, i, desired, batch_motion,
2014 cuda_time_offset, motion.max_time_offset, time_rebase_units, motion.start_translation.data(),
2015 motion.end_translation.data(), motion.start_quaternion.data(), motion.end_quaternion.data(),
2016 calibrate ?
static_cast<int>(calibration_scratch_offset) : -1,
2017 calibrate ?
static_cast<int>(output_calibration_field->offset) : -1,
2018 calibrate ?
static_cast<int>(sensor_msgs::msg::PointField::FLOAT32) : 0,
2019 calibrate ?
static_cast<int>(output_calibration_field->datatype) : 0,
2020 calibrate ?
static_cast<int>(mapping->source.size()) : 0,
2021 calibrate ? mapping->source.data() :
nullptr, calibrate ? mapping->target.data() :
nullptr,
2022 batch_motion ? packed_objects[i] : ObjectMotion{})) {
2023 RCLCPP_ERROR(this->get_logger(),
"CUDA addCloud failed for input %zu", i);
2027 auto output = std::make_unique<PointCloudMsg>();
2029 output->header.stamp = chosen_stamp;
2032 output->point_step = output_layout.
point_step;
2033 output->fields = output_layout.
fields;
2034 output->is_dense = output_layout.
is_dense;
2035 if (!cuda_context_->getBatchOutput(output->data, valid_point_count) || valid_point_count == 0)
return nullptr;
2036 output->width = valid_point_count;
2037 output->row_step = output->point_step * output->width;
double object_motion_max_time_offset_sec_
double range_limits_z_min_
static constexpr int32_t kMaxSyncQueueSize
void validateInputTopicsParameter() const
Validate that the configured input topic list is usable.
double object_motion_max_speed_mps_
double max_time_diff_sec_
ROS parameters.
int64_t feature_calibration_minimum_samples_
std::atomic_uint64_t incompatible_field_count_
void warnUnusedFillOverrides(const std::vector< std::string > &fields) const
~PointCloudFusion() override
Stop background workers before destroying node resources.
double range_limits_x_min_
static constexpr int32_t kStepSizeOutputQueueSize
double range_limits_y_max_
static constexpr int32_t kMinSyncQueueSize
static constexpr int32_t kMaxOutputQueueSize
std::atomic_uint64_t skipped_cloud_count_
static constexpr std::size_t kMaxInputTopics
static constexpr const char * kAllowedOutputStampModes
PointCloudMsg::UniquePtr fusePointCloudBatch(const std::vector< PointCloudMsg::ConstSharedPtr > &msgs, const FusionTiming &timing, std::size_t &valid_point_count) const
Fuse a synchronized point-cloud batch using the CPU path.
void validateRangeLimits()
Validate configured XYZ range limits and disable filtering when invalid.
static constexpr double kMinRangeZ
int64_t feature_calibration_quantiles_
double object_motion_doppler_sign_
int64_t fixed_points_per_input_cloud_
std::vector< std::string > output_fields_
void handleSynchronizedPointClouds(const std::vector< sensor_msgs::msg::PointCloud2::ConstSharedPtr > &msgs)
Process synchronized point clouds.
void configureOutputStampMode(const std::string &mode)
Parse and store the configured output timestamp mode.
std::string target_frame_
double motion_compensation_tf_timeout_sec_
ObjectMotion prepareObjectMotion(const PointCloudMsg &cloud, std::size_t input_index, const rclcpp::Time &reference_stamp) const
void validateObjectMotionParameters() const
std::string feature_calibration_field_
void declareAndLoadParameter(const std::string &name, T ¶m, const std::string &description, const bool add_to_auto_reconfigurable_params=true, const bool is_required=false, const bool read_only=false, const std::optional< double > &from_value=std::nullopt, const std::optional< double > &to_value=std::nullopt, const std::optional< double > &step_value=std::nullopt, const std::string &additional_constraints="")
Declares and loads a ROS parameter.
std::vector< bool > motion_compensation_deskewed_inputs_
rclcpp::Time outputStamp(const FusionTiming &timing) const
Select the timestamp used by the fused cloud and motion compensation.
bool range_limits_enable_
std::string feature_calibration_mode_
bool prepareBatchMotionTransforms(const std::vector< PointCloudMsg::ConstSharedPtr > &msgs, const rclcpp::Time &reference_stamp, const std::vector< int > &time_field_offsets, std::vector< MotionTransform > &transforms) const
Preflight motion transforms for an entire synchronized batch.
std::string object_motion_invalid_flags_field_
std::string motion_compensation_fixed_frame_
double range_limits_x_max_
void setup()
Sets up subscribers, publishers, etc. to configure the node.
rclcpp::TimerBase::SharedPtr setup_timer_
Timer to delay setup.
std::vector< std::string > input_topics_
OnSetParametersCallbackHandle::SharedPtr parameters_callback_
Callback handle for dynamic parameter reconfiguration.
std::shared_mutex config_mutex_
static constexpr const char * kDefaultTransportHint
std::string output_stamp_mode_param_
std::unordered_map< std::string, double > missing_field_fills_
static constexpr double kMaxRangeXY
rcl_interfaces::msg::SetParametersResult parametersCallback(const std::vector< rclcpp::Parameter > ¶meters)
Validate and apply dynamic parameter updates.
static constexpr int32_t kMinOutputQueueSize
std::vector< std::string > input_transport_hints_
double motion_compensation_time_scale_sec_
static constexpr int64_t kMaxFixedPointsPerInputCloud
std::unique_ptr< DistributionFeatureCalibrator > feature_calibrator_
void configureFeatureCalibration()
Validate calibration parameters and start the background calibrator.
int64_t feature_calibration_window_samples_
static constexpr int32_t kStepSizeSyncQueueSize
bool object_motion_compensation_enable_
std::shared_ptr< tf2_ros::Buffer > tf_buffer_
TF2 buffer and transform listener.
double range_limits_z_max_
std::shared_ptr< tf2_ros::TransformListener > tf_listener_
int64_t feature_calibration_samples_per_cloud_
static constexpr int64_t kMinFixedPointsPerInputCloud
std::optional< sensor_msgs::msg::PointField > calibrationOutputField(const std::vector< PointCloudMsg::ConstSharedPtr > &msgs) const
int64_t object_motion_invalid_flags_mask_
bool collectTimingInfo(const std::vector< PointCloudMsg::ConstSharedPtr > &msgs, FusionTiming &timing) const
Collect timestamp statistics for synchronized input clouds.
bool feature_calibration_enable_
std::string object_motion_velocity_field_
static constexpr double kMaxRangeZ
std::shared_ptr< void > synchronizer_
bool motion_compensation_enable_
OutputStampMode output_stamp_mode_
double feature_calibration_update_interval_sec_
void publishFusedCloud(PointCloudMsg::UniquePtr cloud, const FusionTiming &timing, std::size_t input_count, std::size_t total_points, std::chrono::steady_clock::time_point callback_start, std::chrono::steady_clock::time_point processing_start, std::chrono::steady_clock::time_point processing_end, const char *event_name)
Publish a fused point cloud and emit tracing/timing diagnostics.
std::atomic_bool motion_tf_available_
static constexpr int64_t kStepSizeFixedPointsPerInputCloud
void setupSynchronizer()
Create the approximate-time synchronizer for a fixed number of input topics.
std::atomic_uint64_t missing_xyz_count_
std::vector< std::string > feature_calibration_leading_inputs_
int64_t output_queue_size_
std::vector< std::tuple< std::string, std::function< void(const rclcpp::Parameter &)> > > auto_reconfigurable_params_
Auto-reconfigurable parameters for dynamic reconfiguration.
std::vector< std::string > missing_field_fill_values_
std::string motion_compensation_time_field_
std::vector< rclcpp::CallbackGroup::SharedPtr > cloud_subscriber_callback_groups_
sensor_msgs::msg::PointCloud2 PointCloudMsg
std::vector< std::string > feature_calibration_follower_inputs_
bool prepareMotionTransform(const PointCloudMsg &msg, const rclcpp::Time &reference_stamp, int time_field_offset, double timeout_sec, MotionTransform &transform) const
Build an interpolated motion transform for one input scan.
std::shared_ptr< point_cloud_transport::Publisher > cloud_publisher_
Publisher.
static constexpr double kMinRangeXY
std::atomic_uint64_t zero_filled_field_count_
std::vector< std::shared_ptr< point_cloud_transport::SubscriberFilter > > cloud_subscribers_
PointCloudFusion(const rclcpp::NodeOptions &options)
Constructor.
std::vector< std::string > object_motion_velocity_fields_
double range_limits_y_min_
bool fieldIsPublished(const std::vector< std::string > &requested_fields, const std::string &name)
void connectInputsImpl(SyncType< N > &sync, const std::vector< std::shared_ptr< point_cloud_transport::SubscriberFilter > > &subs, std::index_sequence< Is... >)
Connect subscriber filters to the synchronizer through an index sequence.
bool validXyzField(const sensor_msgs::msg::PointField *field, uint32_t point_step)
Check whether a field is a valid scalar FLOAT32 XYZ component.
MissingFieldFillValues parseMissingFieldFillValues(const std::vector< std::string > &entries)
typename SyncPolicyTraits< N >::Policy SyncPolicy
bool sameType(const sensor_msgs::msg::PointField &lhs, const sensor_msgs::msg::PointField &rhs)
Check whether two fields have the same name and element type.
std::size_t fieldDatatypeSize(uint8_t datatype)
Return the size in bytes of one PointField datatype element.
message_filters::Synchronizer< SyncPolicy< N > > SyncType
void fillMissingFields(uint8_t *destination, const InputLayout &input)
std::vector< std::string > processingFields(const std::vector< std::string > &requested_fields, const std::string &time_field_name, bool motion_compensation)
BatchLayout buildBatchLayout(const std::vector< sensor_msgs::msg::PointCloud2::ConstSharedPtr > &clouds, const std::vector< std::string > &requested_fields, const std::string &time_field_name, const MissingFieldFillValues &fill_values={}, const sensor_msgs::msg::PointField *calibration_field=nullptr)
Build a common output layout and per-input copy plan for a cloud batch.
bool validField(const sensor_msgs::msg::PointField &field, uint32_t point_step)
Check whether a field descriptor fits within a point record.
const sensor_msgs::msg::PointField * findField(const sensor_msgs::msg::PointCloud2 &cloud, const std::string &name)
Find a field descriptor by name in a point cloud.
void connectInputs(SyncType< N > &sync, const std::vector< std::shared_ptr< point_cloud_transport::SubscriberFilter > > &subs)
Connect all subscriber filters to the synchronizer for N inputs.
constexpr bool is_vector_v
bool compensateObjectMotion(const ObjectMotion &motion, float velocity, uint32_t point_time, float &x, float &y, float &z)
Advance a measured acquisition ray using absolute radial velocity.
bool writeScalarField(uint8_t *data, uint8_t datatype, bool bigendian, float value)
Convert and write a floating-point value to a PointField scalar.
void transformPointInterpolated(const MotionTransform &transform, uint32_t time_offset, float x, float y, float z, float &transformed_x, float &transformed_y, float &transformed_z)
Transform a point using normalized quaternion interpolation.
bool readScalarField(const uint8_t *data, uint8_t datatype, bool bigendian, float &value)
Read a PointField scalar and convert it to floating point.
void retainDeskewedPose(MotionTransform &transform)
std::vector< std::size_t > followers
double update_interval_sec
std::size_t minimum_samples
std::size_t samples_per_cloud
std::size_t window_samples
std::size_t quantile_count
std::vector< std::size_t > leaders
uint32_t ray_origin_max_time_offset
uint32_t invalid_flags_mask
float reference_offset_sec
float max_time_offset_sec
Timing metadata for one synchronized fusion batch.
rclcpp::Time input0_stamp
rclcpp::Time earliest_stamp
double max_dt_from_input0_sec
rclcpp::Time latest_stamp
std::vector< std::string > conflicting_fields
std::vector< std::string > unused_fill_fields
std::vector< sensor_msgs::msg::PointField > fields
std::vector< InputLayout > inputs
message_filters::sync_policies::ApproximateTime< sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2 > Policy
message_filters::sync_policies:: ApproximateTime< sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2 > Policy
message_filters::sync_policies::ApproximateTime< sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2 > Policy
message_filters::sync_policies::ApproximateTime< sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2 > Policy
message_filters::sync_policies::ApproximateTime< sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2 > Policy
message_filters::sync_policies::ApproximateTime< sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2 > Policy
message_filters::sync_policies::ApproximateTime< sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2 > Policy
message_filters::sync_policies::ApproximateTime< sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2 > Policy
std::vector< int > fields