예제 #1
0
def joinCurves(targetObjects, mode='simple', curveDegree=1):
    try:
        ml_targetObjects = cgmMeta.validateObjListArg(targetObjects)
        d_objInfo = {}
        for i_obj in ml_targetObjects:
            d_buffer = {}
            if i_obj.getMayaType() != 'nurbsCurve':
                raise StandardError, "joinCurve>> %s is not a 'nurbsCurve'. Type: %s" % (
                    i_obj.getShortName(), i_obj.getMayaType())
            l_components = i_obj.getComponents('ep')
            l_componentIndices = []
            for c in l_components:
                l_componentIndices.append(int(c.split('[')[-1].split(']')[0]))
            d_buffer['indices'] = l_componentIndices
            d_buffer['components'] = l_components
            d_buffer['indexMid'] = int(len(l_componentIndices) / 2)
            d_buffer['midComponent'] = l_components[d_buffer['indexMid']]
            d_objInfo[i_obj] = d_buffer

        #components
        l_created = []
        l_toDo = []
        l_nestedPos = []
        if mode == 'simple':
            for ep in [0, 'mid', -1]:
                l_pos = []
                for i_crv in ml_targetObjects:
                    if ep == 'mid': ep = d_objInfo[i_crv]['indexMid']
                    l_pos.append(
                        cgmMeta.cgmNode(
                            d_objInfo[i_crv]['components'][ep]).getPosition())
                l_created.append(mc.curve(d=curveDegree, ep=l_pos,
                                          os=True))  #Make the curve
        elif mode == 'quartered':
            d_pntsConnect = {}
            for mObj in ml_targetObjects:
                l_pos = crvUtils.returnSplitCurveList(mObj.mNode, 5)
                for i, p in enumerate(l_pos):
                    if not d_pntsConnect.get(i): d_pntsConnect[i] = []
                    d_pntsConnect[i].append(p)
            for k in d_pntsConnect.keys():
                l_created.append(
                    mc.curve(d=curveDegree, ep=d_pntsConnect[k],
                             os=True))  #Make the curve
        else:
            for idx in d_objInfo[d_objInfo.keys()[0]]['indices']:
                l_pos = []
                for i_crv in ml_targetObjects:
                    l_pos.append(
                        cgmMeta.cgmNode(
                            d_objInfo[i_crv]['components'][idx]).getPosition())
                l_created.append(mc.curve(d=curveDegree, ep=l_pos,
                                          os=True))  #Make the curve
        return l_created

    except StandardError, error:
        raise StandardError, "joinCurve>> Failure. targets: %s | error: %s" % (
            targetObjects, error)
예제 #2
0
def joinCurves(targetObjects, mode = 'simple', curveDegree = 1):
    try:
	ml_targetObjects = cgmMeta.validateObjListArg(targetObjects)
	d_objInfo = {}
	for i_obj in ml_targetObjects:
	    d_buffer = {}
	    if i_obj.getMayaType() != 'nurbsCurve':
		raise StandardError,"joinCurve>> %s is not a 'nurbsCurve'. Type: %s"%(i_obj.getShortName(),i_obj.getMayaType())
	    l_components = i_obj.getComponents('ep')
	    l_componentIndices = []
	    for c in l_components:
		l_componentIndices.append( int(c.split('[')[-1].split(']')[0]) )	
	    d_buffer['indices'] = l_componentIndices
	    d_buffer['components'] = l_components	
	    d_buffer['indexMid'] = int(len(l_componentIndices)/2)
	    d_buffer['midComponent'] = l_components[ d_buffer['indexMid'] ]
	    d_objInfo[i_obj] = d_buffer
	    
	
	#components
	l_created = []
	l_toDo = []
	l_nestedPos = []
	if mode == 'simple':
	    for ep in [0,'mid',-1]:
		l_pos = []
		for i_crv in ml_targetObjects:
		    if ep == 'mid':ep = d_objInfo[i_crv]['indexMid']
		    l_pos.append( cgmMeta.cgmNode(d_objInfo[i_crv]['components'][ep]).getPosition() )
		l_created.append( mc.curve(d=curveDegree,ep=l_pos,os =True) )#Make the curve
	elif mode == 'quartered':
	    d_pntsConnect = {}
	    for mObj in ml_targetObjects:
		l_pos = crvUtils.returnSplitCurveList( mObj.mNode, 5 ) 
		for i,p in enumerate(l_pos):
		    if not d_pntsConnect.get(i):d_pntsConnect[i] = []
		    d_pntsConnect[i].append(p)
	    for k in d_pntsConnect.keys():
		l_created.append( mc.curve(d=curveDegree,ep=d_pntsConnect[k],os =True) )#Make the curve		    
	else:
	    for idx in d_objInfo[d_objInfo.keys()[0]]['indices']:
		l_pos = []
		for i_crv in ml_targetObjects:
		    l_pos.append( cgmMeta.cgmNode(d_objInfo[i_crv]['components'][idx]).getPosition() )
		l_created.append( mc.curve(d=curveDegree,ep=l_pos,os =True) )#Make the curve	
	return l_created
    
    except StandardError,error:
	raise StandardError,"joinCurve>> Failure. targets: %s | error: %s"%(targetObjects,error)
예제 #3
0
파일: skinDat.py 프로젝트: liudger/cgmTools
        def _validate(self):
            #>> validate ============================================================================
            self._d_data = {"mesh": {},
                            "skin": {},
                            "weights":{},
                            "blendWeights":[],
                            "influences":{}}
            
            #_validate our source
            _source = self.d_kws['source']
            _d = data().validateSourceMesh(_source)

            self._mesh = _d['mesh']
            self._skin = _d['skin']  
            self.mi_mesh = cgmMeta.cgmObject(self._mesh)
            self.mi_cluster = cgmMeta.cgmNode(self._skin)
            
            # Get the skinCluster MObject
            self.selectionList = OM.MSelectionList()
            self.selectionList.add(self._skin, True)
            self.mobject = OM.MObject()
            self.selectionList.getDependNode(0, self.mobject)
            self.fn = OMA.MFnSkinCluster(self.mobject)            
            """self.data = {'weights' : {},
                         'blendWeights' : [],
                         }"""
            
            _d['name'] = self.mi_mesh.mNode
            _d['d_vertPositions'] = {}
            
            self._d_data['mesh'] = _d
예제 #4
0
def doTagChildren(self): 
    try:
        for obj in self.i_templateNull.getAllChildren():
            i_obj = cgmMeta.cgmNode(obj)
            i_obj.doStore('templateOwner',self.templateNull)
    except StandardError,error:
        log.warning(error) 
예제 #5
0
        def _validate(self):
            #>> validate ============================================================================
            self._d_data = {"mesh": {},
                            "skin": {},
                            "weights":{},
                            "blendWeights":[],
                            "influences":{}}
            
            #_validate our source
            _source = self.d_kws['source']
            _d = data().validateSourceMesh(_source)

            self._mesh = _d['mesh']
            self._skin = _d['skin']  
            self.mi_mesh = cgmMeta.cgmObject(self._mesh)
            self.mi_cluster = cgmMeta.cgmNode(self._skin)
            
            # Get the skinCluster MObject
            self.selectionList = OM.MSelectionList()
            self.selectionList.add(self._skin, True)
            self.mobject = OM.MObject()
            self.selectionList.getDependNode(0, self.mobject)
            self.fn = OMA.MFnSkinCluster(self.mobject)            
            """self.data = {'weights' : {},
                         'blendWeights' : [],
                         }"""
            
            _d['name'] = self.mi_mesh.mNode
            _d['d_vertPositions'] = {}
            
            self._d_data['mesh'] = _d
예제 #6
0
 def _fncStep_dataCheck_(self):
     #Key to object name dict
     _d_stuffToFind = {'headModule':'head_part',
                       'neckModule':'neck_part',
                       'l_eyeModule':'l_eye_part',
                       'r_eyeModule':'r_eye_part',
                       'headMasterAnim':'Head_masterAnim',
                       'headPuppet':'Head_puppetNetwork',
                       'BodyPuppet':'MK1_puppetNetwork',
                       'faceGui':'facialRig_gui_grp',
                       'faceCam':'faceCam',
                       'world_eyeLook':'world_driving_head_eyeLook_dynDriver',
                       'world_leftEye':'world_driving_right_eye_ik_dynDriver',
                       'world_rightEye':'world_driving_left_eye_ik_dynDriver',
                       'SDKface':'face_attrHolder',
                       'SDKcustomize':'sdk_custom_attrHolder',
                       'joint_bodyHead':'head_jnt',
                       'joint_faceRigHead':'headRoot_jnt',
                       'ik_eyes':'head_eyeLook_anim',
                       'ik_l_eye':'l_eye_ik_anim',
                       'ik_r_eye':'r_eye_ik_anim',
                       'ik_shoulders':'shoulders_ik_anim',
                       'ik_cog':'cog_anim',
                       }
     self.md_objs = {}
     for k in _d_stuffToFind.keys():
         _obj = cgmValid.objString(arg=_d_stuffToFind[k], noneValid=True, 
                                   calledFrom=self._str_funcName)
         if not _obj:
             return self._FailBreak_("key: {0} | name: ('{1}') | missing".format(k,_d_stuffToFind[k]))
         self.md_objs[k] = cgmMeta.cgmNode(_obj)
         self.log_info("'{0}' found".format(k))
     
     self.log_infoNestedDict('md_objs')
예제 #7
0
    def finalize(self):
        """
        Press action. Clears buffers.
        """
        #Clean our lists...
        self.l_created = lists.returnListNoDuplicates(self.l_created)
        self.l_return = lists.returnListNoDuplicates(self.l_return)

        if self._createMode in ['curve','jointChain','group','follicle'] and self.l_return:
            if self._createMode == 'group':
                bufferList = []
                for i,o in enumerate(self.l_created):
                    buffer = rigging.groupMeObject(o,False)
                    bufferList.append(buffer)                    
                    try:mc.delete(o)
                    except:pass
                self.l_created = bufferList

            elif self._createMode =='follicle':
                if self.mode == 'midPoint':
                    log.warning("Mid point mode doesn't work with follicles")
                    return
                bufferList = []
                for o in self.l_created:
                    mesh = attributes.doGetAttr(o,'cgmHitTarget')
                    if mc.objExists(mesh):
                        uv = distance.returnClosestUVToPos(mesh,distance.returnWorldSpacePosition(o))
                        log.info("uv: {0}".format(uv))
                        follicle = nodes.createFollicleOnMesh(mesh)
                        log.info("follicle: {0}".format(follicle))                        
                        attributes.doSetAttr(follicle[0],'parameterU',uv[0])
                        attributes.doSetAttr(follicle[0],'parameterV',uv[1])
                        try:mc.delete(o)
                        except:pass                        
            else:
                for o in self.l_created:
                    try:mc.delete(o)
                    except:pass
                if self._createMode == 'curve' and len(self.l_return)>1:
                    if len(self.l_return) > 1:
                        self.l_created = [curves.curveFromPosList(self.l_return)]
                    else:
                        log.warning("Need at least 2 points for a curve")                        
                elif self._createMode == 'jointChain':
                    self.l_created = []
                    mc.select(cl=True)
                    for pos in self.l_return:                             
                        self.l_created.append( mc.joint (p = (pos[0], pos[1], pos[2]),radius = 1) ) 
        log.debug( self.l_created)

        if self.d_tagAndName:
            for o in self.l_created:
                try:
                    i_o = cgmMeta.cgmNode(o)
                    for tag in self.d_tagAndName.keys():
                        i_o.doStore(tag,self.d_tagAndName[tag])
                    i_o.doName()
                except StandardError,error:
                    log.error(">>> clickMesh >> Failed to tag and name: %s | error: %s"%(i_o.p_nameShort,error))            	            		
def verify_customizationData(i_network, skinDepth=2.5):
    """
    Gather info from customization asset
    
    from morpheusRig_v2.core import MorpheusFactory as morphyF
    reload(morphyF)
    morphyF.verify_customizationData('Morphy_customizationNetwork')
    """
    #These are the controls we'll drive positional data from to plug to our modules
    d_initialData = {}

    #>>> Verify our arg
    try:
        i_network.mNode
    except:
        if mc.objExists(i_network):
            i_network = r9Meta.MetaClass(i_network)
        else:
            log.error("'%s' doesn't exist" % i_network)
            return False
    assert i_network.mClass == 'cgmMorpheusMakerNetwork', "Not a cgmMorpheusMakerNetwork. Aborted!"

    #>> Collect our positional info
    #====================================================================
    i_objSet = i_network.objSetAll  #Should I use this or the message info
    log.debug(i_objSet.value)

    controlBuffer = i_network.objSetAll.value
    for moduleKey in l_modulesToDoOrder:
        if moduleKey not in d_moduleControls.keys():
            log.warning("Missing controls info for: '%s'" % moduleKey)
            return False
        log.debug("On moduleKey: '%s'" % moduleKey)
        controls = d_moduleControls.get(moduleKey)
        posBuffer = []
        for c in controls:
            if not mc.objExists(c):
                log.warning("Necessary positioning control not found: '%s'" %
                            c)
                return False
            else:
                log.debug("Found: '%s'" % c)
                i_c = cgmMeta.cgmNode(c)
                if i_c.isComponent():  #If it's a component
                    i_loc = cgmMeta.cgmObject(
                        mc.spaceLocator()[0])  #make a loc
                    Snap.go(i_loc.mNode, targets=c, move=True,
                            orient=True)  #Snap to the surface
                    i_loc.tz -= skinDepth  #Offset on z by skin depth
                    pos = i_loc.getPosition()  #get position
                    i_loc.delete()
                else:
                    pos = i_c.getPosition()
                if not pos: return False
                posBuffer.append(pos)
        d_initialData[moduleKey] = posBuffer

    return d_initialData
예제 #9
0
    def buildNetwork(self, *args, **kws):
        if kws: log.debug("kws: %s" % str(kws))
        if args: log.debug("args: %s" % str(args))

        #children = self.i_group.getChildren()
        mChildren = self.i_group.getChildren(asMeta=True)
        children = [mObj.p_nameShort for mObj in mChildren]
        children.insert(0, 'none')

        #Make our attr
        if len(children) == 2:
            self.i_attr.doConvert('bool')  #Like bool better
            #self.i_attr.setEnum('off:on')
        else:
            self.i_attr.setEnum(':'.join(children))

        for i, c in enumerate(children[1:]):
            i_c = cgmMeta.cgmNode(c)
            #see if the node exists
            condNodeTest = attributes.returnDriverObject(
                '%s.%s' % (c, self.connectToAttr))
            if condNodeTest:
                i_node = cgmMeta.cgmNode(condNodeTest)
            else:
                if mc.objExists('%s_condNode' % c):
                    mc.delete('%s_condNode' % c)
                i_node = cgmMeta.cgmNode(name='tmp',
                                         nodeType='condition')  #Make our node

            i_node.addAttr('cgmName', i_c.getShortName(), attrType='string')
            i_node.addAttr('cgmType', 'condNode')
            i_node.doName()
            i_node.secondTerm = i + 1
            attributes.doSetAttr(i_node.mNode, 'colorIfTrueR', 1)
            attributes.doSetAttr(i_node.mNode, 'colorIfFalseR', 0)
            #i_node.colorIfTrueR = 1
            #i_node.colorIfTrueR = 0

            self.i_attr.doConnectOut('%s.firstTerm' % i_node.mNode)
            attributes.doConnectAttr('%s.outColorR' % i_node.mNode,
                                     '%s.%s' % (c, self.connectToAttr))

        return True
def verify_customizationData(i_network, skinDepth = 2.5):
    """
    Gather info from customization asset
    
    from morpheusRig_v2.core import MorpheusFactory as morphyF
    reload(morphyF)
    morphyF.verify_customizationData('Morphy_customizationNetwork')
    """
    #These are the controls we'll drive positional data from to plug to our modules
    d_initialData = {}
    
    #>>> Verify our arg
    try:i_network.mNode
    except:
        if mc.objExists(i_network):
            i_network = r9Meta.MetaClass(i_network)
        else:
            log.error("'%s' doesn't exist"%i_network)
            return False
    assert i_network.mClass == 'cgmMorpheusMakerNetwork',"Not a cgmMorpheusMakerNetwork. Aborted!"
    
    #>> Collect our positional info
    #====================================================================
    i_objSet = i_network.objSetAll#Should I use this or the message info
    log.debug(i_objSet.value)
    
    controlBuffer = i_network.objSetAll.value
    for moduleKey in l_modulesToDoOrder:
        if moduleKey not in d_moduleControls.keys():
            log.warning("Missing controls info for: '%s'"%moduleKey)
            return False
        log.debug("On moduleKey: '%s'"%moduleKey)
        controls = d_moduleControls.get(moduleKey)
        posBuffer = []
        for c in controls:
            if not mc.objExists(c):
                log.warning("Necessary positioning control not found: '%s'"%c)
                return False
            else:
                log.debug("Found: '%s'"%c)
                i_c = cgmMeta.cgmNode(c)
                if i_c.isComponent():#If it's a component
                    i_loc = cgmMeta.cgmObject(mc.spaceLocator()[0])#make a loc
                    Snap.go(i_loc.mNode,targets = c,move = True, orient = True)#Snap to the surface
                    i_loc.tz -= skinDepth#Offset on z by skin depth
                    pos = i_loc.getPosition()#get position
                    i_loc.delete()
                else:
                    pos = i_c.getPosition()
                if not pos:return False
                posBuffer.append(pos)
        d_initialData[moduleKey] = posBuffer
        
    return d_initialData
예제 #11
0
    def test_base(self):
        NF = cgmMeta.NameFactory

        i_net1 = cgmMeta.cgmNode(name='NameFactoryTest', nodeType='network')
        i_net1.addAttr('cgmName', 'net', attrType='string')

        self.assertEqual(NF(i_net1).getBaseIterator(), 0)

        i_net2 = cgmMeta.cgmNode(mc.duplicate(i_net1.mNode)[0])
        self.assertEqual(NF(i_net1).getMatchedSiblings(), [i_net2])
        self.assertEqual(NF(i_net2).getMatchedSiblings(), [i_net1])

        self.assertEqual(NF(i_net1).getBaseIterator(), 1)

        self.assertDictEqual(i_net1.getNameDict(), i_net2.getNameDict())

        i_net1.doName(fastName=False, fastIterate=False)
        self.assertEqual(NF(i_net2).getBaseIterator(), 2)

        NF(i_net2).doNameObject(fastIterate=False)
        self.assertIn('2', list(i_net2.mNode))
