예제 #1
0
def loadSceneAssemblyPlugins(tankError = False):
        ## PLUGIN CHECK
        ## First try to make sure the plugins are loaded in maya
        if not cmds.pluginInfo('AbcExport.mll', query = True, loaded = True):
            try:
                cmds.loadPlugin('AbcExport.mll')
            except RuntimeError:
                if TankError:
                    raise TankError("AbcExport failed to load!!")
        if not cmds.pluginInfo('AbcImport.mll', query = True, loaded = True):
            try:
                cmds.loadPlugin('AbcImport.mll')
            except RuntimeError:
                if TankError:
                    raise TankError("AbcImport plugin failed to load!!")
        if not cmds.pluginInfo('gpuCache.mll', query = True, loaded = True):
            try:
                cmds.loadPlugin('gpuCache.mll')
            except RuntimeError:
                if TankError:
                    raise TankError("gpuCache plugin failed to load!!")            
        if not cmds.pluginInfo('sceneAssembly.mll', query = True, loaded = True):
            try:
                cmds.loadPlugin('sceneAssembly.mll')
            except RuntimeError:
                if TankError:
                    raise TankError("sceneAssembly plugin failed to load!!")   
예제 #2
0
	def __init__(self):
		'''
		load fbxmaya plugin in initialisation
		'''
		try:
			plugin = cmds.pluginInfo( query=True, listPlugins=True, version=True )
			fbxplugin = 'fbxmaya'
			
			if cmds.pluginInfo(fbxplugin+ ".mll", query=True, loaded=True):
				cmds.pluginInfo(fbxplugin + ".mll", edit=True, autoload=True)
			else:
				cmds.loadPlugin(fbxplugin + ".mll")
		except:
			print "fbxMaya was not found on MAYA_PLUG_IN_PATH:", sys.exc_info()[0]

		self.listGrp = []
		self.children = []
		self.childrenLong = []
#		self.listGrp.append('FG')
#		self.listGrp.append('BG')
#		self.listGrp.append('MG')
		self.listGrp = ['fg','mg','bg']

		self.upperL = r'''[A-Z]'''
		'''
		window variables
		'''
		self.win = "fbxExport"
		self.fbxPath1 = "textfield"
		self.fbxPath2 = "button"
		self.expPath = ""
예제 #3
0
def enableaPlugin(filename):
    extDict = {'win64':'mll','mac':'bundle','linux':'so','linux64':'so'}
    os = cmds.about(os=True)
    ext = extDict[os]
    version = cmds.about(v=True)[:4]
    pluginName = 'deltaMushToSkinCluster_%s' % version
    fileFullName = '%s.%s' % (pluginName,ext)
    rootPath = getParentPath(currentFileDirectory())
    pluginsPath = rootPath+'/plug-ins/'
    pluginFilePath = pluginsPath+fileFullName
    pluginStr = mel.eval('getenv "MAYA_PLUG_IN_PATH";')+';'+pluginsPath
    mel.eval('putenv "MAYA_PLUG_IN_PATH" "%s";' % pluginStr)
    with open(filename,'a+') as f:
        state = True
        for line in f.readlines():
            if re.findall(fileFullName,line):
                state = False
        if state:
            f.write(r'evalDeferred("autoLoadPlugin(\"\", \"%s\", \"%s\")");' % (fileFullName,pluginName))

    if not cmds.pluginInfo( pluginFilePath, query=True, autoload=True):
        cmds.pluginInfo( pluginFilePath, edit=True, autoload=True)

    if not cmds.pluginInfo(pluginFilePath,query=True,loaded=True):
        cmds.loadPlugin(pluginFilePath)
예제 #4
0
def loadPlugin():
    """
    load softSelectionQuery plugin
    """
    
    mayaVers = int(mayaVersion())
    os = cmds.about(os=1)
    
    if os == 'win64':
        pluginName = 'softSelectionQuery_%s-x64.mll' % mayaVers
    elif os == 'mac':
        pluginName = 'softSelectionQuery_%s.bundle' % mayaVers
    elif os == 'linux64':
        pluginName = 'softSelectionQuery_%s.so' % mayaVers
    else:
        cmds.error('Soft Cluster EX is available for 64bit version of Autodesk Maya 2011 '
                  'or above under Windows 64bit, Mac OS X and Linux 64bit!')
    
    if not cmds.pluginInfo(pluginName, q=True, l=True ):
        cmds.loadPlugin(pluginName)
        version = cmds.pluginInfo(pluginName, q=1, v=1)
        log.info('Plug-in: %s v%s loaded success!' % (pluginName, version))
    else:
        version = cmds.pluginInfo(pluginName, q=1, v=1)
        log.info('Plug-in: %s v%s has been loaded!' % (pluginName, version))
예제 #5
0
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')
예제 #6
0
def remove_unknown_nodes():
    removed_count = 0

    unknown_nodes = cmds.ls(type="unknown")
    for node in unknown_nodes:
        if cmds.objExists(node):
            sys.stdout.write("Remove unknown node '{}'.\n".format(node))
            cmds.lockNode(node, lock=False)
            cmds.delete(node)
            removed_count += 1

    if cmds.pluginInfo("Turtle.mll", q=True, loaded=True):
        cmds.pluginInfo("Turtle.mll", e=True, autoload=False)
        cmds.unloadPlugin("Turtle.mll", force=True)
    turtle_nodes = ["TurtleDefaultBakeLayer",
                    "TurtleBakeLayerManager",
                    "TurtleRenderOptions",
                    "TurtleUIOptions"]
    for node in turtle_nodes:
        if cmds.objExists(node):
            sys.stdout.write("Remove Turtle node '{}'.\n".format(node))
            cmds.lockNode(node, lock=False)
            cmds.delete(node)
            removed_count += 1

    sys.stdout.write(str(removed_count) + " unknown nodes removed.\n")
예제 #7
0
def loadMentalRayPlugin():
    name = 'Mayatomr'
    if not cmds.pluginInfo(name, q=True, loaded=True):
        cmds.loadPlugin(name)
        cmds.pluginInfo(name, edit=True, autoload=True)
    cmds.setAttr('defaultRenderGlobals.currentRenderer', 'mentalRay', type='string')
    print ('# Result: mental ray Plugin loaded #')
예제 #8
0
def initializePlugin(obj):
    plugin = OpenMayaMPx.MFnPlugin(obj)

    try:
        plugin.registerNode(ms_environment_nodeTypeName, ms_environment_nodeTypeId, ms_environment_nodeCreator, ms_environment_nodeInitializer, OpenMayaMPx.MPxNode.kLocatorNode)
    except:
        sys.stderr.write("Failed to register node: %s" % ms_environment_nodeTypeName)

    try:
        plugin.registerNode(ms_renderSettings_nodeTypeName, ms_renderSettings_nodeTypeId, ms_renderSettings_nodeCreator, ms_renderSettings_nodeInitializer)
    except:
        sys.stderr.write("Failed to register node: %s\n" % ms_renderSettings_nodeTypeName)

    # load objExport plugin if its not loaded yet
    try:
        if not cmds.pluginInfo('objExport', query=True, loaded=True):
            cmds.loadPlugin('objExport')
        if not cmds.pluginInfo('ms_appleseed_material.py', query=True, loaded=True):
            cmds.loadPlugin('ms_appleseed_material.py')
        if not cmds.pluginInfo('ms_appleseed_shading_node.py', query=True, loaded=True):
            cmds.loadPlugin('ms_appleseed_shading_node.py')
    except: 
        print 'objExport plugin could not be loaded, cannot load mayaseed'

    ms_menu.createMenu()
    ms_menu.buildMenu()
예제 #9
0
	def loadDecomposeMatDll(self):
		mversion = (maya.mel.eval("float $mayaVersion = `getApplicationVersionAsFloat` ;"))
		if(mversion >2012):
			if not cmds.pluginInfo(("matrixNodes.mll"),q=True,loaded=True):
				cmds.loadPlugin("matrixNodes.mll")
				#set autoloaded
				cmds.pluginInfo("matrixNodes.mll",e=True,autoload=True)
예제 #10
0
파일: apicache.py 프로젝트: SarielD/pymel
 def isPluginNode(nodeName):
     import maya.cmds as cmds
     for plugin in cmds.pluginInfo(q=1, listPlugins=True):
         plugNodes = cmds.pluginInfo(plugin, q=1, dependNode=True)
         # plugNodes may be None...
         if plugNodes and nodeName in plugNodes:
             return True
     return False
예제 #11
0
파일: RenderOps.py 프로젝트: ahmidou/aphid
 def load_plugin(self, pluginName):
     if self.is_plugin_loaded(pluginName):
         return True
     try:
         cmds.loadPlugin(pluginName, quiet=True)
         cmds.pluginInfo(pluginName, edit=True, autoload=True)
         return True
     except:
         return False
예제 #12
0
파일: util.py 프로젝트: Byron/bsuite
	def setUpAll(cls):
		if cls.env_var_plugin_path not in os.environ:
			raise AssertionError("Missing configuration variable: %s" % cls.env_var_plugin_path)
		#END handle conf
		cls.test_plugin_path = os.environ[cls.env_var_plugin_path]
		if not cmds.pluginInfo(cls.test_plugin_path, q=1, loaded=1):
			cmds.loadPlugin(cls.test_plugin_path)
			# even though loadPlugin may fail, it doesn't throw a runtime error
			if not cmds.pluginInfo(cls.test_plugin_path, q=1, loaded=1):
				raise AssertionError("Failed to load plugin at %s" % cls.test_plugin_path)
예제 #13
0
def checkPlugins(plugins):
    """Check if plugin are loaded."""
    pluginList = cmds.pluginInfo(query=True, listPlugins=True) or []
    for plugin in plugins:
        if plugin not in pluginList:
            loadPlugin(plugin)
    pluginList = cmds.pluginInfo(query=True, listPlugins=True) or []
    notloaded = [i for i in plugins if i not in pluginList]
    if notloaded:
        raise RuntimeError("Some plugins won't load: {}".format(', '.join(notloaded)))
예제 #14
0
	def test(self):
		"""
		Run an internal consistency test on the pattern creator to verify its
		functions are operating correctly.
		"""
		factoryIsLoaded = cmds.pluginInfo('pyJsonAttrPatternFactory.py', query=True, loaded=True)
		if not factoryIsLoaded:
			try:
				cmds.loadPlugin('pyJsonAttrPatternFactory.py', quiet=True)
			except:
				# Repotest environment won't find it so skip it then
				return False
		factoryIsLoaded = cmds.pluginInfo('pyJsonAttrPatternFactory.py', query=True, loaded=True)
		# If the environment isn't set up to find the plugin there's
		# nothing we can do about it. It's not a failure of the test so
		# don't report anything other than a warning that the test could
		# not be run.
		if not factoryIsLoaded:
			print 'Warning: JSON attribute pattern factory could not be loaded, test aborted'
			return False

		patterns = """
		[
			{
				"name": "testPattern",
				"attributes": [
					{
						"name"			: "floatWithRanges",
						"shortName"		: "fwr",
						"defaultValue"	: 0.5,
						"min"			: -10.0,
						"max"			: 20.0,
						"softMin"		: 1.0,
						"softMax"		: 10.0,
						"attributeType"	: "float"
					} ,
					{
						"name"			: "float3WithRanges",
						"shortName"		: "ftwr",
						"defaultValue"	: [7.5, 7.6, 7.7],
						"min"			: [-17.0, -17.1, -17.2],
						"max"			: [27.0, 27.1, 27.2],
						"attributeType"	: "float3"
					} 
				]
			}
		]
		"""
		cmds.createAttrPatterns( patternType='json', patternDefinition=patterns )
		cmds.file( force=True, new=True )
		node = cmds.createNode( 'addMatrix' )
		cmds.applyAttrPattern( node, patternName='testPattern' )

		jsonString = self.nodeAsJSON( node )
		print json.dumps(jsonString, indent=4)
예제 #15
0
파일: syntax.py 프로젝트: oglops/logcatMaya
    def _cmdsFunctionFormat(self):
        '''set up maya.cmds functions'''
        # mayaBinDir = os.path.dirname(sys.executable)
        # cmdsList = os.path.join(mayaBinDir, 'commandList')

        functions = '\\b('
        # with open(cmdsList) as phile:
        #     for line in phile:
        #         functions += line.split(' ')[0] + '|'

        maya_ver=utils.get_maya_version()
        maya_commands = utils.get_commands(version=maya_ver)
        for c in maya_commands:
            functions += c + '|'




        # global MEL procedures
        try:
            melProcedures = cmds.melInfo()
            maxlen = 1400
            stop = len(melProcedures) / maxlen
            melProc = []
            melProc.append('\\b(' + '|'.join(melProcedures[:maxlen]) + ')\\b')
            for i in range(1, stop - 1):
                start = maxlen * i
                end = maxlen * (i + 1)
                melProc.append('\\b(' + '|'.join(melProcedures[start:end]) + ')\\b')
            melProc.append('\\b(' + '|'.join(melProcedures[maxlen*stop:]) + ')\\b')
        except:
            pass

        # TODO: should update it when a plug-in was load.
        try:
            # function from plug-ins
            plugins = cmds.pluginInfo(q=1, listPlugins=1)
            for plugin in plugins:
                funcFromPlugin = cmds.pluginInfo(plugin, q=1, command=1)
                if funcFromPlugin:
                    functions += '|'.join(funcFromPlugin)
        except:
            pass

        functions = functions[:-1] + ')\\b'

        # function format
        funcFormat = QtGui.QTextCharFormat()
        funcFormat.setForeground(self._keywordColor)
        self.__rules.append((re.compile(functions), funcFormat))
        try:
            for mp in melProc:
                self.__rules.append((re.compile(mp), funcFormat))
        except:
            pass
예제 #16
0
def restoreShelves():
    #restore unloaded plugins
    plugins = prefs.unnecessaryPluginsForAnim
    for plugin in plugins:
        if not (cmds.pluginInfo(plugin, loaded=True, q=True)):
            try:
                cmds.loadPlugin(plugin)
                cmds.pluginInfo(plugin, autoload=True, e=True)
            except:
                print "{0} plugin doesn't exist in this version of Maya".format(plugin)
    #restoren shelves marked as *.deleted
    lib.restoreShelves()
예제 #17
0
파일: HComMayaUi.py 프로젝트: GJpy/HCom
 def _fetchHengine(self):
     
     v = cmds.about(version=True)
     hengineInfo = ""
     mayaType = HComMayaUtils.CLIENT_TYPE.MAYA_NO_HENGINE
     plugins = cmds.pluginInfo( query=True, listPlugins=True )
     if plugins:
         if "houdiniEngine" in cmds.pluginInfo( query=True, listPlugins=True ):
             hengineInfo = " (Houdini Engine Loaded)"
             mayaType = HComMayaUtils.CLIENT_TYPE.MAYA_HENGINE
         
     return [mayaType, "Maya " + str(v) + hengineInfo]
