Search code examples
openglglslshaderfragment-shaderframebuffer

Concept: what is the use of glDrawBuffer and glDrawBuffers?


I am reading the red book OpenGL programming guide when I come across these two methods, which strikes me as unnecessary since we already can specify which color buffer the output is going to go to with layout (location = ) or glBindFragDataLocation. Am I misunderstanding anything here?


Solution

  • Not all color attachments which are attached to a framebuffer have to be rendered to by a shader program. glDrawBuffers specifies a list of color buffers to be drawn into.

    e.g. Lets assume you have a frambuffer with the 3 color attchments GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 and GL_COLOR_ATTACHMENT2:

    Fragment shader

    layout (location = 0) out vec4 out_color1;
    layout (location = 1) out vec4 out_color2;
    

    drawbufferr specification:

    const GLenum buffers[]{ GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT0 };
    glDrawBuffers( 2, buffers );
    

    out_color1 sends its data to the draw buffer at index 0 (because of the location = 0 declaration). The call to glDrawBuffers above sets this buffer to be GL_COLOR_ATTACHMENT2. Similarly, out_color2 sends its data to index 1, which is set to be GL_COLOR_ATTACHMENT0. Attachment 1 doesn't get data written to it.