Exemplo n.º 1
0
def pieslice(pStAn, pEnAn, pR, pH=0.1):
    cyl = mc.polyCylinder(h=pH, r=pR)
    cx = mc.objectCenter(x=True)
    cy = mc.objectCenter(y=True)
    cz = mc.objectCenter(z=True)

    h = pH
    #cut the cylinder, and separate different parts
    cut = mc.polyCut(cyl,
                     cutPlaneCenter=[cx, h / 2, cz],
                     cutPlaneRotate=[0, pStAn, 0],
                     extractFaces=True,
                     extractOffset=[0, 0, 0])
    cut = mc.polyCut(cyl,
                     cutPlaneCenter=[cx, h / 2, cz],
                     cutPlaneRotate=[0, pEnAn, 0],
                     extractFaces=True,
                     extractOffset=[0, 0, 0])
    obj = mc.polySeparate(cyl)
    names = []
    for i in range(len(obj)):
        mc.rename(obj[i], 'part' + str(i))
        names.append('part' + str(i))

    #delete useless parts from the now separated cylinder
    mc.delete(names[0:2] + names[3:], s=True)
    #fill hole of the leftover pieslice
    mc.polyCloseBorder(names[2])
    #add and assign a material (which was deleted when delete was called)
    myBlinn = mc.shadingNode('blinn', asShader=True)
    mc.select(names[2])
    mc.hyperShade(assign=myBlinn)
    return names[2]
Exemplo n.º 2
0
    def pieslice(self, pStAn, pEnAn, pR, pH=0.1):
        cyl = mc.polyCylinder(h=pH, r=pR, n='stairObject')
        cx = mc.objectCenter(x=True)
        cy = mc.objectCenter(y=True)
        cz = mc.objectCenter(z=True)

        h = pH
        #cut the cylinder, and separate different parts
        cut = mc.polyCut(cyl,
                         cutPlaneCenter=[cx, h / 2, cz],
                         cutPlaneRotate=[0, pStAn, 0],
                         extractFaces=True,
                         extractOffset=[0, 0, 0])
        cut = mc.polyCut(cyl,
                         cutPlaneCenter=[cx, h / 2, cz],
                         cutPlaneRotate=[0, pEnAn, 0],
                         extractFaces=True,
                         extractOffset=[0, 0, 0])
        obj = mc.polySeparate(cyl)
        names = []
        for i in range(len(obj)):
            mc.rename(obj[i], 'part' + str(i))
            names.append('part' + str(i))

        #fill hole of the required pieslice
        mc.polyCloseBorder(names[2])
        #delete useless parts from the now separated cylinder
        mc.delete(names[0:2] + names[3:4], s=True)
        return names[2]
Exemplo n.º 3
0
	def getAxis(self):
		if self.axis!=0:
			return self.axis
		if "opposite" in self.__dict__:
		
			if 'bindPose' not in self.__dict__:
				self.bindPose= mc.dagPose(self.Muscle,q=True,bp=True)[0]
			if 'root' not in self.__dict__:
				self.root=mc.dagPose( self.bindPose, q=True, m=True )[0]
			
			offset=mc.xform(self.root,q=True,rp=True,ws=True)
			
			center=mc.objectCenter(self.muscleShape)
			opposite=mc.objectCenter(self.opposite.muscleShape)
			
			greatestDistance=-1
			axisID=-1
			
			for i in range(0,3):
				distance=abs((center[i]-offset[i])-(opposite[i]-offset[i]))
				if(distance>greatestDistance):
					   greatestDistance=distance
					   axisID=i
					   
			self.axis=axisID+1
			
			return self.axis
		else:
			return 0
Exemplo n.º 4
0
    def w12A_uiAddDistAttr(self, *args):
        #objs = []
        shaveHairs = self.getShaveHairData()
        hairs = {}
        for hair in shaveHairs:
            temp = hair[0][0] if str(type(
                hair[0])) == "<type 'tuple'>" else hair[0]
            hairs[temp] = hair
        for pfx in cmds.ls(exactType='pfxHair'):
            hairs[pfx] = pfx
            #objs.extend(  )

        objs = hairs.keys()
        #QM.delAttr(  hairs.values(), ['distCam'] )
        delAttr(objs, ['distCam'])
        cmds.addAttr(objs, ln='distCam', at='float')
        startFrame = int(cmds.playbackOptions(q=True, min=True))
        endFrame = int(cmds.playbackOptions(q=True, max=True) + 1)
        step = cmds.intSliderGrp('w12A_uiStep', q=True, v=True)

        cam = cmds.optionMenu('w12A_uiCameras', q=True, v=True)
        for f in range(startFrame, endFrame, step):
            cmds.currentTime(f, e=True)
            camCenter = cmds.objectCenter(cam)
            for obj in objs:
                objCenter = cmds.objectCenter(obj)
                dist = newOM.MPoint(camCenter).distanceTo(
                    newOM.MPoint(objCenter))
                cmds.setKeyframe(obj + '.distCam', v=dist)
Exemplo n.º 5
0
def matchObjPivot():
	uiInfo		=	MatchOivot()
	if uiInfo.result == 0: # Apply
		sourcePivot		=	uiInfo.dlg.getValue("source object")	
		targetPivot		=	uiInfo.dlg.getValue("target object")
		mkobjCenterX = cmds.objectCenter (targetPivot,x = True)
		mkobjCenterY = cmds.objectCenter (targetPivot,y = True)
		mkobjCenterZ = cmds.objectCenter (targetPivot,z = True)
		cmds.move(mkobjCenterX,mkobjCenterY,mkobjCenterZ,sourcePivot+".scalePivot",sourcePivot+".rotatePivot")
Exemplo n.º 6
0
def matchObjPivot():
    uiInfo = MatchOivot()
    if uiInfo.result == 0:  # Apply
        sourcePivot = uiInfo.dlg.getValue("source object")
        targetPivot = uiInfo.dlg.getValue("target object")
        mkobjCenterX = cmds.objectCenter(targetPivot, x=True)
        mkobjCenterY = cmds.objectCenter(targetPivot, y=True)
        mkobjCenterZ = cmds.objectCenter(targetPivot, z=True)
        cmds.move(mkobjCenterX, mkobjCenterY, mkobjCenterZ,
                  sourcePivot + ".scalePivot", sourcePivot + ".rotatePivot")
Exemplo n.º 7
0
    def makePiston(self):

        #get radius & position channels from rods
        self.topRodRadius = mc.getAttr("{0}.pistonRadius".format(
            self.topRod[0]))
        self.topRodPos = mc.getAttr("{0}.position".format(self.topRod[0]))

        self.botRodRadius = mc.getAttr("{0}.pistonRadius".format(
            self.botRod[0]))
        self.botRodPos = mc.getAttr("{0}.position".format(self.botRod[0]))

        #get position of locators and controllers

        self.topLocPos = mc.objectCenter(self.topLoc, gl=True)
        self.topRadiusPos = mc.objectCenter(self.topRod[0], gl=True)

        self.botLocPos = mc.objectCenter(self.baseLoc, gl=True)
        self.botRadiusPos = mc.objectCenter(self.botRod[0], gl=True)

        #create a group for the piston
        # use Maya's #-sign to automatically add a number to the value,
        #instead of adding a counter
        self.pistonGrp = mc.group(em=True, name="piston_GRP_#")

        #create joints between locators

        self.setJoints(self.topLocPos, self.botLocPos, self.topRadiusPos,
                       self.topLoc, self.baseLoc, self.topRodRadius, "topRod",
                       self.pistonGrp)

        self.setJoints(self.botLocPos, self.topLocPos, self.botRadiusPos,
                       self.baseLoc, self.topLoc, self.botRodRadius, "botRod",
                       self.pistonGrp)

        #delete control curves
        mc.delete(self.topRod, self.botRod)

        #select piston controls
        mc.select(self.baseLoc, self.topLoc, self.conCurve)
        #select all piston parts
        self.selection = mc.ls(sl=True)
        #loop through the parts and rename them accordingly
        for x in self.selection:
            mc.rename(x, (x + "_#"))

        #parent to piston group
        self.newSel = mc.ls(sl=True)
        mc.parent(self.newSel, self.pistonGrp)
        #delete tmp group
        mc.delete(self.tmpGrp)
        #add GRP elements to set
        mc.sets(self.pistonGrp, add=self.pistonSetName)

        mc.select(clear=True)
Exemplo n.º 8
0
    def makePiston(self):
        
        #get radius & position channels from rods
        self.topRodRadius=mc.getAttr("{0}.pistonRadius".format(self.topRod[0]))
        self.topRodPos=mc.getAttr("{0}.position".format(self.topRod[0]))
        
        self.botRodRadius=mc.getAttr("{0}.pistonRadius".format(self.botRod[0]))
        self.botRodPos=mc.getAttr("{0}.position".format(self.botRod[0]))
        
        #get position of locators and controllers
        
        self.topLocPos=mc.objectCenter(self.topLoc,gl=True)
        self.topRadiusPos=mc.objectCenter(self.topRod[0],gl=True)
        
        self.botLocPos=mc.objectCenter(self.baseLoc, gl=True)
        self.botRadiusPos=mc.objectCenter(self.botRod[0],gl=True)
        
        
        #create a group for the piston
        # use Maya's #-sign to automatically add a number to the value, 
        #instead of adding a counter
        self.pistonGrp=mc.group(em=True,name="piston_GRP_#")     
        
        #create joints between locators
        
        self.setJoints(self.topLocPos, self.botLocPos, self.topRadiusPos, 
                       self.topLoc,self.baseLoc, self.topRodRadius,
                       "topRod",self.pistonGrp)
        
        self.setJoints(self.botLocPos, self.topLocPos, self.botRadiusPos, 
                       self.baseLoc,self.topLoc, self.botRodRadius,
                       "botRod",self.pistonGrp)

        #delete control curves
        mc.delete(self.topRod,self.botRod)
        
        #select piston controls
        mc.select(self.baseLoc,self.topLoc,self.conCurve)
        #select all piston parts        
        self.selection=mc.ls(sl=True)
        #loop through the parts and rename them accordingly    
        for x in self.selection:
            mc.rename(x,(x+"_#"))
        
        #parent to piston group
        self.newSel=mc.ls(sl=True)
        mc.parent(self.newSel,self.pistonGrp)
        #delete tmp group
        mc.delete(self.tmpGrp)
        #add GRP elements to set
        mc.sets(self.pistonGrp, add=self.pistonSetName)
        
        mc.select(clear=True)
def generate(pts):
    """Takes in a list of tuples (set of 3D points) and generates a polygon model"""
    cmds.polyCreateFacet(name="shirt", p=points)
    cmds.polyTriangulate()
    cmds.polyQuad(angle=90)
    cmds.polySubdivideFacet(dv=SUBDIVISIONS)
    cmds.polyTriangulate()

    # Center shirt on origin
    centerX = cmds.objectCenter("shirt", x=True, gl=True)
    centerY = cmds.objectCenter("shirt", y=True, gl=True)
    centerZ = cmds.objectCenter("shirt", z=True, gl=True)
    cmds.move(-centerX, -centerY, -centerZ, "shirt", absolute=True)
def generate(pts):
    """Takes in a list of tuples (set of 3D points) and generates a polygon model"""
    cmds.polyCreateFacet(name="shirt", p=points)
    cmds.polyTriangulate()
    cmds.polyQuad(angle=90)
    cmds.polySubdivideFacet(dv=SUBDIVISIONS)
    cmds.polyTriangulate()
    
    # Center shirt on origin
    centerX = cmds.objectCenter("shirt", x = True, gl = True)
    centerY = cmds.objectCenter("shirt", y = True, gl = True)
    centerZ = cmds.objectCenter("shirt", z = True, gl = True)
    cmds.move(-centerX, -centerY, -centerZ, "shirt", absolute=True)
Exemplo n.º 11
0
    def changePos(*pArgs):
        turboAlignUiKemot[0] = cmds.checkBox(posX, query = True, value = True)
        turboAlignUiKemot[1] = cmds.checkBox(posY, query = True, value = True)
        turboAlignUiKemot[2] = cmds.checkBox(posZ, query = True, value = True) 
        turboAlignUiKemot[3] = cmds.radioButtonGrp(currentObj, query = True, select = True)   
        turboAlignUiKemot[4] = cmds.radioButtonGrp(targetObj, query = True, select = True)
        posValuList = turboAlignUiKemot[:3] #lista trzymająca checkboxy x y z pozycji
        #alignTargetTransforms = [] --------przetrzymuje dane o pozycji targetu       

        #==========sekcja kodu do wyznaczania pozycji odniesienia docelowego obiektu TARGET
        if turboAlignUiKemot[4] == 1:
            targetPosition = cmds.xform(alignTarget, query = True, boundingBox = True)[:3]
            
        elif turboAlignUiKemot[4] == 2:
            targetPosition = cmds.objectCenter(alignTarget)
            
        elif turboAlignUiKemot[4] == 3:
            targetPosition = cmds.xform(alignTarget, query = True, rp = True, ws = True)
            
        elif turboAlignUiKemot[4] == 4:
            targetPosition = cmds.xform(alignTarget, query = True, boundingBox = True)[3:]
            
        #==========sekcja kodu do wyznaczania pozycji odniesienia zaznaczonych obiektów CURRENT
        if turboAlignUiKemot[3] == 1:
            for obj in objectList:
                objMinimum = cmds.xform(obj, query = True, boundingBox = True)[:3]
                objCenter = cmds.objectCenter(obj)
                positionMinimum = [targetPosition[0] + (objCenter[0] - objMinimum[0]), targetPosition[1] + (objCenter[1] - objMinimum[1]), targetPosition[2] + (objCenter[2] - objMinimum[2])]
                transform = combineLists(positionMinimum, objectListInitial[objectList.index(obj)],posValuList)
                cmds.setAttr(obj + '.translate', transform[0], transform[1], transform[2])
            
        elif turboAlignUiKemot[3] == 2:
            for obj in objectList:
                transform = combineLists(targetPosition, objectListInitial[objectList.index(obj)],posValuList)
                cmds.setAttr(obj + '.translate', transform[0], transform[1], transform[2]) 
                
            
        elif turboAlignUiKemot[3] == 3:
            for obj in objectList:
                objPivot = cmds.xform(obj, query = True, rp = True)
                positionPivot = [targetPosition[0] - objPivot[0], targetPosition[1] - objPivot[1], targetPosition[2] - objPivot[2]]
                transform = combineLists(positionPivot, objectListInitial[objectList.index(obj)],posValuList)
                cmds.setAttr(obj + '.translate', transform[0], transform[1], transform[2]) 
            
        elif turboAlignUiKemot[3] == 4:
            for obj in objectList:
                objMaximum = cmds.xform(obj, query = True, boundingBox = True)[3:]
                objCenter = cmds.objectCenter(obj)
                positionMaximum = [targetPosition[0] + (objCenter[0] - objMaximum[0]), targetPosition[1] + (objCenter[1] - objMaximum[1]), targetPosition[2] + (objCenter[2] - objMaximum[2])]
                transform = combineLists(positionMaximum, objectListInitial[objectList.index(obj)],posValuList)
                cmds.setAttr(obj + '.translate', transform[0], transform[1], transform[2])