예제 #18
0
def flush():

	pluginPaths = map( Path, api.mel.eval( 'getenv MAYA_PLUG_IN_PATH' ).split( ';' ) )  #NOTE: os.environ is different from the getenv call, and getenv isn't available via python...  yay!

	#before we do anything we need to see if there are any plugins in use that are python scripts - if there are, we need to ask the user to close the scene
	#now as you might expect maya is a bit broken here - querying the plugins in use doesn't return reliable information - instead we ask for all loaded
	#plugins, to which maya returns a list of extension-less plugin names.  We then have to map those names back to disk by searching the plugin path and
	#determining whether the plugins are binary or scripted plugins, THEN we need to see which the scripted ones are unloadable.
	loadedPluginNames = cmd.pluginInfo( q=True, ls=True ) or []
	loadedScriptedPlugins = []
	for pluginName in loadedPluginNames:
		for p in pluginPaths:
			possiblePluginPath = (p / pluginName).setExtension( 'py' )
			if possiblePluginPath.exists():
				loadedScriptedPlugins.append( possiblePluginPath[-1] )

	initialScene = None
	for plugin in loadedScriptedPlugins:
		if not cmd.pluginInfo( plugin, q=True, uo=True ):
			BUTTONS = YES, NO = 'Yes', 'NO'
			ret = cmd.confirmDialog( t='Plugins in Use!', m="Your scene has python plugins in use - these need to be unloaded to properly flush.\n\nIs it cool if I close the current scene?  I'll prompt to save your scene...\n\nNOTE: No flushing has happened yet!", b=BUTTONS, db=NO )
			if ret == NO:
				print "!! FLUSH ABORTED !!"
				return

			initialScene = cmd.file( q=True, sn=True )

			#prompt to make new scene if there are unsaved changes...
			api.mel.saveChanges( 'file -f -new' )

			break

	#now unload all scripted plugins
	for plugin in loadedScriptedPlugins:
		cmd.unloadPlugin( plugin )  #we need to unload the plugin so that it gets reloaded (it was flushed) - it *may* be nessecary to handle the plugin reload here, but we'll see how things go for now

	#lastly, close all windows managed by baseMelUI - otherwise callbacks may fail...
	for melUI in baseMelUI.BaseMelWindow.IterInstances():
		melUI.delete()

	#determine the location of maya lib files - we don't want to flush them either
	mayaLibPath = Path( maya.__file__ ).up( 2 )

	#flush all modules
	dependencies.flush( [ mayaLibPath ] )

	if initialScene and not cmd.file( q=True, sn=True ):
		if Path( initialScene ).exists():
			cmd.file( initialScene, o=True )

	print "WARNING: You'll need to close and re-open any python based tools that are currently open..."
예제 #19
0
파일: procRender.py 프로젝트: snaress/bank
def loadMentalRay(currentEngine=True):
    """ Load Mental Ray plugin
        @param currentEngine: (bool) : Set MentalRay as current render engine """
    name = "Mayatomr"
    #-- Load MentalRay PlugIn --#
    if not mc.pluginInfo(name, q=True, loaded=True):
        print "Load MentalRayPlugin ..."
        mc.loadPlugin(name)
        mc.pluginInfo(name, edit=True, autoload=True)
    #-- Use MentalRay As Current Renderer --#
    if currentEngine:
        print "Set MentalRay as current render engine ..."
        mc.setAttr('defaultRenderGlobals.currentRenderer', 'mentalRay', type='string')
    print "# Result: mental ray Plugin loaded #"
예제 #20
0
 def animPlugin( self ):
     state = pluginInfo( 'animImportExport', q=True, loaded=True )
     if state == 0:
         platform = os.name
         print platform
         if platform == 'Linux':
             cmds.pluginInfo( '/software/apps/maya/2012.sp1/cent5.x86_64/bin/plug-ins/' + 'animImportExport', e=True, a=True )
             cmds.loadPlugin( 'animImportExport' )
         elif platform == 'nt':
             path = "C:\Program Files\Autodesk\Maya2013" + "\\" + "bin\plug-ins" + "\\" + "animImportExport.mll"
             print path
             cmds.pluginInfo( 'C:\Program Files\Autodesk\Maya2013\\bin\plug-ins\\' + 'animImportExport.mll', e=True, a=True )
             cmds.loadPlugin( 'animImportExport' )
         else:
             pass
예제 #21
0
def verifyPlugin(pluginName, requiredBy):
	"""
	Verify that a particular plug-in is loaded and attempt to load it if it
	cannot be found.
	@param pluginName Name of the plugin without extension
	@param requiredBy __file__ member of the caller
	"""
	try: tcpy.indexOf(pluginName, __allPlugins__)
	except:
		try:
			MC.loadPlugin('%s.py'%pluginName)
			MC.pluginInfo('%s.py'%pluginName, e=True, autoload=True)
		except:
			sys.stderr.write('Error: Could not locate the %s plug-in. It is required for the %s module.\nPlease ensure that %s.py is located somewhere in your plug-in path.\n' 
				%(pluginName, os.path.basename(requiredBy), pluginName))
 def __init__(self):
     # set up necessary plug-ins
     if not cmds.pluginInfo('nearestPointOnMesh', query=True, loaded=True):
         try:
             cmds.loadPlugin('nearestPointOnMesh')
         except NameError:
             pass
예제 #23
0
파일: userSetup.py 프로젝트: jonntd/helga
    def load_plugins_deferred():
        
        #plugin_list
        plugin_list = ['vrayformaya.mll', 
                        'rrSubmit_Maya_8.5+.py', 
                        'helga_asset_metadata.py', 
                        'helga_shots_metadata.py', 
                        'AnimSchoolPicker.mll',
                        'LBrush']
        

        #iterate plugin_list and load
        for plugin_name in plugin_list:
            try:
                
                if not(cmds.pluginInfo(plugin_name , query = True, loaded = True)):

                    try:
                        cmds.loadPlugin(plugin_name)
                        #Print to console instead of script editor
                        sys.__stdout__.write('->Successfully loaded ' +plugin_name +' deferred\n')
                    except:
                        sys.__stdout__.write('->Error loading ' +plugin_name +' deferred\n')
                
                else:
                    sys.__stdout__.write('->Skipped loading ' +plugin_name +' deferred. Plugin was already loaded\n')
            
            except:
                sys.__stdout__.write('->Error loading ' +plugin_name +' deferred\n')

        #Dividerline
        sys.__stdout__.write(DIVIDERLINE)
예제 #24
0
def snapObjectsOnSupport(objects, support):
	"""
	Snaps objects on support.

	:param objects: Objects to snap.
	:type objects: list
	:param value: Support.
	:type value: str
	"""

	if cmds.pluginInfo("nearestPointOnMesh", q=True, loaded=False):
		cmds.loadPlugin("nearestPointOnMesh")

	nearestPointOnMesh = cmds.createNode("nearestPointOnMesh")
	supportShape = getShapes(support)[0]
	cmds.connectAttr(supportShape + ".outMesh", nearestPointOnMesh + ".inMesh", f=True)

	allAxis = ("X", "Y", "Z")
	for object in objects:
		position = cmds.xform(object, q=True, rp=True, ws=True, a=True)
		for i, axis in enumerate(allAxis):
			cmds.setAttr(nearestPointOnMesh + ".inPosition" + axis, position[i])

		cmds.select(object)
		cmds.move(cmds.getAttr(nearestPointOnMesh + ".positionX"),
				cmds.getAttr(nearestPointOnMesh + ".positionY"),
				cmds.getAttr(nearestPointOnMesh + ".positionZ"),
				rpr=True)

	cmds.delete(nearestPointOnMesh)
예제 #25
0
	def post_standalone_initialized(self):
		from mrv.maya.util import OptionVarDict
		import maya.cmds as cmds
		import maya.mel
		
		ovars = OptionVarDict()
		ovar = "TEST_OVAR"
		
		# check runtime comamnds
		assert 'MyTestRuntimeCommand' in (cmds.runTimeCommand(q=1, uca=1) or list())
		
		plugins = ("ge2Export", "decomposeMatrix")
		for plugname in plugins:
			assert cmds.pluginInfo(plugname, q=1, loaded=1)
		# check auto load plugins
		
		
		# check option vars
		assert ovar in ovars
		assert ovars[ovar] == 3 
		
		# check user setup
		tscript = """global int $gTestVar;
		if( $gTestVar != 5 ){
			error("AssertionError, global variable was not set");
		}"""
		maya.mel.eval(tscript)		# shouldn't raise
		assert hasattr(sys, 'userSetup') and sys.userSetup == True
def cameraFrustum_build(cam_shape):
    #make sure a camera is loaded
    if cam_shape==0:
        cmds.error('no camera loaded...select a camera and load')
    else:
    #create frustum only if one doesnt already exist
        selCamXform = cmds.listRelatives(cam_shape[0], p=1)
        prefix = 'frust_'
        frustumGrpName = prefix + 'camera_frustum_all_grp'
        if cmds.objExists(frustumGrpName)==0:
        #create main grp
            frustumMainGrp = cmds.group(em=1, n=frustumGrpName);
            cmds.setAttr(frustumGrpName + '.tx', lock=1, keyable=0, channelBox=0)
            cmds.setAttr(frustumGrpName + '.ty', lock=1, keyable=0, channelBox=0)
            cmds.setAttr(frustumGrpName + '.tz', lock=1, keyable=0, channelBox=0)
            cmds.setAttr(frustumGrpName + '.rx', lock=1, keyable=0, channelBox=0)
            cmds.setAttr(frustumGrpName + '.ry', lock=1, keyable=0, channelBox=0)
            cmds.setAttr(frustumGrpName + '.rz', lock=1, keyable=0, channelBox=0)
            cmds.setAttr(frustumGrpName + '.sx', lock=1, keyable=0, channelBox=0)
            cmds.setAttr(frustumGrpName + '.sy', lock=1, keyable=0, channelBox=0)
            cmds.setAttr(frustumGrpName + '.sz', lock=1, keyable=0, channelBox=0)
            cmds.setAttr(frustumGrpName + '.v', lock=1, keyable=0, channelBox=0)

        #create frustum geo
            frustumGeo = cmds.polyCube(w=2, h=2, d=2, n=prefix + 'camera_frustum_geo')
            cmds.delete(frustumGeo[0], constructionHistory=True)
            cmds.parent(frustumGeo[0], frustumMainGrp)

        #load plugin "nearestPointOnMesh.mll" if needed and connect
            plugin = cmds.pluginInfo('nearestPointOnMesh.mll', q=1, l=1)
            if plugin==0:
                cmds.loadPlugin('nearestPointOnMesh.mll')

            nearNodeName = prefix + 'npomNode'
            npomNode = cmds.createNode('nearestPointOnMesh', n=nearNodeName)
            cmds.connectAttr(frustumGeo[0] + '.worldMesh', npomNode + '.inMesh')

        #create clusters
            cmds.select(frustumGeo[0] + '.vtx[4:7]', r=1)
            nearCluster = cmds.cluster(n=prefix + 'camera_nearFrustum_cluster')
            cmds.select(frustumGeo[0] + '.vtx[0:3]', r=1)
            farCluster = cmds.cluster(n=prefix + 'camera_farFrustum_cluster')

        #create near/far/camera locs
            cameraLoc = cmds.spaceLocator(p=(0, 0, 0), n=prefix + 'camera_loc')
            cmds.parent(cameraLoc[0], frustumMainGrp)
            nearLoc = cmds.spaceLocator(p=(0, 0, 0), n=prefix + 'camera_nearFrustum_loc')
            cmds.move(0, 0, -1)
            farLoc = cmds.spaceLocator(p=(0, 0, 0), n=prefix + 'camera_farFrustum_loc')
            cmds.move(0, 0, 1)

        #parent clusters under loc -- parent locs under camera loc
            cmds.parent(nearCluster[1], nearLoc[0])
            cmds.parent(farCluster[1], farLoc[0])
            cmds.parent(nearLoc[0], cameraLoc[0])
            cmds.parent(farLoc[0], cameraLoc[0])
        #constrain camera loc to camera
            cmds.parentConstraint(selCamXform, cameraLoc, weight=1)

        return frustumGeo[0]
예제 #27
0
def loadPlugin():
	'''
	Load edgFlowMirror plugin.
	'''
	if not mc.pluginInfo('edgeFlowMirror',q=True,l=True):
		mc.loadPlugin('edgeFlowMirror')
	return 1
예제 #28
0
def validateRenderer():
	strPlugin = getPluginName()
	if(len(strPlugin) == 0):
		return False

	# Most renderers are in plugins, so by locating that we indentify that the renderer is valid.
	pluginLoaded = cmds.pluginInfo(strPlugin, q=True, l=True)

	# Modo is not a plugin, so check separatly for that if we failed above.
	if(pluginLoaded == False):
		if cmds.getAttr('defaultRenderGlobals.ren') == 'modoRender':
			pluginLoaded = True

	if(pluginLoaded == False):
		# Craft the error string (watching for modo special case).
		if strPlugin == "ModoRender":
			strError = strPlugin + " is not selected or registered - cannot support this renderer at this time"
		else:
			strError = strPlugin + ".mll plugin is not loaded - cannot support this renderer at this time"        

		cmds.scrollField("rendererErrorText", edit=True, text=strError)
		return False

	cmds.scrollField("rendererErrorText", edit=True, text="Maya plugin for Host Renderer detected")
	return True
예제 #29
0
def setTool_hardSkinWeightBrush( evt=0 ):

    appendPluginPath()
    _cmdStr =  """global string $tf_skinSmoothPatin_selection[];
    
    global proc tf_smoothBrush( string $context )     
    {       
     artUserPaintCtx -e -ic "tf_init_smoothBrush"
     -svc "tf_set_smoothBrushValue"
     -fc "" -gvc "" -gsc "" -gac "" -tcc "" $context;
    }
    
    global proc tf_init_smoothBrush( string $name )
    {
        string $sel[] = `ls -sl -fl`;
        string $obj[] = `ls -sl -o`;
        
        sgSmoothWeightCommand $obj;
    }
    
    global proc tf_set_smoothBrushValue( int $slot, int $index, float $val )             
    {         
        sgSmoothWeightCommand -h 1 -i $index -w $val;
    }
    
    ScriptPaintTool;     
    artUserPaintCtx -e -tsc "tf_smoothBrush" `currentCtx`;"""
    
    if not cmds.pluginInfo( 'sgSmoothWeightCommand', q=1, l=1 ):
        cmds.loadPlugin( 'sgSmoothWeightCommand' )
    mel.eval( _cmdStr )
예제 #30
0
def _deleteTurtleNodes(*args):
    pluginName = 'Turtle'
    dn = cmds.pluginInfo(pluginName,q=True,dn=True)
    turtleNodes = cmds.ls(type=dn)
    cmds.lockNode(turtleNodes,l=False)
    cmds.delete(turtleNodes)
    return 0
예제 #31
0
def get_mask():
    if cmds.pluginInfo(PLUG_IN_NAME, q=True, loaded=True):
        nodes = cmds.ls(type=NODE_NAME)
        if len(nodes) > 0:
            return nodes[0]
    return None
