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 "algorithm.hpp"
8#include "../macros.hpp"
9#include "../utility/utility.hpp"
10#include "../time/module.hpp"
11#include <cmath>
12
13
14
15namespace hi::inline v1 {
16
19template<arithmetic T>
20class animator {
21public:
22 using value_type = T;
23
27 animator(std::chrono::nanoseconds animation_duration) noexcept : _animation_duration(animation_duration) {}
28
34 bool update(value_type new_value, utc_nanoseconds current_time) noexcept
35 {
36 if (not initialized) {
37 initialized = true;
38 _old_value = new_value;
39 _new_value = new_value;
40 _start_time = current_time;
41
42 } else if (new_value != _new_value) {
43 _old_value = _new_value;
44 _new_value = new_value;
45 _start_time = current_time;
46 }
47 _current_time = current_time;
48 return is_animating();
49 }
50
53 [[nodiscard]] bool is_animating() const noexcept
54 {
55 hi_axiom(initialized);
56 return progress() < 1.0f;
57 }
58
61 value_type current_value() const noexcept
62 {
63 hi_axiom(initialized);
64 return std::lerp(_old_value, _new_value, progress());
65 }
66
67private:
68 value_type _old_value;
69 value_type _new_value;
70 utc_nanoseconds _start_time;
71 utc_nanoseconds _current_time;
72 std::chrono::nanoseconds _animation_duration;
73 bool initialized = false;
74
75 float progress() const noexcept
76 {
77 using namespace std::chrono_literals;
78
79 hilet dt = _current_time - _start_time;
80 hilet p = static_cast<float>(dt / 1ms) / static_cast<float>(_animation_duration / 1ms);
81 return std::clamp(p, 0.0f, 1.0f);
82 }
83};
84
85} // namespace hi::inline v1
DOXYGEN BUG.
Definition algorithm.hpp:16
constexpr Out narrow_cast(In const &rhs) noexcept
Cast numeric values without loss of precision.
Definition cast.hpp:377
A type that gets animated between two values.
Definition animator.hpp:20
animator(std::chrono::nanoseconds animation_duration) noexcept
Constructor.
Definition animator.hpp:27
bool update(value_type new_value, utc_nanoseconds current_time) noexcept
Update the value and time.
Definition animator.hpp:34
value_type current_value() const noexcept
The interpolated value between start and end value.
Definition animator.hpp:61
bool is_animating() const noexcept
Check if the animation is currently running.
Definition animator.hpp:53