Exemplo n.º 1
0
def setInfluenceWeight(skn, mesh, influenceName, weightList):
    '''
    Set weights on influence using a float list
    '''
    for vertId in range(len(weightList)):
        if weightList[vertId]:
            mc.skinPercent(skn, mesh+'.vtx[%d]'%vertId, transformValue=[influenceName, weightList[vertId]])
Exemplo n.º 2
0
def oldSkooFaceRigWeightImport(path):

    pickleFile = open(path, 'r')
    Import_Info = pickle.load(pickleFile)
    pickleFile.close()
    sknClstr = Import_Info.skinCluster
    cmds.setAttr(sknClstr + '.normalizeWeights', 0)
    points = cmds.getAttr('faceDriver_Crv.spans')
    # Iterate through each point on the faceDriver_Crv
    for i in range(0, points, 1):
        cv = OldSkooPointInfo('faceDriver_Crv.cv[' + str(i) + ']')
        closestPoint = getMapPnt(Import_Info.influenceInfoDict.keys(), cv)
        if Import_Info.influenceInfoDict.has_key(closestPoint[0]):
            setInfList = Import_Info.influenceInfoDict[closestPoint[0]][0]
            setWgtList = Import_Info.influenceInfoDict[closestPoint[0]][1]

            infLst = cmds.skinPercent(sknClstr, cv.name, ib=1e-4, query=True, transform=None)
            # Set the weights to 0
            for i in infLst:
                cmds.skinPercent(sknClstr, cv.name, tv=[i, 0])

            for i, inf in enumerate(setInfList):
                cmds.skinPercent(sknClstr, cv.name, tv=[inf, setWgtList[i]])
        else:
            print '-- point missed: %s, closest point: %s' % (cv.name, closestPoint[0])
    cmds.setAttr(sknClstr + '.normalizeWeights', 1)
Exemplo n.º 3
0
def setInfluenceWeightsSlow(skinCluster,influence,weightList,normalize=True,componentList=[]):
	'''
	'''
	# Verify skinCluster
	if not isSkinCluster(skinCluster):
		raise Exception('Invalid skinCluster "' + skinCluster + '" specified!')
	
	# Check influence
	if not mc.objExists(influence):
		raise Exception('Influence object "'+influence+'" does not exists!')
	if not mc.skinCluster(skinCluster,q=True,inf=True).count(influence):
		raise Exception('Influence "'+influence+'" not connected to skinCluster "'+skinCluster+'"!')
	
	# Get geometry
	affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster).keys()[0]
	
	# Check component list
	if not componentList: componentList = glTools.utils.component.getComponentStrList(affectedGeo)
	componentIndexList = glTools.utils.component.getComponentIndexList(componentList)
	componentIndexList = componentIndexList[componentIndexList.keys()[0]]
	
	# Check component and weight list lengths
	if len(componentIndexList) != len(weightList):
		raise Exception('List length mis-match!')
	
	# Set weight values
	for i in range(len(componentIndexList)):
		comp = glTools.utils.component.getComponentStrList(affectedGeo,[componentIndexList[i]])[0]
		mc.skinPercent(skinCluster,comp,tv=(influence,weightList[i]),normalize=normalize)
Exemplo n.º 4
0
 def test_import_skin_sets_correct_data(self):
     file_path = self.get_temp_filename('temp.skin')
     skinio.export_skin(file_path, self.shape)
     cmds.skinPercent(self.skin, '{0}.vtx[0]'.format(self.shape),
                      transformValue=[(self.joint1, 0.1), (self.joint2, 0.2), (self.joint3, 0.7)])
     skinio.import_skin(file_path)
     self.test_skincluster_data_is_correct()
Exemplo n.º 5
0
def add_skinCluster_weights (vertexIDs, src_mesh, dst_mesh, mask_joint=None):
    src_skin = get_skinCluster(src_mesh)
    dst_skin = get_skinCluster(dst_mesh)
    
    src_skinCls_matrix_dict = loads_skinCluster_matrix(src_mesh)
    dst_skinCls_matrix_dict = loads_skinCluster_matrix(dst_mesh)
    
    cmds.skinCluster(dst_skin, e=True, normalizeWeights=False)
    
    for vertexID in vertexIDs:
        if not mask_joint: #if no mask joint defined, overwrite weight onto dst mesh
            cmds.skinPercent( dst_skin, "%s.vtx[%s]"%(dst_mesh, vertexID), pruneWeights=100)
            maskValue = 1
        else:
            mask_jointIndex = dst_skinCls_matrix_dict[mask_joint]
            maskValue = cmds.getAttr("%s.wl[%s].w[%s]" %(dst_skin, vertexID, mask_jointIndex))
            cmds.setAttr("%s.wl[%s].w[%s]" %(dst_skin, vertexID, mask_jointIndex), 0)
                        
        for src_joint, src_jointIndex in src_skinCls_matrix_dict.iteritems():
            weight = cmds.getAttr("%s.wl[%s].w[%s]" %(src_skin, vertexID, src_jointIndex)) * maskValue
            if weight != 0.0:
                dst_jointIndex = dst_skinCls_matrix_dict[src_joint]
                cmds.setAttr("%s.wl[%s].w[%s]" %(dst_skin, vertexID, dst_jointIndex), weight)

    cmds.skinCluster(dst_skin, e=True, normalizeWeights=True)
Exemplo n.º 6
0
    def normalizeWeights(self, selName, infNames, clusterNode):
        """
        Remove non-zero weighting:
        Temporarily removing weight normalization allows for a weight prune
        Weight pruning is done to remove all non-zero weighting
        Non-zero weighting is removed to compress object data (faster speed) and file size
        """
        clusterName = clusterNode.name()

        # Unlock influences first
        for inf in infNames:
            cmds.setAttr("%s.liw" % inf, 0)

        # Temporarily turn off normalize
        normalizeSetting = cmds.getAttr("%s.normalizeWeights" % clusterName)

        if normalizeSetting != 0:
            cmds.setAttr("%s.normalizeWeights" % clusterName, 0)

        # Prune non-zero weights
        cmds.skinPercent(clusterName, selName, nrm=False, prw=100)
        # Turn normalize back on
        if normalizeSetting != 0:
            # cmds.setAttr('%s.normalizeWeights' % clusterName, normalizeSetting)
            cmds.setAttr("%s.normalizeWeights" % clusterName, normalizeSetting)
Exemplo n.º 7
0
 def clampInfluences(self, mesh, maxInf, debug=0, force=False):
     '''
     Sets max influences on skincluster of mesh / cutting off smallest ones
     '''
     skinClust = self.findRelatedSkinCluster(mesh)
 
     lockedInfluences = self.checkLockedInfluences(skinClust)
     doit = True
     if lockedInfluences:
         if force:
             self.unlockLockedInfluences(skinClust)
             cmds.warning('Locked influences were unlocked on skinCluster')
         else:
             doit = False
     
     if doit:
         verts = self.checkMaxSkinInfluences(mesh, maxInf)
         
         print 'pruneVertWeights>> Pruning', len(verts), 'vertices'
         
         for v in verts:
             infs = cmds.skinPercent(skinClust, (mesh + ".vtx[" + str(v) + "]"), q=1, v=1)
             active = []
             for inf in infs:
                 if inf > 0.0: active.append(inf)
             active = list(reversed(sorted(active)))
             if debug: print 'Clamping vertex', v, 'to', active[maxInf]
             cmds.skinPercent(skinClust, (mesh + ".vtx[" + str(v) + "]"), pruneWeights=(active[maxInf]*1.001))
     else:
         cmds.warning('Cannot clamp influences due to locked weights on skinCluster')
