varying vec4 terrain_pos;


// PGM     //
uniform vec4 camPos;
uniform vec4 camDirX;
uniform vec4 camDirY;
uniform vec4 camDirZ;

uniform float ratio;
uniform float hScale;

uniform vec2 texLookupScale;


uniform float waveScale;
uniform float waveOff;
// PGM //

//
void main1()
//void main()
{
    
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; //screen-aligned quad
  gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;
  



  //perform projection for the 4 quad-vertices only
  
  //vec4 tmp = vec4((gl_MultiTexCoord0.s-0.5)*2.005, (gl_MultiTexCoord0.t-0.5)*-2.005, -1.0, 0.0);
  //
vec4 tmp = vec4((gl_MultiTexCoord0.s-0.5)*2.005, (gl_MultiTexCoord0.t-0.5)*-2.005, -1.0, -1.0);
  
//  vec4 Gij = max(ratio,1.0)*tmp.x*camDirX + max((1.0/ratio),1.0)*tmp.y*camDirY + tmp.z*camDirZ;

//
  vec4 Gij = max(ratio,1.0)*tmp.x*camDirX + max((1.0/ratio),1.0)*tmp.y*camDirY + tmp.z*camDirZ + tmp.w*camDirZ;


  float t = ((camPos.y  )/(- Gij.y));


///////
    vec4 Pij = camPos + t * (Gij);

    //    texCoords = texLookupScale.st*Pij.xz;

    //    float wh = texture3D(wave3D, vec3(texCoords, 12.0*(slice_nr/16.0))).r * waveScale + waveOff;

    float wh = 0.0; // y=0.0 <==> baseplane

    //    Pij.w=1.0;

    //without branch - faster?
    vec4 valid = vec4(Pij.x, wh, Pij.z, Pij.w);
    vec4 invalid = vec4(camPos.x, -100000.0, camPos.z, Pij.w);
    terrain_pos = mix(invalid, valid, float(t>0.0));
///////
  
      
      //  terrain_pos = gl_ModelViewProjectionMatrixInverse * gl_ClipVertex;
      //  terrain_pos = gl_ProjectionMatrixInverse * gl_ClipVertex;


      
      //
  terrain_pos/=gl_Position.w;
      //        terrain_pos/=Pij.w;  
      

      //      terrain_pos = gl_ModelViewProjectionMatrix * terrain_pos;
      //      terrain_pos = gl_ModelViewProjectionMatrixInverse * terrain_pos;

      //      gl_Position = terrain_pos;

      //      terrain_pos /= gl_Position.w;

}


//void main_old() 
//
void main() 
{
  gl_TexCoord[0] = gl_MultiTexCoord0;
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
  gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;
}


 /*
void main() 
{
  gl_TexCoord[0] = gl_MultiTexCoord0;

  //NO STRETCH
  gl_Position = vec4(gl_MultiTexCoord0.s*2.0-1.0, gl_MultiTexCoord0.t*2.0-1.0, 0.0, 1.0);
}
 */
