ferravex_play/animation/
contact.rs

1//! Analytic limb IK and presentation-only foot contacts. Hosts supply actual
2//! support queries and apply rotations after their authored animation graph.
3use super::AnimationError;
4use ferravex_math::Vec3;
5#[derive(Clone, Copy, Debug, PartialEq)]
6pub struct LimbPose {
7    pub root: Vec3,
8    pub joint: Vec3,
9    pub end: Vec3,
10    pub clamped: bool,
11}
12#[derive(Clone, Copy, Debug)]
13pub struct TwoBone {
14    pub upper: f32,
15    pub lower: f32,
16}
17impl TwoBone {
18    pub fn solve(self, root: Vec3, target: Vec3, pole: Vec3) -> Result<LimbPose, AnimationError> {
19        if ![self.upper, self.lower]
20            .iter()
21            .all(|v| v.is_finite() && (0.001..=1000.).contains(v))
22            || ![root, target, pole]
23                .iter()
24                .all(|v| v.is_finite() && v.abs().max_element() <= 1e6)
25        {
26            return Err(AnimationError::InvalidPose);
27        }
28        let delta = target - root;
29        let length = delta.length();
30        let axis = delta.try_normalize().unwrap_or(-Vec3::Y);
31        let epsilon = self.upper.min(self.lower) * 0.0001;
32        let reach = length.clamp(
33            (self.upper - self.lower).abs() + epsilon,
34            self.upper + self.lower - epsilon,
35        );
36        let along =
37            (self.upper * self.upper - self.lower * self.lower + reach * reach) / (2. * reach);
38        let side = (pole - root - axis * (pole - root).dot(axis))
39            .try_normalize()
40            .unwrap_or_else(|| axis.any_orthonormal_vector());
41        Ok(LimbPose {
42            root,
43            joint: root
44                + axis * along
45                + side * (self.upper * self.upper - along * along).max(0.).sqrt(),
46            end: root + axis * reach,
47            clamped: (reach - length).abs() > epsilon,
48        })
49    }
50}
51#[derive(Clone, Copy, Debug)]
52pub struct FootContact {
53    pub position: Vec3,
54    pub normal: Vec3,
55    pub support: u64,
56    pub support_delta: Vec3,
57}
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct FootPose {
60    pub position: Vec3,
61    pub normal: Vec3,
62    pub weight: f32,
63}
64/// Contact acquisition and retention rules for [`FootPlant::with_thresholds`].
65///
66/// A new support must be within `enter_distance` and have `normal.y` strictly
67/// above `enter_normal_y`. The current support may use the full maximum
68/// correction distance and the lower `exit_normal_y` threshold. Both distance
69/// limits are inclusive. A support change always uses the acquisition rules.
70///
71/// ```
72/// use ferravex_play::animation::{FootContact, FootPlant, FootPlantThresholds};
73/// use ferravex_math::Vec3;
74///
75/// let thresholds = FootPlantThresholds {
76///     enter_distance: 0.3,
77///     enter_normal_y: 0.6,
78///     exit_normal_y: 0.4,
79///     release_delay: 0.05,
80/// };
81/// let mut foot = FootPlant::with_thresholds(0.5, 0.05, thresholds)?;
82/// assert_eq!(foot.thresholds(), thresholds);
83/// let contact = FootContact {
84///     position: Vec3::Y * 0.2,
85///     normal: Vec3::Y,
86///     support: 7,
87///     support_delta: Vec3::ZERO,
88/// };
89/// let pose = foot.update(Vec3::ZERO, Some(contact), true, 0.05)?;
90/// assert_eq!(foot.support(), Some(7));
91/// assert_eq!(foot.pose(), pose);
92/// assert!((foot.correction().y - 0.1).abs() < 1e-6);
93/// // One short query dropout holds the anchor and its correction.
94/// assert_eq!(foot.update(Vec3::ZERO, None, true, 0.01)?, pose);
95/// # Ok::<(), ferravex_play::animation::AnimationError>(())
96/// ```
97#[derive(Clone, Copy, Debug, PartialEq)]
98pub struct FootPlantThresholds {
99    /// Finite acquisition distance in `0..=max_correction`.
100    pub enter_distance: f32,
101    /// Finite, strict minimum upward normal component in `0..1`.
102    pub enter_normal_y: f32,
103    /// Finite retention threshold in `0..=enter_normal_y`.
104    pub exit_normal_y: f32,
105    /// Seconds of marginal/missing contact tolerated in `0..=0.25`.
106    /// At this duration the anchor releases; zero disables the grace period.
107    pub release_delay: f32,
108}
109
110/// Allocation-free presentation contact state. The caller supplies support
111/// queries and elapsed presentation time; this never changes body motion.
112#[derive(Clone, Copy, Debug)]
113pub struct FootPlant {
114    support: Option<u64>,
115    pose: FootPose,
116    max_correction: f32,
117    half_life: f32,
118    thresholds: FootPlantThresholds,
119    missing_seconds: f64,
120    correction: Vec3,
121}
122impl FootPlant {
123    /// Uses the original single cutoff: maximum correction distance, upward
124    /// normal component strictly above `0.5`, and no contact-loss grace period.
125    /// Use [`Self::with_thresholds`] to opt into hysteresis.
126    pub fn new(max_correction: f32, half_life: f32) -> Result<Self, AnimationError> {
127        Self::with_thresholds(
128            max_correction,
129            half_life,
130            FootPlantThresholds {
131                enter_distance: max_correction,
132                enter_normal_y: 0.5,
133                exit_normal_y: 0.5,
134                release_delay: 0.,
135            },
136        )
137    }
138
139    /// Creates a plant with validated hysteresis. Maximum correction must be
140    /// in `0.001..=10` world units and half-life in `0.001..=1` seconds. Invalid
141    /// or non-finite configuration returns [`AnimationError::InvalidPose`].
142    /// See [`FootPlantThresholds`] for a compiling usage example and field limits.
143    pub fn with_thresholds(
144        max_correction: f32,
145        half_life: f32,
146        thresholds: FootPlantThresholds,
147    ) -> Result<Self, AnimationError> {
148        if !max_correction.is_finite()
149            || !(0.001..=10.).contains(&max_correction)
150            || !half_life.is_finite()
151            || !(0.001..=1.).contains(&half_life)
152            || !thresholds.enter_distance.is_finite()
153            || !(0. ..=max_correction).contains(&thresholds.enter_distance)
154            || !thresholds.enter_normal_y.is_finite()
155            || !(0. ..1.).contains(&thresholds.enter_normal_y)
156            || !thresholds.exit_normal_y.is_finite()
157            || !(0. ..=thresholds.enter_normal_y).contains(&thresholds.exit_normal_y)
158            || !thresholds.release_delay.is_finite()
159            || !(0. ..=0.25).contains(&thresholds.release_delay)
160        {
161            return Err(AnimationError::InvalidPose);
162        }
163        Ok(Self {
164            support: None,
165            pose: FootPose {
166                position: Vec3::ZERO,
167                normal: Vec3::Y,
168                weight: 0.,
169            },
170            max_correction,
171            half_life,
172            thresholds,
173            missing_seconds: 0.,
174            correction: Vec3::ZERO,
175        })
176    }
177
178    /// Discards the anchor, normal, weight, grace timer and correction. The
179    /// unweighted target returns to the origin; use [`Self::reset`] on teleport.
180    pub fn clear(&mut self) {
181        self.support = None;
182        self.pose = FootPose {
183            position: Vec3::ZERO,
184            normal: Vec3::Y,
185            weight: 0.,
186        };
187        self.missing_seconds = 0.;
188        self.correction = Vec3::ZERO;
189    }
190
191    /// Clears all contact history at a new animated position. A non-finite
192    /// position returns [`AnimationError::InvalidPose`] without changing state.
193    ///
194    /// ```
195    /// use ferravex_math::Vec3;
196    /// use ferravex_play::animation::FootPlant;
197    /// let mut foot = FootPlant::new(0.5, 0.05)?;
198    /// let pose = foot.reset(Vec3::X * 10.)?;
199    /// assert_eq!(pose.position, Vec3::X * 10.);
200    /// assert_eq!(pose.weight, 0.);
201    /// assert_eq!(foot.support(), None);
202    /// assert_eq!(foot.correction(), Vec3::ZERO);
203    /// foot.clear();
204    /// assert_eq!(foot.pose().position, Vec3::ZERO);
205    /// # Ok::<(), ferravex_play::animation::AnimationError>(())
206    /// ```
207    pub fn reset(&mut self, animated: Vec3) -> Result<FootPose, AnimationError> {
208        if !animated.is_finite() {
209            return Err(AnimationError::InvalidPose);
210        }
211        self.clear();
212        self.pose.position = animated;
213        Ok(self.pose)
214    }
215
216    /// Returns the last unweighted target, normal and blend weight.
217    pub fn pose(&self) -> FootPose {
218        self.pose
219    }
220
221    /// Returns the accepted support, including while held during a grace period.
222    pub fn support(&self) -> Option<u64> {
223        self.support
224    }
225
226    /// Returns the validated acquisition/retention configuration.
227    pub fn thresholds(&self) -> FootPlantThresholds {
228        self.thresholds
229    }
230
231    /// Weighted translation from the last positive-time update's animated
232    /// position: `(pose.position - animated) * pose.weight`. Add this to that
233    /// animated position to apply the contact blend. Zero after clear/reset.
234    /// It is bounded by `max_correction`, subject to floating-point rounding.
235    pub fn correction(&self) -> Vec3 {
236        self.correction
237    }
238
239    /// Updates presentation state with finite positions, a unit contact normal
240    /// (squared-length tolerance `0.001`), and `dt` in `0..=0.25` seconds.
241    /// Invalid input leaves all state unchanged; zero time validates input but
242    /// holds all state, so a support delta is not consumed while paused.
243    ///
244    /// Once acquired, an anchor follows the same support's delta exactly once
245    /// per positive-time update, independently of blend weight. Query position
246    /// jitter does not move that anchor. If support motion takes the anchor out
247    /// of range, a usable contact reanchors it within the correction limit.
248    ///
249    /// Missing/marginal contact holds a bounded anchor for less than
250    /// `release_delay` seconds; absent queries imply no known support motion.
251    /// A valid contact resets that timer. `plant = false`, a different support,
252    /// or an out-of-range anchor bypasses the grace period. Release restores the
253    /// animated position/up normal immediately while the blend weight decays.
254    pub fn update(
255        &mut self,
256        animated: Vec3,
257        contact: Option<FootContact>,
258        plant: bool,
259        dt: f32,
260    ) -> Result<FootPose, AnimationError> {
261        if !animated.is_finite()
262            || !dt.is_finite()
263            || !(0. ..=0.25).contains(&dt)
264            || contact.is_some_and(|c| {
265                !c.position.is_finite()
266                    || !c.normal.is_finite()
267                    || (c.normal.length_squared() - 1.).abs() > 0.001
268                    || !c.support_delta.is_finite()
269            })
270        {
271            return Err(AnimationError::InvalidPose);
272        }
273        if dt == 0. {
274            return Ok(self.pose);
275        }
276        let alpha = -(-std::f32::consts::LN_2 * dt / self.half_life).exp_m1();
277        let same_support = contact.is_some_and(|c| self.support == Some(c.support));
278        let anchor = if same_support {
279            self.pose.position + contact.expect("same support has a contact").support_delta
280        } else {
281            self.pose.position
282        };
283        let anchor_in_range =
284            anchor.is_finite() && anchor.distance(animated) <= self.max_correction;
285        let usable = contact.filter(|c| {
286            plant
287                && c.normal.y
288                    > if same_support {
289                        self.thresholds.exit_normal_y
290                    } else {
291                        self.thresholds.enter_normal_y
292                    }
293                && c.position.distance(animated)
294                    <= if same_support {
295                        self.max_correction
296                    } else {
297                        self.thresholds.enter_distance
298                    }
299        });
300        if let Some(c) = usable {
301            self.pose.position = if same_support && anchor_in_range {
302                anchor
303            } else {
304                c.position
305            };
306            self.pose.normal = if same_support {
307                self.pose.normal.lerp(c.normal, alpha)
308            } else {
309                c.normal
310            }
311            .normalize_or(Vec3::Y);
312            self.pose.weight += (1. - self.pose.weight) * alpha;
313            self.support = Some(c.support);
314            self.missing_seconds = 0.;
315        } else if plant
316            && self.support.is_some()
317            && (contact.is_none() || same_support)
318            && anchor_in_range
319            && self.missing_seconds + f64::from(dt) < f64::from(self.thresholds.release_delay)
320        {
321            self.pose.position = anchor;
322            self.missing_seconds += f64::from(dt);
323        } else {
324            self.support = None;
325            self.missing_seconds = 0.;
326            self.pose.weight *= 1. - alpha;
327            self.pose.position = animated;
328            self.pose.normal = Vec3::Y;
329        }
330        self.correction = (self.pose.position - animated) * self.pose.weight;
331        Ok(self.pose)
332    }
333}
334#[cfg(test)]
335mod tests {
336    use super::*;
337    #[test]
338    fn ik_preserves_lengths_and_handles_unreachable_and_collinear_poles() {
339        for target in [Vec3::ZERO, Vec3::X, Vec3::X * 5.] {
340            let p = TwoBone {
341                upper: 0.6,
342                lower: 0.4,
343            }
344            .solve(Vec3::ZERO, target, Vec3::X)
345            .unwrap();
346            assert!((p.joint.distance(p.root) - 0.6).abs() < 0.0001);
347            assert!((p.end.distance(p.joint) - 0.4).abs() < 0.0001);
348            assert!(p.joint.is_finite());
349        }
350    }
351    #[test]
352    fn contact_moves_with_support_and_releases_without_changing_body() {
353        let mut p = FootPlant::new(0.5, 0.01).unwrap();
354        let c = FootContact {
355            position: Vec3::Y * 0.1,
356            normal: Vec3::Y,
357            support: 2,
358            support_delta: Vec3::ZERO,
359        };
360        let a = p.update(Vec3::ZERO, Some(c), true, 0.1).unwrap();
361        assert!(a.weight > 0.9);
362        let b = p
363            .update(
364                Vec3::ZERO,
365                Some(FootContact {
366                    support_delta: Vec3::X * 0.1,
367                    ..c
368                }),
369                true,
370                0.1,
371            )
372            .unwrap();
373        assert!(b.position.x > 0.09);
374        let gone = p.update(Vec3::ZERO, None, false, 0.1).unwrap();
375        assert!(gone.weight < 0.01);
376    }
377
378    fn thresholds() -> FootPlantThresholds {
379        FootPlantThresholds {
380            enter_distance: 0.3,
381            enter_normal_y: 0.6,
382            exit_normal_y: 0.4,
383            release_delay: 0.0625,
384        }
385    }
386
387    fn contact(position: Vec3, normal_y: f32) -> FootContact {
388        FootContact {
389            position,
390            normal: Vec3::new((1. - normal_y * normal_y).sqrt(), normal_y, 0.),
391            support: 7,
392            support_delta: Vec3::ZERO,
393        }
394    }
395
396    fn planted() -> FootPlant {
397        let mut foot = FootPlant::with_thresholds(0.5, 0.1, thresholds()).unwrap();
398        foot.update(Vec3::ZERO, Some(contact(Vec3::Y * 0.2, 1.)), true, 0.1)
399            .unwrap();
400        foot
401    }
402
403    fn assert_same_state(a: FootPlant, b: FootPlant) {
404        assert_eq!(a.pose(), b.pose());
405        assert_eq!(a.support(), b.support());
406        assert_eq!(a.correction(), b.correction());
407        assert_eq!(a.thresholds(), b.thresholds());
408        assert_eq!(a.missing_seconds, b.missing_seconds);
409    }
410
411    #[test]
412    fn thresholds_reject_nonfinite_unordered_and_out_of_range_values() {
413        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 0.51] {
414            assert!(matches!(
415                FootPlant::with_thresholds(
416                    0.5,
417                    0.1,
418                    FootPlantThresholds {
419                        enter_distance: value,
420                        ..thresholds()
421                    }
422                ),
423                Err(AnimationError::InvalidPose)
424            ));
425        }
426        for value in [f32::NAN, f32::INFINITY, -0.01, 0.3, 1.] {
427            assert!(matches!(
428                FootPlant::with_thresholds(
429                    0.5,
430                    0.1,
431                    FootPlantThresholds {
432                        enter_normal_y: value,
433                        ..thresholds()
434                    }
435                ),
436                Err(AnimationError::InvalidPose)
437            ));
438        }
439        for value in [f32::NAN, f32::INFINITY, -0.01, 0.61] {
440            assert!(matches!(
441                FootPlant::with_thresholds(
442                    0.5,
443                    0.1,
444                    FootPlantThresholds {
445                        exit_normal_y: value,
446                        ..thresholds()
447                    }
448                ),
449                Err(AnimationError::InvalidPose)
450            ));
451        }
452        for value in [f32::NAN, f32::INFINITY, -0.01, 0.251] {
453            assert!(matches!(
454                FootPlant::with_thresholds(
455                    0.5,
456                    0.1,
457                    FootPlantThresholds {
458                        release_delay: value,
459                        ..thresholds()
460                    }
461                ),
462                Err(AnimationError::InvalidPose)
463            ));
464        }
465        for (maximum, half_life) in [
466            (f32::NAN, 0.1),
467            (f32::INFINITY, 0.1),
468            (0., 0.1),
469            (10.1, 0.1),
470            (0.5, f32::NAN),
471            (0.5, f32::INFINITY),
472            (0.5, 0.),
473            (0.5, 1.1),
474        ] {
475            assert!(FootPlant::new(maximum, half_life).is_err());
476        }
477        for (maximum, half_life, enter_distance, release_delay) in
478            [(0.001, 0.001, 0., 0.), (10., 1., 10., 0.25)]
479        {
480            assert!(
481                FootPlant::with_thresholds(
482                    maximum,
483                    half_life,
484                    FootPlantThresholds {
485                        enter_distance,
486                        enter_normal_y: 0.,
487                        exit_normal_y: 0.,
488                        release_delay,
489                    },
490                )
491                .is_ok()
492            );
493        }
494    }
495
496    #[test]
497    fn legacy_constructor_keeps_single_cutoffs_and_immediate_release() {
498        let mut foot = FootPlant::new(0.5, 0.1).unwrap();
499        for sample in [contact(Vec3::Y * 0.501, 1.), contact(Vec3::Y * 0.2, 0.5)] {
500            foot.update(Vec3::ZERO, Some(sample), true, 0.1).unwrap();
501            assert_eq!(foot.support(), None);
502        }
503        foot.update(Vec3::ZERO, Some(contact(Vec3::Y * 0.5, 1.)), true, 0.1)
504            .unwrap();
505        assert_eq!(foot.support(), Some(7));
506        foot.update(Vec3::ZERO, None, true, 0.001).unwrap();
507        assert_eq!(foot.support(), None);
508        assert_eq!(foot.correction(), Vec3::ZERO);
509    }
510
511    #[test]
512    fn marginal_contacts_retain_an_anchor_but_cannot_acquire_one() {
513        let mut foot = FootPlant::with_thresholds(0.5, 0.1, thresholds()).unwrap();
514        for sample in [contact(Vec3::Y * 0.31, 1.), contact(Vec3::Y * 0.2, 0.6)] {
515            foot.update(Vec3::ZERO, Some(sample), true, 0.1).unwrap();
516            assert_eq!(foot.support(), None);
517        }
518        let anchor = Vec3::Y * 0.3;
519        foot.update(Vec3::ZERO, Some(contact(anchor, 1.)), true, 0.1)
520            .unwrap();
521        for i in 0..32 {
522            // Both values straddle the old single cutoff while remaining
523            // inside the new retention band, for longer than the grace period.
524            let normal_y = if i % 2 == 0 { 0.49 } else { 0.51 };
525            foot.update(
526                Vec3::ZERO,
527                Some(contact(Vec3::Y * 0.5, normal_y)),
528                true,
529                0.01,
530            )
531            .unwrap();
532            assert_eq!(foot.support(), Some(7));
533            assert_eq!(foot.pose().position, anchor);
534            assert!(foot.pose().normal.is_normalized());
535        }
536    }
537
538    #[test]
539    fn contact_loss_grace_uses_elapsed_time_and_recovery_rearms_it() {
540        let mut foot = planted();
541        let initial = foot.pose();
542        for _ in 0..3 {
543            assert_eq!(foot.update(Vec3::ZERO, None, true, 0.015625), Ok(initial));
544            assert_eq!(foot.support(), Some(7));
545        }
546        foot.update(Vec3::ZERO, None, true, 0.015625).unwrap();
547        assert_eq!(foot.support(), None);
548        assert_eq!(foot.pose().position, Vec3::ZERO);
549
550        let mut foot = planted();
551        foot.update(Vec3::ZERO, None, true, 0.046875).unwrap();
552        foot.update(Vec3::ZERO, Some(contact(Vec3::Y * 0.2, 1.)), true, 0.01)
553            .unwrap();
554        foot.update(Vec3::ZERO, None, true, 0.046875).unwrap();
555        assert_eq!(foot.support(), Some(7));
556        foot.update(Vec3::ZERO, None, true, 0.015625).unwrap();
557        assert_eq!(foot.support(), None);
558    }
559
560    #[test]
561    fn marginal_distance_and_slope_have_bounded_grace() {
562        for sample in [contact(Vec3::Y * 0.501, 1.), contact(Vec3::Y * 0.2, 0.4)] {
563            let mut foot = planted();
564            let initial = foot.pose();
565            foot.update(Vec3::ZERO, Some(sample), true, 0.03125)
566                .unwrap();
567            assert_eq!(foot.support(), Some(7));
568            assert_eq!(foot.pose(), initial);
569            foot.update(Vec3::ZERO, Some(sample), true, 0.03125)
570                .unwrap();
571            assert_eq!(foot.support(), None);
572        }
573    }
574
575    #[test]
576    fn plant_release_and_support_changes_bypass_grace() {
577        let mut foot = planted();
578        foot.update(Vec3::ZERO, Some(contact(Vec3::Y * 0.2, 1.)), false, 0.001)
579            .unwrap();
580        assert_eq!(foot.support(), None);
581        assert_eq!(foot.correction(), Vec3::ZERO);
582
583        let mut foot = planted();
584        let other = FootContact {
585            support: 8,
586            support_delta: Vec3::X * 100.,
587            ..contact(Vec3::Y * 0.4, 0.5)
588        };
589        foot.update(Vec3::ZERO, Some(other), true, 0.001).unwrap();
590        assert_eq!(foot.support(), None);
591        let other = FootContact {
592            position: Vec3::Z * 0.2,
593            normal: Vec3::Y,
594            ..other
595        };
596        foot.update(Vec3::ZERO, Some(other), true, 0.001).unwrap();
597        assert_eq!(foot.support(), Some(8));
598        assert_eq!(foot.pose().position, other.position);
599    }
600
601    #[test]
602    fn moving_support_is_followed_exactly_even_during_low_weight_and_grace() {
603        let mut foot = FootPlant::with_thresholds(0.5, 1., thresholds()).unwrap();
604        foot.update(Vec3::ZERO, Some(contact(Vec3::Y * 0.2, 1.)), true, 0.001)
605            .unwrap();
606        assert!(foot.pose().weight < 0.01);
607        for step in 1..=3 {
608            let sample = FootContact {
609                // Deliberately jitter the query while keeping the anchor.
610                position: Vec3::Y * 0.25,
611                support_delta: Vec3::X * 0.05,
612                ..contact(Vec3::ZERO, 1.)
613            };
614            foot.update(Vec3::ZERO, Some(sample), true, 0.001).unwrap();
615            assert!((foot.pose().position.x - step as f32 * 0.05).abs() < 1e-6);
616            assert_eq!(foot.pose().position.y, 0.2);
617        }
618        let sample = FootContact {
619            support_delta: Vec3::X * 0.05,
620            ..contact(Vec3::Y * 0.2, 0.3)
621        };
622        foot.update(Vec3::ZERO, Some(sample), true, 0.01).unwrap();
623        assert!((foot.pose().position.x - 0.2).abs() < 1e-6);
624        assert_eq!(foot.support(), Some(7));
625    }
626
627    #[test]
628    fn correction_is_weighted_and_unreachable_anchors_never_leak() {
629        let mut foot = planted();
630        assert!((foot.correction().y - 0.1).abs() < 1e-6);
631        let animated = Vec3::X * 0.4;
632        let sample = FootContact {
633            support_delta: -Vec3::X * 0.2,
634            ..contact(animated + Vec3::Y * 0.2, 1.)
635        };
636        let pose = foot.update(animated, Some(sample), true, 0.001).unwrap();
637        // The old anchor is now too far away; reanchor without blending from it.
638        assert_eq!(pose.position, sample.position);
639        assert_eq!(foot.correction(), (pose.position - animated) * pose.weight);
640        assert!(foot.correction().length() <= 0.5);
641
642        foot.update(Vec3::X * 10., None, true, 0.001).unwrap();
643        assert_eq!(foot.support(), None);
644        assert_eq!(foot.correction(), Vec3::ZERO);
645        assert_eq!(foot.pose().position, Vec3::X * 10.);
646    }
647
648    #[test]
649    fn zero_time_and_rejected_updates_preserve_anchor_and_grace_timer() {
650        let mut foot = planted();
651        foot.update(Vec3::ZERO, None, true, 0.03125).unwrap();
652        let before = foot;
653        for (animated, sample, plant) in [
654            (Vec3::X * 10., None, false),
655            (
656                Vec3::ZERO,
657                Some(FootContact {
658                    support_delta: Vec3::X * 0.1,
659                    ..contact(Vec3::Y * 0.2, 1.)
660                }),
661                true,
662            ),
663        ] {
664            foot.update(animated, sample, plant, 0.).unwrap();
665            assert_same_state(foot, before);
666        }
667        let valid = contact(Vec3::Y * 0.2, 1.);
668        for (animated, sample, dt) in [
669            (Vec3::NAN, Some(valid), 0.01),
670            (Vec3::INFINITY, Some(valid), 0.01),
671            (Vec3::ZERO, Some(valid), f32::NAN),
672            (Vec3::ZERO, Some(valid), f32::INFINITY),
673            (Vec3::ZERO, Some(valid), -0.01),
674            (Vec3::ZERO, Some(valid), 0.251),
675            (
676                Vec3::ZERO,
677                Some(FootContact {
678                    position: Vec3::NAN,
679                    ..valid
680                }),
681                0.01,
682            ),
683            (
684                Vec3::ZERO,
685                Some(FootContact {
686                    normal: Vec3::ZERO,
687                    ..valid
688                }),
689                0.01,
690            ),
691            (
692                Vec3::ZERO,
693                Some(FootContact {
694                    normal: Vec3::NAN,
695                    ..valid
696                }),
697                0.,
698            ),
699            (
700                Vec3::ZERO,
701                Some(FootContact {
702                    support_delta: Vec3::INFINITY,
703                    ..valid
704                }),
705                0.01,
706            ),
707        ] {
708            assert_eq!(
709                foot.update(animated, sample, true, dt),
710                Err(AnimationError::InvalidPose)
711            );
712            assert_same_state(foot, before);
713        }
714        foot.update(Vec3::ZERO, None, true, 0.03125).unwrap();
715        assert_eq!(foot.support(), None);
716    }
717
718    #[test]
719    fn clear_and_reset_discard_normal_anchor_weight_and_grace_history() {
720        let mut foot = planted();
721        foot.update(Vec3::ZERO, Some(contact(Vec3::Y * 0.2, 0.5)), true, 0.1)
722            .unwrap();
723        foot.update(Vec3::ZERO, None, true, 0.03125).unwrap();
724        assert_ne!(foot.pose().normal, Vec3::Y);
725        let before = foot;
726        assert_eq!(foot.reset(Vec3::NAN), Err(AnimationError::InvalidPose));
727        assert_same_state(foot, before);
728        foot.clear();
729        assert_eq!(
730            foot.pose(),
731            FootPose {
732                position: Vec3::ZERO,
733                normal: Vec3::Y,
734                weight: 0.
735            }
736        );
737        assert_eq!(foot.correction(), Vec3::ZERO);
738        assert_eq!(foot.support(), None);
739        // Reset must not let a former support bypass acquisition thresholds.
740        foot.update(Vec3::ZERO, Some(contact(Vec3::Y * 0.2, 0.5)), true, 0.01)
741            .unwrap();
742        assert_eq!(foot.support(), None);
743
744        let location = Vec3::X * 10.;
745        let pose = foot.reset(location).unwrap();
746        assert_eq!(pose.position, location);
747        assert_eq!(pose.normal, Vec3::Y);
748        assert_eq!(pose.weight, 0.);
749        foot.update(
750            location,
751            Some(contact(location + Vec3::Y * 0.2, 1.)),
752            true,
753            0.01,
754        )
755        .unwrap();
756        foot.update(location, None, true, 0.046875).unwrap();
757        assert_eq!(foot.support(), Some(7));
758        assert_eq!(foot.pose().normal, Vec3::Y);
759    }
760
761    #[test]
762    fn extreme_finite_positions_and_support_deltas_keep_output_finite() {
763        let huge = Vec3::splat(f32::MAX);
764        let mut foot = planted();
765        foot.update(huge, Some(contact(-huge, 1.)), true, 0.01)
766            .unwrap();
767        assert_eq!(foot.pose().position, huge);
768        assert_eq!(foot.correction(), Vec3::ZERO);
769        foot.update(huge, Some(contact(huge, 1.)), true, 0.01)
770            .unwrap();
771        let sample = FootContact {
772            support_delta: huge,
773            ..contact(huge, 1.)
774        };
775        let pose = foot.update(huge, Some(sample), true, 0.01).unwrap();
776        assert!(pose.position.is_finite());
777        assert!(pose.normal.is_normalized());
778        assert!((0. ..=1.).contains(&pose.weight));
779        assert_eq!(foot.correction(), Vec3::ZERO);
780    }
781
782    #[test]
783    fn two_bone_extremes_remain_finite_and_bound_unreachable_targets() {
784        for (upper, lower) in [
785            (0.001, 0.001),
786            (1000., 1000.),
787            (0.001, 1000.),
788            (1000., 0.001),
789        ] {
790            let limb = TwoBone { upper, lower };
791            for target in [Vec3::ZERO, Vec3::X * 0.001, Vec3::splat(1e6)] {
792                for pole in [Vec3::ZERO, target, -Vec3::Y] {
793                    let pose = limb.solve(Vec3::ZERO, target, pole).unwrap();
794                    assert!(pose.joint.is_finite());
795                    assert!(pose.end.is_finite());
796                    let reach = pose.end.length();
797                    assert!(reach <= upper + lower + 0.001);
798                    assert!(reach + 0.001 >= (upper - lower).abs());
799                    if target == Vec3::splat(1e6) {
800                        assert!(pose.clamped);
801                    }
802                }
803            }
804        }
805    }
806}