Exemplo n.º 8
0
def readDirtyInfInfo(*args):
    sel = cmds.ls(sl=True, fl=True)
    obj = sel[0].split('.')[0]
    shape = cmds.listRelatives(obj, shapes=True)[0]
    skinCluster = mm.eval('findRelatedSkinCluster("' + shape + '")')
    infLst = cmds.skinCluster(skinCluster, query=True, inf=True)
    cmds.setAttr(skinCluster + '.normalizeWeights', 0)

    filePath = os.path.join(os.getenv('HOME'), 'Desktop/tmpWgtExport.txt')
    f = open(filePath, 'r')
    lines = f.readlines()

    cvCnt = 0
    if len(sel) == len(lines):
        for cv in sel:
            wgtLst = cmds.skinPercent(skinCluster, cv, query=True, v=True)
            # set turn off normalization and set all weights to zero
            for i in range(0, len(infLst), 1):
                cmds.skinPercent(skinCluster, cv, tv=(infLst[i], 0))

            rLine = eval(lines[cvCnt])
            for i in range(0, len(rLine), 1):
                cmds.skinPercent(skinCluster, cv, tv=(rLine[i][0], rLine[i][1]))
            f.close()
            cvCnt += 1
        cmds.setAttr(skinCluster + '.normalizeWeights', 1)
    else:
        print 'Maya selection count doesn\'t match exported file component count.'
Exemplo n.º 9
0
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 doIt(self,argList):
        polygons = cmds.filterExpand(sm=12)
        if not polygons:
            print 'Please select a polygon.'
            return

        paths = cmds.fileDialog2(dialogStyle=2, fileMode = 3, okCaption = "Save", cancelCaption = "Cancel")
        if not paths:
            return

        for p in range(0, len(polygons)):
            polygon = polygons[p]
            related_cluster = mel.eval('findRelatedSkinCluster '+polygon)
            if related_cluster == '':
                print 'Please bind skin for this polygon.' + polygon
                continue

            path = paths[0]
            joints = cmds.skinPercent(related_cluster, polygon+'.vtx[0]', q = True, t = None);
            f = open(path+'/'+polygon+'.weights', 'w')

            vertices = cmds.getAttr(polygon+'.vrts', multiIndices = True);
            for i in range(0, len(vertices)):
                infs = cmds.skinPercent(related_cluster, polygon+'.vtx['+str(vertices[i])+']', q = True, v = True)
                pos = cmds.xform(polygon+'.vtx['+str(vertices[i])+']', q=1, ws=1, t=1)
                f.write('vp ' + str(pos[0])+' '+str(pos[1])+' '+str(pos[2]) + '\n')
                f.write('vinf');
                for j in range(0, len(infs)):
                    f.write(' ' + joints[j] + ' ' + str(infs[j]))
                f.write('\n')
            f.close()

        print 'Export Complete.'
Exemplo n.º 11
0
 def cache(s, meshes=None):
     """
     Store joints influence on objects for quick checking later
     """
     if meshes:
         # Cache Joints and Meshes
         for mesh in meshes:
             skin = mel.eval("findRelatedSkinCluster %s" % mesh)
             if skin:
                 joints = cmds.skinPercent(skin, "%s.vtx[0]" % mesh, q=True, t=None)
                 for vert in range(cmds.getAttr("%s.weightList" % skin, size=True)):
                     for i, v in enumerate(cmds.skinPercent(skin, "%s.vtx[%s]" % (mesh, vert), q=True, v=True)):
                         joint = joints[i]
                         if 0.2 < v:
                             # Sort by joints
                             s.joints[joint] = s.joints.get(joint, [])
                             s.joints[joint].append("%s.vtx[%s]" % (mesh, vert))
                             # Sort by meshes
                             s.meshes[mesh] = s.meshes.get(mesh, {})
                             s.meshes[mesh][joint] = s.meshes[mesh].get(joint, {})
                             s.meshes[mesh][joint][vert] = v
         # Speed up Cache
         if s.joints:
             s.select.ignore = True
             for j in s.joints:
                 cmds.select(s.joints[j], r=True)
                 s.joints[j] = cmds.filterExpand(ex=False, sm=31)
             cmds.select(clear=True)
     else:
         s.meshes = {}
         s.joints = {}
     pass
Exemplo n.º 12
0
	def scaleMin( self , arg=None ) :
		
		val = self.getScaleVal()
		
		vtcs = mc.ls( sl=True , fl=True )
		
		for vtc in vtcs :
			
			geo = vtc.split( '.' )[0]
			skn = mm.eval( 'findRelatedSkinCluster( "%s" )' % geo )
			
			mc.setAttr( '%s.normalizeWeights' % skn , False )
			
			infs = mc.skinCluster( skn , q=True , inf=True )
			skinVals = mc.skinPercent( skn , vtc , q = True , v = True )
			
			maxVal = sorted( skinVals )[-1]
			
			minVal = 1
			for skinVal in skinVals :
				if skinVal and skinVal < minVal :
					minVal = skinVal
			
			minId = skinVals.index( minVal )
			maxId = skinVals.index( maxVal )
			
			newMin = minVal * val
			newMax = maxVal + ( minVal - newMin )
			
			mc.skinPercent( skn , vtc , tv = ( infs[minId] , newMin ) )
			mc.skinPercent( skn , vtc , tv = ( infs[maxId] , newMax ) )
			
			mc.setAttr( '%s.normalizeWeights' % skn , True )
Exemplo n.º 13
0
 def setVertWts(self,*args):
     sel = cmds.ls(sl=True,fl=True)
     mesh = sel[0].split('.')[0]
     self.skClstr = mel.eval('findRelatedSkinCluster("%s")'%mesh)        
     for vert in sel:
         for val,inf in zip(self.srcVals,self.infs):
             cmds.skinPercent( self.skClstr, vert, transformValue=[(inf,val)] )
def weightZero(skinClusterName, deformerName):
    scNormalWeights = skinClusterName + '.normalizeWeights'
    cmds.setAttr(scNormalWeights, 1)
    cmds.skinPercent(skinClusterName, transformValue=[ (deformerName, 1.0)])
    cmds.setAttr(scNormalWeights, 0)
    cmds.skinCluster(skinClusterName, edit = True, fnw = True)
    cmds.skinPercent(skinClusterName, transformValue=[ (deformerName, 0.0)])
Exemplo n.º 15
0
 def setWeightFn(self):
     if self.currentInf:
         if len(self.currentInf) > 1:
             cmds.warning('skinWrangler: Set Weight does not work with multi-selection because I am too lazy at the moment to write my own normalization code.')
         else:
             cmds.skinPercent(self.currentSkin, self.currentVerts, tv=[self.currentInf[0], self.setWeightSpin.value()])
         self.refreshUI()
     else: cmds.warning('[skinWrangler] No influences/joints selected')
def assignWeights(skinClusterName, objectName, vertices, deformers):
    scNormalWeights = skinClusterName + '.normalizeWeights'
    cmds.setAttr( scNormalWeights, 0)
    for vertexId in vertices:
        for deformerId in vertices[vertexId]:
            deformerVertex = "%s.vtx[%s]" % (objectName, vertexId)
            deformerName = deformers[deformerId]
            vertexWeight = float( vertices[vertexId][deformerId] )
            cmds.skinPercent( skinClusterName, deformerVertex,  transformValue=[(deformerName, vertexWeight)])
