point_cloud_fusion v1.6.0
Loading...
Searching...
No Matches
point_cloud_fusion.cpp
Go to the documentation of this file.
1// Copyright Institute for Automotive Engineering (ika), RWTH Aachen University
2// SPDX-License-Identifier: Apache-2.0
3
4#include <algorithm>
5#include <cctype>
6#include <chrono>
7#include <cmath>
8#include <cstdlib>
9#include <cstring>
10#include <functional>
11#include <iterator>
12#include <limits>
13#include <numeric>
14#include <sstream>
15#include <thread>
16#include <tuple>
17#include <type_traits>
18#include <utility>
19
22
23#include <tf2/LinearMath/Transform.h>
24#include <tf2/time.h>
25#include <tracetools/tracetools.h>
26#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
27#include <tf2_sensor_msgs/tf2_sensor_msgs.hpp>
28
29#include <rmw/qos_profiles.h>
30#include <rclcpp_components/register_node_macro.hpp>
31RCLCPP_COMPONENTS_REGISTER_NODE(point_cloud_fusion::PointCloudFusion)
32
33namespace {
34
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;
52}
53
62template <typename Byte>
63inline Byte* byteOffset(Byte* data, std::size_t offset) {
64 return std::next(data, static_cast<std::ptrdiff_t>(offset));
65}
66
74inline float loadFloat(const uint8_t* data, std::size_t offset) {
75 float value = 0.0F;
76 std::memcpy(&value, byteOffset(data, offset), sizeof(value));
77 return value;
78}
79
81inline float loadObjectVelocity(const uint8_t* data, int datatype, bool bigendian) {
82 const uint16_t endian_check = 1;
83 uint8_t first_byte{};
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();
87 point_cloud_fusion::readScalarField(data, static_cast<uint8_t>(datatype), bigendian, value);
88 return value;
89 }
90 if (datatype == sensor_msgs::msg::PointField::FLOAT32) return loadFloat(data, 0);
91 double value{};
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();
95}
96
97inline uint32_t loadUint32(const uint8_t* data, std::size_t offset) {
98 uint32_t value = 0;
99 std::memcpy(&value, byteOffset(data, offset), sizeof(value));
100 return value;
101}
102
103inline void storeUint32(uint8_t* data, std::size_t offset, uint32_t value) {
104 std::memcpy(byteOffset(data, offset), &value, sizeof(value));
105}
106
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);
111}
112
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()));
119}
120
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);
125 for (;;) {
126 try {
127 return lookup();
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));
131 }
132 }
133}
134
142inline void storeFloat(uint8_t* data, std::size_t offset, float value) {
143 std::memcpy(byteOffset(data, offset), &value, sizeof(value));
144}
145
147inline void copyConvertedFields(const uint8_t* source,
148 uint8_t* destination,
150 bool source_bigendian,
151 bool destination_bigendian) {
152 for (const auto& conversion : input.conversions) {
153 float value = 0.0F;
154 point_cloud_fusion::readScalarField(byteOffset(source, conversion.source_offset), conversion.source_datatype,
155 source_bigendian, value);
156 // Integer fields cannot represent unknown floating measurements.
157 if (!std::isfinite(value) && conversion.destination_datatype != sensor_msgs::msg::PointField::FLOAT32 &&
158 conversion.destination_datatype != sensor_msgs::msg::PointField::FLOAT64) {
159 value = 0.0F;
160 }
161 point_cloud_fusion::writeScalarField(byteOffset(destination, conversion.destination_offset), conversion.destination_datatype,
162 destination_bigendian, value);
163 }
164}
165
166} // namespace
167
168namespace point_cloud_fusion {
169
170// clang-format off
171PointCloudFusion::PointCloudFusion(const rclcpp::NodeOptions& options) : Node("point_cloud_fusion", options) {
172 this->declareAndLoadParameter("target_frame", target_frame_, // name
173 "Frame into which all input point clouds are transformed before fusion", // description
174 false, // add_to_auto_reconfigurable_params
175 true, // is_required
176 true, // read_only
177 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
178 "Must be set."); // additional_constraints
179 this->declareAndLoadParameter("input_topics", input_topics_, // name
180 "Point-cloud topics to fuse", // description
181 false, // add_to_auto_reconfigurable_params
182 true, // is_required
183 true, // read_only
184 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
185 "Must configure between 1 and " + std::to_string(kMaxInputTopics) + " topics");
187 this->declareAndLoadParameter("input_transport_hints", input_transport_hints_, // name
188 "Transport hint for each input topic; unspecified entries use raw", // description
189 false, // add_to_auto_reconfigurable_params
190 false, // is_required
191 true, // read_only
192 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
193 "Length must be zero or match input_topics; unspecified entries default to '" +
194 std::string(kDefaultTransportHint) + "'."); // additional_constraints
195 this->declareAndLoadParameter("sync_queue_size", sync_queue_size_, // name
196 "Queue depth for approximate-time synchronization", // description
197 false, // add_to_auto_reconfigurable_params
198 false, // is_required
199 true, // read_only
200 kMinSyncQueueSize, // from_value
201 kMaxSyncQueueSize, // to_value
202 kStepSizeSyncQueueSize, // step_value
203 std::string("Must be >= ") + std::to_string(kMinSyncQueueSize)); // additional_constraints
204 this->declareAndLoadParameter("output_queue_size", output_queue_size_, // name
205 "Queue depth for the fused output publisher", // description
206 false, // add_to_auto_reconfigurable_params
207 false, // is_required
208 true, // read_only
209 kMinOutputQueueSize, // from_value
210 kMaxOutputQueueSize, // to_value
211 kStepSizeOutputQueueSize, // step_value
212 std::string("Must be >= ") + std::to_string(kMinOutputQueueSize)); // additional_constraints
214 "output_fields", output_fields_, // name
215 "Fields retained in the fused output; an empty list retains all input fields", // description
216 true, // add_to_auto_reconfigurable_params
217 false, // is_required
218 false, // read_only
219 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
220 "Typical fields include: x, y, z, intensity, t, reflectivity, ring, ambient, range."); // additional_constraints
222 "missing_field_fill_values", missing_field_fill_values_, // name
223 "Missing-field overrides as field=value entries; defaults are NaN for floats and zero for integers", // description
224 true, // add_to_auto_reconfigurable_params
225 false, // is_required
226 false); // read_only
228 this->declareAndLoadParameter("output_stamp_mode", output_stamp_mode_param_, // name
229 "Fused timestamp selection: earliest, latest, mean, or input0",
230 false, // add_to_auto_reconfigurable_params
231 false, // is_required
232 true, // read_only
233 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
234 std::string("Allowed values: ") + kAllowedOutputStampModes); // additional_constraints
235 // Allow user to optionally limit the per-cloud point count to a maximum
236 this->declareAndLoadParameter("fixed_points_per_input_cloud", fixed_points_per_input_cloud_,
237 "Runtime-reconfigurable maximum valid point count per input cloud; 0 disables the limit",
238 true, // add_to_auto_reconfigurable_params
239 false, // is_required
240 false, // read_only
241 kMinFixedPointsPerInputCloud, // from_value
244 "0 = disabled; reasonable range is 0 to 10,000,000 points per input cloud");
245 this->declareAndLoadParameter("use_cuda", use_cuda_, // name
246 "Runtime-reconfigurable backend selection; true uses CUDA and false uses CPU",
247 true, // add_to_auto_reconfigurable_params
248 false, // is_required
249 false, // read_only
250 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
251 "Runtime changes apply between fusion batches."); // additional_constraints
252 this->declareAndLoadParameter("motion_compensation.enable", motion_compensation_enable_,
253 "Compensate inter-sensor capture skew and motion during each scan",
254 true, // add_to_auto_reconfigurable_params
255 false, // is_required
256 false, // read_only
257 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
258 "Requires a connected TF trajectory through motion_compensation.fixed_frame; "
259 "the per-point time field is optional.");
260 this->declareAndLoadParameter("motion_compensation.fixed_frame", motion_compensation_fixed_frame_,
261 "World-fixed TF frame used to compare sensor poses at different times",
262 false, // add_to_auto_reconfigurable_params
263 false, // is_required
264 true, // read_only
265 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
266 "Typically map or odom; must connect target_frame and every input frame.");
267 this->declareAndLoadParameter("motion_compensation.time_field", motion_compensation_time_field_,
268 "UINT32 point field containing an offset from the cloud header stamp",
269 false, // add_to_auto_reconfigurable_params
270 false, // is_required
271 true, // read_only
272 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
273 "If absent, capture-time compensation remains active but scan deskewing is skipped.");
274 this->declareAndLoadParameter("motion_compensation.time_scale_sec", motion_compensation_time_scale_sec_,
275 "Seconds represented by one unit of the per-point time field",
276 false, // add_to_auto_reconfigurable_params
277 false, // is_required
278 true, // read_only
279 1.0e-12, // from_value
280 1.0, // to_value
281 std::nullopt, // step_value
282 "Use 1e-9 for Ouster nanosecond offsets."); // additional_constraints
283 this->declareAndLoadParameter("motion_compensation.deskewed_inputs", motion_compensation_deskewed_inputs_,
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",
286 false, // add_to_auto_reconfigurable_params
287 false, // is_required
288 true, // read_only
289 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
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");
294 }
295 for (std::size_t i = 0; i < motion_compensation_deskewed_inputs_.size(); ++i) {
297 RCLCPP_INFO(this->get_logger(), "Input '%s' is configured as already deskewed; motion compensation skips its scan deskewing",
298 input_topics_[i].c_str());
299 }
300 }
301 this->declareAndLoadParameter("motion_compensation.tf_timeout_sec", motion_compensation_tf_timeout_sec_,
302 "Timeout for the first motion-compensation TF failure [s]",
303 false, // add_to_auto_reconfigurable_params
304 false, // is_required
305 true, // read_only
306 0.0, // from_value
307 1.0, // to_value
308 std::nullopt, // step_value
309 "The entire batch falls back to rigid transforms; recovery probes do not wait.");
310 this->declareAndLoadParameter("object_motion_compensation.enable", object_motion_compensation_enable_, // name
311 "Advance points to the output timestamp using absolute radial velocity", // description
312 true, // add_to_auto_reconfigurable_params
313 false, // is_required
314 false); // read_only
315 this->declareAndLoadParameter("object_motion_compensation.velocity_field", object_motion_velocity_field_, // name
316 "Scalar FLOAT32/FLOAT64 absolute radial velocity field in m/s", // description
317 false, // add_to_auto_reconfigurable_params
318 false, // is_required
319 true); // read_only
320 this->declareAndLoadParameter("object_motion_compensation.velocity_fields", object_motion_velocity_fields_, // name
321 "Optional velocity field per input_topics entry; empty entries disable correction", // description
322 false, // add_to_auto_reconfigurable_params
323 false, // is_required
324 true); // read_only
325 this->declareAndLoadParameter("object_motion_compensation.doppler_sign", object_motion_doppler_sign_, // name
326 "1 for increasing-range-positive velocity, -1 for approaching-positive", // description
327 false, // add_to_auto_reconfigurable_params
328 false, // is_required
329 true); // read_only
330 this->declareAndLoadParameter("object_motion_compensation.max_time_offset_sec", object_motion_max_time_offset_sec_, // name
331 "Maximum absolute point extrapolation duration [s]", // description
332 false, // add_to_auto_reconfigurable_params
333 false, // is_required
334 true, // read_only
335 1.0e-6, // from_value
336 10.0); // to_value
337 this->declareAndLoadParameter("object_motion_compensation.max_speed_mps", object_motion_max_speed_mps_, // name
338 "Maximum accepted absolute radial speed [m/s]", // description
339 false, // add_to_auto_reconfigurable_params
340 false, // is_required
341 true, // read_only
342 1.0e-6, // from_value
343 1000.0); // to_value
344 this->declareAndLoadParameter("object_motion_compensation.invalid_flags_field", object_motion_invalid_flags_field_, // name
345 "Optional UINT32 field containing invalid-velocity flag bits", // description
346 false, // add_to_auto_reconfigurable_params
347 false, // is_required
348 true); // read_only
349 this->declareAndLoadParameter("object_motion_compensation.invalid_flags_mask", object_motion_invalid_flags_mask_, // name
350 "Skip object correction when any masked flag is set; zero disables the mask", // description
351 false, // add_to_auto_reconfigurable_params
352 false, // is_required
353 true, // read_only
354 0, // from_value
355 4294967295.0, // to_value
356 1); // step_value
358 this->declareAndLoadParameter("range_limits.enable", range_limits_enable_, // name
359 "Enable XYZ range filtering after transformation into target_frame",
360 true, // add_to_auto_reconfigurable_params
361 false, // is_required
362 false, // read_only
363 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
364 "When false, no range filtering is applied."); // additional_constraints
365 this->declareAndLoadParameter("range_limits.x_min", range_limits_x_min_, // name
366 "Minimum x coordinate in target_frame to keep [m]", // description
367 true, // add_to_auto_reconfigurable_params
368 false, // is_required
369 false, // read_only
370 kMinRangeXY, // from_value
371 kMaxRangeXY, // to_value
372 std::nullopt, // step_value
373 "Must be less than range_limits.x_max."); // additional_constraints
374 this->declareAndLoadParameter("range_limits.x_max", range_limits_x_max_, // name
375 "Maximum x coordinate in target_frame to keep [m]", // description
376 true, // add_to_auto_reconfigurable_params
377 false, // is_required
378 false, // read_only
379 kMinRangeXY, // from_value
380 kMaxRangeXY, // to_value
381 std::nullopt, // step_value
382 "Must be greater than range_limits.x_min."); // additional_constraints
383 this->declareAndLoadParameter("range_limits.y_min", range_limits_y_min_, // name
384 "Minimum y coordinate in target_frame to keep [m]", // description
385 true, // add_to_auto_reconfigurable_params
386 false, // is_required
387 false, // read_only
388 kMinRangeXY, // from_value
389 kMaxRangeXY, // to_value
390 std::nullopt, // step_value
391 "Must be less than range_limits.y_max."); // additional_constraints
392 this->declareAndLoadParameter("range_limits.y_max", range_limits_y_max_, // name
393 "Maximum y coordinate in target_frame to keep [m]", // description
394 true, // add_to_auto_reconfigurable_params
395 false, // is_required
396 false, // read_only
397 kMinRangeXY, // from_value
398 kMaxRangeXY, // to_value
399 std::nullopt, // step_value
400 "Must be greater than range_limits.y_min."); // additional_constraints
401 this->declareAndLoadParameter("range_limits.z_min", range_limits_z_min_, // name
402 "Minimum z coordinate in target_frame to keep [m]", // description
403 true, // add_to_auto_reconfigurable_params
404 false, // is_required
405 false, // read_only
406 kMinRangeZ, // from_value
407 kMaxRangeZ, // to_value
408 std::nullopt, // step_value
409 "Must be less than range_limits.z_max."); // additional_constraints
410 this->declareAndLoadParameter("range_limits.z_max", range_limits_z_max_, // name
411 "Maximum z coordinate in target_frame to keep [m]", // description
412 true, // add_to_auto_reconfigurable_params
413 false, // is_required
414 false, // read_only
415 kMinRangeZ, // from_value
416 kMaxRangeZ, // to_value
417 std::nullopt, // step_value
418 "Must be greater than range_limits.z_min."); // additional_constraints
420 this->declareAndLoadParameter("max_time_diff_sec", max_time_diff_sec_, // name
421 "Maximum timestamp spread across a synchronized input batch in seconds",
422 false, // add_to_auto_reconfigurable_params
423 false, // is_required
424 true, // read_only
425 0.0, std::nullopt, std::nullopt, // from_value, to_value, step_value
426 "Must be non-negative"); // additional_constraints
427 this->declareAndLoadParameter("age_penalty", age_penalty_, // name
428 "Age penalty used by the approximate-time synchronizer",
429 false, // add_to_auto_reconfigurable_params
430 false, // is_required
431 true, // read_only
432 0.0, // from_value
433 100.0, // to_value
434 std::nullopt, // step_value
435 "Valid range is [0, 100]."); // additional_constraints
437 "feature_calibration.enable",
439 "Continuously map follower feature distributions to the pooled, unchanged "
440 "leader distribution", // description
441 false, // add_to_auto_reconfigurable_params
442 false, // is_required
443 true); // read_only
445 "feature_calibration.mode",
447 "Calibration algorithm; currently only continuous distribution mapping is "
448 "supported", // description
449 false, // add_to_auto_reconfigurable_params
450 false, // is_required
451 true, // read_only
452 std::nullopt, std::nullopt, std::nullopt, // from_value, to_value, step_value
453 "Currently supported value: distribution"); // additional_constraints
455 "feature_calibration.field",
457 "Scalar field to calibrate, typically reflectivity or intensity", // description
458 false, // add_to_auto_reconfigurable_params
459 false, // is_required
460 true); // read_only
462 "feature_calibration.leading_inputs",
464 "Input topics that form the unchanged reference distribution", // description
465 false, // add_to_auto_reconfigurable_params
466 false, // is_required
467 true); // read_only
469 "feature_calibration.follower_inputs",
471 "Input topics whose values are remapped to the reference distribution", // description
472 false, // add_to_auto_reconfigurable_params
473 false, // is_required
474 true); // read_only
476 "feature_calibration.samples_per_cloud",
478 "Maximum rotating stratified samples collected per selected cloud by the "
479 "asynchronous worker", // description
480 false, // add_to_auto_reconfigurable_params
481 false, // is_required
482 true, // read_only
483 1, // from_value
484 100000, // to_value
485 1); // step_value
487 "feature_calibration.window_samples",
489 "Rolling sample capacity maintained separately for each selected input", // description
490 false, // add_to_auto_reconfigurable_params
491 false, // is_required
492 true, // read_only
493 100, // from_value
494 10000000, // to_value
495 1); // step_value
497 "feature_calibration.minimum_samples",
499 "Samples required for a leader pool and follower before calibration "
500 "activates", // description
501 false, // add_to_auto_reconfigurable_params
502 false, // is_required
503 true, // read_only
504 100, // from_value
505 10000000, // to_value
506 1); // step_value
508 "feature_calibration.quantiles",
510 "Number of tail-dense piecewise-linear quantile intervals used by the "
511 "distribution mapping", // description
512 false, // add_to_auto_reconfigurable_params
513 false, // is_required
514 true, // read_only
515 2, // from_value
516 64, // to_value
517 1); // step_value
519 "feature_calibration.update_interval_sec",
521 "Minimum interval between continuous background mapping updates", // description
522 false, // add_to_auto_reconfigurable_params
523 false, // is_required
524 true, // read_only
525 0.1, // from_value
526 3600.0); // to_value
529
530#ifdef ENABLE_CUDA
531 // Keep the CUDA context available even when starting in CPU mode so the
532 // backend can be switched safely at runtime.
533 try {
534 cuda_context_ = std::make_unique<cuda::CudaTransformContext>();
535 if (use_cuda_) {
536 RCLCPP_INFO(this->get_logger(), "CUDA acceleration enabled");
537 } else {
538 RCLCPP_INFO(this->get_logger(), "CUDA context initialized; using CPU backend by parameter");
539 }
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();
544 use_cuda_ = false;
545 this->set_parameter(rclcpp::Parameter("use_cuda", false));
546 }
547#else
548 RCLCPP_INFO(this->get_logger(), "CUDA support not compiled, using CPU-only implementation");
549 use_cuda_ = false;
550 this->set_parameter(rclcpp::Parameter("use_cuda", false));
551#endif
552
553 // run setup after constructor has finished to enable shared_from_this()
554 setup_timer_ = this->create_wall_timer(std::chrono::milliseconds(1), [this]() {
555 setup();
556 setup_timer_->cancel();
557 });
558}
559// clang-format on
560
562
563template <typename T>
564void PointCloudFusion::declareAndLoadParameter(const std::string& name,
565 T& param,
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;
578
579 auto type = rclcpp::ParameterValue(param).get_type();
580
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};
592 } else {
593 RCLCPP_WARN(this->get_logger(),
594 "Parameter type of parameter '%s' does not support "
595 "specifying a range",
596 name.c_str());
597 }
598 }
599
600 this->declare_parameter(name, type, param_desc);
601
602 try {
603 param = this->get_parameter(name).get_value<T>();
604 std::stringstream ss;
605 ss << "Loaded parameter '" << name << "': ";
606 if constexpr (is_vector_v<T>) {
607 ss << "[";
608 for (std::size_t i = 0; i < param.size(); ++i) ss << (i > 0 ? ", " : "") << param[i];
609 ss << "]";
610 } else {
611 ss << param;
612 }
613 RCLCPP_INFO_STREAM(this->get_logger(), ss.str());
614 } catch (rclcpp::exceptions::ParameterUninitializedException&) {
615 if (is_required) {
616 RCLCPP_FATAL_STREAM(this->get_logger(), "Missing required parameter '" << name << "', exiting");
617 exit(EXIT_FAILURE);
618 } else {
619 std::stringstream ss;
620 ss << "Missing parameter '" << name << "', using default value: ";
621 if constexpr (is_vector_v<T>) {
622 ss << "[";
623 for (std::size_t i = 0; i < param.size(); ++i) ss << (i > 0 ? ", " : "") << param[i];
624 ss << "]";
625 } else {
626 ss << param;
627 }
628 RCLCPP_WARN_STREAM(this->get_logger(), ss.str());
629 this->set_parameters({rclcpp::Parameter(name, rclcpp::ParameterValue(param))});
630 }
631 }
632
633 if (add_to_auto_reconfigurable_params) {
634 std::function<void(const rclcpp::Parameter&)> setter = [&param](const rclcpp::Parameter& p) { param = p.get_value<T>(); };
635 auto_reconfigurable_params_.push_back(std::make_tuple(name, setter));
636 }
637}
638
639rcl_interfaces::msg::SetParametersResult PointCloudFusion::parametersCallback(const std::vector<rclcpp::Parameter>& parameters) {
640 std::unique_lock<std::shared_mutex> config_lock(config_mutex_);
641
642 // Pre-validate interdependent and runtime-sensitive parameters before
643 // applying any changes.
644 // Build the prospective state: current values overridden by incoming changes.
645 std::optional<detail::MissingFieldFillValues> prospective_fills;
646 bool prospective_object_motion = object_motion_compensation_enable_;
647 bool prospective_ego_motion = motion_compensation_enable_;
648 bool any_range_param = false;
649 bool prospective_use_cuda = use_cuda_;
650 int64_t prospective_fixed_points_per_input_cloud = fixed_points_per_input_cloud_;
651 double prospective_x_min = range_limits_x_min_;
652 double prospective_x_max = range_limits_x_max_;
653 double prospective_y_min = range_limits_y_min_;
654 double prospective_y_max = range_limits_y_max_;
655 double prospective_z_min = range_limits_z_min_;
656 double prospective_z_max = range_limits_z_max_;
657
658 for (const auto& param : parameters) {
659 const auto& name = param.get_name();
660 if (name == "missing_field_fill_values") {
661 try {
662 prospective_fills = detail::parseMissingFieldFillValues(param.as_string_array());
663 } catch (const std::exception& error) {
664 rcl_interfaces::msg::SetParametersResult result;
665 result.successful = false;
666 result.reason = error.what();
667 return result;
668 }
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;
695 }
696 }
697
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";
702 return result;
703 }
704
705 if (prospective_fixed_points_per_input_cloud < kMinFixedPointsPerInputCloud ||
706 prospective_fixed_points_per_input_cloud > kMaxFixedPointsPerInputCloud) {
707 rcl_interfaces::msg::SetParametersResult result;
708 result.successful = false;
709 result.reason = "fixed_points_per_input_cloud must be in [" + std::to_string(kMinFixedPointsPerInputCloud) + ", " +
710 std::to_string(kMaxFixedPointsPerInputCloud) + "]";
711 RCLCPP_ERROR(this->get_logger(), "Rejecting parameter update: %s", result.reason.c_str());
712 return result;
713 }
714
715 if (prospective_use_cuda) {
716#ifdef ENABLE_CUDA
717 if (!cuda_context_) {
718 rcl_interfaces::msg::SetParametersResult result;
719 result.successful = false;
720 result.reason =
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());
724 return result;
725 }
726#else
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());
731 return result;
732#endif
733 }
734
735 if (any_range_param) {
736 rcl_interfaces::msg::SetParametersResult result;
737 std::string reason;
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) + "). ";
741 }
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) + "). ";
745 }
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) + "). ";
749 }
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());
754 return result;
755 }
756 }
757
758 // All validations passed — apply changes.
759 const bool previous_use_cuda = use_cuda_;
760 for (const auto& param : parameters) {
761 for (auto& auto_reconfigurable_param : auto_reconfigurable_params_) {
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());
766 break;
767 }
768 }
769 }
770 if (prospective_fills) missing_field_fills_ = std::move(*prospective_fills);
771 if (use_cuda_ != previous_use_cuda) {
772 RCLCPP_INFO(this->get_logger(), "Fusion backend switched to %s", use_cuda_ ? "CUDA" : "CPU");
773 }
774
775 rcl_interfaces::msg::SetParametersResult result;
776 result.successful = true;
777
778 return result;
779}
780
781namespace detail {
782
783template <std::size_t N>
785
786template <>
788 using Policy = message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2>;
789};
790
791template <>
793 using Policy = message_filters::sync_policies::
794 ApproximateTime<sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2, sensor_msgs::msg::PointCloud2>;
795};
796
797template <>
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>;
803};
804
805template <>
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>;
812};
813
814template <>
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>;
822};
823
824template <>
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>;
833};
834
835template <>
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>;
845};
846
847template <>
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>;
858};
859
860template <std::size_t N>
862
863template <std::size_t N>
864using SyncType = message_filters::Synchronizer<SyncPolicy<N>>;
865
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...> /*unused*/) {
879 // Fan the subscriber filters into the synchronizer inputs.
880 sync.connectInput(*subs[Is]...);
881}
882
890template <std::size_t N>
891void connectInputs(SyncType<N>& sync, const std::vector<std::shared_ptr<point_cloud_transport::SubscriberFilter>>& subs) {
892 connectInputsImpl<N>(sync, subs, std::make_index_sequence<N>{});
893}
894
895} // namespace detail
896
898 // callback for dynamic parameter configuration
900 this->add_on_set_parameters_callback(std::bind(&PointCloudFusion::parametersCallback, this, std::placeholders::_1));
901
902 // create transform buffer and listener
903 tf_buffer_ = std::make_shared<tf2_ros::Buffer>(this->get_clock());
904 tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);
905
906 // validate inputs
907 if (!input_transport_hints_.empty() && input_transport_hints_.size() != input_topics_.size()) {
908 RCLCPP_WARN(this->get_logger(),
909 "'input_transport_hints' length (%zu) does not match "
910 "'input_topics' (%zu). Missing hints default to "
911 "'%s'",
913 }
914
915 // create subscribers
916 cloud_subscribers_.clear();
918 cloud_subscribers_.reserve(input_topics_.size());
920 for (size_t i = 0; i < input_topics_.size(); ++i) {
921 const std::string configured = input_topics_[i];
922 const std::string resolved = this->get_node_topics_interface()->resolve_topic_name(configured);
923 const std::string hint = (i < input_transport_hints_.size() && !input_transport_hints_[i].empty())
925 : std::string(kDefaultTransportHint);
926
927 auto callback_group = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive);
928 rclcpp::SubscriptionOptions subscription_options;
929 subscription_options.callback_group = callback_group;
930
931 auto subscriber = std::make_shared<point_cloud_transport::SubscriberFilter>();
932 // Point clouds are sensor data and are commonly published best-effort to
933 // avoid back-pressure on high-bandwidth streams. A best-effort subscriber
934 // remains compatible with reliable publishers, so it also supports mixed
935 // sensor setups (for example, best-effort Aeva and reliable Ouster).
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());
938 cloud_subscriber_callback_groups_.push_back(std::move(callback_group));
939 cloud_subscribers_.push_back(std::move(subscriber));
940 }
941
942 RCLCPP_INFO(this->get_logger(), "Configured %zu input subscriber callback groups for %zu input topics",
944
945 synchronizer_.reset();
946
947 // configure synchronization or direct passthrough
948 if (cloud_subscribers_.size() == 1) {
949 cloud_subscribers_.front()->registerCallback([this](const PointCloudMsg::ConstSharedPtr msg) {
950 std::vector<PointCloudMsg::ConstSharedPtr> batch;
951 batch.reserve(1);
952 batch.emplace_back(msg);
954 });
955 RCLCPP_INFO(this->get_logger(), "Configured single-input mode for topic '%s'",
956 cloud_subscribers_.front()->getTopic().c_str());
957 } else if (cloud_subscribers_.size() <= 9) {
958 switch (cloud_subscribers_.size()) {
959 case 2:
961 break;
962 case 3:
964 break;
965 case 4:
967 break;
968 case 5:
970 break;
971 case 6:
973 break;
974 case 7:
976 break;
977 case 8:
979 break;
980 case 9:
982 break;
983 default:
984 RCLCPP_FATAL(this->get_logger(), "Unsupported number of input topics: %zu", cloud_subscribers_.size());
985 exit(EXIT_FAILURE);
986 }
987 }
988
989 // create publisher
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");
992 cloud_publisher_ = std::make_shared<point_cloud_transport::Publisher>(
993 pct.advertise(point_cloud_topic_name, static_cast<uint32_t>(output_queue_size_)));
994 RCLCPP_INFO(this->get_logger(), "Publishing to '%s'", cloud_publisher_->getTopic().c_str());
995
996 // Annotate message links for tracing: Each publisher (for raw and compressed
997 // point clouds) depends an all input point clouds.
998 std::vector<const void*> link_subs;
999 std::vector<const void*> link_pubs;
1000 for (const auto& sub_filter : cloud_subscribers_) {
1001 auto sub_base = sub_filter->getSubscriber().getSubscription();
1002 if (sub_base) {
1003 link_subs.push_back(static_cast<const void*>(sub_base->get_subscription_handle().get()));
1004 }
1005 }
1006 if (cloud_publisher_) {
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()));
1010 }
1011 }
1012 TRACETOOLS_TRACEPOINT(message_link_partial_sync, link_subs.data(), link_subs.size(), link_pubs.data(), link_pubs.size());
1013}
1014
1015template <std::size_t N>
1017 static_assert(N >= 2 && N <= 9, "Supported synchronizer size is between 2 and 9");
1018
1019 using Policy = detail::SyncPolicy<N>;
1020 using Sync = detail::SyncType<N>;
1021
1022 // Instantiate ApproximateTime policy tuned to the active input count.
1023 auto sync = std::make_shared<Sync>(Policy(static_cast<size_t>(sync_queue_size_)));
1024
1025 // Wire the configured subscribers into the synchronizer slots.
1027
1028 sync->setMaxIntervalDuration(rclcpp::Duration::from_seconds(max_time_diff_sec_));
1029 sync->setAgePenalty(age_penalty_);
1030 sync->registerCallback([this](auto&&... msgs) {
1031 std::vector<PointCloudMsg::ConstSharedPtr> batch;
1032 batch.reserve(sizeof...(msgs));
1033 // Extract only valid PointCloud2 pointers from the variadic callback.
1034 auto append = [&batch](auto&& msg) {
1035 using ArgT = std::decay_t<decltype(msg)>;
1036 if constexpr (std::is_same_v<ArgT, PointCloudMsg::ConstSharedPtr>) {
1037 if (msg) {
1038 batch.emplace_back(std::forward<decltype(msg)>(msg));
1039 }
1040 }
1041 };
1042 (append(std::forward<decltype(msgs)>(msgs)), ...);
1043 if (!batch.empty()) {
1044 this->handleSynchronizedPointClouds(batch);
1045 } else {
1046 RCLCPP_WARN(this->get_logger(),
1047 "ApproximateTime synchronizer yielded no "
1048 "valid point clouds; skipping fusion.");
1049 }
1050 });
1051
1052 synchronizer_ = sync;
1053
1054 RCLCPP_INFO(this->get_logger(),
1055 "Configured approximate time synchronizer for %zu inputs "
1056 "(queue=%zu, max_dt=%.3f s, age_penalty=%.6f)",
1057 static_cast<size_t>(N), static_cast<size_t>(sync_queue_size_), max_time_diff_sec_, age_penalty_);
1058}
1059
1060void PointCloudFusion::handleSynchronizedPointClouds(const std::vector<sensor_msgs::msg::PointCloud2::ConstSharedPtr>& msgs) {
1061 if (msgs.empty()) {
1062 return;
1063 }
1064
1065 if (feature_calibrator_) feature_calibrator_->enqueue(msgs);
1066
1067 // Protect runtime-configurable parameter reads against concurrent parameter
1068 // updates.
1069 std::shared_lock<std::shared_mutex> config_lock(config_mutex_);
1070
1071 const auto callback_start = std::chrono::steady_clock::now();
1072
1073 FusionTiming timing;
1074 if (!collectTimingInfo(msgs, timing)) {
1075 return;
1076 }
1077
1078#ifdef ENABLE_CUDA
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;
1084 {
1085 // Guard shared CUDA pipeline state against concurrent synchronized
1086 // callbacks.
1087 std::lock_guard<std::mutex> cuda_lock(cuda_context_mutex_);
1088 // Run either CPU or CUDA implementation based on parameter.
1089 if (cuda_context_ && use_cuda_) {
1090 used_cuda = true;
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();
1094 }
1095 }
1096
1097 if (used_cuda) {
1098 if (cuda_result) {
1099 publishFusedCloud(std::move(cuda_result), timing, msgs.size(), cuda_valid_count, callback_start, processing_start,
1100 processing_end, "cuda_fusion_complete");
1101 } else {
1102 RCLCPP_WARN(this->get_logger(), "CUDA processing failed");
1103 }
1104 return;
1105 }
1106#endif
1107
1108 // CPU-only path
1109 std::size_t valid_count = 0;
1110 const auto cpu_processing_start = std::chrono::steady_clock::now();
1111 auto fused_point_cloud = fusePointCloudBatch(msgs, timing, valid_count);
1112
1113 if (!fused_point_cloud) {
1114 RCLCPP_WARN(this->get_logger(), "All points are invalid, skipping fusion");
1115 return;
1116 }
1117
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");
1121}
1122
1123bool PointCloudFusion::collectTimingInfo(const std::vector<PointCloudMsg::ConstSharedPtr>& msgs, FusionTiming& timing) const {
1124 if (msgs.empty()) {
1125 return false;
1126 }
1127
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;
1133
1134 // Walk every cloud once to gather min/max stamps and the largest skew from
1135 // input0.
1136 for (const auto& pc_msg : msgs) {
1137 if (!pc_msg) {
1138 RCLCPP_WARN(this->get_logger(),
1139 "Received null point cloud pointer in "
1140 "synchronized batch, skipping fusion");
1141 return false;
1142 }
1143
1144 const rclcpp::Time current_stamp(pc_msg->header.stamp);
1145 if (first_stamp) {
1146 earliest_stamp = current_stamp;
1147 latest_stamp = current_stamp;
1148 first_stamp = false;
1149 } else {
1150 if (current_stamp < earliest_stamp) earliest_stamp = current_stamp;
1151 if (current_stamp > latest_stamp) latest_stamp = current_stamp;
1152 }
1153
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;
1157 }
1158 }
1159
1160 timing.earliest_stamp = earliest_stamp;
1161 timing.latest_stamp = latest_stamp;
1162 timing.input0_stamp = input0_stamp;
1163 timing.max_dt_from_input0_sec = max_dt_from_input0_sec;
1164 return true;
1165}
1166
1167rclcpp::Time PointCloudFusion::outputStamp(const FusionTiming& timing) const {
1168 switch (output_stamp_mode_) {
1170 return timing.earliest_stamp;
1171 case OutputStampMode::Mean: {
1172 const auto delta = timing.latest_stamp - timing.earliest_stamp;
1173 return timing.earliest_stamp + rclcpp::Duration::from_nanoseconds(delta.nanoseconds() / 2);
1174 }
1176 return timing.input0_stamp;
1178 default:
1179 return timing.latest_stamp;
1180 }
1181}
1182
1184 const rclcpp::Time& reference_stamp,
1185 int time_field_offset,
1186 double timeout_sec,
1187 MotionTransform& transform) const {
1188 transform = MotionTransform{};
1189
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));
1198 }
1199 transform.max_time_offset = max_time_offset;
1200 }
1201 }
1202
1203 // A cloud already expressed in the fixed output frame needs no TF lookup,
1204 // even when that frame has no entries in the buffer.
1205 if (msg.header.frame_id == target_frame_ && target_frame_ == motion_compensation_fixed_frame_) return true;
1206
1207 const rclcpp::Time scan_start(msg.header.stamp);
1208 const auto scan_duration =
1209 rclcpp::Duration::from_seconds(static_cast<double>(transform.max_time_offset) * motion_compensation_time_scale_sec_);
1210 const rclcpp::Time scan_end = scan_start + scan_duration;
1211 auto lookup_at = [&](const rclcpp::Time& source_stamp) {
1212 return lookupWithWallTimeout(timeout_sec, [&] {
1213 return tf_buffer_->lookupTransform(target_frame_, reference_stamp, msg.header.frame_id, source_stamp,
1214 motion_compensation_fixed_frame_, rclcpp::Duration::from_seconds(0.0));
1215 });
1216 };
1217
1218 geometry_msgs::msg::TransformStamped start_stamped;
1219 geometry_msgs::msg::TransformStamped end_stamped;
1220 try {
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",
1228 msg.header.frame_id.c_str(), motion_compensation_fixed_frame_.c_str(), ex.what());
1229 return false;
1230 }
1231
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);
1241 };
1242 copy_transform(start_stamped.transform, transform.start_translation, transform.start_quaternion);
1243 copy_transform(end_stamped.transform, transform.end_translation, transform.end_quaternion);
1244
1245 const float quaternion_dot =
1246 transform.start_quaternion[0] * transform.end_quaternion[0] + transform.start_quaternion[1] * transform.end_quaternion[1] +
1247 transform.start_quaternion[2] * transform.end_quaternion[2] + transform.start_quaternion[3] * transform.end_quaternion[3];
1248 if (quaternion_dot < 0.0F) {
1249 for (float& component : transform.end_quaternion) {
1250 component = -component;
1251 }
1252 }
1253 return true;
1254}
1255
1256bool PointCloudFusion::prepareBatchMotionTransforms(const std::vector<PointCloudMsg::ConstSharedPtr>& msgs,
1257 const rclcpp::Time& reference_stamp,
1258 const std::vector<int>& time_field_offsets,
1259 std::vector<MotionTransform>& transforms) const {
1260 transforms.clear();
1261 transforms.resize(msgs.size());
1263 return false;
1264 }
1265
1266 if (time_field_offsets.size() != msgs.size()) return false;
1267
1268 const bool recovery_probe = !motion_tf_available_.load(std::memory_order_relaxed);
1269 const double timeout_sec = recovery_probe ? 0.0 : motion_compensation_tf_timeout_sec_;
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) {
1273 continue;
1274 }
1275 prepared_any = true;
1276 // Deskewed XYZ needs only the header pose, but radial object motion still
1277 // needs the acquisition origin expressed in that header frame.
1279 const bool needs_ray_origin =
1280 deskewed && object_motion_compensation_enable_ && prepareObjectMotion(*msgs[i], i, reference_stamp).velocity_offset >= 0;
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])) {
1283 motion_tf_available_.store(false, std::memory_order_relaxed);
1284 return false;
1285 }
1286 if (deskewed) retainDeskewedPose(transforms[i]);
1287 }
1288
1289 if (prepared_any && !motion_tf_available_.exchange(true, std::memory_order_relaxed)) {
1290 RCLCPP_INFO(this->get_logger(),
1291 "Motion-compensation TF is available "
1292 "again; resuming compensated fusion");
1293 }
1294 return prepared_any;
1295}
1296
1299 throw std::invalid_argument("object_motion_compensation.enable requires motion_compensation.enable");
1300 }
1302 throw std::invalid_argument("object_motion_compensation.velocity_fields must match input_topics length");
1303 }
1305 throw std::invalid_argument("object_motion_compensation.doppler_sign must be 1 or -1");
1306 }
1309 throw std::invalid_argument("object motion limits must be finite and positive");
1310 }
1312 throw std::invalid_argument("object_motion_compensation.invalid_flags_mask requires invalid_flags_field");
1313 }
1314}
1315
1317 std::size_t input_index,
1318 const rclcpp::Time& reference_stamp) const {
1319 ObjectMotion motion;
1320 if (!object_motion_compensation_enable_) return motion;
1321 const auto& name =
1323 if (name.empty()) return motion;
1324 const auto* velocity = detail::findField(cloud, name);
1325 if (velocity == nullptr) return motion; // Missing velocity is expected for sensors such as Ouster.
1326 if (velocity->count != 1 || !detail::validField(*velocity, cloud.point_step) ||
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());
1331 return motion;
1332 }
1334 const auto* flags = detail::findField(cloud, object_motion_invalid_flags_field_);
1335 if (flags == nullptr || flags->count != 1 || flags->datatype != sensor_msgs::msg::PointField::UINT32 ||
1336 !detail::validField(*flags, cloud.point_step)) {
1337 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000,
1338 "Object motion: configured invalid_flags_field is unavailable; skipping correction");
1339 return motion;
1340 }
1341 motion.invalid_flags_offset = static_cast<int>(flags->offset);
1342 motion.invalid_flags_mask = static_cast<uint32_t>(object_motion_invalid_flags_mask_);
1343 }
1344 motion.velocity_offset = static_cast<int>(velocity->offset);
1345 motion.velocity_datatype = velocity->datatype;
1346 // Subtract integer ROS timestamps before converting the short interval to float.
1347 motion.reference_offset_sec = static_cast<float>((reference_stamp - rclcpp::Time(cloud.header.stamp)).seconds());
1348 motion.time_scale_sec = static_cast<float>(motion_compensation_time_scale_sec_);
1349 motion.doppler_sign = static_cast<float>(object_motion_doppler_sign_);
1350 motion.max_time_offset_sec = static_cast<float>(object_motion_max_time_offset_sec_);
1351 motion.max_speed_mps = static_cast<float>(object_motion_max_speed_mps_);
1352 return motion;
1353}
1354
1355void PointCloudFusion::warnUnusedFillOverrides(const std::vector<std::string>& fields) const {
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 << ", ";
1360 names << fields[i];
1361 }
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());
1365}
1366
1367std::optional<sensor_msgs::msg::PointField> PointCloudFusion::calibrationOutputField(
1368 const std::vector<PointCloudMsg::ConstSharedPtr>& msgs) const {
1369 if (!feature_calibrator_) return std::nullopt;
1370 for (const auto& topic : feature_calibration_leading_inputs_) {
1371 const auto it = std::find(input_topics_.begin(), input_topics_.end(), topic);
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];
1375 const auto* field = detail::findField(cloud, feature_calibration_field_);
1376 if (field != nullptr && field->count == 1 && detail::validField(*field, cloud.point_step) &&
1377 detail::validXyzField(detail::findField(cloud, "x"), cloud.point_step) &&
1378 detail::validXyzField(detail::findField(cloud, "y"), cloud.point_step) &&
1379 detail::validXyzField(detail::findField(cloud, "z"), cloud.point_step)) {
1380 return *field;
1381 }
1382 }
1383 return std::nullopt;
1384}
1385
1386PointCloudFusion::PointCloudMsg::UniquePtr PointCloudFusion::fusePointCloudBatch(
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;
1390
1391 const auto calibration_field = calibrationOutputField(msgs);
1392 const detail::BatchLayout layout =
1394 calibration_field ? &*calibration_field : nullptr);
1395 if (!layout.fill_error.empty()) {
1396 RCLCPP_ERROR_THROTTLE(this->get_logger(), *this->get_clock(), 5000, "%s; skipping batch", layout.fill_error.c_str());
1397 return nullptr;
1398 }
1399 if (layout.point_step == 0) {
1400 missing_xyz_count_.fetch_add(msgs.size(), std::memory_order_relaxed);
1401 RCLCPP_WARN(this->get_logger(), "No input cloud has valid FLOAT32 x/y/z fields; skipping batch");
1402 return nullptr;
1403 }
1405
1406 if (!layout.conflicting_fields.empty()) {
1407 incompatible_field_count_.fetch_add(layout.conflicting_fields.size(), std::memory_order_relaxed);
1408 std::ostringstream names;
1409 for (std::size_t i = 0; i < layout.conflicting_fields.size(); ++i) {
1410 if (i != 0U) names << ", ";
1411 names << layout.conflicting_fields[i];
1412 }
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());
1415 }
1416
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]) {
1421 if (msgs[i]) {
1422 missing_xyz_count_.fetch_add(1, std::memory_order_relaxed);
1423 skipped_cloud_count_.fetch_add(1, std::memory_order_relaxed);
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(),
1428 static_cast<unsigned long long>(missing_xyz_count_.load()),
1429 static_cast<unsigned long long>(skipped_cloud_count_.load()));
1430 }
1431 continue;
1432 }
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);
1437 count = std::min(count, static_cast<std::size_t>(fixed_points_per_input_cloud_));
1438 }
1439 max_capacity += count;
1440 if (!layout.inputs[i].zero_filled_fields.empty()) {
1441 zero_filled_field_count_.fetch_add(layout.inputs[i].zero_filled_fields.size(), std::memory_order_relaxed);
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(),
1444 static_cast<unsigned long long>(zero_filled_field_count_.load()));
1445 }
1446 }
1447 if (max_capacity == 0) return nullptr;
1448
1449 const auto calibration_mappings =
1450 feature_calibrator_ ? feature_calibrator_->mappings() : std::vector<std::shared_ptr<const FeatureMapping>>(msgs.size());
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;
1453 });
1454
1455 auto output = std::make_unique<PointCloudMsg>();
1456 output->header.frame_id = target_frame_;
1457 const rclcpp::Time chosen_stamp = outputStamp(timing);
1458 output->header.stamp = chosen_stamp;
1459 output->height = 1;
1460 output->is_bigendian = layout.is_bigendian;
1461 output->point_step = layout.point_step;
1462 output->fields = layout.fields;
1463 output->is_dense = layout.is_dense;
1464 output->data.resize(max_capacity * layout.point_step);
1465
1466 const bool check_range = range_limits_enable_;
1467 const float x_min = static_cast<float>(range_limits_x_min_);
1468 const float x_max = static_cast<float>(range_limits_x_max_);
1469 const float y_min = static_cast<float>(range_limits_y_min_);
1470 const float y_max = static_cast<float>(range_limits_y_max_);
1471 const float z_min = static_cast<float>(range_limits_z_min_);
1472 const float z_max = static_cast<float>(range_limits_z_max_);
1473
1474 std::vector<MotionTransform> motion_transforms;
1475 const bool batch_motion = prepareBatchMotionTransforms(msgs, chosen_stamp, time_offsets, motion_transforms);
1476 int output_time_offset = -1;
1477 for (const auto& field : layout.fields) {
1478 if (field.name == motion_compensation_time_field_ && field.datatype == sensor_msgs::msg::PointField::UINT32 &&
1479 field.count == 1) {
1480 output_time_offset = static_cast<int>(field.offset);
1481 break;
1482 }
1483 }
1484 uint8_t* destination = output->data.data();
1485
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;
1491 const auto* input_calibration_field = mapping ? detail::findField(*msg, feature_calibration_field_) : nullptr;
1492 const bool calibrate = mapping && input_calibration_field != nullptr && input_calibration_field->count == 1 &&
1493 detail::validField(*input_calibration_field, msg->point_step) &&
1494 output_calibration_field != layout.fields.end();
1495
1496 const bool apply_transform = batch_motion || msg->header.frame_id != target_frame_;
1497 auto object_motion = batch_motion ? prepareObjectMotion(*msg, input_index, chosen_stamp) : ObjectMotion{};
1498 object_motion.ray_origin_max_time_offset = motion_transforms[input_index].ray_origin_max_time_offset;
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) {
1503 try {
1504 const auto stamped = lookupWithWallTimeout(0.1, [&] {
1505 return tf_buffer_->lookupTransform(target_frame_, msg->header.frame_id, msg->header.stamp,
1506 rclcpp::Duration::from_seconds(0.0));
1507 });
1508 tf2::Transform transform;
1509 tf2::fromMsg(stamped.transform, transform);
1510 translation = transform.getOrigin();
1511 rotation = transform.getBasis();
1512 } catch (const tf2::TransformException& exception) {
1513 skipped_cloud_count_.fetch_add(1, std::memory_order_relaxed);
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(),
1518 static_cast<unsigned long long>(skipped_cloud_count_.load()));
1519 continue;
1520 }
1521 }
1522
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);
1525 const std::size_t samples = fixed_points_per_input_cloud_ > 0
1526 ? std::min(total_points, static_cast<std::size_t>(fixed_points_per_input_cloud_))
1527 : total_points;
1528 if (samples == 0) continue;
1529 const double stride = static_cast<double>(total_points) / static_cast<double>(samples);
1530
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;
1540
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);
1549 compensateObjectMotion(object_motion, velocity, point_time, x, y, z);
1550 }
1551
1552 float transformed_x = x;
1553 float transformed_y = y;
1554 float transformed_z = z;
1555 if (batch_motion) {
1556 transformPointInterpolated(motion_transforms[input_index], point_time, x, y, z, transformed_x, transformed_y,
1557 transformed_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());
1563 }
1564 if (check_range &&
1565 !pointWithinRange(transformed_x, transformed_y, transformed_z, x_min, x_max, y_min, y_max, z_min, z_max)) {
1566 continue;
1567 }
1568
1569 if (input.whole_point_copy) {
1570 std::memcpy(destination, source, layout.point_step);
1571 } else {
1572 std::memset(destination, 0, layout.point_step);
1573 detail::fillMissingFields(destination, input);
1574 for (const auto& copy : input.copies) {
1575 std::memcpy(byteOffset(destination, copy.destination_offset), byteOffset(source, copy.source_offset), copy.byte_length);
1576 }
1577 copyConvertedFields(source, destination, input, msg->is_bigendian, layout.is_bigendian);
1578 }
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 =
1584 batch_motion ? 0U
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);
1588 }
1589 if (calibrate) {
1590 float value = 0.0F;
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));
1595 }
1596 }
1597 destination = byteOffset(destination, layout.point_step);
1598 ++valid_point_count;
1599 }
1600 }
1601
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);
1606 return output;
1607}
1608
1609void PointCloudFusion::publishFusedCloud(PointCloudMsg::UniquePtr cloud,
1610 const FusionTiming& timing,
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) {
1617 // Publish the fused cloud and emit a compact timing summary for
1618 // observability.
1619 cloud_publisher_->publish(std::move(cloud));
1620 const auto publish_end = std::chrono::steady_clock::now();
1621
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;
1626 const double batch_dt_ms = (timing.latest_stamp - timing.earliest_stamp).seconds() * 1000.0;
1627
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 "
1631 "max_dt_ms=%.3f",
1632 event_name, input_count, total_points, e2e_duration_ms, prep_duration_ms, processing_duration_ms,
1633 publish_duration_ms, batch_dt_ms, timing.max_dt_from_input0_sec * 1000.0);
1634}
1635
1636void PointCloudFusion::configureOutputStampMode(const std::string& mode) {
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)); });
1640
1641 if (lowered == "earliest") {
1643 } else if (lowered == "mean" || lowered == "mid" || lowered == "midpoint") {
1645 } else if (lowered == "input0") {
1647 } else if (lowered == "latest") {
1649 } else {
1650 RCLCPP_WARN(this->get_logger(), "Invalid output_stamp_mode '%s'; defaulting to 'earliest'.", mode.c_str());
1652 }
1653}
1654
1656 if (!feature_calibration_enable_) return;
1657 std::string mode = feature_calibration_mode_;
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'");
1662 }
1664 throw std::invalid_argument("feature_calibration.field must be included in output_fields");
1665 }
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) {
1669 const auto it = std::find(input_topics_.begin(), input_topics_.end(), topic);
1670 if (it == input_topics_.end()) {
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");
1673 }
1674 result.push_back(static_cast<std::size_t>(it - input_topics_.begin()));
1675 }
1676 return result;
1677 };
1678 auto leaders = indices(feature_calibration_leading_inputs_, "leader");
1679 auto followers = indices(feature_calibration_follower_inputs_, "follower");
1680 if (feature_calibration_field_.empty() || leaders.empty() || followers.empty()) {
1681 throw std::invalid_argument("enabled feature calibration requires a field, leading_inputs, and follower_inputs");
1682 }
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");
1686 }
1687 }
1689 throw std::invalid_argument("feature_calibration.minimum_samples must not exceed window_samples");
1690 }
1693 config.leaders = std::move(leaders);
1694 config.followers = std::move(followers);
1695 config.input_count = input_topics_.size();
1696 config.samples_per_cloud = static_cast<std::size_t>(feature_calibration_samples_per_cloud_);
1697 config.window_samples = static_cast<std::size_t>(feature_calibration_window_samples_);
1698 config.minimum_samples = static_cast<std::size_t>(feature_calibration_minimum_samples_);
1699 config.quantile_count = static_cast<std::size_t>(feature_calibration_quantiles_);
1701 feature_calibrator_ = std::make_unique<DistributionFeatureCalibrator>(
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)",
1706}
1707
1709 if (input_topics_.empty()) {
1710 RCLCPP_FATAL(this->get_logger(), "No input topics configured (parameter 'input_topics'). Exiting");
1711 exit(EXIT_FAILURE);
1712 }
1713 if (input_topics_.size() > kMaxInputTopics) {
1714 RCLCPP_FATAL(this->get_logger(),
1715 "Configured with %zu input topics, but only up to %zu inputs "
1716 "are supported",
1718 exit(EXIT_FAILURE);
1719 }
1720}
1721
1723 bool valid = true;
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",
1729 valid = false;
1730 }
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",
1736 valid = false;
1737 }
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",
1743 valid = false;
1744 }
1745 if (!valid) {
1746 range_limits_enable_ = false;
1747 }
1748}
1749
1750#ifdef ENABLE_CUDA
1751
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;
1756
1757 const rclcpp::Time chosen_stamp = outputStamp(timing);
1758
1760 const auto processing_fields =
1762 auto processing_fills = missing_field_fills_;
1763 // Private processing fields are not published, so user output-fill overrides
1764 // must not change or invalidate them.
1765 if (!publish_time_field) processing_fills.erase(motion_compensation_time_field_);
1766 const auto calibration_field = calibrationOutputField(msgs);
1767 const auto* calibration_descriptor = calibration_field ? &*calibration_field : nullptr;
1768 const detail::BatchLayout processing_layout = detail::buildBatchLayout(msgs, processing_fields, motion_compensation_time_field_,
1769 processing_fills, calibration_descriptor);
1770 const detail::BatchLayout output_layout = publish_time_field
1771 ? processing_layout
1773 missing_field_fills_, calibration_descriptor);
1774 if (!processing_layout.fill_error.empty() || !output_layout.fill_error.empty()) {
1775 const auto& error = processing_layout.fill_error.empty() ? output_layout.fill_error : processing_layout.fill_error;
1776 RCLCPP_ERROR_THROTTLE(this->get_logger(), *this->get_clock(), 5000, "CUDA: %s; skipping batch", error.c_str());
1777 return nullptr;
1778 }
1779 if (processing_layout.point_step == 0 || output_layout.point_step == 0) {
1780 RCLCPP_WARN(this->get_logger(), "CUDA: no input cloud has valid FLOAT32 x/y/z fields; skipping batch");
1781 return nullptr;
1782 }
1784 for (const auto& name : processing_layout.conflicting_fields) {
1785 incompatible_field_count_.fetch_add(1, std::memory_order_relaxed);
1786 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000, "CUDA: omitting incompatible same-name field '%s'",
1787 name.c_str());
1788 }
1789 const auto calibration_mappings =
1790 feature_calibrator_ ? feature_calibrator_->mappings() : std::vector<std::shared_ptr<const FeatureMapping>>(msgs.size());
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;
1804 source_objects[i] = prepareObjectMotion(*msgs[i], i, chosen_stamp);
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);
1813 }
1814 }
1815 }
1816 return -1;
1817 };
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;
1824 }
1825 }
1826 }
1827 // A private FLOAT32 slot preserves a follower feature even when its ROS
1828 // datatype differs from the output datatype (for example Aeva FLOAT32 to
1829 // Ouster UINT16 reflectivity). It is consumed by the CUDA kernel and never
1830 // appears in the published layout.
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) {
1837 if (field.name == motion_compensation_time_field_ && field.datatype == sensor_msgs::msg::PointField::UINT32 &&
1838 field.count == 1) {
1839 packed_time_offset = static_cast<int>(field.offset);
1840 break;
1841 }
1842 }
1843 // A conflicting same-name time field may be omitted or represented by a
1844 // different datatype. Retain measured UINT32 timing independently of output.
1845 const bool private_time = motion_compensation_enable_ && packed_time_offset < 0 &&
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;
1855 }
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);
1858 }
1859 }
1860
1861 // Heterogeneous clouds are packed into one processing layout on the host.
1862 // It may contain a private time field used by motion compensation. The CUDA
1863 // kernel writes the published layout directly, avoiding a second full-cloud
1864 // compaction pass when that private field is not published.
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) {
1874 if (msg) {
1875 missing_xyz_count_.fetch_add(1, std::memory_order_relaxed);
1876 skipped_cloud_count_.fetch_add(1, std::memory_order_relaxed);
1877 RCLCPP_WARN_THROTTLE(this->get_logger(), *this->get_clock(), 5000, "CUDA: skipping cloud from '%s': %s",
1878 msg->header.frame_id.c_str(), input.rejection_reason.c_str());
1879 }
1880 continue;
1881 }
1882 source_time_offsets[i] = input.time_offset;
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]);
1885 if (input.whole_point_copy && processing_point_step == processing_layout.point_step) {
1886 input_data[i] = msg->data.data();
1887 continue;
1888 }
1889 packed[i].assign(point_counts[i] * processing_point_step, 0);
1890 const auto mapping = i < calibration_mappings.size() ? calibration_mappings[i] : nullptr;
1891 const auto* calibration_field = mapping ? detail::findField(*msg, feature_calibration_field_) : 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);
1903 if (input.whole_point_copy) {
1904 std::memcpy(destination, source, processing_layout.point_step);
1905 } else {
1906 detail::fillMissingFields(destination, input);
1907 for (const auto& copy : input.copies) {
1908 std::memcpy(byteOffset(destination, copy.destination_offset), byteOffset(source, copy.source_offset), copy.byte_length);
1909 }
1910 copyConvertedFields(source, destination, input, msg->is_bigendian, processing_layout.is_bigendian);
1911 }
1912 if (pack_calibration) {
1913 float value = 0.0F;
1914 if (!readScalarField(source + calibration_field->offset, calibration_field->datatype, msg->is_bigendian, value)) {
1915 value = std::numeric_limits<float>::quiet_NaN();
1916 }
1917 // Non-finite measurements must skip calibration and retain the copied field.
1918 std::memcpy(byteOffset(destination, calibration_scratch_offset), &value, sizeof(value));
1919 }
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));
1924 }
1925 if (pack_flags) {
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));
1928 }
1929 if (pack_time) {
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));
1932 }
1933 }
1934 input_data[i] = packed[i].data();
1935 if (!input.zero_filled_fields.empty()) {
1936 zero_filled_field_count_.fetch_add(input.zero_filled_fields.size(), std::memory_order_relaxed);
1937 }
1938 }
1939 if (max_points == 0) return nullptr;
1940
1941 std::vector<MotionTransform> motion_transforms;
1942 const bool batch_motion = prepareBatchMotionTransforms(msgs, chosen_stamp, source_time_offsets, 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());
1953 return nullptr;
1954 }
1955 copy_plan.push_back({static_cast<int>(source->offset), static_cast<int>(output_field.offset),
1956 static_cast<int>(detail::fieldDatatypeSize(output_field.datatype) * output_field.count)});
1957 if (output_field.name == motion_compensation_time_field_ && output_field.datatype == sensor_msgs::msg::PointField::UINT32 &&
1958 output_field.count == 1) {
1959 output_time_offset = static_cast<int>(output_field.offset);
1960 }
1961 }
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),
1966 output_time_offset, copy_plan, static_cast<float>(range_limits_x_min_),
1967 static_cast<float>(range_limits_x_max_), static_cast<float>(range_limits_y_min_),
1968 static_cast<float>(range_limits_y_max_), static_cast<float>(range_limits_z_min_),
1969 static_cast<float>(range_limits_z_max_), range_limits_enable_)) {
1970 RCLCPP_ERROR(this->get_logger(), "CUDA resetBatch failed for heterogeneous layout");
1971 return nullptr;
1972 }
1973
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) {
1981 try {
1982 const auto stamped = lookupWithWallTimeout(0.1, [&] {
1983 return tf_buffer_->lookupTransform(target_frame_, msg->header.frame_id, msg->header.stamp,
1984 rclcpp::Duration::from_seconds(0.0));
1985 });
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];
1992 }
1993 translation[0] = origin.x();
1994 translation[1] = origin.y();
1995 translation[2] = origin.z();
1996 } catch (const tf2::TransformException& exception) {
1997 skipped_cloud_count_.fetch_add(1, std::memory_order_relaxed);
1998 RCLCPP_ERROR(this->get_logger(), "CUDA: cannot transform %s to %s: %s", msg->header.frame_id.c_str(),
1999 target_frame_.c_str(), exception.what());
2000 continue;
2001 }
2002 }
2003 const int desired = fixed_points_per_input_cloud_ > 0 ? static_cast<int>(fixed_points_per_input_cloud_) : 0;
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;
2008 const int64_t time_rebase_units = stampDeltaInTimeUnits(msg->header.stamp, chosen_stamp, motion_compensation_time_scale_sec_);
2009 const auto mapping = i < calibration_mappings.size() ? calibration_mappings[i] : nullptr;
2010 const auto* input_calibration_field = mapping ? detail::findField(*msg, feature_calibration_field_) : 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);
2024 }
2025 }
2026
2027 auto output = std::make_unique<PointCloudMsg>();
2028 output->header.frame_id = target_frame_;
2029 output->header.stamp = chosen_stamp;
2030 output->height = 1;
2031 output->is_bigendian = output_layout.is_bigendian;
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;
2038 return output;
2039}
2040#endif // ENABLE_CUDA
2041
2042} // namespace point_cloud_fusion
void validateInputTopicsParameter() const
Validate that the configured input topic list is usable.
void warnUnusedFillOverrides(const std::vector< std::string > &fields) const
~PointCloudFusion() override
Stop background workers before destroying node resources.
static constexpr int32_t kStepSizeOutputQueueSize
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.
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.
ObjectMotion prepareObjectMotion(const PointCloudMsg &cloud, std::size_t input_index, const rclcpp::Time &reference_stamp) const
void declareAndLoadParameter(const std::string &name, T &param, 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 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.
void setup()
Sets up subscribers, publishers, etc. to configure the node.
rclcpp::TimerBase::SharedPtr setup_timer_
Timer to delay setup.
OnSetParametersCallbackHandle::SharedPtr parameters_callback_
Callback handle for dynamic parameter reconfiguration.
static constexpr const char * kDefaultTransportHint
std::unordered_map< std::string, double > missing_field_fills_
rcl_interfaces::msg::SetParametersResult parametersCallback(const std::vector< rclcpp::Parameter > &parameters)
Validate and apply dynamic parameter updates.
std::vector< std::string > input_transport_hints_
static constexpr int64_t kMaxFixedPointsPerInputCloud
std::unique_ptr< DistributionFeatureCalibrator > feature_calibrator_
void configureFeatureCalibration()
Validate calibration parameters and start the background calibrator.
static constexpr int32_t kStepSizeSyncQueueSize
std::shared_ptr< tf2_ros::Buffer > tf_buffer_
TF2 buffer and transform listener.
std::shared_ptr< tf2_ros::TransformListener > tf_listener_
static constexpr int64_t kMinFixedPointsPerInputCloud
std::optional< sensor_msgs::msg::PointField > calibrationOutputField(const std::vector< PointCloudMsg::ConstSharedPtr > &msgs) const
bool collectTimingInfo(const std::vector< PointCloudMsg::ConstSharedPtr > &msgs, FusionTiming &timing) const
Collect timestamp statistics for synchronized input clouds.
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.
static constexpr int64_t kStepSizeFixedPointsPerInputCloud
void setupSynchronizer()
Create the approximate-time synchronizer for a fixed number of input topics.
std::vector< std::string > feature_calibration_leading_inputs_
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::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.
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_
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.
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)
Endpoint transforms for fast scan motion interpolation.
Timing metadata for one synchronized fusion batch.
std::vector< std::string > conflicting_fields
std::vector< std::string > unused_fill_fields
std::vector< sensor_msgs::msg::PointField > fields
std::vector< FieldConversion > conversions
std::vector< std::string > zero_filled_fields
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
std::size_t point_step