def rsChName(i_s_textField, s_name):
    l_oSels = rsObjList()
    i_LockState = cmds.getAttr(l_oSels[2], lock=True)
    if i_LockState:
        cmds.setAttr(l_oSels[2], lock=False)
    if s_name == "NewName":
        s_NewName = l_oSels[0] + "." + i_s_textField
        cmds.renameAttr(l_oSels[2], i_s_textField)
        if i_LockState:
            cmds.setAttr(s_NewName, lock=True)
        s_search = i_s_textField
    else:
        cmds.addAttr(l_oSels[2], edit=True, niceName=i_s_textField)
        if i_LockState:
            cmds.setAttr(l_oSels[2], lock=True)
        s_search = l_oSels[1]
    l_ChannelAtList = rsChannelAtList()
    l_AttrKey = l_ChannelAtList[0]
    l_AttrKeyHidden = l_ChannelAtList[1]
    if l_AttrKey or l_AttrKeyHidden:
        cmds.textScrollList("rsAttributeScroll", edit=True, removeAll=True, append=l_AttrKey)
        cmds.textScrollList("rsAttributeScrollHidden", edit=True, removeAll=True, append=l_AttrKeyHidden)
    cmds.select(cl=True)
    cmds.select(l_oSels[0], r=True)
    rsSearchInScroll(s_search)
    return True
 def jointOrientConstraints(self):
     """Function to set up the parent contraints on all of the joints"""
     for i, jnt in enumerate(self.masterJointList):
         oriConstName = nameConstraintRebuild(jnt.getName(),
                                              self.nameStringLE.text(),
                                              "jnt",
                                              "oriC",
                                              nameEnd=(self.masterCtrlAtt +
                                                       "Switch"))
         oriConst = cmds.orientConstraint(self.fkJointList[i].getName(),
                                          self.ikJointList[i].getName(),
                                          jnt.getName(),
                                          name=oriConstName)
         for i, att in enumerate(
                 cmds.orientConstraint(oriConstName,
                                       q=1,
                                       weightAliasList=True)):
             if i == 0:  #Set first FK weight
                 cmds.renameAttr(oriConstName + "." + att, "fkWeight")
             elif i == 1:  #Set Second IK Weight
                 cmds.renameAttr(oriConstName + "." + att, "ikWeight")
             #Now we make the correct connections to control the weights
         cmds.connectAttr(self.masterCtrl + "." + self.masterCtrlAtt,
                          oriConstName + ".ikWeight")
         cmds.connectAttr(self.pmaSwitchNode + ".output1D",
                          oriConstName + ".fkWeight")
Example #3
0
def rename_action_unit(index, new_name):
    action_units_dict = get_action_units_dict()
    new_dict = OrderedDict()
    if new_name in action_units_dict.keys():
        if action_units_dict.keys().index(new_name) != index:
            # log only if the name is not the one we're currently editing
            logger.warning(
                'An action unit named "{}" already exists'.format(new_name))
        new_dict = action_units_dict
    else:
        key_to_change = action_units_dict.keys()[index]
        for key, value in action_units_dict.iteritems():
            if key == key_to_change:
                new_dict[new_name] = value
            else:
                new_dict[key] = value

        facs_node = ensure_facs_node_exists()
        if not nicename_to_camelcase(new_name) == nicename_to_camelcase(
                key_to_change):
            cmds.renameAttr(
                facs_node + '.' + nicename_to_camelcase(key_to_change),
                nicename_to_camelcase(new_name))
        cmds.addAttr(facs_node + '.' + nicename_to_camelcase(new_name),
                     edit=True,
                     niceName=new_name)
        cmds.rename(
            nicename_to_camelcase(key_to_change) + '_unitToTime',
            nicename_to_camelcase(new_name) + '_unitToTime',
        )

    return new_dict
    def renameAttr(self, node, old, new, nameLayout, attrLayout, buttonLayout):
        """
        Rename the given attribute to the name given in the "new" argument.
        Update the UI layout.
        """
        # Rename Maya attribute
        plug = '.'.join([node, old])
        cmds.renameAttr(plug, new)

        # Update the layout
        cmds.textField(
            nameLayout,
            edit=True,
            changeCommand=
                lambda
                    text,
                    n=node,
                    a=new,
                    nl=nameLayout,
                    al=attrLayout,
                    bl=buttonLayout:
                self.renameAttr(n, a, PREFIX + '_' + text, nl, al, bl))

        # Update the button.
        cmds.button(
            buttonLayout,
            edit=True,
            command=lambda c, a=new: self.deleteAttr(a))

        # Update the field.
        plug = '.'.join([node, new])
        control = self.getControllerGroup(plug)
        control(attrLayout, edit=True, attribute=plug)
Example #5
0
    def setData(self, index, value, role):  # pylint: disable=invalid-name
        """
        Implement `QtCore.QAbstractItemModel.setData

        :param QtCore.QModelIndex index: The index to set
        :param str value: The value to set
        :param int role: The set role
        :return: True if the set was successful
        :rtype: bool
        """
        if role != QtCore.Qt.EditRole:
            return False

        item = self.itemFromIndex(index)

        src_attr_path = index.data(DataRole)  # type: str
        node = src_attr_path.split(".")[0]
        dst_attr_path = ".".join((node, value))

        # Validate the attribute is available
        if cmds.objExists(dst_attr_path):
            cmds.warning("Attribute %r already exist." % str(dst_attr_path))
            return False

        cmds.renameAttr(src_attr_path, value)

        # Update internal data
        item.setText(value)
        item.setData(dst_attr_path, DataRole)

        self.dataChanged.emit(index, index)
        return True
Example #6
0
def constrainAttributeNaming( cnstrs ) :
	
	for cnstr in cnstrs :
		
		cnstrType = mc.nodeType( cnstr )

		dummyAttr = 'targetTranslate'

		if cnstrType == 'parentConstraint' :

			dummyAttr = 'target[000].targetTranslate'

		elif cnstrType == 'pointConstraint' :

			dummyAttr = 'target[000].targetTranslate'

		elif cnstrType == 'orientConstraint' :

			dummyAttr = 'target[000].targetRotate'

		elif cnstrType == 'scaleConstraint' :

			dummyAttr = 'target[000].targetScale'

		elif cnstrType == 'aimConstraint' :

			dummyAttr = 'target[000].targetTranslate'

		elif cnstrType == 'poleVectorConstraint' :

			dummyAttr = 'constraintRotatePivot'

		if mc.listAttr( cnstr , ud=True ) :

			udAttrs = sorted( mc.listAttr( cnstr , ud=True ) )

			for ix in range( len( udAttrs ) ) :

				currNodeAttrName = '%s.%s' % ( cnstr , udAttrs[ix] )

				outAttr = dummyAttr.replace( '000' , str( ix ) )
				target = mc.listConnections( '%s.%s' % ( cnstr , outAttr ) , s=True )[0]

				newAttrName = '%sW%s' % ( target , str( ix ) )
				print '%s -- %s' % ( udAttrs[ix] , newAttrName )

				lock = False

				if mc.getAttr( currNodeAttrName , l=True ) :
					lock = True
					mc.setAttr( currNodeAttrName , l=False )

				if not udAttrs[ix] == newAttrName :
					mc.renameAttr( currNodeAttrName , newAttrName )

				if lock :
					mc.setAttr( '%s.%s' % ( cnstr , newAttrName ) , l=True )
