I found an interesting blog post.
I think this should work:
// multi sampled color buffer
glGenRenderbuffersEXT(1, &colorBuffer);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, colorBuffer);
glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_RGBA8, width, height);
// multi sampled depth buffer
glGenRenderbuffersEXT(1, &depthBuffer);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthBuffer);
glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH_COMPONENT, width, height);
// create fbo for multi sampled content and attach depth and color buffers to it
glGenFramebuffersEXT(1, &mfbo);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mfbo);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, colorBuffer);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthBuffer);
// create texture
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// set your texture parameters here if required ...
// create final fbo and attach texture to it
glGenFramebuffersEXT(1, &fbo);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture, 0);
...
// rendering procedure
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mfbo);
glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0, 0, width, height);
// ... draw ...
glPopAttrib();
// copy multisampled color buffer to non-multisampled buffer
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, mfbo);
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, fbo);
glBlitFramebufferEXT(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
// you have to unbind all fbos before you can render to the main window
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
So basically I create two FBOs, one multisampled and
the other not. And when I have rendered my scene to
the multisampled one I copy only the depth part to
the non-multisampled one.
Then I can do my stencil operations in this non-multisampled
one that now has the depth values from the previous one.
This should work, right?
What do you think about this solution?