Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-31 07:24:40 -05:00
commit c36061ea3e
64 files changed
+13419

No files matched your search

+421
View File
@@ -0,0 +1,421 @@
#! 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 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;
}
# 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);
val max_spin := most_turn * inv_h;
for i in 0..n {
integrate_velocities(&mut s, this.max_speed, max_spin);
this.warm_joints(&mut s);
warm_contacts(&mut s);
this.solve_joints(&mut s, h, true);
solve_contacts(&mut s, inv_h, this.push_speed, true);
integrate_positions(&mut s, h);
this.solve_joints(&mut s, h, false);
solve_contacts(&mut s, inv_h, this.push_speed, false);
}
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_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);
}
}
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;
}
}
def warm_contacts(s: &mut solver_scratch): void {
for i in 0..s.constraints.length {
val c := &s.constraints[i];
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 i in 0..constraints.length {
val c := &mut constraints[i];
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 center := this.bodies[b].center + st.dp;
val turn := (st.dq * this.bodies[b].at.turn).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;
}
this.place_colliders(b as u32);
}
}