-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbutton.cpp
More file actions
75 lines (66 loc) · 2.64 KB
/
button.cpp
File metadata and controls
75 lines (66 loc) · 2.64 KB
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
#include "button.hpp"
namespace input {
buttons get_state(
const klib::time::us delta, const bool flipped, std::array<klib::time::us, 3>& timing,
const std::array<bool, buttons::amount>& raw)
{
// timing parameters for button presses
constexpr static klib::time::us short_press = 20'000;
constexpr static klib::time::us long_press = 700'000;
// return value
std::array<state, buttons::amount> ret = {};
// check if the buttons are still pressed
for (uint32_t i = 0; i < buttons::amount; i++) {
// check for a release of the button
if (!raw[i]) {
// no button press. Check if we had a button press before
if ((timing[i] >= short_press) && (timing[i] != pressed_marker)) {
// we had a button press before. Set as pressed
ret[i] = state::pressed;
// set the timing with the pressed marker to mark
// it as already pressed
timing[i] = pressed_marker;
}
else if (timing[i] == pressed_marker) {
// button is released as it was marked with the pressed
// marker
ret[i] = state::released;
// clear the timing
timing[i] = 0;
}
else {
// no change
ret[i] = state::no_change;
}
}
else {
// we have a button press. Add the delta time for
// the button press
if (timing[i] < long_press) {
timing[i] = timing[i] + delta;
}
// Check if we have passed the threshold for a long press
if ((timing[i] >= long_press) && (timing[i] != pressed_marker)) {
ret[i] = state::long_pressed;
// set the timing with the pressed marker to mark
// it as already pressed
timing[i] = pressed_marker;
}
else {
// user is still pressing set as no change
ret[i] = state::no_change;
}
}
}
// if we are flipped swap the top and buttom buttons
if (flipped) {
return {ret[0], ret[1], ret[2]};
}
else {
return {ret[2], ret[1], ret[0]};
}
}
bool is_pressed(const state button) {
return button == state::long_pressed || button == state::pressed;
}
}