PostADay-Round2#1 – Calculating surface normals in C++

Given a quad, this is how you can calculate the normals for each face.
This works for triangles, as well as quad.

Loop through each face, and pass in 3 verticies. If you have a quad ABCD pass in ABD. For example for the front facing face on this cube, I would pass in, v2, v3, v0

// cube ///////////////////////////////////////////////////////////////////////
//    v6----- v5
//   /|      /|
//  v1------v0|
//  | |     | |
//  | |v7---|-|v4
//  |/      |/
//  v2------v3

This is in C++ which supports operator overloading, so keep that in mind, when you see p2-p1, its doing: (p2.x-p1.x; p2.y-p1.y; p2.z-p1.z; )

// 
Vec3f RibbonMesh::calcNormal( const Vec3f &p1, const Vec3f &p2, const Vec3f &p3 )
{
    Vec3f V1= (p2 - p1);
    Vec3f V2 = (p3 - p1);
    Vec3f surfaceNormal;
    surfaceNormal.x = (V1.y*V2.z) - (V1.z-V2.y);
    surfaceNormal.y = - ( (V2.z * V1.x) - (V2.x * V1.z) );
    surfaceNormal.z = (V1.x-V2.y) - (V1.y-V2.x);
 
 
    // Dont forget to normalize if needed
    return surfaceNormal;
}