2

我正在尝试使用 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();

你能帮我找出问题吗?

4

2 回答 2

4

如果您要依赖默认纹理环境,请确保您附加的纹理是完整的。

于 2011-10-27T17:53:42.257 回答
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 数量更改参数。

于 2014-03-29T23:03:53.950 回答