Search code examples
opengltexturesframebuffer

Clearing DRAW framebuffer only works if attached to GL_COLOR_ATTACHMENT0?


I am trying to initialize a texture with all zeros, using DRAW framebuffer as suggested by this post. However, I'm quite puzzled that my DRAW framebuffer is only cleared when I attached it to GL_COLOR_ATTACHMENT0:

    int levels = 2;
    int potW = 2; int potH = 2;
    GLuint _potTextureName;
    glGenTextures(1, &_potTextureName);
    glBindTexture(GL_TEXTURE_2D, _potTextureName);
    glTexStorage2D(GL_TEXTURE_2D, levels, GL_RGBA32F, potW, potH);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _potTextureName, 0);
    glDrawBuffer(GL_COLOR_ATTACHMENT0);

    GLuint clearColor[4] = {0,0,0,0};
    glClearBufferuiv(GL_COLOR, 0, clearColor);

Modifying the snippet to use GL_COLOR_ATTACHMENT1, retaining everything else, will NOT clear the framebuffer:

    int levels = 2;
    int potW = 2; int potH = 2;
    GLuint _potTextureName;
    glGenTextures(1, &_potTextureName);
    glBindTexture(GL_TEXTURE_2D, _potTextureName);
    glTexStorage2D(GL_TEXTURE_2D, levels, GL_RGBA32F, potW, potH);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, _potTextureName, 0);
    glDrawBuffer(GL_COLOR_ATTACHMENT1);

    GLuint clearColor[4] = {0,0,0,0};
    glClearBufferuiv(GL_COLOR, 0, clearColor);

I tried using glDrawBuffers instead as suggested here, and I also tried using glClearColor and glClear, but they all behave the same way. What am I missing here?


Solution

  • It turns out that it has todo with what I previously bind to GL_COLOR_ATTACHMENT0.

    In the second case, GL_COLOR_ATTACHMENT0 was already bound to a texture of smaller size. There is a note related to Framebuffer Completeness Rules that although there is no restriction on the texture size, the effective size of the FBO is the intersection of the sizes of all bound images. Therefore, in my second case, if the texture (1) bound to GL_COLOR_ATTACHMENT1 is bigger than what I bound to GL_COLOR_ATTACHMENT0, then the texture (1) will only be cleared partially, no matter what clear operation I used (glClear or glClearBuffer*).

    The first case turns out to work for me since I only have one texture bound to the FBO, in GL_COLOR_ATTACHMENT0.