Ejemplo n.º 1
0
def getUParamOnCurve(obj = None, crv = None):
    """
    Props to Marco Giordano for this method. Oddly, the distance method is faster....

    @Parameters
    curve -- must be a curve instance or obj string
    points -- number of points you want on the curve

    returns param
    """
    _str_funcName = 'getUParamOnCurve'
    log.info(">>> %s >> "%_str_funcName + "="*75)
    mi_obj = cgmValid.objString(obj)
    mi_crv = cgmValid.objString(crv,mayaType='nurbsCurve')
    mi_shape = cgmMeta.validateObjArg(mc.listRelatives(mi_crv,shapes = True)[0],mayaType='shape')
    pos = mc.xform(mi_obj,q=True, t=True, ws=True)
    point = OpenMaya.MPoint(pos[0],pos[1],pos[2])
    #object.__getattribute__(self, "_MObject")
    curveFN = OpenMaya.MFnNurbsCurve(mi_shape.__getattribute__("_MObject"))
    paramUtil = OpenMaya.MScriptUtil()
    paramPtr = paramUtil.asDoublePtr()
    isOnCurve = curveFN.isPointOnCurve(point)
    if isOnCurve:
	curveFN.getParamAtPoint(point,paramPtr,0.001,OpenMaya.MSpace.kObject)
    else:
	point = curveFN.closestPoint(point,paramPtr,0.001,OpenMaya.MSpace.kObject)
	curveFN.getParamAtPoint(point,paramPtr,0.001,OpenMaya.MSpace.kObject)

    buffer = paramPtr
    del(paramPtr)
    return paramUtil.getDouble(buffer)
Ejemplo n.º 2
0
def aim(obj = None, target = None, aimAxis = "z+", upAxis = "y+",mode = 'local',vectorUp = None):
    """
    Aim functionality.
    
    :parameters:
        obj(str): Object to modify
        target(str): object to copy from
        aimAxis(str): axis that is pointing forward
        upAxis(str): axis that is pointing up
        vectorUp(vector): Only relevent during vector mode
        mode(str): 
            'local'-- use standard maya aiming with local axis
            'world' -- use standard maya aiming with world axis
            'matrix' -- use Bokser's fancy method
            'vector' -- maya standard with vector up axis
    :returns
        success(bool)
    """  
    _str_func = 'aim'
          
    _obj = VALID.objString(obj, noneValid=False, calledFrom = __name__ + _str_func + ">> validate obj")
    _target = VALID.objString(target, noneValid=False, calledFrom = __name__ + _str_func + ">> validate target")

    targetPos = POS.get(_target)
    log.debug("|{0}| >> obj: {1} | target:{2} | mode: {3}".format(_str_func,_obj,_target,mode))             

    aim_atPoint(_obj, targetPos, aimAxis, upAxis, mode,vectorUp)

    return True
Ejemplo n.º 3
0
    def bakeTempLocator(self, startTime=None, endTime=None):
        _str_func = 'PostBake.bakeTempLocator'

        if startTime is None:
            startTime = self.startTime
        if endTime is None:
            endTime = self.endTime

        ct = mc.currentTime(q=True)

        self._bakedLoc = cgmMeta.asMeta(LOC.create(name='bakeLoc'))
        self._bakedLoc.rotateOrder = self.obj.rotateOrder

        SNAP.matchTarget_set(self._bakedLoc.mNode, self.obj.mNode)

        _len = endTime - startTime
        _progressBar = cgmUI.doStartMayaProgressBar(_len, "Processing...")

        _obj = VALID.objString(self._bakedLoc.mNode, noneValid=False)
        _target = VALID.objString(
            self.obj.mNode, noneValid=False
        )  #ATTR.get_message(_obj, 'cgmMatchTarget','cgmMatchDat',0)

        ak = mc.autoKeyframe(q=True, state=True)
        mc.autoKeyframe(state=False)
        mc.refresh(su=True)

        completed = True

        for i in range(startTime, endTime + 1):
            mc.currentTime(i)
            SNAP.go(_obj, _target, True, True, pivot='rp')
            mc.setKeyframe(_obj, at=['translate', 'rotate'])

            if _progressBar:
                if mc.progressBar(_progressBar, query=True, isCancelled=True):
                    log.warning('Bake cancelled!')
                    completed = False
                    break

                mc.progressBar(_progressBar,
                               edit=True,
                               status=("{0} On frame {1}".format(_str_func,
                                                                 i)),
                               step=1,
                               maxValue=_len)

        mc.refresh(su=False)
        mc.autoKeyframe(state=ak)

        cgmUI.doEndMayaProgressBar(_progressBar)

        mc.currentTime(ct)

        return completed
Ejemplo n.º 4
0
	def __func__(self):
	    """
	    """
	    obj = cgmValid.objString(self.d_kws['obj'],isTransform=True)
	    crv = cgmValid.objString(self.d_kws['crv'],mayaType='nurbsCurve')	
	    d_returnBuff = distance.returnNearestPointOnCurveInfo(obj,crv)
	    mi_poci = cgmMeta.cgmNode(nodeType = 'pointOnCurveInfo')
	    mc.connectAttr("%s.worldSpace"%d_returnBuff['shape'],"%s.inputCurve"%mi_poci.mNode)
	    mi_poci.parameter = d_returnBuff['parameter']
	    mc.connectAttr("%s.position"%mi_poci.mNode,"%s.t"%obj)
	    mi_poci.doStore('cgmName',obj)
	    mi_poci.doName()
	    
	    return True
