Use meshloader to support multiple file formats loading (#744)

Co-authored-by: Tin Lai <tin@tinyiu.com>
This commit is contained in:
Thierry Berger
2024-11-12 09:02:55 +01:00
committed by GitHub
parent 0d791eb794
commit 71f65fe55a
14 changed files with 214 additions and 189 deletions

View File

@@ -23,7 +23,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Cargo doc - name: Cargo doc
run: cargo doc --features parallel,simd-stable,serde-serialize,debug-render -p rapier3d -p rapier2d -p rapier3d-stl -p rapier3d-urdf run: cargo doc --features parallel,simd-stable,serde-serialize,debug-render -p rapier3d -p rapier2d -p rapier3d-meshloader -p rapier3d-urdf
build-native: build-native:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:

View File

@@ -14,7 +14,7 @@ members = [
"examples3d-f64", "examples3d-f64",
"benchmarks3d", "benchmarks3d",
"crates/rapier3d-urdf", "crates/rapier3d-urdf",
"crates/rapier3d-stl", "crates/rapier3d-meshloader",
] ]
resolver = "2" resolver = "2"

View File

@@ -0,0 +1,22 @@
## Unreleased
Renamed the crate from `rapier3d-stl` to `rapier3d-meshloader`, to better reflect its support for multiple formats.
### Added
- Add optional support for Collada and Wavefront files through new feature flags `collada` and `wavefront`.
### Modified
- Support for STL is now optional through feature `stl`.
- Features `stl`, `wavefront` and `collada` are enabled by default.
## 0.3.0
This is the initial release of the `rapier3d-stl` crate.
### Added
- Add `load_from_path` for creating a shape from a stl file.
- Add `load_from_reader` for creating a shape from an object implementing `Read`.
- Add `load_from_raw_mesh` for creating a shape from an already loaded `IndexedMesh`.

View File

@@ -1,19 +1,31 @@
[package] [package]
name = "rapier3d-stl" name = "rapier3d-meshloader"
version = "0.3.0" version = "0.3.0"
authors = ["Sébastien Crozet <sebcrozet@dimforge.com>"] authors = ["Sébastien Crozet <sebcrozet@dimforge.com>"]
description = "STL file loader for the 3D rapier physics engine." description = "STL file loader for the 3D rapier physics engine."
documentation = "https://docs.rs/rapier3d-stl" documentation = "https://docs.rs/rapier3d-meshloader"
homepage = "https://rapier.rs" homepage = "https://rapier.rs"
repository = "https://github.com/dimforge/rapier" repository = "https://github.com/dimforge/rapier"
readme = "README.md" readme = "README.md"
categories = ["science", "game-development", "mathematics", "simulation", "wasm"] categories = [
"science",
"game-development",
"mathematics",
"simulation",
"wasm",
]
keywords = ["physics", "joints", "multibody", "robotics", "urdf"] keywords = ["physics", "joints", "multibody", "robotics", "urdf"]
license = "Apache-2.0" license = "Apache-2.0"
edition = "2021" edition = "2021"
[features]
default = ["stl", "collada", "wavefront"]
stl = ["mesh-loader/stl"]
collada = ["mesh-loader/collada"]
wavefront = ["mesh-loader/obj"]
[dependencies] [dependencies]
thiserror = "1.0.61" thiserror = "1.0.61"
stl_io = "0.7" mesh-loader = { version = "0.1.12", optional = true }
rapier3d = { version = "0.22", path = "../rapier3d" } rapier3d = { version = "0.22", path = "../rapier3d" }

View File

@@ -1,8 +1,12 @@
## STL loader for the Rapier physics engine ## Mesh loader for the Rapier physics engine
Rapier is a set of 2D and 3D physics engines for games, animation, and robotics. The `rapier3d-stl` Rapier is a set of 2D and 3D physics engines for games, animation, and robotics. The `rapier3d-meshloader`
crate lets you create a shape compatible with `rapier3d` and `parry3d` (the underlying collision-detection crate lets you create a shape compatible with `rapier3d` and `parry3d` (the underlying collision-detection
library) from an STL file. library) from different file formats, see the following features list:
- `stl`: support .stl files
- `collada`: support .dae files
- `wavefront`: support .obj files
## Resources and discussions ## Resources and discussions

