Algorithm Search⌘K

Algorithmintro

Impulse-based collision response

Also called collision impulse.

Change the velocities of two colliding rigid bodies by an impulse along the contact normal whose size makes the restitution law hold.

Time
O(1) one_contactO(c) one_pass
Space
O(1) extra
Where
c = the number of contact points that are processed one at a time
Properties
deterministicin placeonlineiterative
Origin
James K. Hahn, Matthew Moore, Jane Wilhelms, David Baraff, 1988

The collision impulse is the change of momentum that resolves a collision between two rigid bodies at one contact point in one instant. It acts along the contact normal, and its size is chosen so that the normal relative velocity after the collision is −e-e times the one before it, which is Newton's law with the coefficient of restitution ee. The formula takes the masses, the inertia tensors and the lever arms of both bodies into account, so a hit away from the center of mass makes the body spin. This page treats the frictionless case; friction is a variant.

In plain words

Two objects hit each other at a point. In a real collision they press together for a very short time, and a large force pushes them apart. A simulation does not follow that short time. It replaces the whole push by one jump in the velocities, called an impulse.

The direction of the push is the direction that points straight out of the contact surface. The strength of the push is the only unknown. Pick it so that the two touching points separate at a given fraction of their approach speed: all of it for a perfect bounce, none of it for a dead stop.

The push changes how fast each object moves and how fast it spins. A light object reacts more than a heavy one. An object that is hit far from its center turns more. The formula adds up these effects to find the strength.

The problem

