Пример #1
0
    def w08_getData(self, *args):
        resultData = []
        polyObjs = cmds.filterExpand(sm=12)
        faces = cmds.filterExpand(sm=34)
        if polyObjs != None:
            for poly in polyObjs:
                normalData = cmds.polyInfo(poly, fn=True)
                for f in normalData:
                    faceData = str(f).split()
                    faceName = '%s.f[%s]' % (poly, faceData[1][:-1])
                    nor = [
                        float(faceData[2]),
                        float(faceData[3]),
                        float(faceData[4])
                    ]
                    resultData.append((faceName, nor))

        elif faces != None:
            for f in faces:
                normalData = cmds.polyInfo(f, fn=True)[0]
                faceData = str(normalData).split()
                nor = [
                    float(faceData[2]),
                    float(faceData[3]),
                    float(faceData[4])
                ]
                resultData.append((f, nor))

        self.w08_oriSel = resultData
Пример #2
0
def get_vert_neighbours(obj, vert_index):
    """
    Fetches adjacent vertexes.
    
    Args:
        obj(string)
        vert_index(int)
    
    Returns:
        A list of vertex indexes.
    """
    if is_curve(obj):
        return []

    # Get surrounding edges
    edge_string = cmds.polyInfo("{0}.vtx[{1}]".format(obj, vert_index),
                                vertexToEdge=True)[0]
    edge_indexes = edge_string.split()[2:]

    # Convert edges back to vertexes
    neighbours = set()

    for edge_index in edge_indexes:
        vert_string = cmds.polyInfo("{0}.e[{1}]".format(obj, edge_index),
                                    edgeToVertex=True)[0]
        for v in vert_string.split()[2:]:
            if v.isdigit():
                neighbours.add(int(v))

    return list(neighbours)
def create_orient_group():
    #turn on track selection order
    if ( not mc.selectPref(trackSelectionOrder=1, q=1)):
        mc.selectPref(trackSelectionOrder=True)
    sel =  mc.ls(orderedSelection=True)

    if(sel):
        ctrl = sel.pop()
        verts = sel
        print("verts: ", verts)
        if(len(verts)==3 or len(verts)==6):
            #create helper plane/s. Find normals 
            helper_plane_01 = mc.polyCreateFacet( p=[mc.pointPosition(verts[0]), mc.pointPosition(verts[1]), mc.pointPosition(verts[2])] )
            plane01_str_normal = mc.polyInfo(fn=1)[0].split()
            mc.delete(helper_plane_01)
            plane01_normal = (float(plane01_str_normal[2]), float(plane01_str_normal[3]), float(plane01_str_normal[4]))
            vectorN = om.MVector(plane01_normal[0], plane01_normal[1], plane01_normal[2])

            if (len(verts)==6):
                helper_plane_02 = mc.polyCreateFacet( p=[mc.pointPosition(verts[3]), mc.pointPosition(verts[4]), mc.pointPosition(verts[5])] )
                plane02_str_normal = mc.polyInfo(fn=1)[0].split()
                mc.delete(helper_plane_02)
                plane02_normal = (float(plane02_str_normal[2]), float(plane02_str_normal[3]), float(plane02_str_normal[4]))
                vectorT = om.MVector(plane02_normal[0], plane02_normal[1], plane02_normal[2])
            else:
                # if only one plane is provided, find which one of the world axes is orthogonal to the normal
                if (vectorN*om.MVector(1,0,0) == 0):
                    vectorT = om.MVector(1,0,0)
                elif (vectorN*om.MVector(0,1,0) == 0):
                    vectorT = om.MVector(0,1,0)
                elif (vectorN*om.MVector(0,0,1) == 0):
                    vectorT = om.MVector(0,0,1)
                else:
                    #if none of the axes are aligned with a world axis, ask for more verts to define a 2nd plane
                    warning_msg("No axes are aligned with a world axis. You'll need to select 6 vertices and then ctrl.")
                    return

            #find 3rd vector
            vectorX = vectorN^vectorT

            #create orient grp with same pivot as ctrl then parent ctrl
            orientGrp = mc.group(n=str(ctrl).replace('_Ctrl', '_')+'orientGrp', em=1)
            constraint = mc.parentConstraint( ctrl, orientGrp)
            mc.delete(constraint)
            mc.parent(ctrl, orientGrp)

            #make rotation matrix from vectors
            #keep position and assign rotation matrix to orientGrp 
            orientGrp_matrix = mc.xform(orientGrp,q=1, m=1)
            mc.xform(orientGrp, m=(vectorX.x, vectorX.y, vectorX.z, 0, vectorN.x, vectorN.y, vectorN.z, 0, vectorT.x, vectorT.y, vectorT.z, 0,orientGrp_matrix[12],orientGrp_matrix[13],orientGrp_matrix[14],orientGrp_matrix[15] ))
            #freeze transforms
            mc.makeIdentity(orientGrp, apply=1, t=1, n=0)
        else:
            warning_msg("Please select 3 or 6 vertices and then ctrl")
            return
    else:
        warning_msg("Please select 3 or 6 vertices and then ctrl")
        return
Пример #4
0
def findBestEdgePointToCrease(vertex, crease_direction):
	'''
	Try to find the best edge to start the crease based on the crease direction
	return the edge index and edge time in (int, float) form
	'''
	print("crease dir" + str(crease_direction))
	edges = cmds.polyInfo(vertex, ve = True)
	faces = cmds.polyInfo(vertex, vf = True)
	# we skip VERTEX and 0:
	skip = 2
	e_is = edges[0].split()
	# print("e_is len is " + str(len(e_is)))
	best_idx_min = -1
	closeset_dot_min = 0
	best_idx_max = -1
	closeset_dot_max = 0
	for i in range(skip,len(e_is)):
		e_n = getEdgeName(getMeshName(vertex),e_is[i]);
		# print("e_n is " + str(e_n))
		ev_s = cmds.polyInfo(e_n, ev = True)
		from_idx = ev_s[0].split()[2]
		to_idx = ev_s[0].split()[3]
		# what is the Hard edge and soft edge?
		# print(ev_s)
		from_v_name = getVertName(getMeshName(vertex),from_idx)
		to_v_name = getVertName(getMeshName(vertex),to_idx)

		from_p = cmds.pointPosition(from_v_name, w = True)
		to_p = cmds.pointPosition(to_v_name, w =True)
		
		cur_dir = (to_p[0] - from_p[0],to_p[1] - from_p[1],to_p[2] - from_p[2]) 
		# print(cur_dir)

		normalized_dir = getNormalized(cur_dir)
		# print(normalized_dir)
		
		dot = dotProduct(normalized_dir,crease_direction)
		# print(dot)

		if dot > closeset_dot_max:
			closeset_dot_max = dot
			best_idx_max = int(e_is[i])

		if dot < closeset_dot_min:
			closeset_dot_min = dot
			best_idx_min = int(e_is[i])

	# check if min or max is our best choice
	# print("e_is = " + str(e_is))
	print(closeset_dot_max)
	print(best_idx_max)
	print(closeset_dot_min)
	print(best_idx_min)
	if abs(closeset_dot_max) > abs(closeset_dot_min):
		return (best_idx_max, 0.0)
	else:
		return (best_idx_min, 1.0)
