我正在尝试使用帧缓冲区进行对象拾取,并尝试使用 stbi_write_png 来查看我正在渲染的内容,因为该帧缓冲区不会渲染到屏幕上。我想使用无符号整数来确定对象 ID。
这是帧缓冲区定义,我检查帧缓冲区是否有效。
glGenFramebuffers(1, &frameBufferObject);
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferObject);
glGenTextures(1, &frameBufferTexture);
glBindTexture(GL_TEXTURE_2D, frameBufferTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32UI, width, height, 0, GL_RGB_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);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, frameBufferTexture, 0);
这是渲染到帧缓冲区然后保存图像
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferObject);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderScene();
unsigned int* pixelData = new unsigned int[width * height * 3];
glReadPixels(0, 0, width, height, GL_RGB_INTEGER, GL_UNSIGNED_INT, pixelData);
unsigned char* pngData = new unsigned char[width * height * 3];
for (u64 i = 0; i < width * height; i++) {
pngData[i * 3] = pixelData[i*3] & 0xff;
pngData[i * 3 + 1] = pixelData[i * 3 + 1] & 0xff;
pngData[i * 3 + 2] = pixelData[i * 3 + 2] & 0xff;
}
stbi_write_png(path, width, height, 3, data, 0)
delete[] pixelData;
delete[] pngData;
渲染场景是这样的
bindShader();
glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, projection);
glUniformMatrix4fv(viewLocation, 1, GL_FALSE, view);
glBindVertexArray(vertexArrayObject);
glDrawArrays(GL_POINTS, 0, amountObjects);
顶点着色器
#version 330 core
layout(location=0)in vec3 location;
uniform mat4 projection;
uniform mat4 view;
mat4 getTranslationModel(vec3 loc){
mat4 toRet=mat4(1.f);//Init to identity matrix
toRet[3]=vec4(loc,1.0);//Set the translation params
return toRet;
}
void main(){
mat4 model=getTranslationModel(location);
gl_Position=projection*view*model*vec4(0,0,0,1);
}
几何着色器
#version 330 core
layout(points) in;
layout(triangle_strip, max_vertices=4) out;
const vec4 halfX=vec4(0.75,0,0,0);
const vec4 halfY=vec4(0,0.75,0,0);
void main(){
vec4 loc=gl_in[0].gl_Position;
//Top Left
gl_Position=loc-halfX+halfY;
EmitVertex();
//Bottom Left
gl_Position=loc-halfX-halfY;
EmitVertex();
//Top Right
gl_Position=loc+halfX+halfY;
EmitVertex();
//Bottom Right
gl_Position=loc+halfX-halfY;
EmitVertex();
EndPrimitive();
}
片段着色器
#version 330 core
layout(location=0)out uvec3 FragColour;
void main(){
FragColour=uvec3(255,0,0);
}
创建图像时,它只是一个黑色图像。目标是看到一个红色方块,就像我可以看到红色方块一样,我可以轻松地用对象 ID 替换该数字。