def applyShaderToHair(self,shader, sels): """docstring for applyShaderToHair""" hairSel = [] if sels: for s in sels: hai = mn.listRelatives( s.name, type = 'hairSystem', ad = True ) if hai: hairSel.extend( hai ) try: hai = mn.listRelatives( s.name, type = 'shaveHair', ad = True ) if hai: hairSel.extend( hai ) except: pass else: hairSel = mn.ls( typ = 'hairSystem' ) try: hairSel.extend( mn.ls( typ = 'shaveHair' ) ) except: pass if not hairSel: return for h in hairSel: h.a.aiHairShader.overrided = True try: shader.a.outColor >> h.a.aiHairShader except: continue
def renameSelection(): """rename all the selected objects going 1 by 1""" sel = mn.ls( sl = True ) for s in sel: s() #select mc.refresh() result = mc.promptDialog( title = 'Rename Object ' + s.name, message = 'Enter Name:', button = ['OK', 'Cancel','Stop'], defaultButton = 'OK', tx = s.name, cancelButton = 'Cancel', dismissString = 'Cancel') if result == 'OK': text = mc.promptDialog(query=True, text=True) if '#' in text: similars = mn.ls( text.replace( '#', '*' ) ) if not similars: similars = [] s.name = text.replace( '#', str( len( similars ) ) ) else: s.name = text if result == 'Stop': return
def importForAsset(self, asset, area = 1,customNamespace = None, referenceAsset = True, assetInShotFolder = False, shot = None, useDefaultName = False ): """import cache and assign to asset""" #reference render asset #connect cache to objects if referenceAsset: if assetInShotFolder: assetNewPath = asset.areaPath( area ).copy( shot.assetsPath + asset.areaPath( area ).path.split( 'Assets/' )[-1] ) nodes = assetNewPath.reference( customNamespace, useDefaultName ) else: nodes = asset.areaPath( area ).reference( customNamespace, useDefaultName ) mshs = mn.ls( nodes, typ = 'mesh', ni = True, l = True ) else: if useDefaultName: nodes = asset.areaPath( area ).imp( None ) else: nodes = asset.areaPath( area ).imp( customNamespace ) if nodes: mshs = mn.ls( nodes, typ = ['mesh','nurbsCurve'], ni = True, l = True ) else: mshs = mn.ls( customNamespace + ':*', typ = ['mesh','nurbsCurve'], ni = True, l = True ) #filter meshes mshs.select() abcNode = self.imp( mode = 'import', connect = "/", createIfNotFound = True ) if USE_EXOCORTEX: mshsAttrDict = {} for m in mshs: his = [a for a in mn.listHistory( m, f = True ) if a.type == 'mesh'] if len(his) == 2: attrs = ['castsShadows', 'receiveShadows', 'motionBlur','primaryVisibility','smoothShading','visibleInReflections','visibleInRefractions','doubleSided','opposite','aiSelfShadows','aiOpaque','aiVisibleInDiffuse','aiVisibleInGlossy','aiMatte','aiSubdivType','aiSubdivIterations','aiSubdivAdaptiveMetric','aiSubdivUvSmoothing','aiSubdivSmoothDerivs','aiDispHeight','aiDispZeroValue','aiDispAutobump','aiStepSize'] for a in attrs: if his[0].attr(a).exists: his[1].attr( a ).v = his[0].attr( a ).v
def textures(self): """ return the textures in the scene """ fils = mn.ls( typ = 'file' ) aiImage = mn.ls( typ = 'aiImage' ) if aiImage: fils.extend( aiImage ) return fils
def changeSampleLights(self): """change the samples in selected lights, if none is selected change in all""" lits = mn.ls( sl = True, dag = True, typ = ['light', 'aiAreaLight'] ) if not lits: lits = mn.ls( typ = ['light', 'aiAreaLight'] ) if not lits: return val = self.lightSamples_sb.value() for l in lits: l.a.aiSamples.v = val
def createBlendshape( replace = [ 'Rig', 'Final' ]): """create blendshape between RIG and FINAL FINAL allways is the render asset""" sel = mn.ls( sl = True, s = True, dag = True, ni = True ) if sel: sel = mn.ls( sel[0].name[:sel[0].name.rindex(':')] + ':*', dag = True, ni = True, typ = 'mesh' ) for r in sel: rSha = mn.Node( r.name.replace( replace[0], replace[1] ) ) blend = mc.blendShape( r.name, rSha.name, o = 'world' )[0] mc.blendShape( blend, edit=True, w=[(0, 1)] )
def isolateSelectedObjects(self): """isolate Selecetd objects""" sel = mn.ls( sl = True, dag = True, typ = ['transform'], l = 1 ) self.desisolateObjects() if not sel: return self.isolatedObjects = [o for o in mn.ls( typ = 'transform' ) if o.a.v] #only visibile transforms for o in self.isolatedObjects: o.a.v.v = 0 for o in sel: o.a.v.v = 1
def _getObjects(self): """return the objects that match the search""" search = str( self.search_le.text() ) byType = str( self.type_cmb.currentText() ) onSel = self.onSelection_chb.isChecked() objs = [] if byType == '': objs = mn.ls( search, ni = True, sl = onSel ) else: objs = mn.ls( search, type = byType, ni = True, sl = onSel ) return objs
def replace(self): """docstring for replace""" if not USE_EXOCORTEX: mn.Nodes( mn.ls( mn.ls(sl = True)[0].namespace.name[1:] + ':*', typ = ['mesh'] )).select() self.imp( mode = 'import', connect = "/", createIfNotFound = True ) else: sel = mn.ls( sl = True ) his = mn.listHistory(sel[0]) if his: caFileNode = [n for n in his if n.type == 'ExocortexAlembicFile'] if caFileNode: caFileNode[0].a.fileName.v = self.path
def checkDuplicatedNamesInScene(): """check if there is duplicated names if exists.. return the nodes""" alltrfs = mn.ls( '*', typ = 'transform', r = True ) dups = [] for a in alltrfs: if '|' in a.name: dups.append( a.name ) alltrfs = mn.ls( '*', typ = 'mesh', r = True ) for a in alltrfs: if '|' in a.name: dups.append( a.name ) if dups: mc.warning( 'There are duplicated names in scene' ) return mn.Nodes( dups ) return dups
def checkDuplicatedNamesInScene(): """check if there is duplicated names if exists.. return the nodes""" alltrfs = mn.ls('*', typ='transform', r=True) dups = [] for a in alltrfs: if '|' in a.name: dups.append(a.name) alltrfs = mn.ls('*', typ='mesh', r=True) for a in alltrfs: if '|' in a.name: dups.append(a.name) if dups: mc.warning('There are duplicated names in scene') return mn.Nodes(dups) return dups
def replacePath(self): tab, index = self._getCurrentTab() textures = self.getSelected() searchAndReplace = [str(self.searchPath_le.text()),str(self.replacePath_le.text())] if index == 0: if self.inMaya: if textures: self.manager.replacePath( textures, searchAndReplace ) else: self.manager.replacePath( self.manager.textures, searchAndReplace ) else: self.fil.changeTextures( srchAndRep = searchAndReplace ) self.fillTextures() elif index == 1: if self.inMaya: for t in textures: rfn = mc.referenceQuery( t.path, rfn = True ) mc.file( t.path.replace( searchAndReplace[0],searchAndReplace[1]), loadReference = rfn, type = "mayaAscii", options = "v=0" ) else: self.fil.changeReferences( srchAndRep = searchAndReplace ) self.fillReferencesTable() elif index == 2: if self.inMaya: for t in textures: for al in mn.ls( typ = 'AlembicNode' ): if t.path == al.a.abc_File.v: al.a.abc_File.v = t.path.replace( searchAndReplace[0],searchAndReplace[1] ) break else: self.fil.changeCaches( srchAndRep = searchAndReplace ) self.fillCachesTable()
def createAssignOcclusion(self): """docstring for fname""" sels = mn.ls( sl = True ) shaderNode = mn.Node( 'OCC_MAT' ) if not shaderNode.exists: shaderNode = mn.Node( mc.shadingNode( 'aiAmbientOcclusion', asShader = True, n = 'OCC_MAT' ) ) self.applyShaderToSel( shaderNode, sels )
def createAssignAiStandard(self): """docstring for createAssignAiStandard""" sels = mn.ls( sl = True ) shaderNode = mn.Node( 'aiStandard_MAT' ) if not shaderNode.exists: shaderNode = mn.Node( mc.shadingNode( 'aiStandard', asShader = True, n = 'aiStandard_MAT' ) ) self.applyShaderToSel( shaderNode, sels )
def exportAssetCache(self): """docstring for fname""" baseDir = self.fileNameForCache( True ) #TODO add filename and see best way to detect asset exportedAsset = [] steps = self.steps_spb.value() for n in mn.ls( sl = True ): baseName = n.name.split( ':' )[0] if baseName in exportedAsset: continue a = ass.getAssetFromNode(n, self._selectedProject) cacFile = cfl.CacheFile( baseDir + '/' + baseName + '.abc', [n] ) cacFile.exportAsset( a, False, False, steps ) exportedAsset.append( baseName ) if self.copyToServer_chb.isChecked(): serverFile = cfl.CacheFile( cacFile.path.replace( prj.BASE_PATH, self.serverPath ) ) serverFile.newVersion() cacFile.copy( serverFile.path ) selShot = self._selectedShot if self.sendMail: ml.mailFromTool( 'new_cache', { '<ProjectName>': selShot.project.name, '<SequenceName>': selShot.sequence.name, '<ShotName>': selShot.name, '<AssetName>': ','.join( exportedAsset ), '<UserName>': os.getenv('username')}, os.getenv('username') + '@bitt.com', self.mailsPath , self.mailServer, self.mailPort ) self._fillCacheList()
def createAssignShadow(self): """create and assign a aiShadowCatcher to selection""" sels = mn.ls( sl = True ) shaderNode = mn.Node( 'SHADOW_MAT' ) if not shaderNode.exists: shaderNode = mn.Node( mc.shadingNode( 'aiShadowCatcher', asShader = True, n = 'SHADOW_MAT' ) ) self.applyShaderToSel( shaderNode, sels )
def getReferenceFromSelected(): """docstring for getReferenceFromSelected""" objs = mn.ls(sl=True) references = [] for obj in objs: references.append(Reference(mc.referenceQuery(obj.name, rfn=True))) return references
def getReferenceFromSelected(): """docstring for getReferenceFromSelected""" objs = mn.ls( sl = True ) references = [] for obj in objs: references.append( Reference( mc.referenceQuery( obj.name, rfn = True ) ) ) return references
def playblast( movFil ): """main playblast function param path: string for the path for the playblast""" mm.eval( 'setAllMainWindowComponentsVisible 0;' ) try: resNode = mn.Node( 'defaultResolution' ) #resolution = [ resNode.a.width.v, resNode.a.height.v ] resolution = [ 1280, 720 ] #CREATE PLAYBLAST #write files in tmp dir mc.setAttr ('defaultRenderGlobals.imageFormat',32) tmpFile = tempfile.gettempdir() + '/playblastTmp/' + movFil.name asd = mc.playblast( format = "image", filename = tmpFile, forceOverwrite = True, viewer = 0, showOrnaments = 0, percent = 100, widthHeight = resolution ) print asd finally: mm.eval( 'setAllMainWindowComponentsVisible 1;' ) #ADD FRAME NUMBERS print tmpFile + '.png' #sqFil.sequenceFile( tmpFile + '.png' ).insertFrameNumber( tempfile.gettempdir() + '/playblastTmp/', 1, movFil.name ) #EXPORT MOV FILE audioPath = '' audio =[a for a in mn.ls( typ = 'audio' ) if a.a.mute.v == 0] if audio: audioPath = audio[0].a.filename.v fps = { 'film':24, 'pal':25 } curFps = mc.currentUnit( q = True, time=True) sqFile = sqFil.sequenceFile( tmpFile + '.png' ) sqFile.createMov( movFil.dirPath.replace( '\\', '/').replace('//','/'), audioPath, fps[curFps], movFil.name ) os.system("start "+ str( movFil.path ) ) shutil.rmtree( tempfile.gettempdir() + '/playblastTmp/' )
def applyRenderStats(self): """apply settings to render stats for selected objects""" sel = mn.ls( sl = True ) if not sel: return items = [self.shapeOverrides_01_lay.itemAt(i) for i in range(self.shapeOverrides_01_lay.count())] items.extend( [self.shapeOverrides_02_lay.itemAt(i) for i in range(self.shapeOverrides_02_lay.count())] ) valsDict = {} for w in items: valsDict[str( w.widget().text() )] = w.widget().isChecked() with undo.Undo(): for s in sel: childs = s.allchildren sha = s.shape if childs: for c in childs: shap = c.shape if shap: for v in valsDict.keys(): value = valsDict[ v ] try: if not value == shap.attr( v ).v: shap.attr( v ).overrided = True shap.attr( v ).v = valsDict[ v ] except: continue for v in valsDict.keys(): try: value = valsDict[ v ] if not value == sha.attr( v ).v: sha.attr( v ).overrided = True sha.attr( v ).v = valsDict[ v ] except: continue
def addTo(self): """add itmes to To list without cleaning""" for f in mn.ls( sl = True ): item = QtGui.QListWidgetItem( f.name ) item.setData(32, f ) self.to_lw.addItem( item ) self._changeListCount( self.to_lw )
def fillCachesTable(self): """fill the caches table""" if self.inMaya: caches = [] for a in mn.ls( typ = 'AlembicNode' ): caches.append( fl.File( a.a.abc_File.v ) ) else: caches = self.fil.caches self.caches_tw.setRowCount( len( caches ) ) color = [QtGui.QColor( "green" ), QtGui.QColor( "red" )] for i,t in enumerate(caches): #NAME item = QtGui.QTableWidgetItem( t.basename ) item.setData(32, t ) self.caches_tw.setItem( i, 0, item ) #SIZE item = QtGui.QTableWidgetItem( str( t.size ) ) self.caches_tw.setItem( i, 1, item ) #PATH item = QtGui.QTableWidgetItem( t.path ) if t.exists: colVal = 0 else: colVal = 1 if uiH.USEPYQT: item.setBackgroundColor( color[ colVal ]) else: item.setBackground( color[ colVal ] ) self.caches_tw.setItem( i, 2, item )
def assign(self): """assign shader to selection""" sel = mn.ls( sl = True ) if sel: #if not self.exists: shadCount = self.importShader() mc.select( sel ) mc.hyperShade( a = self.name + str( shadCount ) + ':' + self.name )
def getTexturesForSelection(self): """docstring for getTexturesForSelection""" textures = [] for n in mn.ls(sl = True): for t in mn.listHistory( n.shader ): if t.type == 'file': textures.append( t ) return textures
def setTo(self): """clear and add items to To list""" self.to_lw.clear() for f in mn.ls( sl = True ): item = QtGui.QListWidgetItem( f.name ) item.setData(32, f ) self.to_lw.addItem( item ) self._changeListCount( self.to_lw )
def correctNameForCtlCurves(): #rename ctl for n in mn.ls( '*_ctl' ): child = mn.listRelatives( n.name, s = True, ni = True, f = True ) print child if child: print n.name, child[0].name, n.name + 'Shape' child[0].name = n.name + 'Shape' print n.name,child
def createAssignUv(self): """docstring for fname""" sels = mn.ls( sl = True ) shaderNode = mn.Node( 'UV_MAT' ) if not shaderNode.exists: shaderNode = mn.Node( mc.shadingNode( 'aiUtility', asShader = True, n = 'UV_MAT' ) ) shaderNode.a.colorMode.v = 5 shaderNode.a.shadeMode.v = 2 self.applyShaderToSel( shaderNode, sels )
def setNameSpace(self): """docstring for setNameSpace""" sel = mn.ls(sl=True) if sel: self.namespace_lbl.setText(sel[0].namespace.name) Pose.NAMESPACE = sel[0].namespace.name else: self.namespace_lbl.setText(':') Pose.NAMESPACE = ':'
def setNameSpace(self): """docstring for setNameSpace""" sel = mn.ls( sl = True ) if sel: self.namespace_lbl.setText( sel[0].namespace.name ) Pose.NAMESPACE = sel[0].namespace.name else: self.namespace_lbl.setText( ':' ) Pose.NAMESPACE = ':'
def controlsData(self): """returns controls data from current pose""" objs = mn.ls(sl=True) data = {} for o in objs: data[o] = {} for a in o.listAttr(k=True): data[o][a] = a.v return data
def controlsData(self): """returns controls data from current pose""" objs = mn.ls( sl = True ) data = {} for o in objs: data[ o ] = {} for a in o.listAttr( k = True ): data[ o ][ a ] = a.v return data
def isolateSelectedLight(self): """isolate Selected Light""" sel = mn.ls( sl = True, dag = True, typ = ['light','aiAreaLight','aiSkyDomeLight','aiVolumeScattering'], l = 1 ) self.desisolateLight() #back all to normal before we make a light isolated self.isolateLight_btn.setStyleSheet('QPushButton {background-color: rgb(255, 0, 0)}') if not sel: self.isolateLight_btn.setStyleSheet('QPushButton {background-color: rgb(0, 170, 255)}') return lits = mn.ls( typ=['light','aiAreaLight','aiSkyDomeLight','aiVolumeScattering'], l=1 ) self.isolatedLights = [] for l in lits: try: if l.parent.a.v: self.isolatedLights.append( l.parent ) l.parent.a.v.v = 0 except: continue for l in sel: l.parent.a.v.v = 1
def __init__( self, path, nodes = None ): super(CacheFile, self).__init__( path ) if nodes: self._nodes =[] for n in nodes: self._nodes.extend(mn.ls( n, s = True, dag = True, ni = True ) ) print self._nodes self._nodes = mn.Nodes( self._nodes ) else: self._nodes = None
def removeSelected(): """unload selected reference""" objs = mn.ls(sl=True) for obj in objs: try: referenceNode = mc.referenceQuery(obj.name, rfn=True) path = mc.referenceQuery(obj.name, f=True) mc.file(referenceNode=referenceNode, removeReference=True) except: continue
def exportSelShaders(self, catName): """export shaders from selected objects""" lib = self._getSelectedLibrary() makePreview = self.makePreview_chb.isChecked() for a in mn.ls(sl = True): sha = a.shader shaName = sha.a.surfaceShader.input.node shader = sh.Shader( shaName.name, catName, lib ) shader.publish(makePreview) self._createLibUI()
def transformsWithoutFreeze(): """return all the transforms without freeze""" alltrfs = mn.ls('*', typ='transform', r=True) alltrfs = _removeCamerasFromArray(alltrfs) withoutFreeze = [] for t in alltrfs: if any(t.attr(a).v != 0 for a in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']): withoutFreeze.append(t) if any(t.attr(a).v != 1 for a in ['sx', 'sy', 'sz']): withoutFreeze.append(t) return withoutFreeze
def reloadSelected(): """reload selected object""" #reload reference objs = mn.ls(sl=True) for obj in objs: try: referenceNode = mc.referenceQuery(obj.name, rfn=True) path = mc.referenceQuery(obj.name, f=True) mc.file(path, loadReference=referenceNode) except: continue
def groupAll(): """docstring for groupAll""" result = mc.promptDialog(title='Main Group', message='Enter Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if result == 'OK': text = mc.promptDialog(query=True, text=True) trfs = mn.ls('|*', typ='transform', r=True) trfs = _removeCamerasFromArray(trfs) mc.group(trfs, n=text)
def renameSimilarObjects(): result = mc.promptDialog( title = 'Rename Object ' , message = 'Enter Name:', button = ['OK', 'Cancel'], defaultButton = 'OK', cancelButton = 'Cancel', dismissString = 'Cancel') if result == 'OK': text = mc.promptDialog(query=True, text=True) if '#' in text: sel = mn.ls( sl = True ) i = 0 for s in sel: s.name = text.replace( '#', str( i ) ) i += 1
def isMeshWithHistory(): """return meshes that has history or material assigned by face""" withAssignedMaterialByFace = [] withHistory = [] for n in mn.ls(typ='mesh', ni=True): his = mn.listHistory(n) if not len(his) == 1: if any('groupId' in h.name for h in his): withAssignedMaterialByFace.append(n) print 'This mesh has the material assigned by faces', n.name, his if len(his) == 3: continue if any('shaveHair' in h.type for h in his): print 'This mesh is related with Shave and Hair cut', n.name, his continue withHistory.append(n) return withHistory, withAssignedMaterialByFace
def hairSystemAutomator(sysName='', scalp=None): """creates a hair system based on selected lock meshes, if you specify a scalp it will use that to place follicles""" hair_polygons = mn.ls(sl=1) all_grp = mn.Node(mc.group(n=sysName + '_hair_grp', em=True)) hairSystem = mn.createNode('hairSystem') hairSystemPar = hairSystem.parent hairSystemPar.name = sysName + '_hairSystem' hairSystemPar.parent = all_grp hairSystem = hairSystemPar.shape pfxHair = mn.createNode('pfxHair') pfxHairPar = pfxHair.parent pfxHairPar.name = sysName + '_pfxHair' pfxHairPar.parent = all_grp pfxHair = pfxHairPar.shape foll_grp = mn.Node(mc.group(n=sysName + '_foll_grp', em=True)) foll_grp.parent = all_grp curve_grp = mn.Node(mc.group(n=sysName + '_crv_grp', em=True)) curve_grp.parent = all_grp allFollicles = [] allHairCurves = [] allFtbHairCurves = [] hairCount = 0 plugCount = 0 badMesh = [] for hair_poly in hair_polygons: hairLock = HairLock(hair_poly, hairSystem, scalp) hairLock.create() for i in range(5): hairLock.follicles[i].parent = foll_grp #if not scalp: hairLock.curves[i].parent = curve_grp #hairSystem.attr( "clumpFlatness[0].clumpFlatness_Position" ).v = 0 #hairSystem.attr( "clumpFlatness[0].clumpFlatness_FloatValue" ).v = 0.5 hairSystem.a.simulationMethod.v = 1 hairSystem.a.outputRenderHairs >> pfxHair.a.renderHairs ti = mn.Node('time1') ti.a.outTime >> hairSystem.a.currentTime
def playblast(movFil): """main playblast function param path: string for the path for the playblast""" mm.eval('setAllMainWindowComponentsVisible 0;') try: resNode = mn.Node('defaultResolution') #resolution = [ resNode.a.width.v, resNode.a.height.v ] resolution = [1280, 720] #CREATE PLAYBLAST #write files in tmp dir mc.setAttr('defaultRenderGlobals.imageFormat', 32) tmpFile = tempfile.gettempdir() + '/playblastTmp/' + movFil.name asd = mc.playblast(format="image", filename=tmpFile, forceOverwrite=True, viewer=0, showOrnaments=0, percent=100, widthHeight=resolution) print asd finally: mm.eval('setAllMainWindowComponentsVisible 1;') #ADD FRAME NUMBERS print tmpFile + '.png' #sqFil.sequenceFile( tmpFile + '.png' ).insertFrameNumber( tempfile.gettempdir() + '/playblastTmp/', 1, movFil.name ) #EXPORT MOV FILE audioPath = '' audio = [a for a in mn.ls(typ='audio') if a.a.mute.v == 0] if audio: audioPath = audio[0].a.filename.v fps = {'film': 24, 'pal': 25} curFps = mc.currentUnit(q=True, time=True) sqFile = sqFil.sequenceFile(tmpFile + '.png') sqFile.createMov( movFil.dirPath.replace('\\', '/').replace('//', '/'), audioPath, fps[curFps], movFil.name) os.system("start " + str(movFil.path)) shutil.rmtree(tempfile.gettempdir() + '/playblastTmp/')
def fillCurveLE(self): """fill line edit with curve name""" sel = mn.ls(sl=True, dag=True, ni=True, typ='nurbsCurve') self.curve_le.setText(sel[0].name)
def isAllInOneGroup(): """return true if there is all in the same group""" alltrfs = mn.ls('|*', typ='transform', r=True) alltrfs = _removeCamerasFromArray(alltrfs) return len(alltrfs) == 1
def addGroup(self): """docstring for addGroup""" sel = mn.ls(sl=True) if sel: self.groups_lw.addItems(sel.names)
def insertScalp(self): """docstring for insertScalp""" sel = mn.ls(sl=True) if sel: self.scalp_le.setText(sel[0].name)
def hairLockRenamer(): """docstring for hairLockRenamer""" i = 0 for a in mn.ls(sl=True): a.name = 'hair_%i' % i + '_lock' i += 1