use std::collections::VecDeque;
use arc_tokens::SpringSpec;
use crate::spring::SpringSolver;
pub fn rubber_band(distance: f32, limit: f32) -> f32 {
if limit <= 0.0 || distance <= 0.0 {
return 0.0;
}
(1.0 - 1.0 / (distance * 0.55 / limit + 1.0)) * limit
}
pub fn rubber_band_signed(distance: f32, limit: f32) -> f32 {
if distance == 0.0 {
return 0.0;
}
distance.signum() * rubber_band(distance.abs(), limit)
}
pub fn project_deceleration(velocity_px_per_sec: f32) -> f32 {
(velocity_px_per_sec / 1000.0) * 0.99 / (1.0 - 0.99)
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct DragConstraints {
pub min: Option<f32>,
pub max: Option<f32>,
pub elastic_limit: f32,
}
impl DragConstraints {
pub fn apply(self, raw: f32) -> (f32, f32) {
let mut clamped = raw;
if let Some(min) = self.min {
clamped = clamped.max(min);
}
if let Some(max) = self.max {
clamped = clamped.min(max);
}
let excess = raw - clamped;
let elastic = if self.elastic_limit > 0.0 {
rubber_band_signed(excess, self.elastic_limit)
} else {
0.0
};
(clamped, elastic)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DragSample {
pub time_secs: f64,
pub position: f32,
}
#[derive(Clone, Debug)]
pub struct DragTracker {
pub slop_px: f32,
pub active: bool,
start_x: f32,
start_y: f32,
origin_value: f32,
samples: VecDeque<DragSample>,
}
impl DragTracker {
pub fn new(slop_px: f32) -> Self {
Self {
slop_px: slop_px.max(0.0),
active: false,
start_x: 0.0,
start_y: 0.0,
origin_value: 0.0,
samples: VecDeque::with_capacity(8),
}
}
pub fn begin(&mut self, pointer_x: f32, pointer_y: f32, origin_value: f32, time_secs: f64) {
self.active = self.slop_px == 0.0;
self.start_x = pointer_x;
self.start_y = pointer_y;
self.origin_value = origin_value;
self.samples.clear();
if self.active {
self.samples.push_back(DragSample {
time_secs,
position: origin_value,
});
}
}
pub fn update_x(
&mut self,
pointer_x: f32,
pointer_y: f32,
time_secs: f64,
lock_horizontal: bool,
) -> Option<f32> {
if !self.active {
let dx = pointer_x - self.start_x;
let dy = pointer_y - self.start_y;
if dx.hypot(dy) < self.slop_px {
return None;
}
if lock_horizontal && dy.abs() > dx.abs() {
return None;
}
self.active = true;
self.start_x = pointer_x;
self.samples.clear();
}
let raw = self.origin_value + (pointer_x - self.start_x);
self.samples.push_back(DragSample {
time_secs,
position: raw,
});
while self.samples.len() > 2 {
if let Some(front) = self.samples.front()
&& time_secs - front.time_secs > 0.1
{
self.samples.pop_front();
continue;
}
break;
}
Some(raw)
}
pub fn release_velocity(&self, release_time_secs: f64) -> f32 {
let (Some(first), Some(last)) = (self.samples.front(), self.samples.back()) else {
return 0.0;
};
let dt = last.time_secs - first.time_secs;
if dt <= 0.008 || (release_time_secs - last.time_secs) > 0.060 {
return 0.0;
}
((last.position - first.position) as f64 / dt) as f32
}
}
#[derive(Clone, Copy, Debug)]
pub struct InertiaConfig {
pub power: f64,
pub time_constant_ms: f64,
pub bounce_stiffness: f64,
pub bounce_damping: f64,
pub min: Option<f64>,
pub max: Option<f64>,
pub rest_delta: f64,
}
impl Default for InertiaConfig {
fn default() -> Self {
Self {
power: 0.8,
time_constant_ms: 325.0,
bounce_stiffness: 500.0,
bounce_damping: 10.0,
min: None,
max: None,
rest_delta: 0.5,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct InertiaSample {
pub value: f32,
pub done: bool,
}
#[derive(Clone, Debug)]
pub struct InertiaSolver {
target: f64,
amplitude: f64,
config: InertiaConfig,
boundary_time_ms: Option<f64>,
boundary_spring: Option<SpringSolver>,
}
impl InertiaSolver {
pub fn new(origin: f64, velocity_per_sec: f64, config: InertiaConfig) -> Self {
let amplitude = config.power * velocity_per_sec;
let target = origin + amplitude;
let mut solver = Self {
target,
amplitude,
config,
boundary_time_ms: None,
boundary_spring: None,
};
solver.check_boundary(0.0, origin);
if solver.boundary_spring.is_none()
&& solver.is_out_of_bounds(target)
&& amplitude.abs() > 1e-9
&& config.time_constant_ms > 0.0
{
let boundary = solver.nearest_boundary(target);
if (target - boundary).abs() > config.rest_delta {
let ratio = ((target - boundary) / amplitude).clamp(1e-9, 1.0);
let bt = (-config.time_constant_ms * ratio.ln()).max(0.0);
solver.check_boundary(bt, boundary);
}
}
solver
}
fn is_out_of_bounds(&self, v: f64) -> bool {
self.config.min.is_some_and(|min| v < min) || self.config.max.is_some_and(|max| v > max)
}
fn nearest_boundary(&self, v: f64) -> f64 {
match (self.config.min, self.config.max) {
(Some(min), Some(max)) => {
if (min - v).abs() < (max - v).abs() {
min
} else {
max
}
}
(Some(min), None) => min,
(None, Some(max)) => max,
(None, None) => v,
}
}
fn calc_delta(&self, t_ms: f64) -> f64 {
-self.amplitude * (-t_ms / self.config.time_constant_ms).exp()
}
fn check_boundary(&mut self, t_ms: f64, value: f64) {
if self.boundary_spring.is_some() || !self.is_out_of_bounds(value) {
return;
}
self.boundary_time_ms = Some(t_ms);
let boundary = self.nearest_boundary(value);
let velocity_per_sec = (-self.calc_delta(t_ms) / self.config.time_constant_ms) * 1000.0;
let spec = SpringSpec::physics(
self.config.bounce_stiffness as f32,
self.config.bounce_damping as f32,
);
self.boundary_spring = Some(
SpringSolver::new(spec, value, boundary, velocity_per_sec)
.with_rest_thresholds(self.config.rest_delta, 2.0),
);
}
pub fn sample_ms(&mut self, t_ms: f64) -> InertiaSample {
let t_ms = t_ms.max(0.0);
if self.boundary_spring.is_none() {
let delta = self.calc_delta(t_ms);
let done = delta.abs() <= self.config.rest_delta;
let value = if done {
self.target
} else {
self.target + delta
};
self.check_boundary(t_ms, value);
if self.boundary_spring.is_none() {
return InertiaSample {
value: value as f32,
done,
};
}
}
if let (Some(bt), Some(spring)) = (self.boundary_time_ms, &self.boundary_spring)
&& t_ms >= bt
{
let s = spring.sample((t_ms - bt) / 1000.0);
return InertiaSample {
value: s.value,
done: s.settled,
};
}
let delta = self.calc_delta(t_ms);
let done = delta.abs() <= self.config.rest_delta;
let value = if done {
self.target
} else {
self.target + delta
};
InertiaSample {
value: value as f32,
done,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rubber_band_is_monotonic_and_bounded_by_limit() {
let limit = 26.0;
assert_eq!(rubber_band_signed(0.0, limit), 0.0);
let small = rubber_band_signed(10.0, limit);
let large = rubber_band_signed(1000.0, limit);
assert!(small > 0.0 && small < large && large < limit);
assert!((rubber_band_signed(-10.0, limit) + small).abs() < 1e-5);
}
#[test]
fn drag_tracker_handles_slop_and_velocity() {
let mut tracker = DragTracker::new(6.0);
tracker.begin(100.0, 50.0, 0.0, 0.0);
assert_eq!(tracker.update_x(103.0, 50.0, 0.016, true), None);
assert!(!tracker.active);
assert_eq!(tracker.update_x(110.0, 50.0, 0.032, true), Some(0.0));
assert!(tracker.active);
assert_eq!(tracker.update_x(160.0, 50.0, 0.082, true), Some(50.0));
let vel = tracker.release_velocity(0.090);
assert!((vel - 1000.0).abs() < 1.0, "expected ~1000px/s, got {vel}");
}
#[test]
fn inertia_matches_motion_decay_and_bounces_at_boundary() {
let mut free = InertiaSolver::new(0.0, 500.0, InertiaConfig::default());
let s100 = free.sample_ms(100.0);
let expected = 400.0 - 400.0 * (-100.0_f64 / 325.0).exp();
assert!((f64::from(s100.value) - expected).abs() < 1e-3);
let cfg = InertiaConfig {
min: Some(0.0),
max: Some(100.0),
..Default::default()
};
let mut bounded = InertiaSolver::new(0.0, 800.0, cfg);
let mut settled_value = 0.0;
let mut reached_done = false;
for step in 1..=200 {
let s = bounded.sample_ms(step as f64 * 16.0);
settled_value = s.value;
if s.done {
reached_done = true;
break;
}
}
assert!(reached_done);
assert!((settled_value - 100.0).abs() <= 0.5);
}
}