1 module polyplex.core.content.gl.textures; 2 import polyplex.core.content.textures; 3 import polyplex.utils.logging; 4 import polyplex.core.render; 5 import polyplex.core.render.gl.gloo; 6 import polyplex.core.render.gl.shader; 7 import polyplex.core.color; 8 import std.stdio; 9 10 11 alias GlTexture2D = GlTexture2DImpl!(GL_RGBA, 4); 12 13 public class GlTexture2DImpl(int mode = GL_RGBA, int alignment = 4) : Texture2D { 14 private: 15 Texture tex; 16 17 static int MAX_TEX_UNITS = -1; 18 19 protected: 20 override void rebuffer() { 21 glPixelStorei(GL_UNPACK_ALIGNMENT, alignment); 22 if (tex !is null) { 23 UpdatePixelData(image.Pixels); 24 return; 25 } 26 tex = new Texture(); 27 28 Bind(); 29 tex.Image2D(TextureType.Tex2D, 0, mode, image.Width, image.Height, 0, mode, GL_UNSIGNED_BYTE, image.Pixels.ptr); 30 Unbind(); 31 32 // Set max texture units. 33 if (MAX_TEX_UNITS == -1) { 34 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &MAX_TEX_UNITS); 35 Logger.Info("Set max texture units to: {0}", MAX_TEX_UNITS); 36 } 37 } 38 public: 39 override uint Id() { 40 return tex.Id; 41 } 42 43 Texture GLTexture() { 44 return tex; 45 } 46 47 this(TextureImg img) { 48 Logger.VerboseDebug("Created GL Texture from image: {0}", img.InternalName); 49 super(img); 50 } 51 52 this(Color[][] colors) { 53 super(colors); 54 } 55 56 ~this() { 57 destroy(tex); 58 } 59 60 override void UpdatePixelData(ubyte[] data) { 61 Bind(); 62 if (image !is null) image.SetPixels(data); 63 glTexSubImage2D(TextureType.Tex2D, 0, 0, 0, image.Width, image.Height, mode, GL_UNSIGNED_BYTE, data.ptr); 64 Unbind(); 65 } 66 67 /** 68 Binds the texture. 69 */ 70 override void Bind(int attachPos = 0, Shader s = null) { 71 if (s is null) { 72 tex.Bind(TextureType.Tex2D); 73 return; 74 } 75 if (!s.HasUniform("ppTexture")) throw new Exception("Texture2D requires ppTexture sampler2d uniform to attach to!"); 76 if (attachPos > MAX_TEX_UNITS) attachPos = MAX_TEX_UNITS; 77 if (attachPos < 0) attachPos = 0; 78 79 tex.Bind(TextureType.Tex2D); 80 tex.AttachTo(attachPos); 81 } 82 83 /** 84 Unbinds the texture. 85 */ 86 override void Unbind() { 87 tex.Unbind(); 88 } 89 }