예제 #12
0
    def test_mClassConversion_r9(self):
        n1 = cgmMeta.cgmNode(name='test_setClass', nodeType='transform')
        self.assertEqual(type(n1), cgmMeta.cgmNode)

        n1 = r9Meta.convertMClassType(n1, 'cgmObject')
        self.assertEqual(type(n1), cgmMeta.cgmObject)

        n1 = r9Meta.convertMClassType(n1, 'cgmControl')
        self.assertEqual(type(n1), cgmMeta.cgmControl)

        n1 = r9Meta.convertMClassType(n1, 'MetaClass')
        self.assertEqual(type(n1), r9Meta.MetaClass)

        n1.delete()
예제 #13
0
	def __func__(self):
	    """
	    """
	    obj = cgmValid.objString(self.d_kws['obj'],isTransform=True)
	    crv = cgmValid.objString(self.d_kws['crv'],mayaType='nurbsCurve')	
	    d_returnBuff = distance.returnNearestPointOnCurveInfo(obj,crv)
	    mi_poci = cgmMeta.cgmNode(nodeType = 'pointOnCurveInfo')
	    mc.connectAttr("%s.worldSpace"%d_returnBuff['shape'],"%s.inputCurve"%mi_poci.mNode)
	    mi_poci.parameter = d_returnBuff['parameter']
	    mc.connectAttr("%s.position"%mi_poci.mNode,"%s.t"%obj)
	    mi_poci.doStore('cgmName',obj)
	    mi_poci.doName()
	    
	    return True
예제 #14
0
    def test_mClassConversion_cgm(self):
        _str_grp = mc.group(em=True)

        n1 = cgmMeta.cgmNode(_str_grp)
        n1 = r9Meta.convertMClassType(n1, 'cgmControl')

        self.assertEqual(type(n1), cgmMeta.cgmControl)

        n1 = cgmMeta.validateObjArg(n1.mNode, 'cgmObject', setClass=True)
        self.assertEqual(type(n1), cgmMeta.cgmObject)

        n1 = cgmMeta.validateObjArg(n1.mNode, 'cgmControl', setClass=True)
        self.assertEqual(type(n1), cgmMeta.cgmControl)

        n1.delete()
예제 #15
0
    def __init__(self,
                 group,
                 chooseAttr='switcher',
                 controlObject=None,
                 connectTo='visibility',
                 *args,
                 **kws):
        """Constructor"""
        self.d_iAttrs = {}  #attr instances stores as {index:instance}
        self.l_iAttrs = []  #Indices for iAttrs
        self.d_resultNetworksToBuild = {
        }  #Index desctiptions of networks to build {target:[[1,2],3]}
        self.i_group = False
        self.i_control = False
        self.connectToAttr = connectTo
        self.i_attr = False

        #>>>Keyword args
        log.debug(">>> build_conditionNetworkFromGroup.__init__")
        if kws: log.debug("kws: %s" % str(kws))
        if args: log.debug("args: %s" % str(args))

        #Check our group
        if not mc.objExists(group):
            log.error("Group doesn't exist: '%s'" % group)
            return
        elif not search.returnObjectType(group) == 'group':
            log.error("Object is not a group: '%s'" %
                      search.returnObjectType(group))
            return
        self.i_group = cgmMeta.cgmObject(group)
        if not self.i_group.getChildren():
            log.error("No children detected: '%s'" % group)
            return

        #Check our control
        if controlObject is None or not mc.objExists(controlObject):
            log.error("No suitable control object found: '%s'" % controlObject)
            return
        else:
            i_controlObject = cgmMeta.cgmNode(controlObject)
            self.i_attr = cgmMeta.cgmAttr(i_controlObject,
                                          chooseAttr,
                                          attrType='enum',
                                          initialValue=1)
        if self.buildNetwork(*args, **kws):
            log.debug("Chooser Network good to go")
예제 #16
0
    def test_validateObjArg(self):
        null = mc.group(em=True)
        i_node = cgmMeta.cgmNode(nodeType='transform')
        i_obj = cgmMeta.cgmObject(nodeType='transform')

        self.assertRaises(ValueError, cgmMeta.validateObjArg, arg=None)

        self.assertEqual(i_obj,
                         cgmMeta.validateObjArg(i_obj.mNode))  #...string arg
        self.assertEqual(i_obj, cgmMeta.validateObjArg(i_obj))  #...intance arg

        i_obj = cgmMeta.validateObjArg(i_obj.mNode, 'cgmObject', setClass=True)
        self.assertEqual(issubclass(type(i_obj), cgmMeta.cgmObject),
                         True)  #...String + mType

        self.assertEqual(i_obj, cgmMeta.validateObjArg(
            i_obj, 'cgmObject'))  #...Instance + mType

        self.assertEqual(
            issubclass(type(cgmMeta.validateObjArg(null)), cgmMeta.cgmNode),
            True)  #...null string failed

        i_null = cgmMeta.validateObjArg(null, 'cgmObject')

        self.assertEqual(issubclass(type(i_null), cgmMeta.cgmObject),
                         True)  #..."Null as cgmObject

        _objs = [
            mc.joint(),
            mc.group(em=True),
            mc.createNode('multiplyDivide', name='multiplyDivideValideObjArg')
        ]
        for i, obj in enumerate(_objs):
            if i == 2:
                self.assertRaises(ValueError, cgmMeta.validateObjArg, obj,
                                  'cgmObject')
                mc.delete(obj)

                #issubclass(type(n1),cgmMeta.cgmNode),True, type(n1))
            else:
                n1 = cgmMeta.validateObjArg(obj, 'cgmObject')
                self.assertEqual(issubclass(type(n1), cgmMeta.cgmObject), True,
                                 type(n1))
                n1.delete()
예제 #17
0
    def doOrient(self,**kws):
	if len(self.l_targets) == 1:
	    i_target = cgmMeta.cgmNode(self.l_targets[0])
	    #if self.i_obj.rotateOrder != i_target.rotateOrder:
		#raise StandardError, "Can't match different rotate orders yet"
	    if i_target.isComponent():
		if 'poly' in i_target.getMayaType():
		    self.doOrientObjToSurface(i_target.mNode,self.i_obj.mNode)
		else:
		    raise NotImplementedError,"Haven't set orient for type: %s"%i_target.getMayaType()			   
	    elif i_target.getMayaType() == 'mesh':
		self.doOrientObjToSurface(i_target.mNode,self.i_obj.mNode)		

	    else:
		mc.delete(mc.orientConstraint(i_target.mNode,self.i_obj.mNode,mo=False))
		#objRot = mc.xform (i_target.mNode, q=True, ws=True, ro=True)		
		#mc.rotate (objRot[0], objRot[1], objRot[2], [self.i_obj.mNode], ws=True)    
	else:
	    raise NotImplementedError,"Haven't set up: doOrient multi"	
예제 #18
0
    def doOrient(self, **kws):
        if len(self.l_targets) == 1:
            i_target = cgmMeta.cgmNode(self.l_targets[0])
            #if self.i_obj.rotateOrder != i_target.rotateOrder:
            #raise StandardError, "Can't match different rotate orders yet"
            if i_target.isComponent():
                if 'poly' in i_target.getMayaType():
                    self.doOrientObjToSurface(i_target.mNode, self.i_obj.mNode)
                else:
                    raise NotImplementedError, "Haven't set orient for type: %s" % i_target.getMayaType(
                    )
            elif i_target.getMayaType() == 'mesh':
                self.doOrientObjToSurface(i_target.mNode, self.i_obj.mNode)

            else:
                mc.delete(
                    mc.orientConstraint(i_target.mNode,
                                        self.i_obj.mNode,
                                        mo=False))
                #objRot = mc.xform (i_target.mNode, q=True, ws=True, ro=True)
                #mc.rotate (objRot[0], objRot[1], objRot[2], [self.i_obj.mNode], ws=True)
        else:
            raise NotImplementedError, "Haven't set up: doOrient multi"
                                              mControl.mNode, atr))

    #for i,mGrp in enumerate(mGroups):
    #    shortName = mGrp.getShortName()
    #if log.getEffectiveLevel() == 10:log.debug(shortName)
    #Let's get basic info for a good attr name
    #d = nameTools.returnObjectGeneratedNameDict(shortName,ignore=['cgmTypeModifier','cgmType'])
    #n = nameTools.returnCombinedNameFromDict(d)
    #    nodeF.build_conditionNetworkFromGroup(shortName, chooseAttr = i, controlObject = "{0}.{1}".format(mControl.mNode,atr))
    return True


#===================================================================================================
# >> Constraints
#===================================================================================================
n1 = cgmMeta.cgmNode(mc.ls(sl=True)[0])

import cgm.core.lib.constraint_utils as CONSTRAINT
mc.select(CONSTRAINT.get_targets(mc.ls(sl=True)[0]))

_target = 'leg_front_l_IK_anim'
_grp = 'clavicle_front_l_grp'
mc.aimConstraint(_target,
                 _grp,
                 maintainOffset=True,
                 aimVector=[1, 0, 0],
                 upVector=[0, 1, 0],
                 worldUpType='objectrotation',
                 worldUpVector=[0, 1, 0],
                 worldUpObject='COG_c_anim')
예제 #20
0
def segment_handles(self,
                    ml_handles=None,
                    ml_handleParents=None,
                    mIKBaseControl=None,
                    mRoot=None,
                    str_ikBase=None,
                    upMode='asdf'):
    try:
        _str_func = 'segment_handles'
        log_start(_str_func)

        mBlock = self.mBlock
        mRigNull = self.mRigNull
        _offset = self.v_offset
        _jointOrientation = self.d_orientation['str']

        if not ml_handles:
            raise ValueError, "{0} | ml_handles required".format(_str_func)
        if not ml_handleParents:
            raise ValueError, "{0} | ml_handleParents required".format(
                _str_func)

        ml_ribbonIkHandles = mRigNull.msgList_get('ribbonIKDrivers')
        if not ml_ribbonIkHandles:
            ml_ribbonIkHandles = ml_handleParents
            #raise ValueError,"No ribbon IKDriversFound"

        if str_ikBase == None:
            str_ikBase = mBlock.getEnumValueString('ikBase')

        _aim = self.d_orientation['vectorAim']
        _aimNeg = self.d_orientation['vectorAimNeg']
        _up = self.d_orientation['vectorUp']
        _out = self.d_orientation['vectorOut']

        if str_ikBase == 'hips':
            log.debug("|{0}| >> hips setup...".format(_str_func))

        if len(ml_handles) == 1:
            mHipHandle = ml_handles[0]
            RIGCONSTRAINT.build_aimSequence(
                ml_handles,
                ml_ribbonIkHandles,
                [mIKBaseControl],  #ml_handleParents,
                mode='singleBlend',
                upMode='objectRotation')
        else:
            if str_ikBase == 'hips':
                log.debug("|{0}| >> hips handles...".format(_str_func))
                ml_handles[0].masterGroup.p_parent = mIKBaseControl
                mHipHandle = ml_handles[1]
                mHipHandle.masterGroup.p_parent = mRoot
                mc.pointConstraint(mIKBaseControl.mNode,
                                   mHipHandle.masterGroup.mNode,
                                   maintainOffset=True)

                RIGCONSTRAINT.build_aimSequence(
                    ml_handles[1],
                    ml_ribbonIkHandles,
                    [mIKBaseControl],  #ml_handleParents,
                    mode='singleBlend',
                    upParent=self.d_orientation['vectorOut'],
                    upMode='objectRotation')
                """
                        RIGCONSTRAINT.build_aimSequence(ml_handles[-1],
                                                        ml_ribbonIkHandles,
                                                         #[mRigNull.controlIK.mNode],#ml_handleParents,
                                                        mode = 'singleBlend',
                                                        upMode = 'objectRotation')"""

                for i, mHandle in enumerate(ml_handles):
                    if mHandle in ml_handles[:2]:  # + [ml_handles[-1]]:
                        continue

                    mHandle.masterGroup.parent = ml_handleParents[i]
                    s_rootTarget = False
                    s_targetForward = False
                    s_targetBack = False
                    mMasterGroup = mHandle.masterGroup
                    b_first = False
                    if mHandle == ml_handles[0]:
                        log.debug("|{0}| >> First handle: {1}".format(
                            _str_func, mHandle))
                        if len(ml_handles) <= 2:
                            s_targetForward = ml_handleParents[-1].mNode
                        else:
                            s_targetForward = ml_handles[i + 1].getMessage(
                                'masterGroup')[0]
                        s_rootTarget = mRoot.mNode
                        b_first = True

                    elif mHandle == ml_handles[-1]:
                        log.debug("|{0}| >> Last handle: {1}".format(
                            _str_func, mHandle))
                        s_rootTarget = ml_handleParents[i].mNode
                        s_targetBack = ml_handles[i - 1].getMessage(
                            'masterGroup')[0]
                    else:
                        log.debug("|{0}| >> Reg handle: {1}".format(
                            _str_func, mHandle))
                        s_targetForward = ml_handles[i + 1].getMessage(
                            'masterGroup')[0]
                        s_targetBack = ml_handles[i - 1].getMessage(
                            'masterGroup')[0]

                    #Decompose matrix for parent...
                    if upMode == 'matrix':
                        mUpDecomp = cgmMeta.cgmNode(nodeType='decomposeMatrix')
                        mUpDecomp.doStore('cgmName', ml_handleParents[i])
                        mUpDecomp.addAttr('cgmType',
                                          'aimMatrix',
                                          attrType='string',
                                          lock=True)
                        mUpDecomp.doName()

                        ATTR.connect(
                            "%s.worldMatrix" % (ml_handleParents[i].mNode),
                            "%s.%s" % (mUpDecomp.mNode, 'inputMatrix'))

                        _d_up = {
                            'aimVector': _aim,
                            'upVector': _out,
                            'worldUpObject': ml_handleParents[i].mNode,
                            'worldUpType': 'vector',
                            'worldUpVector': [0, 0, 0]
                        }
                    else:
                        _d_up = {
                            'aimVector': _aim,
                            'upVector': _out,
                            'worldUpObject': ml_handleParents[i].mNode,
                            'worldUpType': 'objectRotation',
                            'worldUpVector': [1, 0, 0]
                        }

                    if s_targetForward:
                        mAimForward = mHandle.doCreateAt()
                        mAimForward.parent = mMasterGroup
                        mAimForward.doStore('cgmTypeModifier', 'forward')
                        mAimForward.doStore('cgmType', 'aimer')
                        mAimForward.doName()

                        _const = mc.aimConstraint(s_targetForward,
                                                  mAimForward.mNode,
                                                  maintainOffset=True,
                                                  **_d_up)

                        s_targetForward = mAimForward.mNode
                        if upMode == 'matrix':
                            ATTR.connect(
                                "%s.%s" % (mUpDecomp.mNode, "outputRotate"),
                                "%s.%s" % (_const[0], "upVector"))

                    else:
                        s_targetForward = ml_handleParents[i].mNode

                    if s_targetBack:
                        mAimBack = mHandle.doCreateAt()
                        mAimBack.parent = mMasterGroup
                        mAimBack.doStore('cgmTypeModifier', 'back')
                        mAimBack.doStore('cgmType', 'aimer')
                        mAimBack.doName()

                        _d_up['aimVector'] = _aimNeg

                        _const = mc.aimConstraint(s_targetBack,
                                                  mAimBack.mNode,
                                                  maintainOffset=True,
                                                  **_d_up)
                        s_targetBack = mAimBack.mNode

                        if upMode == 'matrix':
                            ATTR.connect(
                                "%s.%s" % (mUpDecomp.mNode, "outputRotate"),
                                "%s.%s" % (_const[0], "upVector"))
                    else:
                        s_targetBack = s_rootTarget
                        #ml_handleParents[i].mNode

                    #pprint.pprint([s_targetForward,s_targetBack])
                    mAimGroup = mHandle.doGroup(True,
                                                asMeta=True,
                                                typeModifier='aim')

                    mHandle.parent = False

                    if b_first:
                        const = mc.orientConstraint(
                            [s_targetBack, s_targetForward],
                            mAimGroup.mNode,
                            maintainOffset=True)[0]
                    else:
                        const = mc.orientConstraint(
                            [s_targetForward, s_targetBack],
                            mAimGroup.mNode,
                            maintainOffset=True)[0]

                    d_blendReturn = NODEFACTORY.createSingleBlendNetwork(
                        [mHandle.mNode, 'followRoot'],
                        [mHandle.mNode, 'resultRootFollow'],
                        [mHandle.mNode, 'resultAimFollow'],
                        keyable=True)
                    targetWeights = mc.orientConstraint(const,
                                                        q=True,
                                                        weightAliasList=True,
                                                        maintainOffset=True)

                    #Connect
                    d_blendReturn['d_result1']['mi_plug'].doConnectOut(
                        '%s.%s' % (const, targetWeights[0]))
                    d_blendReturn['d_result2']['mi_plug'].doConnectOut(
                        '%s.%s' % (const, targetWeights[1]))
                    d_blendReturn['d_result1']['mi_plug'].p_hidden = True
                    d_blendReturn['d_result2']['mi_plug'].p_hidden = True

                    mHandle.parent = mAimGroup  #...parent back

            else:
                log.debug("|{0}| >> reg handles...".format(_str_func))
                for i, mHandle in enumerate(ml_handles):
                    mHandle.masterGroup.parent = ml_handleParents[i]
                    s_rootTarget = False
                    s_targetForward = False
                    s_targetBack = False
                    mMasterGroup = mHandle.masterGroup
                    b_first = False
                    if mHandle == ml_handles[0]:
                        log.debug("|{0}| >> First handle: {1}".format(
                            _str_func, mHandle))
                        if len(ml_handles) <= 2:
                            s_targetForward = ml_handleParents[-1].mNode
                        else:
                            s_targetForward = ml_handles[i + 1].getMessage(
                                'masterGroup')[0]
                        s_rootTarget = mRoot.mNode
                        b_first = True

                    elif mHandle == ml_handles[-1]:
                        log.debug("|{0}| >> Last handle: {1}".format(
                            _str_func, mHandle))
                        s_rootTarget = ml_handleParents[i].mNode
                        s_targetBack = ml_handles[i - 1].getMessage(
                            'masterGroup')[0]
                    else:
                        log.debug("|{0}| >> Reg handle: {1}".format(
                            _str_func, mHandle))
                        s_targetForward = ml_handles[i + 1].getMessage(
                            'masterGroup')[0]
                        s_targetBack = ml_handles[i - 1].getMessage(
                            'masterGroup')[0]

                    #Decompose matrix for parent...
                    mUpDecomp = cgmMeta.cgmNode(nodeType='decomposeMatrix')
                    mUpDecomp.doStore('cgmName', ml_handleParents[i])
                    mUpDecomp.addAttr('cgmType',
                                      'aimMatrix',
                                      attrType='string',
                                      lock=True)
                    mUpDecomp.doName()

                    ATTR.connect(
                        "%s.worldMatrix" % (ml_handleParents[i].mNode),
                        "%s.%s" % (mUpDecomp.mNode, 'inputMatrix'))

                    if s_targetForward:
                        mAimForward = mHandle.doCreateAt()
                        mAimForward.parent = mMasterGroup
                        mAimForward.doStore('cgmTypeModifier', 'forward')
                        mAimForward.doStore('cgmType', 'aimer')
                        mAimForward.doName()

                        _const = mc.aimConstraint(
                            s_targetForward,
                            mAimForward.mNode,
                            maintainOffset=True,  #skip = 'z',
                            aimVector=_aim,
                            upVector=_out,
                            worldUpObject=ml_handleParents[i].mNode,
                            worldUpType='vector',
                            worldUpVector=[0, 0, 0])
                        s_targetForward = mAimForward.mNode
                        ATTR.connect(
                            "%s.%s" % (mUpDecomp.mNode, "outputRotate"),
                            "%s.%s" % (_const[0], "upVector"))

                    else:
                        s_targetForward = ml_handleParents[i].mNode

                    if s_targetBack:
                        mAimBack = mHandle.doCreateAt()
                        mAimBack.parent = mMasterGroup
                        mAimBack.doStore('cgmTypeModifier', 'back')
                        mAimBack.doStore('cgmType', 'aimer')
                        mAimBack.doName()

                        _const = mc.aimConstraint(
                            s_targetBack,
                            mAimBack.mNode,
                            maintainOffset=True,  #skip = 'z',
                            aimVector=_aimNeg,
                            upVector=_out,
                            worldUpObject=ml_handleParents[i].mNode,
                            worldUpType='vector',
                            worldUpVector=[0, 0, 0])
                        s_targetBack = mAimBack.mNode
                        ATTR.connect(
                            "%s.%s" % (mUpDecomp.mNode, "outputRotate"),
                            "%s.%s" % (_const[0], "upVector"))
                    else:
                        s_targetBack = s_rootTarget
                        #ml_handleParents[i].mNode

                    #pprint.pprint([s_targetForward,s_targetBack])
                    mAimGroup = mHandle.doGroup(True,
                                                asMeta=True,
                                                typeModifier='aim')

                    mHandle.parent = False

                    if b_first:
                        const = mc.orientConstraint(
                            [s_targetBack, s_targetForward],
                            mAimGroup.mNode,
                            maintainOffset=True)[0]
                    else:
                        const = mc.orientConstraint(
                            [s_targetForward, s_targetBack],
                            mAimGroup.mNode,
                            maintainOffset=True)[0]

                    d_blendReturn = NODEFACTORY.createSingleBlendNetwork(
                        [mHandle.mNode, 'followRoot'],
                        [mHandle.mNode, 'resultRootFollow'],
                        [mHandle.mNode, 'resultAimFollow'],
                        keyable=True)
                    targetWeights = mc.orientConstraint(const,
                                                        q=True,
                                                        weightAliasList=True,
                                                        maintainOffset=True)

                    #Connect
                    d_blendReturn['d_result1']['mi_plug'].doConnectOut(
                        '%s.%s' % (const, targetWeights[0]))
                    d_blendReturn['d_result2']['mi_plug'].doConnectOut(
                        '%s.%s' % (const, targetWeights[1]))
                    d_blendReturn['d_result1']['mi_plug'].p_hidden = True
                    d_blendReturn['d_result2']['mi_plug'].p_hidden = True

                    mHandle.parent = mAimGroup  #...parent back

        for mHandle in ml_handles:
            if mHandle in [ml_handles[0], ml_handles[-1]]:
                mHandle.followRoot = 1
                ATTR.set_default(mHandle.mNode, 'followRoot', 1.0)
            else:
                mHandle.followRoot = .5
                ATTR.set_default(mHandle.mNode, 'followRoot', .5)

    except Exception, err:
        cgmGEN.cgmExceptCB(Exception, err, localDat=vars())
