1use ferravex_math::{Vec2, Vec3};
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum MotionError {
29 NonFiniteCurrent,
31 NonFiniteTarget,
33 InvalidRate,
35 InvalidDelta,
37}
38
39impl std::fmt::Display for MotionError {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 f.write_str(match self {
42 Self::NonFiniteCurrent => "current motion vector must be finite",
43 Self::NonFiniteTarget => "target motion vector must be finite",
44 Self::InvalidRate => "motion rate must be finite and nonnegative",
45 Self::InvalidDelta => "motion timestep must be finite and nonnegative",
46 })
47 }
48}
49
50impl std::error::Error for MotionError {}
51
52pub fn approach_vec2(
72 current: Vec2,
73 target: Vec2,
74 max_rate: f32,
75 dt: f32,
76) -> Result<Vec2, MotionError> {
77 approach(current.to_array(), target.to_array(), max_rate, dt).map(Vec2::from_array)
78}
79
80pub fn approach_vec3(
94 current: Vec3,
95 target: Vec3,
96 max_rate: f32,
97 dt: f32,
98) -> Result<Vec3, MotionError> {
99 approach(current.to_array(), target.to_array(), max_rate, dt).map(Vec3::from_array)
100}
101
102pub fn damp_vec2(current: Vec2, target: Vec2, rate: f32, dt: f32) -> Result<Vec2, MotionError> {
125 damp(current.to_array(), target.to_array(), rate, dt).map(Vec2::from_array)
126}
127
128pub fn damp_vec3(current: Vec3, target: Vec3, rate: f32, dt: f32) -> Result<Vec3, MotionError> {
143 damp(current.to_array(), target.to_array(), rate, dt).map(Vec3::from_array)
144}
145
146fn validate<const N: usize>(
147 current: [f32; N],
148 target: [f32; N],
149 rate: f32,
150 dt: f32,
151) -> Result<(), MotionError> {
152 if !current.iter().all(|v| v.is_finite()) {
153 Err(MotionError::NonFiniteCurrent)
154 } else if !target.iter().all(|v| v.is_finite()) {
155 Err(MotionError::NonFiniteTarget)
156 } else if !rate.is_finite() || rate < 0. {
157 Err(MotionError::InvalidRate)
158 } else if !dt.is_finite() || dt < 0. {
159 Err(MotionError::InvalidDelta)
160 } else {
161 Ok(())
162 }
163}
164
165fn approach<const N: usize>(
166 current: [f32; N],
167 target: [f32; N],
168 rate: f32,
169 dt: f32,
170) -> Result<[f32; N], MotionError> {
171 validate(current, target, rate, dt)?;
172 if rate == 0. || dt == 0. || current == target {
173 return Ok(current);
174 }
175 let distance = current
178 .iter()
179 .zip(target)
180 .map(|(&a, b)| (f64::from(b) - f64::from(a)).powi(2))
181 .sum::<f64>()
182 .sqrt();
183 let step = f64::from(rate) * f64::from(dt);
184 if step >= distance {
185 return Ok(target);
186 }
187 Ok(blend(
188 current,
189 target,
190 step / distance,
191 (distance - step) / distance,
192 ))
193}
194
195fn damp<const N: usize>(
196 current: [f32; N],
197 target: [f32; N],
198 rate: f32,
199 dt: f32,
200) -> Result<[f32; N], MotionError> {
201 validate(current, target, rate, dt)?;
202 if rate == 0. || dt == 0. || current == target {
203 return Ok(current);
204 }
205 let exponent = -f64::from(rate) * f64::from(dt);
206 let (toward, remaining) = if exponent > -std::f64::consts::LN_2 {
209 let toward = -exponent.exp_m1();
210 (toward, 1. - toward)
211 } else {
212 let remaining = exponent.exp();
213 (1. - remaining, remaining)
214 };
215 Ok(blend(current, target, toward, remaining))
216}
217
218fn blend<const N: usize>(
219 current: [f32; N],
220 target: [f32; N],
221 toward: f64,
222 remaining: f64,
223) -> [f32; N] {
224 if toward == 0. {
225 return current;
226 }
227 if remaining == 0. {
228 return target;
229 }
230 std::array::from_fn(|i| {
231 let a = f64::from(current[i]);
232 let b = f64::from(target[i]);
233 let next = if toward <= remaining {
234 a + (b - a) * toward
235 } else {
236 b + (a - b) * remaining
237 };
238 next.clamp(a.min(b), a.max(b)) as f32
239 })
240}
241
242pub fn response(rate: f32, dt: f32) -> f32 {
245 if !rate.is_finite() || !dt.is_finite() || rate <= 0. || dt <= 0. {
246 return 0.;
247 }
248 -(-rate * dt).exp_m1()
249}
250
251pub fn impact_velocity(velocity: Vec3, normal: Vec3, restitution: f32, slide: f32) -> Option<Vec3> {
255 if !velocity.is_finite()
256 || !normal.is_finite()
257 || !restitution.is_finite()
258 || !(0. ..=1.).contains(&restitution)
259 || !slide.is_finite()
260 || !(0. ..=1.).contains(&slide)
261 {
262 return None;
263 }
264 let normal = normal.try_normalize()?;
265 let into = velocity.dot(normal);
266 if into >= 0. {
267 return Some(velocity);
268 }
269 Some((velocity - normal * into) * slide - normal * into * restitution)
270}
271
272pub fn radial_velocity(center: Vec3, point: Vec3, radius: f32, speed: f32) -> Option<Vec3> {
275 if !center.is_finite()
276 || !point.is_finite()
277 || !radius.is_finite()
278 || radius <= 0.
279 || !speed.is_finite()
280 || !(0. ..=1000.).contains(&speed)
281 {
282 return None;
283 }
284 let delta = point - center;
285 let distance = delta.length();
286 if distance >= radius {
287 return None;
288 }
289 let weight = (1. - distance / radius).powi(2);
290 Some(delta.try_normalize().unwrap_or(Vec3::Y) * (speed * weight))
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296 #[test]
297 fn response_partitions_and_impacts_preserve_tangent_and_separation() {
298 let once = response(8., 1. / 30.);
299 let twice = 1. - (1. - response(8., 1. / 60.)).powi(2);
300 assert!((once - twice).abs() < 1e-6);
301 assert_eq!(response(f32::NAN, 1.), 0.);
302 let v = Vec3::new(-10., 4., 2.);
303 let hit = impact_velocity(v, Vec3::X * 2., 0.2, 0.9).unwrap();
304 assert!(hit.abs_diff_eq(Vec3::new(2., 3.6, 1.8), 1e-5));
305 assert_eq!(impact_velocity(-v, Vec3::X, 0.2, 0.9), Some(-v));
306 assert_eq!(impact_velocity(v, Vec3::ZERO, 0.2, 0.9), None);
307 }
308 #[test]
309 fn radial_pulse_is_finite_bounded_and_has_no_effect_outside_its_radius() {
310 assert_eq!(radial_velocity(Vec3::ZERO, Vec3::X * 5., 4., 8.), None);
311 assert_eq!(
312 radial_velocity(Vec3::ZERO, Vec3::ZERO, 4., 8.),
313 Some(Vec3::Y * 8.)
314 );
315 assert_eq!(
316 radial_velocity(Vec3::ZERO, Vec3::X * 2., 4., 8.),
317 Some(Vec3::X * 2.)
318 );
319 assert_eq!(radial_velocity(Vec3::ZERO, Vec3::X, f32::NAN, 8.), None);
320 }
321
322 type Step2 = fn(Vec2, Vec2, f32, f32) -> Result<Vec2, MotionError>;
323 type Step3 = fn(Vec3, Vec3, f32, f32) -> Result<Vec3, MotionError>;
324 const HELPERS: [(Step2, Step3); 2] = [(approach_vec2, approach_vec3), (damp_vec2, damp_vec3)];
325
326 #[test]
327 fn approach_bounds_acceleration_across_axes_and_brakes_without_reversing() {
328 let next2 = approach_vec2(Vec2::ZERO, Vec2::new(3., 4.), 2., 0.5).unwrap();
329 assert!(next2.abs_diff_eq(Vec2::new(0.6, 0.8), 1e-6));
330 assert!((next2.length() - 1.).abs() < 1e-6);
331 let next3 = approach_vec3(Vec3::ZERO, Vec3::new(2., 3., 6.), 7., 0.5).unwrap();
332 assert_eq!(next3, Vec3::new(1., 1.5, 3.));
333 assert_eq!(next3.length(), 3.5);
334 assert_eq!(
335 approach_vec2(Vec2::X * 10., -Vec2::X * 10., 4., 0.5),
336 Ok(Vec2::X * 8.)
337 );
338 assert_eq!(
339 approach_vec3(Vec3::Z * 10., -Vec3::Z * 10., 4., 0.5),
340 Ok(Vec3::Z * 8.)
341 );
342 assert_eq!(approach_vec2(next2, Vec2::ZERO, 4., 1.), Ok(Vec2::ZERO));
343 assert_eq!(approach_vec3(next3, Vec3::ZERO, 4., 1.), Ok(Vec3::ZERO));
344 }
345
346 #[test]
347 fn approach_arrives_exactly_at_reachable_targets() {
348 for dt in [1., 2., f32::MAX] {
349 let target2 = Vec2::new(3., 4.);
350 let target3 = Vec3::new(2., 3., 6.);
351 assert_eq!(approach_vec2(Vec2::ZERO, target2, 5., dt), Ok(target2));
352 assert_eq!(approach_vec3(Vec3::ZERO, target3, 7., dt), Ok(target3));
353 }
354 let tiny = f32::from_bits(1);
355 let target2 = Vec2::new(tiny, -tiny);
356 let target3 = Vec3::new(tiny, -tiny, tiny);
357 assert_eq!(
358 approach_vec2(Vec2::splat(f32::MAX), target2, f32::MAX, 2.),
359 Ok(target2)
360 );
361 assert_eq!(
362 approach_vec3(Vec3::splat(f32::MAX), target3, f32::MAX, 2.),
363 Ok(target3)
364 );
365 }
366
367 #[test]
368 fn damping_has_the_expected_half_life_toward_rest_or_a_moving_velocity() {
369 let rate = std::f32::consts::LN_2;
370 let next2 = damp_vec2(Vec2::new(8., -4.), Vec2::ZERO, rate, 1.).unwrap();
371 assert!(next2.abs_diff_eq(Vec2::new(4., -2.), 1e-6));
372 let next3 = damp_vec3(Vec3::new(8., -4., 2.), Vec3::ZERO, rate, 1.).unwrap();
373 assert!(next3.abs_diff_eq(Vec3::new(4., -2., 1.), 1e-6));
374 let next2 = damp_vec2(Vec2::new(-4., 6.), Vec2::new(8., -2.), rate, 1.).unwrap();
375 assert!(next2.abs_diff_eq(Vec2::new(2., 2.), 1e-6));
376 let next3 = damp_vec3(Vec3::new(-4., 6., 2.), Vec3::new(8., -2., 4.), rate, 1.).unwrap();
377 assert!(next3.abs_diff_eq(Vec3::new(2., 2., 3.), 1e-6));
378 }
379
380 #[test]
381 fn fixed_targets_are_stable_across_regular_and_irregular_time_partitions() {
382 for (step2, step3) in HELPERS {
383 for rate in [0.001, 2., 20., 100.] {
384 let start2 = Vec2::new(-3., 4.);
385 let target2 = Vec2::new(7., -2.);
386 let start3 = Vec3::new(-3., 4., -8.);
387 let target3 = Vec3::new(7., -2., 5.);
388 let once2 = step2(start2, target2, rate, 1.).unwrap();
389 let once3 = step3(start3, target3, rate, 1.).unwrap();
390 for hz in [30, 60, 144] {
391 let mut many2 = start2;
392 let mut many3 = start3;
393 for _ in 0..hz {
394 many2 = step2(many2, target2, rate, 1. / hz as f32).unwrap();
395 many3 = step3(many3, target3, rate, 1. / hz as f32).unwrap();
396 }
397 assert!(once2.abs_diff_eq(many2, 1e-4));
398 assert!(once3.abs_diff_eq(many3, 1e-4));
399 }
400 let mut many2 = start2;
401 let mut many3 = start3;
402 for dt in [0.125, 0., 0.25, 0.0625, 0.5625] {
403 many2 = step2(many2, target2, rate, dt).unwrap();
404 many3 = step3(many3, target3, rate, dt).unwrap();
405 }
406 assert!(once2.abs_diff_eq(many2, 1e-5));
407 assert!(once3.abs_diff_eq(many3, 1e-5));
408 }
409 }
410 }
411
412 #[test]
413 fn invalid_vectors_are_rejected_even_with_zero_time_or_rate() {
414 for (step2, step3) in HELPERS {
415 for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
416 for (rate, dt) in [(1., 1.), (0., 1.), (1., 0.)] {
417 for axis in 0..2 {
418 let mut vector = Vec2::ZERO;
419 vector[axis] = bad;
420 assert_eq!(
421 step2(vector, Vec2::ZERO, rate, dt),
422 Err(MotionError::NonFiniteCurrent)
423 );
424 assert_eq!(
425 step2(Vec2::ZERO, vector, rate, dt),
426 Err(MotionError::NonFiniteTarget)
427 );
428 }
429 for axis in 0..3 {
430 let mut vector = Vec3::ZERO;
431 vector[axis] = bad;
432 assert_eq!(
433 step3(vector, Vec3::ZERO, rate, dt),
434 Err(MotionError::NonFiniteCurrent)
435 );
436 assert_eq!(
437 step3(Vec3::ZERO, vector, rate, dt),
438 Err(MotionError::NonFiniteTarget)
439 );
440 }
441 }
442 }
443 }
444 }
445
446 #[test]
447 fn invalid_rates_and_time_are_rejected_before_early_return() {
448 for (step2, step3) in HELPERS {
449 for bad in [
450 -1.,
451 -f32::from_bits(1),
452 f32::NAN,
453 f32::INFINITY,
454 f32::NEG_INFINITY,
455 ] {
456 for other in [0., 1.] {
457 assert_eq!(
458 step2(Vec2::X, Vec2::X, bad, other),
459 Err(MotionError::InvalidRate)
460 );
461 assert_eq!(
462 step3(Vec3::X, Vec3::X, bad, other),
463 Err(MotionError::InvalidRate)
464 );
465 assert_eq!(
466 step2(Vec2::X, Vec2::X, other, bad),
467 Err(MotionError::InvalidDelta)
468 );
469 assert_eq!(
470 step3(Vec3::X, Vec3::X, other, bad),
471 Err(MotionError::InvalidDelta)
472 );
473 }
474 }
475 assert_eq!(
476 step2(Vec2::NAN, Vec2::NAN, -1., -1.),
477 Err(MotionError::NonFiniteCurrent)
478 );
479 assert_eq!(
480 step3(Vec3::NAN, Vec3::NAN, -1., -1.),
481 Err(MotionError::NonFiniteCurrent)
482 );
483 assert_eq!(
484 step2(Vec2::ZERO, Vec2::NAN, -1., -1.),
485 Err(MotionError::NonFiniteTarget)
486 );
487 assert_eq!(
488 step3(Vec3::ZERO, Vec3::NAN, -1., -1.),
489 Err(MotionError::NonFiniteTarget)
490 );
491 }
492 }
493
494 #[test]
495 fn zero_time_rate_and_stationary_targets_preserve_bits() {
496 let start2 = Vec2::new(-0., f32::from_bits(1));
497 let start3 = Vec3::new(-0., f32::from_bits(1), -f32::MAX);
498 for (step2, step3) in HELPERS {
499 for (rate, dt) in [(0., f32::MAX), (-0., 1.), (f32::MAX, 0.), (1., -0.)] {
500 let next2 = step2(start2, Vec2::splat(f32::MAX), rate, dt).unwrap();
501 let next3 = step3(start3, Vec3::splat(f32::MAX), rate, dt).unwrap();
502 assert_eq!(
503 next2.to_array().map(f32::to_bits),
504 start2.to_array().map(f32::to_bits)
505 );
506 assert_eq!(
507 next3.to_array().map(f32::to_bits),
508 start3.to_array().map(f32::to_bits)
509 );
510 }
511 let next2 = step2(start2, start2, f32::MAX, f32::MAX).unwrap();
512 let next3 = step3(start3, start3, f32::MAX, f32::MAX).unwrap();
513 assert_eq!(
514 next2.to_array().map(f32::to_bits),
515 start2.to_array().map(f32::to_bits)
516 );
517 assert_eq!(
518 next3.to_array().map(f32::to_bits),
519 start3.to_array().map(f32::to_bits)
520 );
521 }
522 }
523
524 #[test]
525 fn approach_handles_extreme_differences_products_and_subnormal_steps() {
526 let largest = f32::MAX;
527 assert_eq!(
528 approach_vec2(Vec2::X * -largest, Vec2::X * largest, largest, 1.),
529 Ok(Vec2::ZERO)
530 );
531 assert_eq!(
532 approach_vec3(Vec3::Z * -largest, Vec3::Z * largest, largest, 1.),
533 Ok(Vec3::ZERO)
534 );
535 assert_eq!(
536 approach_vec2(
537 Vec2::splat(-largest),
538 Vec2::splat(largest),
539 largest,
540 largest
541 ),
542 Ok(Vec2::splat(largest))
543 );
544 assert_eq!(
545 approach_vec3(
546 Vec3::splat(-largest),
547 Vec3::splat(largest),
548 largest,
549 largest
550 ),
551 Ok(Vec3::splat(largest))
552 );
553 let tiny = f32::from_bits(1);
554 assert_eq!(
555 approach_vec2(Vec2::ZERO, Vec2::X, tiny, 1.),
556 Ok(Vec2::X * tiny)
557 );
558 assert_eq!(
559 approach_vec3(Vec3::ZERO, Vec3::Z, tiny, 1.),
560 Ok(Vec3::Z * tiny)
561 );
562 }
563
564 #[test]
565 fn damping_preserves_tiny_weights_and_large_vector_residuals() {
566 let rate = f32::MIN_POSITIVE;
569 let expected = (f64::from(f32::MAX) * f64::from(rate).powi(2)) as f32;
570 let next2 = damp_vec2(Vec2::ZERO, Vec2::X * f32::MAX, rate, rate).unwrap();
571 let next3 = damp_vec3(Vec3::ZERO, Vec3::Z * f32::MAX, rate, rate).unwrap();
572 assert_eq!(next2, Vec2::X * expected);
573 assert_eq!(next3, Vec3::Z * expected);
574 assert!(expected > 0.);
575
576 let expected = (f64::from(f32::MAX) * (-100_f64).exp()) as f32;
579 let next2 = damp_vec2(Vec2::X * f32::MAX, Vec2::ZERO, 100., 1.).unwrap();
580 let next3 = damp_vec3(Vec3::Z * f32::MAX, Vec3::ZERO, 100., 1.).unwrap();
581 assert_eq!(next2, Vec2::X * expected);
582 assert_eq!(next3, Vec3::Z * expected);
583 assert!(expected > 1e-5);
584 let split2 = damp_vec2(
585 damp_vec2(Vec2::X * f32::MAX, Vec2::ZERO, 100., 0.5).unwrap(),
586 Vec2::ZERO,
587 100.,
588 0.5,
589 )
590 .unwrap();
591 let split3 = damp_vec3(
592 damp_vec3(Vec3::Z * f32::MAX, Vec3::ZERO, 100., 0.5).unwrap(),
593 Vec3::ZERO,
594 100.,
595 0.5,
596 )
597 .unwrap();
598 assert!((split2.x - expected).abs() <= expected * 1e-6);
599 assert!((split3.z - expected).abs() <= expected * 1e-6);
600 }
601
602 fn assert_bounded<const N: usize>(start: [f32; N], target: [f32; N], next: [f32; N]) {
603 for i in 0..N {
604 assert!(next[i].is_finite());
605 assert!((start[i].min(target[i])..=start[i].max(target[i])).contains(&next[i]));
606 }
607 }
608
609 #[test]
610 fn checked_results_stay_finite_between_endpoints_across_float_scales() {
611 let scales = [
612 -f32::MAX,
613 -1.,
614 -f32::from_bits(1),
615 0.,
616 f32::from_bits(1),
617 1.,
618 f32::MAX,
619 ];
620 for (step2, step3) in HELPERS {
621 for a in scales {
622 for b in scales {
623 let start2 = Vec2::new(a, -a);
624 let target2 = Vec2::new(b, -b);
625 let start3 = Vec3::new(a, -a, a * 0.5);
626 let target3 = Vec3::new(b, -b, b * 0.5);
627 for (rate, dt) in [
628 (0., 1.),
629 (1., 0.),
630 (f32::from_bits(1), 1.),
631 (2., 0.25),
632 (1., 100.),
633 (f32::MAX, f32::MAX),
634 ] {
635 let next2 = step2(start2, target2, rate, dt).unwrap();
636 let next3 = step3(start3, target3, rate, dt).unwrap();
637 assert_bounded(start2.to_array(), target2.to_array(), next2.to_array());
638 assert_bounded(start3.to_array(), target3.to_array(), next3.to_array());
639 }
640 }
641 }
642 }
643 }
644
645 #[test]
646 fn damping_saturates_exactly_at_tiny_targets_and_keeps_legacy_response_contract() {
647 let tiny = f32::from_bits(1);
648 let target2 = Vec2::new(tiny, -tiny);
649 let target3 = Vec3::new(tiny, -tiny, -0.);
650 assert_eq!(
651 damp_vec2(Vec2::splat(f32::MAX), target2, f32::MAX, 1.),
652 Ok(target2)
653 );
654 let next3 = damp_vec3(Vec3::splat(f32::MAX), target3, f32::MAX, 1.).unwrap();
655 assert_eq!(
656 next3.to_array().map(f32::to_bits),
657 target3.to_array().map(f32::to_bits)
658 );
659 for bad in [-1., 0., f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
660 assert_eq!(response(bad, 1.), 0.);
661 assert_eq!(response(1., bad), 0.);
662 }
663 assert_eq!(response(f32::MAX, f32::MAX), 1.);
664 }
665}