'How to store INTEGER vec2 to texture using FBO and read it by glReadPixels

I want to generate an integer texture with two channels, and I want the first channel to store the index of each vertex and the second channel to store the index of the model, so each pixel in this texture is like (vertex_id, model_id) and they are both integers. Texture binding:

glBindTexture(GL_TEXTURE_2D, id_tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RG32UI, width, height, 0, GL_RG_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);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, id_tex, 0);
glBindTexture(GL_TEXTURE_2D, 0);

Read pixels:

double x, y;
glfwGetCursorPos(window, &x, &y);
unsigned rg[2];
glReadBuffer(GL_COLOR_ATTACHMENT1);
glReadPixels(x, height - y - 1, 1, 1, GL_RG_INTEGER, GL_UNSIGNED_INT, rg);
glReadBuffer(GL_NONE);
cout << rg[0] << ' ' << rg[1] << endl;

shader:

#version 450 core
layout( location = 0 ) out vec4 scene_color;
layout( location = 1 ) out vec2 vid_mid;

flat in int index;
in vec3 FragPos;
in vec3 Position;
in vec3 Normal;

uniform int mid;

void main(){
    scene_color = vec4(Normal, 1.0);
    vid_mid = vec2(index, mid);
}

This is what I got(since the vertex index is greater than the model index, so the red color is reasonable):

But when I use glReadPixels to get the pixel color at (x, y), I got:

But what I actually want is the (vertex_id, model_id)



Solution 1:[1]

If you create your texture as GL_RG32UI, you should also make sure to store it in the correct format.

layout( location = 1 ) out vec2 vid_mid;

Assumes that you output to a float format, if you want your shader to output unsigned int, it should be :

layout( location = 1 ) out uvec2 vid_mid;

and

vid_mid = uvec2(index, mid);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mrvux