예제 #21
0
                #Closest setup =====================================================================
                mi_controlLoc = self.mi_obj.doLoc()
                mi_controlLoc.doStore('cgmName', self.mi_obj)
                mi_controlLoc.addAttr('cgmTypeModifier', 'control', lock=True)
                mi_controlLoc.doName()
                self.mi_controlLoc = mi_controlLoc
                self.md_return["controlLoc"] = mi_controlLoc

                if self.b_attachControlLoc:
                    mi_group = cgmMeta.asMeta(mi_controlLoc.doGroup(),
                                              'cgmObject',
                                              setClass=True)
                    mi_group.parent = mi_follicleAttachTrans

                #Create decompose node --------------------------------------------------------------
                mi_worldTranslate = cgmMeta.cgmNode(nodeType='decomposeMatrix')
                mi_worldTranslate.doStore('cgmName', self.mi_obj)
                mi_worldTranslate.doName()
                self.mi_worldTranslate = mi_worldTranslate

                attributes.doConnectAttr(
                    "%s.worldMatrix" % (mi_controlLoc.mNode),
                    "%s.%s" % (mi_worldTranslate.mNode, 'inputMatrix'))

                #Create node --------------------------------------------------------------
                mi_cpos = NodeF.createNormalizedClosestPointNode(
                    self.mi_obj, self.mi_targetSurface)

                attributes.doConnectAttr(
                    (mi_cpos.mNode + '.out_uNormal'),
                    (mi_follicleFollowShape.mNode + '.parameterU'))
m1.__dict__.keys()
m1.rigNull.skinJoints
i_rig = Rig.go(m1)
m1.getState()
i_rig.d_controlShapes
rig_segmentFK(i_rig.d_controlShapes)
Rig.registerControl('pelvis_anim')
l_joints = mc.ls(sl=True)

s = cgmMeta.cgmAttr('pelvis_surfaceJoint','scaleX')
s.p_hidden = False
curves.createControlCurve('semiSphere',10,'z-')
attributes.doSetAttr('closestPointOnSurface1','inPostionX',5)
mc.setAttr('closestPointOnSurface1.inPostionX',5)
m1 = cgmPM.cgmModule(name = 'test')
m1 = cgmMeta.cgmNode('spine_part')
m1.setState('skeleton',forceNew = True)
m1.rigNull.skinJoints
m1.getModuleColors()
m1.getPartNameBase()
m1.modulePuppet.getGeo()
targetObj = mc.ls(sl=True)[0]
distance.returnClosestPointOnSurfaceInfo(targetObj,'test_controlSurface')
distance.returnClosestUV(targetObj,'test_controlSurface')
log.info(a)
nodes.createFollicleOnMesh('spine_controlSurface','test')
locators.locMeClosestUVOnSurface(mc.ls(sl=True)[0], 'test_controlSurface', pivotOnSurfaceOnly = False)


mesh = 'Morphy_Body_GEO'
i_obj = cgmMeta.cgmObject('hips_anim')
예제 #23
0
#So maya can do that, what if you wanted to do something neater like say, store an attribute
mi_catcherObj.doStore(
    'objTX', "%s.tx" %
    mi_catchMeObj.mNode)  #It's gonna just store a string, no message....
mi_catchMeObj.tx = 4  #our attribute changed. That's because, this storage method stores on a compatible attribute format
#That's great and all, but we were talking about messages...
mi_catcherObj.getMessage('objTX')  # we get the attribute, neato...
mi_catcherObj.getMessageAsMeta(
    'objTX')  # we get the attribute, neato...cgmAttr for the win
#implementing attr setup to msgLists is on the ToDO list
#==============================================================================================

#>>Component use ==============================================================================
#We'll make a shphere and buffer that...
l_sphereReturn = mc.sphere(nsp=4, name='MySphere')
mi_sphere = cgmMeta.cgmNode(l_sphereReturn[0])  #We'll meta the sphere object
mi_sphere.mNode  #Just like an mNode, but what if we wanna instance a component...
mi_cv = cgmMeta.cgmNode("%s.cv[3][0]" % mi_sphere.mNode)  #metaNode a cv
mi_cv.mNode  #We get the shape back
mi_cv.getComponent()  #We get the component
mi_cv.isComponent()  #Yup
mi_sphere.isComponent()  #Nope...it's a sphere
mi_sphere.getComponents('cv')  #List of cv's
mi_sphere.getPosition(
)  #Get our position,arg is world space or not, default is worldspace(True)
mi_cv.getPosition()  #Get the position of the cv
mi_cv.getTransform()  #Get the transform of the component
#==============================================================================================

#>>Properties =================================================================================
mi_sphere.p_nameBase  #name string along
reload(mFactory)
mFactory.getMirrorModule(leg1)
mFactory.mirrorPush(leg1)
mFactory.mirrorPull(leg1)

leg1 = r9Meta.MetaClass('l_leg_part')
leg2 = r9Meta.MetaClass('r_leg_part')
leg1.connectChildNode(leg2, 'moduleMirror', 'moduleMirror')

m1 = r9Meta.MetaClass('l_clav_part')
jFactory.go(m1)

#>>> Modules
#=======================================================
m1 = cgmPM.cgmEyeball(name='eye')
m1 = cgmMeta.cgmNode('l_eye_part')
m1.getState()
m1.__verify__()
m1 = r9Meta.MetaClass('spine_part')
m1 = r9Meta.MetaClass('neck_part')
a = cgmPM.cgmPuppet(name='MorphyEye')
a.connectModule(m1)
m1 = r9Meta.MetaClass('l_leg_part')
m1.setState('skeleton', force=True)
m1.setState('rig', force=True)
m1.getPartNameBase()
mFactory.isSkeletonized(m1)
mFactory.isTemplated(m1)
mFactory.doSize(m1, geo=['pSphere1'])
mFactory.isSized(m1)
mFactory.doTemplate(m1)
예제 #25
0
def createWrapControlShape(targetObjects,
                           targetGeo = None,
                           latheAxis = 'z',aimAxis = 'y+',objectUp = 'y+',
                           points = 8,
                           curveDegree = 1,
                           insetMult = None,#Inset multiplier
                           posOffset = [],
                           rootOffset = [],#offset root before cast
                           rootRotate = None,
                           joinMode = False,
                           extendMode = None,
                           closedCurve = True,
                           l_specifiedRotates = None,
                           maxDistance = 1000,
                           closestInRange = True,
                           midMeshCast = False,
                           rotateBank = None,
                           joinHits = None,#keys to processed hits to see what to join
                           axisToCheck = ['x','y'],
                           ):#'segment,radial,disc' 
    """
    Function for creating control curves from other objects. Currently assumes z aim, y up
    1) Cather info
    2) Get initial curves
    3) Store info
    4) return
    
    TODO:
    Change offsets to use lathe axis rather than 
    """
    _str_funcName = "createWrapControlShape"
    log.debug(">> %s >> "%(_str_funcName) + "="*75)  
    
    if type(targetObjects) not in [list,tuple]:targetObjects = [targetObjects]
    if not targetGeo:
	raise NotImplementedError, "Must have geo for now"
    if len(mc.ls(targetGeo))>1:
	raise StandardError,"createWrapControlShape>> More than one mesh named: %s"%targetGeo  
    assert type(points) is int,"Points must be int: %s"%points
    assert type(curveDegree) is int,"Points must be int: %s"%points
    assert curveDegree > 0,"Curve degree must be greater than 1: %s"%curveDegree
    if posOffset is not None and len(posOffset) and len(posOffset)!=3:raise StandardError, "posOffset must be len(3): %s | len: %s"%(posOffset,len(posOffset))
    if rootOffset is not None and len(rootOffset) and len(rootOffset)!=3:raise StandardError, "rootOffset must be len(3): %s | len: %s"%(rootOffset,len(rootOffset))
    if rootRotate is not None and len(rootRotate) and len(rootRotate)!=3:raise StandardError, "rootRotate must be len(3): %s | len: %s"%(rootRotate,len(rootRotate))
    
    if extendMode in ['loliwrap'] and insetMult is None:insetMult = 1
    for axis in ['x','y','z']:
	if axis in latheAxis.lower():latheAxis = axis
    
    log.debug("targetObjects: %s"%targetObjects)
    
    if len(aimAxis) == 2:single_aimAxis = aimAxis[0]
    else:single_aimAxis = aimAxis
    log.debug("Single aim: %s"%single_aimAxis)
    log.debug("createWrapControlShape>> midMeshCast: %s"%midMeshCast)
        
    #>> Info
    l_groupsBuffer = []
    il_curvesToCombine = []
    l_sliceReturns = []
    #Need to do more to get a better size
    
    #>> Build curves
    #=================================================================
    #> Root curve #
    log.debug("RootRotate: %s"%rootRotate)
    mi_rootLoc = cgmMeta.cgmNode(targetObjects[0]).doLoc()
    if rootOffset:
	log.debug("rootOffset: %s"%rootOffset)
	mc.move(rootOffset[0],rootOffset[1],rootOffset[2], [mi_rootLoc.mNode], r=True, rpr = True, os = True, wd = True)
    if rootRotate is not None and len(rootRotate):
	log.debug("rootRotate: %s"%rootRotate)	
	mc.rotate(rootRotate[0],rootRotate[1],rootRotate[2], [mi_rootLoc.mNode], os = True,r=True)   
	    
    #>> Root
    mi_rootLoc.doGroup()#Group to zero    
    if extendMode == 'segment':
	log.debug("segment mode. Target len: %s"%len(targetObjects[1:]))	
	try:
	    if len(targetObjects) < 2:
		log.warning("Segment build mode only works with two objects or more")    
	    else:
		if insetMult is not None:
		    rootDistanceToMove = distance.returnDistanceBetweenObjects(targetObjects[0],targetObjects[1])
		    log.debug("rootDistanceToMove: %s"%rootDistanceToMove)
		    mi_rootLoc.__setattr__('t%s'%latheAxis,rootDistanceToMove*insetMult)
		    #mi_rootLoc.tz = (rootDistanceToMove*insetMult)#Offset it
		
		#Notes -- may need to play with up object for aim snapping
		#mi_upLoc = cgmMeta.cgmNode(targetObjects[0]).doLoc()
		#mi_upLoc.doGroup()#To zero
		objectUpVector = dictionary.returnStringToVectors(objectUp)
		log.debug("objectUpVector: %s"%objectUpVector)		    
		#mi_uploc
		
		for i,obj in enumerate(targetObjects[1:]):
		    log.debug("i: %s"%i)
		    #> End Curve
		    mi_endLoc = cgmMeta.cgmNode(obj).doLoc()
		    aimVector = dictionary.returnStringToVectors(latheAxis+'-')
		    log.debug("segment aimback: %s"%aimVector)		    
		    #Snap.go(mi_endLoc.mNode,mi_rootLoc.mNode,move=False,aim=True,aimVector=aimVector,upVector=objectUpVector)
		    Snap.go(mi_endLoc.mNode,mi_rootLoc.mNode,move=False,orient=True)		    
		    mi_endLoc.doGroup()
		    
		    if i == len(targetObjects[1:])-1:
			if insetMult is not None:
			    log.debug("segment insetMult: %s"%insetMult)			    
			    distanceToMove = distance.returnDistanceBetweenObjects(targetObjects[-1],targetObjects[0])
			    log.debug("distanceToMove: %s"%distanceToMove)
			    #mi_endLoc.tz = -(distanceToMove*insetMult)#Offset it  
			    mi_endLoc.__setattr__('t%s'%latheAxis,-(distanceToMove*insetMult))
		    log.debug("segment lathe: %s"%latheAxis)
		    log.debug("segment aim: %s"%aimAxis)
		    log.debug("segment rotateBank: %s"%rotateBank)		    
		    d_endCastInfo = createMeshSliceCurve(targetGeo,mi_endLoc,midMeshCast=midMeshCast,curveDegree=curveDegree,latheAxis=latheAxis,aimAxis=aimAxis,posOffset = posOffset,points = points,returnDict=True,closedCurve = closedCurve, maxDistance = maxDistance, closestInRange=closestInRange, rotateBank=rotateBank, l_specifiedRotates = l_specifiedRotates,axisToCheck = axisToCheck)  	
		    l_sliceReturns.append(d_endCastInfo)
		    mi_end = cgmMeta.cgmObject(d_endCastInfo['curve'])
		    il_curvesToCombine.append(mi_end)
		    mc.delete(mi_endLoc.parent)#delete the loc
		    
	except StandardError,error:
	    raise StandardError,"createWrapControlShape>> segment wrap fail! | %s"%error
예제 #26
0
import cgm.core
cgm.core._reload()
from cgm.core import cgm_Meta as cgmMeta
from cgm.core import cgm_PuppetMeta as cgmPM
import Red9.core.Red9_Meta as r9Meta
from cgm.core.rigger import RigFactory as Rig
#======================================================================

cgmPM.cgmSimpleBSFace(name = 'm1_face')

face1 = cgmMeta.cgmNode('m1_face_part')#...creation
face1.__verify__()
#...connecting stuff
face1.rigNull.geo_bridgeHead = 'M1_Head_bridge_geo'
face1.rigNull.geo_head = 'M1_Head_geo'
face1.rigNull.bsNode_bridge = 'faceBridge_bsNode'
face1.rigNull.gui_cam = 'faceCam'
face1.rigNull.gui_main = 'facialRig_gui'
face1.rigNull.bsNode_bridge = 'faceBridge_bsNode'

face1.templateNull.rigBlock_eye_left = 'l_eye_rigHelper'
face1.templateNull.rigBlock_eye_right = 'r_eye_rigHelper'
face1.templateNull.rigBlock_face_lwr = 'mouthNose_rigHelper'
face1.templateNull.rigBlock_face_upr = 'brow_rigHelper'


face1.rigNull.msgList_connect(mc.ls(sl=True),'bsNodes','driving')
face1.rigNull.msgList_connect(mc.ls(sl=True),'controlsAll')

#mirroring
from Red9.core import Red9_AnimationUtils as r9Anim
예제 #27
0
파일: eyeball.py 프로젝트: liudger/cgmTools
                except Exception, error:
                    raise Exception, "[registration]{%s}" % (error)

                try:  #Set up some attributes
                    attributes.doSetLockHideKeyableAttr(
                        mObj.mNode,
                        channels=[
                            "r%s" % mi_go._jointOrientation[1],
                            "r%s" % mi_go._jointOrientation[2], 'v'
                        ])
                except Exception, error:
                    raise Exception, "[Attribute setup]{%s}" % (error)

                try:  #Vis Connect
                    for shp in mObj.getShapes():
                        mShp = cgmMeta.cgmNode(shp)
                        mShp.overrideEnabled = 1
                        self.mPlug_result_moduleFaceSubDriver.doConnectOut(
                            "%s.overrideVisibility" % mShp.mNode)
                except Exception, error:
                    raise Exception, "[subVisConnect]{%s}" % (error)

            except Exception, error:
                raise Exception, "[Build Settings fail]{%s}" % (error)

        def _buildConnections_(self):
            #Register our mirror indices ---------------------------------------------------------------------------------------
            mi_go = self._go  #Rig Go instance link
            int_start = self._go._i_puppet.get_nextMirrorIndex(
                mi_go._direction)
            for i, mCtrl in enumerate(self.ml_controlsAll):
