FramerateManager.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. FramerateManager::FramerateManager(int targetFrameRate)
  13. : targetFrameTime(Duration(boost::chrono::seconds(1)) / targetFrameRate)
  14. , lastFrameIndex(0)
  15. , lastFrameTimes({})
  16. , lastTimePoint (Clock::now())
  17. {
  18. boost::range::fill(lastFrameTimes, targetFrameTime);
  19. }
  20. void FramerateManager::framerateDelay()
  21. {
  22. Duration timeSpentBusy = Clock::now() - lastTimePoint;
  23. // FPS is higher than it should be, then wait some time
  24. if(timeSpentBusy < targetFrameTime)
  25. boost::this_thread::sleep_for(targetFrameTime - timeSpentBusy);
  26. // compute actual timeElapsed taking into account actual sleep interval
  27. // limit it to 100 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  28. TimePoint currentTicks = Clock::now();
  29. Duration timeElapsed = currentTicks - lastTimePoint;
  30. if(timeElapsed > boost::chrono::milliseconds(100))
  31. timeElapsed = boost::chrono::milliseconds(100);
  32. lastTimePoint = currentTicks;
  33. lastFrameIndex = (lastFrameIndex + 1) % lastFrameTimes.size();
  34. lastFrameTimes[lastFrameIndex] = timeElapsed;
  35. }
  36. ui32 FramerateManager::getElapsedMilliseconds() const
  37. {
  38. return lastFrameTimes[lastFrameIndex] / boost::chrono::milliseconds(1);
  39. }
  40. ui32 FramerateManager::getFramerate() const
  41. {
  42. Duration accumulatedTime = std::accumulate(lastFrameTimes.begin(), lastFrameTimes.end(), Duration());
  43. auto actualFrameTime = accumulatedTime / lastFrameTimes.size();
  44. if(actualFrameTime == actualFrameTime.zero())
  45. return 0;
  46. return std::round(boost::chrono::duration<double>(1) / actualFrameTime);
  47. };