Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix angular inertia calculation in RigidBody::add_local_inertia_and_com #282

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions src/object/rigid_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,9 @@ impl<N: RealField> Body<N> for RigidBody<N> {

let mass_sum = self.inertia.linear + inertia.linear;

let previous_local_com = self.local_com;
let previous_mass = self.inertia.linear;

// Update center of mass.
if !mass_sum.is_zero() {
self.local_com =
Expand All @@ -760,8 +763,40 @@ impl<N: RealField> Body<N> for RigidBody<N> {
self.com = self.position.translation.vector.into();
}

// Update local inertia.
self.local_inertia += inertia;
// https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor_of_translation
#[inline]
fn shift_inertia_tensor<N: RealField>(
mass: N,
com_distance: &na::Vector3<N>,
com_inertia: &na::Matrix3<N>,
) -> na::Matrix3<N> {
let distance_transposed = com_distance.transpose();
com_inertia
+ ((na::Matrix3::<N>::identity() * com_distance.dot(&com_distance))
- distance_transposed.tr_mul(&distance_transposed))
* mass
}

let old_inertia_com_distance = previous_local_com - self.local_com;
let new_inertia_com_distance = com - self.local_com;

// Update local inertia. Calculates shifted inertia tensors.
// The angular inertia tensor must represent inertia around the center of mass.
// By treating the old and newly added inertia as those of two bodies which are
// each offset from the new center of mass (self.local_com), one can apply the
// parallel axis theorem to translate the inertias and sum them to represent inertia
// around the new center of mass.
self.local_inertia.angular = shift_inertia_tensor::<N>(
previous_mass,
&old_inertia_com_distance,
&self.local_inertia.angular,
) + shift_inertia_tensor::<N>(
inertia.linear,
&new_inertia_com_distance,
&inertia.angular,
);
self.local_inertia.linear = mass_sum;

self.update_inertia_from_local_inertia();
}

Expand Down