Exemplo n.º 17
0
    def loadSkinWeights(self, *args):
        import maya.mel as mel
        
        try:
            character = cmds.ls(sl=True)[0]
        except:
            cmds.headsUpMessage("Please Select Valid Geometry")
            return

        
        # Define the file name and path
        characterName = self.characterName
        skinPath = turbineUtils.setupDirs(characterName, create=False)[4]
        outFileSuffix = '_skinWeight.csv'
        outFile = (character + outFileSuffix )
        finalPath = (skinPath + outFile)

        missingJoints = []
        allCV = []
        if cmds.file(finalPath, q=True, ex=True):
            reader = csv.reader(open(finalPath, 'rb'), delimiter=' ', quotechar='|')
        else:
            return
        
        # Find the skin cluster
        selection= cmds.ls(sl=True, fl=True)
        mel.eval("$selectionList = `ls -sl`")
        skCl = mel.eval('findRelatedSkinCluster $selectionList[0]')
    
        for row in reader:
            if row not in allCV:
                allCV.append(row)
                
        for cv in allCV:
            splitString1 = cv[0].partition(",")
            vert =  splitString1[0]
            splitString2 = splitString1[2].partition(",")
            joint = splitString2[0]
            value = float(splitString2[2])
        
            
            if cmds.objExists(joint):
                cmds.skinPercent( skCl, vert, transformValue=[(joint, value)])
            else:
                missingJoints.append(joint)
                
        """ Normalize the weights """
        cmds.skinPercent(skCl, normalize=True)
        
        if len(missingJoints) == 0:  
            cmds.headsUpMessage("The weight has been loaded from " + finalPath)
        else:
            cmds.headsUpMessage("Influences are missing.  Please view the script editor for details.")
            print "These influences do not exist"
            for joint in missingJoints:
                print joint
    def doIt(self,argList):
        polygon = cmds.filterExpand(sm=12)
        if polygon:
            if len(polygon) > 1:
                print 'Please select only one polygon to import.'
                return
            else:
                polygon = polygon[0];
        else:
            print 'Please select a polygon.'
            return

        related_cluster = mel.eval('findRelatedSkinCluster '+polygon)
        if related_cluster == '':
            print 'Please bind skin for this polygon.'
            return;

        paths = cmds.fileDialog2(dialogStyle=2, fileMode = 4, okCaption = "Load", cancelCaption = "Cancel")
        if not paths:
            return;

        for p in range(0, len(paths)):
            path = paths[p]
            joints = cmds.skinPercent(related_cluster, polygon+'.vtx[0]', q = True, t = None);
            f = open(path, 'r')

            vertices = cmds.getAttr(polygon+'.vrts', multiIndices = True)
            while 1:
                line = f.readline()
                if not line:
                    break

                line = line[:-1]
                parts = line.split(' ')
                if parts[0] != 'vp':
                    break
                weights = f.readline()[:-1].split(' ')
                if weights[0] != 'vinf':
                    break

                pos = [float(parts[1]), float(parts[2]), float(parts[3])]
                index = -1
                for i in range(0, len(vertices)):
                    ver = cmds.xform(polygon+'.vtx['+str(vertices[i])+']', q=1, ws=1, t=1)
                    dist = math.sqrt((pos[0]-ver[0])*(pos[0]-ver[0]) + (pos[1]-ver[1])*(pos[1]-ver[1]) + (pos[2]-ver[2])*(pos[2]-ver[2]))
                    if dist < 0.0001:
                        index = i

                        transformValue = []
                        for j in range(1, len(weights), 2):
                            transformValue.append((weights[j], float(weights[j+1]) ))
                        cmds.skinPercent(related_cluster, polygon+'.vtx['+str(vertices[index])+']', transformValue=transformValue)
                        cmds.skinPercent(related_cluster, polygon+'.vtx['+str(vertices[index])+']', normalize=True)

            f.close()
        print 'Import Complete.'
Exemplo n.º 19
0
 def weightFullFn(self):
     if self.currentInf:
         num = len(self.currentInf)
     if num == 1:
         cmds.skinPercent(self.currentSkin, self.currentVerts, tv=[self.currentInf[0], 1.0])
     elif num > 1:
         if self.currentNormalization != 'None':
             cmds.warning('skinWrangler: Cannot skin more than two influences to 1.0 in a normalization mode')
             return None
     self.refreshUI()
Exemplo n.º 20
0
def pasteWeights(showProgress=True):
    """
    @param showProgress: Show operation progress using the main progress bar
    @type showProgress: bool
    """
    # Global Weight Value
    wt = gl_globals.glCopyPasteWeightCmd

    # Get Component Selection
    sel = cmds.filterExpand(ex=True, sm=[28, 31, 46])
    if not sel: return

    # Begin Progress Bar
    gMainProgressBar = mel.eval('$tmp = $gMainProgressBar')
    if showProgress:
        cmds.progressBar(gMainProgressBar, e=True, bp=True, ii=True, status=('Pasting Skin Weights...'),
                       maxValue=len(sel))

    selComp = glTools.utils.selection.componentListByObject(sel)
    for objComp in selComp:

        # Get Object from Component
        geo = cmds.ls(objComp[0], o=True)[0]

        # Get SkinCluster from Geometry
        skin = glTools.utils.skinCluster.findRelatedSkinCluster(geo)
        if not skin: raise Exception('Geometry "' + geo + '" is not attached to a valid skinCluster!')
        # Disable Weight Normalization
        cmds.setAttr(skin + '.normalizeWeights', 0)

        # For Each Component
        for cv in objComp:

            # Update skinPercent Command
            cmd = wt.replace('###', skin)

            # Evaluate skinPercent Command
            try:
                mel.eval(cmd)
            # print(cmd)
            except Exception, e:
                if showProgress: cmds.progressBar(gMainProgressBar, e=True, endProgress=True)
                raise Exception(str(s))

            # Update Progress Bar
            cvLen = len(cmds.ls(cv, fl=True))
            if showProgress:
                if cmds.progressBar(gMainProgressBar, q=True, isCancelled=True):
                    cmds.progressBar(gMainProgressBar, e=True, endProgress=True)
                    raise UserInterupted('Operation cancelled by user!')
                cmds.progressBar(gMainProgressBar, e=True, step=cvLen)

        # Normalize Weights
        cmds.setAttr(skin + '.normalizeWeights', 1)
        cmds.skinPercent(skin, normalize=True)
Exemplo n.º 21
0
def OldSkooFaceRigWeightExportCMD(OldSkooObj):
    # Interate through each CV on the faceDriver_Crv
    for cv in OldSkooObj.cvList:
        infLst = cmds.skinPercent(OldSkooObj.skinCluster, cv.name, ib=1e-4, query=True, transform=None)
        wgtLst = cmds.skinPercent(OldSkooObj.skinCluster, cv.name, ib=1e-4, query=True, v=True)
        closestPoint = getMapPnt(OldSkooObj.microList, cv)
        # Some debugging info
        # if OldSkooObj.influenceInfoDict.has_key(closestPoint[0]):
        #    print 'Key Exists %s, for %s, %s' %( closestPoint[0], cv.name,closestPoint[1])
        #    print infLst, wgtLst
        OldSkooObj.influenceInfoDict[closestPoint[0]] = [infLst, wgtLst]
Exemplo n.º 22
0
 def getVtxWeightRatio(self):
     jnt01 = cmds.textField('jointA',q = True,text = True)
     jnt02 = cmds.textField('jointB',q = True,text = True)
     vert  = cmds.ls(sl = True)[0]
     model = vert.split('.')[0]
     print vert,model
     skin = mel.eval("findRelatedSkinCluster" +"(\""+ model+"\")")
     jnt01weight = cmds.skinPercent(skin,vert,t=jnt01,q=True)
     jnt02weight = cmds.skinPercent(skin,vert,t=jnt02,q=True)
     VtxWeightRatio = jnt01weight/(jnt01weight + jnt02weight)
     self.editValue(VtxWeightRatio)
Exemplo n.º 23
0
def modify_weights(num):

    stored_joints = [cmds.textField('joint_disp_0', q=True, tx=True), cmds.textField('joint_disp_1', q=True, tx=True)]
    stored_joints = filter(None, stored_joints)
    selected_verts = cmds.filterExpand(sm=31)
    skincluster = get_skinCluster(stored_joints)

    if len(stored_joints) == 1:
        cmds.skinPercent(skincluster, tv=(stored_joints[0], num), r=True)
    
    else:
        cmds.skinPercent(skincluster, tv=[(stored_joints[0],- num), (stored_joints[1], num)], r=True)
