From f3bd7cee24aede7e63eb2d66da92e3f8086a8401 Mon Sep 17 00:00:00 2001 From: Dimitri Sabadie Date: Mon, 15 Apr 2019 00:04:03 +0200 Subject: [PATCH] Add support for polymorphic sampling type. --- Cargo.toml | 3 ++ src/lib.rs | 150 +++++++++++++++++++++++++++++------------------------ 2 files changed, 85 insertions(+), 68 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 67fdab5..d00de1f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,9 @@ std = [] impl-cgmath = ["cgmath"] impl-nalgebra = ["nalgebra"] +[dependencies] +num-traits = "0.2" + [dependencies.nalgebra] version = ">=0.14, <0.17" optional = true diff --git a/src/lib.rs b/src/lib.rs index 44157fa..65d9879 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -107,21 +107,24 @@ #[cfg(feature = "serialization")] extern crate serde; #[cfg(feature = "serialization")] #[macro_use] extern crate serde_derive; -#[cfg(feature = "impl-cgmath")] use cgmath::{InnerSpace, Quaternion, Vector2, Vector3, Vector4}; +#[cfg(feature = "impl-cgmath")] +use cgmath::{ + BaseFloat, InnerSpace, Quaternion, Vector2, Vector3, Vector4 +}; #[cfg(feature = "impl-nalgebra")] use nalgebra as na; #[cfg(feature = "impl-nalgebra")] use nalgebra::core::{DimName, DefaultAllocator, Scalar}; #[cfg(feature = "impl-nalgebra")] use nalgebra::core::allocator::Allocator; #[cfg(feature = "std")] use std::cmp::Ordering; -#[cfg(feature = "std")] use std::f32::consts; #[cfg(feature = "std")] use std::ops::{Add, Div, Mul, Sub}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; #[cfg(not(feature = "std"))] use core::cmp::Ordering; -#[cfg(not(feature = "std"))] use core::f32::consts; #[cfg(not(feature = "std"))] use core::ops::{Add, Div, Mul, Sub}; +use num_traits::{Float, FloatConst}; + /// A spline control point. /// /// This type associates a value at a given interpolation parameter value. It also contains an @@ -130,23 +133,19 @@ #[derive(Copy, Clone, Debug)] #[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))] #[cfg_attr(feature = "serialization", serde(rename_all = "snake_case"))] -pub struct Key { +pub struct Key { /// Interpolation parameter at which the [`Key`] should be reached. - pub t: f32, + pub t: T, /// Held value. - pub value: T, + pub value: V, /// Interpolation mode. - pub interpolation: Interpolation + pub interpolation: Interpolation } -impl Key { +impl Key { /// Create a new key. - pub fn new(t: f32, value: T, interpolation: Interpolation) -> Self { - Key { - t: t, - value: value, - interpolation: interpolation - } + pub fn new(t: T, value: V, interpolation: Interpolation) -> Self { + Key { t, value, interpolation } } } @@ -154,7 +153,7 @@ impl Key { #[derive(Copy, Clone, Debug)] #[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))] #[cfg_attr(feature = "serialization", serde(rename_all = "snake_case"))] -pub enum Interpolation { +pub enum Interpolation { /// Hold a [`Key`] until the time passes the normalized step threshold, in which case the next /// key is used. /// @@ -162,7 +161,7 @@ pub enum Interpolation { /// between the two keys; the second key will be in used afterwards. If you set it to `1.0`, the /// first key will be kept until the next key. Set it to `0.` and the first key will never be /// used.* - Step(f32), + Step(T), /// Linear interpolation between a key and the next one. Linear, /// Cosine interpolation between a key and the next one. @@ -171,7 +170,7 @@ pub enum Interpolation { CatmullRom } -impl Default for Interpolation { +impl Default for Interpolation { /// `Interpolation::Linear` is the default. fn default() -> Self { Interpolation::Linear @@ -181,12 +180,12 @@ impl Default for Interpolation { /// Spline curve used to provide interpolation between control points (keys). #[derive(Debug, Clone)] #[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))] -pub struct Spline(Vec>); +pub struct Spline(Vec>); -impl Spline { +impl Spline { /// Create a new spline out of keys. The keys don’t have to be sorted even though it’s recommended /// to provide ascending sorted ones (for performance purposes). - pub fn from_vec(mut keys: Vec>) -> Self { + pub fn from_vec(mut keys: Vec>) -> Self where T: PartialOrd { keys.sort_by(|k0, k1| k0.t.partial_cmp(&k1.t).unwrap_or(Ordering::Less)); Spline(keys) @@ -199,12 +198,12 @@ impl Spline { /// /// It’s valid to use any iterator that implements `Iterator>`. However, you should /// use `Spline::from_vec` if you are passing a `Vec<_>`. This will remove dynamic allocations. - pub fn from_iter(iter: I) -> Self where I: Iterator> { + pub fn from_iter(iter: I) -> Self where I: Iterator>, T: PartialOrd { Self::from_vec(iter.collect()) } /// Retrieve the keys of a spline. - pub fn keys(&self) -> &[Key] { + pub fn keys(&self) -> &[Key] { &self.0 } @@ -222,7 +221,7 @@ impl Spline { /// sampling impossible. For instance, `Interpolate::CatmullRom` requires *four* keys. If you’re /// near the beginning of the spline or its end, ensure you have enough keys around to make the /// sampling. - pub fn sample(&self, t: f32) -> Option where T: Interpolate { + pub fn sample(&self, t: T) -> Option where V: Interpolate, T: Float { let keys = &self.0; let i = search_lower_cp(keys, t)?; let cp0 = &keys[i]; @@ -244,18 +243,7 @@ impl Spline { Interpolation::Cosine => { let cp1 = &keys[i+1]; let nt = normalize_time(t, cp0, cp1); - let cos_nt = { - #[cfg(feature = "std")] - { - (1. - f32::cos(nt * consts::PI)) * 0.5 - } - - #[cfg(not(feature = "std"))] - { - use core::intrinsics::cosf32; - unsafe { (1. - cosf32(nt * consts::PI)) * 0.5 } - } - }; + let cos_nt = (1. - (nt * T::PI).cos()) * 0.5; Some(Interpolate::lerp(cp0.value, cp1.value, cos_nt)) } @@ -310,13 +298,13 @@ impl Spline { /// Iterator over spline keys. /// /// This iterator type assures you to iterate over sorted keys. -pub struct Iter<'a, T> where T: 'a { - anim_param: &'a Spline, +pub struct Iter<'a, T, V> where T: 'a, V: 'a { + anim_param: &'a Spline, i: usize } -impl<'a, T> Iterator for Iter<'a, T> { - type Item = &'a Key; +impl<'a, T, V> Iterator for Iter<'a, T, V> { + type Item = &'a Key; fn next(&mut self) -> Option { let r = self.anim_param.0.get(self.i); @@ -329,9 +317,9 @@ impl<'a, T> Iterator for Iter<'a, T> { } } -impl<'a, T> IntoIterator for &'a Spline { - type Item = &'a Key; - type IntoIter = Iter<'a, T>; +impl<'a, T, V> IntoIterator for &'a Spline { + type Item = &'a Key; + type IntoIter = Iter<'a, T, V>; fn into_iter(self) -> Self::IntoIter { Iter { @@ -343,18 +331,22 @@ impl<'a, T> IntoIterator for &'a Spline { /// Keys that can be interpolated in between. Implementing this trait is required to perform /// sampling on splines. -pub trait Interpolate: Copy { +/// +/// `T` is the variable used to sample with. Typical implementations use `f32` or `f64`, but you’re +/// free to use the ones you like. +pub trait Interpolate: Copy where T: Copy + Float { /// Linear interpolation. - fn lerp(a: Self, b: Self, t: f32) -> Self; + fn lerp(a: Self, b: Self, t: T) -> Self; + /// Cubic hermite interpolation. /// /// Default to `Self::lerp`. - fn cubic_hermite(_: (Self, f32), a: (Self, f32), b: (Self, f32), _: (Self, f32), t: f32) -> Self { + fn cubic_hermite(_: (Self, T), a: (Self, T), b: (Self, T), _: (Self, T), t: T) -> Self { Self::lerp(a.0, b.0, t) } } -impl Interpolate for f32 { +impl Interpolate for f32 { fn lerp(a: Self, b: Self, t: f32) -> Self { a * (1. - t) + b * t } @@ -364,42 +356,58 @@ impl Interpolate for f32 { } } -#[cfg(feature = "impl-cgmath")] -impl Interpolate for Vector2 { +impl Interpolate for f64 { fn lerp(a: Self, b: Self, t: f32) -> Self { + a * (1. - t as f64) + b * t as f64 + } + + fn cubic_hermite( + (x, tx): (Self, f32), + (a, ta): (Self, f32), + (b, tb): (Self, f32), + (y, ty): (Self, f32), + t: f32 + ) -> Self { + cubic_hermite((x, tx as f64), (a, ta as f64), (b, tb as f64), (y, ty as f64), t as f64) + } +} + +#[cfg(feature = "impl-cgmath")] +impl Interpolate for Vector2 where T: BaseFloat { + fn lerp(a: Self, b: Self, t: T) -> Self { a.lerp(b, t) } - fn cubic_hermite(x: (Self, f32), a: (Self, f32), b: (Self, f32), y: (Self, f32), t: f32) -> Self { + fn cubic_hermite(x: (Self, T), a: (Self, T), b: (Self, T), y: (Self, T), t: T) -> Self { cubic_hermite(x, a, b, y, t) } } #[cfg(feature = "impl-cgmath")] -impl Interpolate for Vector3 { - fn lerp(a: Self, b: Self, t: f32) -> Self { +impl Interpolate for Vector3 where T: BaseFloat { + fn lerp(a: Self, b: Self, t: T) -> Self { a.lerp(b, t) } - fn cubic_hermite(x: (Self, f32), a: (Self, f32), b: (Self, f32), y: (Self, f32), t: f32) -> Self { + fn cubic_hermite(x: (Self, T), a: (Self, T), b: (Self, T), y: (Self, T), t: T) -> Self { cubic_hermite(x, a, b, y, t) } } #[cfg(feature = "impl-cgmath")] -impl Interpolate for Vector4 { - fn lerp(a: Self, b: Self, t: f32) -> Self { +impl Interpolate for Vector4 where T: BaseFloat { + fn lerp(a: Self, b: Self, t: T) -> Self { a.lerp(b, t) } - fn cubic_hermite(x: (Self, f32), a: (Self, f32), b: (Self, f32), y: (Self, f32), t: f32) -> Self { + fn cubic_hermite(x: (Self, T), a: (Self, T), b: (Self, T), y: (Self, T), t: T) -> Self { cubic_hermite(x, a, b, y, t) } } #[cfg(feature = "impl-cgmath")] -impl Interpolate for Quaternion { - fn lerp(a: Self, b: Self, t: f32) -> Self { +impl Interpolate for Quaternion where T: BaseFloat { + fn lerp(a: Self, b: Self, t: T) -> Self { a.nlerp(b, t) } } @@ -460,32 +468,38 @@ impl Interpolate for na::Vector6 { } } -// Default implementation of Interpolate::cubic_hermit. -pub(crate) fn cubic_hermite(x: (T, f32), a: (T, f32), b: (T, f32), y: (T, f32), t: f32) -> T - where T: Copy + Add + Sub + Mul + Div { - // time stuff - let t2 = t * t; +// Default implementation of Interpolate::cubic_hermite. +// +// `V` is the value being interpolated. `T` is the sampling value (also sometimes called time). +pub(crate) fn cubic_hermite(x: (V, T), a: (V, T), b: (V, T), y: (V, T), t: T) -> V +where V: Copy + Add + Sub + Mul + Div, + T: Mul + Mul + Add + Add + Sub { + // sampler stuff + let t2 = t* t; let t3 = t2 * t; - let two_t3 = 2. * t3; - let three_t2 = 3. * t2; + let two_t3 = t3 * 2.; + let three_t2 = t2 * 3.; // tangents let m0 = (b.0 - x.0) / (b.1 - x.1); let m1 = (y.0 - a.0) / (y.1 - a.1); - a.0 * (two_t3 - three_t2 + 1.) + m0 * (t3 - 2. * t2 + t) + b.0 * (-two_t3 + three_t2) + m1 * (t3 - t2) + a.0 * (two_t3 - three_t2 + 1.) + m0 * (t3 - t2 * 2. + t) + b.0 * (three_t2 - two_t3) + m1 * (t3 - t2) } // Normalize a time ([0;1]) given two control points. #[inline(always)] -pub(crate) fn normalize_time(t: f32, cp: &Key, cp1: &Key) -> f32 { +pub(crate) fn normalize_time( + t: T, + cp: &Key, + cp1: &Key +) -> T where T: PartialEq + Sub + Div { assert!(cp1.t != cp.t, "overlapping keys"); - (t - cp.t) / (cp1.t - cp.t) } // Find the lower control point corresponding to a given time. -fn search_lower_cp(cps: &[Key], t: f32) -> Option { +fn search_lower_cp(cps: &[Key], t: T) -> Option where T: PartialOrd { let mut i = 0; let len = cps.len();