Ejemplo n.º 5
0
 def _fncStep_dataCheck_(self):
     #Key to object name dict
     _d_stuffToFind = {'headModule':'head_part',
                       'neckModule':'neck_part',
                       'l_eyeModule':'l_eye_part',
                       'r_eyeModule':'r_eye_part',
                       'headMasterAnim':'Head_masterAnim',
                       'headPuppet':'Head_puppetNetwork',
                       'BodyPuppet':'MK1_puppetNetwork',
                       'faceGui':'facialRig_gui_grp',
                       'faceCam':'faceCam',
                       'world_eyeLook':'world_driving_head_eyeLook_dynDriver',
                       'world_leftEye':'world_driving_right_eye_ik_dynDriver',
                       'world_rightEye':'world_driving_left_eye_ik_dynDriver',
                       'SDKface':'face_attrHolder',
                       'SDKcustomize':'sdk_custom_attrHolder',
                       'joint_bodyHead':'head_jnt',
                       'joint_faceRigHead':'headRoot_jnt',
                       'ik_eyes':'head_eyeLook_anim',
                       'ik_l_eye':'l_eye_ik_anim',
                       'ik_r_eye':'r_eye_ik_anim',
                       'ik_shoulders':'shoulders_ik_anim',
                       'ik_cog':'cog_anim',
                       }
     self.md_objs = {}
     for k in _d_stuffToFind.keys():
         _obj = cgmValid.objString(arg=_d_stuffToFind[k], noneValid=True, 
                                   calledFrom=self._str_funcName)
         if not _obj:
             return self._FailBreak_("key: {0} | name: ('{1}') | missing".format(k,_d_stuffToFind[k]))
         self.md_objs[k] = cgmMeta.cgmNode(_obj)
         self.log_info("'{0}' found".format(k))
     
     self.log_infoNestedDict('md_objs')
Ejemplo n.º 6
0
 def test_falseIfNotObjExistsAndNoneValid(self):
     self.assertFalse(
         validateArgs.objString(arg="does_not_exist",
                                noneValid=True),
         "validateArgs.objString did not return false when the object "+\
         "did not exist and noneValid was set to True"
     )
Ejemplo n.º 7
0
def offsetShape_byVector(dag=None,
                         distance=1,
                         origin=None,
                         component='cv',
                         vector=None,
                         mode='origin',
                         factor=.5,
                         offsetMode='fixed'):
    """
    Attempt for more consistency 
    
    If origin is None, juse the center of each shape
    """
    _str_func = 'offsetShape_byVector'
    log.debug(
        "|{0}| >> dag: {1} | distance: {2} | origin: {3} | component: {4}".
        format(_str_func, dag, distance, origin, component))

    _originUse = None

    if VALID.isListArg(origin):
        _originUse = origin
    elif VALID.objString(origin, noneValid=True):
        log.debug(
            "|{0}| >> Getting origin from transform of origin string: {1}".
            format(_str_func, origin))
        _originUse = POS.get(origin)

    if VALID.is_shape(dag):
        l_shapes = [dag]
    else:
        l_shapes = mc.listRelatives(dag, shapes=True, fullPath=True)

    for i, s in enumerate(l_shapes):
        log.debug("|{0}| >> On shape: {1}".format(_str_func, s))
        if _originUse is None:
            #_trans = VALID.getTransform(dag)
            _origin = POS.get_bb_center(s)
            log.debug("|{0}| >> Getting origin from center of s: {1}".format(
                _str_func, _origin))
        else:
            _origin = _originUse

        _l_source = mc.ls("{0}.{1}[*]".format(s, component),
                          flatten=True,
                          long=True)

        for ii, c in enumerate(_l_source):
            log.debug("|{0}| >> Shape {1} | Comp: {2} | {3}".format(
                _str_func, i, ii, c))
            if offsetMode == 'fixed':
                set_vectorOffset(c, _origin, distance, vector, mode=mode)
            else:
                pMe = POS.get(c)
                _vec = MATHUTILS.get_vector_of_two_points(_origin, pMe)
                d = get_distance_between_points(_origin, pMe)
                newPos = get_pos_by_vec_dist(POS.get(c), _vec, d * factor)
                POS.set(c, newPos)

    return True
Ejemplo n.º 8
0
def position(target = None, infoDict = None, move = True, rotate = True):
    """
    Get data for updating a loc

    :parameters
        target(str): What to use for updating our loc

    :returns
        info(dict)
    """   
    _str_func = "position"
    _target = VALID.objString(target, noneValid=True, calledFrom = __name__ + _str_func + ">> validate target")

    pos = infoDict['position']

    if move:
        mc.move (pos[0],pos[1],pos[2], _target, ws=True)
    if rotate:
        if infoDict.get('rotateOrder'):mc.xform(_target, roo=infoDict['rotateOrder'],p=True)
        if infoDict.get('rotation'):mc.xform(_target, ro=infoDict['rotation'], ws = True)
        if infoDict.get('rotateAxis'):mc.xform(_target, ra=infoDict['rotateAxis'],p=True)

    #mTarget = r9Meta.getMObject(target)
    mc.xform(_target, rp=infoDict['position'], ws = True, p=True)        
    if infoDict.get('scalePivot'):mc.xform(_target, sp=infoDict['scalePivot'], ws = True, p=True)    

    #Rotate
    #if infoDict['objectType'] == 'polyFace':
        #constBuffer = mc.normalConstraint((locInfo['createdFrom']),locatorName)
        #mc.delete(constBuffer[0])

    return True
 def test_falseIfNotObjExistsAndNoneValid(self):
     self.assertFalse(
         validateArgs.objString(arg="does_not_exist",
                                noneValid=True),
         "validateArgs.objString did not return false when the object "+\
         "did not exist and noneValid was set to True"
     )
Ejemplo n.º 10
0
def aim_atMidPoint(obj = None, targets = None, aimAxis = "z+", upAxis = "y+",mode='local',vectorUp = None):
    """
    Aim functionality.
    
    :parameters:
        obj(str): Object to modify
        target(str): object to copy from
        aimAxis(str): axis that is pointing forward
        upAxis(str): axis that is pointing up
        vectorUp(vector): Only relevent during vector mode
        mode(str): 
            'local'-- use standard maya aiming with local axis
            'world' -- use standard maya aiming with world axis
            'matrix' -- use Bokser's fancy method
            'vector' -- maya standard with vector up axis
    :returns
        success(bool)
    """  
    _str_func = 'aimAtMidpoint'
    
    _obj = VALID.objString(obj, noneValid=False, calledFrom = __name__ + _str_func + ">> validate obj")
    _targets = VALID.objStringList(targets, noneValid=False, calledFrom = __name__ + _str_func + ">> validate targets")

    targetPos = MATH.Vector3.zero()

    for t in _targets:
        targetPos += MATH.Vector3.Create(POS.get(t))

    targetPos /= len(_targets)

    aim_atPoint(_obj, MATH.Vector3.AsArray(targetPos), aimAxis, upAxis,mode = mode,vectorUp=vectorUp)
 def test_falseIfWrongMayaTypeNoneValid(self):
     self.assertFalse(
         validateArgs.objString(
             arg=self.maya_obj,
             mayaType='plusMinusAverage',
             noneValid=True
         )
     )
 def test_passIfRightMayaType(self):
     self.assertEquals(
         validateArgs.objString(
             arg=self.maya_obj,
             mayaType='multiplyDivide'
         ),
         self.maya_obj
     )
 def test_passIfIsTransform(self):
     self.assertTrue(
         validateArgs.objString(
             arg=self.maya_obj,
             isTransform=True
         ),
         self.maya_obj
     )
 def test_falseIfNotTransformNoneValid(self):
     print "test_falseIfNotTransformNoneValid"
     self.assertFalse(
         validateArgs.objString(
             arg=self.nonTransform,
             isTransform=True,
             noneValid=True
         )
     )
