go-opengl-pixel/pixelgl/texture.go

65 lines
1.2 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 BeginEnder
tex uint32
}
// NewTexture creates a new texture with the specified width and height.
// The pixels must be a sequence of RGBA values.
2016-11-23 11:06:55 -06:00
func NewTexture(parent BeginEnder, width, height int, pixels []uint8) (*Texture, error) {
2016-11-23 10:29:28 -06:00
texture := &Texture{parent: parent}
err := DoGLErr(func() {
2016-11-23 10:29:28 -06:00
gl.GenTextures(1, &texture.tex)
gl.BindTexture(gl.TEXTURE_2D, texture.tex)
2016-11-23 11:06:55 -06:00
2016-11-23 10:29:28 -06:00
gl.TexImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
int32(width),
int32(height),
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
gl.Ptr(pixels),
)
gl.GenerateMipmap(gl.TEXTURE_2D)
2016-11-23 11:06:55 -06:00
2016-11-23 10:29:28 -06:00
gl.BindTexture(gl.TEXTURE_2D, 0)
})
2016-11-23 11:06:55 -06:00
if err != nil {
return nil, errors.Wrap(err, "failed to create a texture")
}
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() {
Do(func() {
gl.DeleteTextures(1, &t.tex)
})
}
2016-11-23 10:29:28 -06:00
// Begin binds a texture.
func (t *Texture) Begin() {
t.parent.Begin()
Do(func() {
gl.BindTexture(gl.TEXTURE_2D, t.tex)
})
}
// End unbinds a texture.
func (t *Texture) End() {
Do(func() {
gl.BindTexture(gl.TEXTURE_2D, 0)
})
t.parent.End()
}