zntg/play/fps.go

57 lines
1012 B
Go

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)
}