Ejemplo n.º 15
0
def matchTarget_set(obj = None, target = None):
    """
    Set the match target of an object
    
    :parameters:
        obj(str): Object to modify
        target(str): Target to match

    :returns
        success(bool)
    """     
    _str_func = 'matchTarget_set'
        
    _obj = VALID.objString(obj, noneValid=False, calledFrom = __name__ + _str_func + ">> validate obj")
    _target = VALID.objString(target, noneValid=False, calledFrom = __name__ + _str_func + ">> validate target")
    
    ATTR.set_message(_obj, 'cgmMatchTarget',_target,'cgmMatchDat',0)
    
    return True
Ejemplo n.º 16
0
def get_createSize(arg=None, mode=None):
    """
    Attempt to find a good size for control creation or 
    
    :parameters:
        arg(str/list): Object(s) to check


    :returns
        boundingBox size(list)
    """
    def is_resGood(res=None):
        if MATHUTILS.is_float_equivalent(res, 0.000) or res == -2e+20:
            return False
        return True

    _str_func = 'get_createSize'
    _arg = VALID.objString(arg, noneValid=False, calledFrom=_str_func)
    log.debug("|{0}| >> arg: '{1}' ".format(_str_func, _arg))

    _bb_max = get_bb_size(_arg, True, True)
    log.debug("|{0}| >> bbSize: {1} ".format(_str_func, _bb_max))
    if not MATHUTILS.is_float_equivalent(_bb_max,
                                         0.000) and not _bb_max == -2e+20:
        return _bb_max

    log.debug("|{0}| >> Zero boundingBox object...".format(_str_func))

    _children = mc.listRelatives(_arg, children=True,
                                 type='transform') or False
    if _children:
        _closestChild = get_by_dist(_arg, _children, 'close', 'object')
        log.debug("|{0}| >> closest child mode. | closest: {1} ".format(
            _str_func, _closestChild))
        _res = get_distance_between_points(POS.get(_arg),
                                           POS.get(_closestChild))
        if is_resGood(_res):
            return _res
        log.debug("|{0}| >> child mode fail...".format(_str_func))

    _parent = mc.listRelatives(_arg, parent=True, type='transform') or False
    if _parent:
        log.debug("|{0}| >> Parent mode...".format(_str_func))
        _res = get_distance_between_points(POS.get(_arg), POS.get(_parent))
        if is_resGood(_res):
            return _res
        log.debug("|{0}| >> Parent mode fail...".format(_str_func))

    raise RuntimeError, "Shouldn't have gotten here. Failed at finding value"
Ejemplo n.º 17
0
def matchTarget_snap(obj=None,
                     move=True,
                     rotate=True,
                     boundingBox=False,
                     pivot='rp'):
    """
    Snap an object to it's match target
    
    :parameters:
        obj(str): Object to modify
        target(str): Target to match

    :returns
        success(bool)
    """
    _str_func = 'matchTarget_snap'

    _obj = VALID.objString(obj,
                           noneValid=False,
                           calledFrom=__name__ + _str_func + ">> validate obj")

    _target = ATTR.get_message(_obj, 'cgmMatchTarget', 'cgmMatchDat', 0)

    if not _target:
        raise ValueError, "|{0}| >> {1} has no cgmMatchTarget.".format(
            _str_func, NAMES.get_short(_obj))

    log.debug("|{0}| >> {1} snapping to: {2}.".format(_str_func,
                                                      NAMES.get_short(_obj),
                                                      _target[0]))

    go(obj, _target[0], move, rotate, pivot=pivot)
    return True

    _dict = POS.get_info(_target[0])

    #cgmGEN.log_info_dict(_dict)

    pos = _dict['position']

    if move:
        mc.move(pos[0], pos[1], pos[2], _obj, ws=True, rpr=True)
    if rotate:
        #if _dict.get('rotateOrder'):mc.xform(_obj, roo=_dict['rotateOrder'],p=True)
        if _dict.get('rotation'): mc.xform(_obj, ro=_dict['rotation'], ws=True)
        #if _dict.get('rotateAxis'):mc.xform(_obj, ra=_dict['rotateAxis'],p=True)

    return True
Ejemplo n.º 18
0
def verify_aimAttrs(obj=None, aim=None, up=None, checkOnly=False):
    """
    Make sure an object has aim attributes.
    
    :parameters:
        obj(str): Object to modify
        aim(arg): Value to set with on call
        up(arg): Value to set with on call
        out(arg): Value to set with on call
        checkOnly(bool): Check only, no adding attrs

    :returns
        success(bool)
    """
    _str_func = 'verify_aimAttrs'
    _str_enum = 'x+:y+:z+:x-:y-:z-'

    _obj = VALID.objString(obj,
                           noneValid=False,
                           calledFrom=__name__ + _str_func + ">> validate obj")

    _l = [aim, up]
    _l_defaults = [aim or 2, up or 1]

    for i, a in enumerate(['axisAim', 'axisUp']):
        _d = ATTR.validate_arg(_obj, a)
        _good = False
        if mc.objExists(_d['combined']):
            if ATTR.get_type(_d) == 'enum':
                if ATTR.get_enum(_d) == _str_enum:
                    _good = True
        if not _good:
            if checkOnly:
                return False
            log.debug("|{0}| >> {1} not a good attr. Must rebuild".format(
                _str_func, _d['combined']))
            ATTR.delete(_d)
            ATTR.add(_d, 'enum', enumOptions=_str_enum, hidden=False)
            ATTR.set(_d, value=_l_defaults[i])
            ATTR.set_keyable(_d, False)
        _v = _l[i]
        if _v is not None:
            ATTR.set(_d, value=_v)

    return True