예제 #28
0
p1.templateSettings_call('load')
p1.templateSettings_call('update')

p1.templateSettings_call('export')
p1.templateSettings_call('import')

p1.mirrorSetup_verify(mode='template')
"""
store -- store current pose
load -- load stored pose
query -- query the pose
update -- this mode is if the base data has been updated
markStarterData -- this mode is for testing and will mark the base point data
            
"""
m1 = cgmMeta.cgmNode('l_eye_part')
m1 = cgmMeta.cgmNode('spine_part')
m1 = cgmMeta.cgmNode('l_arm_part')
m1 = cgmMeta.cgmNode('l_index_part')
m1.templateSettings_call('query')
m1.templateSettings_call('store')
m1.templateSettings_call('reset')
m1.templateSettings_call('update')
m1.templateSettings_call('markStarterData')

m1.get_controls('template')
m1.isTemplated()

#rigblocks need to get controls
r1 = cgmMeta.asMeta('l_eye_rigHelper')
r1.get_controls(asMeta=False)
import Red9.core.Red9_Meta as r9Meta
reload(r9Meta)
from cgm.lib import curves
from cgm.core.classes import SnapFactory as Snap
reload(Snap)
from cgm.core import cgm_Meta as cgmMeta
reload(cgmMeta)
obj = mc.ls(sl=True)[0] or False
obj = ''
objList = []

#>>> Modules
#=======================================================
i_obj = cgmMeta.cgmObject(mc.spaceLocator()[0])
i_obj = cgmMeta.cgmNode(obj)
i_obj = cgmMeta.cgmNode(mc.ls(sl=True)[0])
i_obj.getComponents()
i_obj.getComponent()
a = i_obj
i_obj.mNode
i_obj.isTransform()
Snap.go(i_obj)
mc.xform(q_object, q=True, os=True, t = True)
mc.xform(a.getComponent(), q=True, ws=True, rp=True)
mc.pointPosition(a.getComponent())
cgmMeta.cgmNode(q_object).getPosition(True)
cgmMeta.cgmNode(q_object).getPosition(False)
i_obj = cgmMeta.cgmObject(mc.spaceLocator()[0])
Snap.go('hips_anim_shape1.ep[3]',targets = q_object,orient = False,posOffset=[0,0,2],
        snapToSurface=True,softSelection=True,softSelectDistance=20)
예제 #30
0
#...okay, how bout a call created node?
o2.delete()
n2 = r9Meta.MetaClass(nodeType='network', name='toConvert')#...let's make one via meta call. It caches by default
n2.mClass = 'cgmNode'#...we'll give it another tag
n2_re = r9Meta.MetaClass(n2.mNode)#...and instantiating it
n2_re#...still gives the original


#...what if we give a node an unknown mClass?
mc.createNode('network', n = 'invalidMClass')#...let's make a null via cmd call
mc.addAttr ('invalidMClass', ln = 'mClass', dt = 'string')
mc.setAttr('invalidMClass.mClass','noIdea',type = 'string')
o3 = r9Meta.MetaClass('invalidMClass')#...and instantiating it
o3#...it's gonna reuturn as a MetaClass because it's mClass is unknown
cgmMeta.cgmNode('invalidMClass')#...I can also call it as a cgmNode with no issue because no valid mClass is set
o3.mClass = 'cgmNode'#...if i set it's mClass to a known mClass however
r9Meta.MetaClass('invalidMClass')#...it's gonna now always return as a cgmNode as it's a valid mClass value

#...so, long story short. Manually changing a node's mClass attribute is not a reliable method of changing the type it instantiates to 
#...The right way...

#r9's method
n3 = r9Meta.MetaClass(nodeType='network', name='r9Convert')#...let's make one via meta call
r9Meta.convertMClassType(n3,'cgmNode')#... This converts our node to a cgmNode type

#cgm's Method
cgmMeta.validateObjArg(n3.mNode,'MetaClass',setLogLevel = 'debug')#...this initially wont' change because our current class is a subclass of MetaClass, trust that this is a feature and not a bug
cgmMeta.validateObjArg(n3.mNode,'MetaClass',setClass = True, setLogLevel = 'debug')#...this pass will get it as we have our setClass flag on
cgmMeta.validateObjArg(n3.mNode,'cgmNode',setClass = True, setLogLevel = 'info')#...convert it back and get out of debug
예제 #31
0
	def _create(self):
	    #>> Quick links ============================================================================ 
	    d_closestInfo = self.d_closestInfo
	    
	    if self.b_attachControlLoc or not self.b_createControlLoc:
		try:#>>> Follicle ============================================================================	    
		    l_follicleInfo = nodes.createFollicleOnMesh(self.mi_targetSurface.mNode)
		    mi_follicleAttachTrans = cgmMeta.asMeta(l_follicleInfo[1],'cgmObject',setClass=True)
		    mi_follicleAttachShape = cgmMeta.asMeta(l_follicleInfo[0],'cgmNode')	    
		    
		    #> Name ----------------------------------------------------------------------------------
		    mi_follicleAttachTrans.doStore('cgmName',self.mi_obj.mNode)
		    mi_follicleAttachTrans.addAttr('cgmTypeModifier','attach',lock=True)
		    mi_follicleAttachTrans.doName()
		    
		    #>Set follicle value ---------------------------------------------------------------------
		    mi_follicleAttachShape.parameterU = d_closestInfo['normalizedU']
		    mi_follicleAttachShape.parameterV = d_closestInfo['normalizedV']
		    
		    self.mi_follicleAttachTrans = mi_follicleAttachTrans#link
		    self.mi_follicleAttachShape = mi_follicleAttachShape#link
		    self.mi_obj.connectChildNode(mi_follicleAttachTrans,"follicleAttach","targetObject")
		    self.md_return["follicleAttach"] = mi_follicleAttachTrans
		    self.md_return["follicleAttachShape"] = mi_follicleAttachShape
		except Exception,error:raise StandardError,"!Attach Follicle! | %s"%(error)
	    
	    if not self.b_createControlLoc:#If we don't have a control loc setup, we're just attaching to the surface
		try:#Groups =======================================================================================
		    mi_followGroup = self.mi_obj.doDuplicateTransform(True)
		    mi_followGroup.doStore('cgmName',self.mi_obj.mNode)
		    mi_followGroup.addAttr('cgmTypeModifier','follow',lock=True)
		    mi_followGroup.doName()	    
		    mi_followGroup.parent = mi_follicleAttachTrans
		    
		    if self.b_parentToFollowGroup:
			#raise StandardError,"shouldn't be here"		    
			self.mi_obj.parent = mi_followGroup	
			self.md_return["followGroup"] = mi_followGroup
		    else:
			#Driver loc -----------------------------------------------------------------------
			mi_driverLoc = self.mi_obj.doLoc()
			mi_driverLoc.doStore('cgmName',self.mi_obj.mNode)
			mi_driverLoc.addAttr('cgmTypeModifier','driver',lock=True)
			mi_driverLoc.doName()
			self.mi_driverLoc = mi_driverLoc
			mi_driverLoc.parent = mi_followGroup
			mi_driverLoc.visibility = False
		    
			self.md_return["driverLoc"] = mi_driverLoc
			#Constrain =====================================================================
			#mc.pointConstraint(self.mi_driverLoc.mNode, self.mi_obj.mNode, maintainOffset = True)
			#mc.orientConstraint(self.mi_driverLoc.mNode, self.mi_obj.mNode, maintainOffset = True)  
			if self.b_pointAttach:
			    mc.pointConstraint(self.mi_driverLoc.mNode, self.mi_obj.mNode, maintainOffset = True)
			else:
			    mc.parentConstraint(self.mi_driverLoc.mNode, self.mi_obj.mNode, maintainOffset = True)
			
		except Exception,error:raise StandardError,"!Groups - no control Loc setup! | %s"%(error)
		
		
	    else:#Setup control loc stuff
		try:#>>> Follicle ============================================================================
		    l_follicleInfo = nodes.createFollicleOnMesh(self.mi_targetSurface.mNode)
		    mi_follicleFollowTrans = cgmMeta.asMeta(l_follicleInfo[1],'cgmObject',setClass=True)
		    mi_follicleFollowShape = cgmMeta.asMeta(l_follicleInfo[0],'cgmNode')
		    
		    #> Name ----------------------------------------------------------------------------------
		    mi_follicleFollowTrans.doStore('cgmName',self.mi_obj.mNode)
		    mi_follicleFollowTrans.addAttr('cgmTypeModifier','follow',lock=True)
		    mi_follicleFollowTrans.doName()
		    
		    #>Set follicle value ---------------------------------------------------------------------
		    mi_follicleFollowShape.parameterU = d_closestInfo['normalizedU']
		    mi_follicleFollowShape.parameterV = d_closestInfo['normalizedV']
		    
		    self.mi_follicleFollowTrans = mi_follicleFollowTrans#link
		    self.mi_follicleFollowShape = mi_follicleFollowShape#link
		    self.md_return["follicleFollow"] = mi_follicleFollowTrans
		    self.md_return["follicleFollowShape"] = mi_follicleFollowShape
		    
		    self.mi_obj.connectChildNode(mi_follicleFollowTrans,"follicleFollow")
		    
		    #Groups =======================================================================================
		    mi_followGroup = mi_follicleFollowTrans.duplicateTransform()
		    mi_followGroup.doStore('cgmName',self.mi_obj.mNode)
		    mi_followGroup.addAttr('cgmTypeModifier','follow',lock=True)
		    mi_followGroup.doName()
		    self.mi_followGroup = mi_followGroup
		    self.mi_followGroup.parent = mi_follicleFollowTrans
		    self.md_return["followGroup"] = mi_followGroup	
		    
		except Exception,error:raise StandardError,"!Follicle - attach Loc setup! | %s"%(error)
		    
		mi_offsetGroup = self.mi_obj.duplicateTransform()
		mi_offsetGroup.doStore('cgmName',self.mi_obj.mNode)
		mi_offsetGroup.addAttr('cgmTypeModifier','offset',lock=True)
		mi_offsetGroup.doName()
		mi_offsetGroup.parent = mi_followGroup
		self.mi_offsetGroup = mi_offsetGroup 
		self.md_return["offsetGroup"] = mi_offsetGroup
		
		if self.b_attachControlLoc:mi_follicleFollowTrans.connectChildNode(mi_offsetGroup,"followOffsetGroup","follicle")
	
		mi_zeroGroup = cgmMeta.asMeta( mi_offsetGroup.doGroup(True),'cgmObject',setClass=True)	 
		mi_zeroGroup.doStore('cgmName',self.mi_obj.mNode)
		mi_zeroGroup.addAttr('cgmTypeModifier','zero',lock=True)
		mi_zeroGroup.doName()	    
		mi_zeroGroup.parent = mi_followGroup
		self.mi_zeroGroup = mi_zeroGroup
		self.md_return["zeroGroup"] = mi_zeroGroup	
		    
		#Driver loc -----------------------------------------------------------------------
		mi_driverLoc = self.mi_obj.doLoc()
		mi_driverLoc.doStore('cgmName',self.mi_obj.mNode)
		mi_driverLoc.addAttr('cgmTypeModifier','driver',lock=True)
		mi_driverLoc.doName()
		self.mi_driverLoc = mi_driverLoc
		mi_driverLoc.parent = mi_offsetGroup
		mi_driverLoc.visibility = False
		
		self.md_return["driverLoc"] = mi_driverLoc
		
		#Closest setup =====================================================================
		mi_controlLoc = self.mi_obj.doLoc()
		mi_controlLoc.doStore('cgmName',self.mi_obj.mNode)
		mi_controlLoc.addAttr('cgmTypeModifier','control',lock=True)
		mi_controlLoc.doName()
		self.mi_controlLoc = mi_controlLoc
		self.md_return["controlLoc"] = mi_controlLoc
		
		if self.b_attachControlLoc:
		    mi_group = cgmMeta.asMeta( mi_controlLoc.doGroup(),'cgmObject',setClass=True )
		    mi_group.parent = mi_follicleAttachTrans
		    
		#Create decompose node --------------------------------------------------------------
		mi_worldTranslate = cgmMeta.cgmNode(nodeType = 'decomposeMatrix')
		mi_worldTranslate.doStore('cgmName',self.mi_obj.mNode)
		mi_worldTranslate.doName()
		self.mi_worldTranslate = mi_worldTranslate
	    
		attributes.doConnectAttr("%s.worldMatrix"%(mi_controlLoc.mNode),"%s.%s"%(mi_worldTranslate.mNode,'inputMatrix'))
		
		#Create node --------------------------------------------------------------
		mi_cpos = NodeF.createNormalizedClosestPointNode(self.mi_obj,self.mi_targetSurface)
    
		attributes.doConnectAttr ((mi_cpos.mNode+'.out_uNormal'),(mi_follicleFollowShape.mNode+'.parameterU'))
		attributes.doConnectAttr  ((mi_cpos.mNode+'.out_vNormal'),(mi_follicleFollowShape.mNode+'.parameterV'))
		#attributes.doConnectAttr  ((mi_controlLoc.mNode+'.translate'),(mi_cpos.mNode+'.inPosition'))
		attributes.doConnectAttr  ((mi_worldTranslate.mNode+'.outputTranslate'),(mi_cpos.mNode+'.inPosition'))
		
		#Constrain =====================================================================
		#mc.pointConstraint(self.mi_driverLoc.mNode, self.mi_obj.mNode, maintainOffset = True)
		#mc.orientConstraint(self.mi_driverLoc.mNode, self.mi_obj.mNode, maintainOffset = True)    
		
		if self.b_pointAttach:
		    mc.pointConstraint(self.mi_driverLoc.mNode, self.mi_obj.mNode, maintainOffset = True)
		else:
		    mc.parentConstraint(self.mi_driverLoc.mNode, self.mi_obj.mNode, maintainOffset = True)
		    
		if self.b_attachControlLoc:
		    for attr in self.mi_orientation.p_string[0]:
			attributes.doConnectAttr  ((mi_controlLoc.mNode+'.t%s'%attr),(mi_offsetGroup.mNode+'.t%s'%attr))
		    
		if self.b_createUpLoc:#Make our up loc =============================================================
		    mi_upLoc = mi_zeroGroup.doLoc()
		    mi_upLoc.doStore('cgmName',self.mi_obj.mNode)
		    mi_upLoc.addAttr('cgmTypeModifier','up',lock=True)
		    mi_upLoc.doName()
		    mi_upLoc.parent = mi_zeroGroup
		    self.md_return["upLoc"] = mi_upLoc
		    mi_follicleFollowTrans.connectChildNode(mi_upLoc,"followUpLoc","follicle")
		    
		    #Move it ----------------------------------------------------------------------------------------
		    mi_upLoc.__setattr__("t%s"%self.mi_orientation.p_string[0],self.f_offset)
	    
	    if self.md_return.get("follicleFollow"):
		mi_follicleFollowTrans.connectChild(mi_driverLoc,"driverLoc","follicle")
				
	    return self.md_return
예제 #32
0
        def _buildControls_(self):
            mi_go = self._go#Rig Go instance link

            try:#Query ====================================================================================
                ml_rigJoints = self.ml_rigJoints

                mi_fkShape = self.md_rigList['fk_shape']
                mi_ikShape = self.md_rigList['ik_shape']
                mi_settingsShape = self.md_rigList['settings_shape']
                mi_eyeMoveShape = self.md_rigList['eyeMove_shape']
                str_mirrorSide = self.str_mirrorSide
            except Exception,error:raise Exception,"[Query]{%s}"%error	


            try:#>>>> FK #==================================================================	
                mi_fkShape.parent = mi_go._i_constrainNull.controlsFKNull.mNode
                i_obj = mi_fkShape
                d_buffer = mControlFactory.registerControl(i_obj,copyTransform = ml_rigJoints[0],
                                                           mirrorSide = str_mirrorSide, mirrorAxis="rotateY,rotateZ",
                                                           makeAimable=True,setRotateOrder ='zxy',typeModifier='fk') 	    
                mi_controlFK = d_buffer['instance']
                mi_controlFK.axisAim = "%s+"%mi_go._jointOrientation[0]
                mi_controlFK.axisUp= "%s+"%mi_go._jointOrientation[1]	
                mi_controlFK.axisOut= "%s+"%mi_go._jointOrientation[2]

                #We're gonna lock the aim rot
                cgmMeta.cgmAttr(mi_controlFK,'r%s'%mi_go._jointOrientation[0], keyable = False, lock=True,hidden=True)
                mi_go._i_rigNull.connectChildNode(mi_controlFK,'controlFK',"rigNull")
                self.ml_controlsAll.append(mi_controlFK)	

                attributes.doSetLockHideKeyableAttr(mi_controlFK.mNode,channels=['tx','ty','tz','sx','sy','sz','v'])				

            except Exception,error:raise Exception,"[Build fk fail]{%s}"%(error)

            try:#>>>> IK 
                #==================================================================	
                mi_ikShape.parent = mi_go._i_constrainNull.controlsIKNull.mNode	
                d_buffer = mControlFactory.registerControl(mi_ikShape,
                                                           mirrorSide = str_mirrorSide, mirrorAxis="",		                                           
                                                           typeModifier='ik',addDynParentGroup=True) 	    
                mi_ikControl = d_buffer['instance']	

                mi_go._i_rigNull.connectChildNode(mi_ikControl,'controlIK',"rigNull")
                self.ml_controlsAll.append(mi_ikControl)
                attributes.doSetLockHideKeyableAttr(mi_ikControl.mNode,channels=['sx','sy','sz','v'])				

            except Exception,error:raise Exception,"[Build ik fail]{%s}"%(error)


            try:#>>>> Settings
                #==================================================================	
                mi_settingsShape.parent = mi_go._i_constrainNull.mNode

                try:#Register the control
                    d_buffer = mControlFactory.registerControl(mi_settingsShape,
                                                               mirrorSide = str_mirrorSide, mirrorAxis="",		                                           		                                               
                                                               makeAimable=False,typeModifier='settings') 
                    mi_settings = d_buffer['instance']
                    mi_go._i_rigNull.connectChildNode(mi_settings,'settings','rigNull')
                    self.ml_controlsAll.append(mi_settings)

                    #>>> Verify out vis controls	    
                    self.mPlug_result_moduleFaceSubDriver = mi_go.build_visSubFace()		    

                except Exception,error:raise StandardError,"registration | %s"%error	

                try:#Set up some attributes
                    attributes.doSetLockHideKeyableAttr(mi_settings.mNode)
                    mPlug_FKIK = cgmMeta.cgmAttr(mi_settings.mNode,'blend_FKIK',attrType='float',lock=False,keyable=True,
                                                 minValue=0,maxValue=1.0)
                except Exception,error:raise StandardError,"attribute setup | %s"%error	

            except Exception,error:raise Exception,"[Build Settings fail]{%s}"%(error)

            try:#>>>> eyeMove #==================================================================	
                mi_eyeMoveShape.parent = mi_go._i_constrainNull.mNode

                try:#Register the control
                    d_buffer = mControlFactory.registerControl(mi_eyeMoveShape,
                                                               addMirrorAttributeBridges = [["mirrorIn","t%s"%mi_go._jointOrientation[2]],
                                                                                            ["mirrorBank","r%s"%mi_go._jointOrientation[0]]],
                                                               mirrorSide = str_mirrorSide, mirrorAxis="",		                                               
                                                               makeAimable=False,typeModifier='eyeMove') 
                    mObj = d_buffer['instance']
                    mi_go._i_rigNull.connectChildNode(mObj,'eyeMove','rigNull')
                    self.ml_controlsAll.append(mObj)
                except Exception,error:raise Exception,"[registration]{%s}"%(error)

                try:#Set up some attributes
                    attributes.doSetLockHideKeyableAttr(mObj.mNode,channels = ["r%s"%mi_go._jointOrientation[1],"r%s"%mi_go._jointOrientation[2],'v'])
                except Exception,error:raise Exception,"[Attribute setup]{%s}"%(error)

                try:#Vis Connect
                    for shp in mObj.getShapes():
                        mShp = cgmMeta.cgmNode(shp)
                        mShp.overrideEnabled = 1    
                        self.mPlug_result_moduleFaceSubDriver.doConnectOut("%s.overrideVisibility"%mShp.mNode)
                except Exception,error:raise Exception,"[subVisConnect]{%s}"%(error)


            except Exception,error:raise Exception,"[Build Settings fail]{%s}"%(error)
