1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
/* Copyright 2017 Takashi Ogura Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //! Joint related structs use errors::*; use na::{Isometry3, RealField, Translation3, Unit, UnitQuaternion, Vector3}; use std::cell::RefCell; use std::fmt::{self, Display}; #[derive(Clone, Debug, Copy)] pub struct Velocity<T: RealField> { pub translation: Vector3<T>, pub rotation: Vector3<T>, } impl<T> Velocity<T> where T: RealField, { pub fn new() -> Self { Self::zero() } pub fn from_parts(translation: Vector3<T>, rotation: Vector3<T>) -> Self { Self { translation, rotation, } } pub fn zero() -> Self { Self { translation: Vector3::zeros(), rotation: Vector3::zeros(), } } } impl<T> Default for Velocity<T> where T: RealField, { fn default() -> Self { Self::new() } } /// Type of Joint, `Fixed`, `Rotational`, `Linear` is supported now #[derive(Copy, Debug, Clone)] pub enum JointType<T: RealField> { /// Fixed joint. It has no `joint_position` and axis. Fixed, /// Rotational joint around axis. It has an position [rad]. Rotational { /// axis of the joint axis: Unit<Vector3<T>>, }, /// Linear joint. position is length Linear { /// axis of the joint axis: Unit<Vector3<T>>, }, } fn axis_to_string<T: RealField>(axis: &Unit<Vector3<T>>) -> &str { if *axis == Vector3::x_axis() { "+X" } else if *axis == Vector3::y_axis() { "+Y" } else if *axis == Vector3::z_axis() { "+Z" } else if *axis == -Vector3::x_axis() { "-X" } else if *axis == -Vector3::y_axis() { "-Y" } else if *axis == -Vector3::z_axis() { "-Z" } else { "" } } impl<T: RealField> Display for JointType<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { JointType::Fixed => write!(f, "[⚓]"), JointType::Rotational { axis } => write!(f, "[⚙{}]", axis_to_string(axis)), JointType::Linear { axis } => write!(f, "[↕{}]", axis_to_string(axis)), } } } /// min/max range to check the joint position #[derive(Copy, Debug, Clone)] pub struct Range<T: RealField> { pub min: T, pub max: T, } impl<T> Range<T> where T: RealField, { /// Create new Range instance /// /// # Examples /// /// ``` /// let range = k::joint::Range::new(-1.0, 1.0); /// ``` pub fn new(min: T, max: T) -> Self { Range { min, max } } /// Check if the value is in the range /// /// `true` means it is OK. /// If the val is the same as the limit value (`min` or `max`), it returns true (valid). /// /// # Examples /// /// ``` /// let range = k::joint::Range::new(-1.0, 1.0); /// assert!(range.is_valid(0.0)); /// assert!(range.is_valid(1.0)); /// assert!(!range.is_valid(1.5)); /// ``` pub fn is_valid(&self, val: T) -> bool { val <= self.max && val >= self.min } } impl<T> From<::std::ops::RangeInclusive<T>> for Range<T> where T: RealField, { /// # Examples /// /// ``` /// let range : k::joint::Range<f64> = (-1.0..=1.0).into(); /// assert!(range.is_valid(0.0)); /// assert!(range.is_valid(1.0)); /// assert!(!range.is_valid(1.5)); /// ``` fn from(range: ::std::ops::RangeInclusive<T>) -> Self { let (min, max) = range.into_inner(); Range { min, max } } } /// Information for copying joint state of other joint /// /// For example, `Mimic` is used to calculate the position of the gripper(R) from /// gripper(L). In that case, the code like below will be used. /// /// ``` /// let mimic_for_gripper_r = k::joint::Mimic::new(-1.0, 0.0); /// ``` /// /// output position (mimic_position() is calculated by `joint positions = joint[name] * multiplier + origin` /// #[derive(Debug, Clone)] pub struct Mimic<T: RealField> { pub multiplier: T, pub origin: T, } impl<T> Mimic<T> where T: RealField, { /// Create new instance of Mimic /// /// # Examples /// /// ``` /// let m = k::joint::Mimic::<f64>::new(1.0, 0.5); /// ``` pub fn new(multiplier: T, origin: T) -> Self { Mimic { multiplier, origin } } /// Calculate the mimic joint position /// /// # Examples /// /// ``` /// let m = k::joint::Mimic::<f64>::new(1.0, 0.5); /// assert_eq!(m.mimic_position(0.2), 0.7); // 0.2 * 1.0 + 0.5 /// ``` /// /// ``` /// let m = k::joint::Mimic::<f64>::new(-2.0, -0.4); /// assert_eq!(m.mimic_position(0.2), -0.8); // 0.2 * -2.0 - 0.4 /// ``` pub fn mimic_position(&self, from_position: T) -> T { from_position * self.multiplier + self.origin } } /// Joint with type #[derive(Debug, Clone)] pub struct Joint<T: RealField> { /// Name of this joint pub name: String, /// Type of this joint pub joint_type: JointType<T>, /// position (angle) of this joint position: T, /// velocity of this joint velocity: T, /// Limits of this joint pub limits: Option<Range<T>>, /// local origin transform of joint origin: Isometry3<T>, /// cache of world transform world_transform_cache: RefCell<Option<Isometry3<T>>>, /// cache of world velocity world_velocity_cache: RefCell<Option<Velocity<T>>>, } impl<T> Joint<T> where T: RealField, { /// Create new Joint with name and type /// /// # Examples /// /// ``` /// extern crate nalgebra as na; /// extern crate k; /// /// // create fixed joint /// let fixed = k::Joint::<f32>::new("f0", k::JointType::Fixed); /// assert!(fixed.joint_position().is_none()); /// /// // create rotational joint with Y-axis /// let rot = k::Joint::<f64>::new("r0", k::JointType::Rotational { axis: na::Vector3::y_axis() }); /// assert_eq!(rot.joint_position().unwrap(), 0.0); /// ``` /// pub fn new(name: &str, joint_type: JointType<T>) -> Joint<T> { Joint { name: name.to_string(), joint_type, position: T::zero(), velocity: T::zero(), limits: None, origin: Isometry3::identity(), world_transform_cache: RefCell::new(None), world_velocity_cache: RefCell::new(None), } } /// Set the position of the joint /// /// It returns Err if it is out of the limits, or this is fixed joint. /// /// # Examples /// /// ``` /// extern crate nalgebra as na; /// extern crate k; /// /// // Create fixed joint /// let mut fixed = k::Joint::<f32>::new("f0", k::JointType::Fixed); /// // Set position to fixed joint always fails /// assert!(fixed.set_joint_position(1.0).is_err()); /// /// // Create rotational joint with Y-axis /// let mut rot = k::Joint::<f64>::new("r0", k::JointType::Rotational { axis: na::Vector3::y_axis() }); /// // As default, it has not limit /// /// // Initial position is 0.0 /// assert_eq!(rot.joint_position().unwrap(), 0.0); /// // If it has no limits, set_joint_position always succeeds. /// rot.set_joint_position(0.2).unwrap(); /// assert_eq!(rot.joint_position().unwrap(), 0.2); /// ``` /// pub fn set_joint_position(&mut self, position: T) -> Result<(), JointError> { if let JointType::Fixed = self.joint_type { return Err(JointError::OutOfLimitError { joint_name: self.name.to_string(), message: "Joint is Fixed".to_owned(), }); } if let Some(ref range) = self.limits { if !range.is_valid(position) { return Err(JointError::OutOfLimitError { joint_name: self.name.to_string(), message: format!( "Joint is out of range: input={}, range={:?}", position, range ), }); } } self.position = position; // TODO: have to reset descendent `world_transform_cache` self.world_transform_cache.replace(None); self.world_velocity_cache.replace(None); Ok(()) } pub fn set_joint_position_unchecked(&mut self, position: T) { self.position = position; // TODO: have to reset descendent `world_transform_cache` self.world_transform_cache.replace(None); self.world_velocity_cache.replace(None); } /// Returns the position (angle) #[inline] pub fn joint_position(&self) -> Option<T> { match self.joint_type { JointType::Fixed => None, _ => Some(self.position), } } #[inline] pub fn origin(&self) -> &Isometry3<T> { &self.origin } #[inline] pub fn set_origin(&mut self, origin: Isometry3<T>) { self.origin = origin; self.world_transform_cache.replace(None); } pub fn set_joint_velocity(&mut self, velocity: T) -> Result<(), JointError> { if let JointType::Fixed = self.joint_type { return Err(JointError::OutOfLimitError { joint_name: self.name.to_string(), message: "Joint is Fixed".to_owned(), }); } self.velocity = velocity; self.world_velocity_cache.replace(None); Ok(()) } /// Returns the velocity #[inline] pub fn joint_velocity(&self) -> Option<T> { match self.joint_type { JointType::Fixed => None, _ => Some(self.velocity), } } /// Calculate and returns the transform of the end of this joint /// /// # Examples /// /// ``` /// extern crate nalgebra as na; /// extern crate k; /// /// // Create linear joint with X-axis /// let mut lin = k::Joint::<f64>::new("l0", k::JointType::Linear { axis: na::Vector3::x_axis() }); /// assert_eq!(lin.local_transform().translation.vector.x, 0.0); /// lin.set_joint_position(-1.0).unwrap(); /// assert_eq!(lin.local_transform().translation.vector.x, -1.0); /// ``` /// pub fn local_transform(&self) -> Isometry3<T> { let joint_transform = match self.joint_type { JointType::Fixed => Isometry3::identity(), JointType::Rotational { axis } => Isometry3::from_parts( Translation3::new(T::zero(), T::zero(), T::zero()), UnitQuaternion::from_axis_angle(&axis, self.position), ), JointType::Linear { axis } => Isometry3::from_parts( Translation3::from(axis.into_inner() * self.position), UnitQuaternion::identity(), ), }; self.origin * joint_transform } #[inline] pub(crate) fn set_world_transform(&self, world_transform: Isometry3<T>) { self.world_transform_cache.replace(Some(world_transform)); } #[inline] pub(crate) fn set_world_velocity(&self, world_velocity: Velocity<T>) { self.world_velocity_cache.replace(Some(world_velocity)); } /// Get the result of forward kinematics /// /// The value is updated by `Chain::update_transforms` #[inline] pub fn world_transform(&self) -> Option<Isometry3<T>> { *self.world_transform_cache.borrow() } #[inline] pub fn world_velocity(&self) -> Option<Velocity<T>> { *self.world_velocity_cache.borrow() } #[inline] pub fn is_movable(&self) -> bool { match self.joint_type { JointType::Fixed => false, _ => true, } } } impl<T: RealField> Display for Joint<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {}", self.name, self.joint_type) } }