Ejemplo n.º 19
0
def matchTarget_clear(obj = None):
    """
    Clear the match target of an object
    
    :parameters:
        obj(str): Object to modify

    :returns
        success(bool)
    """     
    _str_func = 'matchTarget_set'
    
    _obj = VALID.objString(obj, noneValid=False, calledFrom = __name__ + _str_func + ">> validate obj")
    
    ATTR.delete(_obj,'cgmMatchTarget')
    ATTR.delete(_obj,'cgmMatchDat')
    
    return True
Ejemplo n.º 20
0
def get_info(target=None, boundingBox=False):
    """
    Get data for updating a transform
    
    :parameters
        target(str): What to use for updating our loc

    :returns
        info(dict)
    """
    _str_func = "get_info"
    _target = VALID.objString(target,
                              noneValid=True,
                              calledFrom=__name__ + _str_func +
                              ">> validate target")

    _posPivot = 'rp'
    if boundingBox:
        _posPivot = 'boundingBox'

    _transform = VALID.getTransform(target)

    log.debug("|{0}| >> Target: {1}  | tranform: {2}".format(
        _str_func, _target, _transform))

    _d = {}
    _d['createdFrom'] = _target
    _d['objectType'] = VALID.get_mayaType(_target)
    _d['position'] = get(target, _posPivot, 'world')
    _d['translate'] = get(target, _posPivot, 'local')
    _d['scalePivot'] = get(_transform, 'sp', 'world')
    _d['rotation'] = mc.xform(_transform, q=True, ws=True, ro=True)
    _d['rotateOrder'] = mc.xform(_transform, q=True, roo=True)
    _d['rotateAxis'] = mc.xform(_transform, q=True, os=True, ra=True)
    _d['rotateLocal'] = mc.xform(_transform, q=True, os=True, ro=True)

    #cgmGen.log_info_dict(_d,'|{0}.{1}| info...'.format(__name__,_str_func))

    return _d
Ejemplo n.º 21
0
def get_normalized_uv(mesh, uValue, vValue):
    """
    uv Values from many functions need to be normalized to be correct when using those values for other functions

    The calculcaion for doing so is 
    size = maxV - minV
    sum = rawV + minV
    normalValue = sum / size
    
    :parameters:
        mesh(string) | Surface to normalize to
        uValue(float) | uValue to normalize 
        vValue(float) | vValue to normalize 

    :returns
        Dict ------------------------------------------------------------------
        'uv'(double2) |  point from which we cast
        'uValue'(float) | normalized uValue
        'vValue'(float) | normalized vValue

    :raises:
        Exception | if reached
    """
    _str_func = 'get_normalized_uv'

    try:
        try:  #Validation ----------------------------------------------------------------
            reload(VALID)
            _mesh = VALID.objString(mesh, 'nurbsSurface', calledFrom=_str_func)
            #log.debug("|{0}| >> mesh arg: {1} | validated: {2}".format(_str_func,mesh,_mesh))

            if not SEARCH.is_shape(_mesh):
                shape = mc.listRelatives(_mesh, shapes=True)[0]
                log.debug(
                    "|{0}| >> Transform provided. using first shape: {1}".
                    format(_str_func, shape))
            else:
                shape = _mesh

            uMin = ATTR.get(shape, 'mnu')
            uMax = ATTR.get(shape, 'mxu')
            vMin = ATTR.get(shape, 'mnv')
            vMax = ATTR.get(shape, 'mxv')
            """uMin = mi_shape.mnu
            uMax = mi_shape.mxu
            vMin = mi_shape.mnv
            vMax = mi_shape.mxv"""

        except Exception, error:
            raise Exception, "Validation failure | {0}".format(error)

        try:  #Calculation ----------------------------------------------------------------
            uSize = uMax - uMin
            vSize = vMax - vMin

            uSum = uMin + uValue
            vSum = vMin + vValue

            uNormal = uSum / uSize
            vNormal = vSum / vSize
        except Exception, error:
            raise Exception, "Calculation |{0}".format(error)
Ejemplo n.º 22
0
        else:
            log.error("|{0}| >> unknown mode: {1}".format(_str_func, _mode))
            return False

        try:
            return position(**_kws)
        except Exception, err:
            log.error("|{0}| >> loc: {1}".format(_str_func, loc))
            cgmGeneral.log_info_dict(_kws['infoDict'],
                                     "{0} >> {1}".format(_str_func, mode))
            log.error("|{0}| >> err: {1}".format(_str_func, _err))
            return False

    _str_func = "update"
    _loc = VALID.objString(loc,
                           noneValid=True,
                           calledFrom=__name__ + _str_func + ">> validate loc")
    _type = VALID.get_mayaType(_loc)

    _targets = VALID.listArg(targets)

    if _type == 'locator':
        if mode and _targets:
            log.debug("|{0}| >> mode override...".format(_str_func))

            return getAndMove(_loc, _targets, mode, forceBBCenter)

        elif _targets:
            log.debug("|{0}| >> source mode...".format(_str_func))
            if len(_targets) > 1:
                log.debug("|{0}| >> assuming midPoint...".format(_str_func))
