go-opengl-pixel/pixelgl/texture.go

69 lines
1.3 KiB
Go
Raw Normal View History

2016-11-23 10:29:28 -06:00
package pixelgl
2016-11-23 11:06:55 -06:00
import (
"github.com/go-gl/gl/v3.3-core/gl"
"github.com/pkg/errors"
)
2016-11-23 10:29:28 -06:00
// Texture is an OpenGL texture.
type Texture struct {
parent Doer
2016-11-23 10:29:28 -06:00
tex uint32
}
// NewTexture creates a new texture with the specified width and height.
// The pixels must be a sequence of RGBA values.
func NewTexture(parent Doer, width, height int, pixels []uint8) (*Texture, error) {
2016-11-23 10:29:28 -06:00
texture := &Texture{parent: parent}
2016-11-24 07:37:11 -06:00
errChan := make(chan error, 1)
parent.Do(func() {
errChan <- DoGLErr(func() {
gl.GenTextures(1, &texture.tex)
gl.BindTexture(gl.TEXTURE_2D, texture.tex)
gl.TexImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
int32(width),
int32(height),
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
gl.Ptr(pixels),
)
2016-11-23 11:06:55 -06:00
gl.GenerateMipmap(gl.TEXTURE_2D)
2016-11-23 11:06:55 -06:00
gl.BindTexture(gl.TEXTURE_2D, 0)
})
2016-11-23 10:29:28 -06:00
})
err := <-errChan
2016-11-23 11:06:55 -06:00
if err != nil {
return nil, errors.Wrap(err, "failed to create a texture")
}
2016-11-24 07:37:11 -06:00
2016-11-23 11:06:55 -06:00
return texture, nil
2016-11-23 10:29:28 -06:00
}
2016-11-23 13:06:34 -06:00
// Delete deletes a texture. Don't use a texture after deletion.
func (t *Texture) Delete() {
DoNoBlock(func() {
2016-11-23 13:06:34 -06:00
gl.DeleteTextures(1, &t.tex)
})
}
// Do bind a texture, executes sub, and unbinds the texture.
func (t *Texture) Do(sub func()) {
t.parent.Do(func() {
DoNoBlock(func() {
gl.BindTexture(gl.TEXTURE_2D, t.tex)
})
sub()
DoNoBlock(func() {
gl.BindTexture(gl.TEXTURE_2D, 0)
})
2016-11-23 10:29:28 -06:00
})
}