Example #7
0
def aliasAttr(*args):
	selAttr = cmds.channelBox('mainChannelBox', q = True, selectedMainAttributes = True)[0]
	replace = cmds.textFieldGrp('aliasTxtFldGrp', q = True, text = True)

	selList = cmds.ls(sl = True)

	for sel in selList:
		cmds.renameAttr('%s.%s' %(sel, selAttr), replace)

	cmds.select(selList, r = True)
Example #8
0
    def renameLayer(self, sOldLayerName, sNewLayerName):
        """
        Renames the layer on node level, which means rename the attributes
        that are used for storing all parts of the render layer.
        """

        for sSuffix in self.lstLayerAttrs:
            # Make sure each attribute still exists before renaming them
            if mc.objExists(self.sSwNode + "." + sOldLayerName + "_" + sSuffix):
                mc.renameAttr(self.sSwNode + "." + sOldLayerName + "_" + sSuffix,
                    sNewLayerName + "_" + sSuffix)
	def jointOrientConstraints(self):
		"""Function to set up the parent contraints on all of the joints"""
		for i, jnt in enumerate(self.masterJointList):
			oriConstName = nameConstraintRebuild(jnt.getName(), self.nameStringLE.text(), "jnt",  "oriC", nameEnd = (self.masterCtrlAtt + "Switch"))
			oriConst = cmds.orientConstraint(self.fkJointList[i].getName(), self.ikJointList[i].getName(),jnt.getName(), name = oriConstName)
			for i, att in enumerate(cmds.orientConstraint(oriConstName, q=1, weightAliasList = True)):
				if i == 0: #Set first FK weight
					cmds.renameAttr(oriConstName + "." + att , "fkWeight")
				elif i == 1: #Set Second IK Weight 
					cmds.renameAttr(oriConstName + "." + att , "ikWeight")
				#Now we make the correct connections to control the weights
			cmds.connectAttr(self.masterCtrl + "." + self.masterCtrlAtt, oriConstName + ".ikWeight")
			cmds.connectAttr(self.pmaSwitchNode + ".output1D", oriConstName + ".fkWeight")
Example #10
0
 def setName(self, name):
     coral.Node.setName(self, str(name))
     newName = str(self.name())
     
     mayaNode = self.parent().mayaNode()
     cmds.lockNode(mayaNode, lock = False)
     
     for attr in self.attributes():
         if hasattr(attr, "setMayaAttribute"):
             cmds.renameAttr(attr.mayaNode() + "." + attr.mayaAttribute(), newName)
             attr.setMayaAttribute(newName)
     
     cmds.lockNode(mayaNode, lock = True)
Example #11
0
    def update(self):
        """Update the maya scene based on the module's fields

        This should ONLY be called in placement mode.
        """
        if self.is_built.get():
            return

        self.update_parent_joint()

        scene_metadata = mop.metadata.metadata_from_name(self.node_name)
        name_changed = self.name.get() != scene_metadata["base_name"]
        side_changed = self.side.get() != scene_metadata["side"]

        if name_changed or side_changed:
            # rename the module node
            new_name = self._update_node_name(self.node_name)
            self.node_name = new_name

            # rename the owned nodes
            for node in self.owned_nodes.get():
                self._update_node_name(node)

            # rename the persistent attributes
            persistent_attrs = cmds.listAttr(
                self.node_name, category="persistent_attribute_backup"
            )
            if persistent_attrs:
                for attr in persistent_attrs:
                    old_node, attr_name = attr.split("__")

                    metadata = mop.metadata.metadata_from_name(old_node)
                    metadata["base_name"] = self.name.get()
                    metadata["side"] = self.side.get()
                    new_node = mop.metadata.name_from_metadata(metadata)
                    logger.debug(
                        "Renaming persistent attribute from {} to {}".format(
                            self.node_name + "." + attr,
                            self.node_name + "." + new_node + "__" + attr_name,
                        )
                    )
                    cmds.renameAttr(
                        self.node_name + "." + attr, new_node + "__" + attr_name
                    )
        if side_changed:
            new_color = mop.config.side_color[self.side.get()]
            for guide in self.guide_nodes:
                shapeshifter.change_controller_color(guide, new_color)
        self.update_guide_nodes()
        self.update_deform_joints()
        self._constraint_deforms_to_guides()
Example #12
0
    def setName(self, name):
        coral.Node.setName(self, str(name))
        newName = str(self.name())

        mayaNode = self.parent().mayaNode()
        cmds.lockNode(mayaNode, lock=False)

        for attr in self.attributes():
            if hasattr(attr, "setMayaAttribute"):
                cmds.renameAttr(attr.mayaNode() + "." + attr.mayaAttribute(),
                                newName)
                attr.setMayaAttribute(newName)

        cmds.lockNode(mayaNode, lock=True)
Example #13
0
 def grab(self):
     objectsSelected = []
     selection = cmd.ls(selection = True)
     #finding constraints
     #naming constraints
     findConstraint = cmd.ls('grabber*',type='parentConstraint')#list all parent constraints before tt's named *grabber
     counter=len(findConstraint)
     DaGrabber = 'grabber_'+str(counter)
     
     for item in selection :
         if len(selection) == 2 :
             objectsSelected.append(item)
         elif len(selection)>2 or len(selection)<2:
             cmd.error ("please select exactly 2 objects : a parent and a child")
     
     # the Grab
     DaParentLocator = self.makingParentLocator(selection[-1]) 
     theGrab = cmd.parentConstraint( objectsSelected[0], DaParentLocator, n=DaGrabber, mo=True)[0]
     currentFrame = cmd.currentTime(query=True)
     previousFrame = currentFrame - 1
     #key the locator to display Grabber0
     cmd.setKeyframe(DaParentLocator,time=currentFrame)
     cmd.setKeyframe(DaParentLocator,time=previousFrame)
     cmd.setKeyframe(objectsSelected[1],time=currentFrame)
     temp=cmd.listAttr(DaParentLocator,keyable=True)[-1]
 
     if not temp==DaGrabber :
         newAttr=cmd.renameAttr(DaParentLocator+'.'+temp,DaGrabber)
         cmd.setKeyframe(DaParentLocator,at=newAttr, value =0,time=previousFrame)
         cmd.setKeyframe(DaParentLocator,at=newAttr, value =1,time=currentFrame)
Example #14
0
def tidy_constraint_node(constraint_node):
    """The custom weight attrs may refer to non-existant nodes, i.e.
    'ani01:hand_ctrlW0' when ani01 has been swapped out with tim01. This
    script matches their name to the name of the current target objects.
    """
    # Hide the transform channels from the channel box
    for ch in ('.tx',
               '.ty',
               '.tz',
               '.rx',
               '.ry',
               '.rz',
               '.sx',
               '.sy',
               '.sz',
               '.v'):
        cmds.setAttr(constraint_node+ch,
                     keyable=False,
                     channelBox=False)
        
    # Parent the node under the the constrained transform.
    object = get_first_constrained_object(constraint_node)
    if object:
        print constraint_node, object
        cmds.parent(constraint_node, object)
    
    # Create new custom weight attributes with the target names, and
    # transfer the connections.
    if not cmds.objExists(constraint_node+'.target'):
        print(' >>> No targets found for constraint {0}'.format(constraint_node))
        return
    indices = cmds.getAttr(constraint_node+'.target', multiIndices=True)
    for i in indices:
        pm_attr = '.target[{0}].targetParentMatrix'.format(str(i))
        target = cmds.listConnections(constraint_node+pm_attr)
        weight_attr = '.target[{0}].targetWeight'.format(str(i))
        weight = cmds.listConnections(constraint_node+weight_attr,
                                      plugs=True)
        if target and weight:
            cmds.setAttr(weight[0], keyable=True)
            attr_name = target[0].split(':')[-1]+'W'+str(i)
            if not cmds.objExists(constraint_node+'.'+attr_name):
                cmds.renameAttr(weight[0], attr_name)
    
    
    
    return
