#! Contains how far apart two shapes are, their nearest places found as #! Gilbert, Johnson, and Keerthi's GJK finds them; a shape cast along a motion, #! to where it first meets another; and the time of impact of two shapes each #! swept through a step, moving and turning, as continuous collision asks. #! #! GJK finds the place of the shapes' difference, every place of the second #! less every place of the first, nearest the origin, by a tetrahedron of its #! corners at most, each step adding the corner furthest toward the origin and #! keeping only the corner, edge, or face the nearest place lies on, as #! Ericson's Real-Time Collision Detection finds it. It works each shape's #! core, a sphere's middle, a capsule's segment, or a hull, then takes the radii #! off, so a sphere's nearest place is as exact as a box's. #! #! A cast, and a time of impact, advance conservatively, as Mirtich's do: each #! moves the shapes as far as the gap between them, over how fast they can #! close it, says they can't yet meet, so neither ever passes through what it #! meets. import std::math; import malunal::linear; module malunal::physics3d; #! How far apart two shapes are, and the places of each nearest the other. pub struct gap { #! The places of the first's surface and the second's nearest one another: #! one place, midway, where they meet. pub var on_a: vec3; pub var on_b: vec3; #! The direction from the first toward the second, of length 1, or none #! where they meet. pub var normal: vec3; #! How far apart their surfaces are: 0 where they meet. pub var distance: f32; } #! Where a shape cast along a motion first met another: how far along the #! motion, as a fraction of it, the place of the other's surface it met, and #! which way that surface faces, toward the shape cast. pub struct cast_hit { pub var fraction: f32; pub var point: vec3; pub var normal: vec3; } # A corner of the shapes' difference, of a point of each, and its weight in # the nearest place. struct corner { var on_a: vec3; var on_b: vec3; var w: vec3; var weight: f32; var ia: u32; var ib: u32; } # As many as four corners, the nearest place lying among them. struct simplex { var corners: corner[4]; var count: u32; } # A point of a shape's core: a sphere's middle, a capsule's end, or a hull's # corner. def core_point(s: &shape, i: u32): vec3 { return s.as_hull().point(i) if s.kind == shape_kind::hull; return i == 0 ? s.a : s.b; } # The point of a shape's core furthest along a direction of space, where a # pose places it. def support_of(s: &shape, at: &pose, direction: vec3): u32 { val d := at.unrotate(direction); return s.as_hull().support(d) if s.kind == shape_kind::hull; return 1 if s.kind == shape_kind::capsule && (s.b - s.a).dot(d) > 0; return 0; } def corner_of(a: &shape, at_a: &pose, ia: u32, b: &shape, at_b: &pose, ib: u32): corner { val pa := at_a.apply(core_point(a, ia)); val pb := at_b.apply(core_point(b, ib)); return corner{ on_a = pa, on_b = pb, w = pb - pa, weight = 1, ia = ia, ib = ib }; } # Keeps one corner of the simplex. def keep_one(x: &mut simplex, i: u32): void { val kept := x.corners[i]; x.corners[0] = kept; x.corners[0].weight = 1; x.count = 1; } # Keeps two corners of the simplex, weighted so. def keep_two(x: &mut simplex, i: u32, j: u32, wi: f32, wj: f32): void { val first := x.corners[i]; val second := x.corners[j]; x.corners[0] = first; x.corners[0].weight = wi; x.corners[1] = second; x.corners[1].weight = wj; x.count = 2; } # The nearest place of a segment of the difference to the origin. def solve2(x: &mut simplex): void { val a := x.corners[0].w; val ab := x.corners[1].w - a; val along := -a.dot(ab); if along <= 0 { keep_one(x, 0); return; } val length := ab.dot(ab); if along >= length || length <= tiny * tiny { keep_one(x, 1); return; } val t := along / length; keep_two(x, 0, 1, 1 - t, t); } # The nearest place of a triangle of the difference to the origin, by which of # its corners, edges, or face it's on, as Ericson finds it. def solve3(x: &mut simplex): void { val a := x.corners[0].w; val b := x.corners[1].w; val c := x.corners[2].w; val ab := b - a; val ac := c - a; val d1 := -ab.dot(a); val d2 := -ac.dot(a); if d1 <= 0 && d2 <= 0 { keep_one(x, 0); return; } val d3 := -ab.dot(b); val d4 := -ac.dot(b); if d3 >= 0 && d4 <= d3 { keep_one(x, 1); return; } val vc := d1 * d4 - d3 * d2; if vc <= 0 && d1 >= 0 && d3 <= 0 { val v := d1 / (d1 - d3); keep_two(x, 0, 1, 1 - v, v); return; } val d5 := -ab.dot(c); val d6 := -ac.dot(c); if d6 >= 0 && d5 <= d6 { keep_one(x, 2); return; } val vb := d5 * d2 - d1 * d6; if vb <= 0 && d2 >= 0 && d6 <= 0 { val w := d2 / (d2 - d6); keep_two(x, 0, 2, 1 - w, w); return; } val va := d3 * d6 - d5 * d4; if va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0 { val w := (d4 - d3) / ((d4 - d3) + (d5 - d6)); keep_two(x, 1, 2, 1 - w, w); return; } # A triangle of no area, its corners in a line: its nearest edge. if ab.cross(ac).length_squared <= 1e-12 * ab.length_squared * ac.length_squared { nearest_edge(x); return; } val inv := 1 / (va + vb + vc); val v := vb * inv; val w := vc * inv; x.corners[0].weight = 1 - v - w; x.corners[1].weight = v; x.corners[2].weight = w; x.count = 3; } # Keeps the edge of three corners nearest the origin, as `solve2` keeps it. def nearest_edge(x: &mut simplex): void { val pairs: u32[6] = [0, 1, 0, 2, 1, 2]; var best := 1e30f; var kept := simplex{}; for k in 0..3u { var edge := simplex{ count = 2 }; edge.corners[0] = x.corners[pairs[k * 2]]; edge.corners[1] = x.corners[pairs[k * 2 + 1]]; solve2(&mut edge); var v := vec3::zero; for q in 0..edge.count { v = v + edge.corners[q].w * edge.corners[q].weight; } if v.length_squared < best { best = v.length_squared; kept = edge; } } x.corners = kept.corners; x.count = kept.count; } # Six times the signed volume of a tetrahedron. def volume(a: vec3, b: vec3, c: vec3, d: vec3): f32 { return (b - a).dot((c - a).cross(d - a)); } # The nearest place of a tetrahedron of the difference to the origin: within # it, or on the nearest of the faces it's outside of. def solve4(x: &mut simplex): void { val w: vec3[4] = [x.corners[0].w, x.corners[1].w, x.corners[2].w, x.corners[3].w]; # Each face, and the corner across from it. val faces: u32[16] = [0, 1, 2, 3, 0, 2, 3, 1, 0, 3, 1, 2, 1, 3, 2, 0]; var best := 1e30f; var nearest := simplex{}; var outside := false; for f in 0..4u { val i := faces[f * 4]; val j := faces[f * 4 + 1]; val k := faces[f * 4 + 2]; val across := faces[f * 4 + 3]; val n := (w[j] - w[i]).cross(w[k] - w[i]); val origin_side := -n.dot(w[i]); val other_side := n.dot(w[across] - w[i]); # The origin's beyond this face where it's on the side away from the # corner across from it, or the tetrahedron is flat, the corner across # nearly in the face's plane, for as large as the face is. val flat := math::abs(other_side) <= 1e-5 * n.length * (w[across] - w[i]).length; if origin_side * other_side < 0 || flat { outside = true; var face := simplex{ count = 3 }; face.corners[0] = x.corners[i]; face.corners[1] = x.corners[j]; face.corners[2] = x.corners[k]; solve3(&mut face); var v := vec3::zero; for q in 0..face.count { v = v + face.corners[q].w * face.corners[q].weight; } if v.length_squared < best { best = v.length_squared; nearest = face; } } } if outside { x.corners = nearest.corners; x.count = nearest.count; return; } val whole := volume(w[0], w[1], w[2], w[3]); val o := vec3::zero; x.corners[0].weight = volume(o, w[1], w[2], w[3]) / whole; x.corners[1].weight = volume(w[0], o, w[2], w[3]) / whole; x.corners[2].weight = volume(w[0], w[1], o, w[3]) / whole; x.corners[3].weight = volume(w[0], w[1], w[2], o) / whole; x.count = 4; } # Keeps the corners of a simplex the nearest place lies among, weighted. def solve(x: &mut simplex): void { if x.count == 2 { solve2(x); } else if x.count == 3 { solve3(x); } else if x.count == 4 { solve4(x); } } #! How far apart two shapes are, each where its pose places it, and the places #! of each nearest the other: none apart where they meet. pub def gap_between(a: &shape, at_a: pose, b: &shape, at_b: pose): gap { var x := simplex{ count = 1 }; x.corners[0] = corner_of(a, &at_a, 0, b, &at_b, 0); var last := 1e30f; for iteration in 0..32u { solve(&mut x); # Four corners hold the origin: the cores overlap. if x.count == 4 { break; } var v := vec3::zero; for i in 0..x.count { v = v + x.corners[i].w * x.corners[i].weight; } val squared := v.length_squared; # Nearer no more, as rounding among large places may leave it, adding # the same face's corners again: it's found. if squared < tiny * tiny || squared >= last { break; } last = squared; val ia := support_of(a, &at_a, v); val ib := support_of(b, &at_b, -v); val next := corner_of(a, &at_a, ia, b, &at_b, ib); # No corner further toward the origin than the nearest place: it's found. if squared - v.dot(next.w) <= 1e-6 * squared { break; } var again := false; for i in 0..x.count { if x.corners[i].ia == ia && x.corners[i].ib == ib { again = true; } } if again { break; } x.corners[x.count] = next; x.count++; } solve(&mut x); var on_a := vec3::zero; var on_b := vec3::zero; for i in 0..x.count { on_a = on_a + x.corners[i].on_a * x.corners[i].weight; on_b = on_b + x.corners[i].on_b * x.corners[i].weight; } if x.count == 4 { on_b = on_a; } val between := on_b - on_a; val cores := between.length; val reach := a.radius + b.radius; if cores > reach && cores > tiny { val normal := between * (1 / cores); return gap{ on_a = on_a + normal * a.radius, on_b = on_b - normal * b.radius, normal = normal, distance = cores - reach }; } val normal := cores > tiny ? between * (1 / cores) : vec3::zero; val middle := ((on_a + normal * a.radius) + (on_b - normal * b.radius)) * 0.5; return gap{ on_a = middle, on_b = middle, normal = normal, distance = 0 }; } #! Where a shape, `b`, cast along a motion of space from where its pose places #! it, first meets another, `a`, which stays where its pose places it: within #! `tolerance` of its surface, a little short of touching, so what's moved there #! doesn't overlap. Nothing where it doesn't meet it within the motion; a #! fraction of 0 where they meet as it begins, its normal back along the #! motion. pub def shape_cast(a: &shape, at_a: pose, b: &shape, at_b: pose, motion: vec3, tolerance: f32 = 0.0025): maybe { val target := 0.5 * tolerance; var t: f32 = 0; var at := at_b; for iteration in 0..30u { val g := gap_between(a, at_a, b, at); if g.distance <= tolerance { val back := g.distance > 0 ? g.normal : -motion.normalized(); return cast_hit{ fraction = t, point = g.on_a, normal = back }; } val approach := -motion.dot(g.normal); return nothing{} if approach <= tiny; t += (g.distance - target) / approach; return nothing{} if t > 1; at = pose{ at = at_b.at + motion * t, turn = at_b.turn }; } val g := gap_between(a, at_a, b, at); return cast_hit{ fraction = t, point = g.on_a, normal = g.normal }; } #! How a body moves through a step: its center of mass, of its own places, #! where that center begins and ends the step, and how it's turned as it begins #! and ends it, turning the shorter way between. pub struct sweep { pub var local_center: vec3; pub var c1: vec3; pub var c2: vec3; pub var q1 := quat::identity; pub var q2 := quat::identity; } #! A sweep standing still where a pose places a body. pub def sweep::still(at: pose, local_center: vec3 = vec3::zero): sweep { val center := at.apply(local_center); return sweep{ local_center = local_center, c1 = center, c2 = center, q1 = at.turn, q2 = at.turn }; } #! Where it places its body a fraction of the way through the step. pub def sweep::at(&this, t: f32): pose { val turn := this.q1.slerp(this.q2, t); val center := this.c1.lerp(this.c2, t); return pose{ at = center - turn * this.local_center, turn = turn }; } # How far it turns through the step, in radians. def sweep::turning(&this): f32 { val cosine := math::min(math::abs(this.q1.dot(this.q2)), 1f); return 2 * math::acos(cosine); } # How far a shape's surface reaches from a place of its own. def reach_from(s: &shape, center: vec3): f32 { if s.kind == shape_kind::hull { var most: f32 = 0; val h := s.as_hull(); for i in 0..h.count { most = math::max(most, (h.point(i) - center).length); } return most; } return math::max((s.a - center).length, (s.b - center).length) + s.radius; } #! When, as a fraction of the step, two shapes each swept through it first come #! within `target` of one another, to within `tolerance`, as their sweeps move #! and turn them: 1 where they don't. Each moves no further than they can, as #! fast as they close and turn, without meeting, so what's found is never past #! where they meet. pub def time_of_impact(a: &shape, sa: &sweep, b: &shape, sb: &sweep, target: f32, tolerance: f32): f32 { val turn_a := sa.turning() * reach_from(a, sa.local_center); val turn_b := sb.turning() * reach_from(b, sb.local_center); val moved := (sb.c2 - sb.c1) - (sa.c2 - sa.c1); var t: f32 = 0; for iteration in 0..50u { val g := gap_between(a, sa.at(t), b, sb.at(t)); return t if g.distance <= target + tolerance; val closing := -moved.dot(g.normal) + turn_a + turn_b; return 1 if closing <= tiny; t += (g.distance - target) / closing; return 1 if t >= 1; } return t; } # How far a shape reaches along a direction of space, where a pose places it. def reach_along(s: &shape, at: pose, direction: vec3): f32 { if s.kind == shape_kind::hull { val h := s.as_hull(); return direction.dot(at.apply(h.point(h.support(at.unrotate(direction))))); } return math::max(direction.dot(at.apply(s.a)), direction.dot(at.apply(s.b))) + s.radius; } # The middle of a shape: a sphere's, a capsule's, or a hull's center. def shape::middle(&this): vec3 { return this.as_hull().center if this.kind == shape_kind::hull; return (this.a + this.b) * 0.5; } # How far a shape reaches at least from its middle: a sphere's or a capsule's # radius, or the nearest of a hull's faces, as a body may move without passing # through what's in its way. def shape::least_reach(&this): f32 { return this.radius if this.kind != shape_kind::hull; val h := this.as_hull(); var least := 1e30f; for f in 0..h.faces { least = math::min(least, h.offset(f) - h.normal(f).dot(h.center)); } return least; }