Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Towards adding an SDFormat parser to this repo. #32

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Only [link](http://wiki.ros.org/urdf/XML/link) and [joint](http://wiki.ros.org/u
You can access urdf elements like below example.

```rust
let urdf_robo = urdf_rs::read_file("sample.urdf").unwrap();
let urdf_robo = urdf_rs::urdf::read_file("samples/sample.urdf").unwrap();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to keep urdf_rs::read_file() interface.
I think it's acceptable to move to urdf_rs::urdf::read_file, but urdf_rs::read_file should be kept.
How about reading sdf file if the extension is .sdf in urdf_rs::read_file ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would have to manage an enum return type then but we could add that.

Another option might be urdf_rs::read_urdf_file but IDK if that's any better really.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I understand about the type. I prefer to keep the current API.
I mean adding urdf_rs::read_stf_file()

let links = urdf_robo.links;
println!("{:?}", links[0].visual[0].origin.xyz);
let joints = urdf_robo.joints;
Expand Down
6 changes: 6 additions & 0 deletions samples/minimal.sdf
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version='1.0'?>
<sdf version='1.9'>
<model name='my_model'>
<link name='link'/>
</model>
</sdf>
File renamed without changes.
5 changes: 5 additions & 0 deletions src/common.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod elements;
pub use elements::*;

mod space_seperated_vectors;
pub use space_seperated_vectors::*;
38 changes: 38 additions & 0 deletions src/common/elements.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use crate::common::space_seperated_vectors::*;
use serde::Deserialize;

#[derive(Debug, Deserialize, Default, Clone)]
pub struct Mass {
pub value: f64,
}

#[derive(Deserialize, Debug, Clone)]
pub struct Vec3 {
#[serde(with = "ss_vec3")]
pub data: [f64; 3],
}

#[derive(Debug, Deserialize, Default, Clone)]
pub struct ColorRGBA {
#[serde(with = "ss_vec4")]
pub rgba: [f64; 4],
}

#[derive(Debug, Deserialize, Default, Clone)]
pub struct ColorRGB {
#[serde(with = "ss_vec3")]
pub rgba: [f64; 3],
}

#[derive(Debug, Deserialize, Clone)]
pub struct Texture {
pub filename: String,
}

impl Default for Texture {
fn default() -> Texture {
Texture {
filename: "".to_string(),
}
}
}
68 changes: 68 additions & 0 deletions src/common/space_seperated_vectors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
pub mod ss_vec3 {
use serde::{self, Deserialize, Deserializer};
pub fn deserialize<'a, D>(deserializer: D) -> Result<[f64; 3], D::Error>
where
D: Deserializer<'a>,
{
let s = String::deserialize(deserializer)?;
let vec = s
.split(' ')
.filter_map(|x| x.parse::<f64>().ok())
.collect::<Vec<_>>();
if vec.len() != 3 {
return Err(serde::de::Error::custom(format!(
"failed to parse float array in {s}"
)));
}
let mut arr = [0.0f64; 3];
arr.copy_from_slice(&vec);
Ok(arr)
}
}

pub mod ss_option_vec3 {
use serde::{self, Deserialize, Deserializer};
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<[f64; 3]>, D::Error>
where
D: Deserializer<'a>,
{
let s = String::deserialize(deserializer)?;
let vec = s
.split(' ')
.filter_map(|x| x.parse::<f64>().ok())
.collect::<Vec<_>>();
if vec.is_empty() {
Ok(None)
} else if vec.len() == 3 {
let mut arr = [0.0; 3];
arr.copy_from_slice(&vec);
Ok(Some(arr))
} else {
Err(serde::de::Error::custom(format!(
"failed to parse float array in {s}"
)))
}
}
}

pub mod ss_vec4 {
use serde::{self, Deserialize, Deserializer};
pub fn deserialize<'a, D>(deserializer: D) -> Result<[f64; 4], D::Error>
where
D: Deserializer<'a>,
{
let s = String::deserialize(deserializer)?;
let vec = s
.split(' ')
.filter_map(|x| x.parse::<f64>().ok())
.collect::<Vec<_>>();
if vec.len() != 4 {
return Err(serde::de::Error::custom(format!(
"failed to parse float array in {s}"
)));
}
let mut arr = [0.0f64; 4];
arr.copy_from_slice(&vec);
Ok(arr)
}
}
13 changes: 4 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
#![doc = include_str!("../README.md")]
#![warn(missing_debug_implementations, rust_2018_idioms)]

mod common;
mod errors;
pub use errors::*;

mod deserialize;
pub use deserialize::*;

mod funcs;
pub use funcs::*;

pub mod utils;
pub mod ros_utils;
pub mod sdf;
pub mod urdf;
9 changes: 6 additions & 3 deletions src/utils.rs → src/ros_utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use crate::deserialize::Robot;
//! ROS-specific functions that make use of `rosrun` and `rospack` as
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rename also changes the interface, but it might be accepted. Because it's reasonable.

//! subprocesses.

use crate::errors::*;
use crate::funcs::*;
use crate::urdf::Robot;
use crate::urdf::{read_file, read_from_string};

use once_cell::sync::Lazy;
use regex::Regex;
Expand Down Expand Up @@ -91,6 +94,6 @@ fn it_works() {
expand_package_path("/home/aaa.obj", Some(Path::new(""))),
"/home/aaa.obj"
);
assert!(read_urdf_or_xacro("sample.urdf").is_ok());
assert!(read_urdf_or_xacro("samples/sample.urdf").is_ok());
assert!(read_urdf_or_xacro("sample_urdf").is_err());
}
8 changes: 8 additions & 0 deletions src/sdf.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
mod deserialize;
pub use deserialize::*;

mod funcs;
pub use funcs::*;

pub use crate::errors::*;
pub type SdfError = UrdfError;
214 changes: 214 additions & 0 deletions src/sdf/deserialize.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
// use crate::common::*;
use serde::Deserialize;

// #[derive(Debug, Deserialize, Clone)]
// #[serde(rename_all = "snake_case")]
// pub enum Geometry {
// Empty,
// Box {
// #[serde(with = "ss_vec3")]
// size: [f64; 3],
// },
// Capsule {
// radius: f64,
// length: f64,
// },
// Cylinder {
// radius: f64,
// length: f64,
// },
// // Ellipsoid,
// // Heightmap,
// // Image,
// Mesh {
// filename: String,
// #[serde(with = "crate::common::ss_option_vec3", default)]
// scale: Option<[f64; 3]>,
// },
// // Plane,
// // Polyline,
// Sphere {
// radius: f64,
// },
// }

// impl Default for Geometry {
// fn default() -> Geometry {
// Geometry::Box {
// size: [0.0f64, 0.0, 0.0],
// }
// }
// }

// #[derive(Debug, Deserialize, Default, Clone)]
// pub struct Material {
// pub name: String,
// pub color: Option<ColorRGBA>,
// pub texture: Option<Texture>,
// }

// #[derive(Debug, Deserialize, Default, Clone)]
// pub struct Visual {
// pub name: Option<String>,
// #[serde(default)]
// pub origin: Pose,
// pub geometry: Geometry,
// pub material: Option<Material>,
// }

// /// Urdf Link element
// /// See <http://wiki.ros.org/urdf/XML/link> for more detail.
// #[derive(Debug, Deserialize, Clone)]
// pub struct Link {
// pub name: String,
// #[serde(default)]
// pub pose: Pose,
// #[serde(default)]
// pub visual: Vec<Visual>,
// }

// #[derive(Debug, Deserialize, Clone)]
// pub struct Axis {
// #[serde(with = "crate::common::ss_vec3")]
// pub xyz: [f64; 3],
// }

// impl Default for Axis {
// fn default() -> Axis {
// Axis {
// xyz: [0.0f64, 0.0, 1.0],
// }
// }
// }

// #[derive(Debug, Deserialize, Clone)]
// pub struct Pose {
// #[serde(with = "crate::common::ss_vec3")]
// #[serde(default = "default_zero3")]
// pub xyz: [f64; 3],
// #[serde(with = "crate::common::ss_vec3")]
// #[serde(default = "default_zero3")]
// pub rpy: [f64; 3],
// }

// fn default_zero3() -> [f64; 3] {
// [0.0f64, 0.0, 0.0]
// }

// impl Default for Pose {
// fn default() -> Pose {
// Pose {
// xyz: default_zero3(),
// rpy: default_zero3(),
// }
// }
// }

// #[derive(Debug, Deserialize, Clone)]
// pub struct LinkName {
// pub link: String,
// }

// #[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
// #[serde(rename_all = "snake_case")]
// pub enum JointType {
// Revolute,
// Continuous,
// Prismatic,
// Fixed,
// Floating,
// Planar,
// Spherical,
// }

// #[derive(Debug, Deserialize, Default, Clone)]
// pub struct JointLimit {
// #[serde(default)]
// pub lower: f64,
// #[serde(default)]
// pub upper: f64,
// pub effort: f64,
// pub velocity: f64,
// }

// /// Urdf Joint element
// /// See <http://wiki.ros.org/urdf/XML/joint> for more detail.
// #[derive(Debug, Deserialize, Clone)]
// pub struct Joint {
// pub name: String,
// #[serde(rename = "type")]
// pub joint_type: JointType,
// #[serde(default)]
// pub origin: Pose,
// pub parent: LinkName,
// pub child: LinkName,
// #[serde(default)]
// pub axis: Axis,
// #[serde(default)]
// pub limit: JointLimit,
// }

/// Top level struct representing an SDFormat <model> element.
/// http://sdformat.org/spec?ver=1.9&elem=model
#[derive(Debug, Deserialize, Clone, PartialEq)]
pub struct Model {
#[serde(default)]
pub name: String,
// #[serde(rename = "link", default)]
// pub links: Vec<Link>,

// #[serde(rename = "joint", default)]
// pub joints: Vec<Joint>,

// #[serde(rename = "material", default)]
// pub materials: Vec<Material>,
}

/// Top level struct representing an SDFormat <world> element.
/// http://sdformat.org/spec?ver=1.9&elem=world
#[derive(Debug, Deserialize, Clone, PartialEq)]
#[serde(rename = "world")]
pub struct World {
#[serde(default)]
pub name: String,
// #[serde(rename = "frame", default)]
// pub frames: Vec<Frame>,
#[serde(rename = "model", default)]
pub models: Vec<Model>,
}

impl World {
pub fn models(&self) -> Vec<&Model> {
self.models.iter().collect()
}
}

/// Top level enum to access root element of a parsed sdf.
/// http://sdformat.org/spec?ver=1.9&elem=sdf
#[derive(Debug, Clone, PartialEq)]
pub enum Sdf {
Model(Model),
Worlds(Vec<World>),
// TODO: Actor
// TODO: Light
}

impl Sdf {
pub fn models(&self) -> Vec<&Model> {
match &self {
Sdf::Model(m) => {
vec![&m]
},
Sdf::Worlds(ws) => ws.iter().map(|w| w.models()).flatten().collect(),
}
}
}

#[derive(Debug, Deserialize, Clone, PartialEq)]
#[serde(rename = "sdf")]
pub struct SDFormat {
#[serde(rename = "world", default)]
pub worlds: Vec<World>,
#[serde(rename = "model", default)]
pub models: Vec<Model>,
}
Loading