def maxMrg(*args):
	cmds.polyMergeVertex(d=1)
def minMrg(*args):
	cmds.polyMergeVertex(d=.01)
def mrg(*args):
	mrgDis = cmds.floatField("mrgeField", q=True, v=True)
	cmds.polyMergeVertex(d=mrgDis)
def movePolysFromObj():
    '''
    # 1. Select faces
    # 2. Shift-select targetObj
    # 3. Run
    '''
    selFaces = mc.ls(os=1, fl=1)[:-1]
    selFacesIds = [int(faceName.split('[')[1][:-1]) for faceName in selFaces]
    
    # target object is the last selected item
    targetObj = mc.ls(os=1, fl=1)[-1]
    targetObjParent = mc.listRelatives(targetObj, p=1)[0]
    
    # delete the parentConstraint if necessary
    targetObjChildren = mc.listRelatives(targetObj, c=1, type='parentConstraint')
    if not targetObjChildren == None:
        mc.delete(targetObjChildren)
    
    srcObj = selFaces[0].split('.')[0]
    tempObj = mc.duplicate(srcObj, n='tempObj')[0]
    mc.delete(selFaces)
    
    facesToCopy = [faceName.replace(srcObj, tempObj) for faceName in selFaces]
    mc.select(facesToCopy, r=1)
    meval('InvertSelection;')
    mc.delete()
    
    combinedGeo = mc.polyUnite(tempObj, targetObj, ch=0, n='combinedGeo')[0]
    mc.rename(combinedGeo, targetObj)
    mc.parent(targetObj, targetObjParent)
    mc.polyMergeVertex(targetObj, d=0.001, ch=0)
    mc.delete(tempObj)
    mc.select(srcObj, r=1)
Exemple #5
0
 def vertexMergeTool(self):
     length = len(self.getSelection())
     if self.getSelection(
     ) == 'None':  # set tool to the merge vertex tool if no verts are selected
         cmds.setToolTo('polyMergeVertexContext')
     else:  # if verts are already selected, then run the commands below
         if self.getType(
                 0
         ) == 'vertex':  # check to see if the selection is of the vertex type, in case the mask is set to vert but the sel is edge etc.
             if length == 2:
                 cmds.polyMergeVertex(alwaysMergeTwoVertices=True)
             elif length > 2:
                 cmds.polyMergeVertex(distance=0.001)
                 newLength = len(self.getSelection())
                 if newLength == length:  # Nothing was merged because the before and after are the same, state so
                     cmds.headsUpMessage(str(length) +
                                         ' Verts Selected - 0 Merged',
                                         verticalOffset=-100,
                                         horizontalOffset=-200)
                 else:  # means a merge did happen, so tell how many were merged and how many are left now
                     cmds.headsUpMessage('FROM ' + str(length) + ' TO ' +
                                         str(newLength),
                                         verticalOffset=-100,
                                         horizontalOffset=-200)
         else:
             cmds.warning('Vertex not selected')
def checkMergedVerts(eachGeo):
	"""
	Used to find any verts that occupy the same space and merges them. THIS WILL INCREASE PUBLISH TIME!
	DO NOT RUN THIS ON A RIGGED GEO!!
	@param eachGeo: Maya transform
	@type eachGeo: String
	"""
	badVerts = []
	badGeo = []
	toleranceOf = 0.001
	vertCount = cmds.polyEvaluate(eachGeo, v = True)
	myVerts = {}

	try:
		for x in range(0, vertCount):
			myVerts['%s.vtx[%s]' % (eachGeo, x)] = cmds.xform('%s.vtx[%s]' % (eachGeo, x), query = True, translation=True, ws= True)
		dupCheck = []

		for key,var in myVerts.items():
			if not var in dupCheck:
				dupCheck.append(var)
			else:
				badVerts.append(key)
				if eachGeo not in badGeo:
					badGeo.append(eachGeo)
		if len(badGeo) >  0:
			for eachGeo in badGeo:
				cmds.polyMergeVertex(eachGeo, d = toleranceOf, am = 1, ch = 0)
				cmds.select(eachGeo, r = True)
				mel.eval("polyCleanupArgList 3 { \"0\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"1e-005\",\"0\",\"1e-005\",\"0\",\"1e-005\",\"0\",\"-1\",\"1\" };")
				print 'Merged verts on %s with a tolerance of %s' % (eachGeo, toleranceOf)
		else:
			pass
	except:
		pass
def dup(*args):
	neg = cmds.checkBox("negChck", q=True, v=True)
	mrge = cmds.checkBox("mrgChck", q=True, v=True)
	dupAx = cmds.radioButtonGrp("axChck", q=True, sl=True)
	selected = cmds.ls(sl=True)
	print(mrge)
	
	if(dupAx==1):
		scaD = ".scaleX"
	if(dupAx==2):
		scaD = ".scaleY"
	if(dupAx==3):
		scaD = ".scaleZ"
		
	if(neg==1):
		scaVal = -1
	else:
		scaVal = 1
	
	newDup = cmds.duplicate(rr=True)
	cmds.setAttr(newDup[0] + scaD, scaVal)
		
	if (mrge==1):
		cmds.polyUnite(selected, newDup[0])
		cmds.polyMergeVertex(d=1)	
	else:	
		None
  def generate_kink_peice(cls, block_width):
    components = []
    boolean = []
    for x in range(0, block_width + 1):
      hole = cmds.polyCylinder(name=get_unique_name(cls.get_prefix(), "Hole"), radius=Constants["perforation_radius"], height=Constants["block_depth_unit"] + 0.2)
      boolean.append(hole[0])
      cmds.rotate('90deg', 0, 0, hole[0])
      cmds.move(Constants["block_width_unit"] * x , 0, half(Constants["block_depth_unit"]), hole[0])

    cube = cmds.polyCube(sx=5,sy=2,sz=2,name=get_unique_name(cls.get_prefix(), "block"), width=block_width, height=Constants["block_height_unit"], depth=Constants["block_depth_unit"])
    components.append(cube[0])
    cmds.delete(cube[0] + ".f[40:47]")
    cmds.move(half(block_width * Constants["block_width_unit"]), 0, half(Constants["block_depth_unit"]), cube)

    #caps
    cap_one = cmds.polyCylinder(sc=1, sy=2, radius=half(Constants["block_height_unit"]), height=Constants["block_depth_unit"],name=get_unique_name(cls.get_prefix(), "cap"))
    cmds.rotate('90deg',0,0,cap_one[0])
    cmds.move(0,0,half(Constants["block_depth_unit"]),cap_one[0])
    cmds.delete(cap_one[0] + ".f[0:3]", cap_one[0] + ".f[14:23]", cap_one[0] + ".f[34:43]", cap_one[0] + ".f[54:63]", cap_one[0] + ".f[74:79]")
    components.append(cap_one[0])

    #caps
    cap_two = cmds.polyCylinder(sc=1, sy=2, radius=half(Constants["block_height_unit"]), height=Constants["block_depth_unit"])
    cmds.rotate('90deg','180deg',0,cap_two[0])
    cmds.delete(cap_two[0] + ".f[0:3]", cap_two[0] + ".f[14:23]", cap_two[0] + ".f[34:43]", cap_two[0] + ".f[54:63]", cap_two[0] + ".f[74:79]")
    cmds.move(block_width,0,half(Constants["block_depth_unit"]),cap_two[0])
    components.append(cap_two[0])

    solid = cmds.polyUnite(components, name=get_unique_name(cls.get_prefix(), ""))
    boolean_group = cmds.polyUnite(boolean, name=get_unique_name(cls.get_prefix(),"boolean"))
    cmds.polyMergeVertex( solid[0], d=0.15 )
    cmds.delete(solid[0],ch=1)
    return cmds.polyBoolOp( solid[0], boolean_group[0], op=2, n=get_unique_name(cls.get_prefix(), "") )
Exemple #9
0
def dup(*args):
	neg = cmds.checkBox("negChck", q=True, v=True)
	mrge = cmds.checkBox("mrgChck", q=True, v=True)
	dupAx = cmds.radioButtonGrp("axChck", q=True, sl=True)
	selected = cmds.ls(sl=True)
	print(mrge)
	
	if(dupAx==1):
		scaD = ".scaleX"
	if(dupAx==2):
		scaD = ".scaleY"
	if(dupAx==3):
		scaD = ".scaleZ"
		
	if(neg==1):
		scaVal = -1
	else:
		scaVal = 1
	
	newDup = cmds.duplicate(rr=True)
	cmds.setAttr(newDup[0] + scaD, scaVal)
		
	if (mrge==1):
		cmds.polyUnite(selected, newDup[0])
		cmds.polyMergeVertex(d=1)	
	else:	
		None
Exemple #10
0
def mirrorGeo():
    # Variables and selection
    mirrorMode = cmds.radioButtonGrp('mirrorMode', q=True, sl=True)
    mDir = cmds.radioButtonGrp('mDir', q=True, sl=True)
    sel = cmds.ls(sl=True)

    # Duplication type
    if (mirrorMode == 1):
        cmds.duplicate()
    elif (mirrorMode == 2):
        cmds.instance()
    else:
        newHalf = cmds.duplicate()

    # Scaling
    if (mDir == 1):
        cmds.scale(-1, 1, 1)
    elif (mDir == 2):
        cmds.scale(1, -1, 1)
    else:
        cmds.scale(1, 1, -1)

    # Merging Copy
    if (mirrorMode == 3):
        cmds.select(sel[0], r=True)
        cmds.select(newHalf, add=True)
        cmds.polyUnite()
        cmds.ConvertSelectionToVertices()
        cmds.polyMergeVertex(d=0.001, am=1, ch=1)
        cmds.select(sel[0])