a = cgmRigMeta.cgmDynamicMatch(dynObject=dynObject, dynNull=dynNull)

a = cgmRigMeta.cgmDynamicMatch(dynObject=dynObject,
                               dynMatchTargets=dynMatchTargets,
                               dynSnapTargets=dynSnapTargets,
                               dynPrefix='fkik')
a = cgmRigMeta.cgmDynamicMatch(dynObject=dynObject,
                               dynNull=dynNull,
                               dynSuffix='fkik')
a.msgList_getMessage('dynDrivers', False)
a.msgList_getMessage('dynMatchTargets', False)
a.msgList_getMessage('dynSnapTargets', False)

a.doMatch(1)
a.doMatch(0)
cgmMeta.cgmNode('nurbsSphere1').dynMatchDriver_fkik.doMatch(0)
cgmMeta.cgmNode('nurbsSphere1').dynMatchDriver_fkik.doMatch(1)
a.dynDrivers[0].dynMatchAttrs = ['translate', 'rotate', 'scale']
cgmMeta.cgmNode('nurbsSphere1').fkik_dynMatchDriver.doMatch(match=0)
cgmMeta.cgmNode('nurbsSphere1').fkik_dynMatchDriver.doMatch(match=1)
cgmMeta.cgmNode('nurbsSphere1').fkik_dynMatchDriver.doSnap(0)
cgmMeta.cgmNode('nurbsSphere1').fkik_dynMatchDriver.doSnap(1)

#>>> Dynamic group
#=======================================================
parents = mc.ls(sl=True)
dParents = [u'parent1', u'parent2', u'parent3']
dynMode = 'follow'
a = cgmRigMeta.cgmDynParentGroup(dynChild='dynChild',
                                 dynParents=dParents,
                                 dynMode=dynMode)
예제 #34
0
def createWrapControlShape(targetObjects,
                           targetGeo = None,
                           latheAxis = 'z',aimAxis = 'y+',objectUp = 'y+',
                           points = 8,
                           curveDegree = 1,
                           insetMult = None,#Inset multiplier
                           posOffset = [],
                           rootOffset = [],#offset root before cast
                           rootRotate = None,
                           joinMode = False,
                           extendMode = None,
                           closedCurve = True,
                           l_specifiedRotates = None,
                           maxDistance = 1000,
                           closestInRange = True,
                           midMeshCast = False,
                           rotateBank = None,
                           joinHits = None,#keys to processed hits to see what to join
                           axisToCheck = ['x','y'],
                           ):#'segment,radial,disc' 
    """
    This function lathes an axis of an object, shoot rays out the aim axis at the provided mesh and returning hits. 
    it then uses this information to build a curve shape.
    
    :parameters:
        mesh(string) | Surface to cast at
	mi_obj(string/mObj) | our casting object
	latheAxis(str) | axis of the objec to lathe TODO: add validation
	aimAxis(str) | axis to shoot out of
	points(int) | how many points you want in the curve
	curveDegree(int) | specified degree
	minRotate(float) | let's you specify a valid range to shoot
	maxRotate(float) | let's you specify a valid range to shoot
	posOffset(vector) | transformational offset for the hit from a normalized locator at the hit. Oriented to the surface
	markHits(bool) | whether to keep the hit markers
	returnDict(bool) | whether you want all the infomation from the process.
	rotateBank (float) | let's you add a bank to the rotation object
	l_specifiedRotates(list of values) | specify where to shoot relative to an object. Ignores some other settings
	maxDistance(float) | max distance to cast rays
	closestInRange(bool) | True by default. If True, takes first hit. Else take the furthest away hit in range.

    :returns:
        Dict ------------------------------------------------------------------
	'source'(double3) |  point from which we cast
	'hit'(double3) | world space points | active during single return
	'hits'(list) | world space points | active during multi return
	'uv'(double2) | uv on surface of hit | only works for mesh surfaces
	
    :raises:
	Exception | if reached
	
    """     
    _str_funcName = "createWrapControlShape"
    log.debug(">> %s >> "%(_str_funcName) + "="*75)  
    _joinModes = []
    _extendMode = []
    
    if type(targetObjects) not in [list,tuple]:targetObjects = [targetObjects]
    targetGeo = cgmValid.objStringList(targetGeo, calledFrom = _str_funcName)


    assert type(points) is int,"Points must be int: %s"%points
    assert type(curveDegree) is int,"Points must be int: %s"%points
    assert curveDegree > 0,"Curve degree must be greater than 1: %s"%curveDegree
    if posOffset is not None and len(posOffset) and len(posOffset)!=3:raise StandardError, "posOffset must be len(3): %s | len: %s"%(posOffset,len(posOffset))
    if rootOffset is not None and len(rootOffset) and len(rootOffset)!=3:raise StandardError, "rootOffset must be len(3): %s | len: %s"%(rootOffset,len(rootOffset))
    if rootRotate is not None and len(rootRotate) and len(rootRotate)!=3:raise StandardError, "rootRotate must be len(3): %s | len: %s"%(rootRotate,len(rootRotate))
    
    if extendMode in ['loliwrap','cylinder','disc'] and insetMult is None:insetMult = 1
    for axis in ['x','y','z']:
	if axis in latheAxis.lower():latheAxis = axis
    
    log.debug("targetObjects: %s"%targetObjects)
    
    if len(aimAxis) == 2:single_aimAxis = aimAxis[0]
    else:single_aimAxis = aimAxis
    log.debug("Single aim: %s"%single_aimAxis)
    log.debug("createWrapControlShape>> midMeshCast: %s"%midMeshCast)
        
    #>> Info
    l_groupsBuffer = []
    il_curvesToCombine = []
    l_sliceReturns = []
    #Need to do more to get a better size
    
    #>> Build curves
    #=================================================================
    #> Root curve #
    log.debug("RootRotate: %s"%rootRotate)
    mi_rootLoc = cgmMeta.cgmNode(targetObjects[0]).doLoc()
    if rootOffset:
	log.debug("rootOffset: %s"%rootOffset)
	mc.move(rootOffset[0],rootOffset[1],rootOffset[2], [mi_rootLoc.mNode], r=True, rpr = True, os = True, wd = True)
    if rootRotate is not None and len(rootRotate):
	log.debug("rootRotate: %s"%rootRotate)	
	mc.rotate(rootRotate[0],rootRotate[1],rootRotate[2], [mi_rootLoc.mNode], os = True,r=True)   
	    
    #>> Root
    mi_rootLoc.doGroup()#Group to zero    
    if extendMode == 'segment':
	log.debug("segment mode. Target len: %s"%len(targetObjects[1:]))	
	try:
	    if len(targetObjects) < 2:
		log.warning("Segment build mode only works with two objects or more")    
	    else:
		if insetMult is not None:
		    rootDistanceToMove = distance.returnDistanceBetweenObjects(targetObjects[0],targetObjects[1])
		    log.debug("rootDistanceToMove: %s"%rootDistanceToMove)
		    mi_rootLoc.__setattr__('t%s'%latheAxis,rootDistanceToMove*insetMult)
		    #mi_rootLoc.tz = (rootDistanceToMove*insetMult)#Offset it
		
		#Notes -- may need to play with up object for aim snapping
		#mi_upLoc = cgmMeta.cgmNode(targetObjects[0]).doLoc()
		#mi_upLoc.doGroup()#To zero
		objectUpVector = dictionary.returnStringToVectors(objectUp)
		log.debug("objectUpVector: %s"%objectUpVector)		    
		#mi_uploc
		
		for i,obj in enumerate(targetObjects[1:]):
		    log.debug("i: %s"%i)
		    #> End Curve
		    mi_endLoc = cgmMeta.cgmNode(obj).doLoc()
		    aimVector = dictionary.returnStringToVectors(latheAxis+'-')
		    log.debug("segment aimback: %s"%aimVector)		    
		    #Snap.go(mi_endLoc.mNode,mi_rootLoc.mNode,move=False,aim=True,aimVector=aimVector,upVector=objectUpVector)
		    Snap.go(mi_endLoc.mNode,mi_rootLoc.mNode,move=False,orient=True)		    
		    mi_endLoc.doGroup()
		    
		    if i == len(targetObjects[1:])-1:
			if insetMult is not None:
			    log.debug("segment insetMult: %s"%insetMult)			    
			    distanceToMove = distance.returnDistanceBetweenObjects(targetObjects[-1],targetObjects[0])
			    log.debug("distanceToMove: %s"%distanceToMove)
			    #mi_endLoc.tz = -(distanceToMove*insetMult)#Offset it  
			    mi_endLoc.__setattr__('t%s'%latheAxis,-(distanceToMove*insetMult))
		    log.debug("segment lathe: %s"%latheAxis)
		    log.debug("segment aim: %s"%aimAxis)
		    log.debug("segment rotateBank: %s"%rotateBank)		    
		    d_endCastInfo = createMeshSliceCurve(targetGeo,mi_endLoc,midMeshCast=midMeshCast,curveDegree=curveDegree,latheAxis=latheAxis,aimAxis=aimAxis,posOffset = posOffset,points = points,returnDict=True,closedCurve = closedCurve, maxDistance = maxDistance, closestInRange=closestInRange, rotateBank=rotateBank, l_specifiedRotates = l_specifiedRotates,axisToCheck = axisToCheck)  	
		    l_sliceReturns.append(d_endCastInfo)
		    mi_end = cgmMeta.cgmObject(d_endCastInfo['curve'])
		    il_curvesToCombine.append(mi_end)
		    mc.delete(mi_endLoc.parent)#delete the loc
		    
	except StandardError,error:
	    raise StandardError,"createWrapControlShape>> segment wrap fail! | %s"%error
예제 #35
0
        def _fnc_applyData(self):
            '''
            '''    
            _targetSkin = self.mData.d_target['skin']      
            mi_skinCluster = cgmMeta.cgmNode(_targetSkin)
            skinFn = OMA.MFnSkinCluster( mi_skinCluster.mNodeMObject )
            
            #...get some api stuff
            fnSet = OM.MFnSet(skinFn.deformerSet())
            members = OM.MSelectionList()
            fnSet.getMembers(members, False)
            dagPath = OM.MDagPath()
            components = OM.MObject()
            members.getDagPath(0, dagPath, components)         
            influencePaths = OM.MDagPathArray()
            numInfluences = skinFn.influenceObjects(influencePaths)
            if numInfluences != len(self.l_jointsToUse):
                return self._FailBreak_("Influences don't match data")              
            
            #...get weights
            weights = OM.MDoubleArray()
            util = OM.MScriptUtil()
            util.createFromInt(0)
            pUInt = util.asUintPtr()
            skinFn.getWeights(dagPath, components, weights, pUInt)  
                
            numComponentsPerInfluence = weights.length() / numInfluences   
            
            influenceIndices = OM.MIntArray(numInfluences)
            for i in range(numInfluences):
                influenceIndices.set(i, i)   
                
            #...Set our weights ------------------------------------------------------------------------------------
            #weightListP = skinFn.findPlug( "weightList" )
            #weightListObj = weightListP.attribute()
            #weightsP = skinFn.findPlug( "weights" )
        
            #tmpIntArray = OM.MIntArray()
            #baseFmtStr = mi_skinCluster.mNode +'.weightList[{0}]'  #pre build this string: fewer string ops == faster-ness!
            
            self.progressBar_start(stepMaxValue=self.mData.d_target['pointCount'], 
                                   statusMessage='Calculating....', 
                                   interruptableState=False)    
            
            
            for i in range(numInfluences):
                for c in range(numComponentsPerInfluence):
                    weights.set(0.0, c*numInfluences+i)                    
            
            for vertIdx in self._d_vertToWeighting.keys():
                self.progressBar_iter(status = 'Setting {0}'.format(vertIdx))                
                _d_vert = self._d_vertToWeighting[vertIdx]#...{0:value,...}
                
                #we need to use the api to query the physical indices used
                #weightsP.selectAncestorLogicalIndex( vertIdx, weightListObj )
                #weightsP.getExistingArrayAttributeIndices( tmpIntArray )
        
                #weightFmtStr = baseFmtStr.format(vertIdx) +'.weights[{0}]'
            
                #clear out any existing skin data - and awesomely we cannot do this with the api - so we need to use a weird ass mel command
                #for n in range( tmpIntArray.length() ):
                    #mc.removeMultiInstance( weightFmtStr.format(tmpIntArray[n]) )            
            
                #at this point using the api or mel to set the data is a moot point...  we have the strings already so just use mel
                    
                for jointIdx in _d_vert.keys():
                    #self.log_info(" vtx: {0} | jnt:{1} | value:{2}".format(vertIdx,jointIdx, _d_vert[jointIdx]))
                    #self.log_info("{0} | {1}".format( weightFmtStr.format(jointIdx),_d_vert[jointIdx]))
                    #mc.setAttr( weightFmtStr.format(jointIdx), _d_vert[jointIdx] ) 
                    #weights.set(self.data['weights'][src][j], j*numInfluences+1)
                    #weights.set(_d_vert[jointIdx], vertIdx)
                    weights.set(_d_vert[jointIdx], vertIdx*numInfluences+jointIdx)#...this was a bugger to get to, 
            self.progressBar_end()
            
            skinFn.setWeights(dagPath, components, influenceIndices, weights, False)
            

            #...blendWeights
            
            #self.setBlendWeights(dagPath, components)
                    
            #...apply our settings from our skin...
            
            for k in _skinclusterAttributesToCopy:
                _value = _skinclusterAttributesToCopy[k](self.mData.d_sourceSkin[k])
                self.log_info("Setting '{0}' to {1}".format(k,_value))
                try:attributes.doSetAttr(_targetSkin,k,_value)
                except Exception,error:
                    self.log_error("{0} failed | {1}".format(k,error))
예제 #36
0
def blendChainsBy(l_jointChain1 = None,
                  l_jointChain2 = None,
                  l_blendChain = None,
                  driver = None,
                  l_constraints = ['point','orient'],
                  d_scale = {},
                  d_point = {},
                  d_parent = {},
                  d_orient = {},
                  maintainOffset = False):
    """
    :parameters:
        l_jointChain1 - First set of objects
        l_jointChain2 - Second set of objects

        l_blendChain - blend set 
        driver - Attribute to drive our blend
        l_constraints - constraints to be driven by the setup. Default is ['point','orient']

    :returns:

    :raises:
        Exception | if reached

    """
    _str_func = 'blendChainsBy'
    d_funcs = {'point':mc.pointConstraint,
               'orient':mc.orientConstraint,
               'scale':mc.scaleConstraint,
               'parent':mc.parentConstraint}

    for c in l_constraints:
        if c not in ['point','orient','scale','parent']:
            log.warning("|{0}| >> Bad constraint arg. Removing: {1}".format(_str_func, c))
            l_constraints.remove(c)

    if not l_constraints:
        raise StandardError,"Need valid constraints"


    ml_jointChain1 = cgmMeta.validateObjListArg(l_jointChain1,'cgmObject',noneValid=False)
    ml_jointChain2 = cgmMeta.validateObjListArg(l_jointChain2,'cgmObject',noneValid=False)
    ml_blendChain = cgmMeta.validateObjListArg(l_blendChain,'cgmObject',noneValid=False)
    d_driver = cgmMeta.validateAttrArg(driver,noneValid=True)
    d_blendReturn = {}
    mi_driver = False
    if d_driver:
        mi_driver = d_driver.get('mi_plug') or False
    else:
        raise ValueError,"Invalid driver: {0}".format(driver)

    if not len(ml_jointChain1) >= len(ml_blendChain) or not len(ml_jointChain2) >= len(ml_blendChain):
        raise StandardError,"Joint chains aren't equal lengths: l_jointChain1: %s | l_jointChain2: %s | l_blendChain: %s"%(len(l_jointChain1),len(l_jointChain2),len(l_blendChain))

    ml_nodes = []

    #>>> Actual meat ===========================================================
    _creates = []
    for i,i_jnt in enumerate(ml_blendChain):
        log.debug(i_jnt)
        for constraint in l_constraints:
            _d = {}
            if constraint == 'scale':
                _d = d_scale
            """
            log.debug("connectBlendChainByConstraint>>> %s || %s = %s | %s"%(ml_jointChain1[i].mNode,
                                                                             ml_jointChain2[i].mNode,
                                                                             ml_blendChain[i].mNode,
                                                                             constraint))"""
            
            _buff = d_funcs[constraint]([ml_jointChain2[i].mNode,ml_jointChain1[i].mNode],
                                                          ml_blendChain[i].mNode,
                                                          maintainOffset = maintainOffset,**_d)
            
            #func = getattr(mc,'{0}Constraint'.format(constraint))
            #_buff = func([ml_jointChain2[i].mNode,ml_jointChain1[i].mNode],
            #             ml_blendChain[i].mNode,
            #             maintainOffset = maintainOffset,**_d)
            _creates.append(_buff)
            mConst = cgmMeta.cgmNode(_buff[0])

            if constraint in ['parent','orient']:
                mConst.interpType = 2
            
            targetWeights = d_funcs[constraint](mConst.mNode,q=True, weightAliasList=True)
            if len(targetWeights)>2:
                raise StandardError,"Too many weight targets: obj: %s | weights: %s"%(i_jnt.mNode,targetWeights)

            if mi_driver:
                d_blendReturn = NODEFACTORY.createSingleBlendNetwork(mi_driver,
                                                               [mConst.mNode,'result_%s_%s'%(constraint,ml_jointChain1[i].getBaseName())],
                                                               [mConst.mNode,'result_%s_%s'%(constraint,ml_jointChain2[i].getBaseName())],
                                                               keyable=True)

                #Connect                                  
                d_blendReturn['d_result1']['mi_plug'].doConnectOut('%s.%s' % (mConst.mNode,targetWeights[0]))
                d_blendReturn['d_result2']['mi_plug'].doConnectOut('%s.%s' % (mConst.mNode,targetWeights[1]))
            ml_nodes.append(mConst)

    d_blendReturn['ml_nodes'] = ml_nodes
    #pprint.pprint(vars())
    return d_blendReturn