Ejemplo n.º 23
0
 def _fnc_processInfluenceMode(self):
     '''
     Sort out the joint data
     
     If joitn list is passed, try to use that, if not,
     Try skin cluster on target, cluster on source
     '''
     _mode = self._influenceMode
     _l_configInfluenceList = self.get_ConfigJointList()#...get our config influence list
     self.l_configInfluenceList = _l_configInfluenceList#...store it
     _len_configList = len(_l_configInfluenceList)
     _targetMesh = self.mData.d_target['mesh']
     #...See if we have a skin cluster...
     _targetSkin = skinning.querySkinCluster(_targetMesh) or False            
     
     if _mode == 'config':
         _l_jointTargets = _l_configInfluenceList
         
     elif _mode == 'list':
         _l_joints = self.d_kws.get('jointList')
         if not _l_joints:
             return self._FailBreak_("jointList kw required. '{0}' influenceMode".format(_mode))                
         if not cgmValid.isListArg(_l_joints):
             return self._FailBreak_("jointList is not a list. '{0}' influenceMode".format(_mode))                
         if len(_l_joints) != len(_l_configInfluenceList):
             return self._FailBreak_("Non matching counts on target influences({0}) and config data({1}) | Cannot use '{2}' influenceMode".format(len(_l_joints),len(_l_configInfluenceList),_mode))                
         _l_jointTargets = _l_joints
        
     elif _mode == 'target':
         if not _targetSkin:
             return self._FailBreak_("Target mesh not skinned, cannot use '{0}' influenceMode".format(_mode))                
         _l_targetInfluences = mc.listConnections(_targetSkin+'.matrix') or []
         
         if len(_l_targetInfluences) != len(_l_configInfluenceList):
             #for i,jnt in enumerate(_l_configInfluenceList):
                 #try:_bfr = _l_targetInfluences[i]
                 #except:
                 #    _bfr = False    
                 #self.log_info("{0} | Config: {1} | target: {2}".format(i,jnt,_bfr))
             
             if self._b_addMissingInfluences:
                 self._b_case_addMissingInfluences = True#...set our case
             else: return self._FailBreak_("Non matching counts on target influences({0}) and config data({1}) | Cannot use '{2}' influenceMode".format(len(_l_targetInfluences),len(_l_configInfluenceList),_mode))                
             
         _l_jointTargets = _l_targetInfluences
         
     elif _mode == 'source':
         if not self.mData.d_source:
             return self._FailBreak_("No source data found, cannot use '{0}' influenceMode".format(_mode))                
         _sourceSkin = skinning.querySkinCluster(self.mData.d_source['mesh']) or False
         _l_sourceInfluences = mc.listConnections(_sourceSkin+'.matrix') or []
         
         if len(_l_sourceInfluences) != len(_l_configInfluenceList):
             return self._FailBreak_("Non matching counts on source influences({0}) and config data({1}) | Cannot use '{2}' influenceMode".format(len(_l_sourceInfluences),len(_l_configInfluenceList),_mode))                
         
         _l_jointTargets = _l_sourceInfluences
         
     
     if self._b_case_addMissingInfluences:#Missing Influence Add...
         self.log_info("addMissingInfluencesAttempt... "+ cgmGeneral._str_subLine)
         if _len_configList < len(_l_jointTargets):
             self.log_warning("More targetJoints({0}) than config joints({1}). Not implemented".format(len(_l_jointTargets),_len_configList))
         else:
             _d = {}
             
             for i,v in enumerate(_l_jointTargets):_d[i] = v#...push stuff to a list
             
             for i,jnt in enumerate(_l_configInfluenceList):
                 try:_bfr = _l_jointTargets[i]
                 except:
                     _l_search = [jnt, self.mData.d_sourceSkin['matrix'][i]]
                     self.log_info("{0} | Config: {1} | missing joint. Attempting to find: {2}".format(i,jnt,_l_search))
                     for o in _l_search:
                         foundJnt = cgmValid.objString(o, mayaType = _validObjTypes, noneValid=True)#...mayaType = 'joint', 
                         if foundJnt:
                             _d[i] = foundJnt
                             self._l_missingInfluences.append(foundJnt)
                             self.log_info("Found {0}".format(foundJnt))
                             break
                         return self._FailBreak_("{0} | Not able to fo find joint ({1})".format(i,jnt))                
             #...push back to our list
             _l_jointTargets = []
             for i in range(_len_configList):_l_jointTargets.append(False)
             for i,v in _d.iteritems():
                 _l_jointTargets[i] = v
                 #self.log_info("{0} | Config: {1} | target: {2}".format(i,jnt,_bfr))     
         #self.log_info("Joints to use....")
         #for i,j in enumerate(_l_jointsToUse):
             #self.log_info("{0} : {1} | config idxed to: {2}".format(i,j,_l_configInfluenceList[i]))
         
     #...see if they exist with no conflicts
     #_l_jointTargets = l_dataJoints#...this will change
     try:_l_jointsToUse = cgmValid.objStringList(_l_jointTargets,mayaType = _validObjTypes)#...mayaType = 'joint'
     except Exception,Error:return self._FailBreak_("influenceMode '{0}' joint check fail | {1}".format(_mode,Error))
     
     self.l_jointsToUse = _l_jointsToUse
Ejemplo n.º 24
0
 def test_falseIfNotTransformNoneValid(self):
     print "test_falseIfNotTransformNoneValid"
     self.assertFalse(
         validateArgs.objString(arg=self.nonTransform,
                                isTransform=True,
                                noneValid=True))
Ejemplo n.º 25
0
 def test_passIfIsTransform(self):
     self.assertTrue(
         validateArgs.objString(arg=self.maya_obj, isTransform=True),
         self.maya_obj)
