clock: Move FPS calculation from loop to clock

This commit is contained in:
Hajime Hoshi 2017-08-06 02:09:33 +09:00
parent b1d12f08f8
commit f0f115b612
2 changed files with 33 additions and 42 deletions

View File

@ -23,14 +23,27 @@ import (
const FPS = 60
var (
m sync.Mutex
primaryTime int64
lastPrimaryTime int64
frames int64
logicalTime int64
ping func()
currentFPS float64
lastFPSUpdated int64
framesForFPS int64
ping func()
m sync.Mutex
)
func CurrentFPS() float64 {
m.Lock()
v := currentFPS
m.Unlock()
return v
}
func RegisterPing(pingFunc func()) {
m.Lock()
ping = pingFunc
@ -44,6 +57,19 @@ func ProceedPrimaryTimer() {
m.Unlock()
}
func updateFPS(now int64) {
if lastFPSUpdated == 0 {
lastFPSUpdated = now
}
framesForFPS++
if time.Second > time.Duration(now-lastFPSUpdated) {
return
}
currentFPS = float64(framesForFPS) * float64(time.Second) / float64(now-lastFPSUpdated)
lastFPSUpdated = now
framesForFPS = 0
}
// Update updates the inner clock state and returns an integer value
// indicating how many logical frames the game should update.
func Update(now int64) int {
@ -112,5 +138,8 @@ func Update(now int64) int {
} else {
logicalTime += int64(count) * int64(time.Second) / FPS
}
updateFPS(now)
return count
}

View File

@ -16,56 +16,29 @@ package loop
import (
"errors"
"time"
"github.com/hajimehoshi/ebiten/internal/clock"
"github.com/hajimehoshi/ebiten/internal/sync"
)
const FPS = clock.FPS
func CurrentFPS() float64 {
if theRunContext == nil {
return 0
}
return theRunContext.getCurrentFPS()
return clock.CurrentFPS()
}
type runContext struct {
currentFPS float64
framesForFPS int64
lastFPSUpdated int64
m sync.RWMutex
}
type runContext struct{}
var (
theRunContext *runContext
contextInitCh = make(chan struct{})
)
func (c *runContext) getCurrentFPS() float64 {
c.m.RLock()
v := c.currentFPS
c.m.RUnlock()
return v
}
func (c *runContext) updateFPS(fps float64) {
c.m.Lock()
c.currentFPS = fps
c.m.Unlock()
}
func Start() error {
// TODO: Need lock here?
if theRunContext != nil {
return errors.New("loop: The game is already running")
}
theRunContext = &runContext{}
n := now()
theRunContext.lastFPSUpdated = n
close(contextInitCh)
return nil
}
@ -90,16 +63,5 @@ func (c *runContext) update(u Updater) error {
if err := u.Update(count); err != nil {
return err
}
c.framesForFPS++
// Calc the current FPS.
if time.Second > time.Duration(n-c.lastFPSUpdated) {
return nil
}
currentFPS := float64(c.framesForFPS) * float64(time.Second) / float64(n-c.lastFPSUpdated)
c.updateFPS(currentFPS)
c.lastFPSUpdated = n
c.framesForFPS = 0
return nil
}