예제 #32
0
    def accept(self, settings, item):
        """
        Method called by the publisher to determine if an item is of any
        interest to this plugin. Only items matching the filters defined via the
        item_filters property will be presented to this method.

        A publish task will be generated for each item accepted here. Returns a
        dictionary with the following booleans:

            - accepted: Indicates if the plugin is interested in this value at
                all. Required.
            - enabled: If True, the plugin will be enabled in the UI, otherwise
                it will be disabled. Optional, True by default.
            - visible: If True, the plugin will be visible in the UI, otherwise
                it will be hidden. Optional, True by default.
            - checked: If True, the plugin will be checked in the UI, otherwise
                it will be unchecked. Optional, True by default.

        :param settings: Dictionary of Settings. The keys are strings, matching
            the keys returned in the settings property. The values are `Setting`
            instances.
        :param item: Item to process

        :returns: dictionary with boolean keys accepted, required and enabled
        """

        accepted = True
        publisher = self.parent
        template_name = settings["Publish Template"].value

        # SSE: we want this off by default when the UI starts, see also return
        # below (DW 2020-07-28)
        checked = False

        # SSE: check that the Maya-to-Arnold 'mtoa' plug-in is available to
        # allow ASS exports (DW 2020-07-28)
        if not cmds.pluginInfo('mtoa', q=True, l=True):
            self.logger.debug(
                "Item not accepted because the Arnold plugin needed to export "
                "Standins is not loaded!")
            accepted = False

        # ensure a work file template is available on the parent item
        work_template = item.parent.properties.get("work_template")
        if not work_template:
            self.logger.debug(
                "A work template is required for the session item in order to "
                "publish an ASS file. Not accepting ASS item.")
            accepted = False

        # ensure the publish template is defined and valid and that we also have
        publish_template = publisher.get_template_by_name(template_name)
        if not publish_template:
            self.logger.debug(
                "The valid publish template could not be determined for the "
                "ASS item. Not accepting the item.")
            accepted = False

        # we've validated the publish template. add it to the item properties
        # for use in subsequent methods
        item.properties["publish_template"] = publish_template

        # because a publish template is configured, disable context change. This
        # is a temporary measure until the publisher handles context switching
        # natively.
        item.context_change_allowed = False

        return {"accepted": accepted, "checked": checked}
예제 #33
0
    def on_action_create(self, *args):
        sName = self.ui.edtNewName.text()

        # loading Maya matrix node
        if not (cmds.pluginInfo("decomposeMatrix", query=True, loaded=True)):
            try:  # Maya 2012
                cmds.loadPlugin("decomposeMatrix.mll")
            except:
                try:  # Maya 2013 or earlier
                    cmds.loadPlugin("matrixNodes.mll")
                except:
                    print self.langDic[
                        self.langName]['e002_decomposeMatrixNotFound']

        aSel = pymel.selected()
        if (len(aSel) == 2):
            #Create the container of the system data
            pData = PoseReaderData()
            with pymel.UndoChunk():
                #Get Needed matrix information
                pData.nParent = aSel[1]
                pData.nChild = aSel[0]
                m4ParentMat = pData.nParent.getMatrix(worldSpace=True)
                m4ChildMat = pData.nChild.getMatrix(worldSpace=True)

                #Create the two node needed to extract the rotation
                pData.nPGrp = pymel.createNode("transform",
                                               name=sName +
                                               "_PoseReader_Parent_Grp",
                                               p=pData.nParent)
                pData.nPGrp.setMatrix(m4ChildMat, worldSpace=True)
                pData.nParentLoc = self.createLoc(
                    sName + "_AngExtract_ParentLoc", pData.nPGrp)

                pData.nCGrp = pymel.createNode("transform",
                                               name=sName +
                                               "_PoseReader_Child_Grp",
                                               p=pData.nChild)
                pData.nCGrp.setMatrix(m4ChildMat, worldSpace=True)
                pData.nChildLoc = self.createLoc(
                    sName + "_AngExtract_ChildLoc", pData.nCGrp)
                #Add usefull attributes for the tool
                pData.nChildLoc.setDynamicAttr("posereaderdata", True)
                pData.nChildLoc.addAttr("angleMaxValue", min=-360.0, max=360.0)
                pData.nChildLoc.setAttr("angleMaxValue",
                                        180,
                                        edit=True,
                                        keyable=False,
                                        lock=False)
                pData.nChildLoc.addAttr("axis", at="enum", enumName="X:Y:Z")
                pData.nChildLoc.setAttr("axis",
                                        1,
                                        edit=True,
                                        keyable=False,
                                        lock=False)

                #Setup the rotation extaction
                pData.nMultM = pymel.createNode("multMatrix",
                                                name=sName + "_ExtactAngle_MM")
                pymel.connectAttr(pData.nChildLoc.worldMatrix[0],
                                  pData.nMultM.matrixIn[0])
                pymel.connectAttr(pData.nParentLoc.worldInverseMatrix[0],
                                  pData.nMultM.matrixIn[1])
                pData.nDecM = pymel.createNode("decomposeMatrix",
                                               name=sName + "_ExtractAngle_DM")
                pymel.connectAttr(pData.nMultM.matrixSum,
                                  pData.nDecM.inputMatrix)

                #Setup the rotation affection
                pData.nMD = pymel.createNode("multiplyDivide",
                                             name=sName + "_NormValue_MD")
                pData.nMD.operation.set(2)
                pymel.connectAttr(pData.nDecM.outputRotateY, pData.nMD.input1X)
                pymel.connectAttr(pData.nChildLoc.angleMaxValue,
                                  pData.nMD.input2X)
                pData.nCD = pymel.createNode("condition",
                                             name=sName + "_SmallerThanOne_CD")
                pymel.connectAttr(pData.nMD.outputX, pData.nCD.firstTerm)
                pymel.connectAttr(pData.nMD.outputX, pData.nCD.colorIfTrueR)
                pData.nCD.secondTerm.set(1)
                pData.nCD.operation.set(5)  #Less or equal
                pData.nCDNoNeg = pymel.createNode("condition",
                                                  name=sName + "_OverZero_CD")
                pymel.connectAttr(pData.nCD.outColorR,
                                  pData.nCDNoNeg.firstTerm)
                pymel.connectAttr(pData.nCD.outColorR,
                                  pData.nCDNoNeg.colorIfTrueR)
                pData.nCDNoNeg.secondTerm.set(0)
                pData.nCDNoNeg.colorIfFalseR.set(0)
                pData.nCDNoNeg.operation.set(3)  #Greater or Equal

                #Node for manual activation connection
                pData.nMDActive = pymel.createNode("multiplyDivide",
                                                   name=sName + "_Active_MD")
                pymel.connectAttr(pData.nCDNoNeg.outColorR,
                                  pData.nMDActive.input1X)

            #for o in pData.__dict__:
            #print o

            libSerialization.export_network(pData)
            self.addItem(pData)
        else:
            pymel.confirmDialog(
                title='Selection Problem',
                message='You need to have exactly two nodes selected')
예제 #34
0
파일: __init__.py 프로젝트: pbiswal/pymel
def _pluginLoaded(*args):
    global _pluginData

    if len(args) > 1:
        # 2009 API callback, the args are ( [ pathToPlugin, pluginName ], clientData )
        pluginName = args[0][1]
    else:
        pluginName = args[0]
    pluginName = _stripPluginExt(pluginName)

    if not pluginName:
        return

    # Check to see if plugin is really loaded
    if not (cmds.pluginInfo(pluginName, query=1, loaded=1)):
        return

    # Make sure there are no registered callbacks for this plug-in. It has been
    # reported that some 3rd party plug-ins will enter here twice, causing a
    # "callback id leak" which potentially leads to a crash. The reported
    # scenario was:
    # - Launching mayapy.exe
    # - Opening a Maya scene having a requires statement (to the plug-in)
    # - The plug-in imports pymel, causing initialization and entering here.
    if (pluginName in _pluginData) and 'callbackId' in _pluginData[pluginName] \
            and _pluginData[pluginName]['callbackId'] != None:
        _api.MEventMessage.removeCallback(
            _pluginData[pluginName]['callbackId'])

    _logger.debug("Plugin loaded: %s", pluginName)
    _pluginData[pluginName] = {}

    # Commands
    commands = _plugins.pluginCommands(pluginName)

    if commands:
        # clear out the command list first
        _pluginData[pluginName]['commands'] = []
        for funcName in commands:
            try:
                _addPluginCommand(pluginName, funcName)
            except Exception as e:
                _logger.error("Error adding command %s from plugin %s - %s" %
                              (funcName, pluginName, e))
                _logger.debug(traceback.format_exc())

    # Nodes
    try:
        mayaTypes = cmds.pluginInfo(pluginName, query=1, dependNode=1)
    except Exception:
        _logger.error("Failed to get depend nodes list from %s", pluginName)
        mayaTypes = None
    #apiEnums = cmds.pluginInfo(pluginName, query=1, dependNodeId=1)
    if mayaTypes:

        def addPluginPyNodes(*args):
            try:
                id = _pluginData[pluginName].get('callbackId')
            except KeyError:
                _logger.warning("could not find callback id!")
            else:
                if id is not None:
                    _api.MEventMessage.removeCallback(id)
                    if hasattr(id, 'disown'):
                        id.disown()

            _pluginData[pluginName]['dependNodes'] = []
            allTypes = set(cmds.ls(nodeTypes=1))
            for mayaType in mayaTypes:
                # make sure it's a 'valid' type - some plugins list node types
                # that don't show up in ls(nodeTypes=1), and aren't creatable
                # ...perhaps they're abstract types?
                # Unfortunately, can't check this, as only plugin I know of
                # that has such a node - mayalive, mlConstraint - is only
                # available up to 2009, which has a bug with allNodeTypes...
                # Oddly enough, mlConstraint WILL show up in allTypes here,
                # but not after the plugin is loaded / callback finishes...?
                if mayaType not in allTypes:
                    continue
                _addPluginNode(pluginName, mayaType)

        # Note - in my testing, a single _api.MFileIO.isReadingFile() call would
        # also catch opening + referencing operations... but in commit
        # 6e53d7818e9363d55d417c3a80ea7df94c4998ec, a check only against
        # isReadingFile is commented out... so I'm playing it safe, and assuming
        # there are edge cases where isOpeningFile is True but isReadingFile is
        # not

        # Detect if we are currently opening/importing a file and load as a callback versus execute now
        if (_api.MFileIO.isReadingFile() or _api.MFileIO.isOpeningFile()
                or _api.MFileIO.isReferencingFile()):
            if _api.MFileIO.isReferencingFile():
                _logger.debug(
                    "Installing temporary plugin-loaded nodes callback - PostSceneRead"
                )
                id = _api.MEventMessage.addEventCallback(
                    'PostSceneRead', addPluginPyNodes)
            elif _api.MFileIO.isImportingFile():
                _logger.debug(
                    "Installing temporary plugin-loaded nodes callback - SceneImported"
                )
                id = _api.MEventMessage.addEventCallback(
                    'SceneImported', addPluginPyNodes)
            else:
                # pre-2012 referencing operations will fall into this branch,
                # which will not work (ie, pre-2012, plugins loaded due to
                # reference loads will not trigger adding of that plugin's
                # PyNodes).
                # While this is obviously less than ideal, no 2011 versions were
                # available for testing when I made the fix for 2012+, and we
                # decided that making nothing worse would be better than
                # potentially introducing problems/instabilities (ie, see
                # messages in commits 6e53d7818e9363d55d417c3a80ea7df94c4998ec
                # and 81bc5ee28f1775a680449fec8724e21e703a52b8).
                _logger.debug(
                    "Installing temporary plugin-loaded nodes callback - SceneOpened"
                )
                id = _api.MEventMessage.addEventCallback(
                    'SceneOpened', addPluginPyNodes)
            _pluginData[pluginName]['callbackId'] = id
            # scriptJob not respected in batch mode, had to use _api
            #cmds.scriptJob( event=('SceneOpened',doSomethingElse), runOnce=1 )
        else:
            _logger.debug("Running plugin-loaded nodes callback")
            # add the callback id as None, so addPluginPyNodes SHOULD know that
            # SOMETHING is always in _pluginData[pluginName]['callbackId'], and
            # if there isn't, then something is wrong...
            _pluginData[pluginName]['callbackId'] = None
            addPluginPyNodes()
예제 #35
0
def pluginLoaded():
    if os.name != 'posix':
        return cmds.pluginInfo('MayaCollabPlugin', query=True, loaded=True)
    else:
        return cmds.pluginInfo('libMayaCollabPlugin', query=True, loaded=True)
예제 #36
0
"""

 Apply Redshift wireframe shader to selected objects
 @Guilherme Trevisan - [email protected] - 2020-11-04
 
 1.0 - 2020-11-04
 Initial Release

"""
import maya.cmds as cmds

redshift_plugin = 'redshift4maya'

# Load Redshift
if not cmds.pluginInfo(redshift_plugin, q=True, loaded=True):
    try:
        cmds.loadPlugin(redshift_plugin)
    except:
        message = '<span style=\"color:#FF0000;text-decoration:underline;\">Redshift</span> doesn\'t seem to be installed.'
        cmds.inViewMessage(amg=message, pos='botLeft', fade=True, alpha=.9)

is_redshift_available = False
if cmds.pluginInfo(redshift_plugin, q=True, loaded=True):
    is_redshift_available = True


def create_wireframe_node(destination_input):
    rs_wireframe_node = cmds.createNode("RedshiftWireFrame")
    cmds.connectAttr(rs_wireframe_node + '.outColor',
                     destination_input,
                     force=True)
예제 #37
0
    def k_checkassfiles(self):
        #maya节点返回的路径
        kassdso = []
        #记录文件夹内里的文件,避免重复对网络进行获取
        kassfilepath = {}

        self.kexpo = r'(.*?)([\._])([#]*)([\.]?)([#]*)(\.ass\.gz|\.ass|\.obj|\.ply|\.asstoc)$'
        #self.kexpo2 = r'(.*?)([\._])([0-9#]*)([\.]?)([0-9#]*)(\.ass\.gz|\.ass|\.obj|\.ply)$'

        if cc.pluginInfo("mtoa", q=1, l=1):

            version = cc.pluginInfo("mtoa", q=1, v=1)
            self.mayaplugin_version.update({'Arnold': version})
            kassmeshs = cc.ls(type='aiStandIn')

            for kassmesh in kassmeshs:
                #先判断是否无下游输出的节点
                krassmesh = cc.listConnections(kassmesh, s=0, d=1)
                #kcassmesh=cc.listConnections((kassmesh+'.transOp'),s=0,d=1)
                if krassmesh:
                    #print 'kassmesh  '+str(kassmesh)
                    assdsom = cc.getAttr(kassmesh + '.dso')

                    #判断是否为绝对路径
                    if assdsom and not os.path.isabs(assdsom):
                        assdso = self.projectDir + assdsom

                    assdso = assdsom.replace('\\', '/')

                    #获取 缓存名 与 路径
                    assmesh_getpath = os.path.basename(assdso)
                    #print 'assdso  '+str(assdso)
                    assmeshpath = os.path.dirname(assdso)
                    #print 'assmeshpath  '+str(assmeshpath)

                    #先判断有无重复检查
                    if assdsom and not assdsom in kassdso:
                        kassdso.append(assdsom)
                        #如果路径出现过
                        if assmeshpath in kassfilepath:
                            #k_filterseq=[]
                            #asspathfiles=os.listdir(assmeshpath)
                            asspathfiles = kassfilepath[assmeshpath]
                            #print 'asspathfiles  '+str(asspathfiles)
                            krseqfile = self.k_filterassfile(
                                assdso, asspathfiles, kassmesh)
                            #self.kassfiles.append(krseqfile)
                        else:
                            asspathfiles = []
                            #判断是否能根据文件夹 返回 文件夹里面的所有文件
                            try:
                                asspathfiles = os.listdir(assmeshpath)
                            except WindowsError:
                                #print e.message
                                pass

                            #print 'asspathfiles  '+str(asspathfiles)
                            krseqfile = self.k_filterassfile(
                                assdso, asspathfiles, kassmesh)
                            #self.kassfiles.append(krseqfile)

                            k_update = {assmeshpath: asspathfiles}
                            kassfilepath.update(k_update)