Ejemplo n.º 26
0
def returnNormalizedUV(mesh, uValue, vValue):
    """
    uv Values from many functions need to be normalized to be correct when using those values for other functions
    
    The calculcaion for doing so is 
    size = maxV - minV
    sum = rawV + minV
    normalValue = sum / size
    
    :parameters:
	mesh(string) | Surface to normalize to
	uValue(float) | uValue to normalize 
	vValue(float) | vValue to normalize 

    :returns:
	Dict ------------------------------------------------------------------
	'uv'(double2) |  point from which we cast
	'uValue'(float) | normalized uValue
	'vValue'(float) | normalized vValue
	
    :raises:
	Exception | if reached
	
    """      
    try:
	_str_funcName = 'returnNormalizedUV'

	try:#Validation ----------------------------------------------------------------
	    mesh = cgmValid.objString(mesh,'nurbsSurface', calledFrom = _str_funcName)
	    if len(mc.ls(mesh))>1:
		raise StandardError,"{0}>>> More than one mesh named: {1}".format(_str_funcName,mesh)
	    _str_objType = search.returnObjectType(mesh)
	    
	    l_shapes = mc.listRelatives(mesh, shapes=True)
	    if len(l_shapes)>1:
		log.debug( "More than one shape found. Using 0. targetSurface : %s | shapes: %s"%(mesh,l_shapes) )
	    mi_shape = cgmMeta.validateObjArg(l_shapes[0],cgmMeta.cgmNode,noneValid=False)
	    
	    uMin = mi_shape.mnu
	    uMax = mi_shape.mxu
	    vMin = mi_shape.mnv
	    vMax = mi_shape.mxv
	    
	except Exception,error:raise Exception,"Validation failure | {0}".format(error) 		

	try:#Calculation ----------------------------------------------------------------
	    uSize = uMax - uMin
	    vSize = vMax - vMin
	    
	    uSum = uMin + uValue
	    vSum = vMin + vValue
	    
	    uNormal = uSum / uSize
	    vNormal = vSum / vSize
	except Exception,error:raise Exception,"Calculation |{0}".format(error) 		
	    
	try:
	    d_return = {'uv':[uNormal,vNormal],'uValue':uNormal,'vValue':vNormal}
	    return d_return 
	except Exception,error:raise Exception,"Return prep |{0}".format(error) 		

    except Exception,error:
	log.error(">>> {0} >> Failure! mesh: '{1}' | uValue: {2} | vValue {3}".format(_str_funcName,mesh,uValue,vValue))
	log.error(">>> {0} >> error: {1}".format(_str_funcName,error))        
	return None
Ejemplo n.º 27
0
 def _fnc_processInfluenceMode(self):
     '''
     Sort out the joint data
     
     If joitn list is passed, try to use that, if not,
     Try skin cluster on target, cluster on source
     '''
     _mode = self._influenceMode
     _l_configInfluenceList = self.get_ConfigJointList()#...get our config influence list
     self.l_configInfluenceList = _l_configInfluenceList#...store it
     _len_configList = len(_l_configInfluenceList)
     _targetMesh = self.mData.d_target['mesh']
     #...See if we have a skin cluster...
     _targetSkin = skinning.querySkinCluster(_targetMesh) or False            
     
     if _mode == 'config':
         _l_jointTargets = _l_configInfluenceList
         
     elif _mode == 'list':
         _l_joints = self.d_kws.get('jointList')
         if not _l_joints:
             return self._FailBreak_("jointList kw required. '{0}' influenceMode".format(_mode))                
         if not cgmValid.isListArg(_l_joints):
             return self._FailBreak_("jointList is not a list. '{0}' influenceMode".format(_mode))                
         if len(_l_joints) != len(_l_configInfluenceList):
             return self._FailBreak_("Non matching counts on target influences({0}) and config data({1}) | Cannot use '{2}' influenceMode".format(len(_l_joints),len(_l_configInfluenceList),_mode))                
         _l_jointTargets = _l_joints
        
     elif _mode == 'target':
         if not _targetSkin:
             return self._FailBreak_("Target mesh not skinned, cannot use '{0}' influenceMode".format(_mode))                
         _l_targetInfluences = mc.listConnections(_targetSkin+'.matrix') or []
         
         if len(_l_targetInfluences) != len(_l_configInfluenceList):
             #for i,jnt in enumerate(_l_configInfluenceList):
                 #try:_bfr = _l_targetInfluences[i]
                 #except:
                 #    _bfr = False    
                 #self.log_info("{0} | Config: {1} | target: {2}".format(i,jnt,_bfr))
             
             if self._b_addMissingInfluences:
                 self._b_case_addMissingInfluences = True#...set our case
             else: return self._FailBreak_("Non matching counts on target influences({0}) and config data({1}) | Cannot use '{2}' influenceMode".format(len(_l_targetInfluences),len(_l_configInfluenceList),_mode))                
             
         _l_jointTargets = _l_targetInfluences
         
     elif _mode == 'source':
         if not self.mData.d_source:
             return self._FailBreak_("No source data found, cannot use '{0}' influenceMode".format(_mode))                
         _sourceSkin = skinning.querySkinCluster(self.mData.d_source['mesh']) or False
         _l_sourceInfluences = mc.listConnections(_sourceSkin+'.matrix') or []
         
         if len(_l_sourceInfluences) != len(_l_configInfluenceList):
             return self._FailBreak_("Non matching counts on source influences({0}) and config data({1}) | Cannot use '{2}' influenceMode".format(len(_l_sourceInfluences),len(_l_configInfluenceList),_mode))                
         
         _l_jointTargets = _l_sourceInfluences
         
     
     if self._b_case_addMissingInfluences:#Missing Influence Add...
         self.log_info("addMissingInfluencesAttempt... "+ cgmGeneral._str_subLine)
         if _len_configList < len(_l_jointTargets):
             self.log_warning("More targetJoints({0}) than config joints({1}). Not implemented".format(len(_l_jointTargets),_len_configList))
         else:
             _d = {}
             
             for i,v in enumerate(_l_jointTargets):_d[i] = v#...push stuff to a list
             
             for i,jnt in enumerate(_l_configInfluenceList):
                 try:_bfr = _l_jointTargets[i]
                 except:
                     _l_search = [jnt, self.mData.d_sourceSkin['matrix'][i]]
                     self.log_info("{0} | Config: {1} | missing joint. Attempting to find: {2}".format(i,jnt,_l_search))
                     for o in _l_search:
                         foundJnt = cgmValid.objString(o, mayaType = _validObjTypes, noneValid=True)#...mayaType = 'joint', 
                         if foundJnt:
                             _d[i] = foundJnt
                             self._l_missingInfluences.append(foundJnt)
                             self.log_info("Found {0}".format(foundJnt))
                             break
                         return self._FailBreak_("{0} | Not able to fo find joint ({1})".format(i,jnt))                
             #...push back to our list
             _l_jointTargets = []
             for i in range(_len_configList):_l_jointTargets.append(False)
             for i,v in _d.iteritems():
                 _l_jointTargets[i] = v
                 #self.log_info("{0} | Config: {1} | target: {2}".format(i,jnt,_bfr))     
         #self.log_info("Joints to use....")
         #for i,j in enumerate(_l_jointsToUse):
             #self.log_info("{0} : {1} | config idxed to: {2}".format(i,j,_l_configInfluenceList[i]))
         
     #...see if they exist with no conflicts
     #_l_jointTargets = l_dataJoints#...this will change
     try:_l_jointsToUse = cgmValid.objStringList(_l_jointTargets,mayaType = _validObjTypes)#...mayaType = 'joint'
     except Exception,Error:return self._FailBreak_("influenceMode '{0}' joint check fail | {1}".format(_mode,Error))
     
     self.l_jointsToUse = _l_jointsToUse
