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
def average(*args): """ """ if VALID.isListArg(args[0]): l = args[0] else: l = [a for a in args] return sum(l) / len(l)
def euclidVector3Arg(arg): _str_func = 'euclidVector3Arg' if not issubclass(type(arg), EUCLID.Vector3): if VALID.isListArg(arg) and len(arg) == 3: return EUCLID.Vector3(float(arg[0]), float(arg[1]), float(arg[2])) else: raise ValueError, "|{0}| >> arg: {1}".format(_str_func, arg) return arg
def get_greatest(*args): """ """ if VALID.isListArg(args[0]): l = args[0] else: l = [a for a in args] return max(l)
def blendDat(dPrimary, dBlend): """ Assumes two lists of """ _res = {} for k, v1 in dPrimary.iteritems(): v2 = dBlend.get(k) v_use = v1 if v2: if VALID.isListArg(v1) and VALID.isListArg(v2): for v in v2: if v not in v_use: v_use.append(v) if issubclass(type(v1), dict) and issubclass(type(v2), dict): v_use = blendDat(v1, v2) _res[k] = v_use for k, v2 in dBlend.iteritems(): if not _res.get(k): _res[k] = v2 return _res
def median(*args): """ https://stackoverflow.com/questions/24101524/finding-median-of-list-in-python """ if VALID.isListArg(args[0]): l = args[0] else: l = [a for a in args] n = len(l) if n < 1: return None if n % 2 == 1: return sorted(l)[n // 2] else: return sum(sorted(l)[n // 2 - 1:n // 2 + 1]) / 2.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
def create_proxyGeo(proxyShape='cube', size=[1, 1, 1], direction='z+', ch=True): try: #cube:sphere:cylinder:cone:torus _str_func = 'create_proxyGeo' _proxyShape = _d_proxyCreate.get(proxyShape, proxyShape) _call = getattr(mc, _proxyShape, None) if not _call: raise ValueError, "Failed to find maya.cmds call {0}".format( _proxyShape) #if proxyShape not in _d_create.keys(): #raise ValueError,"Unknown shape: {0}".format(proxyShape) _kws = {'ch': ch} if proxyShape in ['cube']: _kws['width'] = size[0] _kws['ch'] = False if proxyShape in ['cylinder', 'sphere', 'cone', 'cylinder', 'torus']: _kws['radius'] = max(size) / 2.0 _kws['axis'] = VALID.simpleAxis(direction).p_vector _res = _call(**_kws) if size is not None: if VALID.isListArg(size): TRANS.scale_to_boundingBox(_res[0], size) else: if absoluteSize: _f_current = DIST.get_bb_size(_res[0], True, True) multiplier = size / _f_current mc.scale(multiplier, multiplier, multiplier, _res[0], relative=True) else: mc.scale(size, size, size, _res[0], os=True) #mc.makeIdentity(_res[0], apply=True,s=1) """ if proxyShape == 'cube': _d_directionXRotates = {'x+':[0,0,0],'x-':[0,180,0],'y+':[0,0,90],'y-':[0,0,-90],'z+':[0,-90,0],'z-':[0,90,0]} _r_factor = _d_directionXRotates.get(direction) mc.rotate (_r_factor[0], _r_factor[1], _r_factor[2], _res[0], ws=True)""" #mc.makeIdentity(_res[0], apply=True,r =1, n= 1) if proxyShape == 'cube': _children = TRANS.children_get(_res[0]) for i, c in enumerate(_children): _children[i] = TRANS.parent_set(c, False) combineShapes(_children + [_res[0]], keepSource=False, replaceShapes=False) return _res except Exception, err: cgmGEN.cgmExceptCB(Exception, err, msg=vars())
def attachCharacterToMount(character= 'Knight01', mount = 'Hawk', totem = False): _str_func = 'attachCharacterToMount' log.info("|{0}| >>...".format(_str_func)) md_dat = {} md_dat['character'] = {} md_char = md_dat['character'] for k,d in d_characters.get(character).iteritems(): md_char[k] = cgmMeta.asMeta('{0}:{1}'.format(character,d)) md_dat['puppet'] = {} md_puppet = md_dat['puppet'] for k,d in d_characters.get(mount).iteritems(): md_puppet[k] = cgmMeta.asMeta('{0}:{1}'.format(mount,d)) pprint.pprint(md_dat) #Attach ------------------------------------------------------------------- log.info(cgmGEN.logString_sub(_str_func,'attach')) log.info(cgmGEN.logString_msg(_str_func,'cog')) mCog = md_dat['character']['cog'] mCog.pivot_0 = 2 mCog.space = 3 mSpacePivot = mCog.spacePivots_0 mc.parentConstraint(md_puppet['snapHip'].mNode, mSpacePivot.mNode, maintainOffset = False) #assuming settings.... d_attaches = {'l_arm':{'control':'controlIK','target':'snapLWrist','space':8}, 'r_arm':{'control':'controlIK','target':'snapRWrist','space':8}, 'l_leg':{'control':'controlIK','target':'snapLAnkle','space':7}, 'r_leg':{'control':'controlIK','target':'snapRAnkle','space':7}, 'totem':{'control':['fk',0],'target':'snapTotem','space':7}, } for k,d in d_attaches.iteritems(): log.info(cgmGEN.logString_msg(_str_func,k)) mPart = md_char[k] mRigNull = md_char[k].rigNull mSettings = mRigNull.settings if k == 'totem' and not totem: continue try: if VALID.isListArg(d['control']): log.info("list arg..") mControl = mRigNull.getMessageAsMeta('{0}Joints_{1}'.format(d['control'][0],d['control'][1])) else: mControl = mRigNull.getMessageAsMeta(d['control']) mTarget = md_puppet[d['target']] mSettings.FKIK = 1 mControl.pivot_0 = 2 mControl.space = d['space'] mSpacePivot = mControl.spacePivots_0 mc.parentConstraint(mTarget.mNode, mSpacePivot.mNode, maintainOffset = False) mControl.doSnapTo(mTarget) except Exception,err: log.error("{0} failed | {1}".format(k, err)) pprint.pprint(vars())
def findMeshIntersections(mesh, raySource, rayDir, maxDistance = 1000, tolerance = .1): """ Return the closest points on a surface from a raySource and rayDir. Can't process uv point for surfaces yet Thanks to Deane @ https://groups.google.com/forum/?fromgroups#!topic/python_inside_maya/n6aJq27fg0o%5B1-25%5D Thanks to Samaneh Momtazmand for doing the r&d to get this working with surfaces :parameters: mesh(string) | Surface to cast at raySource(double3) | point from which to cast in world space rayDir(vector) | world space vector maxDistance(value) | Maximum cast distance :returns: Dict ------------------------------------------------------------------ 'source'(double3) | point from which we cast 'hits'(list) | world space points 'uvs'(list) | uv on surface of hit | only works for mesh surfaces :raises: Exception | if reached """ try: _str_funcName = 'findMeshIntersections' try: if cgmValid.isListArg(mesh): log.debug("{0}>>> list provided. Using first : {1}".format(_str_funcName,mesh)) mesh = mesh[0] if len(mc.ls(mesh))>1: raise StandardError,"{0}>>> More than one mesh named: {1}".format(_str_funcName,mesh) _str_objType = search.returnObjectType(mesh) if _str_objType not in ['mesh','nurbsSurface']: raise ValueError,"Object type not supported | type: {0}".format(_str_objType) #Create an empty selection list. selectionList = om.MSelectionList() #Convert the 'raySource' parameter into an MFloatPoint. #raySource = om.MFloatPoint(raySource[0], raySource[1], raySource[2]) mPoint_raySource = om.MFloatPoint(raySource[0], raySource[1], raySource[2]) #Convert the 'rayDir' parameter into an MVector.` mVec_rayDirection = om.MFloatVector(rayDir[0], rayDir[1], rayDir[2]) #Create an empty MFloatPoint to receive the hit point from the call. mPointArray_hits = om.MFloatPointArray() #centerPointVector = om.MFloatVector(centerPoint[0],centerPoint[1],centerPoint[2]) #rayDir = om.MFloatPoint(centerPointVector - raySourceVector) maxDist = maxDistance spc = om.MSpace.kWorld except Exception,error: raise ValueError,"Validation fail |0}".format(error) try: if _str_objType == 'nurbsSurface': log.debug("{0} | Surface cast mode".format(_str_funcName)) centerPoint = mc.xform(mesh, q=1, ws=1, t=1) surfaceShape = mc.listRelatives(mesh, s=1)[0] mPointArray_hits = om.MPointArray() mPoint_raySource = om.MPoint(raySource[0], raySource[1], raySource[2]) mVec_rayDirection = om.MVector(rayDir[0], rayDir[1], rayDir[2]) selectionList = om.MSelectionList() selectionList.add(surfaceShape) surfacePath = om.MDagPath() selectionList.getDagPath(0, surfacePath) surfaceFn = om.MFnNurbsSurface(surfacePath) #Get the closest intersection. mPointArray_u = om.MDoubleArray() mPointArray_v = om.MDoubleArray() spc = om.MSpace.kWorld #Get the closest intersection. ''' d_kws = {'raySource':mPoint_raySource, 'rayDirection':mVec_rayDirection, 'u':u, 'v':v, 'mPointArray':mPointArray_hits, 'space':spc} for k in d_kws.keys(): print ("# {0} | {1}".format(k,d_kws[k])) ''' gotHit = surfaceFn.intersect(mPoint_raySource, mVec_rayDirection, mPointArray_u,mPointArray_v,mPointArray_hits, tolerance, spc,False,None,False,None) elif _str_objType == 'mesh': log.debug("{0} | Mesh cast mode".format(_str_funcName)) #Put the mesh's name on the selection list. selectionList.add(mesh) #Create an empty MDagPath object. meshPath = om.MDagPath() #Get the first item on the selection list (which will be our mesh) #as an MDagPath. selectionList.getDagPath(0, meshPath) #Create an MFnMesh functionset to operate on the node pointed to by #the dag path. meshFn = om.MFnMesh(meshPath) #Set up a variable for each remaining parameter in the #MFnMesh::closestIntersection call. We could have supplied these as #literal values in the call, but this makes the example more readable. sortIds = False bothDirections = False noFaceIds = None noTriangleIds = None noHitParam = None noSortHits = False noHitFace = None noHitTriangle = None noHitBary1 = None noHitBary2 = None tolerance = 0 noAccelerator = None #Get the closest intersection. gotHit = meshFn.allIntersections( mPoint_raySource, mVec_rayDirection, noFaceIds, noTriangleIds, sortIds, om.MSpace.kWorld, maxDist, bothDirections, noAccelerator, noSortHits, mPointArray_hits, noHitParam, noHitFace, noHitTriangle, noHitBary1, noHitBary2,tolerance) else : raise ValueError,"Wrong surface type!" except Exception,error: raise Exception,"Cast fail |{0}".format(error)