coral_input.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "coral_input.h"
  2. #include "coral_window.h"
  3. #include <iostream>
  4. #include <algorithm>
  5. using namespace coral_3d;
  6. std::vector<coral_input*> coral_input::instances_;
  7. coral_input::coral_input()
  8. {
  9. // Register this class
  10. coral_input::instances_.emplace_back(this);
  11. }
  12. coral_input::~coral_input()
  13. {
  14. // Unregister this class
  15. instances_.erase(std::remove(instances_.begin(), instances_.end(), this),
  16. instances_.end());
  17. }
  18. void coral_input::initialize(GLFWwindow* ptr_window)
  19. {
  20. glfwSetKeyCallback(ptr_window, coral_input::callback);
  21. }
  22. void coral_input::update_key_state(int key, int state)
  23. {
  24. for (auto& key_pair : callbacks_)
  25. {
  26. // If pressed key has registered callbacks
  27. if(key_pair.first == key)
  28. {
  29. // Loop through registered callbacks
  30. for(auto& callback : key_pair.second)
  31. {
  32. // If current key state matches the callback state, invoke
  33. // the callback
  34. if(callback.first == state)
  35. {
  36. callback.second();
  37. }
  38. }
  39. }
  40. }
  41. }
  42. void coral_input::callback(GLFWwindow*, int key, int, int action, int)
  43. {
  44. for(coral_input* input : instances_)
  45. {
  46. input->update_key_state(key, action);
  47. }
  48. }
  49. void coral_input::add_callback(int key, const coral_input::Callback& callback)
  50. {
  51. callbacks_[key].emplace_back(callback);
  52. }