将gl_PrimitiveID输出到自定义帧缓冲区对象(FBO)时出现问题

时间:2012-02-13 16:44:35

标签: opengl glsl gpgpu opengl-3

我有一个非常基本的片段着色器,我想将'gl_PrimitiveID'输出到我定义的片段缓冲区对象(FBO)。下面是我的片段着色器:

#version 150

uniform vec4 colorConst;

out vec4 fragColor;
out uvec4 triID;

void main(void)
{ 
   fragColor = colorConst;
   triID.r = uint(gl_PrimitiveID);
}

我设置了这样的FBO:

  GLuint renderbufId0;
  GLuint renderbufId1;
  GLuint depthbufId;
  GLuint framebufId;


  // generate render and frame buffer objects
  glGenRenderbuffers( 1, &renderbufId0 );
  glGenRenderbuffers( 1, &renderbufId1 );
  glGenRenderbuffers( 1, &depthbufId   );
  glGenFramebuffers ( 1, &framebufId   );


  // setup first renderbuffer (fragColor)
  glBindRenderbuffer(GL_RENDERBUFFER, renderbufId0);
  glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA,    gViewWidth, gViewHeight);


  // setup second renderbuffer (triID)
  glBindRenderbuffer(GL_RENDERBUFFER, renderbufId1);
  glRenderbufferStorage(GL_RENDERBUFFER, GL_RGB32UI, gViewWidth, gViewHeight);


  // setup depth buffer
  glBindRenderbuffer(GL_RENDERBUFFER, depthbufId);
  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, gViewWidth, gViewHeight);


  // setup framebuffer
  glBindFramebuffer(GL_FRAMEBUFFER, framebufId);  
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbufId0);
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_RENDERBUFFER, renderbufId1);
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,  GL_RENDERBUFFER, depthbufId  );


  // check if everything went well
  GLenum stat = glCheckFramebufferStatus(GL_FRAMEBUFFER);  
  if(stat != GL_FRAMEBUFFER_COMPLETE) { exit(0); }


  // setup color attachments
  const GLenum att[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
  glDrawBuffers(2, att);


  // render mesh
  RenderMyMesh()


  // copy second color attachment (triID) to local buffer
  glReadBuffer(GL_COLOR_ATTACHMENT1);
  glReadPixels(0, 0, gViewWidth, gViewHeight, GL_RED, GL_UNSIGNED_INT, data);

由于某些原因,glReadPixels给我一个'GL_INVALID_OPERATION'错误?但是,如果我将renderbufId1的内部格式从'GL_RGB32UI'更改为'GL_RGB'并且我在glReadPixels中使用'GL_FLOAT'而不是'GL_UNSIGNED_INT'那么一切正常。有谁知道为什么我得到'GL_INVALID_OPERATION'错误以及如何解决它?

是否有另一种输出'gl_PrimitiveID'的方法?

PS:我想输出'gl_PrimitiveID'的原因如下:Picking triangles in OpenGL core profile when using glDrawElements

1 个答案:

答案 0 :(得分:3)

  

glReadPixels(0,0,gViewWidth,gViewHeight,GL_RED,GL_UNSIGNED_INT,data);

如上所述on the OpenGL Wiki,您需要在传输真实整数数据时使用GL_RED_INTEGER。否则,OpenGL将尝试在其上使用浮点转换。

BTW,请确保您使用glBindFragDataLocation设置片段着色器输出所使用的缓冲区。或者,如果您使用的是GLSL 3.30或更高版本,则可以set it up explicitly in the shader