Пример #5
0
    def get_invalid(instance):

        meshes = cmds.ls(instance, type='mesh', long=True)

        invalid = []
        for mesh in meshes:
            if (cmds.polyInfo(mesh, nonManifoldVertices=True)
                    or cmds.polyInfo(mesh, nonManifoldEdges=True)):
                invalid.append(mesh)

        return invalid
Пример #6
0
def face_to_vtxs(face):
    """Exctract vertices from given face"""
    face_name = face.split('.')[0]
    edges = mc.polyInfo(face, fe=True)[0].split()[2:]    
    edges_vtxs= []  
      
    for e in edges:
        vtxs = mc.polyInfo(str(face_name + '.e[' + e + ']'), ev=True)[0].split()[1:4]
        edges_vtxs.append(vtxs)
        
    return edges_vtxs  
    def process(self, instance):
        """Process all the nodes in the instance 'objectSet'"""
        meshes = cmds.ls(instance, type="mesh", long=True)

        invalid = []
        for mesh in meshes:
            if cmds.polyInfo(mesh, nonManifoldVertices=True) or cmds.polyInfo(mesh, nonManifoldEdges=True):
                invalid.append(mesh)

        if invalid:
            raise ValueError("Meshes found with non-manifold edges/vertices: {0}".format(invalid))
Пример #8
0
    def get_invalid(instance):
        from maya import cmds

        meshes = cmds.ls(instance, type="mesh", long=True, noIntermediate=True)

        invalid = []
        for mesh in meshes:
            if (cmds.polyInfo(mesh, nonManifoldVertices=True) or
                    cmds.polyInfo(mesh, nonManifoldEdges=True)):
                invalid.append(mesh)

        return invalid
Пример #9
0
def polyAttach(sel):
    edgeInfo=mc.polyInfo(sel,ve=1)[0]
    edge=sel.split('.')[0]+'.e[%s]'%(edgeInfo.split()[3])
    parameter=2
    if sel.find(mc.polyInfo(edge,ev=1)[0].split()[2])!=-1:
        parameter=1
    curveInfo=mc.pointOnCurve(edge,ch=1,pr=parameter,p=1)
    attachLoc=mc.spaceLocator(n=sel.split('.')[0]+'_Loc#')[0]
    mc.connectAttr(curveInfo+'.position',attachLoc+'.t')
    normalCstrt=mc.normalConstraint(sel.split('.')[0],attachLoc,weight=1,aimVector=[0,0,1],upVector=[1,0,0],worldUpType='vector',worldUpVector=[1,0,0])[0]
    mc.connectAttr(curveInfo+'.tangent',normalCstrt+'.worldUpVector')
    return attachLoc
    def get_invalid(instance):
        from maya import cmds

        meshes = cmds.ls(instance, type='mesh', long=True)

        invalid = []
        for mesh in meshes:
            if (cmds.polyInfo(mesh, nonManifoldVertices=True) or
                    cmds.polyInfo(mesh, nonManifoldEdges=True)):
                invalid.append(mesh)

        return invalid
def evaluateAssets():
    if os.path.isdir(pathFolder) and (fileExtension == ".obj"
                                      or fileExtension == ".fbx"):
        findFileExtension(pathFolder, fileExtension)
        mc.select(all=True)
        verticies = mc.polyInfo(nmv=True)
        edges = mc.polyInfo(nme=True)
        info = str("Non-Manifold Verticies: " + str(verticies) + "\n" +
                   "Non-Manifold Edges: " + str(edges))
        input = open(pathFolder + "\Non-Manifold_Information_Sheet.txt", 'w')
        writeFile(info, edges, verticies)
    else:
        print "Try again."
    def process(self, instance):
        """Process all the nodes in the instance 'objectSet'"""
        meshes = cmds.ls(instance, type='mesh', long=True)

        invalid = []
        for mesh in meshes:
            if cmds.polyInfo(mesh, nonManifoldVertices=True) or cmds.polyInfo(
                    mesh, nonManifoldEdges=True):
                invalid.append(mesh)

        if invalid:
            raise ValueError(
                "Meshes found with non-manifold edges/vertices: {0}".format(
                    invalid))
Пример #13
0
    def _find(self):
        """
        :return: Empty meshes
        :rtype: generator
        """
        meshes = self.ls(type="mesh", noIntermediate=True, l=True)
        meshes = reference.removeReferenced(meshes)

        for mesh in meshes:
            nmEdges = cmds.polyInfo(mesh, nonManifoldEdges=True) or []
            nmVertices = cmds.polyInfo(mesh, nonManifoldVertices=True) or []

            for error in nmEdges + nmVertices:
                yield error
Пример #14
0
def averageVertexNormal(verts):
    for v in verts:
        faces = cmds.polyInfo(v, vertexToFace=True)[0].strip()
        faces = re.findall(r'\d+', faces)[1:]
        vn = [0, 0, 0]
        for f in faces:
            fn = cmds.polyInfo('%s.f[%s]' % (v.split('.', 1)[0], f),
                               faceNormals=True)[0].strip()
            fn = fn.split(' ')[-3:]
            fn = [float(n) for n in fn]
            vn = map(lambda x, y: x + y, vn, fn)
        vn = om.MVector(vn[0], vn[1], vn[2])
        vn.normalize()
        vn = (vn.x, vn.y, vn.z)
        cmds.polyNormalPerVertex(v, xyz=vn)
Пример #15
0
def getFalloffDict(polyName, falloffkdTemp):
    falloffkd = dict(falloffkdTemp)

    falloffkdSSR = {}

    for key, val in falloffkd.items():
        print ''
        print key
        print val

        if val:
            tempA = val
            tempList = []
            for ta in tempA:
                print ta

                edge = '%s.e[%s]' % (polyName, str(ta[0]))
                edgeInfo = cmds.polyInfo(edge, edgeToVertex=1)
                edgeID = cleanInfos(edgeInfo[0])
                if int(key) in edgeID:
                    tempList.append(ta)
                else:
                    print ta
                    edge2 = '%s.e[%s]' % (polyName, str(ta[-1]))
                    edgeInfo2 = cmds.polyInfo(edge2, edgeToVertex=1)
                    edgeID2 = cleanInfos(edgeInfo2[0])
                    if int(key) in edgeID2:
                        ta.reverse()
                    tempList.append(ta)
            falloffkdSSR.update({key: tempList})

    returnDict = {}

    for key, val in falloffkdSSR.items():
        vTemp = []
        for v in val:
            vlist = edgeListToVertList(v)

            valList = []
            for i in range(len(vlist)):
                tempv = round(float(i) / float(len(vlist)), 6)
                valList.append(1.0 - tempv)
            #print vlist
            #print valList
            #print '==='
            vTemp.append(valList)
        returnDict.update({key:vTemp})
    return {'ssr': falloffkdSSR, 'weight': returnDict}
