use rapier2d::prelude::*;
use std::collections::HashMap;
use crate::{Force, ForceContext, NodeKey};
pub const DEFAULT_ANCHOR_STIFFNESS: f32 = 12.0;
pub const DEFAULT_ANCHOR_SLACK: f32 = 0.5;
#[derive(Clone, Debug, Default)]
pub struct AnchorSpring {
anchors: HashMap<NodeKey, Vector>,
pub stiffness: f32,
pub slack: f32,
}
impl AnchorSpring {
pub fn new(anchors: impl IntoIterator<Item = (NodeKey, (f32, f32))>) -> Self {
Self {
anchors: anchors
.into_iter()
.map(|(k, (x, y))| (k, Vector::new(x, y)))
.collect(),
stiffness: DEFAULT_ANCHOR_STIFFNESS,
slack: DEFAULT_ANCHOR_SLACK,
}
}
pub fn with_stiffness(mut self, stiffness: f32) -> Self {
self.stiffness = stiffness.max(0.0);
self
}
pub fn len(&self) -> usize {
self.anchors.len()
}
pub fn is_empty(&self) -> bool {
self.anchors.is_empty()
}
}
impl Force for AnchorSpring {
fn apply(&self, ctx: &mut ForceContext<'_>, _dt: f32) {
if self.stiffness <= 0.0 {
return; }
for (node, anchor) in &self.anchors {
let Some(&handle) = ctx.bodies_by_node.get(node) else {
continue; };
let Some(position) = ctx.bodies.get(handle).map(|b| b.translation()) else {
continue;
};
let offset = anchor - position;
let distance = offset.length();
if distance <= self.slack || distance < 1e-4 {
continue;
}
let pull = offset / distance * (self.stiffness * (distance - self.slack));
if let Some(body) = ctx.bodies.get_mut(handle) {
body.add_force(pull, true);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zero_stiffness_is_inert() {
let force = AnchorSpring::new([(NodeKey::new(0), (10.0, 0.0))]).with_stiffness(0.0);
assert_eq!(force.stiffness, 0.0);
assert_eq!(force.len(), 1, "the anchors are kept; only the pull is off");
}
#[test]
fn negative_stiffness_clamps_to_inert() {
let force = AnchorSpring::new([(NodeKey::new(0), (0.0, 0.0))]).with_stiffness(-5.0);
assert_eq!(force.stiffness, 0.0, "an anchor never pushes away");
}
#[test]
fn empty_anchors_report_empty() {
assert!(AnchorSpring::default().is_empty());
}
}