Search code examples
algorithm2dpolygonsegment

2D polygon vertex normal facing inward/outward?


I want to test if a vector (a polygon vertex normal actually) is facing outward or inward. The polygon winds CW, edges goes from A (filled circle) to B (stroked circle). I have these normals a a result of preliminary calculations, now I want to test their facing.

enter image description here

Like this. Gray normals should be invalid while green normals should be validated. Probably I could do it by calculating angles, then simply compare them, but I really want to spare trigonometric calls here.

Is there any cheap method that compare only the "slopes" somehow? Something like this Bryce Boe CCW algorithm in this http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/


Solution

  • If you take the normal vector together with the vector formed by the two points of the segment (tail to head is clockwise), then to get from the segment vector to the normal you have to move counter clockwise. Call the normal N and the segment vector S, the counter-clockwise check becomes:

    if(cross(S, N) > 0)
       // Bad
    else
       // Good
    

    The cross product is computed this way:

    int cross(Vector p, Vector q)
    {   return (p.x*q.y - p.y*q.x);
    }
    

    So if the normal is N = (0, 1) and S = (1, 0), the cross product gives 1*1 - 0*0 = 1 > 0 and this tells you that the normal is pointing out.