At an instant t0t_0, two bodies AA and BB touch at the point pp with the unit normal nn, which points from BB to AA (the convention of Baraff's notes). Body XX has its center of mass xXx_X, linear velocity vXv_X, angular velocity ωX\omega_X, mass mXm_X and world inertia tensor IX=RXIbody,XRXTI_X = R_X I_{body,X} R_X^T. A static body, such as the ground, has mX−1=0m_X^{-1} = 0 and IX−1=0I_X^{-1} = 0. Let rX=p−xXr_X = p - x_X. The velocity of the material point of XX at pp is vX+ωX×rXv_X + \omega_X \times r_X, and the relative normal velocity is

vrel=n⋅((vA+ωA×rA)−(vB+ωB×rB)).v_{rel} = n \cdot \big((v_A + \omega_A \times r_A) - (v_B + \omega_B \times r_B)\big).

If vrel<0v_{rel} < 0, the bodies approach and the contact is a collision. The output is the impulse jnj n on AA and −jn-j n on BB, with j≥0j \ge 0, and the new velocities, such that vrel+=−e vrel−v_{rel}^+ = -e\, v_{rel}^- for the given e∈[0,1]e \in [0, 1]. Positions do not change during the collision. Newton's law of restitution is an empirical model, and ee is a measured value for a pair of materials; see coefficient of restitution.

The algorithm

  1. COLLISION-IMPULSE(A, B, p, n, e)
  2. 1r_A ← p - x_A; r_B ← p - x_B
  3. 2v_rel ← n · ((v_A + ω_A × r_A) - (v_B + ω_B × r_B))
  4. 3if v_rel ≥ 0 then return 0 ▷ not approaching: no impulse
  5. 4k ← 1/m_A + 1/m_B + n · ((I_A⁻¹ (r_A × n)) × r_A) + n · ((I_B⁻¹ (r_B × n)) × r_B)
  6. 5j ← -(1 + e) v_rel / k
  7. 6v_A ← v_A + (j / m_A) n; ω_A ← ω_A + I_A⁻¹ (r_A × j n)
  8. 7v_B ← v_B - (j / m_B) n; ω_B ← ω_B - I_B⁻¹ (r_B × j n)
  9. 8return j

Line L4 computes kk, the change of vrelv_{rel} per unit of impulse. It is the inverse of the effective mass of the contact along nn. Each rotation term equals (rX×n)TIX−1(rX×n)(r_X \times n)^T I_X^{-1} (r_X \times n), so it is never negative, and it is zero when the normal passes through the center of mass. Line L5 is the only solve: vrelv_{rel} is linear in jj, so one division gives the exact value. Lines L6 and L7 apply equal and opposite impulses.

Example

A box of mass m=1m = 1 with sides 2, 1 and 1 along its own x, y and z axes has Ibody=diag(1/6,5/12,5/12)I_{body} = \mathrm{diag}(1/6, 5/12, 5/12). It is turned about the z axis by the angle with cos⁡=4/5\cos = 4/5 and sin⁡=3/5\sin = 3/5, so that its lowest edge is parallel to z. Take the midpoint of that edge as the contact point: rA=(−1/2,−1,0)r_A = (-1/2, -1, 0). The ground is static with n=(0,1,0)n = (0, 1, 0). The box moves with vA=(1,−2,0)v_A = (1, -2, 0) and ωA=0\omega_A = 0, and e=1/2e = 1/2.

step value
L2 vrel=−2v_{rel} = -2
L4 rA×n=(0,0,−1/2)r_A \times n = (0, 0, -1/2), rotation term =(1/2)2⋅12/5=3/5= (1/2)^2 \cdot 12/5 = 3/5, so k=1+3/5=8/5k = 1 + 3/5 = 8/5
L5 j=−(3/2)(−2)/(8/5)=15/8j = -(3/2)(-2) / (8/5) = 15/8
L6 vA+=(1,−1/8,0)v_A^+ = (1, -1/8, 0), ωA+=(0,0,−9/4)\omega_A^+ = (0, 0, -9/4)
after contact point velocity (−5/4,1,0)(-5/4, 1, 0), so vrel+=1=−e vrel−v_{rel}^+ = 1 = -e\, v_{rel}^-

Only (I−1)zz=12/5(I^{-1})_{zz} = 12/5 enters, because rA×nr_A \times n is along z. The kinetic energy goes from 5/25/2 to 25/1625/16. The loss 15/1615/16 equals (1−e2)vrel2/(2k)=(3/4)⋅4/(16/5)(1 - e^2) v_{rel}^2 / (2k) = (3/4) \cdot 4 / (16/5). The tangential velocity of the contact point changes from 11 to −5/4-5/4, although the impulse is purely normal: the spin that the impulse starts moves the contact point sideways.

Correctness

The proof is in proofs/correctness.md. By the Newton-Euler equations integrated over a vanishing time, an impulse JJ at pp changes vXv_X by J/mXJ / m_X and ωX\omega_X by IX−1(rX×J)I_X^{-1}(r_X \times J). These changes are linear in JJ, so vrel+=vrel−+jkv_{rel}^+ = v_{rel}^- + j k, and line L5 gives vrel+=−e vrel−v_{rel}^+ = -e\, v_{rel}^-. These are proved properties of the model:

  • Linear momentum and angular momentum about any fixed point are conserved, because the two impulses are equal, opposite and act at the same point.
  • The kinetic energy drops by exactly (1−e2)vrel2/(2k)(1 - e^2) v_{rel}^2 / (2k). So e=1e = 1 keeps the energy, and e=0e = 0 leaves vrel+=0v_{rel}^+ = 0.
  • k>0k > 0 when at least one body is not static, so line L5 is defined.
Proof: The collision impulse makes Newton's restitution law hold, conserves momentum and removes a known amount of energyfull

The setting is one contact point pp between two rigid bodies AA and BB at one instant. Body X∈{A,B}X \in \{A, B\} has center of mass xXx_X, linear velocity vXv_X, angular velocity ωX\omega_X, mass mXm_X and inertia tensor IXI_X in world coordinates. IXI_X is symmetric positive definite. A static body has mX−1=0m_X^{-1} = 0 and IX−1=0I_X^{-1} = 0. The unit normal nn points from BB to AA, rX=p−xXr_X = p - x_X, and the velocity of the material point of XX at pp is uX=vX+ωX×rXu_X = v_X + \omega_X \times r_X. The relative normal velocity is vrel=n⋅(uA−uB)v_{rel} = n \cdot (u_A - u_B). The collision is instantaneous: positions do not change, and only the impulse jnj n on AA and −jn-j n on BB acts. A superscript −- marks a value before the impulse and ++ a value after it.

Lemma 1 (response of one body). If an impulse JJ acts on body XX at pp, then vX+=vX−+mX−1Jv_X^+ = v_X^- + m_X^{-1} J and ωX+=ωX−+IX−1(rX×J)\omega_X^+ = \omega_X^- + I_X^{-1} (r_X \times J). So uX+−uX−=mX−1J+(IX−1(rX×J))×rXu_X^+ - u_X^- = m_X^{-1} J + (I_X^{-1} (r_X \times J)) \times r_X.

Proof. An impulse is the integral of a force over a time interval of length tending to zero. The linear momentum mXvXm_X v_X changes by JJ, and the angular momentum about the center of mass, IXωXI_X \omega_X, changes by the moment rX×Jr_X \times J (Newton-Euler equations, integrated over the interval; the bounded terms such as ω×Iω\omega \times I \omega integrate to zero as the interval shrinks). Divide by mXm_X and multiply by IX−1I_X^{-1}. The second formula is the definition of uXu_X applied to the differences. □\square

Lemma 2 (the scalar kk). Let k=mA−1+mB−1+n⋅((IA−1(rA×n))×rA)+n⋅((IB−1(rB×n))×rB)k = m_A^{-1} + m_B^{-1} + n \cdot ((I_A^{-1} (r_A \times n)) \times r_A) + n \cdot ((I_B^{-1} (r_B \times n)) \times r_B), the value of line L4. Then n⋅((IX−1(rX×n))×rX)=(rX×n)TIX−1(rX×n)≥0n \cdot ((I_X^{-1} (r_X \times n)) \times r_X) = (r_X \times n)^T I_X^{-1} (r_X \times n) \ge 0, so k≥0k \ge 0, and k>0k > 0 when at least one body is not static.

Proof. For vectors a,b,ca, b, c, the scalar triple product satisfies a⋅(b×c)=b⋅(c×a)a \cdot (b \times c) = b \cdot (c \times a). With a=na = n, b=IX−1(rX×n)b = I_X^{-1} (r_X \times n) and c=rXc = r_X, this gives n⋅(b×rX)=b⋅(rX×n)=(rX×n)TIX−1(rX×n)n \cdot (b \times r_X) = b \cdot (r_X \times n) = (r_X \times n)^T I_X^{-1} (r_X \times n). The inverse of a symmetric positive definite matrix is symmetric positive definite, so this is ≥0\ge 0, and it is 00 for a static body. A body that is not static has mX−1>0m_X^{-1} > 0. □\square

Theorem 1 (restitution). If vrel−<0v_{rel}^- < 0 and k>0k > 0, then after lines L5 to L7, vrel+=−e vrel−v_{rel}^+ = -e\, v_{rel}^-.

Proof. By Lemma 1 with J=jnJ = j n on AA and J=−jnJ = -j n on BB, and by linearity in JJ, n⋅(uA+−uA−)=j (mA−1+n⋅((IA−1(rA×n))×rA))n \cdot (u_A^+ - u_A^-) = j\,(m_A^{-1} + n \cdot ((I_A^{-1} (r_A \times n)) \times r_A)) and n⋅(uB+−uB−)=−j (mB−1+n⋅((IB−1(rB×n))×rB))n \cdot (u_B^+ - u_B^-) = -j\,(m_B^{-1} + n \cdot ((I_B^{-1} (r_B \times n)) \times r_B)). Subtract: vrel+−vrel−=jkv_{rel}^+ - v_{rel}^- = j k. Line L5 sets j=−(1+e)vrel−/kj = -(1 + e) v_{rel}^- / k, so vrel+=vrel−−(1+e)vrel−=−e vrel−v_{rel}^+ = v_{rel}^- - (1 + e) v_{rel}^- = -e\, v_{rel}^-. □\square

For 0≤e≤10 \le e \le 1 and vrel−<0v_{rel}^- < 0, j>0j > 0, so the impulse pushes the bodies apart and vrel+≥0v_{rel}^+ \ge 0. If vrel−≥0v_{rel}^- \ge 0, line L3 returns with no change, because the bodies do not approach and a contact cannot pull.

Theorem 2 (momentum). If neither body is static, the total linear momentum mAvA+mBvBm_A v_A + m_B v_B and the total angular momentum about any fixed point oo, ∑X((xX−o)×mXvX+IXωX)\sum_X ((x_X - o) \times m_X v_X + I_X \omega_X), do not change. A static body takes up the impulse without moving, so with a static body the momentum of the moving body changes, as it must.

Proof. The change of linear momentum is jn−jn=0j n - j n = 0. The change of angular momentum about oo is (xA−o)×jn+rA×jn−(xB−o)×jn−rB×jn(x_A - o) \times j n + r_A \times j n - (x_B - o) \times j n - r_B \times j n by Lemma 1, because xXx_X does not change. Since xX+rX=px_X + r_X = p for both bodies, this is (p−o)×jn−(p−o)×jn=0(p - o) \times j n - (p - o) \times j n = 0. □\square

Theorem 3 (energy). Let T=∑X12(mXvX⋅vX+ωX⋅IXωX)T = \sum_X \tfrac12 (m_X v_X \cdot v_X + \omega_X \cdot I_X \omega_X). Then T−−T+=(1−e2)(vrel−)2/(2k)T^- - T^+ = (1 - e^2) (v_{rel}^-)^2 / (2k). In particular, for e=1e = 1 the kinetic energy does not change, and for 0≤e<10 \le e < 1 it decreases.

Proof. For one body and an impulse JJ at pp: 12m(v+⋅v+−v−⋅v−)=12m(v+−v−)⋅(v++v−)=12J⋅(v++v−)\tfrac12 m (v^+ \cdot v^+ - v^- \cdot v^-) = \tfrac12 m (v^+ - v^-) \cdot (v^+ + v^-) = \tfrac12 J \cdot (v^+ + v^-). Since II is symmetric, 12(ω+TIω+−ω−TIω−)=12(ω+−ω−)TI(ω++ω−)=12(r×J)⋅(ω++ω−)=12J⋅((ω++ω−)×r)\tfrac12 (\omega^{+T} I \omega^+ - \omega^{-T} I \omega^-) = \tfrac12 (\omega^+ - \omega^-)^T I (\omega^+ + \omega^-) = \tfrac12 (r \times J) \cdot (\omega^+ + \omega^-) = \tfrac12 J \cdot ((\omega^+ + \omega^-) \times r), by Lemma 1 and the triple product rule. The sum is 12J⋅(u++u−)\tfrac12 J \cdot (u^+ + u^-). With J=jnJ = j n on AA and −jn-j n on BB, the total change is T+−T−=12j(vrel++vrel−)=12j(1−e)vrel−T^+ - T^- = \tfrac12 j (v_{rel}^+ + v_{rel}^-) = \tfrac12 j (1 - e) v_{rel}^- by Theorem 1. Insert j=−(1+e)vrel−/kj = -(1 + e) v_{rel}^- / k: T+−T−=−(1+e)(1−e)(vrel−)2/(2k)T^+ - T^- = -(1 + e)(1 - e) (v_{rel}^-)^2 / (2k). □\square

Termination and cost. The procedure has no loop. It does a fixed number of cross products, dot products and 3 by 3 matrix-vector products, so it ends after O(1)O(1) arithmetic operations.

What is not proved. The theorems are about the model: an instantaneous collision at one point, no friction, and Newton's law vrel+=−e vrel−v_{rel}^+ = -e\, v_{rel}^- with an empirical ee. They say nothing about the accuracy of that model for real objects. With friction, or with several simultaneous contacts that are treated one at a time, Theorem 3 does not apply as stated.

Complexity

One call does a fixed number of cross products, dot products and 3 by 3 matrix-vector products: O(1)O(1) time and O(1)O(1) extra space in the real RAM. The inverse world inertia I−1=RIbody−1RTI^{-1} = R I_{body}^{-1} R^T is computed once per body per step. A pass over cc contacts costs O(c)O(c). A pass is not a full solve when contacts interact (see Pitfalls); repeated passes are projected Gauss-Seidel, and their number is a measurement unless a convergence bound applies.

Properties

  • Exact in exact arithmetic: one linear equation in one unknown.
  • Conserves linear and angular momentum for any ee, and kinetic energy for e=1e = 1.
  • Never pulls: the result jj is ≥0\ge 0, and a separating contact gets no impulse.
  • Local: it uses only the two bodies at the contact.
  • Positions do not change, so a collision response does not remove an overlap. That is the job of the collision detection and of position correction such as Baumgarte stabilization.

Variants and improvements

  • Friction. With Coulomb friction, the impulse has a tangential part. The simple version computes the impulse that stops the tangential motion and clamps it to the friction cone ∣jt∣≤μjn|j_t| \le \mu j_n. Mirtich and Canny integrate the impulse along the collision, so that sliding can stop or change direction during the collision; see impulse-based simulation. With friction the energy statement above does not hold as stated; the coefficient of restitution page has an example in which Newton's law plus a sticking impulse adds energy.
  • Poisson and Stronge. Instead of Newton's law on velocities, Poisson's hypothesis sets the normal impulse to (1+e)(1 + e) times the impulse at maximum compression, and Stronge's energetic coefficient compares the work of the normal force in the two phases. Without friction, the three give the same impulse as this page.
  • Several contacts at once. The impulses of simultaneous contacts are coupled. They solve a linear complementarity problem, which projected Gauss-Seidel solves by repeated calls of this formula, and a pivoting method such as Baraff's algorithm solves exactly for forces.
  • 2D. In the plane, ω\omega is a scalar, r×nr \times n is the scalar rxny−rynxr_x n_y - r_y n_x, and the rotation term of L4 is (r×n)2/I(r \times n)^2 / I.

When to use it

Use it for the response to a collision at one point, between bodies with known masses and inertia, when the collision is short compared with the time step. It is the inner step of impulse-based simulation and of iterative velocity solvers. For a body that rests on several points, or a stack, one call per contact is not enough; use an iterative solver with accumulated impulses, or a complementarity solver.

Pitfalls

  • Normal direction. The formula assumes that nn points from BB to AA, with the impulse +jn+j n on AA. With the opposite normal and the same signs, the impulse pulls the bodies together.
  • Missing L3. Without the test for separation, a contact that is already separating gets an impulse, and resting bodies stick to each other.
  • Body inertia instead of world inertia. I−1I^{-1} must be RIbody−1RTR I_{body}^{-1} R^T for the current orientation. With Ibody−1I_{body}^{-1}, the spin is wrong for any rotated body.
  • One contact at a time. A 2D box of mass 1 with sides 2 and 1 lands flat on its two bottom corners with speed 1 m/s. With e=0e = 0, one pass over the two corners leaves vy=−84/289v_y = -84/289 and ωz=84/289\omega_z = 84/289, and the first corner still approaches; each further pass multiplies the velocities by 49/28949/289, so the passes converge to rest only in the limit. With e=1e = 1, the first corner still approaches after one pass, and after the second pass both corners separate with vy=4697/4913v_y = 4697/4913 and ωz=2232/4913\omega_z = 2232/4913. The kinetic energy is still 1/21/2, but part of it is now spin, while the symmetric answer is vy=1v_y = 1 and ωz=0\omega_z = 0. The order of the contacts changes the result.
  • Bouncing at rest. With e>0e > 0 and gravity, a resting body makes many small bounces. A ball with e=1/2e = 1/2 dropped from 1 m makes infinitely many bounces in a finite time (the coefficient of restitution page has the numbers). Engines set e=0e = 0 below a speed threshold; that threshold is a tuning value.
  • Rounding. In floating point, the energy for e=1e = 1 is kept only to rounding. Keep the contact normal exactly unit length.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

anim.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.

This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.

Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
  left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
  with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
  rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""

import math

# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6


# ---------------------------------------------------------------- vectors


def add(a, b):
    """Return a + b."""
    return tuple(x + y for x, y in zip(a, b))


def sub(a, b):
    """Return a - b."""
    return tuple(x - y for x, y in zip(a, b))


def scale(a, s):
    """Return s a for a number s."""
    return tuple(s * x for x in a)


def dot(a, b):
    """Return the dot product of a and b."""
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    """Return the cross product of two 3D vectors."""
    return (
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    )


def cross2(a, b):
    """Return the scalar 2D cross product a_x b_y - a_y b_x."""
    return a[0] * b[1] - a[1] * b[0]


def norm(a):
    """Return the Euclidean length of a."""
    return math.sqrt(sum(x * x for x in a))


def normalize(a):
    """Return a / |a|. Raise ValueError for the zero vector."""
    n = norm(a)
    if n == 0.0:
        raise ValueError("cannot normalize the zero vector")
    return tuple(x / n for x in a)


def lerp(a, b, t):
    """Return (1 - t) a + t b."""
    return tuple((1 - t) * x + t * y for x, y in zip(a, b))


# ---------------------------------------------------------------- matrices


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None)."""
    if m is None:
        m = n
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the vector a x as a tuple."""
    return tuple(sum(p * q for p, q in zip(row, x)) for row in a)


