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

+151
View File
@@ -0,0 +1,151 @@
#! Contains `body` and `collider`, what a `space` is given to make a body and
#! the shapes it's of, and `body_id` and `collider_id`, which name them there.
import malunal::linear;
module malunal::physics3d;
#! What moves a body.
pub enum body_kind: u8 {
#! Nothing: it stays where it's put, as the ground does.
static,
#! Its velocity alone, as it's set: what it meets doesn't push it, as a
#! moving platform's doesn't.
kinematic,
#! Forces, gravity, and what it meets, as a crate.
dynamic,
}
#! What a body is made as: its kind, its pose, how fast it moves at first,
#! and how it's slowed and pulled.
pub struct body {
pub var kind := body_kind::dynamic;
#! Where its origin is, and which way it's turned; its colliders' shapes are
#! of places about the origin.
pub var at := pose::identity;
#! How fast its center of mass moves, in lengths a second.
pub var velocity: vec3;
#! How fast it turns, about the axis it points along, by its length in
#! radians a second.
pub var spin: vec3;
#! How much of its velocity, and of its spin, it loses each second, as air
#! slows it.
pub var linear_damping: f32;
pub var angular_damping: f32 = 0.05;
#! How much of the space's gravity, and its own, pulls it: 0 floats.
pub var gravity_scale: f32 = 1;
#! A gravity of its own, added to the space's, as a planet's pulls what's
#! near it toward its middle.
pub var gravity: vec3;
#! Whether it never turns, as a character standing up doesn't.
pub var fixed_rotation: bool;
#! Whether it may sleep when it and what it rests on are still.
pub var can_sleep: bool = true;
#! Whether it's swept against moving bodies too, not only what stands
#! still, so it passes through nothing however fast it goes, as a shot.
pub var bullet: bool;
#! A number of its user's, as an entity's bits.
pub var data: u64;
}
#! What a body's collider is made as: its shape, about the body's origin; its
#! density, which sums to the body's mass; how it slides and bounces; and the
#! layers it's on and meets. A collider of a triangle mesh, which
#! `space::attach_mesh` gives a body, has no shape or density of its own.
pub struct collider {
pub var shape: shape;
#! Its mass for each volume of 1.
pub var density: f32 = 1;
#! How hard it is to slide along: 0 slides freely. Two colliders' are mixed
#! as the square root of their product.
pub var friction: f32 = 0.6;
#! How much of its speed toward what it meets it keeps, bounced back: 0
#! stops, 1 bounces as high as it fell. Two colliders' greater is taken.
pub var restitution: f32;
#! The layers it's on, and those it meets: two colliders meet where each is
#! on a layer of the other's mask.
pub var layers: u32 = 1;
pub var mask: u32 = 0xFFFFFFFF;
#! Whether it only notes what it overlaps, pushing nothing.
pub var sensor: bool;
#! A number of its user's, as an entity's bits.
pub var data: u64;
}
#! A body of a space, as `space::add` names it.
pub struct body_id {
pub var index: u32 = 0xFFFFFFFF;
pub var generation: u32;
}
pub def body_id::equals(&this, other: &body_id): bool {
return this.index == other.index && this.generation == other.generation;
}
#! A collider of a body of a space, as `space::attach` names it.
pub struct collider_id {
pub var index: u32 = 0xFFFFFFFF;
pub var generation: u32;
}
pub def collider_id::equals(&this, other: &collider_id): bool {
return this.index == other.index && this.generation == other.generation;
}
# No body, collider, contact, mesh, or joint.
const none: u32 = 0xFFFFFFFF;
# A body as the space keeps it.
struct body_record {
var kind: body_kind;
var generation: u32;
var alive: bool;
var at: pose; # Of its origin.
var center: vec3; # Its center of mass, in space.
var local_center: vec3; # The same, of its own places.
var velocity: vec3;
var spin: vec3;
var force: vec3;
var torque: vec3;
var mass: f32;
var inv_mass: f32;
var inertia: mat3; # About its center of mass, of its own axes.
var inv_inertia: mat3; # The same, inverted.
var linear_damping: f32;
var angular_damping: f32;
var gravity_scale: f32 = 1;
var gravity: vec3; # Its own, added to the space's.
var fixed_rotation: bool;
var can_sleep: bool = true;
var awake: bool = true;
var sleep_time: f32;
var extent: f32; # How far its colliders reach from its center.
var least: f32; # How far its narrowest shape reaches from its middle.
var bullet: bool;
var colliders: u32 = 0xFFFFFFFF;
var joints: u32 = 0xFFFFFFFF;
var group: u32 = 0xFFFFFFFF;
var next_in_group: u32 = 0xFFFFFFFF;
var slot: u32;
var data: u64;
}
# A collider as the space keeps it: of a shape, or of a mesh the space holds.
struct collider_record {
var made: collider;
var mesh: u32 = 0xFFFFFFFF;
var body: u32;
var leaf: u32 = 0xFFFFFFFF;
var next: u32 = 0xFFFFFFFF;
var generation: u32;
var alive: bool;
var moved: bool;
}
def body_record::is_dynamic(&this): bool {
return this.kind == body_kind::dynamic;
}
# Whether a collider is of a mesh.
def collider_record::is_mesh(&this): bool {
return this.mesh != none;
}
+216
View File
@@ -0,0 +1,216 @@
#! Contains `character`, a body a game walks, as Jolt's virtual character is:
#! not a rigid body of the space, but a shape moved through it by casts, sliding
#! along what it meets, stepping up what's low enough, sticking to the ground as
#! it walks down slopes and off steps, riding what it stands on as that moves,
#! pushed out of what moves into it, and pushing what's dynamic before it.
import std::math;
import malunal::linear;
module malunal::physics3d;
#! A character's body, and what it stands on, as its last move found it.
pub struct character {
#! Its shape, about its origin, a capsule standing up as `shape::pill`
#! makes one.
pub var shape := shape::pill(0.6, 1.8);
#! Where its origin is.
pub var at: vec3;
#! Which way is up, against gravity, of length 1: its shape stands along
#! it, as on a planet, where up is away from the middle.
pub var up := vec3::up;
#! How fast it moved in its last move, but for what it rode: what it was
#! asked to, less what it met. A game adds gravity to it while it's in the
#! air.
pub var velocity: vec3;
#! The steepest ground it stands on and walks up, in radians from flat.
pub var max_slope: f32 = 0.8;
#! The highest it steps up, as onto a stair, and the furthest down it keeps
#! to the ground, as walking down one.
pub var step_height: f32 = 0.35;
pub var snap: f32 = 0.35;
#! How far it keeps from what it meets.
pub var skin: f32 = 0.02;
#! Its mass, and the most force it pushes what's dynamic with.
pub var mass: f32 = 70;
pub var push: f32 = 500;
#! The layers of colliders it meets.
pub var mask: u32 = 0xFFFFFFFF;
#! A body of its own in the space, as a kinematic one moved with it so what
#! moves meets it, which it passes over.
pub var body: body_id;
#! Whether it stands on ground it may, and that ground: which way it faces,
#! its body, and how fast it moves where the character stands.
pub var grounded: bool;
pub var ground_normal := vec3::up;
pub var ground: body_id;
pub var ground_velocity: vec3;
}
#! Whether a character may stand on ground facing a direction.
pub def character::walkable(&this, normal: vec3): bool {
return normal.dot(this.up) >= math::cos(this.max_slope);
}
#! Its pose: at its place, turned from standing along y to stand along its up.
pub def character::pose(&this): pose {
return this.pose_at(this.at);
}
# Its pose, were it somewhere else.
def character::pose_at(&this, at: vec3): pose {
return pose::of(at, quat::between(vec3::up, this.up));
}
#! Moves a character through a step of `dt` seconds, at a velocity, as its
#! game asks, adding how fast what it stands on moves: pushed out of what it
#! overlaps, then cast along its motion, sliding along what it meets, stepping
#! up what's low enough while it's on the ground, and kept to the ground as it
#! walks down. Its velocity after is what it was asked, less what it met; what
#! it stands on is found again.
pub def space::move_character(&mut this, c: &mut character, velocity: vec3, dt: f32): void {
return if dt <= 0;
val was_grounded := c.grounded;
c.velocity = velocity;
this.push_character_out(c);
var motion := velocity * dt;
if was_grounded {
motion = motion + c.ground_velocity * dt;
}
for iteration in 0..4u {
if motion.length_squared < tiny * tiny {
break;
}
val hit := this.shape_cast(&c.shape, c.pose(), motion, c.mask, c.body) else {
c.at = c.at + motion;
break;
};
c.at = c.at + motion * hit.fraction + hit.normal * c.skin;
var left := motion * (1 - hit.fraction);
val walkable := c.walkable(hit.normal);
if !walkable && was_grounded && this.step_up(c, velocity * dt) {
break;
}
# What's left slides along what it met: along a wall it can't walk up,
# not up it.
var n := hit.normal;
if !walkable && was_grounded {
val flat := n - c.up * n.dot(c.up);
if flat.length_squared > tiny {
n = flat.normalized();
}
}
this.push_struck(c, &hit, dt);
left = left - n * math::min(left.dot(n), 0f);
c.velocity = c.velocity - n * math::min(c.velocity.dot(n), 0f);
motion = left;
}
# Kept to the ground walking down a slope or off a step, where it isn't
# moving up.
if was_grounded && c.velocity.dot(c.up) <= 0 && c.snap > 0 {
if this.shape_cast(&c.shape, c.pose(), c.up * -c.snap, c.mask, c.body) is some(down) {
if c.walkable(down.normal) {
c.at = c.at - c.up * (c.snap * down.fraction) + c.up * c.skin;
}
}
}
this.find_ground(c);
}
# Finds what a character stands on, just below it.
def space::find_ground(&this, c: &mut character): void {
c.grounded = false;
c.ground = body_id{};
c.ground_velocity = vec3::zero;
val below := this.shape_cast(&c.shape, c.pose(), c.up * (-3 * c.skin), c.mask, c.body) else { return; };
return if !c.walkable(below.normal);
c.grounded = true;
c.ground_normal = below.normal;
c.ground = below.body;
val b := &this.bodies[below.body.index as u64];
if b.kind != body_kind::static {
c.ground_velocity = b.velocity + b.spin.cross(c.at - b.center);
}
# Standing, it doesn't fall into the ground.
val falling := c.velocity.dot(c.up);
if falling < 0 {
c.velocity = c.velocity - c.up * falling;
}
}
# Steps a character up onto what it walked into, where it's no higher than its
# step: raised, moved on as far as it walks this step, and lowered, where
# feeling further ahead finds ground it may stand on there.
def space::step_up(&this, c: &mut character, left: vec3): bool {
val ahead := left - c.up * left.dot(c.up);
return false if ahead.length_squared < tiny * tiny || c.step_height <= 0;
var rise := c.step_height;
if this.shape_cast(&c.shape, c.pose(), c.up * c.step_height, c.mask, c.body) is some(above) {
rise = math::max(c.step_height * above.fraction - c.skin, 0f);
}
return false if rise <= c.skin;
val raised := c.pose_at(c.at + c.up * rise);
# Felt for further ahead than its round foot reaches, however little it's
# left to move, so it steps only onto what's there to stand on, higher than
# it stands, and not onto the step's edge.
val reach := math::max(ahead.length, c.shape.radius + 2 * c.skin);
val probe := ahead.normalized() * reach;
var moved := probe;
if this.shape_cast(&c.shape, raised, probe, c.mask, c.body) is some(wall) {
moved = probe * wall.fraction;
}
return false if moved.length < 0.5 * reach;
val drop := c.up * -(rise + c.skin);
val landing := this.shape_cast(&c.shape, c.pose_at(raised.at + moved), drop, c.mask, c.body) else { return false; };
return false if !c.walkable(landing.normal) || landing.fraction == 0;
return false if (rise + c.skin) * (1 - landing.fraction) <= c.skin;
# Then moved as far as it walks, and set down, on the step's edge, maybe, to
# walk on from.
val over := c.pose_at(raised.at + ahead * math::min(1f, moved.length / ahead.length));
val down := this.shape_cast(&c.shape, over, drop, c.mask, c.body) else { return false; };
c.at = over.at + drop * down.fraction + c.up * c.skin;
return true;
}
# Pushes a character out of what it overlaps, as what moves into it does, a
# few times over, by the deepest each time.
def space::push_character_out(&this, c: &mut character): void {
for iteration in 0..4u {
var deepest: f32 = 0;
var away := vec3::zero;
val placed := c.pose();
this.tree.query(grown(c.shape.bounds(placed), c.skin), def(leaf: u32, data: u64): bool {
return true if this.colliders[data].body == c.body.index || !this.passes(data as u32, &query_filter{ mask = c.mask });
val held := &this.colliders[data];
val at := this.bodies[held.body as u64].at;
if held.is_mesh() {
this.meshes[held.mesh as u64].collide(at, &c.shape, placed, 0, def(t: u32, m: manifold): bool {
if m.depth > deepest {
deepest = m.depth;
away = m.normal;
}
return true;
});
return true;
}
val m := collide(&held.made.shape, at, &c.shape, placed) else { return true; };
if m.depth > deepest {
deepest = m.depth;
away = m.normal;
}
return true;
});
if deepest <= 0 {
return;
}
c.at = c.at + away * (deepest + c.skin);
}
}
# Pushes a dynamic body a character walked into, by no more than its push.
def space::push_struck(&mut this, c: &character, hit: &space_cast, dt: f32): void {
return if !this.has(hit.body) || this.bodies[hit.body.index as u64].kind != body_kind::dynamic;
val into := -c.velocity.dot(hit.normal);
return if into <= 0;
val impulse := math::min(into * c.mass, c.push * dt);
this.apply_impulse(hit.body, -hit.normal * impulse, hit.point);
}
+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;
}
+499
View File
@@ -0,0 +1,499 @@
#! Contains how a space finds which colliders are near one another, by the
#! boxes of its tree, and where those meet, as contacts kept from one step to
#! the next, so each begins with the impulses that held its bodies apart last.
#! Two shapes have one contact; a shape and a triangle mesh one for each
#! triangle they meet, named by the triangle, so it's kept as they slide.
import std::containers;
import std::math;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
#! Two colliders that began or stopped touching in a step: sensors among
#! them, which touch where they overlap.
pub struct contact_event {
pub var a: collider_id;
pub var b: collider_id;
#! Whether they began touching, or stopped.
pub var began: bool;
#! Whether either is a sensor.
pub var sensor: bool;
}
# Two colliders whose grown boxes meet, the first's index the lesser, and
# their contacts, a list of them: none of sensors, which only note whether
# they overlap.
struct pair_record {
var a: u32;
var b: u32;
var contacts: u32 = 0xFFFFFFFF;
var touching: bool;
var sensor: bool;
var mesh: bool;
var alive: bool;
}
# Where two colliders meet, or a shape and one triangle of a mesh: the
# manifold, and the impulses that held them apart at each of its points last
# step, along the normal and the two tangents.
struct contact_record {
var pair: u32;
var child: u32; # The triangle, of a mesh's.
var next: u32 = 0xFFFFFFFF;
var body_a: u32;
var body_b: u32;
var manifold: manifold;
var normal_impulse: f32[4];
var tangent_impulse: vec3[4]; # Along the first tangent, then the second.
var friction: f32;
var restitution: f32;
var touching: bool;
var seen: bool;
var alive: bool;
}
# A triangle a shape met, and how.
struct met_triangle {
var triangle: u32;
var manifold: manifold;
}
# A manifold's points and another's of the same normal, as four of them that
# hold the most of the area they hold.
def merge_into(into: &mut manifold, other: &manifold): void {
var found: contact[64];
var count: u32 = 0;
for i in 0..into.count {
found[count] = into.points[i];
count++;
}
for i in 0..other.count {
found[count] = other.points[i];
count++;
}
if count <= max_contacts {
for i in 0..count {
into.points[i] = found[i];
}
into.count = count;
return;
}
val kept := reduced(&found, count, into.normal, manifold{ normal = into.normal });
into.points = kept.points;
into.count = kept.count;
}
def pair_key(a: u32, b: u32): u64 {
val low := math::min(a, b) as u64;
val high := math::max(a, b) as u64;
return (low << 32) | high;
}
# Whether two colliders may meet: of two bodies, one of them dynamic, or one
# a sensor and the other not static, on layers each other's masks hold, not
# both meshes, and not of bodies a joint keeps apart.
def space::may_meet(&this, a: u32, b: u32): bool {
val ca := &this.colliders[a as u64];
val cb := &this.colliders[b as u64];
return false if ca.body == cb.body || (ca.is_mesh() && cb.is_mesh());
if !this.bodies[ca.body as u64].is_dynamic() && !this.bodies[cb.body as u64].is_dynamic() {
# A sensor meets what moves into it, kinematic as well as dynamic, but two
# standing still never meet.
return false if !ca.made.sensor && !cb.made.sensor;
return false if this.bodies[ca.body as u64].kind == body_kind::static && this.bodies[cb.body as u64].kind == body_kind::static;
}
return false if (ca.made.layers & cb.made.mask) == 0 || (cb.made.layers & ca.made.mask) == 0;
return !this.joined_apart(ca.body, cb.body);
}
# Pairs each collider whose leaf moved with those its grown box newly meets.
def space::find_pairs(&mut this): void {
return if this.moved.length == 0;
var near := move(this.near);
for m in 0..this.moved.length {
val c := this.moved[m];
continue if !this.colliders[c as u64].alive;
near.clear();
this.tree.query(this.tree.box_of(this.colliders[c as u64].leaf), def(leaf: u32, data: u64): bool {
val other := data as u32;
if other != c && !(this.colliders[data].moved && other < c) {
near.append(other);
}
return true;
});
for k in 0..near.length {
val other := near[k];
val key := pair_key(c, other);
if this.may_meet(c, other) && !this.pair_keys.contains(&key) {
this.make_pair(math::min(c, other), math::max(c, other));
}
}
}
for m in 0..this.moved.length {
this.colliders[this.moved[m] as u64].moved = false;
}
this.moved.clear();
this.near = move(near);
}
def space::make_pair(&mut this, a: u32, b: u32): void {
var p: u32 = 0;
if this.free_pairs.length > 0 {
p = this.free_pairs[this.free_pairs.length - 1];
this.free_pairs.truncate();
} else {
p = this.pairs.length as u32;
this.pairs.append(pair_record{});
}
val sensor := this.colliders[a as u64].made.sensor || this.colliders[b as u64].made.sensor;
val mesh := this.colliders[a as u64].is_mesh() || this.colliders[b as u64].is_mesh();
this.pairs[p as u64] = pair_record{ a = a, b = b, sensor = sensor, mesh = mesh, alive = true };
this.pair_keys.set(pair_key(a, b), p);
if !sensor && !mesh {
this.pairs[p as u64].contacts = this.make_contact(p, 0);
}
}
# A new contact of a pair, put first of its list.
def space::make_contact(&mut this, p: u32, child: u32): u32 {
var k: u32 = 0;
if this.free_contacts.length > 0 {
k = this.free_contacts[this.free_contacts.length - 1];
this.free_contacts.truncate();
} else {
k = this.contacts.length as u32;
this.contacts.append(contact_record{});
}
val a := this.pairs[p as u64].a;
val b := this.pairs[p as u64].b;
val ma := &this.colliders[a as u64].made;
val mb := &this.colliders[b as u64].made;
this.contacts[k as u64] = contact_record{
pair = p, child = child, next = this.pairs[p as u64].contacts,
body_a = this.colliders[a as u64].body, body_b = this.colliders[b as u64].body,
friction = math::sqrt(ma.friction * mb.friction), restitution = math::max(ma.restitution, mb.restitution), alive = true,
};
return k;
}
def space::free_contact(&mut this, k: u32): void {
this.contacts[k as u64].alive = false;
this.free_contacts.append(k);
}
# Frees a pair and its contacts, noting it stopped where it touched, and
# waking its bodies then where `wake` is given.
def space::drop_pair(&mut this, p: u32, wake: bool): void {
val pair := this.pairs[p as u64];
if pair.touching {
this.note(p, false);
if wake {
this.wake_body(this.colliders[pair.a as u64].body);
this.wake_body(this.colliders[pair.b as u64].body);
}
}
var k := pair.contacts;
while k != none {
val next := this.contacts[k as u64].next;
this.free_contact(k);
k = next;
}
this.pair_keys.remove(&pair_key(pair.a, pair.b));
this.pairs[p as u64].alive = false;
this.free_pairs.append(p);
}
def space::note(&mut this, p: u32, began: bool): void {
val a := this.pairs[p as u64].a;
val b := this.pairs[p as u64].b;
this.noted.append(contact_event{
a = collider_id{ index = a, generation = this.colliders[a as u64].generation },
b = collider_id{ index = b, generation = this.colliders[b as u64].generation },
began = began, sensor = this.pairs[p as u64].sensor,
});
}
# Whether a body moves this step: dynamic or kinematic, and awake.
def space::moves(&this, b: u32): bool {
val body := &this.bodies[b as u64];
return body.kind != body_kind::static && body.awake;
}
# Where a pair's shapes meet: as the crew found it, where the step is solved on
# several threads, else found now.
def space::pair_manifold(&this, p: u32): manifold {
return this.found[p as u64] if this.threads > 1;
return this.manifold_of(this.pairs[p as u64].a, this.pairs[p as u64].b, this.speculative);
}
# Finds where each pair of two shapes meets, on the crew, a block of pairs to
# each thread, as none needs another's: what it finds is put to use one pair at
# a time after, so a step gives the same on any number of threads.
def space::find_manifolds(&mut this): void {
this.found.clear();
this.found.resize(this.pairs.length, manifold{});
var job := pairs_job{ space = address(this) };
val block := math::max(this.pairs.length / (this.threads as u64 * 8), 16u);
this.crew.run(run_pairs, address(&mut job) as *mut u8, this.pairs.length, block);
}
struct pairs_job {
var space: *mut space;
}
def run_pairs(context: *mut u8, begin: u64, end: u64): void {
val job := &through(context as *mut pairs_job);
val s := &mut through(job.space);
for p in begin..end {
val pair := &s.pairs[p];
continue if !pair.alive || pair.sensor || pair.mesh;
val ca := &s.colliders[pair.a as u64];
val cb := &s.colliders[pair.b as u64];
continue if !s.moves(ca.body) && !s.moves(cb.body);
continue if !s.tree.box_of(ca.leaf).overlaps(s.tree.box_of(cb.leaf));
s.found[p] = s.manifold_of(pair.a, pair.b, s.speculative);
}
}
# Finds where each pair of a moving body meets, dropping those whose grown
# boxes no longer meet.
def space::update_contacts(&mut this): void {
if this.threads > 1 {
this.find_manifolds();
}
for p in 0..this.pairs.length {
continue if !this.pairs[p].alive;
val a := this.pairs[p].a;
val b := this.pairs[p].b;
val ba := this.colliders[a as u64].body;
val bb := this.colliders[b as u64].body;
continue if !this.moves(ba) && !this.moves(bb);
if !this.tree.box_of(this.colliders[a as u64].leaf).overlaps(this.tree.box_of(this.colliders[b as u64].leaf)) {
this.drop_pair(p as u32, false);
continue;
}
var touching := false;
if this.pairs[p].sensor {
touching = this.sensed(a, b);
} else if this.pairs[p].mesh {
touching = this.update_mesh_contacts(p as u32);
} else {
touching = this.update_contact(this.pairs[p].contacts, this.pair_manifold(p as u32));
}
if touching != this.pairs[p].touching {
this.pairs[p].touching = touching;
this.note(p as u32, touching);
if touching && !this.pairs[p].sensor {
this.note_hit(p as u32);
}
}
if touching {
this.wake_if_pushed(ba, bb);
this.wake_if_pushed(bb, ba);
}
}
}
# Wakes a sleeping dynamic body where what touches it is awake and moves it: a
# dynamic body, or a kinematic one moving.
def space::wake_if_pushed(&mut this, b: u32, by: u32): void {
return if this.bodies[b as u64].awake || this.bodies[b as u64].kind != body_kind::dynamic;
val other := &this.bodies[by as u64];
if other.awake && (other.kind == body_kind::dynamic || other.velocity.length_squared > 0 || other.spin.length_squared > 0) {
this.wake_body(b);
}
}
# Where two colliders' shapes meet, within a margin.
def space::manifold_of(&this, a: u32, b: u32, margin: f32): manifold {
val ca := &this.colliders[a as u64];
val cb := &this.colliders[b as u64];
if collide(&ca.made.shape, this.bodies[ca.body as u64].at, &cb.made.shape, this.bodies[cb.body as u64].at, margin) is some(m) {
return m;
}
return manifold{};
}
# Whether a sensor's pair overlaps: a shape and a shape, or a shape and a
# mesh.
def space::sensed(&this, a: u32, b: u32): bool {
val ca := &this.colliders[a as u64];
val cb := &this.colliders[b as u64];
val at_a := this.bodies[ca.body as u64].at;
val at_b := this.bodies[cb.body as u64].at;
return this.meshes[ca.mesh as u64].overlaps(at_a, &cb.made.shape, at_b) if ca.is_mesh();
return this.meshes[cb.mesh as u64].overlaps(at_b, &ca.made.shape, at_a) if cb.is_mesh();
return overlaps(&ca.made.shape, at_a, &cb.made.shape, at_b);
}
# Gives a contact a manifold, each point beginning with the impulses of last
# step's point of the same features.
# @returns Whether it touches, within the speculative margin.
def space::update_contact(&mut this, k: u32, found: manifold): bool {
val c := &mut this.contacts[k as u64];
var normal: f32[4] = [0, 0, 0, 0];
var tangent: vec3[4];
for i in 0..found.count {
for j in 0..c.manifold.count {
if found.points[i].id == c.manifold.points[j].id {
normal[i] = c.normal_impulse[j];
tangent[i] = c.tangent_impulse[j];
}
}
}
c.manifold = found;
c.normal_impulse = normal;
c.tangent_impulse = tangent;
c.touching = found.count > 0;
c.seen = true;
return c.touching;
}
# Finds the triangles a shape meets of a mesh, a contact for each, keeping
# those it met last step and dropping those it no longer meets.
# @returns Whether any touches.
def space::update_mesh_contacts(&mut this, p: u32): bool {
val a := this.pairs[p as u64].a;
val b := this.pairs[p as u64].b;
# The mesh as the first, its normals from each triangle toward the shape,
# turned back where the shape is the pair's first.
val mesh_first := this.colliders[a as u64].is_mesh();
val m := mesh_first ? a : b;
val s := mesh_first ? b : a;
var met := move(this.met);
met.clear();
val held := &this.colliders[m as u64];
val shaped := &this.colliders[s as u64];
this.meshes[held.mesh as u64].collide(this.bodies[held.body as u64].at, &shaped.made.shape, this.bodies[shaped.body as u64].at, this.speculative, def(t: u32, found: manifold): bool {
# Triangles facing one way are met as one, their points together, as Jolt
# meets them, so a box resting across a seam is pushed as on one face,
# not one triangle's after the other's, which would edge it aside. Each
# point's id is mixed with its triangle, so points of two are told apart.
var made := mesh_first ? found : found.flipped();
val mixed := ((t as u64 * 0x9E3779B1) & 0xFFFFFFFF) as u32;
for i in 0..made.count {
made.points[i].id = made.points[i].id ^ mixed;
}
for k in 0..met.length {
if met[k].manifold.normal.dot(made.normal) > 0.999 {
merge_into(&mut met[k].manifold, &made);
return true;
}
}
met.append(met_triangle{ triangle = t, manifold = made });
return true;
});
var k := this.pairs[p as u64].contacts;
while k != none {
this.contacts[k as u64].seen = false;
k = this.contacts[k as u64].next;
}
var touching := false;
for i in 0..met.length {
var found := this.pairs[p as u64].contacts;
while found != none && this.contacts[found as u64].child != met[i].triangle {
found = this.contacts[found as u64].next;
}
if found == none {
found = this.make_contact(p, met[i].triangle);
this.pairs[p as u64].contacts = found;
}
if this.update_contact(found, met[i].manifold) {
touching = true;
}
}
this.met = move(met);
# Those not met this step are dropped.
var previous: u32 = none;
k = this.pairs[p as u64].contacts;
while k != none {
val next := this.contacts[k as u64].next;
if !this.contacts[k as u64].seen {
if previous == none {
this.pairs[p as u64].contacts = next;
} else {
this.contacts[previous as u64].next = next;
}
this.free_contact(k);
} else {
previous = k;
}
k = next;
}
return touching;
}
#! Two colliders that began touching in a step faster than the space's
#! `hit_speed`, as something landing does: which, where, the normal from the
#! first toward the second, and how fast they met along it, as a sound of it
#! might be loud.
pub struct hit_event {
pub var a: collider_id;
pub var b: collider_id;
pub var point: vec3;
pub var normal: vec3;
pub var speed: f32;
}
#! The hits of the last step.
pub def space::hits(&this): span<hit_event> {
return this.struck.span;
}
# How fast a body's place moves, of a place of space.
def space::speed_at(&this, index: u32, at: vec3): vec3 {
val b := &this.bodies[index as u64];
val r := at - b.center;
return b.velocity + b.spin.cross(r);
}
# Notes how hard a pair that began touching met, where it met faster than the
# hit speed: at its first point, as the step began.
def space::note_hit(&mut this, p: u32): void {
var k := this.pairs[p as u64].contacts;
while k != none && this.contacts[k as u64].manifold.count == 0 {
k = this.contacts[k as u64].next;
}
return if k == none;
val c := &this.contacts[k as u64];
val point := c.manifold.points[0].point;
val n := c.manifold.normal;
val speed := -n.dot(this.speed_at(c.body_b, point) - this.speed_at(c.body_a, point));
return if speed < this.hit_speed;
val a := this.pairs[p as u64].a;
val b := this.pairs[p as u64].b;
this.struck.append(hit_event{
a = collider_id{ index = a, generation = this.colliders[a as u64].generation },
b = collider_id{ index = b, generation = this.colliders[b as u64].generation },
point = point, normal = n, speed = speed,
});
}
#! Visits each pair of colliders touching as the last step left them, a
#! sensor's among them where it overlaps what it meets, as `visit(a, b,
#! sensor)`, until it gives false: what began and stopped touching since a
#! step before, by what it visited then, however colliders were taken away
#! and attached between.
pub def space::each_touching<F>(&this, visit: F): void where F: invokable<def(collider_id, collider_id, bool): bool> {
for p in 0..this.pairs.length {
val pair := &this.pairs[p];
continue if !pair.alive || !pair.touching;
return if !visit(this.named(pair.a), this.named(pair.b), pair.sensor);
}
}
#! Visits each point of each contact touching, as `visit(a, b, point, normal,
#! depth)`, of its two colliders, its normal from the first toward the
#! second, until it gives false, as gizmos draw them.
pub def space::each_contact<F>(&this, visit: F): void where F: invokable<def(collider_id, collider_id, vec3, vec3, f32): bool> {
for k in 0..this.contacts.length {
val c := &this.contacts[k];
continue if !c.alive || !c.touching;
val pair := &this.pairs[c.pair as u64];
val a := collider_id{ index = pair.a, generation = this.colliders[pair.a as u64].generation };
val b := collider_id{ index = pair.b, generation = this.colliders[pair.b as u64].generation };
for i in 0..c.manifold.count {
return if !visit(a, b, c.manifold.points[i].point, c.manifold.normal, c.manifold.points[i].depth);
}
}
}
+123
View File
@@ -0,0 +1,123 @@
#! Contains continuous collision, as in a plane: a dynamic body that moved
#! further in a step than half the least its shapes reach is swept, from where
#! it began the step to where it ended it, against what stands still, a mesh's
#! triangles and a heightfield's among it, and put back where it first comes
#! within the slop of what it met, its velocity kept, so the next step's
#! contacts stop it there. A bullet is swept against moving bodies too, where
#! they ended the step.
import std::containers;
import std::math;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
# A body moving fast enough this step to pass through something thin, and how
# it moved.
struct fast_body {
var body: u32;
var moved: sweep;
}
# Notes a body that moved fast enough to be swept, as the step ends.
def space::note_fast(&mut this, b: u32, moved: sweep): void {
val body := &this.bodies[b as u64];
return if !this.continuous || body.kind != body_kind::dynamic || body.least <= 0;
val travel := (moved.c2 - moved.c1).length + moved.turning() * body.extent;
if travel > 0.5 * body.least {
this.fast.append(fast_body{ body = b, moved = moved });
}
}
# Sweeps the fast bodies, bullets last, so they meet the rest where they end
# up, and places their colliders.
def space::sweep_fast(&mut this): void {
var fast := move(this.fast);
for pass in 0..2u {
for i in 0..fast.length {
val bullet := this.bodies[fast[i].body as u64].bullet;
continue if bullet != (pass == 1);
this.sweep_body(&fast[i]);
this.place_colliders(fast[i].body);
}
}
fast.clear();
this.fast = move(fast);
}
# Puts a fast body back where it first meets what it may pass through.
def space::sweep_body(&mut this, f: &fast_body): void {
val b := f.body;
val bullet := this.bodies[b as u64].bullet;
val target := this.slop;
val tolerance := 0.25 * this.slop;
var first: f32 = 1;
var c := this.bodies[b as u64].colliders;
while c != none {
val own := &this.colliders[c as u64];
if !own.made.sensor && !own.is_mesh() {
val box := own.made.shape.bounds(f.moved.at(0)).merged(own.made.shape.bounds(f.moved.at(1)));
this.tree.query(box, def(leaf: u32, data: u64): bool {
val other := &this.colliders[data];
return true if other.body == b || other.made.sensor;
return true if (other.made.layers & own.made.mask) == 0 || (own.made.layers & other.made.mask) == 0;
val held := &this.bodies[other.body as u64];
return true if held.kind != body_kind::static && (!bullet || held.bullet);
return true if this.joined_apart(b, other.body);
val still := sweep::still(held.at);
if other.is_mesh() {
val surface := &this.meshes[other.mesh as u64];
val start := f.moved.at(0);
val end := f.moved.at(1);
surface.triangles_in(local_box(box, held.at), def(t: u32): bool {
val corners := surface.triangle(t);
# Only a triangle whose plane it reaches by the step's end, from
# in front of it, may it pass through.
val n := held.at.rotate(surface.normal(t));
val offset := n.dot(held.at.apply(corners[0]));
return true if -reach_along(&own.made.shape, end, -n) - offset > target;
return true if reach_along(&own.made.shape, start, n) - offset < 0;
val face := shape::of_hull(hull::triangle(corners[0], corners[1], corners[2]));
val at := impact_of(&face, &still, &own.made.shape, &f.moved, target, tolerance);
if at > 0 && at < first {
first = at;
}
return true;
});
return true;
}
val at := impact_of(&other.made.shape, &still, &own.made.shape, &f.moved, target, tolerance);
if at > 0 && at < first {
first = at;
}
return true;
});
}
c = this.colliders[c as u64].next;
}
return if first >= 1;
val at := f.moved.at(first);
this.bodies[b as u64].at = at;
this.bodies[b as u64].center = at.apply(this.bodies[b as u64].local_center);
}
# When a fast shape first meets what stands still: where they touch as the
# step begins, when a small sphere about the fast shape's middle first meets
# it, so its middle at least never passes through, as Box2D finds it.
def impact_of(still_shape: &shape, still: &sweep, fast: &shape, moved: &sweep, target: f32, tolerance: f32): f32 {
val t := time_of_impact(still_shape, still, fast, moved, target, tolerance);
return t if t > 0;
val core := shape::sphere(0.25 * fast.least_reach(), fast.middle());
return time_of_impact(still_shape, still, &core, moved, target, tolerance);
}
# A box of space as one of a pose's own places, holding it however it's
# turned.
def local_box(box: bounds, at: pose): bounds {
var made := bounds::blank;
for i in 0..8u {
val corner := vec3{ (i & 1) != 0 ? box.max.x : box.min.x, (i & 2) != 0 ? box.max.y : box.min.y, (i & 4) != 0 ? box.max.z : box.min.z };
made = made.including(at.unapply(corner));
}
return made;
}
+140
View File
@@ -0,0 +1,140 @@
#! Contains `crew`: the threads a space solves a step's colors on, besides
#! its caller's, started as a step first asks for more than one and kept until
#! the space closes. Each job is a number of things, taken a block at a time by
#! whichever thread is free, the caller among them, which returns once all are
#! done. Between jobs, as a step's come one after another, the threads spin a
#! little before sleeping, so a job begins in a microsecond rather than the
#! tens a sleeping thread takes to wake, as Box2D's workers spin. They spin by
#! reading what they wait on: `system::pause` is the system's wait for a signal,
#! not the processor's hint that a thread spins.
import system;
import std::containers;
import std::thread;
module malunal::physics3d;
# What the threads are given to do: a function for each range of things.
struct crew_job {
var run: def(*mut u8, u64, u64): void;
var context: *mut u8;
var count: u64;
var block: u64;
}
# What the threads share, on the heap, so it stays where it is.
struct crew_state {
var job: crew_job;
var next: atomic<u64>; # The job's round, high, and the next thing to take, low.
var done: atomic<u64>; # How many things are done.
var round: atomic<u32>; # Counts jobs, and the threads wait on it.
var sleeping: atomic<u32>; # How many threads sleep rather than spin.
var stopping: atomic<u32>;
}
# How many times a thread spins waiting for a job before it sleeps.
const spins: u32 = 200000;
# The threads a space solves on, besides its caller's.
struct crew : owning {
var shared: *mut crew_state;
var threads: vector<thread::handle<void>>;
}
# Starts threads, so there are as many as asked for in all, the caller's among
# them, where there aren't.
def crew::start(&mut this, count: u32): void {
if this.shared != null && this.threads.length + 1 != count as u64 {
this.close();
}
return if this.shared != null || count <= 1;
this.shared = raw_allocate_zeroed(size_of::<crew_state>()) as *mut crew_state;
for _ in 1..count {
var started := thread::spawn_with(work, this.shared) else (_) { break; };
this.threads.append(move(started));
}
}
# Runs a function over ranges of a job's things, a block at a time, on this
# thread and the crew's, and returns once all are done.
def crew::run(&mut this, run: def(*mut u8, u64, u64): void, context: *mut u8, count: u64, block: u64): void {
return if count == 0;
if this.shared == null || count <= block {
run(context, 0, count);
return;
}
val s := &mut through(this.shared);
# The next round's things first, so a thread late from the last takes none
# of this job's by the last's function.
val round := s.round.load(order::relaxed) + 1;
s.next.store((round as u64) << 32, order::release);
s.job = crew_job{ run = run, context = context, count = count, block = block };
s.done.store(0, order::relaxed);
s.round.store(round, order::release);
if s.sleeping.load(order::acquire) > 0 {
_ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF);
}
drain(s, round);
while s.done.load(order::acquire) < count {
}
}
pub def crew::close(&mut this): void {
if this.shared != null {
val s := &mut through(this.shared);
s.stopping.store(1, order::release);
_ = s.round.fetch_add(1, order::release);
_ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF);
this.threads.close();
raw_release(this.shared as *mut u8);
this.shared = null;
}
this.threads.close();
}
# What each thread does: waits for a job, spinning then sleeping, and takes
# its things until none are left.
def work(shared: *mut crew_state): void {
val s := &mut through(shared);
var seen: u32 = 0;
while true {
var round := s.round.load(order::acquire);
var spun: u32 = 0;
while round == seen {
if spun < spins {
spun++;
} else {
_ = s.sleeping.fetch_add(1, order::acq_rel);
if s.round.load(order::acquire) == seen {
_ = system::futex_wait(word_of(&mut s.round), seen, -1);
}
_ = s.sleeping.fetch_sub(1, order::acq_rel);
}
round = s.round.load(order::acquire);
}
seen = round;
return if s.stopping.load(order::acquire) != 0;
drain(s, round);
}
}
# Takes blocks of a round's job, running its function over each, until none
# are left, or the round has passed.
def drain(s: &mut crew_state, round: u32): void {
val job := s.job;
while true {
val held := s.next.load(order::acquire);
return if (held >> 32) as u32 != round;
val at := held & 0xFFFFFFFF;
return if at >= job.count;
val claimed := s.next.compare_exchange_weak(held, held + job.block, order::acq_rel, order::acquire);
continue if claimed is error(_);
val end := at + job.block < job.count ? at + job.block : job.count;
job.run(job.context, at, end);
_ = s.done.fetch_add(end - at, order::acq_rel);
}
}
# The word of an atomic, which the system's futexes wait on.
def word_of(of: &mut atomic<u32>): *mut u32 {
return (address(of) as *mut atomic<u32>) as *mut u32;
}
+451
View File
@@ -0,0 +1,451 @@
#! Contains how far apart two shapes are, their nearest places found as
#! Gilbert, Johnson, and Keerthi's GJK finds them; a shape cast along a motion,
#! to where it first meets another; and the time of impact of two shapes each
#! swept through a step, moving and turning, as continuous collision asks.
#!
#! GJK finds the place of the shapes' difference, every place of the second
#! less every place of the first, nearest the origin, by a tetrahedron of its
#! corners at most, each step adding the corner furthest toward the origin and
#! keeping only the corner, edge, or face the nearest place lies on, as
#! Ericson's Real-Time Collision Detection finds it. It works each shape's
#! core, a sphere's middle, a capsule's segment, or a hull, then takes the radii
#! off, so a sphere's nearest place is as exact as a box's.
#!
#! A cast, and a time of impact, advance conservatively, as Mirtich's do: each
#! moves the shapes as far as the gap between them, over how fast they can
#! close it, says they can't yet meet, so neither ever passes through what it
#! meets.
import std::math;
import malunal::linear;
module malunal::physics3d;
#! How far apart two shapes are, and the places of each nearest the other.
pub struct gap {
#! The places of the first's surface and the second's nearest one another:
#! one place, midway, where they meet.
pub var on_a: vec3;
pub var on_b: vec3;
#! The direction from the first toward the second, of length 1, or none
#! where they meet.
pub var normal: vec3;
#! How far apart their surfaces are: 0 where they meet.
pub var distance: f32;
}
#! Where a shape cast along a motion first met another: how far along the
#! motion, as a fraction of it, the place of the other's surface it met, and
#! which way that surface faces, toward the shape cast.
pub struct cast_hit {
pub var fraction: f32;
pub var point: vec3;
pub var normal: vec3;
}
# A corner of the shapes' difference, of a point of each, and its weight in
# the nearest place.
struct corner {
var on_a: vec3;
var on_b: vec3;
var w: vec3;
var weight: f32;
var ia: u32;
var ib: u32;
}
# As many as four corners, the nearest place lying among them.
struct simplex {
var corners: corner[4];
var count: u32;
}
# A point of a shape's core: a sphere's middle, a capsule's end, or a hull's
# corner.
def core_point(s: &shape, i: u32): vec3 {
return s.as_hull().point(i) if s.kind == shape_kind::hull;
return i == 0 ? s.a : s.b;
}
# The point of a shape's core furthest along a direction of space, where a
# pose places it.
def support_of(s: &shape, at: &pose, direction: vec3): u32 {
val d := at.unrotate(direction);
return s.as_hull().support(d) if s.kind == shape_kind::hull;
return 1 if s.kind == shape_kind::capsule && (s.b - s.a).dot(d) > 0;
return 0;
}
def corner_of(a: &shape, at_a: &pose, ia: u32, b: &shape, at_b: &pose, ib: u32): corner {
val pa := at_a.apply(core_point(a, ia));
val pb := at_b.apply(core_point(b, ib));
return corner{ on_a = pa, on_b = pb, w = pb - pa, weight = 1, ia = ia, ib = ib };
}
# Keeps one corner of the simplex.
def keep_one(x: &mut simplex, i: u32): void {
val kept := x.corners[i];
x.corners[0] = kept;
x.corners[0].weight = 1;
x.count = 1;
}
# Keeps two corners of the simplex, weighted so.
def keep_two(x: &mut simplex, i: u32, j: u32, wi: f32, wj: f32): void {
val first := x.corners[i];
val second := x.corners[j];
x.corners[0] = first;
x.corners[0].weight = wi;
x.corners[1] = second;
x.corners[1].weight = wj;
x.count = 2;
}
# The nearest place of a segment of the difference to the origin.
def solve2(x: &mut simplex): void {
val a := x.corners[0].w;
val ab := x.corners[1].w - a;
val along := -a.dot(ab);
if along <= 0 {
keep_one(x, 0);
return;
}
val length := ab.dot(ab);
if along >= length || length <= tiny * tiny {
keep_one(x, 1);
return;
}
val t := along / length;
keep_two(x, 0, 1, 1 - t, t);
}
# The nearest place of a triangle of the difference to the origin, by which of
# its corners, edges, or face it's on, as Ericson finds it.
def solve3(x: &mut simplex): void {
val a := x.corners[0].w;
val b := x.corners[1].w;
val c := x.corners[2].w;
val ab := b - a;
val ac := c - a;
val d1 := -ab.dot(a);
val d2 := -ac.dot(a);
if d1 <= 0 && d2 <= 0 {
keep_one(x, 0);
return;
}
val d3 := -ab.dot(b);
val d4 := -ac.dot(b);
if d3 >= 0 && d4 <= d3 {
keep_one(x, 1);
return;
}
val vc := d1 * d4 - d3 * d2;
if vc <= 0 && d1 >= 0 && d3 <= 0 {
val v := d1 / (d1 - d3);
keep_two(x, 0, 1, 1 - v, v);
return;
}
val d5 := -ab.dot(c);
val d6 := -ac.dot(c);
if d6 >= 0 && d5 <= d6 {
keep_one(x, 2);
return;
}
val vb := d5 * d2 - d1 * d6;
if vb <= 0 && d2 >= 0 && d6 <= 0 {
val w := d2 / (d2 - d6);
keep_two(x, 0, 2, 1 - w, w);
return;
}
val va := d3 * d6 - d5 * d4;
if va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0 {
val w := (d4 - d3) / ((d4 - d3) + (d5 - d6));
keep_two(x, 1, 2, 1 - w, w);
return;
}
# A triangle of no area, its corners in a line: its nearest edge.
if ab.cross(ac).length_squared <= 1e-12 * ab.length_squared * ac.length_squared {
nearest_edge(x);
return;
}
val inv := 1 / (va + vb + vc);
val v := vb * inv;
val w := vc * inv;
x.corners[0].weight = 1 - v - w;
x.corners[1].weight = v;
x.corners[2].weight = w;
x.count = 3;
}
# Keeps the edge of three corners nearest the origin, as `solve2` keeps it.
def nearest_edge(x: &mut simplex): void {
val pairs: u32[6] = [0, 1, 0, 2, 1, 2];
var best := 1e30f;
var kept := simplex{};
for k in 0..3u {
var edge := simplex{ count = 2 };
edge.corners[0] = x.corners[pairs[k * 2]];
edge.corners[1] = x.corners[pairs[k * 2 + 1]];
solve2(&mut edge);
var v := vec3::zero;
for q in 0..edge.count {
v = v + edge.corners[q].w * edge.corners[q].weight;
}
if v.length_squared < best {
best = v.length_squared;
kept = edge;
}
}
x.corners = kept.corners;
x.count = kept.count;
}
# Six times the signed volume of a tetrahedron.
def volume(a: vec3, b: vec3, c: vec3, d: vec3): f32 {
return (b - a).dot((c - a).cross(d - a));
}
# The nearest place of a tetrahedron of the difference to the origin: within
# it, or on the nearest of the faces it's outside of.
def solve4(x: &mut simplex): void {
val w: vec3[4] = [x.corners[0].w, x.corners[1].w, x.corners[2].w, x.corners[3].w];
# Each face, and the corner across from it.
val faces: u32[16] = [0, 1, 2, 3, 0, 2, 3, 1, 0, 3, 1, 2, 1, 3, 2, 0];
var best := 1e30f;
var nearest := simplex{};
var outside := false;
for f in 0..4u {
val i := faces[f * 4];
val j := faces[f * 4 + 1];
val k := faces[f * 4 + 2];
val across := faces[f * 4 + 3];
val n := (w[j] - w[i]).cross(w[k] - w[i]);
val origin_side := -n.dot(w[i]);
val other_side := n.dot(w[across] - w[i]);
# The origin's beyond this face where it's on the side away from the
# corner across from it, or the tetrahedron is flat, the corner across
# nearly in the face's plane, for as large as the face is.
val flat := math::abs(other_side) <= 1e-5 * n.length * (w[across] - w[i]).length;
if origin_side * other_side < 0 || flat {
outside = true;
var face := simplex{ count = 3 };
face.corners[0] = x.corners[i];
face.corners[1] = x.corners[j];
face.corners[2] = x.corners[k];
solve3(&mut face);
var v := vec3::zero;
for q in 0..face.count {
v = v + face.corners[q].w * face.corners[q].weight;
}
if v.length_squared < best {
best = v.length_squared;
nearest = face;
}
}
}
if outside {
x.corners = nearest.corners;
x.count = nearest.count;
return;
}
val whole := volume(w[0], w[1], w[2], w[3]);
val o := vec3::zero;
x.corners[0].weight = volume(o, w[1], w[2], w[3]) / whole;
x.corners[1].weight = volume(w[0], o, w[2], w[3]) / whole;
x.corners[2].weight = volume(w[0], w[1], o, w[3]) / whole;
x.corners[3].weight = volume(w[0], w[1], w[2], o) / whole;
x.count = 4;
}
# Keeps the corners of a simplex the nearest place lies among, weighted.
def solve(x: &mut simplex): void {
if x.count == 2 {
solve2(x);
} else if x.count == 3 {
solve3(x);
} else if x.count == 4 {
solve4(x);
}
}
#! How far apart two shapes are, each where its pose places it, and the places
#! of each nearest the other: none apart where they meet.
pub def gap_between(a: &shape, at_a: pose, b: &shape, at_b: pose): gap {
var x := simplex{ count = 1 };
x.corners[0] = corner_of(a, &at_a, 0, b, &at_b, 0);
var last := 1e30f;
for iteration in 0..32u {
solve(&mut x);
# Four corners hold the origin: the cores overlap.
if x.count == 4 {
break;
}
var v := vec3::zero;
for i in 0..x.count {
v = v + x.corners[i].w * x.corners[i].weight;
}
val squared := v.length_squared;
# Nearer no more, as rounding among large places may leave it, adding
# the same face's corners again: it's found.
if squared < tiny * tiny || squared >= last {
break;
}
last = squared;
val ia := support_of(a, &at_a, v);
val ib := support_of(b, &at_b, -v);
val next := corner_of(a, &at_a, ia, b, &at_b, ib);
# No corner further toward the origin than the nearest place: it's found.
if squared - v.dot(next.w) <= 1e-6 * squared {
break;
}
var again := false;
for i in 0..x.count {
if x.corners[i].ia == ia && x.corners[i].ib == ib {
again = true;
}
}
if again {
break;
}
x.corners[x.count] = next;
x.count++;
}
solve(&mut x);
var on_a := vec3::zero;
var on_b := vec3::zero;
for i in 0..x.count {
on_a = on_a + x.corners[i].on_a * x.corners[i].weight;
on_b = on_b + x.corners[i].on_b * x.corners[i].weight;
}
if x.count == 4 {
on_b = on_a;
}
val between := on_b - on_a;
val cores := between.length;
val reach := a.radius + b.radius;
if cores > reach && cores > tiny {
val normal := between * (1 / cores);
return gap{ on_a = on_a + normal * a.radius, on_b = on_b - normal * b.radius, normal = normal, distance = cores - reach };
}
val normal := cores > tiny ? between * (1 / cores) : vec3::zero;
val middle := ((on_a + normal * a.radius) + (on_b - normal * b.radius)) * 0.5;
return gap{ on_a = middle, on_b = middle, normal = normal, distance = 0 };
}
#! Where a shape, `b`, cast along a motion of space from where its pose places
#! it, first meets another, `a`, which stays where its pose places it: within
#! `tolerance` of its surface, a little short of touching, so what's moved there
#! doesn't overlap. Nothing where it doesn't meet it within the motion; a
#! fraction of 0 where they meet as it begins, its normal back along the
#! motion.
pub def shape_cast(a: &shape, at_a: pose, b: &shape, at_b: pose, motion: vec3, tolerance: f32 = 0.0025): maybe<cast_hit> {
val target := 0.5 * tolerance;
var t: f32 = 0;
var at := at_b;
for iteration in 0..30u {
val g := gap_between(a, at_a, b, at);
if g.distance <= tolerance {
val back := g.distance > 0 ? g.normal : -motion.normalized();
return cast_hit{ fraction = t, point = g.on_a, normal = back };
}
val approach := -motion.dot(g.normal);
return nothing{} if approach <= tiny;
t += (g.distance - target) / approach;
return nothing{} if t > 1;
at = pose{ at = at_b.at + motion * t, turn = at_b.turn };
}
val g := gap_between(a, at_a, b, at);
return cast_hit{ fraction = t, point = g.on_a, normal = g.normal };
}
#! How a body moves through a step: its center of mass, of its own places,
#! where that center begins and ends the step, and how it's turned as it begins
#! and ends it, turning the shorter way between.
pub struct sweep {
pub var local_center: vec3;
pub var c1: vec3;
pub var c2: vec3;
pub var q1 := quat::identity;
pub var q2 := quat::identity;
}
#! A sweep standing still where a pose places a body.
pub def sweep::still(at: pose, local_center: vec3 = vec3::zero): sweep {
val center := at.apply(local_center);
return sweep{ local_center = local_center, c1 = center, c2 = center, q1 = at.turn, q2 = at.turn };
}
#! Where it places its body a fraction of the way through the step.
pub def sweep::at(&this, t: f32): pose {
val turn := this.q1.slerp(this.q2, t);
val center := this.c1.lerp(this.c2, t);
return pose{ at = center - turn * this.local_center, turn = turn };
}
# How far it turns through the step, in radians.
def sweep::turning(&this): f32 {
val cosine := math::min(math::abs(this.q1.dot(this.q2)), 1f);
return 2 * math::acos(cosine);
}
# How far a shape's surface reaches from a place of its own.
def reach_from(s: &shape, center: vec3): f32 {
if s.kind == shape_kind::hull {
var most: f32 = 0;
val h := s.as_hull();
for i in 0..h.count {
most = math::max(most, (h.point(i) - center).length);
}
return most;
}
return math::max((s.a - center).length, (s.b - center).length) + s.radius;
}
#! When, as a fraction of the step, two shapes each swept through it first come
#! within `target` of one another, to within `tolerance`, as their sweeps move
#! and turn them: 1 where they don't. Each moves no further than they can, as
#! fast as they close and turn, without meeting, so what's found is never past
#! where they meet.
pub def time_of_impact(a: &shape, sa: &sweep, b: &shape, sb: &sweep, target: f32, tolerance: f32): f32 {
val turn_a := sa.turning() * reach_from(a, sa.local_center);
val turn_b := sb.turning() * reach_from(b, sb.local_center);
val moved := (sb.c2 - sb.c1) - (sa.c2 - sa.c1);
var t: f32 = 0;
for iteration in 0..50u {
val g := gap_between(a, sa.at(t), b, sb.at(t));
return t if g.distance <= target + tolerance;
val closing := -moved.dot(g.normal) + turn_a + turn_b;
return 1 if closing <= tiny;
t += (g.distance - target) / closing;
return 1 if t >= 1;
}
return t;
}
# How far a shape reaches along a direction of space, where a pose places it.
def reach_along(s: &shape, at: pose, direction: vec3): f32 {
if s.kind == shape_kind::hull {
val h := s.as_hull();
return direction.dot(at.apply(h.point(h.support(at.unrotate(direction)))));
}
return math::max(direction.dot(at.apply(s.a)), direction.dot(at.apply(s.b))) + s.radius;
}
# The middle of a shape: a sphere's, a capsule's, or a hull's center.
def shape::middle(&this): vec3 {
return this.as_hull().center if this.kind == shape_kind::hull;
return (this.a + this.b) * 0.5;
}
# How far a shape reaches at least from its middle: a sphere's or a capsule's
# radius, or the nearest of a hull's faces, as a body may move without passing
# through what's in its way.
def shape::least_reach(&this): f32 {
return this.radius if this.kind != shape_kind::hull;
val h := this.as_hull();
var least := 1e30f;
for f in 0..h.faces {
least = math::min(least, h.offset(f) - h.normal(f).dot(h.center));
}
return least;
}
+255
View File
@@ -0,0 +1,255 @@
#! Contains how a step solves sliders, ball joints' limits, and six-way joints,
#! as Box2D's soft step solves the rest: each way a joint holds is a row of its
#! own, pushed toward holding it, softly where `use_bias` asks, a limit only as
#! far as closes it, as a speculative contact.
#!
#! A joint's turn is taken within its frame as a twist about its x axis and a
#! swing after it, as Jolt's swing-twist joints take it: a ball joint's swing is
#! held within its cone, and a six-way joint's swing about y and z each within
#! its own limits, as a pyramid.
import std::math;
import malunal::linear;
module malunal::physics3d;
# A joint's frame and levers as its bodies have moved and turned since the step
# began: its axes in space, from `a`'s anchor to `b`'s, and the turn of `b`'s
# frame within `a`'s, as a twist and a swing.
struct joint_frame {
var x: vec3; # Of `a`'s frame.
var y: vec3;
var z: vec3;
var twist_x: vec3; # `b`'s frame's x, which it twists about,
var swing_y: vec3; # and `a`'s y and z across it, which it swings about.
var swing_z: vec3;
var ra: vec3;
var rb: vec3;
var d: vec3;
var twist: f32;
var swung_y: f32;
var swung_z: f32;
}
def frame_of(r: &joint_record, sa: &body_state, sb: &body_state): joint_frame {
val fa := ((sa.dq * r.qa).normalized() * r.made.frame_a).normalized();
val fb := ((sb.dq * r.qb).normalized() * r.made.frame_b).normalized();
val ra := sa.dq * r.ra;
val rb := sb.dq * r.rb;
val x := fa * vec3::right;
val y := fa * vec3::up;
val z := fa * vec3::back;
val bx := fb * vec3::right;
var made := joint_frame{
x = x, y = y, z = z, twist_x = bx,
swing_y = (y - bx * y.dot(bx)).normalized(), swing_z = (z - bx * z.dot(bx)).normalized(),
ra = ra, rb = rb, d = (sb.dp - sa.dp) + r.delta_center + (rb - ra),
};
# `b`'s frame within `a`'s, as a swing after a twist about x.
var q := (fa.inverse() * fb).normalized();
if q.w < 0 {
q = quat{ -q.x, -q.y, -q.z, -q.w };
}
val about := math::sqrt(q.x * q.x + q.w * q.w);
var twist := quat::identity;
if about > tiny {
twist = quat{ q.x / about, 0, 0, q.w / about };
made.twist = 2 * math::atan2(q.x, q.w);
}
val swing := q * twist.inverse();
val across := math::sqrt(swing.y * swing.y + swing.z * swing.z);
if across > tiny {
val angle := 2 * math::atan2(across, math::abs(swing.w));
val sign := swing.w < 0 ? -1f : 1f;
made.swung_y = sign * angle * swing.y / across;
made.swung_z = sign * angle * swing.z / across;
}
return made;
}
# How hard it is to turn the two apart about an axis of space.
def turning_mass(axis: vec3, ia: mat3, ib: mat3): f32 {
val k := axis.dot((ia + ib) * axis);
return k > 0 ? 1 / k : 0f;
}
# How hard it is to push the two apart along a direction of space, `a` turning
# about the place of `b`'s anchor, as a slider's axis is `a`'s.
def sliding_mass(u: vec3, f: &joint_frame, r: &joint_record, ia: mat3, ib: mat3): f32 {
val la := (f.ra + f.d).cross(u);
val lb := f.rb.cross(u);
val k := r.ma + r.mb + la.dot(ia * la) + lb.dot(ib * lb);
return k > 0 ? 1 / k : 0f;
}
# How fast the two part along a direction of space, as a slider's.
def sliding_speed(u: vec3, f: &joint_frame, sa: &body_state, sb: &body_state): f32 {
return u.dot(sb.v - sa.v) + f.rb.cross(u).dot(sb.w) - (f.ra + f.d).cross(u).dot(sa.w);
}
# Pushes the two apart by an impulse along a slider's direction.
def slide_apart(r: &joint_record, f: &joint_frame, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, p: vec3): void {
sa.v = sa.v - p * r.ma;
sa.w = sa.w - ia * (f.ra + f.d).cross(p);
sb.v = sb.v + p * r.mb;
sb.w = sb.w + ib * f.rb.cross(p);
}
# A row held still: its impulse toward undoing `c`, where it's drifted, at
# `cdot`, how fast it drifts.
def held_impulse(c: f32, cdot: f32, mass: f32, held: f32, soft: &softness, use_bias: bool): f32 {
if !use_bias {
return -mass * cdot;
}
return -mass * soft.mass_scale * (cdot + soft.bias_rate * c) - soft.impulse_scale * held;
}
# Each way of a six-way joint, as its frame lies now: its direction, and how
# far it's moved or turned.
def way_of(f: &joint_frame, k: u32): vec3 {
return k == 0 ? f.x : (k == 1 ? f.y : f.z) if k < 3;
return k == 3 ? f.twist_x : (k == 4 ? f.swing_y : f.swing_z);
}
def amount_of(f: &joint_frame, k: u32): f32 {
return f.d.dot(way_of(f, k)) if k < 3;
return k == 3 ? f.twist : (k == 4 ? f.swung_y : f.swung_z);
}
# The impulses a slider, a limited ball joint, or a six-way joint ended the last
# substep with, given again, beyond those `warm_joints` gives every joint.
def warm_free(r: &joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3): void {
val f := frame_of(r, sa, sb);
if r.made.kind == joint_kind::slider {
val axial := r.spring_impulse + r.motor_impulse + r.lower_impulse - r.upper_impulse;
slide_apart(r, &f, sa, sb, ia, ib, f.x * axial + f.y * r.held[1] + f.z * r.held[2]);
} else if r.made.kind == joint_kind::ball {
turn_apart(sa, sb, ia, ib, cone_axis(r, &f) * -r.held[0] + f.twist_x * (r.held[1] - r.held[2]));
} else {
for k in 0..6u {
val total := r.held[k] + r.held[6 + k] - r.held[12 + k] + r.held[18 + k];
continue if total == 0;
if k < 3 {
slide_apart(r, &f, sa, sb, ia, ib, way_of(&f, k as u32) * total);
} else {
turn_apart(sa, sb, ia, ib, way_of(&f, k as u32) * total);
}
}
}
}
# The axis a ball joint's swing turns about, in space, from `a`'s frame's x to
# `b`'s.
def cone_axis(r: &joint_record, f: &joint_frame): vec3 {
val across := f.x.cross(f.twist_x);
return across.length_squared > tiny * tiny ? across.normalized() : vec3::zero;
}
# A slider: its turn held as a fixed joint's, its anchors held to its axis,
# and along the axis its motor, spring, and limits.
def solve_slider(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void {
solve_fixed_turn(r, sa, sb, ia, ib, use_bias);
val made := &r.made;
val f := frame_of(r, sa, sb);
val axial_mass := sliding_mass(f.x, &f, r, ia, ib);
val translation := f.d.dot(f.x);
if made.motor {
val most := h * made.max_motor_force;
val held := r.motor_impulse;
r.motor_impulse = math::clamp(held + axial_mass * (made.motor_speed - sliding_speed(f.x, &f, sa, sb)), -most, most);
slide_apart(r, &f, sa, sb, ia, ib, f.x * (r.motor_impulse - held));
}
if made.spring && made.hertz > 0 {
val impulse := -r.spring_soft.mass_scale * axial_mass * (sliding_speed(f.x, &f, sa, sb) + r.spring_soft.bias_rate * translation) - r.spring_soft.impulse_scale * r.spring_impulse;
r.spring_impulse += impulse;
slide_apart(r, &f, sa, sb, ia, ib, f.x * impulse);
}
if made.limit {
val lower := limit_impulse(translation - made.lower, sliding_speed(f.x, &f, sa, sb), axial_mass, r.lower_impulse, soft, 1 / h, use_bias);
r.lower_impulse += lower;
slide_apart(r, &f, sa, sb, ia, ib, f.x * lower);
val upper := limit_impulse(made.upper - translation, -sliding_speed(f.x, &f, sa, sb), axial_mass, r.upper_impulse, soft, 1 / h, use_bias);
r.upper_impulse += upper;
slide_apart(r, &f, sa, sb, ia, ib, f.x * -upper);
}
# Held to its axis: neither of the directions across it.
for k in 1..3u {
val u := k == 1 ? f.y : f.z;
val impulse := held_impulse(f.d.dot(u), sliding_speed(u, &f, sa, sb), sliding_mass(u, &f, r, ia, ib), r.held[k], soft, use_bias);
r.held[k] += impulse;
slide_apart(r, &f, sa, sb, ia, ib, u * impulse);
}
}
# A ball joint's limits: its swing within its cone, its twist between its
# lower and upper.
def solve_cone(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void {
val f := frame_of(r, sa, sb);
val made := &r.made;
val swung := math::atan2(f.x.cross(f.twist_x).length, f.x.dot(f.twist_x));
val axis := cone_axis(r, &f);
if axis.length_squared > 0 {
val swing := limit_impulse(made.cone - swung, (sa.w - sb.w).dot(axis), turning_mass(axis, ia, ib), r.held[0], soft, 1 / h, use_bias);
r.held[0] += swing;
turn_apart(sa, sb, ia, ib, axis * -swing);
}
val mass := turning_mass(f.twist_x, ia, ib);
val lower := limit_impulse(f.twist - made.lower, (sb.w - sa.w).dot(f.twist_x), mass, r.held[1], soft, 1 / h, use_bias);
r.held[1] += lower;
turn_apart(sa, sb, ia, ib, f.twist_x * lower);
val upper := limit_impulse(made.upper - f.twist, (sa.w - sb.w).dot(f.twist_x), mass, r.held[2], soft, 1 / h, use_bias);
r.held[2] += upper;
turn_apart(sa, sb, ia, ib, f.twist_x * -upper);
}
# A six-way joint: each way driven by its motor, held within its limits, or
# held still, its turns first, then its place; three places locked together
# are held as a ball joint holds its anchors.
def solve_six(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void {
val made := &r.made;
val point := made.holds[0] == axis_hold::locked && made.holds[1] == axis_hold::locked && made.holds[2] == axis_hold::locked;
var k: u32 = 3;
while true {
val f := frame_of(r, sa, sb);
val u := way_of(&f, k);
val amount := amount_of(&f, k);
val sliding := k < 3;
val mass := sliding ? sliding_mass(u, &f, r, ia, ib) : turning_mass(u, ia, ib);
val speed := sliding ? sliding_speed(u, &f, sa, sb) : (sb.w - sa.w).dot(u);
var push: f32 = 0;
if made.holds[k] == axis_hold::locked {
if !sliding || !point {
push = held_impulse(amount, speed, mass, r.held[k], soft, use_bias);
r.held[k] += push;
}
} else {
if made.forces[k] > 0 {
val most := h * made.forces[k];
val before := r.held[18 + k];
r.held[18 + k] = math::clamp(before + mass * (made.drives[k] - speed), -most, most);
push += r.held[18 + k] - before;
}
if made.holds[k] == axis_hold::limited {
val lower := limit_impulse(amount - made.lows[k], speed, mass, r.held[6 + k], soft, 1 / h, use_bias);
r.held[6 + k] += lower;
val upper := limit_impulse(made.highs[k] - amount, -speed - lower / math::max(mass, tiny), mass, r.held[12 + k], soft, 1 / h, use_bias);
r.held[12 + k] += upper;
push += lower - upper;
}
}
if push != 0 {
if sliding {
slide_apart(r, &f, sa, sb, ia, ib, u * push);
} else {
turn_apart(sa, sb, ia, ib, u * push);
}
}
# The turns, 3 to 5, then the places, 0 to 2.
k = k == 5 ? 0 as u32 : k + 1;
if k == 3 {
break;
}
}
if point {
solve_point(r, sa, sb, ia, ib, soft, use_bias);
}
}
+255
View File
@@ -0,0 +1,255 @@
#! Contains `heightfield`, a level's ground as heights on a grid, as terrain is
#! painted: two triangles of each square of four heights, made as they're met
#! rather than kept, so a field of a million heights costs their floats alone.
#! A space keeps one as a `triangle_mesh` keeps its triangles, met a triangle
#! at a time, its edges two triangles share flat or hollow passed over as a
#! mesh's are, so a body rolls across it as along one surface.
import std::containers;
import std::math;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
#! Heights on a grid along x and z, as a terrain's ground: `columns` along x by
#! `rows` along z, `cell` apart each way, the first at its origin.
pub struct heightfield {
var _columns: u32;
var _rows: u32;
var _cell: vec2;
var _heights: vector<f32>;
var _low: f32;
var _high: f32;
}
#! The heights of a grid of `columns` along x by `rows` along z, a row of
#! columns after another, from the origin toward +z, each `cell` apart along x
#! and z: those missing are 0. Of fewer than two each way, it holds no
#! triangles.
pub def heightfield::new(columns: u32, rows: u32, heights: span<f32>, cell: vec2 = vec2{ 1, 1 }): heightfield {
var made := heightfield{ _columns = columns, _rows = rows, _cell = cell, _heights = vector::<f32>::new() };
val count := columns as u64 * rows as u64;
for i in 0..count {
made._heights.append(i < heights.length ? heights[i] : 0f);
}
if count > 0 {
made._low = made._heights[0];
made._high = made._heights[0];
for i in 1..count {
made._low = math::min(made._low, made._heights[i]);
made._high = math::max(made._high, made._heights[i]);
}
}
return made;
}
pub val heightfield::columns: u32 {
get => this._columns;
}
pub val heightfield::rows: u32 {
get => this._rows;
}
#! How far apart its heights are along x, and along z.
pub val heightfield::cell: vec2 {
get => this._cell;
}
#! How many triangles it has: two of each square of four heights.
pub val heightfield::length: u64 {
get => this._columns < 2 || this._rows < 2 ? 0 as u64 : (this._columns - 1) as u64 * (this._rows - 1) as u64 * 2;
}
#! The height at a column and row.
pub def heightfield::height(&this, column: u32, row: u32): f32 {
return this._heights[row as u64 * this._columns as u64 + column as u64];
}
#! The ground's height above a place of its own, between its heights, as its
#! triangles lie: nothing beyond it.
pub def heightfield::height_at(&this, x: f32, z: f32): maybe<f32> {
return nothing{} if this.length == 0;
val fx := x / this._cell.x;
val fz := z / this._cell.y;
return nothing{} if fx < 0 || fz < 0 || fx > (this._columns - 1) as f32 || fz > (this._rows - 1) as f32;
val i := math::min(fx as u32, this._columns - 2);
val j := math::min(fz as u32, this._rows - 2);
val u := fx - i as f32;
val v := fz - j as f32;
val h00 := this.height(i, j);
val h10 := this.height(i + 1, j);
val h01 := this.height(i, j + 1);
val h11 := this.height(i + 1, j + 1);
return h00 + (h10 - h00) * u + (h01 - h00) * v if u + v <= 1;
return h11 + (h01 - h11) * (1 - u) + (h10 - h11) * (1 - v);
}
#! The box holding it, of its own places.
pub val heightfield::bounds: bounds {
get => bounds{
vec3{ 0, this._low, 0 },
vec3{ math::max(this._columns, 1 as u32) as f32 * this._cell.x - this._cell.x, this._high, math::max(this._rows, 1 as u32) as f32 * this._cell.y - this._cell.y },
};
}
# The place of a height, of its own places.
def heightfield::corner(&this, i: u32, j: u32): vec3 {
return vec3{ i as f32 * this._cell.x, this.height(i, j), j as f32 * this._cell.y };
}
# Triangle `t` is of the square at column `i` and row `j`, its first half or
# its second.
def heightfield::triangle_of(&this, i: u32, j: u32, half: u32): u32 {
return (j * (this._columns - 1) + i) * 2 + half;
}
#! A triangle's corners, counterclockwise as they're seen from above: of each
#! square, the half by its first corner, then the half by its last.
pub def heightfield::triangle(&this, t: u32): vec3[3] {
val square := t / 2;
val i := square % (this._columns - 1);
val j := square / (this._columns - 1);
return [this.corner(i, j), this.corner(i, j + 1), this.corner(i + 1, j)] if t % 2 == 0;
return [this.corner(i + 1, j), this.corner(i, j + 1), this.corner(i + 1, j + 1)];
}
#! The way a triangle faces.
pub def heightfield::normal(&this, t: u32): vec3 {
val c := this.triangle(t);
return (c[1] - c[0]).cross(c[2] - c[0]).normalized();
}
# Which of a triangle's edges push as they meet, a bit each, as a mesh's: those
# its neighbor shares flat or hollow don't.
def heightfield::active(&this, t: u32): u8 {
val square := t / 2;
val i := square % (this._columns - 1);
val j := square / (this._columns - 1);
val c := this.triangle(t);
val n := this.normal(t);
var bits: u8 = 7;
for k in 0..3u {
var other: i64 = -1;
var off := vec3::zero;
if t % 2 == 0 {
if k == 0 && i > 0 {
other = this.triangle_of(i - 1, j, 1) as i64;
off = this.corner(i - 1, j + 1);
} else if k == 1 {
other = this.triangle_of(i, j, 1) as i64;
off = this.corner(i + 1, j + 1);
} else if k == 2 && j > 0 {
other = this.triangle_of(i, j - 1, 1) as i64;
off = this.corner(i + 1, j - 1);
}
} else {
if k == 0 {
other = this.triangle_of(i, j, 0) as i64;
off = this.corner(i, j);
} else if k == 1 && j + 2 < this._rows {
other = this.triangle_of(i, j + 1, 0) as i64;
off = this.corner(i, j + 2);
} else if k == 2 && i + 2 < this._columns {
other = this.triangle_of(i + 1, j, 0) as i64;
off = this.corner(i + 2, j);
}
}
continue if other < 0;
val ridged := n.dot(off - c[k]) < 0 && n.dot(this.normal(other as u32)) < ridge;
if !ridged {
bits = without_bit(bits, k as u64);
}
}
return bits;
}
# The columns or rows of squares a span of its own places reaches, within it.
def square_span(low: f32, high: f32, size: f32, squares: u32): i64[2] {
val first := math::max(math::floor(low / size) as i64, (0 as i64));
val last := math::min(math::floor(high / size) as i64, squares as i64 - 1);
return [first, last];
}
#! Visits each triangle whose square a box of its own places reaches, as
#! `visit(triangle)`, until it gives false.
pub def heightfield::triangles_in<F>(&this, box: bounds, visit: F): void where F: invokable<def(u32): bool> {
return if this.length == 0 || box.max.y < this._low || box.min.y > this._high;
val xs := square_span(box.min.x, box.max.x, this._cell.x, this._columns - 1);
val zs := square_span(box.min.z, box.max.z, this._cell.y, this._rows - 1);
var j := zs[0];
while j <= zs[1] {
var i := xs[0];
while i <= xs[1] {
for half in 0..2u {
return if !visit(this.triangle_of(i as u32, j as u32, half as u32));
}
i++;
}
j++;
}
}
# Where a ray, of its own places, first meets a triangle, passed from square to
# square along x and z as Amanatides and Woo pass one: the first square it
# meets a triangle of holds the nearest.
def heightfield::ray_cast(&this, o: vec3, d: vec3, reach: f32): maybe<mesh_hit> {
return nothing{} if this.length == 0;
val box := this.bounds;
var enter: f32 = 0;
var leave := reach;
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];
val os: f32[3] = [o.x, o.y, o.z];
val ds: f32[3] = [d.x, d.y, d.z];
for k in 0..3u {
if math::abs(ds[k]) < tiny {
return nothing{} if os[k] < lows[k] || os[k] > highs[k];
} else {
val t1 := (lows[k] - os[k]) / ds[k];
val t2 := (highs[k] - os[k]) / ds[k];
enter = math::max(enter, math::min(t1, t2));
leave = math::min(leave, math::max(t1, t2));
return nothing{} if enter > leave;
}
}
val start := o + d * enter;
val squares_x := (this._columns - 1) as i64;
val squares_z := (this._rows - 1) as i64;
var i := math::clamp(math::floor(start.x / this._cell.x) as i64, (0 as i64), squares_x - 1);
var j := math::clamp(math::floor(start.z / this._cell.y) as i64, (0 as i64), squares_z - 1);
val step_x: i64 = d.x > 0 ? 1 : -1;
val step_z: i64 = d.z > 0 ? 1 : -1;
val far := 1e30f;
var next_x := math::abs(d.x) < tiny ? far : (((i + (d.x > 0 ? (1 as i64) : (0 as i64))) as f32) * this._cell.x - o.x) / d.x;
var next_z := math::abs(d.z) < tiny ? far : (((j + (d.z > 0 ? (1 as i64) : (0 as i64))) as f32) * this._cell.y - o.z) / d.z;
val across_x := math::abs(d.x) < tiny ? far : this._cell.x / math::abs(d.x);
val across_z := math::abs(d.z) < tiny ? far : this._cell.y / math::abs(d.z);
while i >= 0 && j >= 0 && i < squares_x && j < squares_z {
var best: maybe<mesh_hit> = nothing{};
var nearest := reach;
for half in 0..2u {
val t := this.triangle_of(i as u32, j as u32, half as u32);
val c := this.triangle(t);
if ray_triangle(o, d, c[0], c[1], c[2]) is some(along) {
if along <= nearest {
nearest = along;
val n := this.normal(t);
best = mesh_hit{ distance = along, point = o + d * along, normal = n.dot(d) <= 0 ? n : -n, triangle = t };
}
}
}
return best if best is some(_);
if math::min(next_x, next_z) > leave {
break;
}
if next_x < next_z {
i += step_x;
next_x += across_x;
} else {
j += step_z;
next_z += across_z;
}
}
return nothing{};
}
+509
View File
@@ -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.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.span);
}
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.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;
}
+324
View File
@@ -0,0 +1,324 @@
#! Contains how a step solves joints, as Box2D's soft step solves them: each
#! is prepared as the step begins, begins each substep with the impulses it
#! ended the last with, and pushes its bodies' velocities toward holding it,
#! undoing drift softly where `use_bias` asks.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
def space::prepare_joints(&mut this, s: &mut solver_scratch, h: f32): void {
s.joints.clear();
s.joint_soft = soft_of(this.joint_hertz, this.joint_damping, h);
for j in 0..this.joints.length {
continue if !this.joints[j].alive;
var r := this.joints[j];
val a := &this.bodies[r.body_a as u64];
val b := &this.bodies[r.body_b as u64];
continue if a.slot == 0 && b.slot == 0;
s.joints.append(j as u32);
r.slot_a = a.slot;
r.slot_b = b.slot;
r.ma = a.inv_mass;
r.mb = b.inv_mass;
r.qa = a.at.turn;
r.qb = b.at.turn;
r.ra = a.at.turn * (r.made.anchor_a - a.local_center);
r.rb = b.at.turn * (r.made.anchor_b - b.local_center);
r.delta_center = b.center - a.center;
val ia := s.inertias[a.slot as u64];
val ib := s.inertias[b.slot as u64];
if r.made.kind == joint_kind::distance {
r.axial_mass = mass_along((r.rb - r.ra + r.delta_center).normalized(), r.ra, r.rb, r.ma, r.mb, ia, ib);
} else {
# A hinge turns each body about its axis through the anchor, not about
# its center, as the point it's held at keeps it: how hard that is is its
# moment about the axis, and its mass as far from the axis as its center
# is, so a limit stops a door outright rather than leaving the point to
# turn it back.
val axis := r.qa * r.made.axis_a;
val k := about_hinge(a, axis, r.ra) + about_hinge(b, axis, r.rb);
r.axial_mass = k > 0 ? 1 / k : 0f;
}
r.spring_soft = soft_of(r.made.hertz, r.made.damping, h);
r.linear_soft = r.made.hertz == 0 ? s.joint_soft : soft_of(r.made.hertz, r.made.damping, h);
r.angular_soft = r.made.angular_hertz == 0 ? s.joint_soft : soft_of(r.made.angular_hertz, r.made.angular_damping, h);
this.joints[j] = r;
}
}
# How easily a body turns about an axis through a place `r` from its center:
# the inverse of its moment about it.
def about_hinge(b: &body_record, axis: vec3, r: vec3): f32 {
return 0 if b.inv_mass == 0 || b.fixed_rotation;
val turn := mat3::rotation(b.at.turn);
val inertia := turn * b.inertia * turn.transposed();
val across := r.length_squared - r.dot(axis) * r.dot(axis);
val moment := axis.dot(inertia * axis) + b.mass * across;
return moment > 0 ? 1 / moment : 0f;
}
# A hinge's axis as each body is turned now, and two directions across it.
struct hinge_axes {
var a1: vec3;
var a2: vec3;
var u1: vec3;
var u2: vec3;
}
def axes_of(r: &joint_record, sa: &body_state, sb: &body_state): hinge_axes {
val a1 := (sa.dq * r.qa).normalized() * r.made.axis_a;
val a2 := (sb.dq * r.qb).normalized() * r.made.axis_b;
val u1 := perpendicular_to(a1);
return hinge_axes{ a1 = a1, a2 = a2, u1 = u1, u2 = a1.cross(u1) };
}
def space::warm_joints(&mut this, s: &mut solver_scratch): void {
for i in 0..s.joints.length {
val r := &this.joints[s.joints[i] as u64];
var sa := s.states[r.slot_a as u64];
var sb := s.states[r.slot_b as u64];
val ia := s.inertias[r.slot_a as u64];
val ib := s.inertias[r.slot_b as u64];
val ra := sa.dq * r.ra;
val rb := sb.dq * r.rb;
var p := r.linear;
var turn := vec3::zero;
if r.made.kind == joint_kind::hinge {
val axes := axes_of(r, &sa, &sb);
turn = axes.u1 * r.angular.x + axes.u2 * r.angular.y + axes.a1 * (r.spring_impulse + r.motor_impulse + r.lower_impulse - r.upper_impulse);
} else if r.made.kind == joint_kind::fixed || r.made.kind == joint_kind::slider {
turn = r.angular;
} else if r.made.kind == joint_kind::distance {
val axis := ((sb.dp - sa.dp) + r.delta_center + (rb - ra)).normalized();
p = axis * (r.axial + r.spring_impulse + r.lower_impulse - r.upper_impulse + r.motor_impulse);
}
sa.v = sa.v - p * r.ma;
sa.w = sa.w - ia * (ra.cross(p) + turn);
sb.v = sb.v + p * r.mb;
sb.w = sb.w + ib * (rb.cross(p) + turn);
if r.made.kind == joint_kind::slider || r.made.kind == joint_kind::six_dof || (r.made.kind == joint_kind::ball && r.made.limit) {
warm_free(r, &mut sa, &mut sb, ia, ib);
}
s.states[r.slot_a as u64] = sa;
s.states[r.slot_b as u64] = sb;
}
}
def space::solve_joints(&mut this, s: &mut solver_scratch, h: f32, use_bias: bool): void {
for i in 0..s.joints.length {
val j := s.joints[i] as u64;
var r := this.joints[j];
var sa := s.states[r.slot_a as u64];
var sb := s.states[r.slot_b as u64];
val ia := s.inertias[r.slot_a as u64];
val ib := s.inertias[r.slot_b as u64];
if r.made.kind == joint_kind::ball {
if r.made.limit {
solve_cone(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias);
}
solve_point(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, use_bias);
} else if r.made.kind == joint_kind::slider {
solve_slider(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias);
} else if r.made.kind == joint_kind::six_dof {
solve_six(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias);
} else if r.made.kind == joint_kind::hinge {
solve_hinge(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias);
solve_point(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, use_bias);
} else if r.made.kind == joint_kind::fixed {
solve_fixed_turn(&mut r, &mut sa, &mut sb, ia, ib, use_bias);
solve_point(&mut r, &mut sa, &mut sb, ia, ib, &r.linear_soft, use_bias || r.made.hertz > 0);
} else {
solve_distance(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias);
}
this.joints[j] = r;
s.states[r.slot_a as u64] = sa;
s.states[r.slot_b as u64] = sb;
}
}
# The matrix taking a vector to `r`'s cross product with it.
def skew(r: vec3): mat3 {
return mat3{ vec3{ 0, r.z, -r.y }, vec3{ -r.z, 0, r.x }, vec3{ r.y, -r.x, 0 } };
}
# Turns the two apart by an angular impulse.
def turn_apart(sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, impulse: vec3): void {
sa.w = sa.w - ia * impulse;
sb.w = sb.w + ib * impulse;
}
# Pushes the two apart by an impulse at their anchors.
def push_apart(r: &joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, ra: vec3, rb: vec3, p: vec3): void {
sa.v = sa.v - p * r.ma;
sa.w = sa.w - ia * ra.cross(p);
sb.v = sb.v + p * r.mb;
sb.w = sb.w + ib * rb.cross(p);
}
# A one-sided limit's impulse, as a contact's: of `c` how far it is from
# closing, and `cdot` how fast it closes.
def limit_impulse(c: f32, cdot: f32, mass: f32, held: f32, soft: &softness, inv_h: f32, use_bias: bool): f32 {
var bias: f32 = 0;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if c > 0 {
bias = c * inv_h;
} else if use_bias {
bias = soft.bias_rate * c;
mass_scale = soft.mass_scale;
impulse_scale = soft.impulse_scale;
}
val impulse := -mass * mass_scale * (cdot + bias) - impulse_scale * held;
return math::max(held + impulse, 0f) - held;
}
# Holds two anchors at one point.
def solve_point(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, use_bias: bool): void {
val ra := sa.dq * r.ra;
val rb := sb.dq * r.rb;
val cdot := sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra);
var bias := vec3::zero;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if use_bias {
bias = ((sb.dp - sa.dp) + (rb - ra) + r.delta_center) * soft.bias_rate;
mass_scale = soft.mass_scale;
impulse_scale = soft.impulse_scale;
}
val sa_skew := skew(ra);
val sb_skew := skew(rb);
val k := sa_skew * ia * sa_skew.transposed() + sb_skew * ib * sb_skew.transposed()
+ mat3{ vec3{ r.ma + r.mb, 0, 0 }, vec3{ 0, r.ma + r.mb, 0 }, vec3{ 0, 0, r.ma + r.mb } };
return if k.determinant == 0;
val impulse := (k.inverse() * (cdot + bias)) * -mass_scale - r.linear * impulse_scale;
r.linear = r.linear + impulse;
push_apart(r, sa, sb, ia, ib, ra, rb, impulse);
}
# Holds a hinge's axes together, and turns it by its spring, its motor, and
# its limits.
def solve_hinge(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void {
val made := &r.made;
val axes := axes_of(r, sa, sb);
if made.spring || made.motor || made.limit {
val angle := hinge_angle(made, (sa.dq * r.qa).normalized(), (sb.dq * r.qb).normalized());
if made.spring && made.hertz > 0 {
val bias := r.spring_soft.bias_rate * angle;
val impulse := -r.spring_soft.mass_scale * r.axial_mass * ((sb.w - sa.w).dot(axes.a1) + bias) - r.spring_soft.impulse_scale * r.spring_impulse;
r.spring_impulse += impulse;
turn_apart(sa, sb, ia, ib, axes.a1 * impulse);
}
if made.motor {
val most := h * made.max_motor_force;
val held := r.motor_impulse;
r.motor_impulse = math::clamp(held - r.axial_mass * ((sb.w - sa.w).dot(axes.a1) - made.motor_speed), -most, most);
turn_apart(sa, sb, ia, ib, axes.a1 * (r.motor_impulse - held));
}
if made.limit {
val lower := limit_impulse(angle - made.lower, (sb.w - sa.w).dot(axes.a1), r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias);
r.lower_impulse += lower;
turn_apart(sa, sb, ia, ib, axes.a1 * lower);
val upper := limit_impulse(made.upper - angle, (sa.w - sb.w).dot(axes.a1), r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias);
r.upper_impulse += upper;
turn_apart(sa, sb, ia, ib, axes.a1 * -upper);
}
}
# The axes held together: no turning across them, and what they've drifted
# apart undone.
val both := ia + ib;
val k11 := axes.u1.dot(both * axes.u1);
val k12 := axes.u1.dot(both * axes.u2);
val k22 := axes.u2.dot(both * axes.u2);
val turning := sb.w - sa.w;
var cx := turning.dot(axes.u1);
var cy := turning.dot(axes.u2);
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if use_bias {
val drift := axes.a1.cross(axes.a2);
cx += soft.bias_rate * drift.dot(axes.u1);
cy += soft.bias_rate * drift.dot(axes.u2);
mass_scale = soft.mass_scale;
impulse_scale = soft.impulse_scale;
}
var det := k11 * k22 - k12 * k12;
return if det == 0;
det = 1 / det;
val ix := -mass_scale * det * (k22 * cx - k12 * cy) - impulse_scale * r.angular.x;
val iy := -mass_scale * det * (k11 * cy - k12 * cx) - impulse_scale * r.angular.y;
r.angular = vec3{ r.angular.x + ix, r.angular.y + iy, 0 };
turn_apart(sa, sb, ia, ib, axes.u1 * ix + axes.u2 * iy);
}
# Holds a fixed joint's turn: `b` turned within `a` as it rests.
def solve_fixed_turn(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, use_bias: bool): void {
val turning := sb.w - sa.w;
var bias := vec3::zero;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if use_bias || r.made.angular_hertz > 0 {
val target := (sa.dq * r.qa).normalized() * r.made.reference;
var off := ((sb.dq * r.qb).normalized() * target.inverse()).normalized();
if off.w < 0 {
off = quat{ -off.x, -off.y, -off.z, -off.w };
}
bias = vec3{ 2 * off.x, 2 * off.y, 2 * off.z } * r.angular_soft.bias_rate;
mass_scale = r.angular_soft.mass_scale;
impulse_scale = r.angular_soft.impulse_scale;
}
val k := ia + ib;
return if k.determinant == 0;
val impulse := (k.inverse() * (turning + bias)) * -mass_scale - r.angular * impulse_scale;
r.angular = r.angular + impulse;
turn_apart(sa, sb, ia, ib, impulse);
}
def solve_distance(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void {
val made := &r.made;
val ra := sa.dq * r.ra;
val rb := sb.dq * r.rb;
val d := (sb.dp - sa.dp) + r.delta_center + (rb - ra);
val length := d.length;
val axis := d.normalized();
if made.spring && (!made.limit || made.lower < made.upper) {
if made.hertz > 0 {
val cdot := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra));
val bias := r.spring_soft.bias_rate * (length - made.length);
val impulse := -r.spring_soft.mass_scale * r.axial_mass * (cdot + bias) - r.spring_soft.impulse_scale * r.spring_impulse;
r.spring_impulse += impulse;
push_apart(r, sa, sb, ia, ib, ra, rb, axis * impulse);
}
} else {
val cdot := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra));
var bias: f32 = 0;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if use_bias {
bias = soft.bias_rate * (length - made.length);
mass_scale = soft.mass_scale;
impulse_scale = soft.impulse_scale;
}
val impulse := -mass_scale * r.axial_mass * (cdot + bias) - impulse_scale * r.axial;
r.axial += impulse;
push_apart(r, sa, sb, ia, ib, ra, rb, axis * impulse);
}
if made.limit && made.lower < made.upper {
val closing := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra));
val lower := limit_impulse(length - made.lower, closing, r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias);
r.lower_impulse += lower;
push_apart(r, sa, sb, ia, ib, ra, rb, axis * lower);
val opening := axis.dot(sa.v + sa.w.cross(ra) - sb.v - sb.w.cross(rb));
val upper := limit_impulse(made.upper - length, opening, r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias);
r.upper_impulse += upper;
push_apart(r, sa, sb, ia, ib, ra, rb, axis * -upper);
}
if made.motor {
val most := h * made.max_motor_force;
val held := r.motor_impulse;
val cdot := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra));
r.motor_impulse = math::clamp(held + r.axial_mass * (made.motor_speed - cdot), -most, most);
push_apart(r, sa, sb, ia, ib, ra, rb, axis * (r.motor_impulse - held));
}
}
+435
View File
@@ -0,0 +1,435 @@
#! Contains joints, which hold two bodies together: a `ball` joint holds them
#! at a point they turn about every way, as a shoulder, within a cone it swings
#! in and how far it twists where it's limited, as a ragdoll's limbs are held; a
#! `hinge` holds them at a point and an axis they turn about alone, as a door,
#! with limits to how far it turns and a motor to turn it; a `fixed` joint holds
#! them as one body, rigidly or springily; a `distance` joint keeps two points
#! apart, rigidly as a rod, within lengths as a rope, or springily; a `slider`
#! lets them slide along an axis, turning together, as a piston; and a
#! `six_dof` joint holds each way they move and turn, along and about its own
#! three axes, locked, limited, or free, as any of the others and more.
#!
#! Joints are solved before contacts in each substep, softly as contacts are:
#! each undoes what has drifted as a stiff, damped spring of the space's joint
#! frequency, and a limit pushes only as far as closes it this substep where
#! it's apart, as a speculative contact does.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
#! What a joint holds.
pub enum joint_kind: u8 {
#! The two at a point, about which they turn every way.
ball,
#! The two at a point, about an axis of each, which they turn about alone.
hinge,
#! The two as one.
fixed,
#! Two points apart, as a rod, a rope, or a spring.
distance,
#! The two sliding along an axis, turning together, as a piston.
slider,
#! Each way the two move and turn held as it says.
six_dof,
}
#! How a six-way joint holds one of the ways its bodies move or turn.
pub enum axis_hold: u8 {
#! Not at all: none of it.
locked,
#! Between its low and its high.
limited,
#! As far as it likes.
free,
}
#! What a joint is made as: its kind, its bodies, where it holds each, of the
#! body's own places, and what each kind asks.
pub struct joint {
pub var kind := joint_kind::ball;
pub var a: body_id;
pub var b: body_id;
pub var anchor_a: vec3;
pub var anchor_b: vec3;
#! Of a hinge, the axis it turns about, of each body's own directions.
pub var axis_a := vec3::up;
pub var axis_b := vec3::up;
#! Of a hinge, a fixed joint, or a slider, how `b` is turned within `a`'s own
#! turn, where it rests.
pub var reference := quat::identity;
#! Of a slider, a ball joint's limits, or a six-way joint, the joint's own
#! axes as each body is turned, where they rest together: its x is the
#! slider's axis, or the axis a ball joint swings from and twists about.
pub var frame_a := quat::identity;
pub var frame_b := quat::identity;
#! Of a ball joint limited, the widest it swings from its axis, in radians,
#! its twist about it limited from `lower` to `upper`.
pub var cone: f32;
#! Of a six-way joint, how it holds each way: sliding along its frame's x,
#! y, and z, then twisting about x and swinging about y and z, each by
#! `holds`, from `lows` to `highs` where it's limited; and each way not
#! locked driven at `drives`, in lengths or radians a second, by no more
#! than `forces`, of force or torque, none where that's 0.
pub var holds: axis_hold[6];
pub var lows: f32[6];
pub var highs: f32[6];
pub var drives: f32[6];
pub var forces: f32[6];
#! Whether the two bodies still meet where their colliders do.
pub var collide: bool;
#! Whether it's limited: a hinge to turning from `lower` to `upper` radians
#! from where it rests, and a distance joint to lengths between them.
pub var limit: bool;
pub var lower: f32;
pub var upper: f32;
#! A motor turning a hinge at a speed, in radians a second, or lengthening a
#! distance joint, in lengths a second, with no more than so much torque or
#! force.
pub var motor: bool;
pub var motor_speed: f32;
pub var max_motor_force: f32;
#! A spring toward a hinge's rest or a distance joint's length, of so many
#! cycles a second, damped so: 1 doesn't spring back. Of a fixed joint, how
#! stiff it holds its place, 0 rigid.
pub var spring: bool;
pub var hertz: f32;
pub var damping: f32 = 1;
#! Of a distance joint, the length it holds.
pub var length: f32 = 1;
#! Of a fixed joint, how stiff it holds its turn, 0 rigid.
pub var angular_hertz: f32;
pub var angular_damping: f32 = 1;
#! A number of its user's.
pub var data: u64;
}
#! A joint of a space, as `space::join` names it.
pub struct joint_id {
pub var index: u32 = 0xFFFFFFFF;
pub var generation: u32;
}
pub def joint_id::equals(&this, other: &joint_id): bool {
return this.index == other.index && this.generation == other.generation;
}
# A joint as the space keeps it, and what a step works out of it.
struct joint_record {
var made: joint;
var generation: u32;
var alive: bool;
var body_a: u32;
var body_b: u32;
var next_a: u32 = 0xFFFFFFFF;
var next_b: u32 = 0xFFFFFFFF;
var slot_a: u32;
var slot_b: u32;
var ma: f32;
var mb: f32;
var ra: vec3; # Each anchor from its body's center, as the step began.
var rb: vec3;
var qa: quat; # Each body's turn as the step began.
var qb: quat;
var delta_center: vec3;
var axial_mass: f32;
var linear: vec3; # Impulses, kept from step to step.
var angular: vec3;
var axial: f32;
var spring_impulse: f32;
var motor_impulse: f32;
var lower_impulse: f32;
var upper_impulse: f32;
var spring_soft: softness;
var linear_soft: softness;
var angular_soft: softness;
var held: f32[24]; # Of a six-way joint, each way's impulses: holding it, at its low, at its high, and driving it.
}
#! Joins two bodies.
pub def space::join(&mut this, made: joint): joint_id {
return joint_id{} if !this.has(made.a) || !this.has(made.b) || made.a.index == made.b.index;
var index: u32 = 0;
if this.free_joints.length > 0 {
index = this.free_joints[this.free_joints.length - 1];
this.free_joints.truncate();
} else {
index = this.joints.length as u32;
this.joints.append(joint_record{});
}
val generation := this.joints[index as u64].generation + 1;
val a := made.a.index;
val b := made.b.index;
this.joints[index as u64] = joint_record{
made = made, generation = generation, alive = true, body_a = a, body_b = b,
next_a = this.bodies[a as u64].joints, next_b = this.bodies[b as u64].joints,
};
this.bodies[a as u64].joints = index;
this.bodies[b as u64].joints = index;
if !made.collide {
this.drop_pairs_between(a, b);
}
this.wake_body(a);
this.wake_body(b);
return joint_id{ index = index, generation = generation };
}
#! Holds two bodies at a place of space, about which they turn every way.
pub def space::ball(&mut this, a: body_id, b: body_id, at: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
return this.join(joint{ kind = joint_kind::ball, a = a, b = b, anchor_a = this.pose_of(a).unapply(at), anchor_b = this.pose_of(b).unapply(at) });
}
#! Holds two bodies at a place of space and about an axis through it, of
#! space's directions, as a door's hinge holds it.
pub def space::hinge(&mut this, a: body_id, b: body_id, at: vec3, axis: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
val along := axis.normalized();
return this.join(joint{
kind = joint_kind::hinge, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
axis_a = pa.unrotate(along), axis_b = pb.unrotate(along), reference = (pa.turn.inverse() * pb.turn).normalized(),
});
}
# The joint axes, as a body is turned, of a frame whose x is a direction of
# space.
def frame_along(turn: quat, axis: vec3): quat {
val x := axis.normalized();
val y := perpendicular_to(x);
return (turn.inverse() * quat::of_basis(x, y, x.cross(y))).normalized();
}
#! Lets two bodies slide along an axis of space through a place, turning
#! together, as a piston: a slider, its limits, motor, and spring its own to
#! set.
pub def space::slider(&mut this, a: body_id, b: body_id, at: vec3, axis: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
return this.join(joint{
kind = joint_kind::slider, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
frame_a = frame_along(pa.turn, axis), frame_b = frame_along(pb.turn, axis), reference = (pa.turn.inverse() * pb.turn).normalized(),
});
}
#! Holds two bodies at a place of space, about which they turn, `b` swinging
#! no further than `cone` radians from an axis of space and twisting about it
#! no further than `twist` radians either way, as a shoulder or a hip: a ball
#! joint, limited.
pub def space::cone_twist(&mut this, a: body_id, b: body_id, at: vec3, axis: vec3, cone: f32, twist: f32): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
return this.join(joint{
kind = joint_kind::ball, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
frame_a = frame_along(pa.turn, axis), frame_b = frame_along(pb.turn, axis), limit = true, cone = cone, lower = -twist, upper = twist,
});
}
#! Holds two bodies at a place of space by a six-way joint, its axes those of
#! a rotation of space, each way locked until it's changed, as a fixed joint.
pub def space::six_dof(&mut this, a: body_id, b: body_id, at: vec3, axes: quat = quat::identity): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
return this.join(joint{
kind = joint_kind::six_dof, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
frame_a = (pa.turn.inverse() * axes).normalized(), frame_b = (pb.turn.inverse() * axes).normalized(),
});
}
#! Holds two bodies together as one, about a place of space.
pub def space::fix(&mut this, a: body_id, b: body_id, at: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
return this.join(joint{
kind = joint_kind::fixed, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
reference = (pa.turn.inverse() * pb.turn).normalized(),
});
}
#! Keeps two places of space, one of each body, as far apart as they are.
pub def space::tie(&mut this, a: body_id, b: body_id, at_a: vec3, at_b: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
return this.join(joint{
kind = joint_kind::distance, a = a, b = b, anchor_a = this.pose_of(a).unapply(at_a), anchor_b = this.pose_of(b).unapply(at_b),
length = (at_b - at_a).length, collide = true,
});
}
#! Whether a joint is of it still.
pub def space::has(&this, id: joint_id): bool {
return id.index < this.joints.length as u32 && this.joints[id.index as u64].alive && this.joints[id.index as u64].generation == id.generation;
}
#! What a joint was made as, or last changed to.
pub def space::joint_of(&this, id: joint_id): &joint {
return &this.joints[id.index as u64].made;
}
#! Changes what a joint asks, as its motor or limits, keeping its bodies, and
#! wakes them. What it no longer asks pushes no more: a motor, limits, or a
#! spring turned off, and a six-way joint's ways held otherwise.
pub def space::change(&mut this, id: joint_id, made: joint): void {
return if !this.has(id);
val j := id.index as u64;
var r := this.joints[j];
val a := r.made.a;
val b := r.made.b;
if !made.motor {
r.motor_impulse = 0;
}
if !made.limit {
r.lower_impulse = 0;
r.upper_impulse = 0;
}
if !made.spring {
r.spring_impulse = 0;
}
for k in 0..6u {
if made.holds[k] != r.made.holds[k] || made.kind != r.made.kind || made.limit != r.made.limit {
r.held = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
r.linear = vec3::zero;
}
if made.forces[k] == 0 {
r.held[18 + k] = 0;
}
}
r.made = made;
r.made.a = a;
r.made.b = b;
this.joints[j] = r;
this.wake_body(a.index);
this.wake_body(b.index);
}
#! How far a hinge is turned from where it rests, in radians, about its axis.
pub def space::angle_of(&this, id: joint_id): f32 {
return 0 if !this.has(id);
val j := &this.joints[id.index as u64];
return hinge_angle(&j.made, this.bodies[j.body_a as u64].at.turn, this.bodies[j.body_b as u64].at.turn);
}
# How far `b` is turned about a hinge's axis from where it rests, within `a`'s
# own turn: the twist of the turn between them.
def hinge_angle(made: &joint, qa: quat, qb: quat): f32 {
val apart := (made.reference.inverse() * (qa.inverse() * qb)).normalized();
val axis := made.axis_a;
val along := apart.x * axis.x + apart.y * axis.y + apart.z * axis.z;
return unwound(2 * math::atan2(along, apart.w));
}
# An angle brought within -π to π.
def unwound(angle: f32): f32 {
val pi := math::pi as f32;
return angle < -pi ? angle + 2 * pi : angle > pi ? angle - 2 * pi : angle;
}
#! Takes a joint away, waking its bodies.
pub def space::unjoin(&mut this, id: joint_id): void {
return if !this.has(id);
this.drop_joint(id.index);
}
def space::drop_joint(&mut this, j: u32): void {
val a := this.joints[j as u64].body_a;
val b := this.joints[j as u64].body_b;
this.unlink_joint(j, a);
this.unlink_joint(j, b);
this.joints[j as u64].alive = false;
this.free_joints.append(j);
this.wake_body(a);
this.wake_body(b);
this.touch_colliders(a);
}
def space::unlink_joint(&mut this, j: u32, body: u32): void {
val next := this.next_joint(j, body);
if this.bodies[body as u64].joints == j {
this.bodies[body as u64].joints = next;
return;
}
var k := this.bodies[body as u64].joints;
while k != none {
val after := this.next_joint(k, body);
if after == j {
if this.joints[k as u64].body_a == body {
this.joints[k as u64].next_a = next;
} else {
this.joints[k as u64].next_b = next;
}
return;
}
k = after;
}
}
def space::next_joint(&this, j: u32, body: u32): u32 {
return this.joints[j as u64].body_a == body ? this.joints[j as u64].next_a : this.joints[j as u64].next_b;
}
# Whether a joint holds two bodies and keeps them from meeting.
def space::joined_apart(&this, a: u32, b: u32): bool {
var j := this.bodies[a as u64].joints;
while j != none {
val joint := &this.joints[j as u64];
val other := joint.body_a == a ? joint.body_b : joint.body_a;
return true if other == b && !joint.made.collide;
j = this.next_joint(j, a);
}
return false;
}
def space::drop_joints_of(&mut this, b: u32): void {
while this.bodies[b as u64].joints != none {
this.drop_joint(this.bodies[b as u64].joints);
}
}
def space::drop_pairs_between(&mut this, a: u32, b: u32): void {
for p in 0..this.pairs.length {
continue if !this.pairs[p].alive;
val ba := this.colliders[this.pairs[p].a as u64].body;
val bb := this.colliders[this.pairs[p].b as u64].body;
if (ba == a && bb == b) || (ba == b && bb == a) {
this.drop_pair(p as u32, false);
}
}
}
def space::touch_colliders(&mut this, b: u32): void {
var c := this.bodies[b as u64].colliders;
while c != none {
if !this.colliders[c as u64].moved {
this.colliders[c as u64].moved = true;
this.moved.append(c);
}
c = this.colliders[c as u64].next;
}
}
def space::join_jointed(&this, parent: &mut vector<u32>): void {
for j in 0..this.joints.length {
val joint := &this.joints[j];
continue if !joint.alive;
if parent[joint.body_a as u64] != none && parent[joint.body_b as u64] != none {
join(parent, joint.body_a, joint.body_b);
}
}
}
#! Visits each joint, as `visit(joint, at_a, at_b)`, where it holds each of its
#! bodies, of space's places, until it gives false, as gizmos draw them.
pub def space::each_joint<F>(&this, visit: F): void where F: invokable<def(joint_id, vec3, vec3): bool> {
for j in 0..this.joints.length {
val r := &this.joints[j];
continue if !r.alive;
val at_a := this.bodies[r.body_a as u64].at.apply(r.made.anchor_a);
val at_b := this.bodies[r.body_b as u64].at.apply(r.made.anchor_b);
return if !visit(joint_id{ index = j as u32, generation = r.generation }, at_a, at_b);
}
}
+116
View File
@@ -0,0 +1,116 @@
#! Contains `mass_data`: how heavy a shape is of a density, where its mass is
#! centered, and how hard it is to turn about each axis, its inertia tensor,
#! as a body's colliders sum to it.
import std::math;
import malunal::linear;
module malunal::physics3d;
#! How heavy something is, where its mass is centered, of its body's own
#! places, and its inertia tensor about that center, of the body's own axes.
pub struct mass_data {
pub var mass: f32;
pub var center: vec3;
pub var inertia: mat3;
}
#! It and another together: their masses summed about their joint center.
pub def mass_data::add(&this, other: &mass_data): mass_data {
val mass := this.mass + other.mass;
return mass_data{ inertia = this.inertia + other.inertia } if mass <= 0;
val center := (this.center * this.mass + other.center * other.mass) * (1 / mass);
val inertia := this.inertia + shifted(this.mass, this.center - center) + other.inertia + shifted(other.mass, other.center - center);
return mass_data{ mass = mass, center = center, inertia = inertia };
}
# What a mass adds to an inertia tensor, turning about a center as far off as
# `d`, as the parallel axis theorem finds.
def shifted(mass: f32, d: vec3): mat3 {
val dd := d.dot(d);
return mat3{
vec3{ mass * (dd - d.x * d.x), -mass * d.x * d.y, -mass * d.x * d.z },
vec3{ -mass * d.y * d.x, mass * (dd - d.y * d.y), -mass * d.y * d.z },
vec3{ -mass * d.z * d.x, -mass * d.z * d.y, mass * (dd - d.z * d.z) },
};
}
# A tensor of `across` about every axis but `along` about the axis `u`.
def about_axis(across: f32, along: f32, u: vec3): mat3 {
val k := along - across;
return mat3{
vec3{ across + k * u.x * u.x, k * u.x * u.y, k * u.x * u.z },
vec3{ k * u.y * u.x, across + k * u.y * u.y, k * u.y * u.z },
vec3{ k * u.z * u.x, k * u.z * u.y, across + k * u.z * u.z },
};
}
#! Its mass of a density, a mass for each volume of 1.
pub def shape::mass(&this, density: f32): mass_data {
val pi := math::pi as f32;
val r := this.radius;
if this.kind == shape_kind::sphere {
val mass := density * 4f / 3f * pi * r * r * r;
val i := 0.4 * mass * r * r;
return mass_data{ mass = mass, center = this.a, inertia = about_axis(i, i, vec3::up) };
}
if this.kind == shape_kind::capsule {
# A cylinder between its ends, and a sphere of its two round halves, each
# half's own center 3r/8 past the cylinder's end.
val length := (this.b - this.a).length;
val cylinder := density * pi * r * r * length;
val ball := density * 4f / 3f * pi * r * r * r;
val along := cylinder * r * r * 0.5 + ball * 0.4 * r * r;
val across := cylinder * (length * length / 12 + r * r / 4) + ball * (0.4 * r * r + length * length / 4 + 3 * length * r / 8);
return mass_data{ mass = cylinder + ball, center = (this.a + this.b) * 0.5, inertia = about_axis(across, along, (this.b - this.a).normalized()) };
}
return hull_mass(this.as_hull(), density);
}
# A hull's, as the tetrahedra of each face's triangles and a place within it
# sum it.
def hull_mass(h: &hull, density: f32): mass_data {
val origin := h.center;
var volume: f32 = 0;
var center := vec3::zero;
# The covariance of the hull's places about the origin.
var xx: f32 = 0;
var yy: f32 = 0;
var zz: f32 = 0;
var xy: f32 = 0;
var xz: f32 = 0;
var yz: f32 = 0;
for f in 0..h.faces {
val a := h.point(h.corner(f, 0)) - origin;
for k in 1..h.face_size(f) - 1 {
val b := h.point(h.corner(f, k)) - origin;
val c := h.point(h.corner(f, k + 1)) - origin;
val det := a.dot(b.cross(c));
volume += det / 6;
center = center + (a + b + c) * (det / 24);
val s := a + b + c;
val w := det / 120;
xx += w * (a.x * a.x + b.x * b.x + c.x * c.x + s.x * s.x);
yy += w * (a.y * a.y + b.y * b.y + c.y * c.y + s.y * s.y);
zz += w * (a.z * a.z + b.z * b.z + c.z * c.z + s.z * s.z);
xy += w * (a.x * a.y + b.x * b.y + c.x * c.y + s.x * s.y);
xz += w * (a.x * a.z + b.x * b.z + c.x * c.z + s.x * s.z);
yz += w * (a.y * a.z + b.y * b.z + c.y * c.z + s.y * s.z);
}
}
return mass_data{} if volume <= tiny;
center = center * (1 / volume);
val mass := density * volume;
# Of the covariance about the center of mass, the tensor.
xx = density * xx - mass * center.x * center.x;
yy = density * yy - mass * center.y * center.y;
zz = density * zz - mass * center.z * center.z;
xy = density * xy - mass * center.x * center.y;
xz = density * xz - mass * center.x * center.z;
yz = density * yz - mass * center.y * center.z;
val inertia := mat3{
vec3{ yy + zz, -xy, -xz },
vec3{ -xy, xx + zz, -yz },
vec3{ -xz, -yz, xx + yy },
};
return mass_data{ mass = mass, center = origin + center, inertia = inertia };
}
+318
View File
@@ -0,0 +1,318 @@
#! 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;
var _field: heightfield; # Its triangles, where they're a heightfield's.
var _heights: bool;
}
#! 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;
}
# The triangles of a heightfield, made as they're met.
def triangle_mesh::of_field(field: heightfield): triangle_mesh {
var made := triangle_mesh::new(span::<vec3>::blank(), span::<u32>::blank());
made._field = move(field);
made._heights = true;
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._heights ? this._field.length : this._normals.length;
}
#! A triangle's corners.
pub def triangle_mesh::triangle(&this, t: u32): vec3[3] {
return this._field.triangle(t) if this._heights;
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._field.normal(t) if this._heights;
return this._normals[t as u64];
}
# Which of a triangle's edges push as they meet, a bit each.
def triangle_mesh::active_bits(&this, t: u32): u8 {
return this._field.active(t) if this._heights;
return this._active[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 has_bit(this.active_bits(t), k);
}
def has_bit(bits: u8, k: u32): bool {
return (((bits as u32) >> k) & 1) != 0;
}
#! The box holding it, of its own places.
pub def triangle_mesh::bounds(&this): bounds {
return this._field.bounds if this._heights;
var made := bounds::blank;
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.triangles_in(grown(s.bounds(local), margin), def(t: u32): bool {
val c := this.triangle(t);
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(t, placed(face_pushed(&c, this.normal(t), this.active_bits(t), found, s.radius), &at));
});
}
#! Visits each triangle whose box a box of its own places meets, as
#! `visit(triangle)`, until it gives false.
pub def triangle_mesh::triangles_in<F>(&this, box: bounds, visit: F): void where F: invokable<def(u32): bool> {
if this._heights {
this._field.triangles_in(box, visit);
return;
}
this._tree.query(box, def(leaf: u32, data: u64): bool {
return visit(data as u32);
});
}
#! 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 face_pushed(c: &vec3[3], n: vec3, active: u8, met: manifold, radius: f32): manifold {
val along := met.normal.dot(n);
return met if math::abs(along) > 0.9998 || active == 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 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 has_bit(active, region - 3);
} else if has_bit(active, region) || has_bit(active, (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);
if this._heights {
val found := this._field.ray_cast(o, d, reach) else { return nothing{}; };
return mesh_hit{ distance = found.distance, point = at.apply(found.point), normal = at.rotate(found.normal), triangle = found.triangle };
}
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;
}
+85
View File
@@ -0,0 +1,85 @@
#! Contains `physics3d`: what collides and moves 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.
#!
#! And a `space` of bodies, as `physics2d`'s in a plane: each made of
#! colliders, of shapes, a triangle mesh, or a heightfield, pulled by gravity,
#! pushed by forces and by what it meets, held to others by joints, and stepped
#! forward in time as Box2D's soft step solves it, its contacts as lanes of
#! eight, on as many threads as it's given, swept where it moves fast, and
#! sleeping where it and all it rests on are still; asked of what overlaps and
#! what casts meet; and walking `character`s.
#!
#! 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.
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();
}
+65
View File
@@ -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() };
}
+117
View File
@@ -0,0 +1,117 @@
#! Contains what a space is asked of the shapes in it: which colliders a shape
#! overlaps, and where a shape cast along a motion first meets one, as a
#! character's feet and a thrown stone ask.
import std::containers;
import std::math;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
#! Where a shape cast through a space first met one of its colliders: which,
#! of which body, how far along the motion, as a fraction of it, where on what
#! it met, which way that faces, toward the shape cast, and of a mesh's or a
#! heightfield's, which triangle.
pub struct space_cast {
pub var collider: collider_id;
pub var body: body_id;
pub var fraction: f32;
pub var point: vec3;
pub var normal: vec3;
pub var triangle: u32 = 0xFFFFFFFF;
}
#! What a query of a space passes over: colliders on no layer of its `mask`;
#! sensors, unless `sensors`; and those whose data is `ignore`, where it isn't
#! 0, as the asker's own, a body and its colliders given an entity's bits.
pub struct query_filter {
pub var mask: u32 = 0xFFFFFFFF;
pub var sensors := false;
pub var ignore: u64 = 0;
}
# Whether a query of a filter asks of a collider.
def space::passes(&this, c: u32, filter: &query_filter): bool {
val held := &this.colliders[c as u64].made;
return (held.layers & filter.mask) != 0 && (!held.sensor || filter.sensors) && (filter.ignore == 0 || held.data != filter.ignore);
}
def space::named(&this, c: u32): collider_id {
return collider_id{ index = c, generation = this.colliders[c as u64].generation };
}
def space::body_named(&this, b: u32): body_id {
return body_id{ index = b, generation = this.bodies[b as u64].generation };
}
#! Visits each collider on a layer of a mask that a shape overlaps, where a
#! pose places it, sensors passed over, as `visit(collider, body)`, until it
#! gives false.
pub def space::overlap<F>(&this, s: &shape, at: pose, mask: u32, visit: F): void where F: invokable<def(collider_id, body_id): bool> {
this.overlap(s, at, query_filter{ mask = mask }, visit);
}
#! Visits each collider a shape overlaps, where a pose places it, that a
#! filter asks of, as `visit(collider, body)`, until it gives false.
pub def space::overlap<F>(&this, s: &shape, at: pose, filter: query_filter, visit: F): void where F: invokable<def(collider_id, body_id): bool> {
this.tree.query(s.bounds(at), def(leaf: u32, data: u64): bool {
val c := data as u32;
return true if !this.passes(c, &filter);
val held := &this.colliders[data];
val placed := this.bodies[held.body as u64].at;
var met := false;
if held.is_mesh() {
met = this.meshes[held.mesh as u64].overlaps(placed, s, at);
} else {
met = overlaps(&held.made.shape, placed, s, at);
}
return true if !met;
return visit(this.named(c), this.body_named(held.body));
});
}
#! Where a shape, cast along a motion of space from where a pose places it,
#! first meets a collider on a layer of a mask, sensors passed over: within a
#! quarter of the slop of what it meets, a little short of touching. A
#! fraction of 0 where it overlaps something as it begins. Colliders of
#! `except`, a body of its own, as a character's, are passed over.
pub def space::shape_cast(&this, s: &shape, at: pose, motion: vec3, mask: u32 = 0xFFFFFFFF, except: body_id = body_id{}): maybe<space_cast> {
return this.shape_cast(s, at, motion, query_filter{ mask = mask }, except);
}
#! Where a shape, cast along a motion as `shape_cast` casts it, first meets a
#! collider a filter asks of.
pub def space::shape_cast(&this, s: &shape, at: pose, motion: vec3, filter: query_filter, except: body_id = body_id{}): maybe<space_cast> {
var best: maybe<space_cast> = nothing{};
var first: f32 = 2;
val tolerance := 0.25 * this.slop;
val moved := pose{ at = at.at + motion, turn = at.turn };
val box := s.bounds(at).merged(s.bounds(moved));
this.tree.query(box, def(leaf: u32, data: u64): bool {
val c := data as u32;
return true if !this.passes(c, &filter) || this.colliders[data].body == except.index;
val held := &this.colliders[data];
val placed := this.bodies[held.body as u64].at;
if held.is_mesh() {
val surface := &this.meshes[held.mesh as u64];
surface.triangles_in(local_box(box, placed), def(t: u32): bool {
val corners := surface.triangle(t);
val face := shape::of_hull(hull::triangle(corners[0], corners[1], corners[2]));
val hit := shape_cast(&face, placed, s, at, motion, tolerance) else { return true; };
if hit.fraction < first {
first = hit.fraction;
best = space_cast{ collider = this.named(c), body = this.body_named(held.body), fraction = hit.fraction, point = hit.point, normal = hit.normal, triangle = t };
}
return true;
});
return true;
}
val hit := shape_cast(&held.made.shape, placed, s, at, motion, tolerance) else { return true; };
if hit.fraction < first {
first = hit.fraction;
best = space_cast{ collider = this.named(c), body = this.body_named(held.body), fraction = hit.fraction, point = hit.point, normal = hit.normal };
}
return true;
});
return best;
}
+246
View File
@@ -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) };
}
+119
View File
@@ -0,0 +1,119 @@
#! Contains how a space's bodies sleep: those that touch, or a joint holds
#! together, are an island, found anew each step, and an island sleeps when
#! all its bodies have been still for half a second, so a settled pile costs
#! nothing until something wakes it. A kinematic body sleeps alone, when it
#! has been still as long.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
# How long, in seconds, a body is still before it may sleep.
const time_to_sleep: f32 = 0.5;
# The first body of the island a body is of, each body passed on the way
# pointed nearer it, so the next finding is shorter.
def root_of(parent: &mut vector<u32>, b: u32): u32 {
var x := b;
while parent[x as u64] != x {
val up := parent[parent[x as u64] as u64];
parent[x as u64] = up;
x = up;
}
return x;
}
def join(parent: &mut vector<u32>, a: u32, b: u32): void {
val ra := root_of(parent, a);
val rb := root_of(parent, b);
if ra != rb {
parent[math::max(ra, rb) as u64] = math::min(ra, rb);
}
}
# Finds the islands of awake dynamic bodies, and puts to sleep those all of
# whose bodies have been still long enough.
def space::sleep_islands(&mut this, dt: f32): void {
var parent := move(this.islands);
parent.clear();
parent.resize(this.bodies.length, none);
for b in 0..this.bodies.length {
val body := &this.bodies[b];
if body.alive && body.awake && body.kind == body_kind::dynamic {
parent[b] = b as u32;
}
}
for k in 0..this.contacts.length {
val c := &this.contacts[k];
continue if !c.alive || !c.touching;
val a := c.body_a;
val b := c.body_b;
if parent[a as u64] != none && parent[b as u64] != none {
join(&mut parent, a, b);
} else if parent[a as u64] != none && this.bodies[b as u64].kind == body_kind::kinematic {
this.keep_awake_on(a, b);
} else if parent[b as u64] != none && this.bodies[a as u64].kind == body_kind::kinematic {
this.keep_awake_on(b, a);
}
}
this.join_jointed(&mut parent);
# Each island's least time still, kept at its root.
for b in 0..this.bodies.length {
continue if parent[b] == none;
val root := root_of(&mut parent, b as u32) as u64;
this.bodies[root].sleep_time = math::min(this.bodies[root].sleep_time, this.bodies[b].sleep_time);
}
for b in 0..this.bodies.length {
continue if parent[b] == none;
val root := root_of(&mut parent, b as u32);
continue if this.bodies[root as u64].sleep_time < time_to_sleep;
# Linked after its root, which heads the group.
this.bodies[b].awake = false;
this.bodies[b].velocity = vec3::zero;
this.bodies[b].spin = vec3::zero;
this.bodies[b].group = root;
if b as u32 != root {
this.bodies[b].next_in_group = this.bodies[root as u64].next_in_group;
this.bodies[root as u64].next_in_group = b as u32;
}
}
# A kinematic body still long enough sleeps alone.
for b in 0..this.bodies.length {
val body := &this.bodies[b];
if body.alive && body.awake && body.kind == body_kind::kinematic && body.sleep_time >= time_to_sleep {
this.bodies[b].awake = false;
this.bodies[b].group = b as u32;
}
}
this.islands = move(parent);
}
# Keeps a dynamic body awake where it rests on a kinematic body that moves.
def space::keep_awake_on(&mut this, b: u32, kinematic: u32): void {
val k := &this.bodies[kinematic as u64];
if k.velocity.length_squared > 0 || k.spin.length_squared > 0 {
this.bodies[b as u64].sleep_time = 0;
}
}
# Wakes a body, and every body of the group it sleeps with, and marks it as
# having been still for no time.
def space::wake_body(&mut this, b: u32): void {
return if this.bodies[b as u64].kind == body_kind::static;
this.bodies[b as u64].sleep_time = 0;
return if this.bodies[b as u64].awake;
var m := this.bodies[b as u64].group;
if m == none {
this.bodies[b as u64].awake = true;
return;
}
while m != none {
val next := this.bodies[m as u64].next_in_group;
this.bodies[m as u64].awake = true;
this.bodies[m as u64].sleep_time = 0;
this.bodies[m as u64].group = none;
this.bodies[m as u64].next_in_group = none;
m = next;
}
}
+491
View File
@@ -0,0 +1,491 @@
#! Contains how a space solves a step, as Box2D's soft step solves one: in
#! substeps, each of which moves velocities by forces, pushes apart what meets,
#! softly, moves the bodies, and pushes again without undoing overlaps; then
#! bounces what met fast enough, and keeps each contact's impulses for the
#! next step to begin with.
#!
#! A contact pushes as a stiff, damped spring of the space's frequency, so an
#! overlap is undone over a few substeps, no faster than the push speed, and a
#! stack doesn't jitter. Points apart within the speculative margin push only
#! as much as would close the gap in a substep, so what falls stops at what's
#! below it rather than in it. Friction holds each point along two tangents at
#! once, no harder in all than its share of what pushes it, as a cone allows.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
# How soft a constraint is, as a damped spring of a frequency is: how much of
# its error it undoes each second, and how much of its impulse it gives.
struct softness {
var bias_rate: f32;
var mass_scale: f32 = 1;
var impulse_scale: f32;
}
def soft_of(hertz: f32, damping: f32, h: f32): softness {
return softness{} if hertz == 0;
val omega := 2 * math::pi as f32 * hertz;
val a1 := 2 * damping + h * omega;
val a2 := h * omega * a1;
val a3 := 1 / (1 + a2);
return softness{ bias_rate = omega / a1, mass_scale = a2 * a3, impulse_scale = a3 };
}
# A body as a step moves it: its velocities, and how far its center has moved
# and it has turned since the step began.
struct body_state {
var v: vec3;
var w: vec3;
var dp: vec3;
var dq: quat;
}
# How a body's velocities change each substep: by its forces and gravity, and
# what its damping keeps of them.
struct body_motion {
var dv: vec3;
var dw: vec3;
var linear_keep: f32 = 1;
var angular_keep: f32 = 1;
}
# A point of a contact as the solver pushes at it: where it is from each
# body's center, how far apart the two are there but for how far they've
# moved, and the impulses pushing them apart and along each tangent.
struct point_constraint {
var anchor_a: vec3;
var anchor_b: vec3;
var base_separation: f32;
var normal_impulse: f32;
var tangent_impulse: vec3;
var max_impulse: f32;
var impact: f32; # What stopped it meeting fast, as the step began.
var normal_mass: f32;
var tangent_mass: vec3;
var relative_velocity: f32;
}
struct contact_constraint {
var a: u32; # States.
var b: u32;
var contact: u32;
var normal: vec3;
var t1: vec3;
var t2: vec3;
var friction: f32;
var restitution: f32;
var ma: f32;
var mb: f32;
var soft: softness;
var count: u32;
var points: point_constraint[4];
}
# What a step works in, kept from one to the next so it isn't made anew: the
# first state is of what doesn't move, of no mass and turning by nothing.
struct solver_scratch {
var states: vector<body_state>;
var motions: vector<body_motion>;
var inertias: vector<mat3>; # Each state's inverse inertia, of space's axes.
var bodies: vector<u32>;
var constraints: vector<contact_constraint>;
var joints: vector<u32>;
var joint_soft: softness;
var wide: vector<wide_contact>;
var overflow: vector<u32>; # Constraints of no color.
var colored: vector<u64>; # Each color's bodies, a bit each.
var color_of: vector<u32>;
var color_groups: u32[25]; # Where each color's lanes begin.
}
# The most a body turns in a substep, a quarter of a half turn, so a fast spin
# doesn't skip through what it meets.
const most_turn: f32 = 0.25 * 3.14159265;
# A rotation turned further by a spin over a time, kept of length 1.
def turned(q: quat, w: vec3, h: f32): quat {
val spin := quat{ w.x, w.y, w.z, 0 } * q;
val half := 0.5 * h;
return quat{ q.x + half * spin.x, q.y + half * spin.y, q.z + half * spin.z, q.w + half * spin.w }.normalized();
}
# How hard it is to push the two along a direction at their anchors.
def mass_along(d: vec3, ra: vec3, rb: vec3, ma: f32, mb: f32, ia: mat3, ib: mat3): f32 {
val rda := ra.cross(d);
val rdb := rb.cross(d);
val k := ma + mb + rda.dot(ia * rda) + rdb.dot(ib * rdb);
return k > 0 ? 1 / k : 0f;
}
def space::solve(&mut this, dt: f32): void {
val n: u32 = this.substeps > 0 ? this.substeps : 1;
val h := dt / n as f32;
val inv_h := 1 / h;
var s := move(this.solver);
this.gather(&mut s, h);
this.prepare_contacts(&mut s, h);
this.prepare_joints(&mut s, h);
stop_impacts(&mut s, dt, 2 * this.push_speed);
color_contacts(&mut s);
val max_spin := most_turn * inv_h;
this.crew.start(this.threads);
for i in 0..n {
integrate_velocities(&mut s, this.max_speed, max_spin);
this.warm_joints(&mut s);
this.wide_stage(&mut s, true, inv_h, this.push_speed, true);
warm_contacts(&mut s);
this.solve_joints(&mut s, h, true);
this.wide_stage(&mut s, false, inv_h, this.push_speed, true);
solve_contacts(&mut s, inv_h, this.push_speed, true);
integrate_positions(&mut s, h);
this.solve_joints(&mut s, h, false);
this.wide_stage(&mut s, false, inv_h, this.push_speed, false);
solve_contacts(&mut s, inv_h, this.push_speed, false);
}
unpack_contacts(&mut s);
bounce(&mut s, this.restitution_threshold);
this.keep_impulses(&s);
this.finish(&s, dt);
this.solver = move(s);
}
# Gives each moving body a state, its inverse inertia as it's turned, and how
# its forces move it each substep.
def space::gather(&mut this, s: &mut solver_scratch, h: f32): void {
s.states.clear();
s.motions.clear();
s.inertias.clear();
s.bodies.clear();
s.states.append(body_state{ dq = quat::identity });
s.motions.append(body_motion{});
s.inertias.append(mat3{});
s.bodies.append(none);
for b in 0..this.bodies.length {
if !this.bodies[b].alive || !this.moves(b as u32) {
this.bodies[b].slot = 0;
continue;
}
this.bodies[b].slot = s.states.length as u32;
val inverse := this.world_inverse_inertia(b as u32);
val body := &this.bodies[b];
s.states.append(body_state{ v = body.velocity, w = body.spin, dq = quat::identity });
s.inertias.append(inverse);
if body.kind == body_kind::dynamic {
s.motions.append(body_motion{
dv = ((this.gravity + body.gravity) * body.gravity_scale + body.force * body.inv_mass) * h,
dw = (inverse * body.torque) * h,
linear_keep = 1 / (1 + h * body.linear_damping),
angular_keep = 1 / (1 + h * body.angular_damping),
});
} else {
s.motions.append(body_motion{});
}
s.bodies.append(b as u32);
}
}
def space::prepare_contacts(&this, s: &mut solver_scratch, h: f32): void {
s.constraints.clear();
val hertz := math::min(this.contact_hertz, 0.25 / h);
val soft := soft_of(hertz, this.contact_damping, h);
# Against what doesn't move, twice as stiff.
val stiff := soft_of(2 * hertz, this.contact_damping, h);
for k in 0..this.contacts.length {
val c := &this.contacts[k];
continue if !c.alive || !c.touching;
val a := &this.bodies[c.body_a as u64];
val b := &this.bodies[c.body_b as u64];
continue if a.slot == 0 && b.slot == 0;
val ia := s.inertias[a.slot as u64];
val ib := s.inertias[b.slot as u64];
val n := c.manifold.normal;
val t1 := perpendicular_to(n);
val t2 := n.cross(t1);
var made := contact_constraint{
a = a.slot, b = b.slot, contact = k as u32, normal = n, t1 = t1, t2 = t2, friction = c.friction, restitution = c.restitution,
ma = a.inv_mass, mb = b.inv_mass, soft = a.inv_mass == 0 || b.inv_mass == 0 ? stiff : soft, count = c.manifold.count,
};
for j in 0..c.manifold.count {
val mp := &c.manifold.points[j];
val ra := mp.point - a.center;
val rb := mp.point - b.center;
val vra := a.velocity + a.spin.cross(ra);
val vrb := b.velocity + b.spin.cross(rb);
# The tangents' impulses kept as they were along last step's tangents,
# which turn with the normal: what of them lies along these.
made.points[j] = point_constraint{
anchor_a = ra, anchor_b = rb,
base_separation = -mp.depth - (rb - ra).dot(n),
normal_impulse = c.normal_impulse[j], tangent_impulse = c.tangent_impulse[j],
normal_mass = mass_along(n, ra, rb, made.ma, made.mb, ia, ib),
tangent_mass = vec3{ mass_along(t1, ra, rb, made.ma, made.mb, ia, ib), mass_along(t2, ra, rb, made.ma, made.mb, ia, ib), 0 },
relative_velocity = n.dot(vrb - vra),
};
}
s.constraints.append(made);
}
}
# Stops what meets faster than a threshold before the substeps begin, as far
# as closes its gap through the step, over a few passes, so a crate dropped
# flat lands flat: solved within the substeps, the impulse that stops it would
# be given again as each begins, and taken back, unevenly between its points,
# throwing it. What stops it is kept apart from the impulses the substeps
# begin with, but for bouncing.
def stop_impacts(s: &mut solver_scratch, dt: f32, threshold: f32): void {
for pass in 0..4u {
for i in 0..s.constraints.length {
val c := &mut s.constraints[i];
var fast := false;
for j in 0..c.count {
if c.points[j].relative_velocity < -threshold {
fast = true;
}
}
continue if !fast;
val ia := s.inertias[c.a as u64];
val ib := s.inertias[c.b as u64];
var va := s.states[c.a as u64].v;
var wa := s.states[c.a as u64].w;
var vb := s.states[c.b as u64].v;
var wb := s.states[c.b as u64].w;
val n := c.normal;
for j in 0..c.count {
val cp := &mut c.points[j];
val ra := cp.anchor_a;
val rb := cp.anchor_b;
val gap := cp.base_separation + (rb - ra).dot(n);
val least := gap > 0 ? -gap / dt : 0f;
val vn := (vb + wb.cross(rb) - va - wa.cross(ra)).dot(n);
val sum := math::max(cp.impact - cp.normal_mass * (vn - least), 0f);
val impulse := sum - cp.impact;
cp.impact = sum;
cp.max_impulse = math::max(cp.max_impulse, sum);
val p := n * impulse;
va = va - p * c.ma;
wa = wa - ia * ra.cross(p);
vb = vb + p * c.mb;
wb = wb + ib * rb.cross(p);
}
s.states[c.a as u64].v = va;
s.states[c.a as u64].w = wa;
s.states[c.b as u64].v = vb;
s.states[c.b as u64].w = wb;
}
}
}
def integrate_velocities(s: &mut solver_scratch, max_speed: f32, max_spin: f32): void {
for i in 1..s.states.length {
val m := &s.motions[i];
val st := &mut s.states[i];
var v := st.v * m.linear_keep + m.dv;
var w := st.w * m.angular_keep + m.dw;
val speed_squared := v.length_squared;
if speed_squared > max_speed * max_speed {
v = v * (max_speed / math::sqrt(speed_squared));
}
val spin_squared := w.length_squared;
if spin_squared > max_spin * max_spin {
w = w * (max_spin / math::sqrt(spin_squared));
}
st.v = v;
st.w = w;
}
}
def integrate_positions(s: &mut solver_scratch, h: f32): void {
for i in 1..s.states.length {
val st := &mut s.states[i];
st.dq = turned(st.dq, st.w, h);
st.dp = st.dp + st.v * h;
}
}
# Of the contacts of no color, one at a time.
def warm_contacts(s: &mut solver_scratch): void {
for o in 0..s.overflow.length {
val c := &s.constraints[s.overflow[o] as u64];
val ia := s.inertias[c.a as u64];
val ib := s.inertias[c.b as u64];
var va := s.states[c.a as u64].v;
var wa := s.states[c.a as u64].w;
var vb := s.states[c.b as u64].v;
var wb := s.states[c.b as u64].w;
for j in 0..c.count {
val cp := &c.points[j];
val p := c.normal * cp.normal_impulse + c.t1 * cp.tangent_impulse.x + c.t2 * cp.tangent_impulse.y;
va = va - p * c.ma;
wa = wa - ia * cp.anchor_a.cross(p);
vb = vb + p * c.mb;
wb = wb + ib * cp.anchor_b.cross(p);
}
s.states[c.a as u64].v = va;
s.states[c.a as u64].w = wa;
s.states[c.b as u64].v = vb;
s.states[c.b as u64].w = wb;
}
}
def solve_contacts(s: &mut solver_scratch, inv_h: f32, push: f32, use_bias: bool): void {
val states := s.states.slice;
val constraints := s.constraints.slice;
for o in 0..s.overflow.length {
val c := &mut constraints[s.overflow[o] as u64];
val a := c.a as u64;
val b := c.b as u64;
val ia := s.inertias[a];
val ib := s.inertias[b];
var va := states[a].v;
var wa := states[a].w;
var vb := states[b].v;
var wb := states[b].w;
val dp := states[b].dp - states[a].dp;
val qa := mat3::rotation(states[a].dq);
val qb := mat3::rotation(states[b].dq);
val n := c.normal;
for j in 0..c.count {
val cp := &mut c.points[j];
val ra := cp.anchor_a;
val rb := cp.anchor_b;
# How far apart they are now: as they began, and as far as each anchor
# has moved and turned since.
val d := dp + (qb * rb - qa * ra);
val separation := d.dot(n) + cp.base_separation;
var bias: f32 = 0;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if separation > 0 {
bias = separation * inv_h;
} else if use_bias {
bias = c.soft.bias_rate * separation;
if bias < -push {
bias = -push;
}
mass_scale = c.soft.mass_scale;
impulse_scale = c.soft.impulse_scale;
}
val vn := (vb + wb.cross(rb) - va - wa.cross(ra)).dot(n);
val before := cp.normal_impulse;
var sum := before - cp.normal_mass * mass_scale * (vn + bias) - impulse_scale * before;
if sum < 0 {
sum = 0;
}
val impulse := sum - before;
cp.normal_impulse = sum;
if impulse > cp.max_impulse {
cp.max_impulse = impulse;
}
val p := n * impulse;
va = va - p * c.ma;
wa = wa - ia * ra.cross(p);
vb = vb + p * c.mb;
wb = wb + ib * rb.cross(p);
}
# Friction along both tangents, of no more in all than its share of what
# pushes them apart.
for j in 0..c.count {
val cp := &mut c.points[j];
val ra := cp.anchor_a;
val rb := cp.anchor_b;
val dv := vb + wb.cross(rb) - va - wa.cross(ra);
val before := cp.tangent_impulse;
var sum := vec3{ before.x - cp.tangent_mass.x * dv.dot(c.t1), before.y - cp.tangent_mass.y * dv.dot(c.t2), 0 };
val most := c.friction * cp.normal_impulse;
val squared := sum.x * sum.x + sum.y * sum.y;
if squared > most * most {
sum = sum * (most / math::sqrt(squared));
}
cp.tangent_impulse = sum;
val p := c.t1 * (sum.x - before.x) + c.t2 * (sum.y - before.y);
va = va - p * c.ma;
wa = wa - ia * ra.cross(p);
vb = vb + p * c.mb;
wb = wb + ib * rb.cross(p);
}
states[a].v = va;
states[a].w = wa;
states[b].v = vb;
states[b].w = wb;
}
}
# Bounces what met faster than the threshold, as much as its restitution
# keeps of how fast it met: only at points that pushed, so a speculative
# point that never closed doesn't bounce.
def bounce(s: &mut solver_scratch, threshold: f32): void {
for i in 0..s.constraints.length {
val c := &mut s.constraints[i];
continue if c.restitution == 0;
val ia := s.inertias[c.a as u64];
val ib := s.inertias[c.b as u64];
var va := s.states[c.a as u64].v;
var wa := s.states[c.a as u64].w;
var vb := s.states[c.b as u64].v;
var wb := s.states[c.b as u64].w;
val n := c.normal;
for j in 0..c.count {
val cp := &mut c.points[j];
continue if cp.relative_velocity > -threshold || cp.max_impulse == 0;
val vn := (vb + wb.cross(cp.anchor_b) - va - wa.cross(cp.anchor_a)).dot(n);
var impulse := -cp.normal_mass * (vn + c.restitution * cp.relative_velocity);
val sum := math::max(cp.normal_impulse + impulse, 0f);
impulse = sum - cp.normal_impulse;
cp.normal_impulse = sum;
cp.max_impulse = math::max(cp.max_impulse, impulse);
val p := n * impulse;
va = va - p * c.ma;
wa = wa - ia * cp.anchor_a.cross(p);
vb = vb + p * c.mb;
wb = wb + ib * cp.anchor_b.cross(p);
}
s.states[c.a as u64].v = va;
s.states[c.a as u64].w = wa;
s.states[c.b as u64].v = vb;
s.states[c.b as u64].w = wb;
}
}
def space::keep_impulses(&mut this, s: &solver_scratch): void {
for i in 0..s.constraints.length {
val c := &s.constraints[i];
for j in 0..c.count {
this.contacts[c.contact as u64].normal_impulse[j] = c.points[j].normal_impulse;
this.contacts[c.contact as u64].tangent_impulse[j] = c.points[j].tangent_impulse;
}
}
}
# Puts each moving body where its state moved it, its colliders' leaves with
# it, and times how long it's been still.
def space::finish(&mut this, s: &solver_scratch, dt: f32): void {
val still := 0.05 * this.unit;
for i in 1..s.states.length {
val b := s.bodies[i] as u64;
val st := &s.states[i];
val began := this.bodies[b].center;
val turned_from := this.bodies[b].at.turn;
val center := began + st.dp;
val turn := (st.dq * turned_from).normalized();
this.bodies[b].center = center;
this.bodies[b].at = pose{ at = center - turn * this.bodies[b].local_center, turn = turn };
this.bodies[b].velocity = st.v;
this.bodies[b].spin = st.w;
this.bodies[b].force = vec3::zero;
this.bodies[b].torque = vec3::zero;
val speed := st.v.length + st.w.length * this.bodies[b].extent;
if !this.bodies[b].can_sleep || speed > still {
this.bodies[b].sleep_time = 0;
} else {
this.bodies[b].sleep_time += dt;
}
val count := this.fast.length;
this.note_fast(b as u32, sweep{ local_center = this.bodies[b].local_center, c1 = began, c2 = center, q1 = turned_from, q2 = turn });
if this.fast.length == count {
this.place_colliders(b as u32);
}
}
this.sweep_fast();
}
+505
View File
@@ -0,0 +1,505 @@
#! Contains `space`, where bodies move: each made of colliders, pulled by
#! gravity, pushed by forces and by what they meet, and stepped forward in
#! time, as `physics2d`'s space steps them in a plane.
#!
#! A step finds the colliders newly near one another, by the boxes of its
#! tree; where those near meet, as contacts kept from the last step, a
#! triangle mesh's one for each triangle met; and then solves them, in
#! substeps, as Box2D's soft step does: each substep moves the bodies'
#! velocities by their forces, pushes them apart where they meet, softly so a
#! deep overlap is undone over a few steps rather than at once, moves them, and
#! pushes again without undoing overlaps, so what was pushed apart doesn't fly.
#! Each contact begins a step with the impulses it ended the last with, so a
#! stack settles and stays still. Bodies that rest long enough, with all they
#! touch, sleep until something wakes them.
#!
#! Lengths are a game's units, and its tolerances are made for a unit of a
#! meter: a space of another unit is made with how many units a meter is.
import std::containers;
import std::math;
import std::time;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
#! Where bodies move, as one step after another moves them.
pub struct space {
#! The pull on every dynamic body, in lengths a second each second.
pub var gravity := vec3{ 0, -10, 0 };
#! How many substeps each step is solved in: more is stiffer and slower.
pub var substeps: u32 = 4;
#! How stiff contacts are, as a spring of so many cycles a second, and how
#! much they're damped: past 1, they don't spring back.
pub var contact_hertz: f32 = 30;
pub var contact_damping: f32 = 10;
#! The same of joints.
pub var joint_hertz: f32 = 60;
pub var joint_damping: f32 = 2;
#! The fastest a contact pushes overlapping bodies apart, in lengths a
#! second.
pub var push_speed: f32 = 3;
#! How fast bodies must meet, in lengths a second, to bounce.
pub var restitution_threshold: f32 = 1;
#! How fast colliders must begin touching, in lengths a second, to be told
#! of as a hit.
pub var hit_speed: f32 = 1;
#! The fastest a body moves, in lengths a second.
pub var max_speed: f32 = 400;
#! Whether bodies at rest sleep.
pub var sleeping: bool = true;
#! Whether dynamic bodies moving fast are swept against what stands still,
#! so they never pass through what's thin.
pub var continuous: bool = true;
#! How many threads each step is solved on, its caller's among them: each
#! color of contacts split between them, so a step gives the same on any
#! number. 1 solves on the caller's alone.
pub var threads: u32 = 1;
#! How long the last step took, and each of its parts.
pub var profile: step_profile;
var crew: crew;
var found: vector<manifold>; # Each pair's, found on the crew.
var unit: f32 = 1;
var fast: vector<fast_body>;
var bodies: vector<body_record>;
var colliders: vector<collider_record>;
var meshes: vector<triangle_mesh>;
var pairs: vector<pair_record>;
var contacts: vector<contact_record>;
var joints: vector<joint_record>;
var free_bodies: vector<u32>;
var free_colliders: vector<u32>;
var free_meshes: vector<u32>;
var free_pairs: vector<u32>;
var free_contacts: vector<u32>;
var free_joints: vector<u32>;
var tree: aabb_tree;
var pair_keys: dict<u64, u32>;
var moved: vector<u32>;
var near: vector<u32>;
var met: vector<met_triangle>;
var noted: vector<contact_event>;
var struck: vector<hit_event>;
var solver: solver_scratch;
var islands: vector<u32>;
}
#! How long a step took, in milliseconds, and each of its parts: finding what
#! newly nears, where it meets, solving it, and finding what sleeps.
pub struct step_profile {
pub var pairs: f64;
pub var contacts: f64;
pub var solve: f64;
pub var sleep: f64;
pub var step: f64;
}
#! A space of no bodies, pulled by a gravity: `unit` is how many of its lengths
#! a meter is, which its tolerances, push speed, bounce threshold, and top
#! speed are scaled by.
pub def space::new(gravity: vec3 = vec3{ 0, -10, 0 }, unit: f32 = 1): space {
return space{
gravity = gravity, unit = unit, push_speed = 3 * unit, restitution_threshold = unit, hit_speed = unit, max_speed = 400 * unit,
tree = aabb_tree::new(0.1 * unit), pair_keys = dict::<u64, u32>::new(),
};
}
# How near two surfaces are taken as touching: what contacts let them overlap
# by, and what they meet at before touching.
val space::slop: f32 {
get => 0.005 * this.unit;
}
val space::speculative: f32 {
get => 4 * this.slop;
}
#! How many bodies it holds.
pub val space::body_count: u64 {
get => this.bodies.length - this.free_bodies.length;
}
#! How many contacts it holds: pairs of shapes, or a shape and a triangle,
#! near enough to meet.
pub val space::contact_count: u64 {
get => this.contacts.length - this.free_contacts.length;
}
#! The contacts that began and ended touching in the last step.
pub def space::events(&this): span<contact_event> {
return this.noted.span;
}
#! Adds a body, of no colliders yet.
pub def space::add(&mut this, made: body): body_id {
var index: u32 = 0;
if this.free_bodies.length > 0 {
index = this.free_bodies[this.free_bodies.length - 1];
this.free_bodies.truncate();
} else {
index = this.bodies.length as u32;
this.bodies.append(body_record{});
}
val generation := this.bodies[index as u64].generation + 1;
val moving := made.kind != body_kind::static;
this.bodies[index as u64] = body_record{
kind = made.kind, generation = generation, alive = true, at = made.at, center = made.at.at,
velocity = moving ? made.velocity : vec3::zero, spin = moving ? made.spin : vec3::zero,
linear_damping = made.linear_damping, angular_damping = made.angular_damping, gravity_scale = made.gravity_scale,
gravity = made.gravity, fixed_rotation = made.fixed_rotation, can_sleep = made.can_sleep, bullet = made.bullet, data = made.data,
};
this.find_mass(index);
return body_id{ index = index, generation = generation };
}
#! Whether a body is of it still.
pub def space::has(&this, id: body_id): bool {
return id.index < this.bodies.length as u32 && this.bodies[id.index as u64].alive && this.bodies[id.index as u64].generation == id.generation;
}
#! Removes a body, its colliders, the contacts they're of, and the joints it's
#! of, waking what it touched.
pub def space::remove(&mut this, id: body_id): void {
return if !this.has(id);
this.wake_body(id.index);
var c := this.bodies[id.index as u64].colliders;
while c != none {
val next := this.colliders[c as u64].next;
this.drop_collider(c);
c = next;
}
this.drop_joints_of(id.index);
this.bodies[id.index as u64].alive = false;
this.bodies[id.index as u64].colliders = none;
this.bodies[id.index as u64].group = none;
this.free_bodies.append(id.index);
}
#! Gives a body a collider, its mass summed again of its colliders'.
pub def space::attach(&mut this, to: body_id, made: collider): collider_id {
return collider_id{} if !this.has(to);
return this.attach_record(to, collider_record{ made = made, body = to.index });
}
#! Gives a static body a heightfield's ground, as a terrain, met as a mesh's
#! triangles are.
pub def space::attach_heightfield(&mut this, to: body_id, field: heightfield, made: collider): collider_id {
var held := move(field);
return this.attach_mesh(to, triangle_mesh::of_field(move(held)), made);
}
#! Gives a static body the triangles of a mesh, as a level's ground and walls,
#! which push what meets each as its face does, but at the edges two don't
#! fold at, so what slides across them doesn't catch. Its shape and density
#! are passed over; a mesh meets shapes, not another mesh.
pub def space::attach_mesh(&mut this, to: body_id, mesh: triangle_mesh, made: collider): collider_id {
var held := move(mesh);
return collider_id{} if !this.has(to);
var m: u32 = 0;
if this.free_meshes.length > 0 {
m = this.free_meshes[this.free_meshes.length - 1];
this.free_meshes.truncate();
this.meshes[m as u64] = move(held);
} else {
m = this.meshes.length as u32;
this.meshes.append(move(held));
}
return this.attach_record(to, collider_record{ made = made, mesh = m, body = to.index });
}
def space::attach_record(&mut this, to: body_id, record: collider_record): collider_id {
var index: u32 = 0;
if this.free_colliders.length > 0 {
index = this.free_colliders[this.free_colliders.length - 1];
this.free_colliders.truncate();
} else {
index = this.colliders.length as u32;
this.colliders.append(collider_record{});
}
val generation := this.colliders[index as u64].generation + 1;
var made := record;
made.next = this.bodies[to.index as u64].colliders;
made.generation = generation;
made.alive = true;
made.moved = true;
this.colliders[index as u64] = made;
val box := this.box_of(index, this.bodies[to.index as u64].at);
this.colliders[index as u64].leaf = this.tree.insert(box, index as u64);
this.bodies[to.index as u64].colliders = index;
this.moved.append(index);
this.find_mass(to.index);
this.wake_body(to.index);
return collider_id{ index = index, generation = generation };
}
# The box holding a collider, where a pose places its body.
def space::box_of(&this, c: u32, at: pose): bounds {
val record := &this.colliders[c as u64];
return record.made.shape.bounds(at) if !record.is_mesh();
val own := this.meshes[record.mesh as u64].bounds();
var made := bounds::blank;
for k in 0..8u {
val corner := vec3{ (k & 1) != 0 ? own.max.x : own.min.x, (k & 2) != 0 ? own.max.y : own.min.y, (k & 4) != 0 ? own.max.z : own.min.z };
made = made.including(at.apply(corner));
}
return made;
}
#! Whether a collider is of it still.
pub def space::has(&this, id: collider_id): bool {
return id.index < this.colliders.length as u32 && this.colliders[id.index as u64].alive && this.colliders[id.index as u64].generation == id.generation;
}
#! Takes a collider from its body, its mass summed again of the rest.
pub def space::detach(&mut this, id: collider_id): void {
return if !this.has(id);
val b := this.colliders[id.index as u64].body;
var c := this.bodies[b as u64].colliders;
if c == id.index {
this.bodies[b as u64].colliders = this.colliders[c as u64].next;
} else {
while c != none {
val next := this.colliders[c as u64].next;
if next == id.index {
this.colliders[c as u64].next = this.colliders[next as u64].next;
break;
}
c = next;
}
}
this.drop_collider(id.index);
this.find_mass(b);
this.wake_body(b);
}
# Frees a collider, its leaf, its mesh, and its pairs.
def space::drop_collider(&mut this, c: u32): void {
for p in 0..this.pairs.length {
if this.pairs[p].alive && (this.pairs[p].a == c || this.pairs[p].b == c) {
this.drop_pair(p as u32, true);
}
}
this.tree.remove(this.colliders[c as u64].leaf);
if this.colliders[c as u64].is_mesh() {
val m := this.colliders[c as u64].mesh;
this.meshes[m as u64] = triangle_mesh::new(span::<vec3>::blank(), span::<u32>::blank());
this.free_meshes.append(m);
}
this.colliders[c as u64].alive = false;
this.free_colliders.append(c);
}
#! The body a collider is of.
pub def space::body_of(&this, id: collider_id): body_id {
return body_id{} if !this.has(id);
val b := this.colliders[id.index as u64].body;
return body_id{ index = b, generation = this.bodies[b as u64].generation };
}
#! What a collider was made as.
pub def space::collider_of(&this, id: collider_id): &collider {
return &this.colliders[id.index as u64].made;
}
#! The number its user gave a body.
pub def space::data_of(&this, id: body_id): u64 {
return this.bodies[id.index as u64].data;
}
#! What kind of body it is.
pub def space::kind_of(&this, id: body_id): body_kind {
return this.bodies[id.index as u64].kind;
}
#! Where a body is, and which way it's turned.
pub def space::pose_of(&this, id: body_id): pose {
return this.bodies[id.index as u64].at;
}
#! How fast a body's center of mass moves, and how fast it turns.
pub def space::velocity_of(&this, id: body_id): vec3 {
return this.bodies[id.index as u64].velocity;
}
pub def space::spin_of(&this, id: body_id): vec3 {
return this.bodies[id.index as u64].spin;
}
#! A body's mass, its center of its own places, and its inertia tensor about
#! that center.
pub def space::mass_of(&this, id: body_id): mass_data {
val b := &this.bodies[id.index as u64];
return mass_data{ mass = b.mass, center = b.local_center, inertia = b.inertia };
}
#! Where a body's center of mass is in space.
pub def space::center_of(&this, id: body_id): vec3 {
return this.bodies[id.index as u64].center;
}
#! Whether a body is awake, as it is but where it and all it rests on have
#! been still long enough.
pub def space::is_awake(&this, id: body_id): bool {
return this.bodies[id.index as u64].awake;
}
#! Puts a body somewhere, as it is at once, waking it.
pub def space::set_pose(&mut this, id: body_id, at: pose): void {
return if !this.has(id);
this.bodies[id.index as u64].at = at;
this.bodies[id.index as u64].center = at.apply(this.bodies[id.index as u64].local_center);
this.place_colliders(id.index);
this.wake_body(id.index);
}
#! Sets how fast a body moves, waking it.
pub def space::set_velocity(&mut this, id: body_id, velocity: vec3): void {
return if !this.has(id) || this.bodies[id.index as u64].kind == body_kind::static;
this.bodies[id.index as u64].velocity = velocity;
if velocity.length_squared > 0 {
this.wake_body(id.index);
}
}
#! Sets how fast a body turns, waking it.
pub def space::set_spin(&mut this, id: body_id, spin: vec3): void {
return if !this.has(id) || this.bodies[id.index as u64].kind == body_kind::static || this.bodies[id.index as u64].fixed_rotation;
this.bodies[id.index as u64].spin = spin;
if spin.length_squared > 0 {
this.wake_body(id.index);
}
}
#! Sets a body's own gravity, added to the space's, as a planet's pull changes
#! as the body goes around it; waking it where that turns or grows it by more
#! than a hundredth, so a body asleep stays so as the pull is found again.
pub def space::set_gravity(&mut this, id: body_id, gravity: vec3): void {
return if !this.has(id);
val i := id.index as u64;
val was := this.bodies[i].gravity;
this.bodies[i].gravity = gravity;
if (gravity - was).length_squared > 1e-4 * math::max(gravity.length_squared, was.length_squared) {
this.wake_body(id.index);
}
}
#! A body's own gravity, added to the space's.
pub def space::gravity_of(&this, id: body_id): vec3 {
return this.bodies[id.index as u64].gravity;
}
#! Pushes a dynamic body through the next step by a force at a place of space,
#! which turns it too where that's off its center, waking it.
pub def space::apply_force(&mut this, id: body_id, force: vec3, at: vec3): void {
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
val i := id.index as u64;
this.bodies[i].force = this.bodies[i].force + force;
this.bodies[i].torque = this.bodies[i].torque + (at - this.bodies[i].center).cross(force);
this.wake_body(id.index);
}
#! Pushes a dynamic body through the next step by a force at its center,
#! waking it.
pub def space::apply_force_to_center(&mut this, id: body_id, force: vec3): void {
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
this.bodies[id.index as u64].force = this.bodies[id.index as u64].force + force;
this.wake_body(id.index);
}
#! Turns a dynamic body through the next step by a torque, waking it.
pub def space::apply_torque(&mut this, id: body_id, torque: vec3): void {
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
this.bodies[id.index as u64].torque = this.bodies[id.index as u64].torque + torque;
this.wake_body(id.index);
}
#! Changes how fast a dynamic body moves and turns at once, as a blow at a
#! place of space does, waking it.
pub def space::apply_impulse(&mut this, id: body_id, impulse: vec3, at: vec3): void {
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
val i := id.index as u64;
this.bodies[i].velocity = this.bodies[i].velocity + impulse * this.bodies[i].inv_mass;
this.bodies[i].spin = this.bodies[i].spin + this.world_inverse_inertia(id.index) * (at - this.bodies[i].center).cross(impulse);
this.wake_body(id.index);
}
#! Wakes a body, and those it sleeps with.
pub def space::wake(&mut this, id: body_id): void {
if this.has(id) {
this.wake_body(id.index);
}
}
# A body's inverse inertia tensor, of space's axes as it's turned.
def space::world_inverse_inertia(&this, b: u32): mat3 {
val body := &this.bodies[b as u64];
val r := mat3::rotation(body.at.turn);
return r * body.inv_inertia * r.transposed();
}
# Sums a body's mass of its colliders', where it's dynamic, and how far they
# reach from its center.
def space::find_mass(&mut this, b: u32): void {
var sum := mass_data{};
if this.bodies[b as u64].is_dynamic() {
var c := this.bodies[b as u64].colliders;
while c != none {
val record := &this.colliders[c as u64];
if !record.is_mesh() && record.made.density > 0 {
sum = sum.add(record.made.shape.mass(record.made.density));
}
c = record.next;
}
}
var mass: f32 = 0;
var inertia := mat3{};
var inverse := mat3{};
var local := vec3::zero;
if this.bodies[b as u64].is_dynamic() {
# A dynamic body of no mass moves as one of 1.
mass = sum.mass > 0 ? sum.mass : 1f;
local = sum.center;
if sum.mass > 0 && !this.bodies[b as u64].fixed_rotation && sum.inertia.determinant > 0 {
inertia = sum.inertia;
inverse = sum.inertia.inverse();
}
}
var extent: f32 = 0;
var least: f32 = 0;
var c := this.bodies[b as u64].colliders;
while c != none {
val record := &this.colliders[c as u64];
if !record.is_mesh() {
val box := record.made.shape.bounds(pose::identity);
extent = math::max(extent, (box.max - local).length);
extent = math::max(extent, (box.min - local).length);
val reach := record.made.shape.least_reach();
least = least == 0 ? reach : math::min(least, reach);
}
c = record.next;
}
val i := b as u64;
this.bodies[i].mass = mass;
this.bodies[i].inv_mass = mass > 0 ? 1 / mass : 0f;
this.bodies[i].inertia = inertia;
this.bodies[i].inv_inertia = inverse;
this.bodies[i].local_center = local;
this.bodies[i].center = this.bodies[i].at.apply(local);
this.bodies[i].extent = extent;
this.bodies[i].least = least;
}
# Puts a body's colliders' leaves where it is, each that leaves its grown box
# to find what it newly nears.
def space::place_colliders(&mut this, b: u32): void {
val at := this.bodies[b as u64].at;
var c := this.bodies[b as u64].colliders;
while c != none {
val box := this.box_of(c, at);
if this.tree.move(this.colliders[c as u64].leaf, box) && !this.colliders[c as u64].moved {
this.colliders[c as u64].moved = true;
this.moved.append(c);
}
c = this.colliders[c as u64].next;
}
}
+76
View File
@@ -0,0 +1,76 @@
#! Contains how a space steps forward in time, and what rays meet in it.
import std::containers;
import std::math;
import std::time;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
#! Steps the space forward in time: finds what's newly near, where it meets,
#! and moves its bodies, pushed apart where they meet. Events of what began
#! and stopped touching are those of this step alone after.
pub def space::step(&mut this, dt: f32): void {
this.noted.clear();
this.struck.clear();
return if dt <= 0;
val began := instant::now();
this.crew.start(this.threads);
this.find_pairs();
val paired := instant::now();
this.update_contacts();
val met := instant::now();
this.solve(dt);
val solved := instant::now();
if this.sleeping {
this.sleep_islands(dt);
}
val slept := instant::now();
this.profile = step_profile{
pairs = milliseconds(paired - began), contacts = milliseconds(met - paired),
solve = milliseconds(solved - met), sleep = milliseconds(slept - solved), step = milliseconds(slept - began),
};
}
def milliseconds(d: duration): f64 {
return d.in_nanoseconds as f64 / 1e6;
}
#! Where a ray met a space's collider: which, of which body, where, and of a
#! mesh's, which triangle.
pub struct space_hit {
pub var collider: collider_id;
pub var body: body_id;
pub var distance: f32;
pub var point: vec3;
pub var normal: vec3;
pub var triangle: u32 = 0xFFFFFFFF;
}
#! Where a ray first meets a collider on a layer of a mask, sensors passed
#! over: from a place, along a direction of length 1, as far as `reach`.
pub def space::ray_cast(&this, origin: vec3, direction: vec3, reach: f32, mask: u32 = 0xFFFFFFFF): maybe<space_hit> {
return this.ray_cast(origin, direction, reach, query_filter{ mask = mask });
}
#! Where a ray first meets a collider a filter asks of, as `ray_cast` casts
#! it.
pub def space::ray_cast(&this, origin: vec3, direction: vec3, reach: f32, filter: query_filter): maybe<space_hit> {
var best: maybe<space_hit> = nothing{};
this.tree.ray_cast(origin, direction, reach, def(leaf: u32, data: u64, so_far: f32): f32 {
val c := &this.colliders[data];
return so_far if !this.passes(data as u32, &filter);
val at := this.bodies[c.body as u64].at;
val named := collider_id{ index = data as u32, generation = c.generation };
val of := body_id{ index = c.body, generation = this.bodies[c.body as u64].generation };
if c.is_mesh() {
val met := this.meshes[c.mesh as u64].ray_cast(at, origin, direction, so_far) else { return so_far; };
best = space_hit{ collider = named, body = of, distance = met.distance, point = met.point, normal = met.normal, triangle = met.triangle };
return met.distance;
}
val met := c.made.shape.ray_cast(at, origin, direction, so_far) else { return so_far; };
best = space_hit{ collider = named, body = of, distance = met.distance, point = met.point, normal = met.normal };
return met.distance;
});
return best;
}
+382
View File
@@ -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);
}
+544
View File
@@ -0,0 +1,544 @@
#! Contains how a space solves its contacts eight at a time, as in a plane:
#! each step, every contact is given the first of 24 colors none of its dynamic
#! bodies has yet, so no two contacts of a color push the same body, and the
#! contacts of each color are solved as the lanes of `f32x8`s, eight at once,
#! each body's velocities gathered from where its state is and scattered back.
#! What fits no color is solved one at a time after.
#!
#! A body's inverse inertia, as it's turned as the step begins, is worked into
#! each point's levers as the contacts are packed, so the lanes turn a body by
#! what's packed, never a matrix of their own.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
# How many colors contacts are sorted into.
const colors: u64 = 24;
# How many contacts are solved at once, and the vectors of their numbers.
const width: u64 = 8;
type lanes = f32x8;
type lane_places = i32x8;
# How many numbers a body's state is: its velocities, how far it's moved, and
# how it's turned, each of four.
const state_numbers: u64 = 16;
# A point of eight contacts, a lane each: where it is from each body's
# center, how far apart they are there but for how far they've moved, the
# impulses pushing them apart and along each tangent, how hard each is to push,
# and how each body turns by an impulse along each, its inverse inertia times
# its lever. A lane of a contact of fewer points has the rest of no mass, which
# push nothing.
struct wide_point {
var rax: lanes;
var ray: lanes;
var raz: lanes;
var rbx: lanes;
var rby: lanes;
var rbz: lanes;
var base: lanes;
var normal: lanes;
var tangent1: lanes;
var tangent2: lanes;
var most: lanes;
var mass_n: lanes;
var mass_1: lanes;
var mass_2: lanes;
var nax: lanes;
var nay: lanes;
var naz: lanes;
var nbx: lanes;
var nby: lanes;
var nbz: lanes;
var sax: lanes; # Along the first tangent.
var say: lanes;
var saz: lanes;
var sbx: lanes;
var sby: lanes;
var sbz: lanes;
var tax: lanes; # Along the second.
var tay: lanes;
var taz: lanes;
var tbx: lanes;
var tby: lanes;
var tbz: lanes;
}
# Eight contacts as lanes: where each body's state begins among the states'
# numbers, the normal and tangents, friction, each body's inverse mass, and how
# soft each is. A lane of no contact is of the state of what doesn't move.
struct wide_contact {
var a: lane_places;
var b: lane_places;
var nx: lanes;
var ny: lanes;
var nz: lanes;
var t1x: lanes;
var t1y: lanes;
var t1z: lanes;
var t2x: lanes;
var t2y: lanes;
var t2z: lanes;
var friction: lanes;
var ma: lanes;
var mb: lanes;
var bias_rate: lanes;
var mass_scale: lanes;
var impulse_scale: lanes;
var points: wide_point[4];
var of: u32[8]; # Each lane's constraint, or none.
}
# The states' numbers, sixteen to a state, as `wide_contact`'s lanes gather
# them.
def numbers_of(s: &mut solver_scratch): slice<f32> {
return slice::<f32>::over(s.states.data as *mut f32, s.states.length * state_numbers);
}
# Sorts the step's contacts into colors, and packs each color's into lanes.
def color_contacts(s: &mut solver_scratch): void {
s.wide.clear();
s.overflow.clear();
val words := (s.states.length + 63) / 64;
s.colored.clear();
s.colored.resize(colors * words, 0);
s.color_of.clear();
s.color_of.resize(s.constraints.length, none);
var counts: u32[24];
for k in 0..s.constraints.length {
val c := &s.constraints[k];
# Only a body that's pushed is a body two lanes mustn't share.
val a := c.ma > 0 ? c.a as u64 : 0u;
val b := c.mb > 0 ? c.b as u64 : 0u;
for color in 0..colors {
val row := color * words;
continue if a != 0 && ((s.colored[row + a / 64] >> (a % 64)) & 1) != 0;
continue if b != 0 && ((s.colored[row + b / 64] >> (b % 64)) & 1) != 0;
if a != 0 {
s.colored[row + a / 64] = s.colored[row + a / 64] | (1u << (a % 64));
}
if b != 0 {
s.colored[row + b / 64] = s.colored[row + b / 64] | (1u << (b % 64));
}
s.color_of[k] = color as u32;
counts[color]++;
break;
}
if s.color_of[k] == none {
s.overflow.append(k as u32);
}
}
var first: u32[24];
var groups: u64 = 0;
for color in 0..colors {
first[color] = groups as u32;
s.color_groups[color] = groups as u32;
groups += (counts[color] as u64 + width - 1) / width;
}
s.color_groups[colors] = groups as u32;
s.wide.resize(groups, wide_contact{});
for g in 0..groups {
for lane in 0..width {
s.wide[g].of[lane] = none;
}
}
var filled: u32[24];
for k in 0..s.constraints.length {
val color := s.color_of[k];
continue if color == none;
val at := filled[color as u64];
filled[color as u64]++;
val c := &s.constraints[k];
pack(&mut s.wide[(first[color as u64] as u64 + at as u64 / width)], at as u64 % width, c, k as u32, s.inertias[c.a as u64], s.inertias[c.b as u64]);
}
}
# Puts a contact into a lane.
def pack(w: &mut wide_contact, lane: u64, c: &contact_constraint, k: u32, ia: mat3, ib: mat3): void {
w.of[lane] = k;
w.a[lane] = (c.a as u64 * state_numbers) as i32;
w.b[lane] = (c.b as u64 * state_numbers) as i32;
w.nx[lane] = c.normal.x;
w.ny[lane] = c.normal.y;
w.nz[lane] = c.normal.z;
w.t1x[lane] = c.t1.x;
w.t1y[lane] = c.t1.y;
w.t1z[lane] = c.t1.z;
w.t2x[lane] = c.t2.x;
w.t2y[lane] = c.t2.y;
w.t2z[lane] = c.t2.z;
w.friction[lane] = c.friction;
w.ma[lane] = c.ma;
w.mb[lane] = c.mb;
w.bias_rate[lane] = c.soft.bias_rate;
w.mass_scale[lane] = c.soft.mass_scale;
w.impulse_scale[lane] = c.soft.impulse_scale;
for j in 0..c.count {
val p := &c.points[j];
val q := &mut w.points[j];
val ra := p.anchor_a;
val rb := p.anchor_b;
q.rax[lane] = ra.x;
q.ray[lane] = ra.y;
q.raz[lane] = ra.z;
q.rbx[lane] = rb.x;
q.rby[lane] = rb.y;
q.rbz[lane] = rb.z;
q.base[lane] = p.base_separation;
q.normal[lane] = p.normal_impulse;
q.tangent1[lane] = p.tangent_impulse.x;
q.tangent2[lane] = p.tangent_impulse.y;
q.mass_n[lane] = p.normal_mass;
q.mass_1[lane] = p.tangent_mass.x;
q.mass_2[lane] = p.tangent_mass.y;
val na := ia * ra.cross(c.normal);
val nb := ib * rb.cross(c.normal);
val sa := ia * ra.cross(c.t1);
val sb := ib * rb.cross(c.t1);
val ta := ia * ra.cross(c.t2);
val tb := ib * rb.cross(c.t2);
q.nax[lane] = na.x;
q.nay[lane] = na.y;
q.naz[lane] = na.z;
q.nbx[lane] = nb.x;
q.nby[lane] = nb.y;
q.nbz[lane] = nb.z;
q.sax[lane] = sa.x;
q.say[lane] = sa.y;
q.saz[lane] = sa.z;
q.sbx[lane] = sb.x;
q.sby[lane] = sb.y;
q.sbz[lane] = sb.z;
q.tax[lane] = ta.x;
q.tay[lane] = ta.y;
q.taz[lane] = ta.z;
q.tbx[lane] = tb.x;
q.tby[lane] = tb.y;
q.tbz[lane] = tb.z;
}
}
# Gives each lane's impulses back to its contact, to bounce and keep.
def unpack_contacts(s: &mut solver_scratch): void {
for g in 0..s.wide.length {
for lane in 0..width {
val k := s.wide[g].of[lane];
continue if k == none;
for j in 0..s.constraints[k as u64].count {
val q := &s.wide[g].points[j];
val p := &mut s.constraints[k as u64].points[j];
p.normal_impulse = q.normal[lane];
p.tangent_impulse = vec3{ q.tangent1[lane], q.tangent2[lane], 0 };
p.max_impulse = math::max(p.max_impulse, q.most[lane]);
}
}
}
}
# Which lanes push a body, by its inverse mass: those of what doesn't move, or
# isn't pushed, as a kinematic body, aren't written back, as lanes on other
# threads read its state.
def pushed(m: lanes): bool[8] {
val ms := m.lanes();
var made: bool[8];
for k in 0..width {
made[k] = ms[k] > 0;
}
return made;
}
# Each lane's square root, a lane at a time.
def root_of(x: lanes): lanes {
var each := x.lanes();
for i in 0..width {
each[i] = math::sqrt(each[i]);
}
return lanes::of(each);
}
# A stage of a step's lanes, run on the space's crew a color at a time: the
# lanes of each color split between its threads, as no two lanes of a color
# push one body.
struct wide_job {
var s: *mut solver_scratch;
var first: u64;
var warming: bool;
var inv_h: f32;
var push: f32;
var use_bias: bool;
}
def run_wide(context: *mut u8, begin: u64, end: u64): void {
val job := &through(context as *mut wide_job);
val s := &mut through(job.s);
if job.warming {
warm_groups(s, job.first + begin, job.first + end);
} else {
solve_groups(s, job.first + begin, job.first + end, job.inv_h, job.push, job.use_bias);
}
}
# Warms or solves the lanes, on the crew where the space has one, a color at a
# time.
def space::wide_stage(&mut this, s: &mut solver_scratch, warming: bool, inv_h: f32, push: f32, use_bias: bool): void {
if this.threads <= 1 {
if warming {
warm_groups(s, 0, s.wide.length);
} else {
solve_groups(s, 0, s.wide.length, inv_h, push, use_bias);
}
return;
}
var job := wide_job{ s = address(s), warming = warming, inv_h = inv_h, push = push, use_bias = use_bias };
for color in 0..colors {
val from := s.color_groups[color] as u64;
val to := s.color_groups[color + 1] as u64;
continue if to == from;
job.first = from;
val block := math::max((to - from) / (this.threads as u64 * 4), 1u);
this.crew.run(run_wide, address(&mut job) as *mut u8, to - from, block);
}
}
# Writes each pushed lane's number back to where it was gathered from.
def put(v: lanes, into: slice<f32>, at: lane_places, keep: &bool[8]): void {
val each := v.lanes();
val places := at.lanes();
for k in 0..width {
if keep[k] {
into[places[k] as u64] = each[k];
}
}
}
def warm_groups(s: &mut solver_scratch, from: u64, to: u64): void {
val numbers := numbers_of(s);
val view := numbers.span;
val one := lane_places::splat(1);
val two := lane_places::splat(2);
val four := lane_places::splat(4);
val five := lane_places::splat(5);
val six := lane_places::splat(6);
val groups := s.wide.slice;
for g in from..to {
val w := &groups[g];
val keep_a := pushed(w.ma);
val keep_b := pushed(w.mb);
var vax := lanes::gather(view, w.a);
var vay := lanes::gather(view, w.a + one);
var vaz := lanes::gather(view, w.a + two);
var wax := lanes::gather(view, w.a + four);
var way := lanes::gather(view, w.a + five);
var waz := lanes::gather(view, w.a + six);
var vbx := lanes::gather(view, w.b);
var vby := lanes::gather(view, w.b + one);
var vbz := lanes::gather(view, w.b + two);
var wbx := lanes::gather(view, w.b + four);
var wby := lanes::gather(view, w.b + five);
var wbz := lanes::gather(view, w.b + six);
for j in 0..4u {
val p := &w.points[j];
val n := p.normal;
val t1 := p.tangent1;
val t2 := p.tangent2;
val px := w.nx * n + w.t1x * t1 + w.t2x * t2;
val py := w.ny * n + w.t1y * t1 + w.t2y * t2;
val pz := w.nz * n + w.t1z * t1 + w.t2z * t2;
vax = vax - px * w.ma;
vay = vay - py * w.ma;
vaz = vaz - pz * w.ma;
vbx = vbx + px * w.mb;
vby = vby + py * w.mb;
vbz = vbz + pz * w.mb;
wax = wax - (p.nax * n + p.sax * t1 + p.tax * t2);
way = way - (p.nay * n + p.say * t1 + p.tay * t2);
waz = waz - (p.naz * n + p.saz * t1 + p.taz * t2);
wbx = wbx + (p.nbx * n + p.sbx * t1 + p.tbx * t2);
wby = wby + (p.nby * n + p.sby * t1 + p.tby * t2);
wbz = wbz + (p.nbz * n + p.sbz * t1 + p.tbz * t2);
}
put(vax, numbers, w.a, &keep_a);
put(vay, numbers, w.a + one, &keep_a);
put(vaz, numbers, w.a + two, &keep_a);
put(wax, numbers, w.a + four, &keep_a);
put(way, numbers, w.a + five, &keep_a);
put(waz, numbers, w.a + six, &keep_a);
put(vbx, numbers, w.b, &keep_b);
put(vby, numbers, w.b + one, &keep_b);
put(vbz, numbers, w.b + two, &keep_b);
put(wbx, numbers, w.b + four, &keep_b);
put(wby, numbers, w.b + five, &keep_b);
put(wbz, numbers, w.b + six, &keep_b);
}
}
def solve_groups(s: &mut solver_scratch, from: u64, to: u64, inv_h: f32, push: f32, use_bias: bool): void {
val numbers := numbers_of(s);
val view := numbers.span;
val one := lane_places::splat(1);
val two := lane_places::splat(2);
val four := lane_places::splat(4);
val five := lane_places::splat(5);
val six := lane_places::splat(6);
val eight := lane_places::splat(8);
val nine := lane_places::splat(9);
val ten := lane_places::splat(10);
val twelve := lane_places::splat(12);
val thirteen := lane_places::splat(13);
val fourteen := lane_places::splat(14);
val fifteen := lane_places::splat(15);
val zero := lanes::splat(0);
val unit := lanes::splat(1);
val doubled := lanes::splat(2);
val per_h := lanes::splat(inv_h);
val least := lanes::splat(-push);
val groups := s.wide.slice;
for g in from..to {
val w := &mut groups[g];
val keep_a := pushed(w.ma);
val keep_b := pushed(w.mb);
var vax := lanes::gather(view, w.a);
var vay := lanes::gather(view, w.a + one);
var vaz := lanes::gather(view, w.a + two);
var wax := lanes::gather(view, w.a + four);
var way := lanes::gather(view, w.a + five);
var waz := lanes::gather(view, w.a + six);
var vbx := lanes::gather(view, w.b);
var vby := lanes::gather(view, w.b + one);
var vbz := lanes::gather(view, w.b + two);
var wbx := lanes::gather(view, w.b + four);
var wby := lanes::gather(view, w.b + five);
var wbz := lanes::gather(view, w.b + six);
val dpx := lanes::gather(view, w.b + eight) - lanes::gather(view, w.a + eight);
val dpy := lanes::gather(view, w.b + nine) - lanes::gather(view, w.a + nine);
val dpz := lanes::gather(view, w.b + ten) - lanes::gather(view, w.a + ten);
val qax := lanes::gather(view, w.a + twelve);
val qay := lanes::gather(view, w.a + thirteen);
val qaz := lanes::gather(view, w.a + fourteen);
val qaw := lanes::gather(view, w.a + fifteen);
val qbx := lanes::gather(view, w.b + twelve);
val qby := lanes::gather(view, w.b + thirteen);
val qbz := lanes::gather(view, w.b + fourteen);
val qbw := lanes::gather(view, w.b + fifteen);
val nx := w.nx;
val ny := w.ny;
val nz := w.nz;
val ma := w.ma;
val mb := w.mb;
for j in 0..4u {
val p := &mut w.points[j];
val rax := p.rax;
val ray := p.ray;
val raz := p.raz;
val rbx := p.rbx;
val rby := p.rby;
val rbz := p.rbz;
# Each anchor as its body has turned since the step began: r + w·t +
# q × t, of t = 2 q × r.
val tax := doubled * (qay * raz - qaz * ray);
val tay := doubled * (qaz * rax - qax * raz);
val taz := doubled * (qax * ray - qay * rax);
val tbx := doubled * (qby * rbz - qbz * rby);
val tby := doubled * (qbz * rbx - qbx * rbz);
val tbz := doubled * (qbx * rby - qby * rbx);
val dx := dpx + (rbx + qbw * tbx + (qby * tbz - qbz * tby)) - (rax + qaw * tax + (qay * taz - qaz * tay));
val dy := dpy + (rby + qbw * tby + (qbz * tbx - qbx * tbz)) - (ray + qaw * tay + (qaz * tax - qax * taz));
val dz := dpz + (rbz + qbw * tbz + (qbx * tby - qby * tbx)) - (raz + qaw * taz + (qax * tay - qay * tax));
val separation := dx * nx + dy * ny + dz * nz + p.base;
val apart := separation.greater(&zero);
var bias := select(apart, separation * per_h, zero);
var mass_scale := unit;
var impulse_scale := zero;
if use_bias {
bias = select(apart, bias, (w.bias_rate * separation).max(&least));
mass_scale = select(apart, unit, w.mass_scale);
impulse_scale = select(apart, zero, w.impulse_scale);
}
# How fast they close: along the normal, and as each turns about its
# lever across it.
val vn := (vbx - vax) * nx + (vby - vay) * ny + (vbz - vaz) * nz
+ wbx * (rby * nz - rbz * ny) + wby * (rbz * nx - rbx * nz) + wbz * (rbx * ny - rby * nx)
- wax * (ray * nz - raz * ny) - way * (raz * nx - rax * nz) - waz * (rax * ny - ray * nx);
val before := p.normal;
val sum := (before - p.mass_n * mass_scale * (vn + bias) - impulse_scale * before).max(&zero);
val impulse := sum - before;
p.normal = sum;
p.most = p.most.max(&impulse);
vax = vax - nx * impulse * ma;
vay = vay - ny * impulse * ma;
vaz = vaz - nz * impulse * ma;
vbx = vbx + nx * impulse * mb;
vby = vby + ny * impulse * mb;
vbz = vbz + nz * impulse * mb;
wax = wax - p.nax * impulse;
way = way - p.nay * impulse;
waz = waz - p.naz * impulse;
wbx = wbx + p.nbx * impulse;
wby = wby + p.nby * impulse;
wbz = wbz + p.nbz * impulse;
}
# Friction along both tangents, of no more in all than its share of what
# pushes them apart.
val t1x := w.t1x;
val t1y := w.t1y;
val t1z := w.t1z;
val t2x := w.t2x;
val t2y := w.t2y;
val t2z := w.t2z;
for j in 0..4u {
val p := &mut w.points[j];
val rax := p.rax;
val ray := p.ray;
val raz := p.raz;
val rbx := p.rbx;
val rby := p.rby;
val rbz := p.rbz;
val dvx := vbx + (wby * rbz - wbz * rby) - vax - (way * raz - waz * ray);
val dvy := vby + (wbz * rbx - wbx * rbz) - vay - (waz * rax - wax * raz);
val dvz := vbz + (wbx * rby - wby * rbx) - vaz - (wax * ray - way * rax);
val before1 := p.tangent1;
val before2 := p.tangent2;
var sum1 := before1 - p.mass_1 * (dvx * t1x + dvy * t1y + dvz * t1z);
var sum2 := before2 - p.mass_2 * (dvx * t2x + dvy * t2y + dvz * t2z);
val most := w.friction * p.normal;
val squared := sum1 * sum1 + sum2 * sum2;
val most_squared := most * most;
val over := squared.greater(&most_squared);
val scale := select(over, most / root_of(select(over, squared, unit)), unit);
sum1 = sum1 * scale;
sum2 = sum2 * scale;
p.tangent1 = sum1;
p.tangent2 = sum2;
val d1 := sum1 - before1;
val d2 := sum2 - before2;
val px := t1x * d1 + t2x * d2;
val py := t1y * d1 + t2y * d2;
val pz := t1z * d1 + t2z * d2;
vax = vax - px * ma;
vay = vay - py * ma;
vaz = vaz - pz * ma;
vbx = vbx + px * mb;
vby = vby + py * mb;
vbz = vbz + pz * mb;
wax = wax - (p.sax * d1 + p.tax * d2);
way = way - (p.say * d1 + p.tay * d2);
waz = waz - (p.saz * d1 + p.taz * d2);
wbx = wbx + (p.sbx * d1 + p.tbx * d2);
wby = wby + (p.sby * d1 + p.tby * d2);
wbz = wbz + (p.sbz * d1 + p.tbz * d2);
}
put(vax, numbers, w.a, &keep_a);
put(vay, numbers, w.a + one, &keep_a);
put(vaz, numbers, w.a + two, &keep_a);
put(wax, numbers, w.a + four, &keep_a);
put(way, numbers, w.a + five, &keep_a);
put(waz, numbers, w.a + six, &keep_a);
put(vbx, numbers, w.b, &keep_b);
put(vby, numbers, w.b + one, &keep_b);
put(vbz, numbers, w.b + two, &keep_b);
put(wbx, numbers, w.b + four, &keep_b);
put(wby, numbers, w.b + five, &keep_b);
put(wbz, numbers, w.b + six, &keep_b);
}
}