HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
animator.hpp
1// Copyright Take Vos 2021.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "chrono.hpp"
8#include "algorithm.hpp"
9#include "concepts.hpp"
10#include <cmath>
11
12namespace hi::inline v1 {
13
16template<arithmetic T>
17class animator {
18public:
19 using value_type = T;
20
24 animator(std::chrono::nanoseconds animation_duration) noexcept : _animation_duration(animation_duration) {}
25
31 bool update(value_type new_value, utc_nanoseconds current_time) noexcept
32 {
33 if (not initialized) {
34 initialized = true;
35 _old_value = new_value;
36 _new_value = new_value;
37 _start_time = current_time;
38
39 } else if (new_value != _new_value) {
40 _old_value = _new_value;
41 _new_value = new_value;
42 _start_time = current_time;
43 }
44 _current_time = current_time;
45 return is_animating();
46 }
47
50 [[nodiscard]] bool is_animating() const noexcept
51 {
52 hi_axiom(initialized);
53 return progress() < 1.0f;
54 }
55
58 value_type current_value() const noexcept
59 {
60 hi_axiom(initialized);
61 return std::lerp(_old_value, _new_value, progress());
62 }
63
64private:
65 value_type _old_value;
66 value_type _new_value;
67 utc_nanoseconds _start_time;
68 utc_nanoseconds _current_time;
69 std::chrono::nanoseconds _animation_duration;
70 bool initialized = false;
71
72 float progress() const noexcept
73 {
74 using namespace std::chrono_literals;
75
76 hilet dt = _current_time - _start_time;
77 hilet p = static_cast<float>(dt / 1ms) / static_cast<float>(_animation_duration / 1ms);
78 return std::clamp(p, 0.0f, 1.0f);
79 }
80};
81
82} // namespace hi::inline v1
#define hi_axiom(expression)
Specify an axiom; an expression that is true.
Definition assert.hpp:133
#define hilet
Invariant should be the default for variables.
Definition utility.hpp:23
DOXYGEN BUG.
Definition algorithm.hpp:15
A type that gets animated between two values.
Definition animator.hpp:17
animator(std::chrono::nanoseconds animation_duration) noexcept
Constructor.
Definition animator.hpp:24
bool update(value_type new_value, utc_nanoseconds current_time) noexcept
Update the value and time.
Definition animator.hpp:31
value_type current_value() const noexcept
The interpolated value between start and end value.
Definition animator.hpp:58
bool is_animating() const noexcept
Check if the animation is currently running.
Definition animator.hpp:50