]> Dogcows Code - chaz/yoink/blob - src/Moof/Interpolator.hh
reformatting
[chaz/yoink] / src / Moof / Interpolator.hh
1
2 /*] Copyright (c) 2009-2010, Charles McGarvey [**************************
3 **] All rights reserved.
4 *
5 * vi:ts=4 sw=4 tw=75
6 *
7 * Distributable under the terms and conditions of the 2-clause BSD license;
8 * see the file COPYING for a complete text of the license.
9 *
10 **************************************************************************/
11
12 #ifndef _MOOF_INTERPOLATOR_HH_
13 #define _MOOF_INTERPOLATOR_HH_
14
15 #include <Moof/Log.hh>
16 #include <Moof/Math.hh>
17
18
19 namespace Mf {
20
21
22 namespace Interp {
23
24 typedef enum
25 {
26 STOP = 0,
27 REPEAT = 1,
28 OSCILLATE = 2
29 } Mode;
30
31 } // namespace Interp
32
33
34 template <class T>
35 class Interpolator : public T
36 {
37 public:
38
39 Interpolator(Scalar t = 1.0, Interp::Mode mode = Interp::STOP)
40 {
41 reset(t, mode);
42 }
43
44 void reset(Scalar t = 1.0, Interp::Mode mode = Interp::STOP)
45 {
46 mAlpha = 0.0;
47 mScale = 1.0 / t;
48 mMode = mode;
49 mIsDone = false;
50 }
51
52 void update(Scalar t, Scalar dt)
53 {
54 if (!mIsDone)
55 {
56 mPrevState = T::getValue();
57 mAlpha += dt * mScale;
58 clamp();
59 if (mPrevState == T::calculate(mAlpha)) mIsDone = true;
60 }
61 }
62
63 typename T::Type getState(Scalar alpha) const
64 {
65 return cml::lerp(mPrevState, T::getValue(), alpha);
66 }
67
68 bool isDone() const
69 {
70 return mIsDone;
71 }
72
73 private:
74
75 void clamp()
76 {
77 if (mAlpha > 1.0)
78 {
79 switch (mMode)
80 {
81 case Interp::STOP:
82 mAlpha = SCALAR(1.0);
83 break;
84 case Interp::REPEAT:
85 mAlpha -= SCALAR(1.0);
86 break;
87 case Interp::OSCILLATE:
88 mAlpha = SCALAR(2.0) - mAlpha;
89 mScale = -mScale;
90 break;
91 }
92 }
93 else if (mAlpha < 0.0)
94 {
95 switch (mMode)
96 {
97 case Interp::STOP:
98 mAlpha = SCALAR(0.0);
99 break;
100 case Interp::REPEAT:
101 mAlpha += SCALAR(1.0);
102 break;
103 case Interp::OSCILLATE:
104 mAlpha = -mAlpha;
105 mScale = -mScale;
106 break;
107 }
108 }
109 }
110
111 Scalar mAlpha;
112 Scalar mScale;
113 Interp::Mode mMode;
114 bool mIsDone;
115
116 typename T::Type mPrevState;
117 };
118
119
120 template <typename T = Scalar>
121 class Linear
122 {
123 public:
124
125 typedef T Type;
126
127 void init(const Type& a, const Type& b)
128 {
129 mStart = a;
130 mFinish = b;
131 }
132
133 const Type& calculate(Scalar alpha)
134 {
135 mState = cml::lerp(mStart, mFinish, alpha);
136 return mState;
137 }
138
139 const Type& getValue() const
140 {
141 return mState;
142 }
143
144 private:
145
146 Type mState;
147 Type mStart;
148 Type mFinish;
149 };
150
151
152 typedef Interpolator< Linear<Scalar> > Lerp;
153
154
155 } // namespace Mf
156
157 #endif // _MOOF_INTERPOLATOR_HH_
158
This page took 0.038005 seconds and 4 git commands to generate.