#version 400

uniform sampler2D rayEntranceTexture; 
uniform sampler2D rayExitTexture;

uniform sampler3D volumeTex3D;
uniform float	  volMinVal;
uniform float     volMaxVal;

uniform sampler1D transferFunctionTex;

in vec2 		  fragmentTexCoords;

vec4 backgroundColor = vec4( 0.15, 0.1, 0.15, 0.0 );

vec3 rayEntrancePosition;
vec3 rayExitPosition;
vec3 rayDirection;



layout(location = 0 ) out vec4 fragColor;


//volume:
uniform float 	stepDistance; 
uniform int 	sliceNumber;



//DVR things:
//r == x;
vec4 singleSliceX(){
	float pos = float(sliceNumber) * stepDistance;
	clamp( pos, 0.0, 1.0 );
	if( rayExitPosition.r < pos && rayEntrancePosition.r < pos ) return backgroundColor;
	else if( rayExitPosition.r > pos && rayEntrancePosition.r > pos ) return backgroundColor;
	
	float percent = ( pos - rayEntrancePosition.x)/(rayExitPosition.r - rayEntrancePosition.r);
	clamp( percent, 0.0, 1.0 );

	vec3 position = rayDirection * percent + rayEntrancePosition; //position of the cut through the slice plane
	float val = texture( volumeTex3D,  position ).r; //get volume value
	val /= (volMaxVal - volMinVal); //normaliziation
	vec4 col = texture( transferFunctionTex, val );
	return vec4( col );


	//for DoF set fragment depth:
	gl_FragDepth = percent;
}







const float aperture = 5; //=f/i
const float zf = 0.5; //distance which should be in focus
const float f = 50.0; //focal length will belater set through program


vec4 calcDoF( vec3 pos ){
	float A = f/aperture;
	float cimg = A * (zf - pos.z)/pos.z * f / (zf - f);
	return vec4(cimg, cimg, cimg, 1.0); 
}




void main(void)
{	
	rayEntrancePosition = texture( rayEntranceTexture, fragmentTexCoords).rgb;
	rayExitPosition = texture( rayExitTexture, fragmentTexCoords).rgb;
	rayDirection =  rayExitPosition - rayEntrancePosition;

	fragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
	if( rayDirection == vec3( 0.0, 0.0, 0.0 ) ){
		fragColor = backgroundColor;
	} else {
		fragColor = singleSliceX();
	}

}

