Input.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #include "anki/core/App.h"
  2. #include "anki/core/Logger.h"
  3. #include "anki/core/Globals.h"
  4. #include "anki/input/Input.h"
  5. #include <SDL/SDL.h>
  6. namespace anki {
  7. //==============================================================================
  8. void Input::init()
  9. {
  10. ANKI_INFO("Initializing input...");
  11. warpMouseFlag = false;
  12. hideCursor = true;
  13. reset();
  14. ANKI_INFO("Input initialized");
  15. }
  16. //==============================================================================
  17. void Input::reset(void)
  18. {
  19. memset(&keys[0], 0, keys.size() * sizeof(short));
  20. memset(&mouseBtns[0], 0, mouseBtns.size() * sizeof(short));
  21. mousePosNdc = Vec2(0.0);
  22. mouseVelocity = Vec2(0.0);
  23. }
  24. //==============================================================================
  25. void Input::handleEvents()
  26. {
  27. if(hideCursor)
  28. {
  29. SDL_ShowCursor(SDL_DISABLE);
  30. }
  31. else
  32. {
  33. SDL_ShowCursor(SDL_ENABLE);
  34. }
  35. // add the times a key is bying pressed
  36. for(uint x=0; x<keys.size(); x++)
  37. {
  38. if(keys[x]) ++keys[x];
  39. }
  40. for(int x=0; x<8; x++)
  41. {
  42. if(mouseBtns[x]) ++mouseBtns[x];
  43. }
  44. mouseVelocity = Vec2(0.0);
  45. SDL_Event event_;
  46. while(SDL_PollEvent(&event_))
  47. {
  48. switch(event_.type)
  49. {
  50. case SDL_KEYDOWN:
  51. keys[event_.key.keysym.scancode] = 1;
  52. break;
  53. case SDL_KEYUP:
  54. keys[event_.key.keysym.scancode] = 0;
  55. break;
  56. case SDL_MOUSEBUTTONDOWN:
  57. mouseBtns[event_.button.button] = 1;
  58. break;
  59. case SDL_MOUSEBUTTONUP:
  60. mouseBtns[event_.button.button] = 0;
  61. break;
  62. case SDL_MOUSEMOTION:
  63. {
  64. Vec2 prevMousePosNdc(mousePosNdc);
  65. mousePos.x() = event_.button.x;
  66. mousePos.y() = event_.button.y;
  67. mousePosNdc.x() = (2.0 * mousePos.x()) /
  68. (float)AppSingleton::get().getWindowWidth() - 1.0;
  69. mousePosNdc.y() = 1.0 - (2.0 * mousePos.y()) /
  70. (float)AppSingleton::get().getWindowHeight();
  71. if(warpMouseFlag)
  72. {
  73. // the SDL_WarpMouse pushes an event in the event queue.
  74. // This check is so we wont process the event of the
  75. // SDL_WarpMouse function
  76. if(mousePosNdc == Vec2(0.0))
  77. {
  78. break;
  79. }
  80. uint w = AppSingleton::get().getWindowWidth();
  81. uint h = AppSingleton::get().getWindowHeight();
  82. SDL_WarpMouse(w / 2, h / 2);
  83. }
  84. mouseVelocity = mousePosNdc - prevMousePosNdc;
  85. break;
  86. }
  87. case SDL_QUIT:
  88. AppSingleton::get().quit(1);
  89. break;
  90. }
  91. }
  92. }
  93. } // end namespace