💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.2 KiB

  1. /*
  2. * Copyright (C) 2021 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "game/loop.hpp"
  20. #include <algorithm>
  21. namespace game {
  22. loop::loop():
  23. update_callback([](double, double){}),
  24. render_callback([](double){}),
  25. update_rate(60.0),
  26. update_timestep(1.0 / update_rate),
  27. max_frame_duration(update_timestep)
  28. {
  29. reset();
  30. }
  31. void loop::set_update_callback(std::function<void(double, double)> callback)
  32. {
  33. update_callback = callback;
  34. }
  35. void loop::set_render_callback(std::function<void(double)> callback)
  36. {
  37. render_callback = callback;
  38. }
  39. void loop::set_update_rate(double frequency)
  40. {
  41. update_rate = frequency;
  42. update_timestep = 1.0 / frequency;
  43. }
  44. void loop::set_max_frame_duration(double duration)
  45. {
  46. max_frame_duration = duration;
  47. }
  48. double loop::get_frame_duration() const
  49. {
  50. return frame_duration;
  51. }
  52. void loop::reset()
  53. {
  54. elapsed_time = 0.0;
  55. accumulator = 0.0;
  56. frame_start = std::chrono::high_resolution_clock::now();
  57. frame_end = frame_start;
  58. frame_duration = 0.0;
  59. }
  60. void loop::tick()
  61. {
  62. frame_end = std::chrono::high_resolution_clock::now();
  63. frame_duration = static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(frame_end - frame_start).count()) / 1000000000.0;
  64. frame_start = frame_end;
  65. accumulator += std::min<double>(max_frame_duration, frame_duration);
  66. while (accumulator >= update_timestep)
  67. {
  68. update_callback(elapsed_time, update_timestep);
  69. elapsed_time += update_timestep;
  70. accumulator -= update_timestep;
  71. }
  72. render_callback(accumulator * update_rate);
  73. }
  74. } // namespace game