Cogs.Core
Interpolator.h
1#pragma once
2
3#include "EasingFn.h"
4#include "Interpolation.hpp"
5
6#include "../Platform/Timer.h"
7
8#include <glm/vec3.hpp>
9#include <glm/ext/quaternion_float.hpp>
10#include <glm/ext/quaternion_common.hpp>
11
12namespace Cogs {
13 template<typename T> inline T interpolateFn(const T& s, const T& d, float t) {
14 return Interpolation::linear(s, d, t);
15 }
16
17 template<> inline glm::quat interpolateFn<glm::quat>(const glm::quat& s, const glm::quat& d, float t) {
18 return glm::slerp(s, d, t);
19 }
20
21 template<typename T> class Interpolator {
22 public:
23 Interpolator(T& destination) : mDestination(destination), mTarget(destination) {
24 }
25
26 Interpolator(T& destination, const T& target, EasingFn::Ptr fn, float duration) : Interpolator(destination) {
27 setTarget(target, fn, duration);
28 }
29
30 void setTarget(const T& target, EasingFn::Ptr fn, float duration) {
31 if (fn && (duration > 0.0f)) {
32 mStart = mDestination;
33 mTarget = target;
34 mTimer.start();
35 mFunction = fn;
36 mDuration = duration;
37 }
38 else {
39 mDestination = target;
40 mTarget = target;
41 mFunction = nullptr;
42 }
43 }
44
45 void snapToTarget() {
46 if (mFunction) {
47 mDestination = mTarget;
48 mFunction = nullptr;
49 }
50 }
51
52 bool process() {
53 if (mFunction) {
54 float t = static_cast<float>(mTimer.elapsedSeconds()) / mDuration;
55
56 if (t < 1.0f) {
57 mDestination = interpolateFn(mStart, mTarget, mFunction(t));
58 }
59 else {
60 mDestination = mTarget;
61 mFunction = nullptr;
62 }
63 return true;
64 }
65 return false;
66 }
67
68 void cancel() { mFunction = nullptr; }
69 bool isProcessing() const { return mFunction; }
70
71 float getTime() { return isProcessing() ? static_cast<float>(mTimer.elapsedSeconds()) : 1.0f; }
72 T getTarget() const { return mTarget; }
73 T getValue() const { return mDestination; }
74
75 private:
76 T& mDestination;
77 T mStart;
78 T mTarget;
79 Timer mTimer;
80 EasingFn::Ptr mFunction = nullptr;
81 float mDuration = 0.0f;
82 };
83}
84
Old timer class.
Definition: Timer.h:37
Contains all Cogs related functionality.
Definition: FieldSetter.h:23