def createIKCtrlsOnJnts(ikCrv, parentCtrl, size=1): ikCVNum = ll.getCurveCVCount(ikCrv) prev = parentCtrl for i in range(1, ikCVNum): clus = mc.cluster('%s.cv[%d]' % (ikCrv, i), n=parentCtrl.replace('masterctrl', 'ikClus%d') % i) cvPos = mc.xform('%s.cv[%d]' % (ikCrv, i), q=1, ws=1, t=1) mc.select(parentCtrl) meval('wireShape("plus")') ikCtrl = mc.rename(masterCtrl.replace('masterctrl', 'ikCtrl%d' % i)) mc.xform(ikCtrl, t=cvPos, ws=1) mc.scale(size, size, size, ikCtrl, ocp=1) mc.makeIdentity(ikCtrl, a=1, s=1) mc.parent(ikCtrl, parentCtrl) lsZeroOut(ikCtrl) ctrlPR = lsZeroOut(ikCtrl, 'PR') mc.addAttr(ikCtrl, ln='SPACE', at='bool', k=1) mc.setAttr(ikCtrl + '.SPACE', l=1) mc.addAttr(ikCtrl, ln='parent', at='float', dv=0, min=0, max=1, k=1) mc.addAttr(ikCtrl, ln='master', at='float', dv=1, min=0, max=1, k=1) mc.addAttr(ikCtrl, ln='world', at='float', dv=0, min=0, max=1, k=1) mc.parentConstraint(ikCtrl, clus) cons = mc.parentConstraint(prev, parentCtrl, ctrlPR, mo=1)[0] wal = mc.parentConstraint(cons, q=1, wal=1) if len(wal) > 1: mc.connectAttr(ikCtrl + '.parent', '%s.%s' % (cons, wal[0]), f=1) mc.connectAttr(ikCtrl + '.master', '%s.%s' % (cons, wal[1]), f=1) prev = ikCtrl
def createIKCtrlsOnJnts(ikCrv, parentCtrl, size=1): ikCVNum = ll.getCurveCVCount(ikCrv) prev=parentCtrl for i in range(1, ikCVNum): clus = mc.cluster('%s.cv[%d]'%(ikCrv, i), n=parentCtrl.replace('masterctrl','ikClus%d')%i) cvPos = mc.xform('%s.cv[%d]'%(ikCrv, i), q=1, ws=1, t=1) mc.select(parentCtrl) meval('wireShape("plus")') ikCtrl = mc.rename(masterCtrl.replace('masterctrl','ikCtrl%d'%i)) mc.xform(ikCtrl, t=cvPos, ws=1) mc.scale(size, size, size, ikCtrl, ocp=1) mc.makeIdentity(ikCtrl, a=1, s=1) mc.parent(ikCtrl, parentCtrl) lsZeroOut(ikCtrl) ctrlPR = lsZeroOut(ikCtrl, 'PR') mc.addAttr(ikCtrl, ln='SPACE', at='bool', k=1) mc.setAttr(ikCtrl+'.SPACE', l=1) mc.addAttr(ikCtrl, ln='parent', at='float', dv=0, min=0, max=1, k=1) mc.addAttr(ikCtrl, ln='master', at='float', dv=1, min=0, max=1, k=1) mc.addAttr(ikCtrl, ln='world', at='float', dv=0, min=0, max=1, k=1) mc.parentConstraint(ikCtrl, clus) cons = mc.parentConstraint(prev, parentCtrl, ctrlPR, mo=1)[0] wal = mc.parentConstraint(cons, q=1, wal=1) if len(wal) > 1: mc.connectAttr(ikCtrl+'.parent', '%s.%s'%(cons, wal[0]), f=1) mc.connectAttr(ikCtrl+'.master', '%s.%s'%(cons, wal[1]), f=1) prev=ikCtrl
def snapToPosition(sourceObj, targetObj): ''' wrapper function for abRTSnapToPosition snaps targetObj to sourceObj ''' meval('abRTSnapToPosition("%(sourceObj)s", "%(targetObj)s")' % locals())
def test_setitem_int(self): meval("int $melGlobals_test_setitem_int1") lang.melGlobals["melGlobals_test_setitem_int1"] = 37 self.assertEqual(meval("melGlobals_test_int_getter($melGlobals_test_setitem_int1)"), 37) lang.melGlobals["$melGlobals_test_setitem_int1"] = 47 self.assertEqual(meval("melGlobals_test_int_getter($melGlobals_test_setitem_int1)"), 47)
def test_setitem_str(self): meval("global string $melGlobals_test_setitem_str1") lang.melGlobals["melGlobals_test_setitem_str1"] = "monkey" self.assertEqual(meval("melGlobals_test_str_getter($melGlobals_test_setitem_str1)"), "monkey") lang.melGlobals["$melGlobals_test_setitem_str1"] = "apple" self.assertEqual(meval("melGlobals_test_str_getter($melGlobals_test_setitem_str1)"), "apple")
def movePolysFromObj(): ''' # 1. Select faces # 2. Shift-select targetObj # 3. Run ''' selFaces = mc.ls(os=1, fl=1)[:-1] selFacesIds = [int(faceName.split('[')[1][:-1]) for faceName in selFaces] # target object is the last selected item targetObj = mc.ls(os=1, fl=1)[-1] targetObjParent = mc.listRelatives(targetObj, p=1)[0] # delete the parentConstraint if necessary targetObjChildren = mc.listRelatives(targetObj, c=1, type='parentConstraint') if not targetObjChildren == None: mc.delete(targetObjChildren) srcObj = selFaces[0].split('.')[0] tempObj = mc.duplicate(srcObj, n='tempObj')[0] mc.delete(selFaces) facesToCopy = [faceName.replace(srcObj, tempObj) for faceName in selFaces] mc.select(facesToCopy, r=1) meval('InvertSelection;') mc.delete() combinedGeo = mc.polyUnite(tempObj, targetObj, ch=0, n='combinedGeo')[0] mc.rename(combinedGeo, targetObj) mc.parent(targetObj, targetObjParent) mc.polyMergeVertex(targetObj, d=0.001, ch=0) mc.delete(tempObj) mc.select(srcObj, r=1)
def doDuplicateExtract(): selection = m.ls(sl=True, l=True) if not selection: raise RuntimeError('Bad selection. Select some polygons.') components = defaultdict(list) for s in selection: split = s.split('.') if (len(split) != 2) or (not split[1].startswith('f[')): raise RuntimeError('Bad selection. Only polygons allowed: {}'.format(s)) components[split[0]].append(split[1]) originalObjects = components.keys() newObjects = [] wholeDuplicatedObjects = [] for obj in originalObjects: dup = m.duplicate(obj)[0] newObjects.append(dup) newSelection = [dup + '.' + c for c in components[obj]] m.select(newSelection, r=True) meval('InvertSelection') if m.ls(sl=True): m.delete() else: wholeDuplicatedObjects.append(obj) m.select(selection, r=True) return newObjects, wholeDuplicatedObjects
def fxCombine(merge=False): targets = m.ls(sl=True, l=True) if not targets: return parent = m.listRelatives(targets[0], p=True, pa=True) try: combineResult = m.polyUnite(targets) except RuntimeError: m.error('Invalid selection for combine operation.') return if parent: combineResult = m.parent(combineResult[0], parent[0]) m.delete(combineResult[0], ch=True) for t in targets: if m.objExists(t): m.delete(t) finalObject = m.rename(combineResult[0], getShortName(targets[0])) m.select(finalObject) if merge: meval('performPolyMerge 0') m.polyOptions(finalObject, displayBorder=True, sizeBorder=4) m.select(finalObject)
def bundleRib(frame): from time import time import maya.cmds as m from maya.mel import eval as meval print "=" * 80 trib = time() m.currentTime(frame, e=1) m.setAttr("defaultRenderGlobals.animation", l=0) m.setAttr("defaultRenderGlobals.animation", 1) meval("rmanDisconnectDstAttrs defaultRenderGlobals.startFrame;") m.setAttr('defaultRenderGlobals.startFrame', l=0) m.setAttr('defaultRenderGlobals.startFrame', frame) meval("rmanDisconnectDstAttrs defaultRenderGlobals.endFrame;") m.setAttr('defaultRenderGlobals.endFrame', l=0) m.setAttr('defaultRenderGlobals.endFrame', frame) m.setAttr("renderManRISGlobals.rman__riopt__Hider_incremental", 1) meval('optionVar -intValue "rmanPreviewDisplayStyle" 2;') # meval('renderManRender(640,480,1,1,"camera")') meval('setCurrentRenderer("renderManRIS");') meval('renderManExecCmdlineRender("", 1, 1, 0)') trib = time() - trib print "=" * 80 print "Time to export rib:", trib
def movePolysFromObj(): """ # 1. Select faces # 2. Shift-select targetObj # 3. Run """ selFaces = mc.ls(os=1, fl=1)[:-1] selFacesIds = [int(faceName.split("[")[1][:-1]) for faceName in selFaces] # target object is the last selected item targetObj = mc.ls(os=1, fl=1)[-1] targetObjParent = mc.listRelatives(targetObj, p=1)[0] # delete the parentConstraint if necessary targetObjChildren = mc.listRelatives(targetObj, c=1, type="parentConstraint") if not targetObjChildren == None: mc.delete(targetObjChildren) srcObj = selFaces[0].split(".")[0] tempObj = mc.duplicate(srcObj, n="tempObj")[0] mc.delete(selFaces) facesToCopy = [faceName.replace(srcObj, tempObj) for faceName in selFaces] mc.select(facesToCopy, r=1) meval("InvertSelection;") mc.delete() combinedGeo = mc.polyUnite(tempObj, targetObj, ch=0, n="combinedGeo")[0] mc.rename(combinedGeo, targetObj) mc.parent(targetObj, targetObjParent) mc.polyMergeVertex(targetObj, d=0.001, ch=0) mc.delete(tempObj) mc.select(srcObj, r=1)
def setupScene(): if rad: m.setAttr("perspShape.farClipPlane", 1000000) meval('source createPrefWndUI; changeLinearUnit("meter")') # force bg gradient all the time! (maya doesnt save the prefs for it!) meval('displayPref -displayGradient true;')
def setupRISGlobals(): meval('source "renderManNodes";rmanCreateGlobals') m.setAttr("renderManRISGlobals.rman__toropt___lazyRibGen",0) # prevent crash in the farm if using Render -batchcontext if m.objExists( 'renderManRISGlobals.spoolingBatchContext' ): m.deleteAttr('renderManRISGlobals.spoolingBatchContext') if m.objExists( 'renderManRISGlobals.spoolingBatchContext' ): m.deleteAttr('renderManRISGlobals.spoolingBatchContext')
def bundleLoad(gafferNodes, sceneName='bundle'): print "__progressStep__load__" import os, sys from time import time import maya.cmds as m from maya.mel import eval as meval t = time() meval('setCurrentRenderer("renderManRIS");') # meval('renderManExecCmdlineRender("", 1, 1, 0);') def _gafferBundle_(): import traceback import genericAsset genericAsset.hostApp("maya") import assetUtils print gafferNodes nodes = eval(gafferNodes) print nodes[0]['op'].path print nodes[0]['op'].data for node in m.ls("|SAM_*"): m.setAttr("%s.visibility" % node, 0) for node in nodes: print "=" * 80 print node['op'].path print "-" * 80 try: node['op'].hostApp('maya') ns = node['op'].doesAssetExists() except: from pprint import pprint pprint(node['op'].data) sys.stdout.flush() traceback.print_exc(file=sys.stderr) raise (Exception('')) if not ns and node['enable']: node['op'].doImport() print "#" * 80 for n in ns: m.setAttr("%s.visibility" % n, int(node['enable'])) print "__progressStep__load__" m.file(rename="%s.ma" % sceneName) # m.file( force=True, type='mayaAscii', save=True ) _gafferBundle_() tbundle = time() - t print "=" * 80 print "Time to initialize maya:", sys.tmaya print "Time to construct bundle scene:", tbundle print "Total time before render:", tbundle + sys.tmaya print "=" * 80 print "__progressDone__load__"
def test_setitem_int(self): meval('int $melGlobals_test_setitem_int1') lang.melGlobals['melGlobals_test_setitem_int1'] = 37 self.assertEqual(meval('melGlobals_test_int_getter($melGlobals_test_setitem_int1)'), 37) lang.melGlobals['$melGlobals_test_setitem_int1'] = 47 self.assertEqual(meval('melGlobals_test_int_getter($melGlobals_test_setitem_int1)'), 47)
def test_setitem_str(self): meval('global string $melGlobals_test_setitem_str1') lang.melGlobals['melGlobals_test_setitem_str1'] = 'monkey' self.assertEqual(meval('melGlobals_test_str_getter($melGlobals_test_setitem_str1)'), 'monkey') lang.melGlobals['$melGlobals_test_setitem_str1'] = 'apple' self.assertEqual(meval('melGlobals_test_str_getter($melGlobals_test_setitem_str1)'), 'apple')
def makeIKStretchy(aJnts, aIkJnts, aFkJnts, ikCtrl, statCtrl, stretchTarget, grp, limbName): ''' ''' aJnts = formatStrArray(aJnts) aIkJnts = formatStrArray(aIkJnts) aFkJnts = formatStrArray(aFkJnts) meval('abRTMakeIKStretchy(%(aJnts)s, %(aIkJnts)s, %(aFkJnts)s, "%(ikCtrl)s", "%(statCtrl)s", "%(stretchTarget)s", "%(grp)s", "%(limbName)s")' % locals())
def set_project( shot, task = False): path = '{0}{1}/{2}/{3}'.format( '/jobs/tr/users/', os.getlogin(), shot[:-5], shot) if not task: path += '/trackwork/scenes/maya' else: path += '/animwork/maya' meval('setProject "{0}"'.format( path))
def run(deleteOriginals=True): newObjects, wholeDuplicatedObjects = doDuplicateExtract() if deleteOriginals: m.delete() if wholeDuplicatedObjects: m.delete(wholeDuplicatedObjects) meval('changeSelectMode -object') m.select(newObjects, r=True)
def setupScene(): meval( 'setProject "{}/fxpt/fx_texture_manager/tests/testMayaProject"'.format( getFxptLocation())) loadMayaScene( getFxptLocation() + '/fxpt/fx_texture_manager/tests/testMayaProject/scenes/testScene_01.mb' ) setFileNodeWithAbsPath() os.environ['FXPT_LOCATION'] = getFxptLocation()
def test_get_dict(self): self.assertEqual(lang.melGlobals.get_dict('melGlobals_test_get_dict'), None) self.assertEqual( lang.melGlobals.get_dict('melGlobals_test_get_dict', 'foo'), 'foo') meval('global int $melGlobals_test_get_dict = 3') self.assertEqual(lang.melGlobals.get_dict('melGlobals_test_get_dict'), 3) self.assertEqual( lang.melGlobals.get_dict('melGlobals_test_get_dict', 'foo'), 3)
def test_setitem_int(self): meval('int $melGlobals_test_setitem_int1') lang.melGlobals['melGlobals_test_setitem_int1'] = 37 self.assertEqual( meval('melGlobals_test_int_getter($melGlobals_test_setitem_int1)'), 37) lang.melGlobals['$melGlobals_test_setitem_int1'] = 47 self.assertEqual( meval('melGlobals_test_int_getter($melGlobals_test_setitem_int1)'), 47)
def test_setitem_str(self): meval('global string $melGlobals_test_setitem_str1') lang.melGlobals['melGlobals_test_setitem_str1'] = 'monkey' self.assertEqual( meval('melGlobals_test_str_getter($melGlobals_test_setitem_str1)'), 'monkey') lang.melGlobals['$melGlobals_test_setitem_str1'] = 'apple' self.assertEqual( meval('melGlobals_test_str_getter($melGlobals_test_setitem_str1)'), 'apple')
def test_get_dict(self): self.assertEqual(lang.melGlobals.get_dict('melGlobals_test_get_dict'), None) self.assertEqual(lang.melGlobals.get_dict('melGlobals_test_get_dict', 'foo'), 'foo') meval('global int $melGlobals_test_get_dict = 3') self.assertEqual(lang.melGlobals.get_dict('melGlobals_test_get_dict'), 3) self.assertEqual(lang.melGlobals.get_dict('melGlobals_test_get_dict', 'foo'), 3)
def makeIKStretchy(aJnts, aIkJnts, aFkJnts, ikCtrl, statCtrl, stretchTarget, grp, limbName): ''' ''' aJnts = formatStrArray(aJnts) aIkJnts = formatStrArray(aIkJnts) aFkJnts = formatStrArray(aFkJnts) meval( 'abRTMakeIKStretchy(%(aJnts)s, %(aIkJnts)s, %(aFkJnts)s, "%(ikCtrl)s", "%(statCtrl)s", "%(stretchTarget)s", "%(grp)s", "%(limbName)s")' % locals())
def bundleRender(frame, camera='camera'): print "__progressStep__IPR__" import os from time import time import maya.cmds as m from maya.mel import eval as meval import pymel.core as pm trender = time() name = os.path.basename(os.path.splitext(m.file(q=1, sn=1))[0]) if not name: name = 'untitled' m.currentTime(frame, e=1) camera = 'perspShape' # os.system('prman -progress -incremental 1 -d it %s/renderman/%s/rib/%04d/%04d.rib &' % ( m.workspace(q=1, rd=1), name, int(frame), int(frame)) ) meval('setCurrentRenderer("renderManRIS");') meval('rmanSetRenderViewCamera("%s")' % camera) m.setAttr("defaultRenderGlobals.animation", l=0) m.setAttr("defaultRenderGlobals.animation", 1) meval("rmanDisconnectDstAttrs defaultRenderGlobals.startFrame;") m.setAttr('defaultRenderGlobals.startFrame', l=0) m.setAttr('defaultRenderGlobals.startFrame', frame) meval("rmanDisconnectDstAttrs defaultRenderGlobals.endFrame;") m.setAttr('defaultRenderGlobals.endFrame', l=0) m.setAttr('defaultRenderGlobals.endFrame', frame) m.setAttr("renderManRISGlobals.rman__riopt__Hider_incremental", 1) # check if we have a camera: # if not m.ls('|SAM_camera*'): # m.select( [ x for x in m.ls('|SAM_*') if 'lighting' not in x ] ) # pm.viewFit( 'perspShape' ) # meval('rmanSetRenderViewCamera("persp");') meval('rmanRerenderStart(0)') trender = time() - trender print "__progressStep__IPR__" print "=" * 80 # print "Time to initialize maya:", tmaya # print "Time to construct bundle scene:", tbundle print "Time to start render:", trender print "=" * 80 print '__progressDone__IPR__'
def massCopySkinWeightsGo(): ''' select all destGeos, shift-select srcGeo, run ''' sel = mc.ls(os=True) destGeos = sel[:-1] srcGeo = sel[-1] srcSkn = meval('findRelatedSkinCluster %s' % srcGeo) for geo in destGeos: destSkn = meval('findRelatedSkinCluster %s' % geo) mc.copySkinWeights(ss=srcSkn, ds=destSkn, ia='oneToOne', sa='closestPoint', nm=1)
def test_get_int(self): meval("global int $melGlobals_test_get_int1") meval("$melGlobals_test_get_int1 = 37") self.assertEqual(lang.melGlobals.get("melGlobals_test_get_int1"), 37) meval("$melGlobals_test_get_int1 = 47") self.assertEqual(lang.melGlobals.get("$melGlobals_test_get_int1"), 47) meval("$melGlobals_test_get_int1 = 57") self.assertEqual(lang.MelGlobals.get("melGlobals_test_get_int1"), 57) meval("$melGlobals_test_get_int1 = 67") self.assertEqual(lang.MelGlobals.get("$melGlobals_test_get_int1"), 67)
def test_get_int_arr(self): meval("global int $melGlobals_test_get_int_arr1[]") meval("$melGlobals_test_get_int_arr1 = {1, 2}") self.assertEqual(lang.melGlobals.get("melGlobals_test_get_int_arr1"), [1, 2]) meval("$melGlobals_test_get_int_arr1 = {3, 4}") self.assertEqual(lang.melGlobals.get("$melGlobals_test_get_int_arr1"), [3, 4]) meval("$melGlobals_test_get_int_arr1 = {5, 6}") self.assertEqual(lang.MelGlobals.get("melGlobals_test_get_int_arr1"), [5, 6]) meval("$melGlobals_test_get_int_arr1 = {7, 8}") self.assertEqual(lang.MelGlobals.get("$melGlobals_test_get_int_arr1"), [7, 8])
def test_get_str_arr(self): meval('global string $melGlobals_test_get_str_arr1[]') meval('$melGlobals_test_get_str_arr1 = {"waldo", "funk"}') self.assertEqual(lang.melGlobals.get('melGlobals_test_get_str_arr1'), ["waldo", "funk"]) meval('$melGlobals_test_get_str_arr1 = {"marcy", "jazz"}') self.assertEqual(lang.melGlobals.get('$melGlobals_test_get_str_arr1'), ["marcy", "jazz"]) meval('$melGlobals_test_get_str_arr1 = {"may", "rock"}') self.assertEqual(lang.MelGlobals.get('melGlobals_test_get_str_arr1'), ["may", "rock"]) meval('$melGlobals_test_get_str_arr1 = {"marlene", "trip-hop"}') self.assertEqual(lang.MelGlobals.get('$melGlobals_test_get_str_arr1'), ["marlene", "trip-hop"])
def setUp(self): meval( """global proc int melGlobals_test_int_getter(int $inValue) { return $inValue; }""" ) meval( """global proc string melGlobals_test_str_getter(string $inValue) { return $inValue; }""" ) meval( """global proc int[] melGlobals_test_int_arr_getter(int $inValue[]) { return $inValue; }""" ) meval( """global proc string[] melGlobals_test_str_arr_getter(string $inValue[]) { return $inValue; }""" )
def test_getitem_str(self): meval('global string $melGlobals_test_getitem_str1') meval('$melGlobals_test_getitem_str1 = "waldo"') self.assertEqual(lang.melGlobals.get('melGlobals_test_getitem_str1'), 'waldo') meval('$melGlobals_test_getitem_str1 = "marcy"') self.assertEqual(lang.melGlobals.get('$melGlobals_test_getitem_str1'), 'marcy') meval('$melGlobals_test_getitem_str1 = "may"') self.assertEqual(lang.MelGlobals.get('melGlobals_test_getitem_str1'), 'may') meval('$melGlobals_test_getitem_str1 = "marlene"') self.assertEqual(lang.MelGlobals.get('$melGlobals_test_getitem_str1'), 'marlene')
def test_get_int_arr(self): meval('global int $melGlobals_test_get_int_arr1[]') meval('$melGlobals_test_get_int_arr1 = {1, 2}') self.assertEqual(lang.melGlobals.get('melGlobals_test_get_int_arr1'), [1, 2]) meval('$melGlobals_test_get_int_arr1 = {3, 4}') self.assertEqual(lang.melGlobals.get('$melGlobals_test_get_int_arr1'), [3, 4]) meval('$melGlobals_test_get_int_arr1 = {5, 6}') self.assertEqual(lang.MelGlobals.get('melGlobals_test_get_int_arr1'), [5, 6]) meval('$melGlobals_test_get_int_arr1 = {7, 8}') self.assertEqual(lang.MelGlobals.get('$melGlobals_test_get_int_arr1'), [7, 8])
def test_get_int(self): meval('global int $melGlobals_test_get_int1') meval('$melGlobals_test_get_int1 = 37') self.assertEqual(lang.melGlobals.get('melGlobals_test_get_int1'), 37) meval('$melGlobals_test_get_int1 = 47') self.assertEqual(lang.melGlobals.get('$melGlobals_test_get_int1'), 47) meval('$melGlobals_test_get_int1 = 57') self.assertEqual(lang.MelGlobals.get('melGlobals_test_get_int1'), 57) meval('$melGlobals_test_get_int1 = 67') self.assertEqual(lang.MelGlobals.get('$melGlobals_test_get_int1'), 67)
def test_getitem_str(self): meval("global string $melGlobals_test_getitem_str1") meval('$melGlobals_test_getitem_str1 = "waldo"') self.assertEqual(lang.melGlobals.get("melGlobals_test_getitem_str1"), "waldo") meval('$melGlobals_test_getitem_str1 = "marcy"') self.assertEqual(lang.melGlobals.get("$melGlobals_test_getitem_str1"), "marcy") meval('$melGlobals_test_getitem_str1 = "may"') self.assertEqual(lang.MelGlobals.get("melGlobals_test_getitem_str1"), "may") meval('$melGlobals_test_getitem_str1 = "marlene"') self.assertEqual(lang.MelGlobals.get("$melGlobals_test_getitem_str1"), "marlene")
def makePvControl(jnts, ikHandle, bindJnt, offsetDir, nameRoot, ctrlGrp): ''' returns string[] {pvControlPath, pvConstraintName, pvControlPathGrp, pvLine(annotation)} ''' jnts = formatStrArray(jnts) return meval('abRTMakePvControl(%(jnts)s, "%(ikHandle)s", "%(bindJnt)s", %(offsetDir)d, "%(nameRoot)s", "%(ctrlGrp)s")' % locals())
def cleanDuplicate(targetObj): """ arguments: targetObj - name of mesh that you want to duplicate todo: 1. check that targetObj is a valid mesh 2. currently resets deformer envelopes to 1... need to remember original value? 3. cleanup intermediate object(s), possibly by obj export/import. """ # get list of deformers on targetObj allDeformers = meval('findRelatedDeformer("%s")' % targetObj) # disable all deformers by setting envelope to 0 for eachDfm in allDeformers: print eachDfm mc.setAttr('%s.envelope' % eachDfm, 0) # make duplicate mc.duplicate(targetObj, n='%s_cleanDuplicate' % targetObj) # re-enable all deformers by setting envelope to 1 for eachDfm in allDeformers: mc.setAttr('%s.envelope' % eachDfm, 1)
def loadLast(): projs = m.optionVar(q='RecentProjectsList') meval('setProject "%s"' % projs[-2]) files = m.optionVar(q='RecentFilesList') mf = files[-1] m.file(mf, f=True, o=True) setupScene() # as assiging my generic tools class to globals() doesn't seem to work in a plugin, # I'm assigning it to booth maya and maya.cmds modules so they are availables # globally in maya (aparently globals() inside a plugin is isolated from the # globals environment running when maya finishes initalization) # maya and maya.cmds modules are exactly the same! tools = hradecTools() m.h = tools maya.h = tools
def addFkControls(jnts, names, jntsToAlign, jntsToAddSecondaryCtrls, jntsToOrientCtrlsTo, fkChainUpJnt, localAlignParentJnt, wireType, ctrlGrp, limbName): ''' // adds controls to a joints (in a chain) specified in $aJnts, names them using $aRootNames, and places them in $ctrlGrp // $aJntsToAlign is joints (by index in $aJnts) to add the align attribute to // $aJntsToAddSecondaryCtrl is joints (by index in $aJnts) to which a secondary FK control will be added // $aJntsToOrientCtrlsTo is lookup table in form of joint index in $aJnts, object to which that that joint's control will be aligned {ind, objName, ind2, objName2}. // $fkChainUpJnt is joint to parent $aJnts[0] to // $localAlignParentJnt is joint to use as parent space for local align (can be "") // $wireType is wire to use for controls ("circle", "sphere") -- it must be a valid type. The orientation of the wire can also be specified with "|" to catenate, and then 0-5 for the orientation, in the form of "circle|1". // $limbName is name of attribute in charVars to record newly created nodes (for rig removal) // first control in $aJnts will have align attribute // returns array {joint1, ctrlCurve1, joint2, ctrlCurve2} ''' # format data jnts = formatStrArray(jnts) names = formatStrArray(names) jntsToAlign = formatArray(jntsToAlign) jntsToAddSecondaryCtrls = formatArray(jntsToAddSecondaryCtrls) jntsToOrientCtrlsTo = formatStrArray(jntsToOrientCtrlsTo) # format syntax cmd = 'abRTAddFkControls(%(jnts)s, %(names)s, %(jntsToAlign)s, %(jntsToAddSecondaryCtrls)s, %(jntsToOrientCtrlsTo)s, "%(fkChainUpJnt)s", "%(localAlignParentJnt)s", "%(wireType)s", "%(ctrlGrp)s", "%(limbName)s")' % locals() array = meval(cmd) # format return data as dictionary d = dict(itertools.izip_longest(*[iter(array)] * 2, fillvalue='')) return d
def hideAttr(obj, aAttr): ''' hides $obj's attributes in $aAttr ''' aAttr = formatStrArray(aAttr) return meval('abRTHideAttr("%(obj)s", %(aAttr)s)' % locals())
def re_getCurvePointInfo(curve, retWS=0): ''' I found this proc online at http://ryane.com and modified it if $retWS == true, it returns worldSpace coordinates. Otherwise it returns them in objectSpace. returns {curveCmd, hardnessCmd} ''' return meval('re_getCurvePointInfo("%(curve)s", %(retWS)d)' % locals())
def addFkControls(jnts, names, jntsToAlign, jntsToAddSecondaryCtrls, jntsToOrientCtrlsTo, fkChainUpJnt, localAlignParentJnt, wireType, ctrlGrp, limbName): ''' // adds controls to a joints (in a chain) specified in $aJnts, names them using $aRootNames, and places them in $ctrlGrp // $aJntsToAlign is joints (by index in $aJnts) to add the align attribute to // $aJntsToAddSecondaryCtrl is joints (by index in $aJnts) to which a secondary FK control will be added // $aJntsToOrientCtrlsTo is lookup table in form of joint index in $aJnts, object to which that that joint's control will be aligned {ind, objName, ind2, objName2}. // $fkChainUpJnt is joint to parent $aJnts[0] to // $localAlignParentJnt is joint to use as parent space for local align (can be "") // $wireType is wire to use for controls ("circle", "sphere") -- it must be a valid type. The orientation of the wire can also be specified with "|" to catenate, and then 0-5 for the orientation, in the form of "circle|1". // $limbName is name of attribute in charVars to record newly created nodes (for rig removal) // first control in $aJnts will have align attribute // returns array {joint1, ctrlCurve1, joint2, ctrlCurve2} ''' # format data jnts = formatStrArray(jnts) names = formatStrArray(names) jntsToAlign = formatArray(jntsToAlign) jntsToAddSecondaryCtrls = formatArray(jntsToAddSecondaryCtrls) jntsToOrientCtrlsTo = formatStrArray(jntsToOrientCtrlsTo) # format syntax cmd = 'abRTAddFkControls(%(jnts)s, %(names)s, %(jntsToAlign)s, %(jntsToAddSecondaryCtrls)s, %(jntsToOrientCtrlsTo)s, "%(fkChainUpJnt)s", "%(localAlignParentJnt)s", "%(wireType)s", "%(ctrlGrp)s", "%(limbName)s")' % locals( ) array = meval(cmd) # format return data as dictionary d = dict(itertools.izip_longest(*[iter(array)] * 2, fillvalue='')) return d
def lsCleanDuplicate(targetObj): """ arguments: targetObj - name of mesh that you want to duplicate todo: 1. check that targetObj is a valid mesh 2. currently resets deformer envelopes to 1... need to remember original value? 3. cleanup intermediate object(s), possibly by obj export/import. """ # get list of deformers on targetObj allDeformers = meval('findRelatedDeformer("%s")' % targetObj) # disable all deformers by setting envelope to 0 for eachDfm in allDeformers: print eachDfm mc.setAttr('%s.envelope' % eachDfm, 0) # make duplicate dup = mc.duplicate(targetObj, n='%s_cleanDuplicate' % targetObj)[0] # use pymel to unlock attrs dupNode = pm.PyNode(dup) attrsToUnlock = ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v') [dupNode.attr(attrToUnlock).unlock() for attrToUnlock in attrsToUnlock] # re-enable all deformers by setting envelope to 1 for eachDfm in allDeformers: mc.setAttr('%s.envelope' % eachDfm, 1) return dup
def cleanDuplicate(targetObj): """ arguments: targetObj - name of mesh that you want to duplicate todo: 1. check that targetObj is a valid mesh 2. currently resets deformer envelopes to 1... need to remember original value? 3. cleanup intermediate object(s), possibly by obj export/import. """ # get list of deformers on targetObj allDeformers = meval('findRelatedDeformer("%s")'%targetObj) # disable all deformers by setting envelope to 0 for eachDfm in allDeformers: print eachDfm mc.setAttr('%s.envelope'%eachDfm, 0) # make duplicate mc.duplicate(targetObj, n='%s_cleanDuplicate'%targetObj) # re-enable all deformers by setting envelope to 1 for eachDfm in allDeformers: mc.setAttr('%s.envelope'%eachDfm, 1)
def showPolygonShaderAttributes(): """ Open Attribute Editor of polygon shader """ sg, _, initialSelection = getWorkingData() shaderConnection = m.connectionInfo(sg + ".surfaceShader", sourceFromDestination=True) or m.connectionInfo( sg + ".miMaterialShader", sourceFromDestination=True ) if not shaderConnection: raise RuntimeError("Cannot find shader of {}.".format(sg)) shader = shaderConnection.split(".")[0] m.select(initialSelection, r=True) # need in case of object (not component) selection to remove highlight m.select(shader, r=True) meval("showEditor {}".format(shader))
def colorObj(obj, indexVal): ''' Note: using indexVal instead of indexKey, unless you have abRTGlobals set up... sets $obj color to $indexKey (which must be a global key, like "rootCtrlColor" that shows up in globals) or to $indexVal if $indexVal > -1 ''' return meval('abRTColorObj("%(obj)s", "", %(indexVal)d)' % locals())
def findRelatedBlendShapes(mesh): allDeformers = meval('findRelatedDeformer("%s")' % mesh) allBs = [] for eachDfm in allDeformers: dfmType = mc.objectType(eachDfm) if dfmType == "blendShape": allBs.append(eachDfm) return allBs
def showPolygonShaderAttributes(): """ Open Attribute Editor of polygon shader """ sg, _, initialSelection = getWorkingData() shaderConnection = m.connectionInfo(sg + '.surfaceShader', sourceFromDestination=True) or \ m.connectionInfo(sg + '.miMaterialShader', sourceFromDestination=True) if not shaderConnection: raise RuntimeError('Cannot find shader of {}.'.format(sg)) shader = shaderConnection.split('.')[0] m.select( initialSelection, r=True ) # need in case of object (not component) selection to remove highlight m.select(shader, r=True) meval('showEditor {}'.format(shader))
def setCmd(cmd, qSet=None): if cmd == "select": mc.select(qSet, r=1) if cmd == "delete": mc.delete(qSet) if cmd == "create": meval("ModCreateMenu mainCreateMenu;CreateQuickSelectSet;") if cmd == "addSelect": mc.select(qSet, add=1) if cmd == "subSelect": mc.select(qSet, d=1) if cmd == "intersectSelect": tempSet = mc.sets() selList = mc.sets(qSet, int=tempSet) if not selList: selList = None mc.select(selList, r=1) mc.delete(tempSet)
def makePvControl(jnts, ikHandle, bindJnt, offsetDir, nameRoot, ctrlGrp): ''' returns string[] {pvControlPath, pvConstraintName, pvControlPathGrp, pvLine(annotation)} ''' jnts = formatStrArray(jnts) return meval( 'abRTMakePvControl(%(jnts)s, "%(ikHandle)s", "%(bindJnt)s", %(offsetDir)d, "%(nameRoot)s", "%(ctrlGrp)s")' % locals())