Ejemplo n.º 28
0
 def test_passIfRightMayaType(self):
     self.assertEquals(
         validateArgs.objString(arg=self.maya_obj,
                                mayaType='multiplyDivide'), self.maya_obj)
Ejemplo n.º 29
0
def get_by_dist(source=None,
                targets=None,
                mode='close',
                resMode='point',
                sourcePivot='rp',
                targetPivot='rp'):
    """
    Get the the closest return based on a source and target and variable modes
    
    :parameters:
        :source(str): Our base object to measure from
        :targets(list): List of object types
        :mode(str):What mode are we checking data from
            close
            far
        :resMode(str):
            object -- return the [closest] target
            point -- return the [closest] point
            #component -- return [the closest] base component
            pointOnSurface -- [closest] point on the target shape(s)
            pointOnSurfaceLoc -- [closest] point on target shape(s) Loc'd
            shape -- gets closest point on every shape, returns closest
        resMode(str)
    :returns
        [res,distance]
    """
    def get_fromTargets(sourcePos, targets, targetPivot, resMode, mode):
        _l_distances = []
        _l_pos = []
        for t in targets:
            _tarPos = POS.get(t, targetPivot, space='world')
            _l_pos.append(_tarPos)
            _d = get_distance_between_points(sourcePos, _tarPos)
            log.debug(
                "|{0}| >> target: {1} | pivot: {4} | dist: {3} | pos: {2}...| mode: {5}"
                .format(_str_func, t, _tarPos, _d, targetPivot, mode))
            _l_distances.append(_d)
        if mode == 'close':
            _minDist = min(_l_distances)
            _minIdx = _l_distances.index(_minDist)
            if resMode == 'point': return _l_pos[_minIdx], _minDist
            return targets[_minIdx], _minDist
        else:
            _maxDist = max(_l_distances)
            _maxIdx = _l_distances.index(_maxDist)
            if resMode == 'point': return _l_pos[_maxIdx], _maxDist
            return targets[_maxIdx], _maxDist

    _d_by_dist_modes = {
        'close': ['closest', 'c', 'near'],
        'far': ['furthest', 'long']
    }

    _str_func = 'get_by_dist'
    _source = VALID.objString(source,
                              noneValid=False,
                              calledFrom=__name__ + _str_func +
                              ">> validate targets")
    _mode = VALID.kw_fromDict(mode,
                              _d_by_dist_modes,
                              noneValid=False,
                              calledFrom=__name__ + _str_func +
                              ">> validate mode")
    _resMode = resMode
    _l_targets = VALID.objStringList(targets,
                                     noneValid=False,
                                     calledFrom=__name__ + _str_func +
                                     ">> validate targets")

    _sourcePivot = VALID.kw_fromDict(sourcePivot,
                                     SHARED._d_pivotArgs,
                                     noneValid=False,
                                     calledFrom=__name__ + _str_func +
                                     ">> validate sourcePivot")
    _targetPivot = VALID.kw_fromDict(targetPivot,
                                     SHARED._d_pivotArgs,
                                     noneValid=False,
                                     calledFrom=__name__ + _str_func +
                                     ">> validate targetPivot")

    log.debug("|{0}| >> source: {1} | mode:{2} | resMode:{3}".format(
        _str_func, _source, _mode, _resMode))

    #Source==============================================================
    _sourcePos = POS.get(_source, _sourcePivot, space='ws')
    log.debug("|{0}| >> Source pos({2}): {1}...".format(
        _str_func, _sourcePos, _sourcePivot))

    #Modes
    if _resMode in ['object', 'point']:
        log.debug("|{0}| >> object resMode...".format(_str_func))
        mc.select(cl=True)

        _res = get_fromTargets(_sourcePos, _l_targets, _targetPivot, _resMode,
                               _mode)
        if resMode == 'object':
            mc.select(_res[0])
            return _res[0]
        return _res[0]
    elif _resMode == 'component':
        raise NotImplementedError, "component mode"
    elif _resMode in ['pointOnSurface', 'shape', 'pointOnSurfaceLoc']:
        log.debug("|{0}| >> Shape processing...".format(_str_func))
        #Targets=============================================================
        log.debug("|{0}| >> Targets processing...".format(_str_func))
        _d_targetTypes = {}
        _l_pos = []
        _l_dist = []
        _l_shapes = []
        """for t in _l_targets:
            _t = t
            _bfr_component = VALID.get_component(t)
            if _bfr_component:
                _t = _bfr_component[1]#...shape
            _type = VALID.get_mayaType(_t)
            if _type not in _d_targetTypes.keys():
                _d_targetTypes[_type] = [_t]
            else:
                _d_targetTypes[_type].append(_t)
            log.debug("|{0}| >> obj: {1} | type: {2}".format(_str_func,t,_type))"""
        #cgmGen.log_info_dict(_d_targetTypes,'Targets to type')

        for t in _l_targets:
            res = get_closest_point(_sourcePos, t)
            if not res:
                log.error("|{0}| >> {1} -- failed".format(_str_func, t))
            else:
                log.debug("|{0}| >> {1}: {2}".format(_str_func, t, res))
                _l_pos.append(res[0])
                _l_dist.append(res[1])
                _l_shapes.append(res[2])

        if not _l_dist:
            log.error("|{0}| >> Failed to find any points".format(_str_func))
            return False
        closest = min(_l_dist)
        _idx = _l_dist.index(closest)

        if _resMode == 'pointOnSurfaceLoc':
            _loc = mc.spaceLocator(n='get_by_dist_loc')[0]
            POS.set(_loc, _l_pos[_idx])
            return _loc
        if _resMode == 'shape':
            mc.select(_l_shapes[_idx])
            return _l_shapes[_idx]
        return _l_pos[_idx]
