title: GLSL - computing normals of fragments
body: <p>I'm trying to create a program that displays a globe with terrain, and does all Lat/Long/Alt to XYZ (ECEF) on the GPU.</p>
  
  <p>I've already written a working vertex shader that translates XYZ that represents Longitude, Latitude and Altitude (respectively) to their correct XYZ (using ECEF).</p>
  
  <p>What I can't get done right is the lighting.</p>
  
  <p>I've managed to light each vertex correctly using directional lights as long as there is no terrain data. Terrain data is not lighted correctly and I can't get different slopes to have correct shades.</p>
  
  <p>This is the vertex shader I'm using:</p>
  
  <pre><code>const float a = 6378137.0;
  const float f = 0.003352810664747480719845528618;
  
  varying vec3 Normal;
  varying vec3 ecPos;
  
  vec3 LatLonAltToEcef(in vec3 latLonAlt)
  {
      vec3 v = latLonAlt;
  
      float cosLat = cos(radians(v.y));
      float sinLat = sin(radians(v.y));
      float nfs = (1.0 - f) * (1.0 - f);
  
      float C = 1.0 / (sqrt(cosLat * cosLat + nfs * sinLat * sinLat));
      float S = nfs * C;
  
      float lon = radians(v.x);
      float h = v.z;
  
      v.x = (a * C + h) * cosLat * cos(lon) / a;
      v.y = (a * C + h) * cosLat * sin(lon) / a;
      v.z = (a * S + h) * sinLat / a;
  
      return v;
  }
  
  vec4 LatLonAltToEcef(in vec4 latLonAlt)
  {
      vec3 ecef = LatLonAltToEcef(latLonAlt.xyz);
      return vec4(ecef.x, ecef.y, ecef.z, latLonAlt.w);
  }
  
  void main(void)
  {
      vec4 v = LatLonAltToEcef(gl_Vertex); //x=lon, y=lat, z=alt
      ecPos = vec3(gl_ModelViewMatrix * v);
  
      Normal = normalize(gl_NormalMatrix * v.xyz);
      vec4 lightPos = LatLonAltToEcef(gl_LightSource[0].position);
      vec3 lightDir = normalize(gl_NormalMatrix * lightPos.xyz);
      float NdotL = max(dot(Normal, lightDir), 0.0);
      vec4 diffuse = gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse;
  
      gl_FrontColor =  NdotL * diffuse;
      gl_Position = gl_ModelViewProjectionMatrix * v;
  }
  </code></pre>
  
  <p>In order to draw a globe grid this is what needs to be done:</p>
  
  <pre><code>for (float lat = -90; lat &lt; 90; lat += 5)
  {
      glBegin(GL_LINE_LOOP);
      for (float lon = -180; lon &lt; 180; lon += 5)
          glVertex3f(lon, lat, 0);
      glEnd();
  }
  
  for (float lon = -180; lat &lt; 180; lon += 5)
  {
      glBegin(GL_LINE_LOOP);
      for (float lat = -90; lon &lt; 90; lon += 5)
          glVertex3f(lon, lat, 0);
      glEnd();
  }
  </code></pre>
  
  <p>Can any one please direct me how to shade the terrain correctly?</p>