hexyz is tower defense game, and a lua library for dealing with hexagonal grids
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.

33 lines
1.6 KiB

  1. -- the garbage collector decides when to run its cycles on its own, and this can cause frame spikes in your game.
  2. -- lua provides some amount of control over its garbage collector.
  3. --
  4. -- by storing the average time it takes for a full gc cycle to run, we can check at the end of a frame if we have enough time
  5. -- to run it for 'free'
  6. --
  7. -- if you wish, you can call 'collectgarbage("stop")', and then:
  8. -- at the start of each game frame, call and cache the results of 'am.current_time()' - am.frame_time doesn't seem to work as well
  9. -- at the end of each game frame, call 'check_if_can_collect_garbage_for_free()' with the cached frame time and a desired minimum fps
  10. --
  11. local garbage_collector_cycle_timing_history = {}
  12. local garbage_collector_average_cycle_time = 0
  13. function run_garbage_collector_cycle()
  14. local time, result = fprofile(collectgarbage, "collect")
  15. table.insert(garbage_collector_cycle_timing_history, time)
  16. -- re-calc average gc timing
  17. local total = 0
  18. for _,v in pairs(garbage_collector_cycle_timing_history) do
  19. total = total + v
  20. end
  21. garbage_collector_average_cycle_time = total / #garbage_collector_cycle_timing_history
  22. end
  23. function check_if_can_collect_garbage_for_free(frame_start_time, min_fps)
  24. -- often this will be polled at the end of a frame to see if we're running fast or slow,
  25. -- and if we have some time to kill before the start of the next frame, we could maybe run gc.
  26. if (am.current_time() - frame_start_time) < (1 / (min_fps or 60) + garbage_collector_average_cycle_time) then
  27. run_garbage_collector_cycle()
  28. end
  29. end