split main loop for manual main loop support

This commit is contained in:
Thomas Friedel 2018-03-24 19:20:30 +01:00
parent 385a230aa6
commit f57765cdc5
2 changed files with 58 additions and 35 deletions

2
.gitignore vendored
View file

@ -3,3 +3,5 @@ plan.txt
glowgen
testapp
openglinterface.go.all
videocap

View file

@ -17,7 +17,11 @@ import (
type Window struct {
Window *sdl.Window
GLContext sdl.GLContext
frameTimes [10]time.Time
frameIndex int
frameCount int
fps float32
close bool
}
func CreateCanvasWindow(w, h int, title string) (*Window, *canvas.Canvas, error) {
@ -83,13 +87,15 @@ func (wnd *Window) FPS() float32 {
return wnd.fps
}
func (wnd *Window) MainLoop(drawFunc func()) {
var frameTimes [10]time.Time
frameIndex := 0
frameCount := 0
func (wnd *Window) Close() {
wnd.close = true
}
// main loop
for running := true; running; {
func (wnd *Window) IsClosed() bool {
return wnd.close
}
func (wnd *Window) StartFrame() error {
for {
ei := sdl.PollEvent()
if ei == nil {
@ -98,16 +104,42 @@ func (wnd *Window) MainLoop(drawFunc func()) {
switch e := ei.(type) {
case *sdl.WindowEvent:
if e.Event == sdl.WINDOWEVENT_CLOSE {
running = false
wnd.close = true
}
case *sdl.KeyDownEvent:
if e.Keysym.Scancode == sdl.SCANCODE_ESCAPE {
running = false
wnd.close = true
}
}
}
err := sdl.GL_MakeCurrent(wnd.Window, wnd.GLContext)
if err != nil {
return err
}
return nil
}
func (wnd *Window) FinishFrame() {
now := time.Now()
wnd.frameTimes[wnd.frameIndex] = now
wnd.frameIndex++
wnd.frameIndex %= len(wnd.frameTimes)
if wnd.frameCount < len(wnd.frameTimes) {
wnd.frameCount++
} else {
diff := now.Sub(wnd.frameTimes[wnd.frameIndex]).Seconds()
wnd.fps = float32(wnd.frameCount-1) / float32(diff)
}
sdl.GL_SwapWindow(wnd.Window)
}
func (wnd *Window) MainLoop(drawFunc func()) {
// main loop
for !wnd.close {
err := wnd.StartFrame()
if err != nil {
time.Sleep(10 * time.Millisecond)
continue
@ -115,17 +147,6 @@ func (wnd *Window) MainLoop(drawFunc func()) {
drawFunc()
now := time.Now()
frameTimes[frameIndex] = now
frameIndex++
frameIndex %= len(frameTimes)
if frameCount < len(frameTimes) {
frameCount++
} else {
diff := now.Sub(frameTimes[frameIndex]).Seconds()
wnd.fps = float32(frameCount-1) / float32(diff)
}
sdl.GL_SwapWindow(wnd.Window)
wnd.FinishFrame()
}
}