Skip to main content

crcbl_phys/
joint.rs

1//! Joints: the rest of contact-solver rung 5 (`docs/notes/simulation.md`) —
2//! L3's constraints, solved by the same Soft Step as the contacts.
3//!
4//! A [`Joint`] ties two bodies together at a frame fixed in each: an anchor
5//! point and an orientation. Its [`JointKind`] says which of the six relative
6//! motions it takes away, which it bounds with limits, and which a motor or a
7//! spring drives:
8//!
9//! | Kind                        | Holds                                    | Limits, motor, spring                         |
10//! | --------------------------- | ---------------------------------------- | --------------------------------------------- |
11//! | [`DistanceJoint`]           | the anchors' distance (rigid, or a rope) | minimum and maximum length, a motor, a spring |
12//! | [`RevoluteJoint`] (hinge)   | the anchors together, the frames' z-axes | the angle about z, a motor, a spring          |
13//! | [`PrismaticJoint`] (slider) | the orientation, and B on A's x-axis     | the travel along x, a motor, a spring         |
14//! | [`WeldJoint`] (fixed)       | everything, softly if asked              | —                                             |
15//! | [`SphericalJoint`] (ball)   | the anchors together                     | an elliptical swing, twist, a motor           |
16//!
17//! # Soft zones
18//!
19//! A hinge's angle and a ball's swing and twist can each have a **soft zone**
20//! inside their hard limit: from a soft bound to the hard one the joint meets
21//! resistance that grows with depth, and the hard limit stays rigid. Inside the
22//! soft bounds it is free, so a limb at or near its neutral pose — the frames'
23//! zero, which every bound is measured from — feels nothing.
24//!
25//! A zone's strength is a [`Spring`] read as Box2D v3's soft step at a
26//! stiffness that ramps with depth. Past its soft bound a row is a one-sided
27//! spring pushing back towards the bound, its frequency `hertz × √x` at depth
28//! fraction `x` — the depth past the soft bound over the soft bound's
29//! distance to the hard one, capped at 1. Its stiffness, which goes as the
30//! frequency squared, rises in proportion to depth from zero at the soft bound
31//! to `hertz` at the hard bound, so the restoring torque rises with the depth
32//! squared: smooth where the zone begins and steepest at the stop. The force
33//! is the gradient of a potential; each substep the soft step takes the
34//! secant stiffness at the depth where the joint stands and treats that
35//! implicitly, damped at `damping_ratio` of its frequency there. It is not
36//! an implicit solve of the curve itself, so stability and energy are
37//! measured, not proved: the tests in `crates/crcbl-phys/tests/joints.rs`
38//! find no energy gain undamped, in a zone alone or ending at the stop. Zero
39//! hertz is no resistance at all. This is PhysX's D6 soft limit — a limit
40//! with a stiffness and a damping — with the stiffness ramped so the zone
41//! has no edge to strike.
42//!
43//! These are Box3D's joints (github.com/erincatto/box3d, commit `9e5a4cde`),
44//! the three-dimensional sibling of Box2D v3's, whose solvers the contact
45//! solver's own Soft Step already transcribes; each solver's source is named
46//! in `crates/crcbl-phys/src/contact/joint/`.
47//!
48//! # What a joint does to the rest of the system
49//!
50//! - **It joins an island.** Two dynamic bodies joined by a joint are one
51//!   island, which sleeps and wakes whole; a joint to a static body joins
52//!   nothing, as a contact with one does not.
53//! - **A new joint wakes both its bodies**, and so does changing one through
54//!   [`crate::PhysicsSystem::set_joint`] or taking one away.
55//! - **It is warm-started**: every impulse it carries seeds the next tick.
56//! - **Its bodies do not collide** unless [`Joint::collide_connected`] says
57//!   so, as Box2D's default is: a ragdoll's limbs overlap at every joint.
58//! - **It breaks** when the force or torque it carries reaches
59//!   [`Joint::force_threshold`] or [`Joint::torque_threshold`]: it is taken
60//!   out at the end of that step, and reported as a [`JointBreak`].
61//!
62//! Joints exist in a system made with
63//! [`crate::PhysicsSystem::with_contacts`]: they are constraints in its
64//! solver.
65
66use crcbl_ecs::Entity;
67use glam::DVec3;
68
69use crate::components::Transform;
70
71/// A joint added to a system: see [`crate::PhysicsSystem::add_joint`].
72///
73/// Generational, so an id kept after its joint was removed or broke names
74/// nothing rather than whatever took its slot.
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
76pub struct JointId(pub(crate) crcbl_core::Handle<crate::contact::joint::JointRecord>);
77
78impl JointId {
79    /// The id as one integer, for hashing and replication.
80    #[must_use]
81    pub const fn to_bits(self) -> u64 {
82        self.0.to_bits()
83    }
84}
85
86/// A spring's stiffness and damping.
87#[derive(Clone, Copy, Debug, PartialEq)]
88pub struct Spring {
89    /// How stiff, as the frequency of the oscillation it would make, in hertz.
90    /// Zero is no spring at all.
91    pub hertz: f64,
92    /// Its damping ratio: 1 is critical.
93    pub damping_ratio: f64,
94}
95
96/// A joint between two bodies.
97///
98/// The frames are each body's own: `frame_a` is where the joint sits on
99/// `body_a`, in `body_a`'s frame, relative to its position (its centre of
100/// mass), and likewise `frame_b`. [`Joint::at`] builds both from one frame
101/// in the world. A body may be dynamic, kinematic or static — an entity with
102/// only a transform is a fixed anchor — but a joint neither of whose bodies
103/// is dynamic is never solved.
104#[derive(Clone, Copy, Debug, PartialEq)]
105pub struct Joint {
106    /// The first body.
107    pub body_a: Entity,
108    /// The second body.
109    pub body_b: Entity,
110    /// The joint's frame on `body_a`, in its frame.
111    pub frame_a: Transform,
112    /// The joint's frame on `body_b`, in its frame.
113    pub frame_b: Transform,
114    /// What it holds, and how.
115    pub kind: JointKind,
116    /// Whether the two bodies still collide with each other. Off by default.
117    pub collide_connected: bool,
118    /// The force, in newtons, at which it breaks. Infinite by default.
119    pub force_threshold: f64,
120    /// The torque, in newton-metres, at which it breaks. Infinite by default.
121    pub torque_threshold: f64,
122    /// How stiff its rigid parts are, as a spring's frequency in hertz: decision
123    /// 1's 60 Hz by default, Box3D's `constraintHertz`. Capped at a quarter of
124    /// the substep rate, as a contact's is, and raised in proportion for a
125    /// group with extra substeps: see [`crate::PhysicsSystem::set_substeps`].
126    pub constraint_hertz: f64,
127    /// Their damping ratio: decision 1's 2 by default.
128    pub constraint_damping_ratio: f64,
129}
130
131impl Joint {
132    /// Decision 1's joint stiffness, in hertz, and Box3D's default.
133    pub const CONSTRAINT_HERTZ: f64 = 60.0;
134    /// Decision 1's joint damping ratio, and Box3D's default.
135    pub const CONSTRAINT_DAMPING_RATIO: f64 = 2.0;
136
137    /// A joint of `kind` between `body_a` and `body_b` at the frames given in
138    /// each body's own frame, unbreakable, its bodies not colliding.
139    #[must_use]
140    pub const fn new(
141        body_a: Entity,
142        body_b: Entity,
143        frame_a: Transform,
144        frame_b: Transform,
145        kind: JointKind,
146    ) -> Self {
147        Self {
148            body_a,
149            body_b,
150            frame_a,
151            frame_b,
152            kind,
153            collide_connected: false,
154            force_threshold: f64::INFINITY,
155            torque_threshold: f64::INFINITY,
156            constraint_hertz: Self::CONSTRAINT_HERTZ,
157            constraint_damping_ratio: Self::CONSTRAINT_DAMPING_RATIO,
158        }
159    }
160
161    /// [`new`](Self::new) with both frames taken from one frame in the world,
162    /// `frame`, for bodies standing at `at_a` and `at_b`: the joint holds
163    /// them as they stand.
164    #[must_use]
165    pub fn at(
166        body_a: Entity,
167        at_a: &Transform,
168        body_b: Entity,
169        at_b: &Transform,
170        frame: Transform,
171        kind: JointKind,
172    ) -> Self {
173        Self::new(
174            body_a,
175            body_b,
176            local_frame(at_a, frame),
177            local_frame(at_b, frame),
178            kind,
179        )
180    }
181
182    /// This joint, breaking at `force` newtons or `torque` newton-metres.
183    #[must_use]
184    pub const fn breaking_at(self, force: f64, torque: f64) -> Self {
185        Self {
186            force_threshold: force,
187            torque_threshold: torque,
188            ..self
189        }
190    }
191
192    /// This joint, its bodies colliding with each other or not.
193    #[must_use]
194    pub const fn colliding(self, collide_connected: bool) -> Self {
195        Self {
196            collide_connected,
197            ..self
198        }
199    }
200
201    /// Why this joint cannot be added, if it cannot: a frame or a number
202    /// that is not finite, a threshold below zero, or a limit whose lower end
203    /// is above its upper.
204    pub(crate) fn invalid(&self) -> Option<&'static str> {
205        let finite = |t: &Transform| {
206            t.position.is_finite() && t.rotation.is_finite() && t.rotation.length_squared() > 0.0
207        };
208        if !finite(&self.frame_a) || !finite(&self.frame_b) {
209            return Some("a joint's frames are finite, with non-zero rotations");
210        }
211        if self.force_threshold.is_nan()
212            || self.torque_threshold.is_nan()
213            || self.force_threshold < 0.0
214            || self.torque_threshold < 0.0
215        {
216            return Some("a joint's thresholds are zero or more");
217        }
218        if !self.constraint_hertz.is_finite()
219            || self.constraint_hertz < 0.0
220            || !self.constraint_damping_ratio.is_finite()
221            || self.constraint_damping_ratio < 0.0
222        {
223            return Some("a joint's constraint stiffness and damping are finite and not negative");
224        }
225        self.kind.invalid()
226    }
227}
228
229/// `world` in the frame of a body standing at `body`.
230fn local_frame(body: &Transform, world: Transform) -> Transform {
231    let inverse = body.rotation.conjugate();
232    Transform::new(
233        inverse * (world.position - body.position),
234        (inverse * world.rotation).normalize(),
235    )
236}
237
238/// Which joint, and its settings.
239#[derive(Clone, Copy, Debug, PartialEq)]
240pub enum JointKind {
241    /// Holds the anchors' distance: a rod, a rope or a spring.
242    Distance(DistanceJoint),
243    /// A hinge about the frames' z-axes.
244    Revolute(RevoluteJoint),
245    /// A slider along frame A's x-axis.
246    Prismatic(PrismaticJoint),
247    /// Welds the frames together.
248    Weld(WeldJoint),
249    /// A ball and socket, with a swing and twist limit for ragdoll shoulders
250    /// and hips.
251    Spherical(SphericalJoint),
252}
253
254impl JointKind {
255    fn invalid(&self) -> Option<&'static str> {
256        let finite = |values: &[f64]| values.iter().all(|v| v.is_finite());
257        let spring = |s: &Spring| s.hertz >= 0.0 && s.damping_ratio >= 0.0;
258        let soft_zone = |s: &Spring| finite(&[s.hertz, s.damping_ratio]) && spring(s);
259        match self {
260            Self::Distance(d) => {
261                if !finite(&[d.length, d.min_length, d.motor_speed]) || d.max_length.is_nan() {
262                    return Some("a distance joint's lengths are finite");
263                }
264                if d.length < 0.0 || d.min_length < 0.0 || d.min_length > d.max_length {
265                    return Some("a distance joint's lengths are not negative, min at most max");
266                }
267                (!spring(&d.spring) || d.max_motor_force < 0.0)
268                    .then_some("a distance joint's spring and motor are not negative")
269            }
270            Self::Revolute(r) => {
271                if !finite(&[
272                    r.lower_angle,
273                    r.upper_angle,
274                    r.target_angle,
275                    r.motor_speed,
276                    r.soft_lower_angle,
277                    r.soft_upper_angle,
278                ]) {
279                    return Some("a revolute joint's angles are finite");
280                }
281                if r.lower_angle > r.upper_angle
282                    || r.lower_angle < -core::f64::consts::PI
283                    || r.upper_angle > core::f64::consts::PI
284                {
285                    return Some("a revolute joint's limits lie in [-π, π], lower first");
286                }
287                if r.enable_soft_limit {
288                    if !r.enable_limit {
289                        return Some("a revolute joint's soft limits need its hard limits on");
290                    }
291                    if r.soft_lower_angle < r.lower_angle
292                        || r.soft_upper_angle > r.upper_angle
293                        || r.soft_lower_angle > r.soft_upper_angle
294                    {
295                        return Some(
296                            "a revolute joint's soft limits lie inside its hard limits, lower first",
297                        );
298                    }
299                }
300                if !soft_zone(&r.soft_limit) {
301                    return Some("a revolute joint's soft zone is finite and not negative");
302                }
303                (!spring(&r.spring) || r.max_motor_torque < 0.0)
304                    .then_some("a revolute joint's spring and motor are not negative")
305            }
306            Self::Prismatic(p) => {
307                if !finite(&[
308                    p.lower_translation,
309                    p.upper_translation,
310                    p.target_translation,
311                    p.motor_speed,
312                ]) {
313                    return Some("a prismatic joint's translations are finite");
314                }
315                if p.lower_translation > p.upper_translation {
316                    return Some("a prismatic joint's lower limit is at most its upper");
317                }
318                (!spring(&p.spring) || p.max_motor_force < 0.0)
319                    .then_some("a prismatic joint's spring and motor are not negative")
320            }
321            Self::Weld(w) => (!spring(&w.linear) || !spring(&w.angular))
322                .then_some("a weld joint's springs are not negative"),
323            Self::Spherical(s) => {
324                if !finite(&[
325                    s.swing_x_angle,
326                    s.swing_y_angle,
327                    s.lower_twist_angle,
328                    s.upper_twist_angle,
329                    s.soft_swing_x_angle,
330                    s.soft_swing_y_angle,
331                    s.soft_lower_twist_angle,
332                    s.soft_upper_twist_angle,
333                ]) || !s.motor_velocity.is_finite()
334                {
335                    return Some("a spherical joint's angles are finite");
336                }
337                let half_turn = |angle: f64| (0.0..=core::f64::consts::PI).contains(&angle);
338                if !half_turn(s.swing_x_angle)
339                    || !half_turn(s.swing_y_angle)
340                    || s.lower_twist_angle > s.upper_twist_angle
341                    || s.lower_twist_angle < -core::f64::consts::PI
342                    || s.upper_twist_angle > core::f64::consts::PI
343                {
344                    return Some(
345                        "a spherical joint's swing lies in [0, π] and its twist in [-π, π], lower first",
346                    );
347                }
348                // One zero half-angle makes the ellipse a segment, whose
349                // pushing side flips as the swing crosses it; a hinge, or a
350                // small half-angle, is the joint for that.
351                let one_zero = |x: f64, y: f64| (x == 0.0) != (y == 0.0);
352                if one_zero(s.swing_x_angle, s.swing_y_angle)
353                    || one_zero(s.soft_swing_x_angle, s.soft_swing_y_angle)
354                {
355                    return Some(
356                        "a spherical joint's swing half-angles are both zero or neither, soft or hard",
357                    );
358                }
359                if s.enable_soft_swing
360                    && (!s.enable_swing_limit
361                        || !(0.0..=s.swing_x_angle).contains(&s.soft_swing_x_angle)
362                        || !(0.0..=s.swing_y_angle).contains(&s.soft_swing_y_angle))
363                {
364                    return Some(
365                        "a spherical joint's soft swing needs its swing limit on, and lies inside it",
366                    );
367                }
368                if s.enable_soft_twist
369                    && (!s.enable_twist_limit
370                        || s.soft_lower_twist_angle < s.lower_twist_angle
371                        || s.soft_upper_twist_angle > s.upper_twist_angle
372                        || s.soft_lower_twist_angle > s.soft_upper_twist_angle)
373                {
374                    return Some(
375                        "a spherical joint's soft twist needs its twist limit on, and lies inside it, lower first",
376                    );
377                }
378                if !soft_zone(&s.soft_swing) || !soft_zone(&s.soft_twist) {
379                    return Some("a spherical joint's soft zones are finite and not negative");
380                }
381                (s.max_motor_torque < 0.0).then_some("a spherical joint's motor is not negative")
382            }
383        }
384    }
385}
386
387/// A distance joint: Box3D's `b3DistanceJointDef`.
388///
389/// **Rigid** unless its spring is enabled: then the length is held only by
390/// the spring, and by the limits if they are on — which is a rope, with a
391/// spring of zero hertz and a limit from zero to its length.
392#[derive(Clone, Copy, Debug, PartialEq)]
393pub struct DistanceJoint {
394    /// The rest length, in metres.
395    pub length: f64,
396    /// Whether the length is held by the spring (and the limits) rather than
397    /// rigidly.
398    pub enable_spring: bool,
399    /// The spring, while it is enabled.
400    pub spring: Spring,
401    /// Whether the length is kept between the limits.
402    pub enable_limit: bool,
403    /// The shortest it may be, in metres.
404    pub min_length: f64,
405    /// The longest it may be, in metres; infinite for no bound.
406    pub max_length: f64,
407    /// Whether the motor drives the length.
408    pub enable_motor: bool,
409    /// The most force the motor applies, in newtons.
410    pub max_motor_force: f64,
411    /// The speed the motor drives the length at, in m/s.
412    pub motor_speed: f64,
413}
414
415impl DistanceJoint {
416    /// A rigid rod of `length`.
417    #[must_use]
418    pub const fn rigid(length: f64) -> Self {
419        Self {
420            length,
421            enable_spring: false,
422            spring: Spring {
423                hertz: 0.0,
424                damping_ratio: 0.0,
425            },
426            enable_limit: false,
427            min_length: 0.0,
428            max_length: f64::INFINITY,
429            enable_motor: false,
430            max_motor_force: 0.0,
431            motor_speed: 0.0,
432        }
433    }
434
435    /// A rope of `length`: it goes slack when shorter and holds at its
436    /// length — Box2D's rope, a spring of no stiffness with a limit.
437    #[must_use]
438    pub const fn rope(length: f64) -> Self {
439        Self {
440            enable_spring: true,
441            enable_limit: true,
442            min_length: 0.0,
443            max_length: length,
444            ..Self::rigid(length)
445        }
446    }
447
448    /// A spring of `length` at `hertz` and `damping_ratio`.
449    #[must_use]
450    pub const fn spring(length: f64, hertz: f64, damping_ratio: f64) -> Self {
451        Self {
452            enable_spring: true,
453            spring: Spring {
454                hertz,
455                damping_ratio,
456            },
457            ..Self::rigid(length)
458        }
459    }
460
461    /// This joint, kept between `min` and `max` metres.
462    #[must_use]
463    pub const fn with_limits(self, min: f64, max: f64) -> Self {
464        Self {
465            enable_limit: true,
466            min_length: min,
467            max_length: max,
468            ..self
469        }
470    }
471
472    /// This joint, its length driven at `speed` m/s by up to `max_force`
473    /// newtons.
474    #[must_use]
475    pub const fn with_motor(self, speed: f64, max_force: f64) -> Self {
476        Self {
477            enable_motor: true,
478            motor_speed: speed,
479            max_motor_force: max_force,
480            ..self
481        }
482    }
483}
484
485/// A revolute joint, a hinge about the frames' z-axes: Box3D's
486/// `b3RevoluteJointDef`.
487///
488/// Its angle is frame B's turn about frame A's z-axis, zero where the frames
489/// agree, in `[-π, π]`.
490#[derive(Clone, Copy, Debug, PartialEq)]
491pub struct RevoluteJoint {
492    /// Whether the spring pulls the angle towards `target_angle`.
493    pub enable_spring: bool,
494    /// The spring.
495    pub spring: Spring,
496    /// The angle the spring pulls towards, in radians.
497    pub target_angle: f64,
498    /// Whether the angle is kept between the limits.
499    pub enable_limit: bool,
500    /// The least angle, in radians, at least −π.
501    pub lower_angle: f64,
502    /// The greatest angle, in radians, at most π.
503    pub upper_angle: f64,
504    /// Whether the motor drives the angle.
505    pub enable_motor: bool,
506    /// The most torque the motor applies, in newton-metres.
507    pub max_motor_torque: f64,
508    /// The speed it drives at, in rad/s.
509    pub motor_speed: f64,
510    /// Whether the angle meets a soft zone's resistance past the soft
511    /// limits, on the way to the hard ones: see the module's soft zones. It
512    /// needs `enable_limit`.
513    pub enable_soft_limit: bool,
514    /// Where the soft zone below begins, in radians, at least `lower_angle`.
515    pub soft_lower_angle: f64,
516    /// Where the soft zone above begins, in radians, at most `upper_angle`.
517    pub soft_upper_angle: f64,
518    /// The soft zones' strength.
519    pub soft_limit: Spring,
520}
521
522impl RevoluteJoint {
523    /// A free hinge.
524    #[must_use]
525    pub const fn hinge() -> Self {
526        Self {
527            enable_spring: false,
528            spring: Spring {
529                hertz: 0.0,
530                damping_ratio: 0.0,
531            },
532            target_angle: 0.0,
533            enable_limit: false,
534            lower_angle: 0.0,
535            upper_angle: 0.0,
536            enable_motor: false,
537            max_motor_torque: 0.0,
538            motor_speed: 0.0,
539            enable_soft_limit: false,
540            soft_lower_angle: 0.0,
541            soft_upper_angle: 0.0,
542            soft_limit: Spring {
543                hertz: 0.0,
544                damping_ratio: 0.0,
545            },
546        }
547    }
548
549    /// This hinge, kept between `lower` and `upper` radians.
550    #[must_use]
551    pub const fn with_limits(self, lower: f64, upper: f64) -> Self {
552        Self {
553            enable_limit: true,
554            lower_angle: lower,
555            upper_angle: upper,
556            ..self
557        }
558    }
559
560    /// This hinge, driven at `speed` rad/s by up to `max_torque`.
561    #[must_use]
562    pub const fn with_motor(self, speed: f64, max_torque: f64) -> Self {
563        Self {
564            enable_motor: true,
565            motor_speed: speed,
566            max_motor_torque: max_torque,
567            ..self
568        }
569    }
570
571    /// This hinge, pulled towards `target` radians by `spring`.
572    #[must_use]
573    pub const fn with_spring(self, target: f64, spring: Spring) -> Self {
574        Self {
575            enable_spring: true,
576            spring,
577            target_angle: target,
578            ..self
579        }
580    }
581
582    /// This hinge, resisted by `zone` below `lower` and above `upper`
583    /// radians, on the way to its hard limits — which it needs, from
584    /// [`with_limits`](Self::with_limits).
585    #[must_use]
586    pub const fn with_soft_limits(self, lower: f64, upper: f64, zone: Spring) -> Self {
587        Self {
588            enable_soft_limit: true,
589            soft_lower_angle: lower,
590            soft_upper_angle: upper,
591            soft_limit: zone,
592            ..self
593        }
594    }
595}
596
597/// A prismatic joint, a slider along frame A's x-axis with the bodies'
598/// orientation held: Box3D's `b3PrismaticJointDef`.
599///
600/// Its translation is how far frame B's origin is from frame A's along that
601/// axis.
602#[derive(Clone, Copy, Debug, PartialEq)]
603pub struct PrismaticJoint {
604    /// Whether the spring pulls the translation towards `target_translation`.
605    pub enable_spring: bool,
606    /// The spring.
607    pub spring: Spring,
608    /// The translation the spring pulls towards, in metres.
609    pub target_translation: f64,
610    /// Whether the translation is kept between the limits.
611    pub enable_limit: bool,
612    /// The least translation, in metres.
613    pub lower_translation: f64,
614    /// The greatest translation, in metres.
615    pub upper_translation: f64,
616    /// Whether the motor drives the translation.
617    pub enable_motor: bool,
618    /// The most force the motor applies, in newtons.
619    pub max_motor_force: f64,
620    /// The speed it drives at, in m/s.
621    pub motor_speed: f64,
622}
623
624impl PrismaticJoint {
625    /// A free slider.
626    #[must_use]
627    pub const fn slider() -> Self {
628        Self {
629            enable_spring: false,
630            spring: Spring {
631                hertz: 0.0,
632                damping_ratio: 0.0,
633            },
634            target_translation: 0.0,
635            enable_limit: false,
636            lower_translation: 0.0,
637            upper_translation: 0.0,
638            enable_motor: false,
639            max_motor_force: 0.0,
640            motor_speed: 0.0,
641        }
642    }
643
644    /// This slider, kept between `lower` and `upper` metres.
645    #[must_use]
646    pub const fn with_limits(self, lower: f64, upper: f64) -> Self {
647        Self {
648            enable_limit: true,
649            lower_translation: lower,
650            upper_translation: upper,
651            ..self
652        }
653    }
654
655    /// This slider, driven at `speed` m/s by up to `max_force` newtons.
656    #[must_use]
657    pub const fn with_motor(self, speed: f64, max_force: f64) -> Self {
658        Self {
659            enable_motor: true,
660            motor_speed: speed,
661            max_motor_force: max_force,
662            ..self
663        }
664    }
665
666    /// This slider, pulled towards `target` metres by `spring`.
667    #[must_use]
668    pub const fn with_spring(self, target: f64, spring: Spring) -> Self {
669        Self {
670            enable_spring: true,
671            spring,
672            target_translation: target,
673            ..self
674        }
675    }
676}
677
678/// A weld joint, holding the frames together: Box3D's `b3WeldJointDef`.
679///
680/// A spring of zero hertz is rigid — the joint's own constraint stiffness —
681/// and any other makes that half of the weld a spring.
682#[derive(Clone, Copy, Debug, PartialEq)]
683pub struct WeldJoint {
684    /// How the frames' origins are held together.
685    pub linear: Spring,
686    /// How their orientations are.
687    pub angular: Spring,
688}
689
690impl WeldJoint {
691    /// A rigid weld.
692    #[must_use]
693    pub const fn rigid() -> Self {
694        let rigid = Spring {
695            hertz: 0.0,
696            damping_ratio: 0.0,
697        };
698        Self {
699            linear: rigid,
700            angular: rigid,
701        }
702    }
703}
704
705/// A spherical joint, a ball and socket: Box3D's `b3SphericalJointDef`
706/// without its spring, its cone made an ellipse as Jolt's
707/// `SwingTwistConstraint` makes it.
708///
709/// Frame B's turn from frame A is split into a **swing**, which tips frame
710/// B's z-axis away from frame A's, and a **twist**, frame B's turn about its
711/// own z-axis. The swing limit is an elliptical cone: a swing about frame
712/// A's x-axis alone goes as far as `swing_x_angle`, one about its y-axis as
713/// far as `swing_y_angle`, and one between them as far as the ellipse
714/// through both allows. Equal half-angles make it the circular cone of
715/// [`with_cone`](Self::with_cone). Any asymmetry beyond that — a shoulder
716/// that swings further forward than back — is carried by the frames: the
717/// cone is centred on frame A's z-axis. Together they are a ragdoll's
718/// shoulder or hip.
719#[derive(Clone, Copy, Debug, PartialEq)]
720pub struct SphericalJoint {
721    /// Whether the swing limit is on.
722    pub enable_swing_limit: bool,
723    /// The swing's half-angle about frame A's x-axis, in radians, in
724    /// `[0, π]`; zero only with `swing_y_angle` zero too.
725    pub swing_x_angle: f64,
726    /// The swing's half-angle about frame A's y-axis, in radians, in
727    /// `[0, π]`; zero only with `swing_x_angle` zero too.
728    pub swing_y_angle: f64,
729    /// Whether the twist limit is on.
730    pub enable_twist_limit: bool,
731    /// The least twist, in radians.
732    pub lower_twist_angle: f64,
733    /// The greatest twist, in radians.
734    pub upper_twist_angle: f64,
735    /// Whether the motor drives the relative angular velocity.
736    pub enable_motor: bool,
737    /// The most torque the motor applies, in newton-metres.
738    pub max_motor_torque: f64,
739    /// The relative angular velocity it drives towards, in rad/s, in the
740    /// world.
741    pub motor_velocity: DVec3,
742    /// Whether the swing meets a soft zone's resistance past a softer
743    /// ellipse inside the hard one: see the module's soft zones. It needs
744    /// `enable_swing_limit`.
745    pub enable_soft_swing: bool,
746    /// The soft ellipse's half-angle about frame A's x-axis, at most
747    /// `swing_x_angle`.
748    pub soft_swing_x_angle: f64,
749    /// The soft ellipse's half-angle about frame A's y-axis, at most
750    /// `swing_y_angle`.
751    pub soft_swing_y_angle: f64,
752    /// The soft swing's strength.
753    pub soft_swing: Spring,
754    /// Whether the twist meets a soft zone's resistance past the soft twist
755    /// bounds. It needs `enable_twist_limit`.
756    pub enable_soft_twist: bool,
757    /// Where the soft zone below begins, at least `lower_twist_angle`.
758    pub soft_lower_twist_angle: f64,
759    /// Where the soft zone above begins, at most `upper_twist_angle`.
760    pub soft_upper_twist_angle: f64,
761    /// The soft twist's strength.
762    pub soft_twist: Spring,
763}
764
765impl SphericalJoint {
766    /// A free ball and socket.
767    #[must_use]
768    pub const fn ball() -> Self {
769        let none = Spring {
770            hertz: 0.0,
771            damping_ratio: 0.0,
772        };
773        Self {
774            enable_swing_limit: false,
775            swing_x_angle: 0.0,
776            swing_y_angle: 0.0,
777            enable_twist_limit: false,
778            lower_twist_angle: 0.0,
779            upper_twist_angle: 0.0,
780            enable_motor: false,
781            max_motor_torque: 0.0,
782            motor_velocity: DVec3::ZERO,
783            enable_soft_swing: false,
784            soft_swing_x_angle: 0.0,
785            soft_swing_y_angle: 0.0,
786            soft_swing: none,
787            enable_soft_twist: false,
788            soft_lower_twist_angle: 0.0,
789            soft_upper_twist_angle: 0.0,
790            soft_twist: none,
791        }
792    }
793
794    /// This joint, its frame B's z-axis kept within `angle` of frame A's:
795    /// [`with_swing`](Self::with_swing) at `angle` about both axes.
796    #[must_use]
797    pub const fn with_cone(self, angle: f64) -> Self {
798        self.with_swing(angle, angle)
799    }
800
801    /// This joint, its swing kept inside the ellipse of half-angles `x`
802    /// about frame A's x-axis and `y` about its y-axis.
803    #[must_use]
804    pub const fn with_swing(self, x: f64, y: f64) -> Self {
805        Self {
806            enable_swing_limit: true,
807            swing_x_angle: x,
808            swing_y_angle: y,
809            ..self
810        }
811    }
812
813    /// This joint, its twist kept between `lower` and `upper` radians.
814    #[must_use]
815    pub const fn with_twist(self, lower: f64, upper: f64) -> Self {
816        Self {
817            enable_twist_limit: true,
818            lower_twist_angle: lower,
819            upper_twist_angle: upper,
820            ..self
821        }
822    }
823
824    /// This joint, its swing resisted by `zone` past the ellipse of
825    /// half-angles `x` and `y`, on the way to its hard swing limit — which
826    /// it needs, from [`with_swing`](Self::with_swing).
827    #[must_use]
828    pub const fn with_soft_swing(self, x: f64, y: f64, zone: Spring) -> Self {
829        Self {
830            enable_soft_swing: true,
831            soft_swing_x_angle: x,
832            soft_swing_y_angle: y,
833            soft_swing: zone,
834            ..self
835        }
836    }
837
838    /// This joint, its twist resisted by `zone` below `lower` and above
839    /// `upper` radians, on the way to its hard twist limit — which it needs,
840    /// from [`with_twist`](Self::with_twist).
841    #[must_use]
842    pub const fn with_soft_twist(self, lower: f64, upper: f64, zone: Spring) -> Self {
843        Self {
844            enable_soft_twist: true,
845            soft_lower_twist_angle: lower,
846            soft_upper_twist_angle: upper,
847            soft_twist: zone,
848            ..self
849        }
850    }
851
852    /// This joint, driving the relative angular velocity towards `velocity`
853    /// with up to `max_torque`: a friction joint, at zero velocity.
854    #[must_use]
855    pub const fn with_motor(self, velocity: DVec3, max_torque: f64) -> Self {
856        Self {
857            enable_motor: true,
858            motor_velocity: velocity,
859            max_motor_torque: max_torque,
860            ..self
861        }
862    }
863}
864
865/// A joint that broke: the force or torque it carried reached its
866/// threshold. Raised by the step it broke in, which took it out.
867#[derive(Clone, Copy, Debug, PartialEq)]
868pub struct JointBreak {
869    /// The joint, which no longer exists.
870    pub joint: JointId,
871    /// Its first body.
872    pub body_a: Entity,
873    /// Its second body.
874    pub body_b: Entity,
875    /// What it held when it broke.
876    pub joint_def: Joint,
877    /// The force it carried in the substep it broke, in newtons.
878    pub force: f64,
879    /// The torque it carried, in newton-metres.
880    pub torque: f64,
881}
882
883/// Why [`crate::PhysicsSystem::add_joint`] refused a joint.
884#[derive(Clone, Copy, Debug, PartialEq, Eq)]
885pub enum JointError {
886    /// An entity that is not registered with the system.
887    UnknownBody(Entity),
888    /// Both ends are one body.
889    SameBody,
890    /// A setting out of range, and which.
891    Invalid(&'static str),
892}
893
894impl core::fmt::Display for JointError {
895    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
896        match self {
897            Self::UnknownBody(entity) => write!(f, "{entity:?} is not registered"),
898            Self::SameBody => f.write_str("a joint joins two different bodies"),
899            Self::Invalid(why) => f.write_str(why),
900        }
901    }
902}
903
904impl std::error::Error for JointError {}
905
906/// How far a joint is from holding, as
907/// [`crate::PhysicsSystem::joint_drift`] measures it: how far its positional
908/// rows are broken, and by what angle its rotational ones are.
909#[derive(Clone, Copy, Debug, Default, PartialEq)]
910pub struct JointDrift {
911    /// In metres.
912    pub linear: f64,
913    /// In radians.
914    pub angular: f64,
915}