Reputation: 379
When Im rendering to on-screen buffer everything goes fine, but when reading pixels from FrameBuffer with glReadPixels it always returns 0.
The pseudocode is the following:
Bind texture to FrameBuffer:
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
int width, height;
width = 2;
height = 2;
float texture_data[] = {
1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f
};
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, texture_data);
GLuint framebuffer;
glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
GLint texture_coord_attribute = glGetAttribLocation(program, "texture_coord");
glEnableVertexAttribArray(texture_coord_attribute);
glVertexAttribPointer(texture_coord_attribute, 2, GL_FLOAT, GL_FALSE,
sizeof(vertices[0]), (void*)(sizeof(float) * 5));
Fragment/Vertex shaders:
static const char* vertex_shader_text =
"#version 330\n""
"attribute vec2 vPos;\n"
"attribute vec2 texture_coord;\n"
"varying vec2 Texcoord;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(vPos, 0.0, 1.0);\n"
" Texcoord = texture_coord;\n"
"}\n";
static const char* fragment_shader_text =
"#version 330\n"
"varying vec2 Texcoord;\n"
"uniform sampler2D tex;\n"
"void main()\n"
"{\n"
" gl_FragColor = texture(tex, Texcoord);\n"
"}\n";
Read Pixels in Main loop:
glViewport(0, 0, 720, 480);
glUseProgram(program);
glDrawArrays(GL_TRIANGLES, 0, 6);
GLubyte pixels[3] = {0};
glReadBuffer(GL_COLOR_ATTACHMENT0);
glReadPixels(360, 240, 1, 1, GL_RGB, GL_FLOAT, pixels);
// Any value returns 0 not only 360 and 240
printf("|%f||%f||%f|\n", pixels[0], pixels[1], pixels[2]);
glfwSwapBuffers(window);
glfwPollEvents();
This is the pipeline I follow. What is wrong here? Thanks.
Upvotes: 3
Views: 2413
Reputation: 210878
The 5th and 6th parameter (format
and type
) of glReadPixels
specifies the format and data type of the target pixel data.
Since you want to read to a buffer with the element data type GLubyte
, the type has to be GL_BYTE
.
Change your code like this:
glReadPixels(360, 240, 1, 1, GL_RGB, GL_BYTE, pixels);
Or read the data to a buffer of type GLfloat
:
GLfloat pixels[3];
glReadPixels(360, 240, 1, 1, GL_RGB, GL_FLOAT, pixels);
Note, what you do, is to read 12 bytes (sizeof(float)*3
) to a buffer with a size of 3 bytes (GLubyte pixels[3]
). This means a part of the floating point value which represents the red color channel is stored to the buffer. The rest overwrites some memory with bad access.
Upvotes: 2