-
Notifications
You must be signed in to change notification settings - Fork 261
/
Copy pathFpsTracker.cs
94 lines (81 loc) · 3.04 KB
/
FpsTracker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
///////////////////////////////////////////////////////////////////////////////////
// Open 3D Model Viewer (open3mod) (v2.0)
// [FpsTracker.cs]
// (c) 2012-2015, Open3Mod Contributors
//
// Licensed under the terms and conditions of the 3-clause BSD license. See
// the LICENSE file in the root folder of the repository for the details.
//
// HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
using System.Threading;
namespace open3mod
{
/// <summary>
/// Tracks performance and draws the nice fps counter in the rendering panel
/// </summary>
public class FpsTracker
{
private int _frameCnt = 1;
private Stopwatch _sw;
private double _lastFrameDelta;
private double _lastFps;
// limit maximum framerate to avoid taking too much CPU, overheating
// laptop mainboards or accidentially causing nuclear detonations.
public const int FRAMERATE_LIMIT = 100;
public double LastFrameDelta
{
get { return _lastFrameDelta; }
}
public int FrameCnt
{
get { return _frameCnt; }
}
public double LastFps
{
get { return _lastFps; }
}
/// <summary>
/// Called once per frame to update the internal frame statistics
/// </summary>
public void Update()
{
_frameCnt = FrameCnt + 1;
if(_sw == null)
{
_sw = new Stopwatch();
_lastFrameDelta = 0.0;
}
else
{
_lastFrameDelta = _sw.Elapsed.TotalMilliseconds / 1000.0;
_sw.Reset();
}
_sw.Start();
// prevent divide by zero
if (_lastFrameDelta < 1e-8)
{
_lastFps = 0.0;
}
else
{
_lastFps = 1/_lastFrameDelta;
}
if (_lastFps > FRAMERATE_LIMIT)
{
Thread.Sleep(1 + (int)(1000.0 / FRAMERATE_LIMIT - _lastFrameDelta * 1000));
}
}
}
}
/* vi: set shiftwidth=4 tabstop=4: */