OpenGL渲染到纹理(FBO)不起作用

时间:2011-10-27 17:50:43

标签: c++ opengl fbo

我正在尝试使用FBO渲染纹理,然后显示纹理,但我得到的只是一个黑色矩形。我的代码是:

初​​始化:

#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glext.h>
#include <assert.h>

// ...
GLuint fbo_, rbo_, tex_;

glGenFramebuffers(1, &fbo_);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);

glGenRenderbuffers(1, &rbo_);
glBindRenderbuffer(GL_RENDERBUFFER, rbo_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width_, height_);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo_);

glGenTextures(1, &tex_);
glBindTexture(GL_TEXTURE_2D, tex_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width_, height_, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glGenerateMipmap(GL_TEXTURE_2D);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_, 0);

assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);

glBindFramebuffer(GL_FRAMEBUFFER, 0);

渲染给FBO:

glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0, 0, width_, height_);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
//draw stuff
glPopAttrib();
glBindFramebuffer(GL_FRAMEBUFFER, 0);

使用纹理(问题可能在上面的代码中,因为如果我只使用一些静态纹理,下面的代码可以工作):

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_);

glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex3f(x_, y_, 0);
glTexCoord2f(width_, 0);
glVertex3f(x_ + width_, y_, 0);
glTexCoord2f(width_, height_);
glVertex3f(x_ + width_, y_ + height_, 0);
glTexCoord2f(0, height_);
glVertex3f(x_, y_ + height_, 0);
glEnd();

你能帮我发现问题吗?

2 个答案:

答案 0 :(得分:4)

如果您要依赖默认纹理环境,请确保附加的纹理为complete

答案 1 :(得分:1)

我遇到了同样的问题,并使用了genpfault的建议来创建完整纹理。不幸的是,我没有足够的声誉来添加评论,所以我在这里添加了这个答案。不过,下面的代码可能会为您节省一些时间:

// generate full viewport texture
    glGenTextures(1, &fb_tex);
    glBindTexture(GL_TEXTURE_2D, fb_tex);
    // IMPORTANT: texture must be COMPLETE (mipmaps must be specified..
    // or the following parameters can be used if there are none)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);

    glTexImage2D(
        GL_TEXTURE_2D,
        0,
        GL_RGBA,
        width,
        height,
        0,
        GL_RGBA,
        GL_UNSIGNED_BYTE,
        NULL
        );

我在原始代码中唯一更改的是两个用glTexParameteri添加两行。可以根据您想要/拥有的mipmap数量更改参数。