예제 #38
0
    def k_checkTexfiles(self):
        texfiles = cc.ls(type='file')
        for texfile in texfiles:
            #判断有无自定义属性
            userAttrs = cc.listAttr(texfile, ud=1)
            if userAttrs:
                #获取有无UDIM模式
                ktexmode = cc.getAttr(texfile + '.uvTilingMode')
                #如果无:
                if not ktexmode:
                    for userAttr in userAttrs:
                        #判断自定义内容是否 Tex 开头
                        if userAttr[:3] == 'Tex':
                            #获取自定义属性的 内容
                            userTex = cc.getAttr(texfile + "." + userAttr)

                            #设置节点内容 及 加入到节点数据
                            ktemp = {'path': userTex, 'userAttr': userAttr}
                            if self.kNodedate.has_key('kmayaTex_userTex'):
                                if self.kNodedate['kmayaTex_userTex'].has_key(
                                        texfile):
                                    self.kNodedate['kmayaTex_userTex'][
                                        texfile].append(ktemp)
                                else:
                                    self.kNodedate['kmayaTex_userTex'].update(
                                        {texfile: [ktemp]})
                            else:
                                self.kNodedate['kmayaTex_userTex'] = {
                                    texfile: [ktemp]
                                }

                            #添加入总数组
                            if userTex and not userTex in self.kmayaTex:
                                if os.path.exists(userTex):
                                    #print texfile
                                    self.kmayaTex.append(userTex)
                                    #print userTex
                                    userTex_tx = os.path.splitext(
                                        userTex)[0] + '.tx'
                                    if os.path.exists(
                                            userTex_tx
                                    ) and not userTex_tx in self.kmayaTex:
                                        self.kmayaTex.append(userTex_tx)
                                        #print userTex_tx

                #有UDIM模式
                else:
                    for userAttr in userAttrs:
                        #判断自定义内容是否 Tex 开头
                        if userAttr[:3] == 'Tex':
                            userTex = cc.getAttr(texfile + "." + userAttr)

                            #设置节点内容 及 加入到节点数据
                            ktemp = {'path': userTex, 'userAttr': userAttr}
                            if self.kNodedate.has_key('kmayaTex_userTex'):
                                if self.kNodedate['kmayaTex_userTex'].has_key(
                                        texfile):
                                    self.kNodedate['kmayaTex_userTex'][
                                        texfile].append(ktemp)
                                else:
                                    self.kNodedate['kmayaTex_userTex'].update(
                                        {texfile: [ktemp]})
                            else:
                                self.kNodedate['kmayaTex_userTex'] = {
                                    texfile: [ktemp]
                                }

                            #获取自定义内容 的UDIM贴图
                            k_getUDIMp = k.getFilePatternString(
                                userTex, False, ktexmode)
                            k_exudims = k.findAllFilesForPattern(
                                k_getUDIMp, None)
                            #添加贴图入总数组
                            for k_exudim in k_exudims:
                                if k_exudim and not k_exudim in self.kmayaTex:
                                    #print texfile
                                    self.kmayaTex.append(k_exudim)
                                    #print k_exudim

                                    k_exudim_tx = os.path.splitext(
                                        k_exudim)[0] + '.tx'
                                    if os.path.exists(
                                            k_exudim_tx
                                    ) and not k_exudim_tx in self.kmayaTex:
                                        self.kmayaTex.append(k_exudim_tx)
                                        #print k_exudim_tx

            else:
                ktexfile = cc.getAttr(texfile + '.fileTextureName')
                ktexmode = cc.getAttr(texfile + '.uvTilingMode')

                #设置节点内容 及 加入到节点数据
                ktemp = {'path': ktexfile}
                if self.kNodedate.has_key('kmayaTex_default'):
                    self.kNodedate['kmayaTex_default'].update(
                        {texfile: [ktemp]})
                else:
                    self.kNodedate['kmayaTex_default'] = {texfile: [ktemp]}

                if not ktexmode:
                    if ktexfile and not os.path.isabs(ktexfile):
                        ktexfile = self.projectDir + ktexfile
                    ktexfile = ktexfile.replace('\\', '/')
                    if ktexfile and not ktexfile in self.kmayaTex:
                        if os.path.exists(ktexfile):
                            #print texfile
                            self.kmayaTex.append(ktexfile)
                            #print ktexfile

                            ktexfile_tx = os.path.splitext(ktexfile)[0] + '.tx'
                            if os.path.exists(
                                    ktexfile_tx
                            ) and not ktexfile_tx in self.kmayaTex:
                                self.kmayaTex.append(ktexfile_tx)
                                #print ktexfile_tx

                else:
                    if ktexfile and not os.path.isabs(ktexfile):
                        ktexfile = self.projectDir + ktexfile
                    ktexfile = ktexfile.replace('\\', '/')
                    #maya内部UDIM命令
                    k_getUDIMp = k.getFilePatternString(
                        ktexfile, False, ktexmode)
                    k_exudim = k.findAllFilesForPattern(k_getUDIMp, None)
                    for ktexfile in k_exudim:
                        if ktexfile and not ktexfile in self.kmayaTex:
                            #print texfile
                            self.kmayaTex.append(ktexfile)
                            #print ktexfile

                            ktexfile_tx = os.path.splitext(ktexfile)[0] + '.tx'
                            if os.path.exists(
                                    ktexfile_tx
                            ) and not ktexfile_tx in self.kmayaTex:
                                self.kmayaTex.append(ktexfile_tx)
                                #print ktexfile_tx

        #先判断插件有没开,防止找不到节点类型
        if cc.pluginInfo("mtoa", q=1, l=1):
            aiTexfiles = cc.ls(type='aiImage')
            if aiTexfiles:
                for aiTexfile in aiTexfiles:
                    #返回文件路径
                    aiTexfilesname = cc.getAttr(aiTexfile + '.filename')
                    #判断是否为空 及 在总数组有无重复 及 文件是否存在
                    if aiTexfilesname and not aiTexfilesname in self.kaiTex:
                        if os.path.exists(aiTexfilesname):
                            #print aiTexfilesname
                            self.kaiTex.append(aiTexfilesname)

                            #判断此文件有无tx版本的路径
                            aiTexfilesname_tx = os.path.splitext(
                                aiTexfilesname)[0] + '.tx'
                            #判断文件是否存在 及 在总数组有无重复
                            if os.path.exists(
                                    aiTexfilesname_tx
                            ) and not aiTexfilesname_tx in self.kaiTex:
                                self.kaiTex.append(aiTexfilesname_tx)
                                #print aiTexfilesname_tx

        #先判断插件有没开,防止找不到节点类型
        if cc.pluginInfo("vrayformaya", q=1, l=1):
            Vptexfiles = cc.ls(type='VRayPtex')
            if Vptexfiles:
                for Vptexfile in Vptexfiles:
                    #返回文件路径
                    Vptexfilename = cc.getAttr(Vptexfile + '.ptexFile')
                    #判断是否为空 及 在总数组有无重复 及 文件是否存在
                    if Vptexfilename and not Vptexfilename in self.kVpTex:
                        if os.path.exists(Vptexfilename):
                            #print Vptexfilename
                            self.kaiTex.append(Vptexfilename)

                            #判断此文件有无tx版本的路径
                            Vptexfilename_tx = os.path.splitext(
                                Vptexfilename)[0] + '.tx'
                            #判断文件是否存在 及 在总数组有无重复
                            if os.path.exists(
                                    Vptexfilename_tx
                            ) and not Vptexfilename_tx in self.kaiTex:
                                self.kaiTex.append(Vptexfilename_tx)
                                #print Vptexfilename_tx

        self.kTexture = list(set(self.kmayaTex + self.kaiTex + self.kVpTex))
예제 #39
0
    def k_checkYeticache(self):
        #缓存匹配公式
        self.kexpo3 = r'(.*?)([\.]?)([%][0-9]*d)(\.fur)$'
        #贴图匹配公式
        self.kexpo4 = r'(.*?)([\.]?)([%][0-9]*d)(\.png|\.tif|\.exr)$'
        self.kexpu4 = r'(.*)(\.png|\.tif|\.exr)$'
        #节点返回的路径存放地  为了不重复检查

        if cc.pluginInfo("pgYetiMaya", q=1, l=1):
            yetis = cc.ls(type='pgYetiMaya')

            version = cc.pluginInfo("pgYetiMaya", q=1, v=1)
            self.mayaplugin_version.update({'Yeti': version})

            for yeti in yetis:
                yeticache = cc.getAttr(yeti + '.cacheFileName')

                #判断是否绝对路径
                if yeticache and not os.path.isabs(yeticache):
                    yeticache = self.projectDir + yeticache

                if yeticache:

                    #设置节点内容 及 加入到节点数据
                    ktemp = {'path': yeticache}
                    if self.kNodedate.has_key('kYeticache'):
                        self.kNodedate['kYeticache'].update({yeti: [ktemp]})
                    else:
                        self.kNodedate['kYeticache'] = {yeti: [ktemp]}

                    #获取 缓存名 与 路径
                    yeticache_name = os.path.basename(yeticache)
                    yeticache_dir = os.path.dirname(yeticache)

                    pattern = re.search(self.kexpo3, yeticache)

                    if pattern:
                        try:
                            #返回路径下的所谓文件
                            yeticachefiles = os.listdir(yeticache_dir)
                            for yeticachefile in yeticachefiles:
                                #print yeticachefile
                                #匹配
                                kexpc = r'%s%s([0-9]*)(\.fur)$' % (
                                    pattern.group(1), pattern.group(2))

                                #判断是否在盘的根目录   防止出现E://xxxxx 这种情况
                                if yeticache_dir[-2:] == ':/':
                                    yeticachefilef = yeticache_dir + yeticachefile
                                else:
                                    yeticachefilef = yeticache_dir + '/' + yeticachefile

                                pattern2 = re.search(kexpc, yeticachefilef)
                                if pattern2 and not yeticachefilef in self.kYeticache:
                                    self.kYeticache.append(yeticachefilef)
                                    #print yeticachefilef

                        except:
                            #print e.message
                            pass

                    else:
                        #非序列的文件
                        if os.path.exists(
                                yeticache
                        ) and not yeticache in self.kYeticache:
                            self.kYeticache.append(yeticache)
                            #print yeticache

                #pgYetiGraph为 yeti提供的mel
                try:
                    yetiTexs = cc.pgYetiGraph(yeti,
                                              listNodes=True,
                                              type='texture')

                    if yetiTexs:

                        for yetiTex in yetiTexs:
                            #获取yeti Graph里面的节点 及 参数
                            yetiTexfile = cc.pgYetiGraph(yeti,
                                                         node=yetiTex,
                                                         param='file_name',
                                                         getParamValue=True)
                            if yetiTexfile and not os.path.isabs(yetiTexfile):
                                yetiTexfile = self.projectDir + yetiTexfile
                            yetiTexfile = yetiTexfile.replace('\\', '/')

                            if yetiTexfile:

                                #设置节点内容 及 加入到节点数据

                                ktemp = {
                                    'path': yetiTexfile,
                                    'texNode': yetiTex
                                }

                                if self.kNodedate.has_key('kYetitex'):
                                    #一个maya节点内 如果有多个 Yeti贴图节点 用数组添加法
                                    if self.kNodedate['kYetitex'].has_key(
                                            yeti):
                                        self.kNodedate['kYetitex'][
                                            yeti].append(ktemp)
                                    else:
                                        self.kNodedate['kYetitex'].update(
                                            {yeti: [ktemp]})

                                else:
                                    self.kNodedate['kYetitex'] = {
                                        yeti: [ktemp]
                                    }

                                yetiTex_name = os.path.basename(yetiTexfile)
                                yetiTex_dir = os.path.dirname(yetiTexfile)

                                patternt = re.search(self.kexpo4, yetiTexfile)
                                #匹配是否为序列格式
                                if patternt:
                                    try:
                                        YetiTexfiles = os.listdir(yetiTex_dir)
                                        for YetiTexfile in YetiTexfiles:
                                            #print yeticachefile
                                            kexpt = r'%s%s([0-9]*)(\.png|\.tif|\.exr)$' % (
                                                patternt.group(1),
                                                patternt.group(2))
                                            #判断是否在盘的根目录   防止出现E://xxxxx 这种情况
                                            if yetiTex_dir[-2:] == ':/':
                                                YetiTexfilef = yetiTex_dir + YetiTexfile
                                            else:
                                                YetiTexfilef = yetiTex_dir + '/' + YetiTexfile
                                            #匹配完整路径格式
                                            pattern = re.search(
                                                kexpt, YetiTexfilef)
                                            if pattern and not YetiTexfilef in self.kYetitex:
                                                self.kYetitex.append(
                                                    YetiTexfilef)
                                                print YetiTexfilef
                                    except:
                                        #print e.message
                                        pass
                                else:
                                    if os.path.exists(
                                            yetiTexfile
                                    ) and not yetiTexfile in self.kYeticache:
                                        #匹配yeti支持的图片格式
                                        patternt = re.search(
                                            self.kexpu4, yetiTexfile)
                                        if patternt and not yetiTexfile in self.kYetitex:
                                            self.kYetitex.append(yetiTexfile)
                                            print yetiTexfile

                except:
                    pass

            self.kYeti = list(set(self.kYeticache + self.kYetitex))
예제 #40
0
 def updatePluginList(self):
     self._pluginList = cmds.pluginInfo(q=1, listPlugins=1)
