def get_invalid(cls, instance):
        invalid = []

        for node in cmds.ls(instance, type='mesh'):
            uv = cmds.polyEvaluate(node, uv=True)

            if uv == 0:
                invalid.append(node)
                continue

            vertex = cmds.polyEvaluate(node, vertex=True)
            if uv < vertex:

                # Workaround:
                # Maya can have instanced UVs in a single mesh, for example
                # imported from an Alembic. With instanced UVs the UV count from
                # `maya.cmds.polyEvaluate(uv=True)` will only result in the unique
                # UV count instead of for all vertices.
                #
                # Note: Maya can save instanced UVs to `mayaAscii` but cannot
                #       load this as instanced. So saving, opening and saving
                #       again will lose this information.
                uv_to_vertex = cmds.polyListComponentConversion(node + ".map[*]",
                                                                toVertex=True)
                uv_vertex_count = len_flattened(uv_to_vertex)
                if uv_vertex_count < vertex:
                    invalid.append(node)
                else:
                    cls.log.warning("Node has instanced UV points: {0}".format(node))

        return invalid
Example #2
0
def copyWeights(sourceMesh, targetMesh, sourceDeformer, targetDeformer):
    """
	Copy deformer weights from one mesh to another.
	Source and Target mesh objects must have matching point order!
	@param sourceMesh: Mesh to copy weights from
	@type sourceMesh: str
	@param targetMesh: Mesh to copy weights to
	@type targetMesh: str
	@param sourceDeformer: Deformer to query weights from
	@type sourceDeformer: str
	@param targetDeformer: Deformer to apply weights to
	@type targetDeformer: str
	"""
    # Check source and target mesh
    if not mc.objExists(sourceMesh):
        raise Exception('Source mesh "' + sourceMesh + '" does not exist!!')
    if not mc.objExists(targetMesh):
        raise Exception('Target mesh "' + targetMesh + '" does not exist!!')

        # Check deformers
    if not mc.objExists(sourceDeformer):
        raise Exception('Source deformer "' + sourceDeformer + '" does not exist!!')
    if targetDeformer and not mc.objExists(targetDeformer):
        raise Exception('Target deformer "' + targetDeformer + '" does not exist!!')
    if not targetDeformer:
        targetDeformer = sourceDeformer

    # Compare vertex count
    if mc.polyEvaluate(sourceMesh, v=True) != mc.polyEvaluate(targetMesh, v=True):
        raise Exception("Source and Target mesh vertex counts do not match!!")

        # Copy weights
    wtList = glTools.utils.deformer.getWeights(sourceDeformer, sourceMesh)
    # Paste weights
    glTools.utils.deformer.setWeights(targetDeformer, wtList, targetMesh)
def getFaces():
    # count faces
    faceCount = cmds.polyEvaluate(geometryName[0],f=True)
    # make a list of face count
    faceRange = list(range(1,faceCount))

    # empty list for face
    faceList = []

    # for each face in faceRange, get the name of the face
    for f in faceRange:
        # get the name of each face on the model
        face = (str(geometryName[0])+'.f['+str(f)+']')

        # append each face to the faceList
        faceList.append(face)

    faceCount = cmds.polyEvaluate(geometryName[0],f=True)

    # empty list for facebounds
    fb = []

    # if the faceList is equal to the number of faces found    
    if len(faceList) == faceCount-1:
        # for each face name found in face list
        for face in faceList:
            # select each face
            cmds.select(face)
            # get the UV bounding box on each face
            faceBounds = cmds.polyEvaluate(bc2=True)
            # print the facebounds
            fb.append(faceBounds)

    if len(fb) == len(faceList):
        return fb,faceList
Example #4
0
def MeshDict(mesh = None, pointCounts = True, calledFrom = None):
    """
    Validates a mesh and returns a dict of data.
    If a shape is the calling object, it will be the shape returned, otherwise, the first shape in the chain will be

    :param mesh: mesh to evaluate
    
    :returns:
    dict -- mesh,meshType,shapes,shape,pointCount,pointCountPerShape
    

    """        
    _str_funcName = 'MeshDict'
    if calledFrom: _str_funcName = "{0} calling {1}".format(calledFrom,_str_funcName) 
    
    _mesh = None 
    
    if mesh is None:
        _bfr = mc.ls(sl=True)
        if not _bfr:raise ValueError,"No selection found and no source arg"
        mesh = _bfr[0]
        log.info("{0}>> No source specified, found: '{1}'".format(_str_funcName,mesh))
           
    _type = search.returnObjectType(mesh)
    _shape = None
    _callObjType = None
    
    if _type in ['mesh']:
        _mesh = mesh
        _callObjType = 'meshCall'
    elif _type in ['shape']:
        _shape = mesh
        _callObjType = 'shapeCall'
        _mesh = getTransform(mesh)
    else:
        raise ValueError,"{0} error. Not a usable mesh type : obj: '{1}' | type: {2}".format(_str_funcName, mesh, _type)

    _shapes = mc.listRelatives(_mesh,shapes=True,fullPath=False)
    
    if _shape is None:
        _shape = _shapes[0]
        
    _return = {'mesh':_mesh,
               'meshType':_type,
               'shapes':_shapes,
               'shape':_shape,
               'callType':_callObjType,
               }
    
    if pointCounts:
        if _callObjType == 'shapeCall':
            _return['pointCount'] = mc.polyEvaluate(_shape, vertex=True)
        else:
            _l_counts = []
            for s in _return['shapes']:
                _l_counts.append( mc.polyEvaluate(s, vertex=True))
            _return['pointCountPerShape'] = _l_counts
            _return['pointCount'] = sum(_l_counts)

    return _return   
