uniform sampler3D volumeTex;
uniform sampler1D transferTex;
uniform sampler2D backfaceTex;
uniform int steps;
varying vec4 pos;
varying vec3 Light;
varying vec3 HalfVector;

void main(void)
{
	vec2 backfaceCoord = ((pos.xy/pos.w)+1.0)/2.0;
	vec3 entryPoint = gl_TexCoord[0].stp;
	vec3 exitPoint = texture2D(backfaceTex, backfaceCoord).rgb;
	vec3 direction = exitPoint - entryPoint;
	float len = length(direction);
	direction = normalize(direction);
	float stepLen = 2.5/float(steps);
	direction *= stepLen;
	vec3 currentPoint = entryPoint;
	float currentLen = 0.0;
	vec4 currentVolData;
	vec4 currentColor;
	vec3 currentNormal;

	vec4 accColor = vec4(0.0,0.0,0.0,0.0);
	
	for (int i = 0; i < steps; i++)
	{
		currentVolData = texture3D(volumeTex,currentPoint);
		currentColor =  texture1D(transferTex, currentVolData.a).bgra;
		currentNormal = currentVolData.xyz - 0.5;
		currentNormal = normalize(gl_NormalMatrix * currentNormal);
		
		vec4 Diffuse = gl_LightSource[0].diffuse * max(dot(currentNormal, -Light),0.0);
		vec4 Ambient = gl_LightSource[0].ambient;
		vec4 Specular = gl_LightSource[0].specular * pow(max(dot(currentNormal,-HalfVector),0.0), gl_FrontMaterial.shininess);
		currentColor.rgb = (Ambient.rgb + Specular.rgb  + Diffuse.rgb) * currentColor.rgb;

		accColor.rgb = accColor.rgb + (1.0 - accColor.a) * currentColor.rgb * currentColor.a;
		accColor.a = accColor.a + (1.0 - accColor.a) * currentColor.a;
		if (currentLen > len || accColor.a >= 1.0) break;
		currentPoint += direction;
		currentLen += stepLen;
	}
	gl_FragColor = accColor;
}
