FramerateManager.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * FramerateManager.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "FramerateManager.h"
  12. #include "../../lib/CConfigHandler.h"
  13. #include <SDL_video.h>
  14. FramerateManager::FramerateManager(int targetFrameRate)
  15. : targetFrameTime(Duration(boost::chrono::seconds(1)) / targetFrameRate)
  16. , lastFrameIndex(0)
  17. , lastFrameTimes({})
  18. , lastTimePoint(Clock::now())
  19. , vsyncEnabled(settings["video"]["vsync"].Bool())
  20. {
  21. boost::range::fill(lastFrameTimes, targetFrameTime);
  22. }
  23. void FramerateManager::framerateDelay()
  24. {
  25. Duration timeSpentBusy = Clock::now() - lastTimePoint;
  26. if(!vsyncEnabled)
  27. {
  28. // if FPS is higher than it should be, then wait some time
  29. if(timeSpentBusy < targetFrameTime)
  30. {
  31. boost::this_thread::sleep_for(targetFrameTime - timeSpentBusy);
  32. }
  33. }
  34. // compute actual timeElapsed taking into account actual sleep interval
  35. // limit it to 100 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  36. TimePoint currentTicks = Clock::now();
  37. Duration timeElapsed = currentTicks - lastTimePoint;
  38. if(timeElapsed > boost::chrono::milliseconds(100))
  39. timeElapsed = boost::chrono::milliseconds(100);
  40. lastTimePoint = currentTicks;
  41. lastFrameIndex = (lastFrameIndex + 1) % lastFrameTimes.size();
  42. lastFrameTimes[lastFrameIndex] = timeElapsed;
  43. }
  44. ui32 FramerateManager::getElapsedMilliseconds() const
  45. {
  46. return lastFrameTimes[lastFrameIndex] / boost::chrono::milliseconds(1);
  47. }
  48. ui32 FramerateManager::getFramerate() const
  49. {
  50. Duration accumulatedTime = std::accumulate(lastFrameTimes.begin(), lastFrameTimes.end(), Duration());
  51. auto actualFrameTime = accumulatedTime / lastFrameTimes.size();
  52. if(actualFrameTime == actualFrameTime.zero())
  53. return 0;
  54. return std::round(boost::chrono::duration<double>(1) / actualFrameTime);
  55. };