| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- //
- // game_dispatch.cpp
- // gameutils
- //
- // Created by Sam Jaffe on 9/2/16.
- //
- #include <thread>
- #include "game_dispatch.hpp"
- #include "events.hpp"
- #include "scene.hpp"
- namespace engine {
- namespace {
- event::event_type mask( event::event_type t, bool pressed ) {
- return static_cast<event::event_type>( t | ( pressed ? event::PRESSED_MASK : event::RELEASED_MASK ) );
- }
- }
-
- game_dispatch::game_dispatch( )
- : screen_size( { 1920.f, 1080.f } )
- , minimum_frame_duration( engine::FPS60 )
- , 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;
- }
- }
|