use crcbl_ecs::Entity;
use glam::DVec3;
use crate::components::Transform;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct JointId(pub(crate) crcbl_core::Handle<crate::contact::joint::JointRecord>);
impl JointId {
#[must_use]
pub const fn to_bits(self) -> u64 {
self.0.to_bits()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
pub hertz: f64,
pub damping_ratio: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Joint {
pub body_a: Entity,
pub body_b: Entity,
pub frame_a: Transform,
pub frame_b: Transform,
pub kind: JointKind,
pub collide_connected: bool,
pub force_threshold: f64,
pub torque_threshold: f64,
pub constraint_hertz: f64,
pub constraint_damping_ratio: f64,
}
impl Joint {
pub const CONSTRAINT_HERTZ: f64 = 60.0;
pub const CONSTRAINT_DAMPING_RATIO: f64 = 2.0;
#[must_use]
pub const fn new(
body_a: Entity,
body_b: Entity,
frame_a: Transform,
frame_b: Transform,
kind: JointKind,
) -> Self {
Self {
body_a,
body_b,
frame_a,
frame_b,
kind,
collide_connected: false,
force_threshold: f64::INFINITY,
torque_threshold: f64::INFINITY,
constraint_hertz: Self::CONSTRAINT_HERTZ,
constraint_damping_ratio: Self::CONSTRAINT_DAMPING_RATIO,
}
}
#[must_use]
pub fn at(
body_a: Entity,
at_a: &Transform,
body_b: Entity,
at_b: &Transform,
frame: Transform,
kind: JointKind,
) -> Self {
Self::new(
body_a,
body_b,
local_frame(at_a, frame),
local_frame(at_b, frame),
kind,
)
}
#[must_use]
pub const fn breaking_at(self, force: f64, torque: f64) -> Self {
Self {
force_threshold: force,
torque_threshold: torque,
..self
}
}
#[must_use]
pub const fn colliding(self, collide_connected: bool) -> Self {
Self {
collide_connected,
..self
}
}
pub(crate) fn invalid(&self) -> Option<&'static str> {
let finite = |t: &Transform| {
t.position.is_finite() && t.rotation.is_finite() && t.rotation.length_squared() > 0.0
};
if !finite(&self.frame_a) || !finite(&self.frame_b) {
return Some("a joint's frames are finite, with non-zero rotations");
}
if self.force_threshold.is_nan()
|| self.torque_threshold.is_nan()
|| self.force_threshold < 0.0
|| self.torque_threshold < 0.0
{
return Some("a joint's thresholds are zero or more");
}
if !self.constraint_hertz.is_finite()
|| self.constraint_hertz < 0.0
|| !self.constraint_damping_ratio.is_finite()
|| self.constraint_damping_ratio < 0.0
{
return Some("a joint's constraint stiffness and damping are finite and not negative");
}
self.kind.invalid()
}
}
fn local_frame(body: &Transform, world: Transform) -> Transform {
let inverse = body.rotation.conjugate();
Transform::new(
inverse * (world.position - body.position),
(inverse * world.rotation).normalize(),
)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum JointKind {
Distance(DistanceJoint),
Revolute(RevoluteJoint),
Prismatic(PrismaticJoint),
Weld(WeldJoint),
Spherical(SphericalJoint),
}
impl JointKind {
fn invalid(&self) -> Option<&'static str> {
let finite = |values: &[f64]| values.iter().all(|v| v.is_finite());
let spring = |s: &Spring| s.hertz >= 0.0 && s.damping_ratio >= 0.0;
let soft_zone = |s: &Spring| finite(&[s.hertz, s.damping_ratio]) && spring(s);
match self {
Self::Distance(d) => {
if !finite(&[d.length, d.min_length, d.motor_speed]) || d.max_length.is_nan() {
return Some("a distance joint's lengths are finite");
}
if d.length < 0.0 || d.min_length < 0.0 || d.min_length > d.max_length {
return Some("a distance joint's lengths are not negative, min at most max");
}
(!spring(&d.spring) || d.max_motor_force < 0.0)
.then_some("a distance joint's spring and motor are not negative")
}
Self::Revolute(r) => {
if !finite(&[
r.lower_angle,
r.upper_angle,
r.target_angle,
r.motor_speed,
r.soft_lower_angle,
r.soft_upper_angle,
]) {
return Some("a revolute joint's angles are finite");
}
if r.lower_angle > r.upper_angle
|| r.lower_angle < -core::f64::consts::PI
|| r.upper_angle > core::f64::consts::PI
{
return Some("a revolute joint's limits lie in [-π, π], lower first");
}
if r.enable_soft_limit {
if !r.enable_limit {
return Some("a revolute joint's soft limits need its hard limits on");
}
if r.soft_lower_angle < r.lower_angle
|| r.soft_upper_angle > r.upper_angle
|| r.soft_lower_angle > r.soft_upper_angle
{
return Some(
"a revolute joint's soft limits lie inside its hard limits, lower first",
);
}
}
if !soft_zone(&r.soft_limit) {
return Some("a revolute joint's soft zone is finite and not negative");
}
(!spring(&r.spring) || r.max_motor_torque < 0.0)
.then_some("a revolute joint's spring and motor are not negative")
}
Self::Prismatic(p) => {
if !finite(&[
p.lower_translation,
p.upper_translation,
p.target_translation,
p.motor_speed,
]) {
return Some("a prismatic joint's translations are finite");
}
if p.lower_translation > p.upper_translation {
return Some("a prismatic joint's lower limit is at most its upper");
}
(!spring(&p.spring) || p.max_motor_force < 0.0)
.then_some("a prismatic joint's spring and motor are not negative")
}
Self::Weld(w) => (!spring(&w.linear) || !spring(&w.angular))
.then_some("a weld joint's springs are not negative"),
Self::Spherical(s) => {
if !finite(&[
s.swing_x_angle,
s.swing_y_angle,
s.lower_twist_angle,
s.upper_twist_angle,
s.soft_swing_x_angle,
s.soft_swing_y_angle,
s.soft_lower_twist_angle,
s.soft_upper_twist_angle,
]) || !s.motor_velocity.is_finite()
{
return Some("a spherical joint's angles are finite");
}
let half_turn = |angle: f64| (0.0..=core::f64::consts::PI).contains(&angle);
if !half_turn(s.swing_x_angle)
|| !half_turn(s.swing_y_angle)
|| s.lower_twist_angle > s.upper_twist_angle
|| s.lower_twist_angle < -core::f64::consts::PI
|| s.upper_twist_angle > core::f64::consts::PI
{
return Some(
"a spherical joint's swing lies in [0, π] and its twist in [-π, π], lower first",
);
}
let one_zero = |x: f64, y: f64| (x == 0.0) != (y == 0.0);
if one_zero(s.swing_x_angle, s.swing_y_angle)
|| one_zero(s.soft_swing_x_angle, s.soft_swing_y_angle)
{
return Some(
"a spherical joint's swing half-angles are both zero or neither, soft or hard",
);
}
if s.enable_soft_swing
&& (!s.enable_swing_limit
|| !(0.0..=s.swing_x_angle).contains(&s.soft_swing_x_angle)
|| !(0.0..=s.swing_y_angle).contains(&s.soft_swing_y_angle))
{
return Some(
"a spherical joint's soft swing needs its swing limit on, and lies inside it",
);
}
if s.enable_soft_twist
&& (!s.enable_twist_limit
|| s.soft_lower_twist_angle < s.lower_twist_angle
|| s.soft_upper_twist_angle > s.upper_twist_angle
|| s.soft_lower_twist_angle > s.soft_upper_twist_angle)
{
return Some(
"a spherical joint's soft twist needs its twist limit on, and lies inside it, lower first",
);
}
if !soft_zone(&s.soft_swing) || !soft_zone(&s.soft_twist) {
return Some("a spherical joint's soft zones are finite and not negative");
}
(s.max_motor_torque < 0.0).then_some("a spherical joint's motor is not negative")
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DistanceJoint {
pub length: f64,
pub enable_spring: bool,
pub spring: Spring,
pub enable_limit: bool,
pub min_length: f64,
pub max_length: f64,
pub enable_motor: bool,
pub max_motor_force: f64,
pub motor_speed: f64,
}
impl DistanceJoint {
#[must_use]
pub const fn rigid(length: f64) -> Self {
Self {
length,
enable_spring: false,
spring: Spring {
hertz: 0.0,
damping_ratio: 0.0,
},
enable_limit: false,
min_length: 0.0,
max_length: f64::INFINITY,
enable_motor: false,
max_motor_force: 0.0,
motor_speed: 0.0,
}
}
#[must_use]
pub const fn rope(length: f64) -> Self {
Self {
enable_spring: true,
enable_limit: true,
min_length: 0.0,
max_length: length,
..Self::rigid(length)
}
}
#[must_use]
pub const fn spring(length: f64, hertz: f64, damping_ratio: f64) -> Self {
Self {
enable_spring: true,
spring: Spring {
hertz,
damping_ratio,
},
..Self::rigid(length)
}
}
#[must_use]
pub const fn with_limits(self, min: f64, max: f64) -> Self {
Self {
enable_limit: true,
min_length: min,
max_length: max,
..self
}
}
#[must_use]
pub const fn with_motor(self, speed: f64, max_force: f64) -> Self {
Self {
enable_motor: true,
motor_speed: speed,
max_motor_force: max_force,
..self
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RevoluteJoint {
pub enable_spring: bool,
pub spring: Spring,
pub target_angle: f64,
pub enable_limit: bool,
pub lower_angle: f64,
pub upper_angle: f64,
pub enable_motor: bool,
pub max_motor_torque: f64,
pub motor_speed: f64,
pub enable_soft_limit: bool,
pub soft_lower_angle: f64,
pub soft_upper_angle: f64,
pub soft_limit: Spring,
}
impl RevoluteJoint {
#[must_use]
pub const fn hinge() -> Self {
Self {
enable_spring: false,
spring: Spring {
hertz: 0.0,
damping_ratio: 0.0,
},
target_angle: 0.0,
enable_limit: false,
lower_angle: 0.0,
upper_angle: 0.0,
enable_motor: false,
max_motor_torque: 0.0,
motor_speed: 0.0,
enable_soft_limit: false,
soft_lower_angle: 0.0,
soft_upper_angle: 0.0,
soft_limit: Spring {
hertz: 0.0,
damping_ratio: 0.0,
},
}
}
#[must_use]
pub const fn with_limits(self, lower: f64, upper: f64) -> Self {
Self {
enable_limit: true,
lower_angle: lower,
upper_angle: upper,
..self
}
}
#[must_use]
pub const fn with_motor(self, speed: f64, max_torque: f64) -> Self {
Self {
enable_motor: true,
motor_speed: speed,
max_motor_torque: max_torque,
..self
}
}
#[must_use]
pub const fn with_spring(self, target: f64, spring: Spring) -> Self {
Self {
enable_spring: true,
spring,
target_angle: target,
..self
}
}
#[must_use]
pub const fn with_soft_limits(self, lower: f64, upper: f64, zone: Spring) -> Self {
Self {
enable_soft_limit: true,
soft_lower_angle: lower,
soft_upper_angle: upper,
soft_limit: zone,
..self
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PrismaticJoint {
pub enable_spring: bool,
pub spring: Spring,
pub target_translation: f64,
pub enable_limit: bool,
pub lower_translation: f64,
pub upper_translation: f64,
pub enable_motor: bool,
pub max_motor_force: f64,
pub motor_speed: f64,
}
impl PrismaticJoint {
#[must_use]
pub const fn slider() -> Self {
Self {
enable_spring: false,
spring: Spring {
hertz: 0.0,
damping_ratio: 0.0,
},
target_translation: 0.0,
enable_limit: false,
lower_translation: 0.0,
upper_translation: 0.0,
enable_motor: false,
max_motor_force: 0.0,
motor_speed: 0.0,
}
}
#[must_use]
pub const fn with_limits(self, lower: f64, upper: f64) -> Self {
Self {
enable_limit: true,
lower_translation: lower,
upper_translation: upper,
..self
}
}
#[must_use]
pub const fn with_motor(self, speed: f64, max_force: f64) -> Self {
Self {
enable_motor: true,
motor_speed: speed,
max_motor_force: max_force,
..self
}
}
#[must_use]
pub const fn with_spring(self, target: f64, spring: Spring) -> Self {
Self {
enable_spring: true,
spring,
target_translation: target,
..self
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WeldJoint {
pub linear: Spring,
pub angular: Spring,
}
impl WeldJoint {
#[must_use]
pub const fn rigid() -> Self {
let rigid = Spring {
hertz: 0.0,
damping_ratio: 0.0,
};
Self {
linear: rigid,
angular: rigid,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SphericalJoint {
pub enable_swing_limit: bool,
pub swing_x_angle: f64,
pub swing_y_angle: f64,
pub enable_twist_limit: bool,
pub lower_twist_angle: f64,
pub upper_twist_angle: f64,
pub enable_motor: bool,
pub max_motor_torque: f64,
pub motor_velocity: DVec3,
pub enable_soft_swing: bool,
pub soft_swing_x_angle: f64,
pub soft_swing_y_angle: f64,
pub soft_swing: Spring,
pub enable_soft_twist: bool,
pub soft_lower_twist_angle: f64,
pub soft_upper_twist_angle: f64,
pub soft_twist: Spring,
}
impl SphericalJoint {
#[must_use]
pub const fn ball() -> Self {
let none = Spring {
hertz: 0.0,
damping_ratio: 0.0,
};
Self {
enable_swing_limit: false,
swing_x_angle: 0.0,
swing_y_angle: 0.0,
enable_twist_limit: false,
lower_twist_angle: 0.0,
upper_twist_angle: 0.0,
enable_motor: false,
max_motor_torque: 0.0,
motor_velocity: DVec3::ZERO,
enable_soft_swing: false,
soft_swing_x_angle: 0.0,
soft_swing_y_angle: 0.0,
soft_swing: none,
enable_soft_twist: false,
soft_lower_twist_angle: 0.0,
soft_upper_twist_angle: 0.0,
soft_twist: none,
}
}
#[must_use]
pub const fn with_cone(self, angle: f64) -> Self {
self.with_swing(angle, angle)
}
#[must_use]
pub const fn with_swing(self, x: f64, y: f64) -> Self {
Self {
enable_swing_limit: true,
swing_x_angle: x,
swing_y_angle: y,
..self
}
}
#[must_use]
pub const fn with_twist(self, lower: f64, upper: f64) -> Self {
Self {
enable_twist_limit: true,
lower_twist_angle: lower,
upper_twist_angle: upper,
..self
}
}
#[must_use]
pub const fn with_soft_swing(self, x: f64, y: f64, zone: Spring) -> Self {
Self {
enable_soft_swing: true,
soft_swing_x_angle: x,
soft_swing_y_angle: y,
soft_swing: zone,
..self
}
}
#[must_use]
pub const fn with_soft_twist(self, lower: f64, upper: f64, zone: Spring) -> Self {
Self {
enable_soft_twist: true,
soft_lower_twist_angle: lower,
soft_upper_twist_angle: upper,
soft_twist: zone,
..self
}
}
#[must_use]
pub const fn with_motor(self, velocity: DVec3, max_torque: f64) -> Self {
Self {
enable_motor: true,
motor_velocity: velocity,
max_motor_torque: max_torque,
..self
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct JointBreak {
pub joint: JointId,
pub body_a: Entity,
pub body_b: Entity,
pub joint_def: Joint,
pub force: f64,
pub torque: f64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JointError {
UnknownBody(Entity),
SameBody,
Invalid(&'static str),
}
impl core::fmt::Display for JointError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::UnknownBody(entity) => write!(f, "{entity:?} is not registered"),
Self::SameBody => f.write_str("a joint joins two different bodies"),
Self::Invalid(why) => f.write_str(why),
}
}
}
impl std::error::Error for JointError {}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct JointDrift {
pub linear: f64,
pub angular: f64,
}