Example #15
0
def addOns():
    """
    """
    #===========================================================================
    # KNEE SNAP
    #===========================================================================
    # reuse arm module's elbowSnap
    pvCtl = 'PoleLeg_R'
    hipGrp = 'IKOffsetHip_R'
    footCtl = 'IKLeg_R'
    footIkH = 'IKXLegHandle_R'
    kneeMdl = 'IKXKnee_R_IKLenght_R'
    ankleMdl = 'IKXAnkle_R_IKLenght_R'
    stretchyRange = 'IKSetRangeStretchLeg_R'
    ar.addElbowSnap(pvCtl, hipGrp, footCtl, footIkH, kneeMdl, ankleMdl,
                    stretchyRange)
    # but rename the attribute
    mc.renameAttr(pvCtl + '.elbowSnap', 'kneeSnap')

    # reuse arm module's elbowSnap
    pvCtl = 'PoleLeg_L'
    hipGrp = 'IKOffsetHip_L'
    footCtl = 'IKLeg_L'
    footIkH = 'IKXLegHandle_L'
    kneeMdl = 'IKXKnee_L_IKLenght_L'
    ankleMdl = 'IKXAnkle_L_IKLenght_L'
    stretchyRange = 'IKSetRangeStretchLeg_L'
    ar.addElbowSnap(pvCtl, hipGrp, footCtl, footIkH, kneeMdl, ankleMdl,
                    stretchyRange)
    # but rename the attribute
    mc.renameAttr(pvCtl + '.elbowSnap', 'kneeSnap')

    #===========================================================================
    # FOOT ROLL
    #===========================================================================
    footCtl = 'IKLeg_R'
    mc.deleteAttr(footCtl, at='roll')
    mc.deleteAttr(footCtl, at='rollAngle')
    addFootRoll(footCtl, 'IKRollLegHeel_R', 'IKRollLegBall_R',
                'IKRollLegToe_R')

    footCtl = 'IKLeg_L'
    mc.deleteAttr(footCtl, at='roll')
    mc.deleteAttr(footCtl, at='rollAngle')
    addFootRoll(footCtl, 'IKRollLegHeel_L', 'IKRollLegBall_L',
                'IKRollLegToe_L')
	def rename(self, attr_name, new_name):
		""" Change the name of a capture.
			TODO: rename snapshot image file also
		"""
		# new_name = self.sender().text()

		if new_name == "":
			mc.warning("Please give the capture a valid name.")
			self.refresh_capture_ui()
			return

		new_attr_name = CAPTURE_ATTR_PREFIX + new_name
		# print(self.root_set+"."+attr_name, new_attr_name)
		try:
			mc.renameAttr(self.root_set+"."+attr_name, new_attr_name)
		except RuntimeError as e:
			mc.warning(str(e))

		self.refresh_capture_ui()
Example #17
0
def addOns():
    """
    """
    #===========================================================================
    # KNEE SNAP
    #===========================================================================
    # reuse arm module's elbowSnap
    pvCtl = 'PoleLeg_R'
    hipGrp = 'IKOffsetHip_R'
    footCtl = 'IKLeg_R'
    footIkH = 'IKXLegHandle_R'
    kneeMdl = 'IKXKnee_R_IKLenght_R'
    ankleMdl = 'IKXAnkle_R_IKLenght_R'
    stretchyRange = 'IKSetRangeStretchLeg_R'
    ar.addElbowSnap(pvCtl, hipGrp, footCtl, footIkH, kneeMdl, ankleMdl, stretchyRange)
    # but rename the attribute
    mc.renameAttr(pvCtl+'.elbowSnap', 'kneeSnap')
    
    # reuse arm module's elbowSnap
    pvCtl = 'PoleLeg_L'
    hipGrp = 'IKOffsetHip_L'
    footCtl = 'IKLeg_L'
    footIkH = 'IKXLegHandle_L'
    kneeMdl = 'IKXKnee_L_IKLenght_L'
    ankleMdl = 'IKXAnkle_L_IKLenght_L'
    stretchyRange = 'IKSetRangeStretchLeg_L'
    ar.addElbowSnap(pvCtl, hipGrp, footCtl, footIkH, kneeMdl, ankleMdl, stretchyRange)
    # but rename the attribute
    mc.renameAttr(pvCtl+'.elbowSnap', 'kneeSnap')
    
    #===========================================================================
    # FOOT ROLL
    #===========================================================================
    footCtl = 'IKLeg_R'
    mc.deleteAttr(footCtl, at='roll')
    mc.deleteAttr(footCtl, at='rollAngle')
    addFootRoll(footCtl, 'IKRollLegHeel_R', 'IKRollLegBall_R', 'IKRollLegToe_R')
    
    footCtl = 'IKLeg_L'
    mc.deleteAttr(footCtl, at='roll')
    mc.deleteAttr(footCtl, at='rollAngle')
    addFootRoll(footCtl, 'IKRollLegHeel_L', 'IKRollLegBall_L', 'IKRollLegToe_L')
def rsChangeDefault(i_s_button):
    l_ChangeAttribute = rsChangeAttribute()
    if l_ChangeAttribute[5]:
        cmds.setAttr(l_ChangeAttribute[3], lock=0)
    f_NewValue = cmds.floatField("rsDefaultField", query=True, value=True)
    cmds.addAttr(longName=(l_ChangeAttribute[2] + "_cons"), niceName=l_ChangeAttribute[4], attributeType=l_ChangeAttribute[0], hasMinValue=l_ChangeAttribute[8], hasMaxValue=l_ChangeAttribute[10], defaultValue=f_NewValue)
    s_NewAt = l_ChangeAttribute[1] + "." + l_ChangeAttribute[2] + "_cons"
    if l_ChangeAttribute[10]:
        cmds.addAttr(s_NewAt, edit=True, maxValue=l_ChangeAttribute[11])
    if l_ChangeAttribute[8]:
        cmds.addAttr(s_NewAt, edit=True, minValue=l_ChangeAttribute[9])
    if l_ChangeAttribute[6]:
        cmds.setAttr(s_NewAt, keyable=True, channelBox=False)
    if not l_ChangeAttribute[6] and l_ChangeAttribute[7]:
        cmds.setAttr(s_NewAt, keyable=False, channelBox=True)
    if not l_ChangeAttribute[6] and not l_ChangeAttribute[7]:
        cmds.setAttr(s_NewAt, keyable=False, channelBox=False)
    l_IncomingConnections = cmds.listConnections(l_ChangeAttribute[3], plugs=True, destination=False, source=True)
    if l_IncomingConnections:
        print "l_IncomingConnections"
        print l_IncomingConnections
        for s_InConn in l_IncomingConnections:
            cmds.connectAttr(s_InConn, s_NewAt, force=True)
    l_OutcomingConnections = cmds.listConnections(l_ChangeAttribute[3], plugs=True, destination=True, source=False)
    if l_OutcomingConnections:
        print "l_OutcomingConnections"
        print l_OutcomingConnections
        for s_OutConn in l_OutcomingConnections:
            cmds.connectAttr(s_NewAt, s_OutConn, force=True)
    cmds.deleteAttr(l_ChangeAttribute[3])
    cmds.renameAttr(s_NewAt, l_ChangeAttribute[2])
    rsReAtt()
    cmds.setAttr(l_ChangeAttribute[3], lock=l_ChangeAttribute[5])
    l_ChannelAtList = rsChannelAtList()
    l_AttrKey = l_ChannelAtList[0]
    l_AttrKeyHidden = l_ChannelAtList[1]
    if l_AttrKey or l_AttrKeyHidden:
        cmds.textScrollList("rsAttributeScroll", edit=True, removeAll=True, append=l_AttrKey)
        cmds.textScrollList("rsAttributeScrollHidden", edit=True, removeAll=True, append=l_AttrKeyHidden)
    rsSearchInScroll(l_ChangeAttribute[2])
    return True
