Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-14 15:41:09 -06:00
commit 11d94dba85
84 files changed
+18825

No files matched your search

+707
View File
@@ -0,0 +1,707 @@
#! Contains collision between shapes: whether two meet, where they're placed,
#! and the `manifold` of where and how deep, which way to push them apart.
#!
#! Each shape is taken as a core, with its radius around it: a sphere's a
#! place, a capsule's a segment, and a hull itself, of no radius. Two spheres
#! or capsules meet as their cores near, a capsule lying along another at two
#! points. A sphere or capsule and a hull meet as the core nears the hull's
#! surface, a capsule lying along a face at two points; or, where the core
#! passes within the hull, by the face or edge that holds them furthest apart,
#! as the separating axis theorem finds it. Two hulls meet by the face of
#! either, or the pair of edges, one of each, that holds them furthest apart,
#! edges only where they make a face of the hulls' Minkowski difference, as
#! Gregorius tests them; at a face, the other's face most against it is
#! clipped to it, at as many as four points, and at two edges, at one.
import std::math;
import malunal::linear;
module malunal::physics3d;
#! The most points a manifold holds.
pub const max_contacts: u32 = 4;
#! A point where two shapes meet: midway between their surfaces, how deep the
#! one is within the other there, 0 where they touch, and which of their
#! features met there, the same from one step to the next while they still
#! meet so, by which a solver carries over what it found.
pub struct contact {
pub var point: vec3;
pub var depth: f32;
pub var id: u32;
}
#! Where and how deep two shapes meet: the normal from the first toward the
#! second, along which the second is pushed out of the first, and one to four
#! points, as a box resting flat on another rests on four.
pub struct manifold {
pub var normal: vec3;
pub var points: contact[4];
pub var count: u32;
}
#! The deepest of its points.
pub val manifold::depth: f32 {
get => this.deepest();
}
def manifold::deepest(&this): f32 {
var most := this.count == 0 ? 0f : this.points[0].depth;
for i in 1..this.count {
most = math::max(most, this.points[i].depth);
}
return most;
}
#! The manifold turned around, of the second shape against the first.
pub def manifold::flipped(&this): manifold {
return manifold{ normal = -this.normal, points = this.points, count = this.count };
}
#! Where two shapes meet, each where its pose places it, or nothing where they
#! don't: the manifold's normal from the first toward the second. Within a
#! `margin`, shapes apart are given points too, of depths below 0, as far as
#! they're apart, as a solver keeps what's about to meet from passing through.
pub def collide(a: &shape, at_a: pose, b: &shape, at_b: pose, margin: f32 = 0): maybe<manifold> {
if a.kind != shape_kind::hull && b.kind == shape_kind::hull {
if collide(b, at_b, a, at_a, margin) is some(m) {
return m.flipped();
}
return nothing{};
}
# Everything is worked out as the first shape sees it, then placed.
val rel := at_a.unapply_pose(at_b);
var found: maybe<manifold> = nothing{};
if a.kind != shape_kind::hull {
found = cores(a.a, a.b, a.radius, rel.apply(b.a), rel.apply(b.b), b.radius, margin);
} else if b.kind != shape_kind::hull {
found = hull_and_core(a.as_hull(), rel.apply(b.a), rel.apply(b.b), b.radius, margin);
} else {
found = hulls(a.as_hull(), b.as_hull(), &rel, margin);
}
if found is some(m) {
return placed(m, &at_a);
}
return nothing{};
}
#! Whether two shapes meet, each where its pose places it, touching among it.
pub def overlaps(a: &shape, at_a: pose, b: &shape, at_b: pose): bool {
return collide(a, at_a, b, at_b) is some(_);
}
# A manifold of a shape's own places, in space, where a pose places the shape.
def placed(m: manifold, at: &pose): manifold {
val turn := mat3::rotation(at.turn);
var made := manifold{ normal = turn * m.normal, count = m.count };
for i in 0..m.count {
made.points[i] = contact{ point = at.at + turn * m.points[i].point, depth = m.points[i].depth, id = m.points[i].id };
}
return made;
}
# A manifold of one point, between the surfaces of the first, at `on_a`
# within `radius_a` of it along the normal, and the second's, at `on_b` less
# `radius_b`.
def one_point(normal: vec3, on_a: vec3, radius_a: f32, on_b: vec3, radius_b: f32, depth: f32, id: u32): manifold {
var made := manifold{ normal = normal, count = 1 };
made.points[0] = contact{ point = ((on_a + normal * radius_a) + (on_b - normal * radius_b)) * 0.5, depth = depth, id = id };
return made;
}
# Two spheres or capsules, by their cores, each a segment, a sphere's of one
# place.
def cores(a1: vec3, a2: vec3, ra: f32, b1: vec3, b2: vec3, rb: f32, margin: f32): maybe<manifold> {
val reach := ra + rb;
val pair := nearest_of_segments(a1, a2, b1, b2);
val between := pair[1] - pair[0];
val distance := between.length;
return nothing{} if distance > reach + margin;
val da := a2 - a1;
val db := b2 - b1;
var normal := vec3::up;
if distance > tiny {
normal = between * (1 / distance);
} else {
# Their cores cross: apart along what's at right angles to both, or to
# either, from the first's middle toward the second's.
var across := da.cross(db);
if across.length_squared <= tiny {
across = da.length_squared > tiny ? perpendicular_to(da.normalized()) : db.length_squared > tiny ? perpendicular_to(db.normalized()) : vec3::up;
}
normal = across.normalized();
if normal.dot((b1 + b2) * 0.5 - (a1 + a2) * 0.5) < 0 {
normal = -normal;
}
}
# Two capsules lying along one another meet at the ends of what of the
# second lies beside the first.
val la := da.length_squared;
if la > tiny && db.length_squared > tiny && math::abs(da.normalized().dot(db.normalized())) > 0.99 {
val s1 := (b1 - a1).dot(da) / la;
val s2 := (b2 - a1).dot(da) / la;
var low: f32 = 0;
var high: f32 = 1;
if math::abs(s2 - s1) > tiny {
val u0 := -s1 / (s2 - s1);
val u1 := (1 - s1) / (s2 - s1);
low = math::max(0f, math::min(u0, u1));
high = math::min(1f, math::max(u0, u1));
}
if high - low > 1e-3 {
var made := manifold{ normal = normal };
val ends: f32[2] = [low, high];
for k in 0..2u {
val q := b1 + db * ends[k];
val p := nearest_on_segment(q, a1, a2);
val s := (q - p).dot(normal);
continue if s > reach + margin;
made.points[made.count] = contact{ point = ((p + normal * ra) + (q - normal * rb)) * 0.5, depth = reach - s, id = k as u32 };
made.count++;
}
return made if made.count == 2;
}
}
return one_point(normal, pair[0], ra, pair[1], rb, reach - distance, 0);
}
# A hull and a sphere or capsule, by its core, a segment, a sphere's of one
# place.
def hull_and_core(h: &hull, b1: vec3, b2: vec3, rb: f32, margin: f32): maybe<manifold> {
val point := (b2 - b1).length_squared <= tiny * tiny;
# Whether the core passes within the hull: the part of it within each
# face's side, as Cyrus and Beck clip a line.
val d := b2 - b1;
var low: f32 = 0;
var high: f32 = 1;
for f in 0..h.faces {
val out := h.normal(f).dot(b1) - h.offset(f);
val rate := h.normal(f).dot(d);
if math::abs(rate) <= tiny {
if out > 0 {
high = -1;
break;
}
continue;
}
val t := -out / rate;
if rate < 0 {
low = math::max(low, t);
} else {
high = math::min(high, t);
}
break if low > high;
}
return core_within(h, b1, b2, point, rb, margin) if low <= high;
# Apart: the nearest of the hull to either end, or of its edges to the
# segment.
var best := 1e30f;
var on_hull := b1;
var on_core := b1;
val ends: vec3[2] = [b1, b2];
for k in 0..(point ? 1u : 2u) {
val near := nearest_on_hull(h, ends[k]);
val d2 := (ends[k] - near).length_squared;
if d2 < best {
best = d2;
on_hull = near;
on_core = ends[k];
}
}
if !point {
for e in 0..h.edges {
val corners := h.edge(e);
val pair := nearest_of_segments(h.point(corners[0]), h.point(corners[1]), b1, b2);
val d2 := (pair[1] - pair[0]).length_squared;
if d2 < best {
best = d2;
on_hull = pair[0];
on_core = pair[1];
}
}
}
val distance := math::sqrt(best);
return nothing{} if distance > rb + margin;
return core_within(h, b1, b2, point, rb, margin) if distance <= tiny;
val normal := (on_core - on_hull) * (1 / distance);
if !point {
# Lying along a face, it meets it where it lies over it, at two points.
val face := most_facing(h, normal);
if h.normal(face).dot(normal) > 0.995 {
val along := face_contacts(h, face, b1, b2, rb, margin);
return along if along.count > 0;
}
}
return one_point(normal, on_hull, 0, on_core, rb, rb - distance, 0);
}
# A core passing within a hull: apart along the hull's face, or the axis at
# right angles to an edge of the hull and the segment, holding them furthest
# apart.
def core_within(h: &hull, b1: vec3, b2: vec3, point: bool, rb: f32, margin: f32): maybe<manifold> {
var face: u32 = 0;
var face_apart := -1e30f;
for f in 0..h.faces {
val n := h.normal(f);
val s := math::min(n.dot(b1), n.dot(b2)) - h.offset(f);
if s > face_apart {
face_apart = s;
face = f;
}
}
var edge: u32 = 0;
var edge_apart := -1e30f;
var axis := vec3::zero;
if !point {
val db := b2 - b1;
for e in 0..h.edges {
val corners := h.edge(e);
val ea := h.point(corners[0]);
var l := (h.point(corners[1]) - ea).cross(db);
continue if l.length_squared <= tiny;
l = l.normalized();
if l.dot(ea - h.center) < 0 {
l = -l;
}
val s := math::min(l.dot(b1), l.dot(b2)) - h.point(h.support(l)).dot(l);
if s > edge_apart {
edge_apart = s;
edge = e;
axis = l;
}
}
}
if better_edge(edge_apart, face_apart) {
val corners := h.edge(edge);
val pair := nearest_of_segments(h.point(corners[0]), h.point(corners[1]), b1, b2);
return one_point(axis, pair[0], 0, pair[1], rb, rb - edge_apart, 0x80000000 | edge);
}
val n := h.normal(face);
if !point {
val along := face_contacts(h, face, b1, b2, rb, margin);
return along if along.count > 0;
}
# The deepest end, pushed out by the face.
val q := n.dot(b1) <= n.dot(b2) ? b1 : b2;
val s := n.dot(q) - h.offset(face);
return one_point(n, q - n * s, 0, q, rb, rb - s, 0);
}
# The face whose normal is most along a direction.
def most_facing(h: &hull, direction: vec3): u32 {
var found: u32 = 0;
var most := -2f;
for f in 0..h.faces {
val d := h.normal(f).dot(direction);
if d > most {
most = d;
found = f;
}
}
return found;
}
# The hull's place nearest a place outside it: on a face it's in front of,
# where it lies over the face, else on one of the face's edges.
def nearest_on_hull(h: &hull, q: vec3): vec3 {
var best := 1e30f;
var found := q;
for f in 0..h.faces {
val n := h.normal(f);
val s := n.dot(q) - h.offset(f);
continue if s <= 0;
val on_plane := q - n * s;
if within_face(h, f, on_plane) {
if s * s < best {
best = s * s;
found = on_plane;
}
continue;
}
val size := h.face_size(f);
for k in 0..size {
val p := nearest_on_segment(q, h.point(h.corner(f, k)), h.point(h.corner(f, (k + 1) % size)));
val d2 := (q - p).length_squared;
if d2 < best {
best = d2;
found = p;
}
}
}
return found;
}
# Whether a place in a face's plane lies within its edges.
def within_face(h: &hull, f: u32, p: vec3): bool {
val n := h.normal(f);
val size := h.face_size(f);
for k in 0..size {
val a := h.point(h.corner(f, k));
val b := h.point(h.corner(f, (k + 1) % size));
return false if (b - a).cross(p - a).dot(n) < 0;
}
return true;
}
# A segment clipped to a hull's face, where it lies over it: each end left
# within reach of the face a point.
def face_contacts(h: &hull, face: u32, b1: vec3, b2: vec3, rb: f32, margin: f32): manifold {
val n := h.normal(face);
var ends: vec3[2] = [b1, b2];
var made := manifold{ normal = n };
val size := h.face_size(face);
for k in 0..size {
val a := h.point(h.corner(face, k));
val b := h.point(h.corner(face, (k + 1) % size));
val side := (b - a).cross(n);
return made if !clip_segment(&mut ends, side, side.dot(a));
}
val offset := h.offset(face);
for k in 0..2u {
val q := ends[k];
val s := n.dot(q) - offset;
continue if s > rb + margin;
made.points[made.count] = contact{ point = ((q - n * s) + (q - n * rb)) * 0.5, depth = rb - s, id = k as u32 };
made.count++;
}
return made;
}
# Clips a segment to the side of a plane where `normal.dot(p) <= offset`, as
# Sutherland and Hodgman clip: false where none of it is there.
def clip_segment(ends: &mut vec3[2], normal: vec3, offset: f32): bool {
val d0 := normal.dot(ends[0]) - offset;
val d1 := normal.dot(ends[1]) - offset;
return true if d0 <= 0 && d1 <= 0;
return false if d0 > 0 && d1 > 0;
val crossing := ends[0] + (ends[1] - ends[0]) * (d0 / (d0 - d1));
if d0 > 0 {
ends[0] = crossing;
} else {
ends[1] = crossing;
}
return true;
}
# Whether two edges' arcs on the sphere of directions cross, so the edge
# between faces `a` and `b` of one hull and that between `c` and `d` of the
# other, its normals turned around, make a face of their Minkowski
# difference, as Gregorius tests it: the only pairs of edges whose axis is a
# separating axis worth testing.
def minkowski_face(a: vec3, b: vec3, c: vec3, d: vec3): bool {
val bxa := b.cross(a);
val dxc := d.cross(c);
val cba := c.dot(bxa);
val dba := d.dot(bxa);
val adc := a.dot(dxc);
val bdc := b.dot(dxc);
return cba * dba < 0 && adc * bdc < 0 && cba * bdc > 0;
}
# Whether a separation is better than another by enough to be taken over it,
# so the same pair is met the same way from one step to the next: a face of
# the second hull's over the first's by a millimeter and 2 percent, and an
# edge's over a face's by a millimeter and 5, as an edge's point moves more as
# they turn.
def better(separation: f32, than: f32): bool {
return separation > than + 1e-3 + 0.02 * math::abs(than);
}
def better_edge(separation: f32, than: f32): bool {
return separation > than + 1e-3 + 0.05 * math::abs(than);
}
# Two hulls, the second placed in the first's places by `rel`.
def hulls(a: &hull, b: &hull, rel: &pose, margin: f32): maybe<manifold> {
val turn := mat3::rotation(rel.turn);
var bp: vec3[32];
var bn: vec3[60];
for i in 0..b.count {
bp[i] = rel.at + turn * b.point(i);
}
for f in 0..b.faces {
bn[f] = turn * b.normal(f);
}
val b_center := rel.at + turn * b.center;
# The faces of the first.
var face_a: u32 = 0;
var apart_a := -1e30f;
for f in 0..a.faces {
val n := a.normal(f);
var least := 1e30f;
for j in 0..b.count {
least = math::min(least, n.dot(bp[j]));
}
val s := least - a.offset(f);
if s > apart_a {
apart_a = s;
face_a = f;
}
}
return nothing{} if apart_a > margin;
# The faces of the second.
var face_b: u32 = 0;
var apart_b := -1e30f;
for f in 0..b.faces {
val n := bn[f];
val offset := n.dot(bp[b.corner(f, 0)]);
var least := 1e30f;
for i in 0..a.count {
least = math::min(least, n.dot(a.point(i)));
}
val s := least - offset;
if s > apart_b {
apart_b = s;
face_b = f;
}
}
return nothing{} if apart_b > margin;
# Pairs of edges, one of each.
val flat := a.is_flat || b.is_flat;
var edge_a: u32 = 0;
var edge_b: u32 = 0;
var apart_e := -1e30f;
var axis := vec3::zero;
for ea in 0..a.edges {
val ac := a.edge(ea);
val p1 := a.point(ac[0]);
val da := a.point(ac[1]) - p1;
val af := a.edge_faces(ea);
for eb in 0..b.edges {
# Only pairs whose arcs of the Gauss map cross make a face of the
# Minkowski difference, which is cheaper to ask than the axis is to find.
if !flat {
val bf := b.edge_faces(eb);
continue if !minkowski_face(a.normal(af[0]), a.normal(af[1]), -bn[bf[0]], -bn[bf[1]]);
}
val bc := b.edge(eb);
val q1 := bp[bc[0]];
val db := bp[bc[1]] - q1;
var l := da.cross(db);
val length := l.length;
continue if length <= 1e-4 * math::sqrt(da.length_squared * db.length_squared);
l = l * (1 / length);
var s: f32 = 0;
if flat {
# A flat hull's edges meet the other's anywhere, so each axis is
# tested by how far the hulls reach along it, either way.
var a_low := 1e30f;
var a_high := -1e30f;
for i in 0..a.count {
val x := l.dot(a.point(i));
a_low = math::min(a_low, x);
a_high = math::max(a_high, x);
}
var b_low := 1e30f;
var b_high := -1e30f;
for j in 0..b.count {
val x := l.dot(bp[j]);
b_low = math::min(b_low, x);
b_high = math::max(b_high, x);
}
s = b_low - a_high;
if a_low - b_high > s {
s = a_low - b_high;
l = -l;
}
} else {
if l.dot(p1 - a.center) < 0 {
l = -l;
}
s = l.dot(q1 - p1);
}
if s > apart_e {
apart_e = s;
edge_a = ea;
edge_b = eb;
axis = l;
}
}
}
return nothing{} if apart_e > margin;
val apart_face := math::max(apart_a, apart_b);
if better_edge(apart_e, apart_face) {
val ac := a.edge(edge_a);
val bc := b.edge(edge_b);
val pair := nearest_of_segments(a.point(ac[0]), a.point(ac[1]), bp[bc[0]], bp[bc[1]]);
return one_point(axis, pair[0], 0, pair[1], 0, -apart_e, 0x80000000 | (edge_a << 8) | edge_b);
}
return clipped(a, b, &bp, &bn, face_a, face_b, better(apart_b, apart_a), margin);
}
# The face of the other hull most against the reference face, clipped to the
# reference face's sides: each corner left within the margin of the reference
# face a point, as many as four kept.
def clipped(a: &hull, b: &hull, bp: &vec3[32], bn: &vec3[60], face_a: u32, face_b: u32, flip: bool, margin: f32): maybe<manifold> {
# The reference face's corners and normal, and the incident face's corners.
var reference: vec3[32];
var size: u32 = 0;
var n := vec3::zero;
var polygon: vec3[64];
var ids: u32[64];
var count: u32 = 0;
var incident: u32 = 0;
if !flip {
n = a.normal(face_a);
size = a.face_size(face_a);
for k in 0..size {
reference[k] = a.point(a.corner(face_a, k));
}
var least := 2f;
for f in 0..b.faces {
val d := bn[f].dot(n);
if d < least {
least = d;
incident = f;
}
}
count = b.face_size(incident);
for k in 0..count {
polygon[k] = bp[b.corner(incident, k)];
ids[k] = k;
}
} else {
n = bn[face_b];
size = b.face_size(face_b);
for k in 0..size {
reference[k] = bp[b.corner(face_b, k)];
}
var least := 2f;
for f in 0..a.faces {
val d := a.normal(f).dot(n);
if d < least {
least = d;
incident = f;
}
}
count = a.face_size(incident);
for k in 0..count {
polygon[k] = a.point(a.corner(incident, k));
ids[k] = k;
}
}
# The faces met, in the high bits of each point's id.
val flipped: u32 = flip ? 0x40000000 : 0;
val tag := flipped | ((flip ? face_b : face_a) << 22) | (incident << 16);
# Clipped by the plane through each edge of the reference face, at right
# angles to it.
var next: vec3[64];
var next_ids: u32[64];
for k in 0..size {
val from := reference[k];
val side := (reference[(k + 1) % size] - from).cross(n);
val offset := side.dot(from);
var made: u32 = 0;
for i in 0..count {
val p := polygon[i];
val q := polygon[(i + 1) % count];
val dp := side.dot(p) - offset;
val dq := side.dot(q) - offset;
if dp <= 0 && made < 64 {
next[made] = p;
next_ids[made] = ids[i];
made++;
}
if (dp <= 0) != (dq <= 0) && made < 64 {
next[made] = p + (q - p) * (dp / (dp - dq));
next_ids[made] = ((k + 1) << 8) | i;
made++;
}
}
count = made;
for i in 0..count {
polygon[i] = next[i];
ids[i] = next_ids[i];
}
break if count == 0;
}
# What's within the margin of the reference face, midway between it and
# the incident face.
val offset := n.dot(reference[0]);
var found: contact[64];
var kept: u32 = 0;
for i in 0..count {
val s := n.dot(polygon[i]) - offset;
continue if s > margin;
found[kept] = contact{ point = polygon[i] - n * (s * 0.5), depth = -s, id = tag | ids[i] };
kept++;
}
return nothing{} if kept == 0;
var made := manifold{ normal = flip ? -n : n };
if kept <= max_contacts {
for i in 0..kept {
made.points[i] = found[i];
}
made.count = kept;
return made;
}
return reduced(&found, kept, n, made);
}
# Four of many points, holding the most of the area they hold: the deepest,
# the one furthest from it, the one making the largest triangle of those, and
# the one adding the most to the triangle.
def reduced(found: &contact[64], count: u32, n: vec3, into: manifold): manifold {
var made := into;
var first: u32 = 0;
for i in 1..count {
if found[i].depth > found[first].depth {
first = i;
}
}
val p1 := found[first].point;
var second := first;
var best: f32 = -1;
for i in 0..count {
val d := (found[i].point - p1).length_squared;
if d > best {
best = d;
second = i;
}
}
val p2 := found[second].point;
var third := first;
var area: f32 = 0;
for i in 0..count {
val a := (p2 - p1).cross(found[i].point - p1).dot(n);
if math::abs(a) > math::abs(area) {
area = a;
third = i;
}
}
# Counterclockwise about the normal.
if area < 0 {
val swapped := second;
second = third;
third = swapped;
}
val q1 := found[first].point;
val q2 := found[second].point;
val q3 := found[third].point;
var fourth := first;
var added: f32 = 0;
for i in 0..count {
val q := found[i].point;
val a1 := (q1 - q).cross(q2 - q).dot(n);
val a2 := (q2 - q).cross(q3 - q).dot(n);
val a3 := (q3 - q).cross(q1 - q).dot(n);
val least := math::min(a1, math::min(a2, a3));
if least < added {
added = least;
fourth = i;
}
}
made.points[0] = found[first];
made.points[1] = found[second];
made.points[2] = found[third];
made.count = 3;
if fourth != first {
made.points[3] = found[fourth];
made.count = 4;
}
return made;
}