Search code examples
c++openglglsl

OpenGL texture function always return 0 on integer data


I'm working on a deferred shading pipeline, and i stored some information into a texture, and this is the texture attached to my gbuffer

// objectID, drawID, primitiveID
glGenTextures(1, &_gPixelIDsTex);
glBindTexture(GL_TEXTURE_2D, _gPixelIDsTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32UI, _width, _height, 0, GL_RGB_INTEGER, GL_UNSIGNED_INT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

And this is how i write IDs into it:

// some other gbuffer textures...
layout (location = 4) out uvec3 gPixelIDs;

gPixelIDs = uvec3(objectID, drawID, gl_PrimitiveID + 1);

After the geometry pass, i can read from it using the following code:

struct PixelIDs {
    GLuint ObjectID, DrawID, PrimitiveID;
}pixel;

glBindFramebuffer(GL_READ_FRAMEBUFFER, _gBufferFBO);
glReadBuffer(GL_COLOR_ATTACHMENT4);
glReadPixels(x, y, 1, 1, GL_RGB_INTEGER, GL_UNSIGNED_INT, &pixel);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);

So far, so good. The output is what i need.

But when i try to use this shader to display the object id on the screen(just for debug purpose)

uniform sampler2D gPixelIDsTex;

uint objID = uint(texture(gPixelIDsTex, fragData.TexCoords).r);
FragColor = vec4(objID, objID, objID, 1);

the result is 0 (I used the Snipaste to read the pixel color), which means i cant use the data in my following process.

Other gbuffer textures with data format in floating point (eg. vec4) all be fine, so i dont know why texture always return 0 on it


Solution

  • uniform sampler2D gPixelIDsTex;
    

    Your texture is not a floating-point texture. It's an unsigned integer texture. So your sampler declaration needs to express that. Just as you write to a uvec3, so too must you read from a usampler2D.