InputTarget.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * Triangles
  3. * Copyright (C) 2016 POSITIVE MENTAL ATTITUDE
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, version 3 of the License.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #pragma once
  18. #include <list>
  19. #include <functional>
  20. #include <SFML/Window.hpp>
  21. #include "InputMap.hpp"
  22. #include <iostream>
  23. template<typename T = int>
  24. class InputTarget
  25. {
  26. public:
  27. InputTarget(const InputTarget<T>&) = delete;
  28. InputTarget<T>& operator=(const InputTarget<T>&) = delete;
  29. InputTarget(const InputMap<T>& map): _inputMap(map) {}
  30. bool think(const sf::Event& event) const
  31. {
  32. for(auto& pair: _eventsPoll)
  33. {
  34. if(_inputMap.get(pair.first) == event)
  35. {
  36. pair.second(event, 1.f);
  37. return true;
  38. }
  39. }
  40. return false;
  41. }
  42. void think() const
  43. {
  44. for(auto& pair: _eventsRealTime)
  45. {
  46. const Input& input = _inputMap.get(pair.first);
  47. float power = input.test();
  48. if(power != 0.f)
  49. pair.second(input._event, power);
  50. }
  51. }
  52. void bind(const T& key, const std::function<void(const sf::Event&, float)>& callback)
  53. {
  54. const Input& input = _inputMap.get(key);
  55. if(input._type & Input::Type::RealTime)
  56. _eventsRealTime.emplace_back(key, callback);
  57. else
  58. _eventsPoll.emplace_back(key, callback);
  59. }
  60. void unbind(const T& key)
  61. {
  62. auto remove_func = [&key](const std::pair<T, std::function<void(const sf::Event&, float)>>& pair) -> bool
  63. {
  64. return pair.first == key;
  65. };
  66. if(_inputMap.get(key)._type & Input::Type::RealTime)
  67. _eventsRealTime.remove_if(remove_func);
  68. else
  69. _eventsPoll.remove_if(remove_func);
  70. }
  71. private:
  72. std::list<std::pair<T, std::function<void(const sf::Event&, float power)>>> _eventsRealTime;
  73. std::list<std::pair<T, std::function<void(const sf::Event&, float power)>>> _eventsPoll;
  74. const InputMap<T>& _inputMap;
  75. };