lazarus/platform/platform.go

128 lines
2.0 KiB
Go
Raw Normal View History

package platform
import (
2018-12-27 21:59:35 +00:00
"errors"
2018-12-27 22:35:06 +00:00
"runtime"
"time"
2018-12-27 21:59:35 +00:00
"github.com/FooSoft/lazarus/platform/imgui_backend"
"github.com/go-gl/gl/v2.1/gl"
"github.com/veandco/go-sdl2/sdl"
)
var (
ErrAlreadyInit = errors.New("platform is already initialized")
ErrWasNotInit = errors.New("platform was not initialized")
)
2018-12-28 03:28:33 +00:00
var state struct {
isInit bool
windows []*Window
}
type Scene interface {
Init(window *Window) error
Advance(window *Window) error
Shutdown(window *Window) error
2018-12-28 03:28:33 +00:00
}
2018-12-27 21:59:35 +00:00
func Init() error {
2018-12-28 03:28:33 +00:00
if state.isInit {
return ErrAlreadyInit
2018-12-27 21:59:35 +00:00
}
2018-12-27 22:35:06 +00:00
runtime.LockOSThread()
2018-12-27 21:59:35 +00:00
if err := sdl.Init(sdl.INIT_VIDEO); err != nil {
return err
}
2018-12-27 21:59:35 +00:00
if err := gl.Init(); err != nil {
return err
}
if err := imgui_backend.Init(); err != nil {
return err
}
2018-12-28 03:28:33 +00:00
state.isInit = true
2018-12-27 21:59:35 +00:00
return nil
}
func Shutdown() error {
2018-12-28 03:28:33 +00:00
if !state.isInit {
return ErrWasNotInit
}
2018-12-28 03:28:33 +00:00
for _, w := range state.windows {
if err := w.Destroy(); err != nil {
return err
}
}
if err := imgui_backend.Shutdown(); err != nil {
return err
}
2018-12-28 03:28:33 +00:00
state.windows = nil
state.isInit = false
return nil
}
func CreateWindow(title string, width, height int, scene Scene) (*Window, error) {
if !state.isInit {
return nil, ErrWasNotInit
}
window, err := newWindow(title, width, height, scene)
if err != nil {
return nil, err
}
state.windows = append(state.windows, window)
return window, err
}
2018-12-27 22:35:06 +00:00
func ProcessEvents() error {
2018-12-28 03:28:33 +00:00
if !state.isInit {
return ErrWasNotInit
}
2018-12-27 22:35:06 +00:00
for running := true; running; {
advanceWindows()
2018-12-27 22:35:06 +00:00
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
if !processEvent(event) {
running = false
2018-12-27 22:35:06 +00:00
break
}
}
<-time.After(time.Millisecond * 25)
}
return nil
}
func advanceWindows() {
for _, window := range state.windows {
window.advance()
}
}
func processEvent(event sdl.Event) bool {
handled, _ := imgui_backend.ProcessEvent(event)
if handled {
return true
}
switch event.(type) {
case *sdl.QuitEvent:
return false
}
return true
}