zntg/ui/loop.go
2018-09-22 16:31:09 +02:00

122 lines
2.0 KiB
Go

package ui
import (
"time"
"opslag.de/schobers/zntg/allg5"
)
func shouldClose(ev allg5.Event) bool {
switch e := ev.(type) {
case *allg5.KeyCharEvent:
switch e.KeyCode {
case allg5.KeyEscape:
return true
case allg5.KeyF4:
if e.Modifiers&allg5.KeyModAlt == allg5.KeyModAlt {
return true
}
}
case *allg5.DisplayCloseEvent:
return true
}
return false
}
func shouldToggleDebug(ev allg5.Event) bool {
switch e := ev.(type) {
case *allg5.KeyCharEvent:
switch e.KeyCode {
case allg5.KeyD:
return e.Modifiers&allg5.KeyModAlt == allg5.KeyModAlt
}
}
return false
}
func switchState(ctx Context, curr State, s State) error {
var err error
err = curr.Leave(ctx)
if nil != err {
return err
}
return s.Enter(ctx)
}
func Init() error {
return allg5.Init(allg5.InitAll)
}
func Run(w, h int, title string, s State, f Fonts, opts *allg5.NewDisplayOptions) error {
if nil == opts {
opts = &allg5.NewDisplayOptions{}
}
disp, err := allg5.NewDisplay(w, h, *opts)
if nil != err {
return err
}
disp.SetWindowTitle(title)
defer disp.Destroy()
evq, err := allg5.NewEventQueue()
if nil != err {
return err
}
evq.RegisterDisplay(disp)
evq.RegisterKeyboard()
evq.RegisterMouse()
defer evq.Destroy()
ctx := newContext(disp, f)
var state = s
err = state.Enter(ctx)
if nil != err {
return err
}
var t = time.Now()
main:
for nil != state {
for ev := evq.Get(); ev != nil; ev = evq.Get() {
if shouldClose(ev) {
break main
}
if shouldToggleDebug(ev) {
ctx.dbg.enbl = !ctx.dbg.enbl
}
err := state.Handle(ctx, ev)
if nil != err {
return err
}
}
var now = time.Now()
var dt = now.Sub(t)
var s, err = state.Update(ctx, dt)
if nil != err {
return err
}
t = now
if s != nil {
err = switchState(ctx, state, s)
if nil != err {
return err
}
state = s
}
ctx.dbg.resetRainbow()
err = state.Render(ctx)
if nil != err {
return err
}
disp.Flip()
time.Sleep(10 * time.Millisecond)
}
err = state.Leave(ctx)
if nil != err {
return err
}
return nil
}