def transpose(a):
    """Return the transpose of a."""
    return [list(col) for col in zip(*a)]


def _lu(a):
    """Gaussian elimination with partial pivoting on a copy of a square a.

    Return (lu, perm, sign), or None if a pivot is exactly zero.
    """
    n = len(a)
    lu = [list(map(float, row)) for row in a]
    perm = list(range(n))
    sign = 1.0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(lu[i][k]))
        if lu[p][k] == 0.0:
            return None
        if p != k:
            lu[k], lu[p] = lu[p], lu[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        piv = lu[k][k]
        for i in range(k + 1, n):
            f = lu[i][k] / piv
            lu[i][k] = f
            if f != 0.0:
                rk = lu[k]
                ri = lu[i]
                for j in range(k + 1, n):
                    ri[j] -= f * rk[j]
    return lu, perm, sign


def det(a):
    """Return the determinant of a square matrix."""
    n = len(a)
    if n == 1:
        return a[0][0]
    if n == 2:
        return a[0][0] * a[1][1] - a[0][1] * a[1][0]
    if n == 3:
        return (
            a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
            - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
            + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
        )
    r = _lu(a)
    if r is None:
        return 0.0
    lu, _, sign = r
    d = sign
    for i in range(n):
        d *= lu[i][i]
    return d


def _lu_solve(lu, perm, b):
    n = len(lu)
    y = [float(b[perm[i]]) for i in range(n)]
    for i in range(n):
        s = y[i]
        row = lu[i]
        for j in range(i):
            s -= row[j] * y[j]
        y[i] = s
    for i in range(n - 1, -1, -1):
        s = y[i]
        row = lu[i]
        for j in range(i + 1, n):
            s -= row[j] * y[j]
        y[i] = s / row[i]
    return y


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (returns a list) or a matrix given as a list of rows
    (returns a list of rows, one column of x per column of b).
    Raise ValueError if a is singular.
    """
    r = _lu(a)
    if r is None:
        raise ValueError("singular matrix")
    lu, perm, _ = r
    if len(b) > 0 and isinstance(b[0], (list, tuple)):
        cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
        return [list(row) for row in zip(*cols)]
    return _lu_solve(lu, perm, b)


def inv(a):
    """Return the inverse of a square matrix. Raise ValueError if singular."""
    return solve(a, eye(len(a)))


# ---------------------------------------------------------------- polar decomposition


def rot2(theta):
    """Return the 2 by 2 rotation matrix by the angle theta."""
    c, s = math.cos(theta), math.sin(theta)
    return [[c, -s], [s, c]]


def _frob(a):
    return math.sqrt(sum(x * x for row in a for x in row))


def _sym_eig3(s):
    """Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).

    Return (values, vectors), where vectors[k] is the unit eigenvector of
    values[k].
    """
    a = [list(map(float, row)) for row in s]
    v = eye(3)
    for _ in range(50):
        off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
        if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
            break
        for p, q in ((0, 1), (0, 2), (1, 2)):
            if a[p][q] == 0.0:
                continue
            theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
            t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
            c = 1.0 / math.sqrt(t * t + 1.0)
            sn = t * c
            for k in range(3):
                akp, akq = a[k][p], a[k][q]
                a[k][p] = c * akp - sn * akq
                a[k][q] = sn * akp + c * akq
            for k in range(3):
                apk, aqk = a[p][k], a[q][k]
                a[p][k] = c * apk - sn * aqk
                a[q][k] = sn * apk + c * aqk
            for k in range(3):
                vkp, vkq = v[k][p], v[k][q]
                v[k][p] = c * vkp - sn * vkq
                v[k][q] = sn * vkp + c * vkq
    values = [a[i][i] for i in range(3)]
    vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
    return values, vectors


def polar(f, tol=1e-14, max_iter=100):
    """Return (R, S) with F = R S, det R = +1 and S symmetric.

    2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
    the rotation that maximizes trace(R^T F), and S = R^T F.
    3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
    the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
    is above 1e-2. It stops when the relative change in the Frobenius norm is
    at most tol, or after max_iter steps. The iteration gives the orthogonal
    polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
    eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
    If det F > 0, S is symmetric positive definite. If det F < 0, S is
    symmetric with one negative eigenvalue. Raise ValueError for a singular
    3 by 3 F.
    """
    n = len(f)
    if n == 2:
        theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
        r = rot2(theta)
        s = mul(transpose(r), f)
        s01 = 0.5 * (s[0][1] + s[1][0])
        s[0][1] = s[1][0] = s01
        return r, s
    if n != 3:
        raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
    x = [list(map(float, row)) for row in f]
    change = float("inf")
    for _ in range(max_iter):
        xi = inv(x)
        if change > 1e-2:
            g = math.sqrt(_frob(xi) / _frob(x))
        else:
            g = 1.0
        xit = transpose(xi)
        y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
        change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
        x = y
        if change <= tol:
            break
    u = x
    s = mul(transpose(u), f)
    s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    if det(u) < 0.0:
        values, vectors = _sym_eig3(s)
        k = min(range(3), key=lambda i: values[i])
        v = vectors[k]
        h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
        u = mul(u, h)
        s = mul(h, s)
        s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    return u, s


# ---------------------------------------------------------------- quaternions


def q_mul(p, q):
    """Return the Hamilton product p q."""
    a1, b1, c1, d1 = p
    a2, b2, c2, d2 = q
    return (
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    )


def q_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return (q[0], -q[1], -q[2], -q[3])


def q_dot(p, q):
    """Return the dot product of p and q as vectors of R^4."""
    return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]


def q_normalize(q):
    """Return q / |q|."""
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("cannot normalize the zero quaternion")
    return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)


def q_from_axis_angle(axis, angle):
    """Return the unit quaternion of the rotation by angle about axis (any length)."""
    u = normalize(axis)
    s = math.sin(0.5 * angle)
    return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])


def q_to_mat3(q):
    """Return the 3 by 3 rotation matrix of a unit quaternion."""
    w, x, y, z = q
    return [
        [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
        [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
        [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
    ]


def q_rotate(q, v):
    """Return the vector part of q (0, v) q* for a unit quaternion q."""
    r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
    return (r[1], r[2], r[3])


def q_log(q):
    """Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).

    For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
    phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
    """
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("log of the zero quaternion")
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    lw = math.log(n)
    if vn == 0.0:
        return (lw, 0.0, 0.0, 0.0)
    phi = math.atan2(vn, q[0])
    f = phi / vn
    return (lw, f * q[1], f * q[2], f * q[3])


def q_exp(q):
    """Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    ew = math.exp(q[0])
    if vn == 0.0:
        return (ew, 0.0, 0.0, 0.0)
    f = ew * math.sin(vn) / vn
    return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])