Пример #16
0
def makePlanar(components):
	"""
	Planarizes the given Components.

	:param components: Components to planarizes.
	:type components: list
	"""

	object = cmds.ls(components, o=True)
	if object:
		transform = getTransform(object)
		vertices = cmds.ls(cmds.polyListComponentConversion(components, toVertex=True), fl=True)

		barycenters = cmds.xform(vertices, q=True, t=True, ws=True)
		barycenter = getAverageVector([(barycenters[i], barycenters[i + 1], barycenters[i + 2]) for i in range(0, len(barycenters), 3)])

		normals = [float(normal) for data in cmds.polyInfo(cmds.polyListComponentConversion(components, toFace=True), faceNormals=True) for normal in data.split()[2:5]]
		normals = [(normals[i], normals[i + 1], normals[i + 2]) for i in range(0, len(normals), 3)]
		averageNormal = vectorMatrixMultiplication(normalize(getAverageVector(normals)), cmds.xform(transform, query=True, matrix=True, worldSpace=True))

		offset = -dot(averageNormal, barycenter)

		for vertex in vertices:
			position = cmds.xform(vertex, q=True, t=True, ws=True)
			distance = -(dot(averageNormal, position) + offset)
			cmds.xform(vertex, r=True, t=(averageNormal[0] * distance, averageNormal[1] * distance, averageNormal[2] * distance))
Пример #17
0
def makePlanar(components):
	"""
	This definition planarizes the given Components.

	:param components: Components to planarizes. ( List )
	"""

	object = cmds.ls(components, o=True)
	if object:
		transform = getTransform(object)
		vertices = cmds.ls(cmds.polyListComponentConversion(components, toVertex=True), fl=True)

		barycenters = cmds.xform(vertices, q=True, t=True, ws=True)
		barycenter = getAverageVector([(barycenters[i], barycenters[i + 1], barycenters[i + 2]) for i in range(0, len(barycenters), 3)])

		normals = [float(normal) for data in cmds.polyInfo(cmds.polyListComponentConversion(components, toFace=True), faceNormals=True) for normal in data.split()[2:5]]
		normals = [(normals[i], normals[i + 1], normals[i + 2]) for i in range(0, len(normals), 3)]
		averageNormal = vectorMatrixMultiplication(normalize(getAverageVector(normals)), cmds.xform(transform, query=True, matrix=True, worldSpace=True))

		offset = -dot(averageNormal, barycenter)

		for vertex in vertices:
			position = cmds.xform(vertex, q=True, t=True, ws=True)
			distance = -(dot(averageNormal, position) + offset)
			cmds.xform(vertex, r=True, t=(averageNormal[0] * distance, averageNormal[1] * distance, averageNormal[2] * distance))
Пример #18
0
def record_obj(root, geoList, file_obj, obj_name):
    start_v_number = 1
    # save texture map, obj, mtl to intermediate files
    cmds.select(geoList[0])  # select a mesh.
    output_filename = os.path.splitext(obj_name)[0] + '_intermediate.obj'
    cmds.file(
        output_filename,
        force=True,
        op="groups=0;ptgroups=0;materials=1;smoothing=0;normals=1",
        typ="OBJexport",
        pr=True,
        es=True
    )  # save the selected mesh to OBJ file   vtxIndexList = cmds.getAttr(geo + ".vrts", multiIndices=True)
    cmds.select(clear=True)

    for geo in geoList:
        vtxIndexList = cmds.getAttr(geo + ".vrts", multiIndices=True)
        for i in vtxIndexList:
            pos = cmds.xform(geo + ".vtx[" + str(i) + "]",
                             query=True,
                             translation=True,
                             worldSpace=True)
            new_line = "v {:f} {:f} {:f}\n".format(pos[0], pos[1], pos[2])
            file_obj.write(new_line)
        faceIndexList = cmds.getAttr(geo + ".face", multiIndices=True)
        for i in faceIndexList:
            cmds.select(geo + ".f[" + str(i) + "]", r=True)
            fv = cmds.polyInfo(fv=True)
            fv = fv[0].split()
            new_line = "f {:d} {:d} {:d}\n".format(
                int(fv[2]) + start_v_number,
                int(fv[3]) + start_v_number,
                int(fv[4]) + start_v_number)
            file_obj.write(new_line)
        start_v_number += len(vtxIndexList)
Пример #19
0
    def get_invalid(instance):
        meshes = cmds.ls(instance, type='mesh', long=True)
        invalid = [
            mesh for mesh in meshes if cmds.polyInfo(mesh, laminaFaces=True)
        ]

        return invalid
Пример #20
0
def getPolyCreateInfo( meshName ):
    
    selList = om.MSelectionList()
    selList.add( meshName )
    path = om.MDagPath()
    selList.getDagPath( 0,path )
    
    fnMesh = om.MFnMesh( path )
    
    numVtx  = fnMesh.numVertices()
    numPoly = fnMesh.numPolygons()
    mPointArr = om.MPointArray()
    mCountArr = om.MIntArray()
    mConnectArr = om.MIntArray()
    
    fnMesh.getPoints( mPointArr )
    
    mCountArr.setLength( numPoly )
    
    for i in range( numPoly ):
        mCountArr[i] = fnMesh.polygonVertexCount( i )
        
        numStr = cmds.polyInfo( meshName+'.f[%d]' % i, fv=1 )[0].split( ':' )[1].strip()
        nums = numStr.split( '    ' )
        for j in range( len( nums ) ):
            mConnectArr.append( int(nums[j].strip()) )
        
    return numVtx, numPoly, mPointArr, mCountArr, mConnectArr
Пример #21
0
def faceToAdjacentVertex(face):
    transName = polyToTrans(face)
    cmds.select(face)
    indexString = cmds.polyInfo(faceToVertex=True)[0]
    indexList = infoToIndex(indexString)
    vertList = indexToPoly(transName, "vtx", indexList)
    return vertList