Exemplo n.º 24
0
	def pull( self , arg=None ) :
		
		# Info
		srch = mc.textField( '%sSrchTF'%self.ui , q=True , tx=True )
		rep = mc.textField( '%sRepTF'%self.ui , q=True , tx=True )
		mult = mc.floatField( '%sMultFF'%self.ui , q=True , v=True )
		
		sels = mc.ls( sl=True , fl=True )
		
		# Collect all skin cluster nodes as a dict
		skns = []
		sknDct = {}
		
		for sel in sels :
			skn = mm.eval( 'findRelatedSkinCluster %s' % sel.split( '.' )[0] )
			sknDct[ sel ] = skn
			
			if not skn in skns :
				skns.append( skn )
		
		# Disable normalize weight for all skin cluster nodes
		for skn in skns :
			if mc.getAttr( '%s.normalizeWeights' % skn ) :
				mc.setAttr( '%s.normalizeWeights' % skn , 0 )
		
		# Iterate through selected points
		for sel in sels :
			
			skn = sknDct[sel]
			infs = mc.skinCluster( skn , q=True , inf=True )
			wghtVals = mc.skinPercent( skn , sel , q=True , v=True )
			
			# Iterate through all influence nodes
			for ix in range( len( infs ) ) :
				
				# If keyword is found in the current influence node
				if srch in infs[ix] :
					
					pullVal = wghtVals[ix] * mult
					srcVal = wghtVals[ix] - pullVal
					repInf = infs[ix].replace( srch , rep )
					
					# If replaced influence is member of object's influences
					if repInf in infs :
						mc.skinPercent( skn , sel , transformValue=[ ( infs[ix] , srcVal ) ,
							( repInf , pullVal ) ] )
					else :
						print '%s has no %s as its influence' % ( skn , repInf )
		
		# Enable normalize weights
		for skn in skns :
			if not mc.getAttr( '%s.normalizeWeights' % skn ) :
				mc.setAttr( '%s.normalizeWeights' % skn , 1 )
Exemplo n.º 25
0
    def mulObjWeights(self):
        sourceMeshs = rig.textScrollList(self.skinTV, q=True, si=True)
        sourceJointIndexs = rig.textScrollList(self.jointTV, q=True, sii=True)
        targetMeshs = rig.textScrollList(self.slSkinTV, q=True, si=True)
        targetJointNames = rig.treeView(self.slJointTV, q=True, si=True)

        if targetMeshs and sourceMeshs and targetJointNames and sourceJointIndexs:
            sourceMeshIndexs = rig.textScrollList(self.skinTV,
                                                  q=True,
                                                  sii=True)
            mainIndex = sourceMeshIndexs[0] - 1

            skin = SK_getSkinCluster(targetMeshs)  #获得SkinCluster
            infs = rig.treeView(self.slJointTV, q=True, si=True)  #获得目标物体的影响体

            sourData = self.allData[mainIndex][1]  #获得权重数据

            if len(rig.ls(targetMeshs[0] + '.vtx[*]',
                          fl=True)) == len(sourData):
                if len(sourceJointIndexs) == len(infs):

                    lockInfs = self.getLockInfs(infs)  #解锁

                    rig.progressBar(self.infsPB,
                                    e=True,
                                    maxValue=len(infs),
                                    vis=True)  #显示进度条

                    for num, jnt in enumerate(infs):  #迭代选择影响体
                        if not ('NONE_JOINT_X' in jnt):  #骨骼是否被忽略
                            Index = sourceJointIndexs[num] - 1
                            print 'complele:' + jnt
                            for i, data in enumerate(sourData):  #迭代所有的点

                                rig.skinPercent(
                                    skin,
                                    targetMeshs[0] + '.vtx[' + str(i) + ']',
                                    transformValue=[(jnt, data[Index])])
                            rig.setAttr(jnt + '.liw', 1)  #锁定已完成的影响体
                            rig.progressBar(self.infsPB, edit=True,
                                            step=1)  #设置进度条
                        else:
                            print u'忽略.......' + jnt

                    self.setUnLockInfs(lockInfs)
                    rig.progressBar(self.infsPB, e=True, vis=False)  #隐藏进度条
                else:
                    SM_warning(u'选择的影响体个数不一样')
            else:
                SM_warning(u'物体拓扑不一样,请选择正确的物体')

        else:
            SM_warning(u'请确定已经正确的选择')
Exemplo n.º 26
0
def performSkinning(fakeInput, argList):

    [
        meshList, boxList, vertList, globalArmJntList, globalMeshList,
        globalSkinClusterDict, globalRootJnt
    ] = argList
    infVertList = []

    # get verts into the list
    getVertsFromMesh(globalMeshList, vertList)

    # add each joint to influence
    for index in xrange(len(boxList)):
        box = boxList[index]
        box.updateMath()

        jnt = globalArmJntList[index]

        # for each skincluster, add them one by one
        if jnt != globalRootJnt:
            for mesh in globalSkinClusterDict:
                cmds.skinCluster(globalSkinClusterDict[mesh],
                                 edit=True,
                                 addInfluence=jnt,
                                 weight=0)

    # calculate weight for each vertex
    for vert in vertList:
        mesh = polyToTrans(vert)
        infJntList = []
        vertPosition = cmds.xform(vert,
                                  query=True,
                                  translation=True,
                                  worldSpace=True)
        for index in xrange(len(boxList)):
            box = boxList[index]
            if box.insideBox(vertPosition):
                infJntList += [globalArmJntList[index]]

        # if the vert is assigned to some joint
        if infJntList != []:
            weight = 1.0 / len(infJntList)

            # zip joint with skin weight
            jntWeightList = []
            for jnt in infJntList:
                jntWeightList += [(jnt, weight)]

            # set skin weight for the vertex
            cmds.skinPercent(globalSkinClusterDict[mesh],
                             vert,
                             transformValue=jntWeightList)
Exemplo n.º 27
0
def averageVertWeights (targetVerts, *args, **kwargs):
    targetVerts = cmds.ls(targetVerts, flatten=True)
    allWeights = {}
    for targetVert in targetVerts:
        skinCluster = getSkinFromVert(targetVert)
        if not skinCluster in allWeights:
            allWeights[skinCluster] = {}
        averageWeights = getAverageVertWeights(targetVert, *args, **kwargs)
        allWeights[skinCluster][targetVert] = averageWeights
    for skinCluster, allWeights in allWeights.items():
        for targetVert, weights in allWeights.items():
            cmds.skinPercent(skinCluster, targetVert, normalize=False,
                    zeroRemainingInfluences=False, transformValue=weights)
Exemplo n.º 28
0
 def skinPolyShells(self, mesh, skin):
     # floods each shell with it's avg vtx weight
     try:
         cmds.undoInfo(openChunk=True)
         for shell in self.getPolyShells(mesh):
             facesNice = [mesh + '.f[' + str(f) + ']' for f in shell]
             aw = self.getAvgVertWeights(facesNice, skin)
             tvTuples = self.vDictToTv(aw)
             cmds.skinPercent(skin, facesNice, tv=tvTuples)
     except Exception as e:
         print e
     finally:
         cmds.undoInfo(closeChunk=True)
Exemplo n.º 29
0
 def minusWeightFn(self):
     try:
         cmds.undoInfo(openChunk=True)
         val = -self.setWeightSpin.value()
         if self.currentInf:
             for inf in self.currentInf:
                 cmds.skinPercent(self.currentSkin, self.currentVerts, tv=[inf, val], r=1)
         else: cmds.warning('[skinWrangler] No influences/joints selected')
         self.refreshUI()
     except Exception as e:
         print e
     finally:
         cmds.undoInfo(closeChunk=True)
Exemplo n.º 30
0
def setAllSkinWeightsToZero(skin):
	mesh = cmds.listConnections('{}.outputGeometry'.format(skin))[0]
	maxAttr = '{}.maintainMaxInfluences'.format(skin)
	normalAttr = '{}.normalizeWeights'.format(skin)

	if cmds.getAttr(maxAttr) == 1:
		cmds.setAttr(maxAttr, 0)

	cmds.setAttr(normalAttr, 0)

	cmds.skinPercent(skin, mesh, prw=100.0, nrm=False)
	cmds.setAttr(normalAttr, 1)
	return