예제 #37
0
    def doMove(self, **kws):
        if kws: log.debug("Snap.doMove>>> kws: %s" % kws)
        if len(self.l_targets) == 1:
            #>>> Check our target
            i_target = cgmMeta.cgmNode(self.l_targets[0])
            log.debug("i_target: %s" % i_target)
            targetType = i_target.getMayaType()

            if self.b_snapComponents:
                components = self.i_obj.getComponents()
                if not components:
                    raise StandardError, "This objects has no components to snap: '%s'" % self.i_obj.getShortName(
                    )
                #>>>Progress bar
                mayaMainProgressBar = gui.doStartMayaProgressBar(
                    len(components))
                for c in components:
                    if mc.progressBar(mayaMainProgressBar,
                                      query=True,
                                      isCancelled=True):
                        break
                    mc.progressBar(mayaMainProgressBar,
                                   edit=True,
                                   status=("Wrapping '%s'" % c),
                                   step=1)

                    if targetType in ['mesh', 'nurbsSurface', 'nurbsCurve']:
                        pos = distance.returnWorldSpacePosition(c)
                        targetLoc = mc.spaceLocator()
                        mc.move(pos[0], pos[1], pos[2], targetLoc[0])

                        closestLoc = locators.locClosest([targetLoc[0]],
                                                         i_target.mNode)
                        if self._posOffset:
                            self.doOrientObjToSurface(i_target.mNode,
                                                      closestLoc)
                            mc.move(self._posOffset[0],
                                    self._posOffset[1],
                                    self._posOffset[2], [closestLoc],
                                    r=True,
                                    rpr=True,
                                    os=True,
                                    wd=True)
                        position.movePointSnap(c, closestLoc)
                        mc.delete([targetLoc[0], closestLoc])

                gui.doEndMayaProgressBar(
                    mayaMainProgressBar)  #Close out this progress bar

            else:
                pos = False
                if self.b_snaptoSurface:  #>>> If our target is surface we can use
                    if targetType in ['mesh', 'nurbsCurve', 'nurbsSurface']:
                        i_locObj = self.i_obj.doLoc()  #Get our position loc
                        i_locTarget = cgmMeta.cgmObject(
                            locators.locClosest([i_locObj.mNode],
                                                i_target.mNode))  #Loc closest
                        #i_locObj.rename('objLoc')
                        #i_locTarget.rename('targetLoc')
                        if self._posOffset:
                            try:
                                self.doOrientObjToSurface(
                                    i_target.mNode, i_locTarget.mNode)
                                mc.move(self._posOffset[0],
                                        self._posOffset[1],
                                        self._posOffset[2],
                                        [i_locTarget.mNode],
                                        r=True,
                                        rpr=True,
                                        os=True,
                                        wd=True)
                            except StandardError, error:
                                log.warn("self._posOffset failure!")
                                log.error(error)

                        pos = i_locTarget.getPosition(True)
                        i_locObj.delete()
                        i_locTarget.delete()
                elif self.b_midSurfacePos:
                    log.debug("Snap.move>>> midSurfacePos mode!")
                    if targetType not in [
                            'mesh', 'nurbsCurve', 'nurbsSurface'
                    ]:
                        log.warning(
                            "Can't do midSurfacPos on targetType: '%s'" %
                            targetType)
                        return False
                    #Get the axis info
                    axisToCheck = kws.pop('axisToCheck', False)
                    if not axisToCheck:
                        axisToCheck = []
                        up = dictionary.returnVectorToString(
                            self._upVector) or False
                        if not up:
                            raise StandardError, "SnapFactory>>> must have up vector for midSurfaceSnap: %s" % self._upVector
                        for a in ['x', 'y', 'z']:
                            if a != up[0]:
                                axisToCheck.append(a)
                        if not axisToCheck:
                            raise StandardError, "SnapFactory>>> couldn't find any axis to do"
                    #i_locObj = self.i_obj.doLoc()#Get our position loc
                    #log.debug(axisToCheck)
                    pos = RayCast.findMeshMidPointFromObject(
                        i_target.mNode,
                        self.i_obj.mNode,
                        axisToCheck=axisToCheck,
                        **kws)
                    #i_locObj.delete()

                else:
                    pos = i_target.getPosition(True)
                if pos:
                    if self.i_obj.isComponent():
                        if self.b_softSelection:  #Only need to do this if soft select is on
                            mc.softSelect(softSelectEnabled=True)
                            mc.select(self.i_obj.getComponent())
                            mc.move(pos[0], pos[1], pos[2], rpr=True)
                            mc.select(cl=True)
                        else:
                            mc.move(pos[0], pos[1], pos[2],
                                    self.i_obj.getComponent())
                    else:
                        mc.move(pos[0],
                                pos[1],
                                pos[2],
                                self.i_obj.mNode,
                                rpr=True)
예제 #38
0
def build_aimSequence(l_driven = None,
                      l_targets = None,
                      l_parents = None,
                      l_upTargets = None,
                      msgLink_masterGroup = 'masterGroup',
                      aim = [0,0,1],
                      up = [0,1,0],
                      mode = 'sequence',#sequence,singleBlend
                      upMode = 'objRotation',#objRotation,decomposeMatrix
                      upParent = [0,1,0],
                      rootTargetEnd = None,
                      rootTargetStart=None,#specify root targets by index and mObj
                      mRoot = None,#need for sequence
                      interpType = None,
                      maintainOffset = False):
    """
    This kind of setup is for setting up a blended constraint so  that obj2 in an obj1/obj2/obj3 sequence can aim forward or back as can obj3.

    :parameters:
        l_jointChain1 - First set of objects

    :returns:

    :raises:
        Exception | if reached

    """
    _str_func = 'build_aimSequence'

    ml_driven = cgmMeta.validateObjListArg(l_driven,'cgmObject')
    ml_targets = cgmMeta.validateObjListArg(l_targets,'cgmObject',noneValid=True)
    ml_parents = cgmMeta.validateObjListArg(l_parents,'cgmObject',noneValid=True)
    ml_upTargets = cgmMeta.validateObjListArg(l_upTargets,'cgmObject',noneValid=True)

    if not ml_upTargets:
        ml_upTargets = ml_parents

    axis_aim = VALID.simpleAxis(aim)
    axis_aimNeg = axis_aim.inverse
    axis_up = VALID.simpleAxis(up)

    v_aim = axis_aim.p_vector#aimVector
    v_aimNeg = axis_aimNeg.p_vector#aimVectorNegative
    v_up = axis_up.p_vector   #upVector

    #cgmGEN.func_snapShot(vars())

    if mode == 'singleBlend':
        if len(ml_targets) != 2:
            cgmGEN.func_snapShot(vars())            
            return log.error("|{0}| >> Single blend mode must have 2 targets.".format(_str_func))
        if len(ml_driven) != 1:
            cgmGEN.func_snapShot(vars())            
            return log.error("|{0}| >> Single blend mode must have 1 driven obj.".format(_str_func))
        if not ml_parents:
            cgmGEN.func_snapShot(vars())            
            return log.error("|{0}| >> Single blend mode must have handleParents.".format(_str_func))
        if len(ml_parents) != 1:
            cgmGEN.func_snapShot(vars())            
            return log.error("|{0}| >> Single blend mode must have 1 handleParent.".format(_str_func))

        mDriven = ml_driven[0]
        if not mDriven.getMessage(msgLink_masterGroup):
            log.debug("|{0}| >> No master group, creating...".format(_str_func))
            raise ValueError, log.error("|{0}| >> Add the create masterGroup setup, Josh".format(_str_func))

        mMasterGroup = mDriven.getMessage(msgLink_masterGroup,asMeta=True)[0]

        s_rootTarget = False
        s_targetForward = ml_targets[-1].mNode
        s_targetBack = ml_targets[0].mNode
        i = 0

        mMasterGroup.p_parent = ml_parents[i]
        mUpDecomp = None

        if upMode == 'decomposeMatrix':
            #Decompose matrix for parent...
            mUpDecomp = cgmMeta.cgmNode(nodeType = 'decomposeMatrix')
            mUpDecomp.rename("{0}_aimMatrix".format(ml_parents[i].p_nameBase))

            #mUpDecomp.doStore('cgmName',ml_parents[i])                
            #mUpDecomp.addAttr('cgmType','aimMatrix',attrType='string',lock=True)
            #mUpDecomp.doName()

            ATTR.connect("{0}.worldMatrix".format(ml_parents[i].mNode),"{0}.{1}".format(mUpDecomp.mNode,'inputMatrix'))
            d_worldUp = {'worldUpObject' : ml_parents[i].mNode,
                         'worldUpType' : 'vector', 'worldUpVector': [0,0,0]}
        elif upMode == 'objectRotation':
            d_worldUp = {'worldUpObject' : ml_parents[i].mNode,
                         'worldUpType' : 'objectRotation', 'worldUpVector': upParent}            
        else:
            raise ValueError, log.error("|{0}| >> Unknown upMode: {1}".format(_str_func,upMode))

        if s_targetForward:
            mAimForward = mDriven.doCreateAt()
            mAimForward.parent = mMasterGroup            
            mAimForward.doStore('cgmTypeModifier','forward')
            mAimForward.doStore('cgmType','aimer')
            mAimForward.doName()

            _const=mc.aimConstraint(s_targetForward, mAimForward.mNode, maintainOffset = True, #skip = 'z',
                                    aimVector = v_aim, upVector = v_up, **d_worldUp)            
            s_targetForward = mAimForward.mNode

            if mUpDecomp:
                ATTR.connect("%s.%s"%(mUpDecomp.mNode,"outputRotate"),"%s.%s"%(_const[0],"upVector"))                 

        else:
            s_targetForward = ml_parents[i].mNode

        if s_targetBack:
            mAimBack = mDriven.doCreateAt()
            mAimBack.parent = mMasterGroup                        
            mAimBack.doStore('cgmTypeModifier','back')
            mAimBack.doStore('cgmType','aimer')
            mAimBack.doName()

            _const = mc.aimConstraint(s_targetBack, mAimBack.mNode, maintainOffset = True, #skip = 'z',
                                      aimVector = v_aimNeg, upVector = v_up, **d_worldUp)  
            s_targetBack = mAimBack.mNode
            if mUpDecomp:
                ATTR.connect("%s.%s"%(mUpDecomp.mNode,"outputRotate"),"%s.%s"%(_const[0],"upVector"))                                     
        else:
            s_targetBack = s_rootTarget
            #ml_parents[i].mNode

        pprint.pprint([s_targetForward,s_targetBack])
        mAimGroup = mDriven.doGroup(True,asMeta=True,typeModifier = 'aim')

        mDriven.parent = False


        const = mc.orientConstraint([s_targetForward, s_targetBack], mAimGroup.mNode, maintainOffset = True)[0]


        d_blendReturn = NODEFACTORY.createSingleBlendNetwork([mDriven.mNode,'followRoot'],
                                                             [mDriven.mNode,'resultRootFollow'],
                                                             [mDriven.mNode,'resultAimFollow'],
                                                             keyable=True)

        targetWeights = mc.orientConstraint(const,q=True, weightAliasList=True,maintainOffset=True)

        #Connect                                  
        d_blendReturn['d_result1']['mi_plug'].doConnectOut('%s.%s' % (const,targetWeights[0]))
        d_blendReturn['d_result2']['mi_plug'].doConnectOut('%s.%s' % (const,targetWeights[1]))
        d_blendReturn['d_result1']['mi_plug'].p_hidden = True
        d_blendReturn['d_result2']['mi_plug'].p_hidden = True

        mDriven.parent = mAimGroup#...parent back


        mDriven.followRoot = .5        
        return True

    elif mode == 'sequence':
        """
        if len(ml_targets) != 2:
            cgmGEN.func_snapShot(vars())            
            return log.error("|{0}| >> Single blend mode must have 2 targets.".format(_str_func))
        if len(ml_driven) != 1:
            cgmGEN.func_snapShot(vars())            
            return log.error("|{0}| >> Single blend mode must have 1 driven obj.".format(_str_func))
        if not ml_parents:
            cgmGEN.func_snapShot(vars())            
            return log.error("|{0}| >> Single blend mode must have handleParents.".format(_str_func))
        if len(ml_parents) != 1:
            cgmGEN.func_snapShot(vars())            
            return log.error("|{0}| >> Single blend mode must have 1 handleParent.".format(_str_func))
        """


        for i,mDriven in enumerate(ml_driven):
            log.debug("|{0}| >> on: {1} | {2}".format(_str_func,i,mDriven))
            mUpDecomp = False
            if not mDriven.getMessage(msgLink_masterGroup):
                log.debug("|{0}| >> No master group, creating...".format(_str_func))
                raise ValueError, log.error("|{0}| >> Add the create masterGroup setup, Josh".format(_str_func))

            mDriven.masterGroup.parent = ml_parents[i]


            if upMode == 'decomposeMatrix':
                #Decompose matrix for parent...
                mUpDecomp = cgmMeta.cgmNode(nodeType = 'decomposeMatrix')
                mUpDecomp.rename("{0}_aimMatrix".format(ml_parents[i].p_nameBase))

                #mUpDecomp.doStore('cgmName',ml_parents[i])                
                #mUpDecomp.addAttr('cgmType','aimMatrix',attrType='string',lock=True)
                #mUpDecomp.doName()

                ATTR.connect("{0}.worldMatrix".format(ml_upTargets[i].mNode),"{0}.{1}".format(mUpDecomp.mNode,'inputMatrix'))
                d_worldUp = {'worldUpObject' : ml_upTargets[i].mNode,
                             'worldUpType' : 'vector', 'worldUpVector': [0,0,0]}
            elif upMode == 'objectRotation':
                d_worldUp = {'worldUpObject' : ml_upTargets[i].mNode,
                             'worldUpType' : 'objectRotation', 'worldUpVector': upParent}            
            else:
                raise ValueError, log.error("|{0}| >> Unknown upMode: {1}".format(_str_func,upMode))            



            s_rootTarget = False
            s_targetForward = False
            s_targetBack = False
            mMasterGroup = mDriven.masterGroup
            b_first = False
            if mDriven == ml_driven[0]:
                log.debug("|{0}| >> First handle: {1}".format(_str_func,mDriven))
                if len(ml_driven) <=2:
                    s_targetForward = ml_parents[-1].mNode
                else:
                    s_targetForward = ml_driven[i+1].getMessage('masterGroup')[0]

                if rootTargetStart:
                    s_rootTarget = rootTargetStart.mNode
                else:
                    s_rootTarget = mRoot.mNode
                b_first = True

            elif mDriven == ml_driven[-1]:
                log.debug("|{0}| >> Last handle: {1}".format(_str_func,mDriven))
                if rootTargetEnd:
                    s_rootTarget = rootTargetEnd.mNode
                else:
                    s_rootTarget = ml_parents[i].mNode

                s_targetBack = ml_driven[i-1].getMessage('masterGroup')[0]
            else:
                log.debug("|{0}| >> Reg handle: {1}".format(_str_func,mDriven))            
                s_targetForward = ml_driven[i+1].getMessage('masterGroup')[0]
                s_targetBack = ml_driven[i-1].getMessage('masterGroup')[0]

            #Decompose matrix for parent...
            """
            mUpDecomp = cgmMeta.cgmNode(nodeType = 'decomposeMatrix')
            mUpDecomp.doStore('cgmName',ml_parents[i])                
            mUpDecomp.addAttr('cgmType','aimMatrix',attrType='string',lock=True)
            mUpDecomp.doName()

            ATTR.connect("%s.worldMatrix"%(ml_parents[i].mNode),"%s.%s"%(mUpDecomp.mNode,'inputMatrix'))
            """
            if s_targetForward:
                mAimForward = mDriven.doCreateAt()
                mAimForward.parent = mMasterGroup            
                mAimForward.doStore('cgmTypeModifier','forward')
                mAimForward.doStore('cgmType','aimer')
                mAimForward.doName()

                _const=mc.aimConstraint(s_targetForward, mAimForward.mNode, maintainOffset = True, #skip = 'z',
                                        aimVector = v_aim, upVector = v_up,**d_worldUp)            

                s_targetForward = mAimForward.mNode

                if mUpDecomp:
                    ATTR.connect("%s.%s"%(mUpDecomp.mNode,"outputRotate"),"%s.%s"%(_const[0],"upVector"))         
            elif s_rootTarget:
                s_targetForward = s_rootTarget
            else:
                s_targetForward = ml_parents[i].mNode

            if s_targetBack:
                mAimBack = mDriven.doCreateAt()
                mAimBack.parent = mMasterGroup                        
                mAimBack.doStore('cgmTypeModifier','back')
                mAimBack.doStore('cgmType','aimer')
                mAimBack.doName()

                _const = mc.aimConstraint(s_targetBack, mAimBack.mNode, maintainOffset = True, #skip = 'z',
                                          aimVector = v_aimNeg, upVector = v_up, **d_worldUp)  

                s_targetBack = mAimBack.mNode
                if mUpDecomp:
                    ATTR.connect("%s.%s"%(mUpDecomp.mNode,"outputRotate"),"%s.%s"%(_const[0],"upVector"))                         
            else:
                s_targetBack = s_rootTarget
                #ml_parents[i].mNode

            #pprint.pprint([s_targetForward,s_targetBack])
            mAimGroup = mDriven.doGroup(True,asMeta=True,typeModifier = 'aim')

            mDriven.parent = False

            log.debug("|{0}| >> obj: {1} | {2}".format(_str_func,i,mDriven))
            log.debug("|{0}| >> forward: {1}".format(_str_func,s_targetForward))
            log.debug("|{0}| >> back: {1}".format(_str_func,s_targetBack))
            log.debug(cgmGEN._str_subLine)

            if b_first:
                const = mc.orientConstraint([s_targetBack, s_targetForward], mAimGroup.mNode, maintainOffset = True)[0]
            else:
                const = mc.orientConstraint([s_targetForward, s_targetBack], mAimGroup.mNode, maintainOffset = True)[0]


            d_blendReturn = NODEFACTORY.createSingleBlendNetwork([mDriven.mNode,'followRoot'],
                                                                 [mDriven.mNode,'resultRootFollow'],
                                                                 [mDriven.mNode,'resultAimFollow'],
                                                                 keyable=True)
            targetWeights = mc.orientConstraint(const,q=True, weightAliasList=True,maintainOffset=True)

            #Connect                                  
            d_blendReturn['d_result1']['mi_plug'].doConnectOut('%s.%s' % (const,targetWeights[0]))
            d_blendReturn['d_result2']['mi_plug'].doConnectOut('%s.%s' % (const,targetWeights[1]))
            d_blendReturn['d_result1']['mi_plug'].p_hidden = True
            d_blendReturn['d_result2']['mi_plug'].p_hidden = True

            mDriven.parent = mAimGroup#...parent back

            if interpType:
                ATTR.set(const,'interpType',interpType)
            #if mDriven in [ml_driven[0],ml_driven[-1]]:
            #    mDriven.followRoot = 1
            #else:
            mDriven.followRoot = .5
        return True

    raise ValueError,"Not done..."
    return
    for i,mObj in enumerate(ml_driven):


        return


        mObj.masterGroup.parent = ml_parents[i]
        s_rootTarget = False
        s_targetForward = False
        s_targetBack = False
        mMasterGroup = mObj.masterGroup
        b_first = False
        if mObj == ml_driven[0]:
            log.debug("|{0}| >> First handle: {1}".format(_str_func,mObj))
            if len(ml_driven) <=2:
                s_targetForward = ml_parents[-1].mNode
            else:
                s_targetForward = ml_driven[i+1].getMessage('masterGroup')[0]
            s_rootTarget = mRoot.mNode
            b_first = True

        elif mObj == ml_driven[-1]:
            log.debug("|{0}| >> Last handle: {1}".format(_str_func,mObj))
            s_rootTarget = ml_parents[i].mNode                
            s_targetBack = ml_driven[i-1].getMessage('masterGroup')[0]
        else:
            log.debug("|{0}| >> Reg handle: {1}".format(_str_func,mObj))            
            s_targetForward = ml_driven[i+1].getMessage('masterGroup')[0]
            s_targetBack = ml_driven[i-1].getMessage('masterGroup')[0]

        #Decompose matrix for parent...
        mUpDecomp = cgmMeta.cgmNode(nodeType = 'decomposeMatrix')
        mUpDecomp.doStore('cgmName',ml_parents[i])                
        mUpDecomp.addAttr('cgmType','aimMatrix',attrType='string',lock=True)
        mUpDecomp.doName()

        ATTR.connect("%s.worldMatrix"%(ml_parents[i].mNode),"%s.%s"%(mUpDecomp.mNode,'inputMatrix'))

        if s_targetForward:
            mAimForward = mObj.doCreateAt()
            mAimForward.parent = mMasterGroup            
            mAimForward.doStore('cgmTypeModifier','forward')
            mAimForward.doStore('cgmType','aimer')
            mAimForward.doName()

            _const=mc.aimConstraint(s_targetForward, mAimForward.mNode, maintainOffset = True, #skip = 'z',
                                    aimVector = [0,0,1], upVector = [1,0,0], worldUpObject = ml_parents[i].mNode,
                                    worldUpType = 'vector', worldUpVector = [0,0,0])            
            s_targetForward = mAimForward.mNode
            ATTR.connect("%s.%s"%(mUpDecomp.mNode,"outputRotate"),"%s.%s"%(_const[0],"upVector"))                 

        else:
            s_targetForward = ml_parents[i].mNode

        if s_targetBack:
            mAimBack = mObj.doCreateAt()
            mAimBack.parent = mMasterGroup                        
            mAimBack.doStore('cgmTypeModifier','back')
            mAimBack.doStore('cgmType','aimer')
            mAimBack.doName()

            _const = mc.aimConstraint(s_targetBack, mAimBack.mNode, maintainOffset = True, #skip = 'z',
                                      aimVector = [0,0,-1], upVector = [1,0,0], worldUpObject = ml_parents[i].mNode,
                                      worldUpType = 'vector', worldUpVector = [0,0,0])  
            s_targetBack = mAimBack.mNode
            ATTR.connect("%s.%s"%(mUpDecomp.mNode,"outputRotate"),"%s.%s"%(_const[0],"upVector"))                                     
        else:
            s_targetBack = s_rootTarget
            #ml_parents[i].mNode

        pprint.pprint([s_targetForward,s_targetBack])
        mAimGroup = mObj.doGroup(True,asMeta=True,typeModifier = 'aim')

        mObj.parent = False

        if b_first:
            const = mc.orientConstraint([s_targetBack, s_targetForward], mAimGroup.mNode, maintainOffset = True)[0]
        else:
            const = mc.orientConstraint([s_targetForward, s_targetBack], mAimGroup.mNode, maintainOffset = True)[0]


        d_blendReturn = NODEFACTORY.createSingleBlendNetwork([mObj.mNode,'followRoot'],
                                                             [mObj.mNode,'resultRootFollow'],
                                                             [mObj.mNode,'resultAimFollow'],
                                                             keyable=True)
        targetWeights = mc.orientConstraint(const,q=True, weightAliasList=True,maintainOffset=True)

        #Connect                                  
        d_blendReturn['d_result1']['mi_plug'].doConnectOut('%s.%s' % (const,targetWeights[0]))
        d_blendReturn['d_result2']['mi_plug'].doConnectOut('%s.%s' % (const,targetWeights[1]))
        d_blendReturn['d_result1']['mi_plug'].p_hidden = True
        d_blendReturn['d_result2']['mi_plug'].p_hidden = True

        mObj.parent = mAimGroup#...parent back

        if mObj in [ml_driven[0],ml_driven[-1]]:
            mObj.followRoot = 1
        else:
            mObj.followRoot = .5
