Initial Commit
This commit is contained in:
42 files changed
+7557
No files matched your search
@@ -0,0 +1,703 @@
|
||||
#! 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 {
|
||||
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 {
|
||||
val bf := b.edge_faces(eb);
|
||||
continue if !minkowski_face(a.normal(af[0]), a.normal(af[1]), -bn[bf[0]], -bn[bf[1]]);
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
#! Contains `hull`, a convex polyhedron: its corners; its faces, each a convex
|
||||
#! polygon of its corners, counterclockwise as it's seen from outside, its
|
||||
#! normal facing out; and its edges, each between two faces. It's made as a box,
|
||||
#! as a triangle, flat, with a face each way, or around places, as the least
|
||||
#! hull holding them, each of its faces as many of their triangles as lie in one
|
||||
#! plane.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics3d;
|
||||
|
||||
#! The most corners a hull has.
|
||||
pub const max_hull_points: u32 = 32;
|
||||
|
||||
# The most faces and edges a hull of so many corners has, as Euler's formula
|
||||
# bounds them: 2V - 4 faces and 3V - 6 edges, each edge a corner of two faces.
|
||||
const max_hull_faces: u32 = 60;
|
||||
const max_hull_edges: u32 = 90;
|
||||
|
||||
# Faces whose normals are nearer one another than this are one face.
|
||||
const coplanar: f32 = 0.9999;
|
||||
|
||||
#! A convex polyhedron, about the origin of its body, as plain data, so a shape
|
||||
#! holding one is copied whole.
|
||||
pub struct hull {
|
||||
var _count: u32;
|
||||
var _faces: u32;
|
||||
var _edges: u32;
|
||||
var _points: vec3[32];
|
||||
var _normals: vec3[60];
|
||||
var _first: u8[60]; # Of each face, where its corners begin in `_corners`.
|
||||
var _sizes: u8[60]; # Of each face, how many corners.
|
||||
var _corners: u8[180]; # Each face's corners, counterclockwise from outside.
|
||||
var _ends: u8[180]; # Each edge's two corners.
|
||||
var _sides: u8[180]; # Each edge's two faces.
|
||||
var _center: vec3;
|
||||
}
|
||||
|
||||
#! A box reaching so far each way from its middle, about a place, turned by a
|
||||
#! rotation.
|
||||
pub def hull::box(half: vec3, center: vec3 = vec3::zero, turn: quat = quat::identity): hull {
|
||||
var made := hull{ _count = 8, _faces = 6 };
|
||||
val m := mat3::rotation(turn);
|
||||
# Corner `i` is on the high side of x where bit 0 is set, of y where bit 1
|
||||
# is, and of z where bit 2 is.
|
||||
for i in 0..8u {
|
||||
val corner := vec3{ (i & 1) != 0 ? half.x : -half.x, (i & 2) != 0 ? half.y : -half.y, (i & 4) != 0 ? half.z : -half.z };
|
||||
made._points[i] = center + m * corner;
|
||||
}
|
||||
val loops: u8[24] = [1, 3, 7, 5, 0, 4, 6, 2, 2, 6, 7, 3, 0, 1, 5, 4, 4, 5, 7, 6, 0, 2, 3, 1];
|
||||
for i in 0..24u {
|
||||
made._corners[i] = loops[i];
|
||||
}
|
||||
for f in 0..6u {
|
||||
made._first[f] = (f * 4) as u8;
|
||||
made._sizes[f] = 4;
|
||||
}
|
||||
made.finish();
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A triangle of three places, flat: a face each way, the first facing where
|
||||
#! they turn counterclockwise, and three edges, each between the two faces.
|
||||
pub def hull::triangle(a: vec3, b: vec3, c: vec3): hull {
|
||||
var made := hull{ _count = 3, _faces = 2 };
|
||||
made._points[0] = a;
|
||||
made._points[1] = b;
|
||||
made._points[2] = c;
|
||||
val loops: u8[6] = [0, 1, 2, 0, 2, 1];
|
||||
for i in 0..6u {
|
||||
made._corners[i] = loops[i];
|
||||
}
|
||||
made._first[1] = 3;
|
||||
made._sizes[0] = 3;
|
||||
made._sizes[1] = 3;
|
||||
made.finish();
|
||||
return made;
|
||||
}
|
||||
|
||||
# A triangle of the hull being made, by its corners' indices among the places.
|
||||
struct building {
|
||||
var a: u32;
|
||||
var b: u32;
|
||||
var c: u32;
|
||||
var normal: vec3;
|
||||
var offset: f32;
|
||||
var alive: bool;
|
||||
}
|
||||
|
||||
def building_of(places: span<vec3>, a: u32, b: u32, c: u32): building {
|
||||
val normal := (places[b] - places[a]).cross(places[c] - places[a]).normalized();
|
||||
return building{ a = a, b = b, c = c, normal = normal, offset = normal.dot(places[a]), alive = true };
|
||||
}
|
||||
|
||||
# A place, and how far it is from the middle of the first four corners, by
|
||||
# which the furthest are put on first.
|
||||
struct by_reach {
|
||||
var reach: f32;
|
||||
var index: u32;
|
||||
}
|
||||
|
||||
def further(x: &by_reach, y: &by_reach): bool {
|
||||
return x.reach > y.reach;
|
||||
}
|
||||
|
||||
#! The least convex hull holding places: what's within it, or on its faces,
|
||||
#! left out. Nothing where the places hold no volume, or their hull has more
|
||||
#! than `max_hull_points` corners.
|
||||
pub def hull::of(places: span<vec3>): maybe<hull> {
|
||||
return nothing{} if places.length < 4;
|
||||
# How near a place is to a face to be taken as on it, of the places' size.
|
||||
var low := places[0];
|
||||
var high := places[0];
|
||||
for i in 1..places.length {
|
||||
low = low.min(places[i]);
|
||||
high = high.max(places[i]);
|
||||
}
|
||||
val reach := low.abs().max(high.abs());
|
||||
val near := (reach.x + reach.y + reach.z) * 4e-6 + tiny;
|
||||
|
||||
# The first four corners: the place furthest left, the one furthest from
|
||||
# it, the one furthest from the line of those, and the one furthest from
|
||||
# the plane of the three.
|
||||
var i0: u32 = 0;
|
||||
for i in 1..places.length {
|
||||
if places[i].x < places[i0 as u64].x {
|
||||
i0 = i as u32;
|
||||
}
|
||||
}
|
||||
var i1 := i0;
|
||||
var best: f32 = 0;
|
||||
for i in 0..places.length {
|
||||
val d := (places[i] - places[i0 as u64]).length;
|
||||
if d > best {
|
||||
best = d;
|
||||
i1 = i as u32;
|
||||
}
|
||||
}
|
||||
return nothing{} if best <= near;
|
||||
val along := (places[i1 as u64] - places[i0 as u64]).normalized();
|
||||
var i2 := i0;
|
||||
best = 0;
|
||||
for i in 0..places.length {
|
||||
val d := (places[i] - places[i0 as u64]).cross(along).length;
|
||||
if d > best {
|
||||
best = d;
|
||||
i2 = i as u32;
|
||||
}
|
||||
}
|
||||
return nothing{} if best <= near;
|
||||
val facing := (places[i1 as u64] - places[i0 as u64]).cross(places[i2 as u64] - places[i0 as u64]).normalized();
|
||||
var i3 := i0;
|
||||
best = 0;
|
||||
var side: f32 = 0;
|
||||
for i in 0..places.length {
|
||||
val d := facing.dot(places[i] - places[i0 as u64]);
|
||||
if math::abs(d) > best {
|
||||
best = math::abs(d);
|
||||
side = d;
|
||||
i3 = i as u32;
|
||||
}
|
||||
}
|
||||
return nothing{} if best <= near;
|
||||
|
||||
# The first face faces away from the fourth corner.
|
||||
var a := i0;
|
||||
var b := i1;
|
||||
var c := i2;
|
||||
if side > 0 {
|
||||
b = i2;
|
||||
c = i1;
|
||||
}
|
||||
var faces := vector::<building>::new();
|
||||
faces.append(building_of(places, a, b, c));
|
||||
faces.append(building_of(places, a, i3, b));
|
||||
faces.append(building_of(places, b, i3, c));
|
||||
faces.append(building_of(places, c, i3, a));
|
||||
|
||||
# The rest, the furthest from the middle first, each outside the hull so
|
||||
# far replacing the faces it sees with faces from their horizon to it.
|
||||
val middle := (places[i0 as u64] + places[i1 as u64] + places[i2 as u64] + places[i3 as u64]) * 0.25;
|
||||
var order := vector::<by_reach>::new();
|
||||
for i in 0..places.length {
|
||||
order.append(by_reach{ reach = (places[i] - middle).length_squared, index = i as u32 });
|
||||
}
|
||||
order.sort_by(further);
|
||||
var seen := vector::<u64>::new();
|
||||
for k in 0..order.length {
|
||||
val p := order[k].index;
|
||||
val place := places[p as u64];
|
||||
# The directed edges of the faces it sees.
|
||||
seen.clear();
|
||||
for f in 0..faces.length {
|
||||
continue if !faces[f].alive || faces[f].normal.dot(place) - faces[f].offset <= near;
|
||||
faces[f].alive = false;
|
||||
seen.append(edge_key(faces[f].a, faces[f].b));
|
||||
seen.append(edge_key(faces[f].b, faces[f].c));
|
||||
seen.append(edge_key(faces[f].c, faces[f].a));
|
||||
}
|
||||
continue if seen.is_empty;
|
||||
# An edge seen one way only is on the horizon.
|
||||
val count := seen.length;
|
||||
for e in 0..count {
|
||||
val key := seen[e];
|
||||
val from := (key >> 32) as u32;
|
||||
val to := (key & 0xFFFFFFFF) as u32;
|
||||
var shared := false;
|
||||
for o in 0..count {
|
||||
if seen[o] == edge_key(to, from) {
|
||||
shared = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !shared {
|
||||
faces.append(building_of(places, from, to, p));
|
||||
}
|
||||
}
|
||||
}
|
||||
return hull::of_triangles(places, faces.view());
|
||||
}
|
||||
|
||||
def edge_key(from: u32, to: u32): u64 {
|
||||
return ((from as u64) << 32) | to as u64;
|
||||
}
|
||||
|
||||
# The hull of the triangles left: those in one plane made one face, the
|
||||
# corners they use numbered from 0.
|
||||
def hull::of_triangles(places: span<vec3>, faces: span<building>): maybe<hull> {
|
||||
# Which triangle lies across each directed edge.
|
||||
var across := dict::<u64, u64>::new();
|
||||
var alive := vector::<u64>::new();
|
||||
for f in 0..faces.length {
|
||||
continue if !faces[f].alive;
|
||||
alive.append(f);
|
||||
across.set(edge_key(faces[f].a, faces[f].b), f);
|
||||
across.set(edge_key(faces[f].b, faces[f].c), f);
|
||||
across.set(edge_key(faces[f].c, faces[f].a), f);
|
||||
}
|
||||
# Each triangle's face: those reached from it across edges, facing as it
|
||||
# does.
|
||||
var group := vector::<i64>::new();
|
||||
for f in 0..faces.length {
|
||||
group.append(-1);
|
||||
}
|
||||
var made := hull{};
|
||||
var numbered := dict::<u32, u32>::new();
|
||||
var corners: u32 = 0;
|
||||
var pending := vector::<u64>::new();
|
||||
var edges := vector::<u64>::new();
|
||||
var ring := dict::<u32, u32>::new();
|
||||
for k in 0..alive.length {
|
||||
val seed := alive[k];
|
||||
# A triangle of no area takes the face of one beside it.
|
||||
continue if group[seed] >= 0 || faces[seed].normal.length_squared < 0.25;
|
||||
return nothing{} if made._faces >= max_hull_faces;
|
||||
val face := made._faces;
|
||||
val normal := faces[seed].normal;
|
||||
group[seed] = face as i64;
|
||||
pending.clear();
|
||||
pending.append(seed);
|
||||
edges.clear();
|
||||
while !pending.is_empty {
|
||||
val t := pending[pending.length - 1];
|
||||
pending.truncate();
|
||||
val keys: u64[3] = [edge_key(faces[t].a, faces[t].b), edge_key(faces[t].b, faces[t].c), edge_key(faces[t].c, faces[t].a)];
|
||||
for e in 0..3u {
|
||||
edges.append(keys[e]);
|
||||
val reverse := edge_key((keys[e] & 0xFFFFFFFF) as u32, (keys[e] >> 32) as u32);
|
||||
if across.get(&reverse) is some(&other) {
|
||||
val o: u64 = other;
|
||||
if group[o] < 0 && (faces[o].normal.dot(normal) > coplanar || faces[o].normal.length_squared < 0.25) {
|
||||
group[o] = face as i64;
|
||||
pending.append(o);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
# The face's boundary: its triangles' edges whose reverse isn't among
|
||||
# them, walked from one to the next.
|
||||
ring.clear();
|
||||
var start: u32 = 0;
|
||||
var length: u32 = 0;
|
||||
for e in 0..edges.length {
|
||||
val from := (edges[e] >> 32) as u32;
|
||||
val to := (edges[e] & 0xFFFFFFFF) as u32;
|
||||
var inner := false;
|
||||
for o in 0..edges.length {
|
||||
if edges[o] == edge_key(to, from) {
|
||||
inner = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !inner {
|
||||
ring.set(from, to);
|
||||
start = from;
|
||||
length++;
|
||||
}
|
||||
}
|
||||
val first := made.corner_total();
|
||||
return nothing{} if first + length > max_hull_edges * 2;
|
||||
var at := start;
|
||||
var walked: u32 = 0;
|
||||
var newell := vec3::zero;
|
||||
while walked < length {
|
||||
if numbered.get(&at) is none {
|
||||
return nothing{} if corners >= max_hull_points;
|
||||
made._points[corners] = places[at as u64];
|
||||
numbered.set(at, corners);
|
||||
corners++;
|
||||
}
|
||||
if numbered.get(&at) is some(&n) {
|
||||
val number: u32 = n;
|
||||
made._corners[first + walked] = number as u8;
|
||||
}
|
||||
var next := at;
|
||||
if ring.get(&at) is some(&n) {
|
||||
next = n;
|
||||
} else {
|
||||
return nothing{};
|
||||
}
|
||||
newell = newell + places[at as u64].cross(places[next as u64]);
|
||||
at = next;
|
||||
walked++;
|
||||
break if at == start;
|
||||
}
|
||||
return nothing{} if walked != length || walked < 3;
|
||||
made._first[face] = first as u8;
|
||||
made._sizes[face] = walked as u8;
|
||||
made._normals[face] = newell.normalized();
|
||||
made._faces++;
|
||||
}
|
||||
made._count = corners;
|
||||
return nothing{} if !made.find_edges();
|
||||
made.find_center();
|
||||
return made;
|
||||
}
|
||||
|
||||
# How many corners its faces have in all.
|
||||
def hull::corner_total(&this): u32 {
|
||||
var total: u32 = 0;
|
||||
for f in 0..this._faces {
|
||||
total += this._sizes[f] as u32;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
# Finds its normals, edges, and middle, of its corners and faces.
|
||||
def hull::finish(&mut this): void {
|
||||
for f in 0..this._faces {
|
||||
var newell := vec3::zero;
|
||||
for k in 0..this.face_size(f) {
|
||||
newell = newell + this.point(this.corner(f, k)).cross(this.point(this.corner(f, (k + 1) % this.face_size(f))));
|
||||
}
|
||||
this._normals[f] = newell.normalized();
|
||||
}
|
||||
_ = this.find_edges();
|
||||
this.find_center();
|
||||
}
|
||||
|
||||
# Finds its edges, each once, and the two faces either side, of its faces'
|
||||
# corners: an edge from a lesser corner to a greater in one face, and back in
|
||||
# the other. Gives false where one isn't, as a hull with a hole.
|
||||
def hull::find_edges(&mut this): bool {
|
||||
this._edges = 0;
|
||||
for f in 0..this._faces {
|
||||
val size := this.face_size(f);
|
||||
for k in 0..size {
|
||||
val from := this.corner(f, k);
|
||||
val to := this.corner(f, (k + 1) % size);
|
||||
continue if from > to;
|
||||
return false if this._edges >= max_hull_edges;
|
||||
val e := this._edges;
|
||||
this._ends[e * 2] = from as u8;
|
||||
this._ends[e * 2 + 1] = to as u8;
|
||||
this._sides[e * 2] = f as u8;
|
||||
this._sides[e * 2 + 1] = 0xFF;
|
||||
this._edges++;
|
||||
}
|
||||
}
|
||||
for f in 0..this._faces {
|
||||
val size := this.face_size(f);
|
||||
for k in 0..size {
|
||||
val from := this.corner(f, k);
|
||||
val to := this.corner(f, (k + 1) % size);
|
||||
continue if from < to;
|
||||
for e in 0..this._edges {
|
||||
if this._ends[e * 2] as u32 == to && this._ends[e * 2 + 1] as u32 == from {
|
||||
this._sides[e * 2 + 1] = f as u8;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for e in 0..this._edges {
|
||||
return false if this._sides[e * 2 + 1] == 0xFF;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
def hull::find_center(&mut this): void {
|
||||
var sum := vec3::zero;
|
||||
for i in 0..this._count {
|
||||
sum = sum + this._points[i];
|
||||
}
|
||||
this._center = sum * (1 / this._count as f32);
|
||||
}
|
||||
|
||||
#! How many corners it has.
|
||||
pub val hull::count: u32 {
|
||||
get => this._count;
|
||||
}
|
||||
|
||||
#! A corner.
|
||||
pub def hull::point(&this, i: u32): vec3 {
|
||||
return this._points[i];
|
||||
}
|
||||
|
||||
#! How many faces it has.
|
||||
pub val hull::faces: u32 {
|
||||
get => this._faces;
|
||||
}
|
||||
|
||||
#! A face's normal, facing out.
|
||||
pub def hull::normal(&this, face: u32): vec3 {
|
||||
return this._normals[face];
|
||||
}
|
||||
|
||||
#! How many corners a face has.
|
||||
pub def hull::face_size(&this, face: u32): u32 {
|
||||
return this._sizes[face] as u32;
|
||||
}
|
||||
|
||||
#! Which corner is a face's `k`th, counterclockwise from outside.
|
||||
pub def hull::corner(&this, face: u32, k: u32): u32 {
|
||||
return this._corners[this._first[face] as u32 + k] as u32;
|
||||
}
|
||||
|
||||
#! How far its plane is along a face's normal from the origin.
|
||||
pub def hull::offset(&this, face: u32): f32 {
|
||||
return this._normals[face].dot(this.point(this.corner(face, 0)));
|
||||
}
|
||||
|
||||
#! How many edges it has.
|
||||
pub val hull::edges: u32 {
|
||||
get => this._edges;
|
||||
}
|
||||
|
||||
#! An edge's corners, the lesser first.
|
||||
pub def hull::edge(&this, e: u32): u32[2] {
|
||||
return [this._ends[e * 2] as u32, this._ends[e * 2 + 1] as u32];
|
||||
}
|
||||
|
||||
#! The faces either side of an edge.
|
||||
pub def hull::edge_faces(&this, e: u32): u32[2] {
|
||||
return [this._sides[e * 2] as u32, this._sides[e * 2 + 1] as u32];
|
||||
}
|
||||
|
||||
#! The middle of its corners, which is within it.
|
||||
pub val hull::center: vec3 {
|
||||
get => this._center;
|
||||
}
|
||||
|
||||
#! Whether it's flat, of two faces, as a triangle is.
|
||||
pub val hull::is_flat: bool {
|
||||
get => this._faces == 2;
|
||||
}
|
||||
|
||||
#! The corner furthest along a direction.
|
||||
pub def hull::support(&this, direction: vec3): u32 {
|
||||
var found: u32 = 0;
|
||||
var most := this._points[0].dot(direction);
|
||||
for i in 1..this._count {
|
||||
val d := this._points[i].dot(direction);
|
||||
if d > most {
|
||||
most = d;
|
||||
found = i;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
#! The hull scaled along each axis, as a transform scales what it holds: its
|
||||
#! normals turned as the faces they're of are.
|
||||
pub def hull::scaled(&this, by: vec3): hull {
|
||||
var made: hull = this;
|
||||
for i in 0..this._count {
|
||||
made._points[i] = this._points[i] * by;
|
||||
}
|
||||
for f in 0..this._faces {
|
||||
made._normals[f] = (this._normals[f] / by).normalized();
|
||||
}
|
||||
made._center = this._center * by;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The hull moved and turned as a pose places it.
|
||||
pub def hull::moved(&this, by: pose): hull {
|
||||
var made: hull = this;
|
||||
val m := mat3::rotation(by.turn);
|
||||
for i in 0..this._count {
|
||||
made._points[i] = by.at + m * this._points[i];
|
||||
}
|
||||
for f in 0..this._faces {
|
||||
made._normals[f] = m * this._normals[f];
|
||||
}
|
||||
made._center = by.at + m * this._center;
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
#! Contains `triangle_mesh`, the triangles of a surface, as a level's ground and
|
||||
#! walls are: kept in a tree of their boxes, and met a triangle at a time by
|
||||
#! shapes and rays.
|
||||
#!
|
||||
#! A shape meeting a triangle by an edge or a corner is pushed out as the
|
||||
#! triangle's face pushes it, where that edge is one two triangles share flat,
|
||||
#! or hollow, as a floor's seams and a room's corners are, as Jolt's active
|
||||
#! edges keep: so a body slides along a floor of many triangles as along one,
|
||||
#! never caught on the seams between them. An edge two triangles share at a
|
||||
#! ridge, turning more than 5 degrees, and an edge of one triangle alone, push
|
||||
#! as they meet.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import malunal::geometry;
|
||||
import malunal::linear;
|
||||
module malunal::physics3d;
|
||||
|
||||
# Two triangles sharing an edge turning less than this, the cosine of 5
|
||||
# degrees, are as one.
|
||||
const ridge: f32 = 0.9962;
|
||||
|
||||
#! The triangles of a surface, of places of its own, as a pose places it.
|
||||
pub struct triangle_mesh {
|
||||
var _points: vector<vec3>;
|
||||
var _indices: vector<u32>;
|
||||
var _normals: vector<vec3>;
|
||||
var _active: vector<u8>; # Of each triangle, bit `k` where edge `k`, from corner `k` to the next, pushes as it meets.
|
||||
var _tree: aabb_tree;
|
||||
}
|
||||
|
||||
#! Where a ray met a mesh: how far along it, where, which way the triangle it
|
||||
#! met faces, toward the ray's beginning, and which triangle.
|
||||
pub struct mesh_hit {
|
||||
pub var distance: f32;
|
||||
pub var point: vec3;
|
||||
pub var normal: vec3;
|
||||
pub var triangle: u32;
|
||||
}
|
||||
|
||||
# An edge, and the triangles using it, each as its index times 3 and the
|
||||
# edge's place in it.
|
||||
struct edge_use {
|
||||
var first: u64;
|
||||
var second: u64;
|
||||
var count: u32;
|
||||
}
|
||||
|
||||
#! The mesh of places and triangles of them, three indices each,
|
||||
#! counterclockwise as their front is seen: those of no area, or of an index
|
||||
#! past the places, left out.
|
||||
pub def triangle_mesh::new(points: span<vec3>, indices: span<u32>): triangle_mesh {
|
||||
var made := triangle_mesh{
|
||||
_points = vector::<vec3>::new(), _indices = vector::<u32>::new(), _normals = vector::<vec3>::new(),
|
||||
_active = vector::<u8>::new(), _tree = aabb_tree::new(0),
|
||||
};
|
||||
made._points.extend(points);
|
||||
var t: u64 = 0;
|
||||
while t + 2 < indices.length {
|
||||
val a := indices[t];
|
||||
val b := indices[t + 1];
|
||||
val c := indices[t + 2];
|
||||
t += 3;
|
||||
continue if a as u64 >= points.length || b as u64 >= points.length || c as u64 >= points.length;
|
||||
val facing := (points[b as u64] - points[a as u64]).cross(points[c as u64] - points[a as u64]);
|
||||
continue if facing.length_squared <= tiny * tiny;
|
||||
made._indices.append(a);
|
||||
made._indices.append(b);
|
||||
made._indices.append(c);
|
||||
made._normals.append(facing.normalized());
|
||||
made._active.append(7);
|
||||
}
|
||||
made.find_edges();
|
||||
for i in 0..made._normals.length {
|
||||
val c := made.triangle(i as u32);
|
||||
_ = made._tree.insert(bounds{ c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2]) }, i);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Finds which edges push as they meet: those two triangles share, turning
|
||||
# less than 5 degrees or hollow, don't.
|
||||
def triangle_mesh::find_edges(&mut this): void {
|
||||
var uses := vector::<edge_use>::new();
|
||||
var found := dict::<u64, u64>::new();
|
||||
for t in 0..this._normals.length {
|
||||
for k in 0..3u {
|
||||
val from := this._indices[t * 3 + k];
|
||||
val to := this._indices[t * 3 + (k + 1) % 3];
|
||||
val key := ((math::min(from, to) as u64) << 32) | math::max(from, to) as u64;
|
||||
if found.get(&key) is some(&at) {
|
||||
val index: u64 = at;
|
||||
if uses[index].count == 1 {
|
||||
uses[index].second = t * 3 + k;
|
||||
}
|
||||
uses[index].count++;
|
||||
} else {
|
||||
found.set(key, uses.length);
|
||||
uses.append(edge_use{ first = t * 3 + k, count = 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in 0..uses.length {
|
||||
continue if uses[i].count != 2;
|
||||
val t1 := uses[i].first / 3;
|
||||
val k1 := uses[i].first % 3;
|
||||
val t2 := uses[i].second / 3;
|
||||
val k2 := uses[i].second % 3;
|
||||
val n1 := this._normals[t1];
|
||||
val n2 := this._normals[t2];
|
||||
# The corner of the second triangle off the edge, below the first's plane
|
||||
# where the edge is a ridge.
|
||||
val off := this._points[this._indices[t2 * 3 + (k2 + 2) % 3] as u64];
|
||||
val on := this._points[this._indices[t1 * 3 + k1] as u64];
|
||||
val ridged := n1.dot(off - on) < 0 && n1.dot(n2) < ridge;
|
||||
continue if ridged;
|
||||
this._active[t1] = without_bit(this._active[t1], k1);
|
||||
this._active[t2] = without_bit(this._active[t2], k2);
|
||||
}
|
||||
}
|
||||
|
||||
# Bits of three edges, but one.
|
||||
def without_bit(bits: u8, k: u64): u8 {
|
||||
val bit: u32 = 1;
|
||||
return ((bits as u32) & (7 - (bit << k as u32))) as u8;
|
||||
}
|
||||
|
||||
#! How many triangles it has.
|
||||
pub val triangle_mesh::length: u64 {
|
||||
get => this._normals.length;
|
||||
}
|
||||
|
||||
#! A triangle's corners.
|
||||
pub def triangle_mesh::triangle(&this, t: u32): vec3[3] {
|
||||
val at := t as u64 * 3;
|
||||
return [
|
||||
this._points[this._indices[at] as u64], this._points[this._indices[at + 1] as u64], this._points[this._indices[at + 2] as u64],
|
||||
];
|
||||
}
|
||||
|
||||
#! The way a triangle's front faces.
|
||||
pub def triangle_mesh::normal(&this, t: u32): vec3 {
|
||||
return this._normals[t as u64];
|
||||
}
|
||||
|
||||
#! Whether a triangle's edge `k`, from its corner `k` to the next, pushes as it
|
||||
#! meets a shape, rather than as the triangle's face.
|
||||
pub def triangle_mesh::is_active(&this, t: u32, k: u32): bool {
|
||||
return (this._active[t as u64] & (1 << k) as u8) != 0;
|
||||
}
|
||||
|
||||
#! The box holding it, of its own places.
|
||||
pub def triangle_mesh::bounds(&this): bounds {
|
||||
var made := bounds::empty;
|
||||
for i in 0..this._points.length {
|
||||
made = made.including(this._points[i]);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Visits the manifold of a shape against each triangle it meets, as
|
||||
#! `visit(triangle, m)`, until it gives false: `at` places the mesh, and `at_s`
|
||||
#! the shape, and each manifold's normal is from the triangle toward the shape,
|
||||
#! in space. Within a `margin`, as `collide` gives them, triangles apart are
|
||||
#! visited too.
|
||||
pub def triangle_mesh::collide<F>(&this, at: pose, s: &shape, at_s: pose, margin: f32, visit: F): void
|
||||
where F: invokable<def(u32, manifold): bool> {
|
||||
val local := at.unapply_pose(at_s);
|
||||
this._tree.query(grown(s.bounds(local), margin), def(leaf: u32, data: u64): bool {
|
||||
val c := this.triangle(data as u32);
|
||||
val face := shape::of_hull(hull::triangle(c[0], c[1], c[2]));
|
||||
val found := collide(&face, pose::identity, s, local, margin) else { return true; };
|
||||
return visit(data as u32, placed(this.faced(data, found, s.radius), &at));
|
||||
});
|
||||
}
|
||||
|
||||
#! Whether a shape meets any triangle, `at` placing the mesh and `at_s` the
|
||||
#! shape.
|
||||
pub def triangle_mesh::overlaps(&this, at: pose, s: &shape, at_s: pose): bool {
|
||||
var met := false;
|
||||
this.collide(at, s, at_s, 0, def(t: u32, m: manifold): bool {
|
||||
met = true;
|
||||
return false;
|
||||
});
|
||||
return met;
|
||||
}
|
||||
|
||||
# A manifold of a triangle, as its face pushes where it met an edge, or a
|
||||
# corner, of the triangle that doesn't push: its normal the face's, and each
|
||||
# point as deep below the face's plane as the shape is there, of a radius
|
||||
# around its core.
|
||||
def triangle_mesh::faced(&this, t: u64, met: manifold, radius: f32): manifold {
|
||||
val n := this._normals[t];
|
||||
val along := met.normal.dot(n);
|
||||
return met if math::abs(along) > 0.9998 || this._active[t] == 7;
|
||||
var deepest: u32 = 0;
|
||||
for i in 1..met.count {
|
||||
if met.points[i].depth > met.points[deepest].depth {
|
||||
deepest = i;
|
||||
}
|
||||
}
|
||||
# Where the deepest point is on the triangle: half its depth along the
|
||||
# normal from midway.
|
||||
val c := this.triangle(t as u32);
|
||||
val on := met.points[deepest].point + met.normal * (met.points[deepest].depth * 0.5);
|
||||
val region := region_of(on, c[0], c[1], c[2]);
|
||||
# Within the face, or by a corner or edge that pushes, it pushes as it met.
|
||||
return met if region == 6;
|
||||
if region >= 3 {
|
||||
return met if this.is_active(t as u32, region - 3);
|
||||
} else if this.is_active(t as u32, region) || this.is_active(t as u32, (region + 2) % 3) {
|
||||
return met;
|
||||
}
|
||||
# Each point's place on the shape's surface, half its depth back along the
|
||||
# normal, and its core within; then the shape's deepest there along the
|
||||
# face's normal.
|
||||
val facing := along >= 0 ? n : -n;
|
||||
var made := met;
|
||||
made.normal = facing;
|
||||
for i in 0..met.count {
|
||||
val surface := met.points[i].point - met.normal * (met.points[i].depth * 0.5);
|
||||
val deepest := surface + met.normal * radius - facing * radius;
|
||||
val depth := facing.dot(c[0] - deepest);
|
||||
made.points[i].point = deepest + facing * (depth * 0.5);
|
||||
made.points[i].depth = depth;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Which part of a triangle a place on it is on, within a ten-thousandth of
|
||||
# its longest edge: a corner, 0 to 2; an edge, 3 to 5, of edge `k` from corner
|
||||
# `k` to the next; or within its face, 6.
|
||||
def region_of(p: vec3, a: vec3, b: vec3, c: vec3): u32 {
|
||||
val corners: vec3[3] = [a, b, c];
|
||||
val longest := math::max((b - a).length, math::max((c - b).length, (a - c).length));
|
||||
val near := longest * 1e-4 + tiny;
|
||||
for k in 0..3u {
|
||||
return k as u32 if (p - corners[k]).length <= near;
|
||||
}
|
||||
for k in 0..3u {
|
||||
return (3 + k) as u32 if (p - nearest_on_segment(p, corners[k], corners[(k + 1) % 3])).length <= near;
|
||||
}
|
||||
return 6;
|
||||
}
|
||||
|
||||
#! Where a ray first meets a triangle, `at` placing the mesh: from a place,
|
||||
#! along a direction of length 1, as far as `reach`, from either side.
|
||||
pub def triangle_mesh::ray_cast(&this, at: pose, origin: vec3, direction: vec3, reach: f32): maybe<mesh_hit> {
|
||||
val o := at.unapply(origin);
|
||||
val d := at.unrotate(direction);
|
||||
var best: maybe<mesh_hit> = nothing{};
|
||||
this._tree.ray_cast(o, d, reach, def(leaf: u32, data: u64, so_far: f32): f32 {
|
||||
val c := this.triangle(data as u32);
|
||||
val t := ray_triangle(o, d, c[0], c[1], c[2]) else { return so_far; };
|
||||
return so_far if t > so_far;
|
||||
val n := this._normals[data];
|
||||
best = mesh_hit{ distance = t, point = at.apply(o + d * t), normal = at.rotate(n.dot(d) <= 0 ? n : -n), triangle = data as u32 };
|
||||
return math::max(t, tiny);
|
||||
});
|
||||
return best;
|
||||
}
|
||||
|
||||
# How far along a ray it meets a triangle, from either side, as Möller and
|
||||
# Trumbore find it.
|
||||
def ray_triangle(o: vec3, d: vec3, a: vec3, b: vec3, c: vec3): maybe<f32> {
|
||||
val e1 := b - a;
|
||||
val e2 := c - a;
|
||||
val p := d.cross(e2);
|
||||
val det := e1.dot(p);
|
||||
return nothing{} if math::abs(det) < 1e-12;
|
||||
val inverse := 1 / det;
|
||||
val s := o - a;
|
||||
val u := s.dot(p) * inverse;
|
||||
return nothing{} if u < 0 || u > 1;
|
||||
val q := s.cross(e1);
|
||||
val v := d.dot(q) * inverse;
|
||||
return nothing{} if v < 0 || u + v > 1;
|
||||
val t := e2.dot(q) * inverse;
|
||||
return nothing{} if t < 0;
|
||||
return t;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
#! 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();
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
#! Contains `pose`, where a body is in space and which way it's turned, which
|
||||
#! places its shapes.
|
||||
|
||||
import std::serial;
|
||||
import malunal::linear;
|
||||
module malunal::physics3d;
|
||||
|
||||
#! Where a body is in space, and which way it's turned: what a place of its own,
|
||||
#! as its shapes' corners are, is in space.
|
||||
@serial
|
||||
pub struct pose {
|
||||
@serial pub var at: vec3;
|
||||
@serial pub var turn := quat::identity;
|
||||
}
|
||||
|
||||
#! At the origin, unturned.
|
||||
pub val pose::identity := pose{};
|
||||
|
||||
#! A pose at a place, turned by a rotation.
|
||||
pub def pose::of(at: vec3, turn: quat = quat::identity): pose {
|
||||
return pose{ at = at, turn = turn };
|
||||
}
|
||||
|
||||
pub def pose::equals(&this, other: &pose): bool {
|
||||
return this.at == other.at && this.turn == other.turn;
|
||||
}
|
||||
|
||||
#! Where a place of the body's own is in space.
|
||||
pub def pose::apply(&this, local: vec3): vec3 {
|
||||
return this.at + this.turn * local;
|
||||
}
|
||||
|
||||
#! Where a place of space is in the body's own.
|
||||
pub def pose::unapply(&this, place: vec3): vec3 {
|
||||
return this.turn.inverse() * (place - this.at);
|
||||
}
|
||||
|
||||
#! A direction of the body's own, turned as it's turned.
|
||||
pub def pose::rotate(&this, direction: vec3): vec3 {
|
||||
return this.turn * direction;
|
||||
}
|
||||
|
||||
#! A direction of space, as the body's own.
|
||||
pub def pose::unrotate(&this, direction: vec3): vec3 {
|
||||
return this.turn.inverse() * direction;
|
||||
}
|
||||
|
||||
#! It after another: the pose of what's placed by `other` within what this
|
||||
#! places.
|
||||
pub def pose::mul(&this, other: &pose): pose {
|
||||
return pose{ at = this.apply(other.at), turn = (this.turn * other.turn).normalized() };
|
||||
}
|
||||
|
||||
#! The pose undoing it: a place it puts somewhere, put back.
|
||||
pub def pose::inverse(&this): pose {
|
||||
val back := this.turn.inverse();
|
||||
return pose{ at = back * -this.at, turn = back };
|
||||
}
|
||||
|
||||
#! Another pose of space, as one within what this places, of its own places:
|
||||
#! what `this * found` is `other` of.
|
||||
pub def pose::unapply_pose(&this, other: pose): pose {
|
||||
val back := this.turn.inverse();
|
||||
return pose{ at = back * (other.at - this.at), turn = (back * other.turn).normalized() };
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
#! Contains `shape`: a sphere, a capsule, or a convex hull, about the origin of
|
||||
#! its body; the box holding it where a pose places it; whether it holds a
|
||||
#! place; and where a ray first meets it.
|
||||
|
||||
import std::math;
|
||||
import malunal::geometry;
|
||||
import malunal::linear;
|
||||
module malunal::physics3d;
|
||||
|
||||
#! What a shape is.
|
||||
pub enum shape_kind: u8 {
|
||||
#! The places within its radius of its middle.
|
||||
sphere,
|
||||
#! The places within its radius of a segment, between its two ends, as a
|
||||
#! pill.
|
||||
capsule,
|
||||
#! A convex polyhedron, as a box.
|
||||
hull,
|
||||
}
|
||||
|
||||
#! A shape of a body, about the body's origin, as a pose places it: a sphere,
|
||||
#! a capsule, or a convex hull. A sphere is its middle and a radius around it,
|
||||
#! a capsule its two ends and a radius around the segment between them, and a
|
||||
#! hull its corners and faces.
|
||||
pub struct shape {
|
||||
var _kind: shape_kind;
|
||||
var _radius: f32;
|
||||
var _a: vec3;
|
||||
var _b: vec3;
|
||||
var _hull: hull;
|
||||
}
|
||||
|
||||
#! Where a ray met a shape: how far along it, where, and which way the shape
|
||||
#! faces there.
|
||||
pub struct ray_hit {
|
||||
pub var distance: f32;
|
||||
pub var point: vec3;
|
||||
pub var normal: vec3;
|
||||
}
|
||||
|
||||
#! A sphere of a radius, about a middle, the body's origin at first.
|
||||
pub def shape::sphere(radius: f32, center: vec3 = vec3::zero): shape {
|
||||
return shape{ _kind = shape_kind::sphere, _radius = radius, _a = center, _b = center };
|
||||
}
|
||||
|
||||
#! A capsule of a radius about the segment between two places: a sphere of the
|
||||
#! radius, where they're one place.
|
||||
pub def shape::capsule(a: vec3, b: vec3, radius: f32): shape {
|
||||
return shape::sphere(radius, a) if (b - a).length_squared <= tiny * tiny;
|
||||
return shape{ _kind = shape_kind::capsule, _radius = radius, _a = a, _b = b };
|
||||
}
|
||||
|
||||
#! A capsule standing up, along y, as a character's body: so wide and so high
|
||||
#! in all, its ends round, about a middle. Narrower than it's high, or a
|
||||
#! sphere.
|
||||
pub def shape::pill(width: f32, height: f32, center: vec3 = vec3::zero): shape {
|
||||
val radius := width / 2;
|
||||
val reach := math::max(height / 2 - radius, 0f);
|
||||
return shape::capsule(center - vec3{ 0, reach, 0 }, center + vec3{ 0, reach, 0 }, radius);
|
||||
}
|
||||
|
||||
#! A box reaching so far each way from its middle, about a place, turned by a
|
||||
#! rotation.
|
||||
pub def shape::box(half: vec3, center: vec3 = vec3::zero, turn: quat = quat::identity): shape {
|
||||
return shape::of_hull(hull::box(half, center, turn));
|
||||
}
|
||||
|
||||
#! The convex hull around places, as `hull::of` makes it: nothing where they
|
||||
#! hold no volume, or their hull has too many corners.
|
||||
pub def shape::hull_of(places: span<vec3>): maybe<shape> {
|
||||
if hull::of(places) is some(made) {
|
||||
return shape::of_hull(made);
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
#! A shape of a hull.
|
||||
pub def shape::of_hull(h: hull): shape {
|
||||
return shape{ _kind = shape_kind::hull, _a = h.center, _b = h.center, _hull = h };
|
||||
}
|
||||
|
||||
pub val shape::kind: shape_kind {
|
||||
get => this._kind;
|
||||
}
|
||||
|
||||
#! How far around its middle or segment it reaches: a sphere's or a capsule's
|
||||
#! radius, and none of a hull.
|
||||
pub val shape::radius: f32 {
|
||||
get => this._radius;
|
||||
}
|
||||
|
||||
#! A sphere's middle, or a capsule's first end.
|
||||
pub val shape::a: vec3 {
|
||||
get => this._a;
|
||||
}
|
||||
|
||||
#! A capsule's second end, or a sphere's middle.
|
||||
pub val shape::b: vec3 {
|
||||
get => this._b;
|
||||
}
|
||||
|
||||
#! A hull's corners and faces.
|
||||
pub def shape::as_hull(&this): &hull {
|
||||
return &this._hull;
|
||||
}
|
||||
|
||||
#! The box holding it, where a pose places it.
|
||||
pub def shape::bounds(&this, at: pose): bounds {
|
||||
if this._kind == shape_kind::hull {
|
||||
val m := mat3::rotation(at.turn);
|
||||
var low := m * this._hull.point(0);
|
||||
var high := low;
|
||||
for i in 1..this._hull.count {
|
||||
val p := m * this._hull.point(i);
|
||||
low = low.min(p);
|
||||
high = high.max(p);
|
||||
}
|
||||
return bounds{ at.at + low, at.at + high };
|
||||
}
|
||||
val a := at.apply(this._a);
|
||||
val b := at.apply(this._b);
|
||||
val r := vec3{ this._radius, this._radius, this._radius };
|
||||
return bounds{ a.min(b) - r, a.max(b) + r };
|
||||
}
|
||||
|
||||
#! Whether it holds a place of space, where a pose places it, its surface
|
||||
#! among it.
|
||||
pub def shape::contains(&this, at: pose, p: vec3): bool {
|
||||
val local := at.unapply(p);
|
||||
if this._kind == shape_kind::hull {
|
||||
for f in 0..this._hull.faces {
|
||||
return false if this._hull.normal(f).dot(local) > this._hull.offset(f);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
val nearest := nearest_on_segment(local, this._a, this._b);
|
||||
return (local - nearest).length_squared <= this._radius * this._radius;
|
||||
}
|
||||
|
||||
#! Where a ray first meets it, where a pose places it: from a place, along a
|
||||
#! direction of length 1, as far as `reach`. A ray beginning within it meets
|
||||
#! it at 0, facing back along the ray.
|
||||
pub def shape::ray_cast(&this, at: pose, origin: vec3, direction: vec3, reach: f32): maybe<ray_hit> {
|
||||
val o := at.unapply(origin);
|
||||
val d := at.unrotate(direction);
|
||||
var found: maybe<ray_hit> = nothing{};
|
||||
if this._kind == shape_kind::hull {
|
||||
found = ray_hull(&this._hull, o, d, reach);
|
||||
} else if this._kind == shape_kind::capsule {
|
||||
found = ray_capsule(o, d, reach, this._a, this._b, this._radius);
|
||||
} else {
|
||||
found = ray_sphere(o, d, reach, this._a, this._radius);
|
||||
}
|
||||
if found is some(hit) {
|
||||
return ray_hit{ distance = hit.distance, point = at.apply(hit.point), normal = at.rotate(hit.normal) };
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
# A ray, of the shape's own places, meeting a sphere.
|
||||
def ray_sphere(o: vec3, d: vec3, reach: f32, center: vec3, radius: f32): maybe<ray_hit> {
|
||||
val s := o - center;
|
||||
val c := s.dot(s) - radius * radius;
|
||||
return ray_hit{ distance = 0, point = o, normal = -d } if c <= 0;
|
||||
val b := s.dot(d);
|
||||
return nothing{} if b > 0;
|
||||
val disc := b * b - c;
|
||||
return nothing{} if disc < 0;
|
||||
val t := -b - math::sqrt(disc);
|
||||
return nothing{} if t > reach;
|
||||
val p := o + d * t;
|
||||
return ray_hit{ distance = t, point = p, normal = (p - center) * (1 / radius) };
|
||||
}
|
||||
|
||||
# A ray meeting a capsule: its round side, where it meets it between its ends,
|
||||
# as an infinite cylinder's, else its round ends.
|
||||
def ray_capsule(o: vec3, d: vec3, reach: f32, a: vec3, b: vec3, radius: f32): maybe<ray_hit> {
|
||||
val nearest := nearest_on_segment(o, a, b);
|
||||
return ray_hit{ distance = 0, point = o, normal = -d } if (o - nearest).length_squared <= radius * radius;
|
||||
# The cylinder, as Ericson's Real-Time Collision Detection meets one: where
|
||||
# the ray's distance from its axis is the radius.
|
||||
val axis := b - a;
|
||||
val m := o - a;
|
||||
val dd := axis.dot(axis);
|
||||
val md := m.dot(axis);
|
||||
val nd := d.dot(axis);
|
||||
val qa := dd - nd * nd;
|
||||
if qa > tiny {
|
||||
val qb := dd * m.dot(d) - nd * md;
|
||||
val qc := dd * (m.dot(m) - radius * radius) - md * md;
|
||||
val disc := qb * qb - qa * qc;
|
||||
if disc >= 0 {
|
||||
val t := (-qb - math::sqrt(disc)) / qa;
|
||||
val along := md + t * nd;
|
||||
if t >= 0 && t <= reach && along >= 0 && along <= dd {
|
||||
val p := o + d * t;
|
||||
val on_axis := a + axis * (along / dd);
|
||||
return ray_hit{ distance = t, point = p, normal = (p - on_axis) * (1 / radius) };
|
||||
}
|
||||
}
|
||||
}
|
||||
var best: maybe<ray_hit> = nothing{};
|
||||
val first := ray_sphere(o, d, reach, a, radius);
|
||||
val second := ray_sphere(o, d, reach, b, radius);
|
||||
if first is some(hit) {
|
||||
best = hit;
|
||||
}
|
||||
if second is some(hit) {
|
||||
if best is some(held) {
|
||||
if hit.distance < held.distance {
|
||||
best = hit;
|
||||
}
|
||||
} else {
|
||||
best = hit;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
# A ray meeting a hull, clipped by each face's side in turn, as Cyrus and Beck
|
||||
# clip a line: where it enters the last side it crosses into is where it meets
|
||||
# the hull.
|
||||
def ray_hull(h: &hull, o: vec3, d: vec3, reach: f32): maybe<ray_hit> {
|
||||
var lower: f32 = 0;
|
||||
var upper := reach;
|
||||
var entered: i64 = -1;
|
||||
for f in 0..h.faces {
|
||||
val n := h.normal(f);
|
||||
val numerator := h.offset(f) - n.dot(o);
|
||||
val denominator := n.dot(d);
|
||||
if denominator == 0 {
|
||||
return nothing{} if numerator < 0;
|
||||
continue;
|
||||
}
|
||||
val t := numerator / denominator;
|
||||
if denominator < 0 && t > lower {
|
||||
lower = t;
|
||||
entered = f as i64;
|
||||
} else if denominator > 0 && t < upper {
|
||||
upper = t;
|
||||
}
|
||||
return nothing{} if upper < lower;
|
||||
}
|
||||
return ray_hit{ distance = 0, point = o, normal = -d } if entered < 0;
|
||||
return ray_hit{ distance = lower, point = o + d * lower, normal = h.normal(entered as u32) };
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
#! Contains `aabb_tree`, a tree of boxes: each leaf a box holding a number of
|
||||
#! its user's, as an entity's bits, and each branch the least box holding its
|
||||
#! two children, so what's near a box, or along a ray, is found by passing down
|
||||
#! only the branches that reach it, as Box2D's dynamic tree finds it.
|
||||
#!
|
||||
#! A leaf's box is grown past what it holds by the tree's margin, so what moves
|
||||
#! a little stays within it, and the tree isn't changed. A leaf is put where it
|
||||
#! grows the area of the boxes above it least, and each branch it passes is
|
||||
#! turned, as an AVL tree turns one, where one child is two or more deeper than
|
||||
#! the other, so the tree stays shallow whatever order its leaves come in.
|
||||
|
||||
import std::math;
|
||||
import malunal::geometry;
|
||||
import malunal::linear;
|
||||
module malunal::physics3d;
|
||||
|
||||
# No node.
|
||||
const none_node: u32 = 0xFFFFFFFF;
|
||||
|
||||
# The deepest a tree of shallow branches can be, with room to spare: past 2^40
|
||||
# leaves.
|
||||
const most_depth: u64 = 64;
|
||||
|
||||
struct tree_node {
|
||||
var box: bounds;
|
||||
var data: u64;
|
||||
var parent: u32 = 0xFFFFFFFF; # Or the next free node, where it's free.
|
||||
var left: u32 = 0xFFFFFFFF; # None of a leaf.
|
||||
var right: u32 = 0xFFFFFFFF;
|
||||
var height: i32; # 0 of a leaf, and -1 where it's free.
|
||||
}
|
||||
|
||||
#! A tree of boxes, each leaf holding a number of its user's, named by the leaf
|
||||
#! `insert` gives, which stays its name until it's removed.
|
||||
pub struct aabb_tree {
|
||||
var nodes: vector<tree_node>;
|
||||
var root: u32 = 0xFFFFFFFF;
|
||||
var free: u32 = 0xFFFFFFFF;
|
||||
var leaves: u64;
|
||||
#! How far each leaf's box is grown past what it holds.
|
||||
pub var margin: f32 = 0.1;
|
||||
}
|
||||
|
||||
#! A tree of no leaves, its boxes grown by a margin.
|
||||
pub def aabb_tree::new(margin: f32 = 0.1): aabb_tree {
|
||||
return aabb_tree{ nodes = vector::<tree_node>::new(), margin = margin };
|
||||
}
|
||||
|
||||
#! How many leaves it holds.
|
||||
pub val aabb_tree::length: u64 {
|
||||
get => this.leaves;
|
||||
}
|
||||
|
||||
#! How deep it is: 0 of no leaves or one, and 1 more for each branch down to
|
||||
#! its deepest leaf.
|
||||
pub val aabb_tree::height: i32 {
|
||||
get => this.root == none_node ? 0 : this.nodes[this.root as u64].height;
|
||||
}
|
||||
|
||||
#! Adds a box, and a number of the user's, as a leaf.
|
||||
#! @returns The leaf, which names it until it's removed.
|
||||
pub def aabb_tree::insert(&mut this, box: bounds, data: u64): u32 {
|
||||
val leaf := this.allocate();
|
||||
this.nodes[leaf as u64].box = grown(box, this.margin);
|
||||
this.nodes[leaf as u64].data = data;
|
||||
this.nodes[leaf as u64].height = 0;
|
||||
this.insert_leaf(leaf);
|
||||
this.leaves++;
|
||||
return leaf;
|
||||
}
|
||||
|
||||
#! Removes a leaf.
|
||||
pub def aabb_tree::remove(&mut this, leaf: u32): void {
|
||||
this.remove_leaf(leaf);
|
||||
this.release(leaf);
|
||||
this.leaves--;
|
||||
}
|
||||
|
||||
#! Moves a leaf to hold a box, where its grown box doesn't hold it already.
|
||||
#! @returns Whether it was moved.
|
||||
pub def aabb_tree::move(&mut this, leaf: u32, box: bounds): bool {
|
||||
return false if this.nodes[leaf as u64].box.contains(box);
|
||||
this.remove_leaf(leaf);
|
||||
this.nodes[leaf as u64].box = grown(box, this.margin);
|
||||
this.insert_leaf(leaf);
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The number a leaf holds.
|
||||
pub def aabb_tree::data(&this, leaf: u32): u64 {
|
||||
return this.nodes[leaf as u64].data;
|
||||
}
|
||||
|
||||
#! A leaf's box, grown by the margin.
|
||||
pub def aabb_tree::box_of(&this, leaf: u32): bounds {
|
||||
return this.nodes[leaf as u64].box;
|
||||
}
|
||||
|
||||
#! Visits each leaf whose box meets a box, as `visit(leaf, data)`, until it
|
||||
#! gives false.
|
||||
pub def aabb_tree::query<F>(&this, box: bounds, visit: F): void where F: invokable<def(u32, u64): bool> {
|
||||
return if this.root == none_node;
|
||||
var stack: u32[64];
|
||||
var top: u64 = 1;
|
||||
stack[0] = this.root;
|
||||
while top > 0 {
|
||||
top--;
|
||||
val index := stack[top] as u64;
|
||||
continue if !this.nodes[index].box.overlaps(box);
|
||||
if this.nodes[index].left == none_node {
|
||||
return if !visit(index as u32, this.nodes[index].data);
|
||||
} else if top + 2 <= most_depth {
|
||||
stack[top] = this.nodes[index].left;
|
||||
stack[top + 1] = this.nodes[index].right;
|
||||
top += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Visits each leaf whose box a ray meets, from a place, along a direction of
|
||||
#! length 1, as far as `reach`, as `visit(leaf, data, reach)`, which gives how
|
||||
#! far to go on: the distance of what it found there, so only what's nearer is
|
||||
#! visited after; `reach` as it was, to go on as far; or 0, to stop.
|
||||
pub def aabb_tree::ray_cast<F>(&this, origin: vec3, direction: vec3, reach: f32, visit: F): void
|
||||
where F: invokable<def(u32, u64, f32): f32> {
|
||||
return if this.root == none_node;
|
||||
var far := reach;
|
||||
var stack: u32[64];
|
||||
var top: u64 = 1;
|
||||
stack[0] = this.root;
|
||||
while top > 0 {
|
||||
top--;
|
||||
val index := stack[top] as u64;
|
||||
continue if !ray_reaches(&this.nodes[index].box, origin, direction, far);
|
||||
if this.nodes[index].left == none_node {
|
||||
val next := visit(index as u32, this.nodes[index].data, far);
|
||||
return if next <= 0;
|
||||
far = math::min(far, next);
|
||||
} else if top + 2 <= most_depth {
|
||||
stack[top] = this.nodes[index].left;
|
||||
stack[top + 1] = this.nodes[index].right;
|
||||
top += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether the tree is as it should be: each node's parent its parent, each
|
||||
#! branch's box the least holding its children's, and its height one more than
|
||||
#! its deeper child's, each branch's children no more than one apart in height.
|
||||
#! For tests.
|
||||
pub def aabb_tree::is_sound(&this): bool {
|
||||
return true if this.root == none_node;
|
||||
return false if this.nodes[this.root as u64].parent != none_node;
|
||||
var stack: u32[64];
|
||||
var top: u64 = 1;
|
||||
var seen: u64 = 0;
|
||||
stack[0] = this.root;
|
||||
while top > 0 {
|
||||
top--;
|
||||
val index := stack[top] as u64;
|
||||
val left := this.nodes[index].left;
|
||||
val right := this.nodes[index].right;
|
||||
if left == none_node {
|
||||
return false if right != none_node || this.nodes[index].height != 0;
|
||||
seen++;
|
||||
continue;
|
||||
}
|
||||
val l := &this.nodes[left as u64];
|
||||
val r := &this.nodes[right as u64];
|
||||
return false if l.parent != index as u32 || r.parent != index as u32;
|
||||
return false if this.nodes[index].height != 1 + math::max(l.height, r.height) || math::abs(l.height - r.height) > 1;
|
||||
return false if !(l.box.merged(r.box) == this.nodes[index].box);
|
||||
return false if top + 2 > most_depth;
|
||||
stack[top] = left;
|
||||
stack[top + 1] = right;
|
||||
top += 2;
|
||||
}
|
||||
return seen == this.leaves;
|
||||
}
|
||||
|
||||
# A box grown so far each way.
|
||||
def grown(box: bounds, by: f32): bounds {
|
||||
val reach := vec3{ by, by, by };
|
||||
return bounds{ box.min - reach, box.max + reach };
|
||||
}
|
||||
|
||||
# The area of a box's faces, which a tree weighs where to put a box by, as the
|
||||
# chance a ray or a box passing by meets it.
|
||||
def area_of(box: bounds): f32 {
|
||||
val size := box.max - box.min;
|
||||
return 2 * (size.x * size.y + size.y * size.z + size.z * size.x);
|
||||
}
|
||||
|
||||
# Whether a ray reaches a box, from a place, along a direction, as far as
|
||||
# `reach`: whether it's between the box's faces along every axis at once.
|
||||
def ray_reaches(box: &bounds, origin: vec3, direction: vec3, reach: f32): bool {
|
||||
var low: f32 = 0;
|
||||
var high := reach;
|
||||
val origins: f32[3] = [origin.x, origin.y, origin.z];
|
||||
val ways: f32[3] = [direction.x, direction.y, direction.z];
|
||||
val lows: f32[3] = [box.min.x, box.min.y, box.min.z];
|
||||
val highs: f32[3] = [box.max.x, box.max.y, box.max.z];
|
||||
for i in 0..3u {
|
||||
if math::abs(ways[i]) < tiny {
|
||||
return false if origins[i] < lows[i] || origins[i] > highs[i];
|
||||
continue;
|
||||
}
|
||||
var near := (lows[i] - origins[i]) / ways[i];
|
||||
var far := (highs[i] - origins[i]) / ways[i];
|
||||
if near > far {
|
||||
val swapped := near;
|
||||
near = far;
|
||||
far = swapped;
|
||||
}
|
||||
low = math::max(low, near);
|
||||
high = math::min(high, far);
|
||||
return false if low > high;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# A node to use: a free one, or a new one.
|
||||
def aabb_tree::allocate(&mut this): u32 {
|
||||
if this.free == none_node {
|
||||
this.nodes.append(tree_node{});
|
||||
return (this.nodes.length - 1) as u32;
|
||||
}
|
||||
val made := this.free;
|
||||
this.free = this.nodes[made as u64].parent;
|
||||
this.nodes[made as u64] = tree_node{};
|
||||
return made;
|
||||
}
|
||||
|
||||
# Frees a node, for another to use.
|
||||
def aabb_tree::release(&mut this, index: u32): void {
|
||||
this.nodes[index as u64] = tree_node{ parent = this.free, height = -1 };
|
||||
this.free = index;
|
||||
}
|
||||
|
||||
# What putting a box beneath a child costs: what the child's box grows by, or
|
||||
# all of it, of a leaf, which a new branch takes the place of.
|
||||
def aabb_tree::descent_cost(&this, child: u32, box: bounds): f32 {
|
||||
val node := &this.nodes[child as u64];
|
||||
val merged := area_of(box.merged(node.box));
|
||||
return merged if node.left == none_node;
|
||||
return merged - area_of(node.box);
|
||||
}
|
||||
|
||||
# Puts a leaf where it grows the boxes above it least: beside a node, beneath a
|
||||
# new branch holding both.
|
||||
def aabb_tree::insert_leaf(&mut this, leaf: u32): void {
|
||||
if this.root == none_node {
|
||||
this.root = leaf;
|
||||
this.nodes[leaf as u64].parent = none_node;
|
||||
return;
|
||||
}
|
||||
val box := this.nodes[leaf as u64].box;
|
||||
var index := this.root;
|
||||
while this.nodes[index as u64].left != none_node {
|
||||
val node_box := this.nodes[index as u64].box;
|
||||
val left := this.nodes[index as u64].left;
|
||||
val right := this.nodes[index as u64].right;
|
||||
val combined := area_of(node_box.merged(box));
|
||||
# Beside this node, a new branch holding both; beneath it, every box
|
||||
# above grows as this one does.
|
||||
val here := 2 * combined;
|
||||
val inherited := 2 * (combined - area_of(node_box));
|
||||
val to_left := this.descent_cost(left, box) + inherited;
|
||||
val to_right := this.descent_cost(right, box) + inherited;
|
||||
break if here < to_left && here < to_right;
|
||||
index = to_left < to_right ? left : right;
|
||||
}
|
||||
|
||||
val sibling := index;
|
||||
val old_parent := this.nodes[sibling as u64].parent;
|
||||
val branch := this.allocate();
|
||||
this.nodes[branch as u64].parent = old_parent;
|
||||
this.nodes[branch as u64].box = box.merged(this.nodes[sibling as u64].box);
|
||||
this.nodes[branch as u64].height = this.nodes[sibling as u64].height + 1;
|
||||
this.nodes[branch as u64].left = sibling;
|
||||
this.nodes[branch as u64].right = leaf;
|
||||
this.nodes[sibling as u64].parent = branch;
|
||||
this.nodes[leaf as u64].parent = branch;
|
||||
if old_parent == none_node {
|
||||
this.root = branch;
|
||||
} else if this.nodes[old_parent as u64].left == sibling {
|
||||
this.nodes[old_parent as u64].left = branch;
|
||||
} else {
|
||||
this.nodes[old_parent as u64].right = branch;
|
||||
}
|
||||
this.refit(this.nodes[leaf as u64].parent);
|
||||
}
|
||||
|
||||
# Takes a leaf out, its sibling taking its parent's place.
|
||||
def aabb_tree::remove_leaf(&mut this, leaf: u32): void {
|
||||
if leaf == this.root {
|
||||
this.root = none_node;
|
||||
return;
|
||||
}
|
||||
val parent := this.nodes[leaf as u64].parent;
|
||||
val grandparent := this.nodes[parent as u64].parent;
|
||||
val sibling := this.nodes[parent as u64].left == leaf ? this.nodes[parent as u64].right : this.nodes[parent as u64].left;
|
||||
this.nodes[sibling as u64].parent = grandparent;
|
||||
this.release(parent);
|
||||
if grandparent == none_node {
|
||||
this.root = sibling;
|
||||
return;
|
||||
}
|
||||
if this.nodes[grandparent as u64].left == parent {
|
||||
this.nodes[grandparent as u64].left = sibling;
|
||||
} else {
|
||||
this.nodes[grandparent as u64].right = sibling;
|
||||
}
|
||||
this.refit(grandparent);
|
||||
}
|
||||
|
||||
# Walks up from a branch to the root, turning each that's out of balance, and
|
||||
# making its box and height those of its children again.
|
||||
def aabb_tree::refit(&mut this, from: u32): void {
|
||||
var index := from;
|
||||
while index != none_node {
|
||||
index = this.balance(index);
|
||||
val left := this.nodes[index as u64].left;
|
||||
val right := this.nodes[index as u64].right;
|
||||
this.nodes[index as u64].height = 1 + math::max(this.nodes[left as u64].height, this.nodes[right as u64].height);
|
||||
this.nodes[index as u64].box = this.nodes[left as u64].box.merged(this.nodes[right as u64].box);
|
||||
index = this.nodes[index as u64].parent;
|
||||
}
|
||||
}
|
||||
|
||||
# Turns a branch whose children are two or more apart in height: the deeper
|
||||
# child takes its place, and it takes the deeper child's shallower child.
|
||||
# @returns The node in its place now.
|
||||
def aabb_tree::balance(&mut this, a: u32): u32 {
|
||||
return a if this.nodes[a as u64].left == none_node || this.nodes[a as u64].height < 2;
|
||||
val b := this.nodes[a as u64].left;
|
||||
val c := this.nodes[a as u64].right;
|
||||
val leaning := this.nodes[c as u64].height - this.nodes[b as u64].height;
|
||||
if leaning > 1 {
|
||||
this.raise(a, c, b, true);
|
||||
return c;
|
||||
}
|
||||
if leaning < -1 {
|
||||
this.raise(a, b, c, false);
|
||||
return b;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
# Raises `up`, a child of `a`, into its place: `a` becomes `up`'s first child,
|
||||
# beside `up`'s deeper child, and takes `up`'s shallower child where `up` was,
|
||||
# `other` its child still. `on_right` says `up` was `a`'s right child.
|
||||
def aabb_tree::raise(&mut this, a: u32, up: u32, other: u32, on_right: bool): void {
|
||||
val f := this.nodes[up as u64].left;
|
||||
val g := this.nodes[up as u64].right;
|
||||
# `up` takes `a`'s place beneath its parent.
|
||||
val above := this.nodes[a as u64].parent;
|
||||
this.nodes[up as u64].left = a;
|
||||
this.nodes[up as u64].parent = above;
|
||||
this.nodes[a as u64].parent = up;
|
||||
if above == none_node {
|
||||
this.root = up;
|
||||
} else if this.nodes[above as u64].left == a {
|
||||
this.nodes[above as u64].left = up;
|
||||
} else {
|
||||
this.nodes[above as u64].right = up;
|
||||
}
|
||||
# `up` keeps its deeper child; `a` takes the shallower where `up` was.
|
||||
val deeper := this.nodes[f as u64].height > this.nodes[g as u64].height ? f : g;
|
||||
val shallower := deeper == f ? g : f;
|
||||
this.nodes[up as u64].right = deeper;
|
||||
if on_right {
|
||||
this.nodes[a as u64].right = shallower;
|
||||
} else {
|
||||
this.nodes[a as u64].left = shallower;
|
||||
}
|
||||
this.nodes[shallower as u64].parent = a;
|
||||
this.nodes[a as u64].box = this.nodes[other as u64].box.merged(this.nodes[shallower as u64].box);
|
||||
this.nodes[a as u64].height = 1 + math::max(this.nodes[other as u64].height, this.nodes[shallower as u64].height);
|
||||
this.nodes[up as u64].box = this.nodes[a as u64].box.merged(this.nodes[deeper as u64].box);
|
||||
this.nodes[up as u64].height = 1 + math::max(this.nodes[a as u64].height, this.nodes[deeper as u64].height);
|
||||
}
|
||||
Reference in new issue
Block a user