def slerp(q0, q1, t):
    """Spherical linear interpolation of unit quaternions on the short arc.

    If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
    comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
    normalized linear interpolation is returned. See
    robotics/rigid-body-motion/spherical-linear-interpolation.
    """
    if q_dot(q0, q1) < 0.0:
        q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
    a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
    b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
    w = 2.0 * math.atan2(a, b)
    if w < SLERP_SMALL_ANGLE:
        return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
    s = math.sin(w)
    c0 = math.sin((1 - t) * w) / s
    c1 = math.sin(t * w) / s
    return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))


def q_from_mat3(r):
    """Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.

    Shepperd's method: take the largest of the trace, r00, r11 and r22, and
    divide by the component that it gives. See
    robotics/rigid-body-motion/shepperd-method.
    """
    t = r[0][0] + r[1][1] + r[2][2]
    k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
    if k == 0:
        w = math.sqrt(1.0 + t) / 2.0
        f = 4.0 * w
        q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
    elif k == 1:
        x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
        f = 4.0 * x
        q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
    elif k == 2:
        y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
        f = 4.0 * y
        q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
    else:
        z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
        f = 4.0 * z
        q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
    if q[0] < 0.0:
        q = (-q[0], -q[1], -q[2], -q[3])
    return q


# ---------------------------------------------------------------- transforms


