Use depth buffer in a Shader

Hi !

I’d like to make a post processing effet that detects depth contrast to make a kind of cartoon effect.
My idea was to use an Fbo, take its depth layer and make a contour detection with a shader.
OF warns me that I should use ofFbo::Setting, the problem is that there is no documention in the OF web site. An other thing I was wondering, a depth buffer has only one layer (grey scales) so I was wondering who it should be dealt in my fragment shader.

Has any one any help or documentation about this ?

Thanks

Nico.

1 Like

Hi Nico,

To use depth you have to use an ofFbo::Settings object.

ofFbo fbo;
ofFbo::Settings settings;
settings.width = width;
settings.height	= height;
settings.internalformat = GL_RGB; // or GL_RGBA?
settings.useDepth = true;
settings.depthStencilAsTexture = true;
fbo.allocate(settings);

Then use in the shader send it as a uniform texture:

shader.setUniformTexture("depth", fbo.getDepthTexture(), 0);

Although when I used the depth texture I didnt have access for some unknown reason, and had to paint it first on a new fbo in the color buffer, and then use this depthFbo.getTexture() to access the depth information:

depthFbo.begin();
ofClear(0);
ofSetColor(255);
fbo.getDepthTexture().draw(0,0);
depthFbo.end();

shader.setUniformTexture("depth", depthFbo.getTexture(), 0);

Tell me if you are able to use the getDepthTexture() directly.

To use it in the fragment shader, as it is a grayscale image, RGB channels contain the same information, so simply use depth.r to access the values.

Cheers

@Hennio Thank you very much for this very clear and precise answer! I didn’t that the fbo could be allocated this way. Using depth buffers is a bit more tricky than I expected indeed.

I’ll try your methode during the week and I’ll give you feedback.

Cheers,

Nicolas

also to be get anything in the depth texture you need to enable depth testing using ofEnableDepthTest() of glEnable(GL_DEPTH_TEST) otherwise the graphics card won’t write to the depth butffer

It’s okay with this, the main problem was how to get the depth buffer to make post processing effect.
Juste a question, before writing the post, I tried to do

ofTexture myTexture = fbo.getDepthTexture();
shader.setUniformTexture("depth", myTexture, 0);

instead of

depthFbo.begin();
ofClear(0);
ofSetColor(255);
fbo.getDepthTexture().draw(0,0);
depthFbo.end();
shader.setUniformTexture("depth", depthFbo.getTexture(), 0);

I was wondering why It didn’t work