Beispiel #1
0
	def _getCreaseFromXML(self, rootPrefix = ''):
		scene_path = os.path.abspath( cmds.file(query = True, sn = True) )
		xmlPath = '%s/Anm/publish/crease_xml/ep000_Docks_Addon.xml' % '/'.join( os.path.abspath( cmds.file(query = True, sn = True) ).replace('\\', '/').split('/')[:5] ) if scene_path else ''

		print xmlPath

		if os.path.isfile(xmlPath):
			tree = ET.parse(xmlPath)
			root = tree.getroot()
			if root.tag == 'CreaseXML':

				for mesh in root.getchildren():
					mesh_name = mesh.attrib.get('name')
					mesh_name = '|'.join( [x.split(':')[-1] for x in mesh_name.split('|')] )
					mesh_name = '%s%s' % (rootPrefix, mesh_name) if rootPrefix else mesh_name

					if cmds.objExists(mesh_name):
						for edge in mesh.getchildren():
							vertexA 	= int( edge.attrib.get('vertexA') )
							vertexB 	= int( edge.attrib.get('vertexB') )
							creaseValue = edge.attrib.get('creaseValue')
							edgeID 		= cmds.polyListComponentConversion('%s.vtx[%d]' % (mesh_name, vertexA), '%s.vtx[%d]' % (mesh_name, vertexB), fromVertex = 1, toEdge = 1, internal = 1)[0].split('.')[-1]

							if '-inf' not in creaseValue:
								cmds.polyCrease( '%s.%s' % (mesh_name, edgeID), value = float(creaseValue) )
					else:
						cmds.warning('%s doesn\'t exist, skipping...' % mesh_name)
			else:
				cmds.warning('Not a valid xml...')
		else:
			cmds.warning('Not a valid crease xml path...')
Beispiel #2
0
def creaseHardEdges():
    #crsAmt = 10
    crsAmt = cmds.floatSliderGrp('crsAmt', q=True, value=True)
    cmds.selectType(pe=True)  # Selects Edges
    cmds.polySelectConstraint(m=3, t=0x8000,
                              sm=1)  # Constrains selection to hard edges
    cmds.polyCrease(value=crsAmt)
    cmds.polySelectConstraint(sm=0)  # Turns off contraint
Beispiel #3
0
def clearCrease():
    """ Select edges matching a specific crease value """
    sel = cmds.ls(sl=True, l=True)
    edgeCollection = cmds.polyListComponentConversion(sel, te=True)
    edges = cmds.filterExpand(edgeCollection, sm=32, expand=True)

    for edge in edges:
        cmds.polyCrease(edge, ch=True, value=0, vertexValue=0)
Beispiel #4
0
def filterCrease(polyName, wholeDelArrayTemp, isProtectCreaseLoop=True):
    arrayWithoutCrease = []
    noneCreaseArray = []
    creaseArray = []
    for pwda in wholeDelArrayTemp:
        fullString = '%s.e[%s]' % (polyName, str(pwda))
        cVal = cmds.polyCrease(fullString, q=1, value=1)
        if cVal[0] <= 0:
            noneCreaseArray.append(int(pwda))
        else:
            creaseArray.append(int(pwda))
    #

    creaseProtectArray = []
    if isProtectCreaseLoop:
        for i in creaseArray:
            edgeLoop = cmds.polySelect(polyName, edgeLoop=int(i), ass=0, q=1)
            for el in edgeLoop:
                creaseProtectArray.append(int(el))

        for i in noneCreaseArray:
            if i not in creaseProtectArray:
                arrayWithoutCrease.append(i)
    else:
        arrayWithoutCrease = list(noneCreaseArray)

    return arrayWithoutCrease
