Stencil shadows

This demo shows how you can use the stencil buffer to create shadows. The basic WebGL code in this demo is based on a demo from LearningWebGL which is an excellent place to start learning WebGL.

Finding the silhouette
Each polygon in the object is checked if it's facing the light. If the polygon faces the light source then the sides are added to a list, if the line already exists in the list then the line is removed from the list. Every line in the list has a start and end vertex.

Calculating the volume
A vector is caluclated from the light source to each of the vertices in the line list. The vector is flipped -to make it point away from the light-, normalized and scaled. The shadow volume sides are build from these vectors which create the sides of the volume. The end caps are created based on the polygons which face the light.

Rendering the volume
Most of the rendering of the volume is about removing stuff... The volumes are only rendered in the stencil buffer. The front facing polygons decrease the stencil value, the back facing polygons increase the stencil value. The polygon fragments which don't touch any surface cancel each other out.

Rendering the shadow
After the scene is rendered and the shadows are rendered in the stencil buffer then all values which are higher than the start value of the stencil buffer are made darker with a blended polygon. The darkness depends on the stencil value, if more shadows overlap then the shadow is made darker.

The source of this demo is published under the Creative Commons Attribution/Share-Alike license.

Download the source

Several people have contacted me that this demo doesn't work on Firefox. During the development I've tested this demo on an older beta version of Firefox (4.0b7) which worked fine however after updating Firefox the demo didn't work anymore.

Place a new comment

Copyright © Arno van der Vegt 2010, 2011  Disclaimer