c++openglglsl

How to get texelFetch to read and return ints?


The function texelFetch is working fine with floats, but not with ints.

This is the working example with floats. Host code:

float Test[5][2] = { 2.0f, 2.0f };

GLuint tex;
GLuint tbo;
glGenBuffers(1, &tbo);
glBindBuffer(GL_TEXTURE_BUFFER, tbo);
glBufferData(GL_TEXTURE_BUFFER, sizeof(Test), Test, GL_STATIC_DRAW);
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_BUFFER, tex);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, tbo);

Fragment Shader code:

uniform samplerBuffer textureData;

void main()
{    
   vec2 TexBegin = texelFetch(textureData, 0).xy;

   if (TexBegin.x == 2)
   {
      color = vec4(1.0, 0.0, 0.0, 1.0); 
   }
   else
   {
       color = vec4(0.0, 0.0, 0.0, 1.0); 
   }
}

This is with int format, which only returns 0. Host code:

int Test[5][2] = { 2, 2 };

GLuint tex;
GLuint tbo;
glGenBuffers(1, &tbo);
glBindBuffer(GL_TEXTURE_BUFFER, tbo);
glBufferData(GL_TEXTURE_BUFFER, sizeof(Test), Test, GL_STATIC_DRAW);
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_BUFFER, tex);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32I, tbo);

Fragment Shader code:

uniform samplerBuffer textureData;

void main()
{    
   vec2 TexBegin = texelFetch(textureData, 0).xy;

   if (TexBegin.x == 2)
   {
      color = vec4(1.0, 0.0, 0.0, 1.0); 
   }
   else
   {
       color = vec4(0.0, 0.0, 0.0, 1.0); 
   }
}

Changing vec2 to ivec2 errors with: "cannot convert float to int".


Solution

  • texelFetch has different overloads for different data types:

    gvec4 texelFetch(gsamplerBuffer sampler, int P);
    

    Whenever you see a definition in the glsl spec (or docs) that contains a g like in gsamplerBuffer, this means that the the appropriate letter for the datatype has to be used: samplerBuffer for float, isamplerBuffer for integer and so on. The return value of texelFetch will then have the same type.

    For your specific case, you need to use an isamplerBuffer, then the result will be a ivec4.