1 /++ 2 Module for limiting the release of frames per second. 3 4 Macros: 5 LREF = <a href="#$1">$1</a> 6 HREF = <a href="$1">$2</a> 7 8 Authors: $(HREF https://github.com/TodNaz,TodNaz) 9 Copyright: Copyright (c) 2020 - 2021, TodNaz. 10 License: $(HREF https://github.com/TodNaz/Tida/blob/master/LICENSE,MIT) 11 +/ 12 module tida.fps; 13 14 import std.datetime; 15 16 /++ 17 The object that will keep track of the cycle time, counts and 18 limits the executable frames. 19 +/ 20 class FPSManager 21 { 22 import core.thread; 23 24 private: 25 MonoTime controlTime; 26 Duration _deltatime; 27 28 MonoTime startProgramTime; 29 bool isFirstControl = true; 30 31 MonoTime lastRenderTime; 32 long countFPS = 0; 33 long resultFPS = 0; 34 35 public: 36 /++ 37 Sets the maximum number of frames per second. 38 +/ 39 long maxFPS = 60; 40 41 /++ 42 Shows how many frames were formed in a second. 43 Please note that the counter is updated once per second. 44 +/ 45 @property long fps() @safe 46 { 47 return resultFPS; 48 } 49 50 /++ 51 Shows the running time of the program. 52 +/ 53 @property Duration timeJobProgram() @safe 54 { 55 return MonoTime.currTime - startProgramTime; 56 } 57 58 /++ 59 Delta time. 60 +/ 61 @property Duration deltatime() @safe 62 { 63 return _deltatime; 64 } 65 66 @trusted: 67 /++ 68 The origin of the frame unit. Measures time and also changes the 69 state of the frame counter. 70 +/ 71 void countDown() 72 { 73 if (isFirstControl) 74 { 75 isFirstControl = false; 76 startProgramTime = MonoTime.currTime; 77 } 78 79 if (MonoTime.currTime - lastRenderTime > dur!"msecs"(1000)) 80 { 81 resultFPS = countFPS; 82 countFPS = 0; 83 lastRenderTime = MonoTime.currTime; 84 } 85 86 controlTime = MonoTime.currTime; 87 } 88 89 /++ 90 Frame limiting function. Also, it counts frames per second. 91 +/ 92 void control() 93 { 94 countFPS++; 95 96 immutable timePerFrame = dur!"msecs"(1000) / maxFPS; 97 _deltatime = MonoTime.currTime - controlTime; 98 99 if (_deltatime < timePerFrame) 100 { 101 Thread.sleep(timePerFrame - _deltatime); 102 } 103 } 104 }