Stencil Routing

I wrote a quick OpenGL prototype implementing the stencil routing technique described by Purcell in the paper “Photon mapping on programmable graphics hardware.” The basic technique involves dividing the render target into a two dimensional grid and rendering points centered in the grid cells with the point size set to cover the entire cell. The stencil buffer is initialized so that each stencil ref in a cell counts from $ 0 $ to $ n-1 $, where $ n $ is the number of pixels in the cell. The stencil test is set to pass when the stencil buffer equals $ n-1 $, and the stencil operation is set to always increment. This configuration ensures that only one pixel is rendered in the cell for each point and more importantly provides a means to group data together in a common location without the need to predetermine unique destination addresses.
 

 
This prototype randomly distributes points around a 32×32 pixel render target. Each point is colored according to the grid cell in which it belongs. Stencil routing is used to tightly pack all the points in a cell together beginning at the top-right corner. Press any key on the keyboard to toggle stencil routing off, and the points will return to their original locations. Clicking the left mouse button will randomly redistribute the points around the render target.
 
The program is written in C++ and uses the OpenGL extensions EXT_framebuffer_object, EXT_packed_depth_stencil and ARB_pixel_buffer_object. While I would have preferred to use a texture for the depth-stencil render target, I ran into a bug on one of my test machines that caused the memory passed to glTexImage2D and glTexSubImage2D to become tiled on depth-stencil textures smaller than 128×128, so the sample code is implemented using a renderbuffer instead. The initial stencil buffer state is created as a pixel unpack buffer during application start and is copied to the depth-stencil render target every frame using glDrawPixels.
 
I would like to provide a short disclaimer that I do not have access to ATI hardware, so it is very probable that this program will only work on nVidia graphics cards.
 


download win32 source + binary
 

USER INPUT -

LEFT MOUSE - randomly redistribute points
KEY PRESS  - toggle stencil routing on or off