comparison src/th06/interpolator.rs @ 642:9e40bd5cc26d

Move interpolators in another module.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Sun, 07 Jul 2019 12:19:50 +0200
parents
children 6020e33d4fc4
comparison
equal deleted inserted replaced
641:a58103f2f264 642:9e40bd5cc26d
1 //! Animation runner.
2
3 #[derive(Debug, Clone, Copy, PartialEq)]
4 pub(crate) enum Formula {
5 Linear,
6 Power2,
7 InvertPower2,
8 }
9
10 impl Formula {
11 fn apply(&self, x: f32) -> f32 {
12 match self {
13 Formula::Linear => x,
14 Formula::Power2 => x * x,
15 Formula::InvertPower2 => 2. * x - x * x,
16 }
17 }
18 }
19
20 macro_rules! generate_interpolator {
21 ($name:ident, $n:tt) => {
22 #[derive(Debug, Clone)]
23 pub(crate) struct $name<T> {
24 start_values: [T; $n],
25 end_values: [T; $n],
26 start_frame: u16,
27 end_frame: u16,
28 formula: Formula,
29 }
30
31 impl<T> $name<T>
32 where f32: From<T>,
33 T: From<f32>,
34 T: std::ops::Sub<Output = T>,
35 T: std::ops::Add<Output = T>,
36 T: Copy,
37 T: Default,
38 {
39 pub fn new(start_values: [T; $n], start_frame: u16, end_values: [T; $n], end_frame: u16, formula: Formula) -> $name<T> {
40 $name {
41 start_values,
42 end_values,
43 start_frame,
44 end_frame,
45 formula,
46 }
47 }
48
49 // XXX: Make it return [T; $n] instead, we don’t want to only do f32 here.
50 pub fn values(&self, frame: u16) -> [f32; $n] {
51 if frame + 1 >= self.end_frame {
52 // XXX: skip the last interpolation step.
53 // This bug is replicated from the original game.
54 //self.start_frame = self.end_frame;
55 //self.end_values
56 let mut values: [f32; $n] = [Default::default(); $n];
57 for (i, value) in self.end_values.iter().enumerate() {
58 values[i] = f32::from(*value);
59 }
60 values
61 } else {
62 let mut coeff = (frame - self.start_frame) as f32 / (self.end_frame - self.start_frame) as f32;
63 coeff = self.formula.apply(coeff);
64 let mut values: [f32; $n] = [Default::default(); $n];
65 for (i, (start, end)) in self.start_values.iter().zip(&self.end_values).enumerate() {
66 values[i] = f32::from(*start + T::from(coeff * f32::from(*end - *start)));
67 }
68 values
69 }
70 }
71 }
72 };
73 }
74
75 generate_interpolator!(Interpolator1, 1);
76 generate_interpolator!(Interpolator2, 2);
77 generate_interpolator!(Interpolator3, 3);