Buttons.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "input/Buttons.h"
  2. Buttons::Axis::Axis() : less(0.0f), greater(0.0f), lessIndex(-1), greaterIndex(-1) {
  3. }
  4. Buttons::Buttons(const Window& window) : window(window), dummy(0, "Dummy"), activeController(-1), gamepadToButton(-1) {
  5. }
  6. Button& Buttons::add(int key, const char* name) {
  7. if(buttons.add(key, name)) {
  8. return dummy;
  9. }
  10. return buttons[buttons.getLength() - 1];
  11. }
  12. void Buttons::mapGamepadButton(const Button& button, int mapping) {
  13. gamepadToButton[mapping] = searchButton(button);
  14. }
  15. void Buttons::mapGamepadAxis(const Button& button, float value, int index) {
  16. if(value > 0.0f) {
  17. gamepadAxisToButton[index].greater = value;
  18. gamepadAxisToButton[index].greaterIndex = searchButton(button);
  19. } else {
  20. gamepadAxisToButton[index].less = value;
  21. gamepadAxisToButton[index].lessIndex = searchButton(button);
  22. }
  23. }
  24. void Buttons::tick() {
  25. DownArray down(false);
  26. if(searchForGamepad()) {
  27. checkGamepad(down);
  28. }
  29. for(int i = 0; i < buttons.getLength(); i++) {
  30. buttons[i].tick(window.isKeyDown(buttons[i].key) || down[i]);
  31. }
  32. }
  33. const ButtonList& Buttons::get() const {
  34. return buttons;
  35. }
  36. bool Buttons::searchForGamepad() {
  37. if(activeController != -1) {
  38. return true;
  39. }
  40. for(int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++) {
  41. if(glfwJoystickIsGamepad(i)) {
  42. activeController = i;
  43. return true;
  44. }
  45. }
  46. return false;
  47. }
  48. void Buttons::checkGamepad(DownArray& down) {
  49. GLFWgamepadstate state;
  50. if(!glfwGetGamepadState(activeController, &state)) {
  51. return;
  52. }
  53. for(int i = 0; i <= GLFW_GAMEPAD_BUTTON_LAST; i++) {
  54. if(gamepadToButton[i] != -1 && state.buttons[i]) {
  55. down[gamepadToButton[i]] = true;
  56. }
  57. }
  58. for(int i = 0; i <= GLFW_GAMEPAD_AXIS_LAST; i++) {
  59. if(gamepadAxisToButton[i].greaterIndex != -1 && state.axes[i] > gamepadAxisToButton[i].greater) {
  60. down[gamepadAxisToButton[i].greaterIndex] = true;
  61. } else if(gamepadAxisToButton[i].lessIndex != -1 && state.axes[i] < gamepadAxisToButton[i].less) {
  62. down[gamepadAxisToButton[i].lessIndex] = true;
  63. }
  64. }
  65. }
  66. int Buttons::searchButton(const Button& button) const {
  67. for(int i = 0; i < buttons.getLength(); i++) {
  68. if(&button == &(buttons[i])) {
  69. return i;
  70. }
  71. }
  72. return -1;
  73. }