opengltexturesglreadpixels

getting a crash while using glReadPixels to map texture in memory


I'm trying to use glReadPixels to map a texture in memory to be able to use openGL's immutable storage feature.

I'm using deferred shading so I prepare my G-Buffers as following:

glGenFramebuffers(1, &_gBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, _gBuffer);
glGenTextures(1, &_pos3dTex);
glBindTexture(GL_TEXTURE_2D, _pos3dTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
GLuint layout = glGetFragDataLocation(_progID, "positionTexture");
...
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + layout, GL_TEXTURE_2D, _pos3dTex, 0);
...
unsigned int attachments[1] = { GL_COLOR_ATTACHMENT0 + layout };
glDrawBuffers(1, attachments);

glGenRenderbuffers(1, &_rboDepth);
glBindRenderbuffer(GL_RENDERBUFFER, _rboDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _rboDepth);

And then I want to map my texture in memory so I can use immutable storage:

//Bind Data
glGenBuffers(1, &_pos3dPbo);
glBindBuffer(GL_PIXEL_PACK_BUFFER, _pos3dPbo);
//w*h*4 (Channels)*4(size of float)
glBufferData(GL_PIXEL_PACK_BUFFER,width*height*4* 4, 0, GL_STREAM_READ);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

glBindFramebuffer(GL_FRAMEBUFFER, _gBuffer);
glReadBuffer(GL_COLOR_ATTACHMENT0 + layout);
glPixelStorei(GL_PACK_ALIGNMENT, 4);//4 channels

glReadPixels(0, 0, width, height, GL_RGBA,GL_FLOAT,NULL);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

//Reading
glBindBuffer(GL_PIXEL_PACK_BUFFER, _pos3dPbo);
void* outPos3d = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

//Releasing 
glBindBuffer(GL_PIXEL_PACK_BUFFER, _pos3dPbo);
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

I'm getting an "Access Violation" just after the glReadPixels function. What Am I doing wrong plz?


Solution

  • You are unbinding your GL_PIXEL_PACK_BUFFER before the glReadPixels, so the NULL pointer will be interpreted relative to your client memory address space, and trying to copy the data to there will almost certainly result in a crash.