Initial Commit
This commit is contained in:
64 files changed
+13419
No files matched your search
@@ -0,0 +1,94 @@
|
||||
#! Contains `aabb`, a box along the plane's axes, as what holds a shape, and
|
||||
#! what an `aabb_tree` sorts.
|
||||
|
||||
import std::math;
|
||||
import std::serial;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! A box along the plane's axes, from its least corner to its greatest.
|
||||
@serial
|
||||
pub struct aabb {
|
||||
@serial pub var min: vec2;
|
||||
@serial pub var max: vec2;
|
||||
}
|
||||
|
||||
#! The box of a middle, reaching so far each way.
|
||||
pub def aabb::around(center: vec2, half: vec2): aabb {
|
||||
return aabb{ center - half, center + half };
|
||||
}
|
||||
|
||||
pub def aabb::equals(&this, other: &aabb): bool {
|
||||
return this.min == other.min && this.max == other.max;
|
||||
}
|
||||
|
||||
pub val aabb::center: vec2 {
|
||||
get => (this.min + this.max) * 0.5;
|
||||
}
|
||||
|
||||
#! How far it reaches each way from its middle.
|
||||
pub val aabb::half_size: vec2 {
|
||||
get => (this.max - this.min) * 0.5;
|
||||
}
|
||||
|
||||
pub val aabb::size: vec2 {
|
||||
get => this.max - this.min;
|
||||
}
|
||||
|
||||
#! How far around it is, which an `aabb_tree` weighs where to put a box by.
|
||||
pub val aabb::perimeter: f32 {
|
||||
get => 2 * ((this.max.x - this.min.x) + (this.max.y - this.min.y));
|
||||
}
|
||||
|
||||
#! Whether a place is within it, its edges among it.
|
||||
pub def aabb::contains(&this, p: vec2): bool {
|
||||
return p.x >= this.min.x && p.x <= this.max.x && p.y >= this.min.y && p.y <= this.max.y;
|
||||
}
|
||||
|
||||
#! Whether it holds another box whole.
|
||||
pub def aabb::encloses(&this, other: aabb): bool {
|
||||
return other.min.x >= this.min.x && other.min.y >= this.min.y && other.max.x <= this.max.x && other.max.y <= this.max.y;
|
||||
}
|
||||
|
||||
#! Whether it and another box meet, touching among it.
|
||||
pub def aabb::overlaps(&this, other: aabb): bool {
|
||||
return other.min.x <= this.max.x && other.max.x >= this.min.x && other.min.y <= this.max.y && other.max.y >= this.min.y;
|
||||
}
|
||||
|
||||
#! The least box holding it and another.
|
||||
pub def aabb::merged(&this, other: aabb): aabb {
|
||||
return aabb{ this.min.min(other.min), this.max.max(other.max) };
|
||||
}
|
||||
|
||||
#! It grown so far each way.
|
||||
pub def aabb::grown(&this, by: f32): aabb {
|
||||
return aabb{ this.min - vec2{ by, by }, this.max + vec2{ by, by } };
|
||||
}
|
||||
|
||||
#! How far along a ray it's first met, from a place, along a direction, as far
|
||||
#! as `reach` lengths of the direction: 0 where the place is within it.
|
||||
pub def aabb::ray_hit(&this, origin: vec2, direction: vec2, reach: f32): maybe<f32> {
|
||||
var low: f32 = 0;
|
||||
var high := reach;
|
||||
val origins: f32[2] = [origin.x, origin.y];
|
||||
val ways: f32[2] = [direction.x, direction.y];
|
||||
val lows: f32[2] = [this.min.x, this.min.y];
|
||||
val highs: f32[2] = [this.max.x, this.max.y];
|
||||
for i in 0..2u {
|
||||
if math::abs(ways[i]) < tiny {
|
||||
return nothing{} 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 nothing{} if low > high;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
#! 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::physics2d;
|
||||
|
||||
#! 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: vec2;
|
||||
#! How fast it turns, in radians a second, counterclockwise.
|
||||
pub var spin: f32;
|
||||
#! 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;
|
||||
#! How much of the space's gravity pulls it: 0 floats.
|
||||
pub var gravity_scale: f32 = 1;
|
||||
#! 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;
|
||||
#! 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 grid, which `space::attach_grid`
|
||||
#! gives a body, has no shape or density of its own.
|
||||
pub struct collider {
|
||||
pub var shape: shape;
|
||||
#! Its mass for each area 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, 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: vec2; # Its center of mass, in the plane.
|
||||
var local_center: vec2; # The same, of its own places.
|
||||
var velocity: vec2;
|
||||
var spin: f32;
|
||||
var force: vec2;
|
||||
var torque: f32;
|
||||
var mass: f32;
|
||||
var inv_mass: f32;
|
||||
var inertia: f32; # About its center of mass.
|
||||
var inv_inertia: f32;
|
||||
var linear_damping: f32;
|
||||
var angular_damping: f32;
|
||||
var gravity_scale: f32 = 1;
|
||||
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 colliders: u32 = 0xFFFFFFFF;
|
||||
var joints: u32 = 0xFFFFFFFF; # Its first joint edge.
|
||||
var group: u32 = 0xFFFFFFFF; # The first body of the group it sleeps with.
|
||||
var next_in_group: u32 = 0xFFFFFFFF;
|
||||
var slot: u32; # Its solver state this step, 0 where it doesn't move.
|
||||
var data: u64;
|
||||
}
|
||||
|
||||
# A collider as the space keeps it: of a shape, or of a grid the space holds.
|
||||
struct collider_record {
|
||||
var made: collider;
|
||||
var grid: u32 = 0xFFFFFFFF;
|
||||
var body: u32;
|
||||
var leaf: u32 = 0xFFFFFFFF; # Its leaf of the space's tree.
|
||||
var next: u32 = 0xFFFFFFFF; # The body's next collider.
|
||||
var generation: u32;
|
||||
var alive: bool;
|
||||
var moved: bool; # Whether it's to find what it newly nears.
|
||||
}
|
||||
|
||||
# Whether a body's kind is moved by what it meets.
|
||||
def body_record::is_dynamic(&this): bool {
|
||||
return this.kind == body_kind::dynamic;
|
||||
}
|
||||
|
||||
# Whether a collider is of a grid.
|
||||
def collider_record::is_grid(&this): bool {
|
||||
return this.grid != none;
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
#! 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 hull, its points where its pose places them, with
|
||||
#! its radius around them: a circle of one point, a capsule of two, a polygon
|
||||
#! of its corners. Two circles meet as their middles near; a circle and a hull
|
||||
#! as the circle's middle nears the hull's edges, or lies within it; and two
|
||||
#! hulls by the edge of either that holds them furthest apart, as the
|
||||
#! separating axis theorem finds it. Where their hulls overlap, or their round
|
||||
#! sides near along a face, the other's nearest edge is clipped to that face,
|
||||
#! as Box2D clips one, so a box resting flat on another meets it at two
|
||||
#! points; where only their round sides meet, they meet at one, along the line
|
||||
#! between the hulls' nearest points.
|
||||
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! A point where two shapes meet: midway between their surfaces, how deep the
|
||||
#! one is within the other there, 0 where they touch and below where they're
|
||||
#! apart within a margin, and the features of each that meet there, which stay
|
||||
#! the same as they slide, so a solver knows the point from one step to the
|
||||
#! next.
|
||||
pub struct contact {
|
||||
pub var point: vec2;
|
||||
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 or two
|
||||
#! points, as a box resting flat on another rests on two.
|
||||
pub struct manifold {
|
||||
pub var normal: vec2;
|
||||
pub var points: contact[2];
|
||||
pub var count: u32;
|
||||
}
|
||||
|
||||
#! The deepest of its points.
|
||||
pub val manifold::depth: f32 {
|
||||
get => this.count == 0 ? 0f : this.count == 1 ? this.points[0].depth : math::max(this.points[0].depth, this.points[1].depth);
|
||||
}
|
||||
|
||||
#! The manifold turned around, of the second shape against the first.
|
||||
pub def manifold::flipped(&this): manifold {
|
||||
return manifold{ normal = this.normal * -1f, points = this.points, count = this.count };
|
||||
}
|
||||
|
||||
# A shape's points where its pose places it, and its edges' normals.
|
||||
struct hull {
|
||||
var points: vec2[8];
|
||||
var normals: vec2[8];
|
||||
var count: u32;
|
||||
var radius: f32;
|
||||
}
|
||||
|
||||
# Turned a number at a time, which sakurac keeps in registers.
|
||||
def hull_of(s: &shape, at: pose): hull {
|
||||
var made := hull{ count = s.count, radius = s.radius };
|
||||
val c := at.turn.c;
|
||||
val sn := at.turn.s;
|
||||
for i in 0..s.count {
|
||||
val p := s.point(i);
|
||||
val n := s.normal(i);
|
||||
made.points[i] = vec2{ at.at.x + c * p.x - sn * p.y, at.at.y + sn * p.x + c * p.y };
|
||||
made.normals[i] = vec2{ c * n.x - sn * n.y, sn * n.x + c * n.y };
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# A shape's own points and normals, unturned.
|
||||
def own_hull(s: &shape): hull {
|
||||
var made := hull{ count = s.count, radius = s.radius };
|
||||
for i in 0..s.count {
|
||||
made.points[i] = s.point(i);
|
||||
made.normals[i] = s.normal(i);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! 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. Where a
|
||||
#! margin is given, shapes apart by no more than it meet too, at points of a
|
||||
#! depth below 0, as a solver's speculative contacts are, which keep what falls
|
||||
#! from passing into what's below it in one step.
|
||||
pub def collide(a: &shape, at_a: pose, b: &shape, at_b: pose, margin: f32 = 0): maybe<manifold> {
|
||||
# Worked among the first's own places, so only the second's points are
|
||||
# turned, then the manifold turned back.
|
||||
val found := collide_own(a, b, at_a.unapply_pose(at_b), margin) else { return nothing{}; };
|
||||
val c := at_a.turn.c;
|
||||
val sn := at_a.turn.s;
|
||||
var placed := manifold{ normal = vec2{ c * found.normal.x - sn * found.normal.y, sn * found.normal.x + c * found.normal.y }, count = found.count };
|
||||
for i in 0..found.count {
|
||||
val p := found.points[i].point;
|
||||
placed.points[i] = contact{ point = vec2{ at_a.at.x + c * p.x - sn * p.y, at_a.at.y + sn * p.x + c * p.y }, depth = found.points[i].depth, id = found.points[i].id };
|
||||
}
|
||||
return placed;
|
||||
}
|
||||
|
||||
# The same of the second placed among the first's own places.
|
||||
def collide_own(a: &shape, b: &shape, at_b: pose, margin: f32): maybe<manifold> {
|
||||
val ha := own_hull(a);
|
||||
val hb := hull_of(b, at_b);
|
||||
if ha.count == 1 && hb.count == 1 {
|
||||
return circles(ha.points[0], ha.radius, hb.points[0], hb.radius, margin);
|
||||
}
|
||||
if hb.count == 1 {
|
||||
return hull_and_circle(&ha, hb.points[0], hb.radius, margin);
|
||||
}
|
||||
if ha.count == 1 {
|
||||
if hull_and_circle(&hb, ha.points[0], ha.radius, margin) is some(m) {
|
||||
return m.flipped();
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
return hulls(&ha, &hb, margin);
|
||||
}
|
||||
|
||||
#! 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 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: vec2, on_a: vec2, radius_a: f32, on_b: vec2, radius_b: f32, depth: f32): 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 };
|
||||
return made;
|
||||
}
|
||||
|
||||
def circles(a: vec2, ra: f32, b: vec2, rb: f32, margin: f32): maybe<manifold> {
|
||||
val between := b - a;
|
||||
val distance := between.length;
|
||||
return nothing{} if distance > ra + rb + margin;
|
||||
val normal := distance > tiny ? between * (1 / distance) : vec2{ 0, 1 };
|
||||
return one_point(normal, a, ra, b, rb, ra + rb - distance);
|
||||
}
|
||||
|
||||
# A hull and a circle: within a polygon, pushed out by the face it's nearest;
|
||||
# else by the hull's point nearest the circle's middle.
|
||||
def hull_and_circle(h: &hull, c: vec2, radius: f32, margin: f32): maybe<manifold> {
|
||||
val reach := h.radius + radius;
|
||||
# The face the middle is furthest in front of.
|
||||
var face: u32 = 0;
|
||||
var separation := -1e30f;
|
||||
for i in 0..h.count {
|
||||
val s := h.normals[i].dot(c - h.points[i]);
|
||||
if s > separation {
|
||||
separation = s;
|
||||
face = i;
|
||||
}
|
||||
}
|
||||
return nothing{} if separation > reach + margin;
|
||||
if h.count >= 3 && separation <= 0 {
|
||||
val n := h.normals[face];
|
||||
return one_point(n, c - n * separation, h.radius, c, radius, reach - separation);
|
||||
}
|
||||
var nearest := h.points[0];
|
||||
var best := 1e30f;
|
||||
for i in 0..h.count {
|
||||
val p := nearest_on_segment(c, h.points[i], h.points[(i + 1) % h.count]);
|
||||
val d := (c - p).length_squared;
|
||||
if d < best {
|
||||
best = d;
|
||||
nearest = p;
|
||||
}
|
||||
}
|
||||
val distance := math::sqrt(best);
|
||||
return nothing{} if distance > reach + margin;
|
||||
val normal := distance > tiny ? (c - nearest) * (1 / distance) : h.normals[face];
|
||||
return one_point(normal, nearest, h.radius, c, radius, reach - distance);
|
||||
}
|
||||
|
||||
# How far in front of a hull's edge another hull lies, of the edge that holds
|
||||
# it furthest: the edge, and the distance, below 0 where they overlap.
|
||||
struct apart {
|
||||
var edge: u32;
|
||||
var separation: f32;
|
||||
}
|
||||
|
||||
def furthest_apart(from: &hull, other: &hull): apart {
|
||||
var found := apart{ separation = -1e30f };
|
||||
for i in 0..from.count {
|
||||
val n := from.normals[i];
|
||||
var least := 1e30f;
|
||||
for j in 0..other.count {
|
||||
least = math::min(least, n.dot(other.points[j] - from.points[i]));
|
||||
}
|
||||
if least > found.separation {
|
||||
found = apart{ edge = i, separation = least };
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
# Two hulls of two or more points each.
|
||||
def hulls(a: &hull, b: &hull, margin: f32): maybe<manifold> {
|
||||
val reach := a.radius + b.radius;
|
||||
val of_a := furthest_apart(a, b);
|
||||
return nothing{} if of_a.separation > reach + margin;
|
||||
val of_b := furthest_apart(b, a);
|
||||
return nothing{} if of_b.separation > reach + margin;
|
||||
# The face of the first is taken where it's as good, so the same pair gives
|
||||
# the same face from one frame to the next.
|
||||
val flip := of_b.separation > of_a.separation + 1e-4;
|
||||
val reference := flip ? b : a;
|
||||
val incident := flip ? a : b;
|
||||
val face := flip ? of_b.edge : of_a.edge;
|
||||
val separation := flip ? of_b.separation : of_a.separation;
|
||||
|
||||
if separation > 1e-4 && reach > 0 {
|
||||
# Apart but for their round sides: they meet along the line between the
|
||||
# hulls' nearest points, or along a face nearly that way.
|
||||
var best := 1e30f;
|
||||
var on_a := a.points[0];
|
||||
var on_b := b.points[0];
|
||||
for i in 0..edges_of(a) {
|
||||
for j in 0..edges_of(b) {
|
||||
val pair := nearest_of_segments(a.points[i], a.points[(i + 1) % a.count], b.points[j], b.points[(j + 1) % b.count]);
|
||||
val d := (pair[1] - pair[0]).length_squared;
|
||||
if d < best {
|
||||
best = d;
|
||||
on_a = pair[0];
|
||||
on_b = pair[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
val distance := math::sqrt(best);
|
||||
return nothing{} if distance > reach + margin;
|
||||
val normal := (on_b - on_a) * (1 / distance);
|
||||
val along_face := flip ? normal * -1f : normal;
|
||||
if along_face.dot(reference.normals[face]) < 0.995 {
|
||||
return one_point(normal, on_a, a.radius, on_b, b.radius, reach - distance);
|
||||
}
|
||||
}
|
||||
return clipped(reference, incident, face, flip, margin);
|
||||
}
|
||||
|
||||
# How many distinct edges a hull has: a capsule's two are one segment.
|
||||
def edges_of(h: &hull): u32 {
|
||||
return h.count == 2 ? 1 : h.count;
|
||||
}
|
||||
|
||||
# The incident hull's edge facing most against the reference face, clipped to
|
||||
# the face's width: each point of it within reach of the face a contact, named
|
||||
# by the face, the edge, and which end of it the point is of.
|
||||
def clipped(reference: &hull, incident: &hull, face: u32, flip: bool, margin: f32): maybe<manifold> {
|
||||
val n := reference.normals[face];
|
||||
val v1 := reference.points[face];
|
||||
val v2 := reference.points[(face + 1) % reference.count];
|
||||
var edge: u32 = 0;
|
||||
var least := 1e30f;
|
||||
for i in 0..incident.count {
|
||||
val d := n.dot(incident.normals[i]);
|
||||
if d < least {
|
||||
least = d;
|
||||
edge = i;
|
||||
}
|
||||
}
|
||||
var points: vec2[2] = [incident.points[edge], incident.points[(edge + 1) % incident.count]];
|
||||
val tangent := (v2 - v1).normalized();
|
||||
var kept: u32 = 2;
|
||||
kept = clip(&mut points, kept, tangent * -1f, -tangent.dot(v1));
|
||||
return nothing{} if kept < 2;
|
||||
kept = clip(&mut points, kept, tangent, tangent.dot(v2));
|
||||
return nothing{} if kept < 2;
|
||||
|
||||
val reach := reference.radius + incident.radius;
|
||||
var made := manifold{ normal = flip ? n * -1f : n };
|
||||
val flipped: u32 = flip ? 0x10000 : 0;
|
||||
val named := flipped | (face << 8) | (edge << 1);
|
||||
for i in 0..2u {
|
||||
val s := n.dot(points[i] - v1);
|
||||
continue if s > reach + margin;
|
||||
# Midway between the reference's surface and the incident's.
|
||||
val on_reference := points[i] - n * (s - reference.radius);
|
||||
val on_incident := points[i] - n * incident.radius;
|
||||
made.points[made.count] = contact{ point = (on_reference + on_incident) * 0.5, depth = reach - s, id = named | i as u32 };
|
||||
made.count++;
|
||||
}
|
||||
return nothing{} if made.count == 0;
|
||||
return made;
|
||||
}
|
||||
|
||||
# Clips a segment to the side of a line where `normal.dot(p) <= offset`, as
|
||||
# Sutherland and Hodgman clip, keeping two points where any of it is there.
|
||||
def clip(points: &mut vec2[2], kept: u32, normal: vec2, offset: f32): u32 {
|
||||
val d0 := normal.dot(points[0]) - offset;
|
||||
val d1 := normal.dot(points[1]) - offset;
|
||||
return 2 if d0 <= 0 && d1 <= 0;
|
||||
return 0 if d0 > 0 && d1 > 0;
|
||||
val t := d0 / (d0 - d1);
|
||||
val crossing := points[0] + (points[1] - points[0]) * t;
|
||||
if d0 > 0 {
|
||||
points[0] = crossing;
|
||||
} else {
|
||||
points[1] = crossing;
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
#! 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 grid one for each solid cell they
|
||||
#! meet, named by the cell, so it's kept as they slide.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! 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 grid: bool;
|
||||
var alive: bool;
|
||||
}
|
||||
|
||||
# Where two colliders meet, or a shape and one cell of a grid: the manifold,
|
||||
# and the impulses that held them apart at each of its points last step.
|
||||
struct contact_record {
|
||||
var pair: u32;
|
||||
var child: u32; # The cell, of a grid's.
|
||||
var next: u32 = 0xFFFFFFFF;
|
||||
var body_a: u32;
|
||||
var body_b: u32;
|
||||
var manifold: manifold;
|
||||
var normal_impulse: f32[2];
|
||||
var tangent_impulse: f32[2];
|
||||
var friction: f32;
|
||||
var restitution: f32;
|
||||
var touching: bool;
|
||||
var seen: bool;
|
||||
var alive: bool;
|
||||
}
|
||||
|
||||
# A cell a shape met, and how.
|
||||
struct met_cell {
|
||||
var cell: u32;
|
||||
var manifold: manifold;
|
||||
}
|
||||
|
||||
# The key of a pair of colliders, whichever comes first.
|
||||
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, on
|
||||
# layers each other's masks hold, not both grids, 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_grid() && cb.is_grid());
|
||||
return false if !this.bodies[ca.body as u64].is_dynamic() && !this.bodies[cb.body as u64].is_dynamic();
|
||||
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;
|
||||
# Where both moved, the one of the lesser index pairs them.
|
||||
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 grid := this.colliders[a as u64].is_grid() || this.colliders[b as u64].is_grid();
|
||||
this.pairs[p as u64] = pair_record{ a = a, b = b, sensor = sensor, grid = grid, alive = true };
|
||||
this.pair_keys.set(pair_key(a, b), p);
|
||||
if !sensor && !grid {
|
||||
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);
|
||||
}
|
||||
|
||||
# Notes that a pair began or stopped touching.
|
||||
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;
|
||||
}
|
||||
|
||||
# Finds where each pair of a moving body meets, dropping those whose grown
|
||||
# boxes no longer meet.
|
||||
def space::update_contacts(&mut this): void {
|
||||
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].grid {
|
||||
touching = this.update_grid_contacts(p as u32);
|
||||
} else {
|
||||
touching = this.update_contact(this.pairs[p].contacts, this.manifold_of(a, b));
|
||||
}
|
||||
if touching != this.pairs[p].touching {
|
||||
this.pairs[p].touching = touching;
|
||||
this.note(p as u32, touching);
|
||||
}
|
||||
# What touches a sleeping body, moving, wakes it, as a lift that sets off
|
||||
# wakes what rests on it.
|
||||
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 != 0) {
|
||||
this.wake_body(b);
|
||||
}
|
||||
}
|
||||
|
||||
# Where two colliders' shapes meet, within the speculative margin.
|
||||
def space::manifold_of(&this, a: u32, b: u32): 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, this.speculative) is some(m) {
|
||||
return m;
|
||||
}
|
||||
return manifold{};
|
||||
}
|
||||
|
||||
# Whether a sensor's pair overlaps: a shape and a shape, or a shape and a
|
||||
# grid.
|
||||
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.grids[ca.grid as u64].overlaps(at_a, &cb.made.shape, at_b) if ca.is_grid();
|
||||
return this.grids[cb.grid as u64].overlaps(at_b, &ca.made.shape, at_a) if cb.is_grid();
|
||||
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[2] = [0, 0];
|
||||
var tangent: f32[2] = [0, 0];
|
||||
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 solid cells a shape meets of a grid, a contact for each, keeping
|
||||
# those it met last step and dropping those it no longer meets.
|
||||
# @returns Whether any touches.
|
||||
def space::update_grid_contacts(&mut this, p: u32): bool {
|
||||
val a := this.pairs[p as u64].a;
|
||||
val b := this.pairs[p as u64].b;
|
||||
# The grid as the first, its normals from each cell toward the shape,
|
||||
# turned back where the shape is the pair's first.
|
||||
val grid_first := this.colliders[a as u64].is_grid();
|
||||
val g := grid_first ? a : b;
|
||||
val s := grid_first ? b : a;
|
||||
var met := move(this.met);
|
||||
met.clear();
|
||||
val held := &this.colliders[g as u64];
|
||||
val shaped := &this.colliders[s as u64];
|
||||
val cells := &this.grids[held.grid as u64];
|
||||
val width := cells.width;
|
||||
cells.collide(this.bodies[held.body as u64].at, &shaped.made.shape, this.bodies[shaped.body as u64].at, def(x: u32, y: u32, found: manifold): bool {
|
||||
met.append(met_cell{ cell = y * width + x, manifold = grid_first ? found : found.flipped() });
|
||||
return true;
|
||||
}, this.speculative);
|
||||
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].cell {
|
||||
found = this.contacts[found as u64].next;
|
||||
}
|
||||
if found == none {
|
||||
found = this.make_contact(p, met[i].cell);
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
#! Contains `grid`: solid cells of a grid, as a tilemap's walls are, each a box
|
||||
#! of the grid's cell size, from the grid's origin at the bottom left of its
|
||||
#! first cell, x to the right and y up.
|
||||
#!
|
||||
#! A shape meets each solid cell as a box, but for the faces two solid cells
|
||||
#! share: a manifold pushing the shape into a solid neighbor, along the axis
|
||||
#! it pushes most, is passed over, so a body sliding along a floor of many
|
||||
#! cells slides as along one, never caught on the seams between them.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! Solid cells of a grid, so many across and up.
|
||||
pub struct grid {
|
||||
#! How wide and high each cell is.
|
||||
pub var cell := vec2{ 1, 1 };
|
||||
var _width: u32;
|
||||
var _height: u32;
|
||||
var _solid: vector<u8>; # Each cell, a row at a time, from the bottom left.
|
||||
}
|
||||
|
||||
#! A grid so many cells across and up, each so wide and high, none solid.
|
||||
pub def grid::new(width: u32, height: u32, cell: vec2 = vec2{ 1, 1 }): grid {
|
||||
var made := grid{ cell = cell, _width = width, _height = height, _solid = vector::<u8>::new() };
|
||||
made._solid.resize(width as u64 * height as u64, 0);
|
||||
return made;
|
||||
}
|
||||
|
||||
pub val grid::width: u32 {
|
||||
get => this._width;
|
||||
}
|
||||
|
||||
pub val grid::height: u32 {
|
||||
get => this._height;
|
||||
}
|
||||
|
||||
#! Whether a cell is solid: none outside the grid is.
|
||||
pub def grid::is_solid(&this, x: i64, y: i64): bool {
|
||||
return false if x < 0 || y < 0 || x >= this._width as i64 || y >= this._height as i64;
|
||||
return this._solid[(y as u64) * this._width as u64 + x as u64] != 0;
|
||||
}
|
||||
|
||||
#! Makes a cell solid, or not.
|
||||
pub def grid::set(&mut this, x: u32, y: u32, solid: bool): void {
|
||||
return if x >= this._width || y >= this._height;
|
||||
this._solid[y as u64 * this._width as u64 + x as u64] = solid ? 1 : 0;
|
||||
}
|
||||
|
||||
#! A cell's box, of the grid's own places.
|
||||
pub def grid::box_of(&this, x: u32, y: u32): aabb {
|
||||
val low := vec2{ x as f32 * this.cell.x, y as f32 * this.cell.y };
|
||||
return aabb{ low, low + this.cell };
|
||||
}
|
||||
|
||||
#! The box of all its cells, of its own places.
|
||||
pub val grid::bounds: aabb {
|
||||
get => aabb{ vec2::zero, vec2{ this._width as f32 * this.cell.x, this._height as f32 * this.cell.y } };
|
||||
}
|
||||
|
||||
#! Visits each solid cell a box of the grid's own places meets, as
|
||||
#! `visit(x, y)`, until it gives false.
|
||||
pub def grid::cells_in<F>(&this, box: aabb, visit: F): void where F: invokable<def(u32, u32): bool> {
|
||||
return if this._width == 0 || this._height == 0;
|
||||
val x0 := math::max(math::floor(box.min.x / this.cell.x) as i64, 0);
|
||||
val y0 := math::max(math::floor(box.min.y / this.cell.y) as i64, 0);
|
||||
val x1 := math::min(math::floor(box.max.x / this.cell.x) as i64, this._width as i64 - 1);
|
||||
val y1 := math::min(math::floor(box.max.y / this.cell.y) as i64, this._height as i64 - 1);
|
||||
var y := y0;
|
||||
while y <= y1 {
|
||||
var x := x0;
|
||||
while x <= x1 {
|
||||
if this.is_solid(x, y) {
|
||||
return if !visit(x as u32, y as u32);
|
||||
}
|
||||
x++;
|
||||
}
|
||||
y++;
|
||||
}
|
||||
}
|
||||
|
||||
#! Visits the manifold of a shape against each solid cell it meets, as
|
||||
#! `visit(x, y, m)`, until it gives false: `at` places the grid, and `at_s`
|
||||
#! the shape, and each manifold's normal is from the cell toward the shape,
|
||||
#! of the plane's places. Those pushing the shape into a solid neighbor are
|
||||
#! passed over. Cells apart from the shape by no more than a margin are met
|
||||
#! too, as `collide` meets them.
|
||||
pub def grid::collide<F>(&this, at: pose, s: &shape, at_s: pose, visit: F, margin: f32 = 0): void
|
||||
where F: invokable<def(u32, u32, manifold): bool> {
|
||||
val local := at.unapply_pose(at_s);
|
||||
val half := this.cell * 0.5;
|
||||
this.cells_in(s.bounds(local).grown(margin), def(x: u32, y: u32): bool {
|
||||
val box := shape::box(half, vec2{ (x as f32 + 0.5) * this.cell.x, (y as f32 + 0.5) * this.cell.y });
|
||||
val found := collide(&box, pose::identity, s, local, margin) else { return true; };
|
||||
# Along the axis it pushes most, toward a solid neighbor, it's a face the
|
||||
# two share.
|
||||
val n := found.normal;
|
||||
var nx: i64 = 0;
|
||||
var ny: i64 = 0;
|
||||
if math::abs(n.x) > math::abs(n.y) {
|
||||
nx = n.x > 0 ? 1 : -1;
|
||||
} else {
|
||||
ny = n.y > 0 ? 1 : -1;
|
||||
}
|
||||
return true if this.is_solid(x as i64 + nx, y as i64 + ny);
|
||||
var placed := manifold{ normal = at.turn.apply(n), count = found.count };
|
||||
for i in 0..found.count {
|
||||
placed.points[i] = contact{ point = at.apply(found.points[i].point), depth = found.points[i].depth, id = found.points[i].id };
|
||||
}
|
||||
return visit(x, y, placed);
|
||||
});
|
||||
}
|
||||
|
||||
#! Whether a shape meets any solid cell, `at` placing the grid and `at_s` the
|
||||
#! shape, but where it only meets the faces solid cells share.
|
||||
pub def grid::overlaps(&this, at: pose, s: &shape, at_s: pose): bool {
|
||||
var met := false;
|
||||
this.collide(at, s, at_s, def(x: u32, y: u32, m: manifold): bool {
|
||||
met = true;
|
||||
return false;
|
||||
});
|
||||
return met;
|
||||
}
|
||||
|
||||
#! Where a ray met a grid: the hit, and the solid cell it met.
|
||||
pub struct grid_hit {
|
||||
pub var hit: ray_hit;
|
||||
pub var x: u32;
|
||||
pub var y: u32;
|
||||
}
|
||||
|
||||
#! Where a ray first meets a solid cell, `at` placing the grid: from a place,
|
||||
#! along a direction of length 1, as far as `reach`, passing from cell to cell
|
||||
#! as Amanatides and Woo pass, the face it enters by its normal. A ray
|
||||
#! beginning in a solid cell meets it at 0, facing back along the ray.
|
||||
pub def grid::ray_cast(&this, at: pose, origin: vec2, direction: vec2, reach: f32): maybe<grid_hit> {
|
||||
val o := at.unapply(origin);
|
||||
val d := at.turn.unapply(direction);
|
||||
val whole := this.bounds;
|
||||
val start := whole.ray_hit(o, d, reach) else { return nothing{}; };
|
||||
val p := o + d * start;
|
||||
var x := math::clamp(math::floor(p.x / this.cell.x) as i64, 0, this._width as i64 - 1);
|
||||
var y := math::clamp(math::floor(p.y / this.cell.y) as i64, 0, this._height as i64 - 1);
|
||||
# The face of the grid it entered by, or none where it began within it.
|
||||
var normal := d * -1f;
|
||||
if start > 0 {
|
||||
val gaps: f32[4] = [math::abs(p.x - whole.min.x), math::abs(p.x - whole.max.x), math::abs(p.y - whole.min.y), math::abs(p.y - whole.max.y)];
|
||||
val faces: vec2[4] = [vec2{ -1, 0 }, vec2{ 1, 0 }, vec2{ 0, -1 }, vec2{ 0, 1 }];
|
||||
var nearest: u64 = 0;
|
||||
for i in 1..4u {
|
||||
if gaps[i] < gaps[nearest] {
|
||||
nearest = i;
|
||||
}
|
||||
}
|
||||
normal = faces[nearest];
|
||||
}
|
||||
val step_x: i64 = d.x > 0 ? 1 : d.x < 0 ? -1 : 0;
|
||||
val step_y: i64 = d.y > 0 ? 1 : d.y < 0 ? -1 : 0;
|
||||
val across_x := step_x != 0 ? this.cell.x / math::abs(d.x) : 1e30f;
|
||||
val across_y := step_y != 0 ? this.cell.y / math::abs(d.y) : 1e30f;
|
||||
# How far along the ray, from its beginning, each next line of cells is.
|
||||
var next_x := 1e30f;
|
||||
var next_y := 1e30f;
|
||||
if step_x > 0 {
|
||||
next_x = ((x + 1) as f32 * this.cell.x - o.x) / d.x;
|
||||
} else if step_x < 0 {
|
||||
next_x = (x as f32 * this.cell.x - o.x) / d.x;
|
||||
}
|
||||
if step_y > 0 {
|
||||
next_y = ((y + 1) as f32 * this.cell.y - o.y) / d.y;
|
||||
} else if step_y < 0 {
|
||||
next_y = (y as f32 * this.cell.y - o.y) / d.y;
|
||||
}
|
||||
var t := start;
|
||||
while true {
|
||||
if this.is_solid(x, y) {
|
||||
return grid_hit{
|
||||
hit = ray_hit{ distance = t, point = at.apply(o + d * t), normal = at.turn.apply(normal) }, x = x as u32, y = y as u32,
|
||||
};
|
||||
}
|
||||
if next_x < next_y {
|
||||
t = next_x;
|
||||
next_x += across_x;
|
||||
x += step_x;
|
||||
normal = vec2{ -step_x as f32, 0 };
|
||||
} else {
|
||||
t = next_y;
|
||||
next_y += across_y;
|
||||
y += step_y;
|
||||
normal = vec2{ 0, -step_y as f32 };
|
||||
}
|
||||
return nothing{} if t > reach || x < 0 || y < 0 || x >= this._width as i64 || y >= this._height as i64;
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
#! 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::physics2d;
|
||||
|
||||
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.ia = a.inv_inertia;
|
||||
r.mb = b.inv_mass;
|
||||
r.ib = b.inv_inertia;
|
||||
r.ra = a.at.turn.apply(r.made.anchor_a - a.local_center);
|
||||
r.rb = b.at.turn.apply(r.made.anchor_b - b.local_center);
|
||||
r.delta_center = b.center - a.center;
|
||||
r.delta_angle = unwound(angle_between(b.at.turn, a.at.turn) - r.made.reference_angle);
|
||||
var k := r.ia + r.ib;
|
||||
if r.made.kind == joint_kind::revolute {
|
||||
# A pin turns each body about itself, not about its center, as the
|
||||
# point it's held at keeps it: how hard that is is its inertia, and its
|
||||
# mass as far from the pin as its center is, so a limit stops a door
|
||||
# outright rather than leaving the point to turn it back.
|
||||
k = about_pin(a, r.ra) + about_pin(b, r.rb);
|
||||
}
|
||||
r.axial_mass = k > 0 ? 1 / k : 0f;
|
||||
if r.made.kind == joint_kind::distance {
|
||||
val axis := (r.rb - r.ra + r.delta_center).normalized();
|
||||
val cra := r.ra.cross(axis);
|
||||
val crb := r.rb.cross(axis);
|
||||
val kd := r.ma + r.mb + r.ia * cra * cra + r.ib * crb * crb;
|
||||
r.axial_mass = kd > 0 ? 1 / kd : 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 a place `r` from its center: the inverse of
|
||||
# its inertia about it.
|
||||
def about_pin(b: &body_record, r: vec2): f32 {
|
||||
return 0 if b.inv_mass == 0 || b.inv_inertia == 0;
|
||||
return 1 / (b.inertia + b.mass * r.length_squared);
|
||||
}
|
||||
|
||||
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 ra := sa.dq.apply(r.ra);
|
||||
val rb := sb.dq.apply(r.rb);
|
||||
var p := vec2::zero;
|
||||
var turn: f32 = 0;
|
||||
if r.made.kind == joint_kind::revolute {
|
||||
p = r.linear;
|
||||
turn = r.spring_impulse + r.motor_impulse + r.lower_impulse - r.upper_impulse;
|
||||
} else if r.made.kind == joint_kind::weld {
|
||||
p = r.linear;
|
||||
turn = r.axial;
|
||||
} else {
|
||||
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 -= r.ia * (ra.cross(p) + turn);
|
||||
sb.v = sb.v + p * r.mb;
|
||||
sb.w += r.ib * (rb.cross(p) + turn);
|
||||
s.states[r.slot_a as u64].v = sa.v;
|
||||
s.states[r.slot_a as u64].w = sa.w;
|
||||
s.states[r.slot_b as u64].v = sb.v;
|
||||
s.states[r.slot_b as u64].w = sb.w;
|
||||
}
|
||||
}
|
||||
|
||||
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];
|
||||
if r.made.kind == joint_kind::revolute {
|
||||
solve_revolute(&mut r, &mut sa, &mut sb, &s.joint_soft, h, use_bias);
|
||||
} else if r.made.kind == joint_kind::weld {
|
||||
solve_weld(&mut r, &mut sa, &mut sb, use_bias);
|
||||
} else {
|
||||
solve_distance(&mut r, &mut sa, &mut sb, &s.joint_soft, h, use_bias);
|
||||
}
|
||||
this.joints[j] = r;
|
||||
s.states[r.slot_a as u64].v = sa.v;
|
||||
s.states[r.slot_a as u64].w = sa.w;
|
||||
s.states[r.slot_b as u64].v = sb.v;
|
||||
s.states[r.slot_b as u64].w = sb.w;
|
||||
}
|
||||
}
|
||||
|
||||
# Turns the two apart by an angular impulse.
|
||||
def turn_apart(r: &joint_record, sa: &mut body_state, sb: &mut body_state, impulse: f32): void {
|
||||
sa.w -= r.ia * impulse;
|
||||
sb.w += r.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, ra: vec2, rb: vec2, p: vec2): void {
|
||||
sa.v = sa.v - p * r.ma;
|
||||
sa.w -= r.ia * ra.cross(p);
|
||||
sb.v = sb.v + p * r.mb;
|
||||
sb.w += r.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;
|
||||
}
|
||||
|
||||
def solve_revolute(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, soft: &softness, h: f32, use_bias: bool): void {
|
||||
val made := &r.made;
|
||||
val turned_by := unwound(r.delta_angle + angle_between(sb.dq, sa.dq));
|
||||
if made.spring && made.hertz > 0 {
|
||||
val bias := r.spring_soft.bias_rate * turned_by;
|
||||
val impulse := -r.spring_soft.mass_scale * r.axial_mass * (sb.w - sa.w + bias) - r.spring_soft.impulse_scale * r.spring_impulse;
|
||||
r.spring_impulse += impulse;
|
||||
turn_apart(r, sa, sb, 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 - made.motor_speed), -most, most);
|
||||
turn_apart(r, sa, sb, r.motor_impulse - held);
|
||||
}
|
||||
if made.limit {
|
||||
val lower := limit_impulse(turned_by - made.lower, sb.w - sa.w, r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias);
|
||||
r.lower_impulse += lower;
|
||||
turn_apart(r, sa, sb, lower);
|
||||
val upper := limit_impulse(made.upper - turned_by, sa.w - sb.w, r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias);
|
||||
r.upper_impulse += upper;
|
||||
turn_apart(r, sa, sb, -upper);
|
||||
}
|
||||
# The anchors held at one point.
|
||||
val ra := sa.dq.apply(r.ra);
|
||||
val rb := sb.dq.apply(r.rb);
|
||||
val cdot := sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra);
|
||||
var bias := vec2::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 k11 := r.ma + r.mb + ra.y * ra.y * r.ia + rb.y * rb.y * r.ib;
|
||||
val k12 := -ra.y * ra.x * r.ia - rb.y * rb.x * r.ib;
|
||||
val k22 := r.ma + r.mb + ra.x * ra.x * r.ia + rb.x * rb.x * r.ib;
|
||||
val b := solved(k11, k12, k12, k22, cdot + bias);
|
||||
val impulse := vec2{ -mass_scale * b.x - impulse_scale * r.linear.x, -mass_scale * b.y - impulse_scale * r.linear.y };
|
||||
r.linear = r.linear + impulse;
|
||||
push_apart(r, sa, sb, ra, rb, impulse);
|
||||
}
|
||||
|
||||
def solve_weld(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, use_bias: bool): void {
|
||||
# Their turn held.
|
||||
var bias: f32 = 0;
|
||||
var mass_scale: f32 = 1;
|
||||
var impulse_scale: f32 = 0;
|
||||
if use_bias || r.made.angular_hertz > 0 {
|
||||
bias = r.angular_soft.bias_rate * unwound(angle_between(sb.dq, sa.dq) + r.delta_angle);
|
||||
mass_scale = r.angular_soft.mass_scale;
|
||||
impulse_scale = r.angular_soft.impulse_scale;
|
||||
}
|
||||
val turn := -r.axial_mass * mass_scale * (sb.w - sa.w + bias) - impulse_scale * r.axial;
|
||||
r.axial += turn;
|
||||
turn_apart(r, sa, sb, turn);
|
||||
# Their anchors held at one point.
|
||||
val ra := sa.dq.apply(r.ra);
|
||||
val rb := sb.dq.apply(r.rb);
|
||||
var place := vec2::zero;
|
||||
mass_scale = 1;
|
||||
impulse_scale = 0;
|
||||
if use_bias || r.made.hertz > 0 {
|
||||
place = ((sb.dp - sa.dp) + (rb - ra) + r.delta_center) * r.linear_soft.bias_rate;
|
||||
mass_scale = r.linear_soft.mass_scale;
|
||||
impulse_scale = r.linear_soft.impulse_scale;
|
||||
}
|
||||
val cdot := sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra);
|
||||
val k11 := r.ma + r.mb + ra.y * ra.y * r.ia + rb.y * rb.y * r.ib;
|
||||
val k12 := -ra.y * ra.x * r.ia - rb.y * rb.x * r.ib;
|
||||
val k22 := r.ma + r.mb + ra.x * ra.x * r.ia + rb.x * rb.x * r.ib;
|
||||
val b := solved(k11, k12, k12, k22, cdot + place);
|
||||
val impulse := vec2{ -mass_scale * b.x - impulse_scale * r.linear.x, -mass_scale * b.y - impulse_scale * r.linear.y };
|
||||
r.linear = r.linear + impulse;
|
||||
push_apart(r, sa, sb, ra, rb, impulse);
|
||||
}
|
||||
|
||||
def solve_distance(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, soft: &softness, h: f32, use_bias: bool): void {
|
||||
val made := &r.made;
|
||||
val ra := sa.dq.apply(r.ra);
|
||||
val rb := sb.dq.apply(r.rb);
|
||||
val d := (sb.dp - sa.dp) + r.delta_center + (rb - ra);
|
||||
val length := d.length;
|
||||
val axis := d.normalized();
|
||||
# Soft where it springs between its limits; else a rod.
|
||||
if made.spring && (!made.limit || made.lower < made.upper) {
|
||||
if made.hertz > 0 {
|
||||
val cdot := axis.dot(sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, 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, ra, rb, axis * impulse);
|
||||
}
|
||||
} else {
|
||||
val cdot := axis.dot(sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, 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, ra, rb, axis * impulse);
|
||||
}
|
||||
if made.limit && made.lower < made.upper {
|
||||
val closing := axis.dot(sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, 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, ra, rb, axis * lower);
|
||||
val opening := axis.dot(sa.v + spun(sa.w, ra) - sb.v - spun(sb.w, 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, 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 + spun(sb.w, rb) - sa.v - spun(sa.w, ra));
|
||||
r.motor_impulse = math::clamp(held + r.axial_mass * (made.motor_speed - cdot), -most, most);
|
||||
push_apart(r, sa, sb, ra, rb, axis * (r.motor_impulse - held));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
#! Contains joints, which hold two bodies together: a `revolute` joint pins
|
||||
#! them at a point they turn about, as a hinge or an axle, with limits to how
|
||||
#! far it turns and a motor to turn it; a `distance` joint keeps two points
|
||||
#! apart, rigidly as a rod, within lengths as a rope, or springily; and a
|
||||
#! `weld` holds them as one body, rigidly or springily.
|
||||
#!
|
||||
#! Joints are solved before contacts in each substep, as Box2D's are, 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::physics2d;
|
||||
|
||||
#! What a joint holds.
|
||||
pub enum joint_kind: u8 {
|
||||
#! The two at a point, about which they turn, as a hinge.
|
||||
revolute,
|
||||
#! Two points apart, as a rod, a rope, or a spring.
|
||||
distance,
|
||||
#! The two as one.
|
||||
weld,
|
||||
}
|
||||
|
||||
#! 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::revolute;
|
||||
pub var a: body_id;
|
||||
pub var b: body_id;
|
||||
pub var anchor_a: vec2;
|
||||
pub var anchor_b: vec2;
|
||||
#! Whether the two bodies still meet where their colliders do.
|
||||
pub var collide: bool;
|
||||
#! Of a revolute joint or a weld, how far `b` is turned from `a`, in
|
||||
#! radians, where it rests.
|
||||
pub var reference_angle: f32;
|
||||
#! Whether it's limited: a revolute joint to turning from `lower` to
|
||||
#! `upper` radians from its reference, and a distance joint to lengths
|
||||
#! between them.
|
||||
pub var limit: bool;
|
||||
pub var lower: f32;
|
||||
pub var upper: f32;
|
||||
#! A motor turning a revolute joint 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 revolute joint's reference angle or a distance joint's
|
||||
#! length, of so many cycles a second, damped so: 1 doesn't spring back.
|
||||
#! Of a weld, 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 weld, 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; # The next joint of each body.
|
||||
var next_b: u32 = 0xFFFFFFFF;
|
||||
var slot_a: u32;
|
||||
var slot_b: u32;
|
||||
var ma: f32;
|
||||
var ia: f32;
|
||||
var mb: f32;
|
||||
var ib: f32;
|
||||
var ra: vec2; # Each anchor from its body's center, as the step began.
|
||||
var rb: vec2;
|
||||
var delta_center: vec2;
|
||||
var delta_angle: f32;
|
||||
var axial_mass: f32;
|
||||
var linear: vec2; # Impulses, kept from step to step.
|
||||
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;
|
||||
}
|
||||
|
||||
#! 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 };
|
||||
}
|
||||
|
||||
#! Pins two bodies at a place of the plane, about which they turn.
|
||||
pub def space::pin(&mut this, a: body_id, b: body_id, at: vec2): 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::revolute, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
|
||||
reference_angle = angle_between(pb.turn, pa.turn),
|
||||
});
|
||||
}
|
||||
|
||||
#! Keeps two places of the plane, one of each body, as far apart as they are.
|
||||
pub def space::tie(&mut this, a: body_id, b: body_id, at_a: vec2, at_b: vec2): 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,
|
||||
});
|
||||
}
|
||||
|
||||
#! Holds two bodies together as one, about a place of the plane.
|
||||
pub def space::weld(&mut this, a: body_id, b: body_id, at: vec2): 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::weld, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
|
||||
reference_angle = angle_between(pb.turn, pa.turn),
|
||||
});
|
||||
}
|
||||
|
||||
#! 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
|
||||
#! anchors, and wakes them.
|
||||
pub def space::change(&mut this, id: joint_id, made: joint): void {
|
||||
return if !this.has(id);
|
||||
val j := id.index as u64;
|
||||
val a := this.joints[j].made.a;
|
||||
val b := this.joints[j].made.b;
|
||||
this.joints[j].made = made;
|
||||
this.joints[j].made.a = a;
|
||||
this.joints[j].made.b = b;
|
||||
this.wake_body(a.index);
|
||||
this.wake_body(b.index);
|
||||
}
|
||||
|
||||
#! How far a revolute joint is turned from its reference, in radians.
|
||||
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 unwound(angle_between(this.bodies[j.body_b as u64].at.turn, this.bodies[j.body_a as u64].at.turn) - j.made.reference_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);
|
||||
# What it kept apart may meet again.
|
||||
this.touch_colliders(a);
|
||||
}
|
||||
|
||||
# Takes a joint from a body's list of them.
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
# The joint after another of a body's.
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
# Drops the pairs of two bodies' colliders.
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Has a body's colliders find what they near again, as after a joint that
|
||||
# kept them from meeting is gone.
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# How far `b` is turned past `a`, from -π to π.
|
||||
def angle_between(b: rot, a: rot): f32 {
|
||||
return math::atan2(b.s * a.c - b.c * a.s, b.c * a.c + b.s * a.s);
|
||||
}
|
||||
|
||||
# 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;
|
||||
}
|
||||
|
||||
# What solves `[k11 k12; k21 k22] x = b`.
|
||||
def solved(k11: f32, k12: f32, k21: f32, k22: f32, b: vec2): vec2 {
|
||||
var det := k11 * k22 - k12 * k21;
|
||||
if det != 0 {
|
||||
det = 1 / det;
|
||||
}
|
||||
return vec2{ det * (k22 * b.x - k12 * b.y), det * (k11 * b.y - k21 * b.x) };
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
#! Contains `mass_data`: how heavy a shape is of a density, where its mass is
|
||||
#! centered, and how hard it is to turn, as a body's colliders sum to it.
|
||||
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! How heavy something is, where its mass is centered, of its body's own
|
||||
#! places, and how hard it is to turn about that center: its rotational
|
||||
#! inertia.
|
||||
pub struct mass_data {
|
||||
pub var mass: f32;
|
||||
pub var center: vec2;
|
||||
pub var inertia: f32;
|
||||
}
|
||||
|
||||
#! 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);
|
||||
# Each turns about the joint center as about its own, and as far as it's
|
||||
# from it, as the parallel axis theorem finds.
|
||||
val inertia := this.inertia + this.mass * (this.center - center).length_squared
|
||||
+ other.inertia + other.mass * (other.center - center).length_squared;
|
||||
return mass_data{ mass = mass, center = center, inertia = inertia };
|
||||
}
|
||||
|
||||
#! Its mass of a density, a mass for each area of 1.
|
||||
pub def shape::mass(&this, density: f32): mass_data {
|
||||
if this.kind == shape_kind::circle {
|
||||
val rr := this.radius * this.radius;
|
||||
val mass := density * math::pi as f32 * rr;
|
||||
return mass_data{ mass = mass, center = this.point(0), inertia = mass * rr * 0.5 };
|
||||
}
|
||||
if this.kind == shape_kind::capsule {
|
||||
return capsule_mass(this.point(0), this.point(1), this.radius, density);
|
||||
}
|
||||
return polygon_mass(this, density);
|
||||
}
|
||||
|
||||
# A capsule's: a box between its ends, and a circle of its two round halves,
|
||||
# each half's own center 4r/3π past the box's end, as Box2D finds it.
|
||||
def capsule_mass(p1: vec2, p2: vec2, radius: f32, density: f32): mass_data {
|
||||
val rr := radius * radius;
|
||||
val length := (p2 - p1).length;
|
||||
val circle := density * math::pi as f32 * rr;
|
||||
val box := density * 2 * radius * length;
|
||||
val half := length * 0.5;
|
||||
val off := 4 * radius / (3 * math::pi as f32);
|
||||
val inertia := circle * (0.5 * rr + half * half + 2 * half * off) + box * (4 * rr + length * length) / 12;
|
||||
return mass_data{ mass = circle + box, center = (p1 + p2) * 0.5, inertia = inertia };
|
||||
}
|
||||
|
||||
# A polygon's, as the triangles fanned from its first corner sum it.
|
||||
def polygon_mass(s: &shape, density: f32): mass_data {
|
||||
val origin := s.point(0);
|
||||
var area: f32 = 0;
|
||||
var center := vec2::zero;
|
||||
var inertia: f32 = 0;
|
||||
for i in 1..s.count - 1 {
|
||||
val e1 := s.point(i) - origin;
|
||||
val e2 := s.point(i + 1) - origin;
|
||||
val d := e1.cross(e2);
|
||||
val triangle := 0.5 * d;
|
||||
area += triangle;
|
||||
center = center + (e1 + e2) * (triangle / 3);
|
||||
val xx := e1.x * e1.x + e2.x * e1.x + e2.x * e2.x;
|
||||
val yy := e1.y * e1.y + e2.y * e1.y + e2.y * e2.y;
|
||||
inertia += (0.25 / 3 * d) * (xx + yy);
|
||||
}
|
||||
return mass_data{} if area <= tiny;
|
||||
center = center * (1 / area);
|
||||
val mass := density * area;
|
||||
# Of the corner it was summed about, moved to the center.
|
||||
return mass_data{ mass = mass, center = origin + center, inertia = density * inertia - mass * center.length_squared };
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#! Contains `physics2d`: what collides and moves in a plane, as a game of two
|
||||
#! dimensions asks it. Shapes, circles, capsules, and convex polygons, 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 `grid` of solid cells, as a
|
||||
#! tilemap's walls are, met as boxes, each but the faces it shares with a solid
|
||||
#! neighbor, so a body slides along a floor of many cells as along one.
|
||||
#!
|
||||
#! And a `space` of bodies: each made of colliders, of shapes or a grid, 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, sleeping where
|
||||
#! it and all it rests on are still.
|
||||
#!
|
||||
#! The plane is `linear`'s x and y: x to the right, y up, and angles
|
||||
#! counterclockwise, in radians. A polygon's corners are counterclockwise, and
|
||||
#! each edge's normal faces 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::physics2d;
|
||||
|
||||
# How near two numbers are taken as one, as lengths in a game's units are.
|
||||
const tiny: f32 = 1e-6;
|
||||
|
||||
# The point of a segment nearest a place.
|
||||
def nearest_on_segment(p: vec2, a: vec2, b: vec2): vec2 {
|
||||
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: vec2, a2: vec2, b1: vec2, b2: vec2): vec2[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];
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#! Contains `rot`, a rotation in the plane, and `pose`, where a body is and
|
||||
#! which way it's turned, which places its shapes.
|
||||
|
||||
import std::math;
|
||||
import std::serial;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! A rotation in the plane, counterclockwise, as its angle's cosine and sine,
|
||||
#! so turning a vector takes no trigonometry.
|
||||
@serial
|
||||
pub struct rot {
|
||||
@serial pub var c: f32 = 1;
|
||||
@serial pub var s: f32;
|
||||
}
|
||||
|
||||
#! No rotation.
|
||||
pub val rot::identity := rot{ 1, 0 };
|
||||
|
||||
#! A rotation by an angle, in radians, counterclockwise.
|
||||
pub def rot::of(angle: f32): rot {
|
||||
return rot{ math::cos(angle), math::sin(angle) };
|
||||
}
|
||||
|
||||
#! Its angle, in radians, from -π to π.
|
||||
pub val rot::angle: f32 {
|
||||
get => math::atan2(this.s, this.c);
|
||||
}
|
||||
|
||||
pub def rot::equals(&this, other: &rot): bool {
|
||||
return this.c == other.c && this.s == other.s;
|
||||
}
|
||||
|
||||
#! A vector turned by it.
|
||||
pub def rot::apply(&this, v: vec2): vec2 {
|
||||
return vec2{ this.c * v.x - this.s * v.y, this.s * v.x + this.c * v.y };
|
||||
}
|
||||
|
||||
#! A vector turned back by it, as its inverse turns it.
|
||||
pub def rot::unapply(&this, v: vec2): vec2 {
|
||||
return vec2{ this.c * v.x + this.s * v.y, this.c * v.y - this.s * v.x };
|
||||
}
|
||||
|
||||
#! It after another: turning by the product turns by `other`, then by this.
|
||||
pub def rot::mul(&this, other: &rot): rot {
|
||||
return rot{ this.c * other.c - this.s * other.s, this.s * other.c + this.c * other.s };
|
||||
}
|
||||
|
||||
#! Where a body is in the plane, and which way it's turned: what a place of its
|
||||
#! own, as its shapes' corners are, is in the plane.
|
||||
@serial
|
||||
pub struct pose {
|
||||
@serial pub var at: vec2;
|
||||
@serial pub var turn := rot::identity;
|
||||
}
|
||||
|
||||
#! At the origin, unturned.
|
||||
pub val pose::identity := pose{};
|
||||
|
||||
#! A pose at a place, turned by an angle, in radians, counterclockwise.
|
||||
pub def pose::of(at: vec2, angle: f32 = 0): pose {
|
||||
return pose{ at = at, turn = rot::of(angle) };
|
||||
}
|
||||
|
||||
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 the plane.
|
||||
pub def pose::apply(&this, local: vec2): vec2 {
|
||||
return this.at + this.turn.apply(local);
|
||||
}
|
||||
|
||||
#! Where a place of the plane is in the body's own.
|
||||
pub def pose::unapply(&this, place: vec2): vec2 {
|
||||
return this.turn.unapply(place - this.at);
|
||||
}
|
||||
|
||||
#! 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 };
|
||||
}
|
||||
|
||||
#! Another pose of the plane, 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 c := this.turn.c * other.turn.c + this.turn.s * other.turn.s;
|
||||
val s := this.turn.c * other.turn.s - this.turn.s * other.turn.c;
|
||||
return pose{ at = this.unapply(other.at), turn = rot{ c, s } };
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
#! Contains `shape`: a circle, a capsule, or a convex polygon, 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::containers;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! The most corners a polygon has.
|
||||
pub const max_corners: u32 = 8;
|
||||
|
||||
#! What a shape is.
|
||||
pub enum shape_kind: u8 {
|
||||
#! The places within its radius of its middle.
|
||||
circle,
|
||||
#! The places within its radius of a segment, between its two ends, as a
|
||||
#! pill; of a radius of 0, the segment itself, as a thin wall.
|
||||
capsule,
|
||||
#! A convex polygon of three to eight corners.
|
||||
polygon,
|
||||
}
|
||||
|
||||
#! A shape of a body, about the body's origin, as a pose places it: a circle,
|
||||
#! a capsule, or a convex polygon, each its points and a radius around them. A
|
||||
#! circle is its middle, a capsule its two ends, and a polygon its corners,
|
||||
#! counterclockwise, each edge's normal facing out.
|
||||
pub struct shape {
|
||||
var _kind: shape_kind;
|
||||
var _radius: f32;
|
||||
var _count: u32;
|
||||
var _points: vec2[8];
|
||||
var _normals: vec2[8]; # Of edge `i`, from point `i` to the next.
|
||||
}
|
||||
|
||||
#! 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: vec2;
|
||||
pub var normal: vec2;
|
||||
}
|
||||
|
||||
#! A circle of a radius, about a middle, the body's origin at first.
|
||||
pub def shape::circle(radius: f32, center: vec2 = vec2::zero): shape {
|
||||
var made := shape{ _kind = shape_kind::circle, _radius = radius, _count = 1 };
|
||||
made._points[0] = center;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A capsule of a radius about the segment between two places: a circle of
|
||||
#! the radius, where they're one place.
|
||||
pub def shape::capsule(a: vec2, b: vec2, radius: f32): shape {
|
||||
return shape::circle(radius, a) if (b - a).length_squared <= tiny * tiny;
|
||||
var made := shape{ _kind = shape_kind::capsule, _radius = radius, _count = 2 };
|
||||
made._points[0] = a;
|
||||
made._points[1] = b;
|
||||
made.find_normals();
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A capsule standing up, 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 circle.
|
||||
pub def shape::pill(width: f32, height: f32, center: vec2 = vec2::zero): shape {
|
||||
val radius := width / 2;
|
||||
val reach := math::max(height / 2 - radius, 0f);
|
||||
return shape::capsule(center - vec2{ 0, reach }, center + vec2{ 0, reach }, radius);
|
||||
}
|
||||
|
||||
#! A segment between two places, of no thickness, as a capsule of no radius.
|
||||
pub def shape::segment(a: vec2, b: vec2): shape {
|
||||
return shape::capsule(a, b, 0);
|
||||
}
|
||||
|
||||
#! A box reaching so far each way from its middle, turned by an angle, in
|
||||
#! radians.
|
||||
pub def shape::box(half: vec2, center: vec2 = vec2::zero, angle: f32 = 0): shape {
|
||||
val turn := rot::of(angle);
|
||||
var made := shape{ _kind = shape_kind::polygon, _count = 4 };
|
||||
val corners: vec2[4] = [vec2{ -half.x, -half.y }, vec2{ half.x, -half.y }, vec2{ half.x, half.y }, vec2{ -half.x, half.y }];
|
||||
for i in 0..4u {
|
||||
made._points[i] = center + turn.apply(corners[i]);
|
||||
}
|
||||
made.find_normals();
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The convex polygon around places, three to eight of its corners among
|
||||
#! them: what's inside it and on its edges left out. Nothing where the places
|
||||
#! hold no area, or their hull has more than eight corners.
|
||||
pub def shape::polygon(places: span<vec2>): maybe<shape> {
|
||||
var sorted := vector::<vec2>::new();
|
||||
for i in 0..places.length {
|
||||
sorted.append(places[i]);
|
||||
}
|
||||
sorted.sort_by(before_in_x);
|
||||
# Andrew's monotone chain: the hull's lower half, left to right, then its
|
||||
# upper, right to left, each corner turning left of the last two.
|
||||
var hull := vector::<vec2>::new();
|
||||
for i in 0..sorted.length {
|
||||
while hull.length >= 2 && turning(hull[hull.length - 2], hull[hull.length - 1], sorted[i]) <= tiny {
|
||||
hull.truncate();
|
||||
}
|
||||
hull.append(sorted[i]);
|
||||
}
|
||||
val lower := hull.length + 1;
|
||||
var i := sorted.length;
|
||||
while i > 1 {
|
||||
i--;
|
||||
val p := sorted[i - 1];
|
||||
while hull.length >= lower && turning(hull[hull.length - 2], hull[hull.length - 1], p) <= tiny {
|
||||
hull.truncate();
|
||||
}
|
||||
hull.append(p);
|
||||
}
|
||||
# Its last corner is its first again.
|
||||
if hull.length > 0 {
|
||||
hull.truncate();
|
||||
}
|
||||
return nothing{} if hull.length < 3 || hull.length > max_corners as u64;
|
||||
var made := shape{ _kind = shape_kind::polygon, _count = hull.length as u32 };
|
||||
for k in 0..hull.length {
|
||||
made._points[k] = hull[k];
|
||||
}
|
||||
made.find_normals();
|
||||
return made;
|
||||
}
|
||||
|
||||
# Whether a place comes before another, left to right, then bottom to top.
|
||||
def before_in_x(a: &vec2, b: &vec2): bool {
|
||||
return a.x < b.x if a.x != b.x;
|
||||
return a.y < b.y;
|
||||
}
|
||||
|
||||
# Twice the area of the triangle of three places, positive where they turn
|
||||
# counterclockwise.
|
||||
def turning(a: vec2, b: vec2, c: vec2): f32 {
|
||||
return (b - a).cross(c - a);
|
||||
}
|
||||
|
||||
# Finds the normal of each edge: its direction turned a quarter clockwise,
|
||||
# which faces out of corners counterclockwise.
|
||||
def shape::find_normals(&mut this): void {
|
||||
for i in 0..this._count {
|
||||
val edge := this._points[(i + 1) % this._count] - this._points[i];
|
||||
this._normals[i] = vec2{ edge.y, -edge.x }.normalized();
|
||||
}
|
||||
}
|
||||
|
||||
pub val shape::kind: shape_kind {
|
||||
get => this._kind;
|
||||
}
|
||||
|
||||
#! How far around its points it reaches: a circle's or a capsule's radius,
|
||||
#! and none of a polygon.
|
||||
pub val shape::radius: f32 {
|
||||
get => this._radius;
|
||||
}
|
||||
|
||||
#! How many points it's of: a circle 1, a capsule 2, and a polygon its
|
||||
#! corners.
|
||||
pub val shape::count: u32 {
|
||||
get => this._count;
|
||||
}
|
||||
|
||||
#! A point of it: a circle's middle, a capsule's end, or a polygon's corner.
|
||||
pub def shape::point(&this, i: u32): vec2 {
|
||||
return this._points[i];
|
||||
}
|
||||
|
||||
#! The normal of an edge of a capsule or a polygon, from point `i` to the
|
||||
#! next, facing out.
|
||||
pub def shape::normal(&this, i: u32): vec2 {
|
||||
return this._normals[i];
|
||||
}
|
||||
|
||||
#! The box holding it, where a pose places it.
|
||||
pub def shape::bounds(&this, at: pose): aabb {
|
||||
var low := at.apply(this._points[0]);
|
||||
var high := low;
|
||||
for i in 1..this._count {
|
||||
val p := at.apply(this._points[i]);
|
||||
low = low.min(p);
|
||||
high = high.max(p);
|
||||
}
|
||||
val r := vec2{ this._radius, this._radius };
|
||||
return aabb{ low - r, high + r };
|
||||
}
|
||||
|
||||
#! Whether it holds a place of the plane, where a pose places it, its surface
|
||||
#! among it.
|
||||
pub def shape::contains(&this, at: pose, p: vec2): bool {
|
||||
val local := at.unapply(p);
|
||||
if this._kind == shape_kind::circle {
|
||||
return (local - this._points[0]).length_squared <= this._radius * this._radius;
|
||||
}
|
||||
if this._kind == shape_kind::capsule {
|
||||
val nearest := nearest_on_segment(local, this._points[0], this._points[1]);
|
||||
return (local - nearest).length_squared <= this._radius * this._radius;
|
||||
}
|
||||
for i in 0..this._count {
|
||||
return false if this._normals[i].dot(local - this._points[i]) > 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! 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: vec2, direction: vec2, reach: f32): maybe<ray_hit> {
|
||||
val o := at.unapply(origin);
|
||||
val d := at.turn.unapply(direction);
|
||||
var found: maybe<ray_hit> = nothing{};
|
||||
match this._kind {
|
||||
circle => found = ray_circle(o, d, reach, this._points[0], this._radius);
|
||||
capsule => found = ray_capsule(o, d, reach, this._points[0], this._points[1], this._radius);
|
||||
polygon => found = this.ray_polygon(o, d, reach);
|
||||
}
|
||||
if found is some(hit) {
|
||||
return ray_hit{ distance = hit.distance, point = at.apply(hit.point), normal = at.turn.apply(hit.normal) };
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
# A ray, of the shape's own places, meeting a circle.
|
||||
def ray_circle(o: vec2, d: vec2, reach: f32, center: vec2, 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 * -1f } 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 flat sides, where it meets them between its
|
||||
# ends, else its round ends; or a segment, of no radius, from either side.
|
||||
def ray_capsule(o: vec2, d: vec2, reach: f32, a: vec2, b: vec2, radius: f32): maybe<ray_hit> {
|
||||
val nearest := nearest_on_segment(o, a, b);
|
||||
if (o - nearest).length_squared <= radius * radius {
|
||||
return ray_hit{ distance = 0, point = o, normal = d * -1f };
|
||||
}
|
||||
val along := (b - a).normalized();
|
||||
val length := (b - a).length;
|
||||
# The side facing the ray's beginning.
|
||||
var side := along.perpendicular();
|
||||
if side.dot(o - a) < 0 {
|
||||
side = side * -1f;
|
||||
}
|
||||
val toward := d.dot(side);
|
||||
var best: maybe<ray_hit> = nothing{};
|
||||
if toward < 0 {
|
||||
val t := (side.dot(o - a) - radius) / -toward;
|
||||
if t >= 0 && t <= reach {
|
||||
val p := o + d * t;
|
||||
val s := (p - a).dot(along);
|
||||
if s >= 0 && s <= length {
|
||||
return ray_hit{ distance = t, point = p, normal = side };
|
||||
}
|
||||
}
|
||||
}
|
||||
return nothing{} if radius <= 0;
|
||||
val first := ray_circle(o, d, reach, a, radius);
|
||||
val second := ray_circle(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 polygon, clipped by each edge'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 polygon.
|
||||
def shape::ray_polygon(&this, o: vec2, d: vec2, reach: f32): maybe<ray_hit> {
|
||||
var lower: f32 = 0;
|
||||
var upper := reach;
|
||||
var entered: i64 = -1;
|
||||
for i in 0..this._count {
|
||||
val n := this._normals[i];
|
||||
val numerator := n.dot(this._points[i] - 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 = i as i64;
|
||||
} else if denominator > 0 && t < upper {
|
||||
upper = t;
|
||||
}
|
||||
return nothing{} if upper < lower;
|
||||
}
|
||||
return ray_hit{ distance = 0, point = o, normal = d * -1f } if entered < 0;
|
||||
return ray_hit{ distance = lower, point = o + d * lower, normal = this._normals[entered as u32] };
|
||||
}
|
||||
@@ -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::physics2d;
|
||||
|
||||
# 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 = vec2::zero;
|
||||
this.bodies[b].spin = 0;
|
||||
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 != 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
#! 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.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
# 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. It's eight numbers, which
|
||||
# `wide_contact`'s lanes gather by where each begins.
|
||||
struct body_state {
|
||||
var v: vec2;
|
||||
var w: f32;
|
||||
var pad: f32;
|
||||
var dp: vec2;
|
||||
var dq: rot;
|
||||
}
|
||||
|
||||
# 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: vec2;
|
||||
var dw: f32;
|
||||
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.
|
||||
struct point_constraint {
|
||||
var anchor_a: vec2;
|
||||
var anchor_b: vec2;
|
||||
var base_separation: f32;
|
||||
var normal_impulse: f32;
|
||||
var tangent_impulse: f32;
|
||||
var max_impulse: f32;
|
||||
var normal_mass: f32;
|
||||
var tangent_mass: f32;
|
||||
var relative_velocity: f32;
|
||||
}
|
||||
|
||||
struct contact_constraint {
|
||||
var a: u32; # States.
|
||||
var b: u32;
|
||||
var contact: u32;
|
||||
var normal: vec2;
|
||||
var friction: f32;
|
||||
var restitution: f32;
|
||||
var ma: f32;
|
||||
var ia: f32;
|
||||
var mb: f32;
|
||||
var ib: f32;
|
||||
var soft: softness;
|
||||
var count: u32;
|
||||
var points: point_constraint[2];
|
||||
}
|
||||
|
||||
# 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.
|
||||
struct solver_scratch {
|
||||
var states: vector<body_state>;
|
||||
var motions: vector<body_motion>;
|
||||
var bodies: vector<u32>;
|
||||
var constraints: vector<contact_constraint>;
|
||||
var joints: vector<u32>; # Joints of a moving body.
|
||||
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 an angle, kept of length 1.
|
||||
def turned(q: rot, angle: f32): rot {
|
||||
val c := q.c - angle * q.s;
|
||||
val s := q.s + angle * q.c;
|
||||
val length := math::sqrt(c * c + s * s);
|
||||
return length > 0 ? rot{ c / length, s / length } : rot::identity;
|
||||
}
|
||||
|
||||
# The velocity of a place a body turning at `w` is `r` from its center of.
|
||||
def spun(w: f32, r: vec2): vec2 {
|
||||
return vec2{ -w * r.y, w * r.x };
|
||||
}
|
||||
|
||||
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);
|
||||
color_contacts(&mut s);
|
||||
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_wide(&mut s);
|
||||
warm_contacts(&mut s);
|
||||
this.solve_joints(&mut s, h, true);
|
||||
solve_wide(&mut s, 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);
|
||||
solve_wide(&mut s, 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, 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.bodies.clear();
|
||||
s.states.append(body_state{});
|
||||
s.motions.append(body_motion{});
|
||||
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 body := &this.bodies[b];
|
||||
s.states.append(body_state{ v = body.velocity, w = body.spin });
|
||||
if body.kind == body_kind::dynamic {
|
||||
s.motions.append(body_motion{
|
||||
dv = (this.gravity * body.gravity_scale + body.force * body.inv_mass) * h,
|
||||
dw = h * body.inv_inertia * body.torque,
|
||||
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 n := c.manifold.normal;
|
||||
val t := vec2{ n.y, -n.x };
|
||||
var made := contact_constraint{
|
||||
a = a.slot, b = b.slot, contact = k as u32, normal = n, friction = c.friction, restitution = c.restitution,
|
||||
ma = a.inv_mass, ia = a.inv_inertia, mb = b.inv_mass, ib = b.inv_inertia,
|
||||
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 rna := ra.cross(n);
|
||||
val rnb := rb.cross(n);
|
||||
val kn := made.ma + made.mb + made.ia * rna * rna + made.ib * rnb * rnb;
|
||||
val rta := ra.cross(t);
|
||||
val rtb := rb.cross(t);
|
||||
val kt := made.ma + made.mb + made.ia * rta * rta + made.ib * rtb * rtb;
|
||||
val vra := a.velocity + spun(a.spin, ra);
|
||||
val vrb := b.velocity + spun(b.spin, rb);
|
||||
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 = kn > 0 ? 1 / kn : 0f, tangent_mass = kt > 0 ? 1 / kt : 0f,
|
||||
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));
|
||||
}
|
||||
if w * w > max_spin * max_spin {
|
||||
w = w * (max_spin / math::abs(w));
|
||||
}
|
||||
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, h * st.w);
|
||||
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];
|
||||
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;
|
||||
val t := vec2{ n.y, -n.x };
|
||||
for j in 0..c.count {
|
||||
val cp := &c.points[j];
|
||||
val p := n * cp.normal_impulse + t * cp.tangent_impulse;
|
||||
wa -= c.ia * cp.anchor_a.cross(p);
|
||||
va = va - p * c.ma;
|
||||
wb += c.ib * cp.anchor_b.cross(p);
|
||||
vb = vb + p * c.mb;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
# Worked a number at a time rather than as `vec2`s: sakurac keeps numbers in
|
||||
# registers, where it passes small vectors through memory, which made this,
|
||||
# the hottest loop of a step, several times slower.
|
||||
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;
|
||||
var vax := states[a].v.x;
|
||||
var vay := states[a].v.y;
|
||||
var wa := states[a].w;
|
||||
var vbx := states[b].v.x;
|
||||
var vby := states[b].v.y;
|
||||
var wb := states[b].w;
|
||||
val dpx := states[b].dp.x - states[a].dp.x;
|
||||
val dpy := states[b].dp.y - states[a].dp.y;
|
||||
val qac := states[a].dq.c;
|
||||
val qas := states[a].dq.s;
|
||||
val qbc := states[b].dq.c;
|
||||
val qbs := states[b].dq.s;
|
||||
val nx := c.normal.x;
|
||||
val ny := c.normal.y;
|
||||
val ma := c.ma;
|
||||
val ia := c.ia;
|
||||
val mb := c.mb;
|
||||
val ib := c.ib;
|
||||
for j in 0..c.count {
|
||||
val cp := &mut c.points[j];
|
||||
val rax := cp.anchor_a.x;
|
||||
val ray := cp.anchor_a.y;
|
||||
val rbx := cp.anchor_b.x;
|
||||
val rby := cp.anchor_b.y;
|
||||
# How far apart they are now: as they began, and as far as each anchor
|
||||
# has moved and turned since.
|
||||
val dx := dpx + (qbc * rbx - qbs * rby) - (qac * rax - qas * ray);
|
||||
val dy := dpy + (qbs * rbx + qbc * rby) - (qas * rax + qac * ray);
|
||||
val separation := dx * nx + dy * ny + cp.base_separation;
|
||||
var bias: f32 = 0;
|
||||
var mass_scale: f32 = 1;
|
||||
var impulse_scale: f32 = 0;
|
||||
if separation > 0 {
|
||||
# Apart: only what closes the gap this substep.
|
||||
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 := (vbx - wb * rby - vax + wa * ray) * nx + (vby + wb * rbx - vay - wa * rax) * ny;
|
||||
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 px := nx * impulse;
|
||||
val py := ny * impulse;
|
||||
vax -= px * ma;
|
||||
vay -= py * ma;
|
||||
wa -= ia * (rax * py - ray * px);
|
||||
vbx += px * mb;
|
||||
vby += py * mb;
|
||||
wb += ib * (rbx * py - rby * px);
|
||||
}
|
||||
# Friction, of no more than its share of what pushes them apart, along
|
||||
# the tangent: the normal turned a quarter clockwise.
|
||||
val tx := ny;
|
||||
val ty := -nx;
|
||||
for j in 0..c.count {
|
||||
val cp := &mut c.points[j];
|
||||
val rax := cp.anchor_a.x;
|
||||
val ray := cp.anchor_a.y;
|
||||
val rbx := cp.anchor_b.x;
|
||||
val rby := cp.anchor_b.y;
|
||||
val vt := (vbx - wb * rby - vax + wa * ray) * tx + (vby + wb * rbx - vay - wa * rax) * ty;
|
||||
val most := c.friction * cp.normal_impulse;
|
||||
val before := cp.tangent_impulse;
|
||||
var sum := before - cp.tangent_mass * vt;
|
||||
if sum > most {
|
||||
sum = most;
|
||||
} else if sum < -most {
|
||||
sum = -most;
|
||||
}
|
||||
val impulse := sum - before;
|
||||
cp.tangent_impulse = sum;
|
||||
val px := tx * impulse;
|
||||
val py := ty * impulse;
|
||||
vax -= px * ma;
|
||||
vay -= py * ma;
|
||||
wa -= ia * (rax * py - ray * px);
|
||||
vbx += px * mb;
|
||||
vby += py * mb;
|
||||
wb += ib * (rbx * py - rby * px);
|
||||
}
|
||||
states[a].v.x = vax;
|
||||
states[a].v.y = vay;
|
||||
states[a].w = wa;
|
||||
states[b].v.x = vbx;
|
||||
states[b].v.y = vby;
|
||||
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;
|
||||
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 ra := cp.anchor_a;
|
||||
val rb := cp.anchor_b;
|
||||
val vn := (vb + spun(wb, rb) - va - spun(wa, ra)).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 -= c.ia * ra.cross(p);
|
||||
vb = vb + p * c.mb;
|
||||
wb += c.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 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 := normalized(st.dq * this.bodies[b].at.turn);
|
||||
this.bodies[b].center = center;
|
||||
this.bodies[b].at = pose{ at = center - turn.apply(this.bodies[b].local_center), turn = turn };
|
||||
this.bodies[b].velocity = st.v;
|
||||
this.bodies[b].spin = st.w;
|
||||
this.bodies[b].force = vec2::zero;
|
||||
this.bodies[b].torque = 0;
|
||||
val speed := st.v.length + math::abs(st.w) * 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);
|
||||
}
|
||||
}
|
||||
|
||||
# A rotation kept of length 1.
|
||||
def normalized(q: rot): rot {
|
||||
val length := math::sqrt(q.c * q.c + q.s * q.s);
|
||||
return length > 0 ? rot{ q.c / length, q.s / length } : rot::identity;
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
#! 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 Box2D's world steps them.
|
||||
#!
|
||||
#! 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; 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, as pixels, is made with how many units a
|
||||
#! meter is, so a tolerance of 5 millimeters stays 5 millimeters.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import std::time;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! 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 := vec2{ 0, -10 };
|
||||
#! 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;
|
||||
#! 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;
|
||||
var unit: f32 = 1;
|
||||
var bodies: vector<body_record>;
|
||||
var colliders: vector<collider_record>;
|
||||
var grids: vector<grid>;
|
||||
var free_grids: vector<u32>;
|
||||
var met: vector<met_cell>;
|
||||
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_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>; # Colliders whose leaves moved.
|
||||
var near: vector<u32>;
|
||||
var noted: vector<contact_event>;
|
||||
var solver: solver_scratch;
|
||||
var islands: vector<u32>;
|
||||
#! How long the last step took, and each of its parts.
|
||||
pub var profile: step_profile;
|
||||
}
|
||||
|
||||
#! 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: vec2 = vec2{ 0, -10 }, unit: f32 = 1): space {
|
||||
return space{
|
||||
gravity = gravity, unit = unit, push_speed = 3 * unit, restitution_threshold = 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 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.view();
|
||||
}
|
||||
|
||||
#! 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;
|
||||
this.bodies[index as u64] = body_record{
|
||||
kind = made.kind, generation = generation, alive = true, at = made.at, center = made.at.at,
|
||||
velocity = made.kind == body_kind::static ? vec2::zero : made.velocity, spin = made.kind == body_kind::static ? 0f : made.spin,
|
||||
linear_damping = made.linear_damping, angular_damping = made.angular_damping, gravity_scale = made.gravity_scale,
|
||||
fixed_rotation = made.fixed_rotation, can_sleep = made.can_sleep, 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);
|
||||
# Those it sleeps with wake, as what held them may be gone.
|
||||
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 grid's solid cells, as a tilemap's walls, met as
|
||||
#! boxes, each but the faces it shares with a solid neighbor, so what slides
|
||||
#! along a floor of many cells slides as along one. Its shape and density are
|
||||
#! passed over; a grid meets shapes, not another grid.
|
||||
pub def space::attach_grid(&mut this, to: body_id, cells: grid, made: collider): collider_id {
|
||||
var held := move(cells);
|
||||
return collider_id{} if !this.has(to);
|
||||
var g: u32 = 0;
|
||||
if this.free_grids.length > 0 {
|
||||
g = this.free_grids[this.free_grids.length - 1];
|
||||
this.free_grids.truncate();
|
||||
this.grids[g as u64] = move(held);
|
||||
} else {
|
||||
g = this.grids.length as u32;
|
||||
this.grids.append(move(held));
|
||||
}
|
||||
return this.attach_record(to, collider_record{ made = made, grid = g, 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): aabb {
|
||||
val record := &this.colliders[c as u64];
|
||||
return record.made.shape.bounds(at) if !record.is_grid();
|
||||
val own := this.grids[record.grid as u64].bounds;
|
||||
val corners: vec2[4] = [own.min, vec2{ own.max.x, own.min.y }, own.max, vec2{ own.min.x, own.max.y }];
|
||||
var low := at.apply(corners[0]);
|
||||
var high := low;
|
||||
for k in 1..4u {
|
||||
val p := at.apply(corners[k]);
|
||||
low = low.min(p);
|
||||
high = high.max(p);
|
||||
}
|
||||
return aabb{ low, high };
|
||||
}
|
||||
|
||||
#! 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;
|
||||
# Unlinked from its body's colliders.
|
||||
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, 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_grid() {
|
||||
val g := this.colliders[c as u64].grid;
|
||||
this.grids[g as u64] = grid::new(0, 0);
|
||||
this.free_grids.append(g);
|
||||
}
|
||||
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): vec2 {
|
||||
return this.bodies[id.index as u64].velocity;
|
||||
}
|
||||
|
||||
pub def space::spin_of(&this, id: body_id): f32 {
|
||||
return this.bodies[id.index as u64].spin;
|
||||
}
|
||||
|
||||
#! A body's mass, its center of its own places, and its rotational inertia
|
||||
#! 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 the plane.
|
||||
pub def space::center_of(&this, id: body_id): vec2 {
|
||||
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: vec2): 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: f32): 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 != 0 {
|
||||
this.wake_body(id.index);
|
||||
}
|
||||
}
|
||||
|
||||
#! Pushes a dynamic body through the next step by a force at a place of the
|
||||
#! plane, which turns it too where that's off its center, waking it.
|
||||
pub def space::apply_force(&mut this, id: body_id, force: vec2, at: vec2): 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 += (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: vec2): 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: f32): void {
|
||||
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
|
||||
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 the plane does, waking it.
|
||||
pub def space::apply_impulse(&mut this, id: body_id, impulse: vec2, at: vec2): 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].inv_inertia * (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);
|
||||
}
|
||||
}
|
||||
|
||||
# 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 made := &this.colliders[c as u64].made;
|
||||
if !this.colliders[c as u64].is_grid() && made.density > 0 {
|
||||
sum = sum.add(made.shape.mass(made.density));
|
||||
}
|
||||
c = this.colliders[c as u64].next;
|
||||
}
|
||||
}
|
||||
var mass: f32 = 0;
|
||||
var inertia: f32 = 0;
|
||||
var local := vec2::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.inertia > 0 && !this.bodies[b as u64].fixed_rotation {
|
||||
inertia = sum.inertia;
|
||||
}
|
||||
}
|
||||
var extent: f32 = 0;
|
||||
var c := this.bodies[b as u64].colliders;
|
||||
while c != none {
|
||||
val s := &this.colliders[c as u64].made.shape;
|
||||
if !this.colliders[c as u64].is_grid() {
|
||||
for i in 0..s.count {
|
||||
extent = math::max(extent, (s.point(i) - local).length + s.radius);
|
||||
}
|
||||
}
|
||||
c = this.colliders[c as u64].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 = inertia > 0 ? 1 / inertia : 0f;
|
||||
this.bodies[i].local_center = local;
|
||||
this.bodies[i].center = this.bodies[i].at.apply(local);
|
||||
this.bodies[i].extent = extent;
|
||||
}
|
||||
|
||||
# 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;
|
||||
}
|
||||
}
|
||||
|
||||
#! Where a ray met a space's collider: which, of which body, and where.
|
||||
pub struct space_hit {
|
||||
pub var collider: collider_id;
|
||||
pub var body: body_id;
|
||||
pub var distance: f32;
|
||||
pub var point: vec2;
|
||||
pub var normal: vec2;
|
||||
}
|
||||
|
||||
#! 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: vec2, direction: vec2, reach: f32, mask: u32 = 0xFFFFFFFF): 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 (c.made.layers & mask) == 0 || c.made.sensor;
|
||||
val at := this.bodies[c.body as u64].at;
|
||||
var met := ray_hit{};
|
||||
if c.is_grid() {
|
||||
val cell := this.grids[c.grid as u64].ray_cast(at, origin, direction, so_far) else { return so_far; };
|
||||
met = cell.hit;
|
||||
} else {
|
||||
met = c.made.shape.ray_cast(at, origin, direction, so_far) else { return so_far; };
|
||||
}
|
||||
best = space_hit{
|
||||
collider = collider_id{ index = data as u32, generation = c.generation },
|
||||
body = body_id{ index = c.body, generation = this.bodies[c.body as u64].generation },
|
||||
distance = met.distance, point = met.point, normal = met.normal,
|
||||
};
|
||||
return met.distance;
|
||||
});
|
||||
return best;
|
||||
}
|
||||
|
||||
#! 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();
|
||||
return if dt <= 0;
|
||||
val began := instant::now();
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
#! 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;
|
||||
}
|
||||
|
||||
def milliseconds(d: duration): f64 {
|
||||
return d.in_nanoseconds as f64 / 1e6;
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
#! 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 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::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
# 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: aabb;
|
||||
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: aabb, data: u64): u32 {
|
||||
val leaf := this.allocate();
|
||||
this.nodes[leaf as u64].box = box.grown(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: aabb): bool {
|
||||
return false if this.nodes[leaf as u64].box.encloses(box);
|
||||
this.remove_leaf(leaf);
|
||||
this.nodes[leaf as u64].box = box.grown(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): aabb {
|
||||
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: aabb, 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: vec2, direction: vec2, 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 this.nodes[index].box.ray_hit(origin, direction, far) is none;
|
||||
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 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: aabb): f32 {
|
||||
val node := &this.nodes[child as u64];
|
||||
val merged := box.merged(node.box).perimeter;
|
||||
return merged if node.left == none_node;
|
||||
return merged - node.box.perimeter;
|
||||
}
|
||||
|
||||
# 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 := node_box.merged(box).perimeter;
|
||||
# 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 - node_box.perimeter);
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
#! Contains how a space solves its contacts eight at a time, as Box2D's solver
|
||||
#! does: 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.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
# 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;
|
||||
|
||||
# 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, and the
|
||||
# impulses pushing them apart and along. A lane of a contact of one point has
|
||||
# a second of no mass, which pushes nothing.
|
||||
struct wide_point {
|
||||
var rax: lanes;
|
||||
var ray: lanes;
|
||||
var rbx: lanes;
|
||||
var rby: lanes;
|
||||
var base: lanes;
|
||||
var normal: lanes;
|
||||
var tangent: lanes;
|
||||
var most: lanes;
|
||||
var normal_mass: lanes;
|
||||
var tangent_mass: lanes;
|
||||
}
|
||||
|
||||
# Eight contacts as lanes: where each body's state begins among the states'
|
||||
# numbers, the normal, friction, each body's inverse mass and inertia, and how
|
||||
# soft each is. A lane of no contact is of the state of what doesn't move, and
|
||||
# pushes nothing.
|
||||
struct wide_contact {
|
||||
var a: lane_places;
|
||||
var b: lane_places;
|
||||
var nx: lanes;
|
||||
var ny: lanes;
|
||||
var friction: lanes;
|
||||
var ma: lanes;
|
||||
var ia: lanes;
|
||||
var mb: lanes;
|
||||
var ib: lanes;
|
||||
var bias_rate: lanes;
|
||||
var mass_scale: lanes;
|
||||
var impulse_scale: lanes;
|
||||
var points: wide_point[2];
|
||||
var of: u32[8]; # Each lane's constraint, or none.
|
||||
}
|
||||
|
||||
# The states' numbers, eight 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 * 8);
|
||||
}
|
||||
|
||||
# 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.ia > 0 ? c.a as u64 : 0u;
|
||||
val b := c.mb > 0 || c.ib > 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);
|
||||
}
|
||||
}
|
||||
# Each color's lanes, a group of eight after another.
|
||||
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]++;
|
||||
pack(&mut s.wide[(first[color as u64] as u64 + at as u64 / width)], at as u64 % width, &s.constraints[k], k as u32);
|
||||
}
|
||||
if experiment {
|
||||
s.overflow.clear();
|
||||
for g in 0..s.wide.length {
|
||||
for lane in 0..width {
|
||||
if s.wide[g].of[lane] != none {
|
||||
s.overflow.append(s.wide[g].of[lane]);
|
||||
}
|
||||
}
|
||||
}
|
||||
s.wide.clear();
|
||||
}
|
||||
}
|
||||
|
||||
const experiment: bool = false;
|
||||
|
||||
# Puts a contact into a lane.
|
||||
def pack(w: &mut wide_contact, lane: u64, c: &contact_constraint, k: u32): void {
|
||||
w.of[lane] = k;
|
||||
w.a[lane] = (c.a * 8) as i32;
|
||||
w.b[lane] = (c.b * 8) as i32;
|
||||
w.nx[lane] = c.normal.x;
|
||||
w.ny[lane] = c.normal.y;
|
||||
w.friction[lane] = c.friction;
|
||||
w.ma[lane] = c.ma;
|
||||
w.ia[lane] = c.ia;
|
||||
w.mb[lane] = c.mb;
|
||||
w.ib[lane] = c.ib;
|
||||
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];
|
||||
w.points[j].rax[lane] = p.anchor_a.x;
|
||||
w.points[j].ray[lane] = p.anchor_a.y;
|
||||
w.points[j].rbx[lane] = p.anchor_b.x;
|
||||
w.points[j].rby[lane] = p.anchor_b.y;
|
||||
w.points[j].base[lane] = p.base_separation;
|
||||
w.points[j].normal[lane] = p.normal_impulse;
|
||||
w.points[j].tangent[lane] = p.tangent_impulse;
|
||||
w.points[j].normal_mass[lane] = p.normal_mass;
|
||||
w.points[j].tangent_mass[lane] = p.tangent_mass;
|
||||
}
|
||||
}
|
||||
|
||||
# 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 {
|
||||
s.constraints[k as u64].points[j].normal_impulse = s.wide[g].points[j].normal[lane];
|
||||
s.constraints[k as u64].points[j].tangent_impulse = s.wide[g].points[j].tangent[lane];
|
||||
s.constraints[k as u64].points[j].max_impulse = s.wide[g].points[j].most[lane];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def warm_wide(s: &mut solver_scratch): void {
|
||||
val numbers := numbers_of(s);
|
||||
val view := numbers.view();
|
||||
val one := lane_places::splat(1);
|
||||
val two := lane_places::splat(2);
|
||||
val groups := s.wide.slice();
|
||||
for g in 0..groups.length {
|
||||
val w := &groups[g];
|
||||
val a1 := w.a + one;
|
||||
val a2 := w.a + two;
|
||||
val b1 := w.b + one;
|
||||
val b2 := w.b + two;
|
||||
var vax := lanes::gather(view, w.a);
|
||||
var vay := lanes::gather(view, a1);
|
||||
var wa := lanes::gather(view, a2);
|
||||
var vbx := lanes::gather(view, w.b);
|
||||
var vby := lanes::gather(view, b1);
|
||||
var wb := lanes::gather(view, b2);
|
||||
val tx := w.ny;
|
||||
val ty := -w.nx;
|
||||
for j in 0..2u {
|
||||
val p := &w.points[j];
|
||||
val px := w.nx * p.normal + tx * p.tangent;
|
||||
val py := w.ny * p.normal + ty * p.tangent;
|
||||
wa = wa - w.ia * (p.rax * py - p.ray * px);
|
||||
vax = vax - px * w.ma;
|
||||
vay = vay - py * w.ma;
|
||||
wb = wb + w.ib * (p.rbx * py - p.rby * px);
|
||||
vbx = vbx + px * w.mb;
|
||||
vby = vby + py * w.mb;
|
||||
}
|
||||
vax.scatter(numbers, w.a);
|
||||
vay.scatter(numbers, a1);
|
||||
wa.scatter(numbers, a2);
|
||||
vbx.scatter(numbers, w.b);
|
||||
vby.scatter(numbers, b1);
|
||||
wb.scatter(numbers, b2);
|
||||
}
|
||||
}
|
||||
|
||||
def solve_wide(s: &mut solver_scratch, inv_h: f32, push: f32, use_bias: bool): void {
|
||||
val numbers := numbers_of(s);
|
||||
val view := numbers.view();
|
||||
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 seven := lane_places::splat(7);
|
||||
val zero := lanes::splat(0);
|
||||
val unit := lanes::splat(1);
|
||||
val per_h := lanes::splat(inv_h);
|
||||
val least := lanes::splat(-push);
|
||||
val groups := s.wide.slice();
|
||||
for g in 0..groups.length {
|
||||
val w := &mut groups[g];
|
||||
val a1 := w.a + one;
|
||||
val a2 := w.a + two;
|
||||
val b1 := w.b + one;
|
||||
val b2 := w.b + two;
|
||||
var vax := lanes::gather(view, w.a);
|
||||
var vay := lanes::gather(view, a1);
|
||||
var wa := lanes::gather(view, a2);
|
||||
var vbx := lanes::gather(view, w.b);
|
||||
var vby := lanes::gather(view, b1);
|
||||
var wb := lanes::gather(view, b2);
|
||||
val dpx := lanes::gather(view, w.b + four) - lanes::gather(view, w.a + four);
|
||||
val dpy := lanes::gather(view, w.b + five) - lanes::gather(view, w.a + five);
|
||||
val qac := lanes::gather(view, w.a + six);
|
||||
val qas := lanes::gather(view, w.a + seven);
|
||||
val qbc := lanes::gather(view, w.b + six);
|
||||
val qbs := lanes::gather(view, w.b + seven);
|
||||
val nx := w.nx;
|
||||
val ny := w.ny;
|
||||
val ma := w.ma;
|
||||
val ia := w.ia;
|
||||
val mb := w.mb;
|
||||
val ib := w.ib;
|
||||
for j in 0..2u {
|
||||
val p := &mut w.points[j];
|
||||
val rax := p.rax;
|
||||
val ray := p.ray;
|
||||
val rbx := p.rbx;
|
||||
val rby := p.rby;
|
||||
val dx := dpx + (qbc * rbx - qbs * rby) - (qac * rax - qas * ray);
|
||||
val dy := dpy + (qbs * rbx + qbc * rby) - (qas * rax + qac * ray);
|
||||
val separation := dx * nx + dy * ny + p.base;
|
||||
# Apart, only what closes the gap this substep; else, pushing softly.
|
||||
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);
|
||||
}
|
||||
val vn := (vbx - wb * rby - vax + wa * ray) * nx + (vby + wb * rbx - vay - wa * rax) * ny;
|
||||
val before := p.normal;
|
||||
val sum := (before - p.normal_mass * mass_scale * (vn + bias) - impulse_scale * before).max(&zero);
|
||||
val impulse := sum - before;
|
||||
p.normal = sum;
|
||||
p.most = p.most.max(&impulse);
|
||||
val px := nx * impulse;
|
||||
val py := ny * impulse;
|
||||
vax = vax - px * ma;
|
||||
vay = vay - py * ma;
|
||||
wa = wa - ia * (rax * py - ray * px);
|
||||
vbx = vbx + px * mb;
|
||||
vby = vby + py * mb;
|
||||
wb = wb + ib * (rbx * py - rby * px);
|
||||
}
|
||||
val tx := ny;
|
||||
val ty := -nx;
|
||||
for j in 0..2u {
|
||||
val p := &mut w.points[j];
|
||||
val rax := p.rax;
|
||||
val ray := p.ray;
|
||||
val rbx := p.rbx;
|
||||
val rby := p.rby;
|
||||
val vt := (vbx - wb * rby - vax + wa * ray) * tx + (vby + wb * rbx - vay - wa * rax) * ty;
|
||||
val most := w.friction * p.normal;
|
||||
val before := p.tangent;
|
||||
val sum := (before - p.tangent_mass * vt).min(&most).max(&-most);
|
||||
val impulse := sum - before;
|
||||
p.tangent = sum;
|
||||
val px := tx * impulse;
|
||||
val py := ty * impulse;
|
||||
vax = vax - px * ma;
|
||||
vay = vay - py * ma;
|
||||
wa = wa - ia * (rax * py - ray * px);
|
||||
vbx = vbx + px * mb;
|
||||
vby = vby + py * mb;
|
||||
wb = wb + ib * (rbx * py - rby * px);
|
||||
}
|
||||
vax.scatter(numbers, w.a);
|
||||
vay.scatter(numbers, a1);
|
||||
wa.scatter(numbers, a2);
|
||||
vbx.scatter(numbers, w.b);
|
||||
vby.scatter(numbers, b1);
|
||||
wb.scatter(numbers, b2);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user