Search code examples
opengltextures

Does a frame buffer attached to a texture have to be bound to a texture unit?


I'm trying to render to a frame buffer. I did this:

    renderer.gl_context.make_current();
    renderer.gl.GenFramebuffers(1, &mut fbo);
    renderer.gl.BindFramebuffer(gl::FRAMEBUFFER, fbo);
    renderer.gl.GenTextures(1, &mut tex);
    renderer.gl.BindTexture(gl::TEXTURE_2D, tex);
    renderer.gl.TexImage2D(
        gl::TEXTURE_2D,
        0,
        gl::RGB as i32,
        width as i32,
        height as i32,
        0,
        gl::RGB,
        gl::UNSIGNED_BYTE,
        std::ptr::null() as *const libc::c_void,
    );
    renderer.gl.TexParameteri(
        gl::TEXTURE_2D,
        gl::TEXTURE_MIN_FILTER,
        gl::LINEAR.try_into().unwrap(),
    );
    renderer.gl.TexParameteri(
        gl::TEXTURE_2D,
        gl::TEXTURE_MAG_FILTER,
        gl::LINEAR.try_into().unwrap(),
    );
    renderer.gl.FramebufferTexture2D(
        gl::FRAMEBUFFER,
        gl::COLOR_ATTACHMENT0,
        gl::TEXTURE_2D,
        tex,
        0,
    );

but the drawing code makes use of other textures as well, and they are bound to GL_TEXTURE0 to GL_TEXTURE_2. I'm always calling renderer.gl.BindFramebuffer(gl::FRAMEBUFFER, fbo) before drawing, but the drawing calls use GL_TEXTURE0 to GL_TEXTURE_2, so where is the tex texture bound? Should I bind it to a texture unit before drawing? Should this texture unit be different from GL_TEXTURE0 to GL_TEXTURE_2?


Solution

  • You don't have to bind the framebuffer texture to a texture unit while render to the FBO. The texture is associate with the framebuffer object, and when you bind the FBO before rendering, everything will be setup correctly.

    In your code, you only need the binding for TexParameteri and TexImage2D, but even FramebufferTexture2D does not need the texture to be bound.

    As a rule of thumb: If a method takes the handle to an object, then it doesn't need the object to be bound.