def make_T(r, t):
    """Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
    d = len(t)
    m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
    m.append([0.0] * d + [1.0])
    return m


def T_mul(a, b):
    """Return the product a b of two homogeneous transforms."""
    return mul(a, b)


def T_inv(m):
    """Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].

    The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
    """
    d = len(m) - 1
    a = [row[:d] for row in m[:d]]
    t = [m[i][d] for i in range(d)]
    ai = inv(a)
    ti = matvec(ai, t)
    return make_T(ai, tuple(-x for x in ti))


def T_apply(m, p):
    """Apply a homogeneous transform to a point p and return a tuple."""
    d = len(m) - 1
    return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))


# ---------------------------------------------------------------- derivatives


def num_grad(f, x, h=1e-6):
    """Return the gradient of a scalar f at x by central differences of step h."""
    x = list(x)
    g = []
    for i in range(len(x)):
        xi = x[i]
        x[i] = xi + h
        fp = f(x)
        x[i] = xi - h
        fm = f(x)
        x[i] = xi
        g.append((fp - fm) / (2.0 * h))
    return g
collision_impulse.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/collision-impulse/. The authors are listed in prov/RVWXT5.jsonl.

"""Frictionless collision impulse between two rigid bodies in 3D.

A body has its center of mass x, linear velocity v, angular velocity w (in
world coordinates), inverse mass inv_m and inverse inertia tensor inv_I (a
3 by 3 matrix in world coordinates, R I_body^(-1) R^T). A static body has
inv_m = 0 and inv_I = 0. All functions accept Fraction values, so the tests
can check the identities exactly.

