def setWipFolder(self): currentScene = pm.sceneName() if currentScene: projectPath, fileName = os.path.split(currentScene) wipFolder = '' try: wipFolder = pm.fileDialog2(dir=projectPath, ds=2, fm=3, okc='Select Folder')[0] except: pm.warning('No folder was selected') if wipFolder: self.wipFolderEdit.setText(wipFolder) self.wipFolderPath = wipFolder self.bdPopulateFiles() else: projectPath = pm.workspace.name charactersFolder = os.path.abspath( os.path.join(projectPath, 'scenes', 'characters')) path = '' try: path = pm.fileDialog2(dir=charactersFolder, ds=2, fm=3, okc='Select Folder')[0] except: pm.warning('No folder was selected') if path: self.wipFolderEdit.setText(path) self.wipFolderPath = path self.bdPopulateFiles()
def SetupAlembicInput(): loadAlembic() fileFilter = 'Alembic Files (*.abc)' title = 'Select Alembic caches' files = pm.fileDialog2(fileFilter=fileFilter, dialogStyle=1, fileMode=4, caption=title) data = {} if files: for f in files: fileFilter = 'Maya Files (*.ma *.mb)' title = 'Select shader file for %s' % os.path.basename(f) maFile = pm.fileDialog2(fileFilter=fileFilter, dialogStyle=1, fileMode=1, caption=title) if maFile: data[f] = maFile[0] for k in data: SetupAlembic(k, data[k])
def setWipFolder(self): currentScene = pm.sceneName() if currentScene: projectPath,fileName = os.path.split(currentScene) wipFolder = '' try: wipFolder = pm.fileDialog2(dir=projectPath,ds=2,fm=3,okc='Select Folder')[0] except: pm.warning('No folder was selected') if wipFolder: self.wipFolderEdit.setText(wipFolder) self.wipFolderPath = wipFolder self.bdPopulateFiles() else: projectPath = pm.workspace.path charactersFolder = os.path.abspath(os.path.join(projectPath,'scenes','characters')) path = '' try: path = pm.fileDialog2(dir=charactersFolder,ds=2,fm=3,okc='Select Folder')[0] except: pm.warning('No folder was selected') if path: self.wipFolderEdit.setText(path) self.wipFolderPath = path self.bdPopulateFiles()
def bdGetPath(self, which): projectPath = pm.workspace.name if which == 'cam' or which == 'rig': multipleFilters = "Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb);;All Files (*.*)" path = pm.fileDialog2(fileFilter=multipleFilters, dir=projectPath, ds=2, fm=1, okc='Select Camera')[0] else: path = pm.fileDialog2(dir=projectPath, ds=2, fm=3, okc='Select Folder')[0] if path: if which == 'maya': self.animPath.setText(path) self.bdPopulateFiles(path) elif which == 'avi': self.blastPath.setText(path) elif which == 'cam': self.camPath.setText(path) elif which == 'rig': self.rigPath.setText(path)
def _buttonAction(self): #inputs the first object in the selection as the textfield text upon button press if not self.disabler.getSelect()-1: file = pm.fileDialog2( ds=2, fm=1, cap='Select a binary proxy', ff='*.mib', dir=( self.project_path+"/export/GEO/RENDERPROXY/"+self.user ) ) else: file = pm.fileDialog2( ds=2, fm=3, cap='Select a binary proxy folder', dir=( self.project_path+"/export/GEO/RENDERPROXY/"+self.user ) ) pm.textFieldButtonGrp( self.button, e=True, text=file[0] )
def exportSelPattern(self): """ !@Brief Allow user to export the pattern """ pm.select(cl=True) selGarment = pm.select("|soloPatternObjectsGRP|pattern_%s" % (self.qLineGarment.text())) ### user must pick a file location ### exportPath = self.dataNode.getExportPath() singleFilter = "*.obj;;*.fbx;;*.ma;;*.mb" if exportPath == "": selection = pm.fileDialog2(fileFilter=singleFilter, dialogStyle=2, cap="Flatten objects exporter", rf=True) else: selection = pm.fileDialog2(fileFilter=singleFilter, dialogStyle=2, cap="Flatten objects exporter", rf=True, dir=exportPath) exportObject = selection[0] ### perform the export ### if selection[0][-1] == "*": exportObject = selection[0].replace("*", "obj") if selection[1] == "*.obj": pm.exportSelected( exportObject, type='OBJexport', options='groups=1;ptgroups=1;materials=0;smoothing=1;normals=1', f=True) elif selection[1] == "*.fbx": pm.exportSelected( exportObject, type='FBX export', options='groups=1;ptgroups=1;materials=0;smoothing=1;normals=1', f=True) elif selection[1] == "*.ma": pm.exportSelected(exportObject, type='mayaAscii', options='v=0;', f=True) else: pm.exportSelected(exportObject, type='mayaBinary', options='v=0;', f=True)
def fileBrowser(self, *args): erg = pm.fileDialog2(dialogStyle=2, fileMode=2) print "Result", erg if len(erg) > 0: if len(erg[0]) > 0: exportPath = erg[0] pm.textFieldButtonGrp(self.pathUI, edit=True, text=exportPath)
def _exportGroup( self, *args ): path = pm.fileDialog2( dialogStyle=2, fileMode=0, caption='Choose Group File', okCaption='Export', selectFileFilter='Group', fileFilter='Group (*.group)' ) if path is None: return else: path = path[0] groupName = self.groupOM.getValueStr() group = self._poseGroups[ groupName ] f = open( path, 'w' ) pp = pprint.PrettyPrinter( stream=f, indent=1 ) #output = ( groupName, 'group', group ) pp.pprint( group ) f.close() print "Exported Group: '%s' to: %s" % ( groupName, path )
def __importBone__(self): """import from file data""" # check if we have an object to work with if self.objSwc != None: # opening file dialog to choose a file basicFilter = "*.swc" path = pmc.fileDialog2(fileFilter=basicFilter, dialogStyle=2, caption='Import Bones Influences', okCaption='Import', fileMode=1) if (path): # get all items from both array itemsL = self.boneUI['tslBoneL'].getAllItems() itemsR = self.boneUI['tslBoneR'].getAllItems() # open the file f = open(str(path[0]), 'r') for line in f: if line.count('#') == 0: if line != '\n': tmp = line.split('=') if itemsL.count(tmp[0]) > 0: index = itemsL.index(tmp[0]) self.__renameBone__(tmp[1].replace('\n', ''), index+1) # and then close the file f.close()
def _exportPose( self, *args ): path = pm.fileDialog2( dialogStyle=2, fileMode=0, caption='Choose Pose File', okCaption='Export', selectFileFilter='Pose', fileFilter='Pose (*.pose)' ) if path is None: return else: path = path[0] group = self._poseGroups[ self.groupOM.getValueStr() ] #try: poseName = self.poseListTSL.getSelectItem()[0] f = open( path, 'w' ) pp = pprint.PrettyPrinter( stream=f, indent=1 ) #output = ( poseName, 'pose', group[poseName] ) pp.pprint( group[poseName] ) f.close() print "Exported Pose: '%s' to: %s" % ( group[poseName], path )
def __exportBone__(self): """export into file current data""" # check if we have an object to work with if self.objSwc != None: # opening file dialog to choose a file basicFilter = "*.swc" path = pmc.fileDialog2(fileFilter=basicFilter, dialogStyle=2, caption='Export Bones Influences', okCaption='Export', fileMode=0) if (path): # get all items from both array itemsL = self.boneUI['tslBoneL'].getAllItems() itemsR = self.boneUI['tslBoneR'].getAllItems() # create and open the file f = open(str(path[0]), 'w') # writting in the file f.write('# SWC export for %s \n' % self.objSwc.name()) for i in range(0, len(itemsL)): f.write(str(itemsL[i]).replace('=', '_')) f.write('=') f.write(str(itemsR[i]).replace('=', '_')) f.write('\n') # and then close the file f.close() vp.vPrint('Export Done, %s' % path[0], 2)
def Maya_createNode(self, nodeType, *args): if nodeType == 'aiStandard': # Ask for name name = self.User_inputDialog("Create aiStandard", "Enter a name for the node: ") # Create and assign shader aiStd = pc.shadingNode('aiStandard', asShader=True, name=name) aiStdSg = pc.sets(renderable=True, noSurfaceShader=True, empty=True, name=name + 'SG') aiStd.outColor >> aiStdSg.surfaceShader self.UI_refreshShaders() return(str(aiStd)) if nodeType == 'file': # Ask for name name = self.User_inputDialog("Create file", "Enter a name for the node: ") # Ask for location of the file location = pc.fileDialog2(fm=1, dialogStyle=2) myTex = pc.shadingNode('file', asTexture=True, name=name) myTex.fileTextureName.set(location) return(str(myTex)) if nodeType == 'ygColorCorrect': # Ask for name name = self.User_inputDialog("Create ygColorCorrect", "Enter a name for the node: ") ygC = pc.shadingNode('ygColorCorrect', asShader=True, name=name) return(str(ygC))
def new_scene(self): cmds.file(newFile=True, force=True) location = "{0}{1}{2}".format(os.path.dirname(os.path.realpath(__file__)), os.path.sep, self.cleanScene) self.set_project(location) cmds.file("cleanScene.ma", open=True) select_dir = pm.fileDialog2(fileMode=2, dialogStyle=3, startingDirectory=self.statusDir) if select_dir != None: print select_dir[0] sDir = str(select_dir[0]) result = cmds.promptDialog( title='Asset Name', message='Enter Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if result == 'OK': assetName = cmds.promptDialog(query=True, text=True) print assetName # makes project folder projectFolder = os.path.join(sDir, assetName) if not os.path.exists(projectFolder): print "Creating {0}".format(projectFolder) os.makedirs(projectFolder) # makes scenes folder scenesFolder = os.path.join(projectFolder, SCENE_FOLDER) if not os.path.exists(scenesFolder): print "Creating {0}".format(scenesFolder) os.makedirs(scenesFolder) # makes turntable folder turntableFolder = os.path.join(projectFolder, TURNTABLE_FOLDER) if not os.path.exists(turntableFolder): print "Creating {0}".format(turntableFolder) os.makedirs(turntableFolder) # makes export folder exportFolder = os.path.join(projectFolder, EXPORT_FOLDER) if not os.path.exists(exportFolder): print "Creating {0}".format(exportFolder) os.makedirs(exportFolder) # makes sourceimages folder sourceimagesFolder = os.path.join(projectFolder, SOURCEIMAGES_FOLDER) if not os.path.exists(sourceimagesFolder): print "Creating {0}".format(sourceimagesFolder) os.makedirs(sourceimagesFolder) fileName = assetName + "_v001_" + get_author_initials() + ".ma" fileSavePath = os.path.join(scenesFolder, fileName) print fileSavePath cmds.file(rename=fileSavePath) cmds.file(save=True)
def choose(self): self.applyButton.setEnabled(False) destination = pm.fileDialog2(cap='Open', ds=2, fm=3, okc='Open') if destination is not None: self.locationLineEdit.setText(destination[0]) self.applyButton.setEnabled(True) self.location = destination[0]
def exportAnim(self, *args): objs = pm.ls( sl=True ) successState = True filePath = pm.fileDialog2( caption='Save Animation', startingDirectory=uad , fileFilter="Anim Files (*.anim)" ) if not filePath: sys.stdout.write('Save animation cancelled.') return None animInfos = {} # dictionary containing dictionaries of every object's animations for obj in objs: if not ( self.hasUniqueName( obj ) ): # if object'n name is not unique, doesn't save animation for it successState = False pm.warning( "Object %s's name is not unique. skipped"%obj.name() ) continue nameSpace = self.getNameSpace( obj ) if nameSpace: objName = obj.name().split(':')[1] else: objName = obj.name() # find all anim curves on the object curves = pm.findKeyframe( obj , curve=True ) if not curves: # jump to next object if no anim curve found continue animInfo = {} # dictionary containing one object's animations for curve in curves: # for each curve, find where it's connected to, keys' times, values and tangents attr = pm.listConnections( '%s.output'%curve, plugs=True )[0] if nameSpace: attrName = attr.name().split(':')[1] else: attrName = attr.name() times = pm.keyframe( attr, q=True, timeChange=True ) values = pm.keyframe( attr, q=True, valueChange=True ) outWeights = pm.keyTangent( attr, q=True, outWeight=True ) outAngles = pm.keyTangent( attr, q=True, outAngle=True ) inWeights = pm.keyTangent( attr, q=True, inWeight=True ) inAngles = pm.keyTangent( attr, q=True, inAngle=True ) animInfo[ attrName ] = { 'times':times, 'values':values, 'outWeights':outWeights, 'outAngles':outAngles, 'inWeights':inWeights, 'inAngles':inAngles } animInfos[ objName ] = animInfo # write anim info to file filePath = filePath[0] logfile = open( filePath , 'w') logfile.write( str(animInfos) ) logfile.close() if successState: sys.stdout.write( 'Animation was successfully exported.' ) else: pm.warning( 'Some objects animtions were not saved due to multiple object with the same name, check script editor for more info.' )
def Export(data): multipleFilters = "JSON Files (*.json)" f = pm.fileDialog2(fileMode=0, fileFilter=multipleFilters) if f: f = open(f[0], 'w') json.dump(data, f) f.close()
def press_vdb_path(param_name): basic_filter = "OpenVDB File(*.vdb)" project_dir = pm.workspace(query=True, directory=True) vdb_path = pm.fileDialog2(fileFilter=basic_filter, cap="Select OpenVDB File", okc="Load", fm=1, startingDirectory=project_dir) if vdb_path is not None and len(vdb_path) > 0: vdb_path = vdb_path[0] # inspect file and try to figure out the padding and such try: dirname, filename = os.path.split(vdb_path) if re.match(".*[\._][0-9]+[\._]vdb", filename): m = re.findall("[0-9]+", filename) frame_number = m[-1] padding = len(frame_number) cache_start = int(frame_number) cache_end = int(frame_number) frame_location = filename.rfind(frame_number) check_file_re = re.compile((filename[:frame_location] + "[0-9]{%i}" % padding + filename[frame_location + padding:]).replace(".", "\\.")) for each in os.listdir(dirname): if os.path.isfile(os.path.join(dirname, each)): if check_file_re.match(each): current_frame_number = int(each[frame_location : frame_location + padding]) cache_start = min(cache_start, current_frame_number) cache_end = max(cache_end, current_frame_number) frame_location = vdb_path.rfind(frame_number) vdb_path = vdb_path[:frame_location] + "#" * padding + vdb_path[frame_location + padding:] node_name = param_name.split(".")[0] pm.setAttr("%s.cache_playback_start" % node_name, cache_start) pm.setAttr("%s.cache_playback_end" % node_name, cache_end) except: print "[openvdb] Error while trying to figure out padding, and frame range!" import sys, traceback traceback.print_exc(file=sys.stdout) pm.textFieldButtonGrp("OpenVDBPathGrp", edit=True, text=vdb_path) pm.setAttr(param_name, vdb_path, type="string")
def _getObjsFromSkinFile(filePath=None, *args): # retrive the object names inside gSkin file if not filePath: f1 = 'mGear Skin (*{0} *{1})'.format(FILE_EXT, FILE_JSON_EXT) f2 = ";;gSkin Binary (*{0});;jSkin ASCII (*{1})".format( FILE_EXT, FILE_JSON_EXT) f3 = ";;All Files (*.*)" fileFilters = f1 + f2 + f3 startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(dialogStyle=2, fileMode=1, startingDirectory=startDir, fileFilter=fileFilters) if not filePath: return if not isinstance(filePath, basestring): filePath = filePath[0] # Read in the file with open(filePath, 'r') as fp: if filePath.endswith(FILE_EXT): data = pickle.load(fp) else: data = json.load(fp) return data["objs"]
def exec_button(*args): path = pmc.fileDialog2(fileFilter='*.abc') if path: path = path[0] else: exit("Canceled") #query ui values framemode = pmc.radioCollection('framemode', query=True, sl=True) preroll = pmc.checkBox('preroll', q=True, value=True) qstart = pmc.intField('start', q=True, value=True) qend = pmc.intField('end', q=True, value=True) preframe = pmc.intField('prerollstart', q=True, value=True) step = pmc.intField('step', q=True, value=True) toguerilla = pmc.checkBox('guerilla', q=True, value=True) #export with maUtils abc_export marilla.maUtils.abc_export(path=path,framemode=framemode,preroll=preroll, qstart=qstart, qend=qend, preframe=preframe, step=step, nodes=pmc.ls(sl=True)) #send to guerilla if toguerilla: command=("local mod = Document:modify(); mod.createref ('{filename}'" ",'{path}',nil,{{prefixnodes=false,containschildren=false}}); " "mod.finish()").format( filename=os.path.basename(path).split('.')[0], path=path) try: sock = marilla.utils.sockette.SendCommand(port=1978, command=command) sock.send() except: raise SystemError("Maybe Guerilla is closed ? ") if pmc.window('exportabc', exists=True): pmc.deleteUI('exportabc')
def bdGetObjPath(self): projectPath = pm.workspace.name self.path = pm.fileDialog2(dir=projectPath,ds=2,fm=3,okc='Select Folder')[0] if self.path: self.objPath.setText(self.path) self.bdPopulateFiles()
def export_curve(filePath=None, objs=None): """Export the curve data to a json file Args: filePath (None, optional): Description objs (None, optional): Description Returns: TYPE: Description """ if not filePath: startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(dialogStyle=2, fileMode=0, startingDirectory=startDir, fileFilter='NURBS Curves .crv (*%s)' % ".crv") if not filePath: pm.displayWarning("Invalid file path") return if not isinstance(filePath, (six.string_types, six.text_type)): filePath = filePath[0] data = collect_selected_curve_data(objs) data_string = json.dumps(data, indent=4, sort_keys=True) f = open(filePath, 'w') f.write(data_string) f.close()
def xmlFileBrowse(self, args=None): filename = pm.fileDialog2(fileMode=0, caption="Export Corona File Name") if len(filename) > 0: filename = filename[0] if not filename.endswith(".igs"): filename += ".igs" self.rendererTabUiDict['xml']['xmlFile'].setText(filename)
def _mouseDoubleClickEventInPolycountTreeView(self, event): polycount.getPolyCountGroupByContainer() scene_path = pm.system.sceneName().dirname() path = pm.fileDialog2(cap='Open', ds=2, fm=1, dir=scene_path, okc='Open', ff='All Json Files (*.json)') if path is not None: with open(path[0], 'r') as source: polyCount = json.load(source, encoding='utf-8') index = 0 self.modelInPolycountTreeView.clear() for header in ('Asset', 'Tris', 'Verts'): item = QStandardItem(header) item.setFont(self.font) item.setEditable(False) self.modelInPolycountTreeView.setHorizontalHeaderItem( index, item) index += 1 self._displayPolyCountInTreeView(polyCount) self.polycountTreeView.resizeColumnToContents(0) self.polycountTreeView.resizeColumnToContents(1) self.polycountTreeView.resizeColumnToContents(2) QTreeView.mouseDoubleClickEvent(self.polycountTreeView, event)
def get_file(caption = 'Open', filter = '*.*', dir = ''): import pymel.core as pm path = pm.fileDialog2(spe=False, caption = caption, dir = dir, fileFilter=filter, fm=1, dialogStyle=2) if path: return path[0] return None
def export(self): if not pm.ls(sl=True): pm.warning("No objects selected") return path = pm.fileDialog2(fileFilter="*.obj", dialogStyle=2, fileMode=0, dir=pm.workspace.path) if not path: return path = path[0] for f in range(self.start_frame, self.end_frame + 1): frame_path = ('%s_%04d.obj' % (path[:-4], f)) print frame_path pm.currentTime(f) pm.exportSelected( frame_path, force=True, options="groups=1;ptgroups=1;materials=0;smoothing=1;normals=1", typ="OBJexport", preserveReferences=False, exportSelected=True)
def readStandin(*args): ff = "*.binarymesh" filename = pm.fileDialog2(fileMode=1, caption="Select binarymesh", fileFilter = ff) if len(filename) > 0: bm = BinaryMesh() bm.path = filename[0] bm.loadStandins()
def exportGuidePlacement(filepath=None, refMesh=UNIVERSAL_MESH_NAME, rootNode=GUIDE_ROOT, avoidCrawl=SKIP_CRAWL_NODES, skipStrings=[]): """Export the position of the supplied root node to a file. Args: filepath (str, optional): path to export too refMesh (str, optional): mesh to query verts rootNode (str, optional): name of node to query against avoidCrawl (list, optional): of nodes not to crawl skipStrings (list, optional): strings to check to skip node Returns: list: dict, list, str """ if filepath is None: filepath = pm.fileDialog2(dialogStyle=2, fileMode=0, startingDirectory="/", fileFilter="Export position(*.json)") if filepath: filepath = filepath[0] (relativeGuide_dict, ordered_hierarchy) = recordInitialGuidePlacement(refMesh=refMesh, rootNode=rootNode, avoidCrawl=avoidCrawl, skipStrings=skipStrings) data = {} data["relativeGuide_dict"] = relativeGuide_dict data["ordered_hierarchy"] = ordered_hierarchy _exportData(data, filepath) print "Guide position exported: {}".format(filepath) return relativeGuide_dict, ordered_hierarchy, filepath
def _doCacheBlend(self): sel = pm.ls(sl=True, type=["transform", "mesh"]) if not sel \ or sel[0].nodeType() == "transfrom" and sel[0].getShape().nodeType() != "mesh": pm.warning("Please select cloth mesh to create cache blend.") return None cachePath = pm.fileDialog2(dialogStyle=2, fileMode=1) if not cachePath: return None clothMesh = sel[0] if sel[0].nodeType( ) == "transform" else sel[0].getParent() timeNode = pm.PyNode("time1") blendOutMesh = pm.duplicate(clothMesh, name=clothMesh.name() + "_blend1")[0] cacheInMesh = pm.duplicate(clothMesh, name=clothMesh.name() + "_orig_blend1")[0] cacheInMesh.hide() qlCacheNode = pm.createNode("qlCache") cacheInMesh.outMesh.connect(qlCacheNode.input) qlCacheNode.output.connect(blendOutMesh.inMesh) timeNode.outTime.connect(qlCacheNode.time) qlCacheNode.cacheName.set(cachePath) qlCacheNode.perFrameCache.set(1) qlCacheNode.startTime.set(pm.playbackOptions(query=True, minTime=True))
def createSymData(*args): """ write sym table to a file """ # Get file path filepath = pm.fileDialog2(fileMode=0, caption="Save sym data") if filepath is None: return filepath = filepath[0] if len(cmds.ls(sl=True)) == 0: cmds.warning("Nothing is selected") return result = cmds.buildSymmetryTable() # Convret Long to Int pp = [int(i) for i in result] # Split two ints to a dict # eg. [x, x, x, x, x, x, ...] # to.. # {x: x, x: x, x: x, ...} # Key is left verts and values are right verts pDict = {} pList = [pp[i:i + 2] for i in range(0, len(pp), 2)] for i in pList: pDict[i[0]] = i[1] # Store data (serialize) with open(filepath, 'wb') as handle: pickle.dump(pDict, handle, protocol=pickle.HIGHEST_PROTOCOL)
def changeOutputDestination(self, dest = None): '''updates the output location for muster renders''' #TODO: check access to proposed render location location if not dest: dest = pm.fileDialog2(fileMode = 3, dialogStyle = 1, startingDirectory = self.widgets['outputDir'].getFileName()) if dest: self.widgets['outputDir'].setText(pm.Path(dest[0]))
def loadDeformerWeights(filename=None): ''' Usage: loadDeformerWeights(filename='/jobs/mercedesFable_5402587/build/charTortoise/maya/export/WEIGHTS/tortoiseAFacial/extraWeights/deformerWeights/v03/deformerWeights.json') loadDeformerWeights() ''' if not filename: try: filename = pm.fileDialog2(cap='Select a json file you stored', fm=1, okc='Load', ff='JSON (*.json)')[0] except: pm.error('file not found, whatever.') with open(filename, 'rb') as fp: data = json.load(fp) for key in data.keys(): if pm.objExists(key): deformer = Deformer(pm.PyNode(key)) print 'Loading weights for deformer:\t%s'%deformer for deformedShape in data[key].keys(): if pm.objExists(deformedShape): print '\tLoading deformer weights on shape:\t%s'%deformedShape deformedTransform = pm.PyNode(deformedShape).getParent() #print data[key][deformedShape] deformer.setWeights(data[key][deformedShape], deformedTransform) else: pm.warning('Object %s does not exist to apply deformer weights to...skipping'%deformedShape) else: pm.warning('Deformer %s doesn\'t exist...skipping'%key)
def _get_file(write=False): """Convinience function to retrive the guide file in at export or import. Args: write (bool, optional): If true, will set the dialog to write. If false will se the dialog to read. Returns: str: the file path """ if write: mode = 0 else: mode = 1 startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(startingDirectory=startDir, fileMode=mode, fileFilter='Shifter Guide Template .sgt (*%s)' % ".sgt") if not filePath: return if not isinstance(filePath, basestring): filePath = filePath[0] return filePath
def load_shelf_UI(cls): """ Gives us a file dialog to pick a specific shelf to reload/create """ prefs = cls.get_user_shelves_dir() shelf_path = pm.fileDialog2(ff='*.mel', ds=2, fm=4,dir=prefs) if shelf_path: cls.shelf_update(shelf_path[0])
def create_file(self): """ Convert the data structure to JSON and save a file with the data. :return: None """ path = pm.fileDialog2(fileFilter="*.avrl", dialogStyle=2, fileMode=0, dir=pm.workspace.path) if path: self.create_data_structure() if not self.data_structure: pm.warning( 'No curve data found. Select 1 or more groups containing curves.' ) return json_data = json.dumps(self.data_structure) path = path[0] f = open(path, 'w+') f.write(json_data) f.close() print('\n// File saved as %s' % path),
def OpenFiles(): newerFile = pm.fileDialog2(ds = 2, ff = '*.sb', fm = 1) if(newerFile == None): sys.stdout.write('Warning: At lest one animation file must be selected.') return return newerFile
def storeDeformerWeights(selection=True, type='rig_vertSnap'): ''' Usage: storeDeformerWeights(selection=False) storeDeformerWeights(selection=True, type=['rig_vertSnap']) storeDeformerWeights(selection=False, type=['rig_vertSnap', 'wire']) ''' deformers = pm.ls(type=type) if selection: if len(pm.ls(sl=True))==0: pm.error('select something numbnuts!') deformers = pm.ls(sl=True)[0].listHistory(type='rig_vertSnap') vsFile = {} for deformer in deformers: vs = Deformer(deformer) vs.initializeWeights() if len(vs.weightsList) > 0: vsFile[deformer.name()] = vs.weightsList try: filename = os.path.join( pm.fileDialog2(cap='Select a folder to store the weights', fm=3, okc='Select')[0], 'deformerWeights.json' ) except: pm.error('Why did you cancel? :(') with open(filename, 'wb') as fp: print 'Storing weights in file:\n\t%s'%(filename) print '\t\tDeformers Stored:\n\t\t\t%s'%('\n\t\t\t'.join([deformer.name() for deformer in deformers])) json.dump(vsFile, fp, indent=4)
def CreateFilePath(): newFile = pm.fileDialog2(fm=0, ds=2, ff='*.sb') if (newFile == None): sys.stdout.write( 'Warning: A name or a path for the file should be chosen.') return return newFile
def ui2py(filePath=None, *args): """Convert qtDesigner .ui files to .py""" if not filePath: startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(dialogStyle=2, fileMode=1, startingDirectory=startDir, fileFilter='PyQt Designer (*%s)' % UI_EXT, okc="Compile to .py") if not filePath: return False filePath = filePath[0] if not filePath: return False if not filePath.endswith(UI_EXT): filePath += UI_EXT compiledFilePath = filePath[:-2] + "py" pyfile = open(compiledFilePath, 'w') compileUi(filePath, pyfile, False, 4, False) pyfile.close() info = "PyQt Designer file compiled to .py in: " pm.displayInfo(info + compiledFilePath)
def importConnections(filePath=None, nsRig=None, nsSkin=None, useMtx=True): """import connections from file Args: filePath (str, optional): Connection json file pth nsRig (str, optional): Rig namespace nsSkin (str, optional): mMdel namespace useMtx (bool, optional): If True will use matrix multiplication, if False, will use constraint connections Returns: None: None """ if not filePath: startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(fileMode=1, startingDirectory=startDir, fileFilter=' Shifter joint cnx matrix ' ' .jmm (*%s)' % ".jmm") if not filePath: return if not isinstance(filePath, basestring): filePath = filePath[0] with open(filePath) as fp: configDict = json.load(fp) if useMtx: connect(configDict, nsRig=nsRig, nsSkin=nsSkin) else: connectCns(configDict, nsRig=nsRig, nsSkin=nsSkin)
def exportSelectionAsABC(): # check for AbcExport command if not 'AbcExport' in dir(pm): pm.error('AbcExport: command not found.') return # retrieve all selected node paths selection = pm.ls(sl=True, recursive=True, dagObjects=True) if not selection: return nodePathtoExport = [] for n in selection: if n.type() != 'transform': nodePathtoExport.append(n.getParent().fullPath()) # get out file path from user outfile = pm.fileDialog2(fileMode=0) if not outfile: return # ensure we use a '*.abc' file extension outfile = os.path.splitext(outfile[0])[0]+'.abc' # build the AbcExport command exportCmd = '-worldSpace -attr mvg_imageSourcePath -attr mvg_intrinsicParams -file %s -uvWrite'%outfile for p in nodePathtoExport: exportCmd += ' -root %s'%p exportCmd = ''' import pymel.core as pm pm.AbcExport(j="%s")'''%exportCmd pm.evalDeferred(exportCmd)
def set_export_path(self): # resolve last file path if self.save_dir: path = self.save_dir else: path = pm.workspace(q=True, rd=True) if self.file_name: path = path + '/' + self.file_name # show dialog result = pm.fileDialog2(caption='Export FBX File', dialogStyle=2, fileMode=0, fileFilter='FBX Export (*.fbx)', okCaption='Export', dir=path) if result is None: return False # set new export directory path = os.path.split(result[0]) self.save_dir = path[0] self.file_name = path[1] self.save_file_option() return True
def importReferenceCallback(*pArgs): mySelection = pm.fileDialog2(caption='Import', fileFilter='*.fbx', fileMode=4, dialogStyle=2, okCaption='Select Directory') newObjects = importWithComparison(mySelection[0]) windowID = 'referenceID' globalGender[0] = getGender() if cmds.window(windowID, exists=True): cmds.deleteUI(windowID) pm.window(windowID, resizeToFitChildren=True, title='Import Reference') pm.rowColumnLayout(numberOfColumns=1) pm.text(label='Describe your reference:') pm.textField("referenceDescription", width=200) pm.rowColumnLayout(numberOfColumns=3) pm.separator(width=100, style='none') pm.button(label='Save', width=50, command=functools.partial(saveReferenceName, newObjects)) pm.button(label='Cancel', width=50, command=functools.partial(cancelName, windowID)) pm.setParent('..') pm.setParent('..') pm.showWindow(windowID)
def bdSaveRenderFile(self): animPath = self.animFile animFileName = animPath.split('/')[-1] renderFilePath = projectPath + self.cachePath.replace('cache', '') renderFile = renderFilePath + animFileName.replace('ANIM', 'CACHE') if os.path.isdir(renderFilePath): if os.path.isfile(renderFile): multipleFilters = "Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb);;All Files (*.*)" renderFile = pm.fileDialog2( fm=0, fileFilter=multipleFilters, dialogStyle=2, dir=os.path.normpath(renderFilePath))[0] unknown = pm.ls(type="unknown") unknown = filter(lambda node: not node.isReferenced(), unknown) for node in unknown: if not pm.objExists(node): continue pm.delete(node) try: pm.saveFile(os.path.normpath(renderFile), force=True) except: pm.warning('Cant save maya ascii') else: pm.warning('Could not save render file !!!')
def open_file_browser(unused): old_path = pm.getAttr(fileAttribute) old_path = old_path.replace('\\', '/') starting_file = os.path.basename(old_path) # Find the absolute path to the current path, if any, and open the browser in the # same directory as the current path. Why don't all Maya file browsers do this? starting_directory = '' if old_path: attr = pm.ls(fileAttribute)[0] node_name = attr.nodeName() absolute_path = omr.MRenderUtil.exactFileTextureName( old_path, False, "", node_name) starting_directory = os.path.dirname(absolute_path) options = pm.mel.eval('fileBrowserActionSetup("image", 1)') files = pm.fileDialog2(caption='Open', okCaption='Open', fileMode=1, fileFilter=options[2], startingDirectory=starting_directory, selectFileFilter=starting_file) if not files: return path = files[0] path = path.replace('\\', '/') pm.setAttr(fileAttribute, path)
def exportSelectionAsABC(): # check for AbcExport command if not 'AbcExport' in dir(pm): pm.error('AbcExport: command not found.') return # retrieve all selected node paths selection = pm.ls(sl=True, recursive=True, dagObjects=True) if not selection: return nodePathtoExport = [] for n in selection: if n.type() != 'transform': nodePathtoExport.append(n.getParent().fullPath()) # get out file path from user outfile = pm.fileDialog2(fileMode=0) if not outfile: return # ensure we use a '*.abc' file extension outfile = os.path.splitext(outfile[0])[0] + '.abc' # build the AbcExport command exportCmd = '-worldSpace -attr mvg_imageSourcePath -attr mvg_intrinsicParams -file %s -uvWrite' % outfile for p in nodePathtoExport: exportCmd += ' -root %s' % p exportCmd = ''' import pymel.core as pm pm.AbcExport(j="%s")''' % exportCmd pm.evalDeferred(exportCmd)
def get_path(): path = pm.fileDialog2(fileMode= 3)[0] path_field.setText(path) dir_name = os.path.dirname(__file__) file_path = os.path.join(dir_name, 'Startup', 'grade.path') f = open(file_path, 'w') pickle_data = pickle.dump(path, f) f.close()
def browse_btn(self, *args): try: self.imagePath = pm.fileDialog2(fileMode=1)[0] except TypeError: self.imagePath = pm.getAttr(self.lightShape+'.texture') self.ibl_filePath.setText(self.imagePath) pm.setAttr(self.lightShape+'.texture', self.imagePath, type="string")
def selectGeoFile(self): print "Select file" startDir = r"C:\daten\3dprojects\mantra\data\fluidGeo" # fileFilter="*.geo;;*.bgeo" seems not to work correctly... self.fileName = pm.fileDialog2(cap="Select Geo File", dir=startDir, fm=1) if len(self.fileName) > 0: self.fileName = self.fileName[0] pm.textFieldButtonGrp("stdingfilename", edit=True, text=self.fileName)
def browsePathTextField(cls, textField, filter, caption, *args, **kwargs): ''' ''' path = pm.textField(textField, query=True, text=True) path = pm.fileDialog2(ds=1, caption=caption, dir=path, fileFilter=filter, fileMode=3) if path: pm.textField(textField, edit=True, text=path[0]) return path
def getImportFilePath(self, *args): filePath = pm.fileDialog2(fileMode = 1) if filePath == None: self._importFilePath = filePath[0] else: self._importFilePath = filePath[0] self.__init__()
def ui_set_path(self, *uiargs, **kwargs): ''' Find/set a new path for sourcing tools from ''' if self.verbose: print '\t...Browsing for new path' new_path = pm.fileDialog2(fileMode=2) self.ui_path.setText(new_path[0])
def lcObj_setExportPath(*args, **kwargs): ''' browse a folder path and update text field ''' global prefix path = pm.textField(prefix+'_textField_export_path', query=True, text=True) filter = "Wavefront Obj (*.obj)" path = pm.fileDialog2(ds=1, caption='Obj Export Location', dir=path, fileFilter=filter, fileMode=3) if path: pm.textField(prefix+'_textField_export_path', edit=True, text=path[0])
def browse(self,*args): defaultPath = pm.textField( self.cacheFolderTextField, q=True, text=True ) # if user has enterd a path in the field, browse from that path if not defaultPath: # else use current open file path in browse window defaultPath=currentFilePath cacheFolder = pm.fileDialog2( caption='Choose Geometry Cache Folder', fileMode=2, startingDirectory=defaultPath, fileFilter='xml' ) if cacheFolder: pm.textField( self.cacheFolderTextField, edit=True, text=cacheFolder[0] )
def readStandin(*args): log.debug("read standin") ff = "*.binarymesh" filename = pm.fileDialog2(fileMode=1, caption="Select binarymesh", fileFilter = ff) if len(filename) > 0: print "Reading binarymesh", filename bm = BinaryMesh() bm.path = filename[0] bm.loadStandins()
def xmlFileBrowse(self, args=None): print "xmlfile", args filename = pm.fileDialog2(fileMode=0, caption="Export Indigo File Name") if len(filename) > 0: filename = filename[0] print "Got filename", filename if not filename.endswith(".igs"): filename += ".igs" self.rendererTabUiDict['xml']['xmlFile'].setText(filename)