View Full Version : Calculating normals in vertex shader

12-30-2016, 12:53 PM
Hi, I have a 2D grid on the xz plane, and I'm displacing the heights of the vertices based on a heightmap (a GetHeight(vec2 pos) function in the vertex shader determines the height of each vertex). I want to calculate the normal of each vertex. My current method is not working for some reason and I don't know why. The current method I'm using is from here (https://github.com/felixpalmer/lod-terrain/blob/master/js/shaders/terrain.vert#L28):

vec3 getNormal() {
float3 normal = float3(0.0, 1.0, 0.0);
// Get 2 vectors perpendicular to the unperturbed normal, and create at point at each (relative to position)
//float delta = 1024.0 / 4.0;
float delta = (vMorphFactor + 1.0) * uScale / TILE_RESOLUTION;
vec3 dA = delta * normalize(cross(normal.yzx, normal));
vec3 dB = delta * normalize(cross(dA, normal));
vec3 p = vPosition;
vec3 pA = vPosition + dA;
vec3 pB = vPosition + dB;

// Now get the height at those points
float h = getHeight(vPosition);
float hA = getHeight(pA);
float hB = getHeight(pB);

// Update the points with their correct heights and calculate true normal
p += normal * h;
pA += normal * hA;
pB += normal * hB;
return normalize(cross(pB - p, pA - p));

So for each vertex, it's getting two perpendicular points, then finding the differences between the points and the vertex position, then cross-producting those differences to find the normal. I thought this would work, but the lighting looks really weird (https://www.dropbox.com/s/0631xxvu880f9s5/pic.png?dl=0) so I don't think it's calculating the normal correctly. If anyone knows what is going wrong I would be happy to know.

12-30-2016, 01:16 PM
I just figured out what was wrong, I'm an idiot. The noise function I was using to determine the vertex heights was essentially returning incoherent random values because I forgot to scale the inputs down, making everything look wonky. I can't delete my post but don't answer it because the normal calculation was actually working correctly and nothing needs to be fixed.