OpenGL ES - 使用或不使用 FBO 时颜色不同

OpenGL ES - Colors are different with or without FBO

我目前正在使用 OpenGL ES 2.0 在 iPhone 上绘制对象(图像、矩形)。

有两种模式:

A) 没有 FBO :

  1. 绘制对象
  2. 渲染到屏幕

B) 与 FBO

  1. 绑定FBO
  2. 绘制对象
  3. 将 FBO 渲染到屏幕

场景绘制顺序为:

  1. 用 glClearColor 绘制红色(或黑色)颜色 (1, 0, 0, 1) 的背景
  2. 绘制透明度颜色为 (1, 1, 1, 0.5) 的纹理

这是结果(左边没有 FBO,右边有 FBO):

1) 没有透明度的图像:两者相同

2) 透明度设置为 0.5,红色背景:两者不同

3) 透明度设置为 0.5,黑色背景:右同 1) 没有透明度

以下是我创建 FBO 的方法:

GLint maxRenderBufferSize;
glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &maxRenderBufferSize);

GLuint textureWidth = (GLuint)self.size.width;
GLuint textureHeight = (GLuint)self.size.height;

if(maxRenderBufferSize <= (GLint)textureWidth || maxRenderBufferSize <= (GLint)textureHeight)
    @throw [NSException exceptionWithName:TAG
                                   reason:@"FBO cannot allocate that much space"
                                 userInfo:nil];

glGenFramebuffers(1, &fbo);
glGenRenderbuffers(1, &fboBuffer);

glBindFramebuffer(GL_FRAMEBUFFER, fbo);

glGenTextures(1, &fboTexture);
glBindTexture(GL_TEXTURE_2D, fboTexture);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fboTexture, 0);

glBindRenderbuffer(GL_RENDERBUFFER, fboBuffer);

GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if(status != GL_FRAMEBUFFER_COMPLETE)
    @throw [NSException exceptionWithName:TAG
                                   reason:@"Failed to initialize fbo"
                                 userInfo:nil];

这是我的片段着色器:

gl_FragColor = (v_Color * texture2D(u_Texture, v_TexCoordinate));

发现问题,这一行是我的 render-FBO-to-window 函数中的问题:

glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

我刚刚删除了它,因为在此步骤中我不需要 alpha 混合。