예제 #41
0
def initializePlugin(mobject):
    global rendererModules
    global generalNodeModules
    global shadingNodeGroups
    global translatorModules

    mplugin = OpenMayaMPx.MFnPlugin(mobject, kPluginCompany, "1.0", "Any")

    # Load needed plugins
    neededPlugins = ["objExport", "OpenEXRLoader"]

    for neededPlugin in neededPlugins:
        try:
            if not cmds.pluginInfo(neededPlugin, query=True, loaded=True):
                cmds.loadPlugin(neededPlugin)
            print("%s - Loaded plugin       : %s" %
                  (kPluginName, neededPlugin))
        except:
            sys.stderr.write("Failed to load %s plugin\n" % neededPlugin)
            raise

    # Register translator nodes
    try:
        for translatorModule in translatorModules:
            if translatorModule:
                moduleName = os.path.split(
                    inspect.getfile(translatorModule))[-1].split('.')[0]

                translatorOptions = None
                if translatorModule.kPluginTranslatorOptionsUIFunction:
                    translatorOptions = createMelPythonCallback(
                        moduleName,
                        translatorModule.kPluginTranslatorOptionsUIFunction,
                        parametersList=[('string', 'parent'),
                                        ('string', 'action'),
                                        ('string', 'initialSettings'),
                                        ('string', 'resultCallback')],
                        returnType="int")

                mplugin.registerFileTranslator(
                    translatorModule.kPluginTranslatorTypeName, None,
                    translatorModule.translatorCreator, translatorOptions,
                    translatorModule.kPluginTranslatorDefaultOptions)
                print(
                    "%s - Registered translator : %s" %
                    (kPluginName, translatorModule.kPluginTranslatorTypeName))
    except:
        sys.stderr.write(
            "%s - Failed to register node: %s\n" %
            (kPluginName, translatorModule.kPluginTranslatorTypeName))
        raise

    # Register general nodes
    try:
        for generalNodeModule in generalNodeModules:
            mplugin.registerNode(generalNodeModule.kPluginNodeName,
                                 generalNodeModule.kPluginNodeId,
                                 generalNodeModule.nodeCreator,
                                 generalNodeModule.nodeInitializer,
                                 OpenMayaMPx.MPxNode.kDependNode)
            print("%s - Registered node     : %s" %
                  (kPluginName, generalNodeModule.kPluginNodeName))
    except:
        sys.stderr.write("%s - Failed to register node: %s\n" %
                         (kPluginName, generalNodeModule.kPluginNodeName))
        raise

    # Register materials, textures, volumes, lights
    for shadingModule, shadingNodeNames in shadingNodeGroups.iteritems():
        #print( "%s - Registering %s nodes" % (kPluginName, shadingModule) )

        for shadingNodeName in shadingNodeNames:
            try:
                #print( "Registering %s" % shadingNodeName )

                node = None
                try:
                    __import__(shadingModule, fromlist=[shadingNodeName])
                    module = sys.modules[shadingModule + '.' + shadingNodeName]
                    reload(module)
                    node = module
                except ImportError:
                    OpenMaya.MGlobal.displayError(
                        "Failed to load %s" %
                        (shadingModule + '.' + shadingNodeName))

                # abstract node classes should return None in nodeName() method
                if node:
                    isNode = node.kPluginNodeName
                    if isNode is None:
                        #print( "isNode == None" )
                        continue

                mplugin.registerNode(node.kPluginNodeName, node.kPluginNodeId,
                                     node.nodeCreator, node.nodeInitializer,
                                     OpenMayaMPx.MPxNode.kDependNode,
                                     node.kPluginNodeClassify)

                PBRTRenderer.registMaterialNodeType(node.kPluginNodeName)

                print("%s - Registered %s : %s" %
                      (kPluginName, shadingModule, node.kPluginNodeName))
            except:
                sys.stderr.write("%s - Failed to register node: %s\n" %
                                 (kPluginName, shadingNodeName))
                raise

    # Register Renderer commands
    for rendererModule in rendererModules:
        try:
            mplugin.registerCommand(rendererModule.kPluginCmdName,
                                    rendererModule.cmdCreator)
            print("%s - Registered command  : %s" %
                  (kPluginName, rendererModule.kPluginCmdName))
        except:
            sys.stderr.write("%s - Failed to register command: %s\n" %
                             (kPluginName, rendererModule.kPluginCmdName))
            raise

    # Register Renderers
    for rendererModule in rendererModules:
        try:
            rendererModule.registerRenderer()
            print("%s - Registered renderer : %s" %
                  (kPluginName, rendererModule.kPluginCmdName))
        except:
            sys.stderr.write("%s - Failed to register renderer: %s\n" %
                             (kPluginName, rendererModule.kPluginCmdName))
            raise
예제 #42
0
plugin_list = [
    'GamePipeline', 'MayaMuscle', 'redshift4maya', 'bifrostvisplugin',
    'dx11Shader', 'Mayatomr', 'BifrostMain', 'deformerEvaluator',
    'shaderFXPlugin', 'bifrostshellnode', 'gameFbxExporter',
    'GPUBuiltInDeformer', 'stereoCamera', 'lookdevKit', 'Unfold3D', 'Type',
    'poseDeformer', 'fbxmaya', 'poseReader', 'modelingToolkit', 'OneClick',
    'AbcImport', 'AbcExport', 'AbcBullet'
]

logging('initializing maya')

try:
    mel.eval("source UserSetupStand.mel")
    execfile('%s//userSetup.py' % (os.environ['myDocPath']))
    loaded_plugins = cmds.pluginInfo(query=True, listPlugins=True)
    for p in plugin_list:
        if p not in loaded_plugins:
            cmds.loadPlugin(p)
except Exception, e:
    exitstand(str(repr(e)))

logging('maya initialized')
'''
This function unlocks and loads references in the maya file.
'''


def unLocknLoadReferences():

    badRefs = ['sharedReferenceNode', '_UNKNOWN_REF_NODE_']
예제 #43
0
###############################################################################
## 
#  @file	kmAnimImpExp.py
#  @brief	AnimファイルとSelectファイル同時書き出し
#  @version	1.0.1
#  @date	2016/04/23
#  @note	- edit
#  					- cleanup
#  @todo	
#  
###############################################################################
import os
import maya.cmds as mc
import maya.mel as mm
###############################################################################
if not mc.pluginInfo("animImportExport",q=True,loaded=True):
	mc.loadPlugin( 'animImportExport' )
	mc.pluginInfo( 'animImportExport', edit=True, autoload=True )
