use std::collections::HashMap;
use std::ops::Range;
use glam::{Vec2, vec2};
use slotmap::DenseSlotMap;
slotmap::new_key_type! {
pub struct BodyId;
pub struct RopeId;
}
const MIN_AREA: f32 = 0.5;
const EPSILON: f32 = 1e-4;
#[derive(Clone, Copy, Debug, Default)]
pub struct PointMass {
pub position: Vec2,
pub velocity: Vec2,
pub force: Vec2,
pub mass: f32,
}
impl PointMass {
#[inline]
pub fn is_static(&self) -> bool {
self.mass <= 0.0
}
#[inline]
pub fn inverse_mass(&self) -> f32 {
if self.is_static() {
0.0
} else {
1.0 / self.mass
}
}
}
fn apply_air_drag(points: &mut [PointMass], drag: f32, dt: f32) {
let factor = (1.0 - drag).powf(dt * 60.0);
for point in points {
point.velocity *= factor;
}
}
fn integrate(points: &mut [PointMass], dt: f32) {
for point in points.iter_mut().filter(|point| !point.is_static()) {
point.velocity += point.force / point.mass * dt;
point.position += point.velocity * dt;
}
}
#[inline]
fn collide_axis(
position: &mut f32,
velocity: &mut f32,
slide_velocity: &mut f32,
(min, max): (f32, f32),
elasticity: f32,
slide: f32,
) {
if *position < min {
*position = min;
if *velocity < 0.0 {
*velocity = -*velocity * elasticity;
}
*slide_velocity *= slide;
} else if *position > max {
*position = max;
if *velocity > 0.0 {
*velocity = -*velocity * elasticity;
}
*slide_velocity *= slide;
}
}
fn collide_bounds(points: &mut [PointMass], bounds: Aabb, material: Material, dt: f32) {
let slide = (1.0 - material.friction).clamp(0.0, 1.0).powf(dt * 60.0);
for point in points.iter_mut().filter(|point| !point.is_static()) {
collide_axis(
&mut point.position.x,
&mut point.velocity.x,
&mut point.velocity.y,
(bounds.min.x, bounds.max.x),
material.elasticity,
slide,
);
collide_axis(
&mut point.position.y,
&mut point.velocity.y,
&mut point.velocity.x,
(bounds.min.y, bounds.max.y),
material.elasticity,
slide,
);
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Spring {
pub a: usize,
pub b: usize,
pub rest: f32,
pub body: BodyId,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct RopeAnchor {
pub node: usize,
pub target: usize,
}
#[derive(Clone, Debug, Default)]
pub struct Rope {
pub first: usize,
pub count: usize,
pub rest: Vec<f32>,
pub stiffness: f32,
pub iterations: usize,
pub group: usize,
pub material: usize,
pub anchors: Vec<RopeAnchor>,
pub aabb: Aabb,
}
impl Rope {
#[inline]
pub fn range(&self) -> Range<usize> {
self.first..self.first + self.count
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Material {
pub elasticity: f32,
pub friction: f32,
}
#[inline]
fn pair_key(a: usize, b: usize) -> (usize, usize) {
(a.min(b), a.max(b))
}
#[inline]
fn shift_after(range: &Range<usize>, count: usize, index: &mut usize) {
if *index >= range.end {
*index -= count;
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Contact {
pub point: usize,
pub edge_a: usize,
pub edge_b: usize,
pub edge_t: f32,
pub normal: Vec2,
pub depth: f32,
pub elasticity: f32,
pub friction: f32,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Aabb {
pub min: Vec2,
pub max: Vec2,
}
impl Aabb {
pub fn from_points(points: &[PointMass]) -> Option<Self> {
let (first, rest) = points.split_first()?;
let start = Self {
min: first.position,
max: first.position,
};
Some(rest.iter().fold(start, |bounds, point| Self {
min: bounds.min.min(point.position),
max: bounds.max.max(point.position),
}))
}
#[inline]
pub fn overlaps(&self, other: &Self) -> bool {
self.min.cmple(other.max).all() && other.min.cmple(self.max).all()
}
#[inline]
pub fn contains(&self, point: Vec2) -> bool {
point.cmpge(self.min).all() && point.cmple(self.max).all()
}
#[inline]
pub fn center(&self) -> Vec2 {
(self.min + self.max) * 0.5
}
}
#[derive(Clone, Debug, Default)]
pub struct Body {
pub first: usize,
pub count: usize,
pub rest: Vec<Vec2>,
pub center: Vec2,
pub angle: f32,
pub target: Vec<Vec2>,
pub gas: f32,
pub area: f32,
pub push: Vec<Vec2>,
pub aabb: Aabb,
pub group: usize,
pub material: usize,
pub torque: f32,
pub max_spin: f32,
pub spring_k: f32,
pub spring_damping: f32,
pub shape_matching_enabled: bool,
pub shape_matching_k: f32,
pub shape_matching_damping: f32,
}
impl Body {
#[inline]
pub fn range(&self) -> Range<usize> {
self.first..self.first + self.count
}
#[inline]
pub fn is_static(&self, points: &[PointMass]) -> bool {
points[self.first].is_static()
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct BodyJoint {
pub point: usize,
pub body: BodyId,
pub k: f32,
pub damping: f32,
}
#[derive(Clone, Copy, Debug)]
pub struct Settings {
pub air_drag: f32,
pub body_collisions: bool,
pub world_bound_collisions: bool,
pub default_material: Material,
pub time_step: f32,
pub iterations: usize,
pub max_frame_time: f32,
pub max_steps_per_frame: usize,
pub gravity: Vec2,
}
impl Default for Settings {
fn default() -> Self {
Self {
air_drag: 0.004,
body_collisions: true,
world_bound_collisions: true,
default_material: Material {
elasticity: 0.5,
friction: 0.5,
},
time_step: 1.0 / 60.0,
iterations: 4,
max_frame_time: 0.1,
max_steps_per_frame: 32,
gravity: vec2(0.0, -9.8),
}
}
}
#[derive(Clone, Debug)]
pub struct World {
pub points: Vec<PointMass>,
pub springs: Vec<Spring>,
pub bodies: DenseSlotMap<BodyId, Body>,
pub ropes: DenseSlotMap<RopeId, Rope>,
pub contacts: Vec<Contact>,
pub joints: Vec<BodyJoint>,
pub bounds: Aabb,
pub bounds_material: Material,
pub material_pairs: HashMap<(usize, usize), Material>,
pub group_collisions: HashMap<(usize, usize), bool>,
pub grab: Grab,
pub settings: Settings,
accumulator: f32,
}
impl Default for World {
fn default() -> Self {
Self {
points: Vec::new(),
springs: Vec::new(),
bodies: DenseSlotMap::with_key(),
ropes: DenseSlotMap::with_key(),
contacts: Vec::new(),
joints: Vec::new(),
bounds: Self::DEFAULT_BOUNDS,
bounds_material: Self::DEFAULT_BOUNDS_MATERIAL,
material_pairs: HashMap::new(),
group_collisions: HashMap::new(),
grab: Grab::default(),
settings: Settings::default(),
accumulator: 0.0,
}
}
}
impl World {
pub const DEFAULT_BOUNDS: Aabb = Aabb {
min: vec2(0.0, 0.0),
max: vec2(16.0, 9.0),
};
pub const DEFAULT_BOUNDS_MATERIAL: Material = Material {
elasticity: 0.2,
friction: 0.5,
};
pub fn add_point(&mut self, position: Vec2, velocity: Vec2, mass: f32) -> usize {
let index = self.points.len();
self.points.push(PointMass {
position,
velocity,
force: Vec2::ZERO,
mass,
});
index
}
pub fn add_body(&mut self, shape: &[Vec2], origin: Vec2, mass: f32) -> BodyId {
assert!(
!shape.is_empty(),
"Bir gövde en az bir noktaya sahip olmalı"
);
let count = shape.len();
let centroid = shape.iter().copied().sum::<Vec2>() / count as f32;
let first = self.points.len();
let rest: Vec<Vec2> = shape.iter().map(|&point| point - centroid).collect();
for &point in shape {
self.add_point(origin + point, Vec2::ZERO, mass);
}
let key = self.bodies.insert(Body {
first,
count,
rest,
target: vec![Vec2::ZERO; count],
push: vec![Vec2::ZERO; count],
spring_k: 100.0,
spring_damping: 15.0,
shape_matching_enabled: true,
shape_matching_k: 400.,
shape_matching_damping: 15.0,
gas: 40.0,
..Body::default()
});
for i in 0..count {
self.add_spring(key, first + i, first + (i + 1) % count);
}
key
}
pub fn add_spring(&mut self, body: BodyId, a: usize, b: usize) {
let rest = self.points[a].position.distance(self.points[b].position);
self.springs.push(Spring { a, b, rest, body });
}
pub fn add_rope(&mut self, nodes: &[Vec2], mass: f32) -> RopeId {
assert!(nodes.len() >= 2, "Bir ip en az iki noktaya sahip olmalı");
let first = self.points.len();
for &position in nodes {
self.add_point(position, Vec2::ZERO, mass);
}
let rest = nodes
.windows(2)
.map(|pair| pair[0].distance(pair[1]))
.collect();
self.ropes.insert(Rope {
first,
count: nodes.len(),
rest,
stiffness: 1.0,
iterations: 4,
group: 0,
material: 0,
anchors: Vec::new(),
aabb: Aabb::default(),
})
}
pub fn add_straight_rope(
&mut self,
start: Vec2,
end: Vec2,
segments: usize,
mass: f32,
) -> RopeId {
assert!(segments >= 1, "Bir ip en az bir segmente sahip olmalı");
let nodes: Vec<Vec2> = (0..=segments)
.map(|i| start.lerp(end, i as f32 / segments as f32))
.collect();
self.add_rope(&nodes, mass)
}
pub fn anchor_rope(&mut self, rope: RopeId, node: usize, target: usize) -> bool {
let Some(current) = self.ropes.get(rope) else {
return false;
};
if node >= current.count || target >= self.points.len() {
return false;
}
self.ropes[rope].anchors.push(RopeAnchor { node, target });
true
}
pub fn set_all_springs(&mut self, k: f32, damping: f32) {
for body in self.bodies.values_mut() {
body.spring_k = k;
body.spring_damping = damping;
}
}
pub fn set_material_pair(&mut self, a: usize, b: usize, pair: Material) {
self.material_pairs.insert(pair_key(a, b), pair);
}
pub fn material_pair(&self, a: usize, b: usize) -> Material {
self.material_pairs
.get(&pair_key(a, b))
.copied()
.unwrap_or(self.settings.default_material)
}
pub fn set_group_collision(&mut self, a: usize, b: usize, collide: bool) {
self.group_collisions.insert(pair_key(a, b), collide);
}
pub fn groups_collide(&self, a: usize, b: usize) -> bool {
match self.group_collisions.get(&pair_key(a, b)) {
Some(&collide) => collide,
None => a == 0 || a != b,
}
}
pub fn remove_body(&mut self, key: BodyId) -> bool {
let Some(removed) = self.bodies.remove(key) else {
return false;
};
let range = removed.range();
let count = removed.count;
self.points.drain(range.clone());
self.springs.retain(|spring| spring.body != key);
for spring in &mut self.springs {
if spring.a >= range.end {
spring.a -= count;
}
if spring.b >= range.end {
spring.b -= count;
}
}
for body in self.bodies.values_mut() {
if body.first >= range.end {
body.first -= count;
}
}
self.joints
.retain(|joint| joint.body != key && !range.contains(&joint.point));
for joint in &mut self.joints {
if joint.point >= range.end {
joint.point -= count;
}
}
for rope in self.ropes.values_mut() {
shift_after(&range, count, &mut rope.first);
rope.anchors
.retain(|anchor| !range.contains(&anchor.target));
for anchor in &mut rope.anchors {
shift_after(&range, count, &mut anchor.target);
}
}
if self.grab.active {
if range.contains(&self.grab.point) {
self.grab.active = false;
} else if self.grab.point >= range.end {
self.grab.point -= count;
}
}
self.contacts.clear();
true
}
pub fn remove_rope(&mut self, key: RopeId) -> bool {
let Some(removed) = self.ropes.remove(key) else {
return false;
};
let range = removed.first..removed.first + removed.count;
let count = removed.count;
self.points.drain(range.clone());
self.springs
.retain(|spring| !range.contains(&spring.a) && !range.contains(&spring.b));
for spring in &mut self.springs {
shift_after(&range, count, &mut spring.a);
shift_after(&range, count, &mut spring.b);
}
for body in self.bodies.values_mut() {
shift_after(&range, count, &mut body.first);
}
self.joints.retain(|joint| !range.contains(&joint.point));
for joint in &mut self.joints {
shift_after(&range, count, &mut joint.point);
}
for rope in self.ropes.values_mut() {
shift_after(&range, count, &mut rope.first);
rope.anchors
.retain(|anchor| !range.contains(&anchor.target));
for anchor in &mut rope.anchors {
shift_after(&range, count, &mut anchor.target);
}
}
if self.grab.active {
if range.contains(&self.grab.point) {
self.grab.active = false;
} else {
shift_after(&range, count, &mut self.grab.point);
}
}
self.contacts.clear();
true
}
pub fn clear(&mut self) {
self.points.clear();
self.springs.clear();
self.bodies.clear();
self.ropes.clear();
self.contacts.clear();
self.joints.clear();
self.bounds = Self::DEFAULT_BOUNDS;
self.bounds_material = Self::DEFAULT_BOUNDS_MATERIAL;
self.material_pairs.clear();
self.group_collisions.clear();
self.grab = Grab::default();
self.settings = Settings::default();
self.accumulator = 0.0;
}
pub fn body_points(&self, body: &Body) -> &[PointMass] {
&self.points[body.range()]
}
pub fn step(&mut self, frame_time: f32) {
let settings = self.settings;
let sub_dt = settings.time_step / settings.iterations.max(1) as f32;
self.accumulator += frame_time.min(settings.max_frame_time);
let mut steps = 0;
while self.accumulator >= sub_dt && steps < settings.max_steps_per_frame {
self.fixed_step(sub_dt);
self.accumulator -= sub_dt;
steps += 1;
}
if self.accumulator >= sub_dt {
self.accumulator = 0.0;
}
}
fn apply_gravity(&mut self) {
for point in &mut self.points {
point.force = self.settings.gravity * point.mass;
}
}
fn apply_springs(&mut self) {
for spring in &self.springs {
if self.points[spring.a].is_static() && self.points[spring.b].is_static() {
continue;
}
let Some(body) = self.bodies.get(spring.body) else {
continue;
};
let force = spring_force(
self.points[spring.a],
self.points[spring.b],
spring.rest,
body.spring_k,
body.spring_damping,
);
self.points[spring.a].force += force;
self.points[spring.b].force -= force;
}
}
fn solve_ropes(&mut self, dt: f32) {
for rope in self.ropes.values_mut() {
let mut touched: Vec<usize> = Vec::with_capacity(rope.count + rope.anchors.len());
touched.extend(rope.range());
touched.extend(rope.anchors.iter().map(|anchor| anchor.target));
touched.sort_unstable();
touched.dedup();
let before: Vec<Vec2> = touched.iter().map(|&i| self.points[i].position).collect();
let stiffness = rope.stiffness.clamp(0.0, 1.0);
let iterations = rope.iterations.max(1);
for _ in 0..iterations {
for i in 0..rope.rest.len() {
project_constraint(
&mut self.points,
rope.first + i,
rope.first + i + 1,
rope.rest[i],
stiffness,
true, );
}
for anchor in &rope.anchors {
project_constraint(
&mut self.points,
rope.first + anchor.node,
anchor.target,
0.0,
stiffness,
false, );
}
}
for (&index, &old) in touched.iter().zip(&before) {
let point = &mut self.points[index];
if !point.is_static() {
point.velocity += (point.position - old) / dt;
}
}
}
}
pub fn fixed_step(&mut self, dt: f32) {
let settings = self.settings;
self.apply_gravity();
self.apply_springs();
for body in self.bodies.values_mut() {
let points = &mut self.points[body.range()];
derive_frame(body, points);
if body.shape_matching_enabled {
apply_shape_matching(body, points);
}
if body.gas > 0.0 && !points[0].is_static() {
apply_pressure(body, points);
}
if body.torque != 0.0 {
apply_torque(body, points);
}
}
for joint in &self.joints {
let Some(body) = self.bodies.get(joint.body) else {
continue;
};
apply_joint(&mut self.points, body, joint);
}
apply_grab_spring(self.grab, &mut self.points);
integrate(&mut self.points, dt);
apply_air_drag(&mut self.points, settings.air_drag, dt);
self.solve_ropes(dt);
if settings.body_collisions {
self.collide_bodies();
}
if settings.world_bound_collisions {
collide_bounds(&mut self.points, self.bounds, self.bounds_material, dt);
}
}
fn find_contacts(&mut self) {
for body in self.bodies.values_mut() {
if let Some(bounds) = Aabb::from_points(&self.points[body.range()]) {
body.aabb = bounds;
}
}
for rope in self.ropes.values_mut() {
if let Some(bounds) = Aabb::from_points(&self.points[rope.range()]) {
rope.aabb = bounds;
}
}
self.contacts.clear();
for (a_key, a) in self.bodies.iter() {
let a_static = a.is_static(&self.points);
for (b_key, b) in self.bodies.iter() {
if a_key == b_key || !a.aabb.overlaps(&b.aabb) {
continue;
}
if !self.groups_collide(a.group, b.group) {
continue;
}
if a_static && b.is_static(&self.points) {
continue;
}
let pair = self.material_pair(a.material, b.material);
let ring = &self.points[b.range()];
for (offset, point) in self.points[a.range()].iter().enumerate() {
let position = point.position;
if !b.aabb.contains(position) || !point_in_polygon(position, ring) {
continue;
}
if let Some(mut contact) = closest_edge(position, ring, b.first) {
contact.point = a.first + offset;
contact.elasticity = pair.elasticity;
contact.friction = pair.friction;
self.contacts.push(contact);
}
}
}
}
for rope in self.ropes.values() {
for body in self.bodies.values() {
if !rope.aabb.overlaps(&body.aabb) {
continue;
}
if !self.groups_collide(rope.group, body.group) {
continue;
}
let pair = self.material_pair(rope.material, body.material);
let ring = &self.points[body.range()];
for offset in 0..rope.count {
let index = rope.first + offset;
let position = self.points[index].position;
if !body.aabb.contains(position) || !point_in_polygon(position, ring) {
continue;
}
if let Some(mut contact) = closest_edge(position, ring, body.first) {
contact.point = index;
contact.elasticity = pair.elasticity;
contact.friction = pair.friction;
self.contacts.push(contact);
}
}
}
}
}
fn collide_bodies(&mut self) {
self.find_contacts();
for &contact in &self.contacts {
resolve_contact(&mut self.points, contact);
}
}
}
pub fn spring_force(a: PointMass, b: PointMass, rest: f32, k: f32, damping: f32) -> Vec2 {
let delta = a.position - b.position;
let distance = delta.length();
if distance < EPSILON {
return Vec2::ZERO;
}
let direction = delta / distance;
let stretch = rest - distance;
let closing_speed = (a.velocity - b.velocity).dot(direction);
direction * (k * stretch - damping * closing_speed)
}
fn project_constraint(
points: &mut [PointMass],
a: usize,
b: usize,
rest: f32,
stiffness: f32,
slack: bool,
) {
if a == b {
return;
}
let inv_a = points[a].inverse_mass();
let inv_b = points[b].inverse_mass();
let inv_sum = inv_a + inv_b;
if inv_sum <= 0.0 {
return;
}
let delta = points[b].position - points[a].position;
let distance = delta.length();
if distance < EPSILON || (slack && distance <= rest) {
return;
}
let correction = delta * ((distance - rest) / distance * stiffness.clamp(0.0, 1.0) / inv_sum);
points[a].position += correction * inv_a;
points[b].position -= correction * inv_b;
}
fn derive_frame(body: &mut Body, points: &[PointMass]) {
if points.is_empty() {
return;
}
let center = points.iter().map(|point| point.position).sum::<Vec2>() / points.len() as f32;
let (sin_sum, cos_sum) = points.iter().zip(&body.rest).fold(
(0.0_f32, 0.0_f32),
|(sin_sum, cos_sum), (point, rest)| {
let current = point.position - center;
(
sin_sum + rest.perp_dot(current),
cos_sum + rest.dot(current),
)
},
);
body.center = center;
body.angle = sin_sum.atan2(cos_sum);
let rotation = Vec2::from_angle(body.angle);
for (target, rest) in body.target.iter_mut().zip(&body.rest) {
*target = center + rotation.rotate(*rest);
}
}
fn apply_shape_matching(body: &Body, points: &mut [PointMass]) {
let mean_velocity = mean_velocity(points);
for (point, &position) in points.iter_mut().zip(&body.target) {
let target = PointMass {
position,
velocity: mean_velocity,
..PointMass::default()
};
point.force += spring_force(
*point,
target,
0.0,
body.shape_matching_k,
body.shape_matching_damping,
);
}
}
fn edges(ring: &[PointMass]) -> impl Iterator<Item = (&PointMass, &PointMass)> {
ring.iter().zip(ring.iter().cycle().skip(1))
}
pub fn polygon_area(points: &[PointMass]) -> f32 {
if points.len() < 3 {
return 0.0;
}
let sum: f32 = edges(points)
.map(|(a, b)| a.position.perp_dot(b.position))
.sum();
sum * 0.5
}
fn apply_pressure(body: &mut Body, points: &mut [PointMass]) {
body.area = polygon_area(points).abs().max(MIN_AREA);
body.push.fill(Vec2::ZERO);
let count = points.len();
if count < 2 {
return;
}
for i in 0..count {
let j = (i + 1) % count;
let edge = points[j].position - points[i].position;
let edge_length = edge.length();
if edge_length < EPSILON {
continue;
}
let normal = vec2(edge.y, -edge.x) / edge_length;
let force = normal * (body.gas * edge_length / body.area);
body.push[i] += force * 0.5;
body.push[j] += force * 0.5;
}
for (point, push) in points.iter_mut().zip(&body.push) {
point.force += *push;
}
}
const GRAB_STIFFNESS: f32 = 400.0;
const GRAB_DAMPING: f32 = 20.0;
#[derive(Clone, Copy, Debug, Default)]
pub struct Grab {
pub active: bool,
pub point: usize,
pub target: Vec2,
}
fn apply_grab_spring(grab: Grab, points: &mut [PointMass]) {
if !grab.active {
return;
}
let Some(&point) = points.get(grab.point) else {
return;
};
let anchor = PointMass {
position: grab.target,
..PointMass::default()
};
points[grab.point].force += spring_force(point, anchor, 0.0, GRAB_STIFFNESS, GRAB_DAMPING);
}
pub fn nearest_point(points: &[PointMass], at: Vec2, max_dist: f32) -> Option<usize> {
points
.iter()
.enumerate()
.map(|(index, point)| (index, point.position.distance(at)))
.filter(|(_, distance)| *distance < max_dist)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(index, _)| index)
}
pub fn point_in_polygon(point: Vec2, ring: &[PointMass]) -> bool {
if ring.len() < 3 {
return false;
}
let mut inside = false;
for (a, b) in edges(ring) {
let (a, b) = (a.position, b.position);
if (a.y > point.y) != (b.y > point.y) {
let cross_x = a.x + (point.y - a.y) / (b.y - a.y) * (b.x - a.x);
if point.x < cross_x {
inside = !inside;
}
}
}
inside
}
pub fn closest_edge(point: Vec2, ring: &[PointMass], first: usize) -> Option<Contact> {
let mut closest: Option<Contact> = None;
for (i, (a, b)) in edges(ring).enumerate() {
let edge = b.position - a.position;
let length_squared = edge.length_squared();
if length_squared < EPSILON * EPSILON {
continue;
}
let t = ((point - a.position).dot(edge) / length_squared).clamp(0.0, 1.0);
let distance = point.distance(a.position + edge * t);
if closest.is_none_or(|contact| distance < contact.depth) {
closest = Some(Contact {
edge_a: first + i,
edge_b: first + (i + 1) % ring.len(),
edge_t: t,
normal: vec2(edge.y, -edge.x) / length_squared.sqrt(),
depth: distance,
..Contact::default()
});
}
}
closest
}
fn resolve_contact(points: &mut [PointMass], contact: Contact) {
let (elasticity, friction) = (contact.elasticity, contact.friction);
let mut point = points[contact.point];
let mut edge_a = points[contact.edge_a];
let mut edge_b = points[contact.edge_b];
let weight_a = 1.0 - contact.edge_t;
let weight_b = contact.edge_t;
let inv_point = point.inverse_mass();
let edge_mass = edge_a.mass + edge_b.mass;
let inv_edge = if edge_mass > 0.0 {
1.0 / edge_mass
} else {
0.0
};
let inv_sum = inv_point + inv_edge;
if inv_sum <= 0.0 {
return;
}
point.position += contact.normal * (contact.depth * inv_point / inv_sum);
let edge_move = contact.normal * (contact.depth * inv_edge / inv_sum);
edge_a.position -= edge_move * weight_a;
edge_b.position -= edge_move * weight_b;
let relative_velocity =
point.velocity - (edge_a.velocity * weight_a + edge_b.velocity * weight_b);
let approach = relative_velocity.dot(contact.normal);
if approach < 0.0 {
let tangent = contact.normal.perp();
let bounce = -(1.0 + elasticity) * approach / inv_sum;
let rub = -relative_velocity.dot(tangent) * friction / inv_sum;
let impulse = contact.normal * bounce + tangent * rub;
point.velocity += impulse * inv_point;
edge_a.velocity -= impulse * (inv_edge * weight_a);
edge_b.velocity -= impulse * (inv_edge * weight_b);
}
points[contact.point] = point;
points[contact.edge_a] = edge_a;
points[contact.edge_b] = edge_b;
}
pub fn mean_velocity(points: &[PointMass]) -> Vec2 {
if points.is_empty() {
return Vec2::ZERO;
}
points.iter().map(|point| point.velocity).sum::<Vec2>() / points.len() as f32
}
pub fn make_rectangle(center: Vec2, w: f32, h: f32) -> Vec<Vec2> {
let hx = w * 0.5;
let hy = h * 0.5;
vec![
center + vec2(-hx, -hy),
center + vec2(hx, -hy),
center + vec2(hx, hy),
center + vec2(-hx, hy),
]
}
pub fn make_rounded_rectangle(center: Vec2, w: f32, h: f32) -> Vec<Vec2> {
let hx = w * 0.5;
let hy = h * 0.5;
let cut = (w.min(h) * 0.25).min(hx).min(hy).max(0.0);
vec![
center + vec2(-hx + cut, -hy),
center + vec2(hx - cut, -hy),
center + vec2(hx, -hy + cut),
center + vec2(hx, hy - cut),
center + vec2(hx - cut, hy),
center + vec2(-hx + cut, hy),
center + vec2(-hx, hy - cut),
center + vec2(-hx, -hy + cut),
]
}
pub fn make_regular_polygon(center: Vec2, r: f32, n: usize) -> Vec<Vec2> {
let segments = n.max(3);
(0..segments)
.map(|i| {
let angle = i as f32 / segments as f32 * std::f32::consts::TAU;
center + Vec2::from_angle(angle) * r
})
.collect()
}
fn apply_joint(points: &mut [PointMass], body: &Body, joint: &BodyJoint) {
let center = PointMass {
position: body.center,
velocity: mean_velocity(&points[body.range()]),
..PointMass::default()
};
let force = spring_force(points[joint.point], center, 0.0, joint.k, joint.damping);
points[joint.point].force += force;
let share = force / body.count as f32;
for point in &mut points[body.range()] {
point.force -= share;
}
}
fn tangent_of(radius: Vec2) -> Option<Vec2> {
let distance = radius.length();
(distance > EPSILON).then(|| radius.perp() / distance)
}
fn apply_torque(body: &Body, points: &mut [PointMass]) {
if points.is_empty() {
return;
}
let mean_velocity = mean_velocity(points);
let spin = points
.iter()
.filter_map(|point| {
let tangent = tangent_of(point.position - body.center)?;
Some((point.velocity - mean_velocity).dot(tangent))
})
.sum::<f32>()
/ points.len() as f32;
let direction = body.torque.signum();
let strength = if body.max_spin > 0.0 {
(1.0 - spin * direction / body.max_spin).clamp(0.0, 1.0)
} else {
1.0
};
for point in points {
if let Some(tangent) = tangent_of(point.position - body.center) {
point.force += tangent * (body.torque * strength);
}
}
}
#[cfg(test)]
mod tests;