opengl 帧缓冲区对象拾取

tv6aics1  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(153)

我尝试使用帧缓冲区进行对象拾取,并尝试使用stbi_write_png来查看我正在渲染的内容,因为此帧缓冲区不会渲染到屏幕上。我想使用unsigned int来确定对象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替换那个数字。

des4xlb0

des4xlb01#

我认为你有一个错误的format参数。
(Have你试过在每一行后测试glGetError()吗?看起来很乏味,但有时这是发现问题的唯一方法。)
根据在线文档,format参数仅指定像素布局,而不是像素组件大小,因此应该是GL_RGB。
https://registry.khronos.org/OpenGL-Refpages/gl4/html/glReadPixels.xhtml

相关问题