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 currTime; 26 MonoTime lastTime; 27 long _deltatime; 28 29 MonoTime startProgramTime; 30 bool isCountDownStartTime = false; 31 long cfps = 0; 32 long cpfps; 33 MonoTime ctime; 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 cpfps; 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 long 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 (!isCountDownStartTime) 74 { 75 startProgramTime = MonoTime.currTime; 76 isCountDownStartTime = true; 77 } 78 79 lastTime = MonoTime.currTime; 80 81 if ((MonoTime.currTime - ctime).total!"msecs" > 1000) 82 { 83 cpfps = cfps; 84 cfps = 0; 85 ctime = MonoTime.currTime; 86 } 87 } 88 89 /++ 90 Frame limiting function. Also, it counts frames per second. 91 +/ 92 void control() 93 { 94 cfps++; 95 currTime = MonoTime.currTime; 96 _deltatime = 1000 / maxFPS - (currTime - lastTime).total!"msecs"; 97 98 if (_deltatime > 0) 99 { 100 Thread.sleep(dur!"msecs"(_deltatime)); 101 } 102 } 103 }