opengl-deferred/types/texture/texture.go

61 lines
1.3 KiB
Go
Raw Normal View History

2024-10-11 23:02:12 +00:00
package texture
import (
"errors"
"image"
"image/draw"
_ "image/png"
"os"
2024-10-12 00:22:54 +00:00
_ "golang.org/x/image/tiff"
2024-10-11 23:02:12 +00:00
"github.com/go-gl/gl/v4.6-core/gl"
)
type Texture struct {
texture uint32
}
func (t Texture) Bind(slot uint32) {
gl.ActiveTexture(slot)
gl.BindTexture(gl.TEXTURE_2D, t.texture)
}
func (t Texture) Delete() {
gl.DeleteTextures(1, &t.texture)
}
func Load(path string) (texture Texture, _ error) {
file, err := os.Open(path)
if err != nil {
return texture, err
}
img, _, err := image.Decode(file)
if err != nil {
return texture, err
}
rgba := image.NewRGBA(img.Bounds())
if rgba.Stride != rgba.Rect.Size().X*4 {
return texture, errors.New("unsupported stride")
}
draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src)
gl.GenTextures(1, &texture.texture)
gl.ActiveTexture(gl.TEXTURE0)
gl.BindTexture(gl.TEXTURE_2D, texture.texture)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
gl.TexImage2D(
gl.TEXTURE_2D, 0, gl.RGBA,
int32(rgba.Rect.Size().X),
int32(rgba.Rect.Size().Y),
0, gl.RGBA, gl.UNSIGNED_BYTE,
gl.Ptr(rgba.Pix))
return texture, nil
}