generateNormals function
Generate vertex normals based on a list of positions
and indices
.
normals
is assumed to be zeroed out, and much match positions
in length.
indices
is assumed to represent a triangle list.
Implementation
void generateNormals(
Vector3List normals, Vector3List positions, Uint16List indices) {
final p0 = Vector3.zero(),
p1 = Vector3.zero(),
p2 = Vector3.zero(),
norm = Vector3.zero();
// Loop through every polygon, find it's normal, and add that to the vertex
// normals.
for (var i = 0; i < indices.length; i += 3) {
final i0 = indices[i], i1 = indices[i + 1], i2 = indices[i + 2];
positions
..load(i0, p0)
..load(i1, p1)
..load(i2, p2);
p1.sub(p0);
p2.sub(p0);
// Store the normalized cross product of p1 and p2 in p0.
p1.crossInto(p2, p0).normalize();
// Add the face normal to each vertex normal.
normals.load(i0, norm);
normals[i0] = norm..add(p0);
normals.load(i1, norm);
normals[i1] = norm..add(p0);
normals.load(i2, norm);
normals[i2] = norm..add(p0);
}
// Loop through all the normals and normalize them.
for (var i = 0; i < normals.length; ++i) {
normals.load(i, norm);
normals[i] = norm..normalize();
}
}