Polygon order

Richard Suchenwirth 2004-12-08 - The corners of a polygon can come in clockwise or counter-clockwise order. The latter is to be preferred, but Tk's canvas displays both without problems. However, a clockwise-ordered polygon may indicate that a transformation (e.g. mirroring) has to take place. So I modified KBK's ccw code from convex hull, so that given a polygon as an {x y x y x y ...} list returns 1 if the polygon is counterclockwise, else 0. Should the first three points be collinear, the second to fourth are taken instead. If the polygon's points are all collinear, you get an error from one of the exprs :p

That the ccw code returns -1 for counterclockwise, 1 for clockwise, is because Kevin used conventional coordinates (where positive y goes "up"), while I used canvas coordinates, where y goes "down".


 proc counterclockwise polygon {
     foreach { x0 y0 x1 y1 x2 y2} $polygon break
     set dx1 [expr { $x1 - $x0 }]
     set dy1 [expr { $y1 - $y0 }]
     set dx2 [expr { $x2 - $x0 }]
     set dy2 [expr { $y2 - $y0 }]
     set prod1 [expr { $dx1 * $dy2 }]
     set prod2 [expr { $dy1 * $dx2 }]
     if { $prod1 > $prod2 } {return 0}
     if { $prod1 < $prod2 } {return 1}
     if { $dx1*$dx2 < 0 || $dy1*$dy2 < 0 } {return 1}
     if { $dx1*$dx1 + $dy1*$dy1 < $dx2*$dx2 + $dy2*$dy2 } {return 0}
     counterclockwise [lrange $polygon 2 end]
 }

Category Polygon | Arts and crafts of Tcl-Tk programming