Thursday, 29 March 2012

Game of Life shader

This is another simple and quick shader, this time done to see how easy it would be to implement Conway's Game of Life after seeing the same logic implemented using filters. It's an ideal fit for shaders not only as the code that runs on each pixel is identical but also as the 'game' is essentially a graphics algorithm. Turned out to be every straightforward, taking only an hour to write, test and deploy here at Wonderfl.

The code implements the Life algorithm straightforwardly. The most interesting part is the threshold checking, done in three lines based on the sums of the cells around the cell being drawn and the cell itself:

    float deadTo = abs(neighbours - 3.0) < 0.5 ? 1.0 : 0.0;
    float liveTo = abs(neighbours - 2.5) < 1.0 ? 1.0 : 0.0;
    float goesTo = sampleNearest(src, outCoord()).r > 0.5 ? liveTo : deadTo;

It actually uses the red channel, but could use any or with a bit of work do all three channels at the same time, using the vector types and functions in the Pixel Bender language.

The code that runs the filter, in full, is

    dat.applyFilter(dat, dat.rect, pt, filter);

as it has no parameters to update or user interaction. The data is just a BitmapData (initially filled with random black and white cells), but it could use any graphic as source. In testing in the Pixel Bender Toolkit the effect on a photographic source is sort of a untidy posterising find-edges filter. The image could be created by a user in an editor, or the result used to generate further effects.

It's embedded below, with source available on Wonderfl and the full shader code in a comment at the end. Again the shader is embedded as base64 in the source, generated using the following command line:

openssl base64 -in Life.pbj -out Life.b64

No comments:

Post a comment