Пример #22
0
def createGraph(mesh, name):
    print 'Creating graph...'
    cmds.select(name)
    # Extract edges
    numEdges = cmds.polyEvaluate(e=True)
    # Extract vertices
    numVerts = cmds.polyEvaluate(v=True)
    # Initialize graph
    graph = []
    for i in range(0, numVerts):
        graph.append([])
    # Fill graph with vertices
    for i in range(0, numVerts):
        cmds.select('{0}.vtx[{1}]'.format(name, i))
        found = cmds.polyInfo(ve=True)
        #print found
        tokens = found[0].split(' ')
        # Skip over non-alphanumeric strings
        for t in tokens:
            tmp = '{0}'.format(t)
            if (tmp.isalnum() == True) and (tmp != 'VERTEX'):
                # Add each alphanumeric string to the graph
                graph[i].append(int(tmp))
    cmds.select(mesh)
    return graph
Пример #23
0
def getNormalDirOLD(obj):
    # get number of faces
    faceNum = cmds.polyEvaluate(obj, face=True)

    for x in range(faceNum):

        # face select
        cmds.select('{}.f[{}:{}]'.format(obj, x, x))  # select face 0
        print('{}.f[0:{}]'.format(obj, x))

        # get the current selection
        selection = cmds.ls(sl=True)

        # trying to get the face normal angles of the current selection
        polyInfo = cmds.polyInfo(selection, fn=True)

        # convert the string to array with regular expression
        polyInfoArray = re.findall(r"[\w.-]+", polyInfo[0])
        polyInfoX = float(polyInfoArray[2])
        polyInfoY = float(polyInfoArray[3])
        polyInfoZ = float(polyInfoArray[4])

        # deselect current selection
        cmds.select(d=True)

        print str(polyInfoX) + ', ' + str(polyInfoY) + ', ' + str(polyInfoZ)
Пример #24
0
def facesDel(obj):
    """
	delete faces point up or downward
	- firt get number of faces
	- loop throught all faces
	- check for there normal direction
	- if normal Y is not 0, a face to list
	- delete al faces in list
	"""
    faces = []

    # get number of faces
    faceNum = cmds.polyEvaluate(obj, face=True)

    for x in range(faceNum):

        # select face number
        face = '{}.f[{}]'.format(obj, x)

        # get normal Y value
        polyInfo = cmds.polyInfo(face, fn=True)
        polyInfoArray = re.findall(r"[\w.-]+", polyInfo[0])
        polyInfoY = float(polyInfoArray[3])

        # append face
        if not polyInfoY == 0.0:
            faces.append(face)

    # delete faces in list
    cmds.delete(faces)
Пример #25
0
    def getEdgesByVertex(self, vid):

        vert = '%s.vtx[%s]' % (self.polyName, str(vid))

        if cmds.objExists(vert):

            edgeInfo = cmds.polyInfo(vert, vertexToEdge=1)

            edgeID = self.cleanInfos(edgeInfo[0])

            relativeList = []
            for eid in edgeID:
                edgeLoop = cmds.polySelect(self.polyName,
                                           edgeLoop=int(eid),
                                           ass=0,
                                           q=1)

                intArray = []
                for el in edgeLoop:
                    intArray.append(int(el))

                if self.isEdgesListMirror(intArray):
                    spArray = self.splitLinesByMiddle([intArray])
                    for spa in spArray:
                        if int(eid) in spa:
                            relativeList.append(spa)
                else:
                    relativeList.append(intArray)

            return relativeList
def findNewPosition(object, vert, push_dist):
    vert_name = object + '.vtx[' + str(vert) + ']'
    cmds.select(vert_name, replace=True)
    faces = cmds.polyListComponentConversion(vert_name, toFace=True)
    normals = cmds.polyInfo(faces, faceNormals=True)
    x_avg = 0
    y_avg = 0
    z_avg = 0
    for norm in normals:
        label, vertex, x, y, z = norm.split()
        x_avg += float(x)
        y_avg += float(y)
        z_avg += float(z)
    x_avg = x_avg / len(normals)
    y_avg = y_avg / len(normals)
    z_avg = z_avg / len(normals)
    print x_avg, y_avg, z_avg
    vert_pos = cmds.xform(vert_name, query=True, translation=True)
    print "-----"
    print vert_pos
    new_x = vert_pos[0] + -x_avg * push_dist
    new_y = vert_pos[1] + -y_avg * push_dist
    new_z = vert_pos[2] + -z_avg * push_dist
    print new_x, new_y, new_z
    print "------"
    return [new_x, new_y, new_z]
Пример #27
0
def getPolyCreateInfo(meshName):

    selList = om.MSelectionList()
    selList.add(meshName)
    path = om.MDagPath()
    selList.getDagPath(0, path)

    fnMesh = om.MFnMesh(path)
    meshMatrix = path.inclusiveMatrix()
    meshMtxList = []

    for i in range(4):
        for j in range(4):
            meshMtxList.append(meshMatrix(i, j))

    numVtx = fnMesh.numVertices()
    numPoly = fnMesh.numPolygons()
    mPointArr = om.MPointArray()
    mCountArr = om.MIntArray()
    mConnectArr = om.MIntArray()

    fnMesh.getPoints(mPointArr)

    mCountArr.setLength(numPoly)

    for i in range(numPoly):
        mCountArr[i] = fnMesh.polygonVertexCount(i)

        numStr = cmds.polyInfo(meshName + '.f[%d]' % i,
                               fv=1)[0].split(':')[1].strip()

        eachStr = ''

        nums = []

        for char in numStr:
            if char == ' ':
                if eachStr.isdigit():
                    nums.append(int(eachStr))
                eachStr = ''
            else:
                eachStr += char
        if eachStr:
            nums.append(int(eachStr))

        for j in range(len(nums)):
            mConnectArr.append(nums[j])

    lPointArr = []
    lCountArr = []
    lConnectArr = []

    for i in range(mPointArr.length()):
        lPointArr.append([mPointArr[i].x, mPointArr[i].y, mPointArr[i].z])
    for i in range(mCountArr.length()):
        lCountArr.append(mCountArr[i])
    for i in range(mConnectArr.length()):
        lConnectArr.append(mConnectArr[i])

    return meshName, meshMtxList, numVtx, numPoly, lPointArr, lCountArr, lConnectArr
Пример #28
0
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)) )
Пример #29
0
def create_branches(obj_name,
                    num_branches=4,
                    max_iterations=4,
                    length_range=(0.5, 1.5),
                    height_range=(0.2, 1.5)):
    num_faces = cmds.polyEvaluate(obj_name, f=True)
    branch_faces = []
    while len(branch_faces) < num_branches:
        rand_face = random.randint(0, num_faces)
        cmds.select("{}.f[{}]".format(obj_name, rand_face))
        face_verts = format_polyinfo(cmds.polyInfo(fv=True))
        # Only accepting quads and faces above 0 on the Y axis
        if len(face_verts) > 3 and get_position(
        )[1] > 0 and rand_face not in branch_faces:
            branch_faces.append(rand_face)
    branch_ends = []
    for face in branch_faces:
        cmds.select("{}.f[{}]".format(obj_name, face))
        cmds.polyExtrudeFacet()
        cmds.scale(0.7, 0.7, 0.7, cs=True)
        iterations = random.randint(1, max_iterations)
        for i in range(iterations):
            ty = random.uniform(*height_range)
            ltz = random.uniform(*length_range)
            cmds.polyExtrudeFacet(ltz=ltz, ty=ty)
            cmds.scale(0.6, 0.6, 0.6, cs=True)
        branch_ends.append(cmds.ls(selection=True)[0])
    return branch_ends
