6

I'm quite a bit confused about framebuffers. What I want to do is using a framebuffer with multiple textures attached, fill every texture and then use a shader to combine (blend) all textures to create a new output. Sounds easy? yeah that's what I thought too, but I don't understand it.

How can I pass the currently binded texture to a shader?

toolchainX
  • 1,998
  • 3
  • 27
  • 43
Donny
  • 549
  • 2
  • 10
  • 24

1 Answers1

9

What you need is to put the texture in a specific slot, then use a sampler to read from it. In your app:

GLuint frameBuffer;
glGenFramebuffersEXT(1, &frameBuffer); //Create a frame buffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer); //Bind it so we draw to it
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, yourTexture, 0); //Attach yourTexture so drawing goes into it

//Draw here and it'll go into yourTexture.

glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); //Unbind the framebuffer so that you can draw normally again

//Here we put the texture in slot 1.
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, yourTexture);
glActiveTexture(GL_TEXTURE0); //Don't forget to go back to GL_TEXTURE0 if you're going to do more drawing later

//Now we tell your shader where to look.
GLint var = glGetUniformLocationARB(yourShaderProgram, "yourSampler");
glUniform1i(var, 1); //We use 1 here because we used GL_TEXTURE1 to bind our texture

And in your fragment shader:

uniform sampler2D yourSampler;

void main()
{
    gl_FragColor = texture2D(yourSampler, whateverCoordinatesYouWant);
}

You can use this with GL_TEXTURE2 and so on to access even more textures in your shader.

andyvn22
  • 14,696
  • 1
  • 52
  • 74
  • and further I would have to select the drawbuffer, right? thus having something like: glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, yourTexture); //draw GLint var = glGetUniformLocationARB(yourShaderProgram, "yourSampler"); glUniform1i(var, 1); //We use 1 here because we used GL_TEXTURE1 to bind our texture – Donny Sep 09 '11 at 06:58
  • 3
    @Donny You are mixing two completely different things (namely rendering to a framebuffer and reading from a previously rendered texture). – Christian Rau Sep 09 '11 at 07:22
  • What I'm trying to do is rendering to a framebuffer, take that result in a shader. The idea is that this how i can have many different textures all generatad by rendering into the framebuffer. As a result i want to mix all these textures. Is this possible? – Donny Sep 09 '11 at 07:31
  • I've edited my answer to include the framebuffer part as well. – andyvn22 Sep 09 '11 at 15:11
  • Can you define yourTexture? – Tyguy7 Dec 16 '15 at 01:09