def findReference( path="", expression="", force=False, dialog=False ): """ List similar files for current file . """ result = "" if os.path.isfile( path ): filename = path.split( "/" ) directory = "/".join( filename[0:-1] ) + "/" filename = filename[-1].split( "." )[0] files = os.listdir( directory ) expression = re.compile( expression, re.IGNORECASE ) if expression.findall( filename ): ignore = True else: ignore = False for i in range( 0, len( files )): if re.findall( ".ma|.mb", files[i] ): mfiletemp = files[i].split( "/" )[-1].split( "." )[0] if filename != mfiletemp: if ignore is True: if mfiletemp == expression.sub( "", filename ): return os.path.join( directory, files[i] ) else: if filename == expression.sub( "", mfiletemp ): return os.path.join( directory, files[i] ) if result != "" and force is True and dialog is False: result = cmds.fileDialog2( caption="Reference", fileFilter="Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb)", startingDirectory=directory, fileMode=1 ) elif dialog is True: result = cmds.fileDialog2( caption="Reference", fileFilter="Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb)", startingDirectory=directory, fileMode=1 ) if result: result = result[-1] return result
def browse(folder,*args): if folder=='renderFolder': mc.textField(str(folder),edit=1,text=mc.fileDialog2(ds=2,dir=os.path.join(mc.workspace(q=1,rd=1),'scenes'),fm=3,okc="Set",cc="Cancel")[0].split('/')[-1]) else: mc.textField(str(folder),edit=1,text=mc.fileDialog2(ds=2,dir=os.path.join(mc.workspace(q=1,rd=1),'scenes'),fm=3,okc="Set",cc="Cancel")[0]) commitUI() UI()
def __init__(self) : # create a promptDialog for the base group name of our mesh this will help to # avoid name conflicts, may be good to modify this at some stage to check if mesh # exists and prompt to replace data / key result = cmds.promptDialog( title='Name', message='Enter Name for import', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') # if ok was pressed lets process the data if result == 'OK': # first we get the text entered by the user self.m_text = cmds.promptDialog(query=True, text=True) # now get the obj file to import self.m_objFileName=cmds.fileDialog2(caption="Please select obj file to import",fileFilter="*.obj", fm=1) cmds.file(self.m_objFileName,i=True,type="OBJ",ns=self.m_text) # now the xml file basicFilter = "*.xml" self.m_pointBakeFile=cmds.fileDialog2(caption="Please select xml file to import",fileFilter=basicFilter, fm=1) # select the object imported print self.m_pointBakeFile cmds.select("%s:Mesh"%(self.m_text)) # and pass control back to the parser parser = xml.sax.make_parser() parser.setContentHandler(ParseHandler("%s:Mesh"%(self.m_text))) parser.parse(open(str(self.m_pointBakeFile[0]),"r"))
def get_open_file_name(file_filter=None): if file_filter: files = mc.fileDialog2(fileFilter='.' + file_filter, fileMode=1) else: files = mc.fileDialog2(fileMode=1) if files: return files[0] else: return None
def getSaveFileName(filter = None): if filter: files = mc.fileDialog2(fileFilter = '.' + filter, fileMode = 0) else: files = mc.fileDialog2(fileMode = 0) if files: return files[0] else: return None
def Dialog(mode): singleFilter = "SKL Files (*.skl)" if mode == "export": path = cmds.fileDialog2(ff=singleFilter, fm=0, okc = "OK")[0].rpartition(".")[0] if mode == "import": path = cmds.fileDialog2(ff=singleFilter, fm=1, okc = "OK")[0].rpartition(".")[0] return path + ".skl"
def shotReferenceTool_getTextFieldInfo(fileFilter, fileMode, textField, *args): filePath = cmds.fileDialog2(fileMode= fileMode, dialogStyle=2, fileFilter = fileFilter)[0] filePath = str(filePath) cmds.textField(textField, edit = True, text = filePath) return filePath
def export_skin(file_path=None, shapes=None): """Exports the skinClusters of the given shapes to disk in a pickled list of skinCluster data. :param file_path: Path to export the data. :param shapes: Optional list of dag nodes to export skins from. All descendent nodes will be searched for skinClusters also. """ if shapes is None: shapes = cmds.ls(sl=True) or [] # If no shapes were selected, export all skins skins = get_skin_clusters(shapes) if shapes else cmds.ls(type='skinCluster') if not skins: raise RuntimeError('No skins to export.') if file_path is None: file_path = cmds.fileDialog2(dialogStyle=2, fileMode=0, fileFilter='Skin Files (*{0})'.format(EXTENSION)) if file_path: file_path = file_path[0] if not file_path: return if not file_path.endswith(EXTENSION): file_path += EXTENSION all_data = [] for skin in skins: skin = SkinCluster(skin) data = skin.gather_data() all_data.append(data) logging.info('Exporting skinCluster %s (%d influences, %d vertices)', skin.node, len(data['weights'].keys()), len(data['blendWeights'])) fh = open(file_path, 'wb') pickle.dump(all_data, fh, pickle.HIGHEST_PROTOCOL) fh.close()
def browseButton( self, *args ): #pops up search window filterType = "*.xyz" self.widgets[ "browseField" ] = cmds.fileDialog2( dialogStyle=2, caption='Load LIDAR', fileMode=1, fileFilter=filterType ) cmds.textField( self.widgets[ "lidarPathField" ], edit=True, text=self.widgets[ "browseField" ][0] )
def getNukeExe(self): # get nuke path on windows defaultNukePath = [ 'C:/Program Files/Nuke6.0v5/Nuke6.0.exe', 'C:/Program Files/Nuke6.3v4/Nuke6.3.exe', 'C:/Program Files (x86)/Nuke6.3v4/Nuke6.3.exe', ] for path in defaultNukePath: if os.path.exists(path): PRESETS.addPreset('nukeexe', path) # get the nuke path preset if exists nukeexe = PRESETS.getPreset('nukeexe') if nukeexe: if os.path.exists(nukeexe[0]): return nukeexe[0] else: raise UserWarning('No exe found !') else: # ask for the sublime text exe path filedialog = cmds.fileDialog2(cap='Please give me the path of Nuke.exe !', fm=1, dir='C:\\Program Files\\', ff='*.exe') if filedialog: nukeexe = str(filedialog[0]) if os.path.exists(nukeexe): # setting preset PRESETS.addPreset('nukeexe', nukeexe) return nukeexe else: raise UserWarning('No exe found !') else: raise UserWarning('No exe found !')
def multObjShapeUpdate(): sel_objs = cmds.ls(sl=True,fl=True) if len(sel_objs)>0: files_to_import = cmds.fileDialog2(fileFilter = '*.obj', dialogStyle = 2, caption = 'import multiple object files', fileMode = 4,okc="Import") if len(files_to_import) == len(sel_objs): object_names = [file_to_import.split('/')[-1].split('.obj')[0] for file_to_import in files_to_import] if len(sel_objs) == len([x for x in object_names if x in sel_objs]): for file_to_import in files_to_import: object_name = file_to_import.split('/')[-1].split('.obj')[0] returnedNodes = cmds.file('%s' % file_to_import, i = True, type = "OBJ", rnn=True, ignoreVersion = True, options = "mo=0", loadReferenceDepth = "all" ) cmds.delete(cmds.ls(returnedNodes,type="objectSet")) geo = cmds.listRelatives(cmds.ls(returnedNodes,g=1)[0],p=1) cmds.rename( geo, "newShape_{0}".format(object_name)) new_shapes = [s for s in cmds.listRelatives(cmds.ls(g=1),p=1) if "newShape_" in s] cur_shapes = sel_objs for new in new_shapes: for cur in cur_shapes: if new.split("newShape_")[1] == cur: blendshapeNd = cmds.blendShape(new,cur)[0] cmds.setAttr("{0}.{1}".format(blendshapeNd,new),1) cmds.delete(cur_shapes,ch=True) cmds.delete(new_shapes) cmds.confirmDialog(m="---===All Shapes Updated!===---") else: cmds.confirmDialog(m="--==Not Matching The Name!==--") else: cmds.confirmDialog(m="--==Please Select The Same Number Of Objects!==--") else: cmds.confirmDialog(m="--==Please Select Something!==--")
def check_editor_preferences(): # get preference values of external app path photo_dir = cmds.optionVar(exists='PhotoshopDir') image_dir = cmds.optionVar(exists='EditImageDir') # if there is no external app, request for an app path if not photo_dir and not image_dir: pref_warn = QMessageBox() pref_warn.setWindowTitle(WINDOW_TITLE) pref_warn.setIcon(QMessageBox.Warning) pref_warn.setText( '<b>Applications for Editing Image Files</b> ' 'is not set in your preferences.<br>' 'Maya needs it to send image in the right Image Editor ' 'instead of file system association.') pref_warn.setInformativeText('Do you want to select an application ?') pref_warn.setStandardButtons(QMessageBox.Yes | QMessageBox.No) pref_warn.setDefaultButton(QMessageBox.Yes) pref_warn.setEscapeButton(QMessageBox.Cancel) ret = pref_warn.exec_() if ret == QMessageBox.Yes: app_path = cmds.fileDialog2( fileFilter='Image editor application (*.exe)', caption='Select image editor application', startingDirectory=os.path.expandvars('%ProgramFiles%'), fileMode=1) if app_path is not None: cmds.optionVar(sv=('PhotoshopDir', app_path[0])) cmds.optionVar(sv=('EditImageDir', app_path[0]))
def browseDirectoryPath(self, *args): basicFilter = "*All(*.*);;tif(*.tif);;jpg(*.jpg);;exr(*.exr);;tx(*.tx)" self.returnPath = cmds.fileDialog2( fileFilter=basicFilter, ds=2, startingDirectory=self.homeDir)[0] cmds.textField(self.uvImagePath, e=True, text=self.returnPath)
def TappInstall_browse(*args): repoPath=cmds.fileDialog2(dialogStyle=1,fileMode=3) if repoPath: repoPath=repoPath[0].replace('\\','/') check=False #checking all subdirectories for name in os.listdir(repoPath): #confirm that this is the Tapp directory if name=='Tapp': check=True if check: #create the text file that contains the Tapp directory path path=cmds.internalVar(upd=True)+'Tapp.yml' f=open(path,'w') data='{launchWindowAtStartup: False, repositoryPath: \''+repoPath+'\'}' f.write(data) f.close() #run setup sys.path.append(repoPath) cmds.evalDeferred('import Tapp') #delete ui cmds.deleteUI('TappInstall_UI') else: cmds.warning('Selected directory is not the \'Tapp\' directory. Please try again')
def confirmSave(): base = studioBase.StudioSQL() result = cmds.confirmDialog( title='File not saved', message='Save file?', button=['Save', 'Dont save', 'Cancel'], defaultButton='Save', cancelButton='Cancel') # --- Save ------------------------------------------------------ if result == 'Save': fileName = cmds.file(q=True, sceneName=True) if not fileName: fileName = cmds.fileDialog2(ds=1, fileMode=0, caption="Save file", fileFilter='Maya ASCII (*.ma);;Maya Binary (*.mb)') if fileName: fileName = fileName[0] cmds.file(rename=fileName) else: return False base.setAction('save', fileName) if fileName.split('.')[-1] == 'ma': cmds.file(save=True, type='mayaAscii') else: cmds.file(save=True, type='mayaBinary') return True # --- Dont save ------------------------------------------------- elif result == 'Dont save': return True # --- Cancel ---------------------------------------------------- else: return False
def openFile(self, *args): """ This opens the file browser and takes the path and puts it in the text field. This is run when the Browse button is pressed. """ self.fileName = cmds.fileDialog2( fileMode=2, caption="Import Image" ) # Open the file browser cmds.textField( self.loadDirPath, edit=True, text=str(self.fileName[0]) ) # Put path in text field
def onAddNewImage(self, *args): imageFilter = "All Files(*.*)" filePaths = cmds.fileDialog2(dialogStyle = 2, fileMode=1, fileFilter=imageFilter) if filePaths: newImageElement = self.createImageElement(filePaths[0]) if newImageElement: self.updateScrollLayout(newImageElement)
def loadDirectoryPath(textField,caption='Load Directory',startDir=None): ''' Select a file path to load into a specified textField. @param textField: TextField UI object to load file path to @type textField: str @param caption: File selection UI caption string @type caption: str @param startDir: Directory to start browsing from. In None, use the default or last selected directory. @type startDir: str ''' # Get File Path dirPath = mc.fileDialog2( dialogStyle=2, fileMode=3, caption=caption, okCaption='Load', startingDirectory=startDir ) # Check File Path if not dirPath: print('Invalid directory path!') return # Load File Path to TextField if mc.textField(textField,q=True,ex=True): mc.textField(textField,e=True,text=dirPath[0]) elif mc.textFieldGrp(textField,q=True,ex=True): mc.textFieldGrp(textField,e=True,text=dirPath[0]) elif mc.textFieldButtonGrp(textField,q=True,ex=True): mc.textFieldButtonGrp(textField,e=True,text=dirPath[0]) else: print('UI element "'+textField+'" is of type "'+mc.objectTypeUI(textField)+'"! Expected textField, textFieldGrp or textFieldButtonGrp.') return # Return Result return dirPath[0]
def setDBPath(self, *args): fileFilters = "Database (*.db *.sqlite) (*.db *.sqlite)" path = cmds.fileDialog2(fileMode=1, caption="Open .db File", dialogStyle=2, okCaption="Open", startingDirectory=self.basedir, fileFilter=fileFilters) if path == None: return cmds.textFieldButtonGrp("tfbDBPath", e=True, tx=path[0])
def tmpShowUsdFilePathBrowser(*args): filePaths = cmds.fileDialog2( caption="Specify USD File", fileFilter="USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc)", fileMode=1) if filePaths: cmds.setAttr(nodeAttr, filePaths[0], type='string')
def _open(self): """open marking menu""" self._file_read = cmds.fileDialog2(fm=1, ff='menu_*.mel', dir=cmds.internalVar(umm=True))[0] self.ui.list_items.clear() self.ui.list_items.setCurrentRow(-1) self._data = [] self._mel_block = open(self._file_read).readlines() i = 0 while i < len(self._mel_block): if 'menuItem' in self._mel_block[i]: i += 1 item = {"label": "", "command": [-1, ""], "language": [-1, "mel"], "icon": ""} include = True while '-' in self._mel_block[i]: if '-label ' in self._mel_block[i]: item["label"] = re.match('(.*)-label "(.*)"(.*)', self._mel_block[i]).group(2) elif '-command ' in self._mel_block[i]: item["command"] = [i, re.match('(.*)-command "(.*)"(.*)', self._mel_block[i]).group(2)] elif '-sourceType ' in self._mel_block[i]: item["language"] = [i, re.match('(.*)-sourceType "(.*)"(.*)', self._mel_block[i]).group(2)] elif '-image ' in self._mel_block[i]: item["icon"] = re.match('(.*)-image "(.*)"(.*)', self._mel_block[i]).group(2) elif '-subMenu 1' in self._mel_block[i] or '-optionBox 1' in self._mel_block[i]: include = False i += 1 if include: self._data.append(item) self.ui.list_items.addItem(item["label"]) else: i += 1
def select_file(self): """ Maya Open Dialog to select file texture """ self.open_dialog_visible = True if MTTSettings.value('browserFirstStart'): image_dir = cmds.optionVar(query='MTT_browserStartFolder') else: image_dir = cmds.workspace(query=True, rootDirectory=True) + cmds.workspace( fileRuleEntry='sourceImages') MTTSettings.set_value('browserFirstStart', True) file_path = cmds.fileDialog2(fileMode=1, startingDirectory=image_dir, caption='Select a texture', okCaption='Select') if file_path: new_path = file_path[0] cmds.optionVar( sv=['MTT_browserStartFolder', os.path.dirname(new_path)]) if MTTSettings.value('forceRelativePath'): new_path = convert_to_relative_path(new_path) # relative_path = workspace(projectPath=new_path) # if relative_path != new_path: # new_path = '/%s' % relative_path self.line_edit.setText(new_path) self.open_dialog_visible = False self.close() self.editingFinished.emit() cmds.showWindow(WINDOW_NAME)
def sublimeTextPathFinder(): """launch sublime text from maya""" # get the sublime text path from default defaultSublimePath = [ 'C:/Program Files/sublime_text/sublime_text.exe', 'C:/Program Files/Sublime Text 2/sublime_text.exe', 'C:/Program Files (x86)/Sublime Text 2/sublime_text.exe', ] for path in defaultSublimePath: if os.path.exists(path): SETTINGS.add('sublime_text_path', path) sublimeTextPath = SETTINGS.get('sublime_text_path') if sublimeTextPath and os.path.exists(sublimeTextPath): # launch sublime text subprocess.Popen(sublimeTextPath[0]) else: # ask for the sublime text exe path filedialog = cmds.fileDialog2(cap='Please give me the path of Sublime Text.exe !', fm=1, dir='C:\\Program Files\\', ff='*.exe') if filedialog: sublimeTextPath = str(filedialog[0]) if os.path.exists(sublimeTextPath): # setting Setting SETTINGS.add('sublime_text_path', sublimeTextPath) return sublimeTextPath else: raise UserWarning('No exe found !')
def dsPartition(partitions,start,end): filename = cmds.fileDialog2(fileMode=2, ds=1,caption="select Folder") path = filename[0] path = path.replace("\\","//") rootPath = path mel.eval('realflowBINExportDialog 0;') mel.eval('deleteUI window1;') objList = cmds.ls(selection=True) for obj in objList: path = rootPath + obj + "/" objShape = cmds.listRelatives( obj, shapes=True ) sParticle = obj part = 1 while part <= partitions: newPath = path + "/" + "v%03d" %(part) if not os.path.isdir(path):os.mkdir(path) if not os.path.isdir(newPath):os.mkdir(newPath) cmds.setAttr(sParticle + ".seed[:0]", int(random.randint(part,1000))) cmds.setAttr("realflowBINExportOptions.path",newPath,type="string") cmds.setAttr("realflowBINExportOptions.prefix","<name>.",type="string") cmds.setAttr("realflowBINExportOptions.nameFormat",1) cmds.setAttr("realflowBINExportOptions.padding",4) cmds.setAttr("realflowBINExportOptions.particleType",2) cmds.setAttr("realflowBINExportOptions.usePlaybackRange",1) cmds.setAttr("realflowBINExportOptions.nodes[0]",sParticle,type="string") mel.eval('realflowBINExportLastSettings 0;') print part part = part + 1
def create_ms_appleseed_scene(): scene_file = cmds.fileDialog2(fm=1, okc='Import', cap='Select an appleseed scene to import', ff='*.appleseed') if scene_file is not None: scene_name = os.path.splitext(os.path.split(scene_file[0])[1])[0] relative_path = os.path.relpath(scene_file[0], cmds.workspace(q=True, rd=True)) file = open(scene_file[0], 'r') data = file.read() file.close() dom = parseString(data) bounding_box = [-0.5, 0.5, -0.5, 0.5, -0.5, 0.5] for scene in dom.getElementsByTagName('scene'): for param in scene.getElementsByTagName('parameter'): if param.getAttribute('name') == 'bounding_box': bounding_box_text = param.getAttribute('value') bounding_box = bounding_box_text.split(' ') for i in range(len(bounding_box)): bounding_box[i] = float(bounding_box[i]) new_node = cmds.createNode('ms_appleseed_scene', name=legalize_name(scene_name).replace('.', '_')) cmds.setAttr(new_node + '.appleseed_file', relative_path, type='string') cmds.setAttr(new_node + '.x_min', bounding_box[0]) cmds.setAttr(new_node + '.x_max', bounding_box[3]) cmds.setAttr(new_node + '.y_min', bounding_box[1]) cmds.setAttr(new_node + '.y_max', bounding_box[4]) cmds.setAttr(new_node + '.z_min', bounding_box[2]) cmds.setAttr(new_node + '.z_max', bounding_box[5])
def launchConsole(): """launch console2 from maya""" # get the console path from default defaultConsolePath = [ 'C:/Program Files/Console2/Console.exe', 'C:/Program Files (x86)/Console2/Console.exe', ] for path in defaultConsolePath: if os.path.exists(path): SETTINGS.add('terminator', path) consolePath = SETTINGS.get('terminator') if consolePath and os.path.exists(consolePath): # launch console subprocess.Popen(consolePath[0]) else: # ask for the console exe path filedialog = cmds.fileDialog2(cap='Please give me the path of Console.exe !', fm=1, dir='C:\\Program Files\\', ff='*.exe') if filedialog: consolePath = str(filedialog[0]) if os.path.exists(consolePath): # setting Setting SETTINGS.add('terminator', consolePath) # launch console subprocess.Popen(consolePath) else: raise UserWarning('No exe found !')
def ExportData(data): multipleFilters = "JSON Files (*.json)" f = cmds.fileDialog2(fileMode=0, fileFilter=multipleFilters) if f: f = open(f[0], 'w') json.dump(data, f) f.close()
def savefolder(savepathini): newpath=mc.fileDialog2(ds = 1, fm = 3) if newpath: chkpath= newpath[0]+'/' counts=mc.getFileList (folder=chkpath) nc=counts.count('SavePose') if not nc: cofirm_but=mc.confirmDialog( title='Confirm', message='Do u want to create a new library in '+newpath[0]+ ' ??', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) if cofirm_but=='Yes': getMnuItms=mc.menu('chgFld',q=1,ia=1) if len(getMnuItms) >= 7: mc.deleteUI(getMnuItms[3],mi=1) getMnuItms=mc.menu('chgFld',q=1,ia=1) getItmLab=[] for each in getMnuItms: lab=mc.menuItem(each,q=1,l=1) getItmLab.append(lab) if newpath: if newpath[0] not in getItmLab: mc.menuItem(label=newpath[0],p='chgFld',c=partial(changepath,newpath)) savepathini=newpath[0] else: return else: savepathini=newpath[0] else: return Refresh_UI(savepathini) temp_path(savepathini)
def setShaderPath(self, *args): fileFilters = "Maya File(*.mb *.ma)" path = cmds.fileDialog2(fileMode=1, caption="Set Shader Path", dialogStyle=2, okCaption="Save", startingDirectory=self.basedir, fileFilter=fileFilters) if path == None: return cmds.textFieldButtonGrp("tfbShaderPath", e=True, tx=path[0])
def importParticleFile() : basicFilter = "*.out" fileName=cmds.fileDialog2(caption="Please select file to import",fileFilter=basicFilter, fm=1) if fileName[0] !=None : file=open(str(fileName[0])) frame=0 numParticles=0 #set to frame 0 animControl=OMA.MAnimControl() animControl.setCurrentTime(OM.MTime(frame)) for line in file : line=line.split(" ") if line[0]=="NumParticles" : numParticles=int(line[1]) elif line[0]=="Frame" : frame=int(line[1]) animControl.setCurrentTime(OM.MTime(frame)) else : name=line[0] x=float(line[1]) y=float(line[2]) z=float(line[3]) if frame==0 : #we need to create our initial locators createLocator(name,x,y,z) else : moveLocator(name,x,y,z)
def loadClusters(): filePath = cmds.fileDialog2(dialogStyle=4, okc='Open', cap='Open') clusterDict = DeformerLib.WeightListTool.readWeights(filePath[0]) DeformerLib.loadClusters(clusterDict)
def saveClusters(): clusters = cmds.ls(sl=True) filePath = cmds.fileDialog2(dialogStyle=0) DeformerLib.WeightListTool.saveWeights(clusters, '%s.txt' % filePath[0])
def saveEyePlacement(): filePath = cmds.fileDialog2(dialogStyle=0) SaveEyesA.save(filePath[0])
def BrowseWin(self): tmp = cmds.fileDialog2(dialogStyle=2, fileMode=3, caption=u'输出路径', okCaption=u'选择路径', cancelCaption=u'取消') if tmp: cmds.textField(self.textWin, edit=True, tx=tmp[0])
def browse2(self): browse2filepath = cmds.fileDialog2(fm=3, cap='Shader Path Browser', okc='Set as Path') cmds.textField("shaderPath", e=1, text=str(browse2filepath[0]))
def BrowserFolder(self, sender): root_folder = cmds.fileDialog2(caption=" Select scan folder ", fm=3)[0] cmds.textField(self.ui.ftf, tx=root_folder, edit=True)
'position': [translation[0], translation[1], translation[2]], 'orientation': [orientation[0], orientation[1], orientation[2], orientation[3]], 'scale': [scale1[0], scale1[1], scale1[2]], 'nextLevel': notelist[2] }) elif gameObjectType != "": jsonData['GameObjects'].append({ 'type': gameObjectType, 'model': gameObjectName, 'position': [translation[0], translation[1], translation[2]], 'orientation': [orientation[0], orientation[1], orientation[2], orientation[3]], 'scale': [scale1[0], scale1[1], scale1[2]] }) basicFilter = "*.json" unicodePath = cmds.fileDialog2(caption="Select save location", fileFilter=basicFilter, dialogStyle=2, fileMode=0, returnFilter=1) if unicodePath != None and unicodePath != "": cleanPath = str(unicodePath[0]) with open(unicodePath[0], 'w') as outfile: json.dump(jsonData, outfile, sort_keys=False, indent=2)
def getLoc(field, *args): """ get location, put it in the tfbg """ path = cFuncs.fixPath(cmds.fileDialog2(fileMode=2, ds=1)[0]) cmds.textFieldButtonGrp(widgets[field], e=True, tx=path)
def browse4(self): browse4filepath = cmds.fileDialog2(fm=1, cap='Rust Probability Map Browser', okc='Set as Map') cmds.textField("probMapName", e=1, text=str(browse4filepath[0]))
def openFileDialog(self, filter, fileMode, textField): filePath = cmds.fileDialog2(fileFilter=filter, fileMode = fileMode, dialogStyle=2) if filePath is not None: cmds.textField(self.widgets[textField], edit = True, fi = filePath[0])
def onBtnLoadPressed(self, state): path = cmds.fileDialog2(fileMode=1, caption="Load Shapes") if not path: return path = next(iter(path), None) load_all_ctrls_shapes(path)
def OnOpen(): singleFilter = "All Files (*.*)" file_path = str( cmds.fileDialog2(dialogStyle=2, fileMode=1, okCaption='select')[0]) preview_path.setFileName(file_path)
def execute(): title = "MMDBridge merge tool - Select .abc directory" directory = cmds.fileDialog2(fileFilter=".abc directory", dialogStyle=2, caption=title, fileMode=3) abc = os.path.normpath(directory[0]) print(abc) if not os.path.isdir(abc): return files = os.listdir(abc) if len(files) <= 0: return mtl = "" # find first mtl for file in files: root, ext = os.path.splitext(file) if ext == ".mtl": mtl = os.path.join(abc, file) break if mtl == "": return mtlDict = {} relationDict = {} import_mtl(mtl, mtlDict, relationDict) for name in cmds.ls(): print(name) if 'xform_' in name and 'material_' in name: temp = name[name.find('xform_') + 6:len(name)] objectNumber = int(temp[0:temp.find('_material_')]) materialNumber = temp[temp.find('_material_') + 10:len(temp)] #applyFaceNumber = 0 materialName = 'material_' + str(objectNumber) + '_' + str( materialNumber) if materialName in mtlDict.keys(): # new material mtlData = mtlDict[materialName] material = cmds.shadingNode('blinn', asShader=1, name=materialName) sg = cmds.sets(renderable=1, noSurfaceShader=1, empty=1, name=materialName + 'SG') cmds.connectAttr((material + '.outColor'), (sg + '.surfaceShader'), f=1) # select object cmds.select(name) # select face #cmds.select(name + '.f[' + str(applyFaceNumber) + ':' + str(applyFaceNumber + mtlData.faceSize) + ']', r=True) #applyFaceNumber = applyFaceNumber + mtlData.faceSize # assign material to object cmds.hyperShade(a=materialName, assign=1) # assign texture if len(mtlData.textureMap) > 0: texturePath = os.path.join(abc, mtlData.textureMap) file_node = cmds.shadingNode("file", asTexture=True, n=name + "_tex") cmds.setAttr((file_node + '.fileTextureName'), texturePath, type="string") cmds.connectAttr((file_node + '.outColor'), (material + '.color')) else: if mtlData.isAccessory: cmds.setAttr(material+'.color', \ mtlData.diffuse[0] + 0.5 * mtlData.ambient[0],\ mtlData.diffuse[1] + 0.5 * mtlData.ambient[1],\ mtlData.diffuse[2] + 0.5 * mtlData.ambient[2]) else: cmds.setAttr(material+'.color', \ mtlData.diffuse[0],\ mtlData.diffuse[1],\ mtlData.diffuse[2]) if len(mtlData.alphaMap) > 0: texturePath = os.path.join(abc, mtlData.alphaMap) file_node = cmds.shadingNode("file", asTexture=True, n=name + "_atex") cmds.setAttr((file_node + '.fileTextureName'), texturePath, type="string") cmds.connectAttr((file_node + '.outAlpha'), (material + '.translucence')) """ cmds.setAttr(material+'.transparency', \ mtlData.trans,\ mtlData.trans,\ mtlData.trans) """ cmds.setAttr(material+'.specularColor', \ mtlData.specular[0],\ mtlData.specular[1],\ mtlData.specular[2]) cmds.setAttr(material+'.ambientColor', \ mtlData.ambient[0],\ mtlData.ambient[1],\ mtlData.ambient[2]) # deselect all cmds.select(all=True, deselect=True)
def browseForFile(): filename = cmds.fileDialog2(fileMode=1, caption="Import Image") print filename cmds.textField('jsonPathText',e=True,tx=filename[0]) updateGrpCheckboxes()
def doBake(maya=True, fbx=True): ##_ex_Atts = ["renderable"] _attrs = [ "horizontalFilmAperture", "verticalFilmAperture", "focalLength", "lensSqueezeRatio", "fStop", "focusDistance", "shutterAngle", "centerOfInterest", "nearClipPlane", "farClipPlane", "filmFit", "filmFitOffset", "horizontalFilmOffset", "verticalFilmOffset", "shakeEnabled", "horizontalShake", "verticalShake", "shakeOverscanEnabled", "shakeOverscan", "preScale", "filmTranslateH", "filmTranslateV", "horizontalRollPivot", "verticalRollPivot", "filmRollValue", "filmRollOrder", "postScale", "depthOfField", "focusRegionScale" ] if not (maya or fbx): return if not cmds.ls(sl=1): return src = cmds.ls(sl=1)[0] src_sh = cmds.listRelatives(src, s=True, f=True)[0] if not (cmds.objectType(src_sh) == "camera"): return trg = cmds.camera()[0] trg = cmds.rename(trg, src.split("|")[-1] + "_Bake") trg_sh = cmds.listRelatives(trg, s=True, f=True)[0] ##for at in cmds.listAttr(src_sh): for at in _attrs: ##if at in _ex_Atts: continue try: ##cmds.setAttr("%s.%s" % (src_sh, at), k=1) cmds.setAttr("%s.%s" % (trg_sh, at), k=1) cmds.setAttr("%s.%s" % (trg_sh, at), cmds.getAttr("%s.%s" % (src_sh, at))) cmds.connectAttr("%s.%s" % (src_sh, at), "%s.%s" % (trg_sh, at), f=1) except: pass cmds.pointConstraint(src, trg, offset=[0, 0, 0], weight=1) cmds.orientConstraint(src, trg, offset=[0, 0, 0], weight=1) cmds.setAttr(trg + ".rotateAxisX", cmds.getAttr(src + ".rotateAxisX")) cmds.setAttr(trg + ".rotateAxisY", cmds.getAttr(src + ".rotateAxisY")) cmds.setAttr(trg + ".rotateAxisZ", cmds.getAttr(src + ".rotateAxisZ")) _min, _max = cmds.playbackOptions(q=1, min=1), cmds.playbackOptions(q=1, max=1) cmds.refresh(suspend=True) try: cmds.bakeResults(trg, sm=True, t=(_min, _max), sb=1, dic=True, pok=True, sac=False, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, cp=False, s=True) finally: cmds.refresh(suspend=False) cmds.refresh() cmds.delete(trg, constraints=1) try: a = cmds.listConnections(src_sh, s=0, d=1, c=1, p=1, scn=1, sh=1)[::2] b = cmds.listConnections(src_sh, s=0, d=1, c=1, p=1, scn=1, sh=1)[1::2] for i in range(len(a)): cmds.disconnectAttr(a[i], b[i]) except: pass fpsDict = { 'game': "15p", 'film': "24p", 'pal': "25p", 'ntsc': "30p", 'show': "48p", 'palf': "50p", 'ntscf': "60p" } rnt = time.strftime('%Y-%m-%d %H:%M') + " " + socket.gethostname( ) + " " + "%d-%d" % (int(_min), int(_max)) + " " + fpsDict[ cmds.currentUnit(q=1, t=1)] + "\n" curPath = cmds.file(q=1, sn=1) fn = os.path.basename(os.path.splitext(curPath)[0]) out = curPath.split("/ani/")[0] + "/reference/camera/anicam/" outFN = out + trg if not os.path.exists(out): os.makedirs(out) rntN = cmds.fileDialog2(fm=0, dir=outFN) if not rntN: return rntFN = os.path.splitext(rntN[0])[0] if maya: cmds.file(rntFN, force=1, options="v=0;", typ="mayaBinary", pr=1, es=1) rnt += rntFN + ".mb\n" if fbx: cmds.file(rntFN, force=1, options="v=0;", typ="FBX export", pr=1, es=1) rnt += rntFN + ".fbx\n" #print rnt ##setClipboardData(rnt) def showExportCamera(): if cmds.window("exportCamera", ex=1): cmds.deleteUI("exportCamera") cmds.window("exportCamera") cmds.columnLayout(adjustableColumn=True) cmds.rowColumnLayout(numberOfColumns=2, columnWidth=[(1, 100), (2, 100)]) mayaCB = cmds.checkBox(l="Maya", v=True) fbxCB = cmds.checkBox(l="FBX", v=True) cmds.setParent("..") #cmds.button(l="Tear off", c=lambda x:tearOffPanel()) cmds.button(l="Export", c=lambda x: doBake(cmds.checkBox(mayaCB, q=1, v=1), cmds.checkBox(fbxCB, q=1, v=1))) cmds.showWindow() showExportCamera()
def onBtnSavePressed(self, state): path = cmds.fileDialog2(fileMode=0, caption="Safe Shapes") if not path: return path = next(iter(path), None) save_all_ctrls_shapes(path)
def browse3(self): browse3filepath = cmds.fileDialog2(fm=3, cap='Output Path Browser', okc='Set as Path') cmds.textField("outPath", e=1, text=str(browse3filepath[0]))
def localOpen(): curScenePath = cmds.file(q = True, sceneName = True) curWorkDir = os.path.dirname(curScenePath) filePath = cmds.fileDialog2(fileMode = 1, caption = 'Open with Reference Update', startingDirectory = curWorkDir)[0] updateRef(filePath)
def selectIndivFiles(textField, *args): FilePath = cmds.fileDialog2(fileFilter = multipleFilters, selectFileFilter = '.png (*.png)', fileMode = 1, ds = 2, okc = 'Okay', cc = "Never!" )[0] cmds.textField( textField, edit = True, text = FilePath )
def selectMainProjectPath(self): fileResult = cmds.fileDialog2(fm=3) if fileResult != None: print(fileResult[0]) self.MainProjectPathLine.setText(fileResult[0]) mainWin.update()
def browse(self): browsefilepath = cmds.fileDialog2(fm=1, cap='Rust Distribution Map Browser', okc='Set as Map') cmds.textField("mapName", e=1, text=str(browsefilepath[0]))
def selectByDirectory(textField, *args): oldCheck = queryEditFields()[0] if len(oldCheck) > 0 : for field in txtFieldList: cmds.textField(field, e = True, tx = '' ) udimCheck = cmds.checkBox("udimCB", q = True, v = True) inputDirectory = cmds.fileDialog2(fileMode = 2, ds = 2, okc = 'Okay', cc = "Never!" )[0] shaderFiles = os.listdir(inputDirectory) shaderFiles = [ file for file in shaderFiles if file.endswith( ('.bmp', '.ico', '.jpeg', '.jpg', '.jng', '.pbm', '.pgm', '.ppm', '.png','.targa', '.tiff', '.wbmp', '.xpm', '.gif', '.hdr', '.exr', '.j2k', '.jpeg-2000', '.pfm', '.psd'))] bcList = ['BaseColor', 'basecolor', 'diff', 'bc', 'Diffuse'] metalList = ['Metalness', 'metal', 'reflect', 'Reflectiv', 'Metal'] roughList = ['Roughness', 'roughness', 'rough'] normList = ['Normal', 'normal', 'Nor', 'nor'] heightList = ['Height', 'height', 'disp', 'displacement'] ambientList = ['AO', 'ambient', 'Ambient'] emissList = ['Emissive', 'emiss'] opacList = ['Opacity', 'opac', 'transpar', 'Trans'] if udimCheck == True: shaderFiles = [ file for file in shaderFiles if '1001' in file] print shaderFiles for name in shaderFiles: if any(x in name for x in bcList): cmds.textField('BaseColor', edit = True, tx = name) elif any(x in name for x in metalList): cmds.textField('Metalness', edit = True, tx = name) elif any(x in name for x in roughList): cmds.textField('Roughness', edit = True, tx = name) elif any(x in name for x in normList): cmds.textField('Normal', edit = True, tx = name) elif any(x in name for x in heightList): cmds.textField('Height', edit = True, tx = name) elif any(x in name for x in ambientList): cmds.textField('AO', edit = True, tx = name) elif any(x in name for x in emissList): cmds.textField('Emissive', edit = True, tx = name) elif any(x in name for x in opacList): cmds.textField('Opacity', edit = True, tx = name) cmds.textField(textField, edit = True, text = inputDirectory ) inputName = inputDirectory.split("/")[-1] texName = cmds.textField("texName", q = True, text = True) if texName == "": cmds.textField("texName", edit = True, text = inputName) elif texName != inputName: cmds.textField("texName", edit = True, text = inputName)