def bulge_button( self, *args ): if( cmds.objExists( "ZBend" ) ): cmds.confirmDialog( title="Error", message="First delete the bulge history on the previously\ndeformed object before bulging another.", button="Okie Dokie" ) return 0 latestSelection = cmds.ls( selection=True ) if( len( latestSelection ) == 0 ): return 0 if( len( latestSelection ) == 1 ): self.relatives = cmds.listRelatives( children=True ) if( len(self.relatives) == 1 ): self.bbox = cmds.exactWorldBoundingBox( latestSelection ) cmds.nonLinear( type='bend', curvature=cmds.intSliderGrp( "x_bulge_slider", value=True, query=True ) ) cmds.rename( "XBend" ) cmds.move((self.bbox[0] + self.bbox[3])/2, self.bbox[1], (self.bbox[2] + self.bbox[5])/2, "XBend", rpr=True ) cmds.setAttr( "XBend.rotateZ", -90 ) cmds.select( latestSelection ) cmds.nonLinear( type='bend', curvature=cmds.intSliderGrp( "z_bulge_slider", value=True, query=True ) ) cmds.rename( "ZBend" ) cmds.move((self.bbox[0] + self.bbox[3])/2, self.bbox[1], (self.bbox[2] + self.bbox[5])/2, "ZBend", rpr=True ) cmds.setAttr( "ZBend.rotateZ", -90 ) cmds.setAttr( "ZBend.rotateX", 90 ) cmds.connectControl( "x_bulge_slider", "bend1.curvature" ) cmds.connectControl( "z_bulge_slider", "bend2.curvature" ) cmds.select( latestSelection )
def saveSettings(self, *args): #this function will save out the user's preferences they have set in the UI to disk settingsLocation = self.mayaToolsDir + "/General/Scripts/projectSettings.txt" try: f = open(settingsLocation, 'w') #create a dictionary with values settings = {} settings["UseSourceControl"] = cmds.checkBox(self.widgets["useSourceControl"], q = True, v = True) settings["FavoriteProject"] = cmds.optionMenu(self.widgets["favoriteProject_OM"], q = True, v = True) #write our dictionary to file cPickle.dump(settings, f) f.close() except: cmds.confirmDialog(title = "Error", icon = "critical", message = settingsLocation + " is not writeable. Please make sure this file is not set to read only.") #close the UI cmds.deleteUI("AnimationRiggingTool_SettingsUI")
def __init__(self, uioptions, transformoptions, sourcelist, targetlist): ''' initial setup ''' #create the tool context if (mc.draggerContext(spPaint3dContextID, exists=True)): mc.deleteUI(spPaint3dContextID); mc.draggerContext(spPaint3dContextID, pressCommand=self.onPress, dragCommand=self.onDrag, releaseCommand=self.onRelease, name=spPaint3dContextID, cursor='crossHair', undoMode='step') #create context local options self.runtimeUpdate(uioptions, transformoptions, sourcelist, targetlist) #debug purpose self.reentrance = 0 #initialise world up vector if ( (mc.upAxis(q=True, axis=True)) == "y" ): self.worldUp = om.MVector (0,1,0); elif ( (mc.upAxis(q=True, axis=True)) == "z" ): self.worldUp = om.MVector (0,0,1); else: #can't figure out up vector mc.confirmDialog(title='Weird stuff happening', message='Not getting any proper info on what the current up vector is. Quitting...') sys.exit() #fetch current scene unit self.unit = mc.currentUnit(query=True, linear=True)
def dynamicChainCmd(*args): ''' Get information and create dynamic joint chain network ''' from time import gmtime, strftime verified = True log = "" # get the selected joints joints = cmds.ls(sl=True) if len(joints) != 2: log += "- Need to select the start joint and the end joint\n" verified = False if verified: # create class instance dynChain = lpDynamicChain(joints[0], joints[1]) # create the dynamic network nodes = dynChain.create() if nodes: dateTime = strftime("%a, %b %d %Y - %X", gmtime()) nodesString = "" # build string for feedback for i,node in enumerate(nodes): nodesString += "%d. %s\n" % (i,node) cmds.confirmDialog(messageAlign="left", title="lpDynamicChains", message="%s\n------------------\n\nNew dynamic nodes:\n\n%s\n\nThank you!" % (dateTime, nodesString), button=["Accept"], defaultButton="Accept") # select the custom node last cmds.select(dynChain.mNode) else: cmds.confirmDialog(messageAlign="left", title="lpDynamicChains", message="Log:\n" + log, button=["Accept"], defaultButton="Accept")
def checkout(self): curfilepath = cmd.file(query=True, sceneName=True) if not curfilepath == '': cmd.file(save=True, force=True) toCheckout = self.get_asset_path() try: destpath = amu.checkout(toCheckout, True) except Exception as e: print str(e) if not amu.checkedOutByMe(toCheckout): cmd.confirmDialog( title = 'Can Not Checkout' , message = str(e) , button = ['Ok'] , defaultButton = 'Ok' , cancelButton = 'Ok' , dismissString = 'Ok') return else: destpath = amu.getCheckoutDest(toCheckout) toOpen = os.path.join(destpath, self.get_filename(toCheckout)+'.mb') # open the file if os.path.exists(toOpen): cmd.file(toOpen, force=True, open=True)#, loadReferenceDepth="none") else: # create new file cmd.file(force=True, new=True) cmd.file(rename=toOpen) cmd.file(save=True, force=True) self.close_dialog()
def importPose(filePath): """Import the pose data stored in filePath""" # try to open the file newRootControl = cmds.ls(sl=True, type='transform')[0] newNodeAttr = newRootControl.rpartition('_root_')[0] try: f = open(filePath, 'r') except: cmds.confirmDialog( t='Error', b=['OK'], m='Unable to open file: %s'%filePath ) raise # uncPickle the data pose = cPickle.load(f) # close the file f.close() # set the attributes to the stored pose errAttrs = [] for attrValue in pose: try: cmds.setAttr('%s%s'%(newNodeAttr, attrValue[0]), attrValue[1]) except: try: errAttrs.append(attrValue[0]) except: errAttrs.append(attrValue) # display error message if needed if len(errAttrs) > 0: importErrorWindow(errAttrs) sys.stderr.write('Not all attributes could be loaded.')
def run(parent): """requires amTinyTools""" try: import amTinyTools amTinyTools.Menu.menuSelect(parent) except ImportError: cmds.confirmDialog(m="this module requires amTinyTools")
def checkSelObj(self): """检查选中的物体是否为mesh节点 Description: 选有物体且所选的是mesh节点,返回True 没选物体或所选物体类型不符合,则返回False Arguments: 无 Returns: result = True:通过检查 result = False:没通过检查,释放所有选择 """ selObj = cmds.ls(sl =True) lenOfSel = len(selObj) result = True if lenOfSel < 1: cmds.confirmDialog(title = "Warning", message = "Please Select Objects!", button = "OK", defaultButton = "OK") result = False else: for eachObj in selObj: if cmds.nodeType(eachObj) != "transform": cmds.confirmDialog(title = "Warning", message = "There Has An Object With Incorrect Type!", button = "OK", defaultButton = "OK") cmds.select(deselect = True) #去除所有选择 result = False break return result
def getSelection(self): rootNodes = cmds.ls(sl=True, type='transform') if rootNodes is None or len(rootNodes) < 1: cmds.confirmDialog(t='Error', b=['OK'], m='Please select one or more transform nodes.') return None else: return rootNodes
def setupScene(): ''' Setup some scene attributes we want to be common to all Spinifex car scenes TODO: make width over height as float ''' # Check if we haven't done this before if cmds.objExists('vraySettings.setupSceneHasBeenRun'): # Check that everything is setup correctly before continuing. dialogMessage = 'setupScene has already been run. Do you wish to continue? Some of your render settings will be reset.' result = cmds.confirmDialog( title='spckSetupScene', message=dialogMessage, button=['YES','NO'], defaultButton='NO', cancelButton='NO', dismissString='NO' ) if result == 'NO' : print("Aborted. We\'ve done this before...\n") return else: # Check that everything is setup correctly before continuing. dialogMessage = 'Have you set up your workspace.mel?' result = cmds.confirmDialog( title='spckSetupScene', message=dialogMessage, button=['YES','NO'], defaultButton='YES', cancelButton='NO', dismissString='NO' ) if result == 'NO' : print('Go setup your workspace and run again.\n') return # Units for working in metric and 30fps cmds.currentUnit (linear='cm') cmds.currentUnit (angle='deg') cmds.currentUnit (time='ntsc') # Load VRAY if not active cmds.loadPlugin ('vrayformaya', quiet=True) cmds.pluginInfo ('vrayformaya', edit=True, autoload=True) cmds.setAttr ('defaultRenderGlobals.ren', 'vray', type='string') cmds.evalDeferred ( 'createBaseRenderSettings()' , lowestPriority=True ) print('Success.\n')
def saveFileToPublish(self): self.currentFilePath = cmds.file(q=1, sn=1) if self.currentFilePath: if '/work/' in self.currentFilePath: self.baseName = os.path.basename(self.currentFilePath) self.publishPath = self.currentFilePath.split(self.baseName)[0].replace('/work/', '/publish/') self.publishFilePath = os.path.join(self.publishPath, self.baseName) if os.listdir(self.publishPath): fileName = sorted(os.listdir(self.publishPath))[-1].replace('.ma', '.mb') newPublishFilePath = os.path.join(self.publishPath, fileName) curVersion = os.path.splitext(fileName)[0].split('.v')[-1] newVersion = int(curVersion) + 1 newVersionStr = '.v%03d' % newVersion self.publishFilePath = newPublishFilePath.replace('.v%03d' % int(curVersion), newVersionStr) cmds.file(f=1, save=1) cmds.file(rename=self.publishFilePath) cmds.file(f=1, save=1, type = 'mayaBinary') cmds.file(self.currentFilePath, f=1, open=1) return self.publishFilePath else: fileName = self.baseName.replace('.ma', '.mb') newPublishFilePath = os.path.join(self.publishPath, fileName) self.publishFilePath = newPublishFilePath cmds.file(f=1, save=1) cmds.file(rename=self.publishFilePath) cmds.file(f=1, save=1, type = 'mayaBinary') cmds.file(self.currentFilePath, f=1, open=1) return self.publishFilePath else: cmds.confirmDialog(m="File is not in work directory.. Kindly save your file in work directory and run this script", b="Ok") else: cmds.warning('Cannot find proper file. Please save our file and proceed....')
def initUI(self): # self.setMinimumSize(200, 100) self.ui = ui.loadUiWidgetFromPyFile(__file__, parent=self) # layout self.setLayout(QtGui.QVBoxLayout()) self.layout().addWidget(self.ui) self.layout().setSpacing(0) self.layout().setContentsMargins(2, 2, 2, 2) # fill UI info isValid = self.isValidContext() if isValid: self.ui.cb_imagePlanes.addItems(shader.getAllSceneImagePlanes()) else: self.ui.setEnabled(False) cmds.confirmDialog(t="Alert", message="There are no ImagePlanes in the scene, there must be one at least.", button=["OK"], icon="warning") # add signals to the ui elements self.ui.pb_bakeImagePlane.clicked.connect(self.bakeImagePlane) self.ui.pb_useBackgroundShader.clicked.connect(self.applyUseBackgroundShader) self.ui.pb_lambertProjection.clicked.connect(self.applyLambertShader) self.ui.pb_surfaceShader.clicked.connect(self.applySurfaceShader) self.ui.pb_applyGreenScreenShader.clicked.connect(self.applyGreenScreenShader) self.ui.pb_applyGreenScreenShaderFx.clicked.connect(self.applyGreenScreenShaderFx) self.ui.pb_applyDefaultShader.clicked.connect(self.applyDefaultShader)
def exportRig(self): """ will export SH and Geo found in the geo folder """ # rig and geo should not be referenced # find SH, delete constraints, parent to world # find geo folder parent to world # select SH and geo folder and export as fbx to fbx folder pymelLogger.debug( 'Starting rig export' ) export = 0 for rig in self.rootList: if cmds.objExists(rig): # check if geo folder also exists if cmds.objExists(self.geo): self._delConstraints(rig) cmds.parent(rig, w=1) cmds.parent(self.geo, w=1) cmds.select(rig,self.geo, r=1) #print rig, self.geo if self._fbxExport( 2 ): cmds.confirmDialog(m='FBX Rig Exported', button='Ok') pymelLogger.debug( 'Finished rig export' ) export = 1 break else: pymelLogger.error( 'No geo folder has been found' ) if export == 0 : pymelLogger.error( 'No Rig Exported. Note: Referenced Rigs Will Not Export' )
def __init__(self) : # get the currently selected objects and make sure we have only one object selected = OM.MSelectionList() OM.MGlobal.getActiveSelectionList(selected) self.selectedObjects = [] selected.getSelectionStrings(self.selectedObjects) if len(self.selectedObjects) == 0 : cmds.confirmDialog( title='No objects Selected', message='Select a Mesh Object', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' ) elif len(self.selectedObjects) > 1 : cmds.confirmDialog( title='Select One Object', message='Only One Mesh mat be exported at a time', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' ) # now we have the correct criteria we can proceed with the export else : # get the start and end values for our UI sliders anim=OMA.MAnimControl() minTime=anim.minTime() maxTime=anim.maxTime() self.m_start=int(minTime.value()) self.m_end=int(maxTime.value()) # now we create a window ready to populate the components self.m_window = cmds.window( title='NCCA Pointbake Export' ) # create a layout cmds.columnLayout() # create two sliders for start and end we also attach methods to be called when the slider # changes self.m_startSlider=cmds.intSliderGrp( changeCommand=self.startChanged,field=True, label='Start Frame', minValue=self.m_start, maxValue=self.m_end, fieldMinValue=self.m_start, fieldMaxValue=self.m_end, value=self.m_start ) self.m_endSlider=cmds.intSliderGrp( changeCommand=self.endChanged ,field=True, label='End Frame', minValue=self.m_start, maxValue=self.m_end, fieldMinValue=self.m_end, fieldMaxValue=self.m_end, value=self.m_end ) # create a button and add the method called when pressed cmds.button( label='Export', command=self.export ) # finally show the window cmds.showWindow( self.m_window )
def mkIngestionDir(source,type): mkFile = source filename =source.split("/") filename = filename[-1] mkSource =source.split("/") mkSource = mkSource[-1] mkSource = mkSource.replace( type, "" ) mkFolder =source.split("/") mkFolder.pop(-1) mkFolder = "/".join(mkFolder) mkFolder=mkFolder+"/"+mkSource if os.path.exists( mkFolder ) == False: os.makedirs( mkFolder ) copycmd = 'sysFile -copy'+' '+'"'+mkFolder+'/'+ filename +'"'+' ' + '"'+ mkFile+'"'+';' mel.eval (copycmd) dst = "Q:/Tools/Nearline/ingestion/3dModels" delcmd = 'sysFile -delete'+' "'+mkFile+'";' mel.eval (delcmd) createdirCmd = 'sysFile -makeDir'+' '+'"'+dst+'/' +mkSource+'/"' mel.eval(createdirCmd) cpyDepotCmd = 'sysFile -mov'+' '+'"'+dst+'/' +mkSource+'/'+filename +'"'+' ' + '"'+mkFolder+'/'+ filename +'"'+';' mel.eval (cpyDepotCmd) print "copied "+filename+" to depot" removeEmptydir = 'sysFile -removeEmptyDir'+' '+'"'+mkFolder+'/";' mel.eval (removeEmptydir) cmds.confirmDialog(m=filename+" ready for upload", cb = "cancel") return mkFolder
def help_pushButton_released(self): directory = os.path.dirname(__file__) readme = os.path.join(directory, 'README.md') f = open(readme, 'r') msg = f.read() f.close() cmds.confirmDialog(title='Help', message=msg, button=['OK'])
def drawError(self,errormsg=""): """ Draw a error message dialog @type errormsg: string @param errormsg: the messag to display """ cmds.confirmDialog(title='ERROR:', message=errormsg, button=['OK'], defaultButton='OK')
def SetLayerForPSD(id, *args): #extra check if the @psdNode exists or not. this is check is - when you open the scene and tool, and close the scene if cmds.objExists(psdNode): cmds.setAttr("%s.layerSetName" % psdNode, layerNames[id], type="string") log.info("layer selected is " + layerNames[id]) else: cmds.confirmDialog( title='psd Connection Error', message='psd node is not connected to nyTR node. Connect the node \n [Or psd node is not Available]', button=['OK'], defaultButton='OK', icn="critical" )
def add_pushButton_released(self): msg = 'Do you want to add an empty row,' msg += ' or open a file to fill in the row?' addRow = cmds.confirmDialog(title='Cameras', message=msg, button=['Empty', 'Open File']) if addRow == 'Open File': filePath = QtGui.QFileDialog.getOpenFileName(self, 'Open Maya File', '../..', 'Maya File (*.ma)') filePath = filePath[0] if filePath: utils.SavePrompt() cmds.file(filePath, open=True, force=True) cameras = [] for cam in pm.ls(type='camera'): if not cam.orthographic.get(): cameras.append(str(cam.getParent())) cameras.append('Close') msg = 'Select camera to add.' camera = cmds.confirmDialog(title='Cameras', message=msg, button=cameras) self.addRow(filePath, camera) else: self.addRow('', '')
def msgWin(title = 'test', msg = 'This is a test message??', silent = False): if silent== "disabled": pass elif silent == True: print msg else: mc.confirmDialog(title = title, message = msg, button = ['OK'], defaultButton = 'OK', cancelButton = 'OK', dismissString = 'OK')
def discard(filePath=cmds.file(q=True, sceneName=True)): if not filePath: return print filePath dlgResult = showWarningDialog() if dlgResult == "Yes": # get discard directory before opening new file toDiscard = os.path.join(amu.getUserCheckoutDir(), os.path.basename(os.path.dirname(filePath))) if amu.isCheckedOutCopyFolder(toDiscard): cmds.file(force=True, new=True) # open new file amu.discard(toDiscard) # discard changes else: cmds.confirmDialog( title="Invalid Command", message="This is not a checked out file. There is nothing to discard.", button=["Ok"], defaultButton="Ok", cancelButton="Ok", dismissString="Ok", ) elif dlgResult == "Brent": brent.go() else: cmds.confirmDialog( title="Discard Cancelled", message="Thank you for being responsible.", button=["Ok"], defaultButton="Ok", cancelButton="Ok", dismissString="Ok", )
def CreateHydraulicRig(upDir, *args): selection = cmds.ls(sl=True) if len(selection) != 3: cmds.confirmDialog(icon = "warning!!", title = "Hydraulic Rig Tool", message = "You must select exactly 3 objects. Top of hydraulic, bottom of hydraulic, and the up vector.") return else: hyd_start_01_anim = selection[0] hyd_start_02_anim = selection[1] upObject = selection[2] hyd_start_01 = hyd_start_01_anim.rpartition("_")[0] hyd_start_02 = hyd_start_02_anim.rpartition("_")[0] # Create a rig for the lower arm extra hydraulic piston. cmds.delete("driver_"+hyd_start_01+"_parentConstraint1") robo_lowarm_pistonrod_01_anim_sub = cmds.group(em=True, name=hyd_start_01_anim+"_sub", parent=hyd_start_01_anim) const = cmds.parentConstraint(hyd_start_01_anim, robo_lowarm_pistonrod_01_anim_sub, weight=1, mo=False) cmds.delete(const) const = cmds.parentConstraint(robo_lowarm_pistonrod_01_anim_sub, "driver_"+hyd_start_01, weight=1, mo=True) cmds.delete("driver_"+hyd_start_02+"_parentConstraint1") robo_lowarm_pistonrod_02_anim_sub = cmds.group(em=True, name=hyd_start_02_anim+"_sub", parent=hyd_start_02_anim) const = cmds.parentConstraint(hyd_start_02_anim, robo_lowarm_pistonrod_02_anim_sub, weight=1, mo=False) cmds.delete(const) const = cmds.parentConstraint(robo_lowarm_pistonrod_02_anim_sub, "driver_"+hyd_start_02, weight=1, mo=True) # Hook up the hydraulics for the lowerarm piston. const1 = cmds.aimConstraint(robo_lowarm_pistonrod_01_anim_sub, robo_lowarm_pistonrod_02_anim_sub, weight=1, mo=True, aimVector=(-1, 0, 0), upVector=(0, 0, upDir), worldUpType="object", worldUpVector=(0, 0, -1), worldUpObject=upObject) const2 = cmds.aimConstraint(robo_lowarm_pistonrod_02_anim_sub, robo_lowarm_pistonrod_01_anim_sub, weight=1, mo=True, aimVector=(1, 0, 0), upVector=(0, 0, upDir), worldUpType="object", worldUpVector=(0, 0, -1), worldUpObject=upObject) cmds.select(const1, const2)
def cacheFluidsToCTemp(): if cmds.objExists(CONST.FOAM_FLUID_SHAPENODE) and cmds.objExists(CONST.WAKE_FLUID_SHAPENODE): ## Get default non-cached wake and foam fluidsToCache = [] for cache in [CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE]: fluidConnection = cmds.listConnections(cache, type = 'cacheFile') or cmds.listConnections(cache, type = 'cacheBlend') if fluidConnection: if cmds.nodeType(fluidConnection[0]) == 'cacheFile' or cmds.nodeType(fluidConnection[0]) == 'cacheBlend': cmds.confirmDialog(title = 'CACHE FLUIDS', message = 'Cache already exist for "%s". You should cleanup your caches if you want to re-cache a newer one!' % cache, button = 'OK') else: fluidsToCache.append(cache) else: fluidsToCache.append(cache) ## Cache em fluids at one go to save time if fluidsToCache: cachePath = _getPathFromSceneName() if cachePath: if os.path.exists(cachePath): _cacheWake(cachepath = cachePath, fluids = fluidsToCache) ## Set time to min [cmds.currentTime( cmds.playbackOptions(q = True, min = True) ) for x in range(2)] else: cmds.confirmDialog(title = 'CACHE FLUIDS', message = 'Both "%s" and "%s" fluids don\'t exist in your scene!' % (CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE), button = 'OK')
def runTestCases( testCases=TEST_CASES ): thisPath = Path( __file__ ).up() testResults = TestResult() for ATestCase in testCases: testCase = ATestCase() testCase.run( testResults ) #force a new scene cmd.file( new=True, f=True ) OK = 'Ok' BUTTONS = (OK,) if testResults.errors: print '------------- THE FOLLOWING ERRORS OCCURRED -------------' for error in testResults.errors: print error[0] print error[1] print '--------------------------' cmd.confirmDialog( t='TEST ERRORS OCCURRED!', m='Errors occurred running the tests - see the script editor for details!', b=BUTTONS, db=OK ) else: print '------------- %d TESTS WERE RUN SUCCESSFULLY -------------' % len( testCases ) cmd.confirmDialog( t='SUCCESS!', m='All tests were successful!', b=BUTTONS, db=OK ) return testResults
def creatStereo(): camL = mc.ls(sl=1) if camL == []: mc.confirmDialog(title="Missing", message="Please select a camera!", button=["Ok"]) return cam = camL[0] camShape = mc.listRelatives(cam, s=1)[0] FL = mc.camera(cam, q=1, fl=1) NCP = mc.camera(cam, q=1, ncp=1) FCP = mc.camera(cam, q=1, fcp=1) cam3d = maya.app.stereo.stereoCameraRig.createStereoCameraRig() mc.parent(cam3d[0], cam) mc.setAttr(cam3d[0] + ".translate", 0, 0, 0, lock=1) mc.setAttr(cam3d[0] + ".rotate", 0, 0, 0, lock=1) mc.setAttr(cam3d[0] + ".scale", 1, 1, 1, lock=1) cam3dShape = mc.listRelatives(cam3d[0], s=1)[0] mc.connectControl("interaxialSleder", stereoShape + ".interaxialSeparation") mc.connectControl("zeroSleder", stereoShape + ".zeroParallax") mc.setAttr(cam3dShape + ".focalLength", FL) mc.setAttr(cam3dShape + ".nearClipPlane", NCP) mc.setAttr(cam3dShape + ".farClipPlane", FCP) mc.setAttr(cam3dShape + ".zeroParallaxPlane", 1) mc.setAttr(cam3dShape + ".safeViewingVolume", 1) for i in cam3d: mc.rename(i, cam + "_" + i) camListStereo = mc.ls(type="stereoRigTransform") if camListStereo == []: mc.floatSliderGrp(interaxialSleder, e=1, enable=False) mc.floatSliderGrp(zeroSleder, e=1, enable=False) else: stereoShape = mc.listRelatives(camListStereo[0], s=1)[0] mc.floatSliderGrp(interaxialSleder, e=1, enable=True) mc.floatSliderGrp(zeroSleder, e=1, enable=True) mc.connectControl(interaxialSleder, cam3dShape + ".interaxialSeparation") mc.connectControl(zeroSleder, cam3dShape + ".zeroParallax")
def deletetab(*args): alltabs = mc.tabLayout ('tabs',q=1,st=1) chktabs = mc.tabLayout ('Animation',q=1,st=1) chktabs1= mc.tabLayout ('Poses',q=1,st=1) if alltabs == 'Animation': seltab = mc.tabLayout('Animation',q=1,st=1) mc.deleteUI(seltab) Del_tab=savepathini+'Savepose/Animation/'+seltab Del1_in=Del_tab+'/' list_in=mc.getFileList(fld=Del1_in) for i in range(len(list_in)): mc.sysFile(Del1_in+'/'+list_in[i],delete=1) mc.sysFile(Del_tab,red=1) if chktabs=='': mc.confirmDialog (title='Error',message='No tabs to delete', button='OK',defaultButton='Yes') # else : # return else : seltab = mc.tabLayout('Poses',q=1,st=1) mc.deleteUI(seltab) Del_tab=savepathini+'Savepose/Poses/'+seltab Del1_in=Del_tab+'/' list_in=mc.getFileList(fld=Del1_in) for i in range(len(list_in)): mc.sysFile(Del1_in+'/'+list_in[i],delete=1) mc.sysFile(Del_tab,red=1) if chktabs1=='': mc.confirmDialog (title='Error',message='No tabs to delete', button='OK',defaultButton='Yes') else : return
def Pose_rtn(name,*args): lst=mc.ls(sl=1) if lst==[]: mc.confirmDialog (title='About' ,message= 'Nothing is selected',ma='center', button=['OK'] ,defaultButton='Yes') else: files=open(name,'r') nextLine=files.readline() sel_obj = mc.ls(sl=1) char = sel_obj[0].split(':') while (len( nextLine ) > 0 ): splitter= nextLine.split(' ') if splitter[0]=='obj': obj_name= splitter[1].strip() else: attr = splitter[0] value= splitter[1].strip() if len(char)==1: added=char[0]+ "." + attr else: added= (char[0] + ":" + obj_name + "." + attr) setA = "mc.setAttr('"+added+"',"+ value+')' try: eval(setA) except RuntimeError: pass nextLine=files.readline() files.close() print "Pose changed"
def GetGroupName(self): #Check to see if the name is saved with the file if cmds.objExists("CMSettings"): ScenePrepClass.GroupName = cmds.getAttr("CMSettings.ModelName") if cmds.objExists(ScenePrepClass.GroupName): print "Group name from save" return 1 #Check to see if the model is already grouped then use that name# if self.SelectedObjectsAreGrouped() != "": if cmds.textField("NameTextField",query = True, text = True) != "": #Rename the group if a name has been provided cmds.rename(ScenePrepClass.GroupName, cmds.textField("NameTextField",query = True, text = True)) #Replace the name in cursel for x in range(len(ScenePrepClass.Cursel)): if ScenePrepClass.Cursel[x] == ScenePrepClass.GroupName: ScenePrepClass.Cursel[x] = cmds.textField("NameTextField",query = True, text = True) # ScenePrepClass.GroupName = cmds.textField("NameTextField",query = True, text = True) print "Group name from model" return 1 #otherwise check the textfield if cmds.textField("NameTextField",query = True, text = True) != "": ScenePrepClass.GroupName = cmds.textField("NameTextField",query = True, text = True) print "Group name from field" if ScenePrepClass.GroupName == "": cmds.confirmDialog(m = "Please enter a name for the model") return 0
def Newtab(*args): sel_tab = mc.shelfTabLayout('tabs',q=1,st=1) crnt_tab= mc.shelfTabLayout(sel_tab,q=1,ca=1) Newtab = mc.promptDialog( title='Create New Tab', message='New Tab Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if Newtab == 'OK': n_text = mc.promptDialog(query=True, text=True) if n_text == '': mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is not valid', button=['OK'] ,defaultButton='Yes') else: if crnt_tab: for each in crnt_tab: if each == n_text: mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is already exists', button=['OK'] ,defaultButton='Yes') return #else: if sel_tab == 'Animation': Nw_tab=savepathini+'Savepose/Animation/'+n_text+'/' mc.shelfLayout(n_text,w=450,h=200,bgc=(0.3,0.3,0.3),p=Animation) mc.sysFile(Nw_tab, makeDir=True ) else: mc.shelfLayout(n_text,w=450,h=200,bgc=(0.3,0.3,0.3),p=Poses) Nw_tab=savepathini+'Savepose/Poses/'+n_text+'/' mc.sysFile(Nw_tab, makeDir=True ) mc.shelfTabLayout(sel_tab,e=1,st=n_text)
def _createParentMaster(obj, translation=True, rotation=True): '''Crea i gruppi necessari per utilizzare il parent master.''' # creo il parent handle e lo snap group dell'oggetto (aventi stesso pivot) # un file referenziato genera eccezione if cmds.referenceQuery(obj, inr=True) and (not ALLOW_REFERENCE_ROOT or cmds.listRelatives(obj, p=True)): sys.stdout.write('Read-only hierarchy detected\n') msg = 'Are you working with referenced files?\n\nZVPM can\'t group "%s" because it\'s in a read-only hierarchy.\n\n\nDo the following:\n\n- Open the referenced file.\n- Select this object, right-click on "Attach objects" button and "Create parent groups".\n- Save the file.' % obj cmds.confirmDialog(title='Referenced file - ZV Parent Master', message=msg) return False piv = cmds.xform(obj, q=True, rp=True, ws=True) cmds.group(obj, n=_getSnapGroup(obj)) cmds.xform(_getSnapGroup(obj), piv=piv, ws=True) ph = cmds.group(_getSnapGroup(obj), n=_getParentHandle(obj)) cmds.xform(_getParentHandle(obj), piv=piv, ws=True) # locca gli attributi non diponibili e quelli non richiesti ts = set(['tx', 'ty', 'tz']) rs = set(['rx', 'ry', 'rz']) availAttrs = set(cmds.listAttr(obj, k=True, u=True, sn=True) or []) attrsToLock = (ts | rs) - availAttrs if not translation: attrsToLock |= ts if not rotation: attrsToLock |= rs for attr in attrsToLock: cmds.setAttr('%s.%s' % (ph, attr), lock=True) return True
def J_importNcloth(): #读取文件 settingFileName = cmds.fileDialog2(fileMode=1, caption="Import cloth setting") if not cmds.attributeQuery('jClothMark',node='lambert1',exists=True):#添加标记 区分多次导入 cmds.addAttr('lambert1',longName="jClothMark",attributeType='short' ) if settingFileName==None: return readSettingFile=open(settingFileName[0],'r') clothData={} if settingFileName[0][-4:]=='.jcl': clothData=json.load(readSettingFile) else: cmds.confirmDialog(title=u'错误',message=u' 请选择jcl文件 ',button='666') return readSettingFile.close() rootNode=cmds.ls(long=True,sl=True) for item in rootNode: if cmds.objectType(item) !='transform': cmds.confirmDialog(title=u'错误',message=u'选择角色最上层的组\n或者选择需要添加布料的模型',button='666') return #导入解算器###################################################################################################### for itemNucleus in clothData['nucleus']: nucleusName=J_importNcloth_CreateNucleus(itemNucleus,settingFileName[0]) #导入布料###################################################################################################### #查找选择物体下层所有mesh allMeshNode=[]#要比对的模型shape节点 for item0 in rootNode:#如果选择了多个物体 tempMeshList=J_importNcloth_getAllMeshNode(item0) for item1 in tempMeshList: allMeshNode.append(item1) missedMesh=[]#需要加布料,但是丢失的节点 #开始导入 allDynNode=[] state =0 for clothItem in clothData['nCloth']:#导入布料### for meshItem0 in allMeshNode: if J_importNcloth_matchObj(meshItem0,clothItem['inMesh']): getPar=cmds.listRelatives(meshItem0,parent=True)[0] allDynNode.append(J_importNcloth_CreateCloth('nCloth',getPar,clothItem,settingFileName[0])) state=1 if state==0: missedMesh.append(clothItem['inMesh']) state =0 for clothItem in clothData['nRigid']:#导入碰撞### for meshItem0 in allMeshNode: if J_importNcloth_matchObj(meshItem0,clothItem['inMesh']): getPar=cmds.listRelatives(meshItem0,parent=True)[0] allDynNode.append(J_importNcloth_CreateCloth('nRigid',getPar,clothItem,settingFileName[0])) state=1 if state==0: missedMesh.append(clothItem['inMesh']) for clothItem in clothData['dynamicConstraint']:#导入约束### allDynNode.append(J_importNcloth_CreateCloth('dynamicConstraint','',clothItem,settingFileName[0])) for clothItem in clothData['nComponent']:#导入约束### allDynNode.append(J_importNcloth_CreateCloth('nComponent','',clothItem,settingFileName[0])) newNucleusName=nucleusName+'_v'+str(cmds.getAttr('lambert1.jClothMark')) cmds.rename(nucleusName,newNucleusName) #完成提示###################################################################################################### markOrg=cmds.getAttr('lambert1.jClothMark') cmds.setAttr('lambert1.jClothMark',(markOrg+1)) if len(allDynNode)>0: for renameNode in allDynNode: if renameNode is None: return newName=renameNode+'_v'+str(cmds.getAttr('lambert1.jClothMark')) cmds.rename(renameNode,newName) if len(missedMesh)>0: massageTemp='' for itemx in missedMesh: massageTemp+=itemx+' \n' massageTemp+=u'模型未找到。' cmds.confirmDialog(title=u'导入完成',message=massageTemp,button=u'知道了')
def camSeqRenderAll(deleteBakedCam=True): ''' render all shots in sequence manager. ''' #path variables userShotDir = os.getenv("USER_SHOT_DIR") fileRuleImages = mc.workspace("images", fre=True, q=True)[3:] renderGlobalPath = os.path.join(userShotDir, fileRuleImages) renderTempPath = os.path.join(renderGlobalPath, "tmp") #setup output path currentFile = mc.file(q=True, sn=True).split("/")[-1] fileName = os.path.splitext(currentFile)[0] outputDir = os.path.join(renderGlobalPath, fileName) #if shot render already exists. stop the render if os.path.exists(outputDir): mc.warning("output directory already exist. render canceled.") return else: pass #query render settings #todo #check if active panel is allMdPanel = mc.getPanel(type="modelPanel") activePanel = mc.getPanel(wf=True) if activePanel not in allMdPanel: mc.warning("please select the view you want to render.") return #create shot output dir try: #create dir callString = "mkdir " + outputDir mycmd = subprocess.Popen(callString, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, error = mycmd.communicate() except: print error #delete current tmp if found #for my local hacking rendering only ... if os.path.exists(renderTempPath): try: print "deleting current tmp dir: ", renderTempPath callString = "rm -rf " + renderTempPath mycmd = subprocess.Popen(callString, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, error = mycmd.communicate() except: print error else: print "no temp dir found." #get all shots in sequence allshots = mc.sequenceManager(lsh=True) renderedShots = [] #playblast each shot for s in allshots: deleteCam = False #shot render cam vars renderCam = mc.shot(s, cc=True, q=True) startTime = math.floor(mc.shot(s, st=True, q=True)) endTime = math.floor(mc.shot(s, et=True, q=True)) #shot sequence vars seq_startTime = math.floor(mc.shot(s, sst=True, q=True)) seq_endTime = math.floor(mc.shot(s, set=True, q=True)) seq_duration = mc.shot(s, sequenceDuration=True, q=True) seq_scale = mc.shot(s, scale=True, q=True) offsetTime = int(seq_startTime - startTime) #setup render time renderStartFrame = startTime renderEndFrame = startTime + seq_duration - 1 print s, startTime, endTime, "(", seq_startTime, seq_endTime, ")", renderCam, seq_duration if seq_scale != 1.0: print "sequnce scale is not uniform. baking camera animation for endering." renderCam = bakeSequenceScale(s) deleteCam = True print "start rendering: ", renderCam #set current panel to the current shot cam mel.eval("lookThroughModelPanel %s %s;" % (renderCam, activePanel)) #initialize render! note this will render out an image! mel.eval('currentTime %s ;' % (renderStartFrame)) mel.eval('RenderIntoNewWindow;') #close render view mel.eval('removeRenderWindowPanel renderView;') #do the render mel.eval('currentTime %s ;' % (renderStartFrame)) while (renderStartFrame <= renderEndFrame): mel.eval('renderWindowRender redoPreviousRender renderView;') renderStartFrame += 1 mel.eval('currentTime %s ;' % (renderStartFrame)) #remove render camera if deleteBakedCam and deleteCam: print "deleting camera: ", renderCam mc.delete(renderCam) #File Operations #rename and move shot renders shotDirName = s + "_" + str(offsetTime) shotDir = os.path.join(renderGlobalPath, shotDirName) #TODO: handle this better #if there is a same found. this will move the tmp into it instead of rename tmp. #for now just remove the old one assume it's from a preveus failed render if os.path.exists(shotDir): print "found " + shotDir + "removing it..." callString = "rm -rf " + shotDir mycmd = subprocess.Popen(callString, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, error = mycmd.communicate() else: pass #rename the tmp dir to the shot name callString = "mv " + renderTempPath + " " + shotDir mycmd = subprocess.Popen(callString, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, error = mycmd.communicate() #move into output dir callString = "mv " + shotDir + " " + outputDir mycmd = subprocess.Popen(callString, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, error = mycmd.communicate() #write nuke comp makeSeqComp(elementsDir=outputDir) #display result mc.confirmDialog(title='render finished: ', message=outputDir, button=['OK'], defaultButton='OK') #done. mc.warning( "all shots submited for render, Check script editer for more detail.")
__author__ = 'Morgan Loomis' __license__ = 'MIT' __category__ = 'None' __revision__ = 24 import maya.cmds as mc import maya.mel as mm from functools import partial import math, re, warnings try: import ml_utilities as utl utl.upToDateCheck(32) except ImportError: result = mc.confirmDialog( title='Module Not Found', message='This tool requires the ml_utilities module. Once downloaded you will need to restart Maya.', button=['Download Module','Cancel'], defaultButton='Cancel', cancelButton='Cancel', dismissString='Cancel' ) if result == 'Download Module': mc.showHelp('http://morganloomis.com/tool/ml_utilities/',absolute=True) ml_convertRotationOrder = None try: import ml_convertRotationOrder except ImportError: pass ml_resetChannels = None try: import ml_resetChannels except ImportError:
def init_engine(self): self.log_debug("%s: Initializing..." % self) # check that we are running an ok version of maya current_os = cmds.about(operatingSystem=True) if current_os not in ["mac", "win64", "linux64"]: raise tank.TankError("The current platform is not supported! Supported platforms " "are Mac, Linux 64 and Windows 64.") maya_ver = cmds.about(version=True) if maya_ver.startswith("Maya "): maya_ver = maya_ver[5:] if maya_ver.startswith(("2012", "2013", "2014", "2015", "2016")): self.log_debug("Running Maya version %s" % maya_ver) else: # show a warning that this version of Maya isn't yet fully tested with Shotgun: msg = ("The Shotgun Pipeline Toolkit has not yet been fully tested with Maya %s. " "You can continue to use Toolkit but you may experience bugs or instability." "\n\nPlease report any issues to: [email protected]" % (maya_ver)) # determine if we should show the compatibility warning dialog: show_warning_dlg = self.has_ui and "SGTK_COMPATIBILITY_DIALOG_SHOWN" not in os.environ if show_warning_dlg: # make sure we only show it once per session: os.environ["SGTK_COMPATIBILITY_DIALOG_SHOWN"] = "1" # split off the major version number - accomodate complex version strings and decimals: major_version_number_str = maya_ver.split(" ")[0].split(".")[0] if major_version_number_str and major_version_number_str.isdigit(): # check against the compatibility_dialog_min_version setting: if int(major_version_number_str) < self.get_setting("compatibility_dialog_min_version"): show_warning_dlg = False if show_warning_dlg: # Note, title is padded to try to ensure dialog isn't insanely narrow! title = "Warning - Shotgun Pipeline Toolkit Compatibility! " # padded! cmds.confirmDialog(title = title, message = msg, button = "Ok") # always log the warning to the script editor: self.log_warning(msg) self._maya_version = maya_ver if self.context.project is None: # must have at least a project in the context to even start! raise tank.TankError("The engine needs at least a project in the context " "in order to start! Your context: %s" % self.context) # Set the Maya project based on config self._set_project() # add qt paths and dlls self._init_pyside() # default menu name is Shotgun but this can be overriden # in the configuration to be Sgtk in case of conflicts self._menu_name = "Shotgun" if self.get_setting("use_sgtk_as_menu_name", False): self._menu_name = "Sgtk" # need to watch some scene events in case the engine needs rebuilding: cb_fn = lambda en=self.instance_name, pc=self.context, mn=self._menu_name:on_scene_event_callback(en, pc, mn) self.__watcher = SceneEventWatcher(cb_fn) self.log_debug("Registered open and save callbacks.")
def func(*args, **kwargs): ans = cmd.confirmDialog(**dec_kwargs) if ans == dec_kwargs.get('answer', 'OK'): return f(*args, **kwargs)
def checkIfp4Edit(sceneName): p4Enabled = isPerforceEnabled() sceneName = P4File(sceneName) #check out of perforce if not Path(sceneName).exists: return if not p4Enabled: ans = cmd.confirmDialog( t="p4 integration disabled", m= "perforce integration has been turned off\ndo you want to turn it back on?", b=("Yes", "No"), db="Yes") if ans == "Yes": enablePerforce() else: return names = [] data = [] isEdit = sceneName.isEdit() if isEdit is False: ans = '' default = cmd.optionVar(q='vSaveAutoCheckout') if cmd.optionVar( ex='vSaveAutoCheckout') else '' if default == "": ans = cmd.confirmDialog( t="file isn't checked out", m="the file: %s\nisn't checked out\ndo you want me to open for edit?" % sceneName, b=("Yes", "No", "always", "never"), db="OK") if ans == "always": cmd.optionVar(sv=('vSaveAutoCheckout', "always")) elif ans == "never": cmd.optionVar(sv=('vSaveAutoCheckout', "never")) melWarning( "file is checked into perforce - and pref is set to never checkout before save, so bailing..." ) return default = cmd.optionVar(q='vSaveAutoCheckout') #if the user has specified never - and the file isn't open for edit, then bail. we don't even want to try to save because the file isn't writeable if default == "never": ans = cmd.confirmDialog( t="file isn't checked out", m="file isn't checked out - bailing on save", b=("OK", "turn auto checkout back on"), db="OK") if ans != "OK": cmd.optionVar(rm='vSaveAutoCheckout') else: melWarning( "file is checked into perforce - and pref is set to never checkout before save, so bailing..." ) return if ans == "Yes" or ans == "always": sceneName.edit()
def createTechPasses(): ''' Setup render elements TODO: fix world normals ''' # first we make the sampler node as we will use this twice samplerNodeName = 'samplerInfo_for_render_elements' if not cmds.objExists(samplerNodeName): samplerNode = cmds.shadingNode('samplerInfo', asUtility=True) samplerNode = cmds.rename(samplerNode, samplerNodeName) # Surface Normals channel layerToMake = 'surfaceNormals' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement normalsChannel;') cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_name_normals', layerToMake, type='string') cmds.setAttr(layerToMake + '.vray_filtering_normals', True) # Camera Normals channel layerToMake = 'cameraNormals' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement ExtraTexElement;') cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_name_extratex', layerToMake, type='string') cmds.setAttr(layerToMake + '.vray_explicit_name_extratex', layerToMake, type='string') cmds.connectAttr(samplerNodeName + '.normalCamera', layerToMake + '.vray_texture_extratex') cmds.setAttr(layerToMake + '.vray_filtering_extratex', True) # World Normals channel layerToMake = 'worldNormals' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement ExtraTexElement;') cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_name_extratex', layerToMake, type='string') cmds.setAttr(layerToMake + '.vray_explicit_name_extratex', layerToMake, type='string') cmds.connectAttr(samplerNodeName + '.normalCamera', layerToMake + '.vray_texture_extratex') cmds.setAttr(layerToMake + '.vray_filtering_extratex', True) # zDepth channel layerToMake = 'zDepth' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement zdepthChannel;') renderElement = cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_name_zdepth', layerToMake, type='string') cmds.setAttr(layerToMake + '.vray_depthFromCamera_zdepth', True) cmds.setAttr(layerToMake + '.vray_depthClamp', False) cmds.setAttr(layerToMake + '.vray_filtering_zdepth', False) # zDepth with AA layerToMake = 'zDepthAA' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement zdepthChannel;') renderElement = cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_name_zdepth', layerToMake, type='string') cmds.setAttr(layerToMake + '.vray_depthFromCamera_zdepth', True) cmds.setAttr(layerToMake + '.vray_depthClamp', False) cmds.setAttr(layerToMake + '.vray_filtering_zdepth', True) # UVs layerToMake = 'UV' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement ExtraTexElement;') cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_name_extratex', layerToMake, type='string') cmds.setAttr(layerToMake + '.vray_explicit_name_extratex', layerToMake, type='string') cmds.connectAttr( samplerNodeName + '.uvCoord.uCoord', layerToMake + '.vray_texture_extratex.vray_texture_extratexR') cmds.connectAttr( samplerNodeName + '.uvCoord.vCoord', layerToMake + '.vray_texture_extratex.vray_texture_extratexG') cmds.setAttr(layerToMake + '.vray_filtering_extratex', False) # worldXYZ layerToMake = 'worldXYZ' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement ExtraTexElement;') cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_name_extratex', layerToMake, type='string') cmds.setAttr(layerToMake + '.vray_explicit_name_extratex', 'worldXYZ', type='string') cmds.setAttr(layerToMake + '.vray_considerforaa_extratex', False) cmds.connectAttr(samplerNodeName + '.pointWorld', layerToMake + '.vray_texture_extratex') # Ambient Occlusion layerToMake = 'AO' nodeToMake = 'ao_tex' if not cmds.objExists(layerToMake): if not cmds.objExists(nodeToMake): newNode = cmds.shadingNode('VRayDirt', name=nodeToMake, asTexture=True) cmds.setAttr(newNode + '.invertNormal', False) cmds.setAttr(newNode + '.ignoreForGi', 0) cmds.setAttr(newNode + '.blackColor', -0.5, -0.5, -0.5, type='double3') cmds.setAttr(newNode + '.falloff', 5) renderElement = mel.eval('vrayAddRenderElement ExtraTexElement;') renderElement = cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_name_extratex', layerToMake, type='string') cmds.setAttr(layerToMake + '.vray_explicit_name_extratex', layerToMake, type='string') cmds.connectAttr(nodeToMake + '.outColor', layerToMake + '.vray_texture_extratex') # TopDown falloff pass ''' Top down BROKEN layerToMake = 'topDown' nodeToMake = 'topdown_tex' if not cmds.objExists (layerToMake) : if not cmds.objExists (nodeToMake) : # now create the vray plugin with no placement on UV (0 = none, 1 = 2d, 2 = 3d) newNode = mel.eval( 'catchQuiet (vrayCreateNodeFromDll ("topdown_tex", "texture", "TexFalloff", 2));') newNode = cmds.rename( nodeToMake , nodeToMake ) cmds.setAttr (newNode + '.direction_type', 2) cmds.setAttr (newNode + '.color1', 1, 0, 0, type='double3') cmds.setAttr (newNode + '.color2', 0, 1, 0, type='double3') renderElement = mel.eval ('vrayAddRenderElement ExtraTexElement;') renderElement = cmds.rename (renderElement,layerToMake) cmds.setAttr (renderElement + '.vray_explicit_name_extratex', layerToMake, type = 'string') cmds.connectAttr (nodeToMake + '.outColor', renderElement + '.vray_texture_extratex') ''' # Give some feedback for next steps cmds.select(clear=True) dialogMessage = 'Tech Passes Created' result = cmds.confirmDialog(title='spck', message=dialogMessage, button=['OK'], defaultButton='OK') print('Tech Channels Success.\n')
def publish_maya_scene(versionUp=True, origScene=None, *args): """ only do for rigging and modeling phase of assets ARGS: versionUp (bool): whether to version up the maya scene origScene (string): the full path to the file to publish """ if not origScene: cmds.warning( "assetPublish.publish_maya_scene: You haven't passed in a scene path!" ) return (False) pp = uf.PathParser(origScene) cmds.file(s=True) sel = cmds.ls(sl=True) if not sel: cmds.warning( "assetManager.publish_maya_scene: You haven't selected anything in your scene. Please select what you wish to publish. (hint: for models, your geo/geo grp. For rigs, usually it will be your char group and ctrl set)" ) return (False) if versionUp: verUpFile = get_version_up_name(origScene) # parse the new path/name for publish(current scene) pubPath = uf.fix_path(os.path.join(pp.phasePath, "Publish/MB/")) tokens = pp.fileName.split("_") tokens[-2] = "Publish" pubFileName = "_".join(tokens) pubFilePath = uf.fix_path(os.path.join(pubPath, pubFileName)) if os.path.isfile(pubFilePath): overwrite = cmds.confirmDialog( title="Overwrite Confirmation", message= "A publish MB already exists for this file.\nShould we overwrite?", button=("Overwrite", "Cancel"), defaultButton="Overwrite", cancelButton="Cancel", dismissString="Cancel") if overwrite == "Cancel": print "Publish skipped (no overwrite) for maya file (.mb) stage of {0}".format( pubFilePath) return (True) if versionUp: # in background copy the orig to the new version # (essentially just versioning up while staying in old version) copy2(origScene, verUpFile) print "===== Versioned up {0} to {1}!".format(origScene, verUpFile) else: print "===== Not versioning up publish of {0}".format(origScene) # export selection to publish file print "===== AssetPublish.publish_maya_scene: Preparing to export items to publish file: {0}".format( sel) export = cmds.file(pubFilePath, exportSelected=True, type="mayaBinary") if export == pubFilePath: print "===== AssetPublish.publish_maya_scene: Succesfully published file to: {0}".format( pubFilePath) return (True)
def blendShapeExists(name): cmds.confirmDialog( title='Warning', message=name +' Possibly because an attribute of that name already exists.', button=['Yes'], defaultButton='Yes' )
def publish_fbx_anim_file(versionUp=True, origScene=None, *args): # THIS IS FOR ANIM EXPORTING # save current scene # move this to end and use Zed's script to version up afterwards? ? maybe? # version up if versionUp: verUpFile = get_version_up_name(origScene) copy2(origScene, verUpFile) print "===== Versioned up {0} to {1}!".format(origScene, verUpFile) else: print "===== Not versioning up publish of {0}".format(origScene) if not origScene: cmds.warning( "assetPublish.publish_fbx_anim_file: You haven't passed in a scene path!" ) return (False) # assuming references refs = cmds.file(q=True, r=True) if not refs: cmds.warning("There are no references in this scene. . .") return (False) if len(refs) > 1: cmds.warning("There are too many references in this scene. . .") return (False) # below would all be under a for loop for each reference in the stages? pp = uf.PathParser(origScene) # assuming a namespace geoGrp = cmds.ls("*:GEO") jntGrp = cmds.ls("*:EXPORT_JNT_Grp") # check for geo grps if not geoGrp or len(geoGrp) > 1: cmds.warning( "AssetPublish.publish_fbx_anim_file:You either have no grp called 'GEO' -IN A NAMESPACE-, or too many objects called 'GEO'.\n fbx export aborted!" ) return (False) geos = child_match_check(geoGrp[0], "*_Geo_Grp") if not geos: return (False) # check for jnt grps if not jntGrp or len(jntGrp) > 1: cmds.warning( "AssetPublish.publish_fbx_anim_file:You either have no grp called 'EXPORT_JNT_Grp' -IN A NAMESPACE-, or too many objects called 'EXPORT_JNT_Grp'.\n fbx export aborted!" ) return (False) roots = child_match_check(jntGrp[0], "*_Root_Jnt") if not roots: return (False) cmds.file(refs[0], ir=True) # check correspondence of geo and root jnts correspond = check_correspondence(geos, roots) if not correspond: return (False) pubFbxPath = uf.fix_path(os.path.join(pp.phasePath, "Publish/FBX/")) tokens = pp.fileName.split("_") tokens[-2] = "Publish" pubFileName = "_".join(tokens)[:-3] + ".fbx" pubFilePath = uf.fix_path(os.path.join(pubFbxPath, pubFileName)) start, end = uf.get_frame_range() # bake joints for r in roots: # get child roots if joints allD = cmds.listRelatives(r, allDescendents=True) jnts = [x for x in allD if cmds.objectType(x, isa="joint")] # function to bake selected on all jnts under this root bake_selected(jnts, start, end) namespace = cmds.file(refs[0], q=True, ns=True) uf.remove_namespaces() # delete constraints cmds.delete(cmds.ls(type="constraint")) cmds.select(cl=True) # move jnts and geo into world parent for root in roots: rootremove = "{0}:".format(namespace) basename = root.split(":")[1].split("_Root_Jnt")[0] geo = "{0}_Geo_Grp".format(basename) root = "{0}_Root_Jnt".format(basename) cmds.parent([geo, root], w=True) tokens[-2] = basename pubFileName = "_".join(tokens)[:-3] + ".fbx" pubFilePath = uf.fix_path(os.path.join(pubFbxPath, pubFileName)) rootremove = "{0}:".format(namespace) cmds.select([root, geo], r=True) # if this exists, should we overwrite? if os.path.isfile(pubFilePath): overwrite = cmds.confirmDialog( title="Overwrite Confirmation", message= "A publish FBX already exists for this file.\nShould we overwrite?", button=("Overwrite", "Cancel"), defaultButton="Overwrite", cancelButton="Cancel", dismissString="Cancel") if overwrite == "Cancel": print "Publish skipped for FBX file (.fbx) called {0}".format( pubFilePath) return (True) mel.eval('FBXLoadExportPresetFile -f "{0}";'.format(anmPreset)) mel.eval('FBXExport -f "{0}" -s'.format(pubFilePath)) return (True)
def checking(): importAssign = cmds.radioButton(importAssignBox, q=True, sl=1) importOnly = cmds.radioButton(importOnlyBox, q=True, sl=1) scenesList = cmds.textField(scenesListBox, q=True, tx=True).replace(' ', '').split(',') existingShadersList = [] for sceneName in scenesList: if cmds.namespace(exists=sceneName): existingShadersList.append(sceneName) else: pass if len(existingShadersList) > 0: if importOnly == 1: if cmds.namespace(exists=sceneName): confirmRefresh = cmds.confirmDialog( title='Import only', ma='center', message= 'The shaders your trying to import already exist in the scene. To avoid clashing names, they will have an "import only" namespace.', button=['Okay']) applyShaders(1, 1, scenesList) else: confirmRefresh = cmds.confirmDialog( title='Refresh shaders', ma='center', message= 'The following shaders already exist in the scene : ' + ','.join(existingShadersList).replace(".ma", "") + '.\nWould you like to refresh them ? (this will delete the shaders and import them again.)', button=['Yes', 'No']) if confirmRefresh == 'Yes': if importAssign: applyShaders(1, 0, scenesList) else: applyShaders(1, 1, scenesList) if confirmRefresh == 'No': pass #else, we execute the apply function else: if importAssign == True: applyShaders(0, 0, scenesList) else: applyShaders(0, 1, scenesList)
def publish_fbx_rig_file(versionUp=True, origScene=None, *args): """ requires an EXPORT_JNT_Grp group with one root for each export rig named: 'name_Root_Jnt' requires a GEO group with one folder for each export rig named: 'name_Geo_Grp' names should correspond ("fish_Root_Jnt", "fish_Geo_Grp") """ # all happens in current: if not origScene: cmds.warning( "assetPublish.publish_fbx_rig_file: You haven't passed in a scene path!" ) return (False) pp = uf.PathParser(origScene) geoGrp = cmds.ls("GEO") jntGrp = cmds.ls("EXPORT_JNT_Grp") # check for geo grps if not geoGrp or len(geoGrp) > 1: cmds.warning( "AssetPublish.publish_fbx_rig_file:You either have no grp called 'GEO', or too many objects called 'GEO'.\n fbx export aborted!" ) return (False) geos = child_match_check(geoGrp, "*_Geo_Grp") if not geos: return (False) # check for jnt grps if not jntGrp or len(jntGrp) > 1: cmds.warning( "AssetPublish.publish_fbx_rig_file:You either have no grp called 'EXPORT_JNT_Grp', or too many objects called 'EXPORT_JNT_Grp'.\n fbx export aborted!" ) return (False) roots = child_match_check(jntGrp, "*_Root_Jnt") if not roots: return (False) # check correspondence correspond = check_correspondence(geos, roots) if not correspond: return (False) pubFbxPath = uf.fix_path(os.path.join(pp.phasePath, "Publish/FBX/")) tokens = pp.fileName.split("_") tokens[-2] = "Publish" pubFileName = "_".join(tokens)[:-3] + ".fbx" pubFilePath = uf.fix_path(os.path.join(pubFbxPath, pubFileName)) # check if there's any animation in the file (time based), abort if there is # check for references, etc. . # delete constraints cmds.delete(cmds.ls(type="constraint")) cmds.select(cl=True) # move jnts and geo into world parent for root in roots: basename = root.split("_Root_Jnt")[0] geo = "{0}_Geo_Grp".format(basename) cmds.parent([geo, root], w=True) # create filename tokens[-2] = basename pubFileName = "_".join(tokens)[:-3] + ".fbx" pubFilePath = uf.fix_path(os.path.join(pubFbxPath, pubFileName)) cmds.select([root, geo], r=True) # if this exists, should we overwrite? if os.path.isfile(pubFilePath): overwrite = cmds.confirmDialog( title="Overwrite Confirmation", message= "A publish FBX already exists for this file.\nShould we overwrite?", button=("Overwrite", "Cancel"), defaultButton="Overwrite", cancelButton="Cancel", dismissString="Cancel") if overwrite == "Cancel": print "Publish skipped for FBX file (.fbx) called {0}".format( pubFilePath) return (True) mel.eval('FBXLoadExportPresetFile -f "{0}";'.format(rigPreset)) mel.eval('FBXExport -f "{0}" -s'.format(pubFilePath)) return (True)
def __init__(self, *args, **kwds): self.result = mc.confirmDialog(*args, **kwds)
def saveFile(self, local=False): pBlast, cchChk, pbStat = False, False, True cmsObj = self.getCmsObj() if cmsObj.deptShort in ["ly", "bk", "an"]: pBlast = mc.checkBox("chkPlayblast", q=1, v=1) if pBlast: viewport = utils.getActiveViewport() if not viewport: utils.msgWin( "Error", "Couldn't get active viewport. Please\nactivate viewport and try again.", False) return cchChk = mc.checkBox("chkCache", q=1, v=1) if cchChk: cacheDataObj = ppc.CacheDataXml() cacheExportError = cacheDataObj.checkExportErrors(False) if cacheExportError: return mayaShot = ppc.MayaShot(silent="disabled") if not mayaShot.validShot: utils.msgWin("Error", "Not a valid shot", False) return if not (mayaShot.deptShort == cmsObj.deptShort): msg = "Scene department does not match the dept selected in manager." utils.msgWin("Error", msg, False) return if not (mayaShot.epSqName == cmsObj.epsq and mayaShot.shName == cmsObj.shot): msg = "Scene shot number does not match the shot selected in manager." msg += "\nDo you want to save using the shot number selected in manager?" msg += "\nThis will rename camera and obtain frames from breakdown list." conf = mc.confirmDialog(t="Warning", m=msg, button=['Save', 'Cancel'], cancelButton='Cancel', dismissString='Cancel') if conf == 'Cancel': return if local: wsFileFldr = mc.fileDialog2(dialogStyle=1, fm=3) if wsFileFldr: newFilePath = os.path.join( wsFileFldr[0], "%s.%s" % (cmsObj.fileName, cmsObj.ext)) if os.path.exists(newFilePath): utils.saveVersion(newFilePath) mc.file(rename=newFilePath) mc.file(save=True) blastPath = newFilePath.replace(".%s" % cmsObj.ext, ".avi") else: utils.msgWin("Error", "No folder selected", True) return else: wsFilePath = os.path.join(cmsObj.wsPath, "%s.%s" % (cmsObj.fileName, cmsObj.ext)) utils.saveVersion(wsFilePath) mc.file(rename=wsFilePath) utils.sceneCleanup() mc.file(save=True) blastPath = None msg = "File successfully Saved" if pBlast: pbStat = utils.takePlayblast(True, False, blastPath) mc.refresh() if cchChk and not local: cacheDataObj = ppc.CacheDataXml() cacheDataObj.writeXML() msg = "File successfully Saved and Cached" if not pbStat: msg = msg + "\n\nThere were errors while taking the playblast.\nPlease check the script editor for details." utils.msgWin("Success", msg, False) self.loadVersions()
def sceneInfo(self): seqInfo = cmds.textScrollList('shotContent', q=True, si=True)[0] episodeName = cmds.textScrollList('ecfList', q=True, si=True)[0] record = [] for chk in epsInts: if chk[0].find(seqInfo) != -1: record.append(chk) #implement sequence information enviFetch = asiist.getEnvi() for chk in enviFetch: if chk[0] == 'resWidth': resWidth = chk[1] if chk[0] == 'resHeight': resHeight = chk[1] if chk[0] == 'resAspectRatio': resAspectRatio = chk[1] cmds.setAttr('defaultResolution.width', float(resWidth)) cmds.setAttr('defaultResolution.height', float(resHeight)) cmds.setAttr('defaultResolution.deviceAspectRatio', float(resAspectRatio)) #create empty group cmds.group(em=True, n='sceneInfo', p='shotMaster') if not cmds.objExists('char'): cmds.group(em=True, n='char', p='shotMaster') if not cmds.objExists('prop'): cmds.group(em=True, n='prop', p='shotMaster') if not cmds.objExists('sets'): cmds.group(em=True, n='sets', p='shotMaster') #generate data from record duration = 0 for chk in record: duration = duration + int(chk[1]) #additional data to sceneInfo cmds.select('sceneInfo') for chk in asiist.getEnvi(): cmds.addAttr(ln=str(chk[0]), k=True, at='enum', en=str(chk[1])) cmds.setAttr('sceneInfo.' + str(chk[0]), l=True) if chk[0] == 'unit': cmds.currentUnit(time=chk[1]) cmds.addAttr(ln='__________', k=True, at='enum', en='__________') cmds.setAttr('sceneInfo.__________', l=True) cmds.addAttr(ln='episodeName', k=True, at='enum', en=str(episodeName)) cmds.setAttr('sceneInfo.episodeName', l=True) cmds.addAttr(ln='sequenceName', k=True, at='enum', en=str(seqInfo)) cmds.setAttr('sceneInfo.sequenceName', l=True) cmds.addAttr(ln='startFrame', k=True, at='enum', en='101') cmds.setAttr('sceneInfo.startFrame', l=True) cmds.addAttr(ln='endFrame', k=True, at='enum', en=str(100 + (duration))) cmds.setAttr('sceneInfo.endFrame', l=True) cmds.addAttr(ln='key', k=True) cmds.addAttr(ln='___________', k=True, at='enum', en='__________') cmds.setAttr('sceneInfo.___________', l=True) base = 101 for chk in epsInts: if chk[0].find(seqInfo) != -1: #create shot entry cmds.addAttr(ln=chk[0], k=True, at='enum', en=str(chk[1])) cmds.setAttr('sceneInfo.' + chk[0], l=True) #create shot key shotNum = chk[0] shotNum = shotNum[shotNum.rfind('_') + 1:] shotNum = int(shotNum.replace('SH', '')) cmds.setAttr('sceneInfo.key', shotNum) cmds.setKeyframe('sceneInfo', attribute='key', t=base) base = base + (int(chk[1]) - 1) cmds.setAttr('sceneInfo.key', shotNum) cmds.setKeyframe('sceneInfo', attribute='key', t=base) base = base + 1 #cmds.setKeyframe('sceneInfo', attribute='key', t=base) #lock standard channel for object in ['shotMaster', 'sceneInfo', 'char', 'prop', 'sets']: for channel in [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'visibility' ]: cmds.setAttr(object + '.' + channel, l=True, cb=False, k=False) #impose shot range cmds.rangeControl(min=101, max=101 + (int(duration) - 1)) cmds.playbackOptions(min=101, max=101 + (int(duration) - 1)) #insert sound soundName = str(shotNum) if len(soundName) == 1: soundName = '0' + soundName if not os.path.isfile(SOUND_ROOT + '/' + PRJ_NAME + '/' + episodeName + '/SQ' + str(soundName) + '.wav'): cmds.confirmDialog( icn='information', t='Missing File', m='Missing sound file. Skip sound insertion process.', button=['OK']) else: if cmds.objExists('seqSoundtrack'): cmds.delete('seqSoundtrack') ret = mel.eval('doSoundImportArgList ("1", {"' + SOUND_ROOT + '/' + PRJ_NAME + '/' + episodeName + '/SQ' + str(soundName) + '.wav' + '","101.0"});') cmds.rename(ret, 'seqSoundtrack') return
def getNodesOverload(poseObj, nodes, *args): # NOTE: poseObj already has an attr 'metaRig' which is filled # automatically in the main buildInternalPoseData() call metaNode = poseObj.metaRig currentSelection = cmds.ls(sl=True, l=True) filteredNodes = [] if not issubclass(type(metaNode), r9Meta.MetaHIKControlSetNode): # see if we have a controller selected thats connected to an # appropriate subMetaSystem if not currentSelection: result = cmds.confirmDialog( title='selection hint missing', button=[ 'L_Fingers', 'R_Fingers', 'L_Toes', 'R_Toes', 'Cancel' ], message= 'We need a hint to ID which finger system to load/save the data too,\nIdeally you should select something in the correct limb system that we can use', defaultButton='Cancel', cancelButton='Cancel', icon='information', dismissString='Cancel') if result == 'L_Fingers': msystem = metaNode.L_ArmSystem elif result == 'R_Fingers': msystem = metaNode.R_ArmSystem elif result == 'L_Toes': msystem = metaNode.L_LegSystem elif result == 'R_Toes': msystem = metaNode.R_LegSystem else: msystem = r9Meta.getConnectedMetaNodes(cmds.ls(sl=True))[0] # from selected node, or selected system find our finger / toe subSystem if not msystem.systemType.lower() in ['fingers', 'toes']: fingersystem = msystem.getChildMetaNodes(mAttrs=['systemType']) if fingersystem: fingersystem = fingersystem[0] else: fingersystem = msystem if not fingersystem or not fingersystem.systemType.lower() in [ 'fingers', 'toes' ]: raise IOError( 'no finger / toe metaSubSystems found from the selected node') print '\nFinger : PoseOverload Handler : %s >> subSystem: %s' % ( metaNode, fingersystem) filteredNodes = fingersystem.getChildren() # if cmds.getAttr('%s.mirrorSide' % currentSelection[0]) == 1: # print '\nFinger : PoseOverload Handler : %s >> side: Left' % metaNode # filteredNodes = metaNode.L_ArmSystem.L_FingerSystem.getChildren() # elif cmds.getAttr('%s.mirrorSide' % currentSelection[0]) == 2: # print '\nFinger : PoseOverload Handler : %s >> side: Right' % metaNode # filteredNodes = metaNode.R_ArmSystem.R_FingerSystem.getChildren() # modify the actual PoseData object, changing the data to be matched on index # rather than using the standard name or metaMap matching poseObj.metaPose = False poseObj.matchMethod = 'mirrorIndex_ID' poseObj.mirrorInverse = True # set the mirror inverse code to active to cope with mirror differences between Left and Right fingers return filteredNodes
def Cas_massCopyWeight_cmd(pruneValue, autoConvertRigid): """ Author : Saehoon Lee Date : 06/02/2013 Email : [email protected] http://www.castorlee.com Tested for Maya v8.5 v2008 v2009 Description : Python version of Cas_massCopyWeight. More stable and less code than mel. GUI added more functions related to rigid skin DO NOT DISTRIBUTE WITHOUT PERMISSION FROM AUTHOR How to use : ( v 4.1 ) run command in python script editor: import maya.cmds as cmds import Cas_massCopyWeight_python Cas_massCopyWeight_python.Cas_massCopyWeight_UI() Select source and Target objects/groups to transfer binding/weights the press buttons on GUI that you want to perform """ # Date: 06/02/2013 # V 4.1 : # minor bug fix , issue with Maya 8.5 (Thanks Alexander from CD4 team) # # Date: 17/07/2009 # V 4.0 : # minor bug fix , issue with Maya 2009 # # Date: 16/02/2009 # V 3.9 : # just realized that if rigid body's weight is less than 1 , resulted smooth skin weight of less than 1 (combined) # is going to move the vertices. With bit of help from Tom, managed to come up with workable version of the converter # # Date: 07/01/2009 # V 3.8 : # Fixed bug when root of joint is not joint node. (group node) Thanks Andrew # # Date: 27/11/2008 # V 3.7 : # Fixed iteration bug with Maya 8.5 implementation. # # Date: 05/11/2008 # V 3.6 : First GUI version with Rigid skin converter # Added GUI for normal weight copying function # Added function to convert rigid skin to smooth skin and copy the weights from rigid to smooth skin # Added option to toggle auto delete rigid joint cluster and auto convert rigid skin to smooth skin # Added additional function to delete rigid skin jointcluster if wanted # Converting from rigid skin to smooth skin does not delete rigid skin jointcluster by default. # But the weights of rigid skin jointCluster is set to 0 after copying the weight to new smooth skinCluster # # More error checking. Better progress bar. Implemented own function for deleteunusedinfluence # # Date: 03/11/2008 # V 3.5 : Non Pymel version # Pymel was used last version of this sctipt to simplify the process and shorten the code. # But this led to some complication of distributing to the other studios. # Therefore removed Pymel commands and used native # Maya commands only. Implemented few of own functions that does not exist in Python commands in Maya. # # Date: 15/10/2008 # V 3.4 : First Python version of the script # Python version seems to be more stable and works better. # Added more rigrious error checking prune small weight function. Modified the way it works by changing the command # # Date: 09/10/2008 # V 3.3 : Changed prune small weight method. # there was heavy memory leak bug with Maya when UV editor is open and run default # prune small weight function. Modified the way it works by changing the command to # skinPercent -prw 0.01 ClusterName. Faster and with no memory leak. Also minimised doing # lots of selections. Apprently there is another bug or stupid feature in Maya where Texture UV # editor keeps the cache of displayed images, so if you do lots of selection it will eat memory # and significantly slow down the process. Known Maya behaviour. # # Date: 14/09/2008 # V 3.2 : Changed bonding option. Removed cloest joint option which was not # working well with the joints with the same position. # # Date: 15/02/2008 # V 3.1 : Changed how removing unused influence work. This fixes weird # flashing mouse icon issue with Evaldeferred command. But less intuative. # # Date: 18/01/2008 # V 3.0 : Uses Maya's copyweight function more wisely and now it # is possible to map the objects without the same names. but slower. # It is possible to make this bit faster, but don't want to start # modifying the user's skin binding, copy weight settings. # # Date: 15/01/2008 # V 2.0 : Version 2 works with groups of objects too. Meshes needs # to have the same names to work. # # Date: 1/10/2007 # V 1.0 : First version # Select source and destination mesh and it will bind the relevent # joints and copy weights across. # time = cmds.timerX() time2 = 0 timeTook2 = 0 progressCount = 0 sel = cmds.ls(sl=True, tr=1) if (sel == None) or (sel == []): Cas_IO.Cas_printWarning( "Please select one object for source and at least one object/groups for target..." ) return if len(sel) < 2: Cas_IO.Cas_printWarning( "Please select one objects for source and at least one object/groups for target..." ) return warningCount = 0 undoState = cmds.undoInfo(q=1, st=1) texWin = cmds.getPanel(sty="polyTexturePlacementPanel") #texState = cmds.textureWindow(texWin[0],q=1,id=1) texState = False cmds.progressWindow(min=0, max=100, t="Cas_massCopyWeight_Python 3.6") #cmds.textureWindow(texWin[0],q=1,id=0) #disable undo for memory issue cmds.undoInfo(swf=0) #print rootjoint #print "done" #return # compile both source and target node lists org = [] rel = cmds.listRelatives(sel[0], ad=1, pa=1, typ="transform") if rel != None: org = rel org.append(sel[0]) #print org #org.append(sel[0]) source = org[:] # make a copy #find mesh only for node in org: shape = cmds.listRelatives(node, s=1, type="mesh", pa=1) if shape == None: #print "opps no mesh shape node has been found for node : %s" % node #print node source.remove(node) #convert to soft skin if necessary if autoConvertRigid == True: #need some sort of warning system .. here ? result = Cas_convertRigidToSmooth.Cas_convertRigidToSmooth_cmd(source) if result[1] == 0: Cas_IO.Cas_printInfo("%s rigid skin converted to smooth skin" % result[0]) else: Cas_IO.Cas_printWarning( "%s rigid skin converted to smooth skin with %s warnings. please check your script editor" % (result[0], result[1])) autoDelete = cmds.checkBox(Cas_MCW_autoDeleteJointClusterCheckCT, q=True, v=True) if autoDelete == True: time2 = cmds.timerX() confirm = cmds.confirmDialog( title="Delete rigid joint clusters" , message="It will disconnect the other objects bind to the deleted clusters as well"+"\n"\ +" Are you sure?", button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) timeTook2 = cmds.timerX(st=time2) if confirm == "Yes": Cas_convertRigidToSmooth.Cas_CRTS_deleteJointCluster(source) print "copying smooth skin weights now..." progressCount = 10 cmds.progressWindow(e=1, pr=progressCount) #now finally check to see if objects actually has skinCluster org = source[:] for node in org: if Cas_MCW_findRelatedSkinSluster(node) == None: print "No skincluster found for node. Removed from list : %s" % node warningCount = warningCount + 1 source.remove(node) # find the root joint to bind to. joints = [] try: joints = cmds.skinCluster(sel[0], q=1, inf=1) except Exception, msg: Cas_IO.Cas_printWarning( "None of the source objects seems to have skin cluster! (or it is rigid skin and not converted to smooth skin) %s" % msg) Cas_MCW_restoreMisc(undoState, texState) return
def deleteShot(self, *args): repVar = cmds.confirmDialog(icn='question', t='New',\ m='This will clear current sequence. Proceed?',\ button=['Ok', 'Cancel']) if repVar == 'Ok': cmds.file(new=True, f=True) return
def warningFunc(key, *args): message = MESSAGE[key] title = TITLE[key] cmds.confirmDialog(t=title, m=message, b='OK') cmds.warning(message) logger.info(message)
if((mc.objExists('BN_FK_L_UpperArm')) and (mc.objExists('BN_IK_L_Thigh'))): fkArms = True ikLegs = True if(mc.objExists('BN_IK_L_UpperArm')): ikArms = True if(mc.objExists('BN_FK_L_Thigh')): fkLegs = True if(mc.objExists('BN_F_Head_Dummy')): iFace = True if(mc.objExists('CTRL_Hair')): includeHair = True if(mc.objExists('BN_L_Finger_Thumb_1')): thumb = True s = mc.ls('BN_Spine_*', type = 'joint') spineCount = len(s) f = mc.ls('BN_L_Finger_*', type = 'joint') fingerCount = len(f)/4 ANIMpresetWindow() else: mc.confirmDialog(title = 'Error!', message = 'There is no FK arms or IK legs system', icon = 'critical')
import maya.cmds as cmds
def pipelineLayout(*args): cmds.confirmDialog(t="doing it now", m="I am old Code with it", b="OK")
lastDigits = 0 if index > 1: lastDigits = len(str(index)) newName = newName[:-lastDigits] newName += str(index) obj = cmds.rename(obj, newName) return obj else: return obj ''' ----------------------------------- First Dialog and Window Creation ----------------------------------------- ''' # __name__ is a variable that all python modules have when executed # When a python module is executed directly (pasting it on script editor, # charcoal or through vsCode), the name is "__main__" # When a python module is imported, the name is the name of the .py file # or the alias assigned to it with "as" keyword # This line specifies that the following should only get called # when running this module directly and not trough imports if __name__ == "__main__": confirm = cmds.confirmDialog(t="Checking", m="Before proceeding, is your model placed on Z direction?", b=["Yes", "No"], db="Yes", cb="No", ds="No") if confirm == "No": cmds.confirmDialog(t="Fix object", m="You MUST place the object at the origin and along the Z axis") else: makeWindow()
def waitforupdate(*args): key = 'waitForUpdate' cmds.confirmDialog(t=TITLE[key], m=MESSAGE[key], b="OK")
def errorWin(message): cmds.confirmDialog(title='Error', message=message, button=['OK'], cancelButton='OK', dismissString='No')
def makeTreadObj(*args): """This function makes a tread out of the selected object""" usePreMade = cmds.radioButton("premadeGeo", query=True, select=True) if usePreMade: renamePreMade() return useProxy = cmds.checkBox("useProxy", query=True, value=True) if useProxy: if cmds.objExists("TreadProxyGeo"): userObj = "TreadProxyGeo" else: userObj = makeProxyGeo() else: userObj = cmds.textFieldButtonGrp("treadName", query=True, text=True) if not userObj: cmds.confirmDialog(t="Select a piece", m="Please choose a piece to build a tread or tick proxy option") return cmds.select(userObj, replace=True) # Verify if we want to use the actual measures of the object useBbox = cmds.checkBox("bboxCheck", q=True, v=True) if useBbox: bbox = cmds.exactWorldBoundingBox(userObj) radius = data.curveRadius perimeter = 2*3.14159*radius bboxDistance = abs(bbox[2]-bbox[-1]) bboxDistance*=.85 amount = round(perimeter / bboxDistance) else: amount = cmds.intSliderGrp("treadAmount", q=True, v=True) cmds.select(data.treadCircle, add=True) pathAnimation = cmds.pathAnimation(fm=True, f=True, fa="z", ua="y", stu=1, etu=amount, wu=(0,1,0), iu=False) # Adjust animCurve cmds.selectKey("{}_uValue".format(pathAnimation), time=(1,amount)) cmds.keyTangent(itt="linear", ott="linear") #Creating snapshot cmds.snapshot(n="TreadSnapShot", ch=False, i=1, st=1, et=amount, update="animCurve") cmds.DeleteMotionPaths() cmds.select("TreadSnapShotGroup", r=True) if not amount == 1: data.treadMesh = cmds.polyUnite(n="TreadMesh", ch=False)[0] data.treadMesh = checkDuplicatedName(data.treadMesh) else: piece = cmds.listRelatives(cmds.ls(selection=True))[0] cmds.select(piece) cmds.parent(world=True) piece = cmds.rename("TreadMesh") cmds.DeleteHistory() cmds.delete("TreadSnapShotGroup") cmds.select(data.treadMesh, r=True) cmds.CenterPivot() # Hide original geo cmds.setAttr("%s.visibility"%userObj, False) # Delete Proxy geo if used if cmds.objExists("TreadProxyGeo"): cmds.delete("TreadProxyGeo")
def initializePlugin(obj): """Initialize Plug-in""" print("Initializing Azure Batch plug-in") existing = cmds.optionVar(exists=EULA_PREF) if not existing: agree = cmds.layoutDialog(ui=eula_prompt, title="Azure Batch Maya Client") if str(agree) != 'Agree': raise RuntimeError("Plugin initialization aborted.") cmds.optionVar(stringValue=(EULA_PREF, VERSION)) else: agreed = cmds.optionVar(query=EULA_PREF) if StrictVersion(agreed) < VERSION: agree = cmds.layoutDialog(ui=eula_prompt, title="Azure Batch Maya Client") if str(agree) != 'Agree': raise RuntimeError("Plugin initialization aborted.") cmds.optionVar(stringValue=(EULA_PREF, VERSION)) print("Checking for dependencies...") missing_libs = [] python_path = os.environ['PYTHONPATH'].lstrip(os.pathsep) os.environ['PYTHONPATH'] = INSTALL_DIR + os.pathsep + python_path for package in REQUIREMENTS: if not dependency_installed(package, REQUIREMENTS[package]): missing_libs.append(package) for package in NAMESPACE_PACKAGES: if not dependency_installed(package, NAMESPACE_PACKAGES[package]): missing_libs.append(package) if missing_libs: message = ("One or more dependencies are missing or out-of-date." "\nWould you like to install the following?\n\n") for lib in missing_libs: message += "{0} v{1}\n".format(*lib.split('==')) install = cmds.confirmDialog(title='Azure Batch', message=message, button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if install == "No": cmds.confirmDialog(message="Could not load Azure Batch plug-in", button='OK') raise ImportError("Failed to load Azure Batch - " "missing one or more dependencies") print("Attempting to install dependencies via Pip.") try: install_script = os.path.normpath( os.path.join(os.environ['AZUREBATCH_TOOLS'], 'install_pip.py')) installer = subprocess.Popen( ["mayapy", install_script, '--target', INSTALL_DIR], stdout=subprocess.PIPE, stderr=subprocess.PIPE) installer.wait() if installer.returncode != 0: print(installer.stdout.read()) print(installer.stderr.read()) raise RuntimeError("Failed to install pip") except BaseException as exp: print( "Failed to install Pip. Please install dependencies manually to continue." ) raise try: print("Installing dependencies") for package in missing_libs: if package in NAMESPACE_PACKAGES: package_path = NAMESPACE_PACKAGES[package].split('.') install_namespace_pkg(package, os.path.join(*package_path)) else: install_pkg(package) shutil.copy( os.path.join(INSTALL_DIR, 'azure', '__init__.py'), os.path.join(INSTALL_DIR, 'azure', 'mgmt', '__init__.py')) except: error = "Failed to install dependencies - please install manually" cmds.confirmDialog(message=error, button='OK') raise ImportError(error) message = ("One or more dependencies have been successfully installed." "\n Please restart Maya to complete installation.") cmds.confirmDialog(message=message, button='OK') raise ImportError("Please restart Maya. Azure Batch installed " "Python dependencies.") print("Dependency check complete") plugin = OpenMayaMPx.MFnPlugin(obj, "Microsoft Corporation", VERSION, "Any") plugin.registerCommand(cmd_name, cmd_creator) try: if (mel.eval("""shelfLayout -exists "AzureBatch" """) == 0): mel.eval('addNewShelfTab %s' % "AzureBatch") mel.eval("""source "create_shelf.mel" """) melPath = get_usershelf_dir() if os.path.exists("{0}.deleted".format(melPath)): os.remove("{0}.deleted".format(melPath)) os.rename(melPath, "{0}.deleted".format(melPath)) except Exception as exp: print("Couldn't add shelf: {}".format(exp)) # Add callback to clean up UI when Maya exits global fMayaExitingCB fMayaExitingCB = OpenMaya.MSceneMessage.addCallback( OpenMaya.MSceneMessage.kMayaExiting, remove_ui)
def _do_playblast(self): MODEL_EDITOR_PARAMS = { "activeView": True, "cameras": False, "controlVertices": False, "deformers": False, "dimensions": False, "displayAppearance": "smoothShaded", "displayLights": "default", "displayTextures": True, "dynamicConstraints": False, "fogging": False, "follicles": False, "grid": False, "handles": False, "headsUpDisplay": True, "hulls": False, "ignorePanZoom": False, "ikHandles": False, "imagePlane": True, "joints": False, "lights": False, "locators": False, "manipulators": False, "nurbsCurves": False, "nurbsSurfaces": True, "pivots": False, "planes": False, "selectionHiliteDisplay": False, "shadows": False, "sortTransparent": True, "strokes": True, "textures": True, "useDefaultMaterial": False, "wireframeOnShaded": False, } windowName = "review_blast" try: _current_panel = pm.getPanel(wf=True) if pm.modelEditor(_current_panel, q=True, fogging=True) == True: MODEL_EDITOR_PARAMS["fogging"] = True except: pass try: if pm.windowPref(windowName, exists=True): pm.windowPref(windowName, remove=True) pm.deleteUI(windowName) except: pass _window = pm.window(windowName, titleBar=True, iconify=True, leftEdge=100, topEdge=100, width=800, height=600, sizeable=False) _layout = pm.formLayout() _editor = pm.modelEditor(**MODEL_EDITOR_PARAMS) pm.formLayout(_layout, edit=True, attachForm=((_editor, "left", 0), (_editor, "top", 0), (_editor, "right", 0), (_editor, "bottom", 0))) # Legacy viewport used try: mel.eval("setRendererInModelPanel ogsRenderer {};".format(_editor)) except: cmds.confirmDialog( message= 'You need to change your viewport as the legacy version', dismissString='No') # viewport 2.0 used # mel.eval( "setRendererInModelPanel \"vp2Renderer\" {};".format( _editor)) pm.setFocus(_editor) pm.lookThru(_editor, self._shot_cam) cmds.refresh() _labelColor = cmds.displayColor('headsUpDisplayLabels', q=True, dormant=True) _labelValue = cmds.displayColor('headsUpDisplayValues', q=True, dormant=True) visibleHUDs = [ f for f in pm.headsUpDisplay(listHeadsUpDisplays=True) if pm.headsUpDisplay(f, query=True, visible=True) ] map(lambda f: pm.headsUpDisplay(f, edit=True, visible=False), visibleHUDs) for h in pm.headsUpDisplay(listHeadsUpDisplays=True): if pm.headsUpDisplay(h, q=1, s=1) == 7: if pm.headsUpDisplay(h, q=1, b=1) == 5: try: pm.headsUpDisplay(h, rem=True) except: pass for h in pm.headsUpDisplay(listHeadsUpDisplays=True): if pm.headsUpDisplay(h, q=1, s=1) == 7: if pm.headsUpDisplay(h, q=1, b=1) == 6: try: pm.headsUpDisplay(h, rem=True) except: pass cmds.displayColor('headsUpDisplayValues', 17, dormant=True) cmds.displayColor('headsUpDisplayLabels', 16, dormant=True) def hudShot(): _nameTemp = cmds.file(q=1, ns=1).split(".")[0] return _nameTemp.rsplit("_", 1)[0] def hudName(): return getpass.getuser() pm.headsUpDisplay('HUDCurrentFrame', edit=True, visible=True, labelFontSize="large", dataFontSize="large", section=5, block=1) #cmds.headsUpDisplay('HUDA',s=7,b=6, blockAlignment='center', dataFontSize='large', command=hudShot) #cmds.headsUpDisplay('HUDB',s=7,b=5, blockAlignment='center', dataFontSize='large', label="Artist:", labelFontSize="large", command=hudName) pm.setFocus(_editor) #if pm.headsUpDisplay('HUDCurrentFrame', query=True, visible=False): # print "works 111" # pass #else: _mov_file = os.path.splitext(self._file)[0] # print _mov_file # __audios = pm.ls(type="audio") __audios = pm.ls(type="audio") if len(__audios) > 0: __audio = str(__audios[0]) else: __audio = False # frame catching min, max, current _min_frame = pm.playbackOptions(q=1, min=1) _max_frame = pm.playbackOptions(q=1, max=1) _current_frame = pm.currentTime(q=1) pm.currentTime(_min_frame) ### playblast option ### # play_args = "playblast -format avfoundation -filename \"{}\" -sound \"{}\" -sequenceTime 0 -clearCache 1 -viewer 1 -forceOverwrite -showOrnaments 1 -offScreen -fp 4 -percent 100 -compression \"H.264\" -quality 70 -widthHeight {} {};".format( self._file, __audio, self.resolution_size[0], self.resolution_size[1]) try: _temp_path, _temp_file = os.path.split(self._file) _temp_mov_path = _temp_path + "/.temp" _temp_file_01 = os.path.splitext(_temp_file) _temp_mov_file = _temp_file_01[0] + "_uncomp" + _temp_file_01[1] _full_temp_mov_file = os.path.join(_temp_mov_path, _temp_mov_file) print _full_temp_mov_file try: if not os.path.exists(_temp_mov_path): os.makedirs(_temp_mov_path) if os.path.exists(_full_temp_mov_file): os.remove(_full_temp_mov_file) except: raise ### making playblast play_args = "playblast -format qt -filename \"{}\" -sound \"{}\" -sequenceTime 0 -clearCache 1 -viewer 0 -showOrnaments 1 -compression \"H.264\" -offScreen -fp 4 -percent 100 -quality 100 -widthHeight {} {};".format( _full_temp_mov_file, __audio, self.resolution_size[0], self.resolution_size[1]) mel.eval(play_args) pm.currentTime(_current_frame) sceneName = pm.sceneName() tk = sgtk.sgtk_from_path(sceneName) # get entity information _context = tk.context_from_path(sceneName) _date = datetime.date.today() _task = _context.step["name"] _shot_name = _context.entity["name"] _png_file = os.path.normpath( _temp_mov_path + "/" + _context.user["name"].translate(None, string.whitespace) + ".png") try: if not os.path.exists(_temp_mov_path): os.makedirs(_temp_mov_path) if os.path.exists(_png_file): os.remove(_png_file) except: raise ### write information on png file ### _copylight = "Copyright (C) {} JibJab Studios - All Rights Reserved".format( _date.year) _img = Image.new('RGBA', (1920, 1080), (0, 0, 0, 0)) _slate_image = ImageDraw.Draw(_img) _type_shot_asset = ImageFont.truetype('/Library/Fonts/arial.ttf', 30) _type_copyright = ImageFont.truetype('/Library/Fonts/arial.ttf', 15) _type_task = ImageFont.truetype('/Library/Fonts/arial.ttf', 18) _slate_image.text((820, 1000), _shot_name, font=_type_shot_asset, fill=(255, 255, 255, 128)) _slate_image.text((780, 1060), _copylight, font=_type_copyright, fill=(255, 255, 255, 128)) _slate_image.text((910, 1035), "Task : {}".format(_task), font=_type_task, fill=(255, 255, 255, 128)) # _slate_image.text((1610, 1060), _review_file, font=_type_copyright, fill=(255,255,255,80)) _img.save(_png_file, 'PNG') ### convert uncomppresed file to h.264 #t = os.system("/Volumes/public/StoryBots/production/series/ask_the_storybots/03_shared_assets/01_cg/05_maya_tools/pipeline/module/ffmpeg/ffmpeg -y -i " + _full_temp_mov_file + " -vcodec libx264 -pix_fmt yuv420p -preset slower -crf 0 -vf eq=brightness=0.04 -g 1 -acodec copy " + self._file) t = os.system( "/Volumes/public/StoryBots/production/series/ask_the_storybots/03_shared_assets/01_cg/05_maya_tools/pipeline/module/ffmpeg/ffmpeg -y -i " + _full_temp_mov_file + " -i " + _png_file + " -vcodec libx264 -pix_fmt yuv420p -preset slow -crf 22 -filter_complex \"overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2\" -g 0 -acodec copy " + self._file) ###################################### #### This is RV open with mov file ### ###################################### _mov_path_RV, _mov_file_RV = os.path.split(self._file) os.chdir(_mov_path_RV) subprocess.Popen(self._RV_path + _mov_file_RV, shell=True) if os.path.exists(_full_temp_mov_file): os.remove(_full_temp_mov_file) if os.path.exists(_png_file): os.remove(_png_file) except: pm.confirmDialog( title="Playblast Error", message= "Close your RV or deselect the file.\nYour file is being used from other application", defaultButton="Yes") raise # playblast -format avfoundation -sound "ATS_301_sq020_020" -sequenceTime 0 -clearCache 1 -viewer 1 -showOrnaments 0 -offScreen -fp 4 -percent 80 -compression "H.264" -quality 70 -widthHeight 1920 1080; #pm.showWindow( _window ) pm.headsUpDisplay('HUDCurrentFrame', edit=True, visible=False, section=5, block=1) # cmds.headsUpDisplay( 'HUDA', rem=True ) # cmds.headsUpDisplay( 'HUDB', rem=True ) # delete playblast window pm.deleteUI(_window) # revive HOD modes cmds.displayColor('headsUpDisplayValues', _labelColor, dormant=True) cmds.displayColor('headsUpDisplayLabels', _labelValue, dormant=True) map(lambda f: pm.headsUpDisplay(f, edit=True, visible=True), visibleHUDs)
def createProject(self, *args): newRoot = os.path.dirname( os.path.dirname(os.path.dirname(self.currentPath))) message = "Creating a new project in:\n\n" + newRoot + "\n\nEnter name:" projectName = cmds.promptDialog(title="New project", message=message, button=['OK', 'Cancel'], defaultButton='OK', text=cmds.optionMenu(self.menus[2], q=True, v=True), cancelButton='Cancel', dismissString='Cancel') if projectName == 'OK': if cmds.promptDialog(q=True, text=True) == "": print "Empty project name. Aborting." else: switchProjectDialog = cmds.confirmDialog( title='New Maya file', message='Create and open a new Maya file?', button=['Yes', "No new file for now"], defaultButton='OK', cancelButton="No new file for now", dismissString="No new file for now") newFolders = ["maya", "marvelous", "export", "comp"] newProjectPath = os.path.join( newRoot, cmds.promptDialog(q=True, text=True)) for folder in newFolders: projectSubfolders = os.path.join(newProjectPath, folder) if not os.path.exists(projectSubfolders): os.makedirs(projectSubfolders) print "Creating new folder: ", projectSubfolders if switchProjectDialog == "Yes": print 'Creating new Maya file' workspacePath = os.path.join(newProjectPath, "maya") folderPath = os.path.join(workspacePath, "scenes") fileName = cmds.promptDialog(q=True, text=True) + "_v01.ma" mel.eval('setProject \"' + workspacePath.replace('\\', r'\\') + '\"') print "Switching to workspace: ", workspacePath for file_rule in cmds.workspace(query=True, fileRuleList=True): if file_rule == "images" or file_rule == "sourceImages" or file_rule == "fileCache" or file_rule == "scene": file_rule_dir = cmds.workspace( fileRuleEntry=file_rule) maya_file_rule_dir = os.path.join( workspacePath, file_rule_dir) if not os.path.exists(maya_file_rule_dir): os.makedirs(maya_file_rule_dir) cmds.file(new=True, force=True) cmds.file(folderPath, rename=os.path.join(folderPath, fileName)) cmds.file(f=True, type="mayaAscii", save=True)
def something(self): cmds.confirmDialog(title=u'提示', message=u'请转换到 Arnold 渲染器!', button=u'了解') pass