def closestUV(mesh, point=(0, 0, 0), uvSet=""): """ Get the UV of the closest point on a mesh to a specified point @param mesh: Mesh to query @type mesh: str @param point: Find the closest point to THIS point @type point: tuple """ # Check mesh if not isMesh(mesh): raise Exception('Object "' + mesh + '" is not a valid mesh!') # Check uvSet if not uvSet: currentUvSet = mc.polyUVSet(mesh, q=True, cuv=True) if not currentUvSet: raise Exception('Mesh "' + mesh + '" has no valid uvSet!') uvSet = currentUvSet[0] if not mc.polyUVSet(mesh, q=True, auv=True).count(uvSet): raise Exception('Invalid UV set "' + uvSet + '" specified!"') # Get mesh function set meshFn = getMeshFn(mesh) # Get closest UV pnt = OpenMaya.MPoint(point[0], point[1], point[2], 1.0) uv = OpenMaya.MScriptUtil() uv.createFromList([0.0, 0.0], 2) uvPtr = uv.asFloat2Ptr() meshFn.getUVAtPoint(pnt, uvPtr, OpenMaya.MSpace.kWorld, uvSet) # Return result return (uv.getFloat2ArrayItem(uvPtr, 0, 0), uv.getFloat2ArrayItem(uvPtr, 0, 1))
def renameUVSet(self): # スキンウェイト書き戻し用、ウェイトを保存しておく。 if self.uvSetAll[0] != "map1" or len(self.uvSetAll) > 1: weight.WeightCopyPaste().main(self.mesh, mode="copy", saveName=__name__) for self.var in range(1, self.uvNum + 1): var = str(self.var) renameSet = self.uvSetAll[self.var - 1] if renameSet != self.defaultName + var: print("Rename UV Set : " + self.mesh + "." + renameSet + " >>> " + self.defaultName + var) # transfer_weight(self.mesh,skinTemp[0]) # デフォーマヒストリも削除しないとリネーム後UVなくなる cmds.bakePartialHistory(self.shapes, preCache=True) cmds.polyUVSet( self.mesh, uvSet=renameSet, newUVSet=self.defaultName + var, e=True, rename=True, ) # ウェイトを書き戻してくる weight.WeightCopyPaste().main(self.mesh, mode="paste", saveName=__name__)
def crenupMultiUV(self): self.defaultName = "map" # デフォルト名 # print(self.mesh) shapes = cmds.listRelatives(self.mesh, s=True, pa=True) self.shapes = shapes[0] # ヒストリ削除 cmds.bakePartialHistory(self.shapes, ppt=True) # cmds.bakePartialHistory(self.shapes,preCache=True) self.uvSetAll = cmds.polyUVSet(self.mesh, q=True, allUVSets=True) self.currentSet = cmds.polyUVSet(self.mesh, q=True, currentUVSet=True) # 現在のUVが空かどうか調べてスキップフラグがTrueなら関数抜ける if not self.checkCurrentUV(): print("Skip (No UV in Current UVSet) : " + self.mesh) return self.delUVFlag = True self.uvNum = 1 # マルチUVリネーム用 # マルチUVの指定名があれば削除フラグをFalseに if "Multi_UV" in self.mesh or self.delMultiUV is False: self.delUVFlag = False self.uvNum = len(self.uvSetAll) # マルチUVリネーム用 if len(self.uvSetAll) > 0: # UVセットがあったら self.deleteUV() # UVセットの名前を変更、マルチUVの場合は繰り返し処理 self.renameUVSet() # UVセットが複数の場合セットに追加する if self.groupMultiUV is True and len(self.uvSetAll) > 1: cmds.sets(self.mesh, add="Multi_UV_Set") # setに追加
def getUVs(self): # Getting current uvset currUVSet = cmds.polyUVSet(self.name, q=True, currentUVSet=True)[0] for i, uvSet in enumerate(self.uvSets): self.uvs[uvSet] = [] # Setting uvSet temp cmds.polyUVSet(self.name, currentUVSet=True, uvSet=uvSet) # Get uv maps uvMaps = cmds.polyListComponentConversion(self.name, ff=1, tuv=1) if (uvMaps): uvMaps = [ cmds.polyListComponentConversion(vtxFace, tuv=1) for vtxFace in self.vtxFaceNames ] # Check to make sure there are uv's on this face. for uvMap in uvMaps: # Get my uvValues uvCoords = cmds.polyEditUV(uvMap, q=True) self.uvs[uvSet].append(uvCoords) # Returning to orginal uvSet cmds.polyUVSet(self.name, currentUVSet=True, uvSet=currUVSet)
def getUVs(self): # Getting current uvset currUVSet = cmds.polyUVSet( self.name, q=True, currentUVSet=True )[0] for i, uvSet in enumerate(self.uvSets): self.uvs[uvSet] = [] # Setting uvSet temp cmds.polyUVSet( self.name, currentUVSet=True, uvSet=uvSet ) # Get uv maps uvMaps = cmds.polyListComponentConversion( self.name, ff=1, tuv=1 ) # verts = PolyFace.findWindingOrder(self.name) # print(self.vtxFaceNames) # cmds.polyListComponentConversion('pPlane2.vtxFace[2][1]', tuv=1 ) if( uvMaps ): # uvMaps = cmds.filterExpand( uvMaps, expand=True, sm=35 ) uvMaps = [cmds.polyListComponentConversion(vtxFace, tuv=1 ) for vtxFace in self.vtxFaceNames ] # Check to make sure there are uv's on this face. for uvMap in uvMaps: # Get my uvValues uvCoords = cmds.polyEditUV( uvMap, q=True ) self.uvs[uvSet].append(uvCoords) # Returning to orginal uvSet cmds.polyUVSet( self.name, currentUVSet=True, uvSet=currUVSet)
def getUVs(self): # Getting current uvset currUVSet = cmds.polyUVSet(self.name, q=True, currentUVSet=True)[0] for i, uvSet in enumerate(self.uvSets): self.uvs[uvSet] = [] # Setting uvSet temp cmds.polyUVSet(self.name, currentUVSet=True, uvSet=uvSet) # Get uv maps uvMaps = cmds.polyListComponentConversion(self.name, ff=1, tuv=1) # verts = PolyFace.findWindingOrder(self.name) # print(self.vtxFaceNames) # cmds.polyListComponentConversion('pPlane2.vtxFace[2][1]', tuv=1 ) if (uvMaps): # uvMaps = cmds.filterExpand( uvMaps, expand=True, sm=35 ) uvMaps = [ cmds.polyListComponentConversion(vtxFace, tuv=1) for vtxFace in self.vtxFaceNames ] # Check to make sure there are uv's on this face. for uvMap in uvMaps: # Get my uvValues uvCoords = cmds.polyEditUV(uvMap, q=True) self.uvs[uvSet].append(uvCoords) # Returning to orginal uvSet cmds.polyUVSet(self.name, currentUVSet=True, uvSet=currUVSet)
def TryLoadExternalUVs(): with mayaUtils.DebugTimer('TryLoadExternalUVs'): mainMesh = mayaUtils.FindMeshByWildcard('Genesis8Female*', checkForMatWithName='Torso') if mainMesh is None: print 'Error! Can`t find body(Torso) mesh' return cmds.delete(mainMesh, constructionHistory=True) uvMeshFile = os.path.join(env.GetIntermediateFullPath(), env.BASE_FEMALE_MESH_WITH_UV1_NAME + '.obj') uvMeshFileExist = os.path.exists(uvMeshFile) print 'UV mesh file: {} Exist: {}'.format(uvMeshFile, uvMeshFileExist) if not uvMeshFileExist: print 'ABORTED: no uv mesh file found' return uvMesh = cmds.file(uvMeshFile, i=True, returnNewNodes=True)[0] uvMesh = cmds.rename(uvMesh, 'UV_Source') cmds.xform(uvMesh, absolute=True, translation=[0, 0, 100]) cmds.polyUVSet(mainMesh, create=True, uvSet='Tesselation_UV') cmds.transferAttributes(uvMesh, mainMesh, transferPositions=0, transferNormals=0, transferUVs=1, sourceUvSet='map1', targetUvSet='Tesselation_UV', sampleSpace=5) cmds.delete(mainMesh, constructionHistory=True) cmds.delete(uvMesh)
def closestUV(mesh, point=(0, 0, 0), uvSet=''): ''' Get the UV of the closest point on a mesh to a specified point @param mesh: Mesh to query @type mesh: str @param point: Find the closest point to THIS point @type point: tuple ''' # Check mesh if not isMesh(mesh): raise Exception('Object "' + mesh + '" is not a valid mesh!') # Check uvSet if not uvSet: currentUvSet = mc.polyUVSet(mesh, q=True, cuv=True) if not currentUvSet: raise Exception('Mesh "' + mesh + '" has no valid uvSet!') uvSet = currentUvSet[0] if not mc.polyUVSet(mesh, q=True, auv=True).count(uvSet): raise Exception('Invalid UV set "' + uvSet + '" specified!"') # Get mesh function set meshFn = getMeshFn(mesh) # Get closest UV pnt = OpenMaya.MPoint(point[0], point[1], point[2], 1.0) uv = OpenMaya.MScriptUtil() uv.createFromList([0.0, 0.0], 2) uvPtr = uv.asFloat2Ptr() meshFn.getUVAtPoint(pnt, uvPtr, OpenMaya.MSpace.kWorld, uvSet) # Return result return (uv.getFloat2ArrayItem(uvPtr, 0, 0), uv.getFloat2ArrayItem(uvPtr, 0, 1))
def _fix(self, meshAttribute): """ :param str meshAttribute: """ mesh = meshAttribute.split(".")[0] uvSet = cmds.getAttr(meshAttribute) cmds.polyUVSet(mesh, edit=True, delete=True, uvSet=uvSet)
def jointify(name=''): from maya.cmds import * # get mesh transforms import ezLib.transform mTrfs = ezLib.transform.get(shape='mesh') if not mTrfs: raise IOError, 'No mesh shapes found!' if not name: p = mTrfs[0].split('|')[1] if p[0:14] == 'cryExportNode_': name = p.split('_')[1] else: name = 'jointify' js = [] counts = [] for mt in mTrfs: sn = mt.split('|')[-1] # create joints at transform positions pos = xform(mt, q=1, t=1, ws=1) j = createNode('joint', n=(sn + 'joint')) xform(j, t=pos) js.append(j) # plug each channel driver into the appropriate joint for t in 'trs': for d in 'xyz': input = listConnections((mt + '.' + t + d), p=1) if input: connectAttr(input[0], (j + '.' + t + d)) # collect nr of verts - this method collects also children if any counts.append(len(ls(polyListComponentConversion(mt, tv=1), fl=1))) dupMesh = duplicate(mTrfs, renameChildren=1) dupMesh = polyUnite(dupMesh, ch=0) # check for multiple UVsets uvSets = polyUVSet(dupMesh, q=1, allUVSets=1) for i in range(1,len(uvSets)): # for each set other than the 1st: set it, copy to 1st, delete it polyUVSet(dupMesh, currentUVSet=1, uvSet=uvSets[i]) polyCopyUV(dupMesh[0] + '.map[*]', uvSetNameInput=uvSets[i], uvSetName=uvSets[0]) polyUVSet(dupMesh, uvSet=uvSets[i], delete=1) # cleanup history crap delete(dupMesh, ch=1) sc = skinCluster(js, dupMesh)[0] vtxNr = 0 for i in range(len(js)): vtxSel = dupMesh[0] + '.vtx[' + str(vtxNr) + ':' + str(vtxNr + counts[i] - 1) + ']' skinPercent(sc, vtxSel, transformValue=[js[i], 1]) vtxNr += counts[i] root = createNode('joint', n=name + 'rootjoint') setAttr(root + '.drawStyle', 2) parent(js, root) select(root, dupMesh)
def runCmd(self): setName = cmds.textFieldButtonGrp(self.setNameFld, tx=1, q=1) #print('setName:{0}'.format(setName)) curSel = cmds.ls(sl=1,fl=1) for sel in curSel: for uset in cmds.polyUVSet(sel,auv=1,q=1): if uset == setName: cmds.polyUVSet(sel,uvSet=setName,d=1) cmds.deleteUI(self.window)
def make_scene(): cmds.file(new=True, f=True) cmds.polyPlane(w=1, sw=2, h=1, sh=1, name="square") cmds.polyUVSet(create=True, uvSet="map2") cmds.polyUVSet(copy=True, uvSet="map1", newUVSet="map2") mel.eval("displayStyle -textured;") mel.eval("displayStyle -wireframeOnShaded;") cmds.file(rename="C:\\TwoPolygonMesh.ma") cmds.file(type="mayaAscii", save=True)
def rename_uvset(mesh, original, newname): try: cmds.polyUVSet(mesh, rename=True, uvSet=original, newUVSet=newname) except RuntimeError: cls.log.error("Mesh '%s' UVSet '%s' cannot be renamed." % (mesh, original))
def replaceLightMap(self, none): self.currentMapCheck = cmds.optionMenuGrp(self.uvSetChoice, q=True, v=True) if self.inputLightmap == self.currentMapCheck: OpenMaya.MGlobal.displayError("Can't overwrite uv set of the same name.") cmds.deleteUI(self.replaceWindow) else: OpenMaya.MGlobal.displayInfo("Lightmap '" + self.inputLightmap + "' exists, overwriting") cmds.polyUVSet(self.selFace, uvs=self.inputLightmap, d=True) #delete lightmap if already exists self.copyAndLayout() cmds.deleteUI(self.replaceWindow)
def Delete_UvsetApply(): renamecheckbox = cmds.checkBox('rm_cbox_UI', q=1, v=1) SelectObjects = cmds.ls(sl=1, l=1) if SelectObjects: for item in SelectObjects: firstUvSet = cmds.getAttr(item + '.uvSet[0].uvSetName') cmds.polyCopyUV(item, uvs=firstUvSet) for uvset in cmds.polyUVSet(q=1, auv=1): if uvset != firstUvSet: cmds.polyUVSet(item, d=1, uvs=uvset) if renamecheckbox: cmds.polyUVSet(e=1, rn=1, uvs=firstUvSet, nuv="map1")
def tryMakeUVSet(self, inNode, inName): sets = cmds.polyUVSet(inNode.mNode, q=True, auv=True) # We need a source UV set to copy from if sets is None: raise Exception('%s has no sets' % inNode.mNode) if inName not in sets: cmds.polyUVSet(inNode.mNode, create=True, uvSet=inName) cmds.polyCopyUV(inNode.mNode, uvi=sets[0], uvs=inName)
def cleanUvSets(): shapes = cmds.ls(type='mesh') for s in shapes: indices = cmds.polyUVSet(s, q=True, allUVSetsIndices=True) garbage = [] for i in indices: setname = cmds.getAttr(s + '.uvSet[%d].uvSetName' % i) if setname != 'map1': garbage.append(setname) for g in garbage: cmds.polyUVSet(s, delete=True, uvSet=g) print('[%s] Deleting %s' % (s, g))
def skinAs(source=None, target=None, sel=True): ''' copies across the skin cluster and weights from a source mesh to a target mesh can work on selection - ensure that source is selected first, followed by target mesh ''' if sel: source, target = cmds.ls(sl=True, l=True) elif not cmds.objExists(source) and not cmds.objExists(target): print "No valid geometry selected - try again" return False source_shp = cmds.listRelatives(source, s=True, ni=True) target_shp = cmds.listRelatives(target, s=True, ni=True) # find the skin cluster on the mesh his = cmds.listHistory(source_shp, pdo=True) skin = False for node in his: if cmds.nodeType(node) == "skinCluster": skin = node # skin = cmds.listConnections(source_shp, type="skinCluster" ) if skin: joints = cmds.skinCluster(skin, q=True, inf=True) else: print "source mesh does not have a skinCluster to copy" return False if joints and source_shp and target_shp: new_skin = cmds.skinCluster(joints, target, tsb=True, sm=1, nw=1) source_UV = cmds.polyUVSet(source, q=True, auv=True) target_UV = cmds.polyUVSet(target, q=True, auv=True) if source_UV == target_UV: # if UV sets match, copy across using the UV maps - get a better result for transfer from low to high res meshes cmds.copySkinWeights(ss=skin, ds=new_skin[0], sa="closestPoint", nm=True, nr=True, uv=[source_UV[0], target_UV[0]]) else: # else do a standard weight copy cmds.copySkinWeights(ss=skin, ds=new_skin[0], sa="closestPoint", nr=True, nm=True) print "skin weights copied from %s to %s" % (source, target) return True else: print "copying skin weights failed - check your source and target mesh selections" return False
def _repair_mesh(cls, mesh): """Process a single mesh, deleting other UV sets than the active one. Keep only current UV set and ensure it's the default 'map1' """ from maya import cmds uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True) current = cmds.polyUVSet(mesh, query=True, currentUVSet=True)[0] # Copy over to map1 if current != 'map1': cmds.polyUVSet(mesh, uvSet=current, newUVSet='map1', copy=True) cmds.polyUVSet(mesh, currentUVSet=True, uvSet='map1') current = 'map1' # Delete all non-current UV sets deleteUVSets = [uvSet for uvSet in uvSets if uvSet != current] uvSet = None # Maya Bug (tested in 2015/2016): # In some cases the API's MFnMesh will report less UV sets # than maya.cmds.polyUVSet. # This seems to happen when the deletion of UV sets has not # triggered a cleanup of the UVSet array # attribute on the mesh node. It will still have extra # entries in the attribute, though it will not # show up in API or UI. Nevertheless it does show up in # maya.cmds.polyUVSet. # To ensure we clean up the array we'll force delete the # extra remaining 'indices' that we don't want. # TODO: Implement a better fix # The best way to fix would be to get the UVSet # indices from api with MFnMesh (to ensure we keep # correct ones) and then only force delete the other # entries in the array attribute on the node. # But for now we're deleting all entries except first # one. Note that the first entry could never # be removed (the default 'map1' always exists and is # supposed to be undeletable.) try: for uvSet in deleteUVSets: cmds.polyUVSet(mesh, delete=True, uvSet=uvSet) except RuntimeError, e: cls.log.warning('uvSet: {0} - ' 'Error: {1}'.format(uvSet, e)) indices = cmds.getAttr('{0}.uvSet'.format(mesh), multiIndices=True) if not indices: cls.log.warning( "No uv set found indices for: {0}".format(mesh)) return # Delete from end to avoid shifting indices # and remove the indices in the attribute indices = reversed(indices[1:]) for i in indices: attr = '{0}.uvSet[{1}]'.format(mesh, i) cmds.removeMultiInstance(attr, b=True)
def uv_sets(self, fix): """ First line. Description. """ problems = False details = False # lists all the mesh type objects objects = cmds.ls(type='mesh') objects_len = len(objects) if objects_len: for o in objects: # checks if there are more than one UV set uv_set = cmds.polyUVSet(o, q=1, auv=1) uv_set_len = len(uv_set) if not details: details = True self.details.append("UV set problems") self.details.append("\t" + str(o)) if uv_set_len > 1: if not fix: problems = True else: # deletes all the extra UV sets for current_set in uv_set: original_uv_set = cmds.polyUVSet(o, q=1, cuv=1) cmds.polyUVSet(o, cuv=1, uvs=current_set) converted_uvset = cmds.polyListComponentConversion( o + '.vtx[0]', fv=1, tuv=1) cmds.polyUVSet(o, cuv=1, uvs=original_uv_set[0]) if current_set != uv_set[0]: if converted_uvset: cmds.polyCopyUV(o, uvi=current_set, uvs=uv_set[0]) cmds.polyUVSet(o, d=1, uvs=current_set) if uv_set[0] != 'map1': cmds.polyUVSet(o, uvs=uv_set[0], rn=1, nuv='map1') if problems: if fix: self.posible_fix.append("UV sets fixed") else: self.posible_fix.append("UV sets problems") else: self.posible_fix.append("UV sets clear")
def uvsetTgl(): shape_node = cmds.ls(sl=True, fl=True, dag=True, type='shape') current_uvset = cmds.polyUVSet(shape_node[0],q=True, currentUVSet=True) for shape in shape_node: uvsets = cmds.polyUVSet(shape,q=True,auv=True) if "map1" and "atlasUV" in uvsets: if current_uvset[0] == 'map1': cmds.polyUVSet(shape, currentUVSet=True, uvSet="atlasUV") elif current_uvset[0] == 'atlasUV': cmds.polyUVSet(shape, currentUVSet=True, uvSet="map1") else: cmds.polyUVSet(shape, currentUVSet=True, uvSet="map1") elif "map1" in uvsets and "atlasUV" not in uvsets: cmds.polyUVSet(shape, currentUVSet=True, uvSet="map1")
def __init__( self, face ): ''' This class will contain 3 Vertex Class (triangle) and the winding order ''' self.name = face # Face ID self.faceID = self.getFaceID() self.vertex = [] self._getVertex() self.numOfVertex = len(self.vertex) # Remember the order of these vertex line up with the Vertex Object held in # self.vertex self.windingOrder = PolyFace.findWindingOrder(self.name) self.vertexCoords = [] self.getVertexCoords() # This will be according to the face we're currently recording. self.normals = [] self.vtxFaceNames = self.getNormals() # http://xyz2.net/mel/mel.005.htm self.uvSets = cmds.polyUVSet(self.name, query=True, allUVSets=True) self.uvs = {} self.getUVs()
def getUvShelList(name): selList = om.MSelectionList() selList.add(name) selListIter = om.MItSelectionList(selList, om.MFn.kMesh) pathToShape = om.MDagPath() selListIter.getDagPath(pathToShape) meshNode = pathToShape.fullPathName() uvSets = cmds.polyUVSet(meshNode, query=True, allUVSets=True) allSets = [] for uvset in uvSets: shapeFn = om.MFnMesh(pathToShape) shells = om.MScriptUtil() shells.createFromInt(0) # shellsPtr = shells.asUintPtr() nbUvShells = shells.asUintPtr() uArray = om.MFloatArray() # array for U coords vArray = om.MFloatArray() # array for V coords uvShellIds = om.MIntArray() # The container for the uv shell Ids shapeFn.getUVs(uArray, vArray) shapeFn.getUvShellsIds(uvShellIds, nbUvShells, uvset) # shellCount = shells.getUint(shellsPtr) shells = {} for i, n in enumerate(uvShellIds): if n in shells: # shells[n].append([uArray[i],vArray[i]]) shells[n].append('%s.map[%i]' % (name, i)) else: # shells[n] = [[uArray[i],vArray[i]]] shells[n] = ['%s.map[%i]' % (name, i)] allSets.append({uvset: shells}) return allSets
def __init__(self, face): ''' This class will contain 3 Vertex Class (triangle) and the winding order ''' self.name = face # Face ID self.faceID = self.getFaceID() self.vertex = [] self._getVertex() self.numOfVertex = len(self.vertex) # Remember the order of these vertex line up with the Vertex Object held in # self.vertex self.windingOrder = PolyFace.findWindingOrder(self.name) self.vertexCoords = [] self.getVertexCoords() # This will be according to the face we're currently recording. self.normals = [] self.vtxFaceNames = self.getNormals() # http://xyz2.net/mel/mel.005.htm self.uvSets = cmds.polyUVSet(self.name, query=True, allUVSets=True) self.uvs = {} self.getUVs()
def getMoreThanOneUVSet(): kMesh = cc.ls(type='mesh', l=1) kMoreThanOneUVSet = [] for i in kMesh: kUVSets = cc.polyUVSet(i, query=True, allUVSets=1) if len(kUVSets) > 1: kMoreThanOneUVSet.append(i) return kMoreThanOneUVSet
def wt02(objectList, searchPattern): '''{"del_path":"Modeling/wt02(cmds.ls(sl=True,exactType='transform'),'forEm')", "icon":"uvChooser.svg", "usage":"deleteUVSet(cmds.ls(sl=True,exactType='transform'),'forEm')", } ''' if str(type(objectList)) == "<type 'str'>" or str( type(objectList)) == "<type 'unicode'>": objectList = [objectList] for tfNode in objectList: if cmds.listRelatives(tfNode, shapes=True, type='mesh', f=True) is not None: for uvSet in cmds.polyUVSet(tfNode, q=True, allUVSets=True): if re.search(searchPattern, uvSet): cmds.polyUVSet(tfNode, delete=True, uvSet=uvSet)
def deleteUVSet(objectList, searchPattern): '''{'del_path':'Polygons/EditUVs/deleteUVSet(cmds.ls(sl=True,exactType="transform"),"forEm")', 'icon':':/uvChooser.svg', 'usage':'$fun(cmds.ls(sl=True,exactType="transform"),"forEm")' } ''' if str(type(objectList)) == "<type 'str'>" or str( type(objectList)) == "<type 'unicode'>": objectList = [objectList] for tfNode in objectList: if cmds.listRelatives(tfNode, shapes=True, type='mesh', f=True) is not None: for uvSet in cmds.polyUVSet(tfNode, q=True, allUVSets=True): if re.search(searchPattern, uvSet): cmds.polyUVSet(tfNode, delete=True, uvSet=uvSet)
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)
def deleteUV(self): # print(self.uvSetAll) # print(self.uvSetAll) if len(self.uvSetAll) > 1 and self.delUVFlag: # UVセットが複数あったら削除処理 cmds.polyUVSet(self.mesh, uvSet=self.uvSetAll[0], e=True, currentUVSet=True) # カレントを1に dummy = common.TemporaryReparent().main(mode="create") for var in range(1, len(self.uvSetAll)): # print(self.uvSetAll[var]) # tempUV = cmds.polyUVSet(self.mesh, q=True, allUVSets=True) # for uv in tempUV: # print(u'UV名確認用 : '+str(uv)) if self.uvSetAll[var] == self.currentSet[0]: # 親子付けしたまま親のノードを処理するとなぜかUVSet名で処理できないので退避しておく common.TemporaryReparent().main(self.mesh, dummyParent=dummy, mode="cut") # カレントUVを1番目にコピー cmds.polyCopyUV(self.mesh, uvi=self.uvSetAll[var], uvs=self.uvSetAll[0]) # 親子付けを戻す common.TemporaryReparent().main(self.mesh, dummyParent=dummy, mode="parent") if self.uvSetAll[var].split(".")[-1] in self.exclusion: print("Skip UV in Exclusion List :", self.uvSetAll[var]) continue # 最初のUVセット以外は削除 try: print("Delete UV Set : " + self.mesh + "." + self.uvSetAll[var]) cmds.polyUVSet(self.mesh, uvSet=self.uvSetAll[var], delete=True) except: print("Delete UV Set Error : " + self.mesh + "." + self.uvSetAll[var] + " is not exsist\n" + "Skip this mesh object") # ダミー削除 common.TemporaryReparent().main(dummyParent=dummy, mode="delete") # ヒストリ削除 cmds.bakePartialHistory(self.shapes, ppt=True)
def __init__(self): self.lightmap = "Lightmap" for self.sel in selection: print "test" cmds.select(self.sel) faceCount = cmds.polyEvaluate(self.sel, face=True) self.selFace = self.sel + ".f[0:"+str(faceCount)+"]" self.uvList = cmds.polyUVSet(self.selFace, q=True, auv=True) self.uvSetOptions()
def getAllUVsCoords( vertex ): uvSets = Vertex.getUVSets(vertex) currUVSet = cmds.polyUVSet( vertex, q=True, currentUVSet=True )[0] totalUVs = [] for uvSet in uvSets: # Set uv to this current uvSet. cmds.polyUVSet( vertex, currentUVSet=True, uvSet=uvSet ) # getting a list of the coords uvCoords = Vertex.getCurrentCoords( vertex ) totalUVs.append(uvCoords) # Returns the current set back to its orginal cmds.polyUVSet( vertex, currentUVSet=True, uvSet=currUVSet) return totalUVs
def get_invalid(instance): meshes = cmds.ls(instance, type='mesh', long=True) invalid = [] for mesh in meshes: # Get existing mapping of uv sets by index indices = cmds.polyUVSet(mesh, query=True, allUVSetsIndices=True) maps = cmds.polyUVSet(mesh, query=True, allUVSets=True) mapping = dict(zip(indices, maps)) # Get the uv set at index zero. name = mapping[0] if name != "map1": invalid.append(mesh) return invalid
def setCurrentUVSet(objectList, matchPattern): '''{'del_path':'Polygons/EditUVs/setCurrentUVSet(cmds.ls(sl=True),"forEm")', 'icon':'uvChooser.svg', 'usage':'$fun(cmds.ls(sl=True),"forEm")', } ''' if str(type(objectList)) == "<type 'str'>" or str( type(objectList)) == "<type 'unicode'>": objectList = [objectList] for tfNode in objectList: if cmds.listRelatives(tfNode, shapes=True, type='mesh', f=True) is not None: for uvSet in cmds.polyUVSet(tfNode, q=True, allUVSets=True): if re.search(matchPattern, uvSet): cmds.polyUVSet(tfNode, currentUVSet=True, uvSet=uvSet) break
def getAllUVsCoords(vertex): uvSets = Vertex.getUVSets(vertex) currUVSet = cmds.polyUVSet(vertex, q=True, currentUVSet=True)[0] totalUVs = [] for uvSet in uvSets: # Set uv to this current uvSet. cmds.polyUVSet(vertex, currentUVSet=True, uvSet=uvSet) # getting a list of the coords uvCoords = Vertex.getCurrentCoords(vertex) totalUVs.append(uvCoords) # Returns the current set back to its orginal cmds.polyUVSet(vertex, currentUVSet=True, uvSet=currUVSet) return totalUVs
def wt01(objectList, matchPattern): '''{"del_path":"Modeling/wt01(cmds.ls(sl=True),'forEm')ONLYSE", "icon":"uvChooser.svg", "usage":"QM.setCurrentUVSet(cmds.ls(sl=True),'forEm')" } ''' if str(type(objectList)) == "<type 'str'>" or str( type(objectList)) == "<type 'unicode'>": objectList = [objectList] for tfNode in objectList: if cmds.listRelatives(tfNode, shapes=True, type='mesh', f=True) is not None: for uvSet in cmds.polyUVSet(tfNode, q=True, allUVSets=True): if re.search(matchPattern, uvSet): cmds.polyUVSet(tfNode, currentUVSet=True, uvSet=uvSet) break
def listEmptyUvsObjs(self, *args): cmds.textScrollList("w15_uiEmptyUVS", e=True, removeAll=True) objs = cmds.ls(sl=True) emptyUVS = [ obj for obj in objs if not cmds.polyUVSet(obj, q=True, allUVSets=True) or not cmds.polyEvaluate(obj, uvcoord=True) ] cmds.textScrollList("w15_uiEmptyUVS", e=True, append=emptyUVS)
def fix_invalid(cls, instance): """Rename uv map at index zero to map1""" from maya import cmds def rename_uvset(mesh, original, newname): try: cmds.polyUVSet(mesh, rename=True, uvSet=original, newUVSet=newname) except RuntimeError: cls.log.error("Mesh '%s' UVSet '%s' cannot be renamed." % (mesh, original)) for mesh in cls.get_invalid(instance): # Get existing mapping of uv sets by index indices = cmds.polyUVSet(mesh, query=True, allUVSetsIndices=True) maps = cmds.polyUVSet(mesh, query=True, allUVSets=True) mapping = dict(zip(indices, maps)) # Ensure there is no uv set named map1 to avoid # a clash on renaming the "default uv set" to map1 existing = set(maps) if "map1" in existing: # Find a unique name index i = 2 while True: name = "map{0}".format(i) if name not in existing: break i += 1 cls.log.warning( "Renaming clashing uv set name on mesh" " %s to '%s'", mesh, name) rename_uvset(mesh, "map1", name) # Rename the initial index to map1 original = mapping[0] rename_uvset(mesh, original, "map1")
def repair(self, instance): """Keep only current UV set and ensure it's the default 'map1'""" meshes = cmds.ls(instance, type='mesh', long=True) for mesh in meshes: uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True) currentUVSet = cmds.polyUVSet(mesh, query=True, currentUVSet=True)[0] if len(uvSets) != 1: # Copy over to map1 if currentUVSet != 'map1': cmds.polyUVSet(mesh, uvSet=currentUVSet, newUVSet='map1', copy=True) cmds.polyUVSet(mesh, currentUVSet=True, uvSet='map1') currentUVSet = 'map1' # Delete all non-current UV sets deleteUVSets = [ uvSet for uvSet in uvSets if uvSet != currentUVSet ] uvSet = None # Maya Bug (present in 2015; not sure if also earlier): # In some cases the API's MFnMesh will report less UV sets than maya.cmds.polyUVSet. # This seems to happen when the deletion of UV sets has not triggered a cleanup of the UVSet array # attribute on the mesh node. It will still have extra entries in the attribute, though it will not # show up in API or UI. Nevertheless it does show up in maya.cmds.polyUVSet. # To ensure we clean up the array we'll force delete the extra remaining 'indices' that we don't want. # TODO: Implement a better fix # ----- The best way to fix would be to get the UVSet indices from api with MFnMesh (to ensure we keep # ----- correct ones) and then only force delete the other entries in the array attribute on the node. # ----- But for now we're deleting all entries except first one. Note that the first entry could never # ----- be removed (the default 'map1' always exists and is supposed to be undeletable.) try: for uvSet in deleteUVSets: cmds.polyUVSet(mesh, delete=True, uvSet=uvSet) except RuntimeError, e: print 'uvSet: {0} - Error: {1}'.format( uvSet, e) # print the error indices = cmds.getAttr('{0}.uvSet'.format(mesh), multiIndices=True) indices = reversed( indices ) # delete from end to avoid shifting indices :) it = iter(indices) next(it) # skip first for i in it: cmds.removeMultiInstance('{0}.uvSet[{1}]'.format( mesh, i), b=True)
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: uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True) if len(uvSets) != 1: invalid.append(mesh) if invalid: raise ValueError("Nodes found with multiple UV sets: {0}".format(invalid))
def removeExtraUVSets(): from maya.cmds import polyUVSet, polyCopyUV import ezLib.transform mts = ezLib.transform.get(shape='mesh') for m in mts: uvSets = polyUVSet(m, q=1, allUVSets=1) for i in range(1,len(uvSets)): # for each set other than the 1st: set it, copy to 1st, delete it polyUVSet(m, currentUVSet=1, uvSet=uvSets[i]) polyCopyUV(m + '.map[*]', uvSetNameInput=uvSets[i], uvSetName=uvSets[0]) polyUVSet(m, uvSet=uvSets[i], delete=1) # copy vertexColorsWithoutTransferNode #obj = ls(sl=1, tr=1) #vtxs = ls(obj[0] + '.vtx[*]', fl=1) #for v in vtxs: # vtx = '.' + v.split('.')[1] # rgb = polyColorPerVertex(obj[0] + vtx, q=1, rgb=1) # a = polyColorPerVertex(obj[0] + vtx, q=1, a=1)[0] # polyColorPerVertex(obj[1] + vtx, a=a, rgb=rgb)
def getUVs(self): # Getting current uvset currUVSet = cmds.polyUVSet( self.name, q=True, currentUVSet=True )[0] for i, uvSet in enumerate(self.uvSets): self.uvs[uvSet] = [] # Setting uvSet temp cmds.polyUVSet( self.name, currentUVSet=True, uvSet=uvSet ) # Get uv maps uvMaps = cmds.polyListComponentConversion( self.name, ff=1, tuv=1 ) if( uvMaps ): uvMaps = cmds.filterExpand( uvMaps, expand=True, sm=35 ) # Check to make sure there are uv's on this face. for uvMap in uvMaps: # Get my uvValues uvCoords = cmds.polyEditUV( uvMap, q=True ) self.uvs[uvSet].append(uvCoords) # Returning to orginal uvSet cmds.polyUVSet( self.name, currentUVSet=True, uvSet=currUVSet)
def shadeUVShells(): uvSet = 'map1' data = [] shellDict = {} goldenRatio = 0.618033988749895 # use golden ratio selList = om.MSelectionList() om.MGlobal.getActiveSelectionList( selList ) selListIter = om.MItSelectionList( selList, om.MFn.kMesh ) uvShellArray = om.MIntArray() while not selListIter.isDone(): pathToShape = om.MDagPath() selListIter.getDagPath(pathToShape) meshNode = pathToShape.fullPathName() uvSets = cmds.polyUVSet( meshNode, query=True, allUVSets =True ) if (uvSet in uvSets): shapeFn = om.MFnMesh(pathToShape) shells = om.MScriptUtil() shells.createFromInt(0) shellsPtr = shells.asUintPtr() shapeFn.getUvShellsIds(uvShellArray, shellsPtr, uvSet) # Convert uvShellArray for index, value in enumerate(uvShellArray): shellDict.setdefault(value,[]).append(index) # Assign shaders for index, value in shellDict.iteritems(): shaderNode = cmds.shadingNode( 'surfaceShader', asShader=True ) faceShell = cmds.polyListComponentConversion( [('%s.map[%s]' % ( meshNode, u )) for u in value ], toFace=True ) cmds.select( faceShell ) cmds.hyperShade( assign=shaderNode ) hue = random.random() hue += goldenRatio hue %= 1 rgbColor = colorsys.hsv_to_rgb(hue, random.uniform(0.8, 1), random.uniform(0.8, 1)) cmds.setAttr( shaderNode + ".outColor", *rgbColor, type="double3" ) shellDict.clear() uvShellArray.clear() selListIter.next() cmds.select(clear=True)
def __init__(self): self.lightmap = "Lightmap" self.shellSpacingSlider = "shellSpacingSlider" self.spacingPresets = ["Custom", "2048 Map", "1024 Map", "512 Map", "256 Map", "128 Map", "64 Map", "32 Map"] self.spacingPresetValues = [3.2, .05, .1, .2, .4, .8, 1.6, 3.2] self.presetSelect = "presetSelect" for self.sel in selection: print "test" cmds.select(self.sel) faceCount = cmds.polyEvaluate(self.sel, face=True) self.selFace = self.sel + ".f[0:"+str(faceCount)+"]" self.uvList = cmds.polyUVSet(self.selFace, q=True, auv=True) self.uvSetOptions()
def makeSeamless(meshName): """Makes a supplied mesh "seamless" in Unity by deleting its UV coordinates, smoothing normals, triangulating, and clearing material assignments""" # clear uvs so there are no seams or tangents uvs = cmds.polyUVSet(meshName, q=True, auv=True) for uv in uvs: try: cmds.polyUVSet(meshName, e=True, uvSet=uv, delete=True) except: pass uvSet = cmds.polyUVSet(meshName, q=True, auv=True)[0] sel = om.MSelectionList() sel.add(meshName) dagPath = om.MDagPath() sel.getDagPath(0, dagPath) fn = om.MFnMesh(dagPath) fn.clearUVs(uvSet) # smooth normals so there are no normal separations cmds.polySoftEdge(meshName, a=180, ch=True) # triangulate geometry cmds.polyTriangulate(meshName) # apply a single material so there are no submesh separations cmds.sets(meshName, e=True, forceElement='initialShadingGroup') # delete all history cmds.delete(meshName, ch=True) cmds.select(clear=True)
def deleteEmptyUVSets(): """ Function to remove empty uv's """ getMeshes = cmds.ls(type = 'mesh', l = True) emptyExists = False if getMeshes: for eachMesh in getMeshes: selectionList = om.MSelectionList() selectionList.add(eachMesh) nodeDagPath = selectionList.getDagPath(0) shapeFn = om.MFnMesh(nodeDagPath) ## Now fetch data from shapeFn shapeName = shapeFn.name() currentUVSets = shapeFn.getUVSetNames() validUVSets = [] getFaceCount = shapeFn.numPolygons try: [[validUVSets.extend([eachUVset]) for eachUVset in shapeFn.getFaceUVSetNames(x) if eachUVset not in validUVSets] for x in range(0, getFaceCount)] except: uvsets = None for eachUVSet in currentUVSets: if eachUVSet not in validUVSets: logger.info('Removing empty UVSet %s from %s' % (eachUVSet, eachMesh)) cmds.select(eachMesh, r = True) try: cmds.polyUVSet(delete = True, uvSet = eachUVSet) emptyExists = True except: cmds.warning('Failed to empty uv set %s of %s...' % (eachUVSet, eachMesh)) if emptyExists: cmds.headsUpMessage('YOU HAD EMPTY UV SETS CLEANED UP!!', time = 3)
def deleteEmptyUVSets(): """ Function to remove empty uv's """ getMeshes = cmds.ls(type = 'mesh', l = True) emptyExists = False if getMeshes: for eachMesh in getMeshes: selectionList = om.MSelectionList() selectionList.add(eachMesh) nodeDagPath = selectionList.getDagPath(0) shapeFn = om.MFnMesh(nodeDagPath) ## Now fetch data from shapeFn shapeName = shapeFn.name() #debug(None, method = 'uv_getUVs.getUVs', message = '{0:<10}{1}'.format('shapeName:', shapeName), verbose = False) currentUVSets = shapeFn.getUVSetNames() #debug(None, method = 'uv_getUVs._getUVSets', message = 'Fetching uvsets now..', verbose = False) validUVSets = [] getFaceCount = shapeFn.numPolygons try: [[validUVSets.extend([eachUVset]) for eachUVset in shapeFn.getFaceUVSetNames(x) if eachUVset not in validUVSets] for x in range(0, getFaceCount) ] except: uvsets = None for eachUVSet in currentUVSets: if eachUVSet not in validUVSets: print 'Removing empty UVSet %s from %s' % (eachUVSet, eachMesh) cmds.select(eachMesh, r = True) try: cmds.polyUVSet(delete = True, uvSet = eachUVSet) emptyExists = True except: cmds.warning('Failed to empty uv set %s of %s...' % (eachUVSet, eachMesh)) if emptyExists: cmds.headsUpMessage('YOU HAD EMPTY UV SETS CLEANED UP! MAKE SURE YOU EXPORT SHD.XML AS WELL!', time = 3)
def searchUVSet(mesh_list, multiple_UV_set, not_UV_set): # get mesh list for mesh in mesh_list: uvset_list = cmds.polyUVSet(mesh, query=True, allUVSets=True) uvset_count = len(uvset_list) if uvset_count == 1: continue # Multiple UVSet elif uvset_count > 1: uvname_list = [] for uvset_name in uvset_list: uvname_list.append(uvset_name) multiple_UV_set.update({mesh: uvname_list}) # Not has UVSet elif uvset_count == 0: not_UV_set.append(mesh)
def validateUVs(mesh): ''' ''' # Initiate check check = 0 # Get meshFn meshFn = glTools.utils.mesh.getMeshFn(mesh) # Get UV Sets uvSetList = mc.polyUVSet(mesh,q=True,allUVSets=True) if not uvSetList: print('No UV Set : '+mesh) check += 1 for uvSet in uvSetList: # Get UV values uArray = OpenMaya.MFloatArray() vArray = OpenMaya.MFloatArray() meshFn.getUVs(uArray,vArray,uvSet) # Check empty UV set if not uArray.length() and not vArray.length(): print('Empty UV Set : '+mesh+' - '+uvSet) check += 1 # Check U values for i in range(uArray.length()): if math.isnan(uArray[i]): print('Found NaN : '+mesh+'.uv['+str(i)+']') check += 1 if math.isinf(uArray[i]): print('Found INF : '+mesh+'.uv['+str(i)+']') check += 1 # Check V values for i in range(vArray.length()): if math.isnan(vArray[i]): print('Found NaN : '+mesh+'.uv['+str(i)+']') check += 1 if math.isinf(vArray[i]): print('Found INF : '+mesh+'.uv['+str(i)+']') check += 1 # Return result return check
def checkUvShells(meshList=[], faceCountTol=1): """ Check number of UV shells compared to the mesh face count. Returns a list of mesh objects that have as many UV shells as faces. @param meshList: List of meshes to check for UV shells. If empty, check all mesh objects in the scene. @type meshList: list @param faceCountTol: Only consider mesh objects that have a face count greater this number. @type faceCountTol: int """ # Check meshList meshList = getMeshList(meshList) if not meshList: return [] # Check Multiple UV Sets meshUVshells = [] for mesh in meshList: # Shapes meshShapes = mc.listRelatives(mesh, s=True, ni=True, pa=True) if not meshShapes: continue for meshShape in meshShapes: # Get Face Count faceCount = mc.polyEvaluate(meshShape, f=True) if faceCount <= faceCountTol: continue # Get UV Sets uvSets = mc.polyUVSet(meshShape, q=True, allUVSets=True) if not uvSets: continue # For Each UV Set for uvSet in uvSets: # Get Num UV Shells UVshells = glTools.utils.mesh.numUvShells(meshShape, uvSet=uvSet) if UVshells == faceCount: meshUVshells.append(mesh) break # Return Result return meshUVshells
def get_invalid(instance): from maya import cmds meshes = cmds.ls(instance, type='mesh', long=True) invalid = [] for mesh in meshes: uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True) or [] # ensure unique (sometimes maya will list 'map1' twice) uvSets = set(uvSets) if len(uvSets) != 1: invalid.append(mesh) return invalid
def checkMissingUVsets(meshList=[]): """ Check missing UV sets for each specified mesh @param meshList: List of meshes to check for UV sets. If empty, check all mesh objects in the scene. @type meshList: list """ # Check meshList meshList = getMeshList(meshList) if not meshList: return [] # Check Missing UV Sets missingUVsets = [] for mesh in meshList: UVsets = cmds.polyUVSet(mesh, q=True, allUVSets=True) if not UVsets: missingUVsets.append(mesh) # Return Result return missingUVsets
def repair(self, instance): """Keep only current UV set and ensure it's the default 'map1'""" meshes = cmds.ls(instance, type='mesh', long=True) for mesh in meshes: uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True) currentUVSet = cmds.polyUVSet(mesh, query=True, currentUVSet=True)[0] if len(uvSets) != 1: # Copy over to map1 if currentUVSet != 'map1': cmds.polyUVSet(mesh, uvSet=currentUVSet, newUVSet='map1', copy=True) cmds.polyUVSet(mesh, currentUVSet=True, uvSet='map1') currentUVSet = 'map1' # Delete all non-current UV sets deleteUVSets = [uvSet for uvSet in uvSets if uvSet != currentUVSet] uvSet = None # Maya Bug (present in 2015; not sure if also earlier): # In some cases the API's MFnMesh will report less UV sets than maya.cmds.polyUVSet. # This seems to happen when the deletion of UV sets has not triggered a cleanup of the UVSet array # attribute on the mesh node. It will still have extra entries in the attribute, though it will not # show up in API or UI. Nevertheless it does show up in maya.cmds.polyUVSet. # To ensure we clean up the array we'll force delete the extra remaining 'indices' that we don't want. # TODO: Implement a better fix # ----- The best way to fix would be to get the UVSet indices from api with MFnMesh (to ensure we keep # ----- correct ones) and then only force delete the other entries in the array attribute on the node. # ----- But for now we're deleting all entries except first one. Note that the first entry could never # ----- be removed (the default 'map1' always exists and is supposed to be undeletable.) try: for uvSet in deleteUVSets: cmds.polyUVSet(mesh, delete=True, uvSet=uvSet) except RuntimeError, e: print 'uvSet: {0} - Error: {1}'.format(uvSet, e) # print the error indices = cmds.getAttr('{0}.uvSet'.format(mesh), multiIndices=True) indices = reversed(indices) # delete from end to avoid shifting indices :) it = iter(indices) next(it) # skip first for i in it: cmds.removeMultiInstance('{0}.uvSet[{1}]'.format(mesh, i), b=True)
def _fixUVNames(): """ used to cleanup map renames as the behind the scenes maya uvSetName doens't change when using the rename i in the maya uv editor.. gg maya!!! """ for eachMesh in cmds.ls(type = 'mesh'): getParent = cmds.listRelatives(eachMesh, parent = True)[0] fullPathToParent = cmds.ls(getParent, l = True)[0] selectionList = om.MSelectionList() selectionList.add(fullPathToParent) nodeDagPath = selectionList.getDagPath(0) shapeFn = om.MFnMesh(nodeDagPath) ## Now fetch data from shapeFn try: shapeName = shapeFn.name() currentUVSets = shapeFn.getUVSetNames() originalSize = len(currentUVSets) for x, each in enumerate(currentUVSets): cmds.setAttr('%s.uvSet[%s].uvSetName' % (getParent, x), each, type = 'string') uvDict = {} uvSets = cmds.polyUVSet(getParent, allUVSets = True, query = True) uvSetIds = cmds.polyUVSet(getParent, allUVSetsIndices = True, query = True) for i, uv in enumerate(uvSets): uvDict.setdefault(uv, []) uvDict[uv].append(uvSetIds[i]) if len(uvSets) > originalSize: if len(uvDict[each]) > 1: cmds.polyUVSet(getParent, uvSet = each, rename = True, newUVSet = '%s_temp' % each) textureLink = cmds.uvLink(uvSet = '%s.uvSet[%s].uvSetName' % (getParent, uvDict[each][-1]), query = True) if textureLink: [cmds.uvLink(uvSet = '%s.uvSet[%s].uvSetName' % (getParent, x), texture = tex) for tex in textureLink] cmds.polyUVSet(getParent, uvSet = each, delete = True) cmds.polyUVSet(getParent, uvSet = '%s_temp' % each, rename = True, newUVSet = each) except RuntimeError: logger.warning('Failed to process "%s", probably corrupted mesh, skipping...' % eachMesh)
def bake_texture_range_v001 ( _resXY ): # get shape from selection to get texture later _geo = cmds.ls (selection = True)[0] _shape = cmds.pickWalk (direction = 'down')[0] _scene = Scene() _path = _scene.project + 'sourceImages/' + _scene.name + '_textureBake/' # get texture from geo from shading group connections _shadingGroup = cmds.listConnections (_shape + '.instObjGroups[0]', source = True)[0] _shader = cmds.listConnections (_shadingGroup + '.surfaceShader', destination = True)[0] if cmds.nodeType (_shader) == 'surfaceShader': _texture = cmds.listConnections (_shader + '.outColor', destination = True)[0] else: _texture = cmds.listConnections (_shader + '.color', destination = True)[0] # get the current UV set to bake into _UVset = cmds.polyUVSet (_geo, query = True, currentUVSet = True)[0] _bakeRange = _scene.animationEndFrame - _scene.animationStartFrame + 1 if not os.path.isdir (_path): os.mkdir (_path) # bake textures in frame range for _k in range (_bakeRange): _currentFrame = int (cmds.currentTime (_k + _scene.animationStartFrame) ) _currentFrame = ('0000' + str (_currentFrame) )[-4:] _fileName = _path + _scene.name + '_' + _geo + '_' + _texture + '_' + _UVset + '.' + _currentFrame + '.tga' # do bake cmds.convertSolidTx (_texture, _geo, antiAlias = False, alpha = False, doubleSided = False, force = False, fileFormat = 'tga', fileImageName = _fileName, resolutionX = _resXY, resolutionY = _resXY, shadows = False, backgroundMode = 'shader', fillTextureSeams = False, uvSetName = _UVset) print _fileName # delete imported file textures from scene mm.eval ( 'hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes");' )
def checkMultipleUVsets(meshList=[]): """ Check multiple UV sets for each specified mesh @param meshList: List of meshes to check for UV sets. If empty, check all mesh objects in the scene. @type meshList: list """ # Check meshList meshList = getMeshList(meshList) if not meshList: return [] # Check Multiple UV Sets multipleUVsets = [] for mesh in meshList: UVsets = mc.polyUVSet(mesh, q=True, allUVSets=True) if not UVsets: continue if len(UVsets) > 1: multipleUVsets.append(mesh) # Return Result return multipleUVsets
def getUVSets( vertex ): return cmds.polyUVSet(vertex, query=True, allUVSets=True)
def bake_texture_range ( _resXY, _range = 0, _reopenRange = 10 ): # get scene name with path to reopen _scene = Scene() _reOpenName = _scene.path + _scene.name + '.mb' # _bakePath = _scene.project + 'images/' + _scene.name + '_textureBake/' _bakePath = _scene.project + 'images/' # create bake path if not exists if not os.path.isdir (_bakePath): os.mkdir (_bakePath) # get shape from selection to get texture _geo = cmds.ls (selection = True)[0] _shape = cmds.pickWalk (direction = 'down')[0] # get texture from geo from shading group connections _shadingGroup = cmds.listConnections (_shape + '.instObjGroups[0]', source = True)[0] _shader = cmds.listConnections (_shadingGroup + '.surfaceShader', destination = True)[0] # decide node type for "color" if normal shader or "outcolor" for surface shader if cmds.nodeType (_shader) == 'surfaceShader': _texture = cmds.listConnections (_shader + '.outColor', destination = True)[0] else: _texture = cmds.listConnections (_shader + '.color', destination = True)[0] # get the current UV set to bake into _UVset = cmds.polyUVSet (_geo, query = True, currentUVSet = True)[0] # range = current frame only if _range == 0: _frame = int(_scene.getCurrentFrame()) # _fileName = _bakePath + _scene.name + '_' + _geo + '_' + _texture + '_' + _UVset + '.' + ('0000' + str (_frame) )[-4:] + '.iff' _fileName = _bakePath + _scene.name + '_footageBake.' + ('0000' + str (_frame) )[-4:] + '.iff' #bake single frame cmds.convertSolidTx (_texture, _geo, antiAlias = False, alpha = False, doubleSided = False, force = False, fileFormat = 'iff', fileImageName = _fileName, resolutionX = _resXY, resolutionY = _resXY, shadows = False, backgroundMode = 'shader', fillTextureSeams = False, uvSetName = _UVset) print _fileName else: if _range == 1: # get bake range from playBack range _startFrame = _scene.playBackStartFrame _endFrame = _scene.playBackEndFrame _bakeRange = _endFrame - _startFrame + 1 _reOpenTimes = (_bakeRange / _reopenRange) if _reOpenTimes > int(_reOpenTimes): _reOpenTimes = int(_reOpenTimes) + 1 else: _reOpenTimes = int(_reOpenTimes) _frame = _scene.playBackStartFrame _frame = int(_frame) else: # get bake range from playBack range _startFrame = _scene.renderStartFrame _endFrame = _scene.renderEndFrame _bakeRange = _endFrame - _startFrame + 1 _reOpenTimes = int(_bakeRange / _reopenRange) + 1 _frame = _scene.renderStartFrame _frame = int(_frame) for _k in range (_reOpenTimes): for _l in range (_reopenRange): if _frame <= _endFrame: cmds.currentTime (_frame) # _fileName = _bakePath + _scene.name + '_' + _geo + '_' + _texture + '_' + _UVset + '.' + ('0000' + str (_frame) )[-4:] + '.iff' _fileName = _bakePath + _scene.name + '_footageBake.' + ('0000' + str (_frame) )[-4:] + '.iff' print _fileName # do bake cmds.convertSolidTx (_texture, _geo, antiAlias = False, alpha = False, doubleSided = False, force = False, fileFormat = 'iff', fileImageName = _fileName, resolutionX = _resXY, resolutionY = _resXY, shadows = False, backgroundMode = 'shader', fillTextureSeams = False, uvSetName = _UVset) _frame = _frame + 1 # reopen scene to empty RAM if _k < _reOpenTimes - 1: cmds.file (_reOpenName, open = True, force = True)
def createLightmap(self, *args): selection = cmds.ls(sl=True) if len(selection) == 0: return mesh = selection[0] if cmds.checkBox("cbDeleteHistory", q=True, v=True) == True: cmds.delete(mesh, ch=True) maxArc = cmds.textFieldGrp("tTolerance", q=True, text=True) if re.search("[a-zA-Z]", maxArc) != None: cmds.textFieldGrp("tTolerance", e=True, text="5") maxArc = int(cmds.textFieldGrp("tTolerance", q=True, text=True)) # 1. Create a new UV Set if "lightmap" in cmds.polyUVSet(q=True, auv=True): cmds.polyUVSet(uvs="lightmap", delete=True) faceCount = cmds.polyEvaluate(mesh, f=True) cmds.polyUVSet(copy=True, nuv="lightmap") cmds.polyUVSet(mesh, cuv=True, uvs="lightmap") # 2. Cut every UV Edge edgeCount = cmds.polyEvaluate(mesh, e=True) cmds.polyMapCut(mesh + ".e[0:" + str(edgeCount - 1) + "]", cch=True, ch=False) cmds.progressWindow( title="Creating Lightmap...", progress=0, maxValue=faceCount + 1, isInterruptable=True, status="Facecount: " + str(faceCount), ) # 3. Check if faces are connected and facing the same direction, if they do, then sew the uv edge i = 0 while i < faceCount: if cmds.progressWindow(query=True, isCancelled=True): break face = mesh + ".f[" + str(i) + "]" adjacentFaces = self.getAdjacentFaces(mesh, i) normal1 = self.getFaceNormal(face) for adj in adjacentFaces: normal2 = self.getFaceNormal(adj) arc = self.getAngle(normal1, normal2) if arc < maxArc: self.sewFaces(face, adj) cmds.progressWindow(edit=True, progress=i) i += 1 cmds.select(mesh) # 4. unfold cmds.unfold(i=5000, ss=0.001, gb=False, gmb=0.5, ps=0, oa=0, us=True) # 5. layout preset = self.maps[cmds.optionMenuGrp("omTexSize", q=True, value=True)] cmds.polyMultiLayoutUV(lm=1, sc=1, rbf=1, fr=True, l=2, ps=preset) cmds.progressWindow(endProgress=True)