###############################################################################
def main():
	mc.python('from kmAnimImpExp import *')

	if mc.window( 'AnimImpExpUI', exists=True ):
		mc.deleteUI('AnimImpExpUI')
		
	WinName = mc.window( 
		'AnimImpExpUI', 
		title='Anim Import/Export with select', 
		iconName='AnimImpExpUI', 
		width=100, 
		height=200,
예제 #44
0
def renderThumbs(checkBoxLow, checkBoxMid, checkBoxHigh, checkBoxRenderRegion,
                 intField_res, floatField_thrhld, *args):
    global cancel
    cams = cmds.ls(type="camera")
    cancel = 0
    popup_win = 0
    no_cam_set_list = []
    cmds.loadPlugin('vrayformaya', quiet=True)
    cmds.pluginInfo('vrayformaya', edit=True, autoload=True)
    cmds.setAttr("defaultRenderGlobals.ren", "vray", type="string")

    curLay = cmds.editRenderLayerGlobals(currentRenderLayer=True, query=True)
    changeLay = curLay

    rls = cmds.ls(type="renderLayer")
    renCams = cmds.ls(type="camera")
    renCam = "persp"

    lowBut = cmds.checkBox(checkBoxLow, value=True, query=True)
    midBut = cmds.checkBox(checkBoxMid, value=True, query=True)
    highBut = cmds.checkBox(checkBoxHigh, value=True, query=True)
    globopt_cache_geom_plugins = cmds.getAttr(
        'vraySettings.globopt_cache_geom_plugins')
    #print 'globopt_cache_geom_plugins = ',globopt_cache_geom_plugins

    print " "
    print "-- batch_review --"

    res = cmds.intField(intField_res, v=True, query=True)
    thr = cmds.floatField(floatField_thrhld, v=True, query=True)

    if lowBut == 1:
        cmds.setAttr("vraySettings.dmcThreshold", thr)
        cmds.setAttr("vraySettings.width", res)
        cmds.setAttr("vraySettings.height", res)
        cmds.setAttr("vraySettings.globopt_cache_geom_plugins", 1)
        cmds.setAttr("vraySettings.globopt_ray_maxIntens_on", 1)
        #cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
        print " "
        print "---"
        print "quality = %s, dmcThreshold = %s" % (res, thr)
    if midBut == 1:
        cmds.setAttr("vraySettings.dmcThreshold", thr)
        cmds.setAttr("vraySettings.width", res)
        cmds.setAttr("vraySettings.height", res)
        cmds.setAttr("vraySettings.globopt_cache_geom_plugins", 1)
        cmds.setAttr("vraySettings.globopt_ray_maxIntens_on", 1)
        #cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
        print " "
        print "---"
        print "quality = %s, dmcThreshold = %s" % (res, thr)
    if highBut == 1:
        cmds.setAttr("vraySettings.dmcThreshold", thr)
        cmds.setAttr("vraySettings.width", res)
        cmds.setAttr("vraySettings.height", res)
        cmds.setAttr("vraySettings.globopt_cache_geom_plugins", 1)
        cmds.setAttr("vraySettings.globopt_ray_maxIntens_on", 1)
        #cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
        print " "
        print "---"
        print "quality = %s, dmcThreshold = %s" % (res, thr)

    print "--- "
    print " "

    for rl in rls:
        found_cam = 0
        if rl != "defaultRenderLayer" and cancel == 0:
            rlState = cmds.getAttr(rl + ".renderable")
            if rlState == 1:
                print ' '
                print "rende layer = ", rl
                cmds.editRenderLayerGlobals(currentRenderLayer=rl)
                for cam in cams:
                    camState = cmds.getAttr(cam + ".renderable")
                    if camState == 1:
                        rrState = cmds.checkBox(checkBoxRenderRegion,
                                                value=True,
                                                query=True)
                        reg = cmds.vray("vfbControl", "-getregion")
                        if rrState == 0:
                            cmds.vray("vfbControl", "-setregion", "reset")
                        if rrState == 1:
                            cmds.vray("vfbControl", "-setregionenabled", 1)
                            cmds.vray("vfbControl", "-setregion", reg[0],
                                      reg[1], reg[2], reg[3])
                        mayaString = "renderWindowRenderCamera render renderView " + cam
                        print 'using ' + cam + ' for ' + rl
                        maya.mel.eval(mayaString)
                        cmds.vray("vfbControl", "-historysave")
                        cmds.vray("vfbControl", "-historyselect", 0)
                        #dte = datetime.now().strftime('%H:%M:%S')
                        dte = datetime.now().strftime('%H:%M')
                        editStr = rl + "," + cam
                        cmds.vray("vfbControl", "-historycomment", editStr)
                        print " "
                        found_cam = 1
                if found_cam == 0:
                    print 'no camera link found, using persp cam for ', rl
                    cam = 'persp'
                    rrState = cmds.checkBox(checkBoxRenderRegion,
                                            value=True,
                                            query=True)
                    reg = cmds.vray("vfbControl", "-getregion")
                    if rrState == 0:
                        cmds.vray("vfbControl", "-setregion", "reset")
                    if rrState == 1:
                        cmds.vray("vfbControl", "-setregionenabled", 1)
                        cmds.vray("vfbControl", "-setregion", reg[0], reg[1],
                                  reg[2], reg[3])
                    mayaString = "renderWindowRenderCamera render renderView " + cam
                    maya.mel.eval(mayaString)
                    cmds.vray("vfbControl", "-historysave")
                    cmds.vray("vfbControl", "-historyselect", 0)
                    dte = datetime.now().strftime('%H:%M:%S')
                    editStr = rl + "," + cam
                    cmds.vray("vfbControl", "-historycomment", editStr)
                    popup_win = 1
                    no_cam_set_list.append(rl)
예제 #45
0
def abcoutput(arg):
    filename = os.path.basename(os.path.splitext(cmds.file(expandName=1,q=1))[0])
    path =cmds.textField('pathnum',tx=1,q=1).replace("\\","/")
    rangea =cmds.textField('rangenuma',tx=1,q=1)
    rangeb =cmds.textField('rangenumb',tx=1,q=1)
    rangesam =cmds.textField('rangesamnum',tx=1,q=1)
    geocb=cmds.checkBox("geonlycb" ,q=True,v=True)
    furcb = cmds.checkBox("furonlycb" ,q=True,v=True)
    if cmds.pluginInfo("AbcExport",q=1,loaded=1,name=1)==0:
        try:
            cmds.loadPlugin("AbcExport")
        except:
            pass
    if os.path.exists(path):
        sels = cmds.ls(sl=1)
        yeticols =[]
        yetiAss =[]
        locatercols = []  
        geoout = []  
        if sels!=[]:
            for sel in sels:
                locsels = [ y for y in cmds.listRelatives(sel,c=1) if y.find("arnold_loc")!=-1 and cmds.getAttr(y+".visibility")==1]
                yetiselgrps = [ y for y in cmds.listRelatives(sel,c=1) if y.find("yeti_G")!=-1]
                if geocb==1:
                    geodels = []
                    Miajudge = sel.find('Miarmy_Contents')
                    if Miajudge ==-1:
                        geogrps = [ y for y in cmds.listRelatives(sel,c=1) if y.find("_geo")!=-1]
                    else:
                        Agent =[a for a in cmds.listRelatives(sel,c=1) if a.find('Agent')!=-1]
                        if Agent!=[]:
                            geogrps = [b for b in  cmds.listRelatives(Agent[0],c=1) if b.find('Geometry')!=-1]
                        else:
                            geogrps = []
                    if geogrps!=[]:
                        for geogrp in geogrps:
                            if cmds.getAttr(geogrp+".visibility")==0:
                                try:
                                    cmds.setAttr(geogrp+".visibility",1)
                                except:
                                    cmds.warning(geogrp+".visibility cant be set!!")
                            #mainCtrl
                            if cmds.listConnections(geogrp,d=0,type="transform")!=None:
                                mainctrl =[m for m in cmds.listConnections(geogrp,d=0,type="transform") if m.find("Main")!=-1]
                                if mainctrl!=[]:
                                    mainFurAttrs =[f for f in cmds.listAttr(mainctrl[0],k=1) if f in['hair','yeti','hairYeti']]
                                    if mainFurAttrs!=[]:
                                        for  mainFurAttr in mainFurAttrs:
                                            if cmds.getAttr(mainctrl[0]+'.'+mainFurAttr)!=1:
                                                cmds.setAttr(mainctrl[0]+'.'+mainFurAttr,1)
                            #geoall
                            geoalls =[a for a in cmds.listRelatives(geogrp,ad=1) if cmds.nodeType(a)=="transform"]
                            for geoall in geoalls:
                                if cmds.listConnections(geoall+".visibility",type="animCurve")==None:
                                    if cmds.getAttr(geoall+".visibility")==False:
                                        geodels.append(geoall)
                            geoout.append(geogrp)
                        if  geodels !=[]:
                            if cmds.objExists(str(geogrps[0]+"_del"))==True:
                                cmds.rename(str(geogrps[0]+"_del"),str(geogrp[0]+"_tmp"))
                                cmds.parent(geodels,w=1)
                                cmds.group(geodels,name=str(geogrps[0]+"_del"))
                            else:
                                cmds.parent(geodels,w=1)
                                cmds.group(geodels,name=str(geogrps[0]+"_del") ) 

                    #bake blender
                    try:
                        blctrl = sel[:len(sel.split(":")[-1])]+":key_Ani"
                    except:
                        blctrl = []
                    if blctrl!=[]:
                        if cmds.objExists(blctrl):
                            blnode = [ bln for bln in  cmds.hyperShade(listDownstreamNodes =blctrl) if cmds.nodeType(bln)=="blendColors"]
                            cmds.bakeResults(blnode,simulation=1,t=rangea+":"+rangeb,sampleBy = int(rangesam))
                        
                if furcb==1:
                    locatercols += locsels
                    if yetiselgrps!=[]:
                        yetishowgrps = [yt for yt in  cmds.listRelatives(yetiselgrps,c=1) if yt.find("yeti_show_G")!=-1]
                        yetinodes =cmds.listRelatives(yetishowgrps,c=1)
                        if yetinodes!=None:
                            for yetinode in yetinodes:
                                if cmds.getAttr(yetinode+".visibility")==True:
                                    if cmds.getAttr(cmds.listRelatives(yetinode,p=1)[0]+".visibility")==True:
                                        yeticols.append(yetinode)
        if geocb==False:
            geoout=[]
        if furcb==False:
            yeticols=[]
            locatercols=[]

        #output abc
        cmds.select(geoout,r=1)
        abcname ="-frameRange {0} {1} -uvWrite -worldSpace -writeVisibility -dataFormat hdf".format(rangea,rangeb)
        for ou in range(len(geoout)):
            abcname = abcname+" -root "+geoout[ou]
        if abcname!="-frameRange {0} {1} -uvWrite -worldSpace -writeVisibility -dataFormat hdf".format(rangea,rangeb):
            abcoutputfurpath = path+"/"+filename+".abc"
            nn=1
            while os.path.exists(abcoutputfurpath)==True:
                abcoutputfurpath = path+"/"+filename+"_"+str(nn)+".abc"
                nn =nn+1 
            cmds.AbcExport(j = abcname+" -file {0}".format(abcoutputfurpath)) 
  
        #output yeticache    
        if yeticols!=[]:
            yeticachename = yeticols[0].replace(":","__")
            cmds.select(yeticols,r=1)
            cmds.pgYetiCommand(flushGeometryCache=1)
            cmds.pgYetiCommand(flushTextureCache=1)
            cmds.pgYetiCommand(flushDisplayCache=1)
            if os.path.exists(path+"/yetiAss")==False:
                os.mkdir(path+"/yetiAss")
            cmds.select(yeticols,r=1)
            cmds.arnoldExportAss(f=path+"/yetiAss/"+yeticachename+".ass",s=1,expandProcedurals=1,startFrame=int(rangea),endFrame=int(rangeb),frameStep=int(rangesam),lightLinks=0,compressed=1,boundingBox=1,shadowLinks=0,mask=24,cam='perspShape')
            mtoa.core.createStandIn(path+"/yetiAss/"+yeticachename+r".####.ass.gz")
            assShape = cmds.ls(sl=1,type="aiStandIn") 
            cmds.expression(s =assShape[0]+ ".frameNumber=frame")
            yetiAss = cmds.listRelatives(assShape[0],p=1)
            print "已输出"+str(len(yeticols))+"个毛发节点!!",

        #bak hairAss locater    
        if locatercols!=[]:
            for locatercol in locatercols:
                locaterAttrs =  cmds.listAttr(locatercol,v=1,k=1)
                for locaterAttr in locaterAttrs:
                    lockjudge = cmds.getAttr(locatercol+"."+locaterAttr,l=1)
                    if lockjudge==1:
                        cmds.setAttr(locatercol+"."+locaterAttr,l=0)

            pm.bakeResults(locatercols,simulation=1,t=rangea+":"+rangeb,sampleBy = int(rangesam))
            for locatercol in locatercols:
                parentCons =  cmds.listRelatives(locatercol,c=1,type=("parentConstraint","scaleConstraint"))
                cmds.delete(parentCons)
                lacattrv =   cmds.listConnections(locatercol+".visibility",d=0,plugs=1)
                if lacattrv!=[]:
                    cmds.disconnectAttr(lacattrv[0],locatercol+".visibility")
            cmds.parent(locatercols,w=1)  
        if yetiAss!=[] and locatercols!=[]:
            rmparentCons(filename,"Ass_G",locatercols)
            furcachegrp = cmds.group(yetiAss,filename+"_Ass_G",name=filename+"_furCache_G")
            cmds.select(furcachegrp,r=1,hi=1)
            cmds.rename(yetiAss[0],filename+"_yetiAss_Aist")
            outputfurpath = path+"/"+filename+"_fur.mb"
            nn=1
            while os.path.exists(outputfurpath)==True:
                outputfurpath = path+"/"+filename+"_fur_"+str(nn)+".mb"
                nn =nn+1
            cmds.file(outputfurpath,force = 1,options ='v=0;' ,typ = 'mayaBinary',pr=1,es=1 )

        elif locatercols!=[]:
            rmparentCons(filename,"Ass_G",locatercols)
            furcachegrp = cmds.group(filename+"_Ass_G",name=filename+"_furCache_G")
            cmds.select(furcachegrp,r=1,hi=1)
            outputfurpath = path+"/"+filename+"_fur.mb"
            nn=1
            while os.path.exists(outputfurpath)==True:
                outputfurpath = path+"/"+filename+"_fur_"+str(nn)+".mb"
                nn =nn+1 
            cmds.file(outputfurpath,force = 1,options ='v=0;' ,typ = 'mayaBinary',pr=1,es=1 )
    else:
        cmds.warning('目标路径不存在!!!')
def createLensShaders(centerCam, leftCam, rightCam):
    import maya.mel as mel
    import maya.cmds as cmds
    print "Center: " + centerCam + "Left: " + leftCam + "Right: " + rightCam
    # ---------------------------------------------------------------------
    #Set up the base folder path for the Domemaster3D control maps
    # ---------------------------------------------------------------------

    #Variables
    # separationMapFileTexture = getSourceImagesPath("separation_map.png")
    # turnMapFileTexture = getSourceImagesPath("turn_map.png")
    # tiltMapFileTexture = getSourceImagesPath("head_tilt_map.png")

    # Arnold camera type
    cameraType = 'DomemasterStereo'

    # Check if Arnold is loaded before linking the attributes
    if (cmds.pluginInfo("mtoa", q=True, loaded=True)):
        # Switch the active camera type
        #cmds.setAttr( centerCam+'.ai_translator', cameraType, type='string')
        cmds.setAttr(leftCam + '.ai_translator', cameraType, type='string')
        cmds.setAttr(rightCam + '.ai_translator', cameraType, type='string')

        # ---------------------------------------------------------------------
        # Create the fulldome nodes for the rig
        # ---------------------------------------------------------------------
        #cmds.setAttr( centerCam+'.aiCamera', 0 ) #Set the view to center

        cmds.setAttr(leftCam + '.aiCamera', 1)  #Set the view to left
        cmds.setAttr(rightCam + '.aiCamera', 2)  #Set the view to right

        # ---------------------------------------------------------------------
        # Link the common left and right camera attributes to the center camera
        # ---------------------------------------------------------------------
        # Link the right camera attributes
        cmds.connectAttr(leftCam + '.aiFovAngle',
                         rightCam + '.aiFovAngle',
                         force=True)
        cmds.connectAttr(leftCam + '.aiZeroParallaxSphere',
                         rightCam + '.aiZeroParallaxSphere',
                         force=True)
        cmds.connectAttr(leftCam + '.aiSeparation',
                         rightCam + '.aiSeparation',
                         force=True)
        cmds.connectAttr(leftCam + '.aiForwardTilt',
                         rightCam + '.aiForwardTilt',
                         force=True)
        cmds.connectAttr(leftCam + '.aiTiltCompensation',
                         rightCam + '.aiTiltCompensation',
                         force=True)
        cmds.connectAttr(leftCam + '.aiVerticalMode',
                         rightCam + '.aiVerticalMode',
                         force=True)

        cmds.connectAttr(leftCam + '.aiSeparationMap',
                         rightCam + '.aiSeparationMap',
                         force=True)
        cmds.connectAttr(leftCam + '.aiHeadTurnMap',
                         rightCam + '.aiHeadTurnMap',
                         force=True)
        cmds.connectAttr(leftCam + '.aiHeadTiltMap',
                         rightCam + '.aiHeadTiltMap',
                         force=True)

        cmds.connectAttr(leftCam + '.aiFlipRayX',
                         rightCam + '.aiFlipRayX',
                         force=True)
        cmds.connectAttr(leftCam + '.aiFlipRayY',
                         rightCam + '.aiFlipRayY',
                         force=True)

        # ---------------------------------------------------------------------
        # Create the custom Domemaster3D shading networks
        # ---------------------------------------------------------------------

        # Create the nodes

        # ---------------------------------------------------------------------
        # Link the center camera lens shader to the Maya camera rig stereo3d settings
        # This enables real-time 3D previews in the viewport
        # ---------------------------------------------------------------------
        cmds.connectAttr(leftCam + '.aiZeroParallaxSphere',
                         centerCam + '.zeroParallax',
                         force=True)
        cmds.connectAttr(leftCam + '.aiSeparation',
                         centerCam + '.interaxialSeparation',
                         force=True)

        #Turn off the Stereo 3D effect on the native Maya camera rig
        # This skips the need for a pre-render and post-render mel script.
        cmds.setAttr(centerCam + '.stereo', 0)
예제 #47
0
def xrivetTrOnNurbs(tr,
                    surface,
                    mainDirection=1,
                    out='worldSpace[0]',
                    u=None,
                    v=None,
                    offsetOrient=[0, 0, 0],
                    min=False):
    '''

    :param tr:
    :type tr:
    :param surface:
    :type surface:
    :param mainDirection:
    :type mainDirection:
    :param out:
    :type out:
    :param u:
    :type u:
    :param v:
    :type v:
    :param offsetOrient:
    :type offsetOrient:
    :return:
    :rtype:
    '''
    attrsFrom = ['outTranslation', 'outRotation', 'outScale', 'outShear']
    attrsTo = ['translate', 'rotate', 'scale', 'shear']
    require_plugin = ['xRivet']
    for plugin in require_plugin:
        if not mc.pluginInfo(plugin, q=True, l=True):
            try:
                mc.loadPlugin(plugin, quiet=True)
            except:
                print 'warning : {0} plugin could not load'.format(plugin)
                return
    xRivet = '{0}_xRivetNurbs'.format(surface)
    if not mc.objExists(xRivet):
        xRivet = mc.createNode('xRivetNurbs', n=xRivet)
        mc.connectAttr('{0}.{1}'.format(surface, out),
                       '{0}.inNurbsSurface'.format(xRivet))
    indexLast = getXrivetEntryAvailable(xRivet)
    if u != None and v != None:
        valU, valV = u, v
    else:
        valU, valV = getUvOnSurfaceFromeTr(tr, surface, out)

    # if min:
    #     valV/=2
    #print valV,'***********---------------'
    # xrivetTrans = mc.createNode('transform', n = tr + 'Xrivet')
    mc.setAttr('{0}.xRivetDatas[{1}].uValue'.format(xRivet, indexLast), valU)
    mc.setAttr('{0}.xRivetDatas[{1}].vValue'.format(xRivet, indexLast), valV)
    mc.setAttr('{0}.xRivetDatas[{1}].mainDirection'.format(xRivet, indexLast),
               mainDirection)
    mc.setAttr('{0}.xRivetDatas[{1}].stretchSquash'.format(xRivet, indexLast),
               0)

    # for attrFrom, attrTo in zip(attrsFrom, attrsTo):
    #     mc.connectAttr('{0}.outputTransforms[{1}].{2}'.format(xRivet, indexLast, attrFrom),
    #                    '{0}.{1}'.format(xrivetTrans, attrTo))

    # mc.parentConstraint(xrivetTrans, tr, mo = True)
    mc.connectAttr(
        '{0}.outputTransforms[{1}].{2}'.format(xRivet, indexLast,
                                               'outTranslation'),
        '{0}.{1}'.format(tr, 'translate'))

    addRot = mc.createNode('animBlendNodeAdditiveRotation',
                           n=tr + 'AdditiveRotation')
    mc.setAttr(addRot + '.accumulationMode', 1)
    mc.connectAttr(
        '{0}.outputTransforms[{1}].{2}'.format(xRivet, indexLast,
                                               'outRotation'),
        '{0}.{1}'.format(addRot, 'inputA'))
    mc.setAttr(addRot + '.inputB', *offsetOrient)
    mc.connectAttr(addRot + '.output', tr + '.rotate')
    # mc.pointConstraint(xrivetTrans, tr, mo = True)
    # mc.orientConstraint(xrivetTrans, tr, mo = True)

    return xRivet, indexLast
예제 #48
0
def vrayLoad(*args):
    if not cmds.pluginInfo('vrayformaya', q=1, loaded=1):
        cmds.loadPlugin('vrayformaya')
        cmds.loadPlugin('xgenVRay')
    cmds.setAttr('defaultRenderGlobals.currentRenderer', 'vray', type='string')
예제 #49
0
파일: mayafacade.py 프로젝트: vvzen/kiko
    def pre_import():
        if not cmds.pluginInfo('kikoUndoer', q=1, l=1):
            cmds.loadPlugin('kikoUndoer', quiet=True)

        MayaUndoHelper.anim_curve_change = OpenMayaAnim.MAnimCurveChange()
        MayaUndoHelper.dg_modifier = OpenMaya.MDGModifier()
    def load(self, context, name=None, namespace=None, options=None):

        # (NOTE) AnimWire modifier has a bug that not able to find wires if
        #        namespace is applied.
        #        The hairSystem is okay to work with, but not able to update
        #        XGen preview. So you either simulate without the update, or
        #        build the simulation without namespace and save with .xgen
        #        file exported, then reference it with namespace.
        #
        #        https://forums.autodesk.com/t5/maya-dynamics/anim-wire-
        #        errors-when-using-namespaces/m-p/7329883#M5642
        #

        if not cmds.pluginInfo("xgenToolkit", query=True, loaded=True):
            cmds.loadPlugin("xgenToolkit", quiet=True)

        representation = context["representation"]

        asset = context["asset"]
        asset_name = asset["data"].get("shortName", asset["name"])
        family_name = context["version"]["data"]["families"][0].split(".")[-1]
        namespace = namespace or unique_root_namespace(asset_name, family_name)

        descriptions_data = representation["data"]["descriptionsData"]
        baked = representation["data"]["step"] != xgen.SHAPING
        bound_meshes = list()

        # Varify selection
        selected = cmds.ls(sl=True, long=True)

        all_bound_geos = set()
        for data in descriptions_data.values():
            for geo in data["bound"]:
                all_bound_geos.add("|" + geo)

        msg = ("Require bound geos: {0}\n"
               "Selected: {1}".format(all_bound_geos, selected))
        assert set(selected) == all_bound_geos, msg

        # Rename bound geos to namespace
        for node in selected:
            bound_meshes.append(node)

        # Copy maps
        local_map_dir = os.path.join(avalon.api.Session["AVALON_WORKDIR"],
                                     "xgen",
                                     "published",
                                     # Add username to ease out file lock issue
                                     getpass.getuser())
        map_dir = os.path.join(self.package_path, "maps")
        for palette in os.listdir(map_dir):
            palette_dir = os.path.join(map_dir, palette)
            local_palette_dir = os.path.join(local_map_dir, palette)

            # Copy
            copy_tree(palette_dir, local_palette_dir)

        # Import palette
        palette_nodes = list()
        xgen.preview_clear()

        for file in representation["data"]["palettes"]:

            xgen_path = os.path.join(self.package_path, file)
            xgen_path = xgen_path.replace("\\", "/")
            palette_node = xgen.import_palette(xgen_path,
                                               wrapPatches=True)
            palette_nodes.append(palette_node)

            # Set xgDataPath
            palette = os.path.splitext(file)[0]
            data_path = os.path.join(local_map_dir, palette).replace("\\", "/")
            xgen.set_data_path(palette_node, data_path)

            if not baked:
                # Bind grooming descriptions to geometry
                for desc in xgen.list_descriptions(palette_node):
                    groom = xgen.get_groom(desc)
                    if groom:
                        groom_dir = os.path.join(self.package_path,
                                                 "groom",
                                                 palette_node,
                                                 desc)
                        xgen.import_grooming(desc, groom, groom_dir)

            # Apply ID
            asset_id = str(asset["_id"])
            with utils.id_namespace(asset_id):
                for desc in xgen.list_descriptions(palette_node):
                    _desc = desc.rsplit(":", 1)[-1]
                    id = descriptions_data[_desc]["id"]
                    utils.upsert_id(desc, id)

            # Ensure tube shade disabled
            xgen.disable_tube_shade(palette_node)

        group_name = self.group_name(namespace, name)
        # Cannot be grouped
        # cmds.group(palette_nodes, name=group_name, world=True)
        # palette_nodes = cmds.ls(palette_nodes, long=True)

        # Containerising..
        nodes = palette_nodes[:]
        nodes += bound_meshes
        nodes += cmds.listRelatives(palette_nodes,
                                    allDescendents=True,
                                    fullPath=True)
        nodes += apply_namespace_wrapper(namespace, nodes)

        container_id = options.get("containerId",
                                   utils.generate_container_id())
        container = subset_containerising(name=name,
                                          namespace=namespace,
                                          container_id=container_id,
                                          nodes=nodes,
                                          context=context,
                                          cls_name=self.__class__.__name__,
                                          group_name=group_name)
        return container
예제 #51
0
def load_hyperdrive_plugin():
    plugin_name = "hyperdrive"
    if not cmds.pluginInfo(plugin_name, q=True, l=True):
        cmds.loadPlugin(plugin_name)
    cmds.evaluator(enable=True, name='hdEvaluator')
예제 #52
0
def invert(base=None, corrective=None, name=None):
    """@brief Inverts a shape through the deformation chain.

    @param[in] base Deformed base mesh.
    @param[in] corrective Sculpted corrective mesh.
    @param[in] name Name of the generated inverted shape.
    @return The name of the inverted shape.
    """
    if not cmds.pluginInfo('cvShapeInverter.py', query=True, loaded=True):
        cmds.loadPlugin('cvShapeInverter.py')
    cmds.undoInfo(openChunk=True)
    if not base or not corrective:
        sel = cmds.ls(sl=True)
        if not sel or len(sel) != 2:
            cmds.undoInfo(closeChunk=True)
            raise RuntimeError, 'Select base then corrective'
        base, corrective = sel

    # Get points on base mesh
    basePoints = getPoints(base)
    numPoints = basePoints.length()

    # Get points on corrective mesh
    correctivePoints = getPoints(corrective)

    # Get the intermediate mesh
    shapes = cmds.listRelatives(base, children=True, shapes=True)
    for s in shapes:
        if cmds.getAttr('%s.intermediateObject' % s) and cmds.listConnections(
                '%s.worldMesh' % s, source=False):
            origMesh = s
            break
    else:
        cmds.undoInfo(closeChunk=True)
        raise RuntimeError('No intermediate shape found for %s.' % base)

    # Get the component offset axes
    origPoints = getPoints(origMesh)
    xPoints = OpenMaya.MPointArray(origPoints)
    yPoints = OpenMaya.MPointArray(origPoints)
    zPoints = OpenMaya.MPointArray(origPoints)

    for i in range(numPoints):
        xPoints[i].x += 1.0
        yPoints[i].y += 1.0
        zPoints[i].z += 1.0
    setPoints(origMesh, xPoints)
    xPoints = getPoints(base)
    setPoints(origMesh, yPoints)
    yPoints = getPoints(base)
    setPoints(origMesh, zPoints)
    zPoints = getPoints(base)
    setPoints(origMesh, origPoints)

    # Create the mesh to get the inversion deformer
    if not name:
        name = '%s_inverted' % corrective

    invertedShape = cmds.duplicate(base, name=name)[0]
    # Delete the unnessary shapes
    shapes = cmds.listRelatives(invertedShape, children=True, shapes=True)
    for s in shapes:
        if cmds.getAttr('%s.intermediateObject' % s):
            cmds.delete(s)
    setPoints(invertedShape, origPoints)
    # Unlock the transformation attrs
    for attr in 'trs':
        for x in 'xyz':
            cmds.setAttr('%s.%s%s' % (invertedShape, attr, x), lock=False)
    cmds.setAttr('%s.visibility' % invertedShape, 1)
    deformer = cmds.deformer(invertedShape, type='cvShapeInverter')[0]

    # Calculate the inversion matrices
    oDeformer = getMObject(deformer)
    fnDeformer = OpenMaya.MFnDependencyNode(oDeformer)
    plugMatrix = fnDeformer.findPlug('inversionMatrix', False)
    fnMatrixData = OpenMaya.MFnMatrixData()
    for i in range(numPoints):
        matrix = OpenMaya.MMatrix()
        setMatrixRow(matrix, xPoints[i] - basePoints[i], 0)
        setMatrixRow(matrix, yPoints[i] - basePoints[i], 1)
        setMatrixRow(matrix, zPoints[i] - basePoints[i], 2)
        matrix = matrix.inverse()
        oMatrix = fnMatrixData.create(matrix)

        plugMatrixElement = plugMatrix.elementByLogicalIndex(i)
        plugMatrixElement.setMObject(oMatrix)

    # Store the base points.
    fnPointData = OpenMaya.MFnPointArrayData()
    oPointData = fnPointData.create(basePoints)
    plugDeformedPoints = fnDeformer.findPlug('deformedPoints', False)
    plugDeformedPoints.setMObject(oPointData)

    cmds.connectAttr('%s.outMesh' % getShape(corrective),
                     '%s.correctiveMesh' % deformer)
    cmds.setAttr('%s.activate' % deformer, True)

    cmds.undoInfo(closeChunk=True)
    return invertedShape
예제 #53
0
def createLensShaders(centerCam, leftCam, rightCam):
    import maya.mel as mel
    import maya.cmds as cmds
    print "[Center] " + centerCam + " [Left] " + leftCam + " [Right] " + rightCam
    # ---------------------------------------------------------------------
    #Set up the base folder path for the Domemaster3D control maps
    # ---------------------------------------------------------------------

    #Variables
    # separationMapFileTexture = getSourceImagesPath("latlong_separation_map.png")
    # turnMapFileTexture = getSourceImagesPath("latlong_turn_map.png")
    # tiltMapFileTexture = getSourceImagesPath("latlong_head_tilt_map.png")

    # Check if Vray is loaded before linking the attributes
    if (cmds.pluginInfo("vrayformaya", query=True, loaded=True)):
        # -------------------------------------------------------------------------
        # Center Camera Lens Shader
        # -------------------------------------------------------------------------
        print("[Center Camera] " + centerCam + "\n")

        #cmds.select( centerCam, replace=True )

        # Enable the Lens Shader's Vray Extra Attributes
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoOn',
                     longName='vrayLatLongStereoOn',
                     attributeType='long',
                     defaultValue=1)

        # Center Camera View
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoCamera',
                     longName='vrayLatLongStereoCamera',
                     attributeType='long',
                     defaultValue=0)

        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoFovVertAngle',
                     longName='vrayLatLongStereoFovVertAngle',
                     attributeType='float',
                     min=0.1,
                     softMaxValue=180,
                     defaultValue=180)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoFovHorizAngle',
                     longName='vrayLatLongStereoFovHorizAngle',
                     attributeType='float',
                     min=0.1,
                     softMaxValue=360,
                     defaultValue=360)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoParallaxDistance',
                     longName='vrayLatLongStereoParallaxDistance',
                     attributeType='float',
                     min=0.001,
                     softMaxValue=5000,
                     defaultValue=720)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoSeparation',
                     longName='vrayLatLongStereoSeparation',
                     attributeType='float',
                     min=0,
                     softMaxValue=650,
                     defaultValue=6.5)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoZenithMode',
                     longName='vrayLatLongStereoZenithMode',
                     attributeType='long',
                     defaultValue=0)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoSeparationMap',
                     longName='vrayLatLongStereoSeparationMap',
                     attributeType='float3',
                     usedAsColor=True,
                     numberOfChildren=3)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoSeparationMap',
                     longName='vrayLatLongStereoSeparationMap',
                     usedAsColor=True,
                     attributeType='float3')
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoSeparationMapr',
                     longName='vrayLatLongStereoSeparationMapr',
                     attributeType='float',
                     parent='vrayLatLongStereoSeparationMap',
                     defaultValue=1.0)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoSeparationMapg',
                     longName='vrayLatLongStereoSeparationMapg',
                     attributeType='float',
                     parent='vrayLatLongStereoSeparationMap',
                     defaultValue=1.0)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoSeparationMapb',
                     longName='vrayLatLongStereoSeparationMapb',
                     attributeType='float',
                     parent='vrayLatLongStereoSeparationMap',
                     defaultValue=1.0)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoFlipX',
                     longName='vrayLatLongStereoFlipX',
                     attributeType='long',
                     defaultValue=0)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoFlipY',
                     longName='vrayLatLongStereoFlipY',
                     attributeType='long',
                     defaultValue=0)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoNeckOffset',
                     longName='vrayLatLongStereoNeckOffset',
                     attributeType='float',
                     min=-10000.0,
                     softMaxValue=1000.0,
                     defaultValue=0.0)
        cmds.addAttr(centerCam,
                     shortName='vrayLatLongStereoZenithFov',
                     longName='vrayLatLongStereoZenithFov',
                     attributeType='long',
                     defaultValue=0)

        # -------------------------------------------------------------------------
        # Left Camera Lens Shader
        # -------------------------------------------------------------------------
        leftCamShape = leftCam + 'Shape'
        # leftCamShape = leftCam
        # leftCamShape = getObjectShapeNode(leftCam)
        print("[Left Camera Shape] " + leftCamShape + "\n")

        #cmds.select( leftCamShape, replace=True )

        # Enable the Lens Shader's Vray Extra Attributes
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoOn',
                     longName='vrayLatLongStereoOn',
                     attributeType='long',
                     defaultValue=1)

        # Left Camera View
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoCamera',
                     longName='vrayLatLongStereoCamera',
                     attributeType='long',
                     defaultValue=1)

        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoFovVertAngle',
                     longName='vrayLatLongStereoFovVertAngle',
                     attributeType='float',
                     min=0.1,
                     softMaxValue=180,
                     defaultValue=180)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoFovHorizAngle',
                     longName='vrayLatLongStereoFovHorizAngle',
                     attributeType='float',
                     min=0.1,
                     softMaxValue=360,
                     defaultValue=360)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoParallaxDistance',
                     longName='vrayLatLongStereoParallaxDistance',
                     attributeType='float',
                     min=0.001,
                     softMaxValue=5000,
                     defaultValue=720)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoSeparation',
                     longName='vrayLatLongStereoSeparation',
                     attributeType='float',
                     min=0,
                     softMaxValue=650,
                     defaultValue=6.5)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoZenithMode',
                     longName='vrayLatLongStereoZenithMode',
                     attributeType='long',
                     defaultValue=0)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoSeparationMap',
                     longName='vrayLatLongStereoSeparationMap',
                     attributeType='float3',
                     usedAsColor=True,
                     numberOfChildren=3)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoSeparationMap',
                     longName='vrayLatLongStereoSeparationMap',
                     usedAsColor=True,
                     attributeType='float3')
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoSeparationMapr',
                     longName='vrayLatLongStereoSeparationMapr',
                     attributeType='float',
                     parent='vrayLatLongStereoSeparationMap',
                     defaultValue=1.0)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoSeparationMapg',
                     longName='vrayLatLongStereoSeparationMapg',
                     attributeType='float',
                     parent='vrayLatLongStereoSeparationMap',
                     defaultValue=1.0)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoSeparationMapb',
                     longName='vrayLatLongStereoSeparationMapb',
                     attributeType='float',
                     parent='vrayLatLongStereoSeparationMap',
                     defaultValue=1.0)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoFlipX',
                     longName='vrayLatLongStereoFlipX',
                     attributeType='long',
                     defaultValue=0)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoFlipY',
                     longName='vrayLatLongStereoFlipY',
                     attributeType='long',
                     defaultValue=0)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoNeckOffset',
                     longName='vrayLatLongStereoNeckOffset',
                     attributeType='float',
                     min=-10000.0,
                     softMaxValue=1000.0,
                     defaultValue=0.0)
        cmds.addAttr(leftCamShape,
                     shortName='vrayLatLongStereoZenithFov',
                     longName='vrayLatLongStereoZenithFov',
                     attributeType='long',
                     defaultValue=0)

        # -------------------------------------------------------------------------
        # Right Camera Lens Shader
        # -------------------------------------------------------------------------
        rightCamShape = rightCam + 'Shape'
        # rightCamShape = rightCam
        # rightCamShape = getObjectShapeNode(rightCam)
        print("[Right Camera Shape] " + rightCamShape + "\n")

        #cmds.select( rightCamShape, replace=True )

        # Enable the Lens Shader's Vray Extra Attributes
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoOn',
                     longName='vrayLatLongStereoOn',
                     attributeType='long',
                     defaultValue=1)

        # Center Camera View
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoCamera',
                     longName='vrayLatLongStereoCamera',
                     attributeType='long',
                     defaultValue=2)

        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoFovVertAngle',
                     longName='vrayLatLongStereoFovVertAngle',
                     attributeType='float',
                     min=0.1,
                     softMaxValue=180,
                     defaultValue=180)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoFovHorizAngle',
                     longName='vrayLatLongStereoFovHorizAngle',
                     attributeType='float',
                     min=0.1,
                     softMaxValue=360,
                     defaultValue=360)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoParallaxDistance',
                     longName='vrayLatLongStereoParallaxDistance',
                     attributeType='float',
                     min=0.001,
                     softMaxValue=5000,
                     defaultValue=720)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoSeparation',
                     longName='vrayLatLongStereoSeparation',
                     attributeType='float',
                     min=0,
                     softMaxValue=650,
                     defaultValue=6.5)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoZenithMode',
                     longName='vrayLatLongStereoZenithMode',
                     attributeType='long',
                     defaultValue=0)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoSeparationMap',
                     longName='vrayLatLongStereoSeparationMap',
                     attributeType='float3',
                     usedAsColor=True,
                     numberOfChildren=3)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoSeparationMap',
                     longName='vrayLatLongStereoSeparationMap',
                     usedAsColor=True,
                     attributeType='float3')
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoSeparationMapr',
                     longName='vrayLatLongStereoSeparationMapr',
                     attributeType='float',
                     parent='vrayLatLongStereoSeparationMap',
                     defaultValue=1.0)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoSeparationMapg',
                     longName='vrayLatLongStereoSeparationMapg',
                     attributeType='float',
                     parent='vrayLatLongStereoSeparationMap',
                     defaultValue=1.0)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoSeparationMapb',
                     longName='vrayLatLongStereoSeparationMapb',
                     attributeType='float',
                     parent='vrayLatLongStereoSeparationMap',
                     defaultValue=1.0)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoFlipX',
                     longName='vrayLatLongStereoFlipX',
                     attributeType='long',
                     defaultValue=0)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoFlipY',
                     longName='vrayLatLongStereoFlipY',
                     attributeType='long',
                     defaultValue=0)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoNeckOffset',
                     longName='vrayLatLongStereoNeckOffset',
                     attributeType='float',
                     min=-10000.0,
                     softMaxValue=1000.0,
                     defaultValue=0.0)
        cmds.addAttr(rightCamShape,
                     shortName='vrayLatLongStereoZenithFov',
                     longName='vrayLatLongStereoZenithFov',
                     attributeType='long',
                     defaultValue=0)

        # ---------------------------------------------------------------------
        # Link the common left and right camera attributes to the center camera
        # ---------------------------------------------------------------------

        # Link the left camera attributes
        cmds.connectAttr(centerCam + '.vrayLatLongStereoOn',
                         leftCam + '.vrayLatLongStereoOn',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoFovVertAngle',
                         leftCam + '.vrayLatLongStereoFovVertAngle',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoFovHorizAngle',
                         leftCam + '.vrayLatLongStereoFovHorizAngle',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoParallaxDistance',
                         leftCam + '.vrayLatLongStereoParallaxDistance',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoSeparation',
                         leftCam + '.vrayLatLongStereoSeparation',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoZenithMode',
                         leftCam + '.vrayLatLongStereoZenithMode',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoFlipX',
                         leftCam + '.vrayLatLongStereoFlipX',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoFlipY',
                         leftCam + '.vrayLatLongStereoFlipY',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoNeckOffset',
                         leftCam + '.vrayLatLongStereoNeckOffset',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoZenithFov',
                         leftCam + '.vrayLatLongStereoZenithFov',
                         force=True)

        # Link the right camera attributes
        cmds.connectAttr(centerCam + '.vrayLatLongStereoOn',
                         rightCam + '.vrayLatLongStereoOn',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoFovVertAngle',
                         rightCam + '.vrayLatLongStereoFovVertAngle',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoFovHorizAngle',
                         rightCam + '.vrayLatLongStereoFovHorizAngle',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoParallaxDistance',
                         rightCam + '.vrayLatLongStereoParallaxDistance',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoSeparation',
                         rightCam + '.vrayLatLongStereoSeparation',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoZenithMode',
                         rightCam + '.vrayLatLongStereoZenithMode',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoFlipX',
                         rightCam + '.vrayLatLongStereoFlipX',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoFlipY',
                         rightCam + '.vrayLatLongStereoFlipY',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoNeckOffset',
                         rightCam + '.vrayLatLongStereoNeckOffset',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoZenithFov',
                         rightCam + '.vrayLatLongStereoZenithFov',
                         force=True)

        # ---------------------------------------------------------------------
        # Create the custom Domemaster3D shading networks
        # ---------------------------------------------------------------------

        # Create the nodes

        # ---------------------------------------------------------------------
        # Link the center camera lens shader to the Maya camera rig stereo3d settings
        # This enables real-time 3D previews in the viewport
        # ---------------------------------------------------------------------
        cmds.connectAttr(centerCam + '.vrayLatLongStereoParallaxDistance',
                         centerCam + '.zeroParallax',
                         force=True)
        cmds.connectAttr(centerCam + '.vrayLatLongStereoSeparation',
                         centerCam + '.interaxialSeparation',
                         force=True)

        #Turn off the Stereo 3D effect on the native Maya camera rig
        # This skips the need for a pre-render and post-render mel script.
        cmds.setAttr(centerCam + '.stereo', 0)
