#  ------------------------------------------------------------------------------------
#  gbPivot.py - Maya Python Script 
#  ------------------------------------------------------------------------------------
#
#  DESCRIPTION:
#  This script moves the pivot of an object to match the position of a selected vertex.
#  If two vertex are selected the pivot will be placed in average position.	
#
#  USAGE:
#  (PYTHON)  import gbPivot; gbPivot.pivot()
#  (MEL)     python("import gbPivot;gbPivot.pivot()")
#
#  AUTHOR:
#  Giorgio Bertolone - mail@giorgiobertolone.com - www.giorgiobertolone.com
#  Copyright (C)2010 Giorgio Bertolone - All Rights Reserved.
#
#  VERSIONS:
#  1.01 - Dec 28, 2010 - Cleaned some lines and added go back to object mode
#  1.00 - Aug 05, 2008 - Initial Release
#
#  ------------------------------------------------------------------------------------


import maya.cmds as mc

def pivot():

# check and warn if nothing is selected
	sel = mc.ls( sl=True, fl=True )
	if sel == []:
		mc.confirmDialog( title="Selection Error", message="No vertex selected. Please select one or two vertex.", button=["Ok"], defaultButton="Ok" )

# calculate number of selected vertex and warn in case of selection errors	
	verNum = mc.polyEvaluate( vc=True )
	if verNum == 0:
		mc.confirmDialog( title="Selection Error", message="No vertex selected. Please select one or two vertex.", button=["Ok"], defaultButton="Ok" )
	if verNum > 2 and sel != []:
		mc.confirmDialog( title="Selection Error", message="More than two vertex are selected. Please select only one or two.", button=["Ok"], defaultButton="Ok" )

# if only one vertex is selected
	if verNum == 1:

# get the position of the vertex
		pos = mc.xform( sel, q=True, ws=True, t=True )
		pX = pos[0]
		pY = pos[1]
		pZ = pos[2]

# move pivot to the position of the vertex 		
		selObj = mc.ls( hl=True )
		mc.xform( selObj, ws=True, rp=(pX, pY, pZ) )
		
# go back to object mode
		mc.select( selObj )		

# if two vertex are selected
	if verNum == 2:

# get the position of both vertex	
		posFir = mc.xform( sel[0], q=True, ws=True, t=True )
		posSec = mc.xform( sel[1], q=True, ws=True, t=True )
		pXFir = posFir[0]
		pYFir = posFir[1]
		pZFir = posFir[2]
		pXSec = posSec[0]
		pYSec = posSec[1]
		pZSec = posSec[2]

# calculate the average between the two
		pXTot =( posFir[0] + posSec[0] ) / 2
		pYTot =( posFir[1] + posSec[1] ) / 2
		pZTot =( posFir[2] + posSec[2] ) / 2

# move pivot to the average position 
		selObj = mc.ls( hl=True )
		mc.xform( selObj, ws=True, rp=(pXTot, pYTot, pZTot) )

# go back to object mode
		mc.select( selObj )
	

