0

I am writing a 3ds file parser in c++. Now I am working on normals, and I found this piece of code somewhere on web:

void calculateNormals(vert a, vert b, vert c,GLfloat *nx,GLfloat *ny, GLfloat *nz){

    GLfloat Qx, Qy, Qz, Px, Py, Pz;


    GLfloat v1[3] = {a.x,a.y,a.z};
    GLfloat v2[3] = {b.x,b.y,b.z};
    GLfloat v3[3] = {c.x,c.y,c.z};

       Qx = v2[0]-v1[0];
       Qy = v2[1]-v1[1];
       Qz = v2[2]-v1[2];
       Px = v3[0]-v1[0];
       Py = v3[1]-v1[1];
       Pz = v3[2]-v1[2];

    *nx = Py*Qz - Pz*Qy;
    *ny = Pz*Qx - Px*Qz;
    *nz = Px*Qy - Py*Qx;
}

I understand almost everything, except 3 last lines. I just... can't figure out how and why it works.

Can someone explain how it's calculated?

Szczepenson
  • 55
  • 1
  • 5
  • 7
    You can calculate the normals using the [cross product (as shown here)](https://math.stackexchange.com/questions/305642/how-to-find-surface-normal-of-a-triangle), which is basically what your code is doing. – Cory Kramer May 11 '15 at 12:32
  • 1
    Here is about calculating a surface normal, as you can see in https://www.opengl.org/wiki/Calculating_a_Surface_Normal. – Mihai8 May 11 '15 at 12:34
  • 1
    The last line are computing the [cross product of two 3-vectors](http://en.wikipedia.org/wiki/Cross_product). Regarding the calculation of normals I refer you to this answer http://stackoverflow.com/a/6661242/524368 – datenwolf May 11 '15 at 18:31

2 Answers2

3

As Cyber said in comments the solution is calculating the cross product. The math is described here.

The code is turning the triangle points into the 2 vectors ( from point 1 to 2 and from point 1 to 3) then it is taking them and calculating the cross product over them.

cerkiewny
  • 2,761
  • 18
  • 36
1

It is a cross product. Note that when a vector (I,j,k) is multiplied (cross product) in (i0,j0,k0), the result is (jk0-kj0,ki0-ik0,ij0-ji0) usually normals should be normalized too if the vectors are not unit length.

Good Luck
  • 1,104
  • 5
  • 12