Ejemplo n.º 30
0
def aim_atPoint(obj = None, position = [0,0,0], aimAxis = "z+", upAxis = "y+", mode = 'local',vectorUp = None,ignoreAimAttrs = False):
    """
    Aim functionality.
    
    :parameters:
        obj(str): Object to modify
        position(array): object to copy from
        aimAxis(str): axis that is pointing forward
        upAxis(str): axis that is pointing up
        mode(str): 
            'local'-- use standard maya aiming with local axis
            'world' -- use standard maya aiming with world axis
            'matrix' -- use Bokser's fancy method
            'vector' -- maya standard with vector up axis
            'object' -- maya standard with object

    :returns
        success(bool)
    """ 
    try:
        _str_func = 'aimAtPoint'
        _loc = False
        
        
        _obj = VALID.objString(obj, noneValid=False, calledFrom = __name__ + _str_func + ">> validate obj")
        try:position = position.x,position.y,position.z
        except:pass
        try:vectorUp = vectorUp.x,vectorUp.y,vectorUp.z
        except:pass
        
        log.debug("|{0}| >> obj: {1} | position:{2} | mode: {3}".format(_str_func,_obj,position,mode))  
        
        if not ignoreAimAttrs:
            _d_aim = ATTR.validate_arg(_obj,'axisAim')
            _d_up =ATTR.validate_arg(_obj,'axisUp')
            if ATTR.has_attr(_d_aim) and ATTR.has_attr(_d_up):
                aimAxis = ATTR.get_enumValueString(_d_aim)
                upAxis = ATTR.get_enumValueString(_d_up)
                log.debug("|{0}| >> obj: {1} aimable from attrs. aim: {2} | up: {3}".format(_str_func,_obj,aimAxis,upAxis))              
        
        if mode == 'matrix':
            '''Rotate transform based on look vector'''
            # get source and target vectors
            objPos = POS.get(_obj, asEuclid=True)
            targetPos = MATH.Vector3.Create(position)
        
            aim = (targetPos - objPos).normalized()
            
            if not vectorUp:
                upVector = MATH.Vector3.up()
                if upAxis == "y-":
                    upVector = MATH.Vector3.down()
                elif upAxis == "z+":
                    upVector = MATH.Vector3.forward()
                elif upAxis == "z-":
                    upVector = MATH.Vector3.back()
                elif upAxis == "x+":
                    upVector = MATH.Vector3.right()
                elif upAxis == "x-":
                    upVector = MATH.Vector3.left()
                else:
                    upVector = MATH.Vector3.up()
                
                vectorUp = MATH.transform_direction( _obj, upVector )

            wantedAim, wantedUp = MATH.convert_aim_vectors_to_different_axis(aim, vectorUp, aimAxis, upAxis)
            
            xformPos = mc.xform(_obj, q=True, matrix = True, ws=True)
            pos = MATH.Vector3(xformPos[12], xformPos[13], xformPos[14])
            rot_matrix = EUCLID.Matrix4.new_look_at(MATH.Vector3.zero(), -wantedAim, wantedUp)
            
            s = MATH.Vector3.Create( mc.xform(_obj, q=True, ws=True, s=True) )
            
            scale_matrix = EUCLID.Matrix4()
            scale_matrix.a = s.x
            scale_matrix.f = s.y
            scale_matrix.k = s.z
            scale_matrix.p = 1
        
            result_matrix = rot_matrix * scale_matrix
        
            transform_matrix = result_matrix[0:12] + [pos.x, pos.y, pos.z, 1.0]
        
            mc.xform(_obj, matrix = transform_matrix , roo="xyz", ws=True)
            """elif mode == 'world':
            _loc = mc.spaceLocator()[0]
            mc.move (position[0],position[1],position[2], _loc, ws=True)  
            
            mAxis_aim = VALID.simpleAxis(aimAxis)
            mAxis_up = VALID.simpleAxis(upAxis)
            
            _constraint = mc.aimConstraint(_loc,_obj,
                                           maintainOffset = False,
                                           aimVector = mAxis_aim.p_vector,
                                           upVector = mAxis_up.p_vector,
                                           worldUpType = 'scene',)
            mc.delete(_constraint + [_loc])"""
        elif mode in ['local','world','vector','object']:
            _loc = mc.spaceLocator(name='test')[0]
            _loc_snap = POS.create_loc(_obj)
            
            mc.move (position[0],position[1],position[2], _loc, ws=True)  
            mAxis_aim = VALID.simpleAxis(aimAxis)
            mAxis_up = VALID.simpleAxis(upAxis) 
            
            if mode == 'world':                
                _constraint = mc.aimConstraint(_loc,_loc_snap,
                                               maintainOffset = False,
                                               aimVector = mAxis_aim.p_vector,
                                               upVector = mAxis_up.p_vector,
                                               worldUpType = 'scene',) 
            elif mode == 'object':
                vectorUp = VALID.mNodeString(vectorUp)
                _constraint = mc.aimConstraint(_loc,_loc_snap,
                                               maintainOffset = False,
                                               aimVector = mAxis_aim.p_vector,
                                               upVector = mAxis_up.p_vector,
                                               worldUpType = 'object',
                                               worldUpObject = vectorUp)
                                               #worldUpVector = _vUp)
            else:
                if mode == 'vector':
                    _vUp = vectorUp
                else:
                    _vUp = MATH.get_obj_vector(_obj,upAxis)
                _constraint = mc.aimConstraint(_loc,_loc_snap,
                                               maintainOffset = False,
                                               aimVector = mAxis_aim.p_vector,
                                               upVector = mAxis_up.p_vector,
                                               worldUpType = 'vector',
                                               worldUpVector = _vUp)                 
                
            go(obj,_loc_snap)
            mc.delete(_constraint,_loc_snap)    
        else:
            raise NotImplementedError,"mode: {0}".format(mode)
        
        if _loc:mc.delete(_loc)
        return True
    except Exception,err:
        try:mc.delete(_loc)
        except:pass
        log.error( "aim_atPoint | obj: {0} | err: {1}".format(obj,err) )
Ejemplo n.º 31
0
 def test_falseIfWrongMayaTypeNoneValid(self):
     self.assertFalse(
         validateArgs.objString(arg=self.maya_obj,
                                mayaType='plusMinusAverage',
                                noneValid=True))