Initial Commit
This commit is contained in:
84 files changed
+18825
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,155 @@
|
||||
#! 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, and its own, pulls it: 0 floats.
|
||||
pub var gravity_scale: f32 = 1;
|
||||
#! A gravity of its own, added to the space's, as a planet's pulls what's
|
||||
#! near it toward its middle.
|
||||
pub var gravity: vec2;
|
||||
#! Whether it never turns, as a character standing up doesn't.
|
||||
pub var fixed_rotation: bool;
|
||||
#! Whether it may sleep when it and what it rests on are still.
|
||||
pub var can_sleep: bool = true;
|
||||
#! Whether it's swept against moving bodies too, not only what stands
|
||||
#! still, so it passes through nothing however fast it goes, as a shot.
|
||||
pub var bullet: bool;
|
||||
#! A number of its user's, as an entity's bits.
|
||||
pub var data: u64;
|
||||
}
|
||||
|
||||
#! What a body's collider is made as: its shape, about the body's origin; its
|
||||
#! density, which sums to the body's mass; how it slides and bounces; and the
|
||||
#! layers it's on and meets. A collider of a 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;
|
||||
#! Whether it's solid only to what comes onto it from the side `up` faces,
|
||||
#! of its body's own directions, as a platform jumped through from below.
|
||||
pub var one_way: bool;
|
||||
pub var up := vec2{ 0, 1 };
|
||||
#! 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 gravity: vec2; # Its own, added to the space's.
|
||||
var fixed_rotation: bool;
|
||||
var can_sleep: bool = true;
|
||||
var awake: bool = true;
|
||||
var sleep_time: f32;
|
||||
var extent: f32; # How far its colliders reach from its center.
|
||||
var least: f32; # How far its narrowest shape reaches from its middle.
|
||||
var bullet: bool;
|
||||
var colliders: u32 = 0xFFFFFFFF;
|
||||
var joints: u32 = 0xFFFFFFFF; # 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,121 @@
|
||||
#! Contains chains of segments, as a level's ground and a cave's walls are
|
||||
#! drawn, and one-way platforms, as a game jumps through from below.
|
||||
#!
|
||||
#! A chain's segments are each a collider of their own, met only on the side
|
||||
#! their normals face, to the right going along the chain, as a polygon's
|
||||
#! counterclockwise edges face out: what's behind a segment passes through it.
|
||||
#! Where two segments join flat or hollow, neither pushes by the corner they
|
||||
#! share, only by their faces, so a body slides across the joints as along one
|
||||
#! surface, never caught on them, as Box2D's chains keep it; where they join at
|
||||
#! a corner sticking out, the segment after it pushes by the corner, as far
|
||||
#! around it as its face and the one before turn.
|
||||
#!
|
||||
#! A one-way collider is solid only to what comes onto it from the side its
|
||||
#! `up` faces: a contact beginning from below it, or beside it, passes through
|
||||
#! until the two part, as a platform is jumped through and landed on.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! Gives a body a chain of segments through places, as a level's ground or a
|
||||
#! cave's walls: each a collider of the chain's own, met on its side to the
|
||||
#! right going from one place to the next, so ground runs right to left, and a
|
||||
#! cave's walls, met from within, clockwise; `looped` joins the last place to
|
||||
#! the first. Their density is passed over, so a chain weighs nothing.
|
||||
pub def space::attach_chain(&mut this, to: body_id, places: span<vec2>, looped: bool, made: collider): vector<collider_id> {
|
||||
var ids := vector::<collider_id>::new();
|
||||
val n := places.length;
|
||||
return ids if n < 2 || !this.has(to);
|
||||
val segments := looped ? n : n - 1;
|
||||
for i in 0..segments {
|
||||
var before: maybe<vec2> = nothing{};
|
||||
var after: maybe<vec2> = nothing{};
|
||||
if looped || i > 0 {
|
||||
before = places[(i + n - 1) % n];
|
||||
}
|
||||
if looped || i + 2 < n {
|
||||
after = places[(i + 2) % n];
|
||||
}
|
||||
var piece := made;
|
||||
piece.shape = shape::chain_segment(places[i], places[(i + 1) % n], before, after);
|
||||
piece.density = 0;
|
||||
ids.append(this.attach(to, piece));
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
# The middle of a shape's points, of its own places.
|
||||
def shape::middle(&this): vec2 {
|
||||
var sum := vec2::zero;
|
||||
for i in 0..this._count {
|
||||
sum = sum + this._points[i];
|
||||
}
|
||||
return sum * (1 / this._count as f32);
|
||||
}
|
||||
|
||||
# A manifold of a chain's segment against another shape, met only on the
|
||||
# segment's front, and by its ends only where they're the chain's own, or a
|
||||
# corner sticking out the segment begins at: nothing where it's met otherwise,
|
||||
# as the segment beside it meets it by its face.
|
||||
def chained(segment: &shape, at: pose, other: &shape, at_other: pose, m: manifold): manifold {
|
||||
return m if m.count == 0;
|
||||
val p1 := at.apply(segment._points[0]);
|
||||
val p2 := at.apply(segment._points[1]);
|
||||
val n := at.turn.apply(segment._normals[0]);
|
||||
return manifold{} if n.dot(at_other.apply(other.middle()) - p1) < 0;
|
||||
return m if m.normal.dot(n) >= 0.9999;
|
||||
val along := p2 - p1;
|
||||
var spot := vec2::zero;
|
||||
for i in 0..m.count {
|
||||
spot = spot + m.points[i].point;
|
||||
}
|
||||
spot = spot * (1 / m.count as f32);
|
||||
if (spot - p1).dot(along) >= 0.5 * along.length_squared {
|
||||
# Its end: the segment after it meets what's there.
|
||||
return manifold{} if (segment._chained & 4) != 0;
|
||||
return m;
|
||||
}
|
||||
return m if (segment._chained & 2) == 0;
|
||||
val incoming := p1 - at.apply(segment._points[2]);
|
||||
# A corner flat or hollow: the segment before meets it by its face.
|
||||
return manifold{} if incoming.cross(along) <= 0.017 * incoming.length * along.length;
|
||||
val n_before := vec2{ incoming.y, -incoming.x }.normalized();
|
||||
return m if n_before.cross(m.normal) >= 0 && m.normal.cross(n) >= 0;
|
||||
return manifold{};
|
||||
}
|
||||
|
||||
# Whether a one-sided collider, a chain's segment or a one-way collider, lets
|
||||
# a shape where a pose places it through, as it's behind or below it.
|
||||
def space::behind_one_way(&this, c: u32, s: &shape, at: pose): bool {
|
||||
val held := &this.colliders[c as u64];
|
||||
return false if held.is_grid();
|
||||
val placed := this.bodies[held.body as u64].at;
|
||||
if held.made.shape.is_one_sided {
|
||||
val n := placed.turn.apply(held.made.shape._normals[0]);
|
||||
return n.dot(at.apply(s.middle()) - placed.apply(held.made.shape._points[0])) < 0;
|
||||
}
|
||||
return false if !held.made.one_way;
|
||||
val g := gap_between(&held.made.shape, placed, s, at);
|
||||
return g.distance <= 0 || g.normal.dot(placed.turn.apply(held.made.up)) < 0.7;
|
||||
}
|
||||
|
||||
# Whether a contact of a one-way collider holds: one beginning from its `up`
|
||||
# side does, until the two part; one beginning otherwise passes through until
|
||||
# then.
|
||||
def space::one_way_holds(&mut this, k: u32, platform: u32, began: bool): bool {
|
||||
val c := &mut this.contacts[k as u64];
|
||||
if !c.touching {
|
||||
c.passing = false;
|
||||
return false;
|
||||
}
|
||||
if began {
|
||||
val held := &this.colliders[platform as u64];
|
||||
val up := this.bodies[held.body as u64].at.turn.apply(held.made.up);
|
||||
# The normal from the platform toward what met it.
|
||||
val toward := this.pairs[c.pair as u64].a == platform ? c.manifold.normal : c.manifold.normal * -1f;
|
||||
c.passing = toward.dot(up) < 0.7;
|
||||
}
|
||||
return !c.passing;
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
#! Contains `character`, a body a game walks, as Box2D's character mover is:
|
||||
#! not a rigid body of the space, but a shape moved through it by casts, sliding
|
||||
#! along what it meets, stepping up what's low enough, sticking to the ground as
|
||||
#! it walks down slopes and off steps, riding what it stands on as that moves,
|
||||
#! pushed out of what moves into it, and pushing what's dynamic before it.
|
||||
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! A character's body, and what it stands on, as its last move found it.
|
||||
pub struct character {
|
||||
#! Its shape, about its origin, a capsule standing up as `shape::pill`
|
||||
#! makes one.
|
||||
pub var shape := shape::pill(0.6, 1.8);
|
||||
#! Where its origin is.
|
||||
pub var at: vec2;
|
||||
#! Which way is up, against gravity, of length 1: its shape stands along
|
||||
#! it, as on a planet, where up is away from the middle.
|
||||
pub var up := vec2{ 0, 1 };
|
||||
#! How fast it moved in its last move, but for what it rode: what it was
|
||||
#! asked to, less what it met. A game adds gravity to it while it's in the
|
||||
#! air.
|
||||
pub var velocity: vec2;
|
||||
#! The steepest ground it stands on and walks up, in radians from flat.
|
||||
pub var max_slope: f32 = 0.8;
|
||||
#! The highest it steps up, as onto a stair, and the furthest down it keeps
|
||||
#! to the ground, as walking down one.
|
||||
pub var step_height: f32 = 0.35;
|
||||
pub var snap: f32 = 0.35;
|
||||
#! How far it keeps from what it meets.
|
||||
pub var skin: f32 = 0.02;
|
||||
#! Its mass, and the most force it pushes what's dynamic with.
|
||||
pub var mass: f32 = 70;
|
||||
pub var push: f32 = 500;
|
||||
#! The layers of colliders it meets.
|
||||
pub var mask: u32 = 0xFFFFFFFF;
|
||||
#! A body of its own in the space, as a kinematic one moved with it so what
|
||||
#! moves meets it, which it passes over.
|
||||
pub var body: body_id;
|
||||
#! Whether it stands on ground it may, and that ground: which way it faces,
|
||||
#! its body, and how fast it moves where the character stands.
|
||||
pub var grounded: bool;
|
||||
pub var ground_normal := vec2{ 0, 1 };
|
||||
pub var ground: body_id;
|
||||
pub var ground_velocity: vec2;
|
||||
}
|
||||
|
||||
#! Whether a character may stand on ground facing a direction.
|
||||
pub def character::walkable(&this, normal: vec2): bool {
|
||||
return normal.dot(this.up) >= math::cos(this.max_slope);
|
||||
}
|
||||
|
||||
#! Its pose: at its place, turned from standing along y to stand along its up.
|
||||
pub def character::pose(&this): pose {
|
||||
return this.pose_at(this.at);
|
||||
}
|
||||
|
||||
# Its pose, were it somewhere else.
|
||||
def character::pose_at(&this, at: vec2): pose {
|
||||
return pose::of(at, math::atan2(-this.up.x, this.up.y));
|
||||
}
|
||||
|
||||
#! Moves a character through a step of `dt` seconds, at a velocity, as its
|
||||
#! game asks, adding how fast what it stands on moves: pushed out of what it
|
||||
#! overlaps, then cast along its motion, sliding along what it meets, stepping
|
||||
#! up what's low enough while it's on the ground, and kept to the ground as it
|
||||
#! walks down. Its velocity after is what it was asked, less what it met; what
|
||||
#! it stands on is found again.
|
||||
pub def space::move_character(&mut this, c: &mut character, velocity: vec2, dt: f32): void {
|
||||
return if dt <= 0;
|
||||
val was_grounded := c.grounded;
|
||||
c.velocity = velocity;
|
||||
this.push_character_out(c);
|
||||
var motion := velocity * dt;
|
||||
if was_grounded {
|
||||
motion = motion + c.ground_velocity * dt;
|
||||
}
|
||||
for iteration in 0..4u {
|
||||
if motion.length_squared < tiny * tiny {
|
||||
break;
|
||||
}
|
||||
val hit := this.shape_cast(&c.shape, c.pose(), motion, c.mask, c.body) else {
|
||||
c.at = c.at + motion;
|
||||
break;
|
||||
};
|
||||
c.at = c.at + motion * hit.fraction + hit.normal * c.skin;
|
||||
var left := motion * (1 - hit.fraction);
|
||||
val walkable := c.walkable(hit.normal);
|
||||
if !walkable && was_grounded && this.step_up(c, velocity * dt) {
|
||||
break;
|
||||
}
|
||||
# What's left slides along what it met: along a wall it can't walk up,
|
||||
# not up it.
|
||||
var n := hit.normal;
|
||||
if !walkable && was_grounded {
|
||||
val flat := n - c.up * n.dot(c.up);
|
||||
if flat.length_squared > tiny {
|
||||
n = flat.normalized();
|
||||
}
|
||||
}
|
||||
this.push_struck(c, &hit, dt);
|
||||
left = left - n * math::min(left.dot(n), 0f);
|
||||
c.velocity = c.velocity - n * math::min(c.velocity.dot(n), 0f);
|
||||
motion = left;
|
||||
}
|
||||
# Kept to the ground walking down a slope or off a step, where it isn't
|
||||
# moving up.
|
||||
if was_grounded && c.velocity.dot(c.up) <= 0 && c.snap > 0 {
|
||||
if this.shape_cast(&c.shape, c.pose(), c.up * -c.snap, c.mask, c.body) is some(down) {
|
||||
if c.walkable(down.normal) {
|
||||
c.at = c.at - c.up * (c.snap * down.fraction) + c.up * c.skin;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.find_ground(c);
|
||||
}
|
||||
|
||||
# Finds what a character stands on, just below it.
|
||||
def space::find_ground(&this, c: &mut character): void {
|
||||
c.grounded = false;
|
||||
c.ground = body_id{};
|
||||
c.ground_velocity = vec2::zero;
|
||||
val below := this.shape_cast(&c.shape, c.pose(), c.up * (-3 * c.skin), c.mask, c.body) else { return; };
|
||||
return if !c.walkable(below.normal);
|
||||
c.grounded = true;
|
||||
c.ground_normal = below.normal;
|
||||
c.ground = below.body;
|
||||
val b := &this.bodies[below.body.index as u64];
|
||||
if b.kind != body_kind::static {
|
||||
c.ground_velocity = b.velocity + spun(b.spin, c.at - b.center);
|
||||
}
|
||||
# Standing, it doesn't fall into the ground.
|
||||
val falling := c.velocity.dot(c.up);
|
||||
if falling < 0 {
|
||||
c.velocity = c.velocity - c.up * falling;
|
||||
}
|
||||
}
|
||||
|
||||
# Steps a character up onto what it walked into, where it's no higher than its
|
||||
# step: raised, moved on as far as it walks this step, and lowered, where
|
||||
# feeling further ahead finds ground it may stand on there.
|
||||
def space::step_up(&this, c: &mut character, left: vec2): bool {
|
||||
val ahead := left - c.up * left.dot(c.up);
|
||||
return false if ahead.length_squared < tiny * tiny || c.step_height <= 0;
|
||||
var rise := c.step_height;
|
||||
if this.shape_cast(&c.shape, c.pose(), c.up * c.step_height, c.mask, c.body) is some(above) {
|
||||
rise = math::max(c.step_height * above.fraction - c.skin, 0f);
|
||||
}
|
||||
return false if rise <= c.skin;
|
||||
val raised := c.pose_at(c.at + c.up * rise);
|
||||
# Felt for further ahead than its round foot reaches, however little it's
|
||||
# left to move, so it steps only onto what's there to stand on, higher than
|
||||
# it stands, and not onto the step's edge.
|
||||
val reach := math::max(ahead.length, c.shape.radius + 2 * c.skin);
|
||||
val probe := ahead.normalized() * reach;
|
||||
var moved := probe;
|
||||
if this.shape_cast(&c.shape, raised, probe, c.mask, c.body) is some(wall) {
|
||||
moved = probe * wall.fraction;
|
||||
}
|
||||
return false if moved.length < 0.5 * reach;
|
||||
val drop := c.up * -(rise + c.skin);
|
||||
val landing := this.shape_cast(&c.shape, c.pose_at(raised.at + moved), drop, c.mask, c.body) else { return false; };
|
||||
return false if !c.walkable(landing.normal) || landing.fraction == 0;
|
||||
return false if (rise + c.skin) * (1 - landing.fraction) <= c.skin;
|
||||
# Then moved as far as it walks, and set down, on the step's edge, maybe, to
|
||||
# walk on from.
|
||||
val over := c.pose_at(raised.at + ahead * math::min(1f, moved.length / ahead.length));
|
||||
val down := this.shape_cast(&c.shape, over, drop, c.mask, c.body) else { return false; };
|
||||
c.at = over.at + drop * down.fraction + c.up * c.skin;
|
||||
return true;
|
||||
}
|
||||
|
||||
# Pushes a character out of what it overlaps, as what moves into it does, a
|
||||
# few times over, by the deepest each time.
|
||||
def space::push_character_out(&this, c: &mut character): void {
|
||||
for iteration in 0..4u {
|
||||
var deepest: f32 = 0;
|
||||
var away := vec2::zero;
|
||||
val placed := c.pose();
|
||||
this.tree.query(c.shape.bounds(placed).grown(c.skin), def(leaf: u32, data: u64): bool {
|
||||
return true if this.colliders[data].body == c.body.index || !this.passes(data as u32, &query_filter{ mask = c.mask }) || this.behind_one_way(data as u32, &c.shape, placed);
|
||||
val held := &this.colliders[data];
|
||||
val at := this.bodies[held.body as u64].at;
|
||||
if held.is_grid() {
|
||||
this.grids[held.grid as u64].collide(at, &c.shape, placed, def(x: u32, y: u32, m: manifold): bool {
|
||||
if m.depth > deepest {
|
||||
deepest = m.depth;
|
||||
away = m.normal;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
var m := collide(&held.made.shape, at, &c.shape, placed) else { return true; };
|
||||
if held.made.shape.is_one_sided {
|
||||
m = chained(&held.made.shape, at, &c.shape, placed, m);
|
||||
}
|
||||
if m.depth > deepest {
|
||||
deepest = m.depth;
|
||||
away = m.normal;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if deepest <= 0 {
|
||||
return;
|
||||
}
|
||||
c.at = c.at + away * (deepest + c.skin);
|
||||
}
|
||||
}
|
||||
|
||||
# Pushes a dynamic body a character walked into, by no more than its push.
|
||||
def space::push_struck(&mut this, c: &character, hit: &space_cast, dt: f32): void {
|
||||
return if !this.has(hit.body) || this.bodies[hit.body.index as u64].kind != body_kind::dynamic;
|
||||
val into := -c.velocity.dot(hit.normal);
|
||||
return if into <= 0;
|
||||
val impulse := math::min(into * c.mass, c.push * dt);
|
||||
this.apply_impulse(hit.body, -hit.normal * impulse, hit.point);
|
||||
}
|
||||
@@ -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,474 @@
|
||||
#! 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 passing: bool; # Of a one-way collider's, met from below.
|
||||
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, or one
|
||||
# a sensor and the other not static, 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());
|
||||
if !this.bodies[ca.body as u64].is_dynamic() && !this.bodies[cb.body as u64].is_dynamic() {
|
||||
# A sensor meets what moves into it, kinematic as well as dynamic, but two
|
||||
# standing still never meet.
|
||||
return false if !ca.made.sensor && !cb.made.sensor;
|
||||
return false if this.bodies[ca.body as u64].kind == body_kind::static && this.bodies[cb.body as u64].kind == body_kind::static;
|
||||
}
|
||||
return false if (ca.made.layers & cb.made.mask) == 0 || (cb.made.layers & ca.made.mask) == 0;
|
||||
return !this.joined_apart(ca.body, cb.body);
|
||||
}
|
||||
|
||||
# Pairs each collider whose leaf moved with those its grown box newly meets.
|
||||
def space::find_pairs(&mut this): void {
|
||||
return if this.moved.length == 0;
|
||||
var near := move(this.near);
|
||||
for m in 0..this.moved.length {
|
||||
val c := this.moved[m];
|
||||
continue if !this.colliders[c as u64].alive;
|
||||
near.clear();
|
||||
this.tree.query(this.tree.box_of(this.colliders[c as u64].leaf), def(leaf: u32, data: u64): bool {
|
||||
val other := data as u32;
|
||||
# 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;
|
||||
}
|
||||
|
||||
# Where a pair's shapes meet: as the crew found it, where the step is solved on
|
||||
# several threads, else found now.
|
||||
def space::pair_manifold(&this, p: u32): manifold {
|
||||
return this.found[p as u64] if this.threads > 1;
|
||||
return this.manifold_of(this.pairs[p as u64].a, this.pairs[p as u64].b);
|
||||
}
|
||||
|
||||
# Finds where each pair of two shapes meets, on the crew, a block of pairs to
|
||||
# each thread, as none needs another's: what it finds is put to use one pair at
|
||||
# a time after, so a step gives the same on any number of threads.
|
||||
def space::find_manifolds(&mut this): void {
|
||||
this.found.clear();
|
||||
this.found.resize(this.pairs.length, manifold{});
|
||||
var job := pairs_job{ space = address(this) };
|
||||
val block := math::max(this.pairs.length / (this.threads as u64 * 8), 16u);
|
||||
this.crew.run(run_pairs, address(&mut job) as *mut u8, this.pairs.length, block);
|
||||
}
|
||||
|
||||
struct pairs_job {
|
||||
var space: *mut space;
|
||||
}
|
||||
|
||||
def run_pairs(context: *mut u8, begin: u64, end: u64): void {
|
||||
val job := &through(context as *mut pairs_job);
|
||||
val s := &mut through(job.space);
|
||||
for p in begin..end {
|
||||
val pair := &s.pairs[p];
|
||||
continue if !pair.alive || pair.sensor || pair.grid;
|
||||
val ca := &s.colliders[pair.a as u64];
|
||||
val cb := &s.colliders[pair.b as u64];
|
||||
continue if !s.moves(ca.body) && !s.moves(cb.body);
|
||||
continue if !s.tree.box_of(ca.leaf).overlaps(s.tree.box_of(cb.leaf));
|
||||
s.found[p] = s.manifold_of(pair.a, pair.b);
|
||||
}
|
||||
}
|
||||
|
||||
# Finds where each pair of a moving body meets, dropping those whose grown
|
||||
# boxes no longer meet.
|
||||
def space::update_contacts(&mut this): void {
|
||||
if this.threads > 1 {
|
||||
this.find_manifolds();
|
||||
}
|
||||
for p in 0..this.pairs.length {
|
||||
continue if !this.pairs[p].alive;
|
||||
val a := this.pairs[p].a;
|
||||
val b := this.pairs[p].b;
|
||||
val ba := this.colliders[a as u64].body;
|
||||
val bb := this.colliders[b as u64].body;
|
||||
continue if !this.moves(ba) && !this.moves(bb);
|
||||
if !this.tree.box_of(this.colliders[a as u64].leaf).overlaps(this.tree.box_of(this.colliders[b as u64].leaf)) {
|
||||
this.drop_pair(p as u32, false);
|
||||
continue;
|
||||
}
|
||||
var touching := false;
|
||||
if this.pairs[p].sensor {
|
||||
touching = this.sensed(a, b);
|
||||
} else if this.pairs[p].grid {
|
||||
touching = this.update_grid_contacts(p as u32);
|
||||
} else {
|
||||
val k := this.pairs[p].contacts;
|
||||
val before := this.contacts[k as u64].touching;
|
||||
touching = this.update_contact(k, this.pair_manifold(p as u32));
|
||||
if this.colliders[a as u64].made.one_way {
|
||||
touching = this.one_way_holds(k, a, !before);
|
||||
} else if this.colliders[b as u64].made.one_way {
|
||||
touching = this.one_way_holds(k, b, !before);
|
||||
}
|
||||
}
|
||||
if touching != this.pairs[p].touching {
|
||||
this.pairs[p].touching = touching;
|
||||
this.note(p as u32, touching);
|
||||
if touching && !this.pairs[p].sensor {
|
||||
this.note_hit(p as u32);
|
||||
}
|
||||
}
|
||||
# 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];
|
||||
val at_a := this.bodies[ca.body as u64].at;
|
||||
val at_b := this.bodies[cb.body as u64].at;
|
||||
val m := collide(&ca.made.shape, at_a, &cb.made.shape, at_b, this.speculative) else { return manifold{}; };
|
||||
return chained(&ca.made.shape, at_a, &cb.made.shape, at_b, m) if ca.made.shape.is_one_sided;
|
||||
return chained(&cb.made.shape, at_b, &ca.made.shape, at_a, m.flipped()).flipped() if cb.made.shape.is_one_sided;
|
||||
return m;
|
||||
}
|
||||
|
||||
# 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;
|
||||
}
|
||||
|
||||
#! Two colliders that began touching in a step faster than the space's
|
||||
#! `hit_speed`, as something landing does: which, where, the normal from the
|
||||
#! first toward the second, and how fast they met along it, as a sound of it
|
||||
#! might be loud.
|
||||
pub struct hit_event {
|
||||
pub var a: collider_id;
|
||||
pub var b: collider_id;
|
||||
pub var point: vec2;
|
||||
pub var normal: vec2;
|
||||
pub var speed: f32;
|
||||
}
|
||||
|
||||
#! The hits of the last step.
|
||||
pub def space::hits(&this): span<hit_event> {
|
||||
return this.struck.span;
|
||||
}
|
||||
|
||||
# How fast a body's place moves, of a place of space.
|
||||
def space::speed_at(&this, index: u32, at: vec2): vec2 {
|
||||
val b := &this.bodies[index as u64];
|
||||
val r := at - b.center;
|
||||
return b.velocity + spun(b.spin, r);
|
||||
}
|
||||
|
||||
# Notes how hard a pair that began touching met, where it met faster than the
|
||||
# hit speed: at its first point, as the step began.
|
||||
def space::note_hit(&mut this, p: u32): void {
|
||||
var k := this.pairs[p as u64].contacts;
|
||||
while k != none && this.contacts[k as u64].manifold.count == 0 {
|
||||
k = this.contacts[k as u64].next;
|
||||
}
|
||||
return if k == none;
|
||||
val c := &this.contacts[k as u64];
|
||||
val point := c.manifold.points[0].point;
|
||||
val n := c.manifold.normal;
|
||||
val speed := -n.dot(this.speed_at(c.body_b, point) - this.speed_at(c.body_a, point));
|
||||
return if speed < this.hit_speed;
|
||||
val a := this.pairs[p as u64].a;
|
||||
val b := this.pairs[p as u64].b;
|
||||
this.struck.append(hit_event{
|
||||
a = collider_id{ index = a, generation = this.colliders[a as u64].generation },
|
||||
b = collider_id{ index = b, generation = this.colliders[b as u64].generation },
|
||||
point = point, normal = n, speed = speed,
|
||||
});
|
||||
}
|
||||
|
||||
#! Visits each pair of colliders touching as the last step left them, a
|
||||
#! sensor's among them where it overlaps what it meets, as `visit(a, b,
|
||||
#! sensor)`, until it gives false: what began and stopped touching since a
|
||||
#! step before, by what it visited then, however colliders were taken away
|
||||
#! and attached between.
|
||||
pub def space::each_touching<F>(&this, visit: F): void where F: invokable<def(collider_id, collider_id, bool): bool> {
|
||||
for p in 0..this.pairs.length {
|
||||
val pair := &this.pairs[p];
|
||||
continue if !pair.alive || !pair.touching;
|
||||
return if !visit(this.named(pair.a), this.named(pair.b), pair.sensor);
|
||||
}
|
||||
}
|
||||
#! Visits each point of each contact touching, as `visit(a, b, point, normal,
|
||||
#! depth)`, of its two colliders, its normal from the first toward the
|
||||
#! second, until it gives false, as gizmos draw them.
|
||||
pub def space::each_contact<F>(&this, visit: F): void where F: invokable<def(collider_id, collider_id, vec2, vec2, f32): bool> {
|
||||
for k in 0..this.contacts.length {
|
||||
val c := &this.contacts[k];
|
||||
continue if !c.alive || !c.touching;
|
||||
val pair := &this.pairs[c.pair as u64];
|
||||
val a := collider_id{ index = pair.a, generation = this.colliders[pair.a as u64].generation };
|
||||
val b := collider_id{ index = pair.b, generation = this.colliders[pair.b as u64].generation };
|
||||
for i in 0..c.manifold.count {
|
||||
return if !visit(a, b, c.manifold.points[i].point, c.manifold.normal, c.manifold.points[i].depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
#! Contains continuous collision, as Box2D's keeps a fast body from passing
|
||||
#! through what's thin: a dynamic body that moved further in a step than half
|
||||
#! the least its shapes reach is swept, from where it began the step to where
|
||||
#! it ended it, against what stands still, and put back where it first comes
|
||||
#! within the slop of what it met, its velocity kept, so the next step's
|
||||
#! contacts stop it there. A bullet is swept against moving bodies too, where
|
||||
#! they ended the step, as a shot against a crate.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
# A body moving fast enough this step to pass through something thin, and how
|
||||
# it moved.
|
||||
struct fast_body {
|
||||
var body: u32;
|
||||
var moved: sweep;
|
||||
}
|
||||
|
||||
# Notes a body that moved fast enough to be swept, as the step ends.
|
||||
def space::note_fast(&mut this, b: u32, moved: sweep): void {
|
||||
val body := &this.bodies[b as u64];
|
||||
return if !this.continuous || body.kind != body_kind::dynamic || body.least <= 0;
|
||||
val travel := (moved.c2 - moved.c1).length + math::abs(angle_between(moved.q2, moved.q1)) * body.extent;
|
||||
if travel > 0.5 * body.least {
|
||||
this.fast.append(fast_body{ body = b, moved = moved });
|
||||
}
|
||||
}
|
||||
|
||||
# Sweeps the fast bodies, bullets last, so they meet the rest where they end
|
||||
# up, and places their colliders.
|
||||
def space::sweep_fast(&mut this): void {
|
||||
var fast := move(this.fast);
|
||||
for pass in 0..2u {
|
||||
for i in 0..fast.length {
|
||||
val bullet := this.bodies[fast[i].body as u64].bullet;
|
||||
continue if bullet != (pass == 1);
|
||||
this.sweep_body(&fast[i]);
|
||||
this.place_colliders(fast[i].body);
|
||||
}
|
||||
}
|
||||
fast.clear();
|
||||
this.fast = move(fast);
|
||||
}
|
||||
|
||||
# Puts a fast body back where it first meets what it may pass through.
|
||||
def space::sweep_body(&mut this, f: &fast_body): void {
|
||||
val b := f.body;
|
||||
val bullet := this.bodies[b as u64].bullet;
|
||||
val target := this.slop;
|
||||
val tolerance := 0.25 * this.slop;
|
||||
var first: f32 = 1;
|
||||
var c := this.bodies[b as u64].colliders;
|
||||
while c != none {
|
||||
val own := &this.colliders[c as u64];
|
||||
if !own.made.sensor && !own.is_grid() {
|
||||
val start := f.moved.at(0);
|
||||
val box := own.made.shape.bounds(start).merged(own.made.shape.bounds(f.moved.at(1)));
|
||||
this.tree.query(box, def(leaf: u32, data: u64): bool {
|
||||
val other := &this.colliders[data];
|
||||
return true if other.body == b || other.made.sensor;
|
||||
return true if (other.made.layers & own.made.mask) == 0 || (own.made.layers & other.made.mask) == 0;
|
||||
val held := &this.bodies[other.body as u64];
|
||||
return true if held.kind != body_kind::static && (!bullet || held.bullet);
|
||||
return true if this.joined_apart(b, other.body);
|
||||
val still := sweep::still(held.at);
|
||||
if other.is_grid() {
|
||||
val cells := &this.grids[other.grid as u64];
|
||||
cells.cells_in(local_box(box, held.at), def(x: u32, y: u32): bool {
|
||||
val cell := cells.box_of(x, y);
|
||||
val solid := shape::box(cell.half_size, cell.center);
|
||||
val t := impact_of(&solid, &still, &own.made.shape, &f.moved, target, tolerance);
|
||||
if t > 0 && t < first {
|
||||
first = t;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return true if this.behind_one_way(data as u32, &own.made.shape, start);
|
||||
val t := impact_of(&other.made.shape, &still, &own.made.shape, &f.moved, target, tolerance);
|
||||
if t > 0 && t < first {
|
||||
first = t;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
c = this.colliders[c as u64].next;
|
||||
}
|
||||
return if first >= 1;
|
||||
val at := f.moved.at(first);
|
||||
this.bodies[b as u64].at = at;
|
||||
this.bodies[b as u64].center = at.apply(this.bodies[b as u64].local_center);
|
||||
}
|
||||
|
||||
# When a fast shape first meets what stands still: where they touch as the
|
||||
# step begins, as a corner resting on the ground does, when a small circle
|
||||
# about the fast shape's middle first meets it, so its middle at least never
|
||||
# passes through, as Box2D finds it.
|
||||
def impact_of(still_shape: &shape, still: &sweep, fast: &shape, moved: &sweep, target: f32, tolerance: f32): f32 {
|
||||
val t := time_of_impact(still_shape, still, fast, moved, target, tolerance);
|
||||
return t if t > 0;
|
||||
val core := shape::circle(0.25 * fast.least_reach(), fast.middle());
|
||||
return time_of_impact(still_shape, still, &core, moved, target, tolerance);
|
||||
}
|
||||
|
||||
# A box of the plane as one of a pose's own places, holding it however it's
|
||||
# turned.
|
||||
def local_box(box: aabb, at: pose): aabb {
|
||||
val corners: vec2[4] = [box.min, vec2{ box.max.x, box.min.y }, box.max, vec2{ box.min.x, box.max.y }];
|
||||
var low := at.unapply(corners[0]);
|
||||
var high := low;
|
||||
for k in 1..4u {
|
||||
val p := at.unapply(corners[k]);
|
||||
low = low.min(p);
|
||||
high = high.max(p);
|
||||
}
|
||||
return aabb{ low, high };
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
#! Contains `crew`: the threads a space solves a step's colors on, besides
|
||||
#! its caller's, started as a step first asks for more than one and kept until
|
||||
#! the space closes. Each job is a number of things, taken a block at a time by
|
||||
#! whichever thread is free, the caller among them, which returns once all are
|
||||
#! done. Between jobs, as a step's come one after another, the threads spin a
|
||||
#! little before sleeping, so a job begins in a microsecond rather than the
|
||||
#! tens a sleeping thread takes to wake, as Box2D's workers spin. They spin by
|
||||
#! reading what they wait on: `system::pause` is the system's wait for a signal,
|
||||
#! not the processor's hint that a thread spins.
|
||||
|
||||
import system;
|
||||
import std::containers;
|
||||
import std::thread;
|
||||
module malunal::physics2d;
|
||||
|
||||
# What the threads are given to do: a function for each range of things.
|
||||
struct crew_job {
|
||||
var run: def(*mut u8, u64, u64): void;
|
||||
var context: *mut u8;
|
||||
var count: u64;
|
||||
var block: u64;
|
||||
}
|
||||
|
||||
# What the threads share, on the heap, so it stays where it is.
|
||||
struct crew_state {
|
||||
var job: crew_job;
|
||||
var next: atomic<u64>; # The job's round, high, and the next thing to take, low.
|
||||
var done: atomic<u64>; # How many things are done.
|
||||
var round: atomic<u32>; # Counts jobs, and the threads wait on it.
|
||||
var sleeping: atomic<u32>; # How many threads sleep rather than spin.
|
||||
var stopping: atomic<u32>;
|
||||
}
|
||||
|
||||
# How many times a thread spins waiting for a job before it sleeps.
|
||||
const spins: u32 = 200000;
|
||||
|
||||
# The threads a space solves on, besides its caller's.
|
||||
struct crew : owning {
|
||||
var shared: *mut crew_state;
|
||||
var threads: vector<thread::handle<void>>;
|
||||
}
|
||||
|
||||
# Starts threads, so there are as many as asked for in all, the caller's among
|
||||
# them, where there aren't.
|
||||
def crew::start(&mut this, count: u32): void {
|
||||
if this.shared != null && this.threads.length + 1 != count as u64 {
|
||||
this.close();
|
||||
}
|
||||
return if this.shared != null || count <= 1;
|
||||
this.shared = raw_allocate_zeroed(size_of::<crew_state>()) as *mut crew_state;
|
||||
for _ in 1..count {
|
||||
var started := thread::spawn_with(work, this.shared) else (_) { break; };
|
||||
this.threads.append(move(started));
|
||||
}
|
||||
}
|
||||
|
||||
# Runs a function over ranges of a job's things, a block at a time, on this
|
||||
# thread and the crew's, and returns once all are done.
|
||||
def crew::run(&mut this, run: def(*mut u8, u64, u64): void, context: *mut u8, count: u64, block: u64): void {
|
||||
return if count == 0;
|
||||
if this.shared == null || count <= block {
|
||||
run(context, 0, count);
|
||||
return;
|
||||
}
|
||||
val s := &mut through(this.shared);
|
||||
# The next round's things first, so a thread late from the last takes none
|
||||
# of this job's by the last's function.
|
||||
val round := s.round.load(order::relaxed) + 1;
|
||||
s.next.store((round as u64) << 32, order::release);
|
||||
s.job = crew_job{ run = run, context = context, count = count, block = block };
|
||||
s.done.store(0, order::relaxed);
|
||||
s.round.store(round, order::release);
|
||||
if s.sleeping.load(order::acquire) > 0 {
|
||||
_ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF);
|
||||
}
|
||||
drain(s, round);
|
||||
while s.done.load(order::acquire) < count {
|
||||
}
|
||||
}
|
||||
|
||||
pub def crew::close(&mut this): void {
|
||||
if this.shared != null {
|
||||
val s := &mut through(this.shared);
|
||||
s.stopping.store(1, order::release);
|
||||
_ = s.round.fetch_add(1, order::release);
|
||||
_ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF);
|
||||
this.threads.close();
|
||||
raw_release(this.shared as *mut u8);
|
||||
this.shared = null;
|
||||
}
|
||||
this.threads.close();
|
||||
}
|
||||
|
||||
# What each thread does: waits for a job, spinning then sleeping, and takes
|
||||
# its things until none are left.
|
||||
def work(shared: *mut crew_state): void {
|
||||
val s := &mut through(shared);
|
||||
var seen: u32 = 0;
|
||||
while true {
|
||||
var round := s.round.load(order::acquire);
|
||||
var spun: u32 = 0;
|
||||
while round == seen {
|
||||
if spun < spins {
|
||||
spun++;
|
||||
} else {
|
||||
_ = s.sleeping.fetch_add(1, order::acq_rel);
|
||||
if s.round.load(order::acquire) == seen {
|
||||
_ = system::futex_wait(word_of(&mut s.round), seen, -1);
|
||||
}
|
||||
_ = s.sleeping.fetch_sub(1, order::acq_rel);
|
||||
}
|
||||
round = s.round.load(order::acquire);
|
||||
}
|
||||
seen = round;
|
||||
return if s.stopping.load(order::acquire) != 0;
|
||||
drain(s, round);
|
||||
}
|
||||
}
|
||||
|
||||
# Takes blocks of a round's job, running its function over each, until none
|
||||
# are left, or the round has passed.
|
||||
def drain(s: &mut crew_state, round: u32): void {
|
||||
val job := s.job;
|
||||
while true {
|
||||
val held := s.next.load(order::acquire);
|
||||
return if (held >> 32) as u32 != round;
|
||||
val at := held & 0xFFFFFFFF;
|
||||
return if at >= job.count;
|
||||
val claimed := s.next.compare_exchange_weak(held, held + job.block, order::acq_rel, order::acquire);
|
||||
continue if claimed is error(_);
|
||||
val end := at + job.block < job.count ? at + job.block : job.count;
|
||||
job.run(job.context, at, end);
|
||||
_ = s.done.fetch_add(end - at, order::acq_rel);
|
||||
}
|
||||
}
|
||||
|
||||
# The word of an atomic, which the system's futexes wait on.
|
||||
def word_of(of: &mut atomic<u32>): *mut u32 {
|
||||
return (address(of) as *mut atomic<u32>) as *mut u32;
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
#! Contains how far apart two shapes are, their nearest places found as
|
||||
#! Gilbert, Johnson, and Keerthi's GJK finds them; a shape cast along a motion,
|
||||
#! to where it first meets another; and the time of impact of two shapes each
|
||||
#! swept through a step, moving and turning, as continuous collision asks.
|
||||
#!
|
||||
#! GJK finds the place of the shapes' difference, every place of the second
|
||||
#! less every place of the first, nearest the origin, by a triangle of its
|
||||
#! corners at most, each step adding the corner furthest toward the origin and
|
||||
#! keeping only what the nearest place lies on, as Box2D's distance does. It
|
||||
#! works each shape's core, its points without their radius, then takes the
|
||||
#! radii off, so a circle's nearest place is as exact as a box's.
|
||||
#!
|
||||
#! A cast, and a time of impact, advance conservatively, as Mirtich's do: each
|
||||
#! moves the shapes as far as the gap between them, over how fast they can
|
||||
#! close it, says they can't yet meet, so neither ever passes through what it
|
||||
#! meets.
|
||||
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! How far apart two shapes are, and the places of each nearest the other.
|
||||
pub struct gap {
|
||||
#! The places of the first's surface and the second's nearest one another:
|
||||
#! one place, midway, where they meet.
|
||||
pub var on_a: vec2;
|
||||
pub var on_b: vec2;
|
||||
#! The direction from the first toward the second, of length 1, or none
|
||||
#! where they meet.
|
||||
pub var normal: vec2;
|
||||
#! How far apart their surfaces are: 0 where they meet.
|
||||
pub var distance: f32;
|
||||
}
|
||||
|
||||
#! Where a shape cast along a motion first met another: how far along the
|
||||
#! motion, as a fraction of it, the place of the other's surface it met, and
|
||||
#! which way that surface faces, toward the shape cast.
|
||||
pub struct cast_hit {
|
||||
pub var fraction: f32;
|
||||
pub var point: vec2;
|
||||
pub var normal: vec2;
|
||||
}
|
||||
|
||||
# A corner of the shapes' difference, of a point of each, and its weight in
|
||||
# the nearest place.
|
||||
struct corner {
|
||||
var on_a: vec2;
|
||||
var on_b: vec2;
|
||||
var w: vec2;
|
||||
var weight: f32;
|
||||
var ia: u32;
|
||||
var ib: u32;
|
||||
}
|
||||
|
||||
# As many as three corners, the nearest place lying among them.
|
||||
struct simplex {
|
||||
var corners: corner[3];
|
||||
var count: u32;
|
||||
}
|
||||
|
||||
# The point of a shape furthest along a direction of the plane, where a pose
|
||||
# places it.
|
||||
def support_of(s: &shape, at: &pose, direction: vec2): u32 {
|
||||
val d := at.turn.unapply(direction);
|
||||
var best: u32 = 0;
|
||||
var most := s.point(0).dot(d);
|
||||
for i in 1..s.count {
|
||||
val reach := s.point(i).dot(d);
|
||||
if reach > most {
|
||||
most = reach;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
def corner_of(a: &shape, at_a: &pose, ia: u32, b: &shape, at_b: &pose, ib: u32): corner {
|
||||
val pa := at_a.apply(a.point(ia));
|
||||
val pb := at_b.apply(b.point(ib));
|
||||
return corner{ on_a = pa, on_b = pb, w = pb - pa, weight = 1, ia = ia, ib = ib };
|
||||
}
|
||||
|
||||
# The nearest place of a segment of the difference to the origin, keeping only
|
||||
# the corner it's at where it's at one.
|
||||
def solve2(x: &mut simplex): void {
|
||||
val w1 := x.corners[0].w;
|
||||
val w2 := x.corners[1].w;
|
||||
val e12 := w2 - w1;
|
||||
val d12_2 := -w1.dot(e12);
|
||||
if d12_2 <= 0 {
|
||||
x.corners[0].weight = 1;
|
||||
x.count = 1;
|
||||
return;
|
||||
}
|
||||
val d12_1 := w2.dot(e12);
|
||||
if d12_1 <= 0 {
|
||||
x.corners[0] = x.corners[1];
|
||||
x.corners[0].weight = 1;
|
||||
x.count = 1;
|
||||
return;
|
||||
}
|
||||
val inv := 1 / (d12_1 + d12_2);
|
||||
x.corners[0].weight = d12_1 * inv;
|
||||
x.corners[1].weight = d12_2 * inv;
|
||||
x.count = 2;
|
||||
}
|
||||
|
||||
# The same of a triangle, by which of its corners, edges, or inside the
|
||||
# origin's nearest place is in, as Box2D's distance finds it.
|
||||
def solve3(x: &mut simplex): void {
|
||||
val w1 := x.corners[0].w;
|
||||
val w2 := x.corners[1].w;
|
||||
val w3 := x.corners[2].w;
|
||||
val e12 := w2 - w1;
|
||||
val d12_1 := w2.dot(e12);
|
||||
val d12_2 := -w1.dot(e12);
|
||||
val e13 := w3 - w1;
|
||||
val d13_1 := w3.dot(e13);
|
||||
val d13_2 := -w1.dot(e13);
|
||||
val e23 := w3 - w2;
|
||||
val d23_1 := w3.dot(e23);
|
||||
val d23_2 := -w2.dot(e23);
|
||||
val n123 := e12.cross(e13);
|
||||
val d123_1 := n123 * w2.cross(w3);
|
||||
val d123_2 := n123 * w3.cross(w1);
|
||||
val d123_3 := n123 * w1.cross(w2);
|
||||
if d12_2 <= 0 && d13_2 <= 0 {
|
||||
x.corners[0].weight = 1;
|
||||
x.count = 1;
|
||||
return;
|
||||
}
|
||||
if d12_1 > 0 && d12_2 > 0 && d123_3 <= 0 {
|
||||
val inv := 1 / (d12_1 + d12_2);
|
||||
x.corners[0].weight = d12_1 * inv;
|
||||
x.corners[1].weight = d12_2 * inv;
|
||||
x.count = 2;
|
||||
return;
|
||||
}
|
||||
if d13_1 > 0 && d13_2 > 0 && d123_2 <= 0 {
|
||||
val inv := 1 / (d13_1 + d13_2);
|
||||
x.corners[0].weight = d13_1 * inv;
|
||||
x.corners[1] = x.corners[2];
|
||||
x.corners[1].weight = d13_2 * inv;
|
||||
x.count = 2;
|
||||
return;
|
||||
}
|
||||
if d12_1 <= 0 && d23_2 <= 0 {
|
||||
x.corners[0] = x.corners[1];
|
||||
x.corners[0].weight = 1;
|
||||
x.count = 1;
|
||||
return;
|
||||
}
|
||||
if d13_1 <= 0 && d23_1 <= 0 {
|
||||
x.corners[0] = x.corners[2];
|
||||
x.corners[0].weight = 1;
|
||||
x.count = 1;
|
||||
return;
|
||||
}
|
||||
if d23_1 > 0 && d23_2 > 0 && d123_1 <= 0 {
|
||||
val inv := 1 / (d23_1 + d23_2);
|
||||
x.corners[0] = x.corners[2];
|
||||
x.corners[0].weight = d23_2 * inv;
|
||||
x.corners[1].weight = d23_1 * inv;
|
||||
x.count = 2;
|
||||
return;
|
||||
}
|
||||
val whole := d123_1 + d123_2 + d123_3;
|
||||
# A triangle of no area, its corners in a line: none holds the origin.
|
||||
if !(whole > 0) {
|
||||
x.corners[0].weight = 1;
|
||||
x.count = 1;
|
||||
return;
|
||||
}
|
||||
val inv := 1 / whole;
|
||||
x.corners[0].weight = d123_1 * inv;
|
||||
x.corners[1].weight = d123_2 * inv;
|
||||
x.corners[2].weight = d123_3 * inv;
|
||||
x.count = 3;
|
||||
}
|
||||
|
||||
# Which way the next corner is looked for: toward the origin from the nearest
|
||||
# corner, or across the nearest edge, on the origin's side.
|
||||
def search_direction(x: &simplex): vec2 {
|
||||
return x.corners[0].w * -1f if x.count == 1;
|
||||
val e12 := x.corners[1].w - x.corners[0].w;
|
||||
return e12.perpendicular() if e12.cross(x.corners[0].w * -1f) > 0;
|
||||
return vec2{ e12.y, -e12.x };
|
||||
}
|
||||
|
||||
#! How far apart two shapes are, each where its pose places it, and the places
|
||||
#! of each nearest the other: none apart where they meet.
|
||||
pub def gap_between(a: &shape, at_a: pose, b: &shape, at_b: pose): gap {
|
||||
var x := simplex{ count = 1 };
|
||||
x.corners[0] = corner_of(a, &at_a, 0, b, &at_b, 0);
|
||||
var saved_a: u32[3] = [0, 0, 0];
|
||||
var saved_b: u32[3] = [0, 0, 0];
|
||||
for iteration in 0..20u {
|
||||
val saved := x.count;
|
||||
for i in 0..saved {
|
||||
saved_a[i] = x.corners[i].ia;
|
||||
saved_b[i] = x.corners[i].ib;
|
||||
}
|
||||
if x.count == 2 {
|
||||
solve2(&mut x);
|
||||
} else if x.count == 3 {
|
||||
solve3(&mut x);
|
||||
}
|
||||
# Three corners hold the origin: the cores overlap.
|
||||
if x.count == 3 {
|
||||
break;
|
||||
}
|
||||
val d := search_direction(&x);
|
||||
if d.length_squared < tiny * tiny {
|
||||
break;
|
||||
}
|
||||
val ia := support_of(a, &at_a, d * -1f);
|
||||
val ib := support_of(b, &at_b, d);
|
||||
# A corner it has already found makes no progress.
|
||||
var again := false;
|
||||
for i in 0..saved {
|
||||
if saved_a[i] == ia && saved_b[i] == ib {
|
||||
again = true;
|
||||
}
|
||||
}
|
||||
if again {
|
||||
break;
|
||||
}
|
||||
x.corners[x.count] = corner_of(a, &at_a, ia, b, &at_b, ib);
|
||||
x.count++;
|
||||
}
|
||||
# The corner added last solved with the rest, where the passes ran out.
|
||||
if x.count == 2 {
|
||||
solve2(&mut x);
|
||||
} else if x.count == 3 {
|
||||
solve3(&mut x);
|
||||
}
|
||||
var on_a := vec2::zero;
|
||||
var on_b := vec2::zero;
|
||||
for i in 0..x.count {
|
||||
on_a = on_a + x.corners[i].on_a * x.corners[i].weight;
|
||||
on_b = on_b + x.corners[i].on_b * x.corners[i].weight;
|
||||
}
|
||||
if x.count == 3 {
|
||||
on_b = on_a;
|
||||
}
|
||||
val between := on_b - on_a;
|
||||
val cores := between.length;
|
||||
val reach := a.radius + b.radius;
|
||||
if cores > reach && cores > tiny {
|
||||
val normal := between * (1 / cores);
|
||||
return gap{ on_a = on_a + normal * a.radius, on_b = on_b - normal * b.radius, normal = normal, distance = cores - reach };
|
||||
}
|
||||
# They meet: midway between their surfaces along the line between their
|
||||
# cores, where they have one.
|
||||
val normal := cores > tiny ? between * (1 / cores) : vec2::zero;
|
||||
val middle := ((on_a + normal * a.radius) + (on_b - normal * b.radius)) * 0.5;
|
||||
return gap{ on_a = middle, on_b = middle, normal = normal, distance = 0 };
|
||||
}
|
||||
|
||||
#! Where a shape, `b`, cast along a motion of the plane from where its pose
|
||||
#! places it, first meets another, `a`, which stays where its pose places it:
|
||||
#! within `tolerance` of its surface, a little short of touching, so what's
|
||||
#! moved there doesn't overlap. Nothing where it doesn't meet it within the
|
||||
#! motion; a fraction of 0 where they meet as it begins, its normal back along
|
||||
#! the motion.
|
||||
pub def shape_cast(a: &shape, at_a: pose, b: &shape, at_b: pose, motion: vec2, tolerance: f32 = 0.0025): maybe<cast_hit> {
|
||||
val target := 0.5 * tolerance;
|
||||
var t: f32 = 0;
|
||||
var at := at_b;
|
||||
for iteration in 0..30u {
|
||||
val g := gap_between(a, at_a, b, at);
|
||||
if g.distance <= tolerance {
|
||||
val back := g.distance > 0 ? g.normal : motion.normalized() * -1f;
|
||||
return cast_hit{ fraction = t, point = g.on_a, normal = back };
|
||||
}
|
||||
val approach := -motion.dot(g.normal);
|
||||
return nothing{} if approach <= tiny;
|
||||
t += (g.distance - target) / approach;
|
||||
return nothing{} if t > 1;
|
||||
at = pose{ at = at_b.at + motion * t, turn = at_b.turn };
|
||||
}
|
||||
val g := gap_between(a, at_a, b, at);
|
||||
return cast_hit{ fraction = t, point = g.on_a, normal = g.normal };
|
||||
}
|
||||
|
||||
#! How a body moves through a step: its center of mass, of its own places,
|
||||
#! where that center begins and ends the step, and how it's turned as it begins
|
||||
#! and ends it, turning the shorter way between.
|
||||
pub struct sweep {
|
||||
pub var local_center: vec2;
|
||||
pub var c1: vec2;
|
||||
pub var c2: vec2;
|
||||
pub var q1 := rot::identity;
|
||||
pub var q2 := rot::identity;
|
||||
}
|
||||
|
||||
#! A sweep standing still where a pose places a body.
|
||||
pub def sweep::still(at: pose, local_center: vec2 = vec2::zero): sweep {
|
||||
val center := at.apply(local_center);
|
||||
return sweep{ local_center = local_center, c1 = center, c2 = center, q1 = at.turn, q2 = at.turn };
|
||||
}
|
||||
|
||||
#! Where it places its body a fraction of the way through the step.
|
||||
pub def sweep::at(&this, t: f32): pose {
|
||||
val turn := rot::of(angle_between(this.q2, this.q1) * t) * this.q1;
|
||||
val center := this.c1.lerp(this.c2, t);
|
||||
return pose{ at = center - turn.apply(this.local_center), turn = turn };
|
||||
}
|
||||
|
||||
# How far a shape's surface reaches from a place of its own.
|
||||
def reach_from(s: &shape, center: vec2): f32 {
|
||||
var most: f32 = 0;
|
||||
for i in 0..s.count {
|
||||
most = math::max(most, (s.point(i) - center).length);
|
||||
}
|
||||
return most + s.radius;
|
||||
}
|
||||
|
||||
#! When, as a fraction of the step, two shapes each swept through it first come
|
||||
#! within `target` of one another, to within `tolerance`, as their sweeps move
|
||||
#! and turn them: 1 where they don't. Each moves no further than they can, as
|
||||
#! fast as they close and turn, without meeting, so what's found is never past
|
||||
#! where they meet.
|
||||
pub def time_of_impact(a: &shape, sa: &sweep, b: &shape, sb: &sweep, target: f32, tolerance: f32): f32 {
|
||||
val turn_a := math::abs(angle_between(sa.q2, sa.q1)) * reach_from(a, sa.local_center);
|
||||
val turn_b := math::abs(angle_between(sb.q2, sb.q1)) * reach_from(b, sb.local_center);
|
||||
val moved := (sb.c2 - sb.c1) - (sa.c2 - sa.c1);
|
||||
var t: f32 = 0;
|
||||
for iteration in 0..50u {
|
||||
val g := gap_between(a, sa.at(t), b, sb.at(t));
|
||||
return t if g.distance <= target + tolerance;
|
||||
val closing := -moved.dot(g.normal) + turn_a + turn_b;
|
||||
return 1 if closing <= tiny;
|
||||
t += (g.distance - target) / closing;
|
||||
return 1 if t >= 1;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
# How far a shape reaches at least from its middle: a circle's or a capsule's
|
||||
# radius, or the nearest of a polygon's edges, as a body may move without
|
||||
# passing through what's in its way.
|
||||
def shape::least_reach(&this): f32 {
|
||||
return this.radius if this.kind != shape_kind::polygon;
|
||||
var middle := vec2::zero;
|
||||
for i in 0..this.count {
|
||||
middle = middle + this.point(i);
|
||||
}
|
||||
middle = middle * (1 / this.count as f32);
|
||||
var least := 1e30f;
|
||||
for i in 0..this.count {
|
||||
least = math::min(least, this.normal(i).dot(this.point(i) - middle));
|
||||
}
|
||||
return least + this.radius;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
#! Contains how a step solves the joints that slide and drive, as Box2D's soft
|
||||
#! step solves them: a prismatic joint holds its bodies to its axis and turning
|
||||
#! together, sliding between its limits, by its motor, or springily; a wheel
|
||||
#! holds them to its axis alone, riding it on its spring, its motor turning
|
||||
#! the wheel; a motor joint drives `b` toward a place and an angle of `a`'s
|
||||
#! own; and a mouse joint pulls a place of `b` toward a target.
|
||||
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
# A sliding joint's axis and the levers about it, as the bodies have moved and
|
||||
# turned since the step began.
|
||||
struct sliding {
|
||||
var axis: vec2;
|
||||
var perp: vec2;
|
||||
var d: vec2; # From `a`'s anchor to `b`'s.
|
||||
var ra: vec2;
|
||||
var rb: vec2;
|
||||
var a1: f32; # How each turns as the joint slides along its axis,
|
||||
var a2: f32;
|
||||
var s1: f32; # and across it.
|
||||
var s2: f32;
|
||||
}
|
||||
|
||||
def sliding_of(r: &joint_record, sa: &body_state, sb: &body_state): sliding {
|
||||
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 axis := sa.dq.apply(r.axis);
|
||||
val perp := axis.perpendicular();
|
||||
return sliding{
|
||||
axis = axis, perp = perp, d = d, ra = ra, rb = rb,
|
||||
a1 = (d + ra).cross(axis), a2 = rb.cross(axis), s1 = (d + ra).cross(perp), s2 = rb.cross(perp),
|
||||
};
|
||||
}
|
||||
|
||||
# Pushes the two apart by an impulse along a sliding joint and turns them by
|
||||
# what it turns each.
|
||||
def slide_apart(r: &joint_record, sa: &mut body_state, sb: &mut body_state, p: vec2, turn_a: f32, turn_b: f32): void {
|
||||
sa.v = sa.v - p * r.ma;
|
||||
sa.w -= r.ia * turn_a;
|
||||
sb.v = sb.v + p * r.mb;
|
||||
sb.w += r.ib * turn_b;
|
||||
}
|
||||
|
||||
def warm_sliding(r: &joint_record, sa: &mut body_state, sb: &mut body_state): void {
|
||||
val g := sliding_of(r, sa, sb);
|
||||
if r.made.kind == joint_kind::prismatic {
|
||||
val axial := r.spring_impulse + r.motor_impulse + r.lower_impulse - r.upper_impulse;
|
||||
val p := g.axis * axial + g.perp * r.linear.x;
|
||||
slide_apart(r, sa, sb, p, axial * g.a1 + r.linear.x * g.s1 + r.linear.y, axial * g.a2 + r.linear.x * g.s2 + r.linear.y);
|
||||
} else {
|
||||
val axial := r.spring_impulse + r.lower_impulse - r.upper_impulse;
|
||||
val p := g.axis * axial + g.perp * r.axial;
|
||||
slide_apart(r, sa, sb, p, axial * g.a1 + r.axial * g.s1 + r.motor_impulse, axial * g.a2 + r.axial * g.s2 + r.motor_impulse);
|
||||
}
|
||||
}
|
||||
|
||||
# How fast a sliding joint slides along its axis.
|
||||
def sliding_speed(g: &sliding, sa: &body_state, sb: &body_state): f32 {
|
||||
return g.axis.dot(sb.v - sa.v) + g.a2 * sb.w - g.a1 * sa.w;
|
||||
}
|
||||
|
||||
def solve_sliding(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 g := sliding_of(r, sa, sb);
|
||||
val translation := g.axis.dot(g.d);
|
||||
if made.motor {
|
||||
val most := h * made.max_motor_force;
|
||||
val held := r.motor_impulse;
|
||||
if made.kind == joint_kind::prismatic {
|
||||
r.motor_impulse = math::clamp(held + r.axial_mass * (made.motor_speed - sliding_speed(&g, sa, sb)), -most, most);
|
||||
val impulse := r.motor_impulse - held;
|
||||
slide_apart(r, sa, sb, g.axis * impulse, impulse * g.a1, impulse * g.a2);
|
||||
} else {
|
||||
# A wheel's motor turns it.
|
||||
r.motor_impulse = math::clamp(held - r.motor_mass * (sb.w - sa.w - made.motor_speed), -most, most);
|
||||
turn_apart(r, sa, sb, r.motor_impulse - held);
|
||||
}
|
||||
}
|
||||
if made.spring && made.hertz > 0 {
|
||||
val bias := r.spring_soft.bias_rate * translation;
|
||||
val impulse := -r.spring_soft.mass_scale * r.axial_mass * (sliding_speed(&g, sa, sb) + bias) - r.spring_soft.impulse_scale * r.spring_impulse;
|
||||
r.spring_impulse += impulse;
|
||||
slide_apart(r, sa, sb, g.axis * impulse, impulse * g.a1, impulse * g.a2);
|
||||
}
|
||||
if made.limit {
|
||||
val lower := limit_impulse(translation - made.lower, sliding_speed(&g, sa, sb), r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias);
|
||||
r.lower_impulse += lower;
|
||||
slide_apart(r, sa, sb, g.axis * lower, lower * g.a1, lower * g.a2);
|
||||
val upper := limit_impulse(made.upper - translation, -sliding_speed(&g, sa, sb), r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias);
|
||||
r.upper_impulse += upper;
|
||||
slide_apart(r, sa, sb, g.axis * -upper, -upper * g.a1, -upper * g.a2);
|
||||
}
|
||||
var bias_scale: f32 = 0;
|
||||
var mass_scale: f32 = 1;
|
||||
var impulse_scale: f32 = 0;
|
||||
if use_bias {
|
||||
bias_scale = soft.bias_rate;
|
||||
mass_scale = soft.mass_scale;
|
||||
impulse_scale = soft.impulse_scale;
|
||||
}
|
||||
val across := g.perp.dot(sb.v - sa.v) + g.s2 * sb.w - g.s1 * sa.w;
|
||||
val k11 := r.ma + r.mb + r.ia * g.s1 * g.s1 + r.ib * g.s2 * g.s2;
|
||||
if made.kind == joint_kind::wheel {
|
||||
# Held to its axis alone, the wheel turning as it likes.
|
||||
val held := r.axial;
|
||||
val impulse := k11 > 0 ? -mass_scale * (across + bias_scale * g.perp.dot(g.d)) / k11 - impulse_scale * held : 0f;
|
||||
r.axial = held + impulse;
|
||||
slide_apart(r, sa, sb, g.perp * impulse, impulse * g.s1, impulse * g.s2);
|
||||
return;
|
||||
}
|
||||
# Held to its axis and turning together, both at once.
|
||||
val k12 := r.ia * g.s1 + r.ib * g.s2;
|
||||
var k22 := r.ia + r.ib;
|
||||
if k22 == 0 {
|
||||
k22 = 1;
|
||||
}
|
||||
val turned_by := unwound(r.delta_angle + angle_between(sb.dq, sa.dq));
|
||||
val c := vec2{ across + bias_scale * g.perp.dot(g.d), sb.w - sa.w + bias_scale * turned_by };
|
||||
val b := solved(k11, k12, k12, k22, c);
|
||||
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;
|
||||
slide_apart(r, sa, sb, g.perp * impulse.x, impulse.x * g.s1 + impulse.y, impulse.x * g.s2 + impulse.y);
|
||||
}
|
||||
|
||||
# A motor joint: its turn driven toward its angle, then its place, each by no
|
||||
# more than its share of its torque or force this substep.
|
||||
def solve_motor(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, h: f32): void {
|
||||
val made := &r.made;
|
||||
val inv_h := 1 / h;
|
||||
val turned_by := unwound(r.delta_angle + angle_between(sb.dq, sa.dq));
|
||||
val most_turn := h * made.max_motor_torque;
|
||||
val turn_held := r.axial;
|
||||
r.axial = math::clamp(turn_held - r.motor_mass * (sb.w - sa.w + inv_h * made.correction * turned_by), -most_turn, most_turn);
|
||||
turn_apart(r, sa, sb, r.axial - turn_held);
|
||||
val ra := sa.dq.apply(r.ra);
|
||||
val rb := sb.dq.apply(r.rb);
|
||||
val off := (sb.dp - sa.dp) + (rb - ra) + r.delta_center;
|
||||
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 + off * (inv_h * made.correction));
|
||||
push_capped(r, sa, sb, ra, rb, b * -1f, h * made.max_motor_force);
|
||||
}
|
||||
|
||||
# A mouse joint: a place of `b` pulled softly toward its target.
|
||||
def solve_mouse(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, h: f32): void {
|
||||
val ra := sa.dq.apply(r.ra);
|
||||
val rb := sb.dq.apply(r.rb);
|
||||
val off := (sb.dp - sa.dp) + (rb - ra) + r.delta_center;
|
||||
val cdot := sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra);
|
||||
val soft := &r.linear_soft;
|
||||
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 + off * soft.bias_rate);
|
||||
val impulse := b * -soft.mass_scale - r.linear * soft.impulse_scale;
|
||||
push_capped(r, sa, sb, ra, rb, impulse, h * r.made.max_motor_force);
|
||||
}
|
||||
|
||||
# Adds an impulse to a joint's at its anchors, its sum no longer than `most`.
|
||||
def push_capped(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ra: vec2, rb: vec2, impulse: vec2, most: f32): void {
|
||||
val held := r.linear;
|
||||
var sum := held + impulse;
|
||||
val length := sum.length;
|
||||
if length > most {
|
||||
sum = sum * (most / length);
|
||||
}
|
||||
r.linear = sum;
|
||||
push_apart(r, sa, sb, ra, rb, sum - held);
|
||||
}
|
||||
@@ -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,289 @@
|
||||
#! 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;
|
||||
}
|
||||
if r.made.kind == joint_kind::prismatic || r.made.kind == joint_kind::wheel {
|
||||
r.axis = a.at.turn.apply(r.made.axis.normalized());
|
||||
val d := r.delta_center + r.rb - r.ra;
|
||||
val a1 := (d + r.ra).cross(r.axis);
|
||||
val a2 := r.rb.cross(r.axis);
|
||||
val ks := r.ma + r.mb + r.ia * a1 * a1 + r.ib * a2 * a2;
|
||||
r.axial_mass = ks > 0 ? 1 / ks : 0f;
|
||||
}
|
||||
val turning := r.ia + r.ib;
|
||||
r.motor_mass = turning > 0 ? 1 / turning : 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::prismatic || r.made.kind == joint_kind::wheel {
|
||||
warm_sliding(r, &mut sa, &mut sb);
|
||||
} else if r.made.kind == joint_kind::motor || r.made.kind == joint_kind::mouse {
|
||||
p = r.linear;
|
||||
turn = r.axial;
|
||||
} else 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::prismatic || r.made.kind == joint_kind::wheel {
|
||||
solve_sliding(&mut r, &mut sa, &mut sb, &s.joint_soft, h, use_bias);
|
||||
} else if r.made.kind == joint_kind::motor {
|
||||
solve_motor(&mut r, &mut sa, &mut sb, h);
|
||||
} else if r.made.kind == joint_kind::mouse {
|
||||
solve_mouse(&mut r, &mut sa, &mut sb, h);
|
||||
} 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,435 @@
|
||||
#! 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,
|
||||
#! The two sliding along an axis, turning together, as a piston or a drawer.
|
||||
prismatic,
|
||||
#! The two along an axis, springily, turning as they like, as a car's wheel
|
||||
#! on its suspension.
|
||||
wheel,
|
||||
#! `b` driven toward a place and an angle of `a`'s own, by no more than so
|
||||
#! much force and torque, as a character steered or a door shut.
|
||||
motor,
|
||||
#! `b` pulled by a spring toward a target, as a mouse drags it.
|
||||
mouse,
|
||||
}
|
||||
|
||||
#! 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;
|
||||
#! Where it holds each, of the body's own places: of a motor joint, where it
|
||||
#! drives `b`'s origin to, of `a`'s, and of a mouse joint, its target.
|
||||
pub var anchor_a: vec2;
|
||||
pub var anchor_b: vec2;
|
||||
#! Of a prismatic or wheel joint, the axis it slides along, of `a`'s own
|
||||
#! directions.
|
||||
pub var axis := vec2{ 1, 0 };
|
||||
#! Whether the two bodies still meet where their colliders do.
|
||||
pub var collide: bool;
|
||||
#! Of a revolute, prismatic, or motor joint or a weld, how far `b` is
|
||||
#! turned from `a`, in radians, where it rests, or is driven to.
|
||||
pub var reference_angle: f32;
|
||||
#! Whether it's limited: a revolute joint to turning from `lower` to
|
||||
#! `upper` radians from its reference, a distance joint to lengths between
|
||||
#! them, and a prismatic or wheel joint to sliding between them along its
|
||||
#! axis, from where its anchors meet.
|
||||
pub var limit: bool;
|
||||
pub var lower: f32;
|
||||
pub var upper: f32;
|
||||
#! A motor turning a revolute or wheel joint at a speed, in radians a
|
||||
#! second, or lengthening a distance joint or sliding a prismatic one, in
|
||||
#! lengths a second, with no more than so much torque or force. Of a motor
|
||||
#! or mouse joint, the most force it drives `b` with.
|
||||
pub var motor: bool;
|
||||
pub var motor_speed: f32;
|
||||
pub var max_motor_force: f32;
|
||||
#! Of a motor joint, the most torque it turns `b` with, and how much of
|
||||
#! what's left to drive it undoes each step.
|
||||
pub var max_motor_torque: f32;
|
||||
pub var correction: f32 = 0.3;
|
||||
#! A spring toward a revolute joint's reference angle, a distance joint's
|
||||
#! length, or where a prismatic or wheel joint's anchors meet, of so many
|
||||
#! cycles a second, damped so: 1 doesn't spring back. Of a weld, how stiff it
|
||||
#! holds its place, 0 rigid, and of a mouse joint, how stiff it pulls.
|
||||
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 axis: vec2; # Of a prismatic or wheel joint, as `a` was turned as the step began.
|
||||
var axial_mass: f32;
|
||||
var motor_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),
|
||||
});
|
||||
}
|
||||
|
||||
#! Lets two bodies slide along an axis of the plane through a place, turning
|
||||
#! together, as a piston: a prismatic joint, its limits and motor its own to
|
||||
#! set.
|
||||
pub def space::slide(&mut this, a: body_id, b: body_id, at: vec2, axis: 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::prismatic, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
|
||||
axis = pa.turn.unapply(axis.normalized()), reference_angle = angle_between(pb.turn, pa.turn),
|
||||
});
|
||||
}
|
||||
|
||||
#! Holds a wheel, `b`, to a body, `a`, at a place of the plane, along an axis
|
||||
#! it rides on springily, as a car's suspension: a spring of so many cycles a
|
||||
#! second, damped so, and a motor to turn it its own to set.
|
||||
pub def space::wheel(&mut this, a: body_id, b: body_id, at: vec2, axis: vec2, hertz: f32 = 4, damping: f32 = 0.7): joint_id {
|
||||
return joint_id{} if !this.has(a) || !this.has(b);
|
||||
val pa := this.pose_of(a);
|
||||
return this.join(joint{
|
||||
kind = joint_kind::wheel, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = this.pose_of(b).unapply(at),
|
||||
axis = pa.turn.unapply(axis.normalized()), spring = true, hertz = hertz, damping = damping,
|
||||
});
|
||||
}
|
||||
|
||||
#! Drives `b` to stay where it is of `a`, and turned as it is, by no more than
|
||||
#! so much force and torque, as `space::drive_to` moves where: a motor joint.
|
||||
pub def space::drive(&mut this, a: body_id, b: body_id, max_force: f32, max_torque: f32): joint_id {
|
||||
return joint_id{} if !this.has(a) || !this.has(b);
|
||||
val pa := this.pose_of(a);
|
||||
val pb := this.pose_of(b);
|
||||
return this.join(joint{
|
||||
kind = joint_kind::motor, a = a, b = b, anchor_a = pa.unapply(pb.at), reference_angle = angle_between(pb.turn, pa.turn),
|
||||
max_motor_force = max_force, max_motor_torque = max_torque, collide = true,
|
||||
});
|
||||
}
|
||||
|
||||
#! Grabs a body at a place of the plane, pulling that place of it toward a
|
||||
#! target by a spring of so many cycles a second, damped so, with no more than
|
||||
#! so much force, as a mouse drags it: a mouse joint, held by `ground`, a body
|
||||
#! standing still, its target moved by `space::drive_to`.
|
||||
pub def space::grab(&mut this, ground: body_id, b: body_id, at: vec2, max_force: f32, hertz: f32 = 5, damping: f32 = 0.7): joint_id {
|
||||
return joint_id{} if !this.has(ground) || !this.has(b);
|
||||
return this.join(joint{
|
||||
kind = joint_kind::mouse, a = ground, b = b, anchor_a = this.pose_of(ground).unapply(at), anchor_b = this.pose_of(b).unapply(at),
|
||||
max_motor_force = max_force, spring = true, hertz = hertz, damping = damping, collide = true,
|
||||
});
|
||||
}
|
||||
|
||||
#! Moves where a motor joint drives its body, a place of the plane, turned by an
|
||||
#! angle from `a`, or a mouse joint's target, waking its bodies.
|
||||
pub def space::drive_to(&mut this, id: joint_id, at: vec2, angle: f32 = 0): void {
|
||||
return if !this.has(id);
|
||||
val j := id.index as u64;
|
||||
val a := this.joints[j].body_a;
|
||||
this.joints[j].made.anchor_a = this.bodies[a as u64].at.unapply(at);
|
||||
if this.joints[j].made.kind == joint_kind::motor {
|
||||
this.joints[j].made.reference_angle = angle;
|
||||
}
|
||||
this.wake_body(a);
|
||||
this.wake_body(this.joints[j].body_b);
|
||||
}
|
||||
|
||||
#! How far a prismatic or wheel joint has slid along its axis, from where its
|
||||
#! anchors meet.
|
||||
pub def space::translation_of(&this, id: joint_id): f32 {
|
||||
return 0 if !this.has(id);
|
||||
val j := &this.joints[id.index as u64];
|
||||
val pa := this.bodies[j.body_a as u64].at;
|
||||
val pb := this.bodies[j.body_b as u64].at;
|
||||
return (pb.apply(j.made.anchor_b) - pa.apply(j.made.anchor_a)).dot(pa.turn.apply(j.made.axis.normalized()));
|
||||
}
|
||||
|
||||
#! 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. What it no longer asks pushes no more: a motor,
|
||||
#! limits, or a spring turned off.
|
||||
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;
|
||||
if !made.motor {
|
||||
this.joints[j].motor_impulse = 0;
|
||||
}
|
||||
if !made.limit {
|
||||
this.joints[j].lower_impulse = 0;
|
||||
this.joints[j].upper_impulse = 0;
|
||||
}
|
||||
if !made.spring {
|
||||
this.joints[j].spring_impulse = 0;
|
||||
}
|
||||
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) };
|
||||
}
|
||||
|
||||
#! Visits each joint, as `visit(joint, at_a, at_b)`, where it holds each of its
|
||||
#! bodies, of space's places, until it gives false, as gizmos draw them.
|
||||
pub def space::each_joint<F>(&this, visit: F): void where F: invokable<def(joint_id, vec2, vec2): bool> {
|
||||
for j in 0..this.joints.length {
|
||||
val r := &this.joints[j];
|
||||
continue if !r.alive;
|
||||
val at_a := this.bodies[r.body_a as u64].at.apply(r.made.anchor_a);
|
||||
val at_b := this.bodies[r.body_b as u64].at.apply(r.made.anchor_b);
|
||||
return if !visit(joint_id{ index = j as u32, generation = r.generation }, at_a, at_b);
|
||||
}
|
||||
}
|
||||
@@ -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,74 @@
|
||||
#! 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, a grid, or a
|
||||
#! chain's segments, 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, on as many threads as it's given, swept through each step where
|
||||
#! it moves fast enough to pass through what's thin, and sleeping where it and
|
||||
#! all it rests on are still. A space answers which colliders a shape overlaps
|
||||
#! and where a cast first meets one, and walks `character`s through it.
|
||||
#!
|
||||
#! 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,115 @@
|
||||
#! Contains what a space is asked of the shapes in it: which colliders a shape
|
||||
#! overlaps, and where a shape cast along a motion first meets one, as a
|
||||
#! character's feet and a thrown stone ask.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::physics2d;
|
||||
|
||||
#! Where a shape cast through a space first met one of its colliders: which,
|
||||
#! of which body, how far along the motion, as a fraction of it, where on what
|
||||
#! it met, and which way that faces, toward the shape cast.
|
||||
pub struct space_cast {
|
||||
pub var collider: collider_id;
|
||||
pub var body: body_id;
|
||||
pub var fraction: f32;
|
||||
pub var point: vec2;
|
||||
pub var normal: vec2;
|
||||
}
|
||||
|
||||
#! What a query of a space passes over: colliders on no layer of its `mask`;
|
||||
#! sensors, unless `sensors`; and those whose data is `ignore`, where it isn't
|
||||
#! 0, as the asker's own, a body and its colliders given an entity's bits.
|
||||
pub struct query_filter {
|
||||
pub var mask: u32 = 0xFFFFFFFF;
|
||||
pub var sensors := false;
|
||||
pub var ignore: u64 = 0;
|
||||
}
|
||||
|
||||
# Whether a query of a filter asks of a collider.
|
||||
def space::passes(&this, c: u32, filter: &query_filter): bool {
|
||||
val held := &this.colliders[c as u64].made;
|
||||
return (held.layers & filter.mask) != 0 && (!held.sensor || filter.sensors) && (filter.ignore == 0 || held.data != filter.ignore);
|
||||
}
|
||||
|
||||
def space::named(&this, c: u32): collider_id {
|
||||
return collider_id{ index = c, generation = this.colliders[c as u64].generation };
|
||||
}
|
||||
|
||||
def space::body_named(&this, b: u32): body_id {
|
||||
return body_id{ index = b, generation = this.bodies[b as u64].generation };
|
||||
}
|
||||
|
||||
#! Visits each collider on a layer of a mask that a shape overlaps, where a
|
||||
#! pose places it, sensors passed over, as `visit(collider, body)`, until it
|
||||
#! gives false.
|
||||
pub def space::overlap<F>(&this, s: &shape, at: pose, mask: u32, visit: F): void where F: invokable<def(collider_id, body_id): bool> {
|
||||
this.overlap(s, at, query_filter{ mask = mask }, visit);
|
||||
}
|
||||
|
||||
#! Visits each collider a shape overlaps, where a pose places it, that a
|
||||
#! filter asks of, as `visit(collider, body)`, until it gives false.
|
||||
pub def space::overlap<F>(&this, s: &shape, at: pose, filter: query_filter, visit: F): void where F: invokable<def(collider_id, body_id): bool> {
|
||||
this.tree.query(s.bounds(at), def(leaf: u32, data: u64): bool {
|
||||
val c := data as u32;
|
||||
return true if !this.passes(c, &filter);
|
||||
val held := &this.colliders[data];
|
||||
val placed := this.bodies[held.body as u64].at;
|
||||
var met := false;
|
||||
if held.is_grid() {
|
||||
met = this.grids[held.grid as u64].overlaps(placed, s, at);
|
||||
} else {
|
||||
met = overlaps(&held.made.shape, placed, s, at);
|
||||
}
|
||||
return true if !met;
|
||||
return visit(this.named(c), this.body_named(held.body));
|
||||
});
|
||||
}
|
||||
|
||||
#! Where a shape, cast along a motion of the plane from where a pose places
|
||||
#! it, first meets a collider on a layer of a mask, sensors passed over, and
|
||||
#! chains' segments and one-way colliders it begins behind: within a quarter of
|
||||
#! the slop of what it meets, a little short of touching. A fraction of 0 where
|
||||
#! it overlaps something as it begins. Colliders of `except`, a body of its
|
||||
#! own, as a character's, are passed over.
|
||||
pub def space::shape_cast(&this, s: &shape, at: pose, motion: vec2, mask: u32 = 0xFFFFFFFF, except: body_id = body_id{}): maybe<space_cast> {
|
||||
return this.shape_cast(s, at, motion, query_filter{ mask = mask }, except);
|
||||
}
|
||||
|
||||
#! Where a shape, cast along a motion as `shape_cast` casts it, first meets a
|
||||
#! collider a filter asks of.
|
||||
pub def space::shape_cast(&this, s: &shape, at: pose, motion: vec2, filter: query_filter, except: body_id = body_id{}): maybe<space_cast> {
|
||||
var best: maybe<space_cast> = nothing{};
|
||||
var first: f32 = 2;
|
||||
val tolerance := 0.25 * this.slop;
|
||||
val moved := pose{ at = at.at + motion, turn = at.turn };
|
||||
val box := s.bounds(at).merged(s.bounds(moved));
|
||||
this.tree.query(box, def(leaf: u32, data: u64): bool {
|
||||
val c := data as u32;
|
||||
return true if !this.passes(c, &filter) || this.behind_one_way(c, s, at) || this.colliders[data].body == except.index;
|
||||
val held := &this.colliders[data];
|
||||
val placed := this.bodies[held.body as u64].at;
|
||||
if held.is_grid() {
|
||||
val cells := &this.grids[held.grid as u64];
|
||||
cells.cells_in(local_box(box, placed), def(x: u32, y: u32): bool {
|
||||
val cell := cells.box_of(x, y);
|
||||
val solid := shape::box(cell.half_size, cell.center);
|
||||
val hit := shape_cast(&solid, placed, s, at, motion, tolerance) else { return true; };
|
||||
if hit.fraction < first {
|
||||
first = hit.fraction;
|
||||
best = space_cast{ collider = this.named(c), body = this.body_named(held.body), fraction = hit.fraction, point = hit.point, normal = hit.normal };
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
val hit := shape_cast(&held.made.shape, placed, s, at, motion, tolerance) else { return true; };
|
||||
if hit.fraction < first {
|
||||
first = hit.fraction;
|
||||
best = space_cast{ collider = this.named(c), body = this.body_named(held.body), fraction = hit.fraction, point = hit.point, normal = hit.normal };
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return best;
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
#! 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, or a segment
|
||||
#! of a chain.
|
||||
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.
|
||||
var _chained: u8; # Of a chain's segment: 1, and 2 where it has a segment before it, 4 where after, at points 2 and 3.
|
||||
}
|
||||
|
||||
#! 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 segment of a chain, from `a` to `b`, between the places of the segments
|
||||
#! before and after it, as `space::attach_chain` makes them: met only on the
|
||||
#! side its normal faces, to the right going from `a` to `b`, as a polygon's
|
||||
#! counterclockwise edges face out, and passed over at its ends where they join
|
||||
#! the chain's segments beside them flat or hollow, so a body slides along a
|
||||
#! chain as along one surface. Where `before` or `after` is nothing, its end
|
||||
#! is the chain's own, met as a segment's is.
|
||||
pub def shape::chain_segment(a: vec2, b: vec2, before: maybe<vec2> = nothing{}, after: maybe<vec2> = nothing{}): shape {
|
||||
var made := shape::capsule(a, b, 0);
|
||||
return made if made._count != 2;
|
||||
made._chained = 1;
|
||||
if before is some(p) {
|
||||
made._points[2] = p;
|
||||
made._chained = made._chained | 2;
|
||||
}
|
||||
if after is some(p) {
|
||||
made._points[3] = p;
|
||||
made._chained = made._chained | 4;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether it's a segment of a chain, met only on the side its normal faces.
|
||||
pub val shape::is_one_sided: bool {
|
||||
get => this._chained != 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,517 @@
|
||||
#! 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 impact: f32; # What stopped it meeting fast, as the step began.
|
||||
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);
|
||||
stop_impacts(&mut s, dt, 2 * this.push_speed);
|
||||
color_contacts(&mut s);
|
||||
val max_spin := most_turn * inv_h;
|
||||
this.crew.start(this.threads);
|
||||
for i in 0..n {
|
||||
integrate_velocities(&mut s, this.max_speed, max_spin);
|
||||
this.warm_joints(&mut s);
|
||||
this.wide_stage(&mut s, true, inv_h, this.push_speed, true);
|
||||
warm_contacts(&mut s);
|
||||
this.solve_joints(&mut s, h, true);
|
||||
this.wide_stage(&mut s, false, inv_h, this.push_speed, true);
|
||||
solve_contacts(&mut s, inv_h, this.push_speed, true);
|
||||
integrate_positions(&mut s, h);
|
||||
this.solve_joints(&mut s, h, false);
|
||||
this.wide_stage(&mut s, false, inv_h, this.push_speed, false);
|
||||
solve_contacts(&mut s, inv_h, this.push_speed, false);
|
||||
}
|
||||
unpack_contacts(&mut s);
|
||||
bounce(&mut s, this.restitution_threshold);
|
||||
this.keep_impulses(&s);
|
||||
this.finish(&s, dt);
|
||||
this.solver = move(s);
|
||||
}
|
||||
|
||||
# Gives each moving body a state, 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) * 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 || c.passing;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
# Stops what meets faster than a threshold before the substeps begin, as far
|
||||
# as closes its gap through the step, over a few passes, so a crate dropped
|
||||
# flat lands flat: solved within the substeps, the impulse that stops it would
|
||||
# be given again as each begins, and taken back, unevenly between its points,
|
||||
# throwing it. What stops it is kept apart from the impulses the substeps
|
||||
# begin with, but for bouncing.
|
||||
def stop_impacts(s: &mut solver_scratch, dt: f32, threshold: f32): void {
|
||||
for pass in 0..4u {
|
||||
for i in 0..s.constraints.length {
|
||||
val c := &mut s.constraints[i];
|
||||
var fast := false;
|
||||
for j in 0..c.count {
|
||||
if c.points[j].relative_velocity < -threshold {
|
||||
fast = true;
|
||||
}
|
||||
}
|
||||
continue if !fast;
|
||||
var va := s.states[c.a as u64].v;
|
||||
var wa := s.states[c.a as u64].w;
|
||||
var vb := s.states[c.b as u64].v;
|
||||
var wb := s.states[c.b as u64].w;
|
||||
val n := c.normal;
|
||||
for j in 0..c.count {
|
||||
val cp := &mut c.points[j];
|
||||
val ra := cp.anchor_a;
|
||||
val rb := cp.anchor_b;
|
||||
val gap := cp.base_separation + (rb - ra).dot(n);
|
||||
val least := gap > 0 ? -gap / dt : 0f;
|
||||
val vn := (vb + spun(wb, rb) - va - spun(wa, ra)).dot(n);
|
||||
val sum := math::max(cp.impact - cp.normal_mass * (vn - least), 0f);
|
||||
val impulse := sum - cp.impact;
|
||||
cp.impact = sum;
|
||||
cp.max_impulse = math::max(cp.max_impulse, sum);
|
||||
val p := n * impulse;
|
||||
va = va - p * c.ma;
|
||||
wa -= 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 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 began := this.bodies[b].center;
|
||||
val turned_from := this.bodies[b].at.turn;
|
||||
val center := began + st.dp;
|
||||
val turn := normalized(st.dq * turned_from);
|
||||
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;
|
||||
}
|
||||
val count := this.fast.length;
|
||||
this.note_fast(b as u32, sweep{ local_center = this.bodies[b].local_center, c1 = began, c2 = center, q1 = turned_from, q2 = turn });
|
||||
if this.fast.length == count {
|
||||
this.place_colliders(b as u32);
|
||||
}
|
||||
}
|
||||
this.sweep_fast();
|
||||
}
|
||||
|
||||
# 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,563 @@
|
||||
#! 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;
|
||||
#! How fast colliders must begin touching, in lengths a second, to be told
|
||||
#! of as a hit.
|
||||
pub var hit_speed: f32 = 1;
|
||||
#! The fastest a body moves, in lengths a second.
|
||||
pub var max_speed: f32 = 400;
|
||||
#! Whether bodies at rest sleep.
|
||||
pub var sleeping: bool = true;
|
||||
#! Whether dynamic bodies moving fast are swept against what stands still,
|
||||
#! so they never pass through what's thin.
|
||||
pub var continuous: bool = true;
|
||||
#! How many threads each step is solved on, its caller's among them: each
|
||||
#! color of contacts split between them, so a step gives the same on any
|
||||
#! number. 1 solves on the caller's alone.
|
||||
pub var threads: u32 = 1;
|
||||
var crew: crew;
|
||||
var found: vector<manifold>; # Each pair's, found on the crew.
|
||||
var unit: f32 = 1;
|
||||
var fast: vector<fast_body>;
|
||||
var bodies: vector<body_record>;
|
||||
var colliders: vector<collider_record>;
|
||||
var 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 struck: vector<hit_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, hit_speed = unit, max_speed = 400 * unit,
|
||||
tree = aabb_tree::new(0.1 * unit), pair_keys = dict::<u64, u32>::new(),
|
||||
};
|
||||
}
|
||||
|
||||
# How near two surfaces are taken as touching: what contacts let them overlap
|
||||
# by, and what they meet at before touching.
|
||||
val space::slop: f32 {
|
||||
get => 0.005 * this.unit;
|
||||
}
|
||||
|
||||
val space::speculative: f32 {
|
||||
get => 4 * this.slop;
|
||||
}
|
||||
|
||||
#! How many bodies it holds.
|
||||
pub val space::body_count: u64 {
|
||||
get => this.bodies.length - this.free_bodies.length;
|
||||
}
|
||||
|
||||
#! How many contacts it holds: pairs of shapes near enough to meet.
|
||||
pub val space::contact_count: u64 {
|
||||
get => this.contacts.length - this.free_contacts.length;
|
||||
}
|
||||
|
||||
#! The contacts that began and ended touching in the last step.
|
||||
pub def space::events(&this): span<contact_event> {
|
||||
return this.noted.span;
|
||||
}
|
||||
|
||||
#! Adds a body, of no colliders yet.
|
||||
pub def space::add(&mut this, made: body): body_id {
|
||||
var index: u32 = 0;
|
||||
if this.free_bodies.length > 0 {
|
||||
index = this.free_bodies[this.free_bodies.length - 1];
|
||||
this.free_bodies.truncate();
|
||||
} else {
|
||||
index = this.bodies.length as u32;
|
||||
this.bodies.append(body_record{});
|
||||
}
|
||||
val generation := this.bodies[index as u64].generation + 1;
|
||||
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,
|
||||
gravity = made.gravity, fixed_rotation = made.fixed_rotation, can_sleep = made.can_sleep, bullet = made.bullet, data = made.data,
|
||||
};
|
||||
this.find_mass(index);
|
||||
return body_id{ index = index, generation = generation };
|
||||
}
|
||||
|
||||
#! Whether a body is of it still.
|
||||
pub def space::has(&this, id: body_id): bool {
|
||||
return id.index < this.bodies.length as u32 && this.bodies[id.index as u64].alive && this.bodies[id.index as u64].generation == id.generation;
|
||||
}
|
||||
|
||||
#! Removes a body, its colliders, the contacts they're of, and the joints it's
|
||||
#! of, waking what it touched.
|
||||
pub def space::remove(&mut this, id: body_id): void {
|
||||
return if !this.has(id);
|
||||
# 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);
|
||||
}
|
||||
}
|
||||
|
||||
#! Sets a body's own gravity, added to the space's, as a planet's pull changes
|
||||
#! as the body goes around it; waking it where that turns or grows it by more
|
||||
#! than a hundredth, so a body asleep stays so as the pull is found again.
|
||||
pub def space::set_gravity(&mut this, id: body_id, gravity: vec2): void {
|
||||
return if !this.has(id);
|
||||
val i := id.index as u64;
|
||||
val was := this.bodies[i].gravity;
|
||||
this.bodies[i].gravity = gravity;
|
||||
if (gravity - was).length_squared > 1e-4 * math::max(gravity.length_squared, was.length_squared) {
|
||||
this.wake_body(id.index);
|
||||
}
|
||||
}
|
||||
|
||||
#! A body's own gravity, added to the space's.
|
||||
pub def space::gravity_of(&this, id: body_id): vec2 {
|
||||
return this.bodies[id.index as u64].gravity;
|
||||
}
|
||||
|
||||
#! 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 least: 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);
|
||||
}
|
||||
val reach := s.least_reach();
|
||||
least = least == 0 ? reach : math::min(least, reach);
|
||||
}
|
||||
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;
|
||||
this.bodies[i].least = least;
|
||||
}
|
||||
|
||||
# Puts a body's colliders' leaves where it is, each that leaves its grown box
|
||||
# to find what it newly nears.
|
||||
def space::place_colliders(&mut this, b: u32): void {
|
||||
val at := this.bodies[b as u64].at;
|
||||
var c := this.bodies[b as u64].colliders;
|
||||
while c != none {
|
||||
val box := this.box_of(c, at);
|
||||
if this.tree.move(this.colliders[c as u64].leaf, box) && !this.colliders[c as u64].moved {
|
||||
this.colliders[c as u64].moved = true;
|
||||
this.moved.append(c);
|
||||
}
|
||||
c = this.colliders[c as u64].next;
|
||||
}
|
||||
}
|
||||
|
||||
#! 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, and chains' segments from behind: 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> {
|
||||
return this.ray_cast(origin, direction, reach, query_filter{ mask = mask });
|
||||
}
|
||||
|
||||
#! Where a ray first meets a collider a filter asks of, as `ray_cast` casts
|
||||
#! it.
|
||||
pub def space::ray_cast(&this, origin: vec2, direction: vec2, reach: f32, filter: query_filter): maybe<space_hit> {
|
||||
var best: maybe<space_hit> = nothing{};
|
||||
this.tree.ray_cast(origin, direction, reach, def(leaf: u32, data: u64, so_far: f32): f32 {
|
||||
val c := &this.colliders[data];
|
||||
return so_far if !this.passes(data as u32, &filter);
|
||||
val at := this.bodies[c.body as u64].at;
|
||||
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 {
|
||||
# A chain's segment is met only from its front.
|
||||
return so_far if c.made.shape.is_one_sided && direction.dot(at.turn.apply(c.made.shape.normal(0))) >= 0;
|
||||
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();
|
||||
this.struck.clear();
|
||||
return if dt <= 0;
|
||||
val began := instant::now();
|
||||
this.crew.start(this.threads);
|
||||
this.find_pairs();
|
||||
val paired := instant::now();
|
||||
this.update_contacts();
|
||||
val met := instant::now();
|
||||
this.solve(dt);
|
||||
val solved := instant::now();
|
||||
if this.sleeping {
|
||||
this.sleep_islands(dt);
|
||||
}
|
||||
val slept := instant::now();
|
||||
this.profile = step_profile{
|
||||
pairs = milliseconds(paired - began), contacts = milliseconds(met - paired),
|
||||
solve = milliseconds(solved - met), sleep = milliseconds(slept - solved), step = milliseconds(slept - began),
|
||||
};
|
||||
}
|
||||
|
||||
#! 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,391 @@
|
||||
#! 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 = math::max(s.constraints[k as u64].points[j].max_impulse, s.wide[g].points[j].most[lane]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# A stage of a step's lanes, run on the space's crew a color at a time: the
|
||||
# lanes of each color split between its threads, as no two lanes of a color
|
||||
# push one body.
|
||||
struct wide_job {
|
||||
var s: *mut solver_scratch;
|
||||
var first: u64;
|
||||
var warming: bool;
|
||||
var inv_h: f32;
|
||||
var push: f32;
|
||||
var use_bias: bool;
|
||||
}
|
||||
|
||||
def run_wide(context: *mut u8, begin: u64, end: u64): void {
|
||||
val job := &through(context as *mut wide_job);
|
||||
val s := &mut through(job.s);
|
||||
if job.warming {
|
||||
warm_groups(s, job.first + begin, job.first + end);
|
||||
} else {
|
||||
solve_groups(s, job.first + begin, job.first + end, job.inv_h, job.push, job.use_bias);
|
||||
}
|
||||
}
|
||||
|
||||
# Warms or solves the lanes, on the crew where the space has one, a color at a
|
||||
# time.
|
||||
def space::wide_stage(&mut this, s: &mut solver_scratch, warming: bool, inv_h: f32, push: f32, use_bias: bool): void {
|
||||
if this.threads <= 1 {
|
||||
if warming {
|
||||
warm_groups(s, 0, s.wide.length);
|
||||
} else {
|
||||
solve_groups(s, 0, s.wide.length, inv_h, push, use_bias);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var job := wide_job{ s = address(s), warming = warming, inv_h = inv_h, push = push, use_bias = use_bias };
|
||||
for color in 0..colors {
|
||||
val from := s.color_groups[color] as u64;
|
||||
val to := s.color_groups[color + 1] as u64;
|
||||
continue if to == from;
|
||||
job.first = from;
|
||||
val block := math::max((to - from) / (this.threads as u64 * 4), 1u);
|
||||
this.crew.run(run_wide, address(&mut job) as *mut u8, to - from, block);
|
||||
}
|
||||
}
|
||||
|
||||
# Which lanes push a body, by its inverse mass and inertia: those of what
|
||||
# doesn't move, or isn't pushed, as a kinematic body, aren't written back, as
|
||||
# lanes on other threads read its state.
|
||||
def pushed(m: lanes, i: lanes): bool[8] {
|
||||
val ms := m.lanes();
|
||||
val turns := i.lanes();
|
||||
var made: bool[8];
|
||||
for k in 0..width {
|
||||
made[k] = ms[k] > 0 || turns[k] > 0;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
# Writes each pushed lane's number back to where it was gathered from.
|
||||
def put(v: lanes, into: slice<f32>, at: lane_places, keep: &bool[8]): void {
|
||||
val each := v.lanes();
|
||||
val places := at.lanes();
|
||||
for k in 0..width {
|
||||
if keep[k] {
|
||||
into[places[k] as u64] = each[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
def warm_groups(s: &mut solver_scratch, from: u64, to: u64): void {
|
||||
val numbers := numbers_of(s);
|
||||
val view := numbers.span;
|
||||
val one := lane_places::splat(1);
|
||||
val two := lane_places::splat(2);
|
||||
val groups := s.wide.slice;
|
||||
for g in from..to {
|
||||
val w := &groups[g];
|
||||
val keep_a := pushed(w.ma, w.ia);
|
||||
val keep_b := pushed(w.mb, w.ib);
|
||||
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;
|
||||
}
|
||||
put(vax, numbers, w.a, &keep_a);
|
||||
put(vay, numbers, a1, &keep_a);
|
||||
put(wa, numbers, a2, &keep_a);
|
||||
put(vbx, numbers, w.b, &keep_b);
|
||||
put(vby, numbers, b1, &keep_b);
|
||||
put(wb, numbers, b2, &keep_b);
|
||||
}
|
||||
}
|
||||
|
||||
def solve_groups(s: &mut solver_scratch, from: u64, to: u64, inv_h: f32, push: f32, use_bias: bool): void {
|
||||
val numbers := numbers_of(s);
|
||||
val view := numbers.span;
|
||||
val one := lane_places::splat(1);
|
||||
val two := lane_places::splat(2);
|
||||
val four := lane_places::splat(4);
|
||||
val five := lane_places::splat(5);
|
||||
val six := lane_places::splat(6);
|
||||
val 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 from..to {
|
||||
val w := &mut groups[g];
|
||||
val keep_a := pushed(w.ma, w.ia);
|
||||
val keep_b := pushed(w.mb, w.ib);
|
||||
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);
|
||||
}
|
||||
put(vax, numbers, w.a, &keep_a);
|
||||
put(vay, numbers, a1, &keep_a);
|
||||
put(wa, numbers, a2, &keep_a);
|
||||
put(vbx, numbers, w.b, &keep_b);
|
||||
put(vby, numbers, b1, &keep_b);
|
||||
put(wb, numbers, b2, &keep_b);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user