#! Contains `physics2d`: what collides and moves in a plane, as a game of two #! dimensions asks it. Shapes, circles, capsules, and convex polygons, 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 `grid` of solid cells, as a #! tilemap's walls are, met as boxes, each but the faces it shares with a solid #! neighbor, so a body slides along a floor of many cells as along one. #! #! And a `space` of bodies: each made of colliders, of shapes, a grid, or a #! chain's segments, pulled by gravity, pushed by forces and by what it meets, #! held to others by joints, and stepped forward in time as Box2D's soft step #! solves it, on as many threads as it's given, swept through each step where #! it moves fast enough to pass through what's thin, and sleeping where it and #! all it rests on are still. A space answers which colliders a shape overlaps #! and where a cast first meets one, and walks `character`s through it. #! #! The plane is `linear`'s x and y: x to the right, y up, and angles #! counterclockwise, in radians. A polygon's corners are counterclockwise, and #! each edge's normal faces out. A shape's surface is within it, so two shapes #! touching meet, at a depth of 0. import std::math; import malunal::linear; module malunal::physics2d; # How near two numbers are taken as one, as lengths in a game's units are. const tiny: f32 = 1e-6; # The point of a segment nearest a place. def nearest_on_segment(p: vec2, a: vec2, b: vec2): vec2 { 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: vec2, a2: vec2, b1: vec2, b2: vec2): vec2[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]; }