glFramebufferTexture2D
Attaches a 2D texture to the bound framebuffer so rendering writes into it.
Signature
void glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
How it works
Plugs a texture into one attachment slot of the FBO. Afterwards, drawing writes into the texture, and later you can sample that same texture in a shader. Use this when you need to READ the result (color for post-processing, depth for shadow maps). If you never read it, a renderbuffer is enough.
Parameters
GL_FRAMEBUFFER (or DRAW/READ variant).
Which slot.
Common values
- GL_COLOR_ATTACHMENT0 … n
- Color outputs. The fragment shader's out variables write here (location 0 → attachment 0).
- GL_DEPTH_ATTACHMENT
- Depth buffer.
- GL_STENCIL_ATTACHMENT
- Stencil buffer.
- GL_DEPTH_STENCIL_ATTACHMENT
- Combined depth + stencil (e.g. GL_DEPTH24_STENCIL8).
GL_TEXTURE_2D, or a cube face GL_TEXTURE_CUBE_MAP_POSITIVE_X + i.
The texture (already allocated with the right format).
Mip level to render into, usually 0.
Tips & pitfalls
Never sample a texture while it is attached to the FBO you are drawing into — the result is undefined (feedback loop).
Errors
When the call is invalid it does nothing and sets an error, which glGetError returns:
- GL_INVALID_OPERATION
- Framebuffer 0 is bound, or textarget does not match the texture type.
Example
1GLuint color;
2glGenTextures(1, &color);
3glBindTexture(GL_TEXTURE_2D, color);
4glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, w, h, 0, GL_RGBA, GL_FLOAT, nullptr);
5glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
6
7glBindFramebuffer(GL_FRAMEBUFFER, fbo);
8glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color, 0);