def writeCreaseData(rootName='', pathToXML=''):
    """
    Function to write out crease data.
    """
    ## Delete existing
    if checkFilePath(pathToXML):
        os.remove(pathToXML)

    ## now process the data into the xml tree
    root = Element(rootName)
    tree = ElementTree(root)

    ## process the scene's geo now...
    creaseDict = {}
    for eachMesh in cmds.ls(type='mesh'):
        getParent = cmds.listRelatives(eachMesh, parent=True, f=True)[0]
        edgeCount = cmds.polyEvaluate(eachMesh, e=True)

        for x in range(0, edgeCount):
            if cmds.polyCrease('%s.e[%s]' %
                               (getParent, x), q=True, v=True)[0] != -1.0:
                getInfo = [
                    x,
                    cmds.polyCrease('%s.e[%s]' % (getParent, x),
                                    q=True,
                                    v=True)[0]
                ]
                if not getParent in creaseDict.keys():
                    creaseDict[getParent] = []
                    creaseDict[getParent].append(getInfo)
                else:
                    if getInfo not in creaseDict[getParent]:
                        creaseDict[getParent].append(getInfo)

    ## Now process the dictionary into the xml tree
    for key, var in creaseDict.items():
        geoName = Element(str(key.replace('|', '_iPipei_')))
        root.append(geoName)
        if var:  ## need a valid list of objects to write else just ignore the darn things...
            for each in var:
                creaseData = SubElement(geoName,
                                        'idx_%s' % str(each[0]),
                                        value=str(each[1]).replace(
                                            '.', '_iPeriodi_'))

    tree.write(open(pathToXML, 'w'), encoding="utf-8")
Beispiel #6
0
    def _colorize(cls, node):
        """"Colorize the mesh by using the crease functionality

        Args:
            node: can be the vis_node, bevel_node or src_node

        """
        bevel_node = cls.get_vis_bevel(node)
        if bevel_node is None:
            raise RuntimeError("Bevel not found on %s" % node)

        edges = cls.get_bevel_edges(bevel_node)
        vis_node = cls.get_vis_node(node)
        # Remove the crease from all the edges
        cmds.polyCrease(vis_node + ".e[:]", createHistory=False, value=0)
        # Set the crease of all the edges
        # value does not bolden the display in the viewport
        cmds.polyCrease(edges, createHistory=False, value=5)
Beispiel #7
0
    def _getCreaseFromXML(self, rootPrefix=''):
        scene_path = os.path.abspath(cmds.file(query=True, sn=True))
        xmlPath = '%s/Anm/publish/crease_xml/ep000_Docks_Addon.xml' % '/'.join(
            os.path.abspath(cmds.file(query=True, sn=True)).replace(
                '\\', '/').split('/')[:5]) if scene_path else ''

        print xmlPath

        if os.path.isfile(xmlPath):
            tree = ET.parse(xmlPath)
            root = tree.getroot()
            if root.tag == 'CreaseXML':

                for mesh in root.getchildren():
                    mesh_name = mesh.attrib.get('name')
                    mesh_name = '|'.join(
                        [x.split(':')[-1] for x in mesh_name.split('|')])
                    mesh_name = '%s%s' % (
                        rootPrefix, mesh_name) if rootPrefix else mesh_name

                    if cmds.objExists(mesh_name):
                        for edge in mesh.getchildren():
                            vertexA = int(edge.attrib.get('vertexA'))
                            vertexB = int(edge.attrib.get('vertexB'))
                            creaseValue = edge.attrib.get('creaseValue')
                            edgeID = cmds.polyListComponentConversion(
                                '%s.vtx[%d]' % (mesh_name, vertexA),
                                '%s.vtx[%d]' % (mesh_name, vertexB),
                                fromVertex=1,
                                toEdge=1,
                                internal=1)[0].split('.')[-1]

                            if '-inf' not in creaseValue:
                                cmds.polyCrease('%s.%s' % (mesh_name, edgeID),
                                                value=float(creaseValue))
                    else:
                        cmds.warning('%s doesn\'t exist, skipping...' %
                                     mesh_name)
            else:
                cmds.warning('Not a valid xml...')
        else:
            cmds.warning('Not a valid crease xml path...')
