Part of the Khronos Group
OpenGL.org

The Industry's Foundation for High Performance Graphics

from games to virtual reality, mobile phones to supercomputers

Results 1 to 2 of 2

Thread: Calculating normals in vertex shader

  1. #1
    Newbie Newbie
    Join Date
    Dec 2016
    Posts
    4

    Calculating normals in vertex shader

    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:

    Code :
    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 so I don't think it's calculating the normal correctly. If anyone knows what is going wrong I would be happy to know.

  2. #2
    Newbie Newbie
    Join Date
    Dec 2016
    Posts
    4
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •