uniform sampler3D volume;
uniform float focus;
uniform float blackAlpha;

uint wang_hash(uint seed)
{
    seed = (seed ^ 61) ^ (seed >> 16);
    seed *= 9;
    seed = seed ^ (seed >> 4);
    seed *= 0x27d4eb2d;
    seed = seed ^ (seed >> 15);
    return seed;
}

float rand(uint value)
{
	return float(wang_hash(value)) * (1.0 / 4294967296.0);
}

void main(void)
{
	vec4 texel = texture3D(volume, gl_TexCoord[0].xyz);

	vec3 color = vec3(0);

	float light = 0.0;
	float lightSum = 0.0;
	for (float j = -1.0; j <= 1.0; j += 0.05)
	{
		float sample;
		float accum = 0.0;
		float sum = 0.0;
		vec3 offset = vec3(0,0,0);
  
		for (uint i = 0; i < 100; i++)
		{
			offset = vec3(
					vec2((-1.0 + 2.0 * vec2(rand(81*i+0), rand(81*i+13))) * 0.1 * (j)),
					j * 0.25
				);
			sample = texture3D(volume, gl_TexCoord[0].xyz + offset).a;

			accum += sample;
			sum++;
		}
		accum /= sum;

		float w = 1.0;
		if (abs(j) > 0.0001 && abs(j) > focus)
		{
			w=0.0;
		}
		light += accum * w;
		lightSum += w;
	}

	light /= lightSum;

	//color = vec3(0.5, 1.8, 0.1) * light * 1.5;

	color = vec3(1,1,1) * light * 2.0;

	gl_FragData[0] = vec4(color, mix(1.0, texel.a * 2.0, blackAlpha)) * gl_Color;
}
