summary refs log tree commit diff stats
path: root/src/input.h
blob: 9f6ff4730887913c283a2bdb2894d369df27e5fe (plain) (blame)
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
#ifndef INPUT_H_0FB34C42
#define INPUT_H_0FB34C42

#include <SDL.h>
#include <vector>

/**
 * Helper class that detects when a key or mouse button is newly pressed.
 */
class Input {
public:

  Input()
  {
    const Uint8* s = SDL_GetKeyboardState(&length_);

    curstate_.assign(s, s + length_);
    prevstate_ = curstate_;

    prevmouse_ = SDL_GetMouseState(&mousePos_.x(), &mousePos_.y());
    prevMousePos_ = mousePos_;
    curmouse_ = prevmouse_;
  }

  void tick()
  {
    const Uint8* keystate = SDL_GetKeyboardState(nullptr);

    prevstate_ = std::move(curstate_);
    curstate_.assign(keystate, keystate + length_);

    prevmouse_ = curmouse_;
    prevMousePos_ = mousePos_;
    curmouse_ = SDL_GetMouseState(&mousePos_.x(), &mousePos_.y());
  }

  bool wasPressed(int scancode) const
  {
    return curstate_.at(scancode) && !prevstate_.at(scancode);
  }

  bool wasClicked(Uint32 mask) const
  {
    return (curmouse_ & SDL_BUTTON(mask)) && !(prevmouse_ & SDL_BUTTON(mask));
  }

  bool wasReleased(Uint32 mask) const
  {
    return !(curmouse_ & SDL_BUTTON(mask)) && (prevmouse_ & SDL_BUTTON(mask));
  }

  bool isClicked(Uint32 mask) const
  {
    return curmouse_ & SDL_BUTTON(mask);
  }

  const vec2i& getMousePos() const
  {
    return mousePos_;
  }

  bool hasMouseMoved() const
  {
    return mousePos_ != prevMousePos_;
  }

private:

  int length_;
  std::vector<Uint8> curstate_;
  std::vector<Uint8> prevstate_;

  Uint32 curmouse_;
  Uint32 prevmouse_;

  vec2i mousePos_;
  vec2i prevMousePos_;
};

#endif /* end of include guard: INPUT_H_0FB34C42 */