Exemple #11
0
 def CombineAndMerge(self, name="combined"):
     original = cmds.ls(sl=True) or []
     cmds.delete(constructionHistory=True)
     cmds.polyUnite(ch=1, mergeUVSets=1, centerPivot=True, name=name)
     cmds.polyMergeVertex(d=0.001, am=0, ch=1)
     cmds.delete(constructionHistory=True)
     cmds.delete(original)
Exemple #12
0
def unbevel():
    """
    Unbevel beveled edges.

    Select Edges along a bevel you want to unbevel. Make sure the edge is not
    connected to another edge from another bevel. This will cause the script
    to get confused.
    """
    selected = mampy.complist()
    for edge in selected:

        # cmds.select(edge.cmdslist(), r=True)
        merge_list = ComponentList()
        for each in edge.get_connected_components():
            outer_edges, inner_verts = get_outer_and_inner_edges_from_edge_loop(each)

            edge1, edge2 = outer_edges
            line1 = Line3D(edge1[0].bbox.center, edge1[1].bbox.center)
            line2 = Line3D(edge2[0].bbox.center, edge2[1].bbox.center)
            intersection = line1.shortest_line_to_other(line2)
            inner_verts.translate(t=intersection.sum() * 0.5, ws=True)
            merge_list.append(inner_verts)

        # Merge components on object after all operation are done. Mergin
        # before will change vert ids and make people sad.
        cmds.polyMergeVertex(merge_list.cmdslist(), distance=0.001)
Exemple #13
0
def movePolysFromObj():
    """
    # 1. Select faces
    # 2. Shift-select targetObj
    # 3. Run
    """
    selFaces = mc.ls(os=1, fl=1)[:-1]
    selFacesIds = [int(faceName.split("[")[1][:-1]) for faceName in selFaces]

    # target object is the last selected item
    targetObj = mc.ls(os=1, fl=1)[-1]
    targetObjParent = mc.listRelatives(targetObj, p=1)[0]

    # delete the parentConstraint if necessary
    targetObjChildren = mc.listRelatives(targetObj, c=1, type="parentConstraint")
    if not targetObjChildren == None:
        mc.delete(targetObjChildren)

    srcObj = selFaces[0].split(".")[0]
    tempObj = mc.duplicate(srcObj, n="tempObj")[0]
    mc.delete(selFaces)

    facesToCopy = [faceName.replace(srcObj, tempObj) for faceName in selFaces]
    mc.select(facesToCopy, r=1)
    meval("InvertSelection;")
    mc.delete()

    combinedGeo = mc.polyUnite(tempObj, targetObj, ch=0, n="combinedGeo")[0]
    mc.rename(combinedGeo, targetObj)
    mc.parent(targetObj, targetObjParent)
    mc.polyMergeVertex(targetObj, d=0.001, ch=0)
    mc.delete(tempObj)
    mc.select(srcObj, r=1)
Exemple #14
0
    def deleteCtrlEdit(self):
        """
    This function is run when we exit ctrl edit stage
    """
        # We delete the objects history so that the curves no longer influence the object
        for i in self.Objects:
            #print "Smoothing ", i
            #CreateRelationships.averageInsideVertices(i)
            cmds.select(i)
            mel.eval('SculptGeometryTool;')
            mel.eval('artPuttyCtx -e -mtm "relax" `currentCtx`;')
            mel.eval('artPuttyCtx -e -opacity 0.3 `currentCtx`;')
            mel.eval('artPuttyCtx -e -clear `currentCtx`;')
            mel.eval('setToolTo $gMove;')
            cmds.delete(i, ch=True)

        # Need to give a better name
        # We then delete the curves and combine the geometry based on the relationship
        cmds.select("*Curve*")
        cmds.delete()
        CreateRelationships.findRelationships(self.relationshipList)

        # We combine the objects together and merge the matching vertices
        cmds.select(self.Objects)
        mesh = cmds.polyUnite(n=self.mesh, ch=0)
        cmds.polyMergeVertex(self.mesh, d=0.0001, am=True, ch=0)

        #We reset the relationshiplist and object
        self.Objects = []
        self.relationshipList = []

        #We delete the edit window
        if cmds.window(self.editWindowID, exists=True):
            cmds.deleteUI(self.editWindowID)
Exemple #15
0
def getcuthead():
    seledge = mc.ls(sl=True)
    basename = seledge[0].split('.')
    if len(basename) > 1:
        if basename[1].find('e') > -1:
            basevtx = mc.polyEvaluate(basename[0], v=True)
            mc.DetachEdgeComponent()
            mc.select(basename[0])
            mc.ExtractFace()
            cuts = mc.ls(sl=True)
            mc.duplicate(cuts[0], n='cuthead', rr=True)
            mc.move(1, 0, 0, 'cuthead')
            mc.select(cuts[0], cuts[1])
            mc.CombinePolygons()
            newbase = mc.ls(sl=True)
            mc.polyMergeVertex(newbase[0] + '.vtx[0:99999]',
                               d=.00001,
                               am=1,
                               ch=1)
            mc.select(newbase)
            mc.DeleteHistory()
            if basevtx == mc.polyEvaluate(newbase, v=True):
                mm.eval('print "/////点数一致,切头成功"')
            else:
                mc.warning("点数不一致,切头失败!!!")
        else:
            mc.warning("请选择模型环线执行!!!")
    else:
        mc.warning("请选择模型环线执行!!!")


#shuai_autoFacialRig()
def main(array,flag1,flag2):
    if flag2 == 'None':
        c1 = creatCurve(array[0],array[1])
        c2 = creatCurve(array[-1],array[-2])
    elif flag2 == '1':
        c1 = creatCurve(array[0],array[-2])
        c2 = creatCurve(array[1],array[-1])
    else:
        c1 = creatCurve(array[0],array[-1])
        c2 = creatCurve(array[1],array[-2])
    cmds.loft( c1, c2, ch=True, rn=True, ar=True, po = True )
    cmds.delete(c1,c2)
    if flag1:
        obj0 = array[0].split('.')[0]
        obj1 = cmds.ls(sl = True, fl = True)[0]
        cmds.polyUnite(obj0,obj1)
        obj2 = cmds.ls(sl = True, fl = True)[0]
        array1 = []
        for a in array:
            a = obj2 + '.' + a.split('.')[1]
            array1.append(a)
        cmds.select(cmds.polyListComponentConversion(obj2, tv = True))
        n0 = cmds.ls(sl = True, fl = True)
        if len(array) == 4:
            cmds.select(n0[-4:])
        else:
            cmds.select(n0[-3:])
        cmds.select(array1,add = True)
        cmds.polyMergeVertex(d = 0.001)
        cmds.select(obj2)
Exemple #17
0
    def merge_tree(self):
        segmentsList = cmds.ls('treePart*')
        foliageList = cmds.ls('leaves*')

        if len(segmentsList) < 3:
            treeTrunk = segmentsList[0]
        else:
            treeTrunk = cmds.polyUnite(segmentsList)

        newTree = cmds.duplicate(treeTrunk, name='miniTreeTrunk')
        cmds.polyMergeVertex(newTree)
        cmds.sets(newTree, e=1, forceElement=treeTrunkShaderSG)
        cmds.delete(treeTrunk)

        if len(foliageList) < 3:
            leaves = foliageList[0]
        else:
            leaves = cmds.polyUnite(foliageList)

        newLeaves = cmds.duplicate(leaves, name='miniTreeFoliage')
        cmds.sets(newLeaves, e=1, forceElement=foliageShaderSG)
        cmds.delete(leaves)

        segmentsList = cmds.ls('treePart*')
        if len(segmentsList) > 0:
            cmds.delete(segmentsList)

        foliageList = cmds.ls('leaves*')
        if len(foliageList) > 0:
            cmds.delete(foliageList)
def centerMergeVerts(dag, firstVerticesList, secondVerticesList):
    vertsToSelectSet = set()
    vertsProcessed = list()

    for a in range(len(firstVerticesList)):
        if firstVerticesList[a] in vertsProcessed:
            continue
        v1_path = '%s.vtx[%s]' % (dag.fullPathName(), firstVerticesList[a])
        v2_path = '%s.vtx[%s]' % (dag.fullPathName(), secondVerticesList[a])
        if v1_path == v2_path:
            continue
        vertsToSelectSet.add(v1_path)
        vertsToSelectSet.add(v2_path)
        v1_pos = cmds.xform(v1_path,
                            query=True,
                            translation=True,
                            worldSpace=True)
        v2_pos = cmds.xform(v2_path,
                            query=True,
                            translation=True,
                            worldSpace=True)
        vAvg_pos = [((v1_pos[0] + v2_pos[0]) / 2.0),
                    ((v1_pos[1] + v2_pos[1]) / 2.0),
                    ((v1_pos[2] + v2_pos[2]) / 2.0)]
        vertsProcessed.append(firstVerticesList[a])
        cmds.xform(v1_path, translation=vAvg_pos, worldSpace=True)
        cmds.xform(v2_path, translation=vAvg_pos, worldSpace=True)

    cmds.select(list(vertsToSelectSet), replace=True)
    cmds.polyMergeVertex()