Exemplo n.º 12
0
def objToBBox():
    '''{'del_path':'Modify/objToBBox( )',
'icon':':/geometryToBoundingBox.png',
'tip' : '将物体转为box',
'usage':"""
#maya 2013.5已经有这个命令了,在convert menu下面
$fun( )""",
}
'''
    objectList = cmds.ls(sl=True, l=True, exactType='transform')
    if isinstance(objectList, str) or isinstance(objectList, unicode):
        objectList = [objectList]

    for object in objectList:
        bbsi = cmds.exactWorldBoundingBox(object, ii=True)
        bbsi = (math.fabs(bbsi[3] - bbsi[0]), math.fabs(bbsi[4] - bbsi[1]),
                math.fabs(bbsi[5] - bbsi[2]))
        pos = cmds.objectCenter(object)
        shortName = cmds.ls(object, sn=True)[0]
        box = cmds.polyCube(w=bbsi[0],
                            h=bbsi[1],
                            d=bbsi[2],
                            ch=False,
                            name=shortName + '_bbox')[0]
        cmds.setAttr(box + '.t', pos[0], pos[1], pos[2], type='double3')
 def CameraToPopDist( self ):
     camPos = Vector(mc.xform(mc.lookThru(q=True),q=True,t=True))
     if self.nearestRoot:
         popPos = Vector(mc.objectCenter(self.nearestRoot))
     else:
         popPos = self.FindNearestObjectToCamera()
     return (camPos-popPos).mag()
Exemplo n.º 14
0
    def w05_filterByMap(self, mapObj, map, objects, *args):
        if isinstance( objects, str) or isinstance( objects, unicode):
            objects = [objects]
            
        if cmds.pluginInfo("nearestPointOnMesh",query=True,l=True)==False:
            cmds.loadPlugin("nearestPointOnMesh")
        
        uvNode = ''     
        for node in cmds.listConnections('%s.worldMesh'%(mapObj), s=False):
            if cmds.objectType(node) == 'nearestPointOnMesh' and cmds.listConnections(node+'.inPosition') == None:
                uvNode = node
                break
        if uvNode == '':
            uvNode = cmds.createNode("nearestPointOnMesh", n="mapUV")
            cmds.connectAttr(mapObj+'.worldMesh[0]', uvNode+'.inMesh',f=True)
        
        data = {}
        for object in objects:     
            objPos=cmds.objectCenter(object)
            cmds.setAttr(uvNode+'.inPosition', objPos[0], objPos[1], objPos[2], type="double3")
            atu = cmds.getAttr(uvNode+'.parameterU')
            atv = cmds.getAttr(uvNode+'.parameterV')
            
            
            rgb = cmds.colorAtPoint(map, o='RGB', u=atu, v=atv)
            value = mel.eval('rgb_to_hsv <<%s, %s, %s>>'%(rgb[0], rgb[1], rgb[2]) )[2]
            data[object]=(value)
        return data

#w05_selectByMapWin()
Exemplo n.º 15
0
def crowd_convertLocatorToParticles(particleNode='new', crowdGrp=None):
    '''{'path':'Dynamics/Particles/Crowd/crowd_convertLocatorToParticles( )ONLYSE',
'icon':':/locator.png',
'usage':"""
#这个命令是将nParticleShape1_locGrp组中locator, 放到nParticleShape1_curGrp组中对应曲线上;
$fun( particleNode="nParticleShape1", crowdGrp="curve_grp" )""",
}
'''
    if not crowdGrp or not cmds.objExists(crowdGrp):
        raise IOError('%s does not exists!' % (crowdGrp))

    posLi, curveId, length, curLength = [], [], [], []
    for i, cur in enumerate(cmds.listRelatives(crowdGrp, f=True)):
        curShape = cmds.listRelatives(cur, type='nurbsCurve')[0]
        locs = cmds.listRelatives(cur, ad=True, type='locator', f=True)
        if not locs:
            continue

        for loc in cmds.listRelatives(locs, parent=True, f=True):
            posLi.append(cmds.objectCenter(loc))
            curveId.append(cmds.getAttr(loc + '.curveId'))
            length.append(cmds.getAttr(loc + '.curveLength'))
            curLength.append(cmds.getAttr(loc + '.currentLength'))

    parName = qm.qsEmit(object=particleNode,
                        position=posLi,
                        attributes=[("cus_curveId", "floatValue", curveId),
                                    ("cus_length", "floatValue", length),
                                    ("cus_currentLength", "floatValue",
                                     curLength)])
    melStr = 'global string $%s_curves[];\n$%s_curves = `listRelatives -f "%s"`;' % (
        parName, parName, crowdGrp)
    print melStr
    mel.eval(melStr)
Exemplo n.º 16
0
def resetDriverParFroWrapedTFNode(tfGrp):
    '''{'del_path':'TfCtrl/Group/resetDriverParFroWrapedTFNode(cmds.ls(sl=True)[0])',
'usage':'$fun(cmds.ls(sl=True)[0])',
}
'''

    if cmds.attributeQuery('nParShapeNode', n=tfGrp, exists=True) == False:
        raise IOError('%s have not particle to modify')
    else:
        nParShape = cmds.getAttr('%s.nParShapeNode' % (tfGrp))
        if nParShape == None or cmds.objExists(nParShape) == False:
            raiseIOError('%s not exists')

    objects = cmds.listRelatives(tfGrp, type='transform', f=True)

    posLi, radiusLi, atULi, atVLi = [], [], [], []
    for tfNode in objects:
        objPos = cmds.objectCenter(tfNode)
        bbsize = cmds.getAttr(tfNode + '.bbsi')[0]
        radius = vectorLen(bbsize) / 2
        atU = cmds.getAttr(tfNode + '.atU')
        atV = cmds.getAttr(tfNode + '.atV')
        posLi.append(objPos)
        radiusLi.append(radius)
        atULi.append(atU)
        atVLi.append(atV)

    qsEmit(object = nParShape, position=posLi, attributes=( ('cus_radiusPP', 'floatValue', radiusLi), ('goalU', 'floatValue', atULi),\

                                                               ('goalV', 'floatValue', atVLi) )     )
Exemplo n.º 17
0
def nurbsCurve_reverse(*args):
    '''{'path':'Surfaces/EditNURBS/nurbsCurve_reverse( )',
'icon':':/reverse.png',
'usage':"""
#先选择曲线,再选择一个物体,这个命令根据曲线和物体的远近,对这些曲线进行reverse操作
$fun( )"""
}
'''
    if len(args):
        curvesNode = args[0]
        refPos = args[1]
    else:
        curvesNode = cmds.ls(sl=True, l=True)[:-1]
        refPos = cmds.objectCenter(cmds.ls(sl=True, l=True)[-1])
    for obj in curvesNode:
        try:
            startPos = cmds.pointOnCurve(obj, pr=0, ch=False, p=True)
            endPos = cmds.pointOnCurve(obj, pr=1, ch=False, p=True)

            startLen = math.sqrt(
                math.pow(refPos[0] - startPos[0], 2) +
                math.pow(refPos[1] - startPos[1], 2) +
                math.pow(refPos[2] - startPos[2], 2))
            endLen = math.sqrt(
                math.pow(refPos[0] - endPos[0], 2) +
                math.pow(refPos[1] - endPos[1], 2) +
                math.pow(refPos[2] - endPos[2], 2))
            if startLen > endLen:
                cmds.reverseCurve(obj, ch=False, rpo=True)
                print 'Reversed %s' % obj
        except:
            print obj, " is not nurbscurve!"
Exemplo n.º 18
0
def FUCBoxCreator():
    pos = [0, 0, 0]
    thisW = 1
    thisH = 1
    thisD = 1

    try:
        pm.select('FUC_Box')
        pos = cmds.objectCenter('FUC_Box', gl=True)
        thisW = pm.getAttr('FUC_Box' + '.sx')
        thisH = pm.getAttr('FUC_Box' + '.sy')
        thisD = pm.getAttr('FUC_Box' + '.sz')
        pm.delete()
    except:
        pass

    try:
        pm.select('FUC_Sphere')
        posX = pm.getAttr('FUC_Sphere' + '.tx')
        posY = pm.getAttr('FUC_Sphere' + '.ty')
        posZ = pm.getAttr('FUC_Sphere' + '.tz')
        pos = [posX, posY, posZ]
        r = pm.getAttr('FUC_Sphere' + '.sx')
        thisW = r
        thisH = thisW
        thisD = thisW
        pm.delete()
    except:
        pass

    pm.polyCube(name='FUC_Box', w=1, h=1, d=1)
    pm.move(pos)
    pm.scale(thisW, thisH, thisD)
    mel.eval('setAttr "FUC_Box.overrideEnabled" 1;')
    mel.eval('setAttr "FUC_Box.overrideShading" 0;')
Exemplo n.º 19
0
def renameTargetsFromClosestSources(sources, targets, suffixe="__"):
	"""
	This definition renames the targets from closest sources.

	:param sources: Sources. ( List )
	:param targets: Targets. ( List )
	:param suffixe: Suffixe. ( String )
	"""

	for target in targets:
		targetBarycenter = cmds.objectCenter(target, gl=True)
		normes = {}
		for source in sources:
			normes[source] = norme(targetBarycenter, cmds.objectCenter(source, gl=True))
		closest = min(normes, key=lambda item: normes[item])
		cmds.rename(target, "%s%s" % (closest.split("|")[-1], suffixe))
Exemplo n.º 20
0
def parent_cluster(cluster_name):
    cluster_parent = cmds.textField('UI_cluster_clusterName', q=True, tx=True)
    cluster_parent = cluster_parent.replace (" ", "_")
    cluster_parent = cmds.createNode( 'transform', n= 'trn_' + cluster_parent, ss=True)
    centre = cmds.objectCenter("loc_guide_deformer", gl=True)
    cmds.move(centre[0], centre[1], centre[2], cluster_parent)
    cmds.cluster (name = cluster_name, bs = True, wn = (cluster_parent, cluster_parent))
    cmds.delete("loc_guide_deformer")
Exemplo n.º 21
0
def getPositions(object):
    thisType = cmds.ls(object, st=True)[1]
    if thisType != "joint":
        thisPos = cmds.objectCenter(cmds.listRelatives(object, fullPath=1, s=True)[0], gl=True)
    else:
        #thisPos = cmds.objectCenter(object, gl=True)
        thisPos = cmds.xform(object, q=True, t=True, a=True, ws=True)
    return thisPos
Exemplo n.º 22
0
    def createRig(self):
        # Create a Cube for test cases
        mc.polySphere(name='mySphere')
        objCenter = mc.objectCenter('mySphere', l=True)

        # Get the bounding box for the selected ojbject
        XYZ = mc.xform('mySphere', bb=True, q=True)
        rad = XYZ[3] / 2 * self.settings.radius
        strltPos = self.settings.lightPos
        lightP = 0.0

        if strltPos == "High":
            lightP = 5.0
        elif strltPos == "Low":
            lightP = -5.0
        else:
            lightP = 0.0

        # Create a circle to place three point lights
        mc.circle(n='curveLights', nr=(0, 1, 0), c=(0, 0, 0), sections=9, radius=rad)

        # Create lights in three positions on the curve
        loc = mc.pointOnCurve('curveLights', pr=0.0, p=True)
        #_item = mc.spotLight(name='FillLight', coneAngle=45)
        _item = self.createLight(self.fillLight, "FillLight")
        mc.move(loc[0], loc[1]+lightP, loc[2], _item, ls=True)

        loc = mc.pointOnCurve('curveLights', pr=3.0, p=True)
        #_item = mc.spotLight(name='KeyLight', coneAngle=45)
        _item = self.createLight(self.keyLight, "KeyLight")
        mc.move(loc[0], loc[1]+lightP, loc[2], _item, ls=True)

        loc = mc.pointOnCurve('curveLights', pr=6.0, p=True)
        #_item = mc.spotLight(name='RimLight', coneAngle=45)
        _item = self.createLight(self.rimLight, "RimLight")
        mc.move(loc[0], loc[1]+lightP, loc[2], _item, ls=True)

        # Create space locator and aimConstraints
        mc.spaceLocator(n='fillLocator', p=(objCenter[0], objCenter[1], objCenter[2]))
        mc.aimConstraint('fillLocator', 'FillLight', aimVector=(0.0, 0.0, -1.0))
        mc.parent('fillLocator', 'curveLights', relative=True)

        mc.spaceLocator(n='keyLocator', p=(objCenter[0], objCenter[1], objCenter[2]))
        mc.aimConstraint('keyLocator', 'KeyLight', aimVector=(0.0, 0.0, -1.0))
        mc.parent('keyLocator', 'curveLights', relative=True)

        mc.spaceLocator(n='rimLocator', p=(objCenter[0], objCenter[1], objCenter[2]))
        mc.aimConstraint('rimLocator', 'RimLight', aimVector=(0.0, 0.0, -1.0))
        mc.parent('rimLocator', 'curveLights', relative=True)

        # Create lights main locator
        mc.spaceLocator(n='lightsMainLocator', p=(objCenter[0], objCenter[1], objCenter[2]))
        mc.parent('FillLight', 'lightsMainLocator', relative=True)
        mc.parent('KeyLight', 'lightsMainLocator', relative=True)
        mc.parent('RimLight', 'lightsMainLocator', relative=True)

        # Create Main Group for the entire light rig
        mc.group('curveLights', 'lightsMainLocator', n='LightRigGroup')
Exemplo n.º 23
0
def swapWallBrick(outputNamePrefix, studHeight):
    rawSelectionDump = cmds.ls(
        sl=True, long=True
    )  #cmds.ls listing sl(selected DAG objects), long(the full names of the objects)
    ascii_encoded = [
        str(selected) for selected in rawSelectionDump
    ]  #re-encodes to ascii from unicode; don't use non-ascii characters in your object names

    #generate a list of parts to duplicate and transform. removes the first character from the string if it's a pipe.
    partsList = []
    for part in ascii_encoded:
        if part[0] == '|':
            partsList.append(part[1:])

        else:
            partsList.append(part)

    for part in partsList:
        #get spacial coordinates and rotation of the object we're replacing
        dest_coords = cmds.objectCenter(
            part, gl=True
        )  #grab XYZ coordinates as a list from the destination object
        dest_rot = cmds.xform(
            part, q=True, ws=True, ro=True
        )  #also grab euler angle rotations from the destination object

        #get size of the object we're replacing
        boundingBox = cmds.exactWorldBoundingBox(part)
        dimensions = [
            boundingBox[3] - boundingBox[0], boundingBox[4] - boundingBox[1],
            boundingBox[5] - boundingBox[2]
        ]  #in the format X, Y, Z

        #this is where the spoopyness happens, if the z coordinate be borked, look here!
        dimensions[1] = dimensions[
            1] - studHeight  #make the new box shorter in the Z axis by studHeight
        dest_coords[1] = dest_coords[1] - (
            studHeight / 2
        )  #the center points of the proxy box and the destination box are no longer the same, so we move it down by half of the stud height
        #most of the spoopiness should be done by here

        #make new cube with the specified dimensions, and move and rotate into position
        proxyCube = cmds.polyCube(w=dimensions[0],
                                  d=dimensions[1],
                                  h=dimensions[2])
        cmds.move(dest_coords[0],
                  dest_coords[1],
                  dest_coords[2],
                  proxyCube,
                  absolute=True)  #move into position
        cmds.rotate(dest_rot[0], dest_rot[1], dest_rot[2],
                    proxyCube)  #rotate into position

    print("All proxy swaps attempted!")
    print(str(len(partsList)) + " part swaps attempted.")
Exemplo n.º 24
0
def renameTargetsFromClosestSources(sources, targets, suffixe="__"):
    """
	Renames the targets from closest sources.

	:param sources: Sources.
	:type sources: list
	:param targets: Targets.
	:type targets: list
	:param suffixe: Suffixe.
	:type suffixe: str
	"""

    for target in targets:
        targetBarycenter = cmds.objectCenter(target, gl=True)
        normes = {}
        for source in sources:
            normes[source] = norme(targetBarycenter,
                                   cmds.objectCenter(source, gl=True))
        closest = min(normes, key=lambda item: normes[item])
        cmds.rename(target, "%s%s" % (closest.split("|")[-1], suffixe))
 def FindNearestObjectToCamera( self ):
     camPos = self.CameraPosition()
     minDist = float("inf")
     closestObj = Vector()
     for obj in self.xformRoots: 
         objPos = Vector(mc.objectCenter(obj))
         dist = ( camPos - objPos ).mag()
         if dist < minDist:
             minDist = dist
             closestObj = objPos
     return closestObj