def _get_hard_edge(mesh):
    """ Returns hard edges on given mesh(s) """
    hard_edges = []

    '''
    # Python API 1.0
    mesh_path = _n(selected_mesh[0])
    edge_iter = OpenMaya.MItMeshEdge(mesh_path.node())

    while not edge_iter.isDone():
        edge_iter.next()
        # if edge_iter.currentItem()
        if not edge_iter.isSmooth():
            hard_edges.append(edge_iter.currentItem())
    '''

    # mel base
    if isinstance(mesh, list):
        all_edges = cmds.ls([str(x) + ".e[*]" for x in mesh], flatten=True)
    else:
        all_edges = cmds.ls("{0}.e[*]".format(mesh), flatten=True)

    for edge in all_edges:
        edge_vertices = cmds.polyInfo(edge, edgeToVertex=True)
        if "Hard" in edge_vertices[0]:
            hard_edges.extend([edge, ])

    return hard_edges
Пример #31
0
def pointOnEdge( obj = '' , edge = '' ) :
	# Create transform node that will be sticked on given edge
	prxy = pc.Dag( obj )
	edgeId = ''.join( [ x for x in edge.split('.')[1] if x.isdigit() ] )
	msh = pc.Dag( edge.split('.')[0] )

	rvt = pc.Null()
	
	# Casting edge to two vertices
	vtxs = [ x for x in mc.polyInfo( edge , ev = True )[0].split( ':' )[1].split( ' ' ) if x.isdigit() ]
	
	# Curve from mesh edge
	cfme = pc.CurveFromMeshEdge()
	msh.attr('w') >> cfme.attr('im')
	cfme.attr('ei[0]').value = int( edgeId )
	
	# Point on curve info
	poci = pc.PointOnCurveInfo()
	cfme.attr('outputCurve') >> poci.attr('ic')
	poci.attr('position') >> rvt.attr('t')
	poci.attr('turnOnPercentage').value = 1
	
	# Finding world position
	vtxAPos = mc.xform( '%s.vtx[%s]' % ( msh , vtxs[0] ) , q = True , t = True , ws = True )
	vtxBPos = mc.xform( '%s.vtx[%s]' % ( msh , vtxs[1] ) , q = True , t = True , ws = True )
	prxyPos = prxy.ws
	
	# Finding length and length ratio
	edgeLen = pc.mag( ( vtxBPos[0] - vtxAPos[0] , vtxBPos[1] - vtxAPos[1] , vtxBPos[2] - vtxAPos[2] ) )
	prxyLen = pc.mag( ( prxyPos[0] - vtxAPos[0] , prxyPos[1] - vtxAPos[1] , prxyPos[2] - vtxAPos[2] ) )
	lenRatio = prxyLen / edgeLen
	
	poci.attr('parameter').value = lenRatio
	
	return rvt , cfme , poci
Пример #32
0
def getNormalFromFace(face, tri):
    #Return normal of a face
    # creates 2 vectors from verts and retrun cross product

    facefv = cmds.polyInfo(face, fv=1)
    verts = facefv[0].split()[2:]

    #create array for face verts
    vertsList = getVerts(verts, tri)

    vert1 = numpy.array(vertsList[0])
    vert2 = numpy.array(vertsList[1])
    vert3 = numpy.array(vertsList[2])
    v = vert2 - vert1
    w = vert3 - vert1

    cp = numpy.cross(v, w)

    n = numpy.array(cp)

    norm = numpy.linalg.norm(n)  #get normalize value
    normalized = n / norm
    x = normalized[0]
    y = normalized[1]
    z = normalized[2]

    return [x, y, z, 0]
Пример #33
0
    def getCrossByStructEdge(self, evDict, sigEdge):
        if str(sigEdge) in evDict.keys():

            sigEdgeVerts = evDict[str(sigEdge)]

            sigEdgeCrossDict = {}
            for sev in sigEdgeVerts[1:-1]:
                vert = '%s.vtx[%s]' % (self.polyName, str(sev))

                edgeInfo = cmds.polyInfo(vert, vertexToEdge=1)

                edgeID = self.cleanInfos(edgeInfo[0])

                for eid in edgeID:

                    if eid not in sigEdge:
                        edgeLoop = cmds.polySelect(self.polyName,
                                                   edgeLoop=int(eid),
                                                   ass=0,
                                                   q=1)
                        intArray = []
                        for el in edgeLoop:
                            intArray.append(int(el))
                        sigEdgeCrossDict.update({sev: intArray})
                        break
            return sigEdgeCrossDict
        else:
            print 'input edge is not in evDict.you need calculate evDict,include the edge you inputted.'
Пример #34
0
 def singlePoly(self, arg=None):
     selObj=self.selection_grab()
     if selObj:
         pass
     else:
         print "select a polygon object"
         return    
     if "." in selObj[0]:
         print "You need to select a polygon object to interogate.(check that you are not in component mode)"
         return     
     else:
         pass 
     cmds.select(cl=True)
     if cmds.objExists("PolyIssues")==True:
         cmds.delete("PolyIssues")
     cmds.sets(n="PolyIssues", co=5)
     cmds.select(selObj)
     errorFound=cmds.polyInfo(selObj, lf=True, nme=True, nmv=True )
     cmds.select (errorFound)
     cmds.ConvertSelectionToVertices(errorFound)
     if errorFound>0:
         print "Polygon error found"
         cmds.sets( fe='PolyIssues')
     cmds.select('PolyIssues', r=True, ne=True)
     cmds.pickWalk(d='Up')
     errorFound=cmds.ls(sl=True)
     if (len(errorFound))==0:
         cmds.delete("PolyIssues")
