From 0fe9a2ce63547ffdb21b6eb328b35b1e04577b44 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Mon, 18 May 2020 21:01:17 +0200 Subject: [PATCH] Added FPS counter. --- play/fps.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 play/fps.go diff --git a/play/fps.go b/play/fps.go new file mode 100644 index 0000000..3ea40d4 --- /dev/null +++ b/play/fps.go @@ -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) +}