ebiten/ui/cocoa/shared_context.go

97 lines
2.0 KiB
Go
Raw Normal View History

2013-12-06 18:20:48 +01:00
package cocoa
2013-12-30 19:17:39 +01:00
// @class NSOpenGLContext;
//
// NSOpenGLContext* CreateGLContext(NSOpenGLContext* sharedGLContext);
// void UseGLContext(NSOpenGLContext* glContext);
2013-12-07 17:35:24 +01:00
// void UnuseGLContext(void);
2013-12-06 18:20:48 +01:00
//
import "C"
import (
2014-12-05 14:16:58 +01:00
"github.com/hajimehoshi/ebiten/graphics"
"github.com/hajimehoshi/ebiten/graphics/opengl"
"image"
2013-12-08 14:13:48 +01:00
"runtime"
2013-12-06 18:20:48 +01:00
)
2014-01-11 02:34:38 +01:00
type sharedContext struct {
2014-05-02 17:06:20 +02:00
inited chan struct{}
funcs chan func()
funcsDone chan struct{}
gameWindows chan *GameWindow
2013-12-06 18:20:48 +01:00
}
2014-01-11 02:34:38 +01:00
func newSharedContext() *sharedContext {
return &sharedContext{
inited: make(chan struct{}),
funcs: make(chan func()),
funcsDone: make(chan struct{}),
gameWindows: make(chan *GameWindow),
2013-12-06 18:20:48 +01:00
}
}
2014-01-11 02:34:38 +01:00
func (t *sharedContext) run() {
var sharedGLContext *C.NSOpenGLContext
2013-12-06 18:20:48 +01:00
go func() {
2013-12-08 14:13:48 +01:00
runtime.LockOSThread()
2014-01-11 02:34:38 +01:00
sharedGLContext = C.CreateGLContext(nil)
close(t.inited)
2014-01-11 02:34:38 +01:00
t.loop(sharedGLContext)
}()
<-t.inited
go func() {
for w := range t.gameWindows {
2014-05-02 17:06:20 +02:00
w.run(sharedGLContext)
}
}()
2013-12-06 18:20:48 +01:00
}
2014-01-11 02:34:38 +01:00
func (t *sharedContext) loop(sharedGLContext *C.NSOpenGLContext) {
2013-12-06 18:20:48 +01:00
for {
select {
case f := <-t.funcs:
2014-01-11 02:34:38 +01:00
C.UseGLContext(sharedGLContext)
2013-12-06 18:20:48 +01:00
f()
2013-12-07 17:35:24 +01:00
C.UnuseGLContext()
2013-12-06 18:20:48 +01:00
t.funcsDone <- struct{}{}
}
}
}
2014-01-11 02:34:38 +01:00
func (t *sharedContext) useGLContext(f func()) {
2013-12-06 18:20:48 +01:00
t.funcs <- f
<-t.funcsDone
}
2014-01-11 02:34:38 +01:00
func (t *sharedContext) createGameWindow(width, height, scale int, title string) *GameWindow {
w := newGameWindow(width, height, scale, title)
go func() {
t.gameWindows <- w
}()
return w
}
2014-05-03 08:25:41 +02:00
func (t *sharedContext) CreateTexture(
img image.Image,
filter graphics.Filter) (graphics.TextureId, error) {
<-t.inited
var id graphics.TextureId
var err error
t.useGLContext(func() {
id, err = opengl.CreateTexture(img, filter)
})
return id, err
}
2014-05-03 08:25:41 +02:00
func (t *sharedContext) CreateRenderTarget(
width, height int,
filter graphics.Filter) (graphics.RenderTargetId, error) {
<-t.inited
var id graphics.RenderTargetId
var err error
t.useGLContext(func() {
id, err = opengl.CreateRenderTarget(width, height, filter)
})
return id, err
2013-12-06 18:20:48 +01:00
}