Exemple #19
0
def makePipe(circle, pipeCurve):
	pipeSweep = sweepPipe(circle, pipeCurve)
	nurbsPipe = cmds.loft(pipeSweep, degree=1, reverseSurfaceNormals=True)
	polyPipe = cmds.nurbsToPoly(nurbsPipe[0], name="fastPipe", format=3, matchNormalDir=True, polygonType=1)
	cmds.polyMergeVertex(polyPipe[0], d=0.1, alwaysMergeTwoVertices=True)
	cmds.delete(pipeSweep[0], nurbsPipe[0], circle[0], pipeCurve[0])
	cmds.select(polyPipe)
Exemple #20
0
 def makePairs(self):
     sel = cmds.ls(os=1)
     garments = cmds.listRelatives(sel[0])  # len(garments)
     patterns = cmds.listRelatives(sel[1])  # len(patterns)
     retopos = cmds.listRelatives(sel[2])  # len(retopos)
     retopos_BB_width = {}
     retopos_BB_length = {}
     retopos_BB_center = {}
     patterns_BB_width = {}
     patterns_BB_length = {}
     patterns_BB_center = {}
     # In case that uv doesn't exists.
     cmds.select(retopos, r=1)
     mel.eval("performPolyAutoProj 0;")
     cmds.select(sel, r=1)
     # In case wrong bb
     for i in retopos:
         cmds.polyMergeVertex(i, d=0.001)
     # Matching
     for i in retopos:
         BB = cmds.polyEvaluate(i, b=1)
         retopos_BB_width[i] = BB[0][1] - BB[0][0]
         retopos_BB_length[i] = BB[1][1] - BB[1][0]
         retopos_BB_center[i] = [(BB[0][1] + BB[0][0]) / 2,
                                 (BB[1][1] + BB[1][0]) / 2]
     for i in patterns:
         BB = cmds.polyEvaluate(i, b=1)
         patterns_BB_width[i] = BB[0][1] - BB[0][0]
         patterns_BB_length[i] = BB[1][1] - BB[1][0]
         patterns_BB_center[i] = [(BB[0][1] + BB[0][0]) / 2,
                                  (BB[1][1] + BB[1][0]) / 2]
     pair_pattern_retopo = {}  # len(pair_pattern_retopo)
     for i in patterns:
         for j in retopos:
             if      abs(patterns_BB_width[i] - retopos_BB_width[j])         < 1 \
                 and abs(patterns_BB_length[i] - retopos_BB_length[j])       < 1 \
                 and abs(patterns_BB_center[i][0] - retopos_BB_center[j][0]) < 1 \
                 and abs(patterns_BB_center[i][1] - retopos_BB_center[j][1]) < 1:
                 pair_pattern_retopo[i] = j
     for i in pair_pattern_retopo:
         cmds.transferAttributes(i, pair_pattern_retopo[i], transferUVs=1)
     for i in pair_pattern_retopo:
         cmds.select(pair_pattern_retopo[i], i, r=1)
         cmds.CreateWrap()
     for i in pair_pattern_retopo:
         pairGarment = i[:-8]
         pattern = i
         blendObjs = [pairGarment, pattern]  # 0: target 1: origin
         blendName = cmds.blendShape(blendObjs,
                                     o='world',
                                     n='clothTransfer#')
         cmds.hide(sel[1])
         cmds.displaySurface(sel[0], x=1)
     cmds.hide(sel[1])
     cmds.displaySurface(sel[0], x=1)
     layerName = cmds.createDisplayLayer(n="garment#", e=1)
     cmds.editDisplayLayerMembers(layerName, sel[0])
     cmds.setAttr(layerName + '.displayType', 2)
Exemple #21
0
def mirrorPieces(arg):

    L = mc.radioButton(buttomL, q=1, select=True)
    R = mc.radioButton(buttomR, q=1, select=True)
    C = mc.radioButton(buttomC, q=1, select=True)
    if L:
        side = 'L'
    elif R:
        side = 'R'
    elif C:
        side = 'C'
    sel = mc.ls(sl=True)
    for o in sel:  # Mirror the piece
        if mc.nodeType(mc.listRelatives(o)[0]) == 'mesh':
            if mc.objExists(o + '_mirror') == False:
                mirroredGeo = ''
                attrs = mc.listAttr(o, keyable=1)
                for attr in attrs:
                    mc.setAttr(o + "." + attr, lock=0)
                mc.xform(o, ws=True, piv=(0, 0, 0))
                mc.makeIdentity(o,
                                translate=1,
                                rotate=1,
                                scale=True,
                                apply=True)
                mirroredGeo = mc.duplicate(o, n=o + '_mirror')[0]
                mc.setAttr(mirroredGeo + '.scaleX', -1)
                mc.makeIdentity(mirroredGeo,
                                translate=1,
                                rotate=1,
                                scale=True,
                                apply=True)
                mc.polyNormal(mirroredGeo, normalMode=0, userNormalMode=0)
                if 'L_' in mirroredGeo:
                    mc.rename(mirroredGeo, o.replace('L_', 'R_'))
                elif 'R_' in mirroredGeo:
                    mc.rename(mirroredGeo, o.replace('R_', 'L_'))
                elif 'Left' in mirroredGeo:
                    mc.rename(mirroredGeo, o.replace('Left', 'Right'))
                elif 'Right' in mirroredGeo:
                    mc.rename(mirroredGeo, o.replace('Right', 'Left'))
                elif 'Mid' or 'C_' or 'mid' in mirroredGeo or None == mirroredGeo:
                    mc.polyUnite(o,
                                 mirroredGeo,
                                 name=str(o),
                                 constructionHistory=1,
                                 mergeUVSets=1,
                                 caching=True)
                    mc.delete(mirroredGeo, ch=True)
                    mc.rename(mirroredGeo, str(o))
                    mc.polyMergeVertex(mirroredGeo, d=0.379)
            else:
                print 'Ya existe el mirror.'
        else:
            print 'No es una geometria'
Exemple #22
0
def setup_scene():
    #manually create a simple tetrahedron
    p1 = cmds.polyCreateFacet(p=[(0, 0, 0), (1, 0, 0), (0, 0, 1)])
    p2 = cmds.polyCreateFacet(p=[(0, 0, 0), (0, 1, 0), (1, 0, 0)])
    p3 = cmds.polyCreateFacet(p=[(0, 0, 0), (0, 0, 1), (0, 1, 0)])
    p4 = cmds.polyCreateFacet(p=[(0, 0, 1), (1, 0, 0), (0, 1, 0)])
    cmds.polyMergeVertex(cmds.polyUnite(p1, p2, p3, p4, ch=0, name="cage"),
                         ch=0)
    poly_map = [[
        "cage.vtx[0]",
        [
            ("cage.vtx[0]", "cage.vtx[2]", "cage.vtx[3]"),
            ("cage.vtx[0]", "cage.vtx[3]", "cage.vtx[1]"),
            ("cage.vtx[0]", "cage.vtx[1]", "cage.vtx[2]"),
        ]
    ],
                [
                    "cage.vtx[1]",
                    [
                        ("cage.vtx[1]", "cage.vtx[0]", "cage.vtx[3]"),
                        ("cage.vtx[1]", "cage.vtx[3]", "cage.vtx[2]"),
                        ("cage.vtx[1]", "cage.vtx[2]", "cage.vtx[0]"),
                    ]
                ],
                [
                    "cage.vtx[2]",
                    [
                        ("cage.vtx[2]", "cage.vtx[3]", "cage.vtx[0]"),
                        ("cage.vtx[2]", "cage.vtx[1]", "cage.vtx[3]"),
                        ("cage.vtx[2]", "cage.vtx[0]", "cage.vtx[1]"),
                    ]
                ],
                [
                    "cage.vtx[3]",
                    [
                        ("cage.vtx[3]", "cage.vtx[2]", "cage.vtx[1]"),
                        ("cage.vtx[3]", "cage.vtx[1]", "cage.vtx[0]"),
                        ("cage.vtx[3]", "cage.vtx[0]", "cage.vtx[2]"),
                    ]
                ]]
    #debug tetra
    """
	for p in poly_map:
		tris = p[1]
		for t in tris:
			pnts = []
			for vert in t:
				pnt = utils.pnt(vert)
				pnts.append([pnt.x, pnt.y, pnt.z])
			cmds.polyCreateFacet(p=pnts)
	"""

    cage = MayaPolyWrapper(poly_map)
    loc = utils.loc([.1, .1, .1])
    return cage, loc
Exemple #23
0
def mergeVertex():
    """merge vertex"""
    sel = cmds.ls(sl=True)
    if sel:
        try:
            for node in sel:
                cmds.select(node, r=True)
                cmds.polyMergeVertex(distance=0.007, am=True, ch=True)
        except:
            pass
        cmds.select(sel, r=True)
