#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 );

uniform int  raycastMode;

vec3 rayEntrancePosition;
vec3 rayExitPosition;
vec3 rayDirection;



layout(location = 0 ) out vec4 fragColor;


//volume:
uniform float stepDistance; //also used as slice 0.0-1.0





//z == b;
vec4 singleSliceZ( float pos, vec4 returnColorWhenNoPlaneCut ){
	if( rayExitPosition.b < pos && rayEntrancePosition.b < pos ) return returnColorWhenNoPlaneCut;
	else if( rayExitPosition.b > pos && rayEntrancePosition.b > pos ) return returnColorWhenNoPlaneCut;
	
	float percent = ( pos - rayEntrancePosition.b)/(rayExitPosition.b - rayEntrancePosition.b);
	vec3 position = rayDirection * percent + rayEntrancePosition; //position of the cut through the slice plane
	float val = texture( volumeTex3D, position).r;
	val /= (volMaxVal - volMinVal); //normaliziation
	vec4 retcol = texture( transferFunctionTex, val );
	//return vec4( retcol * retcol.a );	
	return retcol;
}


vec4 multiSliceZ(){
	if( rayDirection.z == 0.0 ) return backgroundColor;
	vec4 color = vec4( 0.0, 0.0, 0.0, 0.0 );
	if( rayDirection.z > 0.0 ){
		float posz = 0.0;
		while( color.a < 1.0 && posz < 1.0 ){
			vec4 colorNew = singleSliceZ( posz, vec4(0.0, 0.0, 0.0, 0.0 ) );
			color = colorNew * colorNew.a + color * (1.0 - colorNew.a);
			posz += stepDistance;
		}
	}
	else {
		float posz = 1.0;
		while( color.a < 1.0 && posz > 0.0 ){
			vec4 colorNew = singleSliceZ( posz, vec4(0.0, 0.0, 0.0, 0.0 ) );
			color = colorNew * colorNew.a + color * (1.0 - colorNew.a);
			posz -= stepDistance;
		}
	}
	return clamp( color, 0.0, 1.0 );
}



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

	fragColor = multiSliceZ();
}

