Sunday, 21 October 2018

Cellular automata in JPCT

I was looking for a diversion this week so i decided to attempt to recreate Conways Game of Life using shaders in JPCT for Android:

I wanted to see if it could be done, and figure implementing to run in a shader in the GPU will be a lot faster than running it on a device CPU.

This is because Conways Game of Life could be called an "embarrassingly parallel" problem, as long as all cell calculations are completed by the next tick of course.

I reused code i wrote while attempting to create a fluid dynamics effect (failed project) as some of the methods to implement it, were similar, ie. passing the comutations back and forth between two textures.

The four basic rules of Conways Game of Life (taken from wikipedia) are:

  1. Any live cell with fewer than two live neighbors dies, as if by underpopulation.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by overpopulation.
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
 I was able to implement this using the GLSL step function in two lines as show below.
I used step functions native to GLSL to avoid IF statements, as branching can slow down shaders.

float newval = ( step(neighbourcells.x,3.0) * step(  2.0 ,  neighbourcells.x)) * cell.x;newval += step(neighbourcells.x, 3.0)*step(  3.0 ,  neighbourcells.x); /

Below is a screen shot of this running on my android device. 

Because it's running at the device screen resolution you really have to zoom in to make out the cells.

I plan to keep going back to this to allow users to draw to the screen and make cosmetic changes etc.