我正在尝试渲染到帧缓冲区(与窗口/屏幕大小相同)以进行后期处理。一切都是二维的,所以应该不会有太大的麻烦。直接渲染到屏幕上效果很好。但我只得到清晰的颜色和一个空的缓冲区。将任何内容渲染到其中的唯一方法是在位置 (0,0) 处渲染一个与缓冲区大小完全相同的矩形,这很奇怪。
我尝试将随机位置渲染到缓冲区中,但没有任何效果。将缓冲区显示/渲染到屏幕有效。
这是我创建缓冲区的方式:
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
std::cout << "frame buffer fbo: " << fbo << std::endl;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
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, texture, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cout << "error creating screen buffer width: " << width << " height: " << height << std::endl;
}
else {
std::cout << "created screen buffer width: " << width << " height: " << height << std::endl;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
顶点着色器:
#version 330 core
layout (location = 0) in vec2 vertex;
uniform mat4 projection;
void main() {
gl_Position = projection * vec4(vertex.x, vertex.y, 0.0f, 1.0f);
}
片段着色器:
#version 330 core
uniform vec4 in_color;
out vec4 FragColor ;
void main() {
FragColor = in_color;
}
渲染投影矩阵:
glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(this->width), static_cast<GLfloat>(this->height), 0.0f, -1.0f, 1.0f);
渲染到缓冲区的代码:
// binding and clearing the buffer to render into it
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glViewport(0, 0, width, height);
glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// render the rectangle
renderer->drawRectangle(0, 0, 10, 10, glm::vec4(1.0f, 0.0f, 1.0f, 1.0f));
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, resolutionWidth, resolutionHeight);
// rendering main screen showing the quad
结果是这样的(以一半大小呈现到屏幕的缓冲区): Empty Quad/framebuffer showing clear color
最佳答案
我在实现这个时遵循了本教程:https://learnopengl.com/Advanced-OpenGL/Framebuffers
作为我的解决方案,我只是更改了屏幕着色器以接受我的顶点/纹理数据。然后我注意到实际的缓冲区数据非常好......
顶点着色器:
#version 330 core
layout (location = 0) in vec4 aPos;
out vec2 TexCoords;
void main()
{
TexCoords = aPos.zw;
gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);
}
片段着色器:
#version 330 core
out vec4 FragColor;
in vec2 TexCoords;
uniform sampler2D screenTexture;
void main()
{
FragColor = texture(screenTexture, TexCoords);
}
关于c++ - 渲染到帧缓冲区/纹理显示为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56892460/