Пример #35
0
def getBaseStructEdges(polyName):

    cleanVertArray = getAllVertsWhoHave5edges(polyName)
    edgeLoopArray = []
    sortTemp = []
    for cva in cleanVertArray:

        vert = '%s.vtx[%s]' % (polyName, str(cva))

        edgeInfo = cmds.polyInfo(vert, vertexToEdge=1)

        edgeID = cleanInfos(edgeInfo[0])

        for eid in edgeID:
            edgeLoop = cmds.polySelect(polyName, edgeLoop=int(eid), ass=0, q=1)
            intArray = []
            for el in edgeLoop:
                intArray.append(int(el))
            sEdgeLoop = list(intArray)
            sEdgeLoop.sort()

            if not (sEdgeLoop in sortTemp):
                edgeLoopArray.append(intArray)
                sortTemp.append(sEdgeLoop)
    return edgeLoopArray
    def _on_execute_button_clicked(self):
        self._update()

        for face in cmds.ls(self.costume_menu.currentText() + ".f[*]", fl=1):
            result = cmds.polyInfo(
                face, faceToVertex=True)[0].split(":")[1].split("    ")
            v_count = len(result) - 1
            if v_count >= 4:
                cmds.confirmDialog(t="Warning", m="Please Triangulate")
                return

        img = self._create_data_img(self.vertex_size, self.bake_time)

        current_time = self.start_time
        bias = 10**self.detail_slider.value()
        vertex_size = cmds.polyEvaluate(self.costume_menu.currentText(),
                                        v=True)

        out_of_range = False
        while (current_time <= self.end_time):
            cmds.currentTime(current_time)
            if self._set_color(img, self.costume_menu.currentText(),
                               vertex_size, current_time, bias):
                out_of_range = True
            current_time += 1
        img.save(self.tex_file_path_line.text(), quality=100)
        cmds.currentTime(self.start_time)
        if out_of_range:
            cmds.confirmDialog(t="Warning", m="Out of range, down the detail")
Пример #37
0
def GetVertexIndicesFromTriangle(f):
    cmds.select(f)
    vtxs = cmds.polyInfo(fv=True)
    indices = []
    for vtx in vtxs:
        indices += GetIndices(vtx)
    return indices
Пример #38
0
def getPolyCreateInfo( meshName ):
    
    selList = om.MSelectionList()
    selList.add( meshName )
    path = om.MDagPath()
    selList.getDagPath( 0,path )
    
    fnMesh = om.MFnMesh( path )
    meshMatrix = path.inclusiveMatrix()
    meshMtxList = []
    
    for i in range( 4 ):
        for j in range( 4 ):
            meshMtxList.append( meshMatrix( i, j ) )
    
    numVtx  = fnMesh.numVertices()
    numPoly = fnMesh.numPolygons()
    mPointArr = om.MPointArray()
    mCountArr = om.MIntArray()
    mConnectArr = om.MIntArray()
    
    fnMesh.getPoints( mPointArr )
    
    mCountArr.setLength( numPoly )
    
    for i in range( numPoly ):
        mCountArr[i] = fnMesh.polygonVertexCount( i )
        
        numStr = cmds.polyInfo( meshName+'.f[%d]' % i, fv=1 )[0].split( ':' )[1].strip()
        
        eachStr = ''
        
        nums = []
        
        for char in numStr:
            if char == ' ':
                if eachStr.isdigit():
                    nums.append( int( eachStr ) )
                eachStr = ''
            else:
                eachStr += char
        if eachStr:
            nums.append( int( eachStr ) )
        
        for j in range( len( nums ) ):
            mConnectArr.append( nums[j] )
            
    lPointArr = []
    lCountArr = []
    lConnectArr = []
    
    for i in range( mPointArr.length() ):
        lPointArr.append( [mPointArr[i].x,mPointArr[i].y,mPointArr[i].z] )
    for i in range( mCountArr.length() ):
        lCountArr.append( mCountArr[i] )
    for i in range( mConnectArr.length() ):
        lConnectArr.append( mConnectArr[i] )

    return meshName, meshMtxList, numVtx, numPoly, lPointArr, lCountArr, lConnectArr
	def findWindingOrder(face):
		faceInfo = cmds.polyInfo(face, fv=1 )[0]
		pieces = faceInfo.split()	# -1, -2, -3
		allVerts = []
		for i in range( 2 , len(pieces) ):
			allVerts.append( "%s.vtx[%s]" %(face.split(".")[0], pieces[i]))

		return allVerts
Пример #40
0
def setmesh(nodename):
    cmds.select(nodename)

    exts = getnames()
    va, na, pa, uva = exts
    nva, nna, npa, nuva = [nodename+"."+ext for ext in exts]

    # Vertices first.
    vl = cmds.xform(nodename+'.vtx[:]', q=True, os=True, t=True)
    cmds.addAttr(longName=va, dt="string")
    cmds.setAttr(nva, str(vl), type="string")

    # Polygons (called faces in Maya).
    pcnt = cmds.polyEvaluate(f=True)
    cmds.addAttr(longName=pa, dt="string")
    pll = []
    for x in range(pcnt):
        fvl = cmds.polyInfo(nodename+".f[%i]" % x, faceToVertex=True)
        p = fvl[0].split()[2:]
        pll += ["[" + ",".join(p) + "]"]
    pll = "[" + ",".join(pll) + "]"
    cmds.setAttr(npa, pll, type="string")
    pl = eval(pll)

    # Normals and UVs (needs polygons).
    nll = []
    # UVs are only used if user has set a non-default UV-set
    # name (use right-click menu).
    cmds.select(nodename)
    hasUv = (cmds.polyUVSet(q=True, allUVSets=True) != ['map1'])
    uvcnt = 0
    #print("Set is: "+str(cmds.polyUVSet(q=True, allUVSets=True)))
    cmds.addAttr(longName=na, dt="string")
    if hasUv:
        cmds.addAttr(longName=uva, dt="string")
        uvll = []
    for polyidx in range(pcnt):
        poly = pl[polyidx]
        for vtxidx in poly:
            sel = nodename+".vtxFace["+str(vtxidx)+"]["+str(polyidx)+"]"
            cmds.select(sel)
            n = cmds.polyNormalPerVertex(q=True, xyz=True);
            nll += n
            if hasUv:
                uv_names = cmds.polyListComponentConversion(fromVertexFace=True, toUV=True)
                if uv_names:
                    uv_name = uv_names[0]
                    cmds.select(uv_name)
                    uv = cmds.polyEditUV(q=True)
                    uvll += uv
                    uvcnt += 1
    #print "Normals: "+str(nll)
    cmds.setAttr(nna, str(nll), type='string')
    if hasUv:
        #print "UVs: "+str(uvll)
        cmds.setAttr(nuva, str(uvll), type='string')

    return (1, len(vl)/3+len(pl)+len(nll)/3+uvcnt)
Пример #41
0
	def faceVtxList(self, face):
		tmp = mc.polyInfo(face, fv=True)
		idx = tmp[0].find(':')
		sparse = tmp[0][idx+1:]
		result = sparse.split()
		vtxList = []
		for r in result :
			vtxList.append(int(r))
		return vtxList
