def graphFilterCore(attr='', panel=''): '''\n adds/clears filters for the default graphEditor ''' # check for any filters currently being used c = cmds.outlinerEditor(panel + 'OutlineEd', q=True, af=True) cf = '' # if attrs arg is not empty execute, else delete filters reset filter to None if attr != '': # make new filter f = cmds.itemFilterAttr(bn=attr) # if a filter is already being used merge new/current #else use new filter if c != '0': # unify new/current filter cf = cmds.itemFilterAttr(un=[c, f]) cmds.delete(c) # set unified filter cmds.outlinerEditor(panel + 'OutlineEd', e=True, af=cf) else: # set new filter cmds.outlinerEditor(panel + 'OutlineEd', e=True, af=f) else: if c != '0': # clear all user filters cmds.delete(c) # reset filters to None cmds.outlinerEditor(panel + 'OutlineEd', e=True, af=0)
def channelBox_Filter_Items(box): with sysCmd.Undo(0): filters = [] names = [] for f in box.filter_items: if f == "attr_userDefined": user_cb = cmds.listAttr(ud=1, cb=1) user_kv = cmds.listAttr(ud=1, k=1, v=1) if user_cb: names += user_cb if user_kv: names += user_kv elif f == "attr_translate": names.append("translateX") names.append("translateY") names.append("translateZ") elif f == "attr_rotate": names.append("rotateX") names.append("rotateY") names.append("rotateZ") elif f == "attr_scale": names.append("scaleX") names.append("scaleY") names.append("scaleZ") else: filters.append(f.split("_")[-1]) if len(filters) == 0 and len(names) == 0: cmds.channelBox(box.channelbox, e=1, update=1) return _f = [] # create the actual filters if "animCurve" in filters: _f.append(cmds.itemFilterAttr(hasCurve=1)) if "expression" in filters: _f.append(cmds.itemFilterAttr(hasExpression=1)) if "drivenKey" in filters: _f.append(cmds.itemFilterAttr(hasDrivenKey=1)) if "scaleRotateTranslate" in filters: _f.append(cmds.itemFilterAttr(scaleRotateTranslate=1)) if names: _f.append(cmds.itemFilterAttr(byNameString=names)) destination = _f[0] odd = len(_f) % 2 # determines odd/even number loops = len(_f) / 2 + (1 if odd else 0) for i in range(loops): # create union filters index_1 = i * 2 index_2 = i * 2 + 1 use_last = odd and i + 1 == loops destination = cmds.itemFilterAttr(union=(_f[index_1], _f[index_2] if not use_last else destination)) box.filter = destination cmds.itemFilterAttr(box.filter, e=1, negate=box.saved_states["invertShown"][0]) cmds.channelBox(box.channelbox, e=1, attrFilter=box.filter, update=1) for f in _f: cmds.delete(f)
def channelBox_filterAttrs(box): with sysCmd.Undo(0): names = [] for key, value in box.filter_attrs.iteritems(): if value: names.append(key) box.filter = cmds.itemFilterAttr(byNameString=names, negate=box.saved_states["invertShown"][0]) cmds.channelBox(box.channelbox, e=1, attrFilter=box.filter, update=1)
def filterChannels(channels): try: mc.delete(ATTR_FILTER_NAME) except:pass try: mc.delete(OBJ_FILTER_NAME) except:pass channels = list(set(channels)) channelFilter = mc.itemFilterAttr(ATTR_FILTER_NAME, byNameString=channels, classification='user') mc.outlinerEditor('graphEditor1OutlineEd', edit=True, attrFilter=channelFilter)
def filterChannels(channels): try: mc.delete(ATTR_FILTER_NAME) except: pass try: mc.delete(OBJ_FILTER_NAME) except: pass channels = list(set(channels)) channelFilter = mc.itemFilterAttr(ATTR_FILTER_NAME, byNameString=channels, classification='user') mc.outlinerEditor('graphEditor1OutlineEd', edit=True, attrFilter=channelFilter)
def UIButton_Filter(self, iIndex, sSide, *args): # Re-Select Face Control sModel = cmds.button('bChar2', q=True, l=True) if sModel in self.aFaces: self.iChar = self.aFaces.index(sModel) cmds.select(self.aPuppet[self.iChar], r=True) ChannelBoxColourFaceTool.main() K = cmds.getModifiers() if K == 0: self.aActiveButtons = [] b = self.dFilterList[self.aCategoryList[iIndex]][sSide] # Logic to set self.aActiveButtons for UI colour and filter objects if K in [0, 8]: self.colourTweak = 0 if b[-1] == 'B': if b[:-1] + 'B' in self.aActiveButtons: self.aActiveButtons.remove(b) elif b[:-1] + 'R' in self.aActiveButtons: self.aActiveButtons.remove( self.dFilterList[self.aCategoryList[iIndex]]['R']) self.aActiveButtons.append( self.dFilterList[self.aCategoryList[iIndex]]['B']) elif b[:-1] + 'L' in self.aActiveButtons: self.aActiveButtons.remove( self.dFilterList[self.aCategoryList[iIndex]]['L']) self.aActiveButtons.append( self.dFilterList[self.aCategoryList[iIndex]]['B']) else: self.aActiveButtons.append( self.dFilterList[self.aCategoryList[iIndex]]['B']) elif b[-1] == 'R': if b[:-1] + 'B' in self.aActiveButtons: self.aActiveButtons.remove( self.dFilterList[self.aCategoryList[iIndex]]['B']) self.aActiveButtons.append( self.dFilterList[self.aCategoryList[iIndex]]['R']) elif b[:-1] + 'R' in self.aActiveButtons: self.aActiveButtons.remove( self.dFilterList[self.aCategoryList[iIndex]]['R']) elif b[:-1] + 'L' in self.aActiveButtons: self.aActiveButtons.remove( self.dFilterList[self.aCategoryList[iIndex]]['L']) self.aActiveButtons.append( self.dFilterList[self.aCategoryList[iIndex]]['R']) else: self.aActiveButtons.append( self.dFilterList[self.aCategoryList[iIndex]]['R']) else: # if b[-1] == 'L': if b[:-1] + 'B' in self.aActiveButtons: self.aActiveButtons.remove( self.dFilterList[self.aCategoryList[iIndex]]['B']) self.aActiveButtons.append( self.dFilterList[self.aCategoryList[iIndex]]['L']) elif b[:-1] + 'R' in self.aActiveButtons: self.aActiveButtons.remove( self.dFilterList[self.aCategoryList[iIndex]]['R']) self.aActiveButtons.append( self.dFilterList[self.aCategoryList[iIndex]]['L']) elif b[:-1] + 'L' in self.aActiveButtons: self.aActiveButtons.remove( self.dFilterList[self.aCategoryList[iIndex]]['L']) else: self.aActiveButtons.append( self.dFilterList[self.aCategoryList[iIndex]]['L']) else: if self.colourTweak: # 0 = without Tweaks / 1 = with tweaks. self.colourTweak = 0 else: self.colourTweak = 1 #print self.aActiveButtons ### Create a List of Keywords to be Filtered. ### self.oFilter = cmds.itemFilterAttr( bns='Seach for an attr that NEVER EXIST') if self.aActiveButtons: for a in self.aActiveButtons: aKeyWords = self.dFilterList[a[1:-1]]['KeyWords'] aKeyWordList = cmds.listAttr(r=True, st=aKeyWords) or [] aExcept = self.dFilterList[a[1:-1]]['Except'] for k in aKeyWordList[:]: iRemove = 0 if K in [ 0, 8 ]: # Remove Tweaks unless Modifiers are activated. if 'tweak' in k.lower(): iRemove = 1 else: if self.colourTweak == 0: if 'tweak' in k.lower(): iRemove = 1 if 'upper' in a.lower(): if not 'upper' in k.lower(): iRemove = 1 if 'lower' in a.lower(): if not 'lower' in k.lower(): iRemove = 1 if aExcept: for e in aExcept: if e.lower() in k.lower(): aKeyWordList.remove(k) if not a[-1] == 'B': if not k[-1] == sSide: iRemove = 1 if 'fr_' in k.lower(): iRemove = 0 if iRemove: if k in aKeyWordList: aKeyWordList.remove(k) oKeyWordList = cmds.itemFilterAttr(bns=aKeyWordList) self.oFilter = cmds.itemFilterAttr(union=(self.oFilter, oKeyWordList)) if self.aActiveButtons == []: self.oFilter = 0 cmds.channelBox('mainChannelBox', e=True, attrFilter=self.oFilter) self.UIRefresh()
def getShapeNodes(obj): howManyShapes = 0 getShape = maya.cmds.listRelatives(obj, shapes=True) if(getShape == None): print 'ERROR:: getShapeNodes : No Shape Nodes Connected to ' + obj + ' /n' else: howManyShapes = len(getShape[0]) return (getShape, howManyShapes) print getShapeNodes('Plumette01__geo__rig__puppet__C_body_CTL_Plot_CamAim_Anim')[0][0] # Arrow Shapes maya.cmds.curve(d=1, p=[(-0.5, 0, 0),(-0.5, 0, 2),(-2, 0, 2),(0, 0, 4),(2, 0, 2),(0.5, 0, 2),(0.5, 0, 0),(0.5, 0, -2),(2, 0, -2),(0, 0, -4),(-2, 0, -2),(-0.5, 0, -2),(-0.5, 0, 0)]); maya.cmds.curve(d=1, p=[(-4, 0, 0),(-2, 0, -1.5),(-2, 0, -0.5),(-0.5, 0, -0.5),(-0.5, 0, -2),(-1.5, 0, -2),(0, 0, -4),(1.5, 0, -2),(0.5, 0, -2),(0.5, 0, -0.5),(2, 0, -0.5),(2, 0, -1.5),(4, 0, 0),(2, 0, 1.5),(2, 0, 0.5),(0.5, 0, 0.5),(0.5, 0, 2),(1.5, 0, 2),(0, 0, 4),(-1.5, 0, 2),(-0.5, 0, 2),(-0.5, 0, 0.5),(-2, 0, 0.5),(-2, 0, 1.5),(-4, 0, 0)]); maya.cmds.curve(d=1, p=[(-0.5, 2.5, 0),(-0.5, 2.449, 2),(-2, 2.25, 2),(0, 0, 4),(2, 2.25, 2),(0.5, 2.449, 2),(0.5, 2.5, 0),(0.5, 2.449, -2),(2, 2.25, -2),(0, 0, -4),(-2, 2.25, -2),(-0.5, 2.449, -2),(-0.5, 2.5, 0)]); maya.cmds.curve(d=1, p=[(-4, 0, 0),(-2, 3.146, -1.5),(-2, 3.464, -0.5),(-0.5, 3.9680, -0.5),(-0.5, 3.464, -2),(-1.5, 3.146, -2),(0, 0, -4),(1.5, 3.146, -2),(0.5, 3.464, -2),(0.5, 3.968, -0.5),(2, 3.464, -0.5),(2, 3.146, -1.5),(4, 0, 0),(2, 3.146, 1.5),(2, 3.464, 0.5),(0.5, 3.968, 0.5),(0.5, 3.464, 2),(1.5, 3.146, 2),(0, 0, 4),(-1.5, 3.146, 2),(-0.5, 3.464, 2),(-0.5, 3.968, 0.5),(-2, 3.464, 0.5),(-2, 3.146, 1.5),(-4, 0, 0)]); ## Re-Ordering for p in aPreferenceOrder: if p in aKeys: aReorder[aKeys.index(p)] = iReorder iReorder +=1 for i in range(0, len(aReorder)): if aReorder[i] == -1: aReorder[i] = iReorder iReorder +=1 aKeys = [x for (y,x) in sorted(zip(aReorder, aKeys))] # Sound setSoundDisplay Audio01_:main_:audioTrack 1; setAttr "Audio01_:main_:audioTrack.offset" 1001; # ClipBoard import pygtk pygtk.require('2.0') import gtk clipboard = gtk.clipboard_get() clipboard.set_text('Shit!') clipboard.store() # Filter attr in channelBox aKeyWords = ['*nose*','*lip*'] aList = cmds.listAttr(r = True, st = aKeyWords) or [] oFilter = cmds.itemFilterAttr(bns = aList) cmds.channelBox('mainChannelBox', e = True, attrFilter = oFilter) # Apply list to translation cmds.setAttr("TargetFollowOffset.rotate" , *[1,1,0] ) ### Get Selection as a list def ListSelection(): ''' List section into an array of strings''' return [str(o) for o in cmds.ls(sl = True, o = True)] oSel = ListSelection() # Get Current Selected Curve aObjList = [str(s) for s in cmds.selectionConnection('graphEditor1FromOutliner', q = True, object = True)] aCurveList = [str(s) for s in cmds.keyframe(query = True, name = True)] # Get Children oChildren = [str(o) for o in cmds.listRelatives('XXXXXX', c = True)] cmds.rename() # Split example print 'test:ttt:zzz:ccc'.split(':', 2 )[2] # Apply transform cmds.setAttr('%s.translate'%sPivotAni, *[0,0,0]) cmds.setAttr('%s.rotate'%sPivotAni, *[0,0,0]) # Get Keyable channels cmds.listAttr(oSel[0], k = True) # List all windows oWindows = cmds.lsUI( windows=True ) # Apply Const on Non Locked Tx~Rz def Custom_2Const(oSel,sConstName, iMo = False, aSkipTrans = [], aSkipRot = []): aAxis = ['tx','ty','tz','rx','ry','rz'] for i in range(0,6): v = cmds.getAttr(str(oSel[0])+'.%s'%aAxis[i], l = True) if v: if i < 3: if not aAxis[i][-1] in aSkipTrans: aSkipTrans.append(aAxis[i][-1]) else: if not aAxis[i][-1] in aSkipRot: aSkipRot.append(aAxis[i][-1]) cmds.parentConstraint(oSel[-1], oSel[0], st = aSkipTrans, sr = aSkipRot, n = sConstName, mo = iMo) # Returns Non Locked Axis aAdj = ['z','y','x'] for i in range(0,3): if aSkipRot: if aAdj[i] in aSkipRot: aAxis.remove('r%s'%aAdj[i]) if aSkipTrans: if aAdj[i] in aSkipTrans: aAxis.remove('t%s'%aAdj[i]) return aAxis # List files and directories aSceneFiles = os.listdir(sFullPath) # Find keyable attributes print cmds.listAttr(oSel[0], keyable = True) # Check if path exists import os def CreateTxtFilePath(sPath = '/net/homes/dyabu/Personal/TimeStamp/TimeStamp.txt'): if os.path.exists(sPath): print 'yes' # Get Local Transform Values aTrans = cmds.xform(oSel, q = True, translation = True) aRot = cmds.xform(oSel, q = True, ro = True, os = True) ### To get Scene File Path cmds.file( q = True, sn = True) ### In view Message self.PrintOnScreen = ['a7a8af', 'Playblast done [%s]'%sView, 0x6b6c75] cmds.inViewMessage(amg = '<text style="color:#%s";>%s</text>'%(aPrint[0], aPrint[1]), pos = 'topCenter', fade = True, fts = 10, ft = 'arial', bkc = aPrint[2]) ### Display Message Box def MessageBox(Message): '''Displaying Entered Message as Popup ''' oWindow = cmds.window(title = 'Message Box', s = False) if cmds.windowPref(oWindow, exists = True): cmds.windowPref(oWindow, remove = True) cmds.columnLayout(adjustableColumn = True) cmds.text('\n\t%s\t\n' % Message, bgc = (.25,.25,.25),enableBackground = False) cmds.button(label = 'Close', command = ('cmds.deleteUI(\"'+oWindow+'\",window = True)'), bgc = (.2,.2,.2),enableBackground = False) cmds.setParent('..') cmds.showWindow(oWindow) # Print Methods import maya.mel as mel dir(mel) # To Get the creation time of a file from datetime import datetime import os tCreateTime = os.path.getmtime('/job/nysm2/film/bt163/bt163_0485/work/dyabu/maya/scenes/bt163_0485_DY.v001.01.Ohoh.0002.mb') print datetime.fromtimestamp(tCreateTime).strftime('%Y-%m-%d %H:%M:%S') ### Modifiers K = cmds.getModifiers() sMenu = ''' ----- ALT [8] ----- CTL [4] ----- SFT [1] ----- CTL + SFT [5] ----- ALT + SFT [9] ----- CTL + ALT [12] ----- CTL + ALT + SFT [13]''' ### fill with 0 in a string. ex "003" '1'.zfill(3) ### Prompt Dialog Box o = cmds.confirmDialog( title='Confirm', message='Are you sure?', button=['Yes','No','Maybe','Not Sure'], defaultButton='Yes', cancelButton='No', dismissString='No' , bgc = [1.2,1.2,1.2]) ### Prompt Enter Box def EnterBox(): oResult = cmds.promptDialog( title='Rename Object', message='Enter Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if oResult == 'OK': sText = cmds.promptDialog(query=True, text=True) return sText else: return None ### Change all non alpha numeric to '_' def Underscore(sString): if sString[0].isdigit(): sString = '_'+sString sNewString ='' for s in sString: if s.isalnum(): sNewString += s else: sNewString += '_' print sNewString Underscore('a#$^fgg1') ### Current Frame iFrame = int(cmds.currentTime(q = True)) ### In/Out Range iIn = int(cmds.playbackOptions(q = True, minTime = True)) iOut = int(cmds.playbackOptions(q = True, maxTime = True)) # Get List of Audios in the scene. aAudio = [str(a) for a in cmds.ls(typ = 'audio')] # Get Currently Active Sound aPlayBackSlider = mel.eval('$tmpVar=$gPlayBackSlider') sAudio = cmds.timeControl(aPlayBackSlider, q = True, s = True) ### Date Examples from datetime import datetime from datetime import timedelta # String to daytime def MondayFinder(sYear, sMonth, sDate): #date_object = datetime.strptime('05 12 2015 1:33PM', '%b %d %Y %I:%M%p') oEntered = datetime.strptime('%s %s %s'%(sMonth, sD), '%m %d %Y') #print date_object.weekday() oMonday = date_object - timedelta(days = date_object.weekday()) print newDate.weekday() ### Get Current SoundTrack aPlayBackSliderPython = maya.mel.eval('$tmpVar=$gPlayBackSlider') sSound = cmds.timeControl( aPlayBackSliderPython, q = True, sound = True) print sSound if sSound: iOffset = cmds.getAttr(sSound+'.offset') print cmds.sound( sSound, q = True, f = True ) print iOffset ### Open Folder cmd1 ='nautilus /net/homes/dyabu/Desktop/Shots/tu125250/Rv' os.system(cmd1) ### User Define Enter Box oClick = cmds.promptDialog( title='Rename Object', message='Enter Shot : ( ex. fs150 )', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if oClick == 'OK': sShot = cmds.promptDialog(query=True, text=True) ### Get Current Camera ### def getCamera(): oCamera = '' oPanel = cmds.getPanel(wf = True) if 'modelPanel' in oPanel: oCamera = cmds.modelEditor(oPanel, q = True, camera = True) return str(oCamera) ### Warning Message cmds.warning( 'Enter something here' ) ### Rename objects cmds.rename(o, sName) ### Get User Name import getpass print getpass.getuser() ### Write File oRvFile = open(sPath, 'w') oRvFile.write(sContent) oRvFile.close() ### Read File oRvFile = open(sPath, 'r') aLines = oRvFile.readlines() oRvFile.close() for line in aLines: sLine = line.strip() ### Get Active Panel sCurrentPanel = cmds.getPanel(underPointer = True) if sCurrentPanel == None: sCurrentPanel = cmds.getPanel(withFocus = True) tCurrentPanel = cmds.getPanel(typeOf = sCurrentPanel) if tCurrentPanel == 'modelPanel': print tCurrentPanel # Execute Python File #import sys #sys.path.append('/home/ericb/GIT_DEV/ebLabs-workshop/whisKEY2') import ebLabs_whisKEY reload(ebLabs_whisKEY) ebLabs_whisKEY.window.load() # Execute External Python file import sys import os def ExecuteExternal(Mod): sFile = os.path.basename( Mod ) aFiles = sFile.split( '.' ) sDir = os.path.dirname( Mod ) if( os.path.exists( sDir ) ): aPaths = sys.path iCheck = 0 for p in aPaths: if(sDir == p): iCheck = 1 if not iCheck: print iCheck sys.path.append( sDir ) exec( 'import ' + aFiles[0] ) in globals() exec( 'reload( ' + aFiles[0] + ' )' ) in globals() ExecuteExternal('/net/homes/dyabu/maya/2013.5-x64/scripts/HelloWorld.py') ### Linux Run Command def Execute(cmd2): global aMainPath if cmd2: if aMainPath[2] == 'homes': MessageBox('Please open your scene first.') else: cmd1 ='go %s'%aMainPath[2] os.system(cmd1) os.system(cmd2) ### Partial Usage ### from functools import partial cmds.button( .... command = partial(defFunction, arg1, arg2) ...) # in a button # and/or oCMD = cmds.optionMenu( "CustomOptionMenu", label = "Version ", w = fWidth, cc = partial(self.defFunction)) def defFunction(arg1, arg2, *args): print 1 ### Create Hotkey ### def createHotkey(command, name, description=''): ''' Open up the hotkey editor to create a hotkey from the specified command ''' mel.eval('hotkeyEditor') cmds.textScrollList('HotkeyEditorCategoryTextScrollList', edit=True, selectItem='User') mel.eval('hotkeyEditorCategoryTextScrollListSelect') mel.eval('hotkeyEditorCreateCommand') cmds.textField('HotkeyEditorNameField', edit=True, text=name) cmds.textField('HotkeyEditorDescriptionField', edit=True, text=description) cmds.scrollField('HotkeyEditorCommandField', edit=True, text=command) mel.eval('hotkeyEditorAcceptCommand') mel.eval('hotkeyEditorSave') ### Create Shaders and assign to an object. def Colour_The_Balls(): # Create Shaders aColourList = [ [0 ,[ 0.39 , 0.86 , 1.0 ]], [1 ,[ 0.26 , 1.0 , 0.64 ]], [2 ,[ 1.0 , 0.69 , 0.69 ]], [3 ,[ 0.19 , 0.63 , 0.63 ]], [4 ,[ 0.89 , 0.67 , 0.47 ]], [5 ,[ 0.41 , 0.63 , 0.19 ]], [6 ,[ 0 , 0.6 , 0.33 ]], [7 ,[ 1.0 , 0 , 0 ]], [8 ,[ 0 , 1.0 , 0 ]], [9 ,[ 0 , 0 , 0 ]], ] for colour in aColourList: oMaterial = 'PivotColour_%s' % colour[0] oShader = oMaterial+'_SDR' if not cmds.objExists(oMaterial): cmds.shadingNode('lambert', n = oMaterial, asShader = 1, ) cmds.sets(oMaterial, renderable = True, noSurfaceShader = True, empty = True, name = oShader) cmds.connectAttr(oMaterial+'.outColor', oShader+'.surfaceShader', f = True) cmds.setAttr( "%s.color"%oMaterial, type = 'double3', *colour[1]) cmds.setAttr( "%s.incandescence"%oMaterial, type = 'double3', *colour[1]) cmds.setAttr( "%s.ambientColor"%oMaterial, type = 'double3', *colour[1]) # Change the color of the Spheres. for i in range(0,len(GetExistingPivots())): sBall = 'PivotSphere_%s_Pivot' % i # Object Name print sBall cmds.sets( sBall, fe = 'PivotColour_%s_SDR' % i, e = True) ### Copy files in Python from shutil import copyfile copyfile(src, dst) ### Bake Animation ### import maya.mel as mel def SpeedUpBake_1_Store(sName): # store a temporary panel configuration. layout = cmds.panelConfiguration(l=sName, sc=0) evalStr = 'updatePanelLayoutFromCurrent "'+name+'"' mel.eval(evalStr) # switch to fast "hidden" layout evalStr = 'setNamedPanelLayout "Single Perspective View"' mel.eval(evalStr) perspPane = cmds.getPanel(vis=1) cmds.scriptedPanel('graphEditor1',e=1,rp=perspPane[0]) return sName def SpeedUpBake_2_Restore(sName): # restore the layout returned from makeHiddenLayout. evalStr = 'setNamedPanelLayout "'+sName+'"' mel.eval(evalStr) # now delete the old layout. killMe = cmds.getPanel(cwl=sName) cmds.deleteUI(killMe,pc=1) SpeedUpBake_1_Store('tempLayout') try: print 'do something' cmds.bakeResults(aFirst, t = (aRange[0],aRange[1]), simulation = True ) finally: SpeedUpBake_2_Restore('tempLayout') #ScriptJob example (ScriptJob : script must fishish executing completely in order for maya to respond.) def CB(callback): trans = set(cmds.ls(sl = True, type = 'transform')) if trans: cb = cmds.channelBox('mainChannelBox', q = True, sma = True) or [] if cb: callback([a+'.' +b for a in trans for b in cb]) else: objs = set(cmds.ls(sl = True)) - trans if objs: cmds.select(list(objs)) def temp(): res = [a+'.'+b for a in objs for b in cmds.channelBox('mainChannelBox', q = True, sma = True)or[]] cmds.select(list(trans)) callback(res) cmds.scriptJob(e = ('idle', temp), ro = True) def main(): def p(val): print val CB(p) print 'test'
def __init__(self, layout, menu_module, state_file, persistent_state): # PARAMETERS: # layout : The layout that contains this channel box, eg. cmds.frameLayout() # menu_module : String containing module name with menu variables, eg. "jtchannelBox_Menu_Default" # state_file : String containing file name for saved states - Does not have to exist, # eg. "jtchannelBox_State_Default" - Will be created alongside this script (same folder) # saveState : Boolean value whether to save the state to a file, if False you can specify state_file as "" # displayOptions : Array of 3 Boolean values for the following : [Show label on right click menu, # Hide unavailable items instead of disabling, Show Icons] def init_setup(box): # ---------------------------------------------------------------# # INIT : Restoring Serialized Settings # This is where any serialized values are restored when creating # the channel box # ---------------------------------------------------------------# try: # read the state file if it exists sysCmd.channelbox_pickle_read_state(box) except IOError: # create if it doesn't sysCmd.channelbox_pickle_write_state(box) for key, value in box.saved_states.iteritems(): # restore our channelbox states from saved data if value[1] == 1: if key == "hyperbolic": cmds.channelBox(box.channelbox, e=1, hyperbolic=value[0]) if key == "showNamespace": cmds.channelBox(box.channelbox, e=1, showNamespace=value[0]) if key == "assetsShowTop": cmds.channelBox(box.channelbox, e=1, containerAtTop=value[0]) if key == "changePrecision": cmds.channelBox(box.channelbox, e=1, pre=value[0]) if key == "fieldWidth": cmds.channelBox(box.channelbox, e=1, fieldWidth=value[0]) if key == "namesState": if value[0] == 1: cmds.channelBox(box.channelbox, e=1, ln=1, nn=1) elif value[0] == 2: cmds.channelBox(box.channelbox, e=1, ln=1, nn=0) else: cmds.channelBox(box.channelbox, e=1, ln=0, nn=0) if key == "speedState": if value[0] == 1: cmds.channelBox(box.channelbox, e=1, speed=0.1) elif value[0] == 2: cmds.channelBox(box.channelbox, e=1, speed=1) else: cmds.channelBox(box.channelbox, e=1, speed=10) if key == "manipsState": if value[0] == 1: cmds.channelBox(box.channelbox, e=1, useManips="none") elif value[0] == 2: cmds.channelBox(box.channelbox, e=1, useManips="invisible") else: cmds.channelBox(box.channelbox, e=1, useManips="standard") if self.saved_states["showIcons"][0]: cmds.formLayout(box.symbol_layout, e=1, m=1) for key in box.symbols: box.sym["update"](box, key) else: # don't need the layout taking up space if not drawing buttons cmds.formLayout(box.symbol_layout, e=1, m=0) # ---------------------------------------------------------------# # CORE SYSTEM : Modify at own risk # ---------------------------------------------------------------# with sysCmd.Undo(0): # prevents the creation of this UI being placed in the undo queue try: _menu = __import__(menu_module, globals(), locals(), [], -1) # __import__ used instead of import to allow module provided as string reload(_menu) except RuntimeError: cmds.error("Menu failed to load. Files are missing or parameters are set incorrectly. Exiting.") self.state_file = state_file # file containing menu states self.state_persist = persistent_state self.menus = _menu.menus # menu dict from given file self.sym = _menu.symbol_commands # dict containing commands for symbol buttons (icon bar) self.saved_states = _menu.saved_states # menu states from given file self.menu_jobs = _menu.jobIDs # script job IDs from given file self.filter = cmds.itemFilterAttr() # filter created within class as with self so everything can access it self.filter_items = [] # all-accessible filtered pre-defined attributes self.filter_attrs = {} # all-accessible filtered user-defined attributes # copy the default state of anything to be serialized for resetting later if user wants self.menu_default_states = {k: v for k, v in _menu.saved_states.iteritems() if v[1] == 1} self.symbols = {} # saved symbolButton elements for accessing later. # Layouts self.layout = cmds.formLayout(p=layout) # root layout containing all other layouts self.symbol_layout = cmds.formLayout( p=self.layout) # layout containing the 3 symbol buttons (manipulator, speed, hyperbolic) self.menubar_layout = cmds.menuBarLayout(p=self.layout) self.channelbox = cmds.channelBox(p=self.layout) cmds.formLayout(self.layout, e=1, attachForm=[ (self.symbol_layout, "top", 0), (self.symbol_layout, "right", 0), (self.channelbox, "right", 0), (self.channelbox, "bottom", 0), (self.channelbox, "left", 0), (self.menubar_layout, "left", 0), (self.menubar_layout, "right", 0)], attachControl=[ (self.menubar_layout, "top", 0, self.symbol_layout), (self.channelbox, "top", 0, self.menubar_layout)] ) # Initialize self.re_init = init_setup # For resetting attributes via menu. note: storing the function itself, not a result init_setup(self) channelbox_symbols(self) channelbox_setup(self, "Channels", "Edit")