예제 #39
0
    def __init__(self,
                 obj,
                 targets=[],
                 move=True,
                 orient=False,
                 aim=False,
                 pos=[],
                 snapToSurface=False,
                 midSurfacePos=False,
                 posOffset=False,
                 aimVector=[0, 0, 1],
                 upVector=[0, 1, 0],
                 worldUpType='scene',
                 snapComponents=False,
                 softSelection=False,
                 softSelectDistance=20,
                 mode=None,
                 **kws):
        """ 
        Asserts objects existance and that it has a transform. Then initializes. 

        Keyword arguments:
        obj(string/instance)
	targets(list) -- target objects
	
	snapToSurface -- if target is a snappable surface will try to do that
	posOffset
	snapComponents(bool) -- will try to use components if True
	aimVector(vector) -- aim vector for object
	upVector(vector) -- up vector for object (used as lathe axis for midpoint surface snap too)
	midSurfacePos(bool) -- mid point snap with a surface
	worldUpType(string) -- arg for various modes (aim, orient, etc)
	softSelection(bool) -- soft select mode for component objects only
	softSelectDistance(float) -- arg for mc.softSelect
	
	ToDo:
	1) midSurfacePos
        """
        #>>> Check our obj
        log.debug("obj: %s" % obj)
        log.debug("targets: %s" % targets)
        if issubclass(type(obj), cgmMeta.cgmNode):
            self.i_obj = obj
        else:
            i_node = cgmMeta.cgmNode(obj)
            if i_node.isComponent():
                self.i_obj = i_node
            else:
                self.i_obj = cgmMeta.cgmObject(obj)
        assert VALID.is_transform(self.i_obj.mNode) or self.i_obj.isComponent(
        ), "Not a snappable object. Not a transform: '%s" % self.i_obj.getShortName(
        )

        #>>> Pass through args
        self.b_snaptoSurface = snapToSurface
        self.b_midSurfacePos = midSurfacePos
        self.b_snapComponents = snapComponents
        self.b_softSelection = softSelection
        self.b_midSurfacePos = midSurfacePos
        self.b_aim = aim
        self._softSelectionDistance = softSelectDistance,
        self._posOffset = posOffset
        self._aimVector = aimVector
        self._upVector = upVector
        self._worldUpType = worldUpType

        #>>> Check our targets
        if targets and not type(targets) == list: targets = [targets]
        self.l_targets = []
        self.d_targetTypes = {}
        self.d_targetPositions = {}
        for t in targets:
            self.registerTarget(t)

        if not self.l_targets:
            log.error("No existing targets found")
            return

        if self.b_softSelection:
            #Should we save soft select info before changing?
            mc.softSelect(softSelectDistance=softSelectDistance)
            mc.softSelect(softSelectFalloff=0)
        log.debug("targetTypes: %s" % self.d_targetTypes)
        if move:
            log.debug("Moving")
            self.doMove(**kws)
        if orient:
            log.debug("orienting")
            self.doOrient(**kws)
        if aim:
            log.debug("orienting")
            self.doAim(**kws)
예제 #40
0
def attach_toShape(obj = None, targetShape = None, connectBy = 'parent'):
    """
    :parameters:
        obj - transform to attach
        targetShape(str) - Curve, Nurbs, Mesh
        connectBy(str)
            parent - parent to track transform
            parentGroup - parent to group and have group follow
            conPoint - just point contraint
            conPointGroup - pointConstrain group
            conPointOrientGroup - point/orient constrain group
            conParentGroup - parent Constrain group
            None - just the tracker nodes
    :returns:
        resulting dat

    """   
    try:
        _str_func = 'attach_toShape'
        mObj = cgmMeta.validateObjArg(obj,'cgmObject')
        targetShape = VALID.mNodeString(targetShape)
        log.debug("targetShape: {0}".format(targetShape))

        #Get our data...
        d_closest = DIST.get_closest_point_data(targetShape,
                                                mObj.mNode)

        log.debug("|{0}| >> jnt: {1} | {2}".format(_str_func,mObj.mNode, d_closest))
        #pprint.pprint(d_closest)

        if d_closest['type'] in ['mesh','nurbsSurface']:
            log.debug("|{0}| >> Follicle mode...".format(_str_func))
            _shape = SHAPES.get_nonintermediate(d_closest['shape'] )
            log.debug("_shape: {0}".format(_shape))

            l_follicleInfo = NODES.createFollicleOnMesh( _shape )

            i_follicleTrans = cgmMeta.asMeta(l_follicleInfo[1],'cgmObject',setClass=True)
            i_follicleShape = cgmMeta.asMeta(l_follicleInfo[0],'cgmNode')

            #> Name...
            i_follicleTrans.doStore('cgmName',mObj)
            i_follicleTrans.doStore('cgmTypeModifier','surfaceTrack')            
            i_follicleTrans.doName()
            _trackTransform = i_follicleTrans.mNode

            #>Set follicle value...
            if d_closest['type'] == 'mesh':
                i_follicleShape.parameterU = d_closest['parameterU']
                i_follicleShape.parameterV = d_closest['parameterV']
            else:
                i_follicleShape.parameterU = d_closest['normalizedU']
                i_follicleShape.parameterV = d_closest['normalizedV']
            _res = [i_follicleTrans.mNode, i_follicleShape.mNode]
        else:
            log.debug("|{0}| >> Curve mode...".format(_str_func))
            #d_returnBuff = distance.returnNearestPointOnCurveInfo(obj,crv)
            _shape = SHAPES.get_nonintermediate(d_closest['shape'] )            
            mPOCI = cgmMeta.cgmNode(nodeType = 'pointOnCurveInfo')
            mc.connectAttr("%s.worldSpace"%_shape,"%s.inputCurve"%mPOCI.mNode)
            mPOCI.parameter = d_closest['parameter']

            mTrack = mObj.doCreateAt()
            mTrack.doStore('cgmName',mObj)
            mTrack.doStore('cgmType','surfaceTrack')
            mTrack.doName()

            _trackTransform = mTrack.mNode

            mc.connectAttr("%s.position"%mPOCI.mNode,"%s.t"%_trackTransform)
            mPOCI.doStore('cgmName',mObj)            
            mPOCI.doName()            
            _res = [mTrack.mNode, mPOCI.mNode]

        if connectBy is None:
            return _res 

        elif connectBy == 'parent':
            mObj.p_parent = _trackTransform
            return _res
        elif connectBy == 'conPoint':
            mc.pointConstraint(_trackTransform, mObj.mNode,maintainOffset = True)
            return _res
        elif connectBy == 'conParent':
            mc.parentConstraint(_trackTransform, mObj.mNode,maintainOffset = True)
            return _res        
        elif connectBy == 'parentGroup':
            mGroup = mObj.doGroup(asMeta=True)
            #_grp = TRANS.group_me(obj,True)
            #TRANS.parent_set(_grp,_trackTransform)
            mGroup.p_parent = _trackTransform
            return _res + [mGroup.mNode]        
        elif connectBy == 'conPointGroup':
            mLoc = mObj.doLoc()            
            mLoc.p_parent = _trackTransform
            mGroup = mObj.doGroup(asMeta=True)
            mc.pointConstraint(mLoc.mNode,mGroup.mNode)
            return _res + [mGroup.mNode]        

        elif connectBy == 'conPointOrientGroup':
            mLoc = mObj.doLoc()            
            mLoc.p_parent = _trackTransform
            mGroup = mObj.doGroup(asMeta=True)

            mc.pointConstraint(mLoc.mNode,mGroup.mNode)
            mc.orientConstraint(mLoc.mNode,mGroup.mNode)
            return _res + [mGroup.mNode]        

        elif connectBy == 'conParentGroup':
            mLoc = mObj.doLoc()            
            mLoc.p_parent = _trackTransform
            mGroup = mObj.doGroup(asMeta=True)
            mc.parentConstraint(mLoc.mNode,mGroup.mNode)
            return _res + [mGroup.mNode]        

        else:
            raise NotImplementedError,"|{0}| >>invalid connectBy: {1}".format(_str_func,connectBy)  

        #pprint.pprint(vars())
    except Exception,err:cgmGEN.cgmExceptCB(Exception,err)
예제 #41
0
    
    
#RENAME -------------------------------------------------------------------------
#def sceneCleanBrazen():
ml_joints = cgmMeta.validateObjListArg(mc.ls(type='joint'))
for mJnt in ml_joints:
    if not mJnt.getShapes():
        if mJnt.p_nameShort.endswith('jnt'):
            mJnt.rename(mJnt.p_nameBase.replace('jnt','JNT'))
            #print (mJnt.p_nameBase + '>>' + mJnt.p_nameBase.replace('jnt','JNT'))
        else:
            mJnt.rename(mJnt.p_nameBase + '_JNT')
            #print (mJnt.p_nameBase + '>>' + mJnt.p_nameBase + '_JNT')
    

cgmMeta.cgmNode('DragonLord_animSet').select()
ml_CON = cgmMeta.validateObjListArg(mc.ls(sl=1))
for mCon in ml_CON:
    if cgmMeta.VALID.is_transform(mCon.mNode):
        if mCon.p_nameShort.endswith('_anim'):
            #mCon.rename(mCon.p_nameBase.replace('anim','CON'))
            print (mCon.p_nameBase + '>>' + mCon.p_nameBase.replace('anim','CON'))        
        elif mCon.p_nameShort.endswith('_jnt'):
            #mCon.rename(mCon.p_nameBase.replace('jnt','CON'))
            print (mCon.p_nameBase + '>>' + mCon.p_nameBase.replace('jnt','CON'))          
        else:
            print ('>>> ????? ' + mCon.p_nameBase)
#l/r
ml_trans = cgmMeta.validateObjListArg(mc.ls(type='transform'))
for mObj in ml_trans:
    _new = mObj.p_nameBase    
예제 #42
0
o2.delete()
n2 = r9Meta.MetaClass(
    nodeType='network',
    name='toConvert')  #...let's make one via meta call. It caches by default
n2.mClass = 'cgmNode'  #...we'll give it another tag
n2_re = r9Meta.MetaClass(n2.mNode)  #...and instantiating it
n2_re  #...still gives the original

#...what if we give a node an unknown mClass?
mc.createNode('network', n='invalidMClass')  #...let's make a null via cmd call
mc.addAttr('invalidMClass', ln='mClass', dt='string')
mc.setAttr('invalidMClass.mClass', 'noIdea', type='string')
o3 = r9Meta.MetaClass('invalidMClass')  #...and instantiating it
o3  #...it's gonna reuturn as a MetaClass because it's mClass is unknown
cgmMeta.cgmNode(
    'invalidMClass'
)  #...I can also call it as a cgmNode with no issue because no valid mClass is set
o3.mClass = 'cgmNode'  #...if i set it's mClass to a known mClass however
r9Meta.MetaClass(
    'invalidMClass'
)  #...it's gonna now always return as a cgmNode as it's a valid mClass value

#...so, long story short. Manually changing a node's mClass attribute is not a reliable method of changing the type it instantiates to
#...The right way...

#r9's method
n3 = r9Meta.MetaClass(nodeType='network',
                      name='r9Convert')  #...let's make one via meta call
r9Meta.convertMClassType(
    n3, 'cgmNode')  #... This converts our node to a cgmNode type
예제 #43
0
objList = []
orientation = ['xyz']
orientation[1]
cgmMeta.cgmObject(mc.ls(sl=True)[0]).doName()

mi_obj = cgmMeta.cgmObject(obj)
cgmMeta.validateObjArg(mi_obj,cgmMeta.cgmObject)
cgmMeta.validateObjArg(mi_obj)

cgmMeta.validateAttrArg([mi_obj,'tx'])
cgmMeta.validateAttrArg([obj,'tx'])
cgmMeta.validateAttrArg("%s.tx"%obj)


from cgm.core import cgm_Meta as cgmMeta
n1 = cgmMeta.cgmNode(nodeType='transform')#This will create a cgmNode instance of a new transform node




@cgmGeneral.Timer
def check(arg):
    issubclass(arg,cgmMeta.cgmNode):
        return True
    

cgmMeta.validateObjArg(obj)

#>>> verifyAttrDict
d_test = {'string':'string','messageSimple':'messageSimple','bool':'bool','enum':'left:right:center','float':'float'}
cgmMeta.cgmNode(name = 'test').verifyAttrDict(d_test,lock = True)
예제 #44
0
#One of our calls to store info is doStore
mi_catcherObj.doStore('objNoMessage',mi_catchMeObj.mNode,overideMessageCheck = True)#It's gonna just store a string, no message....
mi_catcherObj.doStore('objNoMessage',mi_catchMeObj.mNode,overideMessageCheck = False)#Now it's a message...woot!
#So maya can do that, what if you wanted to do something neater like say, store an attribute
mi_catcherObj.doStore('objTX',"%s.tx"%mi_catchMeObj.mNode)#It's gonna just store a string, no message....
mi_catchMeObj.tx = 4#our attribute changed. That's because, this storage method stores on a compatible attribute format
#That's great and all, but we were talking about messages...
mi_catcherObj.getMessage('objTX')# we get the attribute, neato...
mi_catcherObj.getMessageAsMeta('objTX')# we get the attribute, neato...cgmAttr for the win
#implementing attr setup to msgLists is on the ToDO list
#==============================================================================================