Exemplo n.º 26
0
 def get_distance(self, *args):
     get_sel = cmds.ls(sl=1, fl=1, type="transform", o=1)
     if get_sel and len(get_sel) == 2:
         obj_center = [cmds.objectCenter(obj) for obj in get_sel]
         a, b = obj_center
         distance = ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2) ** 0.5
         cmds.floatField("thresholdField", e=True, v=distance)
         dist_in_field = cmds.floatField("thresholdField", q=True, value=True)
         if distance > dist_in_field:
             dist = dist_in_field + 0.001
             cmds.floatField("thresholdField", e=True, v=dist)
     else:
         cmds.confirmDialog(m="Please select 2 meshes close to each other to calculate the distance!", b="ok")
Exemplo n.º 27
0
    def CreateLevel(self,
                    width=9,
                    depth=5,
                    name=f'level{_iLevel}',
                    patternF=[],
                    patternB=[],
                    patternL=[],
                    patternR=[]):
        front = self.CreateWallMulti(width,
                                     f"frontWall{self._iLevel}",
                                     pattern=patternF)
        cmds.select(front)
        cmds.move(depth / 2, 0, -(width + self._wallbaseWidth) / 2, a=True)
        #cmds.xform(front, ws=True, t=[0, 0, 0])

        back = self.CreateWallMulti(width,
                                    f"backWall{self._iLevel}",
                                    pattern=patternB)
        cmds.select(back)
        cmds.move(-depth / 2, 0, -(width + self._wallbaseWidth) / 2, a=True)

        #this is where error will occur - need to define backwall specifically
        cmds.setAttr(f"{back}.scaleX", -1)

        zCenter = -0.5 * depth - 0.5
        left = self.CreateWallMulti(depth,
                                    f"leftWall{self._iLevel}",
                                    pattern=patternL)
        cmds.select(left)
        cmds.move(0, 0, zCenter - width / 2, a=True, ws=True)
        cmds.setAttr(f"{left}.rotateY", 90)

        right = self.CreateWallMulti(depth,
                                     f"rightWall{self._iLevel}",
                                     pattern=patternR)
        cmds.select(right)
        cmds.move(0, 0, zCenter + width / 2, a=True, ws=True)
        cmds.setAttr(f"{right}.rotateY", 270)

        group = cmds.group(name=name, empty=True)
        cmds.parent([front, back, left, right], group)

        center = cmds.objectCenter(group, gl=True)
        cmds.xform(group, pivots=center)
        cmds.select(group)

        self._iLevel += 1

        return group
 def Center(self, groupName):
     cmds.xform(groupName,cp =True)
     GroupCenter = cmds.objectCenter(groupName, gl = True)
     cmds.move(-GroupCenter[0],-GroupCenter[1],-GroupCenter[2], groupName, relative = True )
     
     if cmds.objExists("CMBackground"):
         cmds.move(-GroupCenter[0],-GroupCenter[1],-GroupCenter[2], "CMBackground", relative = True )
     if cmds.objExists("UserLights"):
         cmds.move(-GroupCenter[0],-GroupCenter[1],-GroupCenter[2], "UserLights", relative = True )
         
     try:cmds.makeIdentity(groupName, apply = True)
     except:print "Could not reset transforms"
     
     if GroupCenter == cmds.objectCenter(groupName, gl = True):
         pass
     else:
         GroupCenterChk= cmds.objectCenter(groupName, gl = True)
         if GroupCenter[0]== - GroupCenterChk[0] and GroupCenter[1]== - GroupCenterChk[1] and GroupCenter[2]== - GroupCenterChk[2]:
             print "Objects are centered"
             pass
         else:
             self.Center(groupName)
             print "Objects are centered"
         
     bbx = cmds.xform(groupName, bb = True, q = True)
     if bbx[1]<0:
         cmds.move(0,-bbx[1],0, groupName)
         if cmds.objExists("CMBackground"):
             cmds.move(0,-bbx[1],0, "CMBackground", relative = True )
         if cmds.objExists("UserLights"):
             cmds.move(0,-bbx[1],0, "UserLights", relative = True )
         
     else:
         pass
     try:cmds.makeIdentity(groupName, apply = True)
     except:print "Could not reset transform"
Exemplo n.º 29
0
def addAtUVAttr(objectList, shellPoly):
    '''{'del_path':'TfCtrl/Utilities/addAtUVAttr(cmds.ls(sl=True)[:-1], cmds.ls(sl=True)[-1] )',
'icon':':/attributes.png',
'usage':'$fun(cmds.ls(sl=True)[:-1], cmds.ls(sl=True)[-1] )',
}
'''

    if isinstance(objectList, str) or isinstance(objectList, unicode):
        objectList = [objectList]

    #Delete attributes
    delAttr(objectList, ['atU', 'atV'])

    #load plugin
    if cmds.pluginInfo("nearestPointOnMesh", query=True, l=True) == False:
        cmds.loadPlugin("nearestPointOnMesh")
    #print 'Loaded plugin'

    #get shellPolyShape
    meshList = cmds.listRelatives(shellPoly, type='mesh')
    for mesh in meshList:
        if cmds.getAttr(mesh + '.intermediateObject') == 0:
            shellPolyShape = mesh
    #print 'Get shellPolyShape'

    #create nearestPointOnMesh node add connection to shellPolyShape
    uvNode = cmds.createNode("nearestPointOnMesh", n="setUV")
    cmds.connectAttr(shellPolyShape + '.worldMesh[0]',
                     uvNode + '.inMesh',
                     f=True)

    for tfNode in objectList:
        tfNodeCenter = cmds.objectCenter(tfNode)
        cmds.setAttr(uvNode + '.inPosition',
                     tfNodeCenter[0],
                     tfNodeCenter[1],
                     tfNodeCenter[2],
                     type="double3")

        u = cmds.getAttr(uvNode + '.parameterU')
        v = cmds.getAttr(uvNode + '.parameterV')

        cmds.addAttr(tfNode, ln='atU', at='double', dv=u)
        cmds.addAttr(tfNode, ln='atV', at='double', dv=v)
        cmds.setAttr(tfNode + '.atU', l=True)
        cmds.setAttr(tfNode + '.atV', l=True)

    cmds.delete(uvNode)
Exemplo n.º 30
0
    def check_object_overlap(self, *args):
        cmds.textScrollList("overlapListTextScroll", e=True, ra=True)
        self.threshold = cmds.floatField("thresholdField", q=True, value=True)
        get_sel = cmds.ls(sl=1, fl=1, type="transform", o=1)
        if get_sel and len(get_sel) > 1:
            obj_center = []
            for obj in get_sel:
                oc = cmds.objectCenter(obj)
                occ = [obj, oc]
                obj_center.append(occ)
            overlap_center = []
            overlap_bbox = []
            for a, b in itertools.combinations(obj_center, 2):
                distance = ((a[1][0] - b[1][0]) ** 2 + (a[1][1] - b[1][1]) ** 2 + (a[1][2] - b[1][2]) ** 2) ** 0.5
                if 0 <= distance <= self.threshold:
                    ab = (a[0], b[0])
                    overlap_center.append(ab)
                    for meshes in overlap_center:
                        bboxA = cmds.polyEvaluate(meshes[0], b=True)
                        bboxB = cmds.polyEvaluate(meshes[1], b=True)
                        diameter_bboxA = ((bboxA[0][1] - bboxA[0][0]) ** 2 + (bboxA[1][1] - bboxA[1][0]) ** 2 + (
                            bboxA[2][1] - bboxA[2][1]) ** 2) ** 0.5
                        diameter_bboxB = ((bboxB[0][1] - bboxB[0][0]) ** 2 + (bboxB[1][1] - bboxB[1][0]) ** 2 + (
                            bboxB[2][1] - bboxB[2][1]) ** 2) ** 0.5
                        diff = abs(diameter_bboxA - diameter_bboxB)
                        if 0 <= diff <= self.threshold:
                            if meshes not in overlap_bbox:
                                overlap_bbox.append(meshes)

            if cmds.checkBox("bboxCheck", q=True, v=True) == 0:
                item_list = []
                for item in overlap_center:
                    for x in item:
                        item_list.append(x)
                item_list = list(set(item_list))
                cmds.textScrollList("overlapListTextScroll", e=True, a=item_list)
                cmds.select(cmds.textScrollList("overlapListTextScroll", q=True, ai=True), r=1)

            elif cmds.checkBox("bboxCheck", q=True, v=True) == 1:
                item_list = []
                for item in overlap_bbox:
                    for x in item:
                        item_list.append(x)
                item_list = list(set(item_list))
                cmds.textScrollList("overlapListTextScroll", e=True, a=item_list)
                cmds.select(cmds.textScrollList("overlapListTextScroll", q=True, ai=True), r=1)
Exemplo n.º 31
0
        def hdri_render_main(self):
            if self.current_renderer not in self.accepted_renderers:
                cmds.inViewMessage(
                    amg=
                    "This feature currently supports Vray, Arnold or Redshift renderers only",
                    pos="botCenter",
                    fade=True)
                return

            if self.render_position == "object":
                if not self.render_geo:
                    cmds.inViewMessage(
                        amg=
                        "Please Select an Object from which to render HDRI View",
                        pos="botCenter",
                        fade=True)
                    return

                else:
                    # get averaged centre of selected objects
                    x, y, z = 0, 0, 0
                    for geo in self.render_geo:
                        xyz = cmds.objectCenter(geo)
                        x += xyz[0]
                        y += xyz[1]
                        z += xyz[2]

                    objs_centre = x / len(self.render_geo), y / len(
                        self.render_geo), z / len(self.render_geo)
                    cmds.hide(self.render_geo)  # hide objects while rendering

            # zero out any camera rotations and reposition to objects centre if needed
            cmds.setAttr("%s.rotate" % self.render_camera, 0, 0, 0)

            if self.render_position == "object":
                cmds.setAttr("%s.translate" % self.render_camera,
                             objs_centre[0], objs_centre[1], objs_centre[2])

            if self.current_renderer == "vray":
                self.vray_render()
            if self.current_renderer == "redshift":
                self.redshift_render()
            if self.current_renderer == "arnold":
                self.arnold_render()
Exemplo n.º 32
0
def centerPivot(selectedGeo):
    pivots = selectedGeo
    pivotCenter = []
    for item in pivots:
        pivotLocation = mel.xform(item, ws=1, query=1, rotatePivot=1)
        pivotNewLocation = mel.objectCenter(item)
        if (abs(float(pivotLocation[0]) - float(pivotNewLocation[0])) < 0.01):
            if (abs(float(pivotLocation[1]) - float(pivotNewLocation[1])) <
                    0.01):
                if (abs(float(pivotLocation[2]) - float(pivotNewLocation[2])) <
                        0.01):
                    pivotCenter.append(item)

    pivotNotCenter = []
    for item in pivots:
        if item in pivotCenter:
            continue
        else:
            pivotNotCenter.append(item)

    return pivotNotCenter
Exemplo n.º 33
0
    def CreateStackedLevels(self, nLevels, name='levels', width=9, depth=5):
        if not name:
            name = 'levels'

        levels = []
        for n in range(0, nLevels):
            if n == 0:  #first floor
                level = self.CreateLevel(
                    name=f'level{n}',
                    width=width,
                    depth=depth,
                    patternF=self._patternDefaultFirstFloor,
                    patternB=self._patternDefaultFirstFloor)
            elif (n % 2 == 0):
                level = self.CreateLevel(name=f'level{n}',
                                         width=width,
                                         depth=depth,
                                         patternF=self._patternDefault,
                                         patternB=self._patternDefault)
            else:
                level = self.CreateLevel(name=f'level{n}',
                                         width=width,
                                         depth=depth)
            cmds.move(0, self._wallbaseHeight * n, 0, a=False)
            levels.append(level)

        roof = self.CreateRoof(width=width, depth=depth)
        cmds.move(0, (self._wallbaseHeight * n + 1), 0, a=False)
        levels.append(roof)

        group = cmds.group(name=name, empty=True)
        cmds.parent(levels, group)

        #center pivot
        center = cmds.objectCenter(group, gl=True)
        cmds.xform(group, pivots=center)
        cmds.select(group)

        return group
Exemplo n.º 34
0
    def pivotsCentered(self, inputNodes):
        pivots = inputNodes
        pivotCenter = []
        for item in pivots:
            pivotLocation = cmds.xform(item, ws=1, query=1, rotatePivot=1)
            pivotNewLocation = cmds.objectCenter(item)
            if (abs(float(pivotLocation[0]) - float(pivotNewLocation[0])) <
                    0.01):
                if (abs(float(pivotLocation[1]) - float(pivotNewLocation[1])) <
                        0.01):
                    if (abs(
                            float(pivotLocation[2]) -
                            float(pivotNewLocation[2])) < 0.01):
                        pivotCenter.append(item)
        pivotNotCenter = []
        for item in pivots:
            if item in pivotCenter:
                continue
            else:
                pivotNotCenter.append(item)

        return pivotNotCenter
Exemplo n.º 35
0
def swapParts(templatePart, outputNamePrefix):
    rawSelectionDump = cmds.ls(
        sl=True, long=True
    )  #cmds.ls listing sl(selected DAG objects), long(the full names of the objects)
    ascii_encoded = [
        str(selected) for selected in rawSelectionDump
    ]  #re-encodes to ascii from unicode; don't use non-ascii characters in your object names

    #generate a list of parts to duplicate and transform. removes the first character from the string if it's a pipe.
    partsList = []
    for part in ascii_encoded:
        if part[0] == '|':
            partsList.append(part[1:])

        else:
            partsList.append(part)

    print(str(len(partsList)) + " objects detected. Hold on to your muffins")

    for part in partsList:
        dest_coords = cmds.objectCenter(
            part, gl=True
        )  #grab XYZ coordinates as a list from the destination object
        dest_rot = cmds.xform(
            part, q=True, ws=True, ro=True
        )  #also grab euler angle rotations from the destination object

        dupe_obj = cmds.duplicate(
            templatePart,
            name=outputNamePrefix)  #duplicate object with specified prefix
        cmds.move(dest_coords[0],
                  dest_coords[1],
                  dest_coords[2],
                  dupe_obj,
                  absolute=True)  #move into position
        cmds.rotate(dest_rot[0], dest_rot[1], dest_rot[2],
                    dupe_obj)  #rotate into position

    print("All objects swaps attempted")
Exemplo n.º 36
0
def movePivots():

    pivPos = cmds.radioButtonGrp('pivPos', q=True, sl=True)

    sel = cmds.ls(sl=True)

    # Testing for number of selected objects
    if (len(sel) < 1):
        cmds.error('No objects selected')
    elif (len(sel) == 1):
        if (pivPos == 1):
            cmds.xform(cp=True)  # Centering Pivot
        else:
            bBox = cmds.xform(q=True, ws=True,
                              bb=True)  # Querying bound box info
            centerPos = cmds.xform(q=True, ws=True,
                                   sp=True)  #Querying transform info
            cmds.xform(
                piv=(centerPos[0], bBox[1], centerPos[2]),
                ws=True,
            )  # Adjusting pivot
    else:
        cmds.group(sel, n='pivotTempGrp', w=True)  # Creating temporary group
        objCenter = cmds.objectCenter('pivotTempGrp')
        objBB = cmds.xform('pivotTempGrp', q=True, ws=True,
                           bb=True)  # Querying bound box info for group
        yAverage = ((objBB[1] + objBB[4]) / 2)  # Calculating height
        for i in range(len(sel)):
            cmds.select(sel[i])
            if (pivPos == 1):
                cmds.xform(piv=(objCenter[0], objBB[1], objCenter[2]), ws=True)
            else:
                cmds.xform(piv=(objCenter[0], yAverage, objCenter[2]), ws=True)

        # Deleting temporary group
        cmds.ungroup('pivotTempGrp')

    cmds.select(sel)
Exemplo n.º 37
0
        def hdri_render_main(self):
            if self.current_renderer not in self.accepted_renderers:
                cmds.inViewMessage(amg="This feature currently supports Vray, Arnold or Redshift renderers only",
                                   pos="botCenter", fade=True)
                return

            if self.render_position == "object":    # will render from object(s) centre
                if not self.render_geo:
                    cmds.inViewMessage(amg="Please Select an Object from which to render HDRI View",
                                       pos="botCenter", fade=True)
                    return

                else:
                    # get averaged centre of selected objects
                    x, y, z = 0, 0, 0
                    for geo in self.render_geo:
                        xyz = cmds.objectCenter(geo)
                        x += xyz[0]
                        y += xyz[1]
                        z += xyz[2]

                    objs_centre = x / len(self.render_geo), y / len(self.render_geo), z / len(self.render_geo)
                    cmds.hide(self.render_geo)  # hide objects while rendering

            # zero out any camera rotations and reposition to objects centre if needed
            cmds.setAttr("%s.rotate" % self.render_camera, 0, 0, 0)

            if self.render_position == "object":
                cmds.setAttr("%s.translate" % self.render_camera, objs_centre[0], objs_centre[1], objs_centre[2])

            if self.current_renderer == "vray":
                self.vray_render()
            if self.current_renderer == "redshift":
                self.redshift_render()
            if self.current_renderer == "arnold":
                self.arnold_render()
Exemplo n.º 38
0
def objsToPar(parName=None, initialState=True):
    """{'del_path':'Dynamics/Particles/objsToPar(parName=None, initialState=True)ONLYSE',
'icon':':/particle.png',
'tip':'选择的组下面的每个物体中心创建一个粒子',
'usage':'$fun(parName=None, initialState=True)',
'help':'''<pre>
parName:
    如果不指定粒子节点的名字,则创建一个新的粒子;
initialState:
    为粒子设不设置初始状态。
''',
}
"""
    grp = cmds.ls(sl=True)
    objects = cmds.listRelatives(grp, type='transform', f=True)
    posLi, radiusLi, cus_objGrp = [], [], []
    for tfNode in objects:
        objPos = cmds.objectCenter(tfNode)
        posLi.append(objPos)

    qsEmit(object=parName,
           position=posLi,
           attributes=[],
           clearAndSaveState=initialState)
Exemplo n.º 39
0
    def CreateWallMulti(self, nSegments, name="wallSection", pattern=[]):
        group = cmds.group(name=name, empty=True)
        nPattern = len(pattern)
        instances = []
        for n in range(0, nSegments):
            if len(pattern) == 0:
                cmds.select(self._wallBase)
            else:
                i = 0 if n == 0 else n % nPattern
                cmds.select(pattern[i])
            instance = cmds.instance()
            cmds.move(0, 0, n + 1)
            instances.append(instance[0])
        cmds.parent(instances, group)

        #center pivot
        center = cmds.objectCenter(group, gl=True)
        # reset the x position (extrudes should not alter the pivot)
        center[0] = 0.0

        cmds.xform(group, pivots=center)
        cmds.select(group)

        return group
Exemplo n.º 40
0
def move_obj_center(obj, new_center):
	center = cmds.objectCenter(obj)
	translation = [x1 - x2 for (x1, x2) in zip(new_center, center)]
	cmds.move(translation[0], translation[1], translation[2], obj, r=1)
	return cmds.objectCenter(obj)
Exemplo n.º 41
0
import random
import math
import maya.app.mayabullet.BulletUtils as BulletUtils
import maya.app.mayabullet.RigidBody as RigidBody
BulletUtils.checkPluginLoaded()

# Get object to be shattered
cmds.select(['log1','log2','log3'])
selected = cmds.ls(sl=True, transforms=True)
objCounter = 0
for obj in selected: 

    print(obj)
    
    # Get center point of collision (in our case center of the logs)
    com = cmds.objectCenter(obj, gl=True)
    numPoints = 30
    fractureRadius = 3
    thickness = 1 # Will get divided by 2
    height = cmds.getAttr(obj + '.translateY')
    transX = cmds.getAttr(obj + '.translateX')
    rotY = cmds.getAttr(obj + '.rotateY')
    voroX = []
    voroY = []
    voroZ = []
    #print(height)
    
    
    # Help function 
    def surfaceMaterial(obj, R, G, B):
        name = (obj + '_shardMaterial')
Exemplo n.º 42
0
            elif "R_" in org_obj and "left" not in org_obj and "right" in org_obj:
                mirrored_obj="L_{0}left{1}".format(org_obj.split('R_')[1].split('right')[0],org_obj.split('R_')[1].split('right')[1])
                return mirrored_obj
            elif "M_" in org_obj and "left" not in org_obj and "right" in org_obj:
                mirrored_obj="{0}left{1}".format(org_obj.split('right')[0],org_obj.split('right')[1])
                return mirrored_obj
            elif "M_" in org_obj and "left" in org_obj and "right" not in org_obj:
                mirrored_obj="{0}right{1}".format(org_obj.split('left')[0],org_obj.split('left')[1])
                return mirrored_obj
            else:
                mirrored_obj="Mirrored_{0}".format(org_obj)
                return mirrored_obj

    def doMirror(self,*args):

# mirror objs
objs = cmds.ls(sl=True,fl=True,tr=True);

for obj in objs:
    cur_center = cmds.objectCenter(obj)
    bbox = cmds.xform(obj,q=True,bb=True)
    cur_piv = cmds.xform(obj,q=True,ws=True,piv=True)[:3]
    origin = [0,0,0]

    dup_node = cmds.duplicate(obj,n=self.renameDup(obj))
    cmds.scale(-1,1,1,dup_node,p=origin,ws=True,r=True)
    cmds.xform(dup_node,ws=True,piv=origin)

    cmds.polyNormal(dup_node,nm=0,ch=0)
    cmds.select(d=True)
def ExecTurntable():
	#==============================================================
	# SHOTGUN GET INFORMATIONS
	#==============================================================
	def getTank():
		if _platform == "win32":
			ProjectPath= "W:\WG\Shotgun_Configs\RTS_Master"
		elif _platform == "linux" or _platform == "linux2":
			ProjectPath="/srv/projects/rts/WG/Shotgun_Configs/RTS_Master"
		else:
			ProjectPath= "W:/WG/Shotgun_Configs/RTS_Master"
		return sgtk.sgtk_from_path(ProjectPath)
	
	tk = getTank()
	sg = tk.shotgun
	
	ScenePath= cmds.file (q=True, sn=True)
	PathWithoutFileName = os.path.split(ScenePath)[0]
	
	tk.reload_templates()

	ContextFromPath = tk.context_from_path(ScenePath)
	
	AssetIdNumber = ContextFromPath.entity.get('id') 

	TemplateFromPath = tk.template_from_path(ScenePath)
	TemplateFields = TemplateFromPath.get_fields(ScenePath)

	AssetType = TemplateFields.get('sg_asset_type')
	AssetName = TemplateFields.get('Asset')
	StepName = TemplateFields.get('Step')
	# format the version with 3 digits
	# VersionScene = '%0*d' % (03, TemplateFields.get('version'))
	VersionScene = TemplateFields.get('version')

	VersionKey = TemplateFromPath.keys['version']
	VersionKeyFormated= VersionKey.str_from_value(VersionScene)

	AssetRenderTemplate = tk.templates['maya_asset_render']
	AssetRenderFullPath = AssetRenderTemplate.apply_fields(TemplateFields)
	AssetRenderPathAndFileBase = AssetRenderFullPath.split('.')[0]
	AssetRenderPath = AssetRenderFullPath.rsplit('\\', 1)[0]
	AssetRenderFile = AssetRenderFullPath.split('\\')[-1]

	#GET PATH OF LAST VERSION OF TURNTABLE SCENE
	fields = ['id', 'code', 'sg_status_list']
	filters = [
		['project','is',{'type':'Project','id':66}],
		['id','is',1022]
		]
	asset= sg.find_one("Asset",filters,fields)
	PublishTemplate = tk.templates['maya_asset_publish']
	listscenerender= []
	PublishsScenesPaths = tk.paths_from_template(PublishTemplate, asset)
	for PublishScene in PublishsScenesPaths:
		if "turntableCharacter" in PublishScene:
			listscenerender.append(PublishScene)
	listscenerender.sort()
	LastTurntablePath = listscenerender[-1]

	#==============================================================
	#RENDER TURNTABLE TD V0.02
	#==============================================================

	CurrentFolder = os.path.dirname(os.path.realpath(__file__))
	# SaveChanges()
	#NUMBER OF GROUPS IN SCENE VERIFICATION
	curentSel = cmds.ls(g=True, an= True, l=True )
	
	list_grps = []
	for theString in curentSel:
		theSplitAr = theString.split(":")
		if theSplitAr [1][:-1] in list_grps:
			None
		else:
			list_grps.append(theSplitAr [1][:-1])
	Grp_AssetName = "GRP_"+AssetName
	if len(list_grps)!= 1:
		cmds.warning("-program need 1 group named: " + Grp_AssetName)
	elif Grp_AssetName not in list_grps :
		cmds.warning("-program need 1 group named: " + Grp_AssetName)
	else:
		print ("1 groupe = OK")
		GroupName = list_grps [0] 

		#PATHS AND TYPE FILE
		#turntableScenePath = 'C:/Users/tdelbergue/Desktop/'
		#turntableScenePath = "W:/RTS/Experimental/People/TDelbergue/"
		turntableScenePath = "W:/RTS/_Library/Presets/Maya/"
		turntableSceneName= 'scene_turntable_07.ma'
		# turntableSceneName= turntableScene

		LibraryPath = "W:/RTS/_Library"
		RendersPath = "W:/RTS/Renders/_Library/mod"
		WorkMayaPath = "work/maya"
		PublishMayaPath = "publish/maya"

		CurrentMayaPath = PathWithoutFileName+"/"

		#OPEN SCENETURNTABLE
		cmds.file(new=True, force=True)
		cmds.file( LastTurntablePath, o=True )
		
		ImportPreviousScene = cmds.file(ScenePath, i=True, pn= True)  	
		cmds.parent( Grp_AssetName, 'locator_fix' )
		
		SceneTurnOutputName = AssetRenderFile.split('.')[0]+'_turn'
		cmds.file(rename =CurrentMayaPath+SceneTurnOutputName)
		cmds.file(save=True)

		#BOUNDING BOX CREATION
		
		locFixSel = cmds.listRelatives("locator_fix", allDescendents=True, noIntermediate=True, s=False, f=True)
		mySel =cmds.select(locFixSel)
		Isel = cmds.ls( selection=True,s=False )

		XMIN=[]
		YMIN=[]
		ZMIN=[]
		XMAX=[]
		YMAX=[]
		ZMAX=[]

		for i in Isel:
			if "Shape" in i:
				None
			else:
				IselBBox = cmds.xform(i, q=True ,bb=True )
				XMIN.append(IselBBox[0])
				YMIN.append(IselBBox[1])
				ZMIN.append(IselBBox[2])
				XMAX.append(IselBBox[3])
				YMAX.append(IselBBox[4])
				ZMAX.append(IselBBox[5])

		Xwidth =(max(XMAX)- min(XMIN))
		Ywidth =(max(YMAX)- min(YMIN))
		Zwidth =(max(ZMAX)- min(ZMIN))
		
		ratioHautMoitie = Ywidth/2

		heightBoundBoxMin= 2.193*Ywidth
		widthBoundBoxMin= 1.425* Xwidth
		
		if heightBoundBoxMin >=  widthBoundBoxMin:
			cmds.setAttr( "camWide.translateZ",heightBoundBoxMin- min(ZMIN))
		if heightBoundBoxMin <=  widthBoundBoxMin:
			cmds.setAttr( "camWide.translateZ",widthBoundBoxMin- min(ZMIN))
		
		cmds.setAttr( "camWide.translateY", ratioHautMoitie )
		
		#SMOOTH MESHES under locator_fix
		# locator_fix_ChildMeshes = cmds.listRelatives( 'locator_fix', ad=True, typ='mesh' )
		# cmds.select( locator_fix_ChildMeshes )
		# cmds.displaySmoothness( du=3, dv=3, pw=16, ps=4,po=3 )
		meshs = cmds.ls(l=True, typ= 'mesh' )
		cmds.select( meshs )
		cmds.displaySmoothness( du=3, dv=3, pw=16, ps=4,po=3 )
		#SCENE PARAMETERS
		#HD720
		cmds.setAttr ("defaultResolution.width", 1280)
		cmds.setAttr ("defaultResolution.height", 720)
		cmds.setAttr ("defaultResolution.deviceAspectRatio",1.777)
		cmds.setAttr ("defaultResolution.pixelAspect", 1)

		#OUTPUT FRAMES NAME
		cmds.setAttr("defaultRenderGlobals.imageFilePrefix", AssetRenderFile.split('.')[0],type="string")
			
		# EYES MESH IN SCENE VERIFICATION
		eyeList = []
			
		allObjects = cmds.ls(l=False, typ= 'mesh' )

		for obj in allObjects:
			if "eye" in obj.lower():
				EyesTrsX = cmds.objectCenter(obj,x=True)
				EyesTrsY = cmds.objectCenter(obj,y=True)
				EyesTrsZ = cmds.objectCenter(obj,z=True)
				eyeList.append(obj)
		
		#WARNING MESSAGES IF MISSING EYES OR GROUP PROBLEMS
		if not eyeList and AssetType == "Prop" or AssetType == "Vehicle" :
			print "prop with no eyes"
			cameraObj = "camMiddle"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",0)
			cameraObj = "camCloseUp"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",0)
			cameraObj = "camWide"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",1)
			# save wide
			cmds.file(rename = CurrentMayaPath+SceneTurnOutputName+'Wide')
			cmds.file(save=True)
			
		if not eyeList and AssetType == "Character":
			cmds.warning("no object with name 'eye' was found, please rename or create one")	
			
		sumX = []
		sumY = []
		sumZ = []
		#print eyeList
		if eyeList:
			for obj in eyeList:
				EyesTrsX = cmds.objectCenter(obj,x=True)
				EyesTrsY = cmds.objectCenter(obj,y=True)
				EyesTrsZ = cmds.objectCenter(obj,z=True)
				sumX.append(EyesTrsX)
				sumY.append(EyesTrsY)
				sumZ.append(EyesTrsZ)    

			EyesTrsX = sum(sumX)/len(sumX)
			EyesTrsY = sum(sumY)/len(sumY)
			EyesTrsZ = sum(sumZ)/len(sumZ)

			cmds.spaceLocator(p=(EyesTrsX,EyesTrsY,EyesTrsZ), name="pivot_head")
			cmds.parent( "pivot_head", eyeList[0][:-5] )
				
			heightToptoEyes = (max(YMAX)-EyesTrsY) 

			cmds.setAttr( "pivot_camCloseUp.translateX", EyesTrsX )
			cmds.setAttr( "pivot_camCloseUp.translateY", EyesTrsY )
			cmds.setAttr( "pivot_camCloseUp.translateZ", EyesTrsZ ) 

			cmds.parent( "pivot_camCloseUp", "pivot_head" )

			#cmds.setAttr( "camCloseUp.translateY", EyesTrsY )
			cmds.setAttr( "camCloseUp.translateZ", 7*heightToptoEyes- min(ZMIN) )
			#eyes one third from the top:
			# cmds.setAttr( "camCloseUp.translateY", EyesTrsY+ ((heightToptoEyes/3)*2))
			Zwide =getAttr( "camWide.translateZ" )
			Zcloseup =getAttr( "camCloseUp.translateZ" )
			CAM3Z = Zwide - ((Zwide-Zcloseup)/2)

			# cmds.setAttr( "camMiddle.translateZ", 2*Ywidth )
			cmds.setAttr( "camMiddle.translateZ", CAM3Z)

			cmds.setAttr("camMiddle.translateY",(ratioHautMoitie+EyesTrsY)/2)
			
			#CHECK IF CAM ORDER (FAR > NEAR IS OKAY, INVERT IF NOT )
			if Zwide < Zcloseup:
				cmds.setAttr("camWide.translateZ",Zcloseup)
				cmds.setAttr("camCloseUp.translateZ",Zwide)
			
			#IF OTHER RENDER LAYERS DELETE THEM:
			for each in cmds.ls(type='renderLayer'):
				if each != 'defaultRenderLayer':
					cmds.delete(each) 
					
			#CREATE_SCENES_AND_CAMS
			cmds.file(rename = CurrentMayaPath+SceneTurnOutputName+'CloseUp')
			cmds.file(save=True)

			cameraObj = "camCloseUp"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",0)
			cameraObj = "camWide"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",1)
			#save wide
			cmds.file(rename = CurrentMayaPath+SceneTurnOutputName+'Wide')
			cmds.file(save=True)

			cameraObj = "camWide"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",0)
			cameraObj = "camMiddle"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",1)
			#save mid
			cmds.file(rename = CurrentMayaPath+SceneTurnOutputName+'Middle')
			cmds.file(save=True)
			#save close
			cmds.file( q=True, ex=True )
		
		#==============================================================
		#DEADLINE SUBMIT
		#==============================================================
		def submitturntable (CharName, CameraName, frameRangeInput ):
			# scenePath = CurrentMayaPath+CharName+"/"
			if not os.path.exists(AssetRenderPath):
				os.makedirs(AssetRenderPath)
			
			Deadline = Connect.DeadlineCon('srv-deadline2', 8080 )
			# Deadline = Connect.DeadlineCon('192.168.0.77', 8080 )

			JobInfo = {
				"Name" : CharName + "_v_"+VersionKeyFormated+ " -" + "turntable" + "- " + CameraName,
				"UserName" : UserName,
				"Frames" : frameRangeInput,
				"Pool" : "maya",
				"Plugin" : "MayaCmd",
				"MachineName": ComputerName,
				# LimitGroups=maya
				"LimitGroups":"maya"

				}
				
			PluginInfo = {
				"Version":"2013",
				"Build":"None",
				"StrictErrorChecking":"True",
				"LocalRendering":"False",
				"MaxProcessors":"0",
				"CommandLineOptions":"",
				"UseOnlyCommandLineOptions":"0",
				"IgnoreError211":"False",
				"SceneFile":PathWithoutFileName+"/"+SceneTurnOutputName+CameraName+".ma",
				"OutputFilePath":AssetRenderPath+"/",
				"Renderer":"MentalRay",
				"Priority":"50"
				}
				
			newJob = Deadline.Jobs.SubmitJob(JobInfo, PluginInfo,idOnly=False)
			print newJob["_id"]
			return newJob["_id"]
			
		# -------------------------------------------------------------------------------------------------
		# ADDING ONE JOB AS A DEPENDENCY
		# -------------------------------------------------------------------------------------------------
		
		def submitTurnChildJob (JobsDepId):
			Deadline = Connect.DeadlineCon('srv-deadline2', 8080 )
			# Deadline = Connect.DeadlineCon('192.168.0.77', 8080 )
			JobInfo = {
				"Name" : AssetName+" Child Job - Make complete sequence ",
				"UserName" : UserName,
				"Frames" : 0,
				"Pool" : "small_tasks",
				"Plugin" : "Python",
				"MachineName": ComputerName,
				"JobDependencies": JobsDepId
			}

			PluginInfo = {
				"Version":2.7,
				"ScriptFile": os.path.abspath(CurrentFolder+"/FillMissingFiles03.py"),
				"Arguments":
				'entityTypeArg='+str(AssetType)+' '+
				'pathArg='+str(AssetRenderPath+"/")+' '+
				'nameArg='+str(AssetRenderFile.split('.')[0])+' '+
				'VersionArg='+str(VersionKeyFormated)+' '+
				'IDAssetArg='+str(AssetIdNumber)
			}

			newJob = Deadline.Jobs.SubmitJob(JobInfo, PluginInfo,idOnly=False)
			print newJob["_id"]	
			
		# -------------------------------------------------------------------------------------------------	

		if AssetType == "Character":			
			JobID1 = submitturntable (AssetName,"Wide", "0-159" )
			JobID2 = submitturntable (AssetName,"Middle", "160-319x10" )
			JobID3 = submitturntable (AssetName,"CloseUp", "320-479x20" )
			JobsDepId = "%s,%s,%s" %(JobID1, JobID2, JobID3)
			childJob = submitTurnChildJob(JobsDepId)
			
		if AssetType == "Prop" or AssetType == "Vehicle" :
			JobID1 = submitturntable (AssetName,"Wide", "0-159" )
			JobsDepId = "%s" %(JobID1)
			childJob = submitTurnChildJob(JobsDepId)
Exemplo n.º 44
0
def constrainShape(shape):

    parentTr = mc.listRelatives(shape, p=True)
    while isIterable(parentTr):
        parentTr = parentTr[0]
    objCenter = mc.objectCenter(shape, gl=True)
    objCenterLocal = mc.objectCenter(shape, l=True)

    obj = mc.ls(parentTr, o=True)[0]

    constraintAttrs = mc.listConnections(parentTr, p=True, s=True, d=True, type="constraint")
    constraints = []
    for c in mc.ls(constraintAttrs, o=True):
        if c not in constraints:
            constraints.append(c)

    if not isIterable(constraintAttrs) or len(constraintAttrs) == 0:
        raise Exception, (shape + " is not under a constrained transform.")

    tgNode = mc.createNode("transformGeometry")
    type = mc.nodeType(shape)
    base = mc.listRelatives(mc.duplicate(parentTr, rc=True)[0], c=True, type=type, s=True, ni=True)[0]
    mel.eval('zenParentShape {"' + base + '","' + parentTr + '"}')

    creationAttr = ""
    creationIn = ""
    creationOut = ""
    if type == "mesh":
        creationIn = ".inMesh"
        creationOut = ".outMesh"
    elif type in ("nurbsCurve", "nurbsSurface"):
        creationIn = ".create"
        creationOut = ".local"

    dummyTr = mc.createNode("unknownTransform", p=parentTr, n="dummyTr#")
    for c in constraints:
        mc.connectAttr(dummyTr + ".t", c + ".restTranslate", f=True)

    mc.xform(dummyTr, ws=True, t=objCenter)

    mc.connectAttr(base + creationOut, tgNode + ".inputGeometry")
    mc.connectAttr(tgNode + ".outputGeometry", shape + creationIn, f=True)
    mc.setAttr(base + ".intermediateObject", True)

    constraintAttrs = removeDuplicates(constraintAttrs)

    for c in constraintAttrs:
        connectedFrom = removeDuplicates(mc.listConnections(c, p=True, s=False, d=True))
        connectedTo = removeDuplicates(mc.listConnections(c, p=True, s=True, d=False))
        for cf in connectedFrom:
            if mc.ls(cf, o=True)[0] == obj:
                if mc.isConnected(c, cf):
                    mc.disconnectAttr(c, cf)
                mc.connectAttr(c, dummyTr + "." + mc.listAttr(cf)[0], f=True)
        for ct in connectedTo:
            if mc.ls(ct, o=True)[0] == obj:
                attr = mc.listAttr(ct)[0]
                if mc.isConnected(ct, c):
                    mc.disconnectAttr(ct, c)
                mc.connectAttr(dummyTr + "." + attr, c, f=True)

    mc.xform(parentTr, ws=True, piv=objCenter)
    for c in constraints:
        mc.xform(c, ws=True, piv=objCenter)

    for c in constraints:
        mc.disconnectAttr(dummyTr + ".t", c + ".restTranslate")

    mc.connectAttr(dummyTr + ".matrix", tgNode + ".transform", f=True)
    mel.eval('rigZenMakeNodesNonKeyable({"' + dummyTr + '"})')

    return dummyTr
Exemplo n.º 45
0
    def sortSelection(self):
        """Re-order the selection list based on various criteria"""

        # Remove locator from selection
        self.deselectLocator(self.locName)

        # Create list from selection, and dictionary for sorting
        sel = mc.ls(selection=True, flatten=True)
        selDic = {}

        # Get options
        mode1 = mc.radioButtonGrp("sortBy1", query=True, select=True)
        mode2 = mc.radioButtonGrp("sortBy2", query=True, select=True)
        mode = mode1 + mode2 * 10
        rev = mc.checkBox("reverse", query=True, value=True)

        # Check locator exists if in proximity mode
        if mode == 20 and not mc.objExists(self.locName):
            mc.error("Create locator before sorting by proximity.")
            #self.createLocator(self.locName)
            return False

        # Construct name to give to new group
        self.grpName = "sortedBy"
        if mode == 1:
            self.grpName += "X"
        elif mode == 2:
            self.grpName += "Y"
        elif mode == 3:
            self.grpName += "Z"
        elif mode == 10:
            self.grpName += "Name"
        elif mode == 20:
            self.grpName += "Distance"
        if rev:
            self.grpName += "Inv"

        # Populate the selection dictionary based on the sort criteria
        for i in range(len(sel)):
            if mode == 1:
                selDic[sel[i]] = (mc.objectCenter(sel[i], x=True))
            elif mode == 2:
                selDic[sel[i]] = (mc.objectCenter(sel[i], y=True))
            elif mode == 3:
                selDic[sel[i]] = (mc.objectCenter(sel[i], z=True))
            elif mode == 10:
                selDic[sel[i]] = sel[i]
            elif mode == 20:
                p = mc.objectCenter(sel[i])
                q = mc.xform(self.locName, query=True, translation=True)
                selDic[sel[i]] = gps.distanceBetween(p, q)

        # Sort the dictionary based on the values and save to a new sorted list
        selSorted = sorted(selDic.iteritems(),
                           key=operator.itemgetter(1),
                           reverse=rev)

        # Re-select objects from sorted list
        mc.select(clear=True)
        for selObj in selSorted:
            mc.select(selObj[0], add=True)
Exemplo n.º 46
0
def createCurveFromObjectsPos(objects,
                              useConnectAttr=False,
                              usePointConstraint=False,
                              name=None):
    '''{'del_path':'Dynamics/Particles/createCurveFromObjectsPos( cmds.ls(sl=True, exactType="transform", l=True), useConnectAttr=False, usePointConstraint=False, name=None )',
'tip':'从选择的物体的位置,创建曲线',
'icon':':/menuIconCurve.png',
'usage':"""
$fun(  cmds.ls(sl=True, exactType="transform"), useConnectAttr=False, usePointConstraint=False, name=None )
#global string $emitList[];
#$emitList = `listRelatives -ad -type "pointEmitter" "group"`;""",
'help':"""<pre>
useConnectAttr:
    将物体的translate关联到曲线的cvpos属性;
usePointConstraint:
    将曲线的cvpos约束到物体的位置上。
</pre>
""",
}
'''
    if isinstance(objects, str) or isinstance(objects, unicode):
        objects = [objects]

    if len(objects) == 0:
        raise IOError('No objects selected!')

    if name == None:
        name = 'pointObj'

    #name = 'pointObj_secCurve'
    createNew = True
    if name != None:
        if cmds.objExists(name):
            shapes = cmds.listRelatives(name, type='nurbsCurve')
            if cmds.objectType(name) == 'nurbsCurve':
                curveNode = cmds.listRealtives(name, p=True)[0]
                curveShape = name
                createNew = False
            elif shapes != [] and cmds.objectType(shapes[0]) == 'nurbsCurve':
                curveNode = name
                curveShape = shapes[0]
                createNew = False

    if createNew:
        curveNode = cmds.curve(name=name, d=1, p=([0, 0, 0]))
        curveShape = cmds.listRelatives(curveNode, shapes=True)[0]

    pointsPos = []
    for obj in objects:
        #pointsPos.append( cmds.getAttr(obj+'.t')[0] )
        pointsPos.append(cmds.objectCenter(obj))

    cmds.curve(curveNode, r=True, p=pointsPos)
    #curveNode = cmds.curve(name=name, d=1,  p=pointsPos)
    #curveShape = cmds.listRelatives(curveNode, shapes=True)[0]

    if useConnectAttr:
        for i in range(len(objects)):
            cmds.connectAttr(objects[i] + '.translate',
                             '%s.controlPoints[%s]' % (curveShape, i))
    elif usePointConstraint == True:
        for tfObj in objects:
            pointCon = cmds.createNode('pointConstraint', p=curveNode)
            cmds.connectAttr('%s.rotatePivotTranslate' % tfObj,
                             '%s.target[0].targetRotateTranslate' % pointCon)
            cmds.connectAttr('%s.parentMatrix[0]' % tfObj,
                             '%s.target[0].targetParentMatrix' % pointCon)
            cmds.connectAttr('%s.translate' % tfObj,
                             '%s.target[0].targetTranslate' % pointCon)
            cmds.connectAttr('%s.rotatePivot' % tfObj,
                             '%s.target[0].targetRotatePivot' % pointCon)

            cmds.connectAttr(
                '%s.constraintTranslate' % pointCon,
                '%s.controlPoints[%s]' % (curveShape, objects.index(tfObj)))
            cmds.setAttr('%s.intermediateObject' % pointCon, 1)

    cmds.setAttr('%s.template' % curveShape, 1)
    cmds.select(curveNode, r=True)
    return curveNode
Exemplo n.º 47
0
def PlacementTool():
	cmds.undoInfo(openChunk=True)
	Start = True
	if cmds.objExists('__Placement_Tool__'): 
		cmds.makeLive(none=True)
		if cmds.objExists('__Placement_Tool_c__'): cmds.delete('__Placement_Tool_c__')
		if cmds.objExists('__Placement_Tool_f__'): cmds.delete('__Placement_Tool_f__')
		if cmds.objExists('__Placement_Tool_g__'): cmds.delete('__Placement_Tool_g__')
		if cmds.objExists('__Placement_Tool__'): cmds.delete('__Placement_Tool__')
		cmds.xform(rp=(osPivot[0],osPivot[1],osPivot[2]),os=1)
		Start = False
		PT_START_UI()
	if Start:
		global osPivot
		osPivot=cmds.xform(q=1,rp=1,os=1)
		global wsPivot
		wsPivot=cmds.xform(q=1,rp=1,ws=1)
		cmds.setToolTo('moveSuperContext')
		sel=cmds.ls(sl=1,l=1)
		cmds.InvertSelection()
		cmds.select(cmds.ls(sl=1,v=1))
		cmds.select(cmds.filterExpand(sm=12))
		selAll=cmds.ls(sl=1)
		cmds.duplicate()
		cmds.group(name=('__Placement_Tool_g__'))
		cmds.CombinePolygons()
		cmds.hyperShade(assign='lambert1')
		cmds.polyMapDel()
		cmds.DeleteHistory()
		cmds.rename('__Placement_Tool__')
		cmds.hide()
		# Move Pivot
		cmds.select(sel)
		for i in sel :
		    pos = cmds.xform(i,q=1,ws=1,piv=1)
		    dup = cmds.duplicate(i,rr=1,po=1)
		    for attr in ['tx','ty','tz','rx','ry','rz','sx','sy','sz'] :
		        if cmds.getAttr(dup[0]+'.'+attr,lock=True):cmds.setAttr(dup[0]+'.'+attr,lock=False)
		    shapeNode = cmds.ls(cmds.listRelatives(i,c=1,f=1),l=1,s=1)
		    for s in shapeNode :
		        cmds.parent(s,dup[0],add=1,s=1)
		    if cmds.listRelatives(dup[0],p=1) :
		        cmds.parent(dup[0],w=1)
		    cmds.setAttr(dup[0]+'.r',0,0,0,type="double3")              
		    bb=cmds.xform(dup[0],q=1,bb=1,ws=1)
		    cp=cmds.objectCenter(dup[0])
		    xpos=cp[0];ypos=bb[1];zpos = cp[2]
		    loc=cmds.spaceLocator()
		    cmds.xform(loc[0],ws=1,t=(xpos,ypos,zpos))
		    cmds.parent(loc[0],dup[0])
		    cmds.delete(cmds.parentConstraint(i,dup[0]))
		    pivPos=cmds.xform(loc[0],q=1,ws=1,t=1)
		    cmds.xform(i,ws=1,piv=(pivPos[0],pivPos[1],pivPos[2]))
		    cmds.delete(dup[0],loc[0])
		cmds.select(sel,r=1)
		cmds.select('__Placement_Tool__',r=1);cmds.select(sel,add=1)
		cmds.normalConstraint(worldUpType="none",aimVector=(0, 1, 0),upVector=(0, 1, 0),weight=1,name='__Placement_Tool_c__')
		cmds.select('__Placement_Tool__',r=1);cmds.makeLive()
		cmds.select(selAll)
		cmds.createDisplayLayer(name="__Placement_Tool_f__",number=1,nr=1)
		import maya.mel as mel
		mel.eval('layerEditorLayerButtonTypeChange("__Placement_Tool_f__")')
		mel.eval('layerEditorLayerButtonTypeChange("__Placement_Tool_f__")')
		cmds.select(sel)
		PT_STOP_UI()
	cmds.undoInfo(closeChunk=True)
Exemplo n.º 48
0
def crowd_LocatorsToParentCurve(crowdGrp=None):
    '''{'path':'Dynamics/Particles/Crowd/crowd_LocatorsToParentCurve( )ONLYSE',
'icon':':/locator.png',
'usage':"""
#这个命令是将nParticleShape1_locGrp组中locator, 放到nParticleShape1_curGrp组中对应曲线上;
$fun( crowdGrp="curve_grp" )""",
}
'''
    if not crowdGrp or not cmds.objExists(crowdGrp):
        raise IOError('%s does not exists!' % (crowdGrp))

    for cur in cmds.listRelatives(crowdGrp, f=True):
        if not cmds.listRelatives(cur, type='nurbsCurve'):
            cmds.parent(cur, w=True)

    allLoc = cmds.listRelatives(crowdGrp, ad=True, type='locator', f=True)
    allLoc = cmds.listRelatives(allLoc, parent=True, f=True)

    qm.delAttr(allLoc, ['curveId', 'curveLength', 'currentLength'])
    cmds.addAttr(allLoc, ln='curveId', at='long')
    cmds.addAttr(allLoc, ln='curveLength', at='double')
    cmds.addAttr(allLoc, ln='currentLength', at='double')

    detachNode = cmds.createNode('detachCurve')
    detachedCurve = pm.createNode('nurbsCurve')
    cmds.setAttr(detachNode + '.parameter[0]', .1)
    cmds.connectAttr(detachNode + '.outputCurve[0]',
                     detachedCurve.name() + '.create')

    try:
        for i, cur in enumerate(cmds.listRelatives(crowdGrp, f=True)):
            curShape = cmds.listRelatives(cur, type='nurbsCurve')[0]
            locs = cmds.listRelatives(cur, ad=True, type='locator', f=True)
            if not locs:
                continue
            curNode = pm.PyNode(curShape)
            cmds.connectAttr(curShape + '.worldSpace',
                             detachNode + '.inputCurve',
                             f=True)
            for loc in cmds.listRelatives(locs, parent=True, f=True):
                if cmds.getAttr(cur + '.minValue') != 0:
                    cmds.rebuildCurve(cur,
                                      ch=0,
                                      rpo=1,
                                      rt=0,
                                      end=1,
                                      kr=0,
                                      kcp=0,
                                      kep=1,
                                      kt=0,
                                      s=0,
                                      d=3,
                                      tol=0.01)

                pos = curNode.closestPoint(cmds.objectCenter(loc),
                                           space='world')
                cmds.xform(loc, ws=True, translation=pos)
                wScale = [
                    1 / s for s in cmds.xform(loc, q=True, ws=True, scale=True)
                ]
                cmds.xform(loc, ws=True, scale=wScale)

                param = curNode.getParamAtPoint(pos, space='world')

                cmds.setAttr(detachNode + '.parameter[0]', param)
                curLength = detachedCurve.length() if param else 0

                cmds.setAttr(loc + '.curveId', i)
                cmds.setAttr(loc + '.curveLength', curNode.length())
                cmds.setAttr(loc + '.currentLength', curLength)

    except:
        cmds.delete(detachNode,
                    cmds.listRelatives(detachedCurve.name(), parent=True))
        raise IOError('Got a error!')
    cmds.delete(detachNode,
                cmds.listRelatives(detachedCurve.name(), parent=True))
Exemplo n.º 49
0
	def create(self):

		worldMatrixNode=mc.createNode('fourByFourMatrix')
		wm=\
		[
			[1,0,0,0],
			[0,1,0,0],
			[0,0,1,0],
			[0,0,0,1]
		]
		for a in range(0,4):
			for b in range(0,4):
				mc.setAttr( worldMatrixNode+'.in'+str(a)+str(b), wm[a][b] )

		self.worldMatrix=worldMatrixNode+'.o'

		wsMatrices=[]

		cleanup=[]

		lattices=[]
		uvPos=[]
		antipodes=[]

		cpos=mc.createNode('closestPointOnSurface')

		if 'surfaceAttr' not in self.__dict__ or len(self.surfaceAttr)==0 and len(self.edges)>0:
			mc.select(self.edges)
			rebuildNode,surfaceNodeTr=mel.eval('zenLoftBetweenEdgeLoopPathRings(2)')[:2]
			self.surfaceAttr=rebuildNode+'.outputSurface'

			children=mc.listRelatives(surfaceNodeTr,c=True,s=True,ni=True,type='nurbsSurface')
			if isIterable(children) and len(children)>0:
				self.uSpans=mc.getAttr(children[0]+'.spansU')
				self.vSpans=mc.getAttr(children[0]+'.spansV')

			mc.disconnectAttr(self.surfaceAttr,surfaceNodeTr+'.create')
			mc.delete(surfaceNodeTr)


		if self.uSpans<0 or self.vSpans<0:
			tempTr=mc.createNode('transform')
			tempCurve=mc.createNode('nurbsCurve',p=tempTr)
			mc.connectAttr(self.surfaceAttr,tempCurve+'.create')
			self.uSpans=mc.getAttr(tempCurve+'.spansU')
			self.vSpans=mc.getAttr(tempCurve+'.spansV')
			mc.disconnectAttr(self.surfaceAttr,tempCurve+'.create')
			mc.delete(tempTr)

		orderedTrs=[]
		orderedCtrls=[]

		if self.distribute not in ['u','v']: #calculate the axis of distribution
			if len(self.trs)!=0:
				mc.connectAttr(self.surfaceAttr,cpos+'.inputSurface')
				uMin=100
				vMin=100
				uMax=0
				vMax=0
				uPosList=[]
				vPosList=[]

				for i in range(0,self.number):

					orderedTrs.append('')
					orderedCtrls.append('')
					t=self.trs[i]

					if mc.objExists(t): # find the closest point
						if self.hasGeometry:
							center=mc.objectCenter(t)
							mc.setAttr(cpos+'.ip',*center)
							posCenter,uCenter,vCenter=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

						rp=mc.xform(t,ws=True,q=True,rp=True)
						mc.setAttr(cpos+'.ip',*rp)
						posRP,uRP,vRP=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

						# see which is closer - object center or rotate pivot
						if self.hasGeometry:
							distCenter=distanceBetween(posCenter,center)
							distRP=distanceBetween(posRP,rp)

						if self.hasGeometry==False or abs(distCenter)>abs(distRP) :
							uPosList.append(uRP)
							vPosList.append(vRP)
							if uRP<uMin: uMin=uRP
							if uRP>uMax: uMax=uRP
							if vRP<vMin: vMin=vRP
							if vRP>vMax: vMax=vRP
						else:
							uPosList.append(uCenter)
							vPosList.append(vCenter)
							if uCenter<uMin: uMin=uCenter
							if uCenter>uMax: uMax=uCenter
							if vCenter<vMin: vMin=vCenter
							if vCenter>vMax: vMax=vCenter

			cfsi=mc.createNode('curveFromSurfaceIso')

			mc.connectAttr(self.surfaceAttr,cfsi+'.is')
			mc.setAttr(cfsi+'.idr',0)
			mc.setAttr(cfsi+'.iv',.5)
			mc.setAttr(cfsi+'.r',True)
			mc.setAttr(cfsi+'.rv',True)

			if len(self.trs)!=0:
				mc.setAttr(cfsi+'.min',uMin)
				mc.setAttr(cfsi+'.max',uMax)

			ci=mc.createNode('curveInfo')
			mc.connectAttr(cfsi+'.oc',ci+'.ic')
			uLength=mc.getAttr(ci+'.al')

			mc.setAttr(cfsi+'.idr',1)

			if len(self.trs)!=0:
				mc.setAttr(cfsi+'.min',vMin)
				mc.setAttr(cfsi+'.max',vMax)

			vLength=mc.getAttr(ci+'.al')

			mc.delete(cfsi,ci)

			if uLength>vLength:
				self.distribute='u'

				if len(self.trs)!=0:
					searchList=uPosList
					orderedList=uPosList[:]
					orderedList.sort()
			else:
				self.distribute='v'

				if len(self.trs)!=0:
					searchList=vPosList
					orderedList=vPosList[:]
					orderedList.sort()

			reverseTrs=False

			orderIDList=[]
			for n in range(0,self.number):
				s=searchList[n]
				for i in range(0,self.number):
					if s==orderedList[i] and i not in orderIDList:
						orderIDList.append(i)
						orderedTrs[i]=self.trs[n]
						orderedCtrls[i]=self.ctrls[n]
						if n==0 and i>len(self.trs)/2:
							reverseTrs=True
						break

			if reverseTrs:
				orderedTrs.reverse()
				self.trs=orderedTrs
				orderedCtrls.reverse()
				self.ctrls=orderedCtrls
			else:
				self.trs=orderedTrs
				self.ctrls=orderedCtrls

		if self.rebuild: # interactive rebuild, maintains even parameterization over the rivet surface, use with caution

			if self.distribute=='u':
				self.surfaceAttr=mel.eval('zenUniformSurfaceRebuild("'+self.surfaceAttr+'",'+str(self.uSpans*2)+',-1)')+'.outputSurface'
			else:
				self.surfaceAttr=mel.eval('zenUniformSurfaceRebuild("'+self.surfaceAttr+'",-1,'+str(self.vSpans*2)+')')+'.outputSurface'

		if not mc.isConnected(self.surfaceAttr,cpos+'.inputSurface'):
			mc.connectAttr(self.surfaceAttr,cpos+'.inputSurface',f=True)

		if self.taper=='distance' or self.createAimCurve or self.closestPoint=='geometry': # find the closest points ( and antipodes )

			for i in range(0,self.number):
				t=self.trs[i]
				cp=ClosestPoints(self.surfaceAttr,t)
				self.ClosestPoints.append(cp)

				if self.taper=='distance' or self.createAimCurve: # antipodes are used for lattice allignment and curve calculations
					antipodes.append(cp.getAntipodes(1))

		if self.taper!='none' or self.scale!='none': # measures scale with scaling

			cfsiLength=mc.createNode('curveFromSurfaceIso')
			ciLength=mc.createNode('curveInfo')
			lengthMultiplierNode=mc.createNode('multDoubleLinear')

			mc.setAttr(cfsiLength+'.relative',True)
			mc.setAttr(cfsiLength+'.relativeValue',True)

			if self.distribute=='u':
				mc.setAttr(cfsiLength+'.isoparmDirection',0)
			else:
				mc.setAttr(cfsiLength+'.isoparmDirection',1)

			mc.setAttr(cfsiLength+'.minValue',0)
			mc.setAttr(cfsiLength+'.maxValue',1)

			mc.setAttr(cfsiLength+".isoparmValue",.5)

			mc.connectAttr(self.surfaceAttr,cfsiLength+'.inputSurface')

			if mc.objExists(self.spaceTr):

				lengthCurve=mc.createNode('nurbsCurve',p=self.spaceTr)
				lengthCurveTG=mc.createNode('transformGeometry')

				mc.connectAttr(self.spaceTr+'.worldMatrix[0]',lengthCurveTG+'.txf')
				mc.connectAttr(cfsiLength+'.outputCurve',lengthCurveTG+'.ig')
				mc.connectAttr(lengthCurveTG+'.og',lengthCurve+'.create')
				mc.connectAttr(lengthCurve+'.worldSpace',ciLength+'.inputCurve')
				mc.setAttr(lengthCurve+'.intermediateObject',True)

				cleanup.extend([lengthCurveTG,cfsiLength])

			else:

				mc.connectAttr(cfsiLength+'.outputCurve',ciLength+'.inputCurve')

			mc.connectAttr(ciLength+'.al',lengthMultiplierNode+'.i1')
			mc.setAttr(lengthMultiplierNode+'.i2',1.0/float(mc.getAttr(ciLength+'.al')))

			lengthMultiplier=lengthMultiplierNode+'.o'


		uvPos=[]
		closestDistanceToCenter=Decimal('infinity')
		centerMostRivetID=0
		closestDistancesToCenter=[Decimal('infinity'),Decimal('infinity')]
		centerMostRivetIDs=[0,0]

		uvMultipliers=[]
		aimGroups=[]

		for i in range(0,self.number):

			pTrs=mc.listRelatives(self.trs[i],p=True)
			parentTr=''
			if len(iterable(pTrs))>0:
				parentTr=pTrs[0]

			t=self.trs[i]
			c=self.ctrls[i]
			r=mc.createNode('transform',n='Rivet#')

			wsMatrices.append(mc.xform(t,q=True,ws=True,m=True))

			if self.constraint: mc.setAttr(r+'.inheritsTransform',False)

			if not mc.objExists(c):
				c=t
				if not mc.objExists(t):
					c=r

			if not mc.objExists(c+'.zenRivet'):
				mc.addAttr(c,at='message',ln='zenRivet',sn='zriv')

			mc.connectAttr(r+'.message',c+'.zriv',f=True)

			if not mc.objExists(c+'.uPos'):
				mc.addAttr(c,k=True,at='double',ln='uPos',dv=50)
			if not mc.objExists(c+'.vPos'):
				mc.addAttr(c,k=True,at='double',ln='vPos',dv=50)

			if self.closestPoint=='geometry':
				up,vp=self.ClosestPoints[i].uvs[0]
			else:
				if mc.objExists(t):
					if self.hasGeometry:
						center=mc.objectCenter(t)
						mc.setAttr(cpos+'.ip',*center)
						posCenter,uCenter,vCenter=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

					rp=mc.xform(t,ws=True,q=True,rp=True)
					mc.setAttr(cpos+'.ip',*rp)
					posRP,uRP,vRP=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

					if self.hasGeometry:
						distCenter=distanceBetween(posCenter,center)
						distRP=distanceBetween(posRP,rp)

					if self.hasGeometry==False or abs(distCenter)>abs(distRP):
						up=uRP
						vp=vRP
					else:
						up=uCenter
						vp=vCenter

				elif len(distribute)>0:

					if self.distribute=='u':
						up=(i+1)/self.number
						vp=.5
					else:
						up=.5
						vp=(i+1)/self.number

			if up>float(self.uSpans)-.01: up=float(self.uSpans)-.01
			if vp>float(self.vSpans)-.01: vp=float(self.vSpans)-.01
			if up<.01: up=.01
			if vp<.01: vp=.01

			uvPos.append((up,vp))

			if up<.5 and self.distribute=='u' and Decimal(str(abs(.5-up)))<Decimal(str(closestDistancesToCenter[0])):
				closestDistancesToCenter[0]=abs(.5-up)
				centerMostRivetIDs[0]=i

			if up>.5 and self.distribute=='u' and Decimal(str(abs(.5-up)))<Decimal(str(closestDistancesToCenter[1])):
				closestDistancesToCenter[1]=abs(.5-up)
				centerMostRivetIDs[1]=i

			if up<.5 and self.distribute=='v' and Decimal(str(abs(.5-vp)))<Decimal(str(closestDistancesToCenter[0])):
				closestDistancesToCenter[0]=abs(.5-vp)
				centerMostRivetIDs[0]=i

			if up>.5 and self.distribute=='v' and Decimal(str(abs(.5-vp)))<Decimal(str(closestDistancesToCenter[1])):
				closestDistancesToCenter[1]=abs(.5-vp)
				centerMostRivetIDs[1]=i

			mc.setAttr(c+'.uPos',up*100)
			mc.setAttr(c+'.vPos',vp*100)

			posi=mc.createNode('pointOnSurfaceInfo')
			mc.setAttr((posi+".caching"),True)
			#mc.setAttr((posi+".top"),True)

			multiplyU=mc.createNode('multDoubleLinear')
			mc.connectAttr(c+".uPos",multiplyU+".i1")
			mc.setAttr(multiplyU+'.i2',.01)
			multiplyV=mc.createNode('multDoubleLinear')
			mc.connectAttr(c+".vPos",multiplyV+".i1")
			mc.setAttr(multiplyV+'.i2',.01)

			uvMultipliers.append([multiplyU,multiplyV])

			mc.connectAttr(self.surfaceAttr,posi+".inputSurface");
			mc.connectAttr(multiplyU+".o",posi+".parameterU")
			mc.connectAttr(multiplyV+".o",posi+".parameterV")

			dm=mc.createNode('decomposeMatrix')
			mc.setAttr(dm+'.caching',True)
			fbfm=mc.createNode('fourByFourMatrix')
			mc.setAttr(fbfm+'.caching',True)

			mc.connectAttr(posi+'.nnx',fbfm+'.in00')
			mc.connectAttr(posi+'.nny',fbfm+'.in01')
			mc.connectAttr(posi+'.nnz',fbfm+'.in02')
			mc.connectAttr(posi+'.nux',fbfm+'.in10')
			mc.connectAttr(posi+'.nuy',fbfm+'.in11')
			mc.connectAttr(posi+'.nuz',fbfm+'.in12')
			mc.connectAttr(posi+'.nvx',fbfm+'.in20')
			mc.connectAttr(posi+'.nvy',fbfm+'.in21')
			mc.connectAttr(posi+'.nvz',fbfm+'.in22')
			mc.connectAttr(posi+'.px',fbfm+'.in30')
			mc.connectAttr(posi+'.py',fbfm+'.in31')
			mc.connectAttr(posi+'.pz',fbfm+'.in32')

			if self.constraint:# and not self.parent:
				mc.connectAttr(fbfm+'.output',dm+'.inputMatrix')
			else:
				multMatrix=mc.createNode('multMatrix')
				mc.connectAttr(r+'.parentInverseMatrix',multMatrix+'.i[1]')
				mc.connectAttr(fbfm+'.output',multMatrix+'.i[0]')
				mc.connectAttr(multMatrix+'.o',dm+'.inputMatrix')

			mc.connectAttr(dm+'.outputTranslate',r+'.t')
			mc.connectAttr(dm+'.outputRotate',r+'.r')

			if t!=r:

				if self.createAimCurve:
					aimGroup=mc.createNode('transform',n='rivetAimGrp#')
					mc.parent(aimGroup,t,r=True)
					mc.parent(aimGroup,r)
					if self.keepPivot or self.closestPoint=='pivot':
						mc.xform(aimGroup,ws=True,piv=mc.xform(t,q=True,ws=True,rp=True))
					else:
						mc.xform(aimGroup,ws=True,piv=self.ClosestPoints[i][1])
					self.aimGroups.append(aimGroup)

				if self.constraint:

					if self.parent: # parent and constraint == ParentSpace

						self.parentSpaces.append(ParentSpace(t,r))
						pc=self.parentSpaces[i].parentConstraint

						sc=self.parentSpaces[i].scaleConstraint

						skip=['x']
						if\
						(
							(self.distribute=='v' and 'length' in self.scaleDirection) or
							(self.distribute=='u' and 'width' in self.scaleDirection) or
							t in self.skipScaleObjects
						):
							skip.append('y')
						if\
						(
							(self.distribute=='u' and 'length' in self.scaleDirection) or
							(self.distribute=='v' and 'width' in self.scaleDirection) or
							t in self.skipScaleObjects
						):
							skip.append('z')

						mc.scaleConstraint(sc,e=True,sk=skip)

						if t in self.skipRotateObjects:
							mc.parentConstraint(pc,e=True,sr=('x','y','z'))
						if t in self.skipTranslateObjects:
							mc.parentConstraint(pc,e=True,st=('x','y','z'))

					else: #just constraint

						if t in self.skipRotateObjects:
							pc=mc.parentConstraint(r,t,sr=('x','y','z'),mo=True)[0]#
						if t in self.skipTranslateObjects:
							pc=mc.parentConstraint(r,t,st=('x','y','z'),mo=self.mo)[0]
						if t not in self.skipRotateObjects and t not in self.skipTranslateObjects:
							pc=mc.parentConstraint(r,t,mo=self.mo)[0]



					pcTargets=mc.parentConstraint(pc,q=True,tl=True)

					pcIDs=[]

					nsc=listNodeConnections(r,pc,s=False,d=True)

					for n in range(0,len(nsc)):
						if len(nsc[n])==2 and mc.objExists(nsc[n][-1]):
							pcID=getIDs(nsc[n][-1])
							if isinstance(pcID,int):
								pcIDs.append(pcID)

					pcIDs=removeDuplicates(pcIDs)

					for pcID in pcIDs:
						mc.connectAttr(self.worldMatrix,pc+'.tg['+str(pcID)+'].tpm',f=True)
						mc.connectAttr(dm+'.outputTranslate',pc+'.tg['+str(pcID)+'].tt',f=True)
						mc.connectAttr(dm+'.outputRotate',pc+'.tg['+str(pcID)+'].tr',f=True)

					cleanup.append(r)

					if self.parent:

						scTargets=mc.scaleConstraint(sc,q=True,tl=True)

						scIDs=[]

						nsc=listNodeConnections(r,sc,s=False,d=True)

						for n in range(0,len(nsc)):
							if len(nsc[n])==2 and mc.objExists(nsc[n][-1]):
								scIDs.append(getIDs(nsc[n][-1]))

						scIDs=removeDuplicates(scIDs)

						scMD=mc.createNode('multiplyDivide')
						mc.setAttr(scMD+'.i1',1,1,1)
						mc.setAttr(scMD+'.i2',1,1,1)

						for scID in scIDs:

							mc.connectAttr(self.worldMatrix,sc+'.tg['+str(scID)+'].tpm',f=True)
							#mc.connectAttr(scMD+'.o',sc+'.tg['+str(scID)+'].ts',f=True)
							mc.connectAttr(scMD+'.ox',sc+'.tg['+str(scID)+'].tsx',f=True)
							mc.connectAttr(scMD+'.oy',sc+'.tg['+str(scID)+'].tsy',f=True)
							mc.connectAttr(scMD+'.oz',sc+'.tg['+str(scID)+'].tsz',f=True)

						r=self.parentSpaces[i][0]
						#xfm=mc.xform(r,q=True,ws=True,m=True)
						#mc.setAttr(r+'.inheritsTransform',False)
						#mc.xform(r,m=xfm)
						#mc.connectAttr(self.surfaceMatrix,multMatrix+'.i[1]',f=True)#self.parentSpaces[i][0]+'.parentInverseMatrix'

				elif self.createAimCurve:
					mc.parent(t,w=True)
					mc.setAttr(t+'.inheritsTransform',False)
					mc.parent(t,r,r=True)
				else:
					mc.parent(t,r)

				if mc.objExists(parentTr) and (self.parent or self.createAimCurve) and not self.constraint:

					if not (parentTr in iterable(mc.listRelatives(r,p=True))):

						if mc.getAttr(r+'.inheritsTransform')==True:
							mc.parent(r,parentTr,r=True)
						else:
							mc.parent(r,parentTr)

					if mc.getAttr(r+'.inheritsTransform')==False:

						dm=mc.createNode('decomposeMatrix')
						mc.connectAttr(parentTr+'.worldMatrix',dm+'.inputMatrix')
						mc.connectAttr(dm+'.os',t+'.s',f=True)

			if self.taper!='none' or self.scale!='none':

				cfsiU=mc.createNode('curveFromSurfaceIso')

				mc.setAttr(cfsiU+'.relative',True)
				mc.setAttr(cfsiU+'.relativeValue',True)
				mc.setAttr(cfsiU+'.isoparmDirection',0)
				mc.setAttr(cfsiU+'.minValue',0)
				mc.setAttr(cfsiU+'.maxValue',1)

				mc.connectAttr(multiplyV+".o",cfsiU+".isoparmValue")
				mc.connectAttr(self.surfaceAttr,cfsiU+'.inputSurface')

				cfsiV=mc.createNode('curveFromSurfaceIso')

				mc.setAttr(cfsiV+'.relative',True)
				mc.setAttr(cfsiV+'.relativeValue',True)
				mc.setAttr(cfsiV+'.isoparmDirection',1)
				mc.setAttr(cfsiV+'.minValue',0)
				mc.setAttr(cfsiV+'.maxValue',1)

				mc.connectAttr(multiplyV+".o",cfsiV+".isoparmValue")
				mc.connectAttr(self.surfaceAttr,cfsiV+'.inputSurface')

				subtractNode=mc.createNode('addDoubleLinear')
				mc.setAttr(subtractNode+'.i1',-(1/(self.number*2)))
				addNode=mc.createNode('addDoubleLinear')
				mc.setAttr(addNode+'.i1',1/(self.number*2))
				addSubClampNode=mc.createNode('clamp')
				mc.setAttr(addSubClampNode+'.min',0,0,0)
				mc.setAttr(addSubClampNode+'.max',1,1,1)
				mc.connectAttr(subtractNode+'.o',addSubClampNode+'.inputR')
				mc.connectAttr(addNode+'.o',addSubClampNode+'.inputG')

				if self.distribute=='u':
					mc.connectAttr(multiplyU+".o",subtractNode+".i2")
					mc.connectAttr(multiplyU+".o",addNode+".i2")
					mc.connectAttr(addSubClampNode+'.outputR',cfsiU+'.minValue')
					mc.connectAttr(addSubClampNode+'.outputG',cfsiU+'.maxValue')
				else:
					mc.connectAttr(multiplyV+".o",subtractNode+".i2")
					mc.connectAttr(multiplyV+".o",addNode+".i2")
					mc.connectAttr(addSubClampNode+'.outputR',cfsiV+'.minValue')
					mc.connectAttr(addSubClampNode+'.outputG',cfsiV+'.maxValue')

				ciU=mc.createNode('curveInfo')
				mc.connectAttr(cfsiU+'.outputCurve',ciU+'.inputCurve')

				ciV=mc.createNode('curveInfo')
				mc.connectAttr(cfsiV+'.outputCurve',ciV+'.inputCurve')

				mdlU=mc.createNode('multDoubleLinear')
				mc.connectAttr(ciU+'.al',mdlU+'.i1')
				mc.setAttr(mdlU+'.i2',1/float(mc.getAttr(ciU+'.al')))

				mdlV=mc.createNode('multDoubleLinear')
				mc.connectAttr(ciV+'.al',mdlV+'.i1')
				mc.setAttr(mdlV+'.i2',1/float(mc.getAttr(ciV+'.al')))

				if not mc.objExists(c+'.minScaleWidth'): mc.addAttr(c,ln='minScaleWidth',at='double',k=True,min=0,dv=self.minScaleWidth)
				if not mc.objExists(c+'.maxScaleWidth'): mc.addAttr(c,ln='maxScaleWidth',at='double',k=True,min=0,dv=self.maxScaleWidth)
				if not mc.objExists(c+'.minScaleLength'): mc.addAttr(c,ln='minScaleLength',at='double',k=True,min=0,dv=self.minScaleLength)
				if not mc.objExists(c+'.maxScaleLength'): mc.addAttr(c,ln='maxScaleLength',at='double',k=True,min=0,dv=self.maxScaleLength)

				clampNode=mc.createNode('clamp')

				minScaleLengthNode=mc.createNode('multDoubleLinear')
				maxScaleLengthNode=mc.createNode('multDoubleLinear')
				minScaleWidthNode=mc.createNode('multDoubleLinear')
				maxScaleWidthNode=mc.createNode('multDoubleLinear')

				mc.connectAttr(c+'.minScaleLength',minScaleLengthNode+'.i1')
				mc.connectAttr(lengthMultiplier,minScaleLengthNode+'.i2')

				mc.connectAttr(c+'.maxScaleLength',maxScaleLengthNode+'.i1')
				mc.connectAttr(lengthMultiplier,maxScaleLengthNode+'.i2')

				mc.connectAttr(c+'.minScaleWidth',minScaleWidthNode+'.i1')
				mc.connectAttr(lengthMultiplier,minScaleWidthNode+'.i2')

				mc.connectAttr(c+'.maxScaleWidth',maxScaleWidthNode+'.i1')
				mc.connectAttr(lengthMultiplier,maxScaleWidthNode+'.i2')

				if self.distribute=='u':
					mc.connectAttr(minScaleLengthNode+'.o',clampNode+'.minR')
					mc.connectAttr(maxScaleLengthNode+'.o',clampNode+'.maxR')
					mc.connectAttr(minScaleWidthNode+'.o',clampNode+'.minG')
					mc.connectAttr(maxScaleWidthNode+'.o',clampNode+'.maxG')
				else:
					mc.connectAttr(minScaleWidthNode+'.o',clampNode+'.minR')
					mc.connectAttr(maxScaleWidthNode+'.o',clampNode+'.maxR')
					mc.connectAttr(minScaleLengthNode+'.o',clampNode+'.minG')
					mc.connectAttr(maxScaleLengthNode+'.o',clampNode+'.maxG')

				mc.connectAttr(mdlU+'.o',clampNode+'.ipr')
				mc.connectAttr(mdlV+'.o',clampNode+'.ipg')

				if self.scale=='relative' and self.parent:#or len(self.scaleDirection)<2:#

					if\
					(
						(self.distribute=='u' and 'length' in self.scaleDirection) or
						(self.distribute=='v' and 'width' in self.scaleDirection)
					):
						if self.constraint:
							mc.connectAttr(clampNode+'.opr',scMD+'.i1y')
						else:
							mc.connectAttr(clampNode+'.opr',r+'.sy',f=True)
					if\
					(
						(self.distribute=='v' and 'length' in self.scaleDirection) or
						(self.distribute=='u' and 'width' in self.scaleDirection)
					):
						if self.constraint:
							mc.connectAttr(clampNode+'.opg',scMD+'.i1z')
						else:
							mc.connectAttr(clampNode+'.opg',r+'.sz',f=True)


				elif self.taper!='none' and self.parent:

					#self.autoFlexGroups

					mc.setAttr(t+'.sx',lock=True)
					mc.setAttr(t+'.sy',lock=True)
					mc.setAttr(t+'.sz',lock=True)
					mc.setAttr(t+'.tx',lock=True)
					mc.setAttr(t+'.ty',lock=True)
					mc.setAttr(t+'.tz',lock=True)
					mc.setAttr(t+'.rx',lock=True)
					mc.setAttr(t+'.ry',lock=True)
					mc.setAttr(t+'.rz',lock=True)

					aimTr=mc.createNode('transform',p=t)
					mc.xform(aimTr,ws=True,t=antipodes[i])

					#mc.setAttr(db+'.p1',*self.ClosestPoints[i][0])
					#mc.setAttr(db+'.p2',*antipodes[i])
					axisLength=distanceBetween(self.ClosestPoints[i][0],antipodes[i])#mc.getAttr(db+'.d')

					ffd,lattice,latticeBase=mc.lattice(t,divisions=(2,2,2),objectCentered=True,ol=1)
					latticeLowEndPoints=mc.ls(lattice+'.pt[0:1][0:0][0:1]',fl=True)
					latticeHighEndPoints=mc.ls(lattice+'.pt[0:1][1:1][0:1]',fl=True)

					mc.parent(latticeBase,lattice)

					mc.setAttr(lattice+'.sy',axisLength)

					lattices.append([ffd,lattice,latticeBase])

					mc.parent(lattice,t)
					mc.xform(lattice,ws=True,a=True,t=mc.xform(r,q=True,ws=True,a=True,rp=True))
					mc.xform(lattice,os=True,a=True,ro=(0,0,0))
					mc.move(0,axisLength/2,0,lattice,r=True,os=True,wd=True)

					xSum,ySum,zSum=0,0,0
					for p in latticeLowEndPoints:
						px,py,pz=mc.pointPosition(p,w=True)
						xSum+=px
						ySum+=py
						zSum+=pz

					mc.xform(lattice,ws=True,piv=(xSum/len(latticeLowEndPoints),ySum/len(latticeLowEndPoints),zSum/len(latticeLowEndPoints)))
					mc.xform(latticeBase,ws=True,piv=(xSum/len(latticeLowEndPoints),ySum/len(latticeLowEndPoints),zSum/len(latticeLowEndPoints)))

					ac=mc.aimConstraint(aimTr,lattice,aim=(0,1,0),wut='objectrotation',wuo=r,u=(0,0,1),mo=False)
					mc.delete(ac)

					ac=mc.aimConstraint(aimTr,aimGroup,aim=(0,1,0),wut='objectrotation',wuo=r,u=(0,0,1),mo=False)
					mc.delete(ac,aimTr)

					lowEndCluster,lowEndClusterHandle=mc.cluster(latticeLowEndPoints)[:2]
					highEndCluster,highEndClusterHandle=mc.cluster(latticeHighEndPoints)[:2]

					lowEndClusterHandleShape=mc.listRelatives(lowEndClusterHandle,c=True)[0]
					highEndClusterHandleShape=mc.listRelatives(highEndClusterHandle,c=True)[0]

					#mc.parent(highEndClusterHandle,t)

					if mc.isConnected(lowEndClusterHandleShape+'.clusterTransforms[0]',lowEndCluster+'.clusterXforms'):
						mc.disconnectAttr(lowEndClusterHandleShape+'.clusterTransforms[0]',lowEndCluster+'.clusterXforms')
					if mc.isConnected(highEndClusterHandleShape+'.clusterTransforms[0]',highEndCluster+'.clusterXforms'):
						mc.disconnectAttr(highEndClusterHandleShape+'.clusterTransforms[0]',highEndCluster+'.clusterXforms')

					self.autoFlexGroups.append\
					(
						(
							mc.createNode('transform',n='rivetBaseAutoFlex#',p=r),
							mc.createNode('transform',n='rivetEndAutoFlex#',p=aimGroup)
						)
					)

					self.handles.append\
					(
						(
							mc.createNode('transform',n='rivetBaseCtrl#',p=self.autoFlexGroups[i][0]),
							mc.createNode('transform',n='rivetEndCtrl#',p=self.autoFlexGroups[i][1])
						)
					)

					self.handleShapes.append\
					(
						(
							mc.createNode('locator',p=self.handles[i][0]),
							mc.createNode('locator',p=self.handles[i][1])
						)
					)

					mc.setAttr(self.handleShapes[i][0]+'.los',.5,.5,.5)
					mc.setAttr(self.handleShapes[i][1]+'.los',.5,.5,.5)

					mc.xform(self.autoFlexGroups[i][0],ws=True,a=True,t=mc.xform(t,q=True,ws=True,rp=True))
					mc.xform(self.autoFlexGroups[i][0],ws=True,a=True,piv=mc.xform(t,q=True,ws=True,rp=True))

					for bp in self.bindPoses: mc.dagPose((self.handles[i][0],self.handles[i][1]),a=True,n=bp)

					mc.xform(self.autoFlexGroups[i][1],ws=True,t=antipodes[i])

					mc.hide(lattice)

					mc.connectAttr(self.handles[i][0]+'.worldInverseMatrix[0]',lowEndCluster+'.bindPreMatrix',f=True)
					mc.disconnectAttr(self.handles[i][0]+'.worldInverseMatrix[0]',lowEndCluster+'.bindPreMatrix')

					mc.connectAttr(self.handles[i][0]+'.worldMatrix[0]',lowEndCluster+'.matrix',f=True)

					mc.connectAttr(self.handles[i][1]+'.worldInverseMatrix[0]',highEndCluster+'.bindPreMatrix',f=True)
					mc.disconnectAttr(self.handles[i][1]+'.worldInverseMatrix[0]',highEndCluster+'.bindPreMatrix')

					mc.connectAttr(self.handles[i][1]+'.worldMatrix[0]',highEndCluster+'.matrix',f=True)

					aimGroups.append(aimGroup)

					if self.distribute=='u':
						mc.connectAttr(clampNode+'.opr',self.autoFlexGroups[i][0]+'.sy')
					else:
						mc.connectAttr(clampNode+'.opg',self.autoFlexGroups[i][0]+'.sz')

					mc.delete([lowEndClusterHandle,highEndClusterHandle])

				self.rivets.append(r)

		if self.createAimCurve and self.parent:

			pmm=mc.createNode('pointMatrixMult')
			arcPoints=[]
			ids=[0,centerMostRivetIDs[0],centerMostRivetIDs[1],-1]

			for id in ids:

				measureTr=mc.createNode('transform')
				aimTr=mc.createNode('transform',p=self.trs[id])
				mc.parent(measureTr,self.trs[id])

				mc.xform(aimTr,ws=True,t=antipodes[id])
				mc.xform(measureTr,ws=True,t=mc.xform(self.rivets[id],q=True,ws=True,a=True,rp=True))
				#mc.xform(measureTr,os=True,a=True,ro=(0,0,0),s=(1,1,1))

				ac=mc.aimConstraint(aimTr,measureTr,aim=(0,1,0),wut='objectrotation',wuo=self.rivets[id],u=(0,0,1),mo=False)
				mc.delete(ac,aimTr)

				mc.connectAttr(measureTr+'.worldInverseMatrix',pmm+'.inMatrix',f=True)

				maxYID=-1
				maxY=0.0
				yVal=0.0

				for i in range(0,self.number):

					mc.setAttr(pmm+'.ip',*antipodes[i])
					yVal=mc.getAttr(pmm+'.oy')
					if yVal>maxY:
						maxY=yVal
						maxYID=i

				mc.setAttr(pmm+'.ip',*antipodes[maxYID])

				oy=mc.getAttr(pmm+'.oy')

				mc.setAttr(pmm+'.ip',*antipodes[id])

				ox=mc.getAttr(pmm+'.ox')
				oz=mc.getAttr(pmm+'.oz')

				mc.connectAttr(measureTr+'.worldMatrix',pmm+'.inMatrix',f=True)
				mc.setAttr(pmm+'.ip',ox,oy,oz)

				ap=mc.getAttr(pmm+'.o')[0]

				arcPoints.append(ap)

				mc.disconnectAttr(measureTr+'.worldMatrix',pmm+'.inMatrix')

				mc.delete(measureTr)

			mc.delete(pmm)

			arcCtrlArg=arcPoints
			arcCtrlKeys={'arcWeight':self.arcWeight,'p':self.parents,'sp':self.softParents}

			for k in arcCtrlKeys:
				if type(arcCtrlKeys[k]).__name__=='NoneType':
					del(arcCtrlKeys[k])

			self.ArcCtrl=ArcCtrl(*arcCtrlArg,**arcCtrlKeys)

			mc.addAttr(self.ArcCtrl[0],at='bool',ln='showHandles',k=True,dv=False)
			mc.setAttr(self.ArcCtrl[0]+'.showHandles',k=False,cb=True)
			mc.setAttr(self.ArcCtrl[0]+'.v',k=False,cb=True)
			mc.setAttr(self.ArcCtrl[1]+'.v',k=False,cb=True)

			for h in self.handles:
				mc.connectAttr(self.ArcCtrl[0]+'.showHandles',h[0]+'.v')
				mc.connectAttr(self.ArcCtrl[0]+'.showHandles',h[1]+'.v')

			for bp in self.bindPoses: mc.dagPose(self.ArcCtrl,a=True,n=bp)

			cpoc=mc.createNode('closestPointOnCurve')
			mc.connectAttr(self.ArcCtrl.outputCurve,cpoc+'.inCurve')

			for i in range(0,self.number):

				aimTr=mc.createNode('transform')
				poci=mc.createNode('pointOnCurveInfo')
				dm=mc.createNode('decomposeMatrix')
				fbfm=mc.createNode('fourByFourMatrix')

				mc.connectAttr(poci+'.nnx',fbfm+'.in00')
				mc.connectAttr(poci+'.nny',fbfm+'.in01')
				mc.connectAttr(poci+'.nnz',fbfm+'.in02')
				mc.connectAttr(poci+'.ntx',fbfm+'.in10')
				mc.connectAttr(poci+'.nty',fbfm+'.in11')
				mc.connectAttr(poci+'.ntz',fbfm+'.in12')

				mc.connectAttr(self.ArcCtrl.outputNormal+'X',fbfm+'.in20')
				mc.connectAttr(self.ArcCtrl.outputNormal+'Y',fbfm+'.in21')
				mc.connectAttr(self.ArcCtrl.outputNormal+'Z',fbfm+'.in22')

				mc.connectAttr(poci+'.px',fbfm+'.in30')
				mc.connectAttr(poci+'.py',fbfm+'.in31')
				mc.connectAttr(poci+'.pz',fbfm+'.in32')

				mc.connectAttr(fbfm+'.output',dm+'.inputMatrix')
				mc.connectAttr(dm+'.outputTranslate',aimTr+'.t')
				mc.connectAttr(dm+'.outputRotate',aimTr+'.r')

				mc.setAttr(cpoc+'.ip',*antipodes[i])
				cpu=mc.getAttr(cpoc+'.u')
				mc.setAttr(poci+'.parameter',cpu)

				mc.connectAttr(self.ArcCtrl.outputCurve,poci+'.inputCurve')

				ac=mc.aimConstraint(aimTr,self.aimGroups[i],aim=(0,1,0),wut='objectrotation',wuo=aimTr,u=(0,0,1),mo=not(self.realign))[0]

				disconnectNodes(aimTr,ac)

				mc.connectAttr(fbfm+'.output',ac+'.worldUpMatrix',f=True)
				mc.connectAttr(dm+'.ot',ac+'.target[0].targetTranslate',f=True)

				mc.delete(aimTr)

				sc=mc.createNode('subCurve')

				mc.setAttr(sc+'.relative',True)
				mc.setAttr(sc+'.minValue',0)
				mc.setAttr(sc+'.maxValue',1)

				mc.connectAttr(self.ArcCtrl.outputCurve,sc+'.ic')

				if self.distribute=='u':
					uMultAttr=uvMultipliers[i][0]+".o"
				else:
					uMultAttr=uvMultipliers[i][1]+".o"

				#adjust for offset

				multOffsetCalc=mc.createNode('multDoubleLinear')
				mc.setAttr(multOffsetCalc+'.i1',1/mc.getAttr(uMultAttr))
				mc.connectAttr(uMultAttr,multOffsetCalc+'.i2')

				multOffset=mc.createNode('multDoubleLinear')
				mc.setAttr(multOffset+'.i1',cpu)
				mc.connectAttr(multOffsetCalc+'.o',multOffset+'.i2')

				mc.connectAttr(multOffset+'.o',poci+'.parameter',f=True)

				subtractNode=mc.createNode('addDoubleLinear')
				mc.setAttr(subtractNode+'.i1',-(1.0/(self.number*2)))
				addNode=mc.createNode('addDoubleLinear')
				mc.setAttr(addNode+'.i1',1.0/(self.number*2))
				addSubClampNode=mc.createNode('clamp')
				mc.setAttr(addSubClampNode+'.min',0,0,0)
				mc.setAttr(addSubClampNode+'.max',1,1,1)
				mc.connectAttr(subtractNode+'.o',addSubClampNode+'.inputR')
				mc.connectAttr(addNode+'.o',addSubClampNode+'.inputG')

				mc.connectAttr(multOffset+".o",subtractNode+".i2")
				mc.connectAttr(multOffset+".o",addNode+".i2")
				mc.connectAttr(addSubClampNode+'.outputR',sc+'.minValue')
				mc.connectAttr(addSubClampNode+'.outputG',sc+'.maxValue')

				ciU=mc.createNode('curveInfo')
				mc.connectAttr(sc+'.outputCurve',ciU+'.inputCurve')

				mdlU=mc.createNode('multDoubleLinear')
				mc.connectAttr(ciU+'.al',mdlU+'.i1')
				mc.setAttr(mdlU+'.i2',1/float(mc.getAttr(ciU+'.al')))

				clampNode=mc.createNode('clamp')

				if not mc.objExists(c+'.minScaleEnd'): mc.addAttr(self.ctrls[i],ln='minScaleEnd',at='double',k=True,min=0,max=1,dv=0)
				if not mc.objExists(c+'.maxScaleEnd'): mc.addAttr(self.ctrls[i],ln='maxScaleEnd',at='double',k=True,min=0,dv=1)

				mc.connectAttr(self.ctrls[i]+'.minScaleEnd',clampNode+'.minR')
				mc.connectAttr(self.ctrls[i]+'.maxScaleEnd',clampNode+'.maxR')

				mc.connectAttr(mdlU+'.o',clampNode+'.ipr')

				if self.distribute=='u':
					mc.connectAttr(clampNode+'.opr',self.autoFlexGroups[i][1]+'.sz')
				else:
					mc.connectAttr(clampNode+'.opr',self.autoFlexGroups[i][1]+'.sy')

			mc.delete(cpoc)

		if self.parent:
			self[:]=self.rivets
		else:
			self[:]=self.trs
		#if self.mo:
		#	#for i in len(self.trs):
		#		#try: mc.xform(t,q=True,ws=True,m=wsMatrices[i]))
		#		#except: pass

		cleanup.append(cpos)

		for c in cleanup:
			if mc.objExists(c):
				disconnectNodes(c)
				mc.delete(c)

		if self.snapToSurface:
			if self.createAimCurve or self.taper:
				for i in range(0,self.number):
					mc.xform(self.handles[i][0],ws=True,t=mc.xform(self.rivets[i],q=True,ws=True,rp=True))
					mc.xform(self.trs[i],ws=True,rp=mc.xform(self.rivets[i],q=True,ws=True,rp=True))
			else:
				for i in range(0,self.number):
					mc.xform(self.trs[i],ws=True,t=mc.xform(self.rivets[i],q=True,ws=True,rp=True))
					mc.xform(self.trs[i],ws=True,ro=mc.xform(self.rivets[i],q=True,ws=True,ro=True))