Anti-Aliased Grid Shader

This shader provides a convenient way to visualize the level set of any value using anti-aliased lines. It uses screen-space partial derivatives to automatically compute the correct line width and falloff. Try different coordinates below to get a sense for the effect:

Screen-space partial derivatives are awesome. They let you compute the approximate partial derivative along x and y for any value, which comes in handy in many different situations. The feature was originally intended for estimating the appropriate mipmap level to use for a texture based on how fast the texture coordinates are changing across a surface. In GLSL, the partial derivative is dFdx(value) for x and dFdy(value) for y. The fwidth() function used above is equivalent to abs(dFdx(p)) + abs(dFdy(p)).

These functions may sound expensive, but they are actually really cheap. The GPU renders many pixels at once using a group of threads that execute in lock-step and all run the same program (the fragment shader). Fragment shader evaluation is always done in 2x2 blocks of pixels, which guarantees that every fragment shader always has one neighbor along x and one along y. This means the partial derivative can be computed easily using a single subtraction (finite differencing).

A good in-depth overview of rasterization can be found at Fabian Giesen's blog. It's part of a series of fantastic articles that I recommend to anyone interested in how GPUs work.