Пример #42
0
 def searchNgons(self, mesh):
     ngonsList = []
     faceCount = cmds.polyEvaluate(mesh, face=True)
     allFaces = [mesh + ".f[%s]" % num for num in range(faceCount)]
     for face in allFaces:
         edges = cmds.polyInfo(
             face, faceToEdge=True)[0].split(":")[-1].split()
         if len(edges) >= 5:
             ngonsList.append(face)
     return ngonsList
Пример #43
0
def get_nonmanifold_vertices(dataDict, nodeList, badNodeList, *args):
    """ Store a list of non manifold vertices. """

    for i in nodeList:
        verts = cmds.polyInfo(i, nonManifoldVertices=True)
        dataDict[i]['nonManifoldVtx'] = verts

        if verts is not None:
            badNodeList.append(i)

        dataDict[i]['nonManifoldVtx'] = []
Пример #44
0
def get_nonmanifold_edges(dataDict, nodeList, badNodeList, *args):
    """ Store a list of non manifold edges. """

    for i in nodeList:
        edges = cmds.polyInfo(i, nonManifoldEdges=True)
        dataDict[i]['nonManifoldEdges'] = edges

        if edges is not None:
            badNodeList.append(i)

        dataDict[i]['nonManifoldEdges'] = []
    def process(self, instance):
        """Process all the nodes in the instance 'objectSet'"""
        meshes = cmds.ls(instance, type='mesh', long=True)

        invalid = []
        for mesh in meshes:
            if cmds.polyInfo(mesh, laminaFaces=True):
                invalid.append(mesh)

        if invalid:
            raise ValueError("Meshes found with lamina faces: {0}".format(invalid))
Пример #46
0
	def _getClosestEdgesFromMesh(self):
		"""return the closets edges from the mesh to use"""
		clos = mn.createNode( 'closestPointOnMesh' )
		self.mesh.a.worldMesh >> clos.a.inMesh
		clos.a.inPosition.v = self.initPosition
		closeFace = clos.a.closestFaceIndex.v
		edges = mc.polyInfo( self.mesh.name + '.f[%i'%closeFace + ']', faceToEdge = True )
		edges = edges[0].split()
		edge1 = int( edges[2] )
		edge2 = int( edges[4] )
		clos.delete()
		return edge1, edge2
    def process(self, instance):
        """Process all the nodes in the instance 'objectSet'"""

        meshes = instance.data['shapes']

        invalid = []
        for mesh in meshes:
            self.log.info('checking: {}'.format(mesh))
            if cmds.polyInfo(mesh, laminaFaces=True):
                invalid.append(mesh)

        if invalid:
            raise ValueError("Meshes found with lamina faces: {0}".format(invalid))
Пример #48
0
 def poles(self, arg=None):
     listOne=list()
     listTwo=list()
     selObj=self.selection_grab()
     if selObj:
         pass
     else:
         print "select polygon vertices"
         return        
     if ".vtx[" in selObj[0]:
         pass
     else:
         print "You need to make a selection of vertices for this tool to interrogate."
         return                  
     cmds.selectMode(object=True)
     jim=cmds.ls (sl=True)
     cmds.select(cl=True)
     if cmds.objExists("Npoles")==True:
         cmds.delete("Npoles")
     cmds.sets(n="Npoles", co=1)
     if cmds.objExists("Epoles")==True:
         cmds.delete("Epoles")
     cmds.sets(n="Epoles", co=4)
     if cmds.objExists("starpoles")==True:
         cmds.delete("starpoles")
     cmds.sets(n="starpoles", co=7)
     for each in selObj:
         getComponent = cmds.polyInfo(each, ve=True)
         getVerts=getComponent[0].split(':')[1]
         edgeCount=re.findall(r'\d+', getVerts)
         if (len(edgeCount))==3:
             cmds.sets(each, fe='Npoles')
         elif (len(edgeCount))==5:
             cmds.sets(each, fe='Epoles')
         elif (len(edgeCount))>5:
             cmds.sets(each, fe='starpoles')
     cmds.select('starpoles', r=True, ne=True)
     cmds.pickWalk(d='Up')
     errorFound=cmds.ls(sl=True)
     if (len(errorFound))==0:
         cmds.delete("starpoles")
     cmds.select('Npoles', r=True, ne=True)
     cmds.pickWalk(d='Up')
     errorFound=cmds.ls(sl=True)
     if (len(errorFound))==0:
         cmds.delete("Npoles")
     cmds.select('Epoles', r=True, ne=True)
     cmds.pickWalk(d='Up')
     errorFound=cmds.ls(sl=True)
     if (len(errorFound))==0:
         cmds.delete("Epoles")
Пример #49
0
	def getNormals(self):
# These could give back incorrect order
# Compared to the face's winding order.
		# Current vertexFace for this face
		vfs = cmds.polyListComponentConversion( self.name,  tvf=1 ) # ff=1,
		vfs = cmds.filterExpand(vfs, expand=True, sm=70)		
		print(vfs)
		print(cmds.polyInfo( self.name, faceNormals=True ))
		for curVfs in vfs:
			for vert in self.vertex:
				if( vert.normals.has_key(curVfs) ):
					self.normals.append( vert.normals[curVfs] )
					
		return vfs
Пример #50
0
def setLocators(plane):
    cmds.select(plane)
    fn = cmds.polyInfo(fn=True)
    #get face normal direction
    fn_x = float(fn[0].split(" ")[7])
    fn_y = float(fn[0].split(" ")[8])
    fn_z = float(fn[0].split(" ")[9])

    #get face center position
    p0 = getVertexPosition(plane, 0)
    p1 = getVertexPosition(plane, 1)
    p2 = getVertexPosition(plane, 2)
    
    px = (p0[0]+p1[0]+p2[0])/3
    py = (p0[1]+p1[1]+p2[1])/3
    pz = (p0[2]+p1[2]+p2[2])/3
    
    p = [px,py,pz] 
    #p = np.average(np.array((p0,p1,p2)), axis = 0)

    #calc locator position
    lo_x = fn_x + p[0]
    lo_y = fn_y + p[1]
    lo_z = fn_z + p[2]

    #create normal aim locator
    cmds.spaceLocator(n = 'locator_normal_aim_' + plane)
    cmds.move(lo_x, lo_y, lo_z, 'locator_normal_aim_' + plane)
    cmds.scale(0.1,0.1,0.1,'locator_normal_aim_' + plane)

    #create locator center
    cmds.spaceLocator(n = 'locator_center_' + plane)
    cmds.move(p[0], p[1], p[2], 'locator_center_' + plane)
    cmds.scale(0.1,0.1,0.1,'locator_center_' + plane)

    #create world up object 
    #(todo : get front edge center)
    cmds.spaceLocator(n = 'locator_for_z_' + plane)
    vert = cmds.select(plane +'.vtx[0]')
    p = cmds.xform(vert, q=True, ws=True, t=True)
    cmds.move(p[0],p[1],p[2], 'locator_for_z_' + plane)
    cmds.scale(0.1,0.1,0.1,'locator_for_z_' + plane)

    #set aim constraint
    cmds.aimConstraint('locator_normal_aim_' + plane, 'locator_center_' + plane,
                       wut='object', wuo='locator_for_z_' + plane, 
                       n = 'aim_node_' + plane)

    cmds.parent(plane, 'aim_node_' + plane)
