#extension GL_ARB_texture_rectangle : enable

uniform sampler2DRect backFaces;
uniform sampler2DRect frontFaces;
uniform sampler3D volumeData;

uniform float stepSize;
uniform float threshold;
uniform float lum;

void main(void)
{
   vec3 rayStart = vec3(texture2DRect(backFaces, gl_TexCoord[0].st).rgb);
   vec3 rayEnd = vec3(texture2DRect(frontFaces, gl_TexCoord[0].st).rgb);
   vec3 rayDirection = rayEnd - rayStart; 
   int iterations =int(length(rayDirection)/stepSize);
   vec3 stepVector = normalize(rayDirection)*stepSize;
   vec3 currentPos=rayStart;
   vec4 color = vec4(0.0,0.0,0.0,1.0);
   vec4 maxColor=vec4( 0.0, 0.0, 0.0, 0.0);
   for(int i = 0; i < iterations; i++){
      color = texture3D(volumeData, currentPos.xyz);
      
      if(color.x > threshold){
         if(color.x > maxColor.w){
            maxColor = color.xyzx;
         }
      }
      if (maxColor.w > 0.98){
		 break;
	  }
     
      currentPos += stepVector; 
   }
   gl_FragColor = maxColor * lum;
}