Create Frame Buffer Object OpenGL

In OpenGL, frame buffer is the final destination in the rendering pipeline. When we create a window for our OpenGL application, it automatically create frame buffer object for us. However we need to create our own frame buffer object in some cases, such as offscreen rendering. OpenGL applications in iOS also need to create frame buffer object. In this post, I will share with you how we can create a frame buffer object (FBO).

Here is the code to create a FBO with 1 color attachment and depth buffer. This is the most common FBO we will use:

In the example above, we use texture for color attachment and render buffer object (RBO) for depth attachment of the FBO. In OpenGL, both types are supported for the FBO. However it prefers render buffer object to texture due to performance. Textures are used if we want the Render-To-Texture feature in our application. As for depth buffer, in some cases after rendering we need to use depth buffer for post processing, then we need to create a texture and attached it to FBO so that we can use use the texture for processing. Here is the code how we create depth buffer for FBO using texture:

That’s for depth buffer of FBO. Now if our FBO need to have stencil buffer to support stencil testing, we have to create and attach it to the FBO. OpenGL support GL_DEPTH24_STENCIL8 format type for texture and render buffer object (24 bit for depth buffer, 8 bit for stencil) and this is most people did to support depth and stencil buffers. For render buffer object, we just need to change the glRenderbufferStorage and glFramebufferRenderbuffer functions to:

For texture, we need to change glTexImage2D and glFramebufferTexture2D functions:

That’s about creating FBO to support render-to-texture features, depth and stencil testing. Hope it helps! =)

  • Hien

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA , inScreenWidth, inScreenHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);

    Why the format is BGRA instead of RGBA ? IOS optimization ?

    • Gia Thuy

      Hi bro, I don’t know whether BGRA format can be an optimization for iOS or not. But i have read some forums about texture format and they said from memory pixels are read as 0xAABBGGRR, and it’s better to set the pixel format as BGBA, for performance I think. And most of image formats such as BMP, TGA, JPG store pixels as BGRA format in memory.

  • Hien

    IOS, yes, texture is stored in BGRA. In fact if turn on png optimization flag, ios will do the internal conversion from RGBA to BGRA. Others, I’m not sure, depends on device, but interesting find :-D, never thought about it.

  • assassini

    Hey, thanks for sharing.

    I was initially having some trouble getting a depth buffer texture to work, but turns out that I was just using a wrong format. Works great with GL_DEPTH24_STENCIL8 and GL_UNSIGNED_INT_24_8.