问题
I've successfully created a frame buffer object and created a texture containing the depth map of my scene. I know I'm doing this correctly since I apply my texture to a rectangle and it looks just fine :
Now I'd like to read the values from the texture I've created in my main program and not inside the shaders. Looking into it I found out about two functions, namely: glGetTexImage() and glReadPixels(). Since I'm quite new to openGL, the documentation about these brings more questions than answers. After looking at the codes of others in here, this is the closet I've gotten to a solution :
renderSceneOnFrameBuffer();//I'm excluding the first pass code since it works fine
GLfloat *data = new GLfloat(1024 * 768);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, fbTexture);
glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, data);//Access Violation Error
// Rectangle
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glUseProgram(rectShaderProgram);
glBindVertexArray(rectangleVAO);
glUniform1i(khTextureLocation, 0);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
I get access violation error when using glGetTexImage. What am I doing wrong?
I'll include the lines of code where I declare my FBO in case it matters:
glGenFramebuffers(1, &FBO);
glBindFramebuffer(GL_FRAMEBUFFER, FBO);
glGenTextures(1, &fbTexture);
glBindTexture(GL_TEXTURE_2D, fbTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1024, 768, 0, GL_DEPTH_COMPONENT,
GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
fbTexture, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
Also,I'm getting the same violation error when using glReadPixels() like this
`GLfloat *data = new GLfloat(1024 * 768);
glBindFramebuffer(GL_READ_FRAMEBUFFER, FBO);
glReadPixels(0, 0, 1024, 768, GL_DEPTH_COMPONENT, GL_FLOAT, data);`
回答1:
The frame buffer might have multiple attachments along with depth.Use glReadPixel() when want to read back the frame buffer attachment.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
data = (GLfloat *) malloc(1024* 768 * sizeof(GLfloat));
assert(data!=nullptr);
glBindFramebuffer(GL_READ_FRAMEBUFFER, fboId);
glReadBuffers(GL_NONE); // Do this call only if you dont have any other attachment that color in Frame buffer
glReadPixels(0, 0, 1024, 768, GL_DEPTH_COMPONENT, GL_FLOAT, &data[0]);
glGetTexture() is used for reading data from textures.
Also one more thing. Use sized formats when you create framebuffer texture like GL_DEPTH_COMPONENT32F-> will map to readpixel as GL_DEPTH_COMPONENT, GL_FLOAT.
来源:https://stackoverflow.com/questions/62423688/cant-use-glgetteximage-to-read-a-depth-map-texture