Stencil culling optimization

I optimized the code by using whats known as stencil buffer optimization as well as cleaned up a lot of test code and other features. The result below looks a bit iffy since I exaggarated the parameters for the light attenuation enough that you can’t really tell that the light gets weaker around the sphere. I’m rendering 100 point lights and one directional light currently.

deferred shading done

For the stencil optimization I basically worked from the picture below:


Where the vectors represent vectors from the camera to the screen that cross certain objects, if we base our stencil optimization on this technique we can see a few things happening. If we set the stencil test to always succeed and then increment the stencil value depending on the depth test, you can see that if you focus on the spheres front/back face, in the case of object A the sphere fails both the back and the front test, while for object C it wins both tests. Then if you look at object B you can see that it wins the front test, but fails the back test, knowing this you can set a few parameters for the stencil operation. If the back facing polygons fail the depth test you increment the value in the stencil buffer and if the front face fails the depth test you decrement the value, this ensures that only the relevant fragments will be shaded and not the entire screen like I had previously.


I didn’t run into many problems implementing this as I found some good information on how to do it. The only “problem” I had was that when I loaded my quad for the directional light I forgot to set all the triangles in a counter clockwise ordering which resulted in the culling messing up the screen a bit like in the picture below. It was easily remedied but it’s interesting to look at since it shows the result of the point light pass in the top left and how everything is merged together in the bottom right.



Now I will focus this day on cleaning up the code, making everything look a bit better and begin implementing the tiles.



Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *