#version 400

in vec2 fragTexCoord;
out vec4 result;

uniform sampler2D lastStep;

void main ( void )
{
	// Lookup the current pixel to check if it's "alive" in game-of-life terms
	bool alive = texture( lastStep, fragTexCoord ).x < 0.5;

	// Find out how many neighbors are "alive"
	float neighborCount = 0;
	neighborCount += 
		(texture( lastStep, fragTexCoord+vec2(1.0/256.0,0.0) ).x < 0.5 ? 1.0 : 0.0);
	neighborCount += 
		(texture( lastStep, fragTexCoord+vec2(-1.0/256.0,0.0) ).x < 0.5 ? 1.0 : 0.0);
	neighborCount += 
		(texture( lastStep, fragTexCoord+vec2(0.0,1.0/256.0) ).x < 0.5 ? 1.0 : 0.0);
	neighborCount += 
		(texture( lastStep, fragTexCoord+vec2(0.0,-1.0/256.0) ).x < 0.5 ? 1.0 : 0.0);
	neighborCount += 
		(texture( lastStep, fragTexCoord+vec2(1.0/256.0,1.0/256.0) ).x < 0.5 ? 1.0 : 0.0);
	neighborCount += 
		(texture( lastStep, fragTexCoord+vec2(-1.0/256.0,1.0/256.0) ).x < 0.5 ? 1.0 : 0.0);
	neighborCount += 
		(texture( lastStep, fragTexCoord+vec2(1.0/256.0,-1.0/256.0) ).x < 0.5 ? 1.0 : 0.0);
	neighborCount += 
		(texture( lastStep, fragTexCoord+vec2(-1.0/256.0,-1.0/256.0) ).x < 0.5 ? 1.0 : 0.0);
		
	// Default -> pixel dies
	result = vec4( 1.0 );
	
	// If there were too many neighbors... We die
	if (neighborCount > 3.1) return;
	
	// If there were too few neighbors... We die
	if (neighborCount < 1.9) return;
		
	// If we're already dead, we need 3 neighbors to be come alive
	if (!alive && neighborCount < 2.9) return;

	// We're ALIVE!!!
	result = vec4( 0.0 );
}