Exemple #24
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
Exemple #25
0
def createBaseMesh():
    ob = cmd.ls(sl=True)[0]
    if (cmd.nodeType(ob) == 'transform') and (cmd.attributeQuery(
            'name', node=ob, exists=True)):

        #initialize
        merge = True
        name = cmd.getAttr('%s.name' % ob)
        frames = cmd.getAttr('%s.count' % ob)
        ctlObj = cmd.getAttr('%s.myCtl' % ob)
        thresh = 0.015
        extrudeAmt = 0.2
        edgeAmt = 0.05
        newGp = cmd.group(em=True, w=True, n='%s_GEO_GP' % name)
        cmd.addAttr(newGp, ln='name', dt='string')
        cmd.setAttr("%s.name" % newGp, name, type='string')

        #create the new objects
        for i in range(1, frames + 1):
            cmd.setAttr('%s.frame' % ctlObj, i)
            newName = '%s_%02d_GEO' % (name, i)
            newOb = cmd.duplicate(ob, n=newName)[0]
            cmd.setAttr('%s.v' % newOb, 0)
            #insert a handler here to detect double faces or bad geo
            if merge:
                cmd.polyMergeVertex(newOb, ch=1, d=thresh)
            selectBorderEdges(newOb)
            cmd.polyExtrudeEdge(ch=1, d=2, lty=edgeAmt)
            cmd.polyExtrudeFacet(newOb, ch=1, kft=True, ltz=extrudeAmt, d=2)
            cmd.select(newOb)
            mel.eval(
                'polyCleanupArgList 4 { "0","1","1","0","1","0","0","0","0","1e-005","0","1e-005","0","1e-005","0","-1","0","0"}'
            )
            cmd.polySoftEdge(newOb, ch=1, a=180)
            cmd.parent(newOb, newGp)
            cmd.setKeyframe('%s.v' % newOb, t=[i - 1, i + 1], v=0)
            cmd.setKeyframe('%s.v' % newOb, t=i, v=1)
            for xyz in ['x', 'y', 'z']:
                cmd.setAttr('%s.t%s' % (newOb, xyz), 0)
            cmd.delete(newOb, ch=True)
            shit = cmd.ls('*%s*' % newName, io=True, type='mesh')
            if shit:
                cmd.delete(shit)

            #check for non-manifold and fix
            if (cmds.polyInfo(newOb, nme=True, nmv=True, nue=True, nuv=True)):
                print('%s had nonmanifold Geo, attempting fix...' % newOb)
                mel.eval(
                    'polyCleanupArgList 4 { "0","1","0","0","0","0","0","0","0","1e-005","0","1e-005","0","1e-005","0","1","0","0" }'
                )
    else:
        cmd.error('You must select only one mesh object')
Exemple #26
0
def makeTetra(size):
    
    pointA = [0, 0, 0]
    pointB = [size, 0, 0]    
    pointC = [size/2.0, 0, 0]
    
    # set the Z position for C
    pointC[2] = math.sqrt((size*size) - (size/2.0 * size/2.0))
    pointE = [0, 0, 0]
    
    # average the A, B, and C to get E
    # first add all the values
    for i in range(0,3):
        pointE[i] += pointA[i]
        pointE[i] += pointB[i]
        pointE[i] += pointC[i]
    
    # now divide by 3
    for i in range(0,3):
        pointE[i] = pointE[i] / 3.0
        
    # start point D with the X and Z coordinates of point E
    pointD = [0, 0, 0]
    pointD[0] = pointE[0]
    pointD[2] = pointE[2]
    
    distanceAE = math.sqrt((pointE[0] * pointE[0]) + (pointE[2] * pointE[2]))
    
    # set the Y coordinate of point D
    pointD[1] = math.sqrt((size*size) - (distanceAE * distanceAE))
    
    faces = []
    faces.append(cmds.polyCreateFacet(p=[pointA, pointB, pointC], texture=1))
    faces.append(cmds.polyCreateFacet(p=[pointA, pointD, pointB], texture=1))
    faces.append(cmds.polyCreateFacet(p=[pointB, pointD, pointC], texture=1))
    faces.append(cmds.polyCreateFacet(p=[pointC, pointD, pointA], texture=1))

    cmds.select(faces[0], replace=True)
    for i in range(1, len(faces)):
        cmds.select(faces[i], add=True)

    obj = cmds.polyUnite()
    
    cmds.select(obj[0] + ".vtx[:]")
    cmds.polyMergeVertex(distance=0.0001)
    
    cmds.select(obj[0])
    
    cmds.move(-pointE[0], 0, -pointE[2])
    cmds.xform(pivots=(pointE[0], 0, pointE[2]))
    cmds.makeIdentity(apply=True)
    cmds.delete(ch=True)
Exemple #27
0
def cleanUpforEdit2(locatorGroup, Objects, relationshipList, mesh):
    """
  This function is to clean up the mesh and average the inside vertices after deformation.
  Args:
    locatorGroup: The locator group to delete
    Objects: The objects to clean up
    relationshipList: The relationship list to attach the child back to the parent
    mesh: The initial mesh to delete
  """

    # We first delete the locators
    cmds.delete(locatorGroup)
    # We also delete the initial mesh
    cmds.delete(mesh)

    # We then delete the objects history so that the curves no longer influence the object
    for i in Objects:
        cmds.delete(i, ch=True)

    # Need to give a better name
    # We then delete the curves and combine the geometry based on the relationship
    cmds.select("*Curve*")
    cmds.delete()
    CreateRelationships.findRelationships(relationshipList)

    # We average out the vertices for each part
    for i in Objects:
        print "Smoothing ", i
        CreateRelationships.averageInsideVertices(i)
        cmds.select(i)
        mel.eval('SculptGeometryTool;')
        try:
            mel.eval('artPuttyCtx -e -mtm "relax" `currentCtx`;')
        except:
            pass
        mel.eval('artPuttyCtx -e -opacity 1.0 `currentCtx`;')
        mel.eval('artPuttyCtx -e -clear `currentCtx`;')
        mel.eval('setToolTo $gMove;')
        cmds.delete(i, ch=True)

    # We then combine the objects together and merge the matching vertices
    cmds.select(Objects)
    mesh = cmds.polyUnite(n=mesh, ch=0)
    cmds.polyMergeVertex(mesh, d=0.0001, am=True, ch=0)

    # We finally do a quick smooth through the mesh vertices
    cmds.select(mesh)
    mel.eval('SculptGeometryTool;')
    mel.eval('artPuttyCtx -e -mtm "relax" `currentCtx`;')
    mel.eval('artPuttyCtx -e -opacity 1.0 `currentCtx`;')
    mel.eval('artPuttyCtx -e -clear `currentCtx`;')
    mel.eval('setToolTo $gMove;')
Exemple #28
0
def runMorph2UV():
    baseObj = cmds.ls(sl=1, o=1)  #1. inputmesh
    baseObjDup = cmds.duplicate()  #2. duplicate
    mel.eval("FreezeTransformations")
    mel.eval("ResetTransformations")
    baseObj = baseObjDup[0]
    deleteNoUV()
    splitIfOnUVBorder()
    morph2UV()
    currentSelection = cmds.ls(sl=1)
    currentUV = cmds.polyListComponentConversion(currentSelection, tuv=1)
    cmds.polyMergeVertex(currentSelection, d=0.0001, cch=0)
    cmds.polyMergeUV(currentUV, d=0.001, cch=0)  # fix split
    cmds.select(baseObj, r=1)
Exemple #29
0
def merge_verts(move):
    """Merges verts to first selection."""
    ordered_selection = mampy.complist(os=True)
    if move or len(ordered_selection) == 2:
        if len(next(iter(ordered_selection))) > 1:
            pass
        else:
            if not move:
                v1, v2 = ordered_selection
                pos = v1.bbox.expand(v2.bbox).center
            else:
                pos = ordered_selection.pop().bbox.center
            cmds.xform(ordered_selection.cmdslist(), t=list(pos)[:3], ws=True)
    cmds.polyMergeVertex(ordered_selection.cmdslist(), distance=0.001, ch=True)
Exemple #30
0
def mirrorGeometry(*args, **keywords):
# Mirror geometry together with UV. The UV of character can be splited into a number of U regions.
# usage: select geometry which is present in the +x side and UVs in U=0.5-1 region (and U=1.5-2, U=2.5-3, ...)

	meshes = cmds.listRelatives(s=True, type="mesh", ni=True, f=True)

	if meshes == None:
		raise Exception, "No mesh selected"

	results = []
	for mesh in cmds.listRelatives(meshes, p=True, f=True):
		verticesInRegion = {}

		parent = cmds.listRelatives(mesh, p=True, f=True, pa=True)
		mesh1 = cmds.duplicate(mesh)
		mesh2 = cmds.duplicate(mesh)

		cmds.scale(-1, 1, 1, mesh2, r=True)

		# detect uv regions
		#		scan all vertices

		vertices = cmds.ls(cmds.polyListComponentConversion(mesh2, tuv=True), fl=True)
		for vertex in vertices:
			uv = cmds.polyEditUV(vertex, query=True)
			region = math.ceil(uv[0]) - 1
			if region < 0:
				region = 1
			if not verticesInRegion.has_key(region):
				verticesInRegion[region] = []
			verticesInRegion[region].append(vertex)

		#		choose vertices in regions
		#			flip uv upon middle of regions

		for region,vertices in verticesInRegion.iteritems():
			cmds.select(vertices, r=True)
			cmds.polyEditUV(pu=(region + 0.5), pv=0.5, su=-1, sv=1)

		#	combine objects and merge vertices

		combined = cmds.polyUnite(mesh1, mesh2, ch=False)
		if parent:
			results += cmds.parent(combined, parent)
		else:
			results += combined
		cmds.polyMergeVertex(d=0.005, ch=0)

	cmds.select(results, r=True)
	return results
