OpenGL Render to Texture

Render to texture is a very handy functionality.
Imagine your game allows for some character customization. You have the body, some different hats, different clothes and other small stuff. Now the easiest way to render this is to just draw it piece by piece every frame. With the proper Z coordinates everything falls in place.

But you now have like 4-5 draw calls for one single object. Worse, you might have different textures and swamping textures is expensive.

What Render to Texture allows is to render those pieces into another texture that you might use later. So you need to draw all pieces once into a new texture, save it and use that from now on.

Of course this is a simple example, there are way cooler ways to use RTT’s.

OpenGL supports fast crossplatform offscreen rendering through the GL_EXT_framebuffer_object extension.

To render to a texture using the framebuffer object you must

Create a framebuffer object

glGenFramebuffersEXT(1, &myFBO);

Bind the framebuffer object

glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, myFBO);

Attach a texture to the Frame Buffer Object

glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, myTexture, 0);

If you need depth testing, create and attach a depth renderbuffer

glGenRenderbuffersEXT(1, &myRB);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, myRB);

Init as a depth buffer

glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, width, height);

Attach for depth

glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, myRB);

Render the stuff you need like you would do normally.

Unbind the Frame Buffer Object

 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); 
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

Use the texture you rendered to the regular way.

One Comment

  1. Great tutorial! It seems faster (and powerful) than using glCopyTex{Sub}Image. Do you have any numbers about it (on iOs devices)?

Leave a Reply