#! Contains `physics3d`: what collides in space, as a game of three dimensions #! asks it. Shapes, spheres, capsules, and convex hulls, boxes among them, each #! about the origin of its body and placed by a `pose`; whether two meet, and #! the `manifold` of where and how deep, which way to push them apart; where a #! ray first meets one; an `aabb_tree` of many, which finds those near a box or #! along a ray without passing over the rest; and a `triangle_mesh`, as a #! level's ground and walls are, met a triangle at a time, but for the edges #! two triangles share flat or hollow, so a body slides along a floor of many #! triangles as along one. #! #! Space is `linear`'s: right-handed, y up, and rotations as quaternions. A #! hull's faces are counterclockwise as they're seen from outside, each normal #! facing out. A shape's surface is within it, so two shapes touching meet, at a #! depth of 0. #! #! What this holds is collision alone: bodies that move by forces and push one #! another apart come after, as `physics3d`'s solver. import std::math; import malunal::linear; module malunal::physics3d; # How near two numbers are taken as one, as lengths in a game's units are. const tiny: f32 = 1e-6; # How far a feature may be past another and still be taken as as good, so the # same pair gives the same face from one frame to the next. const tolerance: f32 = 1e-3; # The point of a segment nearest a place. def nearest_on_segment(p: vec3, a: vec3, b: vec3): vec3 { val e := b - a; val length_squared := e.dot(e); return a if length_squared <= tiny * tiny; val t := math::clamp((p - a).dot(e) / length_squared, 0f, 1f); return a + e * t; } # The points of two segments nearest one another: on `a1`-`a2` first, then on # `b1`-`b2`, as Ericson's Real-Time Collision Detection finds them. def nearest_of_segments(a1: vec3, a2: vec3, b1: vec3, b2: vec3): vec3[2] { val d1 := a2 - a1; val d2 := b2 - b1; val r := a1 - b1; val a := d1.dot(d1); val e := d2.dot(d2); val f := d2.dot(r); var s: f32 = 0; var t: f32 = 0; if a <= tiny && e <= tiny { return [a1, b1]; } if a <= tiny { t = math::clamp(f / e, 0f, 1f); } else { val c := d1.dot(r); if e <= tiny { s = math::clamp(-c / a, 0f, 1f); } else { val b := d1.dot(d2); val denominator := a * e - b * b; s = denominator > tiny ? math::clamp((b * f - c * e) / denominator, 0f, 1f) : 0; t = (b * s + f) / e; if t < 0 { t = 0; s = math::clamp(-c / a, 0f, 1f); } else if t > 1 { t = 1; s = math::clamp((b - c) / a, 0f, 1f); } } } return [a1 + d1 * s, b1 + d2 * t]; } # A direction at right angles to another, of length 1. def perpendicular_to(v: vec3): vec3 { val other := math::abs(v.x) < 0.57 ? vec3::right : vec3::up; return v.cross(other).normalized(); }