def setUV_uvSet1(): selection = mc.ls(selection=True) for mesh in selection: shape = mesh + 'Shape' channelslist = [] for UVchannel in range(0, 10): uvset = mc.getAttr(shape + '.uvSet[' + str(UVchannel) + '].uvSetName') channelslist.append(uvset) nodeTexture = 'TX_' + mesh[:-5] try: uvset1 = channelslist.index('uvSet1') if nodeTexture.endswith('_elements') == True: continue elif nodeTexture.endswith('_elements_big') == True: continue elif nodeTexture.endswith('_elements_medium') == True: continue elif nodeTexture.endswith('_elements_small') == True: continue elif nodeTexture.endswith('_glass') == True: continue else: mc.uvLink(uvSet=shape + '.uvSet[' + str(uvset1) + '].uvSetName', texture=nodeTexture) print('uvSet1 set successfully!'), except ValueError: print('This mesh has not a second UV channel'),
def getShaderInfo(self): # What material is connected to this shapeNode # shapeNode.ShaderMaterial # cmds.getAttr( "pCubeShape6.ShaderMaterial", asString=True ) if (cmds.objExists("%s.ShaderMaterial" % self.nodeName)): # self.material = cmds.getAttr( "%s.ShaderMaterial" %self.nodeName, asString=True) self.material = cmds.getAttr("%s.ShaderMaterial" % self.nodeName) else: self.material = "" ''' # find the text file associated with the material. # What if they don't include a texture file? inputs = cmds.listConnections( source=True ) files = cmds.ls( inputs, type="file" ) fileNames = [] for fn in files: # setAttr -type "string" file1.fileTextureName "c.tga"; textureName = cmds.getAttr( "%s.fileTextureName" %fn ) fileNames.append( textureName ) ''' # self.fileInfo = {} for i, uvSet in enumerate(self.sets): # cmds.uvLink( query=True, uvSet='pCubeShape2.uvSet[0].uvSetName' ) files = cmds.uvLink(query=True, uvSet='%s.uvSet[%s].uvSetName' % (self.nodeName, i)) if (files): self.fileInfo[uvSet] = [ cmds.getAttr("%s.fileTextureName" % curFile) for curFile in files ]
def getShaderInfo(self): # What material is connected to this shapeNode # shapeNode.ShaderMaterial # cmds.getAttr( "pCubeShape6.ShaderMaterial", asString=True ) if( cmds.objExists( "%s.ShaderMaterial" %self.nodeName) ): # self.material = cmds.getAttr( "%s.ShaderMaterial" %self.nodeName, asString=True) self.material = cmds.getAttr( "%s.ShaderMaterial" %self.nodeName) else: self.material = "" ''' # find the text file associated with the material. # What if they don't include a texture file? inputs = cmds.listConnections( source=True ) files = cmds.ls( inputs, type="file" ) fileNames = [] for fn in files: # setAttr -type "string" file1.fileTextureName "c.tga"; textureName = cmds.getAttr( "%s.fileTextureName" %fn ) fileNames.append( textureName ) ''' # self.fileInfo = {} for i, uvSet in enumerate(self.sets): # cmds.uvLink( query=True, uvSet='pCubeShape2.uvSet[0].uvSetName' ) files = cmds.uvLink( query=True, uvSet='%s.uvSet[%s].uvSetName' %(self.nodeName, i) ) if(files): self.fileInfo[uvSet] = [cmds.getAttr( "%s.fileTextureName" %curFile) for curFile in files ]
def getShaderInfo(self): # What material is connected to this shapeNode # shapeNode.ShaderMaterial # cmds.getAttr( "pCubeShape6.ShaderMaterial", asString=True ) if (cmds.objExists("%s.ShaderMaterial" % self.nodeName)): # self.material = cmds.getAttr( "%s.ShaderMaterial" %self.nodeName, asString=True) # self.material = cmds.getAttr( "%s.ShaderMaterial" %self.nodeName) self.material = cmds.getAttr("%s.ShaderMaterial" % self.nodeName, asString=True) else: self.material = "" for i, uvSet in enumerate(self.sets): # cmds.uvLink( query=True, uvSet='pCubeShape2.uvSet[0].uvSetName' ) files = cmds.uvLink(query=True, uvSet='%s.uvSet[%s].uvSetName' % (self.nodeName, i)) if (files): # self.fileInfo[uvSet] = [cmds.getAttr( "%s.fileTextureName" %curFile) for curFile in files ] for curFile in files: if (cmds.nodeType(curFile) == "file"): # print("%s.fileTextureName" %curFile) # print( cmds.getAttr( "%s.fileTextureName" %curFile) ) self.fileInfo[uvSet].append( cmds.getAttr("%s.fileTextureName" % curFile))
def setUV_map1(): selection = mc.ls(selection=True) for item in selection: shape = item + 'Shape' nodeTexture = 'TX_' + item[:-5] if nodeTexture.endswith('_elements') == True: continue elif nodeTexture.endswith('_elements_big') == True: continue elif nodeTexture.endswith('_elements_medium') == True: continue elif nodeTexture.endswith('_elements_small') == True: continue elif nodeTexture.endswith('_glass') == True: continue else: mc.uvLink(uvSet=shape + '.uvSet[0].uvSetName', texture=nodeTexture) print('map1 set successfully!'),
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 _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: cmds.warning('Failed to process "%s", probably corrupted mesh, skipping...' % eachMesh)
def getShaderInfo(self): # What material is connected to this shapeNode # shapeNode.ShaderMaterial # cmds.getAttr( "pCubeShape6.ShaderMaterial", asString=True ) if( cmds.objExists( "%s.ShaderMaterial" %self.nodeName) ): # self.material = cmds.getAttr( "%s.ShaderMaterial" %self.nodeName, asString=True) self.material = cmds.getAttr( "%s.ShaderMaterial" %self.nodeName) else: self.material = "" for i, uvSet in enumerate(self.sets): # cmds.uvLink( query=True, uvSet='pCubeShape2.uvSet[0].uvSetName' ) files = cmds.uvLink( query=True, uvSet='%s.uvSet[%s].uvSetName' %(self.nodeName, i) ) if(files): self.fileInfo[uvSet] = [cmds.getAttr( "%s.fileTextureName" %curFile) for curFile in files ]
def testImportUVSetMappings(self): ''' Tests that importing complex UV set mappings work: ''' usd_path = os.path.join(self.test_dir, "UsdImportUVSetMappings.usda") options = ["shadingMode=[[useRegistry,UsdPreviewSurface]]", "primPath=/"] cmds.file(usd_path, i=True, type="USD Import", ignoreVersion=True, ra=True, mergeNamespacesOnClash=False, namespace="Test", pr=True, importTimeRange="combine", options=";".join(options)) # With merging working, we expect exactly these shading groups (since # two of them were made unmergeable) expected_sg = set(['initialParticleSE', 'initialShadingGroup', 'blinn1SG', 'blinn2SG', 'blinn3SG', 'blinn3SG_uvSet1', 'blinn4SG', 'blinn4SG_uvSet2']) self.assertEqual(set(cmds.ls(type="shadingEngine")), expected_sg) expected_links = [ ("file1", ['pPlane4Shape.uvSet[0].uvSetName', 'pPlane3Shape.uvSet[0].uvSetName', 'pPlane1Shape.uvSet[0].uvSetName', 'pPlane2Shape.uvSet[0].uvSetName']), ("file2", ['pPlane4Shape.uvSet[1].uvSetName', 'pPlane3Shape.uvSet[1].uvSetName', 'pPlane1Shape.uvSet[1].uvSetName', 'pPlane2Shape.uvSet[1].uvSetName']), ("file3", ['pPlane4Shape.uvSet[2].uvSetName', 'pPlane3Shape.uvSet[2].uvSetName', 'pPlane1Shape.uvSet[2].uvSetName', 'pPlane2Shape.uvSet[2].uvSetName']), ("file4", ['pPlane4Shape.uvSet[0].uvSetName', 'pPlane2Shape.uvSet[0].uvSetName']), ("file5", ['pPlane2Shape.uvSet[1].uvSetName',]), ("file6", ['pPlane2Shape.uvSet[2].uvSetName',]), ("file7", ['pPlane4Shape.uvSet[1].uvSetName',]), ("file8", ['pPlane4Shape.uvSet[2].uvSetName',]), ] for file_name, links in expected_links: links = set(links) self.assertEqual(set(cmds.uvLink(texture=file_name)), links)
print(uvSetsList) print(uvSetsNamesList) print(uvSetsIndiciesList) uvSetIndiciesByName = dict(zip(uvSetsNamesList, uvSetsIndiciesList)) print(uvSetIndiciesByName) uvIndex = int(uvSetIndiciesByName[uvSetName]) uvSetQualifiedName = obj.name() + '.uvSet[' + str(uvIndex) + '].uvSetName' try: print(uvSetQualifiedName) print(textureName) cmds.uvLink(uvSet=uvSetQualifiedName, texture=textureName) """ uvCmd = ( 'uvLink -texture ' + textureName + ' -uvSet ' + uvSetQualifiedName + ';' ) print( uvCmd ) pm.mel.eval( uvCmd ) """ except: print(traceback.format_exc())
def testExportUVSetMappings(self): ''' Tests that exporting multiple Maya planes with varying UV mappings setups results in USD data with material specializations: ''' expected = [ ("/pPlane1", "/blinn1SG", "st", "st", "st"), ("/pPlane2", "/blinn1SG", "st", "st", "st"), ("/pPlane3", "/blinn1SG", "st", "st", "st"), ("/pPlane4", "/blinn1SG", "st", "st", "st"), ("/pPlane5", "/blinn1SG_st_st1_st2", "st", "st1", "st2"), ("/pPlane6", "/blinn1SG_st1_st2_st", "st1", "st2", "st"), ("/pPlane7", "/blinn1SG_st2_st_st1", "st2", "st", "st1"), ] for mesh_name, mat_name, f1_name, f2_name, f3_name in expected: plane_prim = self._stage.GetPrimAtPath(mesh_name) binding_api = UsdShade.MaterialBindingAPI(plane_prim) mat = binding_api.ComputeBoundMaterial()[0] self.assertEqual(mat.GetPath(), mat_name) self.assertEqual( mat.GetInput("file1:varname").GetAttr().Get(), f1_name) self.assertEqual( mat.GetInput("file2:varname").GetAttr().Get(), f2_name) self.assertEqual( mat.GetInput("file3:varname").GetAttr().Get(), f3_name) # Initial code had a bug where a material with no UV mappings would # specialize itself. Make sure it stays fixed: plane_prim = self._stage.GetPrimAtPath("/pPlane8") binding_api = UsdShade.MaterialBindingAPI(plane_prim) mat = binding_api.ComputeBoundMaterial()[0] self.assertEqual(mat.GetPath(), "/pPlane8/Materials/blinn2SG") self.assertFalse(mat.GetPrim().HasAuthoredSpecializes()) # Gather some original information: expected_uvs = [] for i in range(1, 9): xform_name = "|pPlane%i" % i selectionList = OM.MSelectionList() selectionList.add(xform_name) dagPath = selectionList.getDagPath(0) dagPath = dagPath.extendToShape() mayaMesh = OM.MFnMesh(dagPath.node()) expected_uvs.append( ("pPlane%iShape" % i, mayaMesh.getUVSetNames())) expected_sg = set(cmds.ls(type="shadingEngine")) expected_links = [] for file_name in cmds.ls(type="file"): links = [] for link in cmds.uvLink(texture=file_name): # The name of the geometry does not survive roundtripping, but # we know the pattern: pPlaneShapeX -> pPlaneXShape plugPath = link.split(".") selectionList = OM.MSelectionList() selectionList.add(link) mayaMesh = OM.MFnMesh(selectionList.getDependNode(0)) meshName = mayaMesh.name() plugPath[0] = "pPlane" + meshName[-1] + "Shape" links.append(".".join(plugPath)) expected_links.append((file_name, set(links))) # Test roundtripping: cmds.file(newFile=True, force=True) # Import back: options = [ "shadingMode=[[useRegistry,UsdPreviewSurface]]", "primPath=/" ] cmds.file(self._usdFilePath, i=True, type="USD Import", ignoreVersion=True, ra=True, mergeNamespacesOnClash=False, namespace="Test", pr=True, importTimeRange="combine", options=";".join(options)) # Names should have been restored: for mesh_name, mesh_uvs in expected_uvs: selectionList = OM.MSelectionList() selectionList.add(mesh_name) mayaMesh = OM.MFnMesh(selectionList.getDependNode(0)) self.assertEqual(mayaMesh.getUVSetNames(), mesh_uvs) # Same list of shading engines: self.assertEqual(set(cmds.ls(type="shadingEngine")), expected_sg) # All links correctly restored: for file_name, links in expected_links: self.assertEqual(set(cmds.uvLink(texture=file_name)), links)
def BakeLightsToVertex(): folderdir = str( cmds.fileDialog2(caption="Select a Folder to save Textures", fileMode=2)[0]) # Ask user what texture size to use result = cmds.promptDialog(title='Vertex Light Baker', message='Texture Size', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if result == 'OK': texturesize = int(cmds.promptDialog(query=True, text=True)) selected = cmds.ls(selection=True) for obj in selected: # Delete any extra uvsets ClearExtraUVSets(obj) # Create new automatic uv set shapes = cmds.listRelatives(obj, shapes=True) cmds.select(obj) cmds.polyUVSet(create=True, uvSet='automatic') # Automatic unwrap the object cmds.polyAutoProjection(obj, layoutMethod=False, projectBothDirections=False, insertBeforeDeformers=True, scaleMode=True, optimize=True, planes=6, uvSetName="automatic", percentageSpace=0.2, worldSpace=False) uvSetName = cmds.polyUVSet(query=True, currentUVSet=True) # Render the lighting to a texture cmds.arnoldRenderToTexture(filter="gaussian", filter_width=2.0, aa_samples=3, r=texturesize, folder=folderdir, uv_set=str(uvSetName[0])) # create a shader shader = cmds.shadingNode("surfaceShader", asShader=True) #a file texture node file_node = cmds.shadingNode("file", asTexture=True, icm=True) Texture2D = cmds.shadingNode("place2dTexture", asUtility=True) # connect the texture to the shader of the object cmds.connectAttr("{0}.coverage".format(Texture2D), "{0}.coverage".format(file_node), force=True) cmds.connectAttr("{0}.translateFrame".format(Texture2D), "{0}.translateFrame".format(file_node), force=True) cmds.connectAttr("{0}.rotateFrame".format(Texture2D), "{0}.rotateFrame".format(file_node), force=True) cmds.connectAttr("{0}.mirrorU".format(Texture2D), "{0}.mirrorU".format(file_node), force=True) cmds.connectAttr("{0}.mirrorV".format(Texture2D), "{0}.mirrorV".format(file_node), force=True) cmds.connectAttr("{0}.stagger".format(Texture2D), "{0}.stagger".format(file_node), force=True) cmds.connectAttr("{0}.wrapU".format(Texture2D), "{0}.wrapU".format(file_node), force=True) cmds.connectAttr("{0}.wrapV".format(Texture2D), "{0}.wrapV".format(file_node), force=True) cmds.connectAttr("{0}.repeatUV".format(Texture2D), "{0}.repeatUV".format(file_node), force=True) cmds.connectAttr("{0}.offset".format(Texture2D), "{0}.offset".format(file_node), force=True) cmds.connectAttr("{0}.rotateUV".format(Texture2D), "{0}.rotateUV".format(file_node), force=True) cmds.connectAttr("{0}.noiseUV".format(Texture2D), "{0}.noiseUV".format(file_node), force=True) cmds.connectAttr("{0}.vertexUvOne".format(Texture2D), "{0}.vertexUvOne".format(file_node), force=True) cmds.connectAttr("{0}.vertexUvTwo".format(Texture2D), "{0}.vertexUvTwo".format(file_node), force=True) cmds.connectAttr("{0}.vertexUvThree".format(Texture2D), "{0}.vertexUvThree".format(file_node), force=True) cmds.connectAttr("{0}.vertexCameraOne".format(Texture2D), "{0}.vertexCameraOne".format(file_node), force=True) cmds.connectAttr("{0}.outUV".format(Texture2D), "{0}.uv".format(file_node), force=True) cmds.connectAttr("{0}.outUvFilterSize".format(Texture2D), "{0}.uvFilterSize".format(file_node), force=True) # a shading group shading_group = cmds.sets(renderable=True, noSurfaceShader=True, empty=True) cmds.setAttr('{0}.fileTextureName'.format(file_node), folderdir + "/" + str(shapes[0]) + ".exr", type="string") cmds.sets(obj, edit=True, forceElement=shading_group) cmds.uvLink(uvSet=shapes[0] + ".uvSet[1].uvSetName", texture=file_node) # Multiply Divide node to fix uv seems multiply_divide = cmds.shadingNode('multiplyDivide', asUtility=True) cmds.connectAttr('{0}.outColor'.format(file_node), '{0}.input1'.format(multiply_divide), force=True) cmds.connectAttr('{0}.outAlpha'.format(file_node), '{0}.input2X'.format(multiply_divide), force=True) cmds.connectAttr('{0}.outAlpha'.format(file_node), '{0}.input2Y'.format(multiply_divide), force=True) cmds.connectAttr('{0}.outAlpha'.format(file_node), '{0}.input2Z'.format(multiply_divide), force=True) #connect shader to sg surface shader cmds.connectAttr('{0}.outColor'.format(shader), '{0}.surfaceShader'.format(shading_group), force=True) #connect multiply_divide node to shader's color cmds.connectAttr('{0}.output'.format(multiply_divide), '{0}.outColor'.format(shader), force=True) cmds.setAttr('{0}.operation'.format(multiply_divide), 2) cmds.select(obj, r=True) # bake the texture into the object's vertex color cmds.polyGeoSampler(ids=True, sf=1, su=True, cdo=True, colorBlend="overwrite", alphaBlend="overwrite") ClearExtraUVSets(obj)
print(uvSetsList) print(uvSetsNamesList) print(uvSetsIndiciesList) uvSetIndiciesByName = dict(zip(uvSetsNamesList, uvSetsIndiciesList)) print(uvSetIndiciesByName) uvIndex = int(uvSetIndiciesByName[uvSetName]) uvSetQualifiedName = obj.name() + ".uvSet[" + str(uvIndex) + "].uvSetName" try: print(uvSetQualifiedName) print(textureName) cmds.uvLink(uvSet=uvSetQualifiedName, texture=textureName) """ uvCmd = ( 'uvLink -texture ' + textureName + ' -uvSet ' + uvSetQualifiedName + ';' ) print( uvCmd ) pm.mel.eval( uvCmd ) """ except: print(traceback.format_exc())