Example #19
0
def tidy_constraint_node(constraint_node):
    """The custom weight attrs may refer to non-existant nodes, i.e.
    'ani01:hand_ctrlW0' when ani01 has been swapped out with tim01. This
    script matches their name to the name of the current target objects.
    """
    # Hide the transform channels from the channel box
    for ch in ('.tx', '.ty', '.tz', '.rx', '.ry', '.rz', '.sx', '.sy', '.sz',
               '.v'):
        cmds.setAttr(constraint_node + ch, keyable=False, channelBox=False)

    # Parent the node under the the constrained transform.
    object = get_first_constrained_object(constraint_node)
    if object:
        print constraint_node, object
        cmds.parent(constraint_node, object)

    # Create new custom weight attributes with the target names, and
    # transfer the connections.
    if not cmds.objExists(constraint_node + '.target'):
        print(
            ' >>> No targets found for constraint {0}'.format(constraint_node))
        return
    indices = cmds.getAttr(constraint_node + '.target', multiIndices=True)
    for i in indices:
        pm_attr = '.target[{0}].targetParentMatrix'.format(str(i))
        target = cmds.listConnections(constraint_node + pm_attr)
        weight_attr = '.target[{0}].targetWeight'.format(str(i))
        weight = cmds.listConnections(constraint_node + weight_attr,
                                      plugs=True)
        if target and weight:
            cmds.setAttr(weight[0], keyable=True)
            attr_name = target[0].split(':')[-1] + 'W' + str(i)
            if not cmds.objExists(constraint_node + '.' + attr_name):
                cmds.renameAttr(weight[0], attr_name)

    return
	def switchBuild(self):
		"""Method to loop through controls in the self.ctrlList, duplicate them and their groups and then create a Global/Local Switch"""
		cmds.undoInfo(openChunk=True)		
		self.checkSwitchCtrlAtt()	
		#Setup plusMinusAverage Reversing Node
		pMAName = nameSwitchRebuild(self.switchCtrl, "cv", "pma", nameEnd = self.switchCtrlAtt + "Switch")
		#Check to see if a plusMinusAverage Node already exists
		testForSwitch = checkForPlusMinusAverage(self.switchCtrl, self.switchCtrlAtt)
		# print "MC",self.switchCtrl, 
		# print "MCA",self.switchCtrlAtt
		# print "testForSwitch",testForSwitch
		if testForSwitch != None: 
			self.pmaSwitchNode = testForSwitch
			cmds.warning("Switch PlusMinusAverage Node has been found for this attribute - Connecting to this node.")
		else:
			#PlusMinusAverage node only needs to be created and connected if it does not already exist! 
			myRigPm = cmds.shadingNode('plusMinusAverage', asUtility=True, name= pMAName)
			self.pmaSwitchNode = myRigPm
			cmds.setAttr(self.pmaSwitchNode + ".operation", 2)
			cmds.setAttr(self.pmaSwitchNode + ".input1D[0]", 1)
			# print "MasterStuff :",self.switchCtrl,self.switchCtrlAtt
			cmds.connectAttr(self.switchCtrl + "." + self.switchCtrlAtt, self.pmaSwitchNode + ".input1D[1]")

		#Now we need to duplicate the control twice. Rename the orginal to a "Ghost Control" and label up the others as local and global Controls, first of all find the Control Group
		currentCtrlGroup = cmds.listRelatives(self.ctrlList[0], parent = True)
		newGlobalCtrlPack = (cmds.duplicate(currentCtrlGroup, renameChildren=True))
		stripConstraintsFromGroup(newGlobalCtrlPack)  #Delete out any constraint Nodes in there
		newGlobalGrpName = ctrlRename(newGlobalCtrlPack[0], "GlobalCtrl")
		newGlobalCtrlName = ctrlRename(newGlobalCtrlPack[1], "GlobalCtrl")
		newGlobalGrpName = cmds.rename(newGlobalCtrlPack[0], newGlobalGrpName)
		newGlobalCtrlName  =cmds.rename(newGlobalCtrlPack[1], newGlobalCtrlName)
		shapeRecolour(newGlobalCtrlName, 13) # Colour Global Control Red

		newLocalCtrlPack = cmds.duplicate(currentCtrlGroup, renameChildren=True)
		stripConstraintsFromGroup(newLocalCtrlPack)  #Delete out any constraint Nodes in there
		newLocalGrpName = ctrlRename(newLocalCtrlPack[0], "LocalCtrl")
		newLocalCtrlName = ctrlRename(newLocalCtrlPack[1], "LocalCtrl")
		newLocalGrpName = cmds.rename(newLocalCtrlPack[0], newLocalGrpName)
		newLocalCtrlName = cmds.rename(newLocalCtrlPack[1], newLocalCtrlName)
		shapeRecolour(newLocalCtrlName, 17) # Colour Local Control Yellow

		#Rename the original Controls to be Ghosts
		currentGroupGhostName = ctrlRename(currentCtrlGroup[0], "Ghost")
		currentCtrlGhostName = ctrlRename(self.ctrlList[0], "Ghost")
		currentGroupGhostName = cmds.rename(currentCtrlGroup, currentGroupGhostName) #reassigning variable to insure unique Name
		currentCtrlGhostName =cmds.rename(self.ctrlList[0], currentCtrlGhostName)
		shapeRecolour(currentCtrlGhostName, 2) #2 is dark grey

		#Now connect up the visibility of the new controls
		cmds.connectAttr(self.pmaSwitchNode + ".output1D", newLocalCtrlName + ".visibility")
		cmds.connectAttr(self.switchCtrl + "." + self.switchCtrlAtt, newGlobalCtrlName + ".visibility")

		#Now we need to add the parent constraint, and sort out all aspects like naming etc. 
		parConstName = nameSwitchRebuild(self.switchCtrl, "cv", "parC", nameEnd = self.switchCtrlAtt + "Switch")
		parConst = (cmds.parentConstraint(newLocalCtrlName, newGlobalCtrlName, currentCtrlGhostName, name = parConstName))[0]
		# print "parConst", parConst 
		weightAtts = cmds.parentConstraint(parConst, q=1, weightAliasList = True)
		# print "weightAtts", weightAtts
		for i, att in enumerate(weightAtts):
			if i == 0: #Set first Local Weight
				print "moo"
				cmds.renameAttr(parConst + "." + att , "localWeight")
			elif i == 1: #Set Second Global Weight
				print "bob"
				cmds.renameAttr(parConst + "." + att , "globalWeight")
			#Now we make the correct connections to control the weights
		cmds.connectAttr(self.switchCtrl + "." + self.switchCtrlAtt, parConst + ".globalWeight")
		cmds.connectAttr(self.pmaSwitchNode + ".output1D", parConst + ".localWeight")