def create(verts, faces, merge=True):
    '''
    Given a list of vertices (iterables of floats) and a list of faces (iterable of integer vert indices),
    creates and returns a maya Mesh
    '''

    cmds.select(cl=True)
    outputMesh = OpenMaya.MObject()

    numFaces = len(faces)
    numVertices = len(verts)

    # point array of plane vertex local positions
    points = OpenMaya.MFloatPointArray()
    for eachVt in verts:
        p = OpenMaya.MFloatPoint(eachVt[0], eachVt[1], eachVt[2])
        points.append(p)

    # vertex connections per poly face in one array of indexs into point array given above
    faceConnects = OpenMaya.MIntArray()
    for eachFace in faces:
        for eachCorner in eachFace:
            faceConnects.append(int(eachCorner))

    # an array to hold the total number of vertices that each face has
    faceCounts = OpenMaya.MIntArray()
    for c in range(0, numFaces, 1):
        faceCounts.append(int(4))

    # create mesh object using arrays above and get name of new mesh
    meshFN = OpenMaya.MFnMesh()
    """
    print numVertices,numFaces
    print points
    print faceCounts
    print faceConnects
    """
    newMesh = meshFN.create(numVertices, numFaces, points, faceCounts,
                            faceConnects, outputMesh)
    nodeName = meshFN.name()
    cmds.sets(nodeName, add='initialShadingGroup')
    cmds.select(nodeName)
    meshFN.updateSurface()
    # this is useful because it deletes stray vertices (ie, those not used in any faces)
    if merge:
        cmds.polyMergeVertex(nodeName, ch=0)
    meshFN.updateSurface()
    return nodeName
Exemple #32
0
def collapse():
    selected = mampy.complist()
    if not selected:
        return logger.warn("Invalid component selection.")

    for comp in selected:
        if comp.type == MFn.kMeshEdgeComponent:
            for comp in comp.get_connected_components():
                for edge in comp.indices:
                    vert = MeshVert.create(comp.dagpath).add(comp.vertices[edge])
                    vert.translate(t=list(comp.bbox.center)[:3], ws=True)
        else:
            vert = comp.to_vert()
            vert.translate(t=list(vert.bbox.center)[:3], ws=True)
        cmds.polyMergeVertex(comp.cmdslist(), distance=0.001)
    cmds.select(cl=True)
Exemple #33
0
	def vertexMergeTool(self):
		length = len( self.getSelection() )
		if self.getSelection() == 'None': # set tool to the merge vertex tool if no verts are selected
			cmds.setToolTo('polyMergeVertexContext')
		else: # if verts are already selected, then run the commands below
			if self.getType(0) == 'vertex': # check to see if the selection is of the vertex type, in case the mask is set to vert but the sel is edge etc.
				if length == 2:
					cmds.polyMergeVertex(alwaysMergeTwoVertices = True)
				elif length  > 2:
					cmds.polyMergeVertex(distance = 0.001)
					newLength = len(self.getSelection())
					if newLength == length: # Nothing was merged because the before and after are the same, state so
						cmds.headsUpMessage( str(length) + ' Verts Selected - 0 Merged', verticalOffset=-100, horizontalOffset=-200 )
					else: # means a merge did happen, so tell how many were merged and how many are left now
						cmds.headsUpMessage( 'FROM ' + str(length) + ' TO ' + str(newLength), verticalOffset=-100, horizontalOffset=-200 )
			else:
				cmds.warning('Vertex not selected')
  def generate(cls, *args):
    components = []
    boolean = []
    width = cmds.intSliderGrp(cls.get_prefix() + Labels["width_label"], query=True, value=True)
    rgb = cmds.colorSliderGrp(cls.get_prefix() + Labels["color_label"], query=True, rgbValue=True)

    block_width = width * Constants["block_width_unit"]
    block_height = Constants["block_height_unit"]
    block_depth = Constants["block_depth_unit"]

    for x in range(0, width + 1):
      hole = cmds.polyCylinder(name=get_unique_name(cls.get_prefix(), "Hole"), radius=Constants["perforation_radius"], height=Constants["block_depth_unit"] + 0.2)
      boolean.append(hole[0])
      cmds.rotate('90deg', 0, 0, hole[0])
      cmds.move(Constants["block_width_unit"] * x , 0, half(Constants["block_depth_unit"]), hole[0])

    cube = cmds.polyCube(sx=5,sy=2,sz=2,name=get_unique_name(cls.get_prefix(), "block"), width=block_width, height=block_height, depth=block_depth)
    components.append(cube[0])
    cmds.delete(cube[0] + ".f[40:47]")
    cmds.move(half(width * Constants["block_width_unit"]), 0, half(Constants["block_depth_unit"]), cube)

    #caps
    cap_one = cmds.polyCylinder(sc=1, sy=2, radius=half(Constants["block_height_unit"]), height=Constants["block_depth_unit"],name=get_unique_name(cls.get_prefix(), "cap"))
    cmds.rotate('90deg',0,0,cap_one[0])
    cmds.move(0,0,half(Constants["block_depth_unit"]),cap_one[0])
    cmds.delete(cap_one[0] + ".f[0:3]", cap_one[0] + ".f[14:23]", cap_one[0] + ".f[34:43]", cap_one[0] + ".f[54:63]", cap_one[0] + ".f[74:79]")
    components.append(cap_one[0])

    #caps
    cap_two = cmds.polyCylinder(sc=1, sy=2, radius=half(Constants["block_height_unit"]), height=Constants["block_depth_unit"])
    cmds.rotate('90deg','180deg',0,cap_two[0])
    cmds.delete(cap_two[0] + ".f[0:3]", cap_two[0] + ".f[14:23]", cap_two[0] + ".f[34:43]", cap_two[0] + ".f[54:63]", cap_two[0] + ".f[74:79]")
    cmds.move(block_width,0,half(Constants["block_depth_unit"]),cap_two[0])
    components.append(cap_two[0])

    solid = cmds.polyUnite(components, name=get_unique_name(cls.get_prefix(), ""))
    boolean_group = cmds.polyUnite(boolean, name=get_unique_name(cls.get_prefix(),"boolean"))
    cmds.polyMergeVertex( solid[0], d=0.15 )
    cmds.delete(solid[0],ch=1)
    final = cmds.polyBoolOp( solid[0], boolean_group[0], op=2, n=get_unique_name(cls.get_prefix(), "") )

    shader = cmds.shadingNode('blinn', asShader=True, name=get_unique_name(cls.get_prefix(),"mat"))
    cmds.setAttr(shader + ".color", rgb[0],rgb[1],rgb[2], type='double3')
    cmds.select(final[0], r=True)
    cmds.hyperShade(assign=shader)
Exemple #35
0
def mergeVertex(defaultValue=0.1):
    """
    merge selected vertices
    """
    dist = SETTINGS.get('default_merge_distance')
    if dist == None:
        dist = defaultValue
        SETTINGS.add('default_merge_distance', dist)

    selection = cmds.ls(sl=True)
    if selection:
        try:
            for node in selection:
                cmds.select(node, r=True)
                cmds.polyMergeVertex(distance=dist, am=True, ch=True)
        except:
            pass
        cmds.select(selection, r=True)
Exemple #36
0
def setup_scene():
	#manually create a simple tetrahedron 
	p1 = cmds.polyCreateFacet(p=[(0,0,0), (1,0,0), (0,0,1)])
	p2 = cmds.polyCreateFacet(p=[(0,0,0), (0,1,0), (1,0,0)])
	p3 = cmds.polyCreateFacet(p=[(0,0,0), (0,0,1), (0,1,0)])
	p4 = cmds.polyCreateFacet(p=[(0,0,1), (1,0,0), (0,1,0)])
	cmds.polyMergeVertex(cmds.polyUnite(p1,p2,p3,p4, ch=0, name = "cage"), ch=0)
	poly_map =[
		["cage.vtx[0]", [ 	("cage.vtx[0]","cage.vtx[2]","cage.vtx[3]"),
							("cage.vtx[0]","cage.vtx[3]","cage.vtx[1]"),
							("cage.vtx[0]","cage.vtx[1]","cage.vtx[2]"),
						]
		],
		["cage.vtx[1]", [ 	("cage.vtx[1]","cage.vtx[0]","cage.vtx[3]"),
							("cage.vtx[1]","cage.vtx[3]","cage.vtx[2]"),
							("cage.vtx[1]","cage.vtx[2]","cage.vtx[0]"),
						]
		],
		["cage.vtx[2]", [ 	("cage.vtx[2]","cage.vtx[3]","cage.vtx[0]"),
							("cage.vtx[2]","cage.vtx[1]","cage.vtx[3]"),
							("cage.vtx[2]","cage.vtx[0]","cage.vtx[1]"),
						]
		],
		["cage.vtx[3]", [ 	("cage.vtx[3]","cage.vtx[2]","cage.vtx[1]"),
							("cage.vtx[3]","cage.vtx[1]","cage.vtx[0]"),
							("cage.vtx[3]","cage.vtx[0]","cage.vtx[2]"),
						]
		]
		]
	#debug tetra
	"""
	for p in poly_map:
		tris = p[1]
		for t in tris:
			pnts = []
			for vert in t:
				pnt = utils.pnt(vert)
				pnts.append([pnt.x, pnt.y, pnt.z])
			cmds.polyCreateFacet(p=pnts)
	"""

	cage = MayaPolyWrapper(poly_map)
	loc = utils.loc([.1,.1,.1])
	return cage, loc
