Added FPS counter.

This commit is contained in:
Sander Schobers 2020-05-18 21:01:17 +02:00
parent 7dde894bf0
commit 0fe9a2ce63

56
play/fps.go Normal file
View File

@ -0,0 +1,56 @@
package play
import (
"fmt"
"time"
"opslag.de/schobers/geom"
"opslag.de/schobers/zntg"
"opslag.de/schobers/zntg/ui"
)
type FPS struct {
ui.ControlBase
update zntg.Animation
i int
frames []int
total int
}
func (f *FPS) Shown() {
f.update.Interval = 20 * time.Millisecond
f.update.Start()
f.i = 0
f.frames = make([]int, 51)
f.total = 0
}
func (f *FPS) Hidden() {
f.update.Pause()
}
func (f *FPS) font(ctx ui.Context) ui.Font {
font := ctx.Fonts().Font("debug")
if font != nil {
return font
}
return ctx.Fonts().Font("default")
}
func (f *FPS) Render(ctx ui.Context) {
_, n := f.update.AnimateDelta()
for i := 0; i < n; i++ {
f.total += f.frames[f.i]
f.i = (f.i + 1) % len(f.frames)
f.total -= f.frames[f.i]
f.frames[f.i] = 0
}
f.frames[f.i]++
font := f.font(ctx)
fps := fmt.Sprintf("FPS: %d", f.total)
ctx.Renderer().Text(font, geom.PtF32(5, 5), ctx.Style().Palette.Background, fps)
ctx.Renderer().Text(font, geom.PtF32(4, 4), ctx.Style().Palette.Text, fps)
}