52 lines
966 B
Go
52 lines
966 B
Go
|
package tins2020
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"time"
|
||
|
|
||
|
"github.com/veandco/go-sdl2/sdl"
|
||
|
)
|
||
|
|
||
|
type FPS struct {
|
||
|
ControlBase
|
||
|
|
||
|
start time.Time
|
||
|
stamp time.Duration
|
||
|
slot int
|
||
|
ticks []int
|
||
|
total int
|
||
|
}
|
||
|
|
||
|
func (f *FPS) Init(*Context) error {
|
||
|
f.start = time.Now()
|
||
|
f.stamp = 0
|
||
|
f.ticks = make([]int, 51)
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (f *FPS) Render(ctx *Context) {
|
||
|
elapsed := time.Since(f.start)
|
||
|
stamp := elapsed / (20 * time.Millisecond)
|
||
|
for f.stamp < stamp {
|
||
|
f.total += f.ticks[f.slot]
|
||
|
f.slot = (f.slot + 1) % len(f.ticks)
|
||
|
f.total -= f.ticks[f.slot]
|
||
|
f.ticks[f.slot] = 0
|
||
|
f.stamp++
|
||
|
}
|
||
|
f.ticks[f.slot]++
|
||
|
|
||
|
font := ctx.Fonts.Font("debug")
|
||
|
surface, err := font.RenderUTF8Solid(fmt.Sprintf("FPS: %d", f.total), sdl.Color{R: 255, G: 255, B: 255, A: 255})
|
||
|
if err != nil {
|
||
|
return
|
||
|
}
|
||
|
defer surface.Free()
|
||
|
texture, err := NewTextureFromSurface(ctx.Renderer, surface)
|
||
|
if err != nil {
|
||
|
return
|
||
|
}
|
||
|
defer texture.Destroy()
|
||
|
texture.Copy(ctx.Renderer, texture.RectOffset(Pt(5, 5)))
|
||
|
}
|