nphysics3d/
lib.rs

1/*!
2nphysics
3========
4**nphysics** is a 2 and 3-dimensional physics engine for games and animations.
5It uses [ncollide](http://ncollide.org) for collision detection, and
6[nalgebra](http://nalgebra.org) for vector/matrix math. 2D and 3D
7implementations both share the same code!
8
9
10Examples are available in the `examples2d` and `examples3d` directories. There
11is also a short (outdated) [demonstration video](http://youtu.be/CANjXZ5rocI).
12An on-line version of this documentation is available
13[here](http://nphysics.org). Feel free to ask for help and discuss features on
14the official [user forum](http://users.nphysics.org).
15
16## Why another physics engine?
17There are a lot of physics engine out there.
18However having a physics engine written in Rust is much more fun than
19writing bindings and has several advantages:
20
21- it shows that Rust is suitable for soft real-time applications
22- it shows how well Rust behaves with highly generic code
23- it shows that there is no need to write two separate engine for 2D and 3D:
24  genericity wrt the dimension is possible (modulo low level arithmetic
25  specializations for each dimension).
26- in a not-that-near future, C++ will die of ugliness. Then, people will
27  search for a physics engine and **nphysics** will be there, proudly
28  exhibiting its _Rusty_ sexyness.
29
30
31## Features
32- Static and dynamic rigid bodies.
33- Common convex primitives: cone, box, ball, cylinder.
34- Concave geometries build from convex primitives (aka. compound geometries).
35- Stable stacking.
36- Island based sleeping (objects deactivation).
37- Ray casting.
38- Swept sphere based continuous collision detection.
39- Ball-in-socket joint.
40- FixedJoint joint.
41- Sensors.
42- Deformable bodies (aka. soft-bodies)
43- Kinematic bodies
44
45## What is missing?
46**nphysics** is a very young library and needs to learn a lot of things to
47become a grown up. Many missing features are because of missing features on
48**ncollide**. Features missing from **nphysics** itself include:
49
50- more joints, joint limits, joint motors and breakable joints.
51- parallel pipeline
52- GPU-based pipeline
53
54## Dependencies
55All dependencies are automatically cloned with a recursive clone.
56The libraries needed to compile the physics engine are:
57
58* [ncollide](http://ncollide.org): the collision detection library.
59* [nalgebra](http://nalgebra.org): the linear algebra library.
60
61The libraries needed to compile the examples are:
62
63*/
64#![deny(non_camel_case_types)]
65#![deny(unused_parens)]
66#![deny(non_upper_case_globals)]
67#![deny(unused_qualifications)]
68#![deny(missing_docs)] // FIXME: deny this
69#![deny(unused_results)]
70#![deny(bare_trait_objects)]
71#![allow(type_alias_bounds)]
72#![warn(non_camel_case_types)]
73#![allow(missing_copy_implementations)]
74#![doc(html_root_url = "http://nphysics.org/rustdoc/")]
75
76#[macro_use]
77extern crate approx;
78#[macro_use]
79extern crate downcast_rs;
80#[macro_use]
81extern crate bitflags;
82
83extern crate nalgebra as na;
84#[cfg(feature = "dim2")]
85extern crate ncollide2d as ncollide;
86#[cfg(feature = "dim3")]
87extern crate ncollide3d as ncollide;
88extern crate num_traits as num;
89
90//#[cfg(test)]
91//extern crate test;
92
93macro_rules! try_ret {
94    ($val: expr) => {
95        try_ret!($val, ())
96    };
97    ($val: expr, $ret: expr) => {
98        if let Some(val) = $val {
99            val
100        } else {
101            return $ret;
102        }
103    };
104}
105
106macro_rules! try_continue {
107    ($val: expr) => {
108        if let Some(val) = $val {
109            val
110        } else {
111            continue;
112        }
113    };
114}
115
116macro_rules! desc_setters(
117    ($($with_method: ident, $set_method: ident $(, $arg: ident: $t: ty)*)*) => {
118        $(
119            #[allow(missing_docs)]
120            #[inline]
121            pub fn $with_method(mut self $(, $arg: $t)*) -> Self {
122                $(
123                    self.$arg = $arg;
124                )*
125                self
126            }
127
128            #[allow(missing_docs)]
129            #[inline]
130            pub fn $set_method(&mut self $(, $arg: $t)*) -> &mut Self {
131                $(
132                    self.$arg = $arg;
133                )*
134                self
135            }
136        )*
137    }
138);
139
140macro_rules! desc_custom_setters(
141    ($($this: ident.$with_method: ident, $set_method: ident $(, $arg: ident: $t: ty)* | $imp: expr)*) => {
142        $(
143            #[allow(missing_docs)]
144            #[inline]
145            pub fn $with_method(mut $this $(, $arg: $t)*) -> Self {
146                $imp
147                $this
148            }
149
150            #[allow(missing_docs)]
151            #[inline]
152            pub fn $set_method(&mut $this $(, $arg: $t)*) -> &mut Self {
153                $imp
154                $this
155            }
156        )*
157    }
158);
159
160macro_rules! desc_custom_getters(
161    ($($this: ident.$get_method: ident: $t: ty | $imp: expr)*) => {
162        $(
163            #[allow(missing_docs)]
164            #[inline]
165            pub fn $get_method(&$this) -> $t {
166                $imp
167            }
168        )*
169    }
170);
171
172macro_rules! desc_getters(
173    ($([val] $name: ident -> $val: ident: $t: ty)* $([ref] $ref_name: ident -> $ref_val: ident: $ref_t: ty)*) => {
174        $(
175            #[allow(missing_docs)]
176            #[inline]
177            pub fn $name(&self) -> $t {
178                self.$val
179            }
180        )*
181        $(
182            #[allow(missing_docs)]
183            #[inline]
184            pub fn $ref_name(&self) -> &$ref_t {
185                &self.$ref_val
186            }
187        )*
188    }
189);
190
191macro_rules! user_data_accessors(
192    () => {
193        /// Retrieves a reference to the user-defined user-data attached to this object.
194        #[inline]
195        pub fn user_data(&self) -> Option<&(dyn Any + Send + Sync)> {
196            self.user_data.as_deref()
197        }
198
199        /// Retrieves a mutable reference to the user-defined user-data attached to this object.
200        #[inline]
201        pub fn user_data_mut(&mut self) -> Option<&mut (dyn Any + Send + Sync)> {
202            self.user_data.as_deref_mut()
203        }
204
205        /// Sets the user-defined data attached to this object.
206        #[inline]
207        pub fn set_user_data(&mut self, data: Option<Box<dyn Any + Send + Sync>>) -> Option<Box<dyn Any + Send + Sync>> {
208            std::mem::replace(&mut self.user_data, data)
209        }
210
211        /// Replace by `None` the user-defined data attached to this object and returns the old value.
212        #[inline]
213        pub fn take_user_data(&mut self) -> Option<Box<dyn Any + Send + Sync>> {
214            self.user_data.take()
215        }
216    }
217);
218
219macro_rules! user_data_desc_accessors(
220    () => {
221        /// Sets a user-data to be attached to the object being built.
222        pub fn user_data(mut self, data: impl UserData) -> Self {
223            self.user_data = Some(UserDataBox(Box::new(data) as Box<dyn UserData>));
224            self
225        }
226
227        /// Sets the user-data to be attached to the object being built.
228        pub fn set_user_data(&mut self, data: Option<impl UserData>) -> &mut Self {
229            self.user_data = data.map(|data| UserDataBox(Box::new(data) as Box<dyn UserData>));
230            self
231        }
232
233        /// Reference to the user-data to be attached to the object being built.
234        pub fn get_user_data(&self) -> Option<&(dyn Any + Send + Sync)> {
235            self.user_data.as_ref().map(|data| data.0.as_any())
236        }
237    }
238);
239
240const NOT_REGISTERED_ERROR: &'static str =
241    "This collider has not been registered into a world (proxy indexes are None).";
242
243pub mod algebra;
244pub mod counters;
245pub mod detection;
246pub mod force_generator;
247pub mod joint;
248pub mod material;
249pub mod object;
250pub mod solver;
251pub mod utils;
252pub mod volumetric;
253pub mod world;
254// mod tests;
255
256pub use nalgebra;
257#[cfg(feature = "dim2")]
258pub use ncollide2d;
259#[cfg(feature = "dim3")]
260pub use ncollide3d;
261pub use simba;
262
263/// Compilation flags dependent aliases for mathematical types.
264#[cfg(feature = "dim3")]
265pub mod math {
266    use crate::algebra::{Force3, Inertia3, Velocity3};
267    use na::{
268        Dynamic, Isometry3, Matrix3, Matrix6, OMatrix, MatrixSlice6xX, MatrixSliceMut6xX, Point3,
269        Rotation3, Translation3, UnitQuaternion, Vector3, Vector6, U3, U6,
270    };
271
272    pub use crate::algebra::ForceType;
273
274    /// The maximum number of possible rotations and translations of a rigid body.
275    pub const SPATIAL_DIM: usize = 6;
276    /// The maximum number of possible rotations of a rigid body.
277    pub const ANGULAR_DIM: usize = 3;
278    /// The maximum number of possible translations of a rigid body.
279    pub const DIM: usize = 3;
280
281    /// The dimension of the ambiant space.
282    pub type Dim = U3;
283
284    /// The dimension of a spatial vector.
285    pub type SpatialDim = U6;
286
287    /// The dimension of the rotations.
288    pub type AngularDim = U3;
289
290    /// The point type.
291    pub type Point<N> = Point3<N>;
292
293    /// The angular vector type.
294    pub type AngularVector<N> = Vector3<N>;
295
296    /// The vector type.
297    pub type Vector<N> = Vector3<N>;
298
299    /// The vector type with dimension `SpatialDim × 1`.
300    pub type SpatialVector<N> = Vector6<N>;
301
302    /// The orientation type.
303    pub type Orientation<N> = Vector3<N>;
304
305    /// The transformation matrix type.
306    pub type Isometry<N> = Isometry3<N>;
307
308    /// The rotation type.
309    pub type Rotation<N> = UnitQuaternion<N>;
310
311    /// The rotation matrix type.
312    pub type RotationMatrix<N> = Rotation3<N>;
313
314    /// The translation type.
315    pub type Translation<N> = Translation3<N>;
316
317    /// The velocity type combining the linear velocity and the angular velocity.
318    pub type Velocity<N> = Velocity3<N>;
319
320    /// The force type combining a linear force and a torque.
321    pub type Force<N> = Force3<N>;
322
323    /// The inertia tensor type.
324    pub type AngularInertia<N> = Matrix3<N>;
325
326    /// The inertia type.
327    pub type Inertia<N> = Inertia3<N>;
328
329    /// The inertia matrix type.
330    pub type InertiaMatrix<N> = Matrix6<N>;
331
332    /// Square matrix with dimension `Dim × Dim`.
333    pub type Matrix<N> = Matrix3<N>;
334
335    /// Square matrix with dimension `SpatialDim × SpatialDim`.
336    pub type SpatialMatrix<N> = Matrix6<N>;
337
338    /// The type of a constraint jacobian in twist coordinates.
339    pub type Jacobian<N> = OMatrix<N, U6, Dynamic>;
340
341    /// The type of a slice of the constraint jacobian in twist coordinates.
342    pub type JacobianSlice<'a, N> = MatrixSlice6xX<'a, N>;
343
344    /// The type of a mutable slice of the constraint jacobian in twist coordinates.
345    pub type JacobianSliceMut<'a, N> = MatrixSliceMut6xX<'a, N>;
346}
347
348/// Compilation flags dependent aliases for mathematical types.
349#[cfg(feature = "dim2")]
350pub mod math {
351    use crate::algebra::{Force2, Inertia2, Velocity2};
352    use na::{
353        Dynamic, Isometry2, Matrix1, Matrix2, Matrix3, OMatrix, MatrixSlice3xX, MatrixSliceMut3xX,
354        Point2, Rotation2, Translation2, UnitComplex, Vector1, Vector2, Vector3, U1, U2, U3,
355    };
356
357    pub use crate::algebra::ForceType;
358
359    /// The maximum number of possible rotations and translations of a rigid body.
360    pub const SPATIAL_DIM: usize = 3;
361    /// The maximum number of possible rotations of a rigid body.
362    pub const ANGULAR_DIM: usize = 1;
363    /// The maximum number of possible translations of a rigid body.
364    pub const DIM: usize = 2;
365
366    /// The dimension of the ambient space.
367    pub type Dim = U2;
368
369    /// The dimension of the rotation.
370    pub type AngularDim = U1;
371
372    /// The dimension of a spatial vector.
373    pub type SpatialDim = U3;
374
375    /// The point type.
376    pub type Point<N> = Point2<N>;
377
378    /// The vector type with dimension `SpatialDim × 1`.
379    pub type SpatialVector<N> = Vector3<N>;
380
381    /// The angular vector type.
382    pub type AngularVector<N> = Vector1<N>;
383
384    /// The vector type.
385    pub type Vector<N> = Vector2<N>;
386
387    /// The orientation type.
388    pub type Orientation<N> = Vector1<N>;
389
390    /// The transformation matrix type.
391    pub type Isometry<N> = Isometry2<N>;
392
393    /// The rotation type.
394    pub type Rotation<N> = UnitComplex<N>;
395
396    /// The rotation matrix type.
397    pub type RotationMatrix<N> = Rotation2<N>;
398
399    /// The translation type.
400    pub type Translation<N> = Translation2<N>;
401
402    /// The velocity type combining the linear velocity and the angular velocity.
403    pub type Velocity<N> = Velocity2<N>;
404
405    /// The force type combining a linear force and a torque.
406    pub type Force<N> = Force2<N>;
407
408    /// The inertia tensor type.
409    pub type AngularInertia<N> = Matrix1<N>;
410
411    /// The inertia type.
412    pub type Inertia<N> = Inertia2<N>;
413
414    /// The inertia matrix type.
415    pub type InertiaMatrix<N> = Matrix3<N>;
416
417    /// Square matrix with dimension `Dim × Dim`.
418    pub type Matrix<N> = Matrix2<N>;
419
420    /// Square matrix with dimension `SpatialDim × SpatialDim`.
421    pub type SpatialMatrix<N> = Matrix3<N>;
422
423    /// The type of a constraint jacobian in twist coordinates.
424    pub type Jacobian<N> = OMatrix<N, U3, Dynamic>;
425
426    /// The type of a slice of the constraint jacobian in twist coordinates.
427    pub type JacobianSlice<'a, N> = MatrixSlice3xX<'a, N>;
428
429    /// The type of a mutable slice of the constraint jacobian in twist coordinates.
430    pub type JacobianSliceMut<'a, N> = MatrixSliceMut3xX<'a, N>;
431}