merge main
This commit is contained in:
commit
b2e9209333
|
|
@ -18,4 +18,4 @@ jobs:
|
|||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: docker build . --file ./tests/Dockerfile_r2r_galactic --tag r2r_galactic
|
||||
- run: docker run r2r_galactic cargo test --features r2r_msg
|
||||
- run: docker run r2r_galactic cargo test --features r2r_msg,derive,nalgebra,rayon
|
||||
|
|
|
|||
|
|
@ -18,4 +18,4 @@ jobs:
|
|||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: docker build . --file ./tests/Dockerfile_r2r_humble --tag r2r_humble
|
||||
- run: docker run r2r_humble cargo test --features r2r_msg
|
||||
- run: docker run r2r_humble cargo test --features r2r_msg,derive,nalgebra,rayon
|
||||
|
|
|
|||
|
|
@ -18,4 +18,4 @@ jobs:
|
|||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: docker build . --file ./tests/Dockerfile_r2r_iron --tag r2r_iron
|
||||
- run: docker run r2r_iron cargo test --features r2r_msg
|
||||
- run: docker run r2r_iron cargo test --features r2r_msg,derive,nalgebra,rayon
|
||||
|
|
|
|||
|
|
@ -18,4 +18,4 @@ jobs:
|
|||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: docker build . --file ./tests/Dockerfile_rclrs_humble --tag rclrs_humble
|
||||
- run: docker run rclrs_humble cargo test
|
||||
- run: docker run rclrs_humble cargo test --features derive,nalgebra,rayon
|
||||
|
|
|
|||
|
|
@ -18,4 +18,4 @@ jobs:
|
|||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: docker build . --file ./tests/Dockerfile_rclrs_iron --tag rclrs_iron
|
||||
- run: docker run rclrs_iron cargo test
|
||||
- run: docker run rclrs_iron cargo test --features derive,nalgebra,rayon
|
||||
|
|
|
|||
|
|
@ -105,4 +105,4 @@ jobs:
|
|||
- name: test
|
||||
run: |
|
||||
source /opt/ros/$ROS_DISTRO/setup.bash
|
||||
cargo test --features rosrust_msg
|
||||
cargo test --features rosrust_msg,derive,nalgebra,rayon
|
||||
|
|
|
|||
|
|
@ -25,4 +25,4 @@ jobs:
|
|||
- name: Linting
|
||||
run: cargo clippy --all-targets -- -D warnings
|
||||
- name: Tests
|
||||
run: cargo test
|
||||
run: cargo test --features derive,nalgebra,rayon
|
||||
|
|
|
|||
44
Cargo.toml
44
Cargo.toml
|
|
@ -1,29 +1,65 @@
|
|||
[package]
|
||||
name = "ros_pointcloud2"
|
||||
version = "0.4.0"
|
||||
version = "1.0.0-rc.1"
|
||||
edition = "2021"
|
||||
authors = ["Christopher Sieh <stelzo@steado.de>"]
|
||||
description = "Customizable conversions for working with sensor_msgs/PointCloud2."
|
||||
repository = "https://github.com/stelzo/ros_pointcloud2"
|
||||
license = "MIT"
|
||||
keywords = ["ros", "pointcloud2", "pointcloud", "message"]
|
||||
categories = ["science::robotics", "encoding", "data-structures", "api-bindings"]
|
||||
categories = [
|
||||
"science::robotics",
|
||||
"encoding",
|
||||
"data-structures",
|
||||
"api-bindings",
|
||||
]
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/ros_pointcloud2"
|
||||
homepage = "https://github.com/stelzo/ros_pointcloud2"
|
||||
exclude = ["**/tests/**", "**/examples/**", "**/benches/**", "**/target/**", "**/build/**", "**/dist/**", "**/docs/**", "**/doc/**", "package.xml"]
|
||||
exclude = [
|
||||
"**/tests/**",
|
||||
"**/examples/**",
|
||||
"**/benches/**",
|
||||
"**/target/**",
|
||||
"**/build/**",
|
||||
"**/dist/**",
|
||||
"**/docs/**",
|
||||
"**/doc/**",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
rosrust_msg = { version = "0.1", optional = true }
|
||||
rosrust = { version = "0.9.11", optional = true }
|
||||
r2r = { version = "0.8.4", optional = true }
|
||||
rayon = { version = "1", optional = true }
|
||||
nalgebra = { version = "0", optional = true }
|
||||
rpcl2_derive = { path = "./rpcl2_derive", optional = true }
|
||||
type-layout = { version = "0.2", optional = true }
|
||||
|
||||
sensor_msgs = { version = "*", optional = true }
|
||||
std_msgs = { version = "*", optional = true }
|
||||
builtin_interfaces = { version = "*", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
rand = "0.8"
|
||||
criterion = { version = "0.5", features = ["html_reports"] }
|
||||
|
||||
[[bench]]
|
||||
name = "roundtrip"
|
||||
harness = false
|
||||
|
||||
[features]
|
||||
default = ["rclrs_msg"]
|
||||
rclrs_msg = ["dep:sensor_msgs", "dep:std_msgs", "dep:builtin_interfaces"]
|
||||
rosrust_msg = ["dep:rosrust_msg", "dep:rosrust"]
|
||||
r2r_msg = ["dep:r2r"]
|
||||
rayon = ["dep:rayon"]
|
||||
derive = ["dep:rpcl2_derive", "dep:type-layout"]
|
||||
nalgebra = ["dep:nalgebra"]
|
||||
|
||||
default = ["rclrs_msg"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["derive", "nalgebra", "rayon"]
|
||||
default-target = "x86_64-unknown-linux-gnu"
|
||||
|
||||
rclrs_msg = ["dep:sensor_msgs", "dep:std_msgs", "dep:builtin_interfaces"]
|
||||
81
README.md
81
README.md
|
|
@ -1,59 +1,52 @@
|
|||
## !! Note !!
|
||||
|
||||
This library is currently in development for v1.0.0, for the documentation of v0.4.0 on crates.io, visit the [docs](https://docs.rs/ros_pointcloud2/0.4.0/ros_pointcloud2/).
|
||||
|
||||
<p align="center">
|
||||
<h3 align="center">ROS PointCloud2</h3>
|
||||
<p align="center">Customizable conversions to and from the PointCloud2 ROS message.</p>
|
||||
<p align="center">A PointCloud2 message conversion library.</p>
|
||||
<p align="center"><a href="https://crates.io/crates/ros_pointcloud2"><img src="https://img.shields.io/crates/v/ros_pointcloud2.svg" alt=""></a> <a href="https://github.com/stelzo/ros_pointcloud2/tree/main/tests"><img src="https://github.com/stelzo/ros_pointcloud2/actions/workflows/tests.yml/badge.svg" alt=""></a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
Providing an easy to use, generics defined, point-wise iterator abstraction over the byte buffer in `PointCloud2` to minimize iterations in your processing pipeline.
|
||||
ros_pointcloud2 uses its own type for the message `PointCloud2Msg` to keep the library framework agnostic. ROS1 and ROS2 are supported with feature flags.
|
||||
|
||||
To keep the crate a general purpose library for the problem and support ROS1 and ROS2, it uses its own type for the message `PointCloud2Msg`.
|
||||
Get started with the example below, check out the other use cases in the `examples` folder or see the [Documentation](https://docs.rs/ros_pointcloud2/1.0.0/ros_pointcloud2/) for a complete guide.
|
||||
|
||||
## Quickstart
|
||||
|
||||
## Examples
|
||||
```rust
|
||||
use ros_pointcloud2::{
|
||||
pcl_utils::PointXYZ, reader::ReaderXYZ, writer::WriterXYZ, PointCloud2Msg,
|
||||
};
|
||||
use ros_pointcloud2::prelude::*;
|
||||
|
||||
// Your points (here using the predefined type PointXYZ).
|
||||
// PointXYZ (and many others) are provided by the crate.
|
||||
let cloud_points = vec![
|
||||
PointXYZ {x: 91.486, y: -4.1, z: 42.0001,},
|
||||
PointXYZ {x: f32::MAX, y: f32::MIN, z: f32::MAX,},
|
||||
PointXYZI::new(91.486, -4.1, 42.0001, 0.1),
|
||||
PointXYZI::new(f32::MAX, f32::MIN, f32::MAX, f32::MIN),
|
||||
];
|
||||
|
||||
// For equality test later
|
||||
let cloud_copy = cloud_points.clone();
|
||||
|
||||
// Vector -> Writer -> Message.
|
||||
// You can also just give the Vec or anything that implements `IntoIterator`.
|
||||
let internal_msg: PointCloud2Msg = WriterXYZ::from(cloud_points.into_iter())
|
||||
.try_into() // iterating points here O(n)
|
||||
.unwrap();
|
||||
|
||||
// Convert to your ROS crate message type, we will use r2r here.
|
||||
// let msg: r2r::sensor_msgs::msg::PointCloud2 = internal_msg.into();
|
||||
let out_msg = PointCloud2Msg::try_from_vec(cloud_points).unwrap();
|
||||
|
||||
// Convert the ROS crate message type, we will use r2r here.
|
||||
// let msg: r2r::sensor_msgs::msg::PointCloud2 = out_msg.into();
|
||||
// Publish ...
|
||||
|
||||
// ... now incoming from a topic.
|
||||
// let internal_msg: PointCloud2Msg = msg.into();
|
||||
// let in_msg: PointCloud2Msg = msg.into();
|
||||
let in_msg = out_msg;
|
||||
|
||||
// Message -> Reader -> your pipeline. The Reader implements the Iterator trait.
|
||||
let reader = ReaderXYZ::try_from(internal_msg).unwrap();
|
||||
let new_cloud_points = reader
|
||||
.map(|point: PointXYZ| {
|
||||
// Some logic here
|
||||
let processed_cloud = in_msg.try_into_iter().unwrap()
|
||||
.map(|point: PointXYZ| { // Define the info you want to have from the Msg.
|
||||
// Some logic here ...
|
||||
|
||||
point
|
||||
})
|
||||
.collect::<Vec<PointXYZ>>(); // iterating points here O(n)
|
||||
|
||||
assert_eq!(new_cloud_points, cloud_copy);
|
||||
point
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
```
|
||||
|
||||
## Integrations
|
||||
|
||||
There are currently 3 integrations for common ROS crates.
|
||||
|
||||
- [rosrust_msg](https://github.com/adnanademovic/rosrust)
|
||||
- [](https://github.com/stelzo/ros_pointcloud2/actions/workflows/rosrust_noetic.yml)
|
||||
- [r2r_msg](https://github.com/sequenceplanner/r2r)
|
||||
|
|
@ -65,33 +58,43 @@ There are currently 3 integrations for common ROS crates.
|
|||
- [](https://github.com/stelzo/ros_pointcloud2/actions/workflows/rclrs_iron.yml)
|
||||
|
||||
You can use `rosrust` and `r2r` by enabling the respective feature:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ros_pointcloud2 = { version = "*", features = ["r2r_msg"]}
|
||||
ros_pointcloud2 = { version = "*", features = ["r2r_msg", "derive"]}
|
||||
# or
|
||||
ros_pointcloud2 = { version = "*", features = ["rosrust_msg"]}
|
||||
ros_pointcloud2 = { version = "*", features = ["rosrust_msg", "derive"]}
|
||||
```
|
||||
|
||||
### rclrs (ros2_rust)
|
||||
|
||||
Features do not work properly with `rcrls` because the messages are linked externally. You need to use tags instead:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ros_pointcloud2 = { git = "https://github.com/stelzo/ros_pointcloud2", tag = "v0.4.0_rclrs" }
|
||||
```
|
||||
|
||||
Also, indicate the following dependencies to your linker inside the `package.xml` of your package.
|
||||
|
||||
```xml
|
||||
<depend>std_msgs</depend>
|
||||
<depend>sensor_msgs</depend>
|
||||
<depend>builtin_interfaces</depend>
|
||||
```
|
||||
|
||||
Please open an issue or PR if you want to see support for other crates.
|
||||
Please open an issue or PR if you need other integrations.
|
||||
|
||||
## Future Work
|
||||
- Benchmark vs PCL
|
||||
- Add more predefined types
|
||||
- Optional derive macros for custom point implementations
|
||||
## Performance
|
||||
|
||||
This library offers a speed up when compared to PointCloudLibrary (PCL) conversions but the specific factor depends heavily on the use case and system.
|
||||
The `_vec` conversions are on average ~6x faster than PCL while the single core iteration `_iter` functions are around ~2x faster.
|
||||
Parallelization with `_par_iter` gives a ~9x speed up compared to an OpenMP accelerated PCL pipeline.
|
||||
|
||||
The results are measured on an Intel i7-14700 with benchmarks from [this repository](https://github.com/stelzo/ros_pcl_conv_bench).
|
||||
|
||||
For minimizing the conversion overhead in general, always use the functions that best fit your use case.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](https://choosealicense.com/licenses/mit/)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,695 @@
|
|||
use criterion::{black_box, criterion_group, criterion_main, Criterion};
|
||||
use ros_pointcloud2::prelude::*;
|
||||
|
||||
use rand::Rng;
|
||||
|
||||
pub type PointXYZB = PointXYZINormal;
|
||||
|
||||
pub fn distance_to_origin(point: &PointXYZ) -> f32 {
|
||||
((point.x.powi(2)) + (point.y.powi(2)) + (point.z.powi(2))).sqrt()
|
||||
}
|
||||
|
||||
pub fn dot_product(point1: &PointXYZ, point2: &PointXYZ) -> f32 {
|
||||
point1.x * point2.x + point1.y * point2.y + point1.z * point2.z
|
||||
}
|
||||
|
||||
pub fn cross_product(point1: &PointXYZ, point2: &PointXYZ) -> PointXYZ {
|
||||
PointXYZ {
|
||||
x: point1.y * point2.z - point1.z * point2.y,
|
||||
y: point1.z * point2.x - point1.x * point2.z,
|
||||
z: point1.x * point2.y - point1.y * point2.x,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scalar_multiply(point: &PointXYZ, scalar: f32) -> PointXYZ {
|
||||
PointXYZ {
|
||||
x: point.x * scalar,
|
||||
y: point.y * scalar,
|
||||
z: point.z * scalar,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn magnitude_squared(point: &PointXYZ) -> f32 {
|
||||
(point.x.powi(2)) + (point.y.powi(2)) + (point.z.powi(2))
|
||||
}
|
||||
|
||||
pub fn reflection_through_plane(
|
||||
point: &PointXYZ,
|
||||
normal: &PointXYZ,
|
||||
point_on_plane: &PointXYZ,
|
||||
) -> PointXYZ {
|
||||
PointXYZ {
|
||||
x: point.x
|
||||
- 2.0
|
||||
* ((point.x - point_on_plane.x) * normal.x
|
||||
+ (point.y - point_on_plane.y) * normal.y
|
||||
+ (point.z - point_on_plane.z) * normal.z),
|
||||
y: point.y
|
||||
- 2.0
|
||||
* ((point.x - point_on_plane.x) * normal.x
|
||||
+ (point.y - point_on_plane.y) * normal.y
|
||||
+ (point.z - point_on_plane.z) * normal.z),
|
||||
z: point.z
|
||||
- 2.0
|
||||
* ((point.x - point_on_plane.x) * normal.x
|
||||
+ (point.y - point_on_plane.y) * normal.y
|
||||
+ (point.z - point_on_plane.z) * normal.z),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rotation_about_x(point: &PointXYZ, angle: f32) -> PointXYZ {
|
||||
let c = f32::cos(angle);
|
||||
let s = f32::sin(angle);
|
||||
PointXYZ {
|
||||
x: point.x,
|
||||
y: point.y * c - point.z * s,
|
||||
z: point.y * s + point.z * c,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn closest_point_on_line(
|
||||
point: &PointXYZ,
|
||||
line_point: &PointXYZ,
|
||||
line_direction: &PointXYZ,
|
||||
) -> PointXYZ {
|
||||
PointXYZ {
|
||||
x: line_point.x
|
||||
+ (line_point.x - point.x) * ((line_point.x - point.x).powi(2))
|
||||
/ ((line_direction.x * 2.0).powi(2))
|
||||
+ (line_direction.y * 2.0) * (point.z - line_point.z)
|
||||
/ ((line_direction.z * 2.0).powi(2)),
|
||||
y: line_point.y
|
||||
+ (line_point.y - point.y) * ((line_point.y - point.y).powi(2))
|
||||
/ ((line_direction.y * 2.0).powi(2))
|
||||
+ (line_direction.x * 2.0) * (point.x - line_point.x)
|
||||
/ ((line_direction.x * 2.0).powi(2)),
|
||||
z: line_point.z
|
||||
+ (line_point.z - point.z) * ((line_point.z - point.z).powi(2))
|
||||
/ ((line_direction.z * 2.0).powi(2))
|
||||
+ (line_direction.y * 2.0) * (point.y - line_point.y)
|
||||
/ ((line_direction.y * 2.0).powi(2)),
|
||||
}
|
||||
}
|
||||
|
||||
fn minus(point1: &PointXYZ, point2: &PointXYZ) -> PointXYZ {
|
||||
PointXYZ {
|
||||
x: point1.x - point2.x,
|
||||
y: point1.y - point2.y,
|
||||
z: point1.z - point2.z,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_random_pointcloud(num_points: usize, min: f32, max: f32) -> Vec<PointXYZB> {
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut pointcloud = Vec::with_capacity(num_points);
|
||||
for _ in 0..num_points {
|
||||
let point = PointXYZB {
|
||||
x: rng.gen_range(min..max),
|
||||
y: rng.gen_range(min..max),
|
||||
z: rng.gen_range(min..max),
|
||||
..Default::default()
|
||||
};
|
||||
pointcloud.push(point);
|
||||
}
|
||||
pointcloud
|
||||
}
|
||||
|
||||
pub fn heavy_computing(point: &PointXYZ, iterations: u32) -> f32 {
|
||||
let mut result = distance_to_origin(point);
|
||||
for _ in 0..iterations {
|
||||
result += dot_product(
|
||||
point,
|
||||
&PointXYZ {
|
||||
x: 1.0,
|
||||
y: 2.0,
|
||||
z: 3.0,
|
||||
},
|
||||
);
|
||||
result += cross_product(
|
||||
point,
|
||||
&PointXYZ {
|
||||
x: 4.0,
|
||||
y: 5.0,
|
||||
z: 6.0,
|
||||
},
|
||||
)
|
||||
.x;
|
||||
result = result + (result * 10.0).sqrt();
|
||||
let reflected_point = reflection_through_plane(
|
||||
point,
|
||||
&PointXYZ {
|
||||
x: 7.0,
|
||||
y: 8.0,
|
||||
z: 9.0,
|
||||
},
|
||||
&PointXYZ {
|
||||
x: 3.0,
|
||||
y: 4.0,
|
||||
z: 5.0,
|
||||
},
|
||||
);
|
||||
let rotated_point = rotation_about_x(
|
||||
&PointXYZ {
|
||||
x: 10.0,
|
||||
y: 11.0,
|
||||
z: 12.0,
|
||||
},
|
||||
std::f32::consts::PI / 2.0,
|
||||
);
|
||||
|
||||
result += magnitude_squared(&minus(&reflected_point, &rotated_point));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
fn roundtrip_vec(cloud: Vec<PointXYZB>) -> bool {
|
||||
let orig_len = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_vec(cloud).unwrap();
|
||||
let total: Vec<PointXYZ> = internal_msg.try_into_vec().unwrap();
|
||||
orig_len == total.len()
|
||||
}
|
||||
|
||||
fn roundtrip(cloud: Vec<PointXYZB>) -> bool {
|
||||
let orig_len = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_iter()
|
||||
.unwrap()
|
||||
.collect::<Vec<PointXYZ>>();
|
||||
orig_len == total.len()
|
||||
}
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
fn roundtrip_filter_vec(cloud: Vec<PointXYZB>) -> bool {
|
||||
let orig_len = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_vec(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_iter()
|
||||
.unwrap()
|
||||
.filter(|point: &PointXYZ| distance_to_origin(point) < 69.9)
|
||||
.fold(PointXYZ::default(), |acc, point| PointXYZ {
|
||||
x: acc.x + point.x,
|
||||
y: acc.y + point.y,
|
||||
z: acc.z + point.z,
|
||||
});
|
||||
orig_len == total.x as usize
|
||||
}
|
||||
|
||||
fn roundtrip_filter(cloud: Vec<PointXYZB>) -> bool {
|
||||
let orig_len = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_iter()
|
||||
.unwrap()
|
||||
.filter(|point: &PointXYZ| distance_to_origin(point) < 69.9)
|
||||
.fold(PointXYZ::default(), |acc, point| PointXYZ {
|
||||
x: acc.x + point.x,
|
||||
y: acc.y + point.y,
|
||||
z: acc.z + point.z,
|
||||
});
|
||||
orig_len == total.x as usize
|
||||
}
|
||||
|
||||
fn roundtrip_computing(cloud: Vec<PointXYZB>) -> bool {
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_iter()
|
||||
.unwrap()
|
||||
.map(|point: PointXYZ| heavy_computing(&point, 100))
|
||||
.sum::<f32>();
|
||||
total > 0.0
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
fn roundtrip_computing_par(cloud: Vec<PointXYZB>) -> bool {
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_par_iter()
|
||||
.unwrap()
|
||||
.map(|point: PointXYZ| heavy_computing(&point, 100))
|
||||
.sum::<f32>();
|
||||
total > 0.0
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
fn roundtrip_computing_par_par(cloud: Vec<PointXYZB>) -> bool {
|
||||
let internal_msg = PointCloud2Msg::try_from_par_iter(cloud.into_par_iter()).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_par_iter()
|
||||
.unwrap()
|
||||
.map(|point: PointXYZ| heavy_computing(&point, 100))
|
||||
.sum::<f32>();
|
||||
total > 0.0
|
||||
}
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
fn roundtrip_computing_vec(cloud: Vec<PointXYZB>) -> bool {
|
||||
let internal_msg = PointCloud2Msg::try_from_vec(cloud).unwrap();
|
||||
let total: f32 = internal_msg
|
||||
.try_into_vec()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|point: PointXYZ| heavy_computing(&point, 100))
|
||||
.sum();
|
||||
total > 0.0
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
fn roundtrip_par(cloud: Vec<PointXYZB>) -> bool {
|
||||
let orig_len = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_par_iter()
|
||||
.unwrap()
|
||||
.collect::<Vec<PointXYZ>>();
|
||||
orig_len != total.len()
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
fn roundtrip_par_par(cloud: Vec<PointXYZB>) -> bool {
|
||||
let orig_len = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_par_iter(cloud.into_par_iter()).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_par_iter()
|
||||
.unwrap()
|
||||
.collect::<Vec<PointXYZ>>();
|
||||
orig_len != total.len()
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
fn roundtrip_filter_par(cloud: Vec<PointXYZB>) -> bool {
|
||||
let orig_len: usize = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_par_iter()
|
||||
.unwrap()
|
||||
.filter(|point: &PointXYZ| distance_to_origin(point) < 69.9)
|
||||
.reduce(PointXYZ::default, |acc, point| PointXYZ {
|
||||
x: acc.x + point.x,
|
||||
y: acc.y + point.y,
|
||||
z: acc.z + point.z,
|
||||
});
|
||||
orig_len == total.x as usize
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
fn roundtrip_filter_par_par(cloud: Vec<PointXYZB>) -> bool {
|
||||
let orig_len: usize = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_par_iter(cloud.into_par_iter()).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_par_iter()
|
||||
.unwrap()
|
||||
.filter(|point: &PointXYZ| distance_to_origin(point) < 69.9)
|
||||
.reduce(PointXYZ::default, |acc, point| PointXYZ {
|
||||
x: acc.x + point.x,
|
||||
y: acc.y + point.y,
|
||||
z: acc.z + point.z,
|
||||
});
|
||||
orig_len == total.x as usize
|
||||
}
|
||||
|
||||
fn roundtrip_benchmark(c: &mut Criterion) {
|
||||
let cloud_points_16k = generate_random_pointcloud(16_000, f32::MIN / 2.0, f32::MAX / 2.0);
|
||||
let cloud_points_60k = generate_random_pointcloud(60_000, f32::MIN / 2.0, f32::MAX / 2.0);
|
||||
let cloud_points_120k = generate_random_pointcloud(120_000, f32::MIN / 2.0, f32::MAX / 2.0);
|
||||
let cloud_points_500k = generate_random_pointcloud(500_000, f32::MIN / 2.0, f32::MAX / 2.0);
|
||||
let cloud_points_1_5m = generate_random_pointcloud(1_500_000, f32::MIN / 2.0, f32::MAX / 2.0);
|
||||
|
||||
// 16k points (Velodyne with 16 beams)
|
||||
|
||||
// Moving memory
|
||||
c.bench_function("16k iter", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("16k iter_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("16k iter_par_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par_par(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("16k vec", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_vec(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// Simple distance filter
|
||||
c.bench_function("16k iter_filter", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter(black_box(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("16k filter_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter_par(black_box(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("16k filter_par_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_filter_par_par(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("16k vec_filter", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter_vec(black_box(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// Heavy computing
|
||||
c.bench_function("16k iter_compute", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing(black_box(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("16k iter_compute_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_par(black_box(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("16k iter_compute_par_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_par_par(black_box(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("16k vec_compute", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_vec(black_box(cloud_points_16k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// 60k points (Ouster with 64 beams)
|
||||
|
||||
// Moving memory
|
||||
c.bench_function("60k iter", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip(cloud_points_60k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("60k iter_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par(cloud_points_60k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("60k iter_par_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par_par(cloud_points_60k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("60k vec", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_vec(cloud_points_60k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// 120k points (Ouster with 128 beams)
|
||||
|
||||
// Moving memory
|
||||
c.bench_function("120k iter", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("120k iter_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("120k iter_par_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par_par(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("120k vec", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_vec(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// Simple distance filter
|
||||
c.bench_function("120k iter_filter", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter(black_box(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("120k filter_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter_par(black_box(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("120k filter_par_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_filter_par_par(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("120k vec_filter", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter_vec(black_box(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// Heavy computing
|
||||
c.bench_function("120k iter_compute", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing(black_box(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("120k iter_compute_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_par(black_box(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("120k iter_compute_par_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_par_par(black_box(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("120k vec_compute", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_vec(black_box(cloud_points_120k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// 500k points (just to show how it scales)
|
||||
|
||||
// Moving memory
|
||||
c.bench_function("500k iter", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("500k iter_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("500k iter_par_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par_par(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("500k vec", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_vec(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// Simple distance filter
|
||||
c.bench_function("500k iter_filter", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter(black_box(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("500k filter_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter_par(black_box(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("500k filter_par_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_filter_par_par(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("500k vec_filter", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter_vec(black_box(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// Heavy computing
|
||||
c.bench_function("500k iter_compute", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing(black_box(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("500k iter_compute_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_par(black_box(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("500k iter_compute_par_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_par_par(black_box(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("500k vec_compute", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_vec(black_box(cloud_points_500k.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// 1.5m points (scale of small localmaps in SLAM)
|
||||
|
||||
// Moving memory
|
||||
c.bench_function("1.5m iter", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("1.5m iter_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("1.5m iter_par_par", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_par_par(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("1.5m vec", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_vec(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// Simple distance filter
|
||||
c.bench_function("1.5m iter_filter", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter(black_box(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("1.5m iter_par_filter", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_filter_par(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("1.5m iter_par_par_filter", |b| {
|
||||
b.iter(|| {
|
||||
black_box(roundtrip_filter_par_par(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("1.5m vec_filter", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_filter_vec(black_box(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
// Heavy computing
|
||||
c.bench_function("1.5m iter_compute", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing(black_box(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("1.5m iter_compute_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_par(black_box(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
c.bench_function("1.5m iter_compute_par_par", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_par_par(black_box(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
c.bench_function("1.5m vec_compute", |b| {
|
||||
b.iter(|| {
|
||||
roundtrip_computing_vec(black_box(cloud_points_1_5m.clone()));
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
criterion_group!(benches, roundtrip_benchmark);
|
||||
criterion_main!(benches);
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
/// This example demonstrates how to use a custom point with encoded metadata.
|
||||
/// The use case is a segmentation point cloud where each point holds a label and we want to filter by it.
|
||||
/// Since the datatypes for the PointCloud2 message are very limited,
|
||||
/// we need to encode the enum into a supported type.
|
||||
/// This needs some manual work to tell the library how to encode and decode the enum.
|
||||
///
|
||||
/// Important Note: This example is only possible with disabled `derive` feature,
|
||||
/// because the library (currently) does not know the size of your chosen supported type at compile time.
|
||||
/// This makes direct copies impossible.
|
||||
use ros_pointcloud2::prelude::*;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Default, Copy)]
|
||||
enum Label {
|
||||
#[default]
|
||||
Human,
|
||||
Deer,
|
||||
Car,
|
||||
}
|
||||
|
||||
// Define a custom point with an enum.
|
||||
// This is normally not supported by PointCloud2 but we will explain the library how to handle it.
|
||||
#[derive(Debug, PartialEq, Clone, Default)]
|
||||
struct CustomPoint {
|
||||
x: f32,
|
||||
y: f32,
|
||||
z: f32,
|
||||
intensity: f32,
|
||||
my_custom_label: Label,
|
||||
}
|
||||
|
||||
// Some convenience functions to convert between the enum and u8.
|
||||
impl From<Label> for u8 {
|
||||
fn from(label: Label) -> Self {
|
||||
match label {
|
||||
Label::Human => 0,
|
||||
Label::Deer => 1,
|
||||
Label::Car => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for Label {
|
||||
fn from(label: u8) -> Self {
|
||||
match label {
|
||||
0 => Label::Human,
|
||||
1 => Label::Deer,
|
||||
2 => Label::Car,
|
||||
_ => panic!("Invalid label"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomPoint {
|
||||
fn new(x: f32, y: f32, z: f32, intensity: f32, my_custom_label: Label) -> Self {
|
||||
Self {
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
intensity,
|
||||
my_custom_label,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We implement the PointConvertible trait (needed for every custom point).
|
||||
// RPCL2Point is the internal representation. It takes the amount of fields as generic arguments.
|
||||
impl From<CustomPoint> for RPCL2Point<5> {
|
||||
fn from(point: CustomPoint) -> Self {
|
||||
[
|
||||
point.x.into(),
|
||||
point.y.into(),
|
||||
point.z.into(),
|
||||
point.intensity.into(),
|
||||
u8::from(point.my_custom_label).into(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<5>> for CustomPoint {
|
||||
fn from(point: RPCL2Point<5>) -> Self {
|
||||
Self::new(
|
||||
point[0].get(),
|
||||
point[1].get(),
|
||||
point[2].get(),
|
||||
point[3].get(),
|
||||
point[4].get(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Define wow we want to name the fields in the message.
|
||||
impl Fields<5> for CustomPoint {
|
||||
fn field_names_ordered() -> [&'static str; 5] {
|
||||
["x", "y", "z", "intensity", "my_custom_label"]
|
||||
}
|
||||
}
|
||||
|
||||
// We implemented everything that is needed for PointConvertible so we declare it as a done.
|
||||
#[cfg(not(feature = "derive"))]
|
||||
impl PointConvertible<5> for CustomPoint {}
|
||||
|
||||
// Now we tell the library how to encode and decode the label.
|
||||
// You don't need to do this if your CustomPoint has a field that is already supported by PointCloud2.
|
||||
impl GetFieldDatatype for Label {
|
||||
fn field_datatype() -> FieldDatatype {
|
||||
FieldDatatype::U8 // Declare that we want to use u8 as the datatype for the label.
|
||||
}
|
||||
}
|
||||
|
||||
// Again, you don't need this with only supported field types.
|
||||
// u8 -> Label
|
||||
impl FromBytes for Label {
|
||||
// Technically, PointCloud2 supports big and little endian even though it is rarely used.
|
||||
// 'be' stands for big endian and 'le' for little endian.
|
||||
fn from_be_bytes(bytes: PointDataBuffer) -> Self {
|
||||
u8::from_be_bytes([bytes[0]]).into()
|
||||
}
|
||||
|
||||
fn from_le_bytes(bytes: PointDataBuffer) -> Self {
|
||||
u8::from_le_bytes([bytes[0]]).into()
|
||||
}
|
||||
}
|
||||
|
||||
// Label -> u8
|
||||
impl From<Label> for PointDataBuffer {
|
||||
fn from(label: Label) -> Self {
|
||||
[u8::from(label)].into()
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
#[cfg(not(feature = "derive"))]
|
||||
{
|
||||
let cloud = vec![
|
||||
CustomPoint::new(1.0, 2.0, 3.0, 4.0, Label::Deer),
|
||||
CustomPoint::new(4.0, 5.0, 6.0, 7.0, Label::Car),
|
||||
CustomPoint::new(7.0, 8.0, 9.0, 10.0, Label::Human),
|
||||
];
|
||||
|
||||
println!("Original cloud: {:?}", cloud);
|
||||
|
||||
let msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
|
||||
println!("filtering by label == Deer");
|
||||
let out = msg
|
||||
.try_into_iter()
|
||||
.unwrap()
|
||||
.filter(|point: &CustomPoint| point.my_custom_label == Label::Deer)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
println!("Filtered cloud: {:?}", out);
|
||||
|
||||
assert_eq!(
|
||||
vec![CustomPoint::new(1.0, 2.0, 3.0, 4.0, Label::Deer),],
|
||||
out
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
use rand::Rng;
|
||||
/// This example implements a naive benchmark for the library so you can evaluate the use of rayon for parallel processing.
|
||||
/// It generates a random point cloud and measures the time it takes to iterate over it.
|
||||
/// The code works mainly as a showcase. For actual benchmarks, check the `benches` directory or run `cargo bench`.
|
||||
use std::time::Duration;
|
||||
|
||||
use ros_pointcloud2::prelude::*;
|
||||
|
||||
pub fn generate_random_pointcloud(num_points: usize, min: f32, max: f32) -> Vec<PointXYZ> {
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut pointcloud = Vec::with_capacity(num_points);
|
||||
for _ in 0..num_points {
|
||||
let point = PointXYZ {
|
||||
x: rng.gen_range(min..max),
|
||||
y: rng.gen_range(min..max),
|
||||
z: rng.gen_range(min..max),
|
||||
};
|
||||
pointcloud.push(point);
|
||||
}
|
||||
pointcloud
|
||||
}
|
||||
|
||||
fn roundtrip(cloud: Vec<PointXYZ>) -> bool {
|
||||
let orig_len = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_iter()
|
||||
.unwrap()
|
||||
.collect::<Vec<PointXYZ>>();
|
||||
orig_len == total.len()
|
||||
}
|
||||
|
||||
fn roundtrip_filter(cloud: Vec<PointXYZ>) -> bool {
|
||||
let orig_len = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_iter()
|
||||
.unwrap()
|
||||
.filter(|point: &PointXYZ| {
|
||||
(point.x.powi(2) + point.y.powi(2) + point.z.powi(2)).sqrt() < 1.9
|
||||
})
|
||||
.fold(PointXYZ::default(), |acc, point| PointXYZ {
|
||||
x: acc.x + point.x,
|
||||
y: acc.y + point.y,
|
||||
z: acc.z + point.z,
|
||||
});
|
||||
orig_len == total.x as usize
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
fn roundtrip_par(cloud: Vec<PointXYZ>) -> bool {
|
||||
let orig_len = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_par_iter()
|
||||
.unwrap()
|
||||
.collect::<Vec<PointXYZ>>();
|
||||
orig_len != total.len()
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
fn roundtrip_filter_par(cloud: Vec<PointXYZ>) -> bool {
|
||||
let orig_len: usize = cloud.len();
|
||||
let internal_msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let total = internal_msg
|
||||
.try_into_par_iter()
|
||||
.unwrap()
|
||||
.filter(|point: &PointXYZ| {
|
||||
(point.x.powi(2) + point.y.powi(2) + point.z.powi(2)).sqrt() < 1.9
|
||||
})
|
||||
.reduce(PointXYZ::default, |acc, point| PointXYZ {
|
||||
x: acc.x + point.x,
|
||||
y: acc.y + point.y,
|
||||
z: acc.z + point.z,
|
||||
});
|
||||
orig_len == total.x as usize
|
||||
}
|
||||
|
||||
// call measure_func X times and print the average time
|
||||
fn measure_func_avg(
|
||||
num_iterations: u32,
|
||||
pcl_size: usize,
|
||||
func: fn(Vec<PointXYZ>) -> bool,
|
||||
) -> Duration {
|
||||
let mut total_time = Duration::new(0, 0);
|
||||
for _ in 0..num_iterations {
|
||||
total_time += measure_func(pcl_size, func);
|
||||
}
|
||||
total_time / num_iterations
|
||||
}
|
||||
|
||||
fn measure_func<F>(pcl_size: usize, func: F) -> Duration
|
||||
where
|
||||
F: Fn(Vec<PointXYZ>) -> bool,
|
||||
{
|
||||
let cloud_points = generate_random_pointcloud(pcl_size, f32::MIN / 2.0, f32::MAX / 2.0);
|
||||
let start = std::time::Instant::now();
|
||||
let _ = func(cloud_points);
|
||||
start.elapsed()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("100k");
|
||||
let how_many = 10_000;
|
||||
let how_often = 1_000;
|
||||
|
||||
let dur = measure_func_avg(how_often, how_many, roundtrip);
|
||||
println!("roundtrip: {:?}", dur);
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
let dur = measure_func_avg(how_often, how_many, roundtrip_par);
|
||||
println!("roundtrip_par: {:?}", dur);
|
||||
|
||||
println!("200k");
|
||||
let how_many = 200_000;
|
||||
let how_often = 100;
|
||||
|
||||
let dur = measure_func_avg(how_often, how_many, roundtrip_filter);
|
||||
println!("roundtrip_filter: {:?}", dur);
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
let dur = measure_func_avg(how_often, how_many, roundtrip_filter_par);
|
||||
println!("roundtrip_filter_par: {:?}", dur);
|
||||
|
||||
println!("10m");
|
||||
let how_many = 10_000_000;
|
||||
let how_often = 10;
|
||||
|
||||
let dur = measure_func_avg(how_often, how_many, roundtrip_filter);
|
||||
println!("roundtrip_filter: {:?}", dur);
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
let dur = measure_func_avg(how_often, how_many, roundtrip_filter_par);
|
||||
println!("roundtrip_filter_par: {:?}", dur);
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
/// This example demonstrates a very simple distance filter with predefined point types.
|
||||
/// Note that this example is a simplified version of the custom_enum_field_filter.rs example.
|
||||
/// Also, it effectively demonstrates a typesafe byte-to-byte buffer filter with a single iteration.
|
||||
///
|
||||
/// It also works without any dependencies, making it a good "hello world" example.
|
||||
use ros_pointcloud2::prelude::*;
|
||||
|
||||
fn main() {
|
||||
let cloud = vec![
|
||||
PointXYZ::new(1.0, 1.0, 1.0),
|
||||
PointXYZ::new(2.0, 2.0, 2.0),
|
||||
PointXYZ::new(3.0, 3.0, 3.0),
|
||||
];
|
||||
|
||||
println!("Original cloud: {:?}", cloud);
|
||||
|
||||
let msg = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
|
||||
println!("filtering by distance < 1.9m");
|
||||
let out = msg
|
||||
.try_into_iter()
|
||||
.unwrap()
|
||||
.filter(|point: &PointXYZ| {
|
||||
(point.x.powi(2) + point.y.powi(2) + point.z.powi(2)).sqrt() < 1.9
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
println!("Filtered cloud: {:?}", out);
|
||||
|
||||
assert_eq!(vec![PointXYZ::new(1.0, 1.0, 1.0),], out);
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
[package]
|
||||
name = "rpcl2_derive"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
syn = "1"
|
||||
quote = "1"
|
||||
proc-macro2 = "1"
|
||||
|
|
@ -0,0 +1,208 @@
|
|||
extern crate proc_macro;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use quote::{quote, ToTokens};
|
||||
use syn::{parse_macro_input, DeriveInput};
|
||||
|
||||
fn get_allowed_types() -> HashMap<&'static str, usize> {
|
||||
let mut allowed_datatypes = HashMap::<&'static str, usize>::new();
|
||||
allowed_datatypes.insert("f32", std::mem::size_of::<f32>());
|
||||
allowed_datatypes.insert("f64", std::mem::size_of::<f64>());
|
||||
allowed_datatypes.insert("i32", std::mem::size_of::<i32>());
|
||||
allowed_datatypes.insert("u8", std::mem::size_of::<u8>());
|
||||
allowed_datatypes.insert("u16", std::mem::size_of::<u16>());
|
||||
allowed_datatypes.insert("u32", std::mem::size_of::<u32>());
|
||||
allowed_datatypes.insert("i8", std::mem::size_of::<i8>());
|
||||
allowed_datatypes.insert("i16", std::mem::size_of::<i16>());
|
||||
allowed_datatypes
|
||||
}
|
||||
|
||||
// Given a field, get the value of the `rpcl2` renaming attribute like
|
||||
// #[rpcl2(name = "new_name")]
|
||||
fn get_ros_fields_attribute(attrs: &[syn::Attribute]) -> Option<syn::Lit> {
|
||||
for attr in attrs {
|
||||
if attr.path.is_ident("rpcl2") {
|
||||
let meta = attr.parse_meta().unwrap();
|
||||
if let syn::Meta::List(meta_list) = meta {
|
||||
for nested_meta in meta_list.nested {
|
||||
if let syn::NestedMeta::Meta(meta) = nested_meta {
|
||||
if let syn::Meta::NameValue(meta_name_value) = meta {
|
||||
if meta_name_value.path.is_ident("name") {
|
||||
return Some(meta_name_value.lit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn struct_field_rename_array(input: &DeriveInput) -> Vec<String> {
|
||||
let fields = match input.data {
|
||||
syn::Data::Struct(ref data) => match data.fields {
|
||||
syn::Fields::Named(ref fields) => &fields.named,
|
||||
_ => panic!("StructNames can only be derived for structs with named fields"),
|
||||
},
|
||||
_ => panic!("StructNames can only be derived for structs"),
|
||||
};
|
||||
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let field_name = field.ident.as_ref().unwrap();
|
||||
let ros_fields_attr = get_ros_fields_attribute(&field.attrs);
|
||||
match ros_fields_attr {
|
||||
Some(ros_fields) => match ros_fields {
|
||||
syn::Lit::Str(lit_str) => {
|
||||
let val = lit_str.value();
|
||||
if val.is_empty() {
|
||||
panic!("Empty string literals are not allowed for the rpcl2 attribute");
|
||||
}
|
||||
val
|
||||
}
|
||||
_ => {
|
||||
panic!("Only string literals are allowed for the rpcl2 attribute")
|
||||
}
|
||||
},
|
||||
None => String::from(field_name.to_token_stream().to_string()),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// This macro will implement the `Fields` trait for your struct so you can use your point for the PointCloud2 conversion.
|
||||
///
|
||||
/// Use the rename attribute if your struct field name should be different to the ROS field name.
|
||||
#[proc_macro_derive(Fields, attributes(rpcl2))]
|
||||
pub fn ros_point_fields_derive(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
let struct_name = &input.ident;
|
||||
|
||||
let field_names = struct_field_rename_array(&input)
|
||||
.into_iter()
|
||||
.map(|field_name| {
|
||||
quote! { #field_name }
|
||||
});
|
||||
|
||||
let field_names_len = field_names.len();
|
||||
|
||||
let expanded = quote! {
|
||||
impl Fields<#field_names_len> for #struct_name {
|
||||
fn field_names_ordered() -> [&'static str; #field_names_len] {
|
||||
[
|
||||
#(#field_names,)*
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Return the generated implementation
|
||||
expanded.into()
|
||||
}
|
||||
|
||||
/// This macro will fully implement the `PointConvertible` trait for your struct so you can use your point for the PointCloud2 conversion.
|
||||
///
|
||||
/// Note that the repr(C) attribute is required for the struct to work efficiently with C++ PCL.
|
||||
/// With Rust layout optimizations, the struct might not work with the PCL library but the message still conforms to the description of PointCloud2.
|
||||
/// Furthermore, Rust layout can lead to smaller messages to be send over the network.
|
||||
#[proc_macro_derive(PointConvertible, attributes(rpcl2))]
|
||||
pub fn ros_point_derive(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
let name = input.clone().ident;
|
||||
|
||||
let fields = match input.data {
|
||||
syn::Data::Struct(ref data) => data.fields.clone(),
|
||||
_ => {
|
||||
return syn::Error::new_spanned(input, "Only structs are supported")
|
||||
.to_compile_error()
|
||||
.into()
|
||||
}
|
||||
};
|
||||
|
||||
let allowed_datatypes = get_allowed_types();
|
||||
|
||||
if fields.is_empty() {
|
||||
return syn::Error::new_spanned(input, "No fields found")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
|
||||
for field in fields.iter() {
|
||||
let ty = field.ty.to_token_stream().to_string();
|
||||
if !allowed_datatypes.contains_key(&ty.as_str()) {
|
||||
return syn::Error::new_spanned(field, "Field type not allowed")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
}
|
||||
|
||||
let field_len_token: usize = fields.len();
|
||||
|
||||
let field_names = struct_field_rename_array(&input)
|
||||
.into_iter()
|
||||
.map(|field_name| {
|
||||
quote! { #field_name }
|
||||
});
|
||||
|
||||
let field_impl = quote! {
|
||||
impl ros_pointcloud2::Fields<#field_len_token> for #name {
|
||||
fn field_names_ordered() -> [&'static str; #field_len_token] {
|
||||
[
|
||||
#(#field_names,)*
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let field_names_get = fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, f)| {
|
||||
let field_name = f.ident.as_ref().unwrap();
|
||||
quote! { #field_name: point[#idx].get() }
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let from_my_point = quote! {
|
||||
impl From<ros_pointcloud2::RPCL2Point<#field_len_token>> for #name {
|
||||
fn from(point: ros_pointcloud2::RPCL2Point<#field_len_token>) -> Self {
|
||||
Self {
|
||||
#(#field_names_get,)*
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let field_names_into = fields
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let field_name = f.ident.as_ref().unwrap();
|
||||
quote! { point.#field_name.into() }
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let from_custom_point = quote! {
|
||||
impl From<#name> for ros_pointcloud2::RPCL2Point<#field_len_token> {
|
||||
fn from(point: #name) -> Self {
|
||||
[ #(#field_names_into,)* ].into()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let convertible = quote! {
|
||||
impl ros_pointcloud2::PointConvertible<#field_len_token> for #name {}
|
||||
};
|
||||
|
||||
let out = TokenStream::from(quote! {
|
||||
#field_impl
|
||||
#from_my_point
|
||||
#from_custom_point
|
||||
#convertible
|
||||
});
|
||||
|
||||
TokenStream::from(out)
|
||||
}
|
||||
361
src/convert.rs
361
src/convert.rs
|
|
@ -1,361 +0,0 @@
|
|||
use crate::*;
|
||||
|
||||
/// Datatypes from the [PointField message](http://docs.ros.org/en/melodic/api/sensor_msgs/html/msg/PointField.html).
|
||||
#[derive(Default, Clone, Debug, PartialEq, Copy)]
|
||||
pub enum FieldDatatype {
|
||||
F32,
|
||||
F64,
|
||||
I32,
|
||||
U8,
|
||||
U16,
|
||||
#[default]
|
||||
U32,
|
||||
I8,
|
||||
I16,
|
||||
}
|
||||
|
||||
impl FieldDatatype {
|
||||
pub fn size(&self) -> usize {
|
||||
match self {
|
||||
FieldDatatype::U8 => 1,
|
||||
FieldDatatype::U16 => 2,
|
||||
FieldDatatype::U32 => 4,
|
||||
FieldDatatype::I8 => 1,
|
||||
FieldDatatype::I16 => 2,
|
||||
FieldDatatype::I32 => 4,
|
||||
FieldDatatype::F32 => 4,
|
||||
FieldDatatype::F64 => 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Getter trait for the datatype of a field value.
|
||||
pub trait GetFieldDatatype {
|
||||
fn field_datatype() -> FieldDatatype;
|
||||
}
|
||||
|
||||
impl GetFieldDatatype for f32 {
|
||||
fn field_datatype() -> FieldDatatype {
|
||||
FieldDatatype::F32
|
||||
}
|
||||
}
|
||||
|
||||
impl GetFieldDatatype for f64 {
|
||||
fn field_datatype() -> FieldDatatype {
|
||||
FieldDatatype::F64
|
||||
}
|
||||
}
|
||||
|
||||
impl GetFieldDatatype for i32 {
|
||||
fn field_datatype() -> FieldDatatype {
|
||||
FieldDatatype::I32
|
||||
}
|
||||
}
|
||||
|
||||
impl GetFieldDatatype for u8 {
|
||||
fn field_datatype() -> FieldDatatype {
|
||||
FieldDatatype::U8
|
||||
}
|
||||
}
|
||||
|
||||
impl GetFieldDatatype for u16 {
|
||||
fn field_datatype() -> FieldDatatype {
|
||||
FieldDatatype::U16
|
||||
}
|
||||
}
|
||||
|
||||
impl GetFieldDatatype for u32 {
|
||||
fn field_datatype() -> FieldDatatype {
|
||||
FieldDatatype::U32
|
||||
}
|
||||
}
|
||||
|
||||
impl GetFieldDatatype for i8 {
|
||||
fn field_datatype() -> FieldDatatype {
|
||||
FieldDatatype::I8
|
||||
}
|
||||
}
|
||||
|
||||
impl GetFieldDatatype for i16 {
|
||||
fn field_datatype() -> FieldDatatype {
|
||||
FieldDatatype::I16
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for FieldDatatype {
|
||||
type Error = ConversionError;
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
1 => Ok(FieldDatatype::I8),
|
||||
2 => Ok(FieldDatatype::U8),
|
||||
3 => Ok(FieldDatatype::I16),
|
||||
4 => Ok(FieldDatatype::U16),
|
||||
5 => Ok(FieldDatatype::I32),
|
||||
6 => Ok(FieldDatatype::U32),
|
||||
7 => Ok(FieldDatatype::F32),
|
||||
8 => Ok(FieldDatatype::F64),
|
||||
_ => Err(ConversionError::UnsupportedFieldType),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FieldDatatype> for u8 {
|
||||
fn from(val: FieldDatatype) -> Self {
|
||||
match val {
|
||||
FieldDatatype::I8 => 1,
|
||||
FieldDatatype::U8 => 2,
|
||||
FieldDatatype::I16 => 3,
|
||||
FieldDatatype::U16 => 4,
|
||||
FieldDatatype::I32 => 5,
|
||||
FieldDatatype::U32 => 6,
|
||||
FieldDatatype::F32 => 7,
|
||||
FieldDatatype::F64 => 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn check_coord(
|
||||
coord: Option<usize>,
|
||||
fields: &[PointFieldMsg],
|
||||
xyz_field_type: &FieldDatatype,
|
||||
) -> Result<PointFieldMsg, ConversionError> {
|
||||
match coord {
|
||||
Some(y_idx) => {
|
||||
let field = &fields[y_idx];
|
||||
if field.datatype != u8::from(*xyz_field_type) {
|
||||
return Err(ConversionError::InvalidFieldFormat);
|
||||
}
|
||||
Ok(field.clone())
|
||||
}
|
||||
None => Err(ConversionError::NotEnoughFields),
|
||||
}
|
||||
}
|
||||
|
||||
/// Matching field names from each meta data per point to the PointField name.
|
||||
/// Always make sure to use the same order as in your conversion implementation to have a correct mapping.
|
||||
///
|
||||
/// This trait is needed to implement the `PointConvertible` trait.
|
||||
///
|
||||
/// # Example for full point conversion.
|
||||
/// ```
|
||||
/// use ros_pointcloud2::{Point, PointConvertible, MetaNames, size_of};
|
||||
///
|
||||
/// #[derive(Clone, Debug, PartialEq, Copy)]
|
||||
/// pub struct MyPointXYZI {
|
||||
/// pub x: f32,
|
||||
/// pub y: f32,
|
||||
/// pub z: f32,
|
||||
/// pub intensity: f32,
|
||||
/// }
|
||||
///
|
||||
/// impl MetaNames<1> for MyPointXYZI {
|
||||
/// fn meta_names() -> [&'static str; 1] {
|
||||
/// ["intensity"]
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait MetaNames<const METADIM: usize> {
|
||||
fn meta_names() -> [&'static str; METADIM];
|
||||
}
|
||||
|
||||
/// This trait is used to convert a byte slice to a primitive type.
|
||||
/// All PointField types are supported.
|
||||
pub trait FromBytes: Default + Sized + Copy + GetFieldDatatype {
|
||||
fn from_be_bytes(bytes: &[u8]) -> Self;
|
||||
fn from_le_bytes(bytes: &[u8]) -> Self;
|
||||
|
||||
fn bytes(_: &Self) -> Vec<u8>;
|
||||
}
|
||||
|
||||
impl FromBytes for i8 {
|
||||
#[inline]
|
||||
fn from_be_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_be_bytes([bytes[0]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_le_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_le_bytes([bytes[0]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bytes(x: &i8) -> Vec<u8> {
|
||||
Vec::from(x.to_le_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBytes for i16 {
|
||||
#[inline]
|
||||
fn from_be_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_be_bytes([bytes[0], bytes[1]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_le_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_le_bytes([bytes[0], bytes[1]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bytes(x: &i16) -> Vec<u8> {
|
||||
Vec::from(x.to_le_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBytes for u16 {
|
||||
#[inline]
|
||||
fn from_be_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_be_bytes([bytes[0], bytes[1]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_le_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_le_bytes([bytes[0], bytes[1]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bytes(x: &u16) -> Vec<u8> {
|
||||
Vec::from(x.to_le_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBytes for u32 {
|
||||
#[inline]
|
||||
fn from_be_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_le_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bytes(x: &u32) -> Vec<u8> {
|
||||
Vec::from(x.to_le_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBytes for f32 {
|
||||
#[inline]
|
||||
fn from_be_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_le_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bytes(x: &f32) -> Vec<u8> {
|
||||
Vec::from(x.to_le_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBytes for i32 {
|
||||
#[inline]
|
||||
fn from_be_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
|
||||
}
|
||||
fn from_le_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
|
||||
}
|
||||
|
||||
fn bytes(x: &i32) -> Vec<u8> {
|
||||
Vec::from(x.to_le_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBytes for f64 {
|
||||
#[inline]
|
||||
fn from_be_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_be_bytes([
|
||||
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
|
||||
])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_le_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_le_bytes([
|
||||
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
|
||||
])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bytes(x: &f64) -> Vec<u8> {
|
||||
Vec::from(x.to_le_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromBytes for u8 {
|
||||
#[inline]
|
||||
fn from_be_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_be_bytes([bytes[0]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_le_bytes(bytes: &[u8]) -> Self {
|
||||
Self::from_le_bytes([bytes[0]])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bytes(x: &u8) -> Vec<u8> {
|
||||
Vec::from(x.to_le_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Debug, PartialEq)]
|
||||
pub(crate) enum Endianness {
|
||||
Big,
|
||||
|
||||
#[default]
|
||||
Little,
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn load_loadable<T: FromBytes, const SIZE: usize>(
|
||||
start_idx: usize,
|
||||
data: &[u8],
|
||||
endian: &Endianness,
|
||||
) -> T {
|
||||
match endian {
|
||||
Endianness::Big => T::from_be_bytes(load_bytes::<SIZE>(start_idx, data).as_slice()),
|
||||
Endianness::Little => T::from_le_bytes(load_bytes::<SIZE>(start_idx, data).as_slice()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Note: check if the data slice is long enough to load the bytes beforehand! Uses unsafe indexing.
|
||||
#[inline(always)]
|
||||
fn load_bytes<const S: usize>(start_idx: usize, data: &[u8]) -> [u8; S] {
|
||||
let mut target = [u8::default(); S];
|
||||
|
||||
debug_assert!(target.len() == S);
|
||||
debug_assert!(data.len() >= start_idx + S);
|
||||
|
||||
let source = unsafe { data.get_unchecked(start_idx..start_idx + S) };
|
||||
target
|
||||
.iter_mut()
|
||||
.zip(source.iter())
|
||||
.for_each(|(target, source)| {
|
||||
*target = *source;
|
||||
});
|
||||
target
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn from_bytes() {
|
||||
i8::bytes(&1);
|
||||
u8::bytes(&1);
|
||||
i16::bytes(&1);
|
||||
u16::bytes(&1);
|
||||
i32::bytes(&1);
|
||||
u32::bytes(&1);
|
||||
f32::bytes(&1.0);
|
||||
f64::bytes(&1.0);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,487 @@
|
|||
//! Iterator implementations for PointCloud2Msg including a parallel iterator for rayon.
|
||||
use crate::{
|
||||
Endian, FieldDatatype, Fields, MsgConversionError, PointCloud2Msg, PointConvertible, PointData,
|
||||
RPCL2Point,
|
||||
};
|
||||
|
||||
/// The PointCloudIterator provides a an iterator abstraction of the PointCloud2Msg.
|
||||
///
|
||||
/// The iterator is defined at compile time, so the point has to be described via template arguments.
|
||||
///
|
||||
/// When using within a ROS node, the PointCloud2 (created by the ROS crate) must be converted first.
|
||||
/// The cost of this operation is low, as it mostly moves ownership without iterating over the point data.
|
||||
///
|
||||
/// ROS1 with rosrust:
|
||||
/// let msg: rosrust_msg::sensor_msgs::PointCloud2; // inside the callback
|
||||
/// let converted: ros_pointcloud2::PointCloud2Msg = msg.into();
|
||||
///
|
||||
/// ROS2 with r2r:
|
||||
/// let msg: r2r::sensor_msgs::msg::PointCloud2 = internal_msg.into();
|
||||
/// let converted: ros_pointcloud2::PointCloud2Msg = msg.into();
|
||||
///
|
||||
/// ros_pointcloud2 supports r2r, rclrs and rosrust as conversion targets out of the box via feature flags.
|
||||
///
|
||||
pub struct PointCloudIterator<const N: usize, C>
|
||||
where
|
||||
C: Fields<N>,
|
||||
{
|
||||
iteration: usize,
|
||||
iteration_back: usize,
|
||||
data: ByteBufferView<N>,
|
||||
phantom_c: std::marker::PhantomData<C>, // internally used for meta names array
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
impl<const N: usize, C> ExactSizeIterator for PointCloudIterator<N, C>
|
||||
where
|
||||
C: PointConvertible<N> + Send + Sync,
|
||||
{
|
||||
fn len(&self) -> usize {
|
||||
self.data.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
impl<const N: usize, C> DoubleEndedIterator for PointCloudIterator<N, C>
|
||||
where
|
||||
C: PointConvertible<N> + Send + Sync,
|
||||
{
|
||||
fn next_back(&mut self) -> Option<Self::Item> {
|
||||
if self.iteration_back < self.iteration {
|
||||
return None; // iteration finished
|
||||
}
|
||||
|
||||
let p = self.data.point_at(self.iteration_back);
|
||||
self.iteration_back -= 1;
|
||||
Some(C::from(p))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
impl<const N: usize, C> rayon::iter::ParallelIterator for PointCloudIterator<N, C>
|
||||
where
|
||||
C: PointConvertible<N> + Send + Sync,
|
||||
{
|
||||
type Item = C;
|
||||
|
||||
fn drive_unindexed<Co>(self, consumer: Co) -> Co::Result
|
||||
where
|
||||
Co: rayon::iter::plumbing::UnindexedConsumer<Self::Item>,
|
||||
{
|
||||
rayon::iter::plumbing::bridge(self, consumer)
|
||||
}
|
||||
|
||||
fn opt_len(&self) -> Option<usize> {
|
||||
Some(self.data.len())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
impl<const N: usize, C> rayon::iter::IndexedParallelIterator for PointCloudIterator<N, C>
|
||||
where
|
||||
C: PointConvertible<N> + Send + Sync,
|
||||
{
|
||||
fn len(&self) -> usize {
|
||||
self.data.len()
|
||||
}
|
||||
|
||||
fn drive<Co>(self, consumer: Co) -> Co::Result
|
||||
where
|
||||
Co: rayon::iter::plumbing::Consumer<Self::Item>,
|
||||
{
|
||||
rayon::iter::plumbing::bridge(self, consumer)
|
||||
}
|
||||
|
||||
fn with_producer<CB: rayon::iter::plumbing::ProducerCallback<Self::Item>>(
|
||||
self,
|
||||
callback: CB,
|
||||
) -> CB::Output {
|
||||
callback.callback(RayonProducer::from(self))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
struct RayonProducer<const N: usize, C: PointConvertible<N>> {
|
||||
iter: PointCloudIterator<N, C>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
impl<const N: usize, C> rayon::iter::plumbing::Producer for RayonProducer<N, C>
|
||||
where
|
||||
C: PointConvertible<N> + Send + Sync,
|
||||
{
|
||||
type Item = C;
|
||||
type IntoIter = PointCloudIterator<N, C>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.iter
|
||||
}
|
||||
|
||||
fn split_at(self, point_index: usize) -> (Self, Self) {
|
||||
let (left, right) = self.iter.split_at(point_index);
|
||||
(RayonProducer { iter: left }, RayonProducer { iter: right })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
impl<const N: usize, C> From<PointCloudIterator<N, C>> for RayonProducer<N, C>
|
||||
where
|
||||
C: PointConvertible<N> + Send + Sync,
|
||||
{
|
||||
fn from(iterator: PointCloudIterator<N, C>) -> Self {
|
||||
Self { iter: iterator }
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementation of the iterator trait.
|
||||
impl<const N: usize, C> Iterator for PointCloudIterator<N, C>
|
||||
where
|
||||
C: PointConvertible<N>,
|
||||
{
|
||||
type Item = C;
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let buf_len = self.data.len();
|
||||
(buf_len, Some(buf_len))
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.iteration >= self.data.len() || self.iteration_back < self.iteration {
|
||||
return None; // iteration finished
|
||||
}
|
||||
|
||||
let p = self.data.point_at(self.iteration);
|
||||
self.iteration += 1;
|
||||
Some(C::from(p))
|
||||
}
|
||||
}
|
||||
|
||||
struct ByteBufferView<const N: usize> {
|
||||
data: std::sync::Arc<[u8]>,
|
||||
start_point_idx: usize,
|
||||
end_point_idx: usize,
|
||||
point_step_size: usize,
|
||||
offsets: [usize; N],
|
||||
meta: Vec<(String, FieldDatatype)>,
|
||||
endian: Endian,
|
||||
}
|
||||
|
||||
impl<const N: usize> ByteBufferView<N> {
|
||||
fn new(
|
||||
data: Vec<u8>,
|
||||
point_step_size: usize,
|
||||
start_point_idx: usize,
|
||||
end_point_idx: usize,
|
||||
offsets: [usize; N],
|
||||
meta: Vec<(String, FieldDatatype)>,
|
||||
endian: Endian,
|
||||
) -> Self {
|
||||
Self {
|
||||
data: std::sync::Arc::<[u8]>::from(data),
|
||||
start_point_idx,
|
||||
end_point_idx,
|
||||
point_step_size,
|
||||
offsets,
|
||||
meta,
|
||||
endian,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn len(&self) -> usize {
|
||||
self.end_point_idx - self.start_point_idx + 1
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn point_at(&self, idx: usize) -> RPCL2Point<N> {
|
||||
let offset = (self.start_point_idx + idx) * self.point_step_size;
|
||||
|
||||
// TODO memcpy entire point at once, then extract fields?
|
||||
let mut meta = [PointData::default(); N];
|
||||
meta.iter_mut()
|
||||
.zip(self.offsets.iter())
|
||||
.zip(self.meta.iter())
|
||||
.for_each(|((p_meta, in_point_offset), (_, meta_type))| {
|
||||
*p_meta = PointData::from_buffer(
|
||||
&self.data,
|
||||
offset + in_point_offset,
|
||||
*meta_type,
|
||||
self.endian,
|
||||
);
|
||||
});
|
||||
|
||||
RPCL2Point { fields: meta }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn clone_with_bounds(&self, start: usize, size: usize) -> Self {
|
||||
Self {
|
||||
data: self.data.clone(),
|
||||
start_point_idx: start,
|
||||
end_point_idx: start + size - 1,
|
||||
point_step_size: self.point_step_size,
|
||||
offsets: self.offsets,
|
||||
meta: self.meta.clone(),
|
||||
endian: self.endian,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn split_at(self, point_index: usize) -> (Self, Self) {
|
||||
let left_start = self.start_point_idx;
|
||||
let left_size = point_index;
|
||||
|
||||
let right_start = point_index;
|
||||
let right_size = self.len() - point_index;
|
||||
|
||||
(
|
||||
self.clone_with_bounds(left_start, left_size),
|
||||
self.clone_with_bounds(right_start, right_size),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize, C> TryFrom<PointCloud2Msg> for PointCloudIterator<N, C>
|
||||
where
|
||||
C: Fields<N>,
|
||||
{
|
||||
type Error = MsgConversionError;
|
||||
|
||||
/// Convert a PointCloud2Msg into an iterator.
|
||||
/// Converting a PointCloud2Msg into an iterator is a fallible operation since the message can contain only a subset of the required fields.
|
||||
///
|
||||
/// The theoretical time complexity is O(n) where n is the number of fields defined in the message for a single point which is typically small.
|
||||
/// It therefore has a constant time complexity O(1) for practical purposes.
|
||||
fn try_from(cloud: PointCloud2Msg) -> Result<Self, Self::Error> {
|
||||
let mut meta_with_offsets = vec![(String::default(), FieldDatatype::default(), 0); N];
|
||||
|
||||
let not_found_fieldnames = C::field_names_ordered()
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let found = cloud.fields.iter().any(|field| field.name == *name);
|
||||
(name, found)
|
||||
})
|
||||
.filter(|(_, found)| !*found)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if !not_found_fieldnames.is_empty() {
|
||||
let names_not_found = not_found_fieldnames
|
||||
.into_iter()
|
||||
.map(|(name, _)| (*name).to_owned())
|
||||
.collect::<Vec<String>>();
|
||||
return Err(MsgConversionError::FieldsNotFound(names_not_found));
|
||||
}
|
||||
|
||||
let ordered_fieldnames = C::field_names_ordered();
|
||||
for (field, with_offset) in cloud.fields.iter().zip(meta_with_offsets.iter_mut()) {
|
||||
if ordered_fieldnames.contains(&field.name.as_str()) {
|
||||
*with_offset = (
|
||||
field.name.clone(),
|
||||
field.datatype.try_into()?,
|
||||
field.offset as usize,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
meta_with_offsets.sort_unstable_by(|(_, _, offset1), (_, _, offset2)| offset1.cmp(offset2));
|
||||
|
||||
debug_assert!(
|
||||
meta_with_offsets.len() == N,
|
||||
"Not all fields were found in the message. Expected {} but found {}.",
|
||||
N,
|
||||
meta_with_offsets.len()
|
||||
);
|
||||
|
||||
let mut offsets = [usize::default(); N];
|
||||
let mut meta = vec![(String::default(), FieldDatatype::default()); N];
|
||||
|
||||
meta_with_offsets
|
||||
.into_iter()
|
||||
.zip(meta.iter_mut())
|
||||
.zip(offsets.iter_mut())
|
||||
.for_each(|(((name, datatype, offset), meta), meta_offset)| {
|
||||
*meta = (name, datatype);
|
||||
*meta_offset = offset;
|
||||
});
|
||||
|
||||
let point_step_size = cloud.point_step as usize;
|
||||
let cloud_length = cloud.dimensions.width as usize * cloud.dimensions.height as usize;
|
||||
if point_step_size * cloud_length != cloud.data.len() {
|
||||
return Err(MsgConversionError::DataLengthMismatch);
|
||||
}
|
||||
|
||||
let last_offset = offsets.last().expect("Dimensionality is 0.");
|
||||
|
||||
let last_meta = meta.last().expect("Dimensionality is 0.");
|
||||
let size_with_last_meta = last_offset + last_meta.1.size();
|
||||
if size_with_last_meta > point_step_size {
|
||||
return Err(MsgConversionError::DataLengthMismatch);
|
||||
}
|
||||
|
||||
let cloud_length = cloud.dimensions.width as usize * cloud.dimensions.height as usize;
|
||||
|
||||
let data = ByteBufferView::new(
|
||||
cloud.data,
|
||||
point_step_size,
|
||||
0,
|
||||
cloud_length - 1,
|
||||
offsets,
|
||||
meta,
|
||||
cloud.endian,
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
iteration: 0,
|
||||
iteration_back: cloud_length - 1,
|
||||
data,
|
||||
phantom_c: std::marker::PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize, C> PointCloudIterator<N, C>
|
||||
where
|
||||
C: Fields<N>,
|
||||
{
|
||||
#[inline]
|
||||
fn from_byte_buffer_view(data: ByteBufferView<N>) -> Self {
|
||||
Self {
|
||||
iteration: 0,
|
||||
iteration_back: data.len() - 1,
|
||||
data,
|
||||
phantom_c: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn split_at(self, point_index: usize) -> (Self, Self) {
|
||||
let (left_data, right_data) = self.data.split_at(point_index);
|
||||
(
|
||||
Self::from_byte_buffer_view(left_data),
|
||||
Self::from_byte_buffer_view(right_data),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
mod test {
|
||||
|
||||
#[test]
|
||||
fn test_double_ended_iter() {
|
||||
let cloud = vec![
|
||||
crate::points::PointXYZ {
|
||||
x: 1.0,
|
||||
y: 1.0,
|
||||
z: 1.0,
|
||||
},
|
||||
crate::points::PointXYZ {
|
||||
x: 2.0,
|
||||
y: 2.0,
|
||||
z: 2.0,
|
||||
},
|
||||
crate::points::PointXYZ {
|
||||
x: 3.0,
|
||||
y: 3.0,
|
||||
z: 3.0,
|
||||
},
|
||||
];
|
||||
|
||||
let internal_msg = crate::PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let mut iter = crate::iterator::PointCloudIterator::try_from(internal_msg).unwrap();
|
||||
let last_p = iter.next_back();
|
||||
|
||||
assert!(last_p.is_some());
|
||||
let last_p: crate::points::PointXYZ = last_p.unwrap();
|
||||
|
||||
assert_eq!(last_p.x, 3.0);
|
||||
assert_eq!(last_p.y, 3.0);
|
||||
assert_eq!(last_p.z, 3.0);
|
||||
|
||||
let first_p = iter.next();
|
||||
assert!(first_p.is_some());
|
||||
let first_p: crate::points::PointXYZ = first_p.unwrap();
|
||||
|
||||
assert_eq!(first_p.x, 1.0);
|
||||
assert_eq!(first_p.y, 1.0);
|
||||
assert_eq!(first_p.z, 1.0);
|
||||
|
||||
let last_p = iter.next_back();
|
||||
assert!(last_p.is_some());
|
||||
let last_p: crate::points::PointXYZ = last_p.unwrap();
|
||||
|
||||
assert_eq!(last_p.x, 2.0);
|
||||
assert_eq!(last_p.y, 2.0);
|
||||
assert_eq!(last_p.z, 2.0);
|
||||
|
||||
let last_p = iter.next_back();
|
||||
assert!(last_p.is_none());
|
||||
|
||||
let first_p = iter.next();
|
||||
assert!(first_p.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_split_at() {
|
||||
let cloud = vec![
|
||||
crate::points::PointXYZ {
|
||||
x: 1.0,
|
||||
y: 1.0,
|
||||
z: 1.0,
|
||||
},
|
||||
crate::points::PointXYZ {
|
||||
x: 2.0,
|
||||
y: 2.0,
|
||||
z: 2.0,
|
||||
},
|
||||
crate::points::PointXYZ {
|
||||
x: 3.0,
|
||||
y: 3.0,
|
||||
z: 3.0,
|
||||
},
|
||||
];
|
||||
|
||||
let internal_msg = crate::PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let iter = crate::iterator::PointCloudIterator::try_from(internal_msg).unwrap();
|
||||
|
||||
let (mut left, mut right) = iter.split_at(1);
|
||||
|
||||
assert_eq!(left.size_hint(), (1, Some(1)));
|
||||
assert_eq!(right.size_hint(), (2, Some(2)));
|
||||
|
||||
let first_left = left.next();
|
||||
assert!(first_left.is_some());
|
||||
let first_left: crate::points::PointXYZ = first_left.unwrap();
|
||||
|
||||
assert_eq!(first_left.x, 1.0);
|
||||
assert_eq!(first_left.y, 1.0);
|
||||
assert_eq!(first_left.z, 1.0);
|
||||
|
||||
let first_right = right.next();
|
||||
assert!(first_right.is_some());
|
||||
let first_right: crate::points::PointXYZ = first_right.unwrap();
|
||||
|
||||
assert_eq!(first_right.x, 2.0);
|
||||
assert_eq!(first_right.y, 2.0);
|
||||
assert_eq!(first_right.z, 2.0);
|
||||
|
||||
let last_right = right.next_back();
|
||||
assert!(last_right.is_some());
|
||||
|
||||
let last_right: crate::points::PointXYZ = last_right.unwrap();
|
||||
assert_eq!(last_right.x, 3.0);
|
||||
assert_eq!(last_right.y, 3.0);
|
||||
assert_eq!(last_right.z, 3.0);
|
||||
|
||||
let last_left = left.next_back();
|
||||
assert!(last_left.is_none());
|
||||
|
||||
let last_right = right.next_back();
|
||||
assert!(last_right.is_none());
|
||||
|
||||
let first_left = left.next();
|
||||
assert!(first_left.is_none());
|
||||
|
||||
let first_right = right.next();
|
||||
assert!(first_right.is_none());
|
||||
}
|
||||
}
|
||||
1466
src/lib.rs
1466
src/lib.rs
File diff suppressed because it is too large
Load Diff
422
src/pcl_utils.rs
422
src/pcl_utils.rs
|
|
@ -1,422 +0,0 @@
|
|||
use crate::{MetaNames, Point, PointConvertible};
|
||||
|
||||
/// Pack an RGB color into a single f32 value as used in ROS with PCL for RViz usage.
|
||||
#[inline]
|
||||
fn pack_rgb(r: u8, g: u8, b: u8) -> f32 {
|
||||
let packed = ((r as u32) << 16) + ((g as u32) << 8) + (b as u32);
|
||||
f32::from_bits(packed)
|
||||
}
|
||||
|
||||
/// Unpack an RGB color from a single f32 value as used in ROS with PCL for RViz usage.
|
||||
#[inline]
|
||||
fn unpack_rgb(rgb: f32) -> [u8; 3] {
|
||||
let packed: u32 = rgb.to_bits();
|
||||
let r: u8 = (packed >> 16) as u8;
|
||||
let g: u8 = (packed >> 8) as u8;
|
||||
let b: u8 = packed as u8;
|
||||
[r, g, b]
|
||||
}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates.
|
||||
#[derive(Clone, Debug, PartialEq, Copy)]
|
||||
pub struct PointXYZ {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
}
|
||||
|
||||
impl From<Point<f32, 3, 0>> for PointXYZ {
|
||||
fn from(point: Point<f32, 3, 0>) -> Self {
|
||||
Self {
|
||||
x: point.coords[0],
|
||||
y: point.coords[1],
|
||||
z: point.coords[2],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZ> for Point<f32, 3, 0> {
|
||||
fn from(point: PointXYZ) -> Self {
|
||||
Point {
|
||||
coords: [point.x, point.y, point.z],
|
||||
meta: [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaNames<0> for PointXYZ {
|
||||
fn meta_names() -> [&'static str; 0] {
|
||||
[]
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<f32, { std::mem::size_of::<f32>() }, 3, 0> for PointXYZ {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and an intensity value.
|
||||
#[derive(Clone, Debug, PartialEq, Copy)]
|
||||
pub struct PointXYZI {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub intensity: f32,
|
||||
}
|
||||
|
||||
impl From<PointXYZI> for Point<f32, 3, 1> {
|
||||
fn from(point: PointXYZI) -> Self {
|
||||
Point {
|
||||
coords: [point.x, point.y, point.z],
|
||||
meta: [point.intensity.into()],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Point<f32, 3, 1>> for PointXYZI {
|
||||
fn from(point: Point<f32, 3, 1>) -> Self {
|
||||
Self {
|
||||
x: point.coords[0],
|
||||
y: point.coords[1],
|
||||
z: point.coords[2],
|
||||
intensity: point.meta[0].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaNames<1> for PointXYZI {
|
||||
fn meta_names() -> [&'static str; 1] {
|
||||
["intensity"]
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<f32, { std::mem::size_of::<f32>() }, 3, 1> for PointXYZI {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and an RGB color value.
|
||||
#[derive(Clone, Debug, PartialEq, Copy)]
|
||||
pub struct PointXYZRGB {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
}
|
||||
|
||||
impl From<Point<f32, 3, 1>> for PointXYZRGB {
|
||||
fn from(point: Point<f32, 3, 1>) -> Self {
|
||||
let rgb = point.meta[0].get::<f32>();
|
||||
let rgb_unpacked = unpack_rgb(rgb);
|
||||
Self {
|
||||
x: point.coords[0],
|
||||
y: point.coords[1],
|
||||
z: point.coords[2],
|
||||
r: rgb_unpacked[0],
|
||||
g: rgb_unpacked[1],
|
||||
b: rgb_unpacked[2],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZRGB> for Point<f32, 3, 1> {
|
||||
fn from(point: PointXYZRGB) -> Self {
|
||||
Point {
|
||||
coords: [point.x, point.y, point.z],
|
||||
meta: [pack_rgb(point.r, point.g, point.b).into()],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaNames<1> for PointXYZRGB {
|
||||
fn meta_names() -> [&'static str; 1] {
|
||||
["rgb"]
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<f32, { std::mem::size_of::<f32>() }, 3, 1> for PointXYZRGB {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and an RGBA color value.
|
||||
/// The alpha channel is commonly used as padding but this crate uses every channel and no padding.
|
||||
#[derive(Clone, Debug, PartialEq, Copy)]
|
||||
pub struct PointXYZRGBA {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
pub a: u8,
|
||||
}
|
||||
|
||||
impl From<Point<f32, 3, 2>> for PointXYZRGBA {
|
||||
fn from(point: Point<f32, 3, 2>) -> Self {
|
||||
let rgb = point.meta[0].get::<f32>();
|
||||
let rgb_unpacked = unpack_rgb(rgb);
|
||||
Self {
|
||||
x: point.coords[0],
|
||||
y: point.coords[1],
|
||||
z: point.coords[2],
|
||||
r: rgb_unpacked[0],
|
||||
g: rgb_unpacked[1],
|
||||
b: rgb_unpacked[2],
|
||||
a: point.meta[1].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZRGBA> for Point<f32, 3, 2> {
|
||||
fn from(point: PointXYZRGBA) -> Self {
|
||||
let rgb = pack_rgb(point.r, point.g, point.b);
|
||||
Point {
|
||||
coords: [point.x, point.y, point.z],
|
||||
meta: [rgb.into(), point.a.into()],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaNames<2> for PointXYZRGBA {
|
||||
fn meta_names() -> [&'static str; 2] {
|
||||
["rgb", "a"]
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<f32, { std::mem::size_of::<f32>() }, 3, 2> for PointXYZRGBA {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates, an RGB color value and a normal vector.
|
||||
#[derive(Clone, Debug, PartialEq, Copy)]
|
||||
pub struct PointXYZRGBNormal {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
pub normal_x: f32,
|
||||
pub normal_y: f32,
|
||||
pub normal_z: f32,
|
||||
}
|
||||
|
||||
impl From<Point<f32, 3, 4>> for PointXYZRGBNormal {
|
||||
fn from(point: Point<f32, 3, 4>) -> Self {
|
||||
let rgb = point.meta[0].get::<f32>();
|
||||
let rgb_unpacked = unpack_rgb(rgb);
|
||||
Self {
|
||||
x: point.coords[0],
|
||||
y: point.coords[1],
|
||||
z: point.coords[2],
|
||||
r: rgb_unpacked[0],
|
||||
g: rgb_unpacked[1],
|
||||
b: rgb_unpacked[2],
|
||||
normal_x: point.meta[1].get(),
|
||||
normal_y: point.meta[2].get(),
|
||||
normal_z: point.meta[3].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZRGBNormal> for Point<f32, 3, 4> {
|
||||
fn from(point: PointXYZRGBNormal) -> Self {
|
||||
let rgb = pack_rgb(point.r, point.g, point.b);
|
||||
Point {
|
||||
coords: [point.x, point.y, point.z],
|
||||
meta: [
|
||||
rgb.into(),
|
||||
point.normal_x.into(),
|
||||
point.normal_y.into(),
|
||||
point.normal_z.into(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaNames<4> for PointXYZRGBNormal {
|
||||
fn meta_names() -> [&'static str; 4] {
|
||||
["rgb", "normal_x", "normal_y", "normal_z"]
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<f32, { std::mem::size_of::<f32>() }, 3, 4> for PointXYZRGBNormal {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates, an intensity value and a normal vector.
|
||||
#[derive(Clone, Debug, PartialEq, Copy)]
|
||||
pub struct PointXYZINormal {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub intensity: f32,
|
||||
pub normal_x: f32,
|
||||
pub normal_y: f32,
|
||||
pub normal_z: f32,
|
||||
}
|
||||
|
||||
impl From<PointXYZINormal> for Point<f32, 3, 4> {
|
||||
fn from(point: PointXYZINormal) -> Self {
|
||||
Point {
|
||||
coords: [point.x, point.y, point.z],
|
||||
meta: [
|
||||
point.intensity.into(),
|
||||
point.normal_x.into(),
|
||||
point.normal_y.into(),
|
||||
point.normal_z.into(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Point<f32, 3, 4>> for PointXYZINormal {
|
||||
fn from(point: Point<f32, 3, 4>) -> Self {
|
||||
Self {
|
||||
x: point.coords[0],
|
||||
y: point.coords[1],
|
||||
z: point.coords[2],
|
||||
intensity: point.meta[0].get(),
|
||||
normal_x: point.meta[1].get(),
|
||||
normal_y: point.meta[2].get(),
|
||||
normal_z: point.meta[3].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaNames<4> for PointXYZINormal {
|
||||
fn meta_names() -> [&'static str; 4] {
|
||||
["intensity", "normal_x", "normal_y", "normal_z"]
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<f32, { std::mem::size_of::<f32>() }, 3, 4> for PointXYZINormal {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and a label.
|
||||
#[derive(Clone, Debug, PartialEq, Copy)]
|
||||
pub struct PointXYZL {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub label: u32,
|
||||
}
|
||||
|
||||
impl From<Point<f32, 3, 1>> for PointXYZL {
|
||||
fn from(point: Point<f32, 3, 1>) -> Self {
|
||||
Self {
|
||||
x: point.coords[0],
|
||||
y: point.coords[1],
|
||||
z: point.coords[2],
|
||||
label: point.meta[0].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZL> for Point<f32, 3, 1> {
|
||||
fn from(point: PointXYZL) -> Self {
|
||||
Point {
|
||||
coords: [point.x, point.y, point.z],
|
||||
meta: [point.label.into()],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaNames<1> for PointXYZL {
|
||||
fn meta_names() -> [&'static str; 1] {
|
||||
["label"]
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<f32, { std::mem::size_of::<f32>() }, 3, 1> for PointXYZL {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and a label.
|
||||
#[derive(Clone, Debug, PartialEq, Copy)]
|
||||
pub struct PointXYZRGBL {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
pub label: u32,
|
||||
}
|
||||
|
||||
impl From<Point<f32, 3, 2>> for PointXYZRGBL {
|
||||
fn from(point: Point<f32, 3, 2>) -> Self {
|
||||
let rgb = point.meta[0].get::<f32>();
|
||||
let rgb_unpacked = unpack_rgb(rgb);
|
||||
Self {
|
||||
x: point.coords[0],
|
||||
y: point.coords[1],
|
||||
z: point.coords[2],
|
||||
r: rgb_unpacked[0],
|
||||
g: rgb_unpacked[1],
|
||||
b: rgb_unpacked[2],
|
||||
label: point.meta[1].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZRGBL> for Point<f32, 3, 2> {
|
||||
fn from(point: PointXYZRGBL) -> Self {
|
||||
Point {
|
||||
coords: [point.x, point.y, point.z],
|
||||
meta: [
|
||||
pack_rgb(point.r, point.g, point.b).into(),
|
||||
point.label.into(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaNames<2> for PointXYZRGBL {
|
||||
fn meta_names() -> [&'static str; 2] {
|
||||
["rgb", "label"]
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<f32, { std::mem::size_of::<f32>() }, 3, 2> for PointXYZRGBL {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and a normal vector.
|
||||
#[derive(Clone, Debug, PartialEq, Copy)]
|
||||
pub struct PointXYZNormal {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub normal_x: f32,
|
||||
pub normal_y: f32,
|
||||
pub normal_z: f32,
|
||||
}
|
||||
|
||||
impl From<Point<f32, 3, 3>> for PointXYZNormal {
|
||||
fn from(point: Point<f32, 3, 3>) -> Self {
|
||||
Self {
|
||||
x: point.coords[0],
|
||||
y: point.coords[1],
|
||||
z: point.coords[2],
|
||||
normal_x: point.meta[0].get(),
|
||||
normal_y: point.meta[1].get(),
|
||||
normal_z: point.meta[2].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZNormal> for Point<f32, 3, 3> {
|
||||
fn from(point: PointXYZNormal) -> Self {
|
||||
Point {
|
||||
coords: [point.x, point.y, point.z],
|
||||
meta: [
|
||||
point.normal_x.into(),
|
||||
point.normal_y.into(),
|
||||
point.normal_z.into(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaNames<3> for PointXYZNormal {
|
||||
fn meta_names() -> [&'static str; 3] {
|
||||
["normal_x", "normal_y", "normal_z"]
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<f32, { std::mem::size_of::<f32>() }, 3, 3> for PointXYZNormal {}
|
||||
|
|
@ -0,0 +1,746 @@
|
|||
//! Predefined point types commonly used in ROS.
|
||||
use crate::{Fields, PointConvertible, RPCL2Point};
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
use type_layout::TypeLayout;
|
||||
|
||||
/// A packed RGB color encoding as used in ROS tools.
|
||||
#[derive(Clone, Copy)]
|
||||
#[repr(C)]
|
||||
pub union RGB {
|
||||
packed: f32,
|
||||
unpacked: [u8; 4], // 1 byte padding
|
||||
}
|
||||
|
||||
unsafe impl Send for RGB {}
|
||||
unsafe impl Sync for RGB {}
|
||||
|
||||
impl Default for RGB {
|
||||
fn default() -> Self {
|
||||
Self { packed: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for RGB {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.r() == other.r() && self.g() == other.g() && self.b() == other.b()
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Display for RGB {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "#{:02X}{:02X}{:02X}", self.r(), self.g(), self.b())
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for RGB {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RGB")
|
||||
.field("r", &self.r())
|
||||
.field("g", &self.g())
|
||||
.field("b", &self.b())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl RGB {
|
||||
pub fn new(r: u8, g: u8, b: u8) -> Self {
|
||||
Self {
|
||||
unpacked: [b, g, r, 0],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_from_packed_f32(packed: f32) -> Self {
|
||||
Self { packed }
|
||||
}
|
||||
|
||||
pub fn new_from_packed(packed: u32) -> Self {
|
||||
Self::new_from_packed_f32(f32::from_bits(packed))
|
||||
}
|
||||
|
||||
pub fn raw(&self) -> f32 {
|
||||
unsafe { self.packed }
|
||||
}
|
||||
|
||||
pub fn r(&self) -> u8 {
|
||||
unsafe { self.unpacked[2] }
|
||||
}
|
||||
|
||||
pub fn g(&self) -> u8 {
|
||||
unsafe { self.unpacked[1] }
|
||||
}
|
||||
|
||||
pub fn b(&self) -> u8 {
|
||||
unsafe { self.unpacked[0] }
|
||||
}
|
||||
|
||||
pub fn set_r(&mut self, r: u8) {
|
||||
unsafe { self.unpacked[2] = r }
|
||||
}
|
||||
|
||||
pub fn set_g(&mut self, g: u8) {
|
||||
unsafe { self.unpacked[1] = g }
|
||||
}
|
||||
|
||||
pub fn set_b(&mut self, b: u8) {
|
||||
unsafe { self.unpacked[0] = b }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RGB> for f32 {
|
||||
fn from(rgb: RGB) -> Self {
|
||||
unsafe { rgb.packed }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f32> for RGB {
|
||||
fn from(packed: f32) -> Self {
|
||||
RGB::new_from_packed_f32(packed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates.
|
||||
#[derive(Clone, Debug, PartialEq, Copy, Default)]
|
||||
#[cfg_attr(feature = "derive", derive(TypeLayout))]
|
||||
#[repr(C)]
|
||||
pub struct PointXYZ {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
impl From<nalgebra::Point3<f32>> for PointXYZ {
|
||||
fn from(point: nalgebra::Point3<f32>) -> Self {
|
||||
Self {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
z: point.z,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
impl From<PointXYZ> for nalgebra::Point3<f32> {
|
||||
fn from(point: PointXYZ) -> Self {
|
||||
nalgebra::Point3::new(point.x, point.y, point.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl PointXYZ {
|
||||
pub fn new(x: f32, y: f32, z: f32) -> Self {
|
||||
Self { x, y, z }
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
pub fn xyz(&self) -> nalgebra::Point3<f32> {
|
||||
nalgebra::Point3::new(self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for PointXYZ {}
|
||||
unsafe impl Sync for PointXYZ {}
|
||||
|
||||
impl Fields<3> for PointXYZ {
|
||||
fn field_names_ordered() -> [&'static str; 3] {
|
||||
["x", "y", "z"]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<3>> for PointXYZ {
|
||||
fn from(point: RPCL2Point<3>) -> Self {
|
||||
Self::new(point[0].get(), point[1].get(), point[2].get())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZ> for RPCL2Point<3> {
|
||||
fn from(point: PointXYZ) -> Self {
|
||||
[point.x.into(), point.y.into(), point.z.into()].into()
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<3> for PointXYZ {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and an intensity value.
|
||||
#[derive(Clone, Debug, PartialEq, Copy, Default)]
|
||||
#[cfg_attr(feature = "derive", derive(TypeLayout))]
|
||||
#[repr(C)]
|
||||
pub struct PointXYZI {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub intensity: f32,
|
||||
}
|
||||
|
||||
impl PointXYZI {
|
||||
pub fn new(x: f32, y: f32, z: f32, intensity: f32) -> Self {
|
||||
Self { x, y, z, intensity }
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
pub fn xyz(&self) -> nalgebra::Point3<f32> {
|
||||
nalgebra::Point3::new(self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for PointXYZI {}
|
||||
unsafe impl Sync for PointXYZI {}
|
||||
|
||||
impl Fields<4> for PointXYZI {
|
||||
fn field_names_ordered() -> [&'static str; 4] {
|
||||
["x", "y", "z", "intensity"]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<4>> for PointXYZI {
|
||||
fn from(point: RPCL2Point<4>) -> Self {
|
||||
Self::new(
|
||||
point[0].get(),
|
||||
point[1].get(),
|
||||
point[2].get(),
|
||||
point[3].get(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZI> for RPCL2Point<4> {
|
||||
fn from(point: PointXYZI) -> Self {
|
||||
[
|
||||
point.x.into(),
|
||||
point.y.into(),
|
||||
point.z.into(),
|
||||
point.intensity.into(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<4> for PointXYZI {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and a label.
|
||||
#[derive(Clone, Debug, PartialEq, Copy, Default)]
|
||||
#[cfg_attr(feature = "derive", derive(TypeLayout))]
|
||||
#[repr(C)]
|
||||
pub struct PointXYZL {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub label: u32,
|
||||
}
|
||||
|
||||
impl PointXYZL {
|
||||
pub fn new(x: f32, y: f32, z: f32, label: u32) -> Self {
|
||||
Self { x, y, z, label }
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
pub fn xyz(&self) -> nalgebra::Point3<f32> {
|
||||
nalgebra::Point3::new(self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for PointXYZL {}
|
||||
unsafe impl Sync for PointXYZL {}
|
||||
|
||||
impl Fields<4> for PointXYZL {
|
||||
fn field_names_ordered() -> [&'static str; 4] {
|
||||
["x", "y", "z", "label"]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<4>> for PointXYZL {
|
||||
fn from(point: RPCL2Point<4>) -> Self {
|
||||
Self::new(
|
||||
point[0].get(),
|
||||
point[1].get(),
|
||||
point[2].get(),
|
||||
point[3].get(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZL> for RPCL2Point<4> {
|
||||
fn from(point: PointXYZL) -> Self {
|
||||
[
|
||||
point.x.into(),
|
||||
point.y.into(),
|
||||
point.z.into(),
|
||||
point.label.into(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<4> for PointXYZL {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and an RGB color value.
|
||||
#[derive(Clone, Debug, PartialEq, Copy, Default)]
|
||||
#[cfg_attr(feature = "derive", derive(TypeLayout))]
|
||||
#[repr(C)]
|
||||
pub struct PointXYZRGB {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub rgb: RGB,
|
||||
}
|
||||
|
||||
impl PointXYZRGB {
|
||||
pub fn new(x: f32, y: f32, z: f32, r: u8, g: u8, b: u8) -> Self {
|
||||
let rgb = RGB::new(r, g, b);
|
||||
Self { x, y, z, rgb }
|
||||
}
|
||||
|
||||
pub fn r(&self) -> u8 {
|
||||
self.rgb.r()
|
||||
}
|
||||
|
||||
pub fn g(&self) -> u8 {
|
||||
self.rgb.g()
|
||||
}
|
||||
|
||||
pub fn b(&self) -> u8 {
|
||||
self.rgb.b()
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
pub fn xyz(&self) -> nalgebra::Point3<f32> {
|
||||
nalgebra::Point3::new(self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for PointXYZRGB {}
|
||||
unsafe impl Sync for PointXYZRGB {}
|
||||
|
||||
impl Fields<4> for PointXYZRGB {
|
||||
fn field_names_ordered() -> [&'static str; 4] {
|
||||
["x", "y", "z", "rgb"]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<4>> for PointXYZRGB {
|
||||
fn from(point: RPCL2Point<4>) -> Self {
|
||||
Self {
|
||||
x: point[0].get(),
|
||||
y: point[1].get(),
|
||||
z: point[2].get(),
|
||||
rgb: point[3].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZRGB> for RPCL2Point<4> {
|
||||
fn from(point: PointXYZRGB) -> Self {
|
||||
[
|
||||
point.x.into(),
|
||||
point.y.into(),
|
||||
point.z.into(),
|
||||
f32::from(point.rgb).into(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<4> for PointXYZRGB {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and an RGBA color value.
|
||||
/// The alpha channel is commonly used as padding but this crate uses every channel and no padding.
|
||||
#[derive(Clone, Debug, PartialEq, Copy, Default)]
|
||||
#[cfg_attr(feature = "derive", derive(TypeLayout))]
|
||||
#[repr(C)]
|
||||
pub struct PointXYZRGBA {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub rgb: RGB,
|
||||
pub a: u8,
|
||||
}
|
||||
|
||||
impl PointXYZRGBA {
|
||||
pub fn new(x: f32, y: f32, z: f32, r: u8, g: u8, b: u8, a: u8) -> Self {
|
||||
let rgb = RGB::new(r, g, b);
|
||||
Self { x, y, z, rgb, a }
|
||||
}
|
||||
|
||||
pub fn r(&self) -> u8 {
|
||||
self.rgb.r()
|
||||
}
|
||||
|
||||
pub fn g(&self) -> u8 {
|
||||
self.rgb.g()
|
||||
}
|
||||
|
||||
pub fn b(&self) -> u8 {
|
||||
self.rgb.b()
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
pub fn xyz(&self) -> nalgebra::Point3<f32> {
|
||||
nalgebra::Point3::new(self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for PointXYZRGBA {}
|
||||
unsafe impl Sync for PointXYZRGBA {}
|
||||
|
||||
impl Fields<5> for PointXYZRGBA {
|
||||
fn field_names_ordered() -> [&'static str; 5] {
|
||||
["x", "y", "z", "rgb", "a"]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<5>> for PointXYZRGBA {
|
||||
fn from(point: RPCL2Point<5>) -> Self {
|
||||
Self {
|
||||
x: point[0].get(),
|
||||
y: point[1].get(),
|
||||
z: point[2].get(),
|
||||
rgb: point[3].get::<f32>().into(),
|
||||
a: point[4].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZRGBA> for RPCL2Point<5> {
|
||||
fn from(point: PointXYZRGBA) -> Self {
|
||||
[
|
||||
point.x.into(),
|
||||
point.y.into(),
|
||||
point.z.into(),
|
||||
f32::from(point.rgb).into(),
|
||||
point.a.into(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<5> for PointXYZRGBA {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates, an RGB color value and a normal vector.
|
||||
#[derive(Clone, Debug, PartialEq, Copy, Default)]
|
||||
#[cfg_attr(feature = "derive", derive(TypeLayout))]
|
||||
#[repr(C)]
|
||||
pub struct PointXYZRGBNormal {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub rgb: RGB,
|
||||
pub normal_x: f32,
|
||||
pub normal_y: f32,
|
||||
pub normal_z: f32,
|
||||
}
|
||||
|
||||
impl PointXYZRGBNormal {
|
||||
pub fn new(
|
||||
x: f32,
|
||||
y: f32,
|
||||
z: f32,
|
||||
rgb: RGB,
|
||||
normal_x: f32,
|
||||
normal_y: f32,
|
||||
normal_z: f32,
|
||||
) -> Self {
|
||||
Self {
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
rgb,
|
||||
normal_x,
|
||||
normal_y,
|
||||
normal_z,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn r(&self) -> u8 {
|
||||
self.rgb.r()
|
||||
}
|
||||
|
||||
pub fn g(&self) -> u8 {
|
||||
self.rgb.g()
|
||||
}
|
||||
|
||||
pub fn b(&self) -> u8 {
|
||||
self.rgb.b()
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
pub fn xyz(&self) -> nalgebra::Point3<f32> {
|
||||
nalgebra::Point3::new(self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for PointXYZRGBNormal {}
|
||||
unsafe impl Sync for PointXYZRGBNormal {}
|
||||
|
||||
impl Fields<7> for PointXYZRGBNormal {
|
||||
fn field_names_ordered() -> [&'static str; 7] {
|
||||
["x", "y", "z", "rgb", "normal_x", "normal_y", "normal_z"]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<7>> for PointXYZRGBNormal {
|
||||
fn from(point: RPCL2Point<7>) -> Self {
|
||||
Self {
|
||||
x: point[0].get(),
|
||||
y: point[1].get(),
|
||||
z: point[2].get(),
|
||||
rgb: point[3].get::<f32>().into(),
|
||||
normal_x: point[4].get(),
|
||||
normal_y: point[5].get(),
|
||||
normal_z: point[6].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZRGBNormal> for RPCL2Point<7> {
|
||||
fn from(point: PointXYZRGBNormal) -> Self {
|
||||
[
|
||||
point.x.into(),
|
||||
point.y.into(),
|
||||
point.z.into(),
|
||||
f32::from(point.rgb).into(),
|
||||
point.normal_x.into(),
|
||||
point.normal_y.into(),
|
||||
point.normal_z.into(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<7> for PointXYZRGBNormal {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates, an intensity value and a normal vector.
|
||||
#[derive(Clone, Debug, PartialEq, Copy, Default)]
|
||||
#[cfg_attr(feature = "derive", derive(TypeLayout))]
|
||||
#[repr(C)]
|
||||
pub struct PointXYZINormal {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub intensity: f32,
|
||||
pub normal_x: f32,
|
||||
pub normal_y: f32,
|
||||
pub normal_z: f32,
|
||||
}
|
||||
|
||||
impl PointXYZINormal {
|
||||
pub fn new(
|
||||
x: f32,
|
||||
y: f32,
|
||||
z: f32,
|
||||
intensity: f32,
|
||||
normal_x: f32,
|
||||
normal_y: f32,
|
||||
normal_z: f32,
|
||||
) -> Self {
|
||||
Self {
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
intensity,
|
||||
normal_x,
|
||||
normal_y,
|
||||
normal_z,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
pub fn xyz(&self) -> nalgebra::Point3<f32> {
|
||||
nalgebra::Point3::new(self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for PointXYZINormal {}
|
||||
unsafe impl Sync for PointXYZINormal {}
|
||||
|
||||
impl Fields<7> for PointXYZINormal {
|
||||
fn field_names_ordered() -> [&'static str; 7] {
|
||||
["x", "y", "z", "i", "normal_x", "normal_y", "normal_z"]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<7>> for PointXYZINormal {
|
||||
fn from(point: RPCL2Point<7>) -> Self {
|
||||
Self::new(
|
||||
point[0].get(),
|
||||
point[1].get(),
|
||||
point[2].get(),
|
||||
point[3].get(),
|
||||
point[4].get(),
|
||||
point[5].get(),
|
||||
point[6].get(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZINormal> for RPCL2Point<7> {
|
||||
fn from(point: PointXYZINormal) -> Self {
|
||||
[
|
||||
point.x.into(),
|
||||
point.y.into(),
|
||||
point.z.into(),
|
||||
point.intensity.into(),
|
||||
point.normal_x.into(),
|
||||
point.normal_y.into(),
|
||||
point.normal_z.into(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<7> for PointXYZINormal {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and a label.
|
||||
#[derive(Clone, Debug, PartialEq, Copy, Default)]
|
||||
#[cfg_attr(feature = "derive", derive(TypeLayout))]
|
||||
#[repr(C)]
|
||||
pub struct PointXYZRGBL {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub rgb: RGB,
|
||||
pub label: u32,
|
||||
}
|
||||
|
||||
unsafe impl Send for PointXYZRGBL {}
|
||||
unsafe impl Sync for PointXYZRGBL {}
|
||||
|
||||
impl PointXYZRGBL {
|
||||
pub fn new(x: f32, y: f32, z: f32, r: u8, g: u8, b: u8, label: u32) -> Self {
|
||||
let rgb = RGB::new(r, g, b);
|
||||
Self {
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
rgb,
|
||||
label,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn r(&self) -> u8 {
|
||||
self.rgb.r()
|
||||
}
|
||||
|
||||
pub fn g(&self) -> u8 {
|
||||
self.rgb.g()
|
||||
}
|
||||
|
||||
pub fn b(&self) -> u8 {
|
||||
self.rgb.b()
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
pub fn xyz(&self) -> nalgebra::Point3<f32> {
|
||||
nalgebra::Point3::new(self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Fields<5> for PointXYZRGBL {
|
||||
fn field_names_ordered() -> [&'static str; 5] {
|
||||
["x", "y", "z", "rgb", "label"]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<5>> for PointXYZRGBL {
|
||||
fn from(point: RPCL2Point<5>) -> Self {
|
||||
Self {
|
||||
x: point[0].get(),
|
||||
y: point[1].get(),
|
||||
z: point[2].get(),
|
||||
rgb: point[3].get::<f32>().into(),
|
||||
label: point[4].get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZRGBL> for RPCL2Point<5> {
|
||||
fn from(point: PointXYZRGBL) -> Self {
|
||||
[
|
||||
point.x.into(),
|
||||
point.y.into(),
|
||||
point.z.into(),
|
||||
f32::from(point.rgb).into(),
|
||||
point.label.into(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<5> for PointXYZRGBL {}
|
||||
|
||||
/// Predefined point type commonly used in ROS with PCL.
|
||||
/// This is a 3D point with x, y, z coordinates and a normal vector.
|
||||
#[derive(Clone, Debug, PartialEq, Copy, Default)]
|
||||
#[cfg_attr(feature = "derive", derive(TypeLayout))]
|
||||
#[repr(C)]
|
||||
pub struct PointXYZNormal {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
pub normal_x: f32,
|
||||
pub normal_y: f32,
|
||||
pub normal_z: f32,
|
||||
}
|
||||
|
||||
impl PointXYZNormal {
|
||||
pub fn new(x: f32, y: f32, z: f32, normal_x: f32, normal_y: f32, normal_z: f32) -> Self {
|
||||
Self {
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
normal_x,
|
||||
normal_y,
|
||||
normal_z,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "nalgebra")]
|
||||
pub fn xyz(&self) -> nalgebra::Point3<f32> {
|
||||
nalgebra::Point3::new(self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for PointXYZNormal {}
|
||||
unsafe impl Sync for PointXYZNormal {}
|
||||
|
||||
impl Fields<6> for PointXYZNormal {
|
||||
fn field_names_ordered() -> [&'static str; 6] {
|
||||
["x", "y", "z", "normal_x", "normal_y", "normal_z"]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RPCL2Point<6>> for PointXYZNormal {
|
||||
fn from(point: RPCL2Point<6>) -> Self {
|
||||
Self::new(
|
||||
point[0].get(),
|
||||
point[1].get(),
|
||||
point[2].get(),
|
||||
point[3].get(),
|
||||
point[4].get(),
|
||||
point[5].get(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PointXYZNormal> for RPCL2Point<6> {
|
||||
fn from(point: PointXYZNormal) -> Self {
|
||||
[
|
||||
point.x.into(),
|
||||
point.y.into(),
|
||||
point.z.into(),
|
||||
point.normal_x.into(),
|
||||
point.normal_y.into(),
|
||||
point.normal_z.into(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl PointConvertible<6> for PointXYZNormal {}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
//! Commonly used types and traits for predefined and custom point conversions.
|
||||
pub use crate::{
|
||||
FieldDatatype, Fields, FromBytes, GetFieldDatatype, MsgConversionError, PointCloud2Msg,
|
||||
PointConvertible, PointDataBuffer, RPCL2Point,
|
||||
};
|
||||
|
||||
pub use crate::points::*;
|
||||
pub use crate::ros::*;
|
||||
|
||||
#[cfg(feature = "rayon")]
|
||||
pub use rayon::prelude::*;
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
pub use type_layout::TypeLayout;
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
pub use rpcl2_derive::*;
|
||||
422
src/reader.rs
422
src/reader.rs
|
|
@ -1,422 +0,0 @@
|
|||
use crate::{
|
||||
pcl_utils::*,
|
||||
Point,
|
||||
PointCloud2Msg,
|
||||
PointConvertible,
|
||||
ConversionError,
|
||||
MetaNames,
|
||||
PointMeta,
|
||||
convert::{
|
||||
FromBytes,
|
||||
FieldDatatype,
|
||||
load_loadable,
|
||||
Endianness,
|
||||
check_coord,
|
||||
},
|
||||
};
|
||||
|
||||
/// Convenience type for a Reader that reads coordinates as f32. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type ReaderF32<const DIM: usize, const METADIM: usize, C> =
|
||||
Reader<f32, { std::mem::size_of::<f32>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Reader that reads coordinates as f64. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type ReaderF64<const DIM: usize, const METADIM: usize, C> =
|
||||
Reader<f64, { std::mem::size_of::<f64>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Reader that reads coordinates as i8. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type ReaderI8<const DIM: usize, const METADIM: usize, C> =
|
||||
Reader<i8, { std::mem::size_of::<i8>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Reader that reads coordinates as i16. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type ReaderI16<const DIM: usize, const METADIM: usize, C> =
|
||||
Reader<i16, { std::mem::size_of::<i16>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Reader that reads coordinates as i32. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type ReaderI32<const DIM: usize, const METADIM: usize, C> =
|
||||
Reader<i32, { std::mem::size_of::<i32>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Reader that reads coordinates as u8. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type ReaderU8<const DIM: usize, const METADIM: usize, C> =
|
||||
Reader<u8, { std::mem::size_of::<u8>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Reader that reads coordinates as u16. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type ReaderU16<const DIM: usize, const METADIM: usize, C> =
|
||||
Reader<u16, { std::mem::size_of::<u16>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Reader that reads coordinates as u32. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type ReaderU32<const DIM: usize, const METADIM: usize, C> =
|
||||
Reader<u32, { std::mem::size_of::<u32>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Provides the message as an Iterator over xyz coordinates (see `PointXYZ`).
|
||||
/// Every additional meta data is ignored.
|
||||
pub type ReaderXYZ = ReaderF32<3, 0, PointXYZ>;
|
||||
|
||||
/// Provides the message as an Iterator over xyz coordinates and intensity (see `PointXYZI`).
|
||||
/// Every additional meta data is ignored.
|
||||
pub type ReaderXYZI = ReaderF32<3, 1, PointXYZI>;
|
||||
|
||||
/// Provides the message as an Iterator over xyz coordinates and normal (see `PointXYZNormal`).
|
||||
/// Every additional meta data is ignored.
|
||||
pub type ReaderXYZNormal = ReaderF32<3, 3, PointXYZNormal>;
|
||||
|
||||
/// Provides the message as an Iterator over xyz coordinates and unpacked rgb (see `PointXYZRGB`).
|
||||
/// Inside the message, the rgb field gets packed into a single u32 which is ROS standard.
|
||||
/// Every additional meta data is ignored.
|
||||
pub type ReaderXYZRGB = ReaderF32<3, 1, PointXYZRGB>;
|
||||
|
||||
/// Provides the message as an Iterator over xyz coordinates and unpacked rgb and intensity (see `PointXYZRGBL`).
|
||||
/// Inside the message, the rgb field gets packed into a single u32 which is ROS standard.
|
||||
/// Every additional meta data is ignored.
|
||||
pub type ReaderXYZRGBL = ReaderF32<3, 2, PointXYZRGBL>;
|
||||
|
||||
/// Provides the message as an Iterator over xyz coordinates and unpacked rgb with additional alpha channel (see `PointXYZRGBA`).
|
||||
/// Inside the message, the rgb field gets packed into a single u32 which is ROS standard.
|
||||
/// Every additional meta data is ignored.
|
||||
pub type ReaderXYZRGBA = ReaderF32<3, 2, PointXYZRGBA>;
|
||||
|
||||
/// Provides the message as an Iterator over xyz coordinates and normal and unpacked rgb (see `PointXYZRGBNormal`).
|
||||
/// Inside the message, the rgb field gets packed into a single u32 which is ROS standard.
|
||||
/// Every additional meta data is ignored.
|
||||
pub type ReaderXYZRGBNormal = ReaderF32<3, 4, PointXYZRGBNormal>;
|
||||
|
||||
/// Provides the message as an Iterator over xyz coordinates and intensity and normal (see `PointXYZINormal`).
|
||||
/// Every additional meta data is ignored.
|
||||
pub type ReaderXYZINormal = ReaderF32<3, 4, PointXYZINormal>;
|
||||
|
||||
/// Provides the message as an Iterator over xyz coordinates and intensity with additional label (see `PointXYZL`).
|
||||
/// Every additional meta data is ignored.
|
||||
/// The label is typically used for semantic segmentation.
|
||||
pub type ReaderXYZL = ReaderF32<3, 1, PointXYZL>;
|
||||
|
||||
/// The Reader provides a an iterator abstraction of the PointCloud2Msg.
|
||||
///
|
||||
/// The iterator is defined at compile time, so the point has to be described via template arguments.
|
||||
///
|
||||
/// # Predefined Readers
|
||||
/// For the most common use cases, there are already predefined types. Examples are `ReaderXYZ` for xyz coordinates or `ReaderXYZI` for xyz coordinates and intensity.
|
||||
///
|
||||
/// When using within a ROS node, the PointCloud2 created by the ROS crate must be converted first.
|
||||
/// The cost of this operation is low, as it mostly moves ownership without iterating over the point data.
|
||||
///
|
||||
/// ROS1 with rosrust:
|
||||
/// let msg: rosrust_msg::sensor_msgs::PointCloud2; // inside the callback
|
||||
/// let converted: ros_pointcloud2::PointCloud2Msg = msg.into();
|
||||
///
|
||||
/// ROS2 with r2r:
|
||||
/// let msg: r2r::sensor_msgs::msg::PointCloud2 = internal_msg.into();
|
||||
/// let converted: ros_pointcloud2::PointCloud2Msg = msg.into();
|
||||
///
|
||||
/// ros_pointcloud2 supports r2r, ros2_rust and rosrust as conversion targets out of the box via feature flags.
|
||||
///
|
||||
/// ## Example
|
||||
/// ```
|
||||
/// use ros_pointcloud2::{
|
||||
/// pcl_utils::PointXYZ, reader::ReaderXYZ, writer::WriterXYZ, PointCloud2Msg,
|
||||
/// };
|
||||
///
|
||||
///
|
||||
/// let cloud_points: Vec<PointXYZ> = vec![
|
||||
/// PointXYZ { x: 1.0, y: 2.0, z: 3.0 },
|
||||
/// PointXYZ { x: 4.0, y: 5.0, z: 6.0 },
|
||||
/// ];
|
||||
///
|
||||
/// let msg: PointCloud2Msg = WriterXYZ::from(cloud_points).try_into().unwrap();
|
||||
/// let convert = ReaderXYZ::try_from(msg).unwrap();
|
||||
/// // ^^^^^^^^^ conversion from PointCloud2Msg to Reader that implements Iterator
|
||||
///
|
||||
/// convert.for_each(|point: PointXYZ| {
|
||||
/// // do something with the point
|
||||
/// });
|
||||
/// ```
|
||||
/// # Fully Custom Reader
|
||||
/// When the predefined types are not enough (like sensor specific metadata), you can describe your Reader with the following template arguments:
|
||||
/// - T: The coordinate type, e.g. f32
|
||||
/// - SIZE: The size of the coordinate type in bytes, e.g. 4 for f32. Use the ros_pointcloud2::size_of! macro for this.
|
||||
/// - DIM: The dimensionality of the point, e.g. 3 for xyz coordinates.
|
||||
/// - METADIM: The number of additional meta data fields per point that are not for dimensionality. Intensity for example is a meta data field.
|
||||
/// Afterwards, implement the PointConvertible trait for your custom point type.
|
||||
///
|
||||
/// ## Example
|
||||
/// ```
|
||||
/// use ros_pointcloud2::{
|
||||
/// reader::Reader, writer::Writer, PointConvertible, Point, size_of, MetaNames, PointMeta,
|
||||
/// };
|
||||
///
|
||||
/// type Xyz = f32; // coordinate type
|
||||
/// const XYZ_S: usize = size_of!(Xyz);
|
||||
/// const DIM: usize = 3; // helper constant for dimensionality
|
||||
/// const METADIM: usize = 1; // helper constant for meta data fields
|
||||
///
|
||||
/// #[derive(Debug, PartialEq, Clone)]
|
||||
/// struct CustomPoint {
|
||||
/// x: f32,
|
||||
/// y: f32,
|
||||
/// z: f32,
|
||||
/// i: u8,
|
||||
/// }
|
||||
///
|
||||
/// impl From<Point<f32, 3, 1>> for CustomPoint {
|
||||
/// fn from(point: Point<f32, 3, 1>) -> Self {
|
||||
/// Self {
|
||||
/// x: point.coords[0],
|
||||
/// y: point.coords[1],
|
||||
/// z: point.coords[2],
|
||||
/// i: point.meta[0].get(),
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
///impl From<CustomPoint> for Point<f32, 3, 1> {
|
||||
/// fn from(point: CustomPoint) -> Self {
|
||||
/// Point {
|
||||
/// coords: [point.x, point.y, point.z],
|
||||
/// meta: [
|
||||
/// point.i.into(),
|
||||
/// ],
|
||||
/// }
|
||||
/// }
|
||||
///}
|
||||
///
|
||||
/// impl MetaNames<METADIM> for CustomPoint {
|
||||
/// fn meta_names() -> [&'static str; METADIM] {
|
||||
/// ["intensity"]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl PointConvertible<Xyz, XYZ_S, DIM, METADIM> for CustomPoint {}
|
||||
///
|
||||
/// type MyReader = Reader<Xyz, XYZ_S, DIM, METADIM, CustomPoint>;
|
||||
/// // ^^^^^^^^ your custom Reader
|
||||
/// type MyWriter = Writer<Xyz, XYZ_S, DIM, METADIM, CustomPoint>;
|
||||
/// ```
|
||||
pub struct Reader<T: FromBytes, const SIZE: usize, const DIM: usize, const METADIM: usize, C>
|
||||
where
|
||||
T: FromBytes,
|
||||
C: MetaNames<METADIM>,
|
||||
{
|
||||
iteration: usize,
|
||||
data: Vec<u8>,
|
||||
point_step_size: usize,
|
||||
cloud_length: usize,
|
||||
offsets: Vec<usize>,
|
||||
meta: Vec<(String, FieldDatatype)>,
|
||||
endianness: Endianness,
|
||||
phantom_t: std::marker::PhantomData<T>, // internally used for byte and datatype conversions
|
||||
phantom_c: std::marker::PhantomData<C>, // internally used for meta names array
|
||||
}
|
||||
|
||||
/// The iterator implementation for the Reader struct.
|
||||
/// The iterator is fallible because the data is read from a byte buffer inside the PointCloud2 message, which is inherently unsafe.
|
||||
///
|
||||
/// See ConversionError for possible errors that can occur during iteration.
|
||||
impl<T, const SIZE: usize, const DIM: usize, const METADIM: usize, C> Iterator
|
||||
for Reader<T, SIZE, DIM, METADIM, C>
|
||||
where
|
||||
T: FromBytes,
|
||||
C: PointConvertible<T, SIZE, DIM, METADIM>,
|
||||
{
|
||||
type Item = C;
|
||||
|
||||
/// The size_hint is the length of the remaining elements and the maximum length of the iterator.
|
||||
///
|
||||
/// PointCloud2 messages contain the length of the cloud, so we can prepare coming operations.
|
||||
/// This hint is used inside common iterator functions like `collect<Vec<_>>`, for example.
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.cloud_length - self.iteration, Some(self.cloud_length))
|
||||
}
|
||||
|
||||
/// Get the data from the byte buffer and convert it to the predefined point.
|
||||
/// It must keep track of the current iteration and the length of the cloud so it has to mutate self.
|
||||
///
|
||||
/// The current point is then converted into the custom type. If the conversion fails, an error is returned.
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.iteration >= self.cloud_length {
|
||||
return None; // iteration finished
|
||||
}
|
||||
|
||||
let mut xyz = [T::default(); DIM];
|
||||
xyz.iter_mut()
|
||||
.zip(self.offsets.iter())
|
||||
.for_each(|(p_xyz, in_point_offset)| {
|
||||
*p_xyz = load_loadable::<T, SIZE>(
|
||||
(self.iteration * self.point_step_size) + in_point_offset,
|
||||
&self.data,
|
||||
&self.endianness,
|
||||
);
|
||||
});
|
||||
|
||||
debug_assert!(self.meta.len() == METADIM, "Meta data length mismatch");
|
||||
debug_assert!(
|
||||
self.offsets.len() == DIM + METADIM,
|
||||
"Offset length mismatch"
|
||||
);
|
||||
|
||||
let mut meta = [PointMeta::default(); METADIM];
|
||||
meta.iter_mut()
|
||||
.zip(self.offsets.iter().skip(DIM))
|
||||
.zip(self.meta.iter())
|
||||
.for_each(|((p_meta, in_point_offset), (_, meta_type))| {
|
||||
let start = (self.iteration * self.point_step_size) + in_point_offset;
|
||||
*p_meta = PointMeta::from_buffer(&self.data, start, meta_type);
|
||||
});
|
||||
|
||||
self.iteration += 1;
|
||||
|
||||
Some(C::from(Point { coords: xyz, meta }))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, const SIZE: usize, const DIM: usize, const METADIM: usize, C> TryFrom<PointCloud2Msg>
|
||||
for Reader<T, SIZE, DIM, METADIM, C>
|
||||
where
|
||||
T: FromBytes,
|
||||
C: MetaNames<METADIM>,
|
||||
{
|
||||
type Error = ConversionError;
|
||||
|
||||
/// Convert a PointCloud2Msg into a Reader.
|
||||
/// Converting a PointCloud2Msg into a Reader is a fallible operation since the message can contain only a subset of the required fields.
|
||||
///
|
||||
/// The theoretical time complexity is O(n) where n is the number of fields defined in the message for a single point which is typically small.
|
||||
/// It therefore has effectively a constant time complexity O(1) for practical purposes.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// use ros_pointcloud2::{
|
||||
/// pcl_utils::PointXYZ, reader::ReaderXYZ, writer::WriterXYZ, PointCloud2Msg,
|
||||
/// };
|
||||
///
|
||||
/// let cloud_points: Vec<PointXYZ> = vec![
|
||||
/// PointXYZ { x: 1.0, y: 2.0, z: 3.0 },
|
||||
/// PointXYZ { x: 4.0, y: 5.0, z: 6.0 },
|
||||
/// ];
|
||||
///
|
||||
/// let msg: PointCloud2Msg = WriterXYZ::from(cloud_points).try_into().unwrap();
|
||||
///
|
||||
/// let convert = ReaderXYZ::try_from(msg).unwrap();
|
||||
/// // ^^^^^^^^ conversion from PointCloud2Msg to Reader
|
||||
/// ```
|
||||
fn try_from(cloud: PointCloud2Msg) -> Result<Self, Self::Error> {
|
||||
if cloud.fields.len() < DIM {
|
||||
return Err(ConversionError::NotEnoughFields);
|
||||
}
|
||||
|
||||
let xyz_field_type = T::field_datatype();
|
||||
|
||||
let mut has_x: Option<usize> = None;
|
||||
let mut has_y: Option<usize> = None;
|
||||
let mut has_z: Option<usize> = None;
|
||||
|
||||
let mut meta_with_offsets = vec![(String::default(), FieldDatatype::default(), 0); METADIM];
|
||||
|
||||
let lower_meta_names = C::meta_names()
|
||||
.iter()
|
||||
.map(|x| x.to_lowercase())
|
||||
.collect::<Vec<String>>();
|
||||
|
||||
for (idx, field) in cloud.fields.iter().enumerate() {
|
||||
let lower_field_name = field.name.to_lowercase();
|
||||
match lower_field_name.as_str() {
|
||||
"x" => has_x = Some(idx),
|
||||
"y" => has_y = Some(idx),
|
||||
"z" => has_z = Some(idx),
|
||||
_ => {
|
||||
if lower_meta_names.contains(&lower_field_name) {
|
||||
let meta_idx = idx - DIM;
|
||||
debug_assert!(
|
||||
meta_idx < meta_with_offsets.len(),
|
||||
"Meta data length mismatch"
|
||||
);
|
||||
meta_with_offsets[meta_idx].0 = field.name.clone();
|
||||
meta_with_offsets[meta_idx].1 = field.datatype.try_into()?;
|
||||
meta_with_offsets[meta_idx].2 = field.offset as usize;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
meta_with_offsets.sort_unstable_by(|(_, _, offset1), (_, _, offset2)| offset1.cmp(offset2));
|
||||
|
||||
debug_assert!(
|
||||
meta_with_offsets.len() == METADIM,
|
||||
"Meta data length mismatch"
|
||||
);
|
||||
|
||||
let mut meta_offsets = [usize::default(); METADIM];
|
||||
let mut meta = vec![(String::default(), FieldDatatype::default()); METADIM];
|
||||
|
||||
meta_with_offsets
|
||||
.into_iter()
|
||||
.zip(meta.iter_mut())
|
||||
.zip(meta_offsets.iter_mut())
|
||||
.for_each(|(((name, datatype, offset), meta), meta_offset)| {
|
||||
*meta = (name, datatype);
|
||||
*meta_offset = offset;
|
||||
});
|
||||
|
||||
let x_field = check_coord(has_x, &cloud.fields, &xyz_field_type)?;
|
||||
let y_field = check_coord(has_y, &cloud.fields, &xyz_field_type)?;
|
||||
|
||||
let mut offsets = vec![x_field.offset as usize, y_field.offset as usize];
|
||||
|
||||
let z_field = check_coord(has_z, &cloud.fields, &xyz_field_type);
|
||||
match z_field {
|
||||
Ok(z_field) => {
|
||||
offsets.push(z_field.offset as usize);
|
||||
}
|
||||
Err(err) => match err {
|
||||
ConversionError::NotEnoughFields => {
|
||||
if DIM == 3 {
|
||||
return Err(ConversionError::NotEnoughFields);
|
||||
}
|
||||
}
|
||||
_ => return Err(err),
|
||||
},
|
||||
}
|
||||
|
||||
let endian = if cloud.is_bigendian {
|
||||
Endianness::Big
|
||||
} else {
|
||||
Endianness::Little
|
||||
};
|
||||
|
||||
if offsets.len() != DIM {
|
||||
return Err(ConversionError::NotEnoughFields);
|
||||
}
|
||||
|
||||
offsets.extend(meta_offsets);
|
||||
|
||||
if offsets.len() != DIM + METADIM {
|
||||
return Err(ConversionError::NotEnoughFields);
|
||||
}
|
||||
|
||||
let point_step_size = cloud.point_step as usize;
|
||||
let cloud_length = cloud.width as usize * cloud.height as usize;
|
||||
if point_step_size * cloud_length != cloud.data.len() {
|
||||
return Err(ConversionError::DataLengthMismatch);
|
||||
}
|
||||
|
||||
let last_offset = offsets.last().expect("Dimensionality is 0.");
|
||||
|
||||
if let Some(last_meta) = meta.last() {
|
||||
let size_with_last_meta = last_offset + last_meta.1.size();
|
||||
if size_with_last_meta > point_step_size {
|
||||
return Err(ConversionError::DataLengthMismatch);
|
||||
}
|
||||
} else if last_offset + xyz_field_type.size() > point_step_size {
|
||||
return Err(ConversionError::DataLengthMismatch);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
iteration: 0,
|
||||
data: cloud.data,
|
||||
point_step_size,
|
||||
cloud_length: cloud.width as usize * cloud.height as usize,
|
||||
offsets,
|
||||
meta,
|
||||
endianness: endian,
|
||||
phantom_t: std::marker::PhantomData,
|
||||
phantom_c: std::marker::PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,313 @@
|
|||
//! Types used to represent ROS messages and convert between different ROS crates.
|
||||
//!
|
||||
//! This intermediate layer allows various ROS libraries to be integrated to the conversion process.
|
||||
//!
|
||||
//! There are 2 functions needed to be implemented for a new ROS message library:
|
||||
//! - `From` for converting from the library-generated message to [`crate::PointCloud2Msg`].
|
||||
//! ```
|
||||
//! #[cfg(feature = "fancy_ros_msg")]
|
||||
//! impl From<fancy_ros::sensor_msgs::msg::PointCloud2> for crate::PointCloud2Msg {
|
||||
//! fn from(msg: r2r::sensor_msgs::msg::PointCloud2) -> Self {
|
||||
//! // Conversion code - avoid any point buffer copy!
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! - `From` for converting from the [`crate::PointCloud2Msg`] to the library-generated message type.
|
||||
//! ```
|
||||
//! #[cfg(feature = "fancy_ros_msg")]
|
||||
//! impl From<crate::PointCloud2Msg> for fancy_ros::sensor_msgs::msg::PointCloud2 {
|
||||
//! fn from(msg: crate::PointCloud2Msg) -> Self {
|
||||
//! // Conversion code - avoid any point buffer copy!
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
/// [Time](https://docs.ros2.org/latest/api/builtin_interfaces/msg/Time.html) representation for ROS messages.
|
||||
#[cfg(not(any(feature = "rclrs_msg")))]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct TimeMsg {
|
||||
pub sec: i32,
|
||||
pub nanosec: u32,
|
||||
}
|
||||
|
||||
#[cfg(feature = "rclrs_msg")]
|
||||
pub use builtin_interfaces::msg::Time as TimeMsg;
|
||||
|
||||
#[cfg(feature = "rosrust_msg")]
|
||||
impl From<rosrust::Time> for TimeMsg {
|
||||
fn from(time: rosrust::Time) -> Self {
|
||||
Self {
|
||||
sec: time.sec as i32,
|
||||
nanosec: time.nsec,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the [header of a ROS message](https://docs.ros2.org/latest/api/std_msgs/msg/Header.html).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct HeaderMsg {
|
||||
pub seq: u32,
|
||||
pub stamp: TimeMsg,
|
||||
pub frame_id: String,
|
||||
}
|
||||
|
||||
/// Describing a point encoded in the byte buffer of a PointCloud2 message. See the [official message description](https://docs.ros2.org/latest/api/sensor_msgs/msg/PointField.html) for more information.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PointFieldMsg {
|
||||
pub name: String,
|
||||
pub offset: u32,
|
||||
pub datatype: u8,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
impl Default for PointFieldMsg {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
offset: 0,
|
||||
datatype: 0,
|
||||
count: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rclrs_msg")]
|
||||
impl From<sensor_msgs::msg::PointCloud2> for crate::PointCloud2Msg {
|
||||
fn from(msg: sensor_msgs::msg::PointCloud2) -> Self {
|
||||
Self {
|
||||
header: HeaderMsg {
|
||||
seq: 0,
|
||||
stamp: msg.header.stamp,
|
||||
frame_id: msg.header.frame_id,
|
||||
},
|
||||
dimensions: crate::CloudDimensions {
|
||||
width: msg.width,
|
||||
height: msg.height,
|
||||
},
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| PointFieldMsg {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
endian: if msg.is_bigendian {
|
||||
crate::Endian::Big
|
||||
} else {
|
||||
crate::Endian::Little
|
||||
},
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
dense: if msg.is_dense {
|
||||
crate::Denseness::Dense
|
||||
} else {
|
||||
crate::Denseness::Sparse
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rclrs_msg")]
|
||||
impl From<crate::PointCloud2Msg> for sensor_msgs::msg::PointCloud2 {
|
||||
fn from(msg: crate::PointCloud2Msg) -> Self {
|
||||
sensor_msgs::msg::PointCloud2 {
|
||||
header: std_msgs::msg::Header {
|
||||
stamp: msg.header.stamp,
|
||||
frame_id: msg.header.frame_id,
|
||||
},
|
||||
height: msg.dimensions.height,
|
||||
width: msg.dimensions.width,
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| sensor_msgs::msg::PointField {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
is_bigendian: match msg.endian {
|
||||
crate::Endian::Big => true,
|
||||
crate::Endian::Little => false,
|
||||
},
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
is_dense: match msg.dense {
|
||||
crate::Denseness::Dense => true,
|
||||
crate::Denseness::Sparse => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "r2r_msg")]
|
||||
impl From<r2r::sensor_msgs::msg::PointCloud2> for crate::PointCloud2Msg {
|
||||
fn from(msg: r2r::sensor_msgs::msg::PointCloud2) -> Self {
|
||||
Self {
|
||||
header: HeaderMsg {
|
||||
seq: 0,
|
||||
stamp: TimeMsg {
|
||||
sec: msg.header.stamp.sec,
|
||||
nanosec: msg.header.stamp.nanosec,
|
||||
},
|
||||
frame_id: msg.header.frame_id,
|
||||
},
|
||||
dimensions: crate::CloudDimensions {
|
||||
width: msg.width,
|
||||
height: msg.height,
|
||||
},
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| PointFieldMsg {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
endian: if msg.is_bigendian {
|
||||
crate::Endian::Big
|
||||
} else {
|
||||
crate::Endian::Little
|
||||
},
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
dense: if msg.is_dense {
|
||||
crate::Denseness::Dense
|
||||
} else {
|
||||
crate::Denseness::Sparse
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "r2r_msg")]
|
||||
impl From<crate::PointCloud2Msg> for r2r::sensor_msgs::msg::PointCloud2 {
|
||||
fn from(msg: crate::PointCloud2Msg) -> Self {
|
||||
r2r::sensor_msgs::msg::PointCloud2 {
|
||||
header: r2r::std_msgs::msg::Header {
|
||||
stamp: r2r::builtin_interfaces::msg::Time {
|
||||
sec: msg.header.stamp.sec,
|
||||
nanosec: msg.header.stamp.nanosec,
|
||||
},
|
||||
frame_id: msg.header.frame_id,
|
||||
},
|
||||
height: msg.dimensions.height,
|
||||
width: msg.dimensions.width,
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| r2r::sensor_msgs::msg::PointField {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
is_bigendian: match msg.endian {
|
||||
crate::Endian::Big => true,
|
||||
crate::Endian::Little => false,
|
||||
},
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
is_dense: match msg.dense {
|
||||
crate::Denseness::Dense => true,
|
||||
crate::Denseness::Sparse => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rosrust_msg")]
|
||||
impl From<rosrust_msg::sensor_msgs::PointCloud2> for crate::PointCloud2Msg {
|
||||
fn from(msg: rosrust_msg::sensor_msgs::PointCloud2) -> Self {
|
||||
Self {
|
||||
header: HeaderMsg {
|
||||
seq: msg.header.seq,
|
||||
stamp: TimeMsg {
|
||||
sec: msg.header.stamp.sec as i32,
|
||||
nanosec: msg.header.stamp.nsec,
|
||||
},
|
||||
frame_id: msg.header.frame_id,
|
||||
},
|
||||
dimensions: crate::CloudDimensions {
|
||||
width: msg.width,
|
||||
height: msg.height,
|
||||
},
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| PointFieldMsg {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
endian: if msg.is_bigendian {
|
||||
crate::Endian::Big
|
||||
} else {
|
||||
crate::Endian::Little
|
||||
},
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
dense: if msg.is_dense {
|
||||
crate::Denseness::Dense
|
||||
} else {
|
||||
crate::Denseness::Sparse
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rosrust_msg")]
|
||||
impl From<crate::PointCloud2Msg> for rosrust_msg::sensor_msgs::PointCloud2 {
|
||||
fn from(msg: crate::PointCloud2Msg) -> Self {
|
||||
rosrust_msg::sensor_msgs::PointCloud2 {
|
||||
header: rosrust_msg::std_msgs::Header {
|
||||
seq: msg.header.seq,
|
||||
stamp: rosrust::Time {
|
||||
sec: msg.header.stamp.sec as u32,
|
||||
nsec: msg.header.stamp.nanosec,
|
||||
},
|
||||
frame_id: msg.header.frame_id,
|
||||
},
|
||||
height: msg.dimensions.height,
|
||||
width: msg.dimensions.width,
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| rosrust_msg::sensor_msgs::PointField {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
is_bigendian: if msg.endian == crate::Endian::Big {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
},
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
is_dense: if msg.dense == crate::Denseness::Dense {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
171
src/ros_types.rs
171
src/ros_types.rs
|
|
@ -1,171 +0,0 @@
|
|||
#[cfg(not(any(feature = "rosrust_msg", feature = "rclrs_msg")))]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct TimeMsg {
|
||||
pub sec: u32,
|
||||
pub nsec: u32,
|
||||
}
|
||||
|
||||
#[cfg(feature = "rosrust_msg")]
|
||||
pub use rosrust::Time as TimeMsg;
|
||||
|
||||
#[cfg(feature = "rclrs_msg")]
|
||||
pub use builtin_interfaces::msg::Time as TimeMsg;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct HeaderMsg {
|
||||
pub seq: u32,
|
||||
pub stamp: TimeMsg,
|
||||
pub frame_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PointFieldMsg {
|
||||
pub name: String,
|
||||
pub offset: u32,
|
||||
pub datatype: u8,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PointCloud2Msg {
|
||||
pub header: HeaderMsg,
|
||||
pub height: u32,
|
||||
pub width: u32,
|
||||
pub fields: Vec<PointFieldMsg>,
|
||||
pub is_bigendian: bool,
|
||||
pub point_step: u32,
|
||||
pub row_step: u32,
|
||||
pub data: Vec<u8>,
|
||||
pub is_dense: bool,
|
||||
}
|
||||
|
||||
#[cfg(feature = "r2r_msg")]
|
||||
impl From<r2r::sensor_msgs::msg::PointCloud2> for PointCloud2Msg {
|
||||
fn from(msg: r2r::sensor_msgs::msg::PointCloud2) -> Self {
|
||||
Self {
|
||||
header: HeaderMsg {
|
||||
seq: 0,
|
||||
stamp: TimeMsg {
|
||||
sec: msg.header.stamp.sec as u32,
|
||||
nsec: msg.header.stamp.nanosec,
|
||||
},
|
||||
frame_id: msg.header.frame_id,
|
||||
},
|
||||
height: msg.height,
|
||||
width: msg.width,
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| PointFieldMsg {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
is_bigendian: msg.is_bigendian,
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
is_dense: msg.is_dense,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "r2r_msg")]
|
||||
impl From<PointCloud2Msg> for r2r::sensor_msgs::msg::PointCloud2 {
|
||||
fn from(msg: PointCloud2Msg) -> Self {
|
||||
r2r::sensor_msgs::msg::PointCloud2 {
|
||||
header: r2r::std_msgs::msg::Header {
|
||||
stamp: r2r::builtin_interfaces::msg::Time {
|
||||
sec: msg.header.stamp.sec as i32,
|
||||
nanosec: msg.header.stamp.nsec,
|
||||
},
|
||||
frame_id: msg.header.frame_id,
|
||||
},
|
||||
height: msg.height,
|
||||
width: msg.width,
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| r2r::sensor_msgs::msg::PointField {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
is_bigendian: msg.is_bigendian,
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
is_dense: msg.is_dense,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rosrust_msg")]
|
||||
impl From<rosrust_msg::sensor_msgs::PointCloud2> for PointCloud2Msg {
|
||||
fn from(msg: rosrust_msg::sensor_msgs::PointCloud2) -> Self {
|
||||
Self {
|
||||
header: HeaderMsg {
|
||||
seq: msg.header.seq,
|
||||
stamp: TimeMsg {
|
||||
sec: msg.header.stamp.sec,
|
||||
nsec: msg.header.stamp.nsec,
|
||||
},
|
||||
frame_id: msg.header.frame_id,
|
||||
},
|
||||
height: msg.height,
|
||||
width: msg.width,
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| PointFieldMsg {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
is_bigendian: msg.is_bigendian,
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
is_dense: msg.is_dense,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rosrust_msg")]
|
||||
impl From<PointCloud2Msg> for rosrust_msg::sensor_msgs::PointCloud2 {
|
||||
fn from(msg: PointCloud2Msg) -> Self {
|
||||
rosrust_msg::sensor_msgs::PointCloud2 {
|
||||
header: rosrust_msg::std_msgs::Header {
|
||||
seq: self.header.seq,
|
||||
stamp: rosrust::Time {
|
||||
sec: self.header.stamp.sec,
|
||||
nsec: self.header.stamp.nsec,
|
||||
},
|
||||
frame_id: self.header.frame_id,
|
||||
},
|
||||
height: msg.height,
|
||||
width: msg.width,
|
||||
fields: msg
|
||||
.fields
|
||||
.into_iter()
|
||||
.map(|field| sensor_msgs::msg::PointField {
|
||||
name: field.name,
|
||||
offset: field.offset,
|
||||
datatype: field.datatype,
|
||||
count: field.count,
|
||||
})
|
||||
.collect(),
|
||||
is_bigendian: msg.is_bigendian,
|
||||
point_step: msg.point_step,
|
||||
row_step: msg.row_step,
|
||||
data: msg.data,
|
||||
is_dense: msg.is_dense,
|
||||
}
|
||||
}
|
||||
}
|
||||
346
src/writer.rs
346
src/writer.rs
|
|
@ -1,346 +0,0 @@
|
|||
use crate::{
|
||||
pcl_utils::*,
|
||||
Point,
|
||||
PointCloud2Msg,
|
||||
PointConvertible,
|
||||
ConversionError,
|
||||
ros_types::PointFieldMsg,
|
||||
convert::{
|
||||
FromBytes,
|
||||
FieldDatatype,
|
||||
},
|
||||
};
|
||||
|
||||
/// Convenience type for a Writer that reads coordinates as f32. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type WriterF32<const DIM: usize, const METADIM: usize, C> =
|
||||
Writer<f32, { std::mem::size_of::<f32>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Writer that reads coordinates as f64. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type WriterF64<const DIM: usize, const METADIM: usize, C> =
|
||||
Writer<f64, { std::mem::size_of::<f64>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Writer that reads coordinates as i8. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type WriterI8<const DIM: usize, const METADIM: usize, C> =
|
||||
Writer<i8, { std::mem::size_of::<i8>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Writer that reads coordinates as i16. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type WriterI16<const DIM: usize, const METADIM: usize, C> =
|
||||
Writer<i16, { std::mem::size_of::<i16>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Writer that reads coordinates as i32. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type WriterI32<const DIM: usize, const METADIM: usize, C> =
|
||||
Writer<i32, { std::mem::size_of::<i32>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Writer that reads coordinates as u8. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type WriterU8<const DIM: usize, const METADIM: usize, C> =
|
||||
Writer<u8, { std::mem::size_of::<u8>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Writer that reads coordinates as u16. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type WriterU16<const DIM: usize, const METADIM: usize, C> =
|
||||
Writer<u16, { std::mem::size_of::<u16>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Convenience type for a Writer that reads coordinates as u32. Specify the number of dimensions, metadata dimensions and C, the point type.
|
||||
pub type WriterU32<const DIM: usize, const METADIM: usize, C> =
|
||||
Writer<u32, { std::mem::size_of::<u32>() }, DIM, METADIM, C>;
|
||||
|
||||
/// Writes a point cloud message from an iterator over xyz coordinates (see `PointXYZ`).
|
||||
pub type WriterXYZ = WriterF32<3, 0, PointXYZ>;
|
||||
|
||||
/// Writes a point cloud message from an iterator over xyz coordinates and intensity (see `PointXYZI`).
|
||||
pub type WriterXYZI = WriterF32<3, 1, PointXYZI>;
|
||||
|
||||
/// Writes a point cloud message from an iterator over xyz coordinates and normal (see `PointXYZNormal`).
|
||||
pub type WriterXYZNormal = WriterF32<3, 3, PointXYZNormal>;
|
||||
|
||||
/// Writes a point cloud message from an iterator over xyz coordinates and packs the rgb channels (see `PointXYZRGB`).
|
||||
pub type WriterXYZRGB = WriterF32<3, 1, PointXYZRGB>;
|
||||
|
||||
/// Writes a point cloud message from an iterator over xyz coordinates and intensity and packs the rgb channels (see `PointXYZRGBL`).
|
||||
pub type WriterXYZRGBL = WriterF32<3, 2, PointXYZRGBL>;
|
||||
|
||||
/// Writes a point cloud message from an iterator over xyz coordinates and intensity and packs the rgb channels and alpha channel (see `PointXYZRGBA`).
|
||||
pub type WriterXYZRGBA = WriterF32<3, 2, PointXYZRGBA>;
|
||||
|
||||
/// Writes a point cloud message from an iterator over xyz coordinates and normal and packs the rgb channels (see `PointXYZRGBNormal`).
|
||||
pub type WriterXYZRGBNormal = WriterF32<3, 4, PointXYZRGBNormal>;
|
||||
|
||||
/// Writes a point cloud message from an iterator over xyz coordinates and intensity and normal (see `PointXYZINormal`).
|
||||
pub type WriterXYZINormal = WriterF32<3, 4, PointXYZINormal>;
|
||||
|
||||
/// Writes a point cloud message from an iterator over xyz coordinates and intensity and label (see `PointXYZL`).
|
||||
pub type WriterXYZL = WriterF32<3, 1, PointXYZL>;
|
||||
|
||||
/// The Write creates a PointCloud2Msg out of your point iterator.
|
||||
///
|
||||
/// The iterator is defined at compile time, so the Point has to be described via template arguments.
|
||||
///
|
||||
/// # Predefined Readers
|
||||
/// For the most common use cases, there are already predefined types. Examples are `ReaderXYZ` for xyz coordinates or `ReaderXYZI` for xyz coordinates and intensity.
|
||||
///
|
||||
/// When using within a ROS node, the PointCloud2 created by the ROS crate must be converted first.
|
||||
/// The cost of this operation is low, as it mostly moves ownership without iterating over the point data.
|
||||
///
|
||||
/// ROS1 with rosrust:
|
||||
/// let msg: rosrust_msg::sensor_msgs::PointCloud2; // inside the callback
|
||||
/// let converted: ros_pointcloud2::PointCloud2Msg = msg.into();
|
||||
///
|
||||
/// ROS2 with r2r:
|
||||
/// let msg: r2r::sensor_msgs::msg::PointCloud2 = internal_msg.into();
|
||||
/// let converted: ros_pointcloud2::PointCloud2Msg = msg.into();
|
||||
///
|
||||
/// ros_pointcloud2 supports r2r, ros2_rust and rosrust as conversion targets out of the box via feature flags.
|
||||
///
|
||||
/// ## Example
|
||||
/// ```
|
||||
/// use ros_pointcloud2::{
|
||||
/// pcl_utils::PointXYZ, writer::WriterXYZ, PointCloud2Msg,
|
||||
/// };
|
||||
///
|
||||
///
|
||||
/// let cloud_points: Vec<PointXYZ> = vec![
|
||||
/// PointXYZ { x: 1.0, y: 2.0, z: 3.0 },
|
||||
/// PointXYZ { x: 4.0, y: 5.0, z: 6.0 },
|
||||
/// ];
|
||||
///
|
||||
/// let msg: PointCloud2Msg = WriterXYZ::from(cloud_points).try_into().unwrap();
|
||||
/// // ^^^^^^^^^ creating PointCloud2Msg from an iterator
|
||||
/// ```
|
||||
/// # Fully Custom Writer
|
||||
/// When the predefined types are not enough (like sensor specific metadata), you can describe your Writer with the following template arguments:
|
||||
/// - T: The coordinate type, e.g. f32
|
||||
/// - SIZE: The size of the coordinate type in bytes, e.g. 4 for f32. Use the ros_pointcloud2::size_of! macro for this.
|
||||
/// - DIM: The dimensionality of the point, e.g. 3 for xyz coordinates.
|
||||
/// - METADIM: The number of additional meta data fields per point that are not for dimensionality. Intensity for example is a meta data field.
|
||||
/// Afterwards, implement the PointConvertible trait for your custom point type.
|
||||
///
|
||||
/// ## Example
|
||||
/// ```
|
||||
/// use ros_pointcloud2::{
|
||||
/// reader::Reader, writer::Writer, PointConvertible, Point, size_of, MetaNames, PointMeta,
|
||||
/// };
|
||||
///
|
||||
/// type Xyz = f32; // coordinate type
|
||||
/// const XYZ_S: usize = size_of!(Xyz);
|
||||
/// const DIM: usize = 3; // helper constant for dimensionality
|
||||
/// const METADIM: usize = 1; // helper constant for meta data fields
|
||||
///
|
||||
/// #[derive(Debug, PartialEq, Clone)]
|
||||
/// struct CustomPoint {
|
||||
/// x: f32,
|
||||
/// y: f32,
|
||||
/// z: f32,
|
||||
/// i: u8,
|
||||
/// }
|
||||
///
|
||||
/// impl From<Point<f32, 3, 1>> for CustomPoint {
|
||||
/// fn from(point: Point<f32, 3, 1>) -> Self {
|
||||
/// Self {
|
||||
/// x: point.coords[0],
|
||||
/// y: point.coords[1],
|
||||
/// z: point.coords[2],
|
||||
/// i: point.meta[0].get(),
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
///impl From<CustomPoint> for Point<f32, 3, 1> {
|
||||
/// fn from(point: CustomPoint) -> Self {
|
||||
/// Point {
|
||||
/// coords: [point.x, point.y, point.z],
|
||||
/// meta: [
|
||||
/// point.i.into(),
|
||||
/// ],
|
||||
/// }
|
||||
/// }
|
||||
///}
|
||||
///
|
||||
/// impl MetaNames<METADIM> for CustomPoint {
|
||||
/// fn meta_names() -> [&'static str; METADIM] {
|
||||
/// ["intensity"]
|
||||
/// }
|
||||
/// }
|
||||
/// impl PointConvertible<Xyz, XYZ_S, DIM, METADIM> for CustomPoint {}
|
||||
///
|
||||
/// type MyReader = Reader<Xyz, XYZ_S, DIM, METADIM, CustomPoint>;
|
||||
/// type MyWriter = Writer<Xyz, XYZ_S, DIM, METADIM, CustomPoint>;
|
||||
/// // ^^^^^^^^ your custom Writer
|
||||
/// ```
|
||||
pub struct Writer<T: FromBytes, const SIZE: usize, const DIM: usize, const METADIM: usize, C>
|
||||
where
|
||||
T: FromBytes,
|
||||
C: PointConvertible<T, SIZE, DIM, METADIM>,
|
||||
{
|
||||
coordinates: Box<dyn Iterator<Item = C>>,
|
||||
phantom_t: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T, const SIZE: usize, const DIM: usize, const METADIM: usize, C> TryInto<PointCloud2Msg>
|
||||
for Writer<T, SIZE, DIM, METADIM, C>
|
||||
where
|
||||
T: FromBytes,
|
||||
C: PointConvertible<T, SIZE, DIM, METADIM>,
|
||||
{
|
||||
type Error = ConversionError;
|
||||
|
||||
/// Writes the points to a PointCloud2Msg.
|
||||
///
|
||||
/// First use the `from` method for initializing the Writer.
|
||||
/// Then use the `try_into` method to do the actual conversion.
|
||||
///
|
||||
/// The operation is O(n) in time complexity where n is the number of points in the point cloud.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// use ros_pointcloud2::{
|
||||
/// pcl_utils::PointXYZ, writer::WriterXYZ, PointCloud2Msg,
|
||||
/// };
|
||||
///
|
||||
/// let cloud_points: Vec<PointXYZ> = vec![
|
||||
/// PointXYZ { x: 1.0, y: 2.0, z: 3.0 },
|
||||
/// PointXYZ { x: 4.0, y: 5.0, z: 6.0 },
|
||||
/// ];
|
||||
/// let msg_out: PointCloud2Msg = WriterXYZ::from(cloud_points).try_into().unwrap();
|
||||
/// // ^^^^^^^^ ROS message conversion
|
||||
/// ```
|
||||
fn try_into(mut self) -> Result<PointCloud2Msg, Self::Error> {
|
||||
if DIM > 3 {
|
||||
return Err(ConversionError::TooManyDimensions); // maybe can be checked at compile time?
|
||||
}
|
||||
|
||||
let mut fields = Vec::with_capacity(METADIM + DIM); // TODO check if we can preallocate the size on the stack
|
||||
|
||||
if DIM > 1 {
|
||||
fields.push(PointFieldMsg {
|
||||
name: "x".into(),
|
||||
offset: 0,
|
||||
datatype: T::field_datatype().into(),
|
||||
count: 1,
|
||||
});
|
||||
|
||||
fields.push(PointFieldMsg {
|
||||
name: "y".into(),
|
||||
offset: SIZE as u32,
|
||||
datatype: T::field_datatype().into(),
|
||||
count: 1,
|
||||
});
|
||||
}
|
||||
|
||||
if DIM == 3 {
|
||||
fields.push(PointFieldMsg {
|
||||
name: "z".into(),
|
||||
offset: 2 * SIZE as u32,
|
||||
datatype: T::field_datatype().into(),
|
||||
count: 1,
|
||||
});
|
||||
}
|
||||
|
||||
let first_point = self.coordinates.next().ok_or(ConversionError::NoPoints)?;
|
||||
let point: Point<T, DIM, METADIM> = first_point.clone().into();
|
||||
let meta_names = C::meta_names();
|
||||
|
||||
let mut meta_offsets_acc = DIM as u32 * SIZE as u32;
|
||||
for (meta_value, meta_name) in point.meta.into_iter().zip(meta_names.into_iter()) {
|
||||
let datatype_code = meta_value.datatype.into();
|
||||
if FieldDatatype::try_from(datatype_code).is_err() {
|
||||
return Err(ConversionError::UnsupportedFieldType);
|
||||
}
|
||||
|
||||
fields.push(PointFieldMsg {
|
||||
name: meta_name.into(),
|
||||
offset: meta_offsets_acc,
|
||||
datatype: datatype_code,
|
||||
count: 1,
|
||||
});
|
||||
meta_offsets_acc += meta_value.datatype.size() as u32
|
||||
}
|
||||
|
||||
let mut cloud = PointCloud2Msg {
|
||||
point_step: fields.iter().fold(Default::default(), |acc, field| {
|
||||
let field_type: FieldDatatype = field
|
||||
.datatype
|
||||
.try_into()
|
||||
.expect("Unsupported field but checked before.");
|
||||
let field_size = field_type.size();
|
||||
acc + field.count * field_size as u32
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// actual point -> byte conversion -- O(n)
|
||||
add_point_to_byte_buffer(first_point, &mut cloud)?;
|
||||
for coords in self.coordinates {
|
||||
add_point_to_byte_buffer(coords, &mut cloud)?;
|
||||
}
|
||||
|
||||
cloud.fields = fields;
|
||||
cloud.height = 1; // everything is in one row (unstructured)
|
||||
cloud.is_bigendian = false; // ROS default
|
||||
cloud.is_dense = true; // ROS default
|
||||
cloud.row_step = cloud.width * cloud.point_step; // Note: redundant but defined in PointCloud2 message
|
||||
|
||||
Ok(cloud)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, const SIZE: usize, const DIM: usize, const METADIM: usize, C>
|
||||
Writer<T, SIZE, DIM, METADIM, C>
|
||||
where
|
||||
T: FromBytes,
|
||||
C: PointConvertible<T, SIZE, DIM, METADIM>,
|
||||
{
|
||||
/// Create a Writer from any iterator that iterates over a template-defined point to a ROS message type.
|
||||
/// First use the `from` method for initializing the Writer.
|
||||
/// Then use the `try_into` method to do the actual conversion.
|
||||
///
|
||||
/// The operation is O(n) in time complexity where n is the number of points in the point cloud.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// use ros_pointcloud2::{
|
||||
/// pcl_utils::PointXYZ, writer::WriterXYZ, PointCloud2Msg,
|
||||
/// };
|
||||
///
|
||||
/// let cloud_points: Vec<PointXYZ> = vec![
|
||||
/// PointXYZ { x: 1.0, y: 2.0, z: 3.0 },
|
||||
/// PointXYZ { x: 4.0, y: 5.0, z: 6.0 },
|
||||
/// ];
|
||||
// let msg_out: PointCloud2Msg = WriterXYZ::from(cloud_points).try_into().unwrap();
|
||||
/// // ^^^^ Writer creation
|
||||
/// ```
|
||||
pub fn from(coordinates: impl IntoIterator<Item = C> + 'static) -> Self {
|
||||
Self {
|
||||
coordinates: Box::new(coordinates.into_iter()),
|
||||
phantom_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn add_point_to_byte_buffer<
|
||||
T: FromBytes,
|
||||
const SIZE: usize,
|
||||
const DIM: usize,
|
||||
const METADIM: usize,
|
||||
C: PointConvertible<T, SIZE, DIM, METADIM>,
|
||||
>(
|
||||
coords: C,
|
||||
cloud: &mut PointCloud2Msg,
|
||||
) -> Result<bool, ConversionError> {
|
||||
let point: Point<T, DIM, METADIM> = coords.into();
|
||||
|
||||
// (x, y, z...)
|
||||
point
|
||||
.coords
|
||||
.iter()
|
||||
.for_each(|x| cloud.data.extend_from_slice(T::bytes(x).as_slice()));
|
||||
|
||||
// meta data description
|
||||
point.meta.iter().for_each(|meta| {
|
||||
let truncated_bytes = &meta.bytes[0..meta.datatype.size()];
|
||||
cloud.data.extend_from_slice(truncated_bytes);
|
||||
});
|
||||
|
||||
cloud.width += 1;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,9 +1,7 @@
|
|||
#[cfg(feature = "r2r_msg")]
|
||||
#[test]
|
||||
fn convertxyz_r2r_msg() {
|
||||
use ros_pointcloud2::{
|
||||
pcl_utils::PointXYZ, reader::ReaderXYZ, writer::WriterXYZ, PointCloud2Msg,
|
||||
};
|
||||
use ros_pointcloud2::{points::PointXYZ, PointCloud2Msg};
|
||||
|
||||
use r2r::sensor_msgs::msg::PointCloud2;
|
||||
|
||||
|
|
@ -25,10 +23,10 @@ fn convertxyz_r2r_msg() {
|
|||
},
|
||||
];
|
||||
let copy = cloud.clone();
|
||||
let internal_cloud: PointCloud2Msg = WriterXYZ::from(cloud).try_into().unwrap();
|
||||
let internal_cloud = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let r2r_msg_cloud: PointCloud2 = internal_cloud.into();
|
||||
let convert_back_internal: PointCloud2Msg = r2r_msg_cloud.into();
|
||||
let to_convert = ReaderXYZ::try_from(convert_back_internal).unwrap();
|
||||
let to_convert = convert_back_internal.try_into_iter().unwrap();
|
||||
let back_to_type = to_convert.collect::<Vec<PointXYZ>>();
|
||||
assert_eq!(copy, back_to_type);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,8 @@
|
|||
#[cfg(feature = "rclrs_msg")]
|
||||
#[test]
|
||||
fn convertxyz_rclrs_msg() {
|
||||
use ros_pointcloud2::{
|
||||
pcl_utils::PointXYZ, reader::ReaderXYZ, writer::WriterXYZ, PointCloud2Msg,
|
||||
};
|
||||
|
||||
use ros_pointcloud2::{points::PointXYZ, PointCloud2Msg};
|
||||
|
||||
use sensor_msgs::msg::PointCloud2;
|
||||
|
||||
let cloud = vec![
|
||||
|
|
@ -25,10 +23,10 @@ fn convertxyz_rclrs_msg() {
|
|||
},
|
||||
];
|
||||
let copy = cloud.clone();
|
||||
let internal_cloud: PointCloud2Msg = WriterXYZ::from(cloud).try_into().unwrap();
|
||||
let internal_cloud = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let rclrs_msg_cloud: PointCloud2 = internal_cloud.into();
|
||||
let convert_back_internal: PointCloud2Msg = rclrs_msg_cloud.into();
|
||||
let to_convert = ReaderXYZ::try_from(convert_back_internal).unwrap();
|
||||
let to_convert = convert_back_internal.try_into_iter().unwrap();
|
||||
let back_to_type = to_convert.collect::<Vec<PointXYZ>>();
|
||||
assert_eq!(copy, back_to_type);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
#[cfg(feature = "rosrust_msg")]
|
||||
#[test]
|
||||
fn convertxyz_rosrust_msg() {
|
||||
use ros_pointcloud2::{
|
||||
pcl_utils::PointXYZ, reader::ReaderXYZ, writer::WriterXYZ, PointCloud2Msg,
|
||||
};
|
||||
use ros_pointcloud2::{points::PointXYZ, PointCloud2Msg};
|
||||
|
||||
let cloud = vec![
|
||||
PointXYZ {
|
||||
|
|
@ -23,10 +21,10 @@ fn convertxyz_rosrust_msg() {
|
|||
},
|
||||
];
|
||||
let copy = cloud.clone();
|
||||
let internal_cloud: PointCloud2Msg = WriterXYZ::from(cloud).try_into().unwrap();
|
||||
let internal_cloud = PointCloud2Msg::try_from_iter(cloud).unwrap();
|
||||
let rosrust_msg_cloud: rosrust_msg::sensor_msgs::PointCloud2 = internal_cloud.into();
|
||||
let convert_back_internal: PointCloud2Msg = rosrust_msg_cloud.into();
|
||||
let to_convert = ReaderXYZ::try_from(convert_back_internal).unwrap();
|
||||
let to_convert = convert_back_internal.try_into_iter().unwrap();
|
||||
let back_to_type = to_convert.collect::<Vec<PointXYZ>>();
|
||||
assert_eq!(copy, back_to_type);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue