-
Notifications
You must be signed in to change notification settings - Fork 3
/
Utils.h
100 lines (85 loc) · 2.2 KB
/
Utils.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#pragma once
HRESULT Fail(HRESULT hr, LPCWSTR pszOperation);
std::vector<uint8_t> FileContents(const std::wstring &filename);
LONG WINAPI CrashDumpUnhandledExceptionFilter(EXCEPTION_POINTERS * ExceptionInfo);
template <typename T>
T TileToPixels(T index, T width, T gap = 0)
{
return index * (width + gap);
}
template <typename T>
T lerp(float t, T a, T b)
{
return a + t * (b - a);
}
uint32_t random_uint32();
inline std::wstring to_wstring(const std::string &str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> conv;
return conv.from_bytes(str);
}
inline std::string to_string(const std::wstring &wstr)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> conv;
return conv.to_bytes(wstr);
}
template <typename T>
class EasedValue
{
public:
EasedValue(T init_value, std::chrono::steady_clock::duration duration_ms)
: m_current_value(init_value), m_end_value(init_value), m_duration(duration_ms)
{
}
operator T() const
{
return m_end_value;
}
bool IsAnimating()
{
return easedValue() != m_end_value;
}
void setValue(T new_value, bool instant = false)
{
if (instant)
{
m_current_value = m_end_value = new_value;
}
else
{
m_start_time = std::chrono::steady_clock::now();
m_start_value = m_end_value;
m_end_value = new_value;
}
}
void setRelativeValue(T new_value, bool instant = false)
{
setValue(m_end_value + new_value, instant);
}
T easedValue()
{
if (m_current_value != m_end_value)
{
auto elapsed = std::chrono::steady_clock::now() - m_start_time;
if (elapsed >= m_duration)
m_current_value = m_end_value;
else
{
auto num = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
auto den = std::chrono::duration_cast<std::chrono::milliseconds>(m_duration).count();
auto t = static_cast<float>(num) / den;
auto relative = sinf(1.5707963f * t);
m_current_value = lerp(relative, m_start_value, m_end_value);
}
}
return m_current_value;
}
private:
T m_current_value{};
T m_start_value{};
T m_end_value{};
std::chrono::steady_clock::time_point m_start_time{};
std::chrono::steady_clock::duration m_duration{};
};