Exemplo n.º 31
0
def yankWireToSkinCluster():
    base = 'pCylinder1_noDeformation'
    target = 'pCylinder1_wireDeformed'
    sc = 'skinCluster2'

    for joint in mc.ls('joint?'):
        mc.move(1, 0, 0, joint, r=1)
        deltas = rigrepo.libs.shape.getDeltas(base, target)
        mc.move(-1, 0, 0, joint, r=1)
        rigrepo.libs.weights.setWeights(sc, deltas, mapList=joint)

    mc.skinPercent(sc, mc.deformer(sc, q=1, geometry=1)[0],
                   normalize=1)  # in case of floating point precision
    def bind_skin(self):
        skin_cluster = mc.skinCluster(self.root, self.combined_node, maximumInfluences=1)[0]

        vertex_index = 0
        for node in self.joint_nodes:
            # print node.Joint
            # print vertex_index, vertex_index + node.Vertex_count - 1
            mc.select('%s.vtx[%i: %i]' % (self.combined_node, vertex_index, vertex_index + node.Vertex_count - 1))
            mc.skinPercent(skin_cluster, transformValue=[(node.Joint, 1)])

            vertex_index += node.Vertex_count

        mc.select(cl=True)
Exemplo n.º 33
0
 def skinPolyShells(self, mesh, skin):
     # floods each shell with it's avg vtx weight
     try:
         cmds.undoInfo(openChunk=True)
         for shell in self.getPolyShells(mesh):
             facesNice = [mesh + '.f[' + str(f) + ']' for f in shell]
             aw = self.getAvgVertWeights(facesNice, skin)
             tvTuples = self.vDictToTv(aw)
             cmds.skinPercent(skin, facesNice, tv=tvTuples)
     except Exception as e:
         print e
     finally:
         cmds.undoInfo(closeChunk=True)
Exemplo n.º 34
0
def soft_selection_to_joint(*args):
    """
    takes a soft selection of verts and creates a joint to bind & wieght them in that proportion
    :param args:
    :return: string - name of the soft sel joint we've created
    """
    # TODO - check for selection of verts!
    selVtx = cmds.ls(sl=True, fl=True)  # to get center for joint
    vtxs, wts = rig.get_soft_selection()  # to get weights for jnt

    tform = vtxs[0].partition(".")[0]
    mesh = cmds.listRelatives(tform, s=True)[0]
    ptOnSurface = cmds.checkBoxGrp(widgets["jntCPOMCBG"], q=True, v1=True)
    auto = cmds.checkBoxGrp(widgets["jntAutoCBG"], q=True, v1=True)
    jntName = cmds.textFieldGrp(widgets["jntNameTFG"], q=True, tx=True)
    rotOnSurface = cmds.checkBoxGrp(widgets["jntRotCBG"], q=True, v1=True)

    cls = mel.eval("findRelatedSkinCluster " + tform)
    if not cls:
        if auto:
            baseJnt, cls = rig.new_joint_bind_at_center(tform)
        else:
            cmds.warning(
                "There isn't an initial bind on this geometry. Either create one or check 'auto'"
            )
            return ()

    center = rig.average_point_positions(selVtx)
    rot = (0, 0, 0)
    if ptOnSurface:
        center = rig.closest_pt_on_mesh_position(center, mesh)
    if rotOnSurface:
        rot = rig.closest_pt_on_mesh_rotation(center, mesh)

    cmds.select(cl=True)
    jnt = cmds.joint(name=jntName)
    cmds.xform(jnt, ws=True, t=center)
    cmds.xform(jnt, ws=True, ro=rot)

    # add influence to skin Cluster
    cmds.select(tform, r=True)
    cmds.skinCluster(e=True, ai=jnt, wt=0)

    # apply weights to that joint
    for v in range(len(vtxs)):
        cmds.skinPercent(cls, vtxs[v], transformValue=[jnt, wts[v]])

    newName = rig.increment_name(jntName)
    cmds.textFieldGrp(widgets["jntNameTFG"], tx=newName, e=True)

    return (jnt)
Exemplo n.º 35
0
 def paint_skin_Weights(self,jnt01,jnt02,paint_operation,weight_value):
     verts1 = cmds.ls(sl = True,fl = True)
     verts = []
     for vert in verts1:
         if '.' in vert:
             verts.append(vert)
     if cmds.objExists(jnt01) != True:
         exit(jnt01 + ' ------ is not exists')
     if cmds.objExists(jnt02) != True:
         exit(jnt02 + ' ------ is not exists')
     model = verts[0].split('.')[0]
     skin = mel.eval("findRelatedSkinCluster" +"(\""+ model+"\")")
     skin_jnts = cmds.skinCluster(skin,q=True,inf = skin)
     for jnt in skin_jnts:
         cmds.setAttr(jnt + '.liw',1)
     cmds.setAttr(jnt01 + '.liw',0)
     cmds.setAttr(jnt02 + '.liw',0)
     if paint_operation == 'Replace':
         cmds.skinPercent(skin,verts,tv = [(jnt02,0)])
     elif paint_operation =='Add':
         pass
     for vert in verts:
         jnt01weight = cmds.skinPercent(skin,vert,t=jnt01,q=True)
         jnt02weight = cmds.skinPercent(skin,vert,t=jnt02,q=True)
         if paint_operation == 'Replace':
             weight = jnt01weight * (1.0-weight_value)
             cmds.skinPercent(skin,vert,tv = [(jnt02,weight)])
         if paint_operation == 'Add':
             jnt01weight = jnt01weight + jnt02weight * weight_value
             cmds.skinPercent(skin,vert,tv = [(jnt01,jnt01weight)])
Exemplo n.º 36
0
def getVertexWeights(vertexList=[], skinCluster="", thresholdValue=0.001):
    if len(vertexList) != 0 and skinCluster != "":
        verticeDict = {}

        for vtx in vertexList:
            influenceVals = cmds.skinPercent(skinCluster, vtx, q=1, v=1, ib=thresholdValue)

            influenceNames = cmds.skinPercent(skinCluster, vtx, transform=None, q=1, ib=thresholdValue)

            verticeDict[vtx] = zip(influenceNames, influenceVals)

        return verticeDict
    else:
        cmds.error("No Vertices or SkinCluster passed.")