Example #5
0
def returnObjectSize(obj,debugReport = False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Semi intelligent object sizer. Currently works for verts, edges,
    faces, poly meshes, nurbs surfaces, nurbs curve

    ARGUMENTS:
    obj(string) - mesh or mesh group

    RETURNS:
    size(float)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    objType = search.returnObjectType(obj)

    #>>> Poly
    if objType == 'mesh':
        size =  mc.polyEvaluate(obj,worldArea = True)

        if debugReport: print ('%s%f' %('mesh area is ',size))
	return size

    elif objType == 'polyVertex':
        meshArea = mc.polyEvaluate(obj,worldArea = True)
        splitBuffer = obj.split('.')
        vertices = mc.ls ([splitBuffer[0]+'.vtx[*]'],flatten=True)
        size = meshArea/len(vertices)

        if debugReport: print ('%s%f' %('Average mesh area per vert is  ',size))
        return size

    elif objType == 'polyEdge':
        size = returnEdgeLength(obj)

        if debugReport: print ('%s%f' %('The Edge length is ',size))
        return size

    elif objType == 'polyFace':
        size =  returnFaceArea(obj)

        if debugReport: print ('%s%f' %('face area is ',size))
        return size

    #>>> Nurbs
    elif objType == 'nurbsSurface':
        boundingBoxSize = returnBoundingBoxSize(obj)
        size = cgmMath.multiplyList(boundingBoxSize)

        if debugReport: print ('%s%f' %('Bounding box volume is ',size))
        return size

    elif objType == 'nurbsCurve':
        size =  returnCurveLength(obj)

        if debugReport: print ('%s%f' %('Curve length is ',size))
        return size
    else:
        if debugReport: print ("Don't know how to handle that one")
        return False
Example #6
0
def triangulateMesh(isObj, simplify, smoothe):
	if isObj and not cmds.objExists('triObj'):
		cmds.select(baseObject)
		cmds.duplicate(baseObject, name = "triObj")
		cmds.select('triObj')

		if smoothe:
			cmds.polySmooth('triObj', c=smoothe)
			cmds.polyReduce(ver = 1)
			cmds.polyReduce(ver = 1)

		if simplify > 0:
			cmds.polyReduce(ver = 1, p = simplify)

		num_faces = cmds.polyEvaluate('triObj', f=True)
		
		print "Triangulating faces..."
		#iterate over faces
		face_i = 0
		while face_i < num_faces:
			if ((num_faces - face_i) % 5 == 0):
				print "Triangulate check: Approximately " + str(num_faces - face_i) + " faces remaining...."
			face = cmds.select('triObj.f['+ str(face_i)+']')		
			verts = getCorners(isObj,face_i)
			if not isCoplanar(verts):
				cmds.polyTriangulate('triObj.f['+ str(face_i)+']')
				num_faces = cmds.polyEvaluate('triObj', f=True)
			face_i +=1
Example #7
0
def ftb_gen_shell_doIt(dist,distUV,div):
	if (mc.window('shellUiWin',q=True,exists=True)):
		mc.deleteUI('shellUiWin')
	#mc.loadPlugin( 'c:/ftb_mayaplugins/ppl/2011 x64/shellNode.mll')
	sel = mc.ls(sl=True)
	if(len(sel)!= 0):
		shape = mc.listRelatives(sel[0],noIntermediate = True,shapes=True)
		His = mc.listHistory(shape[0])
		shell = ''
		for h in His:
			if(mc.nodeType(h) == 'polyShell'):
				shell = h
		if(shell == ''):
			if(mc.attributeQuery('shThickness',node=shape[0],ex=True)):
				dist = mc.getAttr(shape[0]+'.shThickness')
			else:
				mc.addAttr(shape[0],ln="shThickness",at='double',dv=0)
				mc.setAttr(shape[0]+'.shThickness',e=True,keyable=True)
			if(mc.attributeQuery('shUvThickness',node=shape[0],ex=True)):
				distUV = mc.getAttr(shape[0]+'.shUvThickness')
			else:
				mc.addAttr(shape[0],ln="shUvThickness",at='double',dv=0)
				mc.setAttr(shape[0]+'.shUvThickness',e=True,keyable=True)
			if(mc.attributeQuery('shDiv',node=shape[0],ex=True)):
				div = mc.getAttr(shape[0]+'.shDiv')
			else:
				mc.addAttr(shape[0],ln="shDiv",at='long',dv=0,min=0)
				mc.setAttr(shape[0]+'.shDiv',e=True,keyable=True)
			faceInitalCount = mc.polyEvaluate(sel[0],f=True)
			mc.polyShell(thickness = dist,uvOffset = distUV);
			sel2 = mc.ls(sl=True)
			faceFinalCount = mc.polyEvaluate(sel[0],f=True)
			mc.addAttr(sel2[0],ln="div",at='long',min=0,dv=0)
			mc.setAttr(sel2[0]+'.div',e=True,keyable=True)
			mc.setAttr(sel2[0]+'.div',div)
			mc.addAttr(sel2[0],ln="splits",dt="string")
			mc.setAttr(sel2[0]+'.splits',e=True,keyable=True)
			mc.select((sel[0]+'.f[%i' % (faceInitalCount*2)+':%i' % faceFinalCount+']'))
			faceList = mc.ls(sl=True,fl=True)
			facesRings = makeFaceRingGroups(faceList)
			for faceRing in facesRings:
				mc.select(facesRings[faceRing])
				mc.ConvertSelectionToContainedEdges()
				mc.setAttr(sel2[0]+'.thickness',0.2)
				split = mc.polySplitRing(mc.ls(sl=True),ch=True,splitType=2,divisions=0,useEqualMultiplier=1,smoothingAngle=30,fixQuads=1)
				splits = mc.getAttr(sel2[0]+'.splits')
				if(splits == None):
					splits = ""
				mc.setAttr(sel2[0]+'.splits',("%s"%splits+"%s,"%split[0]),type="string")
				mc.connectAttr(sel2[0]+'.div', (split[0]+'.divisions'))
				mc.setAttr(sel2[0]+'.thickness',dist)
				
			mc.connectAttr(sel2[0]+'.thickness',shape[0]+'.shThickness')
			mc.connectAttr(sel2[0]+'.uvOffset',shape[0]+'.shUvThickness')
			mc.connectAttr(sel2[0]+'.div',shape[0]+'.shDiv')
		else:
			print('This mesh have a shellModifier allready!!!!!')
	else:
		mc.error("please select some mesh")
    def hfSplitBadShaded(self, engines):
        modifiedShapes = []
        for sg in engines:
            print('checking shading group: '+sg)
            cmds.hyperShade(objects=sg)
            components = cmds.ls(sl=1)
            uniqueShapes = []
            for entry in components:
                uniqueShapes.append(entry.split('.')[0])
                # remove whole shapes (not components) from the list.
                if entry.rfind('.f') == -1:
                    components.remove(entry)
            if len(components) > 0:
                components.sort()
                # remove duplicates from uniqueShapes.
                uniqueShapes = list(set(uniqueShapes))
                modifiedShapes.extend(uniqueShapes)
                # print('\nunique shapes under shading group: ')
                # print(uniqueShapes)
                for shape in uniqueShapes:
                    cmds.select(cl=1)
                    # get the total num of faces for the shape for later use.
                    totalFaces = cmds.polyEvaluate(shape, f=1)
                    for comp in components:
                        testStr = shape+'.f['
                        if testStr in comp:
                            # the current component is a member of the current mesh we're splitting and it has the shader we want.
                            cmds.select(comp, add=1)
                    selFaces = cmds.ls(sl=1)
                    # print 'selection:'
                    # print selFaces
                    # extract the selected faces if we aren't selecting every face of the current mesh.
                    if len(selFaces) < int(totalFaces) and len(selFaces) > 0:
                        cmds.polyChipOff(selFaces, kft=1, dup=0)
                        cmds.delete(shape,ch=1)
                    # now the mesh is broken into shells. separate it if possible.
                    if cmds.polyEvaluate(shape, s=1) > 1:
                        newObjects = cmds.polySeparate(shape, ch=0)
                        modifiedShapes.extend(newObjects)
                        # print('split new shapes: ')
                        # print(newObjects)
                        cmds.select(newObjects)
                        # print(cmds.ls(sl=1))
                        cmds.delete(ch=1)
        cmds.select(cl=1)
        # now in order to return all the new meshes we made, we should sort through uniqueShapes and remove anything that no longer
        # exists. anything that's been split, etc.
        modifiedShapes = list(set(modifiedShapes))
        returnShapes = []
        for shape in modifiedShapes:
            if cmds.objExists(shape) == 0:
                modifiedShapes.remove(shape)
            else:
                meshNodes = cmds.listRelatives(shape, s=1)
                if meshNodes != None:
                # if we are not testing an xform, meshNodes will be a 'NoneType' object so we should include an exception.
                    returnShapes.extend(meshNodes)

        return returnShapes
def setObjectAsCanvas(name):
	cmds.polyEvaluate(f=True)
	subdivSurface = cmds.polyToSubdiv(maxPolyCount=cmds.polyEvaluate(f=True), maxEdgesPerVert=32, ch=False)[0]
	liveSurface = cmds.subdToNurbs(subdivSurface, ot=0, ch=False)
	cmds.delete(subdivSurface)
	cmds.hide(liveSurface)
	cmds.makeLive(liveSurface)

	return liveSurface
Example #10
0
def rec(object_name, volume_total, cut_planes, volume_ratios, threshold, result, loop_num):
	# base cases
	if loop_num == 0:
		print 'insert more coins to continue'
		return False
	elif mc.polyEvaluate(object_name, shell = True) > 1:
		# more than one shell in object named 'object_name'
		print 'NO REDEMPTION'
		return False
	elif len(volume_ratios) == 1:
		# check ratio matches
		this_ratio = mm.eval('meshVolume(\"' + object_name + '\")') / volume_total
		# since its last one, might have more errors
		if abs(this_ratio - volume_ratios[0]) < threshold * 4:
			# duplicate the object
			temp = mc.duplicate(object_name)
			mc.select(temp[0], r = True)
			# move away the duplication
			mc.move(kMoveAwayXDistance, 0, 0, temp[0])
			# remove the current object
			mc.delete(object_name)
			print 'DONE with last object!'
			result.append(temp[0])
			print result
			return True
		else:
			print 'last object did NOT match last ratio!', this_ratio, volume_ratios[0]
			return False

	# recursive step
	random.shuffle(cut_planes)
	result_from_cutting = cut_object_with_planes_and_ratios(object_name, volume_total, cut_planes, volume_ratios, threshold)
	if isinstance(result_from_cutting, list):
		# this list contains all successfully cut objects and we are done
		result.extend(result_from_cutting)
		print 'lucky!'
		print result
		return True
	else:
		print 'Enter recursive step'
		# dictionary returned
		# extend result list with what we have now
		result.extend(result_from_cutting['good_cut_objs'])
		# merge the remaining objects into one
		bad_cut_objs = result_from_cutting['bad_cut_objs']
		if mc.polyEvaluate(bad_cut_objs, shell = True) > 1:
			united_objects = mc.polyUnite(bad_cut_objs)[0]
			mc.polyMergeVertex(united_objects)
		else:
			united_objects = bad_cut_objs[0]
		# get list of ratios un-resolved
		ratios_remaining = result_from_cutting['ratios_remaining']
		recursion_result = rec(united_objects, volume_total, cut_planes, ratios_remaining, threshold, result, loop_num-1)
		return recursion_result
Example #11
0
	def initMeshFromMayaMesh(self, meshName):
		_vs = []
		_faces = []
		numV = mc.polyEvaluate(meshName, v=True)
		numF = mc.polyEvaluate(meshName, f=True)
		for i in range(numV):
			_vs.append(mc.pointPosition(meshName+".vtx["+str(i)+"]"))
		for i in range(numF):
			_faces.append(self.faceVtxList(meshName+".f["+str(i)+"]"))
		self.vs = _vs
		self.faces = _faces
Example #12
0
def cutCell(obj, mat, pos, rot, shardsGRP):
	#do the cut procedure
	tocut = mc.polyEvaluate(obj, face = True)
	mc.polyCut( ('%s.f[0:%d]'% (obj,tocut)), pc = (pos[0], pos[1], pos[2]), ro = (rot[0], rot[1], rot[2]), ch = False, df = True)
	cutFaces = mc.polyEvaluate(obj, face = True)
	mc.polyCloseBorder(obj, ch = False)
	newFaces = mc.polyEvaluate(obj, face = True)
	newFaces = newFaces - cutFaces
	#assign material to faces
	for face in range(newFaces):
		mc.sets( ( '%s.f[ %d ]' % (obj, (cutFaces + newFaces - 1))), forceElement = ('%sSG' % (mat)),  e = True)
Example #13
0
	def create(self):
		"""create hairsystem for lock"""
		numFace = mc.polyEvaluate( self.mesh.shape.name, f = True )
		numVert = mc.polyEvaluate( self.mesh.shape.name, v = True )
		if not self.hairSystem:
			print 'There is no hairSystem assigned to this HairLock --> init with one or assign one.... '
		if not numFace % 2 or not numVert == ( numFace + 3 ):
			print 'This mesh dosen\'t have odd number of faces', self.mesh.name, 'SKYPING'
			return
		self._curveMesh = mn.createNode('curvesFromMesh' )
		self._curveMesh.name = self.mesh.name + '_curveMesh'
		self.mesh.shape.a.outMesh     >> self._curveMesh.a.inMesh
		self.mesh.shape.a.worldMatrix >> self._curveMesh.a.inWorldMatrix
		for i in range(5):	
			hairCurve = mn.createNode('nurbsCurve' )
			hairCurveParent = hairCurve.parent
			hairCurveParent.name = self.mesh.name + '_%i'%i + '_crv'
			hairCurve = hairCurveParent.shape
			self._curveMesh.attr( 'outCurve[%i'%i + ']' ) >> hairCurve.a.create
			
			follicle = mn.createNode('follicle')
			folliclePar = follicle.parent
			folliclePar.name = self.mesh.name + '_%i'%i + '_foll'
			follicle = folliclePar.shape
			hairSustemOutHairSize = self.hairSystem.a.outputHair.size 
			follicle.a.outHair >> self.hairSystem.attr( 'inputHair[%i'%hairSustemOutHairSize + ']' )
			#follicle.a.outHair >> self.hairSystem.attr( 'inputHair[%i'%i + ']' )
			hairCurve.a.worldSpace >> follicle.a.startPosition
			self.hairSystem.attr( 'outputHair[%i'%hairSustemOutHairSize + ']' ) >> follicle.a.currentPosition
			self._follicles.append(follicle)
			self._curves.append(hairCurve)
			#if there is a scalp mesh use that for the position of the follicle
			if self.scalp:
				self.scalp.shape.a.outMesh >> follicle.a.inputMesh
				self.scalp.a.worldMatrix   >> follicle.a.inputWorldMatrix
				u,v = self._getUVCoordFromScalpForFollicle( hairCurve )
				follicle.a.parameterV.v       = v
				follicle.a.parameterU.v       = u
				#hairCurveParent.parent        = folliclePar
			else:
				self.mesh.shape.a.outMesh  >> follicle.a.inputMesh
				self.mesh.a.worldMatrix    >> follicle.a.inputWorldMatrix
				follicle.a.parameterV.v       = 0.5
				follicle.a.parameterU.v       = 0.5
			follicle.a.overrideDynamics.v = 0
			follicle.a.startDirection.v   = 1
			follicle.a.clumpWidthMult.v   = 1.5
			follicle.a.densityMult.v      = 0.5
			follicle.a.sampleDensity.v    = 1.5
			follicle.a.outTranslate >> follicle.parent.a.translate
			follicle.a.outRotate >> follicle.parent.a.rotate
def flipWeights(sourceDeformer,targetDeformer,sourceInfluence,targetInfluence,axis='x'):
	'''
	'''
	# Check dnBurlyDeformer
	if not glTools.utils.dnBurlyDeformer.isBurlyDeformer(sourceDeformer):
		raise Exception('A valid source dnBurlyDeformer must be provided!')
	
	if not isBurlyDeformer(targetDeformer):
		raise Exception('A valid target dnBurlyDeformer must be provided!')
	
	# Get influence indices
	sourceInfluenceIndex = glTools.utils.dnBurlyDeformer.getInfluenceIndex(sourceDeformer,sourceInfluence)
	targetInfluenceIndex = glTools.utils.dnBurlyDeformer.getInfluenceIndex(targetDeformer,targetInfluence)
	
	# Get affected geometry
	sourceGeo = glTools.utils.deformer.getAffectedGeometry(sourceDeformer).keys()[0]
	targetGeo = glTools.utils.deformer.getAffectedGeometry(targetDeformer).keys()[0]
	sourceGeoPntNum = mc.polyEvaluate(sourceGeo,v=True)
	targetGeoPntNum = mc.polyEvaluate(targetGeo,v=True)
	
	# Get source influence weights
	sourceInfluenceWeights = glTools.utils.dnBurlyDeformer.getInfluenceWeights(dnBurlyDeformer,sourceInfluence)
	
	# Get affected geometry
	targetInfluenceWeights = [0.0 for i in range(targetGeoPntNum)]
	
	# Build vertex correspondence table
	vtxTable = []
	for i in range(sourceGeoPntNum):
		# Get source vertex position
		pos = glTools.utils.base.getPosition(sourceGeo+'.vtx['+str(i)+']')
		
		# Get mirror position
		mPos = pos
		mPos[axisInd] *= -1.0
		
		# Get closest vertex to mirror position
		mVtx = glTools.utils.mesh.closestVertex(targetGeo,mPos)
		vtxTable.append(mVtx)
		
	# Build target influence weights
	for i in range(len(sourceInfluenceWeights)):
		targetInfluenceWeights[vtxTable[i]] = sourceInfluenceWeights[i]
	
	# Set influence weights
	glTools.utils.dnBurlyDeformer.setInfluenceWeights(targetDeformer,targetInfluence,targetInfluenceWeights)
	
	# Rebind influence
	mm.eval('dnBurlyDeformer -rebindMuscle "'+targetDeformer+'" "'+targetInfluence+'"')
Example #15
0
def isComponent(shape):
    result = None
    cmds.select(shape)
    vert = cmds.polyEvaluate(vertexComponent=True)
    face = cmds.polyEvaluate(faceComponent=True)
    edge = cmds.polyEvaluate(edgeComponent=True)
    if vert > 0:
        result = "vert"
    elif face > 0:
        result = "face"
    elif edge > 0:
        result = "edge"
    else:
        result = False
    return result
Example #16
0
File: gui.py Project: mkolar/Tapp
    def on_loadUpVert_pushButton_released(self):

        sel = cmds.ls(selection=True,flatten=True)

        if len(sel) > 0:

            shape = cmds.ls(selection=True, objectsOnly=True)[0]

            if cmds.nodeType(shape) == 'mesh':
                if cmds.polyEvaluate()['vertexComponent']>0:

                    verts = []
                    for vert in sel:

                        verts.append(vert)

                    self.upVert = verts
                    self.upVert_label.setText('Vert loaded!')
                    self.loadUpVert_pushButton.setStyleSheet(self.loadedStyleSheet)
                else:
                    cmds.warning('No vert selected!')
            else:
                cmds.warning('Selection is not a vertex!')
        else:
            cmds.warning('Nothing is selected!')
Example #17
0
	def getObjEdgeCount( self ):
		if (len(self)>0):
			if('objEdgeCount' not in self.__dict__) or self.objEdgeCount==-1:
				self.objEdgeCount = mc.polyEvaluate( self.obj, e=True )
			return self.objEdgeCount
		else: 
			return
Example #18
0
    def getShells(self, obj):
        """
            @param[in] obj: object full name 
            @type obj: string
            @returns: list of shells that is included in the passed in object in format [ [[obj.f[0], obj.f[1], obj.f[2]], [obj.f[3], obj.f[4], obj.f[5]], [another shell]], [another object]]
        """
        output = []

        # total data
        numOfShells = cmds.polyEvaluate(obj, s=1)

        faceList = cmds.ls(cmds.polyListComponentConversion(obj, tf=True), l=1, fl=1)

        for i in range(numOfShells):
            # cmds.select(obj)
            idx = int(faceList[0].split(".f[")[-1].split("]")[0])
            shellFaces = cmds.polySelect(obj, q=1, ets=idx)

            shellFacesFormat = []  # obj.f[0], obj.f[1] ...
            if shellFaces:
                for j in shellFaces:
                    __faceData = obj + ".f[" + str(j) + "]"
                    shellFacesFormat.append(__faceData)

            faceList = self.comprehensionList(faceList, shellFacesFormat)

            output.append(shellFacesFormat)

        return output
Example #19
0
    def __init__(self, model):
        BaseStructure.__init__(self, model)

        print "-------------------"
        print "importing Vertex"

        self.vtx_names = GetVerticesList(model)
        self.uv_names = self.GetUVNameList()
        self.uv_maps = self.GetUVMapList()
        self.uv_count = len(self.uv_names)
        self.vertex_count = cmds.polyEvaluate(model, v=True)

        print "vertex count: ", self.vertex_count

        self.uvs = self.ToUVs()
        self.map_to_vtx = self.BuildVertexIndicesFromMaps()
        self.vtx_to_map = self.BuildMapIndicesFromVertexNames()

        # self.indices = self.ToIndices()
        self.positions = self.ToPositions()
        self.normals = self.ToNormals()
        print "normal count: ", len(self.normals)

        self.bone_weights = self.InitBoneWeight()
        self.bone_num = self.InitBoneNum()
        self.edge_flag = self.InitEdgeFlag()

        self.count = len(self.positions)
Example #20
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,int(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
Example #21
0
File: gui.py Project: mkolar/Tapp
    def on_loadPositionVerts_pushButton_released(self):

        sel = cmds.ls(selection=True, flatten=True)

        if len(sel) > 0:

            shape = cmds.ls(selection=True, objectsOnly=True)[0]

            if cmds.nodeType(shape) == 'mesh':
                if cmds.polyEvaluate()['vertexComponent'] > 0:

                    verts = []
                    for vert in sel:

                        verts.append(vert)

                    if len(verts) == 2:
                        self.posVerts = verts
                        self.positionVerts_label.setText('Verts loaded!')
                        self.loadPositionVerts_pushButton.setStyleSheet(self.loadedStyleSheet)
                    else:
                        cmds.warning('More or Less than two verts selected. Please select only 2 verts.')
                else:
                    cmds.warning('No verts selected!')
            else:
                cmds.warning('Selection is not a vertex!')
        else:
            cmds.warning('Nothing is selected!')
def ShapeInverterCmdold(base=None, corrective=None, name=None):
    mc.undoInfo(openChunk=True)
    if not base or not corrective:
        sel = mc.ls(sl=True)
        base, corrective = sel
    shapes = mc.listRelatives(base, children=True, shapes=True)
    for s in shapes:
        if mc.getAttr("%s.intermediateObject" % s) and mc.listConnections("%s.worldMesh" % s, source=False):
            origMesh = s
            break
    deformed = mc.polyPlane(ch=False)[0]
    mc.connectAttr("%s.worldMesh" % origMesh, "%s.inMesh" % deformed)
    mc.setAttr("%s.intermediateObject" % origMesh, 0)
    mc.delete(deformed, ch=True)
    mc.setAttr("%s.intermediateObject" % origMesh, 1)
    if not name:
        name = "%s_inverted#" % corrective
    invertedShape = duplicateMesh(base, name=name)
    deformer = mc.deformer(invertedShape, type="ShapeInverter")[0]
    mc.ShapeInverterCmd(baseMesh=base, invertedShape=invertedShape, ShapeInverterdeformer=deformer, origMesh=deformed)
    # correctiveShape = duplicateMesh(base,name=corrective+"_corrective#")
    # mc.connectAttr('%s.outMesh' % getShape(correctiveShape), '%s.correctiveMesh' % deformer)
    # transferMesh(corrective,[correctiveShape])
    mc.connectAttr("%s.outMesh" % getShape(corrective), "%s.correctiveMesh" % deformer)
    mc.setAttr("%s.activate" % deformer, True)
    mc.delete(deformed)
    bdingBx = mc.polyEvaluate(corrective, boundingBox=True)
    xDifVal = bdingBx[0][1] - bdingBx[0][0]
    # mc.move(xDifVal*1.10,correctiveShape,r=True,moveX=True)
    mc.move(xDifVal * 2.20, invertedShape, r=True, moveX=True)
    mc.undoInfo(closeChunk=True)
    return invertedShape  # ,correctiveShape
 def deformCharacterShapeSel(self, value):
     RN = mc.referenceQuery(self.core.skCharacter[int(value)-1], referenceNode=1)
     Nodes = mc.referenceQuery(RN, nodes=1)
     self.characterdeformShape = []
     self.allCharacterRightdeformShape = []
     for item in Nodes:
         if self.nodeTypeSelf(item) in self.shapeType:
             self.characterdeformShape.append(item)
     for each in self.characterdeformShape:
         itemP = mc.listRelatives(each, p=1)[0]
         itemPP = mc.listRelatives(itemP, p=1)
         if itemPP != None and mc.getAttr('%s.v'%itemP) != 0 and mc.getAttr('%s.v'%itemPP[0]) != 0:
             self.allCharacterRightdeformShape.append(each)
             self.allCharacterRightdeformShape.reverse()
     #for item in self.allCharacterRightdeformShape:
         #if mc.filterExpand( item, sm=(10,12)) == None:
             #self.allCharacterRightdeformShape.remove(item)
     for i in range(10):
         for item in self.allCharacterRightdeformShape:
             if self.checkStaticCache(item) == False:
                 self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if mc.polyEvaluate( item, v=True ) == 0:
             self.allCharacterRightdeformShape.remove(item)
     return self.allCharacterRightdeformShape
Example #24
0
def buildSymTable(mesh):
    symDict = {}
    posDict = {}
    negDict = {}
    
    # store positions in separate positive and negative dictionaries
    vtxCount = mc.polyEvaluate(mesh, v=1)
    for vtxvertId in range(vtxCount):
        posX, posY, posZ = mc.xform('%s.vtx[%d]'%(mesh,vtxvertId), q=1, t=1, os=1)
        if posX > 0:
            posDict[(posX,posY,posZ)] = vtxvertId
        elif posX < 0:
            negDict[(posX,posY,posZ)] = vtxvertId
    
    # match positive to negative verts in symmetry table
    for posKey, vtxvertId in posDict.items():
        negKey = (-posKey[0], posKey[1], posKey[2])
        if negKey in negDict:
            symDict[vtxvertId] = negDict[negKey]
    
    # select assymetrical verts
    asymVerts = ['%s.vtx[%d]'%(mesh, vertId) for vertId in range(vtxCount) if vertId not in symDict.keys() and vertId not in symDict.values()]
    mc.select(asymVerts)

    return symDict
Example #25
0
def isEmpty(mesh):
    try:
        numfaces = cmds.polyEvaluate(mesh,face=True)
    except IndexError:
        numfaces=0
        pass   
    return False or numfaces == 0
Example #26
0
	def getObjVertCount(self):
		if len(self)>0:
			if 'objVertCount' not in self.__dict__ or self.objVertCount==-1:
				self.objVertCount = mc.polyEvaluate( self.obj, v=True )
			return self.objVertCount
		else: 
			return
def main(log=None):
    if not log:
        import logging
        log = logging.getLogger()

    edge5 = set()
    dagNode = cmds.ls(dag = True, l=True, lf=True, type = 'mesh')
    for dag in dagNode:
        cmds.select(dag)
        numFace = cmds.polyEvaluate(f = True)
        for f in range(0, numFace):
            allEdge = []
            cmds.select(cl = True)
            cmds.select(dag + '.f[' + str(f) + ']')
            edgeNum = cmds.polyInfo(fe = True)
            eSplit1 = edgeNum[0].split(':')
            eSplit2 = eSplit1[1].split(' ')
            for e in eSplit2:
                if(e != ''):
                    allEdge.append(e)
            if(len(allEdge) > 5):
                edge5.add('%s.f[%s]' %(dag, f))
                
    if edge5:
        log.warning("more than four edge:\n%s" % (' '.join(edge5)) )
def modify_surface():
    
    perlin = True
    sel = mc.ls(selection=True,long=True)
    for verts in sel:
        totalVerts = mc.polyEvaluate(verts, vertex=True)
        for number in xrange(totalVerts):
            if perlin == True:
				frequency = 1.0
				amplitude = 1.5
				octaves = 8
				for o in xrange(octaves):
				    randX = random.triangular(-0.2 , 0.0, 0.2)
				    posX = perlinNoise(randX ,0,0)
				    
				    randY = random.triangular(-0.4 , 0.0, 0.6)
				    posY = perlinNoise(0,randY,0)
				    
				    randZ = random.triangular(-0.2 , 0.0, 0.2)
				    posZ = perlinNoise(0,0,randZ)
				    
				    posX *= frequency
				    posY *= frequency
				    posZ *= frequency 
				    
				    mc.select(verts+'.vtx[{number}]'.format(number=number))
				    mc.move(posX,posY*amplitude,posZ,relative=True)
				    mc.rotate(posY*amplitude,y=True)
    mc.select(sel, replace=True)
    mc.makeIdentity(s=True, a=True, t=True,r=True)
def exportWeight (objs, path) :
    xmlFile = open(path,'w')
    root_node = xml.Element('exportedSkinWeight')
        
    for obj in objs:
        skinCluster = getSkinClusterNode(obj)
        vertexCount = cmds.polyEvaluate(obj, v=True)
        jointDicts = getJointDicts(skinCluster)
        
        obj_node = xml.Element('objectName')
        obj_node.text = obj
        root_node.append(obj_node)

        # PROGRESS BAR START
        gMainProgressBar = mel.eval('$tmp = $gMainProgressBar')
        cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, status="PROCESS // Exporting Weight : %s (count = %d)" %(obj,vertexCount), maxValue=vertexCount)
            
        for vertex in range(vertexCount):
            for jointDict in jointDicts:
                value = cmds.getAttr(skinCluster+'.wl[%d].w[%d]' %(int(vertex), int(jointDict['jointIndex'])))
                if not value == 0:
                    vtx_node = xml.Element('skinWeightInfo')
                    obj_node.append(vtx_node)
                    vtx_node.attrib['vertex'] = str(vertex)
                    vtx_node.attrib['jointName'] = jointDict['jointName']
                    vtx_node.attrib['value'] = str(value)
            #PROGRESS BAR STEP
            cmds.progressBar(gMainProgressBar, edit=True, step=1)
            
        # PROGESS BAR END
        cmds.progressBar(gMainProgressBar, edit=True, endProgress=True)
        
    indent(root_node)
    xml.ElementTree(root_node).write(xmlFile)
    xmlFile.close()
Example #30
0
def copyPaintAttr(mesh, attr, sourceAttr, attrType="doubleArray"):
    """
	Copy the value of one paintable attribute to another
	@param mesh: Mesh that contains the attribute to copy values to
	@type mesh: str
	@param attr: The name of the attribute to copy the values to
	@type attr: str
	@param sourceAttr: The attribute to copy values from
	@type sourceAttr: str
	@param attrType: The attribute type to set
	@type attrType: str
	"""
    # Check Mesh
    if not glTools.utils.mesh.isMesh(mesh):
        raise Exception('Mesh "' + mesh + '" does not exist!!')

        # Check Mesh Attribute
    if not mc.objExists(mesh + "." + attr):
        addPaintAttr(mesh, attr, attrType)

    # Copy Attribute Values
    vtxCount = mc.polyEvaluate(mesh, v=True)
    attrVal = []
    for i in range(vtxCount):
        val = mc.getAttr(sourceAttr + "[" + str(i) + "]")
        attrVal.append(val)

        # Set Attribute Value
    mc.setAttr(mesh + "." + attr, attrVal, type=attrType)
 def instantMeshes_remesh(self, face_count=None):
     inst_mesh_path = LDMTPATH + "/ldmt_exe/instantMesh.exe"
     if not os.path.exists(inst_mesh_path):
         cmds.warning('Instant Mesh path not found!')
         return
     # Get current selection
     sel_obj = cmds.ls(sl=True)
     if sel_obj:
         print 'Processing Instant Mesh...'
         # if no polycount set just double the amount of the source object
         if not face_count:
             face_count = int(cmds.polyEvaluate(sel_obj, f=True))
             face_count *= 2
         face_count /= 2
         # Create temp file for OBJ export
         temp = tempfile.NamedTemporaryFile(prefix='instantMesh_',
                                            suffix='.obj',
                                            delete=False)
         temp_path = temp.name
         # Save the currently selected object as an OBJ
         cmds.file(temp_path, force=True, exportSelected=True, type="OBJ")
         # run instamesh command on the OBJ
         print temp_path
         print "Instant Mesh start"
         some_command = inst_mesh_path + " " + temp_path + " -o " + temp_path + " -f " + str(
             face_count) + " -D" + " -b"
         p = subprocess.Popen(some_command,
                              stdout=subprocess.PIPE,
                              shell=True)
         p.communicate()
         p.wait()
         print "Instant Mesh end"
         print some_command
         # import back the temp OBJ file
         returnedNodes = cmds.file(temp_path,
                                   i=True,
                                   type="OBJ",
                                   rnn=True,
                                   ignoreVersion=True,
                                   options="mo=0",
                                   loadReferenceDepth="all")
         # delete the temp file
         temp.close()
         # Select the imported nodes
         if returnedNodes:
             cmds.select(returnedNodes, r=True)
         print 'Instant Mesh done...'
     else:
         cmds.warning('No objects selected...')
Example #32
0
    def badNGons(self):
        sel = cmds.ls(sl=1)

        cmds.selectMode(q=1, co=1)

        cmds.polySelectConstraint(m=3, t=0x0008, sz=3)
        cmds.polySelectConstraint(dis=1)

        numPolys = cmds.polyEvaluate(fc=1)

        try:
            self.polyCountLabel.setText('Poly Counts: %s N-Gon(s)' %
                                        str(int(numPolys)))
        except:
            self.polyCountLabel.setText('Please Select a Mesh!')
Example #33
0
    def get_closest_vtx(self, element, obj):
        vtxs = cmds.polyEvaluate(obj, v=True)

        check_value = float('inf')
        current_vtx = ''
        element_pos = self.get_pos(element)

        for vtx in range(0, vtxs + 1):
            l = self.get_length(element_pos,
                                self.get_pos(obj + '.vtx[%s]' % vtx))
            if l < check_value:
                check_value = l
                match_l = vtx

        return match_l
Example #34
0
def find_same_poly(sel = True) : 
    # find similar polygon by count faces
    sels = mc.ls(sl = True)

    if sels : 
        numFace = mc.polyEvaluate(sels[0], f = True, fmt = True)

        matchPoly = []
        matchPoly.append(sels[0])

        mc.select(cl = True)
        allPlys = mc.ls(type = 'mesh', l = True)

        for each in allPlys : 
            transform = mc.listRelatives(each, p = True, f = True)[0]
            currentFaceCount = mc.polyEvaluate(each, f = True, fmt = True)
            
            if currentFaceCount == numFace : 
                matchPoly.append(transform)
                
        if sel : 
            mc.select(matchPoly)

        return matchPoly
Example #35
0
def vtxInRange(mesh, pos, dist):
    '''
    returns a list of vertices which are near the
    supplied position within the given distance param
    '''
    vtxList = []
    for i in range(0, cmds.polyEvaluate(mesh, vertex=True)):
        vtxPos = cmds.xform('{}.vtx[{}]'.format(mesh, i),
                            q=True,
                            ws=True,
                            t=True)
        currDist = self.distance(vtxPos, pos)
        if currDist > dist: continue
        vtxList.append(i)
    return vtxList
Example #36
0
def uvOrientationCheck():
    sel = cmds.ls(sl=True, l=True)
    offenders = []
    for s in sel:
        uvs = cmds.ls(cmds.polyListComponentConversion(s, toUV=True), fl=True)

        vMax = cmds.polyEvaluate(s, b2=True)[1][0]
        vMin = cmds.polyEvaluate(s, b2=True)[1][1]

        highestUV = ''
        lowestUV = ''
        for u in uvs:
            vValue = cmds.polyEditUV(u, q=True)[1]
            if vValue > vMax:
                vMax = vValue
                highestUV = u
            if vValue < vMin:
                vMin = vValue
                lowestUV = u

        highestVert = cmds.polyListComponentConversion(highestUV,
                                                       toVertex=True)
        lowestVert = cmds.polyListComponentConversion(lowestUV, toVertex=True)

        highestVertY = cmds.xform(highestVert, t=True, q=True, ws=True)[1]
        lowsetVertY = cmds.xform(lowestVert, t=True, q=True, ws=True)[1]

        if lowsetVertY < highestVertY:
            pass
        else:
            offenders.append(s)

    if len(offenders) > 0:
        cmds.select(offenders, r=True)
    else:
        print "All good so far."
Example #37
0
def udim_range():
    bake_sets = list(bake_set for bake_set in cmds.ls(type='VRayBakeOptions') \
        if bake_set != 'vrayDefaultBakeOptions')
    u_max = 0
    v_max = 0
    for bake_set in bake_sets:
        conn_list = cmds.listConnections(bake_set)
        if conn_list == None or len(conn_list) == 0:
            continue
        uv_info = cmds.polyEvaluate(conn_list[0], b2=True)
        if uv_info[0][1] > u_max:
            u_max = int(math.ceil(uv_info[0][1]))
        if uv_info[1][1] > v_max:
            v_max = int(math.ceil(uv_info[1][1]))
    return '1001-%d' % (1001 + u_max + (10 * v_max))
Example #38
0
    def estimate_num_samples(self, node):
        """ estimate how many random samples we need for grid or disk sampling """

        self._node = node
        emit_type = cmds.getAttr('{}.emitType'.format(node))
        if emit_type == 1:
            cell_size = cmds.getAttr(self._node + '.cellSize')
        elif emit_type == 2:
            cell_size = cmds.getAttr(self._node + '.minRadius') / math.sqrt(3)
        else:
            return

        in_mesh = node_utils.get_connected_in_mesh(self._node)
        area = cmds.polyEvaluate(in_mesh, worldArea=True)
        cmds.setAttr(self._node + '.numSamples', int(area/cell_size) * 5)
Example #39
0
def chkTopoOldNewMdl(*args):
	# Check Topology Difference Between Old Model and New Model #

	selLs = cmds.ls(sl=True)
	oldMdlLod03Grp = selLs[0]
	newMdlLod03Grp = selLs[1]

	oldMdlLs = cmds.listRelatives(oldMdlLod03Grp, ad=True, fullPath=True, type='mesh')
	newMdlLs = cmds.listRelatives(newMdlLod03Grp, ad=True, fullPath=True, type='mesh')

	difMdlLs = []
	for i in xrange(len(oldMdlLs)):
		oldMdlNumVertex = cmds.polyEvaluate(oldMdlLs[i], vertex=True)
		newMdlNumVertex = cmds.polyEvaluate(newMdlLs[i], vertex=True)

		if oldMdlNumVertex != newMdlNumVertex:
			difMdlLs.append(oldMdlLs[i])
			difMdlLs.append(newMdlLs[i])

	if difMdlLs:
		cmds.select(difMdlLs, r=True)
		cmds.warning('Selected objecs are have different topology.')
	else:
		cmds.select(cl=True)
 def remesh(self):
     targetCount = self.text_targetCount.toPlainText()
     try:
         if targetCount.endswith('%'):
             sel = cmds.ls(sl=1, o=1)
             sel = sel[0]
             currentFaceCount = int(cmds.polyEvaluate(sel, f=True))
             targetCount = 2 * int(
                 currentFaceCount * float(targetCount[:-1]) / 100)
         else:
             targetCount = int(targetCount)
     except:
         ld.msg('Please input a number or ratio!')
         return
     self.instantMeshes_remesh(targetCount)
Example #41
0
def softSelectToCluster(mesh):
	# Get the manipulator position for the selection
	cmds.setToolTo('Move')
	currentMoveMode = cmds.manipMoveContext('Move', query=True, mode=True) #Get the original mode
	cmds.manipMoveContext('Move', edit=True, mode=0) #set to the correct mode
	pos = cmds.manipMoveContext('Move', query=True, position=True) # get the position
	cmds.manipMoveContext('Move', edit=True, mode=currentMoveMode) # and reset

	# Grab the soft selection values using the API
	selection = om.MSelectionList()
	ssel = om.MRichSelection()
	ssel.getSelection(selection)

	dagPath = om.MDagPath()
	component = om.MObject()

	vertIter = om.MItSelectionList(selection, om.MFn.kMeshVertComponent)
	elements, weights = [], []

	# TODO Be a bit more explicit here with the mesh, its shapeNode, and the dagPath
	# so we can make sure we don't have multiple meshes with verts selected

	softSel = {}
	while not vertIter.isDone():
		vertIter.getDagPath(dagPath, component)
		dagPath.pop() #Grab the parent of the shape node
		node = dagPath.fullPathName()
		fnComp = om.MFnSingleIndexedComponent(component)
		getWeight = lambda i: fnComp.weight(i).influence() if fnComp.hasWeights() else 1.0

		for i in range(fnComp.elementCount()):
			softSel[fnComp.element(i)] = getWeight(i)
		vertIter.next()

	if not softSel:
		print "No Soft Selection"
		return

	# Build the Cluster and set the weights
	clusterNode, clusterHandle = cmds.cluster(mesh, name='softSel')
	vnum = cmds.polyEvaluate(mesh, vertex=1)
	weights = [softSel.get(i, 0.0) for i in range(vnum)]
	cmds.setAttr('{0}.weightList[0].weights[0:{1}]'.format(clusterNode, vnum-1), *weights, size=vnum)

	# Reposition the cluster
	cmds.xform(clusterHandle, a=True, ws=True, piv=(pos[0], pos[1], pos[2]))
	clusterShape = cmds.listRelatives(clusterHandle, c=True, s=True)
	cmds.setAttr(clusterShape[0] + '.origin', pos[0], pos[1], pos[2])
Example #42
0
    def validateMeshArg(self, mesh=None):
        '''
        Validates a mesh and returns a dict of data
        
        :param mesh: mesh to evaluate
        
        '''
        _mesh = None
        _skin = None
        if mesh is None:
            #if self.d_kws.get('sourceMesh'):
            #log.info("Using stored sourceMesh data")
            #sourceMesh = self.d_kws.get('sourceMesh')
            #else:
            log.info("No source specified, checking if selection found")
            _bfr = mc.ls(sl=True)
            if not _bfr:
                raise ValueError, "No selection found and no source arg"
            mesh = _bfr[0]

        _type = search.returnObjectType(mesh)

        if _type in ['mesh', 'nurbsCurve', 'nurbsSurface']:
            if _type in ['nurbsCurve', 'nurbsSurface']:
                raise NotImplementedError, "Haven't implemented nurbsCurve or nurbsSurface yet"
            log.info("Skinnable object '{0}', checking skin".format(mesh))
            _mesh = mesh
            _skin = skinning.querySkinCluster(_mesh) or False
            if _skin:
                log.info("Found skin '{0}' on '{1}'".format(_skin, _mesh))
        elif _type in ['skinCluster']:
            log.info("skinCluster '{0}' passed...".format(mesh))
            _skin = mesh
            _mesh = attributes.doGetAttr(_skin, 'outputGeometry')[0]
            log.info("Found: {0}".format(_mesh))
        else:
            raise ValueError, "Not a usable mesh type : {0}".format(_type)

        _shape = mc.listRelatives(_mesh, shapes=True, fullPath=False)[0]
        _return = {
            'mesh': _mesh,
            'meshType': _type,
            'shape': _shape,
            'skin': _skin,
            'component': data._geoToComponent.get(_type, False),
            'pointCount': mc.polyEvaluate(_shape, vertex=True)
        }
        return _return
Example #43
0
def shaders_export(id, shape, path):

    attributes = cmds.listAttr(shape)
    shadingGrp = cmds.listConnections(shape, type='shadingEngine')
    if shadingGrp != None:
        lenShadingGrp = ''
        lenShadingGrp = len(shadingGrp)
        ShapeListSG = []

        if lenShadingGrp > 1:
            if "Face_id" in attributes:
                print "ok"
            else:
                cmds.addAttr(shape, longName='Face_id', dt="string")

            shadingGrp = list(set(shadingGrp))

            for j in shadingGrp:
                cmds.hyperShade(o=j)
                assignSelected = cmds.ls(sl=1)
                SuperAttr = j + id + "#"

                for t in assignSelected:
                    if ".f" in t:
                        t_tmp = t.split(".f")
                        t = t_tmp[0].rpartition(':')[2]
                        t = t + ".f" + t_tmp[1]
                        vertexes = cmds.polyEvaluate(shape, v=True)
                        t = t + "$vertexes" + str(vertexes) + "$"
                        # t = "{}.f" + t_tmp[1]
                        SuperAttr = SuperAttr + t + ","
                ShapeAttr = cmds.getAttr(shape + '.Face_id')

                if ShapeAttr == None:
                    ShapeAttr = ''
                cmds.setAttr(shape + '.Face_id', ShapeAttr + "@" + SuperAttr, type="string")

            shader = cmds.ls(cmds.listConnections(shadingGrp), materials=1)
            shaderSG = shadingGrp + shader
            cmds.select(shaderSG, r=True, ne=True)

            cmds.file (path + id + ".mb", es=True, type='mayaBinary')

        if lenShadingGrp == 1:
            shader = cmds.ls(cmds.listConnections(shadingGrp), materials=1)
            shaderSG = shadingGrp + shader
            cmds.select(shaderSG, r=True, ne=True)
            cmds.file (path + id + ".mb", es=True, type='mayaBinary')
Example #44
0
def adaptPoly():

    selected = mc.ls(sl=True)
    comp_listRetopo = []
    for a in selected:
        listMesh = cmds.ls(a, dag=True, tl=1, type='mesh')
        listRetopo = cmds.listConnections(listMesh, type='polyRetopo')
        comp_listRetopo.append(listRetopo)

    flattened_Comp_listRetopo = []
    for x in comp_listRetopo:
        for y in x:
            flattened_Comp_listRetopo.append(y)

    srfAreaList = []
    for i in selected:
        srfObj = mc.polyEvaluate(str(i), a=True)
        srfAreaList.append(srfObj)

    objFCountList = []
    tObjFCountList = []
    bigValue = max(srfAreaList)
    minValue = min(srfAreaList)
    ratio = bigValue / minValue
    #if one of selected pieces is smaller then required ratio - increase FaceCount
    if ratio > 210:
        iterObj = iter(srfAreaList)
        for t in srfAreaList:
            objFCount = (10 * t) / minValue
            objFCountList.append(objFCount)
        iterObj = iter(objFCountList)
        for e in flattened_Comp_listRetopo:
            mc.setAttr((e + '.targetFaceCount'), next(iterObj))
    #reset Slider value to 0 and delete all list members
        mc.intSlider('slider', edit=True, value=0)
        del listas[:]
    else:
        for u in srfAreaList:
            objProc = (u * 100) / bigValue
            objFCount = (2000 * objProc) / 100
            objFCountList.append(objFCount)

        iterObj = iter(objFCountList)
        for e in flattened_Comp_listRetopo:
            mc.setAttr((e + '.targetFaceCount'), next(iterObj))
    #reset Slider value to 0 and delete all list members
        mc.intSlider('slider', edit=True, value=0)
        del listas[:]
Example #45
0
def edo_addSkinClusterAfterSkinCluster(m, zj, sk, weight):
    #m=m
    #weight=1
    #sk=sk
    if cmds.objExists(sk):
        return False
    cmds.select(m, r=1)
    sk = cmds.deformer(type='skinCluster', n=sk)[0]
    cmds.connectAttr(zj + '.worldMatrix[0]', sk + '.matrix[0]')
    mt = cmds.getAttr(zj + '.worldInverseMatrix[0]')
    cmds.setAttr(sk + '.bindPreMatrix[0]', mt, type='matrix')
    #cmds.getAttr(sk+'.bindPreMatrix[0]')
    cw = cmds.polyEvaluate(m, v=1)
    for i in range(0, cw):
        #print 'set '+sk+'.weightList['+str(i)+'].weights[0]    ....   1'
        cmds.setAttr(sk + '.weightList[' + str(i) + '].weights[0]', 1)
Example #46
0
def getPosTable(mesh, **kwargs):
    '''
    returns dictionary
    {vertId : dt.Point(x,y,z)}
    '''

    vertCount = mc.polyEvaluate(mesh, v=True)

    retDict = {}

    for vertId in range(vertCount):

        retDict[vertId] = dt.Point(
            *mc.pointPosition('%s.vtx[%d]' % (mesh, vertId), **kwargs))

    return retDict
Example #47
0
 def run(self):
     selected = mc.ls(sl=1)
     if not selected:
         self.fail_check(u"先手动选中模型大组")
         return
     selected = mc.ls(sl=1)[0]
     meshes = mc.listRelatives(selected, ad=1, type="mesh")
     for mesh in meshes:
         vtx_num = mc.polyEvaluate(mesh, vertex=1)
         if not vtx_num:
             continue
         vertexes = "%s.vtx[0:%s]" % (mesh, vtx_num - 1)
         mc.polyMoveVertex(vertexes, ld=(0, 0, 0))
         mc.select(clear=1)
     mc.select(selected, r=1)
     self.pass_check(u"所有的点已清零")
Example #48
0
def getInfo(sel):

    edgeCount = cmds.polyEvaluate(sel, e=True)
    cmds.select(str(sel[0]) + '.e[0:' + str(edgeCount) + ']')
    '''limit selection to hard edges with poly constraint'''
    cmds.polySelectConstraint(t=0x8000, sm=1, m=2)
    getHardEdges = cmds.ls(sl=True)
    cmds.select(r=True)
    ''' turns off poly constraint'''
    cmds.polySelectConstraint(t=0x8000, sm=1, m=0)
    cmds.select(sel, r=True)
    '''seperating hard edge number'''
    a = [x.split('[')[1] for x in getHardEdges]
    hardEdges = [x.strip(']') for x in a]

    return hardEdges, edgeCount
    def get_invalid(cls, instance):
        invalid = []

        meshes = cmds.ls(instance, type="mesh", long=True)
        for mesh in meshes:
            num_vertices = cmds.polyEvaluate(mesh, vertex=True)

            # Vertices from all edges
            edges = "%s.e[*]" % mesh
            vertices = cmds.polyListComponentConversion(edges, toVertex=True)
            num_vertices_from_edges = len_flattened(vertices)

            if num_vertices != num_vertices_from_edges:
                invalid.append(mesh)

        return invalid
Example #50
0
def getUV():
    # collection of uv coordinates
    cmds.select(geometryName)
    count = cmds.polyEvaluate(uv=True)
    listUVCount = range(1, count)
    c = 1
    uvList = []

    for i in listUVCount:
        while c != count:
            c += 1
            cmds.select(str(geometryName[0]) + '.map[' + str(c) + ']')
            positions = cmds.polyEditUV(q=True)
            uvList.append(positions)
            if c == count:
                return uvList
def XYZ_to_vtx(coordinate):
    # takes in coordinate [x,y,z] and returns the minimum distance
    min_dist = -1
    min_vtx = 0
    cmds.select("shirt")
    num_points = cmds.polyEvaluate(v=True)
    for n in range(num_points):
        v = get_position('shirt.vtx[' + str(n) + ']')
        dist = math.sqrt((coordinate[0]-v[0])**2 + (coordinate[2]-v[2])**2)
        if (min_dist < 0):
            min_dist = dist
            min_vtx = n
        if (min_dist > dist):
            min_dist = dist
            min_vtx = n
    return min_vtx
Example #52
0
def selectCreasesEdges(object):
    """
	This definition cleans Maya hierarchical polygonal conversion.

	:param object: Object to select creases edges. ( String )
	"""

    edges = cmds.ls(object + ".e[0:" +
                    str(cmds.polyEvaluate(object, edge=True) - 1) + "]",
                    fl=True)
    creaseEdges = [
        edge for edge in edges
        if cmds.polyCrease(edge, q=True, v=True)[0] > 0.0
    ]
    if creaseEdges:
        cmds.select(creaseEdges)
Example #53
0
def dm2skin_getVertexPositionsOverRange(mesh, startFrame=0, endFrame=1):
    """Gets a list of lists of vertex positions for the given mesh. One list for
    each frame between startFrame and endFrame."""
    numVerts = cmds.polyEvaluate(mesh, v=True)
    resultList = []
    for i in range(startFrame, endFrame + 1):
        tempList = []
        cmds.currentTime(i)
        for j in range(0, numVerts):
            tempPos = cmds.xform(mesh + '.vtx[' + str(j) + ']',
                                 q=True,
                                 ws=True,
                                 t=True)
            tempList.append(np.array([tempPos[0], tempPos[1], tempPos[2]]))
        resultList.append(tempList)
    return resultList
def pre_meshMirror(original, target, axis, position, search, replace):
    listTarget = target.split(', ')
    if len(original) == 0 or len(target) == 0:
        return
    type = mc.objectType(mc.listRelatives(original, c=1, s=1)[0])
    origCompCount = 0
    if type == 'mesh':
        origCompCount = mc.polyEvaluate(original, v=1)
    elif type == 'nurbsSurface':
        origShape = mc.listRelatives(original, c=1, s=1)
        origCompCount = mc.getAttr(origShape[0] +
                                   '.spansU') + mc.getAttr(origShape[0] +
                                                           '.spansV')
    for obj in listTarget:
        meshMirror(original, obj, type, origCompCount, axis, position, search,
                   replace)
Example #55
0
 def __init__(self, numberOfVertices=10):
     if not funnyPlane.plane:
         funnyPlane.plane = mc.polyPlane(sx=10, sy=10, w=10, h=10)[0]
     numVertices = mc.polyEvaluate(funnyPlane.plane, vertex=True)
     self.vertexList = []
     self.positions = []
     if numberOfVertices < numVertices:
         self.vertexList = random.sample(range(numVertices),
                                         numberOfVertices)
         for vertex in self.vertexList:
             position = mc.pointPosition(funnyPlane.plane + ".vtx[" +
                                         str(vertex) + "]")
             self.positions.append(position)
             mc.polyMoveVertex(funnyPlane.plane + ".vtx[" + str(vertex) +
                               "]",
                               translateY=2)
Example #56
0
    def bGQuads(self, _=False):
        bGsel = cmds.ls(sl=True)

        cmds.selectMode(q=True, co=True)

        cmds.polySelectConstraint(m=3, t=0x0008, sz=2)
        cmds.polySelectConstraint(dis=True)

        bGPolys = cmds.polyEvaluate(fc=True)

        try:
            cmds.textField(self.bG_output,
                           e=True,
                           tx=("%s 个四边面" % int(bGPolys)))
        except:
            cmds.textField(self.bG_output, e=True, tx=("请选择模型"))
def findFaces(mesh):
    faces = []
    faceCount = cmds.polyEvaluate(mesh, face=True)

    meshTransform = cmds.xform(mesh, query=True, matrix=True, worldSpace=True)

    for face in range(0, faceCount):
        faceName = mesh + ".f[" + str(face) + "]"
        vtxLst = cmds.polyInfo(faceName, faceToVertex=True)
        vtxIdx = str(vtxLst[0]).split()
        vtxIdx = vtxIdx[2:]
        """ Vertex positions """
        vtxA = cmds.getAttr(mesh + ".vt[" + vtxIdx[0] + "]")
        vtxB = cmds.getAttr(mesh + ".vt[" + vtxIdx[1] + "]")
        vtxC = cmds.getAttr(mesh + ".vt[" + vtxIdx[2] + "]")
        vtxD = cmds.getAttr(mesh + ".vt[" + vtxIdx[3] + "]")
        """ Make each vertex a list """
        vtxA = list(vtxA[0])
        vtxB = list(vtxB[0])
        vtxC = list(vtxC[0])
        vtxD = list(vtxD[0])
        """ Multiply verticies by transform matrix (convert to world space) """
        vtxA = matrixMult(meshTransform, vtxA)
        vtxB = matrixMult(meshTransform, vtxB)
        vtxC = matrixMult(meshTransform, vtxC)
        vtxD = matrixMult(meshTransform, vtxD)
        vertices = [vtxA, vtxB, vtxC, vtxD]
        normal = getNormal(vtxA, vtxB, vtxC)
        """ Getting center of the face by querying the position of the move manipulator """
        cmds.select(faceName)
        cmds.setToolTo('moveSuperContext')
        centerPos = cmds.manipMoveContext('Move', q=True, p=True)
        """ Get radius around center to place start/end point at """
        radius = [0.0, 0.0, 0.0]
        vecAB = convertToVec(vtxA, vtxB)
        vecAC = convertToVec(vtxA, vtxC)
        for axes in range(0, len(vecAB)):
            radius[axes] = ((vecAB[axes] + vecAC[axes]) / 2.0)

        faceInfo = {
            'normal': normal,
            'center': centerPos,
            'radius': radius,
            'vertices': vertices,
        }
        faces.append(faceInfo)
    return faces
Example #58
0
def set_UV_ratio(obj):
    try:
        print active_ratio
    except:
        om.MGlobal.displayError("Please pick a checker size first")
        return

    orig_sele = cmds.ls(sl=True, fl=True)
    if len(orig_sele) == 0:
        om.MGlobal.displayError("Select at least one object")
        return
    prog = 0.00
    cmds.progressBar(progressControl, edit=True, visible=True)
    cmds.progressBar(progressControl, edit=True, beginProgress=True)

    for i in range(0, len(orig_sele)):
        if (len(orig_sele) != 0):
            if (obj == 1):
                prog += (i * 1.000 / len(orig_sele) * 1.000) * 20
                cmds.progressBar(progressControl, edit=True, pr=prog)
            else:
                prog += (i * 1.000 / len(orig_sele) * 1.000) * 15
                cmds.progressBar(progressControl, edit=True, pr=4 + prog)
        cmds.select(cl=True)
        mel.eval("select " + orig_sele[i])
        current_ratio = get_sel_faces_UV_ratio(0)
        if current_ratio == 0:
            current_ratio = 1
        scale_factor = active_ratio / current_ratio
        scale_factor = math.sqrt(scale_factor)
        mel.eval("PolySelectConvert 4")
        UV_bounds = cmds.polyEvaluate(bc2=True)
        u_pivot = (UV_bounds[0][0] + UV_bounds[0][1]) / 2
        v_pivot = (UV_bounds[1][0] + UV_bounds[1][1]) / 2

        cmds.polyEditUV(pu=u_pivot,
                        pv=v_pivot,
                        su=scale_factor,
                        sv=scale_factor)

    cmds.select(cl=True)
    for i in range(0, len(orig_sele)):
        mel.eval("select -add " + orig_sele[i])

    cmds.progressBar(progressControl, edit=True, endProgress=True)
    cmds.progressBar(progressControl, edit=True, visible=False)
    om.MGlobal.displayInfo("Done")
Example #59
0
def get(sel, what):
    if what == "uvid_uv":
        selMesh = MFnMesh(sel)
        uvid_uv = []
        uvArray = selMesh.getUVs()
        for i in xrange(len(uvArray[0])):
            uvid_uv.append([uvArray[0][i], uvArray[1][i]])
        return uvid_uv
    elif what == "vtxid_uvid":
        vtxid_uvid = []
        selVtxIter = MItMeshVertex(sel)
        while not selVtxIter.isDone():
            vtxid_uvid.append(list(set(selVtxIter.getUVIndices()))[0])
            selVtxIter.next()
        return vtxid_uvid
    elif what == "bb":
        return cmds.polyEvaluate(sel, b=1)
Example #60
0
def return_max_vertex_skin_infs(skin_cluster, skin_mesh):
    """
    return_max_vertex_skin_infs('skinCluster1', 'Octopus_LOD0_Mesh')
    """
    vert_count = cmds.polyEvaluate(skin_mesh, v=1) - 1
    max_vert_infs = 0

    for i in range(0, vert_count):
        vert_name = "{}.vtx[{}]".format(skin_mesh, i)
        vert_infs = cmds.skinPercent(skin_cluster,
                                     vert_name,
                                     ignoreBelow=.001,
                                     q=1,
                                     t=None)
        if len(vert_infs) > max_vert_infs:
            max_vert_infs = len(vert_infs)
    return max_vert_infs