def copyWeight( first, second ): hists = cmds.listHistory( first, pdo=1 ) skinNode = None for hist in hists: if cmds.nodeType( hist ) == 'skinCluster': skinNode = hist if not skinNode: return None targetSkinNode = None targetHists = cmds.listHistory( second, pdo=1 ) if targetHists: for hist in targetHists: if cmds.nodeType( hist ) == 'skinCluster': targetSkinNode = hist if not targetSkinNode: bindObjs = cmds.listConnections( skinNode+'.matrix', s=1, d=0, type='joint' ) bindObjs.append( second ) print bindObjs cmds.skinCluster( bindObjs, tsb=1 ) cmds.copySkinWeights( first, second, noMirror=True, surfaceAssociation='closestPoint', influenceAssociation ='oneToOne' )
def isAffected(nodeAffected, nodeDriver): driverFamily = cmds.ls(nodeDriver, dagObjects=True) if nodeAffected in driverFamily: return True nodeAffectedConnections = cmds.listHistory(nodeAffected) if nodeDriver in nodeAffectedConnections: return True steps1to3=set() steps1to3.update(steps1and3) step4=[] for each in (cmds.ls(list(steps1to3),shapes=True)): try: step4.extend(cmds.listConnections(each+'.instObjGroups', t='shadingEngine', et=1)) except TypeError: pass steps1to3.update(step4) steps1to4=set() steps1to4.update(steps1to3) steps1to4.update(step4) step5=set(steps1to4) step5.update(cmds.listHistory(list(steps1to4))) print step5
def findTypeInHistory(obj, type, future=False, past=True): # This is translated from the mel procedure of the same name. if past and future: # In the case that the object type exists in both past and future # find the one that is fewer connections away. pasts = cmds.listHistory(obj, f=0, bf=1, af=1) futures = cmds.listHistory(obj, f=1, bf=1, af=1) pastObjs = cmds.ls(pasts, type=type) futureObjs = cmds.ls(futures, type=type) if len(pastObjs) > 0: if len(futureObjs) > 0: for i in range( min( len(pasts), len(futures) ) ): if pasts[i] == pastObjs[0]: return pastObjs[0] if futures[i] == futureObjs[0]: return futureObjs[0] else: return pastObjs[0] elif len(futureObjs) > 0: return futureObjs[0] else: if past: hist = cmds.listHistory(obj, f=0, bf=1, af=1) objs = cmds.ls(hist, type=type) if len(objs) > 0: return objs[0] if future: hist = cmds.listHistory(obj, f=1, bf=1, af=1) objs = cmds.ls(hist, type=type) if len(objs) > 0: return objs[0] return None
def meshesFromHistory(control): ''' Return all visible meshes downstream from a given control. ''' #try searching backward first for speed meshes = [] allMeshes = mc.ls(type='mesh') for mesh in allMeshes: hist = mc.listHistory(mesh, allConnections=True) if control in hist: if isNodeVisible(mesh): meshes.append(mesh) if meshes: return meshes #if we didn't find any, search forward from control #this takes a bit longer hier = mc.listRelatives(control, ad=True, pa=True) if not hier: hier = [control] else: hier.append(control) hist = mc.listHistory(hier, future=True, allFuture=True, allConnections=True) hist = list(set(hist)) meshes = mc.ls(hist, type='mesh') meshes = [x for x in meshes if isNodeVisible(x)] return meshes
def FilterNodeType(self, type): ''' 返回所选择物体的shader,也可以直接选择shader ''' outputNodeList = [] for input in self.sl : inputType = cmds.nodeType(input) if inputType == type: outputNodeList.append(input) elif inputType == 'transform' or inputType == "mesh" or inputType == "nurbsSurface" : shapeList = cmds.listRelatives(input, ad=1, pa=1, type='surfaceShape') shapeList = sorted(set(shapeList), key=shapeList.index) #去除列表中的重复元素 for shape in shapeList: sg = cmds.listConnections(shape, type='shadingEngine') if sg[0] != 'initialShadingGroup' and len(sg): shadingNetwork = cmds.listHistory(sg[0], pdo=1) if len(shadingNetwork): for outputNode in shadingNetwork: if cmds.nodeType(outputNode) == type: outputNodeList.append(outputNode) else: shadingNetwork = cmds.listHistory(input, pdo=1) if len(shadingNetwork): for outputNode in shadingNetwork: if cmds.nodeType(outputNode) == type: outputNodeList.append(outputNode) self.outputNodeList = sorted(set(outputNodeList), key=outputNodeList.index)
def getHIKCharacterNode_from_node(_node): if type(_node) == str or type(_node) == unicode: # namespace 확인 _namespace = getNamespace(_node) _ls = [] if _namespace: # namespace가 존재할경우 # 레퍼런스로 생각하고 namespace로 시작하는 HIKProperty2State 노드 찾음. _ls = cmds.ls( _namespace+"*", type='HIKCharacterNode') else: # namespace가 존재하지 않을경우 # 임포트되었거나, 캐릭터 원본 파일 # listHistory 를 사용해서 찾음, # 일일히 다 검색해야 해서, 다소 피드백이 느림. _listHistory = cmds.listHistory( _node, #allFuture=True, allConnections=True ) _ls = cmds.ls( _listHistory, type='HIKCharacterNode') # 찾은게 없으면 나감 if not _ls: return # 찾은게 있으면 등록 return _ls[0] elif type(_node) == list: _HIKCharacterNode = [] for _n in _node: _namespace = getNamespace(_n) _ls = [] if _namespace: # namespace가 존재할경우 # 레퍼런스로 생각하고 namespace로 시작하는 HIKProperty2State 노드 찾음. _ls = cmds.ls( _namespace+"*", type='HIKCharacterNode') else: # namespace가 존재하지 않을경우 # 임포트되었거나, 캐릭터 원본 파일 # listHistory 를 사용해서 찾음, # 일일히 다 검색해야 해서, 다소 피드백이 느림. _listHistory = cmds.listHistory( _n, #allFuture=True, allConnections=True ) _ls = cmds.ls( _listHistory, type='HIKCharacterNode') # 찾은게 없으면 나감 if not _ls: return for _i in _ls: _HIKCharacterNode.append(_i) return list(set(_HIKCharacterNode))
def cmdSelectSgWobbleCurve( *args ): sgWobbleCurves = [] for hist in cmds.listHistory( cmds.ls( sl=1 ), pdo=1 ): if cmds.nodeType( hist ) != 'wire': continue targetCrv = cmds.listConnections( hist+'.deformedWire[0]' ) crvHists = cmds.listHistory( targetCrv, pdo=1 ) for crvHist in crvHists: if cmds.nodeType( crvHist ) != 'sgWobbleCurve2': continue sgWobbleCurves.append( crvHist ) if sgWobbleCurves: cmds.select( sgWobbleCurves )
def cmdSelectFollicle( *args ): upObjects = [] for hist in cmds.listHistory( cmds.ls( sl=1 ), pdo=1 ): if cmds.nodeType( hist ) != 'wire': continue targetCrv = cmds.listConnections( hist+'.deformedWire[0]' ) crvHists = cmds.listHistory( targetCrv, pdo=1 ) for crvHist in crvHists: if cmds.nodeType( crvHist ) != 'sgWobbleCurve2': continue mm = cmds.listConnections( crvHist+'.aimMatrix' )[0] upObj = cmds.listConnections( mm+'.matrixIn[0]' )[0] upObjects.append( upObj ) if upObjects: cmds.select( upObjects )
def findTypeInHistory(obj, objType, future=False, past=False): """ returns the node of the specified type that is the closest traversal to the input object :param obj: Object name :type obj: str :param objType: Object type list :type objType: str | list :param future: Future depth :type future: bool :param past: Past depth :type past: bool :return: Connected objType nodes :rtype: list """ #// Test with list return instead of closest connected node #// Replace return pastObjs with return pastObjs[0] etc if past and future: #// In the case that the object type exists in both past and future, #// find the one that is fewer connections away. pastList = mc.listHistory(obj, f=False, bf=True, af=True) futureList = mc.listHistory(obj, f=True, bf=True, af=True) pastObjs = mc.ls(pastList, type=objType) futureObjs = mc.ls(futureList, type=objType) if pastObjs: if futureObjs: mini = len(futureList) if len(pastList) < mini: mini = len(pastList) for i in range(mini): if pastList[i] in pastObjs: return pastObjs if futureList[i] in futureObjs: return futureObjs else: return pastObjs elif futureObjs: return futureObjs else: if past: hist = mc.listHistory(obj, f=False, bf=True, af=True) objs = mc.ls(hist, type=objType) if objs: return objs if future: hist = mc.listHistory(obj, f=True, bf=True, af=True) objs = mc.ls(hist, type=objType) if objs: return objs
def renameHistoryNodes(obj, nodeType, prefix='', suffix='', stripOldSuffix=True): """ Rename nodes in a specified objects history based on a given or derived prefix and suffix @param obj: Object whose history nodes will be renamed @type obj: str @param nodeType: Node types to isolate for rename @type nodeType: str or list @param prefix: Name prefix for nodes. If empty, derive from object name @type prefix: str @param suffix: Name suffix for nodes. If empty, derive from node type @type suffix: str """ # Check object if not cmds.objExists(obj): raise Exception('Object "' + obj + '" does not exist!') # Check prefix if not prefix: if stripOldSuffix: prefix = glTools.utils.stringUtils.stripSuffix(obj) else: prefix = obj # Get object history if nodeType.lower() == 'all': nodeHist = cmds.ls(cmds.listHistory(obj)) else: nodeHist = cmds.ls(cmds.listHistory(obj), type=nodeType) nodeHist.sort() # For each history node nodeCount = len(nodeHist) for n in range(nodeCount): # Check suffix if not suffix: nodeSuffix = cmds.objectType(nodeHist[n]) else: nodeSuffix = suffix # Check index if nodeCount > 1: nodeSuffix = glTools.utils.stringUtils.stringIndex(n, 1) + '_' + nodeSuffix # Rename node nodeHist[n] = cmds.rename(nodeHist[n], prefix + '_' + nodeSuffix) # Return result return nodeHist
def mmSetBindDefault( *args ): sels = cmds.ls( sl=1 ) for sel in sels: hists = cmds.listHistory( sel ) skinNode = None for hist in hists: if cmds.nodeType( hist ) == 'skinCluster': skinNode = hist break fnSkinNode = om.MFnDependencyNode( baseFunctions.getMObject( skinNode ) ) plugMatrix = fnSkinNode.findPlug( 'matrix' ) plugBindPre = fnSkinNode.findPlug( 'bindPreMatrix' ) for i in range( plugMatrix.numElements() ): loIndex = plugMatrix[i].logicalIndex() oMtx = plugMatrix[i].asMObject() mtxData = om.MFnMatrixData( oMtx ) mtx = mtxData.matrix() invData = om.MFnMatrixData() oInv = invData.create( mtx.inverse() ) plugBindPre.elementByLogicalIndex( loIndex ).setMObject( oInv )
def findInputShape1(shape): ''' Return the input shape ('...ShapeOrig') for the specified shape node based on deformer data. This function assumes that the specified shape is affected by at least one valid deformer. @param shape: The shape node to find the corresponding input shape for. @type shape: str ''' # Get MObject for shape shapeObj = glTools.utils.base.getMObject(shape) # Get inMesh connection inConn = mc.listConnections(shape,s=True,d=False) if not inConn: return shape # Find connected deformer deformerHist = mc.ls(mc.listHistory(shape),type='geometryFilter') if not deformerHist: raise Exception('Shape node "'+shape+'" is not affected by any valid deformers! Unable to determine input shape') deformerObj = glTools.utils.base.getMObject(deformerHist[0]) # Get deformer function set deformerFn = OpenMayaAnim.MFnGeometryFilter(deformerObj) # Get input shape for deformer geomIndex = deformerFn.indexForOutputShape(shapeObj) inputShapeObj = deformerFn.inputShapeAtIndex(geomIndex) # Return result return OpenMaya.MFnDagNode(inputShapeObj).partialPathName()
def cleanCacheNodes(): historySwitches = cmds.ls(type='historySwitch') for switch in historySwitches: his = cmds.listHistory(switch) for h in his: if cmds.objExists(h): if cmds.nodeType(h) != 'time': cmds.delete(h) OpenMaya.MGlobal.displayInfo('== %s has been deleted ==' % h) # begin the dumbest f*****g hack ever # maya will delete any sets that connected to the orig node. The connection # only becomes visible when the Relationship Editor is open. Locking the nodes # prevents their deletion sets = cmds.ls(type='objectSet') for s in sets: # lock-em up...dumb as shitty way of doing things cmds.lockNode(s, l=True) nodes = cmds.ls(type='mesh') for node in nodes: if cmds.getAttr(node + '.intermediateObject'): cmds.delete(node) OpenMaya.MGlobal.displayInfo('== %s has been deleted ==' % node) # end the dumbest f*****g hack ever for s in sets: # unlock the nodes cmds.lockNode(s, l=False)
def updateCondition(self, *args ): rootName = cmds.textField( self._rootField, q=1, tx=1 ) children = cmds.listRelatives( rootName, c=1, ad=1 ) angleDriverList = [] for child in children: hists = cmds.listHistory( child ) for hist in hists: if cmds.nodeType( hist ) == 'angleDriver': if not hist in angleDriverList: angleDriverList.append( hist ) onlyMoved = cmds.checkBox( self._showOnlyMovedCheck, q=1, v=1 ) showDrivers = [] minValue = cmds.floatField( self._smallerValueField, q=1, v=1 ) if onlyMoved: for driver in angleDriverList: angle1, angle2, angle3 = cmds.getAttr( driver+'.outDriver' )[0] if math.fabs( angle1 ) > minValue or math.fabs( angle2 ) > minValue or math.fabs( angle3 ) > minValue: showDrivers.append( driver ) else: for driver in angleDriverList: showDrivers.append( driver ) cmds.textScrollList( self._driverList, e=1, ra=1, a=showDrivers )
def clampVertInfluenceCount( geos=None ): ''' ''' global kMAX_INF_PER_VERT progressWindow = cmd.progressWindow skinPercent = cmd.skinPercent if geos is None: geos = cmd.ls(sl=True) for geo in geos: skin = cmd.ls(cmd.listHistory(geo), type='skinCluster')[0] verts = cmd.ls(cmd.polyListComponentConversion(geo, toVertex=True), fl=True) inc = 100.0/len(verts) progress = 0 for vert in verts: progress += inc progressWindow(e=True, progress=progress) weightList = skinPercent(skin, vert, ib=1e-4, q=True, value=True) if len(weightList) > kMAX_INF_PER_VERT: jointList = skinPercent(skin, vert, ib=1e-4, q=True, transform=None) sorted = zip(weightList, jointList) sorted.sort() #now clamp to the highest kMAX_INF_PER_VERT number of weights, and re-normalize sorted = sorted[-kMAX_INF_PER_VERT:] weightSum = sum([a for a, b in sorted]) t_values = [(b, a/weightSum) for a, b in sorted] skinPercent(skin, vert, tv=t_values) #turn in limiting in the skinCluster cmd.setAttr('%s.maxInfluences' % skin, kMAX_INF_PER_VERT) cmd.setAttr('%s.maintainMaxInfluences' % skin, 1)
def skinWeights(x=None, export=None, f=None, fileName=None): # Import/export skin weights from/to a file # x/export: 0 for import, 1 for export # f/fileName: filename under default project directory x = x or export if not (f or fileName): raise Exception, "Missing argument: fileName" if fileName: f = fileName obj = cmds.ls(sl=1) if not obj: raise Exception, "No object selected" obj = obj[0] node = None for n in cmds.listHistory(obj, f=0, bf=1): if cmds.nodeType(n) == 'skinCluster': node = n break if not node: raise Exception, "no skin cluster found" mode = "r" if x: mode = "w" f = open(cmds.internalVar(uwd=1) + f, mode) allTransforms = cmds.skinPercent(node, cmds.ls(cmds.polyListComponentConversion(obj, tv=1), fl=1), q=1, t=None) for vertex in cmds.ls(cmds.polyListComponentConversion(obj,tv=1), fl=1): if x: transforms = cmds.skinPercent(node, vertex, ib=1e-010, q=1, t=None) weights = cmds.skinPercent(node, vertex, ib=1e-010, q=1, v=1) s = "" for i in range(len(transforms)): s += str(weights[i])+"@"+transforms[i]+" " f.write(s+"\n") else: weights = {} for t in allTransforms: weights[t] = float(0) readWeights = f.readline().strip().split(" ") for i in readWeights: w = i.split("@") if w[1] in weights: weights[w[1]] = float(w[0]) w = [] for i in weights.iteritems(): w.append(i) cmds.skinPercent(node, vertex, tv=w) f.close()
def copyVtxAndPast( meshName, index, indices ): hists = cmds.listHistory( meshName ) skinCluster = '' for hist in hists: if cmds.nodeType( hist ) == 'skinCluster': skinCluster = hist if not skinCluster: return None fnSkinCluster = om.MFnDependencyNode( getMObject( skinCluster ) ) weightListPlug = fnSkinCluster.findPlug( 'weightList' ) weightListPlugElement = weightListPlug.elementByLogicalIndex( index ) plugWeights = weightListPlugElement.child( 0 ) indicesAndValues = [] for i in range( plugWeights.numElements() ): index = plugWeights[i].logicalIndex() value = plugWeights[i].asFloat() indicesAndValues.append( [index,value] ) for vtxIndex in indices: weightListPlugElement = weightListPlug.elementByLogicalIndex( vtxIndex ) plugWeights = weightListPlugElement.child( 0 ) for i in range( plugWeights.numElements() ): cmds.removeMultiInstance( plugWeights[0].name() ) for index, value in indicesAndValues: cmds.setAttr( plugWeights.name() + '[%d]' % index, value )
def getDeformerList(geo='',regexFilter='',type='geometryFilter'): ''' Return a list of deformer that match the input criteria. You can list deformers connected to a geo specified geometry, by type and filter the result with a regex. @param geo: Geometry name as string. Optional arg that will list deformers connected to geo. @type geo: str @param regexFilter: Regular Expression as string. Optional arg that will filter results @type regexFilter: str @param type: Deformer Type as string. Optional arg, only return deformers of specified type. @type type: str ''' deformers = [] # Check Geo if geo: inputShapes = [] # Get shapes shapes = mc.listRelatives(geo, shapes=True, ni=True) # Get input shapes for shape in shapes: inputShapes.append( findInputShape(shape) ) # Get deformers by listing all future on input shapes deformers = mc.ls(mc.listHistory(inputShapes, future=True, allFuture=True), type=type) else: deformers = mc.ls(type=type) # Remove duplicate entries deformers = list(set(deformers)) # Filter result if regexFilter if regexFilter: reFilter = re.compile(regexFilter) return filter(reFilter.search, deformers) # Return result return deformers
def getMaterials(nodes=None): """ Returns the materials related to nodes :param nodes: The nodes to get the related materials from. If nodes is None the current selection will be used. :rtype: list """ # Get selected nodes if None provided if nodes is None: nodes = mc.ls(sl=1) # Get materials from list materials = mc.ls(nodes, mat=1, long=True) # Get materials related to nodes (material from object) # And add those materials to the material list we already have if nodes: nodes_history = mc.listHistory(nodes,f=1) if nodes_history: nodes_connections = mc.listConnections(nodes_history) if nodes_connections: connected_materials = mc.ls(nodes_connections, mat=True, long=True) if connected_materials: # Use a set so we don't have any duplicates materials = set(materials) materials.update(connected_materials) materials = list(materials) return materials
def convert(*args): sel_obj = mc.ls(sl=1,l=1) if sel_obj: frmt=mc.optionMenu('texfrmt',q=1,v=1) for each in sel_obj: texNodes = mc.listRelatives(each,c=1,s=1,ni=1,f=1) #print texNodes ShaderNam= mc.listConnections(texNodes[0]) #print ShaderNam Files=mc.listHistory(ShaderNam[0]) TexFiles=[] for file in Files: if mc.nodeType(file) == 'file': TexFiles.append(file) for j in range(len(TexFiles)): file_tex = mc.getAttr(TexFiles[j] + '.fileTextureName') filename = os.path.basename(file_tex) pathname = os.path.dirname(file_tex) print filename Filefrt=filename.split('.') Fulpath=pathname+'\\'+Filefrt[0]+'.'+frmt mc.setAttr((TexFiles[j] + '.fileTextureName'),(Fulpath),type='string') mc.confirmDialog(t='Message', m= 'Selected are successfully converted to '+frmt+' format', b='OK', ma = "center") else: mc.confirmDialog(t='Message', m = 'Please select any objects....', b='OK', ma = "center")
def findInputShape(shape): ''' Return the input shape ('...ShapeOrig') for the specified shape node. This function assumes that the specified shape is affected by at least one valid deformer. @param shape: The shape node to find the corresponding input shape for. @type shape: str ''' # Get MObject for shape shapeObj = getMObject(shape) # Get inMesh connection inMeshConn = mc.listConnections(shape+'.inMesh') if not inMeshConn: raise Exception('Mesh attribute "'+shape+'.inMesh" has no incoming connections!') # Find connected deformer deformerObj = getMObject(inMeshConn[0]) if not deformerObj.hasFn(OpenMaya.MFn.kGeometryFilt): deformerHist = mc.ls(mc.listHistory(shape),type='geometryFilter') if not deformerHist: raise Exception('Shape node "'+shape+'" is not affected by any valid deformers!') else: deformerObj = getMObject(deformerHist[0]) # Get deformer function set deformerFn = OpenMayaAnim.MFnGeometryFilter(deformerObj) # Get input shape for deformer geomIndex = deformerFn.indexForOutputShape(shapeObj) inputShapeObj = deformerFn.inputShapeAtIndex(geomIndex) # Return result return OpenMaya.MFnDependencyNode(inputShapeObj).name()
def geoInfo(vtx=0, geo=0, shape=0, skinC=0): # Returns a list of requested object strings returnValues = [] selVTX = [x for x in cmds.ls(sl=1, fl=1) if ".vtx" in x] if len(selVTX) == 0: # geo can be of bool/int type or of string type. if type(geo) == int or type(geo) == bool: selGEO = cmds.ls(sl=1, objectsOnly=1)[0] elif type(geo) == str or type(geo) == unicode: selGEO = geo geoShape = cmds.listRelatives(selGEO, shapes=1)[0] # Deformed shapes occur when reference geometry has a deformer applied to it that is then cached # the additional section will take out the namespace of the shapefile (if it exists) and try to # apply the deform syntax on it. if ":" in geoShape: # the colon : deliminates namespace references deformShape = geoShape.partition(":")[2] + "Deformed" if len(cmds.ls(deformShape)) != 0: geoShape = deformShape print "deformed shape found: " + geoShape else: geoShape = selVTX[0].partition(".")[0] + "Shape" deformTest = geoShape.partition(":")[2] + "Deformed" if len(deformTest) != 0: geoShape = deformTest print "deformed shape found on selected vertices: " + geoShape # because the deformed shape is the object listed in the JSON file, # the word "Deformed" needs to be injected in the vertex name # and the namespace needs to be stripped out, because a deformed Shape is part of the local namespace for x in range(len(selVTX)): selVTX[x] = (selVTX[x].replace(".", "ShapeDeformed.")).partition(":")[2] selGEO = cmds.listRelatives(geoShape, p=1)[0] print geoShape + " | " + selGEO if vtx == 1: if len(selVTX) != 0: # if vertices are already selected, then we can take that list whole-sale. returnValues.append(selVTX) else: vtxIndexList = [ "{0}.vtx[{1}]".format(geoShape, x) for x in cmds.getAttr(geoShape + ".vrts", multiIndices=True) ] returnValues.append(vtxIndexList) if geo == 1 or geo == True or type(geo) == str or type(geo) == unicode: returnValues.append(selGEO) if shape == 1: returnValues.append(geoShape) if skinC == 1: skinClusterNM = [x for x in cmds.listHistory(geoShape) if cmds.nodeType(x) == "skinCluster"][0] returnValues.append(skinClusterNM) return returnValues
def createFreeCameras(self): debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'self.cameras: %s' % self.cameras, verbose = False) for camera in self.cameras: debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'Processing camera: %s' % camera, verbose = False) cmds.select(camera, r= True) newCamera = cmds.duplicate( rr=True ) newCamera = newCamera[0] debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'newCamera: %s' % newCamera, verbose = False) for attr in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v']: cmds.setAttr(newCamera + "." + attr, lock=False) hisObject = cmds.listHistory(newCamera) for attr in ['hfa', 'vfa', 'fl', 'lsr', 'fs', 'fd', 'sa', 'coi']: cmds.setAttr(hisObject[0] + "." + attr, lock=False) parentNode = cmds.listRelatives(camera, p= True) if parentNode != None: cmds.parent( newCamera, world= True) pointConst = cmds.pointConstraint( camera, newCamera ) orientConst = cmds.orientConstraint( camera, newCamera ) cmds.bakeResults( newCamera+'*', t=(self.startFrame, self.endFrame), simulation=True, sparseAnimCurveBake=False, shape=False) debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'newCamera %s baked successfully...' % newCamera, verbose = False) cmds.delete(pointConst, orientConst, cn=True ) newCameraName = cmds.rename(newCamera, '%s_Cpy' % camera) debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'newCameraName: %s' % newCameraName, verbose = False) self.newCameras.extend([newCameraName]) debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'self.newCameras: %s' % self.newCameras, verbose = False)
def repair(self, instance): """Delete all intermediateObjects""" intermediate_objects = self.list_intermediate_shapes(instance) if intermediate_objects: future = cmds.listHistory(intermediate_objects, future=True) cmds.delete(future, ch=True) cmds.delete(intermediate_objects)
def exportLights(self): for light in self.lights: hisObject = cmds.listHistory(light) hisObject = hisObject[0] exportName = light.replace(':', '_') thisNodeType = cmds.nodeType(hisObject) parameters = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'cr', 'cg', 'cb', 'intensity', 'rotateOrder'] if thisNodeType == 'spotLight': writeOutType = 'spot' parameters.append('coneAngle') parameters.append('penumbraAngle') parameters.append('dropoff') if thisNodeType == 'pointLight': writeOutType = 'point' if thisNodeType == 'directionalLight': writeOutType = 'directional' for i in range(self.startFrame, self.endFrame+1): if thisNodeType == 'spotLight': lightConeAngle = cmds.getAttr(hisObject + '.coneAngle',time=i) lightPenumbraAngle = cmds.getAttr(hisObject + '.penumbraAngle',time=i) lightDropoff = cmds.getAttr(hisObject + '.dropoff',time=i) else: lightConeAngle = 0 lightPenumbraAngle = 0 lightDropoff = 0 self.exportData(light, parameters, self.startFrame, self.endFrame+1, self.exportPath + exportName + '.fm2n') print 'Saved data from: ' + light
def jointVerts( joint, tolerance=1e-4 ): ''' returns a dict containing data about the verts influences by the given joint - dict keys are mesh names the joint affects. each dict value is a list of tuples containing (weight, idx) for the verts affected by the joint ''' newObjs = [] meshVerts = {} try: skins = list( set( cmd.listConnections(joint, s=0, type='skinCluster') ) ) except TypeError: return meshVerts for skin in skins: skinMeshes = cmd.ls(cmd.listHistory(skin, f=1), type='mesh') mesh = skinMeshes[0] dataList = [] meshVerts[mesh] = dataList numVerts = len(cmd.ls("%s.vtx[*]" % mesh, fl=True)) for n in xrange(numVerts): weight = cmd.skinPercent(skin, '%s.vtx[%d]' % (mesh, n), q=True, t=joint) if weight < tolerance: continue dataList.append( (weight, n) ) return meshVerts
def cmdSelectCurve( *args ): sgCurves = [] for hist in cmds.listHistory( cmds.ls( sl=1 ), pdo=1 ): if cmds.nodeType( hist ) != 'wire': continue targetCrv = cmds.listConnections( hist+'.deformedWire[0]' ) sgCurves.append( targetCrv[0] ) if sgCurves: cmds.select( sgCurves )
def history(self,obj): if not MAYA:return hisL = mc.listHistory(obj,leaf=1) shapeL = mc.listRelatives(obj,s=1)[0] hisL = [ x for x in hisL if x != shapeL ] self.num = len(hisL) # if hisL != [] else '' return self.num
def __init__(self, faceDriver_Crv='faceDriver_Crv'): self.microList = ['Up_lip_2x', 'Up_lip_3x', 'Up_lip_4x', 'Up_lip_5x', 'Up_lip_6x', 'Up_lip_7x', 'Up_lip_8x', 'Up_lip_9x', 'Up_lip_10x', 'Up_lip_11x', 'Up_lip_12x', 'Up_lip_13x', 'Up_lip_14x', 'Up_lip_15x', 'Up_lip_16x', 'Dn_lip_3x', 'Dn_lip_4x', 'Dn_lip_5x', 'Dn_lip_6x', 'Dn_lip_7x', 'Dn_lip_8x', 'Dn_lip_9x', 'Dn_lip_10x', 'Dn_lip_11x', 'Dn_lip_12x', 'Dn_lip_13x', 'Dn_lip_14x', 'Dn_lip_15x', 'cheeks_1x', 'cheeks_2x', 'cheeks_3x', 'cheeks_4x', 'cheeks_5x', 'cheeks_6x', 'cheeks_7x', 'cheeks_8x', 'cheeks_9x', 'cheeks_10x', 'cheeks_11x', 'cheeks_12x', 'cheeks_13x', 'cheeks_14x', 'cheeks_15x', 'cheeks_16x', 'cheeks_17x', 'cheeks_18x', 'cheeks_19x', 'Lf_eye_1x', 'Lf_eye_2x', 'Lf_eye_3x', 'Lf_eye_4x', 'Lf_eye_5x', 'Lf_eye_6x', 'Lf_eye_7x', 'Lf_eye_8x', 'Rt_eye_1x', 'Rt_eye_2x', 'Rt_eye_3x', 'Rt_eye_4x', 'Rt_eye_5x', 'Rt_eye_6x', 'Rt_eye_7x', 'Rt_eye_8x', 'Up_lipLft_2x', 'Up_lipLft_3x', 'Up_lipLft_4x', 'Up_lipLft_5x', 'Up_lipLft_6x', 'Up_lipLft_7x', 'Up_lipLft_8x', 'Up_lipLft_9x', 'Up_lipLft_10x', 'Up_lipLft_11x', 'Up_lipLft_12x', 'Up_lipLft_13x', 'Up_lipLft_14x', 'Up_lipLft_15x', 'Up_lipLft_16x', 'Dn_lipLft_3x', 'Dn_lipLft_4x', 'Dn_lipLft_5x', 'Dn_lipLft_6x', 'Dn_lipLft_7x', 'Dn_lipLft_8x', 'Dn_lipLft_9x', 'Dn_lipLft_10x', 'Dn_lipLft_11x', 'Dn_lipLft_12x', 'Dn_lipLft_13x', 'Dn_lipLft_14x', 'Dn_lipLft_15x', 'cheeksLft_1x', 'cheeksLft_2x', 'cheeksLft_3x', 'cheeksLft_4x', 'cheeksLft_5x', 'cheeksLft_6x', 'cheeksLft_7x', 'cheeksLft_8x', 'cheeksLft_9x', 'cheeksLft_10x', 'cheeksLft_11x', 'cheeksLft_12x', 'cheeksLft_13x', 'cheeksLft_14x', 'cheeksLft_15x', 'cheeksLft_16x', 'cheeksLft_17x', 'cheeksLft_18x', 'cheeksLft_19x'] ''' self.meshList = ['Up_lipLoft_msh','cheekLoft_msh','Dn_lipLoft_msh','Lf_eyeLoft_msh','Rt_eyeLoft_msh', 'LfUp_eyeLidLoft_msh','LfDn_eyeLidLoft_msh','RtUp_eyeLidLoft_msh','RtDn_eyeLidLoft_msh'] self.curveList = ['Up_lip_Crv','Dn_lip_Crv','cheeks_Crv','Up_lipLft_Crv','Dn_lipLft_Crv','cheeksLft_Crv', 'Rt_eye','Lf_eye'] ''' self.faceDriver_Crv = faceDriver_Crv self.skinCluster = cmds.ls(cmds.listHistory(faceDriver_Crv), type='skinCluster')[0] self.cvList = [] self.cvCnt = cmds.getAttr(self.faceDriver_Crv + '.spans') self.influenceDict = None self.influenceInfoDict = {} self.createCvList()
def findRelatedSkinCluster(geometry): ''' Return the skinCluster attached to the specified geometry Args: geometry (str): Geometry object/transform to query Returns: str ''' # Check geometry if not cmds.objExists(geometry): om.MGlobal.displayError('Object '+geometry+' does not exist!') return # Check transform if cmds.objectType(geometry) == 'transform': try: geometry = cmds.listRelatives(geometry,s=True,ni=True,pa=True)[0] except: om.MGlobal.displayError('Object %s has no deformable geometry!' % geometry) return # Determine skinCluster skin = mel.eval('findRelatedSkinCluster \"%s\"' % geometry) if not skin: skin = cmds.ls(cmds.listHistory(geometry, pdo=1, gl=1), type='skinCluster') if skin: skin = skin[0] if not skin: skin = None # Return result return skin
def symmetry_weight(srcNode=None, dstNode=None, symWeight=True): ''' ウェイトシンメトリする関数 srcNode→反転元 dstNode→反転先 symWeight→ウェイトミラーするかどうか ''' # スキンクラスタを取得 if srcNode is None: return srcShapes = cmds.listRelatives(srcNode, s=True, pa=True, type='mesh') if srcShapes: srcSkinCluster = cmds.ls(cmds.listHistory(srcNode), type='skinCluster') # スキンクラスタがあったらジョイントラベルを設定してウェイトミラー if srcSkinCluster: # バインド状態を転送する関数呼び出し skinJointAll = cmds.skinCluster(srcSkinCluster, q=True, inf=True) #ジョイントを取得 for skinJoint in skinJointAll: # ジョイントラベル設定関数呼び出し joint_label(skinJoint, visibility=False) if symWeight is False or dstNode is None: return transfer_weight(srcNode, dstNode, transferWeight=False, returnInfluences=True) dstShapes = cmds.listRelatives(dstNode, s=True, pa=True, type='mesh') dstSkinCluster = cmds.listConnections(dstShapes[0] + '.inMesh', s=True, d=False) cmds.copySkinWeights(ss=srcSkinCluster[0], ds=dstSkinCluster[0], mirrorMode='YZ', surfaceAssociation='closestComponent', influenceAssociation='label', normalize=True)
def get_invalid(cls, instance): meshes = cmds.ls(instance, type="mesh", noIntermediate=True, long=True) invalid = list() for mesh in meshes: history = cmds.listHistory(mesh) or [] skins = cmds.ls(history, type="skinCluster") # Ensure at most one skinCluster assert len(skins) <= 1, "Cannot have more than one skinCluster" if skins: skin = skins[0] # Ensure the mesh is also in the skinCluster set # otherwise the skin will not be exported correctly # by the FBX Exporter. deformer_sets = cmds.listSets(object=mesh, type=2) for deformer_set in deformer_sets: used_by = cmds.listConnections(deformer_set + ".usedBy", source=True, destination=False) # Ignore those that don't seem to have a usedBy connection if not used_by: continue # We have a matching deformer set relationship if skin in set(used_by): break else: invalid.append(mesh) cls.log.warning( "Mesh has skinCluster in history but is not included " "in its deformer relationship set: " "{0} (skinCluster: {1})".format(mesh, skin)) return invalid
def clampVertInfluenceCount(geos=None): ''' ''' global kMAX_INF_PER_VERT progressWindow = cmd.progressWindow skinPercent = cmd.skinPercent if geos is None: geos = cmd.ls(sl=True) for geo in geos: skin = cmd.ls(cmd.listHistory(geo), type='skinCluster')[0] verts = cmd.ls(cmd.polyListComponentConversion(geo, toVertex=True), fl=True) inc = 100.0 / len(verts) progress = 0 for vert in verts: progress += inc progressWindow(e=True, progress=progress) weightList = skinPercent(skin, vert, ib=1e-4, q=True, value=True) if len(weightList) > kMAX_INF_PER_VERT: jointList = skinPercent(skin, vert, ib=1e-4, q=True, transform=None) sorted = zip(weightList, jointList) sorted.sort() #now clamp to the highest kMAX_INF_PER_VERT number of weights, and re-normalize sorted = sorted[-kMAX_INF_PER_VERT:] weightSum = sum([a for a, b in sorted]) t_values = [(b, a / weightSum) for a, b in sorted] skinPercent(skin, vert, tv=t_values) #turn in limiting in the skinCluster cmd.setAttr('%s.maxInfluences' % skin, kMAX_INF_PER_VERT) cmd.setAttr('%s.maintainMaxInfluences' % skin, 1)
def _find_inverted_shape_for_deformer(deformer): """ Return the first non-intermediate mesh in the future of the given deformer. For the deformer, this should be the inverted mesh. The output of the blend shape is also in the future, but it comes later in the list. """ # We want to trace the output path through .outputGeometry[0]. listHistory won't # actually do this, since it only works on nodes and not plugs. Follow .outputGeometry[0] # to the next node and start from there. This can still fail if there are deformers # between our deformer and the geometry that have other output connections, since listHistory # will follow them too and may find another mesh. Typically we shouldn't have any extra # stuff in between anyway, but Maya likes to insert garbage createColorSet nodes everywhere. # Those don't have other output connections to interfere with this. outputGeometry = cmds.listConnections( '%s.outputGeometry[0]' % deformer) or [] if not outputGeometry: raise RuntimeError('Couldn\'t find the inverted output mesh for %s.' % deformer) history_nodes = cmds.listHistory(outputGeometry[0], f=True) for history_node in history_nodes: if cmds.nodeType(history_node) != 'mesh': continue if cmds.getAttr('%s.intermediateObject' % history_node): continue # We should always find the mesh before we hit a deformer. This makes sure # that we don't go too far forward and start messing with the real mesh. if set(cmds.nodeType(history_node, inherited=True)) & {'geometryFilter', 'deformer'}: raise RuntimeError( 'Found deformer %s before the inverted mesh for deformer %s' % (node, deformer)) return history_node raise RuntimeError('Couldn\'t find the output mesh for %s.' % deformer)
def returnDriverCurve(driverAttribute,drivenObject): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ACKNOWLEDGEMENT: Jason Schleifer's AFR Materials. DESCRIPTION: Returns the anim curve from a driver to a driven object ARGUMENTS: driverAttribute(string) drivenObject(string) RETURNS: driverCurves(list) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ driverFuture = mc.listConnections(driverAttribute,type = 'animCurve') buffer = mc.listConnections(drivenObject,s=True) drivenPast = mc.listHistory(buffer[0]) return lists.returnMatchList(driverFuture,drivenPast)
def check(self): self.toCheck = cmds.ls(dag=True, type='transform', long=True) baseProgressValue = 100. / (len(self.toCheck) or 1) for i, each in enumerate(self.toCheck): self.setProgressValue(baseProgressValue * i, text='Checking: {0}'.format(each)) history = cmds.listHistory(each, future=False, pruneDagObjects=True) if history: self.toFix.append(each) self.addFeedback(title='These nodes have construction history', toDisplay=[ cmds.ls(node, shortNames=True)[0] for node in self.toFix ], toSelect=self.toFix)
def findRelatedDeltaMush(geometry): """ Return the delta mush deformer attached to the specified geometry Args: geometry (str): Geometry object/transform to query Returns: str """ # Check geometry if not cmds.objExists(geometry): raise Exception('Object ' + geometry + ' does not exist!') hist = cmds.listHistory(geometry, pdo=1, gl=1) try: if mayaVersion() >= 2016: return cmds.ls(hist, type=["deltaMush", "wbDeltaMush"])[0] else: return cmds.ls(hist, type="wbDeltaMush")[0] except: return None
def findRelatedSkinCluster(geometry): ''' Return the skinCluster attached to the specified geometry @param geometry: Geometry object/transform to query @type geometry: str ''' # Check geometry if not mc.objExists(geometry): raise UserInputError('Object '+geometry+' does not exist!') # Check transform if mc.objectType(geometry) == 'transform': try: geometry = mc.listRelatives(geometry,s=True,ni=True,pa=True)[0] except: raise UserInputError('Object '+geometry+' has no deformable geometry!') # Determine skinCluster skin = mm.eval('findRelatedSkinCluster "'+geometry+'"') if not skin: skin = mc.ls(mc.listHistory(geometry),type='skinCluster') if skin: skin = skin[0] if not skin: skin = '' # Return result return skin
def returnObjectDeformers(obj, deformerTypes = 'all'): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ACKNOWLEDGEMENT Pythonized from - http://www.scriptswell.net/2010/09/mel-list-all-deformers-on-mesh.html DESCRIPTION: Returns a list of deformers on an object in order from top to bottom ARGUMENTS: obj(string) RETURNS: deformers(list)/False >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ objHistory = mc.listHistory(obj,pruneDagObjects=True) deformers = [] if objHistory: for node in objHistory: typeBuffer = mc.nodeType(node, inherited=True) if 'geometryFilter' in typeBuffer: deformers.append(node) if len(deformers)>0: if deformerTypes == 'all': return deformers else: foundDeformers = [] #Do a loop to figure out if the types are there for deformer in deformers: if search.returnObjectType(deformer) == deformerTypes: foundDeformers.append(deformer) if len(foundDeformers)>0: return foundDeformers else: return False else: return False
def CenterPivotss(): sel=cmds.ls(sl=1) curves = mel.eval('curve -d 1 -p -0.984151 0 1.018023 -p 0.984151 0 1.018023 -p 0.984151 0 -1.018023 -p -0.984151 0 -1.018023 -p -0.984151 0 1.018023 -k 0 -k 1 -k 2 -k 3 -k 4 -n "Character";') cmds.rename(cmds.listRelatives(curves,s=1)[0],"CharacterShape") circles = cmds.circle(nr=(0, 1, 0), c=(0, 0, 0), n='Main') history = cmds.listHistory(curves, circles[0], ha=1) cmds.makeIdentity(apply=True,r=1,t=1,s=1) groups = cmds.group(curves, n='Character_C', w=1) groupcurve = cmds.group(groups, n='Character_G', w=1) groupss = cmds.group(circles[0], n='Main_C',w=1) groupcircles = cmds.group(groupss, n='Main_G', w = 1) prant = cmds.parent(groupcircles, curves) cmds.delete(cmds.parentConstraint(sel,groupcurve,mo=0)) cmds.select(circles[0],curves) cmds.setAttr(circles[0]+'.scaleX',lock=1,k=0) cmds.setAttr(circles[0]+'.scaleY',lock=1,k=0) cmds.setAttr(circles[0]+'.scaleZ',lock=1,k=0) cmds.setAttr(circles[0]+'.visibility',lock=1,k=0) cmds.setAttr(curves+'.visibility',lock=1,k=0) color = cmds.setAttr(circles[0]+".overrideEnabled",1) colors = cmds.setAttr(circles[0]+".overrideColor",13) showmod= cmds.addAttr (circles[0],ln='showMod',at='double',min=0,max=1,dv=1,k=1)
def selected(time_filter, skip_cycle=True): selection = cmds.ls(selection=True) anim_curves = [] for node in selection: if cmds.nodeType(node) in ( "animCurveTL", "animCurveTA", "animCurveTT", "animCurveTU", ): anim_curves.append(node) else: curves = cmds.ls(cmds.listHistory(node, leaf=False), type=( 'animCurveTL', 'animCurveTA', 'animCurveTT', 'animCurveTU', )) anim_curves += curves pprint.pprint(anim_curves) curve_list(anim_curves, time_filter, skip_cycle)
def _get_ndynamic_mobjs_from_scene(): # Get all nucleus mobjs nucleus_mobjs = MUtil._get_all_mobjs_of_type( MGlobals.ndynamic_dependency_node_types[0]) # mobj_lists holds list of mobjs of all: ncloth_nodes, nrigid_nodes, dynamic_constraint_nodes mobj_lists = [ MUtil._get_all_mobjs_of_type(x) for x in MGlobals.ndynamic_dependency_node_types[1:] ] # Find all nCloth, nRigid and dynamicConstraint mobjs for each nucleus ndynamic_mobj_inventory = {} for nucleus_mobj in nucleus_mobjs: nucleus_name = MUtil._get_name_of_mobj(nucleus_mobj) ndynamic_mobj_inventory[nucleus_name] = { "nucleus": [nucleus_mobj], } nucleus_node = MUtil._get_long_name_of_mobj(nucleus_mobj) history_nodes = cmds.listHistory(nucleus_node, allConnections=True) history_mobj_list = [ MUtil._get_mobj_of_node(x) for x in history_nodes ] for ncloth_node_type, mobj_list in zip( MGlobals.ndynamic_node_types[1:], mobj_lists): # Can't use sets with MObjects, therefore has to be a list comprehension mobjs_of_type_and_in_history = [ x for x in mobj_list if x in history_mobj_list ] ndynamic_mobj_inventory[nucleus_name][ ncloth_node_type] = mobjs_of_type_and_in_history # Test inventory # ndynamic_mobj_inventory = {} # print ndynamic_mobj_inventory return ndynamic_mobj_inventory
def select_skinned_mesh(self): """ Checks if selected object is a skinned mesh before storing and using the object """ import maya.cmds as cmds # pylint: disable=import-error selection = cmds.ls(selection=True) if self._verify_selection(selection): found_skin_cluster = False for history_node in cmds.listHistory(selection[0]): if 'skinCluster' in history_node: self.skinned_mesh_le.setText(str(selection[0])) found_skin_cluster = True self.enable_transfer_uv() break if not found_skin_cluster: self.popup_message('Selected Object is not a Skinned Mesh')
def get_id_from_history(node): """Return first node id in the history chain that matches this node. The nodes in history must be of the exact same node type and must be parented under the same parent. Args: node (str): node to retrieve the Returns: str or None: The id from the node in history or None when no id found on any valid nodes in the history. """ def _get_parent(node): """Return full path name for parent of node""" return cmds.listRelatives(node, parent=True, fullPath=True) node = cmds.ls(node, long=True)[0] # Find all similar nodes in history history = cmds.listHistory(node) node_type = cmds.nodeType(node) similar_nodes = cmds.ls(history, exactType=node_type, long=True) # Exclude itself similar_nodes = [x for x in similar_nodes if x != node] # The node *must be* under the same parent parent = _get_parent(node) similar_nodes = [i for i in similar_nodes if _get_parent(i) == parent] # Check all of the remaining similar nodes and take the first one # with an id and assume it's the original. for similar_node in similar_nodes: _id = get_id(similar_node) if _id: return _id
def parseDrivenKeys(self, debug=0): curves = cmds.ls(type=("animCurveUL","animCurveUU","animCurveUA","animCurveUT")) items = [] for c in curves: drivingAttr = cmds.listConnections(c + '.input', p=1) dk = self.sdk() dk.drivingAttr = drivingAttr[0] dk.curve = c #find the driven attribute futureNodes = [node for node in cmds.listHistory(c, future=1, ac=1)] futureNodes.reverse() drivenAttr = None for node in futureNodes: if cmds.nodeType(node) == 'unitConversion': try: drivenAttr = cmds.listConnections(node + '.output', p=1)[0] break except: cmds.warning('blendWeighted node with no output: ' + node) break elif cmds.nodeType(node) == 'blendWeighted': try: drivenAttr = cmds.listConnections(node + '.output', p=1)[0] break except: cmds.warning('blendWeighted node with no output: ' + node) break if not drivenAttr: drivenAttr = cmds.listConnections(c + '.output', p=1)[0] if drivenAttr: dk.drivenAttr = drivenAttr else: cmds.warning('No driven attr found for ' + c) items.append(dk) if debug: print dk.drivingAttr, dk.curve, dk.drivenAttr return items
def getAllDef(geo): ''' Description: Get all deformer assigned to shape. ''' deformerTypeLs = [ 'skinCluster', 'blendShape', 'cluster', 'ffd', 'wrap', 'nonLinear', 'sculpt', 'softMod', 'jiggle', 'wire' ] assignedDefLs = [] if cmds.nodeType(geo) == 'transform': geo = cmds.listRelatives(geo, s=True, ni=True)[0] allConnections = cmds.listHistory(geo) for deformerType in deformerTypeLs: findDeformer = cmds.ls(allConnections, type=deformerType) if findDeformer: assignedDefLs.append(findDeformer[0]) return assignedDefLs
def get_skin_clusters(nodes): """Get the skinClusters attached to the specified node and all nodes in descendents. :param nodes: List of dag nodes. @return A list of the skinClusters in the hierarchy of the specified root node. """ if isinstance(nodes, string_types): nodes = [ nodes, ] all_skins = [] for node in nodes: relatives = cmds.listRelatives(node, ad=True, path=True) or [] relatives.insert(0, node) relatives = [shortcuts.get_shape(node) for node in relatives] for relative in relatives: history = cmds.listHistory(relative, pruneDagObjects=True, il=2) or [] skins = [x for x in history if cmds.nodeType(x) == 'skinCluster'] if skins: all_skins.append(skins[0]) return list(set(all_skins))
def getDeformers(baseObj, _type=list()): """ Get the list of deformers found on in_obj filtered by in type :param baseObj: The object that give deformers :type baseObj: str :param _type: type of deformers to filter : ['skinCluster', 'blendShape', 'cluster' ] :type _type: str || list :return: list of found deformers :rtype: list """ result = list() history = mc.ls(mc.listHistory(baseObj, pruneDagObjects=True), type='geometryFilter') or list() #--- Get Deformers ---# for item in history: if len(_type) > 0: if mc.nodeType(item) in _type: result.append(str(item)) else: result.append(str(item)) #--- Result ---# return result
def findOutputs(): curves = cmds.ls(type = ('animCurveUL')) items = [] for c in curves: driving = cmds.listConnections(c + '.input', p = 1) futureNodes = [node for node in cmds.listHistory(c, future=1, ac=1)] futureNodes.reverse() drivenAttr = None for node in futureNodes: if cmds.nodeType(node) == 'unitConversion': try: drivenAttr = cmds.listConnections(node + '.output', p=1)[0] break except: cmds.warning('blendWeighted node with no output: ' + node) break elif cmds.nodeType(node) == 'blendWeighted': try: drivenAttr = cmds.listConnections(node + '.output', p=1)[0] break except: cmds.warning('blendWeighted node with no output: ' + node) break if not drivenAttr: drivenAttr = cmds.listConnections(c , p=1)[0] if drivenAttr: drivenAttr2 = drivenAttr else: cmds.warning('No driven attr found for ' + c) #print driving if driving != None: items.append([driving[0], drivenAttr2]) return items
def convert_pre_deformation(target): u"""指定ノードをpre-deformationに変換する Args: target (unicode): 対象のノード """ histories = cmds.listHistory(target, gl=True, pdo=True, lf=True, f=False, il=2) last_blend_shape = None for h in histories: object_type = cmds.objectType(h) if object_type == "skinCluster": last_skin_cluster = h continue if object_type == "blendShape": last_blend_shape = h cmds.reorderDeformers(last_skin_cluster, last_blend_shape, target)
def normalCheckRemove(meshList=[]): ''' Remove normal check properties for a specified list of meshes. @param meshList: List of meshes to removes normal check from @type meshList: list ''' # Check Mesh List meshList = cleanup.getMeshList(meshList) if not meshList: return [] # Remove Normal Check for mesh in meshList: # Clear Selection mc.select(cl=True) # Turn Off Double Sided mc.setAttr(mesh + '.doubleSided', 0) # Remove Extrude Face polyExtrude = mc.ls(mc.listHistory(mesh), type='polyExtrudeFace') if polyExtrude: mc.delete(polyExtrude) # Delete History mc.delete(mesh, ch=True) # Apply Initial Shading Group mc.sets(mesh, fe='initialShadingGroup') # Check normalShader members normalSG = 'normalCheckSG' normalShader = 'normalCheckShader' if not mc.sets(normalSG, q=True): mc.delete(normalShader, normalSG) # Set Selection mc.select(meshList) # Retrun Result return meshList
def rebindCurrentPose(trNode): hists = cmds.listHistory(trNode, pdo=1) for hist in hists: if not cmds.nodeType(hist) == 'skinCluster': continue cons = cmds.listConnections(hist + '.matrix', type='joint', c=1, p=1, s=1, d=0) outputs = cons[1::2] inputs = cons[::2] for i in range(len(outputs)): mtx = cmds.getAttr(outputs[i].replace('worldMatrix', 'worldInverseMatrix')) cmds.setAttr(inputs[i].replace('matrix', 'bindPreMatrix'), mtx, type='matrix')
def EvaluateFrames(node, timeAttr, inRenderFrame): """ timeAttr may have expression applied EvaluateFrames returns adequatly modified render and sample frames """ timePlug = "%s.%s" % (node, timeAttr) outRenderFrame = inRenderFrame outSampleFrame = cmds.getAttr(timePlug) conns = cmds.listConnections(timePlug, s=1, d=0, sh=1, p=1) if conns != None: restoreConns = [] srcPlug = conns[0] srcNode = srcPlug.split(".")[0] hist = cmds.listHistory(srcNode) if hist != None: for h in hist: tconns = cmds.listConnections(h, s=1, d=0, p=1, c=1, type="time") if tconns is None: continue i = 0 n = len(tconns) while i < n: restoreConns.append((tconns[i + 1], tconns[i])) cmds.disconnectAttr(tconns[i + 1], tconns[i]) cmds.setAttr(tconns[i], inRenderFrame) i += 2 if len(restoreConns) > 0: outRenderFrame = cmds.getAttr(srcPlug) for src, dst in restoreConns: cmds.connectAttr(src, dst) return (outRenderFrame, outSampleFrame)
def LabelJoints(*args, **kwargs): sel = cmds.ls(sl=True) # if sel is None or len(sel) == 0: cmds.warning('Not executed, please check selected mesh') return mainSkin = [ item for item in cmds.listHistory(sel[0]) if cmds.objectType(item, isType='skinCluster') ][0] jntList = [itm for itm in cmds.skinCluster(mainSkin, q=1, inf=1)] tempJDict = helpersMain.match_strings(jntList, filter='_L_', replace='_R_') helpersMain.rename_sibilings(tempJDict) jntList = [itm for itm in cmds.skinCluster(mainSkin, q=1, inf=1)] if any([itm for itm in jntList if ':' in itm]): jntList = [itm.split(':')[-1] for itm in jntList] for jnt in jntList: prefix = jnt.split('_')[0] cmds.setAttr(jnt + '.type', 18) cmds.setAttr(jnt + '.otherType', prefix, type='string') if '_L_' in jnt: cmds.setAttr(jnt + '.side', 1) elif '_R_' in jnt: cmds.setAttr(jnt + '.side', 2) else: cmds.setAttr(jnt + '.side', 0) # om.MGlobal.displayInfo("Labeling Done")
def _get_gozid_mismatches(objs): """Return objects from `objs` whose gozbruhBrushID does not match their name Checks object history for instances of gozbruhBrushID, returns a list ofgozbruhBrushID/name conflicts gozbruhBrushID is created by ZBrush on export and is used to track name changes that can occur in maya this function compares object current name against the ID and returns a list of conflicts this list is handled by the gui to allow for dialog boxes """ goz_list = [] for obj in objs: has_attr = cmds.attributeQuery( 'gozbruhBrushID', node=obj, exists=True) if has_attr: # check for 'rename' goz_id = cmds.getAttr(obj + '.gozbruhBrushID') if obj != goz_id: goz_list.append((obj, goz_id)) else: # check for old ID in history for old_obj in cmds.listHistory(obj): has_attr = cmds.attributeQuery('gozbruhBrushID', node=old_obj, exists=True) if has_attr: goz_id = cmds.getAttr(old_obj + '.gozbruhBrushID') if obj != goz_id: goz_list.append((obj, goz_id)) # resulting mismatches to be handled return goz_list
def findMeshWithBlendShapes(nameSpace): """ Purpose: return the meshes connected to blend_shape node Procedure: get a list of blend_shape node, follow those connections to the mesh shape node traverse up the hierarchy to find parent transform node Presumption: character has a valid namespace :param nameSpace: all the blendShapes nodes :return: a list of all the meshes with blendShape """ returnArray = [] blendshapes = cmds.ls((nameSpace + ':*'), type='blendShape') for curBlendShape in blendshapes: downStreamNodes = cmds.listHistory(curBlendShape, future=1) for curNode in downStreamNodes: if cmds.objectType(curNode, isType='mesh'): parents = cmds.listRelatives(curNode, parent=1) returnArray.append(parents[0]) return returnArray
def action_SaveWeights(savePath=''): savePath = '' selectionList = mc.ls(sl=True, objectsOnly=True) if not savePath: savePath = dirPath() for obj in selectionList: if mc.objectType(obj, isType="transform"): mc.select(obj) xmlName = str(obj) + ".xml" try: mesh = mc.ls(sl=True, objectsOnly=True) meshSkinCluster = str( mc.ls(mc.listHistory(mesh), type='skinCluster')[0]) mc.deformerWeights(xmlName, ex=True, path=savePath, deformer=meshSkinCluster) except: e = sys.exc_info()[1] print "Skipping mesh: {obj}: ".format(obj=obj) + str(e) print "----------------------------------------" print savePath.replace("/", "\\") return savePath
def deleteSkeleton(self): intermediateShapes = [] attachedGeo = [] for geo in self.geometryData: if not geo.skinnable(): if geo.attached(): attachedGeo.append(geo) continue history = mc.listHistory(geo.shapeName()) for node in history: if mc.objectType(node, isAType="shape"): if mc.getAttr("%s.intermediateObject" % node): intermediateShapes.append(node) mc.delete(self.skelGroup) mc.delete(intermediateShapes) self.skelGroup = "" self.rootJoint = None self.joints = {} self.primitiveData = [] # Attached geometry has been deleted with the skeleton # for geo in attachedGeo: self.geometryData.remove(geo)
def transferDeformers(source, target, deformerTypes = ["skinCluster"], surfaceAssociation="closestPoint"): ''' This will transfer all deformers and weights. If it's the same :param source: The geomertry you are transfer from :type source: str :param target: The geometry you want to transfer to :type target: str | list :param surfaceAssociation: How to copy the weights from source to target available values are "closestPoint", "rayCast", or "closestComponent" :type surfaceAssociation: str ''' # do some error checking hist = [node for node in mc.listHistory(source, pdo=True, interestLevel=1) if mc.nodeType(node) in deformerTypes] if hist: if 'skinCluster' in deformerTypes: rigrepo.libs.skinCluster.transferSkinCluster(source, target, surfaceAssociation) elif 'cluster' in deformerTypes: for cluster in rigrepo.libs.cluster.getClusters(source): rigrepo.libs.cluster.transferCluster(source, target, cluster, handle=True, surfaceAssociation="closestPoint", createNew=True)
def getMembershipVerts(sel): '''Gets verts affected by deformer and activates Edit Membership Tool.''' print 'SEL: ', sel[0] for each in range(len(sel)): print sel[each] sel_sets = cmds.listSets(extendToShape=True, object=sel[0], type=2) for each in range(len(sel_sets)): type = cmds.nodeType(sel_sets[each]) cmds.select(sel_sets[0], replace=True) verts = cmds.ls(selection=True, flatten=True) for vert in range(len(verts)): print verts[vert] inputs = cmds.listHistory(sel, pruneDagObjects=True, historyAttr=False) getDeformers(sel) cmds.EditMembershipTool() # returns deformer-influenced verts return verts