Ano-Tech Computers
Enter keyword:

Math: How to calculate a 3D face normal
Problem:
In 3D math, a "normal" is a perpendicular vector to a vertex (point), a vector, or a polygon/face. It is commonly used for light calculations, back face culling and other problems. Given the three vertices A / \ B C we can calculate the face normal as follows:
 
Solution:
# Calculate face vectors
my @vector1;
my @vector2;
$vector1[X] = $vertex[A]->[X] - $vertex[C]->[X];
$vector1[Y] = $vertex[A]->[Y] - $vertex[C]->[Y];
$vector1[Z] = $vertex[A]->[Z] - $vertex[C]->[Z];
$vector2[X] = $vertex[A]->[X] - $vertex[B]->[X];
$vector2[Y] = $vertex[A]->[Y] - $vertex[B]->[Y];
$vector2[Z] = $vertex[A]->[Z] - $vertex[B]->[Z];

# Calculate cross product of the face vectors
my @normal;
$normal[X] = ($vector1[Y] * $vector2[Z]) - ($vector2[Y] * $vector1[Z]);
$normal[Y] = ($vector1[Z] * $vector2[X]) - ($vector2[Z] * $vector1[X]);
$normal[Z] = ($vector1[X] * $vector2[Y]) - ($vector2[X] * $vector1[Y]);

# Normalize the cross product so we get the face normal
my $length = sqrt(
($normal[X]**2) +
($normal[Y]**2) +
($normal[Z]**2)
);
if ($length) {
$normal[X] /= $length;
$normal[Y] /= $length;
$normal[Z] /= $length;
}

 
Discuss this solution
Did this article solve your problem? Yes No Did not apply

We welcome anyone who is willing to contribute to this public knowledge base, contact siteadmin@atc.no if you have information you would like to share. The idea is not to replace the commercial support sites, but to publish those hard-to-find solutions you've found yourself looking for over and over again.

Show all articles