1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
//! Linear interpolation and extrapolation traits.
#![doc(html_root_url = "https://coriolinus.github.io/lerp-rs/")]

use num_traits::{Float, One, Zero};
use std::iter;
use std::iter::{Chain, Once, Skip};
use std::ops::{Add, Mul};

/// Types which are amenable to linear interpolation and extrapolation.
///
/// This is mainly intended to be useful for complex
/// numbers, vectors, and other types which may be multiplied by a
/// scalar while retaining their own type.
///
/// It's automatically implemented
/// for all `T: Add<Output = T> + Mul<F, Output = T>`.
pub trait Lerp<F> {
    /// Interpolate and extrapolate between `self` and `other` using `t` as the parameter.
    ///
    /// At `t == 0.0`, the result is equal to `self`.
    /// At `t == 1.0`, the result is equal to `other`.
    /// At all other points, the result is a mix of `self` and `other`, proportional to `t`.
    ///
    /// `t` is unbounded, so extrapolation and negative interpolation are no problem.
    ///
    /// # Examples
    ///
    /// Basic lerping on floating points:
    ///
    /// ```
    /// use lerp::Lerp;
    ///
    /// let four_32 = 3.0_f32.lerp(5.0, 0.5);
    /// assert_eq!(four_32, 4.0);
    /// let four_64 = 3.0_f64.lerp(5.0, 0.5);
    /// assert_eq!(four_64, 4.0);
    /// ```
    ///
    /// Extrapolation:
    ///
    /// ```
    /// # use lerp::Lerp;
    /// assert_eq!(3.0.lerp(4.0, 2.0), 5.0);
    /// ```
    ///
    /// Negative extrapolation:
    ///
    /// ```
    /// # use lerp::Lerp;
    /// assert_eq!(3.0.lerp(4.0, -1.0), 2.0);
    /// ```
    ///
    /// Reverse interpolation:
    ///
    /// ```
    /// # use lerp::Lerp;
    /// assert_eq!(5.0.lerp(3.0, 0.5), 4.0);
    /// ```
    fn lerp(self, other: Self, t: F) -> Self;

    /// Interpolate between `self` and `other` precisely per the `lerp` function, bounding `t`
    /// in the inclusive range [0..1].
    ///
    /// # Examples
    ///
    /// Bounding on numbers greater than one:
    ///
    /// ```
    /// # use lerp::Lerp;
    /// assert_eq!(3.0.lerp_bounded(4.0, 2.0), 4.0);
    /// ```
    ///
    /// Bounding on numbers less than zero:
    ///
    /// ```
    /// # use lerp::Lerp;
    /// assert_eq!(3.0.lerp_bounded(5.0, -2.0), 3.0);
    /// ```
    fn lerp_bounded(self, other: Self, t: F) -> Self
    where
        Self: Sized,
        F: PartialOrd + Copy + Zero + One,
    {
        let t = match t {
            t if t < F::zero() => F::zero(),
            t if t > F::one() => F::one(),
            t => t,
        };
        self.lerp(other, t)
    }
}

/// Types which can construct a lerping iterator from one point to another
/// over a set number of steps.
///
/// This is automatically implemented for all `T: Lerp<f64> + Sized`.
pub trait LerpIter {
    /// Create an iterator which lerps from `self` to `other`.
    ///
    /// The iterator is half-open: it includes `self`, but not `other`
    ///
    /// # Example
    ///
    /// ```
    /// use lerp::LerpIter;
    ///
    /// // lerp between 3 and 5, collecting two items
    /// let items: Vec<_> = 3.0_f64.lerp_iter(5.0, 4).collect();
    /// assert_eq!(vec![3.0, 3.5, 4.0, 4.5], items);
    /// ```
    fn lerp_iter(self, other: Self, steps: usize) -> LerpIterator<Self>
    where
        Self: Sized;

    /// Create an iterator which lerps from `self` to `other`.
    ///
    /// The iterator is closed: it returns both `self` and `other`.
    ///
    /// Note when `steps == 1`, `other` is returned instead of `self`.
    ///
    /// # Example
    ///
    /// ```
    /// use lerp::LerpIter;
    ///
    /// assert_eq!(vec![3.0, 5.0], 3.0_f64.lerp_iter_closed(5.0, 2).collect::<Vec<f64>>());
    /// ```
    fn lerp_iter_closed(
        self,
        other: Self,
        steps: usize,
    ) -> Skip<Chain<LerpIterator<Self>, Once<Self>>>
    where
        Self: Copy,
        LerpIterator<Self>: Iterator<Item = Self>,
    {
        // reduce the number of times we consume the sub-iterator,
        // because we unconditionally add an element to the end.
        if steps == 0 {
            LerpIterator::new(self, other, steps)
                .chain(iter::once(other))
                .skip(1)
        } else {
            LerpIterator::new(self, other, steps - 1)
                .chain(iter::once(other))
                .skip(0)
        }
    }
}