Exemple #37
0
def tieOff():
	global balloonRadius, balloonQuantity
	knotVals = mc.pointPosition('balloonTemp.vtx[96]', w=True)
	knotThickness = balloonRadius * .05
	endHeight = balloonRadius * .15
	knotRadius = knotVals[0]
	knotPos = ( knotVals[1] - (.5 * knotThickness))

	mc.polyCylinder( n="knotTemp", r=knotRadius, h=knotThickness, sx=12, sy=3, sz=0, rcp=0, cuv=3)
	mc.delete( 'knotTemp.f[36:37]')
	mc.setAttr( 'knotTemp.translateY', knotPos )
	mc.scale(1.25, 1.75, 1.25, 'knotTemp.vtx[12:35]', r=True )
	mc.lattice( n='knot', cp=True,  dv =(2, 2, 2), objectCentered=True, ldv=(2,2,2))
	mc.move( (.75 * knotThickness), 'knotLattice.pt[1][0][0:1]', r=True, y=True)
	mc.move( (.25 * knotThickness), 'knotLattice.pt[0][0][0:1]', r=True, y=True)

	mc.duplicate('knotTemp')
	mc.rotate(180, 'knotTemp1', z=True)

	mc.polyCone( n="endTemp", r=knotRadius*2, h=endHeight, sx=12, sy=6, sz=3, rcp=0, cuv=3)
	mc.delete( 'endTemp.f[60:83]', 'endTemp.f[96:107]')
	mc.setAttr( 'endTemp.translateY', knotPos - knotThickness/2 )	
	mc.scale( 1.15, 1, 1.15, 'endTemp.vtx[36:59]') 
	mc.move((.5 * endHeight), 'endTemp.vtx[0:11]', 'endTemp.vtx[72]', y=True, r=True)
	mc.polyUnite( 'balloonTemp', 'knotTemp', 'knotTemp1', 'endTemp', ch=True )
	mc.polySoftEdge( a = 180 )
	mc.polyMergeVertex( d=.001)

	mc.polyEditUV('polySurface1.map[0:126]', pu=0.5, pv=1, su=1, sv=0.575)
	mc.polyEditUV('polySurface1.map[127:230]', pu=0.5, pv=0.35, su=2, sv=.25)
	mc.polyEditUV('polySurface1.map[267:318]', u=0, v=-0.1, pu=0.5, pv=0, su=1, sv=.5)
	mc.polyEditUV('polySurface1.map[231:266]', 'polySurface1.map[319]', u=0, v=-.175, pu=0.5, pv=0.25, su=0.25, sv=0.25)
	mc.polyMergeUV('polySurface1.map[103:126]', d=0.5, ch=True )
	mc.polyEditUV('polySurface1.map[104]',  r=False, u=0)
	mc.polyEditUV('polySurface1.map[103]', r=False, u=1)
	mc.polySmooth('polySurface1',  mth=0, dv=1, c=1, kb=0, ksb=1, khe=0, kt=1, kmb=0, suv=0, peh=0, sl=1, dpe=1, ps=0.1 , ro=1, ch=True)

	mc.DeleteHistory()
	mc.delete( 'knotTemp1')
	mc.rename('polySurface1', 'balloon1')
	mc.select(cl=True)
	return
Exemple #38
0
def convexHull(pointList):
    """
	from maya import cmds
	import sys
	sys.path.insert(0, '/Users/jarlske/Documents/scripts/python/jm_maya/mesh/')
	import delaunay
	reload(delaunay)

	sel = cmds.ls(sl=1)
	pointList = []
	for each in sel:
	    vtxLen = cmds.polyEvaluate(each, vertex=1)
	    for i in range(0, vtxLen):
	        pointList.append(cmds.xform('{0}.vtx[{1}]'.format(each, str(i)), q=1, t=1 ,ws=1))
	geo = delaunay.convexHull(pointList)
	"""
    points = numpy.array(pointList)
    hull = ConvexHull(points)
    facetList = []
    for each in hull.simplices:
        indexList = each.tolist()
        xpoint = [
            pointList[indexList[0]][0], pointList[indexList[0]][1],
            pointList[indexList[0]][2]
        ]
        ypoint = [
            pointList[indexList[1]][0], pointList[indexList[1]][1],
            pointList[indexList[1]][2]
        ]
        zpoint = [
            pointList[indexList[2]][0], pointList[indexList[2]][1],
            pointList[indexList[2]][2]
        ]
        facetList.append(
            cmds.polyCreateFacet(ch=False, p=[xpoint, ypoint, zpoint])[0])
    poly = cmds.polyUnite(facetList, ch=False, mergeUVSets=True)
    cmds.polyMergeVertex(poly, ch=False)
    cmds.polyNormal(poly, normalMode=2, userNormalMode=0, ch=False)
    cmds.select(cl=True)
    return poly
def planeToPVLocation( _sel, _zDistance, *args):
    #quick broken FK/IK SwitchBlend Creator

    zMV = -(_zDistance)
    jL = _sel

    #set up the pole vector by creating a triangle greo and snapping the verts to the joints in the ik chain and then grabbing the one for the elbow or knee and moveing it in Z axis
    #then moving the traingle Ctl to the space in component and I think grabbing the rotation off the middle vertex rotate pivot or something and putting that on to the Ctl
    #then make it the pole vector constrainor of the ik handle

    #lets make a plane and merge two of the verts the 3rd and 4th and then make a short loop to snap them to the joints
    pN = 'pv_plane'
    cmds.polyPlane(n = pN, sx=1,sy=1, w=1, h=1)

    cmds.polyMergeVertex('pv_plane.vtx[2]', 'pv_plane.vtx[3]', d = 1.5)

 
    #I wanted to come up with a more clever way of reading the names for the Vertex and matching them up with the number in the array they should correspond to
    #but for time Im making it less dynamic and more just getting this done because this is a specific part of the tool I can hard code out a lil

    #get the locations for the joints
    jL1  = cmds.xform( jL[0], q = 1, ws = 1, t = 1)
    jL2 = cmds.xform( jL[1], q = 1, ws = 1, t = 1)
    jL3 = cmds.xform( jL[2], q = 1, ws = 1, t = 1)

    #move the vertex to the locations
    cmds.xform('pv_plane.vtx[0]', ws = True, t = jL1)
    cmds.xform('pv_plane.vtx[1]', ws = True, t = jL3)
    #this is for the merged vertex or the point and it should go on the jL2 because thats the knee number
    cmds.xform('pv_plane.vtx[2]', ws = True, t = jL2) 

    cmds.select(cl=True)

    #now move the pv vertex it in the v axis in its normals
    cmds.moveVertexAlongDirection( "pv_plane.vtx[2]",  v= zMV)

    #return the target vertex and the plane name to allow to delete the plane later
    returns = ['pv_plane.vtx[2]','pv_plane']
    return returns
Exemple #40
0
def create(verts, faces, merge=True):
    '''
	Given a list of vertices (iterables of floats) and a list of faces (iterable of integer vert indices),
	creates and returns a maya Mesh
	'''

    cmds.select(cl=True)
    outputMesh = OpenMaya.MObject()

    # point array of mesh vertex local positions
    points = OpenMaya.MFloatPointArray()
    for eachVt in verts:
        p = OpenMaya.MFloatPoint(eachVt[0], eachVt[1], eachVt[2])
        points.append(p)

    # vertex connections per poly face in one array of indexs into point array given above
    faceConnects = OpenMaya.MIntArray()
    for eachFace in faces:
        for eachCorner in eachFace:
            faceConnects.append(int(eachCorner))

    # an array to hold the total number of vertices that each face has in this case quads so 4
    faceCounts = OpenMaya.MIntArray()
    # python lists can be multiplied to duplicate
    faceCounts = [4] * len(faces)
    # get a mesh function set
    meshFN = OpenMaya.MFnMesh()
    # create mesh object using arrays above
    meshFN.create(points, faceCounts, faceConnects, parent=outputMesh)
    # now grab the name of the mesh
    nodeName = meshFN.name()
    cmds.sets(nodeName, add='initialShadingGroup')
    cmds.select(nodeName)
    meshFN.updateSurface()
    # this is useful because it deletes stray vertices (ie, those not used in any faces)
    cmds.polyMergeVertex(nodeName, ch=0)
    meshFN.updateSurface()
    return nodeName
Exemple #41
0
    def apply(cls, *args):
        # cmds.select(cls.selCrvs, r = True)
        selLs = cmds.ls(sl=True)
        selCrvs = cls.getPathCrvFromPoly(selLs)

        for crv in selCrvs:
            # delete cv 1 and before of end cv
            degs = cmds.getAttr('%s.degree' % (crv))
            spans = cmds.getAttr('%s.spans' % (crv))
            cvs = degs + spans
            cmds.delete('%s.cv[%d]' % (crv, cvs - 2))
            cmds.delete('%s.cv[%d]' % (crv, 1))

            # merge vertex
            cmds.select('%s_poly' % crv, r=True)
            cmds.polyMergeVertex(d=0.001)

            # delete construction history of polygon
            cmds.delete('%s_poly' % crv, ch=True)

            # delete curve and profile
            cmds.delete(crv, '%s_profile_scale' % (crv))

        cmds.select(cl=True)
