/
fps.go
60 lines (46 loc) · 986 Bytes
/
fps.go
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
// adapted from github.com/scottferg/Go-SDL/gfx/framerate.go
package nes
import "time"
const (
DefaultFPSNTSC float64 = 60.0988
DefaultFPSPAL float64 = 50.0070
)
type FPS struct {
enabled bool
frames float64
rate float64
ticks uint64
}
func NewFPS(rate float64) *FPS {
fps := &FPS{}
fps.SetRate(rate)
return fps
}
func (fps *FPS) Enable() {
fps.enabled = true
}
func (fps *FPS) Disable() {
fps.enabled = false
}
func (fps *FPS) Resumed() {
fps.frames = 0
fps.ticks = uint64(time.Now().UnixNano()) / 1e6
}
func (fps *FPS) SetRate(rate float64) {
fps.Enable()
fps.Resumed()
fps.rate = 1000.0 / rate
}
func (fps *FPS) Delay() {
// next frame
fps.frames++
// get/calc ticks
current := uint64(time.Now().UnixNano()) / 1e6
target := fps.ticks + uint64(fps.frames*fps.rate)
if fps.enabled && current <= target {
time.Sleep(time.Duration((target - current) * 1e6))
} else {
fps.frames = 0.0
fps.ticks = uint64(time.Now().UnixNano()) / 1e6
}
}