StateMachine.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "StateMachine.h"
  2. #include "Timing.h"
  3. #include "platform.h"
  4. #include "Graphics.h"
  5. #include "render/Text.h"
  6. #include "version.h"
  7. #include "Input.h"
  8. #include <iostream>
  9. using namespace std;
  10. using namespace WalrusRPG::Graphics;
  11. using namespace WalrusRPG::States;
  12. using namespace WalrusRPG::Timing;
  13. #define STATEMACHINE WalrusRPG::StateMachine
  14. STATEMACHINE::StateMachine(State *state)
  15. {
  16. push(state);
  17. }
  18. STATEMACHINE::~StateMachine()
  19. {
  20. while (!stack.empty())
  21. pop();
  22. }
  23. void STATEMACHINE::push(State *state)
  24. {
  25. stack.push_back(state);
  26. }
  27. void STATEMACHINE::pop()
  28. {
  29. delete stack.back();
  30. stack.pop_back();
  31. }
  32. void STATEMACHINE::run()
  33. {
  34. const unsigned loop_time = TIMER_FREQ / 60;
  35. unsigned loop_next = loop_time;
  36. unsigned last_update = 0, update_stamp, update_time;
  37. unsigned last_frame = 0, frame_stamp, frame_time;
  38. while (!stack.empty())
  39. {
  40. update_stamp = Timing::gettime();
  41. update_time = update_stamp - last_update;
  42. stack.back()->update(100*update_time/TIMER_FREQ);
  43. last_update = update_stamp;
  44. if (Timing::gettime() < loop_next)
  45. {
  46. frame_stamp = Timing::gettime();
  47. frame_time = frame_stamp - last_frame;
  48. Graphics::frame_begin();
  49. stack.back()->render(100*frame_time/TIMER_FREQ);
  50. last_frame = frame_stamp;
  51. Text::print_format(0, 0, "WalrusRPG test build %s", git_version);
  52. if (frame_time != 0 && update_time != 0)
  53. {
  54. Text::print_format(0, 240 - 8, "%ufps, %uups", TIMER_FREQ / frame_time,
  55. TIMER_FREQ / update_time);
  56. }
  57. Graphics::frame_end();
  58. }
  59. if (Input::key_select())
  60. {
  61. while (Input::key_select())
  62. ;
  63. this->pop();
  64. }
  65. #ifdef ACTIVE_WAIT
  66. while (Timing::gettime() < loop_next)
  67. ;
  68. #endif
  69. loop_next += loop_time;
  70. }
  71. }