uniform sampler2D tex_exit;
uniform sampler2D tex_entry;
uniform sampler3D tex_intensity;
uniform sampler1D tex_transfer;

void main (void) 
{
  const float dz = 0.003;
  const int maxrange = 1000;
  vec4 transferred, intensity;
  vec4 Result = vec4(0.0, 0.0, 0.0, 0.0); 
  vec4 entry_point = texture2D(tex_entry, vec2(gl_TexCoord[0]));
  vec4 exit_point = texture2D(tex_exit, vec2(gl_TexCoord[0]));
  float dist = distance(entry_point, exit_point)/dz;
  int maxiter = int(floor(dist));
  vec3 diff = (exit_point.xyz - entry_point.xyz)/dist;
  vec3 point = entry_point.xyz;
  //point +=diff*(abs(noise1(gl_TexCoord[0])+0.5))*dz;
  
  if (entry_point.w == 0.0) discard;
  else
  {
    for(int i = 0; i < maxrange; i++)
    {
      intensity = texture3D(tex_intensity, point);
      transferred = texture1D(tex_transfer, intensity.x);
      Result.xyz += (1.0 - Result.w) * transferred.w * transferred.xyz;
      Result.w += (1.0 - Result.w) * transferred.w;
      point +=diff;
      if ((Result.w >= 1.0) || (i >= maxiter)) break;
    }
    gl_FragColor = Result;
  }
}