Пример #51
0
def getTopFaces(mesh):
    """ extrude top faces of given meshes """    

    # rooftop faces
    topfaces = []
    cmds.select(mesh, r=True)
    meshFaces = cmds.ls(mesh+".f[*]")
    faces = cmds.ls(meshFaces, fl=True)
    
    # if the face normal is facing the sky, then fill the rooftop faces dict
    for face in faces:
        if float(cmds.polyInfo(face, fn=True)[0].split(' ')[-2]) >= 1.0:
            topfaces.append(face)

    return topfaces
Пример #52
0
	def findWindingOrder(face):
		faceInfo = cmds.polyInfo(face, fv=1 )[0]
		print(faceInfo)
		pieces = faceInfo.split()	# -1, -2, -3
		allVerts = []
		for i in range( 2 , len(pieces) ):
			allVerts.append( "%s.vtx[%s]" %(face.split(".")[0], pieces[i]))
		print(allVerts)
		'''
		# Converts faces into verts (the are return in the proper winding order
		vertex = cmds.polyListComponentConversion( face, tv=True )
		# if any of the verts of compressed into ranges the will be expanded.
		allVerts = cmds.filterExpand( vertex, sm=31, expand=True )
		'''
		return allVerts
Пример #53
0
def facetoVertNRM():  # FIXME fix usage for faces bordering hard edges.
    '''
    sets the vertex normals of the verts contained in a face to that of the face.
    '''
    fs = cmds.filterExpand(sm=34)
    cmds.select(cl=True)
    for f in fs:
        cmds.select(f, r=True)
        normals = cmds.polyInfo(faceNormals=True)
        buf = str(normals).split()
        plane = range(3)
        plane[0] = float(buf[2])
        plane[1] = float(buf[3])
        plane[2] = float(buf[4].rstrip('\\n\']'))
        vtx = cmds.polyListComponentConversion(f, ff=True, tv=True)
        cmds.polyNormalPerVertex(vtx, xyz=[plane[0], plane[1], plane[2]])
Пример #54
0
    def pickSkeleton(s, mesh, faceID):
        """
        Pick a bone, given a skinned mesh and a face ID
        """
        # Get verts from Face
        meshes = s.meshes
        verts = [int(v) for v in findall(r"\s(\d+)\s", cmds.polyInfo("%s.f[%s]" % (mesh, faceID), fv=True)[0])]

        weights = {}
        for joint in meshes[mesh]:
            weights[joint] = weights.get(joint, 0) # Initialize
            weights[joint] = sum([meshes[mesh][joint][v] for v in verts if v in meshes[mesh][joint]])

        if weights:
            maxWeight = max(weights, key=lambda x: weights.get(x))
            return maxWeight
    def process(self, context):
        # meshs = []
        invalid = []
        for result in context.data["results"]:
            if result["plugin"] is not ValidateMeshNonManifold:
                continue

            if result["error"] is None:
                continue

            instance = result["instance"]
            invalid.extend(cmds.polyInfo(instance, nonManifoldVertices=True) or [])

        # meshs = list(set(meshs))
        invalid = list(set(invalid))
        self.log.info("Selecting bad vertices: %s" % ", ".join(invalid))
        cmds.select(cl=True)
        cmds.select(invalid)
Пример #56
0
def createPatchMesh(vertices, normals):
  width = len(vertices)
  height = len(vertices[0])
  
  cmds.polyPlane(n="tp", sx=width-1, sy=height-1, ax=[0, 0, 1])
  
  for j in range(height):
    for i in range(width):
      cmds.select("tp.vtx[%s]" % (j*width+i), r=True)
      cmds.move(vertices[i][j][0], vertices[i][j][1], vertices[i][j][2], a=True)
      cmds.polyNormalPerVertex(xyz=normals[i][j].tolist())

  normalZ = cmds.polyInfo("tp.f[0]", fn=True)[0].split()[-1]
  if normalZ[0]=="-":
    cmds.polyNormal("tp", normalMode=0, userNormalMode=0, ch=1);
  
  cmds.rename("tp", "patch1")
  cmds.select(cl=True)
Пример #57
0
def j_findoutNoVertexMeshObj():#5
    u'''找出没有点的mesh '''
    j_meshNode = mc.ls(type='mesh')
    j_finalObj = []    
    if len(j_meshNode) == 0:
                j_text1 = "THERE IS MESHES IN CURRENT SCENE !"
                return j_text1 ;       
    for i in j_meshNode:
        j_temp = mc.polyInfo(i , fv =1)
        
        if (j_temp == None):
            j_temp = mc.listRelatives(i , parent = 1)
            j_finalObj.append(j_temp[0])
    if len(j_finalObj) == 0:
        j_text2 = "THERE IS MESHES IN CURRENT SCENE !"
        return j_text2 ;               
    else:
        mc.select(j_finalObj , r = 1)
Пример #58
0
 def singleNgons(self, arg=None):
     selObj=self.selection_grab()
     if selObj:
         pass
     else:
         print "select polygon faces"
         return      
     if ".f[" in selObj[0]:
         pass
     else:
         print "You need to make a selection of faces for this tool to interrogate."
         return               
     cmds.select(cl=True)
     if cmds.objExists("Ngons")==True:
         cmds.delete("Ngons")
     cmds.sets(n="Ngons", co=3)
     if cmds.objExists("Tris")==True:
         cmds.delete("Tris")
     cmds.sets(n="Tris", co=3)        
     for face in selObj:
         getComponent = cmds.polyInfo(face, fe=True)
         getVerts=getComponent[0].split(':')[1]
         edgeCount=re.findall(r'\d+', getVerts) 
         if (len(edgeCount))>=5:
             cmds.ConvertSelectionToVertices(face)
             cmds.select (face)
             cmds.sets( fe='Ngons')                
             print "Ngon found"
         if (len(edgeCount))==3:
             cmds.ConvertSelectionToVertices(face)
             cmds.select (face)
             cmds.sets( fe='Tris')
             print "Tri found"           
     cmds.select('Tris', r=True, ne=True)
     cmds.pickWalk(d='Up')
     errorFound=cmds.ls(sl=True)
     if (len(errorFound))==0:
         cmds.delete("Tris")
     cmds.select('Ngons', r=True, ne=True)
     cmds.pickWalk(d='Up')
     errorFound=cmds.ls(sl=True, fl=1)
     if (len(errorFound))==0:
         cmds.delete("Ngons")