commit 7b2d19954b7f75dfe6c90e7618d60010f261277d
parent a725c6588d5bdc8bd850bd3d90d48590da3f8f83
Author: Matsuda Kenji <info@mtkn.jp>
Date:   Tue,  3 Dec 2024 08:29:28 +0900
move texture unit to program struct
Diffstat:
2 files changed, 9 insertions(+), 11 deletions(-)
diff --git a/shader.go b/shader.go
@@ -63,8 +63,9 @@ func linkShaders(vsID, fsID uint32) (shaderID uint32, err error) {
 }
 
 type Program struct {
-	id       uint32
-	Uniforms any
+	id              uint32
+	Uniforms        any
+	nextTextureUnit uint32 // 0-indexed
 }
 
 // NewProgram creates a shader program from a vertex shader source file
@@ -94,6 +95,7 @@ func (p *Program) Use() {
 }
 
 func (p *Program) SetUniforms() error {
+	p.nextTextureUnit = 0
 	return p.setUniforms(p.Uniforms, "")
 }
 
@@ -198,12 +200,13 @@ func (p *Program) SetMat4(name string, val Mat4) error {
 
 func (p *Program) SetTexture(name string, t *Texture) error {
 	p.Use()
-	gl.ActiveTexture(t.unit)
+	gl.ActiveTexture(p.nextTextureUnit + gl.TEXTURE0)
 	gl.BindTexture(gl.TEXTURE_2D, t.id)
 	l := gl.GetUniformLocation(p.id, gl.Str(name+"\x00"))
 	if l == -1 {
 		return fmt.Errorf("no such uniform: %s", name)
 	}
-	gl.Uniform1i(l, int32(t.unit-gl.TEXTURE0))
+	gl.Uniform1i(l, int32(p.nextTextureUnit))
+	p.nextTextureUnit++
 	return nil
 }
diff --git a/texture.go b/texture.go
@@ -25,12 +25,9 @@ func loadImage(name string) (image.Image, error) {
 }
 
 type Texture struct {
-	id   uint32
-	unit uint32
+	id uint32
 }
 
-var nextUnit uint32 = gl.TEXTURE0
-
 func NewTexture(name string) (*Texture, error) {
 	return NewTextureFlip(name, false, false)
 }
@@ -62,9 +59,7 @@ func NewTextureFlip(name string, v bool, h bool) (*Texture, error) {
 		int32(rgba.Rect.Dx()), int32(rgba.Rect.Dy()), 0,
 		gl.RGBA, gl.UNSIGNED_BYTE, gl.Ptr(rgba.Pix))
 	gl.GenerateMipmap(gl.TEXTURE_2D)
-	unit := nextUnit
-	nextUnit++
-	return &Texture{id: id, unit: unit}, nil
+	return &Texture{id: id}, nil
 }
 
 func flipV(img image.Image) image.Image {