Conventions (Baraff's course notes, Section 8): the contact normal n is a
unit vector that points from B to A, the relative normal velocity is
v_rel = n . (v_A(p) - v_B(p)), and v_rel < 0 means that the bodies approach.
The impulse j n acts on A and -j n acts on B.
"""

from anim import add, cross, dot, matvec, scale, sub


class Body:
    """A rigid body at one instant. m and I are needed only for the energy and momentum checks."""

    def __init__(self, x, v, w, inv_m, inv_I, m=None, I=None):
        self.x = tuple(x)
        self.v = tuple(v)
        self.w = tuple(w)
        self.inv_m = inv_m
        self.inv_I = [list(row) for row in inv_I]
        self.m = m
        self.I = None if I is None else [list(row) for row in I]

    def point_velocity(self, p):
        """Velocity of the material point of the body at the world point p."""
        return add(self.v, cross(self.w, sub(p, self.x)))


def static_body(x):
    """A body that no impulse can move (the ground)."""
    z = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    return Body(x, (0, 0, 0), (0, 0, 0), 0, z, m=None, I=None)


def relative_normal_velocity(a, b, p, n):
    """v_rel = n . (v_A(p) - v_B(p))."""
    return dot(n, sub(a.point_velocity(p), b.point_velocity(p)))


def effective_inverse_mass(a, b, p, n):
    """k = 1/m_A + 1/m_B + n.((I_A^-1 (r_A x n)) x r_A) + n.((I_B^-1 (r_B x n)) x r_B)."""
    r_a = sub(p, a.x)
    r_b = sub(p, b.x)
    k = a.inv_m + b.inv_m
    k += dot(n, cross(matvec(a.inv_I, cross(r_a, n)), r_a))
    k += dot(n, cross(matvec(b.inv_I, cross(r_b, n)), r_b))
    return k


def collision_impulse(a, b, p, n, e):
    """Apply the frictionless collision impulse at the contact point p and return j.

    After the call, n . (v_A(p) - v_B(p)) = -e times its value before the call,
    if the bodies were approaching. If they were not approaching, nothing changes
    and the result is 0.
    """
    r_a = sub(p, a.x)  # @line L1
    r_b = sub(p, b.x)  # @line L1
    v_rel = dot(n, sub(add(a.v, cross(a.w, r_a)), add(b.v, cross(b.w, r_b))))  # @line L2
    if v_rel >= 0:  # @line L3
        return 0  # @line L3
    k = a.inv_m + b.inv_m  # @line L4
    k += dot(n, cross(matvec(a.inv_I, cross(r_a, n)), r_a))  # @line L4
    k += dot(n, cross(matvec(b.inv_I, cross(r_b, n)), r_b))  # @line L4
    if k == 0:
        raise ValueError("both bodies are static")
    j = -(1 + e) * v_rel / k  # @line L5
    jn = scale(n, j)
    a.v = add(a.v, scale(jn, a.inv_m))  # @line L6
    a.w = add(a.w, matvec(a.inv_I, cross(r_a, jn)))  # @line L6
    b.v = sub(b.v, scale(jn, b.inv_m))  # @line L7
    b.w = sub(b.w, matvec(b.inv_I, cross(r_b, jn)))  # @line L7
    return j  # @line L8


def energy_loss(v_rel, k, e):
    """The kinetic energy that the collision removes: (1 - e^2) v_rel^2 / (2 k)."""
    return (1 - e * e) * v_rel * v_rel / (2 * k)


def kinetic_energy(bodies):
    """Sum of (m v.v + w.I w) / 2 over the bodies that have a mass."""
    total = 0
    for body in bodies:
        if body.m is None:
            continue
        total += body.m * dot(body.v, body.v) / 2 + dot(body.w, matvec(body.I, body.w)) / 2
    return total


def linear_momentum(bodies):
    total = (0, 0, 0)
    for body in bodies:
        if body.m is not None:
            total = add(total, scale(body.v, body.m))
    return total


def angular_momentum(bodies, origin=(0, 0, 0)):
    """Sum of (x - origin) x m v + I w over the bodies that have a mass."""
    total = (0, 0, 0)
    for body in bodies:
        if body.m is None:
            continue
        total = add(total, cross(sub(body.x, origin), scale(body.v, body.m)))
        total = add(total, matvec(body.I, body.w))
    return total
test_collision_impulse.py 191 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/collision-impulse/. The authors are listed in prov/RVWXT5.jsonl.

import math
import random
from fractions import Fraction as F

from anim import q_normalize, q_to_mat3
from collision_impulse import (
    Body,
    angular_momentum,
    collision_impulse,
    effective_inverse_mass,
    energy_loss,
    kinetic_energy,
    linear_momentum,
    relative_normal_velocity,
    static_body,
)


def conj(r, d):
    """R diag(d) R^T, exact for Fraction entries."""
    return [[sum(r[i][k] * d[k] * r[j][k] for k in range(3)) for j in range(3)] for i in range(3)]


def rational_rotation(rng):
    """An exact rotation matrix from an integer quaternion (a, b, c, d) divided by its squared norm."""
    while True:
        a, b, c, d = (rng.randint(-5, 5) for _ in range(4))
        s = a * a + b * b + c * c + d * d
        if s:
            break
    return [
        [F(a * a + b * b - c * c - d * d, s), F(2 * (b * c - a * d), s), F(2 * (b * d + a * c), s)],
        [F(2 * (b * c + a * d), s), F(a * a - b * b + c * c - d * d, s), F(2 * (c * d - a * b), s)],
        [F(2 * (b * d - a * c), s), F(2 * (c * d + a * b), s), F(a * a - b * b - c * c + d * d, s)],
    ]


def rand_frac(rng, lo=-3, hi=3, den=4):
    return F(rng.randint(lo * den, hi * den), den)


def random_body(rng, exact=True):
    m = F(rng.randint(1, 8), rng.randint(1, 4))
    d = [F(rng.randint(1, 9), rng.randint(1, 5)) for _ in range(3)]
    r = rational_rotation(rng)
    x = tuple(rand_frac(rng) for _ in range(3))
    v = tuple(rand_frac(rng) for _ in range(3))
    w = tuple(rand_frac(rng) for _ in range(3))
    return Body(x, v, w, 1 / m, conj(r, [1 / t for t in d]), m=m, I=conj(r, d))


def unit_normal(rng):
    """A rational unit vector from an integer quaternion: R e_y."""
    r = rational_rotation(rng)
    return (r[0][1], r[1][1], r[2][1])


def approaching_pair(rng):
    while True:
        a, b = random_body(rng), random_body(rng)
        p = tuple(rand_frac(rng) for _ in range(3))
        n = unit_normal(rng)
        if relative_normal_velocity(a, b, p, n) < 0:
            return a, b, p, n


def test_page_example():
    c, s = F(4, 5), F(3, 5)
    rot = [[c, -s, 0], [s, c, 0], [0, 0, 1]]
    box = Body((0, 0, 0), (F(1), F(-2), F(0)), (0, 0, 0), F(1), conj(rot, [6, F(12, 5), F(12, 5)]), m=F(1),
               I=conj(rot, [F(1, 6), F(5, 12), F(5, 12)]))
    ground = static_body((0, -1, 0))
    p, n = (F(-1, 2), F(-1), F(0)), (0, 1, 0)
    assert effective_inverse_mass(box, ground, p, n) == F(8, 5)
    assert kinetic_energy([box]) == F(5, 2)
    j = collision_impulse(box, ground, p, n, F(1, 2))
    assert j == F(15, 8)
    assert box.v == (1, F(-1, 8), 0)
    assert box.w == (0, 0, F(-9, 4))
    assert box.point_velocity(p) == (F(-5, 4), 1, 0)
    assert kinetic_energy([box]) == F(25, 16)


def test_restitution_law_and_momentum_exact():
    rng = random.Random(7)
    for _ in range(60):
        a, b, p, n = approaching_pair(rng)
        e = F(rng.randint(0, 4), 4)
        v0 = relative_normal_velocity(a, b, p, n)
        k = effective_inverse_mass(a, b, p, n)
        lin0, ang0, ke0 = linear_momentum([a, b]), angular_momentum([a, b]), kinetic_energy([a, b])
        ang_p0 = angular_momentum([a, b], origin=p)
        j = collision_impulse(a, b, p, n, e)
        assert j > 0
        assert relative_normal_velocity(a, b, p, n) == -e * v0
        assert linear_momentum([a, b]) == lin0
        assert angular_momentum([a, b]) == ang0
        assert angular_momentum([a, b], origin=p) == ang_p0
        assert ke0 - kinetic_energy([a, b]) == energy_loss(v0, k, e)


def test_elastic_keeps_energy_and_plastic_stops_normal_motion():
    rng = random.Random(11)
    for _ in range(30):
        a, b, p, n = approaching_pair(rng)
        ke0 = kinetic_energy([a, b])
        collision_impulse(a, b, p, n, F(1))
        assert kinetic_energy([a, b]) == ke0
        a, b, p, n = approaching_pair(rng)
        collision_impulse(a, b, p, n, F(0))
        assert relative_normal_velocity(a, b, p, n) == 0


def test_separating_contact_is_unchanged():
    rng = random.Random(3)
    for _ in range(20):
        a, b = random_body(rng), random_body(rng)
        p = tuple(rand_frac(rng) for _ in range(3))
        n = unit_normal(rng)
        if relative_normal_velocity(a, b, p, n) < 0:
            n = tuple(-t for t in n)
        va, wa, vb, wb = a.v, a.w, b.v, b.w
        assert collision_impulse(a, b, p, n, F(1, 2)) == 0
        assert (a.v, a.w, b.v, b.w) == (va, wa, vb, wb)


def test_head_on_matches_newton_closed_form():
    rng = random.Random(5)
    zero = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    for _ in range(30):
        m1, m2 = F(rng.randint(1, 9)), F(rng.randint(1, 9))
        u1, u2 = F(rng.randint(1, 9)), F(-rng.randint(0, 9))
        e = F(rng.randint(0, 4), 4)
        a = Body((-1, 0, 0), (u1, 0, 0), (0, 0, 0), 1 / m1, zero, m=m1, I=zero)
        b = Body((1, 0, 0), (u2, 0, 0), (0, 0, 0), 1 / m2, zero, m=m2, I=zero)
        collision_impulse(a, b, (0, 0, 0), (-1, 0, 0), e)  # the normal points from b to a
        v1 = (m1 * u1 + m2 * u2 - m2 * e * (u1 - u2)) / (m1 + m2)
        v2 = (m1 * u1 + m2 * u2 + m1 * e * (u1 - u2)) / (m1 + m2)
        assert a.v[0] == v1 and b.v[0] == v2


def test_drop_check_value():
    g, h, e = 9.81, 1.0, 0.5
    ball = Body((0, 0.1, 0), (0, -math.sqrt(2 * g * h), 0), (0, 0, 0), 1.0, [[25, 0, 0], [0, 25, 0], [0, 0, 25]])
    ground = static_body((0, -1, 0))
    collision_impulse(ball, ground, (0, 0, 0), (0, 1, 0), e)
    assert abs(ball.v[1] ** 2 / (2 * g) - 0.25) < 1e-12
    assert ball.w == (0.0, 0.0, 0.0)


def test_float_momentum_with_random_rotations():
    rng = random.Random(19)
    for _ in range(100):
        bodies = []
        for _ in range(2):
            q = q_normalize(tuple(rng.uniform(-1, 1) for _ in range(4)))
            r = q_to_mat3(q)
            d = [rng.uniform(0.2, 3.0) for _ in range(3)]
            m = rng.uniform(0.5, 5.0)
            bodies.append(Body(tuple(rng.uniform(-2, 2) for _ in range(3)), tuple(rng.uniform(-3, 3) for _ in range(3)),
                               tuple(rng.uniform(-3, 3) for _ in range(3)), 1 / m, conj(r, [1 / t for t in d]), m=m,
                               I=conj(r, d)))
        a, b = bodies
        p = tuple(rng.uniform(-2, 2) for _ in range(3))
        n = q_rotate_y(rng)
        if relative_normal_velocity(a, b, p, n) > 0:
            n = tuple(-t for t in n)
        lin0, ang0 = linear_momentum(bodies), angular_momentum(bodies)
        ke0 = kinetic_energy(bodies)
        collision_impulse(a, b, p, n, 1.0)
        for x, y in zip(linear_momentum(bodies) + angular_momentum(bodies), lin0 + ang0):
            assert abs(x - y) <= 1e-10 * (1 + abs(y))
        assert abs(kinetic_energy(bodies) - ke0) <= 1e-12 * max(1.0, ke0)


def q_rotate_y(rng):
    r = q_to_mat3(q_normalize(tuple(rng.uniform(-1, 1) for _ in range(4))))
    return (r[0][1], r[1][1], r[2][1])


def test_two_static_bodies_raise():
    a, b = static_body((0, 0, 0)), static_body((1, 0, 0))
    a.v = (1, 0, 0)
    try:
        collision_impulse(a, b, (0, 0, 0), (-1, 0, 0), 1)
    except ValueError:
        return
    raise AssertionError("expected ValueError")

History

The impulse of a frictionless collision between rigid bodies comes from classical impact mechanics. In computer animation, Hahn (1988) treated collisions between rigid bodies with impulses, and Moore and Wilhelms (1988) gave an analytical collision response next to a spring method. Baraff's SIGGRAPH course notes give the formula with kk written as above, and it is the form used in many physics engines. Mirtich and Canny (1995) extended the impulse to Coulomb friction by integrating it along the collision, and built a whole simulator on impulses.

References

  1. David Baraff, An Introduction to Physically Based Modeling: Rigid Body Simulation II, Nonpenetration Constraints, in Andrew Witkin and David Baraff, Physically Based Modeling: Principles and Practice, SIGGRAPH 97 course notes, Section 8, Colliding Contact: the relative velocity (8-3), Newton's law of restitution (8-10) and the impulse formula (8-18)
  2. James K. Hahn, Realistic animation of rigid bodies, SIGGRAPH 88, Computer Graphics 22(4), 299-308, 1988, the impulse-based treatment of collisions between rigid bodies
  3. Matthew Moore and Jane Wilhelms, Collision detection and response for computer animation, SIGGRAPH 88, Computer Graphics 22(4), 289-298, 1988, the analytical collision response for rigid bodies
  4. Brian Mirtich and John Canny, Impulse-based simulation of rigid bodies, Proceedings of the 1995 Symposium on Interactive 3D Graphics, 181-188, Section 4, Computing collision impulses (the frictional version of the impulse, integrated along the collision)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.one_contact
  • a full proof of time.one_pass
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example