ebiten/ui/cocoa/texture_factory.go

110 lines
2.2 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 (
"github.com/hajimehoshi/go-ebiten/graphics"
"github.com/hajimehoshi/go-ebiten/graphics/opengl"
"image"
2013-12-08 14:13:48 +01:00
"runtime"
2013-12-06 18:20:48 +01:00
)
type textureFactory struct {
sharedContext *C.NSOpenGLContext
graphicsDevice *opengl.Device
events chan interface{}
funcs chan func()
funcsDone chan struct{}
2013-12-06 18:20:48 +01:00
}
func runTextureFactory() *textureFactory {
t := &textureFactory{
2013-12-08 14:13:48 +01:00
funcs: make(chan func()),
2013-12-06 18:20:48 +01:00
funcsDone: make(chan struct{}),
}
ch := make(chan struct{})
go func() {
2013-12-08 14:13:48 +01:00
runtime.LockOSThread()
2013-12-30 19:17:39 +01:00
t.sharedContext = C.CreateGLContext(nil)
2013-12-06 18:20:48 +01:00
close(ch)
t.loop()
}()
<-ch
t.useGLContext(func() {
t.graphicsDevice = opengl.NewDevice()
})
2013-12-06 18:20:48 +01:00
return t
}
func (t *textureFactory) loop() {
for {
select {
case f := <-t.funcs:
C.UseGLContext(t.sharedContext)
f()
2013-12-07 17:35:24 +01:00
C.UnuseGLContext()
2013-12-06 18:20:48 +01:00
t.funcsDone <- struct{}{}
}
}
}
2013-12-13 22:10:24 +01:00
func (t *textureFactory) useGLContext(f func()) {
2013-12-06 18:20:48 +01:00
t.funcs <- f
<-t.funcsDone
}
func (t *textureFactory) createGameWindow(width, height, scale int, title string) *GameWindow {
return runGameWindow(t.graphicsDevice, width, height, scale, title, t.sharedContext)
}
func (t *textureFactory) Events() <-chan interface{} {
if t.events != nil {
return t.events
}
t.events = make(chan interface{})
return t.events
}
func (t *textureFactory) CreateTexture(tag interface{}, img image.Image, filter graphics.Filter) {
go func() {
var id graphics.TextureId
var err error
t.useGLContext(func() {
id, err = t.graphicsDevice.CreateTexture(img, filter)
})
if t.events == nil {
return
}
e := graphics.TextureCreatedEvent{
Tag: tag,
Id: id,
Error: err,
}
t.events <- e
}()
}
func (t *textureFactory) CreateRenderTarget(tag interface{}, width, height int) {
go func() {
var id graphics.RenderTargetId
var err error
t.useGLContext(func() {
id, err = t.graphicsDevice.CreateRenderTarget(width, height)
})
if t.events == nil {
return
}
e := graphics.RenderTargetCreatedEvent{
Tag: tag,
Id: id,
Error: err,
}
t.events <- e
}()
2013-12-06 18:20:48 +01:00
}