#!BPY
"""
Name: 'Quadsorter'
Blender: 233
Group: 'Mesh'
Tip: 'Fix winding order for quad faces for all selected meshes'
Author: Yann Vernier (LoneTech)
"""

from Blender.Mathutils import Vector, CrossVecs, DotVecs

def sortface(f):
  if len(f) != 4:
    return f
  v=[Vector(list(p)) for p in f]
  v2m0=v[2]-v[0]
  # The normal of the plane
  n=CrossVecs(v[1]-v[0], v2m0)
  #k=DotVecs(v[0],n)
  #if DotVecs(v[3],n) != k:
  #  raise "Not Coplanar"
  # Well, the above test would be a good hint to make triangles.
  # Get a vector pointing along the plane perpendicular to v[0]-v[2]
  n2=CrossVecs(n, v2m0)
  # Get the respective distances along that line
  k=[DotVecs(p,n2) for p in v[1:]]
  # Check if the vertices are on the proper side
  if cmp(k[1],k[0]) == cmp(k[1],k[2]):
    #print "Bad",v
    f.v=[f[0],f[2],f[3],f[1]]

from Blender.Object import GetSelected
for obj in GetSelected():
  if obj.getType() == 'Mesh':
    mesh=obj.data
    for face in mesh.faces:
      sortface(face)
    mesh.update()