Example #21
0
        def followMechanismInterms(side, intPosition):

            import maya.cmds as mc

            attributeCtrl = ("%s_%s_sleeve_attr_ctrl" % (side, intPosition))

            mc.setAttr("%s.rx" % attributeCtrl, l=True, k=False, cb=False)
            mc.setAttr("%s.ry" % attributeCtrl, l=True, k=False, cb=False)
            mc.setAttr("%s.rz" % attributeCtrl, l=True, k=False, cb=False)
            mc.setAttr("%s.sx" % attributeCtrl, l=True, k=False, cb=False)
            mc.setAttr("%s.sy" % attributeCtrl, l=True, k=False, cb=False)
            mc.setAttr("%s.sz" % attributeCtrl, l=True, k=False, cb=False)

            chauffeur = ("%s_%s_sleeve_01_interm_02_ctrl" %
                         (side, intPosition))

            passengers = [
                "%s_%s_sleeve_02_interm_02_ctrl" % (side, intPosition),
                "%s_%s_sleeve_03_interm_02_ctrl" % (side, intPosition),
                "%s_%s_sleeve_04_interm_02_ctrl" % (side, intPosition),
                "%s_%s_sleeve_05_interm_02_ctrl" % (side, intPosition)
            ]

            controller = mc.addAttr(attributeCtrl,
                                    at="float",
                                    sn="%s_fp" % chauffeur,
                                    ln="%s_followPercentage" % chauffeur,
                                    max=1.0,
                                    min=0.0,
                                    dv=1.0,
                                    k=True,
                                    h=False)
            # create nodes that control the translation, rotation, and scale of the follow:
            deformations = ["t", "r", "s"]
            for deformation in deformations:
                switches = mc.createNode("multiplyDivide",
                                         n="%s_%s_follow_perCent_md" %
                                         (chauffeur, deformation))
                mc.connectAttr("%s.%s" % (chauffeur, deformation),
                               "%s.input1" % switches)
                mc.connectAttr("%s.%s_fp" % (attributeCtrl, chauffeur),
                               "%s.input2X" % switches)
                mc.connectAttr("%s.%s_fp" % (attributeCtrl, chauffeur),
                               "%s.input2Y" % switches)
                mc.connectAttr("%s.%s_fp" % (attributeCtrl, chauffeur),
                               "%s.input2Z" % switches)

            # create a plusMinus for scale correction for later use
            pmaSubstract = mc.createNode("plusMinusAverage",
                                         n="%s_scale_substract_pma" %
                                         chauffeur)
            mc.setAttr("%s.op" % pmaSubstract, 2)
            mc.setAttr("%s.i3[0]" % pmaSubstract, 0, 0, 0)
            mc.setAttr("%s.i3[1]" % pmaSubstract, 1, 1, 1)
            mc.connectAttr("%s.s" % chauffeur,
                           "%s.i3[0]" % pmaSubstract,
                           f=True)

            for passenger in passengers:
                targets = mc.listRelatives(passenger, p=True)
                grandDad = mc.listRelatives(targets, p=True)
                for target in targets:
                    # create attribute on the slave controls that changes their follow fall off
                    mc.addAttr(attributeCtrl,
                               at="float",
                               sn="%s_fa" % passenger,
                               ln="%s_followAmount" % passenger,
                               max=1.0,
                               min=0.0,
                               dv=1.0,
                               k=True,
                               h=False)
                # create a group on top of the ORIG of each slave control meant to follow the driver control
                phonyFollowGRP = [
                    mc.group(em=True, n="%s_phoney_follow_group" % passenger)
                ]
                mc.parent(phonyFollowGRP, grandDad, a=True)
                tempConst = mc.parentConstraint(targets,
                                                phonyFollowGRP,
                                                n="tempCnst")
                mc.delete(tempConst)
                if "R_" in "%s" % phonyFollowGRP:
                    mc.scale(-1, 1, 1, phonyFollowGRP)
                followGRP = mc.group(em=True, n="%s_follow_group" % passenger)
                mc.parent(followGRP, phonyFollowGRP, r=True)
                mc.parent(target, followGRP)
                # connect everything
                for deformation2 in deformations:
                    followAmountNode = mc.createNode(
                        "multiplyDivide",
                        n="%s_%s_followAmount_md" % (passenger, deformation2))
                    mc.setAttr("%s.input2" % followAmountNode, 1, 1, 1)
                    mc.connectAttr("%s.%s_fa" % (attributeCtrl, passenger),
                                   "%s.input1X" % followAmountNode)
                    mc.connectAttr("%s.%s_fa" % (attributeCtrl, passenger),
                                   "%s.input1Y" % followAmountNode)
                    mc.connectAttr("%s.%s_fa" % (attributeCtrl, passenger),
                                   "%s.input1Z" % followAmountNode)
                    mc.connectAttr(
                        "%s_%s_follow_perCent_md.output" %
                        (chauffeur, deformation2),
                        "%s.input2" % followAmountNode)
                    mc.connectAttr("%s.output" % followAmountNode,
                                   followGRP + ".%s" % deformation2)
                    # redefine the connections for the scale attribute
                    if deformation2 == "s":
                        pmaSubstract = mc.createNode(
                            "plusMinusAverage",
                            n="%s_scale_substract_pma" % passenger)
                        mc.setAttr("%s.op" % pmaSubstract, 2)
                        mc.setAttr("%s.i3[0]" % pmaSubstract, 0, 0, 0)
                        mc.setAttr("%s.i3[1]" % pmaSubstract, 1, 1, 1)
                        mc.connectAttr("%s.s" % chauffeur,
                                       "%s.i3[0]" % pmaSubstract,
                                       f=True)
                        followScale = mc.createNode("multiplyDivide",
                                                    n="%s_s_followScale_md" %
                                                    passenger)
                        mc.connectAttr("%s.o3" % pmaSubstract,
                                       "%s.i1" % followScale,
                                       f=True)
                        mc.connectAttr("%s.o" % followAmountNode,
                                       "%s.i2" % followScale,
                                       f=True)
                        pmaAdd = mc.createNode("plusMinusAverage",
                                               n="%s_scale_correct_pma" %
                                               passenger)
                        mc.setAttr("%s.i3[0]" % pmaAdd, 1, 1, 1)
                        mc.setAttr("%s.i3[1]" % pmaAdd, 0, 0, 0)
                        mc.connectAttr("%s.o" % followScale,
                                       "%s.i3[1]" % pmaAdd,
                                       f=True)
                        mc.connectAttr("%s.o3" % pmaAdd,
                                       "%s.s" % followGRP,
                                       f=True)
            mc.disconnectAttr("%s.s" % chauffeur,
                              "%s_s_follow_perCent_md.i1" % chauffeur)
            mc.setAttr("%s_s_follow_perCent_md.i1" % chauffeur, 1, 1, 1)

            # set initial values for follow fall-off
            mc.setAttr(
                "%s.%s_%s_sleeve_02_interm_02_ctrl_fa" %
                (attributeCtrl, side, intPosition), 0.6)
            mc.setAttr(
                "%s.%s_%s_sleeve_03_interm_02_ctrl_fa" %
                (attributeCtrl, side, intPosition), 0.3)
            mc.setAttr(
                "%s.%s_%s_sleeve_04_interm_02_ctrl_fa" %
                (attributeCtrl, side, intPosition), 0.05)

            # rename sleeve 6 attribute to "shirt"
            if passenger == "%s_%s_sleeve_05_interm_02_ctrl" % (side,
                                                                intPosition):
                mc.renameAttr(
                    "%s.%s_%s_sleeve_05_interm_02_ctrl_followAmount" %
                    (attributeCtrl, side, intPosition),
                    "%s_%s_shirt_interm_followAmount" % (side, intPosition))