def makeSym(*args):
    selLs = cmds.ls(sl = True)

    # When user select center edge loop.
    if '.e' in selLs[0]:
        numOfShells = cmds.polyEvaluate(shell = True)
        if numOfShells > 1:
            cmds.confirmDialog(title = 'Warning', message = 'Selected mesh is made of combining several geometry.\nSeparate mesh and try it again.')
            return False

        centerEdgeLoop = selLs
        objName = centerEdgeLoop[0].split('.')[0]
        uvKeepGeo = cmds.duplicate(objName, n = '{0}_uvKeep_geo'.format(objName))

        mel.eval('PolySelectConvert 3;')
        tak_misc.zeroVtx()

        cmds.select(centerEdgeLoop, r = True)
        cmds.DetachComponent()

        leftVtxDic, rightVtxDic, centerVtxDic = getVtxInfo(objName)

        symOpt = cmds.radioButtonGrp('symOptRadButGrp', q = True, select = True)

        # If user select 'x to -x' mean left to right.
        if symOpt == 1:
            rightestVtx = getSidestVtx(rightVtxDic)
            cmds.select(rightestVtx, r = True)
            mel.eval('PolySelectConvert 1;') # Convert vertex selection to face.

            rightestFace = cmds.ls(sl = True, fl = True)[0]
            rightestFaceId = int(re.search(r'.+f\[(\d+)\]', rightestFace).group(1))
            cmds.polySelect(extendToShell = rightestFaceId)
            cmds.delete()

            # mirror geometry
            mirrorNode = cmds.polyMirrorFace(objName, ws = True, direction = 1, mergeMode = 0, mergeThreshold = 0.001, ch = True)
            cmds.polyMirrorFace(mirrorNode, e = True, pivotX = 0.0)

        # If user select '-x to x' mean right to left.
        if symOpt == 2:
            leftestVtx = getSidestVtx(leftVtxDic)
            cmds.select(leftestVtx, r = True)
            mel.eval('PolySelectConvert 1;') # Convert vertex selection to face.

            leftestFace = cmds.ls(sl = True, fl = True)[0]
            leftestFaceId = int(re.search(r'.+f\[(\d+)\]', leftestFace).group(1))
            cmds.polySelect(extendToShell = leftestFaceId)
            cmds.delete()

            # mirror geometry
            mirrorNode = cmds.polyMirrorFace(objName, ws = True, direction = 1, mergeMode = 0, mergeThreshold = 0.001, ch = True)
            cmds.polyMirrorFace(mirrorNode, e = True, pivotX = 0.0)

    # When user select object.
    else:
        objName = selLs[0]
        uvKeepGeo = cmds.duplicate(objName, n = '{0}_uvKeep_geo'.format(objName))

        leftVtxDic, rightVtxDic, centerVtxDic = getVtxInfo(objName)

        symOpt = cmds.radioButtonGrp('symOptRadButGrp', q = True, select = True)

        if centerVtxDic.keys():
            cmds.select(centerVtxDic.keys(), r = True)
            mel.eval('SelectEdgeLoopSp;')
            tak_misc.zeroVtx()

        leftVtxDic, rightVtxDic, centerVtxDic = getVtxInfo(objName) # Refresh vertex position information.

        # If user select 'x to -x' mean left to right.
        if symOpt == 1:
            cmds.select(rightVtxDic.keys(), r = True)
            mel.eval('PolySelectConvert 1;') # Convert vertex selection to face.
            cmds.delete()

            # mirror geometry
            mirrorNode = cmds.polyMirrorFace(objName, ws = True, direction = 1, ch = True)
            cmds.polyMirrorFace(mirrorNode, e = True, pivotX = 0.0)

        # If user select 'x to -x' mean right to left.
        if symOpt == 2:
            cmds.select(leftVtxDic.keys(), r = True)
            mel.eval('PolySelectConvert 1;') # Convert vertex selection to face.
            cmds.delete()

            # mirror geometry
            mirrorNode = cmds.polyMirrorFace(objName, ws = True, direction = 1, ch = True)
            cmds.polyMirrorFace(mirrorNode, e = True, pivotX = 0.0)


    leftVtxDic, rightVtxDic, centerVtxDic = getVtxInfo(objName)
    if centerVtxDic.keys():
        cmds.select(centerVtxDic.keys(), r = True)
        cmds.polyMergeVertex(distance = 0.001)


    # Copy uv from uv keeped geometry to new symmetrized geometry.
    smpSpc = cmds.radioButtonGrp('symSmpSpcRdoBtn', q = True, select = True)
    if smpSpc == 2:
        smpSpc = 4
    elif smpSpc == 3:
        smpSpc = 5
    cmds.transferAttributes(uvKeepGeo, objName, transferUVs = 2, sampleSpace = smpSpc)

    # cmds.select(objName, r = True)
    # mel.eval("SoftPolyEdgeElements 1;")

    # cmds.select(objName, r = True)
    # mel.eval('polyNormalPerVertex -ufn true;')

    cmds.delete(objName, ch = True)
    cmds.delete(uvKeepGeo)

    cmds.select(objName, r = True)
Exemple #43
0
import maya.cmds as mc
import maya.mel as mel
oEdges = mc.ls(sl=True)
oObj = oEdges[0].split('.')[0]
oFace = ''
for i in oEdges:
    if '.f[' in i:
        oFace = i
mc.DetachComponent()
mc.select(cl=True)
mc.select(oFace)
mc.ConvertSelectionToShell()
oFacesFinal = mc.ls(sl=True)
mc.select(oObj)
mc.polyMergeVertex(d=0.0001)
mc.select(oFacesFinal)
mc.selectType(smp=0, sme=0, smf=1, smu=0, pv=0, pe=0, pf=1, puv=0)
mc.hilite(oObj, r=True)
mel.eval('doDelete;')
mc.select(oObj, r=True)
mc.polyCloseBorder()
Exemple #44
0
# เทียนแดง
mc.polyExtrudeEdge(ty=r)
mc.polyExtrudeEdge(sx=0.8, sz=0.8)
mc.polyExtrudeEdge(ty=-r * 0.1)
nf3 = mc.polyEvaluate(craft_bon, f=1)
# ไส้เทียน
mc.polyExtrudeEdge(sx=0.15, sz=0.15)
sl = mc.ls(sl=1)
kliao = mc.duplicate(craft_bon, n='kliao')[0]
mc.select(sl)
for i in range(15):
    mc.polyExtrudeEdge(ty=r * 0.05,
                       tx=r * 0.004 * i * math.cos(0.6 * i),
                       tz=r * 0.004 * i * math.sin(0.6 * i))
mc.polyExtrudeEdge(sx=0, sz=0, ty=0.02 * r)
mc.polyMergeVertex(d=0.001 * r)
nf4 = mc.polyEvaluate(craft_bon, f=1)
mc.delete(craft_bon, ch=1)

# สร้างเบลนด์เชป
mc.select([s.replace(craft_bon, kliao) for s in sl])
for i in range(15):
    mc.polyExtrudeEdge(ty=r * 0.055)
mc.polyExtrudeEdge(sx=0, sz=0, ty=0.02 * r)
mc.polyMergeVertex(d=0.001 * r)
bs = mc.blendShape(kliao, craft_bon)[0]

# สร้าง uv ให้แต่ละส่วนแยกกัน โดยจัดทำ uv ที่โหนดวัตถุเบลนด์เชป แล้วค่อยคัดลอกมาที่วัตถุหลัก
at = 'pcx pcy pcz rx ry rz phs pvs'.split()
ppj1 = mc.polyProjection(kliao + '.f[%d:%d]' % (nf1, nf2 - 1),
                         t='spherical')[0]
