I am trying to implement per framgent lighting on a heightmap. I am uploading the height map to the shader as a texture and adjusting vertex heights according to respective pixels. To generate the normals I take values of four neighbouring pixels, make vectors of them and compute the cross product like so:
vec3 offset = vec3(-1.0/mapSize, 0, 1.0/mapSize);
float s1 = texture2D(sampler, texCoord + offset.xy).x;
float s2 = texture2D(sampler, texCoord + offset.zy).x;
float s3 = texture2D(sampler, texCoord + offset.yx).x;
float s4 = texture2D(sampler, texCoord + offset.yz).x;
vec3 va = normalize(vec3(1.0, 0.0, s2 - s1));
vec3 vb = normalize(vec3(0.0, 1.0, s3 - s4));
vec3 n = normalize(cross(va, vb));
and heres my lighting function
vec4 directional(Light light){
vec4 ret = vec4(0.0);
vec3 lPos = (V * vec4(light.position, 0.0)).xyz;
vec3 normal = normalize(vNormal);
vec3 lightDir = normalize(lPos);
vec3 reflectDir = reflect(-lightDir, normal);
vec3 viewDir = normalize(-vPosition);
float lambertTerm = max(dot(lightDir, normal), 0.0);
float specular = 0.0;
if(lambertTerm > 0.0){
float specAngle = max(dot(reflectDir, viewDir), 0.0);
specular = pow(specAngle, material.shininess);
}
ret = vec4(light.ambient * material.ambient + light.diffuse * material.diffuse * lambertTerm + light.specular * material.specular * specular, 1.0);
return ret;
}
This kinda works. Only the y and z axis seem to by flipped ie. if I move the light along the y axis it looks like its moving along the z axis and vice versa.
I should also point out that the function works perfectly on regular 3D models, so I assume the problem is in the generation of normals.