ferravex_dynamics/
lib.rs

1//! Original, dependency-free 2D/3D translational rigid-body physics.
2//!
3//! The same fixed-step solver handles circles/spheres and **axis-aligned** boxes.
4//! This foundation deliberately does not claim a full rotational rigid-body or
5//! general-purpose dynamics API. See the crate README for numerical and feature limits.
6//!
7//! ```
8//! use ferravex_dynamics::{BodyDesc, PhysicsWorld, Shape};
9//! let mut world = PhysicsWorld::<3>::new([0., -9.81, 0.]);
10//! world.insert(BodyDesc::fixed(Shape::cuboid([5., 0.5, 5.]), [0., -0.5, 0.])).unwrap();
11//! let ball = world.insert(BodyDesc::dynamic(Shape::ball(0.5), [0., 3., 0.], 1.)).unwrap();
12//! for _ in 0..240 { world.step(1. / 120.).unwrap(); }
13//! assert!((world.body(ball).unwrap().position()[1] - 0.5).abs() < 0.02);
14//! ```
15mod character;
16mod collision;
17mod math;
18mod world;
19pub use character::{CharacterMotion, CharacterSettings};
20pub use collision::{SweepHit, SweepHitKind};
21use math::*;
22pub use world::{PhysicsWorld, StepStats};
23
24/// Non-reusable identity: removing a body invalidates its handle immediately.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub struct BodyHandle {
27    pub(crate) index: u32,
28    pub(crate) generation: u32,
29}
30impl BodyHandle {
31    pub fn index(self) -> u32 {
32        self.index
33    }
34    pub fn generation(self) -> u32 {
35        self.generation
36    }
37}
38
39#[derive(Clone, Copy, Debug, PartialEq)]
40pub enum Shape<const D: usize> {
41    Ball { radius: f32 },
42    Box { half_extents: [f32; D] },
43}
44impl<const D: usize> Shape<D> {
45    pub const fn ball(radius: f32) -> Self {
46        Self::Ball { radius }
47    }
48    /// All sizes are half extents, not full dimensions.
49    pub const fn cuboid(half_extents: [f32; D]) -> Self {
50        Self::Box { half_extents }
51    }
52    pub(crate) fn valid(self) -> bool {
53        match self {
54            Self::Ball { radius } => radius.is_finite() && (1e-5..=1_000_000.).contains(&radius),
55            Self::Box { half_extents } => {
56                valid(half_extents) && half_extents.iter().all(|v| *v >= 1e-5)
57            }
58        }
59    }
60    pub(crate) fn half(self) -> [f32; D] {
61        match self {
62            Self::Ball { radius } => [radius; D],
63            Self::Box { half_extents } => half_extents,
64        }
65    }
66}
67
68#[derive(Clone, Copy, Debug, PartialEq)]
69pub enum BodyKind {
70    Static,
71    /// Kinematic bodies integrate their velocity but never receive solver impulses.
72    Kinematic,
73    Dynamic {
74        mass: f32,
75    },
76}
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub struct CollisionLayers {
79    pub membership: u32,
80    pub filter: u32,
81}
82impl Default for CollisionLayers {
83    fn default() -> Self {
84        Self {
85            membership: 1,
86            filter: u32::MAX,
87        }
88    }
89}
90impl CollisionLayers {
91    pub const fn new(membership: u32, filter: u32) -> Self {
92        Self { membership, filter }
93    }
94    pub(crate) fn allows(self, other: Self) -> bool {
95        self.membership & other.filter != 0 && other.membership & self.filter != 0
96    }
97}
98
99/// Validated when inserted. One primitive collider belongs to each body.
100#[derive(Clone, Copy, Debug)]
101pub struct BodyDesc<const D: usize> {
102    pub shape: Shape<D>,
103    pub position: [f32; D],
104    pub velocity: [f32; D],
105    pub kind: BodyKind,
106    pub restitution: f32,
107    pub friction: f32,
108    pub linear_damping: f32,
109    pub gravity_scale: f32,
110    pub sensor: bool,
111    pub layers: CollisionLayers,
112    /// Continuous ball collision against static, non-sensor terrain. Boxes use discrete collision.
113    pub ccd: bool,
114    pub user_data: u64,
115}
116impl<const D: usize> BodyDesc<D> {
117    pub fn fixed(shape: Shape<D>, position: [f32; D]) -> Self {
118        Self {
119            shape,
120            position,
121            velocity: [0.; D],
122            kind: BodyKind::Static,
123            restitution: 0.,
124            friction: 0.6,
125            linear_damping: 0.,
126            gravity_scale: 1.,
127            sensor: false,
128            layers: CollisionLayers::default(),
129            ccd: false,
130            user_data: 0,
131        }
132    }
133    pub fn dynamic(shape: Shape<D>, position: [f32; D], mass: f32) -> Self {
134        Self {
135            kind: BodyKind::Dynamic { mass },
136            ..Self::fixed(shape, position)
137        }
138    }
139    pub fn kinematic(shape: Shape<D>, position: [f32; D]) -> Self {
140        Self {
141            kind: BodyKind::Kinematic,
142            ..Self::fixed(shape, position)
143        }
144    }
145    pub(crate) fn valid(self) -> bool {
146        self.shape.valid()
147            && valid(self.position)
148            && valid(self.velocity)
149            && self.restitution.is_finite()
150            && (0. ..=1.).contains(&self.restitution)
151            && self.friction.is_finite()
152            && (0. ..=10.).contains(&self.friction)
153            && self.linear_damping.is_finite()
154            && (0. ..=10_000.).contains(&self.linear_damping)
155            && self.gravity_scale.is_finite()
156            && self.gravity_scale.abs() <= 1_000.
157            && match self.kind {
158                BodyKind::Dynamic { mass } => mass.is_finite() && (1e-6..=1e8).contains(&mass),
159                _ => true,
160            }
161    }
162}
163
164#[derive(Clone, Debug)]
165pub struct Body<const D: usize> {
166    pub(crate) desc: BodyDesc<D>,
167    pub(crate) force: [f32; D],
168}
169impl<const D: usize> Body<D> {
170    pub fn position(&self) -> [f32; D] {
171        self.desc.position
172    }
173    pub fn velocity(&self) -> [f32; D] {
174        self.desc.velocity
175    }
176    pub fn shape(&self) -> Shape<D> {
177        self.desc.shape
178    }
179    pub fn kind(&self) -> BodyKind {
180        self.desc.kind
181    }
182    pub fn is_sensor(&self) -> bool {
183        self.desc.sensor
184    }
185    pub fn user_data(&self) -> u64 {
186        self.desc.user_data
187    }
188    pub fn layers(&self) -> CollisionLayers {
189        self.desc.layers
190    }
191    pub fn description(&self) -> BodyDesc<D> {
192        self.desc
193    }
194    pub fn set_position(&mut self, position: [f32; D]) -> Result<(), PhysicsError> {
195        if !valid(position) {
196            return Err(PhysicsError::InvalidBody);
197        }
198        self.desc.position = position;
199        Ok(())
200    }
201    pub fn set_velocity(&mut self, velocity: [f32; D]) -> Result<(), PhysicsError> {
202        if !valid(velocity) || self.desc.kind == BodyKind::Static && velocity != [0.; D] {
203            return Err(PhysicsError::InvalidBody);
204        }
205        self.desc.velocity = velocity;
206        Ok(())
207    }
208    pub fn set_layers(&mut self, layers: CollisionLayers) {
209        self.desc.layers = layers;
210    }
211    pub fn set_user_data(&mut self, data: u64) {
212        self.desc.user_data = data;
213    }
214    pub fn clear_forces(&mut self) {
215        self.force = [0.; D];
216    }
217    pub fn apply_force(&mut self, force: [f32; D]) -> Result<(), PhysicsError> {
218        if !valid(force) {
219            return Err(PhysicsError::InvalidBody);
220        }
221        if self.inv_mass() == 0. {
222            return Ok(());
223        }
224        let sum = add(self.force, force);
225        if !valid(sum) {
226            return Err(PhysicsError::InvalidBody);
227        }
228        self.force = sum;
229        Ok(())
230    }
231    pub fn apply_impulse(&mut self, impulse: [f32; D]) -> Result<(), PhysicsError> {
232        if !valid(impulse) {
233            return Err(PhysicsError::InvalidBody);
234        }
235        if self.inv_mass() == 0. {
236            return Ok(());
237        }
238        self.set_velocity(add(self.desc.velocity, mul(impulse, self.inv_mass())))
239    }
240    pub(crate) fn inv_mass(&self) -> f32 {
241        match self.desc.kind {
242            BodyKind::Dynamic { mass } => mass.recip(),
243            _ => 0.,
244        }
245    }
246}
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249pub enum PhysicsError {
250    InvalidDimension,
251    InvalidConfiguration,
252    InvalidBody,
253    InvalidTimestep,
254    BodyCapacity,
255    PairCapacity,
256    NumericalLimit,
257}
258impl std::fmt::Display for PhysicsError {
259    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260        f.write_str(match self {
261            Self::InvalidDimension => "physics supports only dimension 2 or 3",
262            Self::InvalidConfiguration => "invalid physics world configuration",
263            Self::InvalidBody => "body contains invalid or out-of-range parameters",
264            Self::InvalidTimestep => "physics timestep must be finite and within (0, 0.1] seconds",
265            Self::BodyCapacity => "physics body capacity reached",
266            Self::PairCapacity => "broadphase pair capacity reached; step rolled back",
267            Self::NumericalLimit => "physics numerical range exceeded; step rolled back",
268        })
269    }
270}
271impl std::error::Error for PhysicsError {}
272
273#[derive(Clone, Copy, Debug)]
274pub struct WorldConfig<const D: usize> {
275    pub gravity: [f32; D],
276    pub max_bodies: usize,
277    pub max_pairs: usize,
278    /// Bound work even when many AABBs overlap along the sweep axis only.
279    pub max_pair_tests: usize,
280    pub solver_iterations: u32,
281    pub contact_slop: f32,
282    /// At most this many terrain impacts are processed per CCD body per step.
283    pub ccd_iterations: u32,
284}
285impl<const D: usize> WorldConfig<D> {
286    pub fn new(gravity: [f32; D]) -> Self {
287        Self {
288            gravity,
289            max_bodies: 4096,
290            max_pairs: 65_536,
291            max_pair_tests: 2_000_000,
292            solver_iterations: 12,
293            contact_slop: 0.001,
294            ccd_iterations: 4,
295        }
296    }
297}
298
299#[derive(Clone, Copy, Debug, PartialEq)]
300pub struct Contact<const D: usize> {
301    pub a: BodyHandle,
302    pub b: BodyHandle,
303    /// Unit vector from A toward B.
304    pub normal: [f32; D],
305    pub penetration: f32,
306    pub sensor: bool,
307}
308#[derive(Clone, Copy, Debug, PartialEq, Eq)]
309pub enum ContactEventKind {
310    Started,
311    Stopped,
312}
313#[derive(Clone, Copy, Debug, PartialEq)]
314pub struct ContactEvent<const D: usize> {
315    pub kind: ContactEventKind,
316    pub contact: Contact<D>,
317}
318
319#[derive(Clone, Copy, Debug)]
320pub struct QueryFilter {
321    pub exclude: Option<BodyHandle>,
322    pub layers: CollisionLayers,
323    pub include_sensors: bool,
324    pub only_static: bool,
325}
326impl Default for QueryFilter {
327    fn default() -> Self {
328        Self {
329            exclude: None,
330            layers: CollisionLayers {
331                membership: u32::MAX,
332                filter: u32::MAX,
333            },
334            include_sensors: false,
335            only_static: false,
336        }
337    }
338}
339#[derive(Clone, Copy, Debug, PartialEq)]
340pub struct RayHit<const D: usize> {
341    pub body: BodyHandle,
342    pub distance: f32,
343    pub point: [f32; D],
344    /// Unit surface normal pointing out of the hit collider.
345    pub normal: [f32; D],
346}
347
348pub mod d2 {
349    pub type PhysicsWorld = crate::PhysicsWorld<2>;
350    pub type BodyDesc = crate::BodyDesc<2>;
351    pub type Shape = crate::Shape<2>;
352    pub type Body = crate::Body<2>;
353}
354pub mod d3 {
355    pub type PhysicsWorld = crate::PhysicsWorld<3>;
356    pub type BodyDesc = crate::BodyDesc<3>;
357    pub type Shape = crate::Shape<3>;
358    pub type Body = crate::Body<3>;
359}