// // game_dispatch.cpp // gameutils // // Created by Sam Jaffe on 9/2/16. // #include #include "game/engine/game_dispatch.hpp" #include "game/engine/events.hpp" #include "game/engine/scene.hpp" namespace engine { namespace { event::event_type mask(event::event_type t, bool pressed) { return static_cast( t | (pressed ? event::PRESSED_MASK : event::RELEASED_MASK)); } } game_dispatch::game_dispatch() : screen_size({1920.f, 1080.f}), minimum_frame_duration(engine::fps::v60), scenes(), current_timestamp(clock::now()), curr_scene() {} game_dispatch::current_scene_info::current_scene_info() {} game_dispatch::current_scene_info::current_scene_info(scene * curr) : ptr(curr), current_scene_id(ptr->id), local_size(ptr->get_size()) {} void game_dispatch::process_key_event(raw_key_t key, bool press) { if (!curr_scene.is_keyboard_event) return; auto const & binding = curr_scene.ptr->get_binding(); auto it = binding.find(key); if (it == binding.end()) return; curr_scene.ptr->handle_key_event( {it->second, mask(event::KEY_MASK, press)}); } void game_dispatch::process_mouse_event(math::vec2 mouse_pos, bool press) { if (!curr_scene.is_mouse_event) return; math::vec2 local_scene_position = mouse_pos * curr_scene.local_size / screen_size; curr_scene.ptr->handle_mouse_event( {local_scene_position, mask(event::MOUSE_MASK, press)}); } tick game_dispatch::get_tick() { timestamp now = clock::now(); return {now, now - current_timestamp}; } tick game_dispatch::next_frame() { tick t = get_tick(); while (t.since < minimum_frame_duration) { std::this_thread::sleep_for(minimum_frame_duration - t.since); t = get_tick(); } current_timestamp = t.now; return t; } void game_dispatch::gameloop() try { while (running) { single_frame(next_frame()); } cleanup_resources(); exit(EXIT_SUCCESS); } catch (std::exception const & ex) { // todo: logging exit(EXIT_FAILURE); } void game_dispatch::quit() { running = false; } }