Exemple #45
0
def ImportToMaya(vertexArray, polygonConnects, uvArray, texturePath, texture):
    global g_Mesh_Index

    printMessage("Creating mesh...")
    polygonCounts = OpenMaya.MIntArray(polygonConnects.length() / 3, 3)
    mesh = OpenMaya.MFnMesh()
    transform = mesh.create(vertexArray.length(), polygonCounts.length(),
                            vertexArray, polygonCounts, polygonConnects)

    printDebug("connects cnt {}".format(polygonConnects.length()))
    printDebug("cnt {}".format(polygonCounts.length()))
    printDebug("u cnt {}".format(uvArray[0].length()))
    printDebug("v cnt {}".format(uvArray[1].length()))

    # UV map.
    printMessage("Mapping UVs...")
    mesh.setUVs(uvArray[0], uvArray[1])

    try:
        mesh.assignUVs(polygonCounts, polygonConnects)
    except RuntimeError:
        printDebug("mesh.assignUVs() failed. Assign manually...")
        for i in range(0, polygonConnects.length()):
            try:
                mesh.assignUV(i / 3, i % 3, polygonConnects[i])
            except RuntimeError:
                printMessage("AssignUV failed: " +
                             "[{}] = {}".format(i, polygonConnects[i]))

    # Rename mesh.
    printMessage("Renaming mesh...")
    transformDagPath = OpenMaya.MDagPath()
    OpenMaya.MDagPath.getAPathTo(transform, transformDagPath)
    meshName = cmds.rename(transformDagPath.fullPathName(),
                           "NinjaMesh_{}".format(g_Mesh_Index))
    g_Mesh_Index = g_Mesh_Index + 1

    # Apply textures.
    printMessage("Applying textures...")
    shader = cmds.shadingNode("lambert",
                              name="NinjaTexture_{}".format(g_Mesh_Index),
                              asShader=True)

    cmds.select(meshName)
    cmds.hyperShade(assign=shader)

    colorMap = cmds.shadingNode("file",
                                name="{}_colorMap".format(texture),
                                asTexture=True)

    cmds.connectAttr("{}.outColor".format(colorMap), "{}.color".format(shader))
    cmds.setAttr("{}.fileTextureName".format(colorMap),
                 "{}/{}".format(texturePath, texture),
                 type='string')

    # Set vertex color to White.
    printMessage("Forcing vertex color to white...")
    cmds.select(meshName)
    cmds.polyColorPerVertex(cdo=True, rgb=[1, 1, 1])

    # Apply transformations.
    printMessage("Applying transformations...")
    cmds.setAttr("{}.rotateX".format(meshName), g_ninjarotX)
    cmds.setAttr("{}.rotateY".format(meshName), g_ninjarotY)
    cmds.setAttr("{}.rotateZ".format(meshName), g_ninjarotZ)
    cmds.setAttr("{}.scaleX".format(meshName), mdlscaler)
    cmds.setAttr("{}.scaleY".format(meshName), mdlscaler)
    cmds.setAttr("{}.scaleZ".format(meshName), mdlscaler)

    # Freeze transformations.
    printMessage("Zeroing new transform values...")
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1)

    # Scale UVs.
    printMessage("Scaling UVs...")
    uvs = cmds.polyListComponentConversion(meshName, tuv=True)
    cmds.select(uvs)
    cmds.polyEditUV(su=uvscaler, sv=uvscaler * g_flipUV)

    # Normalize UV.
    if g_normalizeUV:
        printMessage("Normalizing UVs...")
        cmds.polyNormalizeUV(nt=1, pa=True, centerOnTile=True)

    # Merge duplicates.
    printMessage("Removing duplicate vertex...")
    cmds.select(cl=True)
    cmds.select(meshName)
    cmds.polyMergeVertex(d=0.01, am=True, ch=1)
    cmds.polyMergeUV(d=0.01, ch=True)

    # Reverse normals (First met in MWR)
    if g_reverseNormals:
        printMessage("Reversing normals...")
        cmds.select(cl=True)
        cmds.select(meshName)
        cmds.polyNormal(meshName, ch=1)

    cmds.select(cl=True)
    print("Import done for mesh '{}'".format(meshName))
Exemple #46
0
selLs = cmds.ls(sl = True)
drvrCtrl = selLs[0]
drvnCtrlZero = selLs[1]

oriGrp = cmds.duplicate(drvrCtrl, po = True, n = drvrCtrl + '_ori_grp')
cmds.orientConstraint(drvrCtrl, oriGrp, mo = False)
cmds.parent(drvnCtrlZero, oriGrp)





# Stich detached edges.
cmds.polySelectConstraint(t = 0x8000, m = 3, w = 1)
cmds.polySelectConstraint(dis = True)
cmds.polyMergeVertex(d = 0.05)




import tak_misc

# Assign Material to Deformed Shape #
deformedShps = cmds.ls('*ShapeDeformed')
for shp in deformedShps:
	origShpPartialName = shp.split('Deformed')[0]
	origShpFullName = cmds.ls('*:' + origShpPartialName)
	if origShpFullName:
		cmds.select(origShpFullName, shp, r = True)
		tak_misc.copyMat()
def ImportToMaya(vertexArray, polygonConnects, uvArray, texturePath, texture):
    global g_Mesh_Index

    printMessage("Creating mesh...")
    polygonCounts = OpenMaya.MIntArray(polygonConnects.length() / 3, 3)
    mesh = OpenMaya.MFnMesh()
    transform = mesh.create(
        vertexArray.length(), polygonCounts.length(), vertexArray,
        polygonCounts, polygonConnects
    )

    printDebug("connects cnt {}".format(polygonConnects.length()))
    printDebug("cnt {}".format(polygonCounts.length()))
    printDebug("u cnt {}".format(uvArray[0].length()))
    printDebug("v cnt {}".format(uvArray[1].length()))

    # UV map.
    printMessage("Mapping UVs...")
    mesh.setUVs(uvArray[0], uvArray[1])

    try:
        mesh.assignUVs(polygonCounts, polygonConnects)
    except RuntimeError:
        printDebug("mesh.assignUVs() failed. Assign manually...")
        for i in range(0, polygonConnects.length()):
            try:
                mesh.assignUV(i / 3, i % 3, polygonConnects[i])
            except RuntimeError:
                printMessage("AssignUV failed: " + 
                            "[{}] = {}".format(i, polygonConnects[i]))

    # Rename mesh.
    printMessage("Renaming mesh...")
    transformDagPath = OpenMaya.MDagPath()
    OpenMaya.MDagPath.getAPathTo(transform, transformDagPath)
    meshName = cmds.rename(
        transformDagPath.fullPathName(), "NinjaMesh_{}".format(g_Mesh_Index)
    )
    g_Mesh_Index = g_Mesh_Index + 1

    # Apply textures.
    printMessage("Applying textures...")
    shader = cmds.shadingNode(
        "lambert", name="NinjaTexture_{}".format(g_Mesh_Index), asShader=True
    )

    cmds.select(meshName)
    cmds.hyperShade(assign=shader)

    colorMap = cmds.shadingNode(
        "file", name="{}_colorMap".format(texture), asTexture=True
    )

    cmds.connectAttr(
        "{}.outColor".format(colorMap), "{}.color".format(shader)
    )
    cmds.setAttr(
        "{}.fileTextureName".format(colorMap),
        "{}/{}".format(texturePath, texture), type='string'
    )

    # Set vertex color to White.
    printMessage("Forcing vertex color to white...")
    cmds.select(meshName)
    cmds.polyColorPerVertex(cdo=True, rgb=[1, 1, 1])

    # Apply transformations.
    printMessage("Applying transformations...")
    cmds.setAttr("{}.rotateX".format(meshName), g_ninjarotX)
    cmds.setAttr("{}.rotateY".format(meshName), g_ninjarotY)
    cmds.setAttr("{}.rotateZ".format(meshName), g_ninjarotZ)
    cmds.setAttr("{}.scaleX".format(meshName), mdlscaler)
    cmds.setAttr("{}.scaleY".format(meshName), mdlscaler)
    cmds.setAttr("{}.scaleZ".format(meshName), mdlscaler)

    # Freeze transformations.
    printMessage("Zeroing new transform values...")
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1)

    # Scale UVs.
    printMessage("Scaling UVs...")
    uvs = cmds.polyListComponentConversion(meshName, tuv=True)
    cmds.select(uvs)
    cmds.polyEditUV(su=uvscaler, sv=uvscaler*g_flipUV)

    # Normalize UV.
    if g_normalizeUV:
        printMessage("Normalizing UVs...")
        cmds.polyNormalizeUV(nt=1, pa=True, centerOnTile=True)

    # Merge duplicates.
    printMessage("Removing duplicate vertex...")
    cmds.select(cl=True)
    cmds.select(meshName)
    cmds.polyMergeVertex(d=0.01, am=True, ch=1)
    cmds.polyMergeUV(d=0.01, ch=True)

    # Reverse normals (First met in MWR)
    if g_reverseNormals:
        printMessage("Reversing normals...")
        cmds.select(cl=True)
        cmds.select(meshName)
        cmds.polyNormal(meshName, ch=1)

    cmds.select(cl=True)
    print("Import done for mesh '{}'".format(meshName))
def mergeVtx(*args):
    threshold = cmds.floatField('mergeVtxThres', q = True, v = True)
    cmds.polyMergeVertex(distance = threshold)
def mergeVert():

    tolVal = cmds.intField("mTolVal", q=True, value=True)
    cmds.polyMergeVertex(d=tolVal)
import maya.cmds as mc
import maya.mel as mel
oEdges = mc.ls(sl=True)
oObj = oEdges[0].split('.')[0]
oFace = ''
for i in oEdges:
	if '.f[' in i:
		oFace = i
mc.DetachComponent()
mc.select(cl=True)
mc.select(oFace)
mc.ConvertSelectionToShell()
oFacesFinal = mc.ls(sl=True)
mc.select(oObj)
mc.polyMergeVertex(d=0.0001)
mc.select(oFacesFinal)
mc.selectType(smp=0, sme=0, smf=1, smu=0, pv=0, pe=0, pf=1, puv=0)
mc.hilite(oObj, r=True)
Exemple #51
0
import maya.cmds as cmds

sel = cmds.ls(sl=True)

newName = sel[0].split('|')[-1]
combinedMesh = cmds.polyUnite(sel[0],
                              sel[1],
                              mergeUVSets=True,
                              centerPivot=True,
                              n=newName)

vertCount = cmds.polyEvaluate(combinedMesh, v=True)

cmds.polyMergeVertex('%s.vtx[0:%d]' % (combinedMesh[0], vertCount - 1),
                     am=True,
                     ch=False,
                     d=0.001)
cmds.delete(combinedMesh[0], ch=True)
cmds.select(combinedMesh[0], r=True)