def selectCreasesEdges(object):
	"""
	This definition cleans Maya hierarchical polygonal conversion.

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

	edges = cmds.ls(object + ".e[0:" + str(cmds.polyEvaluate(object, edge=True) - 1) + "]", fl=True)
	creaseEdges = [edge for edge in edges if cmds.polyCrease(edge, q=True, v=True)[0] > 0.0]
	if creaseEdges:
		cmds.select(creaseEdges)
Beispiel #9
0
    def getVertInformation(self,
                           polyName,
                           isMoreThan4=True,
                           is2=True,
                           is3=False):
        polyCount = cmds.polyEvaluate(polyName, v=1)

        vertArray = []
        midVertArray = []
        creaseVertexArray = []
        if isMoreThan4 or is2 or is3:
            for i in range(polyCount):
                vert = '%s.vtx[%s]' % (polyName, str(i))

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

                edgeID = self.cleanInfos(edgeInfo[0])

                # get vert who own the defined number of edges.
                IDlength = len(edgeID)

                isThisVertexImportent = False
                if isMoreThan4:
                    if IDlength > 4:
                        vertArray.append(i)
                        isThisVertexImportent = True
                if is2:
                    if IDlength == 2:
                        vertArray.append(i)
                        isThisVertexImportent = True
                if is3:
                    if IDlength == 3:
                        vertArray.append(i)
                        isThisVertexImportent = True

                # get middle edges.may be more than 1.as also are two.
                vertPos = cmds.xform(vert, q=1, ws=1, t=1)
                if round(vertPos[0], 6) == 0:
                    midVertArray.append(i)

                # get crease vertex.this vertex just for 2,3,5 and 5+ stars vertex.
                if isThisVertexImportent:
                    cVal = cmds.polyCrease(vert, q=1, vertexValue=1)
                    if cVal[0] > 0:
                        creaseVertexArray.append(int(i))
            return {
                'keyVerts': vertArray,
                'middleVerts': midVertArray,
                'creaseVerts': creaseVertexArray
            }
        else:
            print 'you need defined a type of vert to get.isMoreThan4 or is2 or is3?'
            return False
Beispiel #10
0
def selectCreasesEdges(object):
	"""
	Cleans Maya hierarchical polygonal conversion.

	:param object: Object to select creases edges.
	:type object: str
	"""

	edges = cmds.ls(object + ".e[0:" + str(cmds.polyEvaluate(object, edge=True) - 1) + "]", fl=True)
	creaseEdges = [edge for edge in edges if cmds.polyCrease(edge, q=True, v=True)[0] > 0.0]
	if creaseEdges:
		cmds.select(creaseEdges)
Beispiel #11
0
def ldmt_turboSmooth():
    mods = cmds.getModifiers()
    mel.eval('resetPolySelectConstraint;')
    sel = cmds.ls(sl=1,o=1)
    sel = sel[0]
    cmds.select(sel+'.e[*]',r=1)
    cmds.polySelectConstraint(m=3,t=0x8000,sm=1)
    cmds.sets(n="ldmt_turboSmoothQS")
    currentSel = cmds.ls(sl=1)
    if currentSel != []:
        try:
            cmds.polyCrease(value=1)
        except:
            pass
    cmds.select(sel,r=1)
    cmds.polySmooth(sel,mth=0,sdt=2,ovb=2,ofb=3,ofc=1,ost=1,ocr=1,dv=1,bnr=1,c=0,kb=0,ksb=1,khe=1,kt=0,kmb=0,suv=1,peh=1,sl=1,dpe=1,ps=0.1,ro=1,ch=1)
    cmds.select("ldmt_turboSmoothQS",r=1)
    currentSel = cmds.ls(sl=1)
    if currentSel != []:
        try:
            cmds.polySoftEdge(a=0,ch=1)
            cmds.polyCrease(value=0)
        except:
            pass
        if mods == 4:
            try:
                cmds.polyCrease(value=1)
            except:
                pass
    cmds.polySelectConstraint(m=0,dis=1)
    cmds.select(sel,r=1)
    cmds.delete("ldmt_turboSmoothQS")
def writeCreaseData(rootName = '', pathToXML = ''):
    """
    Function to write out crease data.
    """
    ## Delete existing
    if checkFilePath(pathToXML):
        os.remove(pathToXML)
    
    ## now process the data into the xml tree   
    root = Element(rootName)
    tree = ElementTree(root)
    
    ## process the scene's geo now...
    creaseDict = {}
    for eachMesh in cmds.ls(type = 'mesh'):
        getParent = cmds.listRelatives(eachMesh, parent = True, f = True)[0]
        edgeCount = cmds.polyEvaluate(eachMesh, e = True)
        
        for x in range(0, edgeCount):
            if cmds.polyCrease('%s.e[%s]' % (getParent, x), q = True, v = True)[0] != -1.0:
                getInfo = [x, cmds.polyCrease('%s.e[%s]' % (getParent, x), q = True, v = True)[0]]
                if not getParent in creaseDict.keys():
                    creaseDict[getParent] = []
                    creaseDict[getParent].append(getInfo)
                else:
                    if getInfo not in creaseDict[getParent]:
                        creaseDict[getParent].append(getInfo)
    
    ## Now process the dictionary into the xml tree
    for key, var in creaseDict.items():
        geoName = Element(str(key.replace('|', '_iPipei_')))
        root.append(geoName)
        if var: ## need a valid list of objects to write else just ignore the darn things...
            for each in var:
                creaseData = SubElement(geoName, 'idx_%s' % str(each[0]), value = str(each[1]).replace('.', '_iPeriodi_'))   
    
    tree.write(open(pathToXML, 'w'), encoding="utf-8")
def readCreaseData(pathToXML = '', parentGrp = ''):
    
    tree = ET.parse(pathToXML)
    root = tree.getroot()
    
    debug(None, method = 'crease_readXML.readCreaseData', message = '{0:<10}{1}'.format('ASSETNAME: ',  root.tag), verbose = False)
    
    ## Now process the xml   
    geoToProcess = root.getchildren()
    if not geoToProcess:
        cmds.warning('THERE IS NO DATA WRITTEN TO FILE: %s' % pathToUVXML)
    else:
        ## Process each geos data now
        for eachGeo in geoToProcess:
            geo  = '%s%s' % (parentGrp, eachGeo.tag.replace('_iPipei_', '|'))
            debug(None, method = 'crease_readXML.readCreaseData', message = '{0:<10}{1}'.format('geo: ',  geo), verbose = False)
            
            edges = eachGeo.getchildren()
            debug(None, method = 'crease_readXML.readCreaseData', message = '{0:<10}{1}'.format('edges: ',  edges), verbose = False)
            for eachChild in edges:
                #print int(eachChild.tag.split('idx_')[-1])
                #print float(eachChild.attrib['value'].replace('_iPeriodi_', '.'))
                cmds.polyCrease('%s.e[%s]' % (geo, int(eachChild.tag.split('idx_')[-1])), e = True, v = float(eachChild.attrib['value'].replace('_iPeriodi_', '.')))
                
Beispiel #14
0
def readCreaseData(pathToXML='', parentGrp=''):

    tree = ET.parse(pathToXML)
    root = tree.getroot()

    debug(None,
          method='crease_readXML.readCreaseData',
          message='{0:<10}{1}'.format('ASSETNAME: ', root.tag),
          verbose=False)

    ## Now process the xml
    geoToProcess = root.getchildren()
    if not geoToProcess:
        cmds.warning('THERE IS NO DATA WRITTEN TO FILE: %s' % pathToUVXML)
    else:
        ## Process each geos data now
        for eachGeo in geoToProcess:
            geo = '%s%s' % (parentGrp, eachGeo.tag.replace('_iPipei_', '|'))
            debug(None,
                  method='crease_readXML.readCreaseData',
                  message='{0:<10}{1}'.format('geo: ', geo),
                  verbose=False)

            edges = eachGeo.getchildren()
            debug(None,
                  method='crease_readXML.readCreaseData',
                  message='{0:<10}{1}'.format('edges: ', edges),
                  verbose=False)
            for eachChild in edges:
                #print int(eachChild.tag.split('idx_')[-1])
                #print float(eachChild.attrib['value'].replace('_iPeriodi_', '.'))
                cmds.polyCrease('%s.e[%s]' %
                                (geo, int(eachChild.tag.split('idx_')[-1])),
                                e=True,
                                v=float(eachChild.attrib['value'].replace(
                                    '_iPeriodi_', '.')))
Beispiel #15
0
def selectCrease(creaseValue=0):
    """ Select edges matching a specific crease value """
    sel = cmds.ls(sl=True, l=True)
    edgeCollection = cmds.polyListComponentConversion(sel, te=True)
    edges = cmds.filterExpand(edgeCollection, sm=32, expand=True)

    creasedEdges = []

    for edge in edges:
        edgeValue = cmds.polyCrease(edge, query=True, value=True)
        if creaseValue == 0:
            if edgeValue[0] > 0:
                creasedEdges.append(edge)
        else:
            if edgeValue[0] == creaseValue:
                creasedEdges.append(edge)
    cmds.select(creasedEdges)
Beispiel #16
0
    def getStructVerts(self, is2=True, is4=True):

        if is2 or is4:

            polyCount = cmds.polyEvaluate(self.polyName, v=1)

            vertArray = []
            midVertArray = []
            creaseVertexArray = []

            for i in range(polyCount):

                vert = '%s.vtx[%s]' % (self.polyName, str(i))
                edgeInfo = cmds.polyInfo(vert, vertexToEdge=1)
                edgeID = self.cleanInfos(edgeInfo[0])

                # get vert who own the defined number of edges.
                IDlength = len(edgeID)

                isThisVertexImportent = False
                if is4:
                    if IDlength > 4:
                        vertArray.append(i)
                        isThisVertexImportent = True
                if is2:
                    if IDlength == 2:
                        vertArray.append(i)
                        isThisVertexImportent = True

                # get middle edges.may be more than 1.as also are two.
                vertPos = cmds.xform(vert, q=1, ws=1, t=1)
                if round(vertPos[0], 6) == 0:
                    midVertArray.append(i)

                # get crease vertex.this vertex just for 2,3,5 and 5+ stars vertex.
                if isThisVertexImportent:
                    cVal = cmds.polyCrease(vert, q=1, vertexValue=1)
                    if cVal[0] > 0:
                        creaseVertexArray.append(int(i))

            self.keyVerts = vertArray
            self.middleVerts = midVertArray
            self.creaseVerts = creaseVertexArray
Beispiel #17
0
    def filterCrease(self,
                     polyName,
                     wholeDelArrayTemp,
                     isProtectCreaseLoop=True):

        arrayWithoutCrease = []

        noneCreaseArray = []

        creaseArray = []

        self.progress.setMaximum(len(wholeDelArrayTemp))
        self.progress.setLabelText('filter Crease...')
        self.progress.setValue(0)

        for count, pwda in enumerate(wholeDelArrayTemp):
            self.progress.setValue(count)
            fullString = '%s.e[%s]' % (polyName, str(pwda))
            cVal = cmds.polyCrease(fullString, q=1, value=1)
            if cVal[0] <= 0:
                noneCreaseArray.append(int(pwda))
            else:
                creaseArray.append(int(pwda))

        creaseProtectArray = []

        if isProtectCreaseLoop:
            for i in creaseArray:
                edgeLoop = cmds.polySelect(polyName,
                                           edgeLoop=int(i),
                                           ass=0,
                                           q=1)
                for el in edgeLoop:
                    creaseProtectArray.append(int(el))

            for i in noneCreaseArray:
                if i not in creaseProtectArray:
                    arrayWithoutCrease.append(i)
        else:
            arrayWithoutCrease = list(noneCreaseArray)

        return arrayWithoutCrease
Beispiel #18
0
    def getAllVertsWhoHave5edges(self,
                                 polyName,
                                 isMoreThan4=True,
                                 is2=True,
                                 is3=False):
        polyCount = cmds.polyEvaluate(polyName, v=1)

        self.progress.setMaximum(polyCount)
        self.progress.setLabelText('analyzing...')
        self.progress.setValue(0)

        vertArray = []
        midEdgeArray = []
        creaseVertexArray = []
        if isMoreThan4 or is2 or is3:
            for i in range(polyCount):

                self.progress.setValue(i)

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

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

                edgeID = self.cleanInfos(edgeInfo[0])

                # get vert who own the defined number of edges.
                IDlength = len(edgeID)

                isThisVertexImportent = False
                if isMoreThan4:
                    if IDlength > 4:
                        vertArray.append(i)
                        isThisVertexImportent = True
                if is2:
                    if IDlength == 2:
                        vertArray.append(i)
                        isThisVertexImportent = True
                if is3:
                    if IDlength == 3:
                        vertArray.append(i)
                        isThisVertexImportent = True

                # get middle edges.may be more than 1.as also are two.
                vertPos = cmds.xform(vert, q=1, ws=1, t=1)
                if round(vertPos[0], 6) == 0:
                    for eid in edgeID:
                        edg = '%s.e[%s]' % (polyName, str(eid))
                        edgePos = cmds.xform(edg, q=1, ws=1, t=1)
                        if round(edgePos[0], 6) == 0 and round(edgePos[3],
                                                               6) == 0:
                            midEdgeArray.append(int(eid))
                            break

                # get crease vertex.this vertex just for 2,3,5 and 5+ stars vertex.

                if isThisVertexImportent:
                    cVal = cmds.polyCrease(vert, q=1, vertexValue=1)
                    if cVal[0] > 0:
                        creaseVertexArray.append(int(i))
            #print 'crease vert:'
            #print creaseVertexArray
            return [vertArray, midEdgeArray, creaseVertexArray]
        else:
            print 'you need defined a type of vert to get.isMoreThan4 or is2 or is3?'
            return False
Beispiel #19
0
    def _writeCreaseToXML(self):
        scene_path = os.path.abspath(
            cmds.file(query=True, sn=True)
        )  # I:\bubblebathbay\episodes\ep106\ep106_sh030\FX\work\maya\ep106sh030.v025.ma
        xmlPath = '%s/publish/crease_xml/ep000_Docks_Addon.xml' % '/'.join(
            os.path.abspath(cmds.file(query=True, sn=True)).replace(
                '\\', '/').split('/')[:6]) if scene_path else ''

        if os.path.isdir(os.path.dirname(xmlPath)):
            ## Get all mesh in scene with all their edges intact i.e. |pCube1|pCubeShape1.e[0:11] (Filter out intermediate object as well as they don't get cache out)
            meshes = [
                '%s.e[0:%s]' % (mesh, cmds.polyEvaluate(mesh, edge=True) - 1)
                for mesh in cmds.ls(type='mesh', long=True)
                if not cmds.getAttr('%s.intermediateObject' % mesh)
                if cmds.polyEvaluate(mesh, edge=True)
            ]
            if meshes:
                edge_creases = []

                for mesh in meshes:
                    mesh_name = mesh.split('.')[0]
                    edges = cmds.polyCrease(mesh, value=True, q=True)

                    if edges:
                        crease_edges = []
                        for edge, value in enumerate(edges, start=0):
                            if value > 0:  ## 0 means no crease, more than 0 means crease...

                                ## 2 vertices = 1 edge. Therefore, get edge's vertices id...
                                crease_edges.append((
                                    filter(
                                        None,
                                        cmds.polyInfo(
                                            '%s.e[%s]' % (mesh_name, edge),
                                            edgeToVertex=True)[0].split(':')
                                        [-1].replace('Hard', '').replace(
                                            '\n',
                                            '').split(' '))[0],  ## Vertex A
                                    filter(
                                        None,
                                        cmds.polyInfo(
                                            '%s.e[%s]' % (mesh_name, edge),
                                            edgeToVertex=True)[0].split(':')
                                        [-1].replace('Hard', '').replace(
                                            '\n',
                                            '').split(' '))[1],  ## Vertex B
                                    str(
                                        value
                                    ),  ## Crease value (Reason why we put it as string is because somehow maya sometimes return value "-inf" which's going to be troublesome when applying crease to poly later...
                                ))
                        edge_creases.append(
                            (mesh_name,
                             crease_edges)) if crease_edges else None

                if edge_creases:
                    ## Process root
                    root = ET.Element('CreaseXML')

                    for each in edge_creases:
                        mesh = '|'.join(
                            [x.split(':')[-1] for x in each[0].split('|')]
                        )  ## Get rid of object names that has ":" in it as it will be stripped out during alembic cache anyways...
                        if 'geo_hrc' in mesh:
                            mesh = '|%s' % '|'.join(
                                mesh.split('|')[([
                                    i for
                                    (i,
                                     x) in enumerate(mesh.split('|'), start=0)
                                    if x == 'geo_hrc'
                                ][0] - 1):]
                            )  ## Get full name until root of geo_hrc

                        meshElem = ET.SubElement(root, 'Mesh')
                        meshElem.set('name', mesh)

                        for child in each[1]:
                            vertexA = child[0]
                            vertexB = child[1]
                            creaseValue = child[2]

                            edgeElem = ET.SubElement(meshElem, 'Edge')
                            edgeElem.set('vertexA', vertexA)
                            edgeElem.set('vertexB', vertexB)
                            edgeElem.set('creaseValue', creaseValue)

                    ## Make directory if it doesn't exist
                    if not os.path.exists(os.path.dirname(xmlPath)):
                        os.makedirs(os.path.dirname(xmlPath))

                    ## Process XML to output nicely so it's human readable i.e. not everything in 1 line
                    self._prettyPrintXML(root)
                    tree = ET.ElementTree(root)

                    ## Output .xml into directory
                    tree.write(xmlPath, encoding='utf-8')
Beispiel #20
0
 def creaseTool(self):
     cmds.polyCrease(value=0.9)
     self.setAttributes(attrs=[('Offset',
                                '.offset'), ('Segments', '.segments')])
     self.Dragger(X, 'Bevel')
Beispiel #21
0
def unCrease():
    cmds.selectType(pe=True)  # Selects Edges
    if (cmds.polyCrease(q=True, value=True) >
            0):  # Tests to see if there are creases
        cmds.polyCrease(value=0.0)  # Uncreases
Beispiel #22
0
	def _writeCreaseToXML(self):
		scene_path = os.path.abspath( cmds.file(query = True, sn = True) ) # I:\bubblebathbay\episodes\ep106\ep106_sh030\FX\work\maya\ep106sh030.v025.ma
		xmlPath = '%s/publish/crease_xml/ep000_Docks_Addon.xml' % '/'.join( os.path.abspath( cmds.file(query = True, sn = True) ).replace('\\', '/').split('/')[:6] ) if scene_path else ''

		if os.path.isdir( os.path.dirname(xmlPath) ):
			## Get all mesh in scene with all their edges intact i.e. |pCube1|pCubeShape1.e[0:11] (Filter out intermediate object as well as they don't get cache out)
			meshes = ['%s.e[0:%s]' % ( mesh, cmds.polyEvaluate(mesh, edge = True) - 1 ) for mesh in cmds.ls(type = 'mesh', long = True) if not cmds.getAttr('%s.intermediateObject' % mesh) if cmds.polyEvaluate(mesh, edge = True)]
			if meshes:
				edge_creases = []

				for mesh in meshes:
					mesh_name = mesh.split('.')[0]
					edges = cmds.polyCrease(mesh, value = True, q = True)

					if edges:
						crease_edges = []
						for edge, value in enumerate(edges, start = 0):
							if value > 0: ## 0 means no crease, more than 0 means crease...

								## 2 vertices = 1 edge. Therefore, get edge's vertices id...
								crease_edges.append(
														(
															filter( None, cmds.polyInfo('%s.e[%s]' % (mesh_name, edge), edgeToVertex = True)[0].split(':')[-1].replace('Hard', '').replace('\n', '').split(' ') )[0], ## Vertex A
															filter( None, cmds.polyInfo('%s.e[%s]' % (mesh_name, edge), edgeToVertex = True)[0].split(':')[-1].replace('Hard', '').replace('\n', '').split(' ') )[1], ## Vertex B
															str(value), ## Crease value (Reason why we put it as string is because somehow maya sometimes return value "-inf" which's going to be troublesome when applying crease to poly later...
														)
													)
						edge_creases.append((mesh_name, crease_edges)) if crease_edges else None

				if edge_creases:
					## Process root
					root = ET.Element('CreaseXML')

					for each in edge_creases:
						mesh = '|'.join( [x.split(':')[-1] for x in each[0].split('|')] ) ## Get rid of object names that has ":" in it as it will be stripped out during alembic cache anyways...
						if 'geo_hrc' in mesh:
							mesh = '|%s' % '|'.join( mesh.split('|')[([i for (i, x) in enumerate(mesh.split('|'), start = 0) if x == 'geo_hrc'][0] - 1):] ) ## Get full name until root of geo_hrc

						meshElem = ET.SubElement(root, 'Mesh')
						meshElem.set('name', mesh)

						for child in each[1]:
							vertexA		= child[0]
							vertexB		= child[1]
							creaseValue	= child[2]

							edgeElem = ET.SubElement(meshElem, 'Edge')
							edgeElem.set('vertexA', vertexA)
							edgeElem.set('vertexB', vertexB)
							edgeElem.set('creaseValue', creaseValue)

					## Make directory if it doesn't exist
					if not os.path.exists( os.path.dirname(xmlPath) ):
						os.makedirs( os.path.dirname(xmlPath) )

					## Process XML to output nicely so it's human readable i.e. not everything in 1 line
					self._prettyPrintXML(root)
					tree = ET.ElementTree(root)

					## Output .xml into directory
					tree.write(xmlPath, encoding = 'utf-8')
Beispiel #23
0
	def creaseTool(self):
		cmds.polyCrease( value=0.9 )
		self.setAttributes( attrs = [ ('Offset', '.offset'), ('Segments', '.segments') ] )
		self.Dragger( X , 'Bevel')
Beispiel #24
0
    def CreateDoorBase(self,
                       name="doorBase",
                       width=_wallbaseWidth,
                       height=_wallbaseHeight,
                       divisions=2):
        if cmds.objExists(name):
            return name
        door = cmds.polyPlane(name=name,
                              w=1,
                              h=1,
                              sx=2,
                              sy=2,
                              cuv=2,
                              ch=1,
                              ax=[1, 0, 0])

        cmds.move(0, height / 2, 0, a=True)

        cmds.polySelect(name, edgeRing=1)
        cmds.polyCrease(value=0.9)

        cmds.select(f'{name}.f[0:]', r=True)
        cmds.sets(e=True, forceElement=self._matWall)

        offset = cmds.polyExtrudeFacet(constructionHistory=True,
                                       keepFacesTogether=True,
                                       offset=0.05,
                                       divisions=divisions)

        cmds.setAttr(f'{offset[0]}.localTranslate', 0, 0.05, 0)

        cmds.scale(1, 1, 0.6, r=True, p=[0, 0.45, 0])

        cmds.polyExtrudeFacet(constructionHistory=True,
                              keepFacesTogether=True,
                              thickness=0.05,
                              divisions=divisions)
        cmds.sets(e=True, forceElement=self._matDoorFrame)

        cmds.polyExtrudeFacet(constructionHistory=True,
                              keepFacesTogether=True,
                              offset=0.02,
                              divisions=divisions)

        cmds.polyExtrudeFacet(constructionHistory=True,
                              keepFacesTogether=True,
                              thickness=-0.2,
                              divisions=divisions)
        cmds.sets(e=True, forceElement=self._matDoor)

        cmds.select(f'{name}.f[4:8]', r=True)
        cmds.polyDelFacet()

        cmds.select(door)
        cmds.polyBevel3(fraction=0.1,
                        offsetAsFraction=1,
                        autoFit=1,
                        depth=1,
                        mitering=0,
                        miterAlong=0,
                        chamfer=0,
                        segments=2,
                        worldSpace=1,
                        smoothingAngle=30)

        #freeze transformations
        cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1)
        return door[0]
Beispiel #25
0
import json
import os
#find current workspace
prePath = cmds.workspace(q=True, dir=True)
#find project name from the workspace path(projectPath variable)
trimPath = prePath.find('/', 41)
firstCut = prePath.find('/', 35) + 1
lastCut = prePath.find('/', firstCut)
projectPath = prePath[firstCut:lastCut]
#Within a given nnumber range(1-10):
for i in range(10):
    #attach the number to the full path (thus creating a path to all the potential files)
    fullPath = prePath[:
                       trimPath] + '/data/creaseData/' + projectPath + '_0%d' % (
                           i) + '.txt'
    if os.path.exists(fullPath):
        #if the file at a specific path exists, then open it and attach information from it to variables
        #if the file at a specific path does NOT exist, then it will keep going down the path
        f = open(fullPath)
        dataFile = json.load(f)
        value = dataFile[-1]
        creaseSel = dataFile[:-1]
        numbOfEdges = len(creaseSel)
        #for all the edges in the variables creaseSel, select them and then apply the crease at the specified crease value
        #if the edges in the files found don't exist, their will be a value error(no object found) but the script will keep going
        for i in creaseSel:
            try:
                cmds.select(creaseSel)
                cmds.polyCrease(ch=True, v=value)
            except ValueError as e:
                print(e)
Beispiel #26
0
def polyCrease(*args, **kwargs):
    res = cmds.polyCrease(*args, **kwargs)
    if not kwargs.get('query', kwargs.get('q', False)):
        res = _factories.maybeConvert(res, _general.PyNode)
    return res
Beispiel #27
0
1.    When making creases- select edges to crease, then create a crease set.  For name- use projectname followed by "_0#" (ex: WIND_01,
      WIND_02,etc.).  This script will only load files in a specific folder with the name of the project as the name of the file.
2.    Crease the edges like normal, using the crease tool
3.    Select the crease set in the outliner, then run script (one instance per crease set)
'''
import os
import maya.cmds as cmds
import json
#get current selection (crease set)
currentSel = cmds.ls(sl=True)
creaseSetName = currentSel[0]
#select children of current selection (edges)
cmds.select(currentSel, ne=False)
selChild = cmds.ls(sl=True)
#get crease value of edges
creaseValue = cmds.polyCrease(q=True, v=True)
valueList = [creaseValue[0]]

#store the creaseset information into variable (the selected edges and the crease value)
toSave = selChild + valueList

#find current workpath
prePath = cmds.workspace(q=True, dir=True)
trimPath = prePath.find('/', 41)
dataPath = prePath[:trimPath] + '/data/'
folderPath = dataPath + '/creaseData/'

#check to see if folder exists already
ifExist = os.path.exists(folderPath)
if not ifExist:
    #make folder to store .txt files
Beispiel #28
0
def setCrease(creaseValue):
    """ Set edges to a specific crease value """
    selection = cmds.ls(sl=True, fl=True)
    for edge in selection:
        cmds.polyCrease(edge, ch=True, value=creaseValue, vertexValue=0)