Esempio n. 1
0
        def _mirrorAttributeBridges_(self):
            addForwardBack = self.d_kws['addForwardBack']

            if addForwardBack:
                mPlug_forwardBackDriver = cgmMeta.cgmAttr(self.mi_control,
                                                          "forwardBack",
                                                          attrType='float',
                                                          keyable=True)
                try:
                    mPlug_forwardBackDriven = cgmMeta.validateAttrArg(
                        [self.mi_control, addForwardBack])['mi_plug']
                except Exception, error:
                    raise StandardError, "push pull driver | %s" % (error)

                if self.str_mirrorSide.lower() == 'right':
                    arg_forwardBack = "%s = -%s" % (
                        mPlug_forwardBackDriven.p_combinedShortName,
                        mPlug_forwardBackDriver.p_combinedShortName)
                else:
                    arg_forwardBack = "%s = %s" % (
                        mPlug_forwardBackDriven.p_combinedShortName,
                        mPlug_forwardBackDriver.p_combinedShortName)

                mPlug_forwardBackDriven.p_locked = True
                mPlug_forwardBackDriven.p_hidden = True
                mPlug_forwardBackDriven.p_keyable = False
                NodeF.argsToNodes(arg_forwardBack).doBuild()
def setUpPickerGroups(control=None, atr=None, groups=[]):
    import cgm.core.classes.NodeFactory as nodeF
    import cgm.core.cgm_Meta as cgmMeta
    import cgm.core.lib.attribute_utils as ATTR

    mGroups = cgmMeta.validateObjListArg(groups, 'cgmObject')
    mControl = cgmMeta.validateObjArg(control, 'cgmObject')

    ATTR.add(mControl.mNode,
             atr,
             'enum',
             enumOptions=[mObj.p_nameBase for mObj in mGroups])
    import cgm.core.classes.NodeFactory as nodeF
    nodeF.build_conditionNetworkFromGroup(shortName,
                                          chooseAttr=i,
                                          controlObject="{0}.{1}".format(
                                              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
Esempio n. 3
0
    def test_a_condition(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.condResult = if %s.ty == 3:5 else 1" % (str_obj, str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()

        _ml_nodes = d_return.get('ml_nodes')
        _ml_outPlugs = d_return.get('ml_outPlugs')
        _plugCall = mc.listConnections("%s.condResult" % (mObj.mNode),
                                       plugs=True,
                                       scn=True)
        _combinedName = _ml_outPlugs[0].p_combinedName

        self.assertIsNotNone(_ml_outPlugs)
        self.assertEqual(len(_ml_outPlugs), 1)
        self.assertIsNotNone(_ml_nodes)
        self.assertEqual(len(_ml_nodes), 1)

        self.assertEqual(_ml_nodes[0].getMayaType(), 'condition')

        self.assertEqual(_ml_nodes[0].operation, 0)
        self.assertEqual(str(_plugCall[0]), _combinedName)

        mObj.ty = 3
        self.assertEqual(mObj.condResult, 5)
        mObj.ty = 1
        self.assertEqual(mObj.condResult, 1)

        return
Esempio n. 4
0
    def test_c_simpleInvsersion(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.simpleInversion = -%s.tx" % (str_obj, str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(d_return['ml_outPlugs'])
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 1, "Only one node should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_outPlugs'][0].obj.getMayaType(
        ) == 'multiplyDivide', "%s != pma" % d_return['ml_outPlugs'][
            0].obj.getMayaType()
        plugCall = mc.listConnections("%s.simpleInversion" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        assert d_return['ml_nodes'][0].operation == 1, "Operation not 1"
        combinedName = d_return['ml_outPlugs'][0].p_combinedName
        assert str(plugCall[0]) == d_return['ml_outPlugs'][
            0].p_combinedName, "Connections don't match: %s | %s" % (
                plugCall[0], combinedName)
        assert mObj.simpleInversion == -mObj.tx, "Inversion doesn't match"
Esempio n. 5
0
    def test_g_sum(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        mObj.tx = 1
        mObj.ty = 2
        mObj.tz = 3
        arg = "%s.sumResult1 = %s.tx - %s.ty - %s.tz" % (str_obj, str_obj,
                                                         str_obj, str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(d_return['ml_outPlugs'])
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 1, "Only one node should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_outPlugs'][0].obj.getMayaType(
        ) == 'plusMinusAverage', "%s != pma" % d_return['ml_outPlugs'][
            0].obj.getMayaType()
        plugCall = mc.listConnections("%s.sumResult1" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        assert d_return['ml_nodes'][0].operation == 2, "Operation not 2"
        combinedName = d_return['ml_outPlugs'][0].p_combinedName
        assert str(plugCall[0]) == d_return['ml_outPlugs'][
            0].p_combinedName, "Connections don't match: %s | %s" % (
                plugCall[0], combinedName)
        assert mObj.sumResult1 == mObj.tx - mObj.ty - mObj.tz, "Sum doesn't match"
Esempio n. 6
0
    def test_i_range(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        mObj.tz = 5
        arg = "%s.setRangeResult = setRange(0,1,0,10,%s.tz" % (str_obj,
                                                               str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(d_return['ml_outPlugs'])
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 1, "Only one node should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_outPlugs'][0].obj.getMayaType(
        ) == 'setRange', "%s != setRange" % d_return['ml_outPlugs'][
            0].obj.getMayaType()
        plugCall = mc.listConnections("%s.setRangeResult" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        combinedName = d_return['ml_outPlugs'][0].p_combinedName
        assert str(plugCall[0]) == d_return['ml_outPlugs'][
            0].p_combinedName, "Connections don't match: %s | %s" % (
                plugCall[0], combinedName)
        assert mObj.setRangeResult == .5, "Value 1 fail"
        mObj.tz = 10
        assert mObj.setRangeResult == 1, "Value 2 fail"
Esempio n. 7
0
    def holder(self):
        mObj = cgmMeta.cgmObject(name='awesomeArgObj_loc')
        str_obj = mObj.getShortName()

        try:  #Mult inversion
            arg = "%s.inverseMultThree = 3 * -%s.tx" % (str_obj, str_obj)
            d_return = NODEFACTORY.argsToNodes(arg).doBuild()
            log.debug(d_return['ml_outPlugs'])
            assert d_return['l_nodes'], "Should have made something"
            assert len(
                d_return['l_nodes']
            ) == 2, "Only two nodes should be made. Found: %s" % len(
                d_return['l_nodes'])
            assert d_return['ml_nodes'][0].getMayaType(
            ) == 'multiplyDivide', "%s != md" % d_return['ml_nodes'][
                0].getMayaType()
            assert d_return['ml_nodes'][1].getMayaType(
            ) == 'multiplyDivide', "%s != md" % d_return['ml_nodes'][
                1].getMayaType()

            plugCall = mc.listConnections("%s.inverseMultThree" % (mObj.mNode),
                                          plugs=True,
                                          scn=True)
            assert d_return['ml_nodes'][-1].operation == 1, "Operation not 1"
            combinedName = d_return['ml_outPlugs'][-1].p_combinedName
            assert str(plugCall[0]) == d_return['ml_outPlugs'][
                -1].p_combinedName, "Connections don't match: %s | %s" % (
                    plugCall[0], combinedName)
            assert mObj.inverseMultThree == 3 * -mObj.tx, "Inversion doesn't match"

        except StandardError, error:
            log.error("test_argsToNodes>>Inversion mult 3 Failure! '%s'" %
                      (error))
            raise StandardError, error
Esempio n. 8
0
    def test_e_directConnect(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.directConnect = %s.ty" % (str_obj, str_obj)
        NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(
            mc.listConnections("%s.directConnect" % str_obj,
                               source=True,
                               scn=True))
        plugCall = mc.listConnections("%s.directConnect" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        assert plugCall[0] == '%s.translateY' % mObj.getShortName(), log.error(
            "Direct connect failed. Plug call:{0}".format(plugCall))
        def _mirrorAttributeBridges_(self):	    		
            addForwardBack = self.d_kws['addForwardBack']

            if addForwardBack:
                mPlug_forwardBackDriver = cgmMeta.cgmAttr(self.mi_control,"forwardBack",attrType = 'float',keyable=True)
                try:
                    mPlug_forwardBackDriven = cgmMeta.validateAttrArg([self.mi_control,addForwardBack])['mi_plug']
                except Exception,error:raise StandardError,"push pull driver | %s"%(error)

                if self.str_mirrorSide.lower() == 'right':
                    arg_forwardBack = "%s = -%s"%(mPlug_forwardBackDriven.p_combinedShortName,
                                                  mPlug_forwardBackDriver.p_combinedShortName)		    
                else:
                    arg_forwardBack = "%s = %s"%(mPlug_forwardBackDriven.p_combinedShortName,
                                                 mPlug_forwardBackDriver.p_combinedShortName)

                mPlug_forwardBackDriven.p_locked = True
                mPlug_forwardBackDriven.p_hidden = True
                mPlug_forwardBackDriven.p_keyable = False		
                NodeF.argsToNodes(arg_forwardBack).doBuild()

            if self._addMirrorAttributeBridges:
                for l_bridge in self._addMirrorAttributeBridges:
                    _attrName = cgmValid.stringArg(l_bridge[0])
                    _attrToBridge = cgmValid.stringArg(l_bridge[1])
                    if not self.mi_control.hasAttr(_attrToBridge):
                        raise StandardError,"['%s' lacks the bridge attr '%s']"%(self.mi_control.p_nameShort,_attrToBridge)

                    mPlug_attrBridgeDriver = cgmMeta.cgmAttr(self.mi_control,_attrName,attrType = 'float',keyable=True)
                    try:
                        mPlug_attrBridgeDriven = cgmMeta.validateAttrArg([self.mi_control,_attrToBridge])['mi_plug']
                    except Exception,error:raise StandardError,"[validate control attribute bridge attr]{%s}"%(error)

                    if self.str_mirrorSide.lower() == 'right':
                        arg_attributeBridge = "%s = -%s"%(mPlug_attrBridgeDriven.p_combinedShortName,
                                                          mPlug_attrBridgeDriver.p_combinedShortName)		    
                    else:
                        arg_attributeBridge = "%s = %s"%(mPlug_attrBridgeDriven.p_combinedShortName,
                                                         mPlug_attrBridgeDriver.p_combinedShortName)

                    mPlug_attrBridgeDriven.p_locked = True
                    mPlug_attrBridgeDriven.p_hidden = True
                    mPlug_attrBridgeDriven.p_keyable = False		
                    NodeF.argsToNodes(arg_attributeBridge).doBuild()
Esempio n. 10
0
        def _mirrorAttributeBridges_(self):	    		
            addForwardBack = self.d_kws['addForwardBack']

            if addForwardBack:
                mPlug_forwardBackDriver = cgmMeta.cgmAttr(self.mi_control,"forwardBack",attrType = 'float',keyable=True)
                try:
                    mPlug_forwardBackDriven = cgmMeta.validateAttrArg([self.mi_control,addForwardBack])['mi_plug']
                except Exception,error:raise StandardError,"push pull driver | %s"%(error)

                if self.str_mirrorSide.lower() == 'right':
                    arg_forwardBack = "%s = -%s"%(mPlug_forwardBackDriven.p_combinedShortName,
                                                  mPlug_forwardBackDriver.p_combinedShortName)		    
                else:
                    arg_forwardBack = "%s = %s"%(mPlug_forwardBackDriven.p_combinedShortName,
                                                 mPlug_forwardBackDriver.p_combinedShortName)

                mPlug_forwardBackDriven.p_locked = True
                mPlug_forwardBackDriven.p_hidden = True
                mPlug_forwardBackDriven.p_keyable = False		
                NodeF.argsToNodes(arg_forwardBack).doBuild()

            if self._addMirrorAttributeBridges:
                for l_bridge in self._addMirrorAttributeBridges:
                    _attrName = VALID.stringArg(l_bridge[0])
                    _attrToBridge = VALID.stringArg(l_bridge[1])
                    if not self.mi_control.hasAttr(_attrToBridge):
                        raise StandardError,"['%s' lacks the bridge attr '%s']"%(self.mi_control.p_nameShort,_attrToBridge)

                    mPlug_attrBridgeDriver = cgmMeta.cgmAttr(self.mi_control,_attrName,attrType = 'float',keyable=True)
                    try:
                        mPlug_attrBridgeDriven = cgmMeta.validateAttrArg([self.mi_control,_attrToBridge])['mi_plug']
                    except Exception,error:raise StandardError,"[validate control attribute bridge attr]{%s}"%(error)

                    if self.str_mirrorSide.lower() == 'right':
                        arg_attributeBridge = "%s = -%s"%(mPlug_attrBridgeDriven.p_combinedShortName,
                                                          mPlug_attrBridgeDriver.p_combinedShortName)		    
                    else:
                        arg_attributeBridge = "%s = %s"%(mPlug_attrBridgeDriven.p_combinedShortName,
                                                         mPlug_attrBridgeDriver.p_combinedShortName)

                    mPlug_attrBridgeDriven.p_locked = True
                    mPlug_attrBridgeDriven.p_hidden = True
                    mPlug_attrBridgeDriven.p_keyable = False		
                    NodeF.argsToNodes(arg_attributeBridge).doBuild()
Esempio n. 11
0
    def test_d_average(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.sumAverage1 = 4 >< 4 >< 4" % (str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 1, "Only one node should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_outPlugs'][0].obj.getMayaType(
        ) == 'plusMinusAverage', "%s != pma" % d_return['ml_outPlugs'][
            0].obj.getMayaType()
        assert d_return['ml_nodes'][0].operation == 3, "Operation not 3"

        assert mObj.sumAverage1 == 4, "Average is wrong: 4 != %s" % mObj.sumAverage1
Esempio n. 12
0
                                              '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'))
                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)
Esempio n. 13
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
Esempio n. 14
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
Esempio n. 15
0
def ribbon_seal(
        driven1=None,
        driven2=None,
        influences1=None,
        influences2=None,
        msgDriver=None,  #...msgLink on joint to a driver group for constaint purposes
        extendEnds=False,
        loftAxis='z',
        orientation='zyx',
        secondaryAxis='y+',
        baseName=None,
        baseName1=None,
        baseName2=None,
        connectBy='constraint',
        sectionSpans=1,
        settingsControl=None,
        specialMode=None,
        sealSplit=False,
        sealDriver1=None,
        sealDriver2=None,
        sealDriverMid=None,
        sealName1='left',
        sealName2='right',
        sealNameMid='center',
        maxValue=10.0,
        moduleInstance=None,
        parentGutsTo=None):

    try:
        _str_func = 'ribbon_seal'

        ml_rigObjectsToConnect = []
        md_drivers = {}
        md_base = {}
        md_seal = {}
        md_blend = {}
        md_follicles = {}
        md_follicleShapes = {}

        d_dat = {1: {}, 2: {}}

        if msgDriver:
            ml_missingDrivers = []

        def check_msgDriver(mObj):
            mDriver = mObj.getMessageAsMeta(msgDriver)
            if mDriver:
                md_drivers[mObj] = mDriver
            else:
                log.error("|{0}| >> Missing driver: {1}".format(
                    _str_func, mObj))
                ml_missingDrivers.append(mObj)
                return False

        #>>> Verify ===================================================================================
        log.debug("|{0}| >> driven1 [Check]...".format(_str_func))
        d_dat[1]['driven'] = cgmMeta.validateObjListArg(driven1,
                                                        mType='cgmObject',
                                                        mayaType=['joint'],
                                                        noneValid=False)
        log.debug("|{0}| >> driven2 [Check]...".format(_str_func))
        d_dat[2]['driven'] = cgmMeta.validateObjListArg(driven2,
                                                        mType='cgmObject',
                                                        mayaType=['joint'],
                                                        noneValid=False)

        #Check our msgDrivers -----------------------------------------------------------
        if msgDriver:
            log.debug("|{0}| >> msgDriver [Check]...".format(_str_func))
            for mObj in d_dat[1]['driven'] + d_dat[2]['driven']:
                if mObj not in ml_missingDrivers:
                    check_msgDriver(mObj)
            if ml_missingDrivers:
                raise ValueError, "Missing drivers. See errors."
            log.debug("|{0}| >> msgDriver [Pass]...".format(_str_func))

        d_dat[1]['int_driven'] = len(d_dat[1]['driven'])
        d_dat[2]['int_driven'] = len(d_dat[2]['driven'])

        log.debug("|{0}| >> Driven lengths   {1} | {2}".format(
            _str_func, d_dat[1]['int_driven'], d_dat[2]['int_driven']))

        log.debug("|{0}| >> influences1 [Check]...".format(_str_func))
        d_dat[1]['mInfluences'] = cgmMeta.validateObjListArg(
            influences1,
            mType='cgmObject',
            mayaType=['joint'],
            noneValid=False)

        log.debug("|{0}| >> influences2 [Check]...".format(_str_func))
        d_dat[2]['mInfluences'] = cgmMeta.validateObjListArg(
            influences2,
            mType='cgmObject',
            mayaType=['joint'],
            noneValid=False)

        d_dat[1]['int_influences'] = len(d_dat[1]['mInfluences'])
        d_dat[2]['int_influences'] = len(d_dat[2]['mInfluences'])

        log.debug("|{0}| >> Influence lengths   {1} | {2}".format(
            _str_func, d_dat[1]['int_influences'], d_dat[2]['mInfluences']))

        mi_mayaOrientation = VALID.simpleOrientation(orientation)
        str_orientation = mi_mayaOrientation.p_string
        str_secondaryAxis = VALID.stringArg(secondaryAxis, noneValid=True)

        if specialMode and specialMode not in [
                'noStartEnd', 'endsToInfluences'
        ]:
            raise ValueError, "Unknown special mode: {0}".format(specialMode)

        #module -----------------------------------------------------------------------------------------------
        mModule = cgmMeta.validateObjArg(moduleInstance, noneValid=True)
        #try:mModule.isModule()
        #except:mModule = False

        mi_rigNull = False
        if mModule:
            log.debug("|{0}| >> mModule [Check]...".format(_str_func))
            mi_rigNull = mModule.rigNull
            if str_baseName is None:
                str_baseName = mModule.getPartNameBase()  #Get part base name
        if not baseName: baseName = 'testRibbonSeal'
        if not baseName1: baseName1 = 'ribbon1'
        if not baseName2: baseName2 = 'ribbon2'

        d_check = {
            'driven1': d_dat[1]['int_driven'],
            'driven2': d_dat[2]['int_driven']
        }

        for k, i in d_check.iteritems():
            if i < 3:
                raise ValueError, "needs at least three driven. Found : {0} | {1}".format(
                    k, i)

        log.debug("|{0}| >> Group [Check]...".format(_str_func))
        if parentGutsTo is None:
            mGroup = cgmMeta.cgmObject(name='newgroup')
            mGroup.addAttr('cgmName', str(baseName), lock=True)
            mGroup.addAttr('cgmTypeModifier', 'segmentStuff', lock=True)
            mGroup.doName()
        else:
            mGroup = cgmMeta.validateObjArg(parentGutsTo, 'cgmObject', False)

        if mModule:
            mGroup.parent = mModule.rigNull

        #Good way to verify an instance list? #validate orientation
        #> axis -------------------------------------------------------------
        """
        axis_aim = VALID.simpleAxis("{0}+".format(str_orientation[0]))
        axis_aimNeg = axis_aim.inverse
        axis_up = VALID.simpleAxis("{0}+".format(str_orientation [1]))
        axis_out = VALID.simpleAxis("{0}+".format(str_orientation [2]))
    
        v_aim = axis_aim.p_vector#aimVector
        v_aimNeg = axis_aimNeg.p_vector#aimVectorNegative
        v_up = axis_up.p_vector   #upVector
        v_out = axis_out.p_vector
        
        str_up = axis_up.p_string
        
        loftAxis2 = False
        #Figure out our loft axis stuff
        if loftAxis not in  orientation:
            _lower_loftAxis = loftAxis.lower()
            if _lower_loftAxis in ['out','up']:
                if _lower_loftAxis == 'out':
                    loftAxis = str_orientation[2]
                else:
                    loftAxis = str_orientation[1]
            else:
                raise ValueError,"Not sure what to do with loftAxis: {0}".format(loftAxis)
        """

        outChannel = str_orientation[2]  #outChannel
        upChannel = str_orientation[1]
        #upChannel = '{0}up'.format(str_orientation[1])#upChannel

        #>>> Ribbon Surface ============================================================================
        log.debug("|{0}| >> Ribbons generating...".format(_str_func))

        l_surfaceReturn1 = IK.ribbon_createSurface(d_dat[1]['driven'],
                                                   loftAxis, sectionSpans,
                                                   extendEnds)

        d_dat[1]['mSurf'] = cgmMeta.validateObjArg(l_surfaceReturn1[0],
                                                   'cgmObject',
                                                   setClass=True)
        d_dat[1]['mSurf'].addAttr('cgmName',
                                  str(baseName1),
                                  attrType='string',
                                  lock=True)
        d_dat[1]['mSurf'].addAttr('cgmType',
                                  'controlSurface',
                                  attrType='string',
                                  lock=True)
        d_dat[1]['mSurf'].doName()

        l_surfaceReturn2 = IK.ribbon_createSurface(d_dat[2]['driven'],
                                                   loftAxis, sectionSpans,
                                                   extendEnds)
        d_dat[2]['mSurf'] = cgmMeta.validateObjArg(l_surfaceReturn1[0],
                                                   'cgmObject',
                                                   setClass=True)
        d_dat[2]['mSurf'].addAttr('cgmName',
                                  str(baseName2),
                                  attrType='string',
                                  lock=True)
        d_dat[2]['mSurf'].addAttr('cgmType',
                                  'controlSurface',
                                  attrType='string',
                                  lock=True)
        d_dat[2]['mSurf'].doName()

        log.debug("d_dat[1]['mSurf']: {0}".format(d_dat[1]['mSurf']))
        log.debug("d_dat[2]['mSurf']: {0}".format(d_dat[2]['mSurf']))

        ml_toConnect = []
        ml_toConnect.extend([d_dat[1]['mSurf'], d_dat[2]['mSurf']])

        #Special Mode =================================================================================
        if specialMode in ['noStartEnd', 'endsToInfluences']:
            log.debug(
                "|{0}| >> Special Mode: {1}".format(_str_func, specialMode) +
                cgmGEN._str_subLine)

            if specialMode == 'endsToInfluences':
                d_special = {
                    '1start': {
                        'mObj': d_dat[1]['driven'][0],
                        'mDriver': d_dat[1]['mInfluences'][0]
                    },
                    '1end': {
                        'mObj': d_dat[1]['driven'][-1],
                        'mDriver': d_dat[1]['mInfluences'][-1]
                    },
                    '2start': {
                        'mObj': d_dat[2]['driven'][0],
                        'mDriver': d_dat[2]['mInfluences'][0]
                    },
                    '2end': {
                        'mObj': d_dat[2]['driven'][-1],
                        'mDriver': d_dat[2]['mInfluences'][-1]
                    }
                }

                for n, dat in d_special.iteritems():
                    mObj = dat['mObj']
                    mDriven = md_drivers[mObj]
                    mDriver = dat['mDriver']
                    log.debug("|{0}| >> {1} | Driver: {2}".format(
                        _str_func, i, mDriven))

                    _const = mc.parentConstraint([mDriver.mNode],
                                                 mDriven.mNode,
                                                 maintainOffset=True)[0]
                    ATTR.set(_const, 'interpType', 2)

            d_dat[1]['driven'] = d_dat[1]['driven'][1:-1]
            d_dat[2]['driven'] = d_dat[2]['driven'][1:-1]
            driven1 = driven1[1:-1]
            driven2 = driven2[1:-1]

        #>>> Setup our Attributes ================================================================
        log.debug("|{0}| >> Settings...".format(_str_func))
        if settingsControl:
            mSettings = cgmMeta.validateObjArg(settingsControl, 'cgmObject')
        else:
            mSettings = d_dat[1]['mSurf']

        mPlug_sealHeight = cgmMeta.cgmAttr(mSettings.mNode,
                                           'sealHeight',
                                           attrType='float',
                                           lock=False,
                                           keyable=True)
        mPlug_sealHeight.doDefault(.5)
        mPlug_sealHeight.value = .5

        #>>> Setup blend results --------------------------------------------------------------------
        if sealSplit:
            d_split = split_blends(
                driven1,  #d_dat[1]['driven'],
                driven2,  #d_dat[2]['driven'],
                sealDriver1,
                sealDriver2,
                sealDriverMid,
                nameSeal1=sealName1,
                nameSeal2=sealName2,
                nameSealMid=sealNameMid,
                settingsControl=mSettings,
                maxValue=maxValue)
            for k, d in d_split.iteritems():
                d_dat[k]['mPlugs'] = d['mPlugs']

        else:
            mPlug_seal = cgmMeta.cgmAttr(mSettings.mNode,
                                         'seal',
                                         attrType='float',
                                         lock=False,
                                         keyable=True)

            mPlug_sealOn = cgmMeta.cgmAttr(mSettings,
                                           'result_sealOn',
                                           attrType='float',
                                           defaultValue=0,
                                           keyable=False,
                                           lock=True,
                                           hidden=False)

            mPlug_sealOff = cgmMeta.cgmAttr(mSettings,
                                            'result_sealOff',
                                            attrType='float',
                                            defaultValue=0,
                                            keyable=False,
                                            lock=True,
                                            hidden=False)

            NODEFACTORY.createSingleBlendNetwork(mPlug_seal.p_combinedName,
                                                 mPlug_sealOn.p_combinedName,
                                                 mPlug_sealOff.p_combinedName)

            d_dat[1]['mPlug_sealOn'] = mPlug_sealOn
            d_dat[1]['mPlug_sealOff'] = mPlug_sealOff
            d_dat[2]['mPlug_sealOn'] = mPlug_sealOn
            d_dat[2]['mPlug_sealOff'] = mPlug_sealOff

        mPlug_FavorOneMe = cgmMeta.cgmAttr(mSettings,
                                           'result_sealOneMe',
                                           attrType='float',
                                           defaultValue=0,
                                           keyable=False,
                                           lock=True,
                                           hidden=False)
        mPlug_FavorOneThee = cgmMeta.cgmAttr(mSettings,
                                             'result_sealOneThee',
                                             attrType='float',
                                             defaultValue=0,
                                             keyable=False,
                                             lock=True,
                                             hidden=False)
        mPlug_FavorTwoMe = cgmMeta.cgmAttr(mSettings,
                                           'result_sealTwoMe',
                                           attrType='float',
                                           defaultValue=0,
                                           keyable=False,
                                           lock=True,
                                           hidden=False)
        mPlug_FavorTwoThee = cgmMeta.cgmAttr(mSettings,
                                             'result_sealTwoThee',
                                             attrType='float',
                                             defaultValue=0,
                                             keyable=False,
                                             lock=True,
                                             hidden=False)

        NODEFACTORY.createSingleBlendNetwork(mPlug_sealHeight.p_combinedName,
                                             mPlug_FavorOneThee.p_combinedName,
                                             mPlug_FavorOneMe.p_combinedName)
        NODEFACTORY.createSingleBlendNetwork(mPlug_sealHeight.p_combinedName,
                                             mPlug_FavorTwoThee.p_combinedName,
                                             mPlug_FavorTwoMe.p_combinedName)

        d_dat[1]['mPlug_me'] = mPlug_FavorOneMe
        d_dat[1]['mPlug_thee'] = mPlug_FavorOneThee
        d_dat[2]['mPlug_me'] = mPlug_FavorTwoMe
        d_dat[2]['mPlug_thee'] = mPlug_FavorTwoThee
        """
        b_attachToInfluences = False
        if attachEndsToInfluences:
            log.debug("|{0}| >> attachEndsToInfluences flag. Checking...".format(_str_func))
            if influences and len(influences) > 1:
                b_attachToInfluences = True
            log.debug("|{0}| >> b_attachToInfluences: {1}".format(_str_func,b_attachToInfluences))
            """

        #>>> Skinning ============================================================================
        log.debug("|{0}| >> Skinning Ribbons...".format(_str_func))

        for idx, dat in d_dat.iteritems():
            max_influences = 2
            mode_tighten = 'twoBlend'
            blendLength = int(dat['int_driven'] / 2)
            blendMin = 2
            _hardLength = 2

            if extendEnds:
                blendMin = 4
                _hardLength = 4
                mode_tighten = None

            if dat['int_influences'] > 2:
                mode_tighten = None
                #blendLength = int(int_lenInfluences/2)
                max_influences = MATH.Clamp(blendLength, 2, 4)
                blendLength = MATH.Clamp(int(dat['int_influences'] / 2), 2, 6)

            if dat['int_influences'] == dat['int_driven']:
                _hardLength = 3
            #Tighten the weights...

            mSkinCluster = cgmMeta.validateObjArg(mc.skinCluster(
                [mObj.mNode for mObj in dat['mInfluences']],
                dat['mSurf'].mNode,
                tsb=True,
                maximumInfluences=max_influences,
                normalizeWeights=1,
                dropoffRate=5.0),
                                                  'cgmNode',
                                                  setClass=True)

            mSkinCluster.doStore('cgmName', dat['mSurf'])
            mSkinCluster.doName()

            #Tighten the weights...
            RIGSKIN.surface_tightenEnds(dat['mSurf'].mNode,
                                        hardLength=_hardLength,
                                        blendLength=blendLength,
                                        mode=mode_tighten)

        #>>> Meat ============================================================================
        ml_processed = []
        for idx, dat in d_dat.iteritems():
            idx_seal = 1
            if idx == 1:
                idx_seal = 2
            dat_seal = d_dat[idx_seal]
            log.debug("|{0}| >> Building [{1}] | seal idx: {2} |".format(
                _str_func, idx, idx_seal) + cgmGEN._str_subLine)

            mSurfBase = dat['mSurf']
            mSurfSeal = dat_seal['mSurf']

            for i, mObj in enumerate(dat['driven']):
                if mObj in ml_processed:
                    log.debug("|{0}| >> Already completed: {1}".format(
                        _str_func, mObj))
                    continue
                ml_processed.append(mObj)
                log.debug("|{0}| >> {1} | Driven: {2}".format(
                    _str_func, i, mObj))
                mDriven = md_drivers[mObj]
                log.debug("|{0}| >> {1} | Driver: {2}".format(
                    _str_func, i, mDriven))

                log.debug("|{0}| >> Create track drivers...".format(_str_func))
                mTrackBase = mDriven.doCreateAt(setClass=True)
                mTrackBase.doStore('cgmName', mObj)
                mTrackSeal = mTrackBase.doDuplicate()
                mTrackBlend = mTrackBase.doDuplicate()

                mTrackSeal.doStore('cgmType', 'trackSeal')
                mTrackBase.doStore('cgmType', 'trackBase')
                mTrackBlend.doStore('cgmType', 'trackBlend')

                for mTrack in mTrackBase, mTrackSeal, mTrackBlend:
                    mTrack.doName()

                log.debug("|{0}| >> Attach drivers...".format(_str_func))

                d_tmp = {
                    'base': {
                        'mSurf': mSurfBase,
                        'mTrack': mTrackBase
                    },
                    'seal': {
                        'mSurf': mSurfSeal,
                        'mTrack': mTrackSeal
                    },
                }

                for n, d in d_tmp.iteritems():
                    mTrack = d['mTrack']
                    mSurf = d['mSurf']

                    _res = RIGCONSTRAINTS.attach_toShape(
                        mTrack.mNode, mSurf.mNode, 'parent')
                    mFollicle = _res[-1][
                        'mFollicle']  #cgmMeta.asMeta(follicle)
                    mFollShape = _res[-1][
                        'mFollicleShape']  #cgmMeta.asMeta(shape)

                    md_follicleShapes[mObj] = mFollShape
                    md_follicles[mObj] = mFollicle

                    mFollicle.parent = mGroup.mNode

                    if mModule:  #if we have a module, connect vis
                        mFollicle.overrideEnabled = 1
                        cgmMeta.cgmAttr(
                            mModule.rigNull.mNode, 'gutsVis',
                            lock=False).doConnectOut(
                                "%s.%s" %
                                (mFollicle.mNode, 'overrideVisibility'))
                        cgmMeta.cgmAttr(
                            mModule.rigNull.mNode, 'gutsLock',
                            lock=False).doConnectOut(
                                "%s.%s" %
                                (mFollicle.mNode, 'overrideDisplayType'))

                #Blend point --------------------------------------------------------------------
                _const = mc.parentConstraint(
                    [mTrackBase.mNode, mTrackSeal.mNode], mTrackBlend.mNode)[0]
                ATTR.set(_const, 'interpType', 2)

                targetWeights = mc.parentConstraint(_const,
                                                    q=True,
                                                    weightAliasList=True)

                #Connect
                if idx == 1:
                    dat['mPlug_thee'].doConnectOut('%s.%s' %
                                                   (_const, targetWeights[0]))
                    dat['mPlug_me'].doConnectOut('%s.%s' %
                                                 (_const, targetWeights[1]))
                else:
                    dat['mPlug_me'].doConnectOut('%s.%s' %
                                                 (_const, targetWeights[0]))
                    dat['mPlug_thee'].doConnectOut('%s.%s' %
                                                   (_const, targetWeights[1]))

                #seal --------------------------------------------------------------------
                _const = mc.parentConstraint(
                    [mTrackBase.mNode, mTrackBlend.mNode], mDriven.mNode)[0]
                ATTR.set(_const, 'interpType', 2)

                targetWeights = mc.parentConstraint(_const,
                                                    q=True,
                                                    weightAliasList=True)

                if sealSplit:
                    dat['mPlugs']['off'][i].doConnectOut(
                        '%s.%s' % (_const, targetWeights[0]))
                    dat['mPlugs']['on'][i].doConnectOut(
                        '%s.%s' % (_const, targetWeights[1]))
                else:
                    dat['mPlug_sealOff'].doConnectOut(
                        '%s.%s' % (_const, targetWeights[0]))
                    dat['mPlug_sealOn'].doConnectOut(
                        '%s.%s' % (_const, targetWeights[1]))

            log.debug("|{0}| >> Blend drivers...".format(_str_func))
        """
        #Simple contrain
        if b_attachToInfluences and mJnt in [ml_joints[0],ml_joints[-1]]:
            if mJnt == ml_joints[0]:
                mUse = ml_influences[0]
            else:
                mUse = ml_influences[-1]
            mc.parentConstraint([mUse.mNode], mDriven.mNode, maintainOffset=True)
        else:
            mc.parentConstraint([mDriver.mNode], mDriven.mNode, maintainOffset=True)
        """

        #pprint.pprint(d_dat)
        return

    except Exception, err:
        cgmGEN.cgmExceptCB(Exception, err, msg=vars())
rUtils.IKHandle_addSplineIKTwist(handle,False)

#>>> Playing with spline Ik twist setup
#=======================================================
#root twist mode off
#Playing with a better spline IK twist setup, ramp multiplier works
handle = 'ikHandle1'
mPlug_start = cgmMeta.cgmAttr(handle,'twistStart',attrType='float',keyable=True, hidden=False)
mPlug_end = cgmMeta.cgmAttr(handle,'twistEnd',attrType='float',keyable=True, hidden=False)
mPlug_equalizedRoll = cgmMeta.cgmAttr(handle,'twistEqualized',attrType='float',keyable=True, hidden=False)
mPlug_twist = cgmMeta.cgmAttr(handle,'twist',attrType='float',keyable=True, hidden=False)
mPlug_start.doConnectOut("%s.roll"%handle)

arg1 = "%s = %s - %s"%(mPlug_equalizedRoll.p_combinedShortName,mPlug_start.p_combinedShortName,mPlug_end.p_combinedShortName)
log.info("arg1: %s"%arg1)
NodeF.argsToNodes(arg1).doBuild()

arg2 = "%s =  %s - %s"%(mPlug_twist.p_combinedShortName,mPlug_end.p_combinedShortName,mPlug_equalizedRoll.p_combinedShortName)
log.info("arg2: %s"%arg2)
NodeF.argsToNodes(arg2).doBuild()

mPlug_twistRampMultiplier = cgmMeta.cgmAttr(handle,'twistRampMultiplier',attrType='float',keyable=True, hidden=False)
mPlug_twistRampMultiplier.doConnectOut("%s.dTwistRampMult"%handle)
#>>>Iterator
#=======================================================
#Value match mode
rUtils.matchValue_iterator(targetAttr = 'l_hip_ik_jnt.rz' , driverAttr = 'ikChain_ikH.twist', matchValue = 0)

rUtils.matchValue_iterator(drivenAttr = 'l_knee_ik_jnt.tz' , driverAttr = 'l_ankle_ik_anim.lengthUpr', maxIterations=2,matchValue = 66.991, minIn=0.1,maxIn=30.0)

#>>>ikHandle
Esempio n. 17
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
Esempio n. 18
0
def split_blends(driven1 = None,
                 driven2 = None,
                 sealDriver1 = None,
                 sealDriver2 = None,
                 sealDriverMid = None,
                 nameSeal1 = 'left',
                 nameSeal2 = 'right',
                 nameSealMid = 'center',
                 maxValue = 10.0,
                 inTangent = 'auto',
                 outTangent = 'auto',
                 settingsControl = None,
                 buildNetwork = True):
    """
    Split for blend data
    """
    try:
        _str_func = 'split_blends'
        d_dat = {1:{'dist1':[],
                    'dist2':[],
                    'distMid':[]},
                 2:{'dist1':[],
                    'dist2':[],
                    'distMid':[]}}
        _lock=False
        _hidden=False
        #>>> Verify ===================================================================================
        log.debug("|{0}| >> driven1 [Check]...".format(_str_func))        
        d_dat[1]['driven'] = cgmMeta.validateObjListArg(driven1,
                                                        mType = 'cgmObject',
                                                        mayaType=['joint'], noneValid = False)
        log.debug("|{0}| >> driven2 [Check]...".format(_str_func))                
        d_dat[2]['driven'] = cgmMeta.validateObjListArg(driven2,
                                                        mType = 'cgmObject',
                                                        mayaType=['joint'], noneValid = False)

        mSettings = cgmMeta.validateObjArg(settingsControl,'cgmObject')
        pprint.pprint(d_dat[1]['driven'])
        pprint.pprint(d_dat[2]['driven'])

        if buildNetwork:
            log.debug("|{0}| >> buildNetwork | building driver attrs...".format(_str_func))                            
            mPlug_sealMid = cgmMeta.cgmAttr(mSettings.mNode,
                                            'seal_{0}'.format(nameSealMid),
                                            attrType='float',
                                            minValue=0.0,
                                            maxValue = maxValue,
                                            lock=False,
                                            keyable=True)
            mPlug_seal1 = cgmMeta.cgmAttr(mSettings.mNode,
                                          'seal_{0}'.format(nameSeal1),
                                          attrType='float',
                                          minValue=0.0,
                                          maxValue = maxValue,
                                          lock=False,
                                          keyable=True)
            mPlug_seal2 = cgmMeta.cgmAttr(mSettings.mNode,
                                          'seal_{0}'.format(nameSeal2),
                                          attrType='float',
                                          minValue=0.0,
                                          maxValue = maxValue,
                                          lock=False,
                                          keyable=True)            

        pos1 = POS.get(sealDriver1)
        pos2 = POS.get(sealDriver2)
        posMid = POS.get(sealDriverMid)

        normMin = maxValue * .1
        normMax = maxValue - normMin

        for idx,dat in d_dat.iteritems():
            mDriven = dat['driven']

            d_tmp = {'dist1':{'pos':pos1,
                              'res':dat['dist1']},
                     'dist2':{'pos':pos2,
                              'res':dat['dist2']},
                     'distMid':{'pos':posMid,
                                'res':dat['distMid']},
                     }

            for mObj in mDriven:
                for n,d in d_tmp.iteritems():
                    dTmp = DIST.get_distance_between_points(d['pos'],mObj.p_position)
                    if MATH.is_float_equivalent(dTmp,0.0):
                        dTmp = 0.0
                    d['res'].append(dTmp)

            dat['dist1Norm'] = MATH.normalizeList(dat['dist1'],normMax)
            dat['dist2Norm'] = MATH.normalizeList(dat['dist2'],normMax)
            dat['distMidNorm'] = MATH.normalizeList(dat['distMid'],normMax)

            dat['dist1On'] = [v + normMin for v in dat['dist1Norm']]
            dat['dist2On'] = [v + normMin for v in dat['dist2Norm']]
            dat['distMidOn'] = [v + normMin for v in dat['distMidNorm']]
            
            if buildNetwork:
                log.debug("|{0}| >> buildNetwork | building driver attrs...".format(_str_func))
                dat['mPlugs'] = {'1':{},
                                 '2':{},
                                 'mid':{},
                                 'on':{},
                                 'off':{},
                                 'sum':{}}
                for i,mObj in enumerate(mDriven):
                    log.debug("|{0}| >> buildNetwork | On: {1}".format(_str_func,mObj) + cgmGEN._str_subLine)
                    dat['mPlugs']['1'][i] = cgmMeta.cgmAttr(mSettings,
                                                            'set{0}_idx{1}_blend{2}'.format(idx,i,'1'),
                                                            attrType='float',
                                                            keyable = False,lock=_lock,hidden=_hidden)
                    dat['mPlugs']['2'][i] = cgmMeta.cgmAttr(mSettings,
                                                            'set{0}_idx{1}_blend{2}'.format(idx,i,'2'),
                                                            attrType='float',
                                                            keyable = False,lock=_lock,hidden=_hidden)
                    dat['mPlugs']['mid'][i] = cgmMeta.cgmAttr(mSettings,
                                                              'set{0}_idx{1}_blend{2}'.format(idx,i,'mid'),
                                                              attrType='float',
                                                              keyable = False,lock=_lock,hidden=_hidden)                    
                    dat['mPlugs']['on'][i] = cgmMeta.cgmAttr(mSettings,
                                                             'set{0}_idx{1}_on'.format(idx,i),
                                                             attrType='float',
                                                             keyable = False,lock=_lock,hidden=_hidden)
                    dat['mPlugs']['off'][i] = cgmMeta.cgmAttr(mSettings,
                                                              'set{0}_idx{1}_off'.format(idx,i),
                                                              attrType='float',
                                                              keyable = False,lock=_lock,hidden=_hidden)

                    dat['mPlugs']['sum'][i] = cgmMeta.cgmAttr(mSettings,
                                                              'set{0}_idx{1}_sum'.format(idx,i),
                                                              attrType='float',
                                                              keyable = False,lock=_lock,hidden=_hidden)

                    args = []
                    args.append("{0} = {1} + {2} + {3}".format(dat['mPlugs']['sum'][i].p_combinedShortName,
                                                               dat['mPlugs']['1'][i].p_combinedShortName,
                                                               dat['mPlugs']['2'][i].p_combinedShortName,
                                                               dat['mPlugs']['mid'][i].p_combinedShortName))
                    args.append("{0} = clamp(0 , 1.0, {1}".format(dat['mPlugs']['on'][i].p_combinedShortName,
                                                                  dat['mPlugs']['sum'][i].p_combinedShortName,))
                    args.append("{0} = 1.0 - {1}".format(dat['mPlugs']['off'][i].p_combinedShortName,
                                                         dat['mPlugs']['on'][i].p_combinedShortName,))                    
                    for a in args:
                        NODEFAC.argsToNodes(a).doBuild()

                    zeroMid = 0
                    zero1 = 0
                    zero2 = 0
                    
                    """
                    1
                    'dist1Norm': [9.0, 7.202468187218439, 4.077128668939619],
                    'dist1On': [10.0, 8.20246818721844, 5.077128668939619],
                    'dist2': [2.055457665682541, 3.632951746156667, 4.537290944991008],
                    'dist2Norm': [4.077128668939596, 7.206186711809993, 9.0],
                    'dist2On': [5.077128668939596, 8.206186711809993, 10.0],
                    
                    2
                    'dist1On': [10.0, 7.77630635569009, 4.3748619466292595],
                    'dist2': [1.6982080013368184, 3.4097921203066526, 4.528739916989064],
                    'dist2Norm': [3.3748619466301477, 6.7763063556899725, 9.0],
                    'dist2On': [4.374861946630148, 7.7763063556899725, 10.0],
                    
                    """
                    

                    try:zero1 = dat['dist1On'][i+1]
                    except:zero1 = 0
                    
                    if i:
                        try:zero2 = dat['dist2On'][i-1]
                        except:zero2 = 0
                        
                    #try:zeroMid = dat['distMidOn'][i-1]
                    #except:zeroMid= 0
                        
                   #if i:
                   #     zero1 = dat['dist1On'][i-1]

                    #try:zero2 = dat['dist2On'][i+1]
                    #except:zero2 = 0
                        #zero1 = MATH.Clamp(dat['dist1On'][i-1],normMin,maxValue)
                        #zero2 = MATH.Clamp(dat['dist2On'][i-1],normMin,maxValue)

                    mc.setDrivenKeyframe(dat['mPlugs']['1'][i].p_combinedShortName,
                                         currentDriver = mPlug_seal1.p_combinedShortName,
                                         itt=inTangent,ott=outTangent,
                                         driverValue = zero1,value = 0.0)

                    mc.setDrivenKeyframe(dat['mPlugs']['1'][i].p_combinedShortName,
                                         currentDriver = mPlug_seal1.p_combinedShortName,
                                         itt=inTangent,ott=outTangent,                                         
                                         driverValue = dat['dist1On'][i],value = 1.0)


                    mc.setDrivenKeyframe(dat['mPlugs']['2'][i].p_combinedShortName,
                                         currentDriver = mPlug_seal2.p_combinedShortName,
                                         itt=inTangent,ott=outTangent,                                         
                                         driverValue = zero2,value = 0.0)                    
                    mc.setDrivenKeyframe(dat['mPlugs']['2'][i].p_combinedShortName,
                                         currentDriver = mPlug_seal2.p_combinedShortName,
                                         itt=inTangent,ott=outTangent,                                         
                                         driverValue = dat['dist2On'][i],value = 1.0)

                    last1 = dat['dist1On'][i]
                    last2 = dat['dist2On'][i]


                    mc.setDrivenKeyframe(dat['mPlugs']['mid'][i].p_combinedShortName,
                                         currentDriver = mPlug_sealMid.p_combinedShortName,
                                         itt=inTangent,ott=outTangent,                                         
                                         driverValue = zeroMid,value = 0.0)                    
                    mc.setDrivenKeyframe(dat['mPlugs']['mid'][i].p_combinedShortName,
                                         currentDriver = mPlug_sealMid.p_combinedShortName,
                                         itt=inTangent,ott=outTangent,                                         
                                         driverValue = dat['distMidOn'][i],value = 1.0)

        pprint.pprint(d_dat)
        #return d_dat

        for idx,dat in d_dat.iteritems():
            for plugSet,mSet in dat['mPlugs'].iteritems():
                for n,mPlug in mSet.iteritems():
                    mPlug.p_lock=True
                    mPlug.p_hidden = True

        return d_dat

    except Exception,err:
        cgmGEN.cgmExceptCB(Exception,err,msg=vars())    
_d = {
    'jointList': [
        u'tail_01_rig', u'tail_02_rig', u'tail_03_rig', u'tail_04_rig',
        u'tail_05_rig', u'tail_06_rig', u'tail_07_rig', u'tail_08_rig',
        u'tail_09_rig', u'tail_10_rig'
    ]
}
reload(IK)
IK.ribbon(**_d)

#===================================================================================================
# >> Guardian fix
#===================================================================================================
import cgm.core.classes.NodeFactory as NODEF
arg = "neck1_c.rx = clamp(0,head.maxRoll, head.rx)"
NODEF.argsToNodes(arg).doBuild()


#===================================================================================================
# >> Abyss work
#===================================================================================================
def renameFinger(base='thumb', direction='l', tag='sknj'):
    import cgm.core.cgm_Meta as cgmMeta
    import maya.cmds as mc
    ml = cgmMeta.validateObjListArg(mc.ls(sl=1))
    for i, mObj in enumerate(ml):
        mObj.rename("{0}_{1}_{2}_{3}".format(base, direction, i, tag))


#>>Arms.....
Esempio n. 20
0
def ik_rp(self,
          mStart,
          mEnd,
          ml_ikFrame=None,
          mIKControl=None,
          mIKBaseControl=None,
          mIKHandleDriver=None,
          mRoot=None,
          mIKGroup=None,
          mIKControlEnd=None,
          ml_ikFullChain=None):
    try:
        _str_func = "ik_rp"
        log.debug("|{0}| >> {1}...".format(_str_func, _str_func) + '-' * 60)

        mRigNull = self.mRigNull
        mBlock = self.mBlock

        if not ml_ikFrame:
            ml_ikFrame = self.ml_handleTargetsCulled
        if not mIKControl:
            raise ValueError, "Must have mIKControl"

        if not mIKHandleDriver:
            raise ValueError, "Must have mIKHandleDriver"
        if not mRoot:
            raise ValueError, "Must have mRoot"

        log.debug("|{0}| >> rp setup...".format(_str_func))
        mIKMid = mRigNull.controlIKMid
        str_ikEnd = mBlock.getEnumValueString('ikEnd')
        #Measture ======================================================
        log.debug("|{0}| >> measure... ".format(_str_func) + '-' * 30)

        res_ikScale = self.UTILS.get_blockScale(
            self, '{0}_ikMeasure'.format(self.d_module['partName'], ),
            ml_ikFrame)

        mPlug_masterScale = res_ikScale[0]
        mMasterCurve = res_ikScale[1]
        mMasterCurve.p_parent = mRoot
        self.fnc_connect_toRigGutsVis(mMasterCurve)
        mMasterCurve.dagLock(True)

        #Unparent the children from the end while we set stuff up...
        log.debug("|{0}| >> end unparent ...".format(_str_func) + '-' * 30)

        ml_end_children = mEnd.getChildren(asMeta=True)
        if ml_end_children:
            for mChild in ml_end_children:
                mChild.parent = False

        #Build the IK ---------------------------------------------------------------------
        reload(IK)
        """
        if mIKControlEnd and str_ikEnd in ['tipCombo']:
            mMainIKControl = mIKControlEnd
        else:
            mMainIKControl = mIKControl
        """
        _d_ik = {
            'globalScaleAttr': mPlug_masterScale.
            p_combinedName,  #mPlug_globalScale.p_combinedName,
            'stretch': 'translate',
            'lockMid': True,
            'rpHandle': mIKMid.mNode,
            'nameSuffix': 'ik',
            'baseName': '{0}_ikRP'.format(self.d_module['partName']),
            'controlObject': mIKControl.mNode,
            'moduleInstance': self.mModule.mNode
        }

        d_ikReturn = IK.handle(mStart.mNode, mEnd.mNode, **_d_ik)
        mIKHandle = d_ikReturn['mHandle']
        ml_distHandlesNF = d_ikReturn['ml_distHandles']
        mRPHandleNF = d_ikReturn['mRPHandle']

        #>>>Parent IK handles -----------------------------------------------------------------
        log.debug("|{0}| >> parent IK stuff ...".format(_str_func) + '-' * 30)

        mIKHandle.parent = mIKHandleDriver.mNode  #handle to control
        for mObj in ml_distHandlesNF[:-1]:
            mObj.parent = mRoot
        ml_distHandlesNF[-1].parent = mIKHandleDriver.mNode  #handle to control
        ml_distHandlesNF[1].parent = mIKMid
        ml_distHandlesNF[1].t = 0, 0, 0
        ml_distHandlesNF[1].r = 0, 0, 0

        if mIKBaseControl:
            ml_distHandlesNF[0].parent = mIKBaseControl

        #>>> Fix our ik_handle twist at the end of all of the parenting
        IK.handle_fixTwist(mIKHandle,
                           self.d_orientation['str'][0])  #Fix the twist

        if mIKControlEnd:
            mIKEndDriver = mIKControlEnd
        else:
            mIKEndDriver = mIKControl

        if ml_end_children:
            for mChild in ml_end_children:
                mChild.parent = mEnd

        #mc.scaleConstraint([mIKControl.mNode],
        #                    ml_ikFrame[self.int_handleEndIdx].mNode,
        #                    maintainOffset = True)
        #if mIKBaseControl:
        #ml_ikFrame[0].parent = mRigNull.controlIKBase

        #if mIKBaseControl:
        #mc.pointConstraint(mIKBaseControl.mNode, ml_ikFrame[0].mNode,maintainOffset=True)

        #Make a spin group ===========================================================
        log.debug("|{0}| >> spin group ...".format(_str_func) + '-' * 30)

        mSpinGroup = mStart.doGroup(False, False, asMeta=True)
        mSpinGroup.doCopyNameTagsFromObject(self.mModule.mNode,
                                            ignore=['cgmName', 'cgmType'])
        mSpinGroup.addAttr('cgmName',
                           '{0}NoFlipSpin'.format(self.d_module['partName']))
        mSpinGroup.doName()
        ATTR.set(mSpinGroup.mNode, 'rotateOrder', self.d_orientation['str'])

        mSpinGroup.parent = mIKGroup
        mSpinGroup.doGroup(True, True, typeModifier='zero')
        mSpinGroupAdd = mSpinGroup.doDuplicate()

        mSpinGroupAdd.doStore('cgmTypeModifier', 'addSpin')
        mSpinGroupAdd.doName()
        mSpinGroupAdd.p_parent = mSpinGroup

        if mIKBaseControl:
            mc.pointConstraint(mIKBaseControl.mNode,
                               mSpinGroup.mNode,
                               maintainOffset=True)

        #Setup arg
        #mPlug_spin = cgmMeta.cgmAttr(mIKControl,'spin',attrType='float',keyable=True, defaultValue = 0, hidden = False)
        #mPlug_spin.doConnectOut("%s.r%s"%(mSpinGroup.mNode,_jointOrientation[0]))

        mSpinTarget = mIKControl

        if mBlock.getMayaAttr('ikRPAim'):
            mc.aimConstraint(mSpinTarget.mNode,
                             mSpinGroup.mNode,
                             maintainOffset=False,
                             aimVector=[0, 0, 1],
                             upVector=[0, 1, 0],
                             worldUpType='none')
        else:
            mc.aimConstraint(mSpinTarget.mNode,
                             mSpinGroup.mNode,
                             maintainOffset=False,
                             aimVector=[0, 0, 1],
                             upVector=[0, 1, 0],
                             worldUpObject=mSpinTarget.mNode,
                             worldUpType='objectrotation',
                             worldUpVector=self.v_twistUp)

        mPlug_spinMid = cgmMeta.cgmAttr(mSpinTarget,
                                        'spinMid',
                                        attrType='float',
                                        defaultValue=0,
                                        keyable=True,
                                        lock=False,
                                        hidden=False)

        _direction = self.d_module.get('direction') or 'center'

        if _direction.lower() == 'right':
            str_arg = "{0}.r{1} = -{2}".format(
                mSpinGroupAdd.mNode, self.d_orientation['str'][0].lower(),
                mPlug_spinMid.p_combinedShortName)
            log.debug("|{0}| >> Right knee spin: {1}".format(
                _str_func, str_arg))
            NODEFACTORY.argsToNodes(str_arg).doBuild()
        else:
            mPlug_spinMid.doConnectOut("{0}.r{1}".format(
                mSpinGroupAdd.mNode, self.d_orientation['str'][0]))

        mSpinGroup.dagLock(True)
        mSpinGroupAdd.dagLock(True)

        #>>> mBallRotationControl ==========================================================
        mIKBallRotationControl = mRigNull.getMessageAsMeta(
            'controlBallRotation')
        if mIKBallRotationControl:  # and str_ikEnd not in ['tipCombo']:
            log.debug("|{0}| >> mIKBallRotationControl...".format(_str_func) +
                      '-' * 30)

            mBallOrientGroup = cgmMeta.validateObjArg(
                mIKBallRotationControl.doGroup(True,
                                               False,
                                               asMeta=True,
                                               typeModifier='orient'),
                'cgmObject',
                setClass=True)
            ATTR.set(mBallOrientGroup.mNode, 'rotateOrder',
                     self.d_orientation['str'])

            mLocBase = mIKBallRotationControl.doCreateAt()
            mLocAim = mIKBallRotationControl.doCreateAt()

            mLocAim.doStore('cgmTypeModifier', 'extendedIK')
            mLocBase = mIKBallRotationControl.doCreateAt()

            mLocBase.doName()
            mLocAim.doName()

            mLocAim.p_parent = ml_ikFullChain[-1]
            mLocBase.p_parent = mIKBallRotationControl.masterGroup

            const = mc.orientConstraint([mLocAim.mNode, mLocBase.mNode],
                                        mBallOrientGroup.mNode,
                                        maintainOffset=True)[0]

            d_blendReturn = NODEFACTORY.createSingleBlendNetwork(
                [mIKControl.mNode, 'extendIK'],
                [mIKControl.mNode, 'resRootFollow'],
                [mIKControl.mNode, 'resFullFollow'],
                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

            mBallOrientGroup.dagLock(True)
            mLocAim.dagLock(True)
            mLocBase.dagLock(True)

            mIKBallRotationControl.p_parent = mBallOrientGroup

            #Joint constraint -------------------------
            mIKBallRotationControl.masterGroup.p_parent = mPivotResultDriver
            mc.orientConstraint([mIKBallRotationControl.mNode],
                                ml_ikFrame[self.int_handleEndIdx].mNode,
                                maintainOffset=True)
            mc.parentConstraint([mPivotResultDriver.mNode],
                                ml_ikFrame[self.int_handleEndIdx + 1].mNode,
                                maintainOffset=True)

            ATTR.set_default(mIKControl.mNode, 'extendIK', 1.0)
            mIKControl.extendIK = 0.0

        elif str_ikEnd == 'bank':
            mc.orientConstraint([mPivotResultDriver.mNode],
                                ml_ikFrame[self.int_handleEndIdx].mNode,
                                maintainOffset=True)
        elif str_ikEnd == 'pad':
            mc.orientConstraint([mPivotResultDriver.mNode],
                                ml_ikFrame[self.int_handleEndIdx].mNode,
                                maintainOffset=True)
        else:
            mc.orientConstraint([mIKEndDriver.mNode],
                                ml_ikFrame[self.int_handleEndIdx].mNode,
                                maintainOffset=True)

        #Mid IK driver -----------------------------------------------------------------------
        log.debug("|{0}| >> mid Ik driver...".format(_str_func) + '-' * 30)

        log.debug("|{0}| >> mid IK driver.".format(_str_func))
        mMidControlDriver = mIKMid.doCreateAt()
        mMidControlDriver.addAttr(
            'cgmName', '{0}_midIK'.format(self.d_module['partName']))
        mMidControlDriver.addAttr('cgmType', 'driver')
        mMidControlDriver.doName()
        mMidControlDriver.addAttr('cgmAlias', 'midDriver')

        if mIKBaseControl:
            l_midDrivers = [mIKBaseControl.mNode]
        else:
            l_midDrivers = [mRoot.mNode]

        if str_ikEnd in ['tipCombo'] and mIKControlEnd:
            log.debug("|{0}| >> mIKControlEnd + tipCombo...".format(_str_func))
            l_midDrivers.append(mIKControl.mNode)
        else:
            l_midDrivers.append(mIKHandleDriver.mNode)

        mc.pointConstraint(l_midDrivers, mMidControlDriver.mNode)
        mMidControlDriver.parent = mSpinGroupAdd  #mIKGroup
        mIKMid.masterGroup.parent = mMidControlDriver
        mMidControlDriver.dagLock(True)

        #Mid IK trace
        log.debug("|{0}| >> midIK track Crv".format(_str_func, mIKMid))
        trackcrv, clusters = CORERIG.create_at(
            [
                mIKMid.mNode, ml_ikFrame[MATH.get_midIndex(
                    len(ml_ikFrame))].mNode
            ],  #ml_handleJoints[1]],
            'linearTrack',
            baseName='{0}_midTrack'.format(self.d_module['partName']))

        mTrackCrv = cgmMeta.asMeta(trackcrv)
        mTrackCrv.p_parent = self.mModule
        mHandleFactory = mBlock.asHandleFactory()
        mHandleFactory.color(mTrackCrv.mNode, controlType='sub')

        for s in mTrackCrv.getShapes(asMeta=True):
            s.overrideEnabled = 1
            s.overrideDisplayType = 2
        mTrackCrv.doConnectIn('visibility', "{0}.v".format(mIKGroup.mNode))

        #Full IK chain -----------------------------------------------------------------------
        if ml_ikFullChain:
            log.debug("|{0}| >> Full IK Chain...".format(_str_func))
            _d_ik = {
                'globalScaleAttr': mPlug_masterScale.
                p_combinedName,  #mPlug_globalScale.p_combinedName,
                'stretch': 'translate',
                'lockMid': False,
                'rpHandle': mIKMid.mNode,
                'baseName':
                '{0}_ikFullChain'.format(self.d_module['partName']),
                'nameSuffix': 'ikFull',
                'controlObject': mIKControl.mNode,
                'moduleInstance': self.mModule.mNode
            }

            d_ikReturn = IK.handle(ml_ikFullChain[0], ml_ikFullChain[-1],
                                   **_d_ik)
            mIKHandle = d_ikReturn['mHandle']
            ml_distHandlesNF = d_ikReturn['ml_distHandles']
            mRPHandleNF = d_ikReturn['mRPHandle']

            mIKHandle.parent = mIKControl.mNode  #handle to control
            for mObj in ml_distHandlesNF[:-1]:
                mObj.parent = mRoot
            ml_distHandlesNF[-1].parent = mIKControl.mNode  #handle to control
            #ml_distHandlesNF[1].parent = mIKMid
            #ml_distHandlesNF[1].t = 0,0,0
            #ml_distHandlesNF[1].r = 0,0,0

            #>>> Fix our ik_handle twist at the end of all of the parenting
            IK.handle_fixTwist(mIKHandle,
                               self.d_orientation['str'][0])  #Fix the twist

            #mIKControl.masterGroup.p_parent = ml_ikFullChain[-2]

        ######mc.parentConstraint([mIKControl.mNode], ml_ikFrame[-1].mNode, maintainOffset = True)

        if mIKBaseControl:
            ml_ikFrame[0].parent = mIKBaseControl
        #if mIKBaseControl:
        #mc.pointConstraint(mIKBaseControl.mNode, ml_ikFrame[0].mNode,maintainOffset=True)

    except Exception, err:
        cgmGEN.cgmExceptCB(Exception, err, localDat=vars())
Esempio n. 21
0
                        raise StandardError, "[validate control attribute bridge attr]{%s}" % (
                            error)

                    if self.str_mirrorSide.lower() == 'right':
                        arg_attributeBridge = "%s = -%s" % (
                            mPlug_attrBridgeDriven.p_combinedShortName,
                            mPlug_attrBridgeDriver.p_combinedShortName)
                    else:
                        arg_attributeBridge = "%s = %s" % (
                            mPlug_attrBridgeDriven.p_combinedShortName,
                            mPlug_attrBridgeDriver.p_combinedShortName)

                    mPlug_attrBridgeDriven.p_locked = True
                    mPlug_attrBridgeDriven.p_hidden = True
                    mPlug_attrBridgeDriven.p_keyable = False
                    NodeF.argsToNodes(arg_attributeBridge).doBuild()

        def _lockNHide(self):
            autoLockNHide = self.d_kws['autoLockNHide']
            if autoLockNHide:
                if self.mi_control.hasAttr('cgmTypeModifier'):
                    if self.mi_control.cgmTypeModifier.lower() == 'fk':
                        attributes.doSetLockHideKeyableAttr(
                            self.mi_control.mNode,
                            channels=['tx', 'ty', 'tz', 'sx', 'sy', 'sz'])
                if self.mi_control.cgmName.lower() == 'cog':
                    attributes.doSetLockHideKeyableAttr(
                        self.mi_control.mNode, channels=['sx', 'sy', 'sz'])
                cgmMeta.cgmAttr(self.mi_control,
                                'visibility',
                                lock=True,
Esempio n. 22
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)	 
Esempio n. 23
0
                                          scn=True)
            assert d_return['ml_nodes'][0].operation == 1, "Operation not 1"
            combinedName = d_return['ml_outPlugs'][0].p_combinedName
            assert str(plugCall[0]) == d_return['ml_outPlugs'][
                0].p_combinedName, "Connections don't match: %s | %s" % (
                    plugCall[0], combinedName)
            assert mObj.simpleInversion == -mObj.tx, "Inversion doesn't match"

        except StandardError, error:
            log.error("test_argsToNodes>>Simple inversion Failure! '%s'" %
                      (error))
            raise StandardError, error

        try:  #Simple Average
            arg = "%s.sumAverage1 = 4 >< 4 >< 4" % (str_obj)
            d_return = NODEFACTORY.argsToNodes(arg).doBuild()
            assert d_return['l_nodes'], "Should have made something"
            assert len(d_return['l_nodes']
                       ) == 1, "Only one node should be made. Found: %s" % len(
                           d_return['l_nodes'])
            assert d_return['ml_outPlugs'][0].obj.getMayaType(
            ) == 'plusMinusAverage', "%s != pma" % d_return['ml_outPlugs'][
                0].obj.getMayaType()
            assert d_return['ml_nodes'][0].operation == 3, "Operation not 3"

            assert mObj.sumAverage1 == 4, "Average is wrong: 4 != %s" % mObj.sumAverage1

        except StandardError, error:
            log.error("test_argsToNodes>>Simple sum Failure! '%s'" % (error))
            raise StandardError, error
Esempio n. 24
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())
Esempio n. 25
0
class Test_argsToNodes(unittest.TestCase):
    def test_a_condition(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.condResult = if %s.ty == 3:5 else 1" % (str_obj, str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()

        _ml_nodes = d_return.get('ml_nodes')
        _ml_outPlugs = d_return.get('ml_outPlugs')
        _plugCall = mc.listConnections("%s.condResult" % (mObj.mNode),
                                       plugs=True,
                                       scn=True)
        _combinedName = _ml_outPlugs[0].p_combinedName

        self.assertIsNotNone(_ml_outPlugs)
        self.assertEqual(len(_ml_outPlugs), 1)
        self.assertIsNotNone(_ml_nodes)
        self.assertEqual(len(_ml_nodes), 1)

        self.assertEqual(_ml_nodes[0].getMayaType(), 'condition')

        self.assertEqual(_ml_nodes[0].operation, 0)
        self.assertEqual(str(_plugCall[0]), _combinedName)

        mObj.ty = 3
        self.assertEqual(mObj.condResult, 5)
        mObj.ty = 1
        self.assertEqual(mObj.condResult, 1)

        return

    def test_b_multiInvsersion(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.inverseMultThree = 3 * -%s.tx" % (str_obj, str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(d_return['ml_outPlugs'])
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 2, "Only two nodes should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_nodes'][0].getMayaType(
        ) == 'multiplyDivide', "%s != md" % d_return['ml_nodes'][
            0].getMayaType()
        assert d_return['ml_nodes'][1].getMayaType(
        ) == 'multiplyDivide', "%s != md" % d_return['ml_nodes'][
            1].getMayaType()

        plugCall = mc.listConnections("%s.inverseMultThree" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        assert d_return['ml_nodes'][-1].operation == 1, "Operation not 1"
        combinedName = d_return['ml_outPlugs'][-1].p_combinedName
        assert str(plugCall[0]) == d_return['ml_outPlugs'][
            -1].p_combinedName, "Connections don't match: %s | %s" % (
                plugCall[0], combinedName)
        assert mObj.inverseMultThree == 3 * -mObj.tx, "Inversion doesn't match"

    def test_c_simpleInvsersion(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.simpleInversion = -%s.tx" % (str_obj, str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(d_return['ml_outPlugs'])
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 1, "Only one node should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_outPlugs'][0].obj.getMayaType(
        ) == 'multiplyDivide', "%s != pma" % d_return['ml_outPlugs'][
            0].obj.getMayaType()
        plugCall = mc.listConnections("%s.simpleInversion" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        assert d_return['ml_nodes'][0].operation == 1, "Operation not 1"
        combinedName = d_return['ml_outPlugs'][0].p_combinedName
        assert str(plugCall[0]) == d_return['ml_outPlugs'][
            0].p_combinedName, "Connections don't match: %s | %s" % (
                plugCall[0], combinedName)
        assert mObj.simpleInversion == -mObj.tx, "Inversion doesn't match"

    def test_d_average(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.sumAverage1 = 4 >< 4 >< 4" % (str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 1, "Only one node should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_outPlugs'][0].obj.getMayaType(
        ) == 'plusMinusAverage', "%s != pma" % d_return['ml_outPlugs'][
            0].obj.getMayaType()
        assert d_return['ml_nodes'][0].operation == 3, "Operation not 3"

        assert mObj.sumAverage1 == 4, "Average is wrong: 4 != %s" % mObj.sumAverage1

    def test_e_directConnect(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.directConnect = %s.ty" % (str_obj, str_obj)
        NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(
            mc.listConnections("%s.directConnect" % str_obj,
                               source=True,
                               scn=True))
        plugCall = mc.listConnections("%s.directConnect" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        assert plugCall[0] == '%s.translateY' % mObj.getShortName(), log.error(
            "Direct connect failed. Plug call:{0}".format(plugCall))

    def test_f_multiConnect(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        arg = "%s.directConnect, %s.ry = %s.ty" % (str_obj, str_obj, str_obj)
        NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(
            mc.listConnections("%s.directConnect" % str_obj,
                               source=True,
                               scn=True))
        plugCall = mc.listConnections("%s.directConnect" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        assert plugCall[0] == '%s.translateY' % mObj.getShortName(), log.error(
            "Direct connect failed: directConnect")
        plugCall = mc.listConnections("%s.rotateY" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        log.debug(plugCall)
        assert plugCall[0] == '%s.translateY' % mObj.getShortName(), log.error(
            "Direct connect failed: rotateY")

    def test_g_sum(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        mObj.tx = 1
        mObj.ty = 2
        mObj.tz = 3
        arg = "%s.sumResult1 = %s.tx - %s.ty - %s.tz" % (str_obj, str_obj,
                                                         str_obj, str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(d_return['ml_outPlugs'])
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 1, "Only one node should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_outPlugs'][0].obj.getMayaType(
        ) == 'plusMinusAverage', "%s != pma" % d_return['ml_outPlugs'][
            0].obj.getMayaType()
        plugCall = mc.listConnections("%s.sumResult1" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        assert d_return['ml_nodes'][0].operation == 2, "Operation not 2"
        combinedName = d_return['ml_outPlugs'][0].p_combinedName
        assert str(plugCall[0]) == d_return['ml_outPlugs'][
            0].p_combinedName, "Connections don't match: %s | %s" % (
                plugCall[0], combinedName)
        assert mObj.sumResult1 == mObj.tx - mObj.ty - mObj.tz, "Sum doesn't match"

    def test_h_clamp(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        mObj.tz = 3
        arg = "%s.clampResult = clamp(0,1,%s.tz" % (str_obj, str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(d_return['ml_outPlugs'])
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 1, "Only one node should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_outPlugs'][0].obj.getMayaType(
        ) == 'clamp', "%s != clamp" % d_return['ml_outPlugs'][
            0].obj.getMayaType()
        plugCall = mc.listConnections("%s.clampResult" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        combinedName = d_return['ml_outPlugs'][0].p_combinedName
        assert str(plugCall[0]) == d_return['ml_outPlugs'][
            0].p_combinedName, "Connections don't match: %s | %s" % (
                plugCall[0], combinedName)
        assert mObj.clampResult == 1, "Value 1 fail"
        mObj.tz = .5
        assert mObj.clampResult == .5, "Value 2 fail"

    def test_i_range(self):
        try:
            mObj = cgmMeta.cgmObject('argsToNodes_catch')
        except:
            mObj = cgmMeta.cgmObject(name='argsToNodes_catch')
        str_obj = mObj.p_nameShort

        mObj.tz = 5
        arg = "%s.setRangeResult = setRange(0,1,0,10,%s.tz" % (str_obj,
                                                               str_obj)
        d_return = NODEFACTORY.argsToNodes(arg).doBuild()
        log.debug(d_return['ml_outPlugs'])
        assert d_return['l_nodes'], "Should have made something"
        assert len(d_return['l_nodes']
                   ) == 1, "Only one node should be made. Found: %s" % len(
                       d_return['l_nodes'])
        assert d_return['ml_outPlugs'][0].obj.getMayaType(
        ) == 'setRange', "%s != setRange" % d_return['ml_outPlugs'][
            0].obj.getMayaType()
        plugCall = mc.listConnections("%s.setRangeResult" % (mObj.mNode),
                                      plugs=True,
                                      scn=True)
        combinedName = d_return['ml_outPlugs'][0].p_combinedName
        assert str(plugCall[0]) == d_return['ml_outPlugs'][
            0].p_combinedName, "Connections don't match: %s | %s" % (
                plugCall[0], combinedName)
        assert mObj.setRangeResult == .5, "Value 1 fail"
        mObj.tz = 10
        assert mObj.setRangeResult == 1, "Value 2 fail"

    def holder(self):
        mObj = cgmMeta.cgmObject(name='awesomeArgObj_loc')
        str_obj = mObj.getShortName()

        try:  #Mult inversion
            arg = "%s.inverseMultThree = 3 * -%s.tx" % (str_obj, str_obj)
            d_return = NODEFACTORY.argsToNodes(arg).doBuild()
            log.debug(d_return['ml_outPlugs'])
            assert d_return['l_nodes'], "Should have made something"
            assert len(
                d_return['l_nodes']
            ) == 2, "Only two nodes should be made. Found: %s" % len(
                d_return['l_nodes'])
            assert d_return['ml_nodes'][0].getMayaType(
            ) == 'multiplyDivide', "%s != md" % d_return['ml_nodes'][
                0].getMayaType()
            assert d_return['ml_nodes'][1].getMayaType(
            ) == 'multiplyDivide', "%s != md" % d_return['ml_nodes'][
                1].getMayaType()

            plugCall = mc.listConnections("%s.inverseMultThree" % (mObj.mNode),
                                          plugs=True,
                                          scn=True)
            assert d_return['ml_nodes'][-1].operation == 1, "Operation not 1"
            combinedName = d_return['ml_outPlugs'][-1].p_combinedName
            assert str(plugCall[0]) == d_return['ml_outPlugs'][
                -1].p_combinedName, "Connections don't match: %s | %s" % (
                    plugCall[0], combinedName)
            assert mObj.inverseMultThree == 3 * -mObj.tx, "Inversion doesn't match"

        except StandardError, error:
            log.error("test_argsToNodes>>Inversion mult 3 Failure! '%s'" %
                      (error))
            raise StandardError, error

        try:  #Simple inversion
            arg = "%s.simpleInversion = -%s.tx" % (str_obj, str_obj)
            d_return = NODEFACTORY.argsToNodes(arg).doBuild()
            log.debug(d_return['ml_outPlugs'])
            assert d_return['l_nodes'], "Should have made something"
            assert len(d_return['l_nodes']
                       ) == 1, "Only one node should be made. Found: %s" % len(
                           d_return['l_nodes'])
            assert d_return['ml_outPlugs'][0].obj.getMayaType(
            ) == 'multiplyDivide', "%s != pma" % d_return['ml_outPlugs'][
                0].obj.getMayaType()
            plugCall = mc.listConnections("%s.simpleInversion" % (mObj.mNode),
                                          plugs=True,
                                          scn=True)
            assert d_return['ml_nodes'][0].operation == 1, "Operation not 1"
            combinedName = d_return['ml_outPlugs'][0].p_combinedName
            assert str(plugCall[0]) == d_return['ml_outPlugs'][
                0].p_combinedName, "Connections don't match: %s | %s" % (
                    plugCall[0], combinedName)
            assert mObj.simpleInversion == -mObj.tx, "Inversion doesn't match"

        except StandardError, error:
            log.error("test_argsToNodes>>Simple inversion Failure! '%s'" %
                      (error))
            raise StandardError, error
Esempio n. 26
0
		mc.orientConstraint(mi_controlIK.mNode,mi_ikEnd.mNode, maintainOffset = True)
	
	    except Exception,error:
		raise Exception,"%s.build_FKIK>>> IK No Flip error: %s"%(self._go._strShortName,error)
	    
	    #=============================================================    
	    try:#>>>Connect Blend Chains and connections
		#>>> Main blend
		mPlug_FKIK = cgmMeta.cgmAttr(mi_settings.mNode,'blend_FKIK',lock=False,keyable=True)
		
		if self.ml_fkAttachJoints:
		    ml_fkUse = self.ml_fkAttachJoints
		    for i,mJoint in enumerate(self.ml_fkAttachJoints):
			mc.pointConstraint(ml_fkJoints[i].mNode,mJoint.mNode,maintainOffset = False)
			#Connect inversed aim and up
			NodeF.connectNegativeAttrs(ml_fkJoints[i].mNode, mJoint.mNode,
		                                   ["r%s"%self._go._jointOrientation[0],"r%s"%self._go._jointOrientation[1]]).go()
			cgmMeta.cgmAttr(ml_fkJoints[i].mNode,"r%s"%self._go._jointOrientation[2]).doConnectOut("%s.r%s"%(mJoint.mNode,self._go._jointOrientation[2]))
		   
		    self.ml_fkAttachJoints[0].parent = ml_controlsFK[0].parent#match parent		    
		    if self._go._partType == 'finger':self.ml_fkAttachJoints[1].parent = ml_controlsFK[1].parent#match parent	
		
		else:
		    ml_fkUse = ml_fkJoints
		    
		rUtils.connectBlendChainByConstraint(ml_fkUse,ml_ikJoints,ml_blendJoints,
	                                             driver = mPlug_FKIK.p_combinedName,l_constraints=['point','orient'])
	
		
		
		
		#>>> Settings - constrain
Esempio n. 27
0
def register(
    controlObject=None,  #(mObject - None) -- The object to use as a control
    typeModifier=None,  #(string - None) -- Tag for cgmTypeModifier for naming
    copyTransform=None,  #(mObject - None) -- Object to copy the transform of for our control object
    copyPivot=None,  #(mObject - None) -- Object to copy the pivot of for our control object
    shapeParentTo=None,  #'(mObject - None) -- Object to shape parent our control curve to to use that transform
    useShape=None,  #'(mObject - None) -- Object to use the curve shape of for our control
    setRotateOrder=None,  #'(rotateOrder - None) -- Argument for a rotate order to set
    autoLockNHide=None,  #'(bool - None) -- Try to set lock and hide
    mirrorAxis=None,  #'(string - None) -- Mirror axis to set - using red9's setup terms
    mirrorSide=None,  #'(string/int - None) -- Mirror side - using red9's setup terms
    makeMirrorable=True,  #'(bool - True) -- Setup for mirrorability (using red9) -- implied by other mirror args
    addDynParentGroup=False,  #'(False) -- Add a dynParent group setup
    addExtraGroups=False,  #'(int - False) -- Number of nested extra groups desired
    addConstraintGroup=False,  #'(bool - False) -- If a group just above the control is desired for consraining
    freezeAll=False,  #'(bool - False) -- Freeze all transforms on the control object
    noFreeze=False,
    addSpacePivots=False,  #'(int - False) -- Number of space pivots to generate and connect
    controlType=None,  #'(string - None) -- Tag for cgmType
    aim=None,  #'(string/int - None) -- aim axis to use
    up=None,  #'(string/int - None) -- up axis to use
    out=None,  #'(string/int - None) -- out axis to use
    makeAimable=None,  #'(mObject - False) -- Make object aimable -- implied by aim/up/out):
    **kws):

    _str_func = 'register'
    """
    [{'step':'validate','call':self._validate},
    {'step':'Copy Transform','call':self._copyTransform},
    {'step':'Shape Parent','call':self._shapeParent},
    {'step':'Copy Pivot','call':self._copyPivot},
    {'step':'Naming','call':self._naming},
    {'step':'Aim Setup','call':self._aimSetup},
    {'step':'Rotate Order','call':self._rotateOrder},
    {'step':'Initial Freeze','call':self._initialFreeze},
    {'step':'Groups Setup','call':self._groupsSetup},
    {'step':'Space Pivot','call':self._spacePivots},
    {'step':'Mirror Setup','call':self._mirrorSetup},	                        
    {'step':'Freeze','call':self._freeze},
    {'step':'Mirror Attribute Bridges','call':self._mirrorAttributeBridges_},	                        
    {'step':'lock N Hide','call':self._lockNHide},
    {'step':'Return build','call':self._returnBuild}]
    """
    try:
        #Validate ================================================================================================
        mi_control = cgmMeta.validateObjArg(controlObject,
                                            'cgmControl',
                                            setClass=True)

        str_mirrorAxis = VALID.stringArg(mirrorAxis, calledFrom=_str_func)
        str_mirrorSide = cgmGeneral.verify_mirrorSideArg(
            mirrorSide)  #VALID.stringArg(mirrorSide,calledFrom = _str_func)
        b_makeMirrorable = VALID.boolArg(makeMirrorable, calledFrom=_str_func)

        _addMirrorAttributeBridges = kws.get('addMirrorAttributeBridges',
                                             False)
        addForwardBack = kws.get('addForwardBack', False)

        if _addMirrorAttributeBridges:
            if type(_addMirrorAttributeBridges) not in [list, tuple]:
                raise ValueError, "[Bad addMirrorAttributeBridge arg]{arg: %s}" % _addMirrorAttributeBridge
            for i, l in enumerate(_addMirrorAttributeBridges):
                if type(l) not in [list, tuple]:
                    raise ValueError, "[Bad addMirrorAttributeBridge arg: %s]{arg: %s}" % (
                        i, l)

        # Running lists ------------------------------------------------------------------------------------------
        ml_groups = []  #Holder for groups
        ml_constraintGroups = []
        ml_spacePivots = []

        #Copy Transform ================================================================================================
        if copyTransform is not None:
            mTarget = cgmMeta.validateObjArg(copyTransform,
                                             'cgmObject',
                                             noneValid=True)
            if not mTarget:
                raise StandardError, "Failed to find suitable copyTransform object: '%s" % copyTransform

            #Need to move this to default cgmNode stuff
            mBuffer = mi_control
            i_newTransform = cgmMeta.cgmObject(
                rigging.groupMeObject(mTarget.mNode, False))
            for a in mc.listAttr(mi_control.mNode, userDefined=True):
                ATTR.copy_to(mi_control.mNode, a, i_newTransform.mNode)
            curves.parentShapeInPlace(i_newTransform.mNode,
                                      mi_control.mNode)  #Parent shape
            i_newTransform.parent = mi_control.parent  #Copy parent
            mi_control = cgmMeta.asMeta(i_newTransform,
                                        'cgmControl',
                                        setClass=True)
            mc.delete(mBuffer.mNode)

        #ShapeParent ================================================================================================
        if shapeParentTo:
            i_target = cgmMeta.validateObjArg(shapeParentTo, 'cgmObject')
            CORERIG.shapeParent_in_place(i_target.mNode, mi_control.mNode)
            i_target = cgmMeta.asMeta(i_target, 'cgmControl', setClass=True)
            #mi_control.delete()
            mi_control = i_target  #replace the control with the joint

        if useShape is not None:
            i_shape = cgmMeta.validateObjArg(useShape,
                                             cgmMeta.cgmObject,
                                             mayaType='nurbsCurve')
            curves.parentShapeInPlace(mi_control.mNode, i_shape.mNode)

        #Copy Pivot ============================================================================================
        if copyPivot is not None:
            if issubclass(type(copyPivot), cgmMeta.cgmNode):
                i_target = copyPivot
            elif mc.objExists(copyPivot):
                i_target = cgmMeta.cgmObject(copyPivot)
            else:
                raise StandardError, "Failed to find suitable copyTransform object: '%s" % copyPivot

            #Need to move this to default cgmNode stuff
            mi_control.doCopyPivot(i_target.mNode)

        #Naming ============================================================================================
        mi_control.addAttr('cgmType', 'controlAnim', lock=True)
        if typeModifier is not None:
            mi_control.addAttr('cgmTypeModifier', str(typeModifier), lock=True)
        mi_control.doName()  #mi_control.doName(nameShapes=True)

        #Rotate Order ============================================================================================
        _rotateOrder = False
        if setRotateOrder is not None:
            _rotateOrder = setRotateOrder
        elif controlType in __d_rotateOrderDefaults__.keys():
            _rotateOrder = __d_rotateOrderDefaults__[controlType]
        elif mi_control.getAttr('cgmName') in __d_rotateOrderDefaults__.keys():
            _rotateOrder = __d_rotateOrderDefaults__[mi_control.getAttr(
                'cgmName')]
        else:
            log.debug("|{0}| >> Rotate order not set on: {1}".format(
                _str_func, mi_control.p_nameShort))

        #Set it ---------------------------------------------------------------
        if _rotateOrder:
            mRotateOrder = VALID.simpleOrientation(_rotateOrder)
            #dictionary.validateRotateOrderString(_rotateOrder)

            mc.xform(mi_control.mNode, rotateOrder=mRotateOrder.p_string)

        #Initial Freeze ============================================================================================
        if freezeAll:
            mc.makeIdentity(mi_control.mNode, apply=True, t=1, r=1, s=1, n=0)

        #Groups ============================================================================================
        if addDynParentGroup or addSpacePivots or mi_control.getAttr(
                'cgmName') == 'cog' or _addMirrorAttributeBridges:
            mi_control.addAttr('________________',
                               attrType='int',
                               keyable=False,
                               hidden=False,
                               lock=True)
            ATTR.reorder(mi_control.mNode, '________________', top=True)
        #Aim Setup ============================================================================================
        if aim is not None or up is not None or makeAimable:
            mi_control._verifyAimable()

        #First our master group:
        i_masterGroup = (cgmMeta.asMeta(mi_control.doGroup(True),
                                        'cgmObject',
                                        setClass=True))
        i_masterGroup.doStore('cgmName', mi_control)
        i_masterGroup.addAttr('cgmTypeModifier', 'master', lock=True)
        i_masterGroup.doName()
        mi_control.connectChildNode(i_masterGroup, 'masterGroup', 'groupChild')

        if addDynParentGroup:
            i_dynGroup = (cgmMeta.cgmObject(mi_control.doGroup(True)))
            i_dynGroup = cgmRigMeta.cgmDynParentGroup(dynChild=mi_control,
                                                      dynGroup=i_dynGroup)
            i_dynGroup.doName()
            """
            i_zeroGroup = (cgmMeta.cgmObject(mi_control.doGroup(True)))
            i_zeroGroup.addAttr('cgmTypeModifier','zero',lock=True)
            i_zeroGroup.doName()
            mi_control.connectChildNode(i_zeroGroup,'zeroGroup','groupChild')"""

        if addExtraGroups:
            for i in range(addExtraGroups):
                i_group = (cgmMeta.asMeta(mi_control.doGroup(True),
                                          'cgmObject',
                                          setClass=True))
                if type(
                        addExtraGroups
                ) == int and addExtraGroups > 1:  #Add iterator if necessary
                    i_group.addAttr('cgmIterator', str(i + 1), lock=True)
                    i_group.doName()
                ml_groups.append(i_group)
            mi_control.msgList_connect("extraGroups", ml_groups, 'groupChild')

        if addConstraintGroup:  #ConstraintGroups
            i_constraintGroup = (cgmMeta.asMeta(mi_control.doGroup(True),
                                                'cgmObject',
                                                setClass=True))
            i_constraintGroup.addAttr('cgmTypeModifier',
                                      'constraint',
                                      lock=True)
            i_constraintGroup.doName()
            ml_constraintGroups.append(i_constraintGroup)
            mi_control.connectChildNode(i_constraintGroup, 'constraintGroup',
                                        'groupChild')

        #Space Pivot ============================================================================================
        if addSpacePivots:
            parent = mi_control.getMessage('masterGroup')[0]
            for i in range(int(addSpacePivots)):
                #i_pivot = rUtils.create_spaceLocatorForObject(mi_control.mNode,parent)
                i_pivot = SPACEPIVOTS.create(mi_control.mNode, parent)
                ml_spacePivots.append(i_pivot)
                #log.info("spacePivot created: {0}".format(i_pivot.p_nameShort))

        #Mirror Setup ============================================================================================
        if str_mirrorSide is not None or b_makeMirrorable:
            for mObj in [mi_control] + ml_spacePivots:
                mi_control._verifyMirrorable()
                l_enum = cgmMeta.cgmAttr(mi_control, 'mirrorSide').p_enum
                if str_mirrorSide in l_enum:
                    #log.debug("|{0}| >> Rotate order not set on: {1}".format(_str_func,mi_control.p_nameShort))
                    #log.debug("%s >> %s >> found in : %s"%(_str_funcCombined, "mirrorSetup", l_enum))
                    mi_control.mirrorSide = l_enum.index(str_mirrorSide)
                if str_mirrorAxis:
                    mi_control.mirrorAxis = str_mirrorAxis
            for mObj in mi_control.msgList_get('spacePivots'):
                mObj._verifyMirrorable()
                mi_control.doConnectOut('mirrorAxis',
                                        mObj.mNode + '.mirrorAxis')
                mi_control.doConnectOut('mirrorSide',
                                        mObj.mNode + '.mirrorSide')

                #cgmMeta.cgmAttr(mObj,'mirrorSide').doConnectIn(mi_control,'mirrorSide')
                #cgmMeta.cgmAttr(mi_control,'mirrorAxis').doCopyTo(mObj,connectTargetToSource = 1)
                #ATTR.connect(mObj.mNode + '.mirrorAxis',"{0}.mirrorAxis".format(mi_control.mNode))
                #ATTR.connect(mObj.mNode + 'mirrorSide',"{0}.mirrorSide".format(mi_control.mNode))

        #Freeze ============================================================================================
        if not shapeParentTo and noFreeze is not True:
            if not freezeAll:
                if mi_control.getAttr(
                        'cgmName'
                ) == 'cog' or controlType in __l_fullFreezeTypes__:
                    mc.makeIdentity(mi_control.mNode,
                                    apply=True,
                                    t=1,
                                    r=1,
                                    s=1,
                                    n=0)
                else:
                    mc.makeIdentity(mi_control.mNode,
                                    apply=True,
                                    t=1,
                                    r=0,
                                    s=1,
                                    n=0)
            else:
                mc.makeIdentity(mi_control.mNode,
                                apply=True,
                                t=1,
                                r=1,
                                s=1,
                                n=0)

        #Mirror attriubte Bridges ==========================================================================
        if addForwardBack:
            mPlug_forwardBackDriver = cgmMeta.cgmAttr(mi_control,
                                                      "forwardBack",
                                                      attrType='float',
                                                      keyable=True)
            try:
                mPlug_forwardBackDriven = cgmMeta.validateAttrArg(
                    [mi_control, addForwardBack])['mi_plug']
            except Exception, error:
                raise StandardError, "push pull driver | %s" % (error)

            if str_mirrorSide.lower() == 'right':
                arg_forwardBack = "%s = -%s" % (
                    mPlug_forwardBackDriven.p_combinedShortName,
                    mPlug_forwardBackDriver.p_combinedShortName)
            else:
                arg_forwardBack = "%s = %s" % (
                    mPlug_forwardBackDriven.p_combinedShortName,
                    mPlug_forwardBackDriver.p_combinedShortName)

            mPlug_forwardBackDriven.p_locked = True
            mPlug_forwardBackDriven.p_hidden = True
            mPlug_forwardBackDriven.p_keyable = False
            NodeF.argsToNodes(arg_forwardBack).doBuild()

        if _addMirrorAttributeBridges:
            for l_bridge in _addMirrorAttributeBridges:
                _attrName = VALID.stringArg(l_bridge[0])
                _attrToBridge = VALID.stringArg(l_bridge[1])
                if not mi_control.hasAttr(_attrToBridge):
                    raise StandardError, "['%s' lacks the bridge attr '%s']" % (
                        mi_control.p_nameShort, _attrToBridge)

                mPlug_attrBridgeDriver = cgmMeta.cgmAttr(mi_control,
                                                         _attrName,
                                                         attrType='float',
                                                         keyable=True)
                try:
                    mPlug_attrBridgeDriven = cgmMeta.validateAttrArg(
                        [mi_control, _attrToBridge])['mi_plug']
                except Exception, error:
                    raise StandardError, "[validate control attribute bridge attr]{%s}" % (
                        error)

                if str_mirrorSide.lower() == 'right':
                    arg_attributeBridge = "%s = -%s" % (
                        mPlug_attrBridgeDriven.p_combinedShortName,
                        mPlug_attrBridgeDriver.p_combinedShortName)
                else:
                    arg_attributeBridge = "%s = %s" % (
                        mPlug_attrBridgeDriven.p_combinedShortName,
                        mPlug_attrBridgeDriver.p_combinedShortName)

                mPlug_attrBridgeDriven.p_locked = True
                mPlug_attrBridgeDriven.p_hidden = True
                mPlug_attrBridgeDriven.p_keyable = False
                NodeF.argsToNodes(arg_attributeBridge).doBuild()
Esempio n. 28
0
def resize_masterShape(self, sizeBy=None, resize=False):
    try:

        _short = self.p_nameShort
        _str_func = '[{0}] resize_masterShape'.format(_short)
        log.debug("|{0}| >> ".format(_str_func) + '-' * 80)
        _sel = mc.ls(sl=True)
        _bb = False
        _bb = self.baseSize

        if resize:
            if _sel:
                _bb = TRANS.bbSize_get(_sel, False)
            #elif self.getBlockChildren():
            #    sizeBy = mc.ls(self.getBlockChildren(asMeta=False))
            #    _bb = TRANS.bbSize_get(sizeBy,False)
            self.baseSize = _bb

        log.debug("|{0}| >> _bb: {1}".format(_str_func, _bb))

        mHandleFactory = self.asHandleFactory(_short)
        mc.delete(self.getShapes())

        _average = MATH.average([_bb[0], _bb[2]])
        _size = _average * 1.5
        _offsetSize = _average * .01
        _blockScale = self.blockScale
        mFormNull = self.atUtils('stateNull_verify', 'form')
        mNoTransformNull = self.atUtils('noTransformNull_verify', 'form')

        if resize or self.controlOffset == .9999:
            self.controlOffset = _offsetSize

        #Main curve ===========================================================================
        _crv = CURVES.create_fromName(name='circle', direction='y+', size=1)
        mCrv = cgmMeta.asMeta(_crv)
        SNAP.go(mCrv.mNode, self.mNode, rotation=False)
        TRANS.scale_to_boundingBox(mCrv.mNode, [_bb[0], None, _bb[2]])

        #mDup = mCrv.doDuplicate(po=False)
        #mDup.p_position = MATH.list_add(mDup.p_position, [0,_offsetSize,0])

        RIG.shapeParent_in_place(self.mNode, _crv, False)
        #RIG.shapeParent_in_place(self.mNode,mDup.mNode,False)

        mHandleFactory.color(self.mNode, 'center', 'main', transparent=False)

        #Bounding box ==================================================================
        if self.getMessage('bbHelper'):
            self.bbHelper.delete()

        _bb_shape = CURVES.create_controlCurve(self.mNode,
                                               'cubeOpen',
                                               size=1,
                                               sizeMode='fixed')
        _bb_newSize = MATH.list_mult(self.baseSize,
                                     [_blockScale, _blockScale, _blockScale])
        TRANS.scale_to_boundingBox(_bb_shape, _bb_newSize)
        mBBShape = cgmMeta.validateObjArg(_bb_shape,
                                          'cgmObject',
                                          setClass=True)
        mBBShape.p_parent = mFormNull

        mBBShape.inheritsTransform = False
        mc.parentConstraint(self.mNode, mBBShape.mNode, maintainOffset=False)

        SNAPCALLS.snap(mBBShape.mNode,
                       self.mNode,
                       objPivot='axisBox',
                       objMode='y-')

        CORERIG.copy_pivot(mBBShape.mNode, self.mNode)
        self.doConnectOut('baseSize', "{0}.scale".format(mBBShape.mNode))
        #mHandleFactory.color(mBBShape.mNode,controlType='sub')
        mBBShape.setAttrFlags()

        mBBShape.doStore('cgmName', self)
        mBBShape.doStore('cgmType', 'bbVisualize')
        mBBShape.doName()
        mBBShape.template = True
        self.connectChildNode(mBBShape.mNode, 'bbHelper')

        #Offset visualize ==================================================================
        if self.getMessage('offsetHelper'):
            self.offsetHelper.delete()

        #Need to guess our offset size based on bounding box volume

        mShape = self.getShapes(asMeta=True)[0]
        l_return = mc.offsetCurve(mShape.mNode, distance=1, ch=True)
        #pprint.pprint(l_return)
        mHandleFactory.color(l_return[0], 'center', 'sub', transparent=False)

        mOffsetShape = cgmMeta.validateObjArg(l_return[0],
                                              'cgmObject',
                                              setClass=True)
        mOffsetShape.p_parent = mNoTransformNull
        #mOffsetShape.doSnapTo(self)
        #mc.pointConstraint(self.mNode,mOffsetShape.mNode,maintainOffset=True)
        #mc.orientConstraint(self.mNode,mOffsetShape.mNode,maintainOffset=True)
        mOffsetShape.inheritsTransform = False

        mOffsetShape.dagLock()

        _arg = '{0}.distance = -{1}.controlOffset'.format(
            l_return[1], self.mNode)
        NODEFACTORY.argsToNodes(_arg).doBuild()
        #self.doConnectOut('controlOffset',"{0}.distance".format(l_return[1]))

        mOffsetShape.doStore('cgmName', self)
        mOffsetShape.doStore('cgmType', 'offsetVisualize')
        mOffsetShape.doName()

        self.connectChildNode(mOffsetShape.mNode, 'offsetHelper')

        return
        #Offset visualize ==================================================================
        if self.getMessage('offsetHelper'):
            self.offsetHelper.delete()

        mShape = self.getShapes(asMeta=True)[0]
        l_return = mc.offsetCurve(mShape.mNode, distance=1, ch=True)
        #pprint.pprint(l_return)
        mHandleFactory.color(l_return[0], 'center', 'sub', transparent=False)

        mOffsetShape = cgmMeta.validateObjArg(l_return[0],
                                              'cgmObject',
                                              setClass=True)
        mOffsetShape.p_parent = mFormNull

        mOffsetShape.inheritsTransform = False
        mc.parentConstraint(self.mNode,
                            mOffsetShape.mNode,
                            maintainOffset=False)

        #mOffsetShape.setAttrFlags()

        _arg = '{0}.distance = -{1}.controlOffset * {1}.blockScale'.format(
            l_return[1], self.mNode)
        NODEFACTORY.argsToNodes(_arg).doBuild()
        #self.doConnectOut('controlOffset',"{0}.distance".format(l_return[1]))

        mOffsetShape.doStore('cgmName', self)
        mOffsetShape.doStore('cgmType', 'offsetVisualize')
        mOffsetShape.doName()

        self.connectChildNode(mOffsetShape.mNode, 'offsetHelper')

        return

        _crv = CURVES.create_fromName(name='squareOpen',
                                      direction='y+',
                                      size=1)
        TRANS.scale_to_boundingBox(_crv, [_bb[0], None, _bb[2]])

        mHandleFactory.color(_crv, 'center', 'sub', transparent=False)

        mCrv = cgmMeta.validateObjArg(_crv, 'cgmObject')
        l_offsetCrvs = []
        for shape in mCrv.getShapes():
            offsetShape = mc.offsetCurve(shape, distance=-_offsetSize,
                                         ch=True)[0]
            mHandleFactory.color(offsetShape,
                                 'center',
                                 'main',
                                 transparent=False)
            l_offsetCrvs.append(offsetShape)

        RIG.combineShapes(l_offsetCrvs + [_crv], True)
        SNAP.go(_crv, self.mNode)

        RIG.shapeParent_in_place(self.mNode, _crv, True)

        self.baseSize = _bb

        #Bounding box ==================================================================
        if self.getMessage('offsetVisualize'):
            self.bbVisualize.delete()

        _bb_shape = CURVES.create_controlCurve(self.mNode,
                                               'cubeOpen',
                                               size=1.0,
                                               sizeMode='fixed')
        mBBShape = cgmMeta.validateObjArg(_bb_shape,
                                          'cgmObject',
                                          setClass=True)
        mBBShape.p_parent = mFormNull

        SNAPCALLS.snap(mBBShape.mNode,
                       self.mNode,
                       objPivot='axisBox',
                       objMode='y-')

        CORERIG.copy_pivot(mBBShape.mNode, self.mNode)
        self.doConnectOut('baseSize', "{0}.scale".format(mBBShape.mNode))
        mHandleFactory.color(mBBShape.mNode, controlType='sub')
        mBBShape.setAttrFlags()

        mBBShape.doStore('cgmName', self)
        mBBShape.doStore('cgmType', 'bbVisualize')
        mBBShape.doName()

        self.connectChildNode(mBBShape.mNode, 'bbHelper')

        return True

    except Exception, err:
        cgmGEN.cgmExceptCB(Exception, err, localDat=vars())
Esempio n. 29
0
def attach_toShape(obj=None,
                   targetShape=None,
                   connectBy='parent',
                   driver=None):
    """
    :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')
        mDriver = cgmMeta.validateObjArg(driver, 'cgmObject', noneValid=True)

        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)
        md_res = {}

        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]

            md_res['mFollicle'] = i_follicleTrans
            md_res['mFollicleShape'] = i_follicleShape
        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 mDriver:
            if d_closest['type'] in ['nurbsSurface']:
                mFollicle = i_follicleTrans
                mFollShape = i_follicleShape

                minU = ATTR.get(_shape, 'minValueU')
                maxU = ATTR.get(_shape, 'maxValueU')
                minV = ATTR.get(_shape, 'minValueV')
                maxV = ATTR.get(_shape, 'maxValueV')

                mDriverLoc = mDriver.doLoc()
                mc.pointConstraint(mDriver.mNode, mDriverLoc.mNode)
                #mLoc = mObj.doLoc()

                str_baseName = "{0}_to_{1}".format(mDriver.p_nameBase,
                                                   mObj.p_nameBase)
                mPlug_normalizedU = cgmMeta.cgmAttr(
                    mDriverLoc.mNode,
                    "{0}_normalizedU".format(str_baseName),
                    attrType='float',
                    hidden=False,
                    lock=False)
                mPlug_sumU = cgmMeta.cgmAttr(mDriverLoc.mNode,
                                             "{0}_sumU".format(str_baseName),
                                             attrType='float',
                                             hidden=False,
                                             lock=False)

                mPlug_normalizedV = cgmMeta.cgmAttr(
                    mDriverLoc.mNode,
                    "{0}_normalizedV".format(str_baseName),
                    attrType='float',
                    hidden=False,
                    lock=False)
                mPlug_sumV = cgmMeta.cgmAttr(mDriverLoc.mNode,
                                             "{0}_sumV".format(str_baseName),
                                             attrType='float',
                                             hidden=False,
                                             lock=False)

                #res_closest = DIST.create_closest_point_node(mLoc.mNode, mCrv_reparam.mNode,True)
                log.debug("|{0}| >> Closest info {1}".format(_str_func, _res))

                srfNode = mc.createNode('closestPointOnSurface')
                mc.connectAttr("%s.worldSpace[0]" % _shape,
                               "%s.inputSurface" % srfNode)
                mc.connectAttr("%s.translate" % mDriverLoc.mNode,
                               "%s.inPosition" % srfNode)
                #mc.connectAttr("%s.position" % srfNode, "%s.translate" % mLoc.mNode, f=True)

                #mClosestPoint =  cgmMeta.validateObjArg(srfNode,setClass=True)
                #mClosestPoint.doStore('cgmName',mObj)
                #mClosestPoint.doName()

                log.debug("|{0}| >> paramU {1}.parameterU | {2}".format(
                    _str_func, srfNode, ATTR.get(srfNode, 'parameterU')))
                log.debug("|{0}| >> paramV {1}.parameterV | {2}".format(
                    _str_func, srfNode, ATTR.get(srfNode, 'parameterV')))

                l_argBuild = []
                mPlug_uSize = cgmMeta.cgmAttr(mDriverLoc.mNode,
                                              "{0}_uSize".format(str_baseName),
                                              attrType='float',
                                              hidden=False,
                                              lock=False)
                mPlug_vSize = cgmMeta.cgmAttr(mDriverLoc.mNode,
                                              "{0}_vSize".format(str_baseName),
                                              attrType='float',
                                              hidden=False,
                                              lock=False)

                l_argBuild.append("{0} = {1} - {2}".format(
                    mPlug_vSize.p_combinedName, maxV, minV))
                l_argBuild.append("{0} = {1} - {2}".format(
                    mPlug_uSize.p_combinedName, maxU, minU))

                l_argBuild.append("{0} = {1} + {2}.parameterU".format(
                    mPlug_sumU.p_combinedName, minU, srfNode))

                l_argBuild.append("{0} = {1} / {2}".format(
                    mPlug_normalizedU.p_combinedName,
                    mPlug_sumU.p_combinedName, mPlug_uSize.p_combinedName))

                l_argBuild.append("{0} = {1} + {2}.parameterV".format(
                    mPlug_sumV.p_combinedName, minV, srfNode))

                l_argBuild.append("{0} = {1} / {2}".format(
                    mPlug_normalizedV.p_combinedName,
                    mPlug_sumV.p_combinedName, mPlug_vSize.p_combinedName))

                for arg in l_argBuild:
                    log.debug("|{0}| >> Building arg: {1}".format(
                        _str_func, arg))
                    NODEFACTORY.argsToNodes(arg).doBuild()

                ATTR.connect(mPlug_normalizedU.p_combinedShortName,
                             '{0}.parameterU'.format(mFollShape.mNode))
                ATTR.connect(mPlug_normalizedV.p_combinedShortName,
                             '{0}.parameterV'.format(mFollShape.mNode))

                md_res['mDriverLoc'] = mDriverLoc

            elif d_closest['type'] in ['curve', 'nurbsCurve']:
                mDriverLoc = mDriver.doLoc()
                mc.pointConstraint(mDriver.mNode, mDriverLoc.mNode)

                _resClosest = DIST.create_closest_point_node(
                    mDriverLoc.mNode, _shape, True)
                _loc = _resClosest[0]

                md_res['mDriverLoc'] = mDriverLoc
                md_res['mDrivenLoc'] = cgmMeta.asMeta(_loc)
                md_res['mTrack'] = mTrack

            else:
                log.warning(
                    cgmGEN.logString_msg(
                        _str_func,
                        "Shape type not currently supported for driver setup. Type: {0}"
                        .format(d_closest['type'])))

        #if connectBy is None:
        #return _res
        if connectBy == 'parent':
            mObj.p_parent = _trackTransform
        elif connectBy == 'conPoint':
            mc.pointConstraint(_trackTransform,
                               mObj.mNode,
                               maintainOffset=True)
        elif connectBy == 'conParent':
            mc.parentConstraint(_trackTransform,
                                mObj.mNode,
                                maintainOffset=True)
        elif connectBy == 'parentGroup':
            mGroup = mObj.doGroup(asMeta=True)
            #_grp = TRANS.group_me(obj,True)
            #TRANS.parent_set(_grp,_trackTransform)
            mGroup.p_parent = _trackTransform
            _res = _res + [mGroup.mNode]
        elif connectBy == 'conPointGroup':
            mLoc = mObj.doLoc()
            mLoc.p_parent = _trackTransform
            mGroup = mObj.doGroup(asMeta=True)
            mc.pointConstraint(mLoc.mNode, mGroup.mNode)
            _res = _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)
            _res = _res + [mGroup.mNode]

        elif connectBy == 'conParentGroup':
            mLoc = mObj.doLoc()
            mLoc.p_parent = _trackTransform
            mGroup = mObj.doGroup(asMeta=True)
            mc.parentConstraint(mLoc.mNode, mGroup.mNode)
            _res = _res + [mGroup.mNode]
        elif connectBy is None:
            pass
        else:
            raise NotImplementedError, "|{0}| >>invalid connectBy: {1}".format(
                _str_func, connectBy)

        if md_res:
            return _res, md_res
        return _res

        #pprint.pprint(vars())
    except Exception, err:
        cgmGEN.cgmExceptCB(Exception, err)
Esempio n. 30
0
for mObj in cgmMeta.validateObjListArg(mc.ls(sl=True)):
    mDup = mObj.doDuplicate(po=True, ic=False)
    #RIG.create_at(mObj.mNode,'joint')
    mDup.parent = mObj
    mDup.segmentScaleCompensate = 0
    mDup.doStore('cgmTypeModifier','armor')
    mDup.doName()
    mDup.setAttrFlags(['scale'],lock=False)
    #ATTR.set(mDup.mNode,'segmentScaleCompensate',0)
    

#Clean up...
#Scale driver - 
import cgm.core.classes.NodeFactory as NODEF
arg = "tongue_splineIKCurve.masterScale = head_ik_anim.sy * MasterControl_masterAnim.masterScale"
NODEF.argsToNodes(arg).doBuild()
_crvs = [u'r_uprLip_CRV_splineIKCurve',
         u'r_lwrLip_CRV_splineIKCurve',
         u'l_uprLip_CRV_splineIKCurve',
         u'l_lwrLip_CRV_splineIKCurve']
for crv in _crvs:
    arg = "{0}.masterScale = head_ik_anim.sy * MasterControl_masterAnim.masterScale".format(crv)
    NODEF.argsToNodes(arg).doBuild()
    
    
#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'):
from cgm.core import cgm_Meta as cgmMeta
from cgm.core import cgm_PuppetMeta as cgmPM
import Red9.core.Red9_Meta as r9Meta
import cgm.core
cgm.core._reload()

from cgm.core.classes import SnapFactory as Snap
reload(Snap)
from cgm.core.rigger import TemplateFactory as TemplateF
from cgm.core.rigger import JointFactory as jFactory
from cgm.core.classes import NodeFactory as nodeF
reload(TemplateF)
TemplateF.doOrientTemplateObjectsToMaster(m1)
reload(jFactory)
reload(Rig)
nodeF.validateAttrArg(['spine_1_anchorJoint', 'rz'])
assert 1 == 2

#Optimization - 05.01.2014
part = 'spine_part'
m1 = r9Meta.MetaClass(part)
TemplateF.go(m1, True)

#Get our module
#=======================================================
part = 'spine_part'
part = 'l_leg_part'
m1 = r9Meta.MetaClass(part)
m1 = cgmPM.cgmModule('l_eye_part')
m1.doTemplate()
m1.isSized()
def create(obj,parentTo = False):
    """   
    Create a spacePivot from a given object

    :parameters:
        *a(varied): - Uses validate_arg 

    :returns
        mSpacePivot(metaList)
    """ 
    _str_func = 'create'
    
    #....inital...
    i_obj = cgmMeta.validateObjArg(obj,cgmMeta.cgmObject,noneValid=False)    
    i_parent = cgmMeta.validateObjArg(parentTo,cgmMeta.cgmObject,noneValid=True)    
    bbSize = DIST.get_bb_size(i_obj.mNode)
    size = max(bbSize)

    #>>>Create #====================================================
    #CURVES.create_controlCurve(i_obj.mNode,'jack')
    i_control = cgmMeta.asMeta(CURVES.create_controlCurve(i_obj.mNode,'jack',sizeMode='guess')[0],'cgmObject',setClass=True)
    log.debug(i_control)
    try:l_color = curves.returnColorsFromCurve(i_obj.mNode)
    except Exception,error:raise Exception,"color | %s"%(error)          
    log.debug("l_color: %s"%l_color)
    curves.setColorByIndex(i_control.mNode,l_color[0])
    
    #>>>Snap and Lock
    #====================================================	
    #Snap.go(i_control,i_obj.mNode,move=True, orient = True)

    #>>>Copy Transform
    #====================================================   
    i_newTransform = i_obj.doCreateAt()

    #Need to move this to default cgmNode stuff
    mBuffer = i_control
    i_newTransform.doCopyNameTagsFromObject(i_control.mNode)
    curves.parentShapeInPlace(i_newTransform.mNode,i_control.mNode)#Parent shape
    i_newTransform.parent = mBuffer.parent#Copy parent
    i_control = i_newTransform
    mc.delete(mBuffer.mNode)
    
    #>>>Register
    #====================================================    
    #Attr
    i = ATTR.get_nextAvailableSequentialAttrIndex(i_obj.mNode,"pivot")
    str_pivotAttr = str("pivot_%s"%i)
    str_objName = str(i_obj.getShortName())
    str_pivotName = str(i_control.getShortName())
    
    #Build the network
    i_obj.addAttr(str_pivotAttr,enumName = 'off:lock:on', defaultValue = 2, value = 0, attrType = 'enum',keyable = False, hidden = False)
    i_control.overrideEnabled = 1
    d_ret = NodeF.argsToNodes("%s.overrideVisibility = if %s.%s > 0"%(str_pivotName,str_objName,str_pivotAttr)).doBuild()
    log.debug(d_ret)
    d_ret = NodeF.argsToNodes("%s.overrideDisplayType = if %s.%s == 2:0 else 2"%(str_pivotName,str_objName,str_pivotAttr)).doBuild()
    
    for shape in mc.listRelatives(i_control.mNode,shapes=True,fullPath=True):
        log.debug(shape)
        mc.connectAttr("%s.overrideVisibility"%i_control.mNode,"%s.overrideVisibility"%shape,force=True)
        mc.connectAttr("%s.overrideDisplayType"%i_control.mNode,"%s.overrideDisplayType"%shape,force=True)
    
    #Vis 
    #>>>Name stuff
    #====================================================
    cgmMeta.cgmAttr(i_control,'visibility',lock=True,hidden=True)   
    i_control = cgmMeta.validateObjArg(i_control,'cgmControl',setClass = True)
    i_control.doStore('cgmName',i_obj)
    i_control.addAttr('cgmType','controlAnim',lock=True)    
    i_control.addAttr('cgmIterator',"%s"%i,lock=True)        
    i_control.addAttr('cgmTypeModifier','spacePivot',lock=True)

    i_control.doName(nameShapes=True)

    i_control.addAttr('cgmAlias',(i_obj.getNameAlias()+'_pivot_%s'%i),lock=False)
    
    #Store on object
    #====================================================    
    i_obj.addAttr("spacePivots", attrType = 'message',lock=True)
    _l_spacePivots = i_obj.getMessage('spacePivots',True) or []
    if i_control.getLongName() not in _l_spacePivots:
        #_l_spacePivots = i_obj.getMessage('spacePivots',True)
        #_l_spacePivots.append(i_control.mNode)
        i_obj.msgList_append('spacePivots',i_control,'controlTarget')
    log.debug("spacePivots: %s"%i_obj.msgList_get('spacePivots',asMeta = True))

    #parent
    if i_parent:
        i_control.parent = i_parent.mNode
        i_constraintGroup = (cgmMeta.asMeta(i_control.doGroup(True),'cgmObject',setClass=True))
        i_constraintGroup.addAttr('cgmTypeModifier','constraint',lock=True)
        i_constraintGroup.doName()
        i_control.connectChildNode(i_constraintGroup,'constraintGroup','groupChild')	

        log.debug("constraintGroup: '%s'"%i_constraintGroup.getShortName())		

    #change to cgmControl
    i_control = cgmMeta.asMeta(i_control.mNode,'cgmControl', setClass=1)

    return i_control
Esempio n. 33
0
obj = ''
objList = []
objList = mc.ls(sl=True)
cgmMeta.cgmObject(obj).createTransformFromObj()


#>>> connect_controlWiring
#=======================================================
reload(NodeF)
_obj = 'face_attrHolder'

_wiringDict = {'mouth_up':{'driverAttr':'ty'},'mouth_dn':{'driverAttr':'-ty'},'mouth_right':{'driverAttr':'-tx'}}

_wiringDict = {'mouth_up':{'driverAttr':'ty','driverAttr2':'tx','mode':'cornerBlend'}}

NodeF.connect_controlWiring('mouth_anim',_obj,_wiringDict,baseName = 33)

NodeF.connect_controlWiring('upper_lipRoll_anim',_obj,_wiringDict,baseName = 33)


#>>> createAndConnectBlendColors
#=======================================================
NodeF.createAndConnectBlendColors('l_knee_seg_0_jnt_Transform_anchor','l_knee_seg_0_jnt_Transform_aim','l_knee_seg_0_jnt_Transform_attach','l_knee_ik_1_anim.followRoot','rotate')


#>>> single blend
#=======================================================
driver = 'null1.FKIK'
result1 = 'null1.resultFK'
result2 = 'null1.resultIK'
NodeF.createSingleBlendNetwork(driver, result1, result2,keyable=True)