Calculating normal vectors

We're given an array of vertex positions and an array of triangles.

We want to apply the lighting equation to shade that object. Lighting requires that each vertex have a normal attribute, so we must calculate that normal.

Assume we have an array of vertex positions called positions and an array of triangles called triangles. We will generate a new array of normals, called normals, like so:

  1. Initialize a zero-valued normal for each vertex position.
  2. Find the normal for each triangle and add it to each adjacent vertex.
  3. Renormalize to ensure that all new normal vectors have unit length.

In pseudocode:

〈Normal Calculation〉 ≡

  normals = []
  foreach vertex in positions
    Push $\V{n}$ = [0, 0, 0] onto normals.

  foreach triangle $[i_0, i_1, i_2]$ in triangles
    $\V{a}$ = normalize(positions[$i_1$] − positions[$i_0$])
    $\V{b}$ = normalize(positions[$i_2$] − positions[$i_0$])

    $\V{n}$ = normalize($\V{a}\times\V{b}$)

    normals[$i_0$] = normals[$i_0$] + $\V{n}$
    normals[$i_1$] = normals[$i_1$] + $\V{n}$
    normals[$i_2$] = normals[$i_2$] + $\V{n}$

  foreach normal $\V{n}$ in normals
    $\V{n}$ = normalize($\V{n}$)