Skrevet av Emne: Math: How to calculate a 3D face normal  (Lest 4320 ganger)

ATC

  • Gjest
Math: How to calculate a 3D face normal
« på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • 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:



    ATC

    • Gjest
    [Solved] Math: How to calculate a 3D face normal
    « Svar #1 på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • # 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->[X];
    $vector2[Y] = $vertex[A]->[Y] - $vertex->[Y];
    $vector2[Z] = $vertex[A]->[Z] - $vertex->[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;
    }