#>>Component use ==============================================================================
#We'll make a shphere and buffer that...
l_sphereReturn = mc.sphere(nsp  = 4, name = 'MySphere')
mi_sphere = cgmMeta.cgmNode(l_sphereReturn[0])#We'll meta the sphere object
mi_sphere.mNode#Just like an mNode, but what if we wanna instance a component...
mi_cv = cgmMeta.cgmNode("%s.cv[3][0]"%mi_sphere.mNode)#metaNode a cv
mi_cv.mNode#We get the shape back
mi_cv.getComponent()#We get the component
mi_cv.isComponent()#Yup
mi_sphere.isComponent()#Nope...it's a sphere
mi_sphere.getComponents('cv')#List of cv's
mi_sphere.getPosition()#Get our position,arg is world space or not, default is worldspace(True)
mi_cv.getPosition()#Get the position of the cv
mi_cv.getTransform()#Ger the transform of the component
#==============================================================================================

#>>Properties =================================================================================
mi_sphere.p_nameBase#name string along
mi_sphere.p_nameLong#long name form
예제 #45
0
    def doMove(self,**kws):
	if kws:log.debug("Snap.doMove>>> kws: %s"%kws)
	if len(self.l_targets) == 1:
	    #>>> Check our target	    
	    i_target = cgmMeta.cgmNode( self.l_targets[0] )
	    log.debug("i_target: %s"%i_target)
	    targetType = i_target.getMayaType()	    

	    if self.b_snapComponents:
		components = self.i_obj.getComponents()
		if not components:raise StandardError,"This objects has no components to snap: '%s'"%self.i_obj.getShortName()
		#>>>Progress bar
		mayaMainProgressBar = gui.doStartMayaProgressBar(len(components))		
		for c in components:
		    if mc.progressBar(mayaMainProgressBar, query=True, isCancelled=True ) :
			break
		    mc.progressBar(mayaMainProgressBar, edit=True, status = ("Wrapping '%s'"%c), step=1)
		    
		    if targetType in ['mesh','nurbsSurface','nurbsCurve']:
			pos = distance.returnWorldSpacePosition(c)
			targetLoc = mc.spaceLocator()
			mc.move (pos[0],pos[1],pos[2], targetLoc[0])

			closestLoc = locators.locClosest([targetLoc[0]],i_target.mNode)
			if self._posOffset:
			    self.doOrientObjToSurface(i_target.mNode,closestLoc)
			    mc.move (self._posOffset[0],self._posOffset[1],self._posOffset[2], [closestLoc], r=True, rpr = True, os = True, wd = True)								
			position.movePointSnap(c,closestLoc)
			mc.delete([targetLoc[0],closestLoc])
			
		gui.doEndMayaProgressBar(mayaMainProgressBar)#Close out this progress bar    
		
	    else:
		pos = False
		if self.b_snaptoSurface:#>>> If our target is surface we can use
		    if targetType in ['mesh','nurbsCurve','nurbsSurface']:
			i_locObj = self.i_obj.doLoc()#Get our position loc
			i_locTarget = cgmMeta.cgmObject( locators.locClosest([i_locObj.mNode],i_target.mNode) )#Loc closest
			#i_locObj.rename('objLoc')
			#i_locTarget.rename('targetLoc')
			if self._posOffset:
			    try:
				self.doOrientObjToSurface(i_target.mNode,i_locTarget.mNode)
				mc.move (self._posOffset[0],self._posOffset[1],self._posOffset[2], [i_locTarget.mNode], r=True, rpr = True, os = True, wd = True)								
			    except StandardError,error:
				log.warn("self._posOffset failure!")
				log.error(error)
			
			pos = i_locTarget.getPosition(True)
			i_locObj.delete()
			i_locTarget.delete()
		elif self.b_midSurfacePos:
		    log.debug("Snap.move>>> midSurfacePos mode!")
		    if targetType not in ['mesh','nurbsCurve','nurbsSurface']:
			log.warning("Can't do midSurfacPos on targetType: '%s'"%targetType)
			return False
		    #Get the axis info
		    axisToCheck = kws.pop('axisToCheck',False)
		    if not axisToCheck:
			axisToCheck = []		    
			up = dictionary.returnVectorToString(self._upVector) or False
			if not up:
			    raise StandardError,"SnapFactory>>> must have up vector for midSurfaceSnap: %s"%self._upVector
			for a in ['x','y','z']:
			    if a != up[0]:
				axisToCheck.append(a)
			if not axisToCheck:
			    raise StandardError,"SnapFactory>>> couldn't find any axis to do"
		    #i_locObj = self.i_obj.doLoc()#Get our position loc		
		    #log.debug(axisToCheck)
		    pos = RayCast.findMeshMidPointFromObject(i_target.mNode, self.i_obj.mNode, axisToCheck=axisToCheck,**kws)
		    #i_locObj.delete()
		    
		else:
		    pos = i_target.getPosition(True)	    
		if pos:
		    if self.i_obj.isComponent():
			if self.b_softSelection:#Only need to do this if soft select is on
			    mc.softSelect(softSelectEnabled = True)
			    mc.select(self.i_obj.getComponent())
			    mc.move (pos[0],pos[1],pos[2],rpr=True)
			    mc.select(cl=True)
			else:
			    mc.move (pos[0],pos[1],pos[2], self.i_obj.getComponent())	    		    
		    else:
			mc.move (pos[0],pos[1],pos[2], self.i_obj.mNode, rpr=True)	    
예제 #46
0
closedCurve = False
mShapeCast.createMeshSliceCurve(geo,
                                l_targetObjects[0],
                                closedCurve=closedCurve,
                                l_specifiedRotates=l_specifiedRotates,
                                curveDegree=curveDegree,
                                posOffset=[0, 0, 1.5],
                                points=8,
                                returnDict=True,
                                latheAxis='z',
                                aimAxis='y+')
l_pos = []
for curve in mc.ls(sl=True):
    l_buffer = []
    for cv in mc.ls("%s.cv[*]" % curve, flatten=True):
        l_buffer.append(cgmMeta.cgmNode(cv).getPosition())
    l_pos.append(l_buffer)
l_pos
for i, pos in enumerate(l_pos[0]):
    mc.curve(degree=1, ep=[pos, l_pos[1][i]])

#>>> Wrap shape
#=======================================================
reload(mShapeCast)
l_targetObjects = mc.ls(sl=True)
log.debug(l_targetObjects)
geo = 'Morphy_Body_GEO'
mShapeCast.createWrapControlShape(l_targetObjects,
                                  geo,
                                  posOffset=posOffset,
                                  points=points,
예제 #47
0
    def __init__(self,obj,targets = [],move = True, orient = False, aim = False, pos = [],
                 snapToSurface = False, midSurfacePos = False,
                 posOffset = False,
                 aimVector = [0,0,1],upVector = [0,1,0], worldUpType = 'scene',
                 snapComponents = False,softSelection = False, softSelectDistance = 20,                 
                 mode = None,**kws):
        """ 
        Asserts objects existance and that it has a transform. Then initializes. 

        Keyword arguments:
        obj(string/instance)
	targets(list) -- target objects
	
	snapToSurface -- if target is a snappable surface will try to do that
	posOffset
	snapComponents(bool) -- will try to use components if True
	aimVector(vector) -- aim vector for object
	upVector(vector) -- up vector for object (used as lathe axis for midpoint surface snap too)
	midSurfacePos(bool) -- mid point snap with a surface
	worldUpType(string) -- arg for various modes (aim, orient, etc)
	softSelection(bool) -- soft select mode for component objects only
	softSelectDistance(float) -- arg for mc.softSelect
	
	ToDo:
	1) midSurfacePos
        """
	#>>> Check our obj
	log.debug("obj: %s"%obj)
	log.debug("targets: %s"%targets)
	if issubclass(type(obj),cgmMeta.cgmNode):
	    self.i_obj = obj
	else:
	    i_node = cgmMeta.cgmNode(obj)
	    if i_node.isComponent():
		self.i_obj = i_node		
	    else :
		self.i_obj = cgmMeta.cgmObject(obj)
	assert self.i_obj.isTransform() or self.i_obj.isComponent(),"Not a snappable object. Not a transform: '%s"%self.i_obj.getShortName()      
	
	#>>> Pass through args
	self.b_snaptoSurface = snapToSurface
	self.b_midSurfacePos = midSurfacePos	
	self.b_snapComponents = snapComponents
	self.b_softSelection = softSelection
	self.b_midSurfacePos = midSurfacePos
	self.b_aim = aim		
	self._softSelectionDistance = softSelectDistance,
	self._posOffset = posOffset
	self._aimVector = aimVector
	self._upVector = upVector
	self._worldUpType = worldUpType
	
	#>>> Check our targets
	if targets and not type(targets)==list:targets=[targets]
	self.l_targets = []	
	self.d_targetTypes = {}
	self.d_targetPositions = {}
	for t in targets:
	    self.registerTarget(t)
	    
	if not self.l_targets:
	    log.error("No existing targets found")
	    return
	
	if self.b_softSelection:
	    #Should we save soft select info before changing?
	    mc.softSelect(softSelectDistance = softSelectDistance)
	    mc.softSelect(softSelectFalloff = 0)	    
	log.debug("targetTypes: %s"%self.d_targetTypes)
	if move:
	    log.debug("Moving")
	    self.doMove(**kws)
	if orient:
	    log.debug("orienting")
	    self.doOrient(**kws)
	if aim:
	    log.debug("orienting")
	    self.doAim(**kws)	    
예제 #48
0
def build_rig(goInstance = None):
    class fncWrap(modUtils.rigStep):
	def __init__(self,goInstance = None):
	    super(fncWrap, self).__init__(goInstance)
	    self._str_funcName = 'build_rig(%s)'%self.d_kws['goInstance']._strShortName	
	    self.__dataBind__()
	    self.l_funcSteps = [{'step':'Build NOT BROKEN UP YET','call':self.build}]	
	    #=================================================================
	    
	def build(self):#================================================================================   	
		    
	    try:#>>>Get data
		orientation = self._go._jointOrientation or modules.returnSettingsData('jointOrientation')
		mi_moduleParent = False
		if self._go._mi_module.getMessage('moduleParent'):
		    mi_moduleParent = self._go._mi_module.moduleParent
		    
		mi_controlIK = self._go._i_rigNull.controlIK
		ml_controlsFK =  self._go._i_rigNull.msgList_get('controlsFK')    
		ml_rigJoints = self._go._i_rigNull.msgList_get('rigJoints')
		ml_blendJoints = self._go._i_rigNull.msgList_get('blendJoints')
		mi_settings = self._go._i_rigNull.settings
		
		log.info("mi_controlIK: %s"%mi_controlIK.getShortName())
		log.info("ml_controlsFK: %s"%[o.getShortName() for o in ml_controlsFK])
		log.info("mi_settings: %s"%mi_settings.getShortName())
		
		log.info("ml_rigJoints: %s"%[o.getShortName() for o in ml_rigJoints])
		log.info("ml_blendJoints: %s"%[o.getShortName() for o in ml_blendJoints])
		
		ml_segmentHandleChains = self._go._get_segmentHandleChains()
		ml_segmentChains = self._go._get_segmentChains()
		ml_influenceChains = self._go._get_influenceChains()	
		
		aimVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[0])
		upVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[1]) 
		
		#Build our contrain to pool
		l_constrainTargetJoints = []
		"""
		for ml_chain in ml_segmentChains:
		    l_constrainTargetJoints.extend([i_jnt.mNode for i_jnt in ml_chain[:-1]])
		l_constrainTargetJoints.extend([i_jnt.mNode for i_jnt in ml_blendJoints[-2:]])
		"""
		if not l_constrainTargetJoints:
		    l_constrainTargetJoints = [i_jnt.mNode for i_jnt in ml_blendJoints]
		    
		for i_jnt in ml_blendJoints:
		    attributes.doSetLockHideKeyableAttr(i_jnt.mNode,lock=True, visible=True, keyable=False)
		    i_jnt.radius = 0#This is how we can hide joints without hiding them since we have children we want to ride along
		    i_jnt.drawStyle = 2
		    
		for i_jnt in ml_controlsFK:
		    i_jnt.radius = 0#This is how we can hide joints without hiding them since we have children we want to ride along
		    i_jnt.drawStyle = 2		    
		    
		#Set group lockks
		for mCtrl in self._go._i_rigNull.msgList_get('controlsAll'):
		    try:mCtrl._setControlGroupLocks()	
		    except Exception,error:log.error("%s _setControlGroupLocks failed on object: %s"%(self._str_reportStart,mCtrl.p_nameShort))
	    	    
	    except Exception,error:
		log.error("finger.build_rig>> Gather data fail!")
		raise Exception,error
	    

	    #Dynamic parent groups
	    #====================================================================================
	    try:#>>>> IK
		ml_fingerDynParents = []
		#Build our dynamic groups
		"""
		1)wrist
		2)fk root
		3)...
		4)world
		"""
		if mi_moduleParent:
		    mi_blendEndJoint = mi_moduleParent.rigNull.msgList_get('blendJoints')[-1]	    
		    mi_parentRigNull = mi_moduleParent.rigNull
		    if mi_moduleParent:
			mi_parentRigNull = mi_moduleParent.rigNull
			buffer = mi_parentRigNull.msgList_get('moduleJoints')
			if buffer:
			    ml_fingerDynParents.append( buffer[-1])	
			
		ml_fingerDynParents.append( ml_controlsFK[0])	
			
		mi_spine = self._go._mi_module.modulePuppet.getModuleFromDict(moduleType= ['torso','spine'])
		if mi_spine:
		    log.info("spine found: %s"%mi_spine)	    
		    mi_spineRigNull = mi_spine.rigNull
		    ml_fingerDynParents.append( mi_spineRigNull.handleIK )	    
		    ml_fingerDynParents.append( mi_spineRigNull.cog )
		    ml_fingerDynParents.append( mi_spineRigNull.hips )	    
		    
		ml_fingerDynParents.append(self._go._i_masterControl)
		if mi_controlIK.getMessage('spacePivots'):
		    ml_fingerDynParents.extend(mi_controlIK.msgList_get('spacePivots',asMeta = True))	
		log.info("%s.build_rig>>> Dynamic parents to add: %s"%(self._go._strShortName,[i_obj.getShortName() for i_obj in ml_fingerDynParents]))
		
	    
		#Add our parents
		i_dynGroup = mi_controlIK.dynParentGroup
		log.info("Dyn group at setup: %s"%i_dynGroup)
		i_dynGroup.dynMode = 0
		
		for o in ml_fingerDynParents:
		    i_dynGroup.addDynParent(o)
		i_dynGroup.rebuild()
		
	    except Exception,error:
		log.error("finger.build_rig>> finger ik dynamic parent setup fail!")
		raise Exception,error
	    
            self._go.collect_worldDynDrivers()#...collect world dyn drivers
	
	    #Make some connections
	    #====================================================================================
	    
	    #Parent and constrain joints
	    #====================================================================================
	    ml_rigJoints[0].parent = self._go._i_deformNull.mNode#shoulder
	    #ml_rigJoints[-1].parent = self._go._i_deformNull.mNode#wrist
	
	    #For each of our rig joints, find the closest constraint target joint
	    log.info("targetJoints: %s"%l_constrainTargetJoints)
	    l_rigJoints = [i_jnt.mNode for i_jnt in ml_rigJoints]
	    for i,i_jnt in enumerate(ml_rigJoints):
		#Don't try scale constraints in here, they're not viable
		log.info("Checking: '%s'"%i_jnt.getShortName())
		attachJoint = distance.returnClosestObject(i_jnt.mNode,l_constrainTargetJoints)
		log.info("'%s'<< drives <<'%s'"%(i_jnt.getShortName(),cgmMeta.cgmNode(attachJoint).getShortName()))
		pntConstBuffer = mc.pointConstraint(attachJoint,i_jnt.mNode,maintainOffset=False,weight=1)
		orConstBuffer = mc.orientConstraint(attachJoint,i_jnt.mNode,maintainOffset=False,weight=1)
		mc.connectAttr((attachJoint+'.s'),(i_jnt.mNode+'.s'))
	     
	    #Setup finger scaling
	    #==================================================================================== 
	    #Parent deform Null to last blend parent
	    if mi_moduleParent:
		mi_blendEndJoint = mi_moduleParent.rigNull.msgList_get('blendJoints')[-1]
		mi_parentBlendPlug = cgmMeta.cgmAttr(mi_blendEndJoint,'scale')
		self._go._i_deformNull.parent = mi_blendEndJoint.mNode
	    
		#connect blend joint scale to the finger blend joints
		for i_jnt in ml_blendJoints:
		    mi_parentBlendPlug.doConnectOut("%s.scale"%i_jnt.mNode)
		    
		#intercept world scale on finger IK and add in the blend wrist scale
		mPlug_moduleMasterScale = cgmMeta.cgmAttr(self._go._i_rigNull,'masterScale',value = 1.0,defaultValue=1.0)
		mPlug_globalScale = cgmMeta.cgmAttr(self._go._i_masterControl.mNode,'scaleY')
		mPlug_globalScale.doConnectOut(mPlug_moduleMasterScale)
		NodeF.argsToNodes("%s = %s * %s.sy"%(mPlug_moduleMasterScale.p_combinedShortName,
			                             mPlug_globalScale.p_combinedShortName,
			                             mi_blendEndJoint.p_nameShort)).doBuild()
	    
	    try:#Vis Network, lock and hide
		#====================================================================================
		#Segment handles need to lock
		for ml_chain in ml_segmentHandleChains:
		    for i_obj in ml_chain:
			attributes.doSetLockHideKeyableAttr(i_obj.mNode,lock=True,
			                                    visible=False, keyable=False,
			                                    channels=['s%s'%orientation[1],
			                                              's%s'%orientation[2]])
			
		attributes.doSetLockHideKeyableAttr(mi_settings.mNode,lock=True,
		                                    visible=False, keyable=False)
		attributes.doSetLockHideKeyableAttr(ml_blendJoints[0].mNode,lock=True,
		                                    visible=True, keyable=False)
		
		for i,mCtrl in enumerate(ml_controlsFK):
		    l_attrs = ['sx','sy','sz','v']
		    if i != 0:
			l_attrs.extend(['tx','ty','tz'])
			
		    attributes.doSetLockHideKeyableAttr(mCtrl.mNode,channels=l_attrs,
		                                        lock=True, visible=False, keyable=False)
		    

		
		attributes.doSetLockHideKeyableAttr(mi_controlIK.mNode,channels=['sx','sy','sz','v'],
	                                            lock=True, visible=False, keyable=False)	    
	    except Exception,error:
		raise Exception,"Lock and hide fail! | {0}".format(error)