/// Default, generic implementation of Lerp.
///
/// Note that due to the implementation details, LerpIterator is only actually
/// an iterator for those types `T` which fit the constraint `Mul<f64, Output = T>`.
/// This means that though you can use the `lerp` method on f32s, it will not work to
/// iterate over the results of calling `lerp_iter` on an f32. Instead, up-cast
/// your f32 as an f64 before calling: `(example_f32 as f64).lerp_iter(...)`.
///
/// This default implementation is mainly intended to be useful for complex
/// numbers, vectors, and other types which may be multiplied by a
/// scalar while retaining their own type.
impl<T, F> Lerp<F> for T
where
    T: Add<Output = T> + Mul<F, Output = T>,
    F: Float,
{
    fn lerp(self, other: T, t: F) -> T {
        self * (F::one() - t) + other * t
    }
}

impl<T> LerpIter for T
where
    T: Lerp<f64> + Sized,
{
    fn lerp_iter(self, other: T, steps: usize) -> LerpIterator<T> {
        LerpIterator::new(self, other, steps)
    }
}

/// An iterator across a range defined by its endpoints and the number of intermediate steps.
pub struct LerpIterator<T> {
    begin: T,
    end: T,
    steps: usize,
    current_step: usize,
}

impl<T> LerpIterator<T> {
    fn new(begin: T, end: T, steps: usize) -> LerpIterator<T> {
        LerpIterator {
            begin,
            end,
            steps,
            current_step: 0,
        }
    }
}

impl<T> Iterator for LerpIterator<T>
where
    T: Lerp<f64> + Copy,
{
    type Item = T;

    fn next(&mut self) -> Option<T> {
        if self.current_step >= self.steps {
            None
        } else {
            let t = self.current_step as f64 / self.steps as f64;
            self.current_step += 1;
            Some(self.begin.lerp(self.end, t))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = if self.current_step >= self.steps {
            0
        } else {
            self.steps - self.current_step
        };
        (remaining, Some(remaining))
    }
}

impl<T> ExactSizeIterator for LerpIterator<T> where T: Lerp<f64> + Copy {}

#[cfg(feature = "derive")]
#[allow(unused_imports)]
#[macro_use]
extern crate lerp_derive;

#[cfg(feature = "derive")]
#[doc(hidden)]
pub use lerp_derive::*;

#[cfg(all(test, feature = "derive"))]
mod test_derive {
    use super::Lerp;
    use std::fmt::Debug;

    // Helper when working with floats to "round" them, so we can compare them better
    fn round(d: &dyn Debug) -> String {
        format!("{:.1?}", d)
    }

    #[test]
    fn tuple() {
        #[derive(PartialEq, Debug, Lerp)]
        struct Data(f64, f64);

        assert_eq!(
            round(&Data(0.0, 1.0).lerp(Data(1.0, 0.0), 0.5)),
            round(&Data(0.5, 0.5))
        );
        assert_eq!(
            round(&Data(0.0, 1.0).lerp(Data(1.0, 0.0), 0.9)),
            round(&Data(0.9, 0.1))
        );
    }

    #[test]
    fn named() {
        #[derive(PartialEq, Debug, Lerp)]
        struct Data {
            a: f32,
            b: f32,
        };

        assert_eq!(
            round(&Data { a: 0.0, b: 1.0 }.lerp(Data { a: 1.0, b: 0.0 }, 0.5)),
            round(&Data { a: 0.5, b: 0.5 })
        );
        assert_eq!(
            round(&Data { a: 0.0, b: 1.0 }.lerp(Data { a: 1.0, b: 0.0 }, 0.9)),
            round(&Data { a: 0.9, b: 0.1 })
        );
    }

    #[test]
    fn manual() {
        #[derive(PartialEq, Debug)]
        struct Data {
            a: f64,
            b: f64,
        };

        impl Lerp<f64> for Data {
            fn lerp(self, other: Self, t: f64) -> Self {
                Self {
                    a: self.a.lerp(other.a, t),
                    b: self.b.lerp(other.b, t),
                }
            }
        }

        assert_eq!(
            round(&Data { a: 0.0, b: 1.0 }.lerp(Data { a: 1.0, b: 0.0 }, 0.5)),
            round(&Data { a: 0.5, b: 0.5 })
        );
        assert_eq!(
            round(&Data { a: 0.0, b: 1.0 }.lerp(Data { a: 1.0, b: 0.0 }, 0.9)),
            round(&Data { a: 0.9, b: 0.1 })
        );
    }
}