game_dispatch.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // game_dispatch.cpp
  3. // gameutils
  4. //
  5. // Created by Sam Jaffe on 9/2/16.
  6. //
  7. #include <thread>
  8. #include "game/engine/game_dispatch.hpp"
  9. #include "game/engine/events.hpp"
  10. #include "game/engine/scene.hpp"
  11. #include "game/graphics/object.hpp"
  12. #include "game/graphics/renderer.hpp"
  13. #include "game/util/env.hpp"
  14. namespace engine {
  15. namespace {
  16. event::event_type mask(event::event_type t, bool pressed) {
  17. return static_cast<event::event_type>(
  18. t | (pressed ? event::PRESSED_MASK : event::RELEASED_MASK));
  19. }
  20. }
  21. game_dispatch::game_dispatch(std::shared_ptr<graphics::renderer> renderer)
  22. : renderer(renderer), screen_size(env::screen_size()),
  23. minimum_frame_duration(env::fps::v60), counter(minimum_frame_duration),
  24. scenes(), current_timestamp(env::clock::now()), curr_scene() {}
  25. game_dispatch::current_scene_info::current_scene_info() {}
  26. game_dispatch::current_scene_info::current_scene_info(scene * curr)
  27. : ptr(curr), current_scene_id(ptr->id), local_size(ptr->size()) {}
  28. void game_dispatch::process_key_event(raw_key_t key, bool press) {
  29. if (!curr_scene.is_keyboard_event) return;
  30. auto const & binding = curr_scene.ptr->keys();
  31. auto it = binding.find(key);
  32. if (it == binding.end()) return;
  33. curr_scene.ptr->handle_key_event(
  34. {it->second, mask(event::KEY_MASK, press)});
  35. }
  36. void game_dispatch::process_mouse_event(math::vec2 mouse_pos, bool press) {
  37. if (!curr_scene.is_mouse_event) return;
  38. math::vec2 local_scene_position =
  39. mouse_pos * curr_scene.local_size / screen_size;
  40. curr_scene.ptr->handle_mouse_event(
  41. {local_scene_position, mask(event::MOUSE_MASK, press)});
  42. }
  43. env::clock::tick game_dispatch::next_frame() {
  44. env::clock::tick t(current_timestamp);
  45. while (t.since < minimum_frame_duration) {
  46. std::this_thread::sleep_for(minimum_frame_duration - t.since);
  47. t = env::clock::tick(current_timestamp);
  48. }
  49. current_timestamp = t.now;
  50. return t;
  51. }
  52. void game_dispatch::update() {
  53. env::clock::tick t = next_frame();
  54. counter.set_frame_step(t.since);
  55. // curr_scene.ptr->update(std::chrono::duration<float>(t.since).count());
  56. }
  57. void game_dispatch::render() {
  58. graphics::batch_renderer batch(renderer.get());
  59. for (auto & obj : counter.glyphs()) {
  60. batch.draw(obj);
  61. }
  62. // curr_scene.ptr->render(batch);
  63. }
  64. }