View File

@@ -0,0 +1,86 @@
#![doc = include_str!("../README.md")]
#![deny(missing_docs)]
use mesh_loader::Mesh;
use rapier3d::geometry::{MeshConverter, SharedShape};
use rapier3d::math::{Isometry, Point, Real, Vector};
use rapier3d::prelude::MeshConverterError;
use std::path::Path;
/// The result of loading a shape.
pub struct LoadedShape {
/// The shape loaded from the file and converted by the [`MeshConverter`].
pub shape: SharedShape,
/// The shapes pose.
pub pose: Isometry<Real>,
/// The raw mesh read from the file without any modification.
pub raw_mesh: Mesh,
}
/// Error while loading an STL file.
#[derive(thiserror::Error, Debug)]
pub enum MeshLoaderError {
/// An error triggered by rapiers [`MeshConverter`].
#[error(transparent)]
MeshConverter(#[from] MeshConverterError),
/// A generic IO error.
#[error(transparent)]
Io(#[from] std::io::Error),
}
/// Loads parry shapes from a file.
///
/// # Parameters
/// - `path`: the files path.
/// - `converter`: controls how the shapes are computed from the content. In particular, it lets
/// you specify if the computed [`SharedShape`] is a triangle mesh, its convex hull,
/// bounding box, etc.
/// - `scale`: the scaling factor applied to the geometry input to the `converter`. This scale will
/// affect at the geometric level the [`LoadedShape::shape`]. Note that raw mesh value stored
/// in [`LoadedShape::raw_mesh`] remains unscaled.
pub fn load_from_path(
path: impl AsRef<Path>,
converter: &MeshConverter,
scale: Vector<Real>,
) -> Result<Vec<Result<LoadedShape, MeshConverterError>>, MeshLoaderError> {
let loader = mesh_loader::Loader::default();
let mut colliders = vec![];
let scene = loader.load(path)?;
for (raw_mesh, _) in scene.meshes.into_iter().zip(scene.materials) {
let shape = load_from_raw_mesh(&raw_mesh, converter, scale);
colliders.push(shape.map(|(shape, pose)| LoadedShape {
shape,
pose,
raw_mesh,
}));
}
Ok(colliders)
}
/// Loads an file as a shape from a preloaded raw [`mesh_loader::Mesh`].
///
/// # Parameters
/// - `raw_mesh`: the raw mesh.
/// - `converter`: controls how the shape is computed from the STL content. In particular, it lets
/// you specify if the computed [`SharedShape`] is a triangle mesh, its convex hull,
/// bounding box, etc.
/// - `scale`: the scaling factor applied to the geometry input to the `converter`. This scale will
/// affect at the geometric level the [`LoadedShape::shape`]. Note that raw mesh value stored
/// in [`LoadedShape::raw_mesh`] remains unscaled.
pub fn load_from_raw_mesh(
raw_mesh: &Mesh,
converter: &MeshConverter,
scale: Vector<Real>,
) -> Result<(SharedShape, Isometry<Real>), MeshConverterError> {
let mut vertices: Vec<_> = raw_mesh
.vertices
.iter()
.map(|xyz| Point::new(xyz[0], xyz[1], xyz[2]))
.collect();
vertices
.iter_mut()
.for_each(|pt| pt.coords.component_mul_assign(&scale));
let indices: Vec<_> = raw_mesh.faces.clone();
converter.convert(vertices, indices)
}

View File

@@ -1,9 +0,0 @@
## Unreleased
This is the initial release of the `rapier3d-stl` crate.
### Added
- Add `load_from_path` for creating a shape from a stl file.
- Add `load_from_reader` for creating a shape from an object implementing `Read`.
- Add `load_from_raw_mesh` for creating a shape from an already loaded `IndexedMesh`.

View File

@@ -1,110 +0,0 @@
//! ## STL loader for the Rapier physics engine
//!
//! Rapier is a set of 2D and 3D physics engines for games, animation, and robotics. The `rapier3d-stl`
//! crate lets you create a shape compatible with `rapier3d` and `parry3d` (the underlying collision-detection
//! library) from an STL file.
#![warn(missing_docs)]
use rapier3d::geometry::{MeshConverter, MeshConverterError, SharedShape};
use rapier3d::math::{Isometry, Point, Real, Vector};
use std::fs::File;
use std::io::{BufReader, Read, Seek};
use std::path::Path;
use stl_io::IndexedMesh;
/// Error while loading an STL file.
#[derive(thiserror::Error, Debug)]
pub enum StlLoaderError {
/// An error triggered by rapiers [`MeshConverter`].
#[error(transparent)]
MeshConverter(#[from] MeshConverterError),
/// A generic IO error.
#[error(transparent)]
Io(#[from] std::io::Error),
}
/// The result of loading a shape from an stl mesh.
pub struct StlShape {
/// The shape loaded from the file and converted by the [`MeshConverter`].
pub shape: SharedShape,
/// The shapes pose.
pub pose: Isometry<Real>,
/// The raw mesh read from the stl file without any modification.
pub raw_mesh: IndexedMesh,
}
/// Loads an STL file as a shape from a file.
///
/// # Parameters
/// - `file_path`: the STL files path.
/// - `converter`: controls how the shape is computed from the STL content. In particular, it lets
/// you specify if the computed [`StlShape::shape`] is a triangle mesh, its convex hull,
/// bounding box, etc.
/// - `scale`: the scaling factor applied to the geometry input to the `converter`. This scale will
/// affect at the geometric level the [`StlShape::shape`]. Note that raw mesh value stored
/// in [`StlShape::raw_mesh`] remains unscaled.
pub fn load_from_path(
file_path: impl AsRef<Path>,
converter: MeshConverter,
scale: Vector<Real>,
) -> Result<StlShape, StlLoaderError> {
let mut reader = BufReader::new(File::open(file_path)?);
load_from_reader(&mut reader, converter, scale)
}
/// Loads an STL file as a shape from an arbitrary reader.
///
/// # Parameters
/// - `reader`: the reader.
/// - `converter`: controls how the shape is computed from the STL content. In particular, it lets
/// you specify if the computed [`StlShape::shape`] is a triangle mesh, its convex hull,
/// bounding box, etc.
/// - `scale`: the scaling factor applied to the geometry input to the `converter`. This scale will
/// affect at the geometric level the [`StlShape::shape`]. Note that raw mesh value stored
/// in [`StlShape::raw_mesh`] remains unscaled.
pub fn load_from_reader<R: Read + Seek>(
read: &mut R,
converter: MeshConverter,
scale: Vector<Real>,
) -> Result<StlShape, StlLoaderError> {
let stl_mesh = stl_io::read_stl(read)?;
Ok(load_from_raw_mesh(stl_mesh, converter, scale)?)
}
/// Loads an STL file as a shape from a preloaded raw stl mesh.
///
/// # Parameters
/// - `raw_mesh`: the raw stl mesh.
/// - `converter`: controls how the shape is computed from the STL content. In particular, it lets
/// you specify if the computed [`StlShape::shape`] is a triangle mesh, its convex hull,
/// bounding box, etc.
/// - `scale`: the scaling factor applied to the geometry input to the `converter`. This scale will
/// affect at the geometric level the [`StlShape::shape`]. Note that raw mesh value stored
/// in [`StlShape::raw_mesh`] remains unscaled.
pub fn load_from_raw_mesh(
raw_mesh: IndexedMesh,
converter: MeshConverter,
scale: Vector<Real>,
) -> Result<StlShape, MeshConverterError> {
let mut vertices: Vec<_> = raw_mesh
.vertices
.iter()
.map(|xyz| Point::new(xyz[0], xyz[1], xyz[2]))
.collect();
vertices
.iter_mut()
.for_each(|pt| pt.coords.component_mul_assign(&scale));
let indices: Vec<_> = raw_mesh
.faces
.iter()
.map(|f| f.vertices.map(|i| i as u32))
.collect();
let (shape, pose) = converter.convert(vertices, indices)?;
Ok(StlShape {
shape,
pose,
raw_mesh,
})
}

View File

@@ -1,5 +1,11 @@
## Unreleased ## Unreleased
### Added
- Add optional support for Collada and Wavefront files through new feature flags `collada` and `wavefront`.
## 0.3.0
This is the initial release of the `rapier3d-urdf` crate. This is the initial release of the `rapier3d-urdf` crate.
### Added ### Added

View File

@@ -7,13 +7,21 @@ documentation = "https://docs.rs/rapier3d-urdf"
homepage = "https://rapier.rs" homepage = "https://rapier.rs"
repository = "https://github.com/dimforge/rapier" repository = "https://github.com/dimforge/rapier"
readme = "README.md" readme = "README.md"
categories = ["science", "game-development", "mathematics", "simulation", "wasm"] categories = [
"science",
"game-development",
"mathematics",
"simulation",
"wasm",
]
keywords = ["physics", "joints", "multibody", "robotics", "urdf"] keywords = ["physics", "joints", "multibody", "robotics", "urdf"]
license = "Apache-2.0" license = "Apache-2.0"
edition = "2021" edition = "2021"
[features] [features]
stl = ["dep:rapier3d-stl"] stl = ["dep:rapier3d-meshloader", "rapier3d-meshloader/stl"]
collada = ["dep:rapier3d-meshloader", "rapier3d-meshloader/collada"]
wavefront = ["dep:rapier3d-meshloader", "rapier3d-meshloader/wavefront"]
[dependencies] [dependencies]
log = "0.4" log = "0.4"
@@ -23,4 +31,4 @@ bitflags = "2"
xurdf = "0.2" xurdf = "0.2"
rapier3d = { version = "0.22", path = "../rapier3d" } rapier3d = { version = "0.22", path = "../rapier3d" }
rapier3d-stl = { version = "0.3.0", path = "../rapier3d-stl", optional = true } rapier3d-meshloader = { version = "0.3.0", path = "../rapier3d-meshloader", default-features = false, optional = true }

View File

@@ -1,4 +1,4 @@
## STL loader for the Rapier physics engine ## Mesh loader for the Rapier physics engine
Rapier is a set of 2D and 3D physics engines for games, animation, and robotics. The `rapier3d-urdf` Rapier is a set of 2D and 3D physics engines for games, animation, and robotics. The `rapier3d-urdf`
crate lets you convert an URDF file into a set of rigid-bodies, colliders, and joints, for usage with the crate lets you convert an URDF file into a set of rigid-bodies, colliders, and joints, for usage with the
@@ -6,7 +6,9 @@ crate lets you convert an URDF file into a set of rigid-bodies, colliders, and j
## Optional cargo features ## Optional cargo features
- `stl`: enables loading STL meshes referenced by the URDF file. - `stl`: enables loading `.STL` meshes referenced by the URDF file.
- `collada`: enables loading `.dae` meshes referenced by the URDF file.
- `wavefront`: enables loading `.obj` meshes referenced by the URDF file.
## Limitations ## Limitations
@@ -14,7 +16,7 @@ Are listed below some known limitations you might want to be aware of before pic
improve improve
these elements are very welcome! these elements are very welcome!
- Mesh file types other than `stl` are not supported yet. Contributions are welcome. You my check the `rapier3d-stl` - Supported mesh formats are `stl`, `collada` and `wavefront`. Contributions are welcome. You my check the `rapier3d-meshloader`
repository for an example of mesh loader. repository for an example of mesh loader.
- When inserting joints as multibody joints, they will be reset to their neutral position (all coordinates = 0). - When inserting joints as multibody joints, they will be reset to their neutral position (all coordinates = 0).
- The following fields are currently ignored: - The following fields are currently ignored:

View File

@@ -1,4 +1,4 @@
//! ## STL loader for the Rapier physics engine //! ## URDF loader for the Rapier physics engine
//! //!
//! Rapier is a set of 2D and 3D physics engines for games, animation, and robotics. The `rapier3d-urdf` //! Rapier is a set of 2D and 3D physics engines for games, animation, and robotics. The `rapier3d-urdf`
//! crate lets you convert an URDF file into a set of rigid-bodies, colliders, and joints, for usage with the //! crate lets you convert an URDF file into a set of rigid-bodies, colliders, and joints, for usage with the
@@ -7,6 +7,8 @@
//! ## Optional cargo features //! ## Optional cargo features
//! //!
//! - `stl`: enables loading STL meshes referenced by the URDF file. //! - `stl`: enables loading STL meshes referenced by the URDF file.
//! - `collada`: enables loading Collada (`.dae`) meshes referenced by the URDF file.
//! - `wavefront`: enables loading Wavefront (`.obj`) meshes referenced by the URDF file.
//! //!
//! ## Limitations //! ## Limitations
//! //!
@@ -14,7 +16,7 @@
//! improve //! improve
//! these elements are very welcome! //! these elements are very welcome!
//! //!
//! - Mesh file types other than `stl` are not supported yet. Contributions are welcome. You my check the `rapier3d-stl` //! - Mesh file types are limited. Contributions are welcome. You may check the `rapier3d-meshloader`
//! repository for an example of mesh loader. //! repository for an example of mesh loader.
//! - When inserting joints as multibody joints, they will be reset to their neutral position (all coordinates = 0). //! - When inserting joints as multibody joints, they will be reset to their neutral position (all coordinates = 0).
//! - The following fields are currently ignored: //! - The following fields are currently ignored:
@@ -35,6 +37,7 @@ use rapier3d::{
geometry::{Collider, ColliderBuilder, ColliderHandle, ColliderSet, SharedShape, TriMeshFlags}, geometry::{Collider, ColliderBuilder, ColliderHandle, ColliderSet, SharedShape, TriMeshFlags},
math::{Isometry, Point, Real, Vector}, math::{Isometry, Point, Real, Vector},
na, na,
prelude::MeshConverter,
}; };
use std::collections::HashMap; use std::collections::HashMap;
use std::path::Path; use std::path::Path;
@@ -289,7 +292,7 @@ impl UrdfRobot {
/// (`UrdfRobot`). Both structures are arranged the same way, with matching indices for each part. /// (`UrdfRobot`). Both structures are arranged the same way, with matching indices for each part.
/// ///
/// If the URDF file references external meshes, they will be loaded automatically if the format /// If the URDF file references external meshes, they will be loaded automatically if the format
/// is supported. The format is detected from the files extension. All the mesh formats are /// is supported. The format is detected mostly from the files extension. All the mesh formats are
/// disabled by default and can be enabled through cargo features (e.g. the `stl` feature of /// disabled by default and can be enabled through cargo features (e.g. the `stl` feature of
/// this crate enabled loading referenced meshes in stl format). /// this crate enabled loading referenced meshes in stl format).
/// ///
@@ -310,13 +313,13 @@ impl UrdfRobot {
name_to_link_id.insert(&link.name, id); name_to_link_id.insert(&link.name, id);
let mut colliders = vec![]; let mut colliders = vec![];
if options.create_colliders_from_collision_shapes { if options.create_colliders_from_collision_shapes {
colliders.extend(link.collisions.iter().filter_map(|co| { colliders.extend(link.collisions.iter().flat_map(|co| {
urdf_to_collider(&options, mesh_dir, &co.geometry, &co.origin) urdf_to_colliders(&options, mesh_dir, &co.geometry, &co.origin)
})) }))
} }
if options.create_colliders_from_visual_shapes { if options.create_colliders_from_visual_shapes {
colliders.extend(link.visuals.iter().filter_map(|vis| { colliders.extend(link.visuals.iter().flat_map(|vis| {
urdf_to_collider(&options, mesh_dir, &vis.geometry, &vis.origin) urdf_to_colliders(&options, mesh_dir, &vis.geometry, &vis.origin)
})) }))
} }
let mut body = urdf_to_rigid_body(&options, &link.inertial); let mut body = urdf_to_rigid_body(&options, &link.inertial);
@@ -488,66 +491,67 @@ fn urdf_to_rigid_body(options: &UrdfLoaderOptions, inertial: &Inertial) -> Rigid
builder.build() builder.build()
} }
fn urdf_to_collider( fn urdf_to_colliders(
options: &UrdfLoaderOptions, options: &UrdfLoaderOptions,
_mesh_dir: &Path, // NOTO: this isnt used if there is no external mesh feature enabled (like stl). mesh_dir: &Path,
geometry: &Geometry, geometry: &Geometry,
origin: &Pose, origin: &Pose,
) -> Option<Collider> { ) -> Vec<Collider> {
let mut builder = options.collider_blueprint.clone();
let mut shape_transform = Isometry::identity(); let mut shape_transform = Isometry::identity();
let shape = match &geometry {
Geometry::Box { size } => SharedShape::cuboid( let mut colliders = Vec::new();
size[0] as Real / 2.0,
size[1] as Real / 2.0, match &geometry {
size[2] as Real / 2.0, Geometry::Box { size } => {
), colliders.push(SharedShape::cuboid(
size[0] as Real / 2.0,
size[1] as Real / 2.0,
size[2] as Real / 2.0,
));
}
Geometry::Cylinder { radius, length } => { Geometry::Cylinder { radius, length } => {
// This rotation will make the cylinder Z-up as per the URDF spec, // This rotation will make the cylinder Z-up as per the URDF spec,
// instead of rapiers default Y-up. // instead of rapiers default Y-up.
shape_transform = Isometry::rotation(Vector::x() * Real::frac_pi_2()); shape_transform = Isometry::rotation(Vector::x() * Real::frac_pi_2());
SharedShape::cylinder(*length as Real / 2.0, *radius as Real) colliders.push(SharedShape::cylinder(
*length as Real / 2.0,
*radius as Real,
));
}
Geometry::Sphere { radius } => {
colliders.push(SharedShape::ball(*radius as Real));
} }
Geometry::Sphere { radius } => SharedShape::ball(*radius as Real),
Geometry::Mesh { filename, scale } => { Geometry::Mesh { filename, scale } => {
let path: &Path = filename.as_ref(); let full_path = mesh_dir.join(filename);
let _scale = scale let scale = scale
.map(|s| Vector::new(s.x as Real, s.y as Real, s.z as Real)) .map(|s| Vector::new(s.x as Real, s.y as Real, s.z as Real))
.unwrap_or_else(|| Vector::<Real>::repeat(1.0)); .unwrap_or_else(|| Vector::<Real>::repeat(1.0));
match path.extension().and_then(|ext| ext.to_str()) { let Ok(loaded_mesh) = rapier3d_meshloader::load_from_path(
#[cfg(feature = "stl")] full_path,
Some("stl") | Some("STL") => { &MeshConverter::TriMeshWithFlags(options.trimesh_flags),
use rapier3d::geometry::MeshConverter; scale,
let full_path = _mesh_dir.join(filename); ) else {
match rapier3d_stl::load_from_path( return Vec::new();
full_path, };
MeshConverter::TriMeshWithFlags(options.trimesh_flags), colliders.append(
_scale, &mut loaded_mesh
) { .into_iter()
Ok(stl_shape) => { .filter_map(|x| x.map(|s| s.shape).ok())
shape_transform = stl_shape.pose; .collect(),
stl_shape.shape );
}
Err(e) => {
log::error!("failed to load STL file {filename}: {e}");
return None;
}
}
}
_ => {
log::error!("failed to load file with unknown type {filename}");
return None;
}
}
} }
}; }
builder.shape = shape; colliders
Some( .drain(..)
builder .map(move |shape| {
.position(urdf_to_isometry(origin) * shape_transform) let mut builder = options.collider_blueprint.clone();
.build(), builder.shape = shape;
) builder
.position(urdf_to_isometry(origin) * shape_transform)
.build()
})
.collect()
} }
fn urdf_to_isometry(pose: &Pose) -> Isometry<Real> { fn urdf_to_isometry(pose: &Pose) -> Isometry<Real> {

View File

@@ -2,8 +2,8 @@
currdir=$(pwd) currdir=$(pwd)
### Publish rapier3d-stl. ### Publish rapier3d-meshloader.
cd "crates/rapier3d-stl" && cargo publish $DRY_RUN || exit 1 cd "crates/rapier3d-meshloader" && cargo publish $DRY_RUN || exit 1
cd "$currdir" || exit 2 cd "$currdir" || exit 2
### Publish rapier3d-urdf. ### Publish rapier3d-urdf.