예제 #54
0
def isPluginLoaded(plugin):
    loaded = cmds.pluginInfo(plugin, q = True, loaded = True)
    return loaded
예제 #55
0
    rotateAxis(optional = [1,0,0]) - The axis that will be read by the angleReader.
    frontAxis(optional = [0,1,0]) - The front axis that will be used by the angleReader.

Output:
    Tuple (angleReaderTransform, angleReaderShape)

Authors:
    Marin Petrov
    www.scroll-lock.eu
'''

# imports
import maya.cmds as mc

# load plugin
if not mc.pluginInfo('angleReader', q=True, loaded=True):
    mc.loadPlugin('angleReader')


def installAngleReader(name, rotateAxis=[1, 0, 0], frontAxis=[0, 1, 0]):
    sel = mc.ls(sl=True)
    if len(sel) != 2:
        raise RuntimeError, 'Please select 2 transforms as base and driver in order to install angleReader'

    base, driver = sel
    if not name:
        raise RuntimeError, 'No name specified'
    else:
        baseName = '%s%sBaseGrp' % (base, name)
        driverName = '%s%sDriverGrp' % (driver, name)
        readerName = '%s%sReader' % (driver, name)
예제 #56
0
def loadPlugin(plugin):
    loaded = cmds.pluginInfo(plugin, q = True, loaded = True)
    if not loaded:
        cmds.loadPlugin(plugin)
예제 #57
0
def initializePlugin(mobject):
    global rendererModules
    global generalNodeModules
    global materialNodeModules

    mplugin = OpenMayaMPx.MFnPlugin(mobject)

    # Load needed plugins
    try:
        if not cmds.pluginInfo("objExport", query=True, loaded=True):
            cmds.loadPlugin("objExport")
    except:
        sys.stderr.write("Failed to load objExport plugin\n")
        raise

    # Register general nodes
    try:
        for generalNodeModule in generalNodeModules:
            mplugin.registerNode(generalNodeModule.kPluginNodeName,
                                 generalNodeModule.kPluginNodeId,
                                 generalNodeModule.nodeCreator,
                                 generalNodeModule.nodeInitializer,
                                 OpenMayaMPx.MPxNode.kDependNode)
            print("%s - Registered node     : %s" %
                  (kPluginName, generalNodeModule.kPluginNodeName))
    except:
        sys.stderr.write("%s - Failed to register node: %s\n" %
                         (kPluginName, generalNodeModule.kPluginNodeName))
        raise

    # Register Materials / Volumes / Lights
    try:
        for materialNodeModule in materialNodeModules:
            mplugin.registerNode(materialNodeModule.kPluginNodeName,
                                 materialNodeModule.kPluginNodeId,
                                 materialNodeModule.nodeCreator,
                                 materialNodeModule.nodeInitializer,
                                 OpenMayaMPx.MPxNode.kDependNode,
                                 materialNodeModule.kPluginNodeClassify)

            CyclesRenderer.registMaterialNodeType(
                materialNodeModule.kPluginNodeName)

            print("%s - Registered material : %s" %
                  (kPluginName, materialNodeModule.kPluginNodeName))
    except:
        sys.stderr.write("%s - Failed to register node: %s\n" %
                         (kPluginName, materialNodeModule.kPluginNodeName))
        raise

    # Register Renderer commands
    for rendererModule in rendererModules:
        try:
            mplugin.registerCommand(rendererModule.kPluginCmdName,
                                    rendererModule.cmdCreator)
            print("%s - Registered command  : %s" %
                  (kPluginName, rendererModule.kPluginCmdName))
        except:
            sys.stderr.write("%s - Failed to register command: %s\n" %
                             (kPluginName, rendererModule.kPluginCmdName))
            raise

    # Register Renderers
    for rendererModule in rendererModules:
        try:
            rendererModule.registerRenderer()
            print("%s - Registered renderer : %s" %
                  (kPluginName, rendererModule.kPluginCmdName))
        except:
            sys.stderr.write("%s - Failed to register renderer: %s\n" %
                             (kPluginName, rendererModule.kPluginCmdName))
            raise
예제 #58
0
파일: twist.py 프로젝트: moChen0607/pubTool
def build_hipAM(hip,
                pelvis,
                twistJoints,
                hipAim='x',
                hipFront='y',
                pelvisAim='x',
                pelvisFront='y',
                prefix=''):
    '''
	Build hip twist using custom hipConstraint node
	@param hip: Hip or upper leg joint 
	@type hip: str
	@param pelvis: Pelvis joint 
	@type pelvis: str
	@param twistJoints: List of twist joints 
	@type twistJoints: list
	@param hipAim: Axis along the length of the hip/leg joint 
	@type hipAim: list or tuple
	@param hipFront: Forward facing axis of the hip/leg joint 
	@type hipFront: list or tuple
	@param pelvisAim: Axis along the length of the pelvis joint 
	@type pelvisAim: list or tuple
	@param pelvisFront: Forward facing axis of the pelvis joint 
	@type pelvisFront: list or tuple
	@param prefix: Naming prefix for created nodes
	@type prefix: str
	'''
    # ==========
    # - Checks -
    # ==========

    if not mc.objExists(hip):
        raise Exception('Hip joint "' + hip + '" does not exist!')
    if not mc.objExists(pelvis):
        raise Exception('Pelvis joint "' + pelvis + '" does not exist!')
    for twistJoint in twistJoints:
        if not mc.objExists(twistJoint):
            raise Exception('Twist joint "' + twistJoint + '" does not exist!')

    if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(hip)

    # Check Plugin
    if not mc.pluginInfo('AM_HipConstraint', q=True, l=True):
        try:
            mc.loadPlugin('AM_HipConstraint')
        except:
            raise Exception('Unable to load plugin "AM_HipConstraint"!')

    # ======================
    # - Configure Modifier -
    # ======================

    # Define Axis Dictionary
    axisDict = {
        'x': (1, 0, 0),
        'y': (0, 1, 0),
        'z': (0, 0, 1),
        '-x': (-1, 0, 0),
        '-y': (0, -1, 0),
        '-z': (0, 0, -1)
    }

    twistCtrlScale = 0.2

    # =======================
    # - Create Twist Joints -
    # =======================

    # Reverse twist joint list
    twistJoints.reverse()

    # Create Twist Driver Joint
    mc.select(cl=True)
    hipTwist = mc.joint(n=prefix + 'Twist_jnt')
    hipTwistGrp = glTools.utils.joint.group(hipTwist)
    mc.delete(mc.parentConstraint(hip, hipTwistGrp))
    mc.parent(hipTwistGrp, hip)

    # Create Hip Twist Joints
    twistJointGrp = []
    twistFactor = 1.0 / (len(twistJoints) - 1)
    jntLen = glTools.utils.joint.length(hip)
    for i in range(len(twistJoints)):

        controlShape = glTools.tools.controlBuilder.controlShape(
            twistJoints[i], 'box', scale=twistCtrlScale * jntLen)
        glTools.rig.utils.tagCtrl(twistJoints[i], 'tertiary')
        mc.addAttr(twistJoints[i],
                   ln='twist',
                   min=-1.0,
                   max=1.0,
                   dv=twistFactor * i)
        twistJointGrp.append(glTools.utils.joint.group(twistJoints[i]))

    # ==========================
    # - Create Hip Twist Setup -
    # ==========================

    # Create hipConstraint node
    hipCon = mc.createNode('am_hipConstraint')

    # Set and connect hipConstraint attributes
    mc.connectAttr(hip + '.worldMatrix[0]', hipCon + '.hip', f=True)
    mc.connectAttr(pelvis + '.worldMatrix[0]', hipCon + '.pelvis', f=True)
    mc.connectAttr(hipTwist + '.parentInverseMatrix[0]',
                   hipCon + '.parentInverseMatrix',
                   f=True)
    mc.connectAttr(hipTwist + '.rotateOrder', hipCon + '.rotateOrder', f=True)
    mc.connectAttr(hipTwist + '.jointOrient', hipCon + '.jointOrient', f=True)
    mc.setAttr(hipCon + '.hipAim', *axisDict[hipAim])
    mc.setAttr(hipCon + '.hipFront', *axisDict[hipFront])
    mc.setAttr(hipCon + '.pelvisAim', *axisDict[pelvisAim])
    mc.setAttr(hipCon + '.pelvisFront', *axisDict[pelvisFront])

    # Connect to hip twist joint
    mc.connectAttr(hipCon + '.rotate', hipTwist + '.rotate', f=True)

    # Correct initial offset
    twistOffset = mc.getAttr(hipTwist + '.r' + hipAim[-1])
    mc.setAttr(hipTwist + '.jo' + hipAim[-1], twistOffset)

    # ========================
    # - Connect Twist Joints -
    # ========================

    twistMultNode = []
    for i in range(len(twistJoints)):

        alphaInd = glTools.utils.stringUtils.alphaIndex(i, upper=True)
        twistMult = mc.createNode('multDoubleLinear',
                                  n=prefix + '_twist' + alphaInd +
                                  '_multDoubleLinear')
        mc.connectAttr(hipTwist + '.r' + hipAim[-1],
                       twistMult + '.input1',
                       f=True)
        mc.connectAttr(twistJoints[i] + '.twist',
                       twistMult + '.input2',
                       f=True)
        mc.connectAttr(twistMult + '.output',
                       twistJointGrp[i] + '.r' + hipAim[-1],
                       f=True)
        twistMultNode.append(twistMult)

    # Reverse twist joint list
    twistJoints.reverse()

    # ======================
    # - Set Channel States -
    # ======================

    chStateUtil = glTools.utils.channelState.ChannelState()
    chStateUtil.setFlags([0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                         objectList=twistJoints)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=twistJointGrp)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[hipTwistGrp])
    chStateUtil.setFlags([2, 2, 2, 1, 1, 1, 2, 2, 2, 1], objectList=[hipTwist])

    # =================
    # - Return Result -
    # =================

    # Define control list
    ctrlList = twistJoints

    return
예제 #59
0
def load_plugin(plugin_name):
    if not mc.pluginInfo(plugin_name, q=1, loaded=1):
        mc.loadPlugin(plugin_name, quiet=1)
예제 #60
0
def check_gpu_plugin():
    """ Check for the gpuCache plugin load
    """

    if not cmds.pluginInfo('gpuCache', query=True, loaded=True):
        cmds.loadPlugin('gpuCache')