Exemplo n.º 37
0
def controlSurfaceSmoothWeights(surface):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Early version of a weight smoother for a

    ARGUMENTS:
    surface(string)

    RETURNS:
    Nada
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    cvList = (mc.ls ([surface+'.cv[*][*]'],flatten=True))
    print cvList
    skinCluster = querySkinCluster (surface)
    influenceObjects = queryInfluences (skinCluster)
    print influenceObjects
    #find the closest influence object to the start
    startObject =  (distance.returnClosestObjToCV (cvList[0], influenceObjects))
    print startObject
    #find the closest influence object to the end
    endObject = (distance.returnClosestObjToCV (cvList[-1], influenceObjects))
    print endObject
    #getting the last cv list number
    cvChainLength =  ((len(cvList)-1)/2)
    #set the skin weights for the top and bottom
    mc.skinPercent (skinCluster,(surface+'.cv[0:1][0:1]'), tv = [startObject,1])
    mc.skinPercent (skinCluster,('%s%s%i%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-1),':',cvChainLength,']')), tv = [endObject,1])
    #Blend in the nearest row to the start and end
    mc.skinPercent (skinCluster,(surface+'.cv[0:1][2]'), tv = [startObject,.4])
    mc.skinPercent (skinCluster,('%s%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-1),']')), tv = [endObject,.4])
Exemplo n.º 38
0
def exportSkinweight(oneMesh):
    '''export a skinweight json to exactly where the maya file saves with selected geo name
       a saved file needed for this func
    '''
    t0 = time.time()

    shapeTfm = oneMesh
    shapeTfmPy = pm.PyNode(oneMesh)
    shape = str(shapeTfmPy.getShape())
    skClst = pm.mel.findRelatedSkinCluster(shapeTfm)
    if not skClst:
        raise Exception('no skincluster found')

    jntList = [
        str(jnt) for jnt in mc.skinCluster(skClst, query=True, inf=True)
    ]

    vCount = int(mc.polyEvaluate(shapeTfm, vertex=True))
    vrts = (shape + ".vtx[0:" + str((vCount - 1)) + "]")
    allVrts = mc.ls(vrts, flatten=True)

    saveFileCheck()

    mayaProjCWD = os.path.split(pm.mel.file(q=True, l=True)[0])[0]
    fileName = shapeTfm + "_skinweights" + '.sw'

    fullPathName = mayaProjCWD + "//" + fileName

    jntWeightDict = {}
    for vert in allVrts:
        infJntList = [
            jnt
            for jnt in mc.skinPercent(skClst, vert, query=True, transform=None)
        ]
        infSkWtList = mc.skinPercent(skClst,
                                     vert,
                                     q=True,
                                     v=True,
                                     ib=0.000000001)
        jntWeightDict[str(vert)] = dict(zip(infJntList, infSkWtList))

    jntWeightDict['maxInf'] = mc.skinCluster(skClst, q=True, mi=True)

    with open(fullPathName, 'wb') as outfile:
        pickle.dump(jntWeightDict, outfile)

    t1 = time.time()
    print t1 - t0
    sys.stdout.write('{}skinweight exported!\n'.format(shapeTfm))
    return fullPathName
Exemplo n.º 39
0
def controlSurfaceSmoothWeights(surface):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Early version of a weight smoother for a

    ARGUMENTS:
    surface(string)

    RETURNS:
    Nada
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    cvList = (mc.ls ([surface+'.cv[*][*]'],flatten=True))
    print cvList
    skinCluster = querySkinCluster (surface)
    influenceObjects = queryInfluences (skinCluster)
    print influenceObjects
    #find the closest influence object to the start
    startObject =  (distance.returnClosestObjToCV (cvList[0], influenceObjects))
    print startObject
    #find the closest influence object to the end
    endObject = (distance.returnClosestObjToCV (cvList[-1], influenceObjects))
    print endObject
    #getting the last cv list number
    cvChainLength =  ((len(cvList)-1)/2)
    #set the skin weights for the top and bottom
    mc.skinPercent (skinCluster,(surface+'.cv[0:1][0:1]'), tv = [startObject,1])
    mc.skinPercent (skinCluster,('%s%s%i%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-1),':',cvChainLength,']')), tv = [endObject,1])
    #Blend in the nearest row to the start and end
    mc.skinPercent (skinCluster,(surface+'.cv[0:1][2]'), tv = [startObject,.4])
    mc.skinPercent (skinCluster,('%s%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-1),']')), tv = [endObject,.4])
Exemplo n.º 40
0
    def __init__(self, parent, vertex):
        ui.QWidget.__init__(self, parent)

        # variables
        self.vertex = vertex
        self.mesh, _ = vertex.split(".", 1)
        self.skinCluster = utils.getSkinCluster(self.mesh)

        # get skinned data
        influences = cmds.skinPercent(self.skinCluster,
                                      vertex,
                                      query=True,
                                      transform=None)

        values = cmds.skinPercent(self.skinCluster,
                                  vertex,
                                  query=True,
                                  value=True)

        # order data
        data = zip(values, influences)
        data.sort()
        data.reverse()

        # create layout
        layout = ui.QVBoxLayout(self)
        layout.setContentsMargins(3, 3, 3, 3)
        layout.setSpacing(3)

        # create divider
        ui.addDivider(self, layout)

        # create label
        self.label = VertexLabelWidget(self, vertex)
        layout.addWidget(self.label)

        # create divider
        ui.addDivider(self, layout)

        # create frame
        self.frame = VertexInfluencesWidget(self, self.skinCluster, data)
        self.frame.signal.connect(self.setWeights)
        layout.addWidget(self.frame)

        # connect influences toggle
        self.label.signal.connect(self.frame.displayInfluences)
        self.frame.warningSignal.connect(self.label.displayWarning)

        # force display
        self.frame.displayMaxInfluences()
Exemplo n.º 41
0
 def click(s):
     try:
         # Grab mouse co-ords on screen
         viewX, viewY, viewZ = cmds.draggerContext(s.myTool,
                                                   q=True,
                                                   ap=True)
         position = om.MPoint()
         direction = om.MVector()
         # Convert 2D screen positions into 3D world positions
         omui.M3dView().active3dView().viewToWorld(int(viewX), int(viewY),
                                                   position, direction)
         sel = om.MSelectionList()
         sel.add(s.sel)
         dagPath = sel.getDagPath(0)
         fnMesh = om.MFnMesh(dagPath)
         intersection = fnMesh.closestIntersection(
             om.MFloatPoint(position), om.MFloatVector(direction),
             om.MSpace.kWorld, 99999, False)
         # Did our ray intersect with the object?
         if intersection:
             hitPoint, hitRayParam, hitFace, hitTriangle, hitBary1, hitBary2 = intersection
             if hitTriangle != -1:
                 # Grab Skin Cluster
                 skin = mel.eval("findRelatedSkinCluster %s" % s.sel)
                 if skin:
                     # Get Face points
                     cmds.select("%s.f[%s]" % (s.sel, hitFace))
                     face = cmds.polyInfo(fv=True)
                     # Get vertexes
                     verts = [
                         "%s.vtx[%s]" % (s.sel, v)
                         for v in findall(r"\s(\d+)\s", face[0])
                     ]
                     # Get Joints
                     cmds.select(verts, r=True)
                     joints = cmds.skinPercent(skin, q=True, t=None)
                     # Get weights
                     weights = sorted(
                         [(j, cmds.skinPercent(skin, t=j, q=True))
                          for j in joints],
                         key=lambda x: x[1],
                         reverse=True)
                     cmds.select(weights[0][0], r=True)
                 else:
                     print "No skin found"
         # Return to previous tool
         cmds.setToolTo(s.tool)
         cmds.refresh()
     except RuntimeError:
         print "There was an issue selecting the object."
Exemplo n.º 42
0
def setWeight(vtx, weightLs):
    oldWeightLs = []
    oldWeightSum = 0
    jntLs = cmds.skinPercent("skinCluster18", vtx, query=True, transform=None)
    valueLs = cmds.skinPercent("skinCluster18", vtx, query=True, value=True)
    for jnt in toJntLs:
        oldWeightSum += crtWeight
    weightLs[-1] = oldWeightSum - sum(weightLs[:-1])
    for i in xrange(len(fromJntLs)):
        valueLs[indexLs[i]] = weightLs[i]
    tvLs = []
    for i in xrange(len(valueLs)):
        tvLs += [(jntLs[i], valueLs[i])]
    cmds.skinPercent("skinCluster18", vtx, transformValue=tvLs)
Exemplo n.º 43
0
 def weightHalfFn(self):
     if self.currentInf:
         num = len(self.currentInf)
         if num == 1:
             cmds.skinPercent(self.currentSkin,
                              self.currentVerts,
                              tv=[str(self.currentInf[0]), 0.5])
         elif num == 2:
             cmds.skinPercent(self.currentSkin,
                              self.currentVerts,
                              tv=[str(self.currentInf[0]), 1.0])
             cmds.skinPercent(self.currentSkin,
                              self.currentVerts,
                              tv=[str(self.currentInf[1]), 0.5])
         elif num > 2:
             if self.currentNormalization != 'None':
                 cmds.warning(
                     'skinWrangler: Cannot skin more than two influences to 0.5 in a normalization mode'
                 )
                 return None
             else:
                 for inf in self.currentInf:
                     cmds.skinPercent(self.currentSkin,
                                      self.currentVerts,
                                      tv=[inf, 0.5])
         self.refreshUI()
 def LaodWeight(self, Unuse):
     FileFullpath = mc.fileDialog2(fm=1, ff=("JSON Files (*.json)"))
     if FileFullpath == None:return
     
     f = open(FileFullpath[0], mode='r')
     fileDt = json.load(f)
     f.close()
     
     latice = mc.ls(sl=True)
     skinNode = mel.eval('findRelatedSkinCluster ' + latice[0])
     for pt, Weilist in fileDt['weightList'].iteritems():
         mc.skinPercent(skinNode, '%s.%s'%(latice[0], pt), tv=zip(fileDt['skinJoints'], Weilist))
     
     print '#   Result:   weight Read Final! ',    
Exemplo n.º 45
0
 def weightFullFn(self):
     if self.currentInf:
         num = len(self.currentInf)
     if num == 1:
         cmds.skinPercent(self.currentSkin,
                          self.currentVerts,
                          tv=[self.currentInf[0], 1.0])
     elif num > 1:
         if self.currentNormalization != 'None':
             cmds.warning(
                 'skinWrangler: Cannot skin more than two influences to 1.0 in a normalization mode'
             )
             return None
     self.refreshUI()
Exemplo n.º 46
0
Arquivo: main.py Projeto: mappp7/tools
    def updateBothFunc(self ):
        self.ui.inprogress_PGB.reset()
        
        iterations = self.ui.initIteration_SPB.value()
        sparseness = self.ui.maxInfluence_SPB.value()
        maxIterations = self.ui.updateIteration_SPB.value()
        
        if self.mode == 1:
            num_bones = len(self.boneList)
            W, bone_transforms, rest_bones_t ,finalBone = self.MTSC(self.poses, self.rest_pose ,num_bones ,iterations , maxIterations , sparseness ,self.mesh ,self.boneList)
        else:
            num_bones = self.ui.boneNum_SPB.value()
            W, bone_transforms, rest_bones_t ,finalBone = self.MTSC(self.poses, self.rest_pose , num_bones ,iterations ,maxIterations ,sparseness)
     
        if not finalBone:
            for x in rest_bones_t:
                    cmds.select(cl=1)
                    j = cmds.joint()
                    cmds.xform(j , t = x)
                    finalBone.append(j)
            for y in finalBone:
                cmds.select(y , add=1)                 
            cmds.skinCluster(finalBone , self.mesh , tsb = 1)    

            self.skincluster = mel.eval('findRelatedSkinCluster("%s")'%self.mesh)

        tvdict = {}
        preX = None
        for x in range(len(W)):
            listClear = []
            for i,na in enumerate(finalBone):
                tp = (na,W[x][i])
                listClear.append(tp)
            preX = x
            tvdict[preX] = listClear

        for x in range(len(W)): 
            cmds.skinPercent(self.skincluster , '{name}.vtx[{num}]'.format(name = self.mesh , num = x) , transformValue = tvdict[x] )
        
        if self.status == 0:
            for pn in range(self.min_ , self.max_ + 1):
                cmds.currentTime(pn)
                for i,na in enumerate(finalBone):
                    rotation = self.euler_angles_from_rotation_matrix(bone_transforms[i][pn][:3,:])
                    trans = bone_transforms[i][pn][3,:]
                    cmds.xform(na , t = trans , ro = rotation)
                
                cmds.select(finalBone)
                cmds.setKeyframe()
Exemplo n.º 47
0
 def setWeightFn(self):
     if self.currentInf:
         if len(self.currentInf) > 1:
             cmds.warning(
                 'skinWrangler: Set Weight does not work with multi-selection because I am too lazy at the moment to write my own normalization code.'
             )
         else:
             cmds.skinPercent(
                 self.currentSkin,
                 self.currentVerts,
                 tv=[self.currentInf[0],
                     self.setWeightSpin.value()])
         self.refreshUI()
     else:
         cmds.warning('[skinWrangler] No influences/joints selected')
Exemplo n.º 48
0
def returnExcessInfluenceVerts(mesh, maxInfluences):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for finding vertices that are over X influences

    ARGUMENTS:
    mesh(string)
    maxInfluences(int)

    RETURNS:
    badVertices(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    skinCluster = querySkinCluster(mesh)
    vertices = (mc.ls([mesh + '.vtx[*]'], flatten=True))

    badVertices = []

    if mayaVersion >= 2011:
        #Find the bad verts
        for v in range(len(vertices)):
            currentVert = ('%s%s%s%s' % (mesh, '.vtx[', v, ']'))
            influenceList = mc.skinPercent(skinCluster,
                                           currentVert,
                                           query=True,
                                           transform=None)
            if len(influenceList) > maxInfluences:
                badVertices.append(currentVert)
        return badVertices
    else:
        guiFactory.warning('Old Maya Version Mode')
        #Find the bad verts
        for v in vertexList:
            rawInfluenceList = mc.skinPercent(skinCluster,
                                              v,
                                              query=True,
                                              transform=None)
            valuesList = mc.skinPercent(skinCluster, v, query=True, value=True)
            cnt = 0
            influenceList = []
            for obj in rawInfluenceList:
                if valuesList[cnt] > 0:
                    influenceList.append(obj)
                cnt += 1
            if len(influenceList) > maxInfluences:
                badVertices.append(v)
        return badVertices
Exemplo n.º 49
0
def loadInfo(info_name, geo_name):
    f_info = open(info_name,'r')
    joint_pos = {}
    joint_hier = {}
    joint_skin = []
    for line in f_info:
        word = line.split()
        if word[0] == 'joints':
            joint_pos[word[1]] = [float(word[2]),  float(word[3]), float(word[4])]
        if word[0] == 'root':
            root_pos = joint_pos[word[1]]
            root_name = word[1]
            cmds.joint(p=(root_pos[0], root_pos[1],root_pos[2]), name = root_name)
        if word[0] == 'hier':
            if word[1] not in joint_hier.keys():
                joint_hier[word[1]] = [word[2]]
            else:
                joint_hier[word[1]].append(word[2])
        if word[0] == 'skin':
            skin_item = word[1:]
            joint_skin.append(skin_item)
    f_info.close()
    
    this_level = [root_name]
    while this_level:
        next_level = []
        for p_node in this_level:
            if p_node in joint_hier.keys():
                for c_node in joint_hier[p_node]:
                    cmds.select(p_node, r=True)
                    child_pos = joint_pos[c_node]
                    cmds.joint(p=(child_pos[0], child_pos[1],child_pos[2]), name = c_node)
                    next_level.append(c_node)
        this_level = next_level         
    cmds.joint(root_name, e=True, oj='xyz', sao='yup', ch=True, zso=True)
    cmds.skinCluster( root_name, geo_name)
    #print len(joint_skin)
    for i in range(len(joint_skin)):
        vtx_name = geo_name + '.vtx['+joint_skin[i][0]+']'
        transValue = []
        for j in range(1,len(joint_skin[i]),2):
            transValue_item = (joint_skin[i][j], float(joint_skin[i][j+1]))
            transValue.append(transValue_item) 
        # print vtx_name, transValue

        cmds.skinPercent( 'skinCluster1', vtx_name, transformValue=transValue)
    cmds.skinPercent( 'skinCluster1', geo_name, pruneWeights=0.01, normalize=False )
    return root_name, joint_pos
Exemplo n.º 50
0
def getInfluencingJoints(skinCluster, vertex):
    jointList = cmds.skinPercent(skinCluster,
                                 vertex,
                                 query=True,
                                 ignoreBelow=0.001,
                                 transform=None)
    resultList = []
    for i in xrange(len(jointList)):
        resultList += [[
            jointList[i],
            cmds.skinPercent(skinCluster,
                             vertex,
                             query=True,
                             transform=jointList[i])
        ]]
    return resultList
Exemplo n.º 51
0
def getInfluenceWeightsSlow(skinCluster,influence,componentList=[]):
	'''
	Return the weights of an influence for a specified skinCluster
	@param skinCluster: SkinCluster to query influence weights from
	@type skinCluster: str
	@param influence: Influence to query weights from
	@type influence: str
	@param componentList: List of components to query weights for
	@type componentList: list
	'''
	# Verify skinCluster
	if not isSkinCluster(skinCluster):
		raise Exception('Invalid skinCluster "' + skinCluster + '" specified!')
	
	# Check influence
	if not mc.objExists(influence):
		raise Exception('Influence object "'+influence+'" does not exists!')
	
	# Get geometry
	affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster).keys()[0]
	
	# Check component list
	if not componentList: componentList = glTools.utils.component.getComponentStrList(affectedGeo)
	componentIndexList = glTools.utils.component.getComponentIndexList(componentList)
	componentIndexList = componentIndexList[componentIndexList.keys()[0]]
	
	# Get weight values
	weightList = [mc.skinPercent(skinCluster,affectedGeo+'.vtx['+str(i)+']',transform=influence,q=True) for i in componentIndexList]
	
	# Return weight array
	return weightList
Exemplo n.º 52
0
def exportWeightsData(shape, skinCluster):
    '''
	Return the weight data for the given shape, skinCluster
	'''
    print 'exportWeightsData ' + str(shape) + ' ' + str(skinCluster)

    data = {}
    data['shape'] = shape
    data['npoints'] = numberOfPoints = cmds.polyEvaluate(shape, v=True)
    influences = cmds.skinCluster(skinCluster, q=True, inf=True)
    data['influences'] = list()
    for influence in influences:
        data['influences'].append(influence)

    allWeights = list()
    allPositions = list()
    for point in range(numberOfPoints):
        weights = cmds.skinPercent(skinCluster,
                                   shape + '.vtx[' + str(point) + ']',
                                   q=True,
                                   v=True)
        allWeights.append(weights)
        position = cmds.pointPosition(shape + '.vtx[' + str(point) + ']')
        allPositions.append(position)

    data['weights'] = allWeights
    data['positions'] = allPositions

    return data
Exemplo n.º 53
0
Arquivo: main.py Projeto: mappp7/tools
    def manual_codebook(self, mayaMesh, jointList):
        sel = om.MSelectionList()
        sel.add(mayaMesh)
        dPath = sel.getDagPath(0)
        mMesh = om.MFnMesh(dPath)
        num = mMesh.numVertices
        #fine skinCluster
        skincluster = mel.eval('findRelatedSkinCluster("%s")' % mayaMesh)
        # array codeBook
        arrayL = []
        correct_JList = []

        for i in range(num):
            spct = cmds.skinPercent(skincluster,
                                    mayaMesh + '.vtx[' + str(i) + ']',
                                    q=1,
                                    value=1)
            # please do not paint skinweight
            for x in range(len(spct)):
                if spct[x] >= 0.6:
                    arrayL.append(x)

        codeBook = np.array(arrayL)
        #correct joint Index

        for y in range(len(jointList)):
            b = cmds.connectionInfo(skincluster + '.matrix[' + str(y) + ']',
                                    sfd=1)
            j = b.split('.')[0]
            correct_JList.append(j)
        print codeBook, correct_JList
        return codeBook, correct_JList
Exemplo n.º 54
0
    def LaodWeight(self, Unuse):
        FileFullpath = mc.fileDialog2(fm=1, ff=("JSON Files (*.json)"))
        if FileFullpath == None: return

        f = open(FileFullpath[0], mode='r')
        fileDt = json.load(f)
        f.close()

        latice = mc.ls(sl=True)
        skinNode = mel.eval('findRelatedSkinCluster ' + latice[0])
        for pt, Weilist in fileDt['weightList'].iteritems():
            mc.skinPercent(skinNode,
                           '%s.%s' % (latice[0], pt),
                           tv=zip(fileDt['skinJoints'], Weilist))

        print '#   Result:   weight Read Final! ',
Exemplo n.º 55
0
def record_info(root, jointDict, geo_name, file_info):
    for key, val in jointDict.items():
        file_info.write('joints {0} {1:.8f} {2:.8f} {3:.8f}\n'.format(
            key, val['pos'][0], val['pos'][1], val['pos'][2]))
    file_info.write('root {}\n'.format(root))
    vtxIndexList = cmds.getAttr(geo_name + ".vrts", multiIndices=True)
    for i in vtxIndexList:
        w_array = cmds.skinPercent('skinCluster1',
                                   geo_name + ".vtx[" + str(i) + "]",
                                   query=True,
                                   value=True,
                                   normalize=True)
        jname_array = mel.eval('skinCluster -query -inf skinCluster1')
        if abs(1 - np.sum(w_array)) > 1e-5:
            print 'nnnnn'
            exit(0)
        cur_line = 'skin {0} '.format(i)
        for cur_j in range(len(jname_array)):
            if w_array[cur_j] > 0:
                cur_line += '{0} {1:.4f} '.format(jname_array[cur_j],
                                                  w_array[cur_j])
        cur_line += '\n'
        file_info.write(cur_line)
    for key, val in jointDict.items():
        if val['pa'] != 'None':
            file_info.write('hier {0} {1}\n'.format(val['pa'], key))
Exemplo n.º 56
0
def edo_exPolyWeights():
    path=''
    paths=cmds.fileDialog2(fileFilter='*.skw',dialogStyle=2)
    if paths:
        path=paths[0]
    if path=='':
        cmds.undoInfo(state=1)
        return False
    sels=cmds.ls(sl=1)
    coms=cmds.polyListComponentConversion(sels,tv=1)
    cmds.select(coms,r=1)
    cs=cmds.ls(sl=1,fl=1)
    if cs:
       fobj=open(path,'w')
    for c in cs:
        #c=cs[0]
        #cmds.select(c)
        infs=cmds.skinCluster(c,q=1,inf=1)
        sk=edo_findNodeFromHis(c,'skinCluster')
        ws=cmds.skinPercent(sk,c,q=1,v=1)
        l=len(infs)
        tx=c+':'
        for i in range(0,l):
            #i=0
            inf=infs[i]
            w=ws[i]
            if w==0.0:
                continue
            iw=inf+'='+str(w)
            tx=tx+iw+' '
        #print tx
        fobj.write(tx+'\n')
    fobj.close()
Exemplo n.º 57
0
    def checkMaxSkinInfluences(self, node, maxInf, debug=1, select=0):
        '''Takes node name string and max influences int.
        From CG talk thread (MEL converted to Python, then added some things)'''

        cmds.select(cl=1)
        skinClust = self.findRelatedSkinCluster(node)
        if skinClust == "":
            cmds.error(
                "checkSkinInfluences: can't find skinCluster connected to '" +
                node + "'.\n")

        verts = cmds.polyEvaluate(node, v=1)
        returnVerts = []
        for i in range(0, verts):
            inf = cmds.skinPercent(skinClust, (node + ".vtx[" + str(i) + "]"),
                                   q=1,
                                   v=1)
            activeInf = []
            for j in range(0, len(inf)):
                if inf[j] > 0.0: activeInf.append(inf[j])
            if len(activeInf) > maxInf:
                returnVerts.append(i)

        if select:
            for vert in returnVerts:
                cmds.select((node + '.vtx[' + str(vert) + ']'), add=1)
        if debug:
            print 'checkMaxSkinInfluences>>> Total Verts:', verts
            print 'checkMaxSkinInfluences>>> Vertices Over Threshold:', len(
                returnVerts)
            print 'checkMaxSkinInfluences>>> Indices:', str(returnVerts)
        return returnVerts
Exemplo n.º 58
0
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
Exemplo n.º 59
0
def _calculate_influences(mesh, cluster, binding_joints, maximum_influences,
                          weights_getter):
    indices = []
    weights = []

    for vertex in _get_vertices(mesh):
        vertex_influence_joints = weights_getter(vertex, cluster)
        influences = len(vertex_influence_joints)

        if influences != maximum_influences:
            raise RuntimeError(
                'Vertex "{vertex}" has "{influences}". It needs to have "{maximum_influences}" influences.'
                .format(
                    vertex=vertex,
                    influences=influences,
                    maximum_influences=maximum_influences,
                ))

        for joint in vertex_influence_joints:
            indices.append(binding_joints.index(joint))

            weights.append(
                cmds.skinPercent(cluster,
                                 vertex,
                                 transform=joint,
                                 normalize=True,
                                 q=True))

    return indices, weights
Exemplo n.º 60
0
def getWeight(vtx, fromJntLs):
    weightLs = []
    for jnt in fromJntLs:
        weightLs += [
            cmds.skinPercent("skinCluster18", vtx, query=True, transform=jnt)
        ]
    return weightLs