Search code examples
c++openglmatrixglsltextures

Accessing matrix as texture in glsl shader


I have a matrix which has 149 rows and 210 cols. I want to sent it to shader to do some calculation. Values of the matrix are between 9-128. I've used the following for binding it to the texture:

m_GLTextureNNZ = new QOpenGLTexture(QOpenGLTexture::Target::Target2DArray);
m_GLTextureNNZ->create();
m_GLTextureNNZ->bind(indx);
m_GLTextureNNZ->setMinificationFilter(QOpenGLTexture::Nearest); 
m_GLTextureNNZ->setMagnificationFilter(QOpenGLTexture::Nearest);
m_GLTextureNNZ->setLayers(1);
m_GLTextureNNZ->setFormat(QOpenGLTexture::R8U);
m_GLTextureNNZ->setSize(m_sizeNZ2DCoeff_r,m_sizeNZ2DCoeff_c,1);
m_GLTextureNNZ->setWrapMode(QOpenGLTexture::ClampToEdge);
m_GLTextureNNZ->allocateStorage(QOpenGLTexture::Red, QOpenGLTexture::UInt8);

m_GLTextureNNZ->setData(0, 0, QOpenGLTexture::Red, QOpenGLTexture::UInt8, m_NNZ.data());

and in the shader I want to access a specific row and col of this texture:

uniform usampler2DArray NNZ;
vec3 getTexCoord(ivec2 indx, ivec3 tsize )
 {
  // ivec3 size = textureSize()
  return vec3( (indx.x+0.5)/tsize.x , (indx.y+0.5)/tsize.y , tsize.z);
 }
 .
 .
 .
 ivec3 patchedTexSize = textureSize(NNZ,0);
 vec3 texCoord = getTexCoord( ivec2(0,0),  ivec3(patchedTexSize.xy,0));

 uint iNNZ =  texture(NNZ, texCoord).r;

So based on my matrix (0,0) should have a value of 1. however I'm not getting this value. Is there something that I'm missing?

EDIT: So I tested with all zeros matrix and the value that I get from texture lookup, no matter what the texcoords are is 2^8-1.


Solution

  • The problem was that my data was int and I was trying to create an unsigned bit texture. So I converted my data to uint8_t and it works. Also, I needed to add glPixelStorei(GL_UNPACK_ALIGNMENT, 1); to be sure the alignment of the pixels are correct.