lazarus/platform/platform.go

103 lines
1.9 KiB
Go
Raw Normal View History

package platform
import (
2019-01-01 01:10:45 +00:00
"log"
2018-12-27 22:35:06 +00:00
"runtime"
2018-12-27 21:59:35 +00:00
2019-01-01 00:52:53 +00:00
"github.com/FooSoft/lazarus/math"
"github.com/veandco/go-sdl2/sdl"
)
2018-12-31 21:28:50 +00:00
var singleton struct {
2019-01-01 00:52:53 +00:00
sdlIsInit bool
windows []*Window
}
2018-12-31 21:40:02 +00:00
func Advance() (bool, error) {
2019-01-01 00:52:53 +00:00
if err := advanceWindows(); err != nil {
return false, err
2018-12-31 21:40:02 +00:00
}
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
switch event.(type) {
case *sdl.QuitEvent:
return false, nil
default:
if err := processWindowEvents(event); err != nil {
return false, err
}
}
}
2019-01-01 00:52:53 +00:00
return len(singleton.windows) > 0, nil
2018-12-31 21:40:02 +00:00
}
2019-01-01 00:52:53 +00:00
func NewWindow(title string, size math.Vec2i, scene Scene) (*Window, error) {
if !singleton.sdlIsInit {
runtime.LockOSThread()
2019-01-01 01:10:45 +00:00
log.Println("sdl global init")
2019-01-01 00:52:53 +00:00
if err := sdl.Init(sdl.INIT_VIDEO); err != nil {
return nil, err
}
2019-01-01 01:10:45 +00:00
sdl.GLSetAttribute(sdl.GL_CONTEXT_MAJOR_VERSION, 2)
sdl.GLSetAttribute(sdl.GL_CONTEXT_MINOR_VERSION, 1)
sdl.GLSetAttribute(sdl.GL_DOUBLEBUFFER, 1)
2019-01-01 00:52:53 +00:00
singleton.sdlIsInit = true
}
2019-01-01 00:52:53 +00:00
w, err := newWindow(title, size, scene)
if err != nil {
return nil, err
}
2018-12-31 21:40:02 +00:00
appendWindow(w)
return w, err
}
2018-12-31 21:40:02 +00:00
func appendWindow(window *Window) {
singleton.windows = append(singleton.windows, window)
}
2018-12-31 21:40:02 +00:00
func removeWindow(window *Window) bool {
for i, w := range singleton.windows {
if w == window {
singleton.windows = append(singleton.windows[:i], singleton.windows[i+1:]...)
return true
2018-12-27 22:35:06 +00:00
}
}
2018-12-31 21:40:02 +00:00
return false
2018-12-27 22:35:06 +00:00
}
2019-01-01 00:52:53 +00:00
func advanceWindows() error {
var windowsToRemove []*Window
2018-12-31 21:28:50 +00:00
for _, window := range singleton.windows {
2019-01-01 00:52:53 +00:00
run, err := window.advance()
if err != nil {
return err
}
if !run {
windowsToRemove = append(windowsToRemove, window)
}
}
2019-01-01 00:52:53 +00:00
for _, window := range windowsToRemove {
removeWindow(window)
}
return nil
}
2018-12-31 21:40:02 +00:00
func processWindowEvents(event sdl.Event) error {
2018-12-31 21:28:50 +00:00
for _, window := range singleton.windows {
2018-12-31 21:40:02 +00:00
if _, err := window.processEvent(event); err != nil {
return err
}
}
2018-12-31 21:40:02 +00:00
return nil
}