Example #22
0
    def switchBuild(self):
        """Method to loop through controls in the self.ctrlList, duplicate them and their groups and then create a Global/Local Switch"""
        cmds.undoInfo(openChunk=True)
        self.checkSwitchCtrlAtt()
        #Setup plusMinusAverage Reversing Node
        pMAName = nameSwitchRebuild(self.switchCtrl,
                                    "cv",
                                    "pma",
                                    nameEnd=self.switchCtrlAtt + "Switch")
        #Check to see if a plusMinusAverage Node already exists
        testForSwitch = checkForPlusMinusAverage(self.switchCtrl,
                                                 self.switchCtrlAtt)
        # print "MC",self.switchCtrl,
        # print "MCA",self.switchCtrlAtt
        # print "testForSwitch",testForSwitch
        if testForSwitch != None:
            self.pmaSwitchNode = testForSwitch
            cmds.warning(
                "Switch PlusMinusAverage Node has been found for this attribute - Connecting to this node."
            )
        else:
            #PlusMinusAverage node only needs to be created and connected if it does not already exist!
            myRigPm = cmds.shadingNode('plusMinusAverage',
                                       asUtility=True,
                                       name=pMAName)
            self.pmaSwitchNode = myRigPm
            cmds.setAttr(self.pmaSwitchNode + ".operation", 2)
            cmds.setAttr(self.pmaSwitchNode + ".input1D[0]", 1)
            # print "MasterStuff :",self.switchCtrl,self.switchCtrlAtt
            cmds.connectAttr(self.switchCtrl + "." + self.switchCtrlAtt,
                             self.pmaSwitchNode + ".input1D[1]")

        #Now we need to duplicate the control twice. Rename the orginal to a "Ghost Control" and label up the others as local and global Controls, first of all find the Control Group
        currentCtrlGroup = cmds.listRelatives(self.ctrlList[0], parent=True)
        newGlobalCtrlPack = (cmds.duplicate(currentCtrlGroup,
                                            renameChildren=True))
        stripConstraintsFromGroup(
            newGlobalCtrlPack)  #Delete out any constraint Nodes in there
        newGlobalGrpName = ctrlRename(newGlobalCtrlPack[0], "GlobalCtrl")
        newGlobalCtrlName = ctrlRename(newGlobalCtrlPack[1], "GlobalCtrl")
        newGlobalGrpName = cmds.rename(newGlobalCtrlPack[0], newGlobalGrpName)
        newGlobalCtrlName = cmds.rename(newGlobalCtrlPack[1],
                                        newGlobalCtrlName)
        shapeRecolour(newGlobalCtrlName, 13)  # Colour Global Control Red

        newLocalCtrlPack = cmds.duplicate(currentCtrlGroup,
                                          renameChildren=True)
        stripConstraintsFromGroup(
            newLocalCtrlPack)  #Delete out any constraint Nodes in there
        newLocalGrpName = ctrlRename(newLocalCtrlPack[0], "LocalCtrl")
        newLocalCtrlName = ctrlRename(newLocalCtrlPack[1], "LocalCtrl")
        newLocalGrpName = cmds.rename(newLocalCtrlPack[0], newLocalGrpName)
        newLocalCtrlName = cmds.rename(newLocalCtrlPack[1], newLocalCtrlName)
        shapeRecolour(newLocalCtrlName, 17)  # Colour Local Control Yellow

        #Rename the original Controls to be Ghosts
        currentGroupGhostName = ctrlRename(currentCtrlGroup[0], "Ghost")
        currentCtrlGhostName = ctrlRename(self.ctrlList[0], "Ghost")
        currentGroupGhostName = cmds.rename(
            currentCtrlGroup,
            currentGroupGhostName)  #reassigning variable to insure unique Name
        currentCtrlGhostName = cmds.rename(self.ctrlList[0],
                                           currentCtrlGhostName)
        shapeRecolour(currentCtrlGhostName, 2)  #2 is dark grey

        #Now connect up the visibility of the new controls
        cmds.connectAttr(self.pmaSwitchNode + ".output1D",
                         newLocalCtrlName + ".visibility")
        cmds.connectAttr(self.switchCtrl + "." + self.switchCtrlAtt,
                         newGlobalCtrlName + ".visibility")

        #Now we need to add the parent constraint, and sort out all aspects like naming etc.
        parConstName = nameSwitchRebuild(self.switchCtrl,
                                         "cv",
                                         "parC",
                                         nameEnd=self.switchCtrlAtt + "Switch")
        parConst = (cmds.parentConstraint(newLocalCtrlName,
                                          newGlobalCtrlName,
                                          currentCtrlGhostName,
                                          name=parConstName))[0]
        # print "parConst", parConst
        weightAtts = cmds.parentConstraint(parConst, q=1, weightAliasList=True)
        # print "weightAtts", weightAtts
        for i, att in enumerate(weightAtts):
            if i == 0:  #Set first Local Weight
                print "moo"
                cmds.renameAttr(parConst + "." + att, "localWeight")
            elif i == 1:  #Set Second Global Weight
                print "bob"
                cmds.renameAttr(parConst + "." + att, "globalWeight")
            #Now we make the correct connections to control the weights
        cmds.connectAttr(self.switchCtrl + "." + self.switchCtrlAtt,
                         parConst + ".globalWeight")
        cmds.connectAttr(self.pmaSwitchNode + ".output1D",
                         parConst + ".localWeight")
Example #23
0
def reorder(attr,pos='bottom'):
	'''
	Reorder specified user defined attribute
	@param attr: Attribute to reorder
	@type attr: str
	@param pos: Reorder position. Valid position values - "up", "down", "top" and "bottom".
	@type pos: str
	'''
	# Checks
	if not mc.objExists(attr):
		raise Exception('Attribute "'+attr+'" does not exist!')
	
	if not attr.count('.'):
		raise Exception('Unable to determine object from attribute"'+attr+'"!')
	
	# Get attribute info
	obj = mc.ls(attr,o=True)
	if not obj: raise Exception('Unable to determine object from attribute"'+attr+'"!')
	obj = obj[0]
	at = attr.replace(obj+'.','')
	
	# Get attribute lists
	udAttrList = mc.listAttr(obj,ud=True)
	keyAttrList = mc.listAttr(obj,k=True)
	cbAttrList = mc.listAttr(obj,cb=True)
	allAttrList = [i for i in udAttrList if keyAttrList.count(i) or cbAttrList.count(i)]
	allAttrLen = len(allAttrList)
	
	# Get relative attribute index 
	attrInd = allAttrList.index(at)
	
	# Move UP
	if pos == 'up':
		
		if not attrInd: return	
		mc.renameAttr(obj+'.'+allAttrList[attrInd-1],allAttrList[attrInd-1]+'XXX')
		mc.renameAttr(obj+'.'+allAttrList[attrInd-1]+'XXX',allAttrList[attrInd-1])
		for i in allAttrList[attrInd+1:]:
			mc.renameAttr(obj+'.'+i,i+'XXX')
			mc.renameAttr(obj+'.'+i+'XXX',i)
		
	# Move DOWN
	if pos == 'down':
		
		if attrInd == (allAttrLen-1): return
		mc.renameAttr(obj+'.'+allAttrList[attrInd],allAttrList[attrInd]+'XXX')
		mc.renameAttr(obj+'.'+allAttrList[attrInd]+'XXX',allAttrList[attrInd])
		
		if attrInd >= (allAttrLen-1): return
		
		for i in allAttrList[attrInd+2:]:
			mc.renameAttr(obj+'.'+i,i+'XXX')
			mc.renameAttr(obj+'.'+i+'XXX',i)
		
	# Move to TOP
	if pos == 'top':
		
		for i in range(len(allAttrList)):
			if i == attrInd: return
			mc.renameAttr(obj+'.'+allAttrList[i],allAttrList[i]+'XXX')
			mc.renameAttr(obj+'.'+allAttrList[i]+'XXX',allAttrList[i])
	
	# Move to BOTTOM
	if pos == 'bottom':
		
		mc.renameAttr(obj+'.'+allAttrList[attrInd],allAttrList[attrInd]+'XXX')
		mc.renameAttr(obj+'.'+allAttrList[attrInd]+'XXX',allAttrList[attrInd])
	
	# Refresh UI
	channelBox = 'MayaWindow|mayaMainWindowForm|formLayout3|formLayout11|formLayout32|formLayout33|ChannelsLayersPaneLayout|formLayout36|menuBarLayout1|frameLayout1|mainChannelBox'
	mc.channelBox(channelBox,e=True,update=True)
Example #24
0
 def name(self, value):
     mc.renameAttr(self.name, value)
Example #25
0
def reorderAttrFromUI(dir):
	'''
	Reorder attributes based on info from the control UI
	@param dir: Direction to move attribute in current oreder
	@type dir: int
	'''
	# Get UI info
	obj = mc.textFieldButtonGrp('reorderAttrTFB',q=True,text=True)
	attrList = mc.textScrollList('reorderAttrTSL',q=True,si=True)
	
	# Check object
	if not mc.objExists(obj):
		raise Exception('Object "'+obj+'" does not exist!')
	
	# Check attributes
	for attr in attrList:
		if not mc.objExists(obj+'.'+attr):
			raise Exception('Attribute "'+obj+'.'+attr+'" does not exist!')
	
	# Get attr list
	udAttrList = mc.listAttr(obj,ud=True)
	keyAttrList = mc.listAttr(obj,k=True)
	cbAttrList = mc.listAttr(obj,cb=True)
	allAttrList = [i for i in udAttrList if keyAttrList.count(i) or cbAttrList.count(i)]
	allAttrLen = len(allAttrList)
	
	# Reorder Attributes
	for attr in attrList:
		
		# Get relative attribute index 
		attrInd = allAttrList.index(attr)
		
		if dir == 0: # Move Up
			
			print 'move up'
			
			if not attrInd: continue
				
			mc.renameAttr(obj+'.'+allAttrList[attrInd-1],allAttrList[attrInd-1]+'XXX')
			mc.renameAttr(obj+'.'+allAttrList[attrInd-1]+'XXX',allAttrList[attrInd-1])
			
			for i in allAttrList[attrInd+1:]:
				mc.renameAttr(obj+'.'+i,i+'XXX')
				mc.renameAttr(obj+'.'+i+'XXX',i)
			
		if dir == 1: # Move Down
			
			print 'move down'
			
			if attrInd == (allAttrLen-1): continue
			
			mc.renameAttr(obj+'.'+allAttrList[attrInd],allAttrList[attrInd]+'XXX')
			mc.renameAttr(obj+'.'+allAttrList[attrInd]+'XXX',allAttrList[attrInd])
			
			if attrInd >= (allAttrLen-1): continue
			
			for i in allAttrList[attrInd+2:]:
				mc.renameAttr(obj+'.'+i,i+'XXX')
				mc.renameAttr(obj+'.'+i+'XXX',i)
			
		
		if dir == 2: # Move to Top
			
			print 'move to top'
			
			for i in range(len(allAttrList)):
				if i == attrInd: continue
				mc.renameAttr(obj+'.'+allAttrList[i],allAttrList[i]+'XXX')
				mc.renameAttr(obj+'.'+allAttrList[i]+'XXX',allAttrList[i])
		
		if dir == 3: # Move to Bottom
			
			print 'move to bottom'
			
			mc.renameAttr(obj+'.'+allAttrList[attrInd],allAttrList[attrInd]+'XXX')
			mc.renameAttr(obj+'.'+allAttrList[attrInd]+'XXX',allAttrList[attrInd])
	
	# Refresh attribute list
	reorderAttrRefreshList(attrList)
	
	# Refresh UI
	channelBox = 'MayaWindow|mayaMainWindowForm|formLayout3|formLayout11|formLayout32|formLayout33|ChannelsLayersPaneLayout|formLayout36|menuBarLayout1|frameLayout1|mainChannelBox'
	mc.channelBox(channelBox,e=True,update=True)
    def mirrorRigPart(self, *args):
        """
        Collect the contents of the asset selection
        and find all the hierarchy and connection
        relationships.
        """
        asset_info = {}
        if len(cmds.ls(sl=True)) == 0:
            return
        sel = cmds.ls(sl=True)[0]
        if cmds.nodeType(sel) != 'dagContainer':
            return
        assetcontents = cmds.container(sel, q=True, nl=True)

        # Find the Main_GRP
        for a in assetcontents:
            if 'Main_GRP' in a:
                maingrp = a

        # Duplicate the Main_GRP
        nodedupe = cmds.duplicate(maingrp, ic=True, rc=True, un=True)

        dupmajor = []
        namereplace = []
        attrconnect = []

        for node in nodedupe:
            if node.endswith('1') == True:
                nn = node.replace('L_', 'R_')[:-1]
            else:
                nn = node.replace('L_', 'R_')
            namereplace.append([node, nn])

            if '_Major_CTRL' in node:
                if cmds.nodeType(node) == 'transform':
                    if cmds.objExists(nn) == True:
                        attrs = cmds.listAttr(node, ud=True)
                        for a in attrs:
                            acons = cmds.listConnections(node + '.' + a,
                                                         d=True,
                                                         p=True)
                            if acons != None:
                                acon = acons[0].replace('_L_', '_R_')
                                attrconnect.append([nn[0] + '.' + a, acon])
                                try:
                                    cmds.connectAttr(nn + '.' + a, acons[0])
                                except:
                                    print(nn + '.' + a, acons[0])

                                try:
                                    cmds.connectAttr(nn + '.' + a, acon)
                                except:
                                    print(nn + '.' + a, acon)

                        cmds.delete(node)
                    else:
                        attrs = cmds.listAttr(node, ud=True)
                        for a in attrs:
                            attrname = a.replace('L_', 'R_', 1)
                            cmds.renameAttr(node + '.' + a, attrname)

                        dupmajor.append(nn)

            if cmds.objExists(node) == True:
                cmds.rename(node, nn)

        mirmaingrp = maingrp.replace('L_', 'R_')
        if cmds.objExists(mirmaingrp) == True:
            cmds.container(sel, edit=True, ish=True, it=True, rn=mirmaingrp)
            cmds.setAttr(mirmaingrp + '.sx', -1)
        else:
            print mirmaingrp

        if dupmajor != []:
            for d in dupmajor:
                if cmds.objExists(d) == True:
                    rot = cmds.xform(d, q=True, ws=True, ro=True)
                    pos = cmds.xform(d, q=True, ws=True, t=True)
                    grp = cmds.group(n=nn + '_GRP', em=True)
                    cmds.xform(grp, ws=True, ro=rot)
                    cmds.xform(grp, ws=True, t=pos)

                    mrot = [rot[0], -rot[1], rot[2]]
                    mpos = [-pos[0], pos[1], pos[2]]

                    nn = d.replace('L_', 'R_')

                    cmds.parent(nn, grp)
                    cmds.xform(grp, ws=True, ro=mrot)
                    cmds.xform(grp, ws=True, t=mpos)
                    cmds.setAttr(grp + '.sx', -1)
Example #27
0
def reorderAttrFromUI(dir):
    '''
	Reorder attributes based on info from the control UI
	@param dir: Direction to move attribute in current oreder
	@type dir: int
	'''
    # Get UI info
    obj = mc.textFieldButtonGrp('reorderAttrTFB', q=True, text=True)
    attrList = mc.textScrollList('reorderAttrTSL', q=True, si=True)

    # Check object
    if not mc.objExists(obj):
        raise Exception('Object "' + obj + '" does not exist!')

    # Check attributes
    for attr in attrList:
        if not mc.objExists(obj + '.' + attr):
            raise Exception('Attribute "' + obj + '.' + attr +
                            '" does not exist!')

    # Get attr list
    udAttrList = mc.listAttr(obj, ud=True)
    keyAttrList = mc.listAttr(obj, k=True)
    cbAttrList = mc.listAttr(obj, cb=True)
    allAttrList = [
        i for i in udAttrList if keyAttrList.count(i) or cbAttrList.count(i)
    ]
    allAttrLen = len(allAttrList)

    # Reorder Attributes
    for attr in attrList:

        # Get relative attribute index
        attrInd = allAttrList.index(attr)

        if dir == 0:  # Move Up

            print 'move up'

            if not attrInd: continue

            mc.renameAttr(obj + '.' + allAttrList[attrInd - 1],
                          allAttrList[attrInd - 1] + 'XXX')
            mc.renameAttr(obj + '.' + allAttrList[attrInd - 1] + 'XXX',
                          allAttrList[attrInd - 1])

            for i in allAttrList[attrInd + 1:]:
                mc.renameAttr(obj + '.' + i, i + 'XXX')
                mc.renameAttr(obj + '.' + i + 'XXX', i)

        if dir == 1:  # Move Down

            print 'move down'

            if attrInd == (allAttrLen - 1): continue

            mc.renameAttr(obj + '.' + allAttrList[attrInd],
                          allAttrList[attrInd] + 'XXX')
            mc.renameAttr(obj + '.' + allAttrList[attrInd] + 'XXX',
                          allAttrList[attrInd])

            if attrInd >= (allAttrLen - 1): continue

            for i in allAttrList[attrInd + 2:]:
                mc.renameAttr(obj + '.' + i, i + 'XXX')
                mc.renameAttr(obj + '.' + i + 'XXX', i)

        if dir == 2:  # Move to Top

            print 'move to top'

            for i in range(len(allAttrList)):
                if i == attrInd: continue
                mc.renameAttr(obj + '.' + allAttrList[i],
                              allAttrList[i] + 'XXX')
                mc.renameAttr(obj + '.' + allAttrList[i] + 'XXX',
                              allAttrList[i])

        if dir == 3:  # Move to Bottom

            print 'move to bottom'

            mc.renameAttr(obj + '.' + allAttrList[attrInd],
                          allAttrList[attrInd] + 'XXX')
            mc.renameAttr(obj + '.' + allAttrList[attrInd] + 'XXX',
                          allAttrList[attrInd])

    # Refresh attribute list
    reorderAttrRefreshList(attrList)

    # Refresh UI
    channelBox = 'MayaWindow|mayaMainWindowForm|formLayout3|formLayout11|formLayout32|formLayout33|ChannelsLayersPaneLayout|formLayout36|menuBarLayout1|frameLayout1|mainChannelBox'
    mc.channelBox(channelBox, e=True, update=True)
Example #28
0
def reorder(attr, pos='bottom'):
    '''
	Reorder specified user defined attribute
	@param attr: Attribute to reorder
	@type attr: str
	@param pos: Reorder position. Valid position values - "up", "down", "top" and "bottom".
	@type pos: str
	'''
    # Checks
    if not mc.objExists(attr):
        raise Exception('Attribute "' + attr + '" does not exist!')

    if not attr.count('.'):
        raise Exception('Unable to determine object from attribute"' + attr +
                        '"!')

    # Get attribute info
    obj = mc.ls(attr, o=True)
    if not obj:
        raise Exception('Unable to determine object from attribute"' + attr +
                        '"!')
    obj = obj[0]
    at = attr.replace(obj + '.', '')

    # Get attribute lists
    udAttrList = mc.listAttr(obj, ud=True)
    keyAttrList = mc.listAttr(obj, k=True)
    cbAttrList = mc.listAttr(obj, cb=True)
    allAttrList = [
        i for i in udAttrList if keyAttrList.count(i) or cbAttrList.count(i)
    ]
    allAttrLen = len(allAttrList)

    # Get relative attribute index
    attrInd = allAttrList.index(at)

    # Move UP
    if pos == 'up':

        if not attrInd: return
        mc.renameAttr(obj + '.' + allAttrList[attrInd - 1],
                      allAttrList[attrInd - 1] + 'XXX')
        mc.renameAttr(obj + '.' + allAttrList[attrInd - 1] + 'XXX',
                      allAttrList[attrInd - 1])
        for i in allAttrList[attrInd + 1:]:
            mc.renameAttr(obj + '.' + i, i + 'XXX')
            mc.renameAttr(obj + '.' + i + 'XXX', i)

    # Move DOWN
    if pos == 'down':

        if attrInd == (allAttrLen - 1): return
        mc.renameAttr(obj + '.' + allAttrList[attrInd],
                      allAttrList[attrInd] + 'XXX')
        mc.renameAttr(obj + '.' + allAttrList[attrInd] + 'XXX',
                      allAttrList[attrInd])

        if attrInd >= (allAttrLen - 1): return

        for i in allAttrList[attrInd + 2:]:
            mc.renameAttr(obj + '.' + i, i + 'XXX')
            mc.renameAttr(obj + '.' + i + 'XXX', i)

    # Move to TOP
    if pos == 'top':

        for i in range(len(allAttrList)):
            if i == attrInd: return
            mc.renameAttr(obj + '.' + allAttrList[i], allAttrList[i] + 'XXX')
            mc.renameAttr(obj + '.' + allAttrList[i] + 'XXX', allAttrList[i])

    # Move to BOTTOM
    if pos == 'bottom':

        mc.renameAttr(obj + '.' + allAttrList[attrInd],
                      allAttrList[attrInd] + 'XXX')
        mc.renameAttr(obj + '.' + allAttrList[attrInd] + 'XXX',
                      allAttrList[attrInd])

    # Refresh UI
    channelBox = 'MayaWindow|mayaMainWindowForm|formLayout3|formLayout11|formLayout32|formLayout33|ChannelsLayersPaneLayout|formLayout36|menuBarLayout1|frameLayout1|mainChannelBox'
    mc.channelBox(channelBox, e=True, update=True)