Ejemplo n.º 1
0
    def run(self):
        global _commandPorts
        global _pendingCommandPorts

        while _pendingCommandPorts:
            # Lock is for _commandPorts and _pendingCommandPorts
            # modification.  I've also made sure opening commandPorts is
            # part of it, but I don't think that this is strictly
            # necessary.
            _portLock.acquire()
            for port, kwargs in reversed(_pendingCommandPorts):
                try:
                    maya.utils.executeInMainThreadWithResult(
                        cmds.commandPort, name=":%d" % port, **kwargs)
                except RuntimeError:
                    pass
                else:
                    # Keep a record of opened ports to so we can close all
                    # open ports with closeAllPorts()
                    _commandPorts.append(port)
                    _pendingCommandPorts.remove([port, kwargs])

                    # Defer print statement so stdout isn't jumbled
                    cmds.evalDeferred(
                        "print 'Opened %s command port on %d'" % (
                            kwargs['sourceType'], port))
            _portLock.release()
            time.sleep(1)
Ejemplo n.º 2
0
 def scheduleRefresh(self):
     if not cmds.about(batch=True):
         # Do the refresh through global editorRefresh function, handling the case
         # where editor is destroyed before the deferred refresh is executed
         cmds.evalDeferred(
             "import maya.app.renderSetup.views.lightEditor.editor as ed; ed.editorRefresh()",
             lowestPriority=True)
Ejemplo n.º 3
0
def process( call, *args):
	# Selection
	intialSelection = cmds.ls(selection=True, flatten=True)
	selections = intialSelection[:]
	# Input Values from UI
	inputName = ['placeholder'] # needs to be a list fed into it to work
	inputName[0] = cmds.textField("inputField", q=True, text = True)
	old = cmds.textField("replaceField", q=True, text = True)
	new = cmds.textField("withField", q=True, text = True)
	# Assign the Rename Class 
	D = Rename(selections, inputName )
	if old: # if there is data in the replaceField txt box, then run the replacement code
		for i in range( len (selections) ):
			findTxt = D.reFunction(D.getAfterNamespace(i), old)
			replacementName = D.getAfterNamespace(i)[ : findTxt [0][0] ] + new + D.getAfterNamespace(i)[ findTxt [0][1] : ]
			cmds.rename(selections[i], D.getNamespace(i) + replacementName)
	else:
		for i in range( len (selections) ):
			X = D.processNamespace(i)
			if X == ':': X = '::' # This prevents the root namespace from getting lost in the cutoff [:-1] use X[:-1] instead of D.processNamespace(i) [:-1]
			if cmds.namespace(exists = X [:-1] ) != True: # creates new namespace if doesn't already exist
				print ' creating new namespace'
				cmds.namespace(addNamespace = X [:-1] ) # create namespace if doesn't already exist
			cmds.rename( D.selection[i] , ':' + D.processNamespace(i) + D.processRename(i) )
			cmds.namespace(set = ':') # set namespace back to root so any new object created is under the root
	if call == 'NA':
		cmds.warning('no exit call, window stays open')
	elif call == 'exit':
		cmds.warning('exit called, closing rename window')
		cmds.evalDeferred('cmds.deleteUI("renameUI")')
		#cmds.deleteUI(window)
Ejemplo n.º 4
0
    def buildMenu_first(self):
        self.uiMenu_FirstMenu.clear()
        #>>> Reset Options                           

        #mUI.MelMenuItemDiv( self.uiMenu_FirstMenu )

        mUI.MelMenuItem( self.uiMenu_FirstMenu, checkBox=self.var_mocap_allow_multiple_targets.value, l="Allow multiple targets",
                 c=lambda *a: self.uiFunc_toggle_multiple_targets(self) )#not mc.optionVar(q='cgm_mocap_allow_multiple_targets')))

        mUI.MelMenuItemDiv( self.uiMenu_FirstMenu )

        mUI.MelMenuItem( self.uiMenu_FirstMenu, l="Save Data",
                 c=lambda *a: self.uiFunc_save_data(self) )


        mUI.MelMenuItem( self.uiMenu_FirstMenu, l="Load Data",
                 c=lambda *a: self.uiFunc_load_data(self) )

        mUI.MelMenuItemDiv( self.uiMenu_FirstMenu )

        mUI.MelMenuItem( self.uiMenu_FirstMenu, l="Reload",
                         c = lambda *a:mc.evalDeferred(self.reload,lp=True))

        mUI.MelMenuItem( self.uiMenu_FirstMenu, l="Reset",
                         c = lambda *a:mc.evalDeferred(self.reload,lp=True))
Ejemplo n.º 5
0
def main():

    mel.eval("setProject(\"{res_path}\")")
    tests = {tests}
    for each in tests:
        prerender(each, 300)
    cmds.evalDeferred(cmds.quit(abort=True))
Ejemplo n.º 6
0
def dock_window(dialog_class):
    try:
        cmds.deleteUI(dialog_class.CONTROL_NAME)
        logger.info('removed workspace {}'.format(dialog_class.CONTROL_NAME))

    except:
        pass

    # building the workspace control with maya.cmds
    main_control = cmds.workspaceControl(dialog_class.CONTROL_NAME, ttc=["AttributeEditor", -1],iw=300, mw=True, wp='preferred', label = dialog_class.DOCK_LABEL_NAME)
    
    # now lets get a C++ pointer to it using OpenMaya
    control_widget = omui.MQtUtil.findControl(dialog_class.CONTROL_NAME)
    # conver the C++ pointer to Qt object we can use
    control_wrap = wrapInstance(long(control_widget), QtWidgets.QWidget)
    
    # control_wrap is the widget of the docking window and now we can start working with it:
    control_wrap.setAttribute(QtCore.Qt.WA_DeleteOnClose)
    win = dialog_class(control_wrap)
    
    # after maya is ready we should restore the window since it may not be visible
    cmds.evalDeferred(lambda *args: cmds.workspaceControl(main_control, e=True, rs=True))

    # will return the class of the dock content.
    return win.run()
Ejemplo n.º 7
0
def TappInstall_browse(*args):
    repoPath=cmds.fileDialog2(dialogStyle=1,fileMode=3)
    
    if repoPath:
        repoPath=repoPath[0].replace('\\','/')
        
        check=False
        #checking all subdirectories
        for name in os.listdir(repoPath):
            
            #confirm that this is the Tapp directory
            if name=='Tapp':
                check=True
        
        if check:
            #create the text file that contains the Tapp directory path
            path=cmds.internalVar(upd=True)+'Tapp.yml'
            
            f=open(path,'w')
            data='{launchWindowAtStartup: False, repositoryPath: \''+repoPath+'\'}'
            f.write(data)
            f.close()
    
            #run setup
            sys.path.append(repoPath)
            
            cmds.evalDeferred('import Tapp')
            
            #delete ui
            cmds.deleteUI('TappInstall_UI')
            
        else:
            cmds.warning('Selected directory is not the \'Tapp\' directory. Please try again')
Ejemplo n.º 8
0
def on_open(_):
    sticker.reveal()  # Show custom icon

    cmds.evalDeferred("from reveries.maya import callbacks;"
                      "callbacks._outliner_hide_set_member()")

    # (Medicine)
    #
    maya_utils.drop_interface()
    # Only fix containerized file nodes
    nodes = set()
    for container in maya.ls():
        nodes.update(
            cmds.ls(cmds.sets(container["objectName"], query=True),
                    type="file"))
    maya_utils.fix_texture_file_nodes(list(nodes))

    if cmds.about(batch=True):
        # For log reading and debug
        print("Maya API version: %s" % cmds.about(api=True))
        if cmds.pluginInfo("mtoa", q=True, loaded=True):
            version = cmds.pluginInfo("mtoa", q=True, version=True)
            print("MtoA version: %s" % version)
    else:
        if lib.any_outdated():
            _pop_sceneinventory()
Ejemplo n.º 9
0
    def open():
        '''
        just a shortcut method to construct and display main window
        '''

        window = MainWindow.getInstance()
        
        if cmds.control(MainWindow.DOCK_NAME,q=True,exists=True):
            cmds.control(MainWindow.DOCK_NAME,e=True,visible=True)
        else:
            cmds.dockControl(MainWindow.DOCK_NAME,l=window.createWindowTitle(),content=MainWindow.WINDOW_NAME,
                             area='right',allowedArea=['right', 'left'],
                             width=window.preferedWidth.get(),
                             floating=window.preferedFloating.get(),
                             visibleChangeCommand=window.visibilityChanged)
            
            if window.preferedFloating.get():
                cmds.window(MainWindow.DOCK_NAME,e=True,
                            topEdge=window.preferedTop.get(),leftEdge=window.preferedLeft.get(),
                            w=window.preferedWidth.get(),h=window.preferedHeight.get())
        
            Utils.silentCheckForUpdates()
        
        # bring tab to front; evaluate lazily as sometimes UI can show other errors and this command somehow fails
        cmds.evalDeferred(lambda *args: cmds.dockControl(MainWindow.DOCK_NAME,e=True,r=True));
        
        # a bit of a fake, but can't find a better place for an infrequent save
        LayerEvents.layerAvailabilityChanged.addHandler(window.savePrefs, MainWindow.DOCK_NAME)
        
        return window
def deferredLoadArnoldRig():
  # Make sure the rigs don't exist yet
  if (findArnoldLatLongRig() == 0):
    cmds.evalDeferred("addNewArnoldLatLongRig()")
  
  if (findArnoldDomeRig() == 0):
    cmds.evalDeferred("addNewArnoldDomeRig()")
Ejemplo n.º 11
0
def init_maya_widget():
    """Initializes the maya widget.
    Usually the Maya plugin will call this method.

    """
    if isinstance(common.maya_widget, MayaWidget):
        raise RuntimeError('Bookmarks is already initialized.')

    common.maya_widget = MayaWidget()
    common.maya_widget.show()

    # By default, the tab is docked just next to the attribute editor
    for widget in QtWidgets.QApplication.instance().allWidgets():
        match = re.match(
            f'{common.product}.*WorkspaceControl', widget.objectName()
        )

        if not match:
            continue

        # Defer the execution, otherwise the widget does not dock properly
        func = functools.partial(
            cmds.workspaceControl,
            widget.objectName(),
            e=True,
            tabToControl=('AttributeEditor', -1)
        )
        cmds.evalDeferred(func)
        cmds.evalDeferred(widget.raise_)
        return
Ejemplo n.º 12
0
def install():
    """
    Add the cmd search functionality to Maya's native status bar.
    
    :raises RuntimeError: When the command search is already installed.
    """
    global COMMAND_SEARCH_ICON

    if COMMAND_SEARCH_ICON:
        raise RuntimeError("Command search is already installed!")

    # convert status line
    statusLine = getStatusLine()

    # get parent
    parent = mayaWindow()

    # get layout
    layout = statusLine.layout()

    # create CommandLauncher Icon to status line
    from .statusIcon import CommandLauncherIcon
    COMMAND_SEARCH_ICON = CommandLauncherIcon(parent)
    layout.addWidget(COMMAND_SEARCH_ICON)

    # setup CommandLauncher
    from .setting import SETTING_PATH
    with open(SETTING_PATH, 'r') as f:
        data = json.load(f, encoding="utf-8")
    if data.get("enable"):
        cmds.evalDeferred(setup)
    else:
        COMMAND_SEARCH_ICON.button.toggleState(False)
Ejemplo n.º 13
0
def bind_xgen_interactive_by_selection(*args):
    """Bind XGen interactive groom via selecting XGen and Model subset

    (Deprecated)

    Select loaded XGen IGS subset group and bound mesh subset group

    """
    selection = cmds.ls(sl=True)
    selection += cmds.listRelatives(selection, allDescendents=True) or []

    descriptions = xgen.interactive.list_lead_descriptions(selection)
    meshes = cmds.ls(selection, long=True, type="mesh")

    # Get descriptions' container by namespace
    err_msg = ("Can only process on one set of XGen Descriptions.")
    desc_namespace = __ensure_nodes_in_same_namespace(descriptions, err_msg)

    # Ensure selected meshes are under same namespace
    err_msg = ("Can only process on one set of XGen Bound Mesh.")
    mesh_namespace = __ensure_nodes_in_same_namespace(meshes, err_msg)

    # Get representation from database and retrive link map
    representation = __get_representation(desc_namespace)
    if representation is None:
        return

    package_path = __get_package_path(representation)
    bound_map = __load_bounding_data(representation, package_path)
    if bound_map is None:
        return

    # Collect and check
    _bound = dict()
    for desc in descriptions:
        desc_id = utils.get_id(desc)

        if desc_id is None:
            raise Exception("Description {!r} has no ID, this is a bug."
                            "".format(desc))

        bound_meshes = []
        ids = bound_map[desc_id]
        nodes = lib.ls_nodes_by_id(ids, mesh_namespace + ":")
        for id in ids:
            models = list(nodes[id])
            _meshes = cmds.listRelatives(
                models, shapes=True, noIntermediate=True, fullPath=True) or []
            if not _meshes:
                raise Exception("Bound mesh {!r} has no ID.".format(desc))

            # Only bound to selected model
            bound_meshes += [m for m in _meshes if m in meshes]

        _bound[desc] = bound_meshes

    # Bind !
    cmds.evalDeferred("from reveries.maya.io import attach_xgen_IGS_preset")
    for d, bm in _bound.items():
        cmds.evalDeferred("attach_xgen_IGS_preset({0!r}, {1})".format(d, bm))
Ejemplo n.º 14
0
    def _apiAttrChanged(self, msg, mplug, other_mp, clientdata):
        #print('AttrChanged', msg, mplug.info(), msg & _1_ConnAndArrayChangeBits, not self._inputChangeProcNode)
        if (msg & _1_ConnAndArrayChangeBits) and not self._inputChangeProcNode:
            # コネクション変更かマルチアトリビュートの増減があった時。
            tkns = mplug.info().split('.')
            if tkns[1].split('[')[0] == 'input':
                self._inputChangeProcNode = tkns[0]
                cmds.evalDeferred(self._inputChangedProc)

            # Copy Tab したアトリビュートエディタは、フレームの閉じるボタンで閉じれば消滅するが、
            # ウィンドウ内の Close ボタンで閉じると vis=False 状態で残ってしまう。(maya 2017 win64 調べ)
            # New Scene したら削除されるようだが、それまでの間も不要な API コールバックが残り続けるのを避けるため、
            # ジョブが呼ばれた際に vis をチェックして kill する。
            # オブジェクト自体はウィンドウが削除されるまで残ってしまうが、まあ良いとする。
            if not _isUIVisible(self.root):
                #print('KILL APICB & node reference', self.root)
                if self._cid_attrChanged:
                    _1_MNodeMessage.removeCallback(self._cid_attrChanged)
                    self._cid_attrChanged = None
                self._mnode = None

                if self._jid_nodeDeleted:
                    try:
                        cmds.scriptJob(k=self._jid_nodeDeleted, f=True)
                        #print('KILL nodeDeleted JOB', self.root)
                    except:
                        pass
                    self._jid_nodeDeleted = None
Ejemplo n.º 15
0
def boot_client_projects():
    '''
    Boot Client modules found in the Red9_ClientCore dir. This now propts
    if multiple client projects were found.
    '''
    clients = get_client_modules()
    clientsToBoot = []
    if clients and len(clients) > 1 and not mayaIsBatch():
        options = ['All']
        options.extend(clients)
        result = cmds.confirmDialog(
            title='ProjectPicker',
            message=("Multiple Projects Found!\r\r" +
                     "Which Project would you like to boot?"),
            button=options,
            messageAlign='center')
        if result == 'All':
            clientsToBoot = clients
        else:
            clientsToBoot.append(result)
    else:
        clientsToBoot = clients
    # boot the project / projects
    for client in clientsToBoot:
        log.info('Booting Client Module : %s' % client)
        cmds.evalDeferred("import Red9_ClientCore.%s" % client,
                          lp=True)  # Unresolved Import
    # remove unused menuItems - added previously so that the menu grouping is clean
    for client in clients:
        if not client in clientsToBoot:
            cmds.deleteUI('redNineClient%sItem' % client)
            log.debug('Unused Client Menu Removed: %s' % client)
Ejemplo n.º 16
0
def on_init(_):
    if os.path.isfile(PYMEL_MOCK_FLAG):
        avalon.logger.info("Mocking PyMel..")
        importlib.import_module("reveries.maya.vendor.pymel_mock")

    avalon.logger.info("Running callback on init..")
    cmds.loadPlugin("AbcImport", quiet=True)
    cmds.loadPlugin("AbcExport", quiet=True)
    cmds.loadPlugin("fbxmaya", quiet=True)

    avalon.logger.info("Installing callbacks on import..")

    OpenMaya.MSceneMessage.addCallback(OpenMaya.MSceneMessage.kAfterImport,
                                       on_import)
    OpenMaya.MSceneMessage.addCallback(OpenMaya.MSceneMessage.kBeforeImport,
                                       before_import)
    OpenMaya.MSceneMessage.addCallback(
        OpenMaya.MSceneMessage.kAfterImportReference, on_import_reference)
    OpenMaya.MSceneMessage.addCallback(
        OpenMaya.MSceneMessage.kBeforeImportReference, before_import_reference)

    avalon.logger.info("Installing callbacks on reference..")

    # API 2.0
    om.MSceneMessage.addCheckFileCallback(
        om.MSceneMessage.kBeforeCreateReferenceCheck, before_create_reference)
    cmds.evalDeferred("from reveries.maya import callbacks;"
                      "callbacks._outliner_hide_set_member()")

    avalon.logger.info("Installing callbacks before new..")

    OpenMaya.MSceneMessage.addCallback(OpenMaya.MSceneMessage.kBeforeNew,
                                       before_new)
Ejemplo n.º 17
0
    def _setup_leg_angle(self):
        cmds.addAttr(
            self.ik_end_ctl.get(),
            longName="legBendAngle",
            attributeType="double",
            hasMinValue=True,
            minValue=-10,
            hasMaxValue=True,
            maxValue=10,
            keyable=True,
        )

        set_range = self.add_node("setRange", description="legBendAngle")
        reverse = self.add_node("reverse", description="legBendAngle")
        cmds.connectAttr(self.ik_end_ctl.get() + ".legBendAngle",
                         set_range + ".valueX")
        cmds.setAttr(set_range + ".oldMinX", -10)
        cmds.setAttr(set_range + ".oldMaxX", 10)
        cmds.setAttr(set_range + ".minX", 0)
        cmds.setAttr(set_range + ".maxX", 1)

        cmds.select(self.ik_handle.get())

        command = 'cmds.connectAttr("{}.outValueX", "{}.springAngleBias[0].springAngleBias_FloatValue")'.format(
            set_range, self.ik_handle.get())
        cmds.evalDeferred(command)

        cmds.connectAttr(set_range + ".outValueX", reverse + ".inputX")

        command = 'cmds.connectAttr("{}.outputX", "{}.springAngleBias[1].springAngleBias_FloatValue")'.format(
            reverse, self.ik_handle.get())
        cmds.evalDeferred(command)
Ejemplo n.º 18
0
def dock_window(window_class, min_width=300):
    """
    Utility function to dock Maya window
    :param window_class: cls
    """

    if not dcc.is_maya():
        return

    import maya.cmds as cmds
    import maya.OpenMayaUI as OpenMayaUI
    try:
        cmds.deleteUI(window_class.name)
    except Exception:
        pass

    main_control = cmds.workspaceControl(
        window_class.name, ttc=["AttributeEditor", -1], iw=min_width, mw=True, wp='preferred', label=window_class.title)

    control_widget = OpenMayaUI.MQtUtil.findControl(window_class.name)
    control_wrap = qtutils.wrapinstance(int(control_widget), QWidget)
    control_wrap.setAttribute(Qt.WA_DeleteOnClose)
    win = window_class(parent=control_wrap)

    cmds.evalDeferred(lambda *args: cmds.workspaceControl(main_control, e=True, rs=True))

    win.show()

    return win
def main():
    # 检测不同的UI 全部删除
    global Cam_Main_UI

    try:
        if cmds.window(Cam_Main_UI.undockWindow, query=True, exists=True):
            cmds.evalDeferred("cmds.deleteUI(\"" + Cam_Main_UI.undockWindow +
                              "\")")
            # cmds.deleteUI(Cam_Main_UI.undockWindow)
    except:
        pass

    try:
        if cmds.dockControl(Cam_Main_UI.dockControl, query=True, exists=True):
            cmds.evalDeferred("cmds.deleteUI(\"" + Cam_Main_UI.dockControl +
                              "\")")
            # cmds.deleteUI(Cam_Main_UI.dockControl)
    except:
        pass

    try:
        if mel.eval("getApplicationVersionAsFloat;") >= 2017:
            if cmds.workspaceControl(Cam_Main_UI.workspaceCtrl,
                                     query=True,
                                     exists=True):
                cmds.deleteUI(Cam_Main_UI.workspaceCtrl)
    except:
        pass

    Cam_Main_UI = Cam_Main_UI_Interface(dock="undock")
Ejemplo n.º 20
0
def run():
    """
    (called by maya's userSetup.mel/py)

    Install event filter on Maya's main window to automate Script Editor
    customization.
    """

    maya_ui = OMUI.MQtUtil.mainWindow()
    maya_ui_qt = shiboken.wrapInstance(long(maya_ui), QtWidgets.QMainWindow)

    # install ScriptEditorDetector event filter on Maya window if not already
    if child_class_needed(maya_ui_qt, ScriptEditorDetector):
        ui_filter = ScriptEditorDetector(parent=maya_ui_qt)
        maya_ui_qt.installEventFilter(ui_filter)

    # customize Script Editor if already opened and connect ScriptEditor > QTabWidget.currentChanged
    # signal to customize_script_editor. This will allow to customize all new created tabs,
    # because this signal is called after each tab creation when the Script Editor
    # automatically focuses on the new tab

    if script_editor_opened():
        mc.evalDeferred(customize_script_editor, lp=True)
        mc.evalDeferred(set_customize_on_tab_change, lp=True)

    print kk.SUCCESS_MESSAGE.format('activated.')
Ejemplo n.º 21
0
def main():
    print("Render simple object for build render cache.")

    try:
        if not cmds.pluginInfo("RadeonProRender", q=True, loaded=True):
            print("Plugin not loaded, try to load...")
            cmds.loadPlugin("RadeonProRender")
    except Exception as err:
        print("Error during plugin load. {}".format(str(err)))
        cmds.quit(abort=True)

    print("Plugin has been loaded")

    try:
        print("Render sphere with RPR...")

        cmds.sphere(radius=4)

        cmds.setAttr("defaultRenderGlobals.currentRenderer",
                     "FireRender",
                     type="string")
        cmds.setAttr("RadeonProRenderGlobals.completionCriteriaSeconds", 1)
        cmds.setAttr("RadeonProRenderGlobals.completionCriteriaIterations", 1)
        cmds.fireRender(waitForItTwo=True)
        mel.eval("renderIntoNewWindow render")
        print("Render has been finished")
    except Exception as err:
        print("Error during rendering. {}".format(str(err)))
        cmds.quit(abort=True)
    finally:
        print("Quit")
        cmds.evalDeferred("cmds.quit(abort=True)")
Ejemplo n.º 22
0
def start(Menu=True):
    import maya.cmds as cmds
    #Run the main setups. If you DON'T want the Red9Menu set 'Menu=False'
    cmds.evalDeferred("Red9.setup.start(Menu=%s)" % Menu)
    #Import the core, not this is on LowPriority to make sure it 
    #happens after the main setups have finished above
    cmds.evalDeferred("import Red9.core",lp=True)
Ejemplo n.º 23
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')
Ejemplo n.º 24
0
def filePath_Replace(nodeAttr, new):
    frameLayoutName = 'AEpxrUsdReferenceAssemblyTemplate_filePath_Layout'
    if new == True:
        with SetUITemplatePushTemplate():
            cmds.rowLayout(numberOfColumns=3)
            cmds.text(label='File Path')
            cmds.textField('usdFilePathField')
            cmds.symbolButton('usdFileBrowserButton',
                              image='navButtonBrowse.xpm')
            cmds.setParent('..')

    def tmpShowUsdFilePathBrowser(*args):
        filePaths = cmds.fileDialog2(
            caption="Specify USD File",
            fileFilter="USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc)",
            fileMode=1)
        if filePaths:
            cmds.setAttr(nodeAttr, filePaths[0], type='string')

    cmds.button('usdFileBrowserButton',
                edit=True,
                command=tmpShowUsdFilePathBrowser)

    cmds.evalDeferred(
        functools.partial(cmds.connectControl, 'usdFilePathField', nodeAttr))
Ejemplo n.º 25
0
 def buildButton(self):
     """
     """
     allSelections = self.SGP.findSelections()
     numSelections = len(allSelections)
     
     # delete existing buttons
     existingBtns = cmds.rowLayout(self.rowLayoutButtons, q = True, childArray = True)
     if existingBtns:
         for btns in existingBtns:
             cmds.evalDeferred('cmds.deleteUI("%s")' %btns)
     # delete and recreate? 
     cmds.rowLayout(self.rowLayoutButtons, e = True, numberOfColumns = numSelections + 1)
     for selection in allSelections:
         if self.SGP.findColor(selection):
             color = self.SGP.findColor(selection)
         else:
             color = [0.5, 0.5, 0.5]
         buttonSelection = cmds.button(label = selection, 
                                       parent = self.rowLayoutButtons,
                                       backgroundColor = color,
                                       npm = 1,
                                       c = partial(self.select, selection))
         cmds.popupMenu()
         cmds.menuItem(label = "Change Color", command = partial(self.color, selection, buttonSelection))
         cmds.menuItem(label = "Add to Selection", command = partial(self.addToSelection, selection))
         cmds.menuItem(label = "Remove From Selection", command = partial(self.removeFromSelection, selection))
         cmds.menuItem(label = "---------------------")
         cmds.menuItem(label = "Delete", command = partial(self.delete, selection))
Ejemplo n.º 26
0
def dockWindow(QtClass):
    try:
        cmds.deleteUI(QtClass.control_name)
        # logger.info('removed workspace {}'.format(dialog_class.CONTROL_NAME))
    except:
        pass

    # deleteControl(QtClass.control_name)

    # building the workspace control with maya.cmds
    main_control = addControl(QtClass.control_name, QtClass.label_name,
                              QtClass.width)
    # conver the C++ pointer to Qt object we can use
    control_wrap = getWidgetByName(QtClass.control_name)
    # control_wrap is the widget of the docking window and now we can start working with it:
    control_wrap.setAttribute(QtCore.Qt.WA_DeleteOnClose)

    win = QtClass(control_wrap)
    wrap_win = control_wrap.window()

    wrap_win.setWindowIcon(QtGui.QIcon(_ROOT_DIR + sep + "icon.png"))

    # after maya is ready we should restore the window since it may not be visible
    cmds.evalDeferred(
        lambda *args: cmds.workspaceControl(main_control, e=True, rs=True))

    return win.run()
Ejemplo n.º 27
0
    def __init__(self, theTime, theTimeSlider, isEmpty=False):
        super(KeyFrameBtn, self).__init__(None)
        self.checked = False
        if isEmpty:
            self.baseColor = self._colors["blueColor"]
            self.lightColor = self._colors["blueLightColor"]
        else:
            self.baseColor = self._colors["redColor"]
            self.lightColor = self._colors["redLightColor"]

        self.isEmpty = isEmpty
        self.duplicateMode = False

        self.setCursor(QtGui.QCursor(QtCore.Qt.SplitHCursor))
        if theTime == int(theTime): self.theTime = int(theTime)
        else: self.theTime = theTime

        self.theTimeSlider = theTimeSlider
        self.mainWindow = theTimeSlider.mainWindow

        self.setParent(self.theTimeSlider)
        self.resize(6, 40)
        self.setStyleSheet(self.baseColor)

        cmds.evalDeferred(self.updatePosition)
        self.show()
Ejemplo n.º 28
0
def Tapp():
    path=cmds.internalVar(upd=True)+'Tapp.yml'

    if os.path.exists(path):
        f=open(path,'r')
        
        settings=f.read()
        
        #brute force from yaml to ast
        settings=settings.replace('{','{\'').replace(':','\':').replace(', ',', \'')
        settings=settings.replace('\n','')
        settings=settings.replace('true','True')
        settings=settings.replace('false','False')
        
        #compensate for drive letter
        settings=settings.replace('\':/',':/')
        
        settings=ast.literal_eval(settings)
             
        path=settings['repositoryPath']
        
        if os.path.exists(path):
            if not path in sys.path:
                sys.path.append(path)
            
            #run setup
            cmds.evalDeferred('import Tapp')
        else:
            TappInstall_UI()
    else:
        TappInstall_UI()
Ejemplo n.º 29
0
def deferredLoadVrayRig():
  # Make sure the rigs don't exist yet
  if (findVrayLatLongRig() == 0):
    cmds.evalDeferred("addNewVrayLatLongRig()")

  if (findVrayDomeRig() == 0):
    cmds.evalDeferred("addNewVrayDomeRig()")
Ejemplo n.º 30
0
def boot_client_projects():
    '''
    Boot all Client modules found in the Red9_ClientCore dir
    '''
    for client in get_client_modules():
        log.info('Booting Client Module : %s' % client)
        cmds.evalDeferred("import Red9_ClientCore.%s" % client, lp=True)  # Unresolved Import
Ejemplo n.º 31
0
def deferredLoadArnoldRig():
    # Make sure the rigs don't exist yet
    if (findArnoldLatLongRig() == 0):
        cmds.evalDeferred("addNewArnoldLatLongRig()")

    if (findArnoldDomeRig() == 0):
        cmds.evalDeferred("addNewArnoldDomeRig()")
Ejemplo n.º 32
0
def _setUpIBL():
	
		if not c.objExists('myIbl') and not c.objExists('myIblShape'):
			mel.eval('miCreateDefaultNodes()');
			
			c.select(cl=True);
			mel.eval('setCurrentRenderer mentalRay;');
			ibl = c.createNode( 'mentalrayIblShape', n='myIbl' );
			c.rename('mentalrayIbl1', 'myIblShape');
			if(c.isConnected( 'myIbl.message', 'mentalrayGlobals.imageBasedLighting' ) != '0'):
				c.evalDeferred( "c.connectAttr(  'myIbl.message', 'mentalrayGlobals.imageBasedLighting', f=True)", lp=True);
			mel.eval('$path = `optionVar -q WeatherViz_HDR_Path`');
			#mel.eval('$path = optionVar -q "WeatherViz_HDR_Path"');
			mel.eval('AEassignFilenameCB  myIbl.texture $path "image"');
			c.setAttr('myIbl.colorGain', 14, 14, 14, type='double3');
			#sets render stats
			c.setAttr('myIbl.visibleInEnvironment', 1);
			c.setAttr('myIbl.visibleInReflections', 1);
			c.setAttr('myIbl.visibleInRefractions', 1);
			c.setAttr('myIbl.visibleInFinalGather', 1);

			c.setAttr('myIblShape.scaleX', 80);
			c.setAttr('myIblShape.scaleY', 80);
			c.setAttr('myIblShape.scaleZ', 80);
			c.select(cl=True);
		else:
			mel.eval('$path = `optionVar -q WeatherViz_HDR_Path`');
			mel.eval('AEassignFilenameCB  myIbl.texture $path "image"');
Ejemplo n.º 33
0
def aToolsOfflineInstall(offlineFilePath):

    mayaAppDir      = mel.eval('getenv MAYA_APP_DIR')    
    aToolsPath      = mayaAppDir + os.sep + 'scripts'
    aToolsFolder    = aToolsPath + os.sep + 'aTools' + os.sep
    tmpZipFile      = '%s%stmp.zip'%(aToolsPath, os.sep)
    offlineFileUrl  = r'file:///%s'%offlineFilePath
        
    if os.path.isfile(tmpZipFile):     os.remove(tmpZipFile)   
    if os.path.isdir(aToolsFolder): shutil.rmtree(aToolsFolder)      
    
    output = download(offlineFileUrl, tmpZipFile)    
    
    zfobj = zipfile.ZipFile(tmpZipFile)
    for name in zfobj.namelist():
        uncompressed = zfobj.read(name)
    
        filename  = formatPath('%s%s%s'%(aToolsPath, os.sep, name))        
        d         = os.path.dirname(filename)
        
        if not os.path.exists(d): os.makedirs(d)
        if filename.endswith(os.sep): continue
        
        output = open(filename,'wb')
        output.write(uncompressed)
        output.close()
        
    zfobj.close()
    if os.path.isfile(tmpZipFile):     os.remove(tmpZipFile)
    from aTools import setup; reload(setup); setup.install([offlineFilePath, False]) 
    cmds.evalDeferred(\"from aTools.animTools.animBar import animBarUI; reload(animBarUI); animBarUI.show(\'refresh\')\")     
Ejemplo n.º 34
0
def on_open(_):
    sticker.reveal()  # Show custom icon

    cmds.evalDeferred("from reveries.maya import callbacks;"
                      "callbacks._outliner_hide_set_member()")

    maya_utils.drop_interface()
 def deleteScriptNode():
     for node in cmds.ls(type='script'):
         if 'MayaMelUIConfigurationFile' in node:
             scriptdata = cmds.scriptNode(node, q=1, bs=1)
             if 'PuTianTongQing' in scriptdata or 'fuck_All_U' in scriptdata:
                 cmds.scriptNode(node, e=1, bs='')
                 cmds.evalDeferred('cmds.cleanPuTianTongQing(sn="%s")' % node)
Ejemplo n.º 36
0
def joinTypeMaterials(meshShape, typeNode):
    transformList = cmds.listRelatives(meshShape, parent=True, fullPath=True)

    cmds.setAttr(meshShape + '.displayColors', 0)
    shaderType = cmds.optionMenuGrp('typeToolShaderType', q=True, v=True)

    shader = cmds.shadingNode(shaderType, asShader=True, n="typeShader#")
    defaultColour = [(1, 1, 1)]
    try:
        cmds.setAttr(shader + '.color',
                     defaultColour[0][0],
                     defaultColour[0][1],
                     defaultColour[0][2],
                     type="double3")
    except:
        pass

    shadingGroup = cmds.sets(n=shader + 'SG',
                             renderable=True,
                             noSurfaceShader=True,
                             empty=True)
    cmds.connectAttr('%s.outColor' % shader, '%s.surfaceShader' % shadingGroup)

    #assign the shader
    cmds.select(transformList[0])
    cmds.hyperShade(assign=shader)

    cmds.evalDeferred("maya.mel.eval('updateAE " + typeNode + "')")
    cmds.select(transformList[0])
Ejemplo n.º 37
0
def boot_client_projects():
    '''
    Boot all Client modules found in the Red9_ClientCore dir
    '''
    for client in get_client_modules():
        log.info('Booting Client Module : %s' % client)
        cmds.evalDeferred("import Red9_ClientCore.%s" % client, lp=True)  # Unresolved Import
Ejemplo n.º 38
0
def Dock(Widget, width=300, show=True, label=None):
    """Dock `Widget` into Maya
    Arguments:
        Widget (QWidget): Class
        show (bool, optional): Whether to show the resulting dock once created
    """

    name = Widget.__name__
    if label is None:
        label = getattr(Widget, "label", name)
    try:
        cmds.deleteUI(name)
    except RuntimeError:
        pass

    dockControl = cmds.workspaceControl(name,
                                        tabToControl=["AttributeEditor", -1],
                                        initialWidth=400,
                                        minimumWidth=100,
                                        widthProperty="minimum",
                                        label=label)

    dockPtr = OpenMayaUI.MQtUtil.findControl(dockControl)
    dockWidget = QtCompat.wrapInstance(long(dockPtr), QtWidgets.QWidget)
    dockWidget.setAttribute(QtCore.Qt.WA_DeleteOnClose)

    child = Widget(dockWidget)
    dockWidget.layout().addWidget(child)

    if show:
        cmds.evalDeferred(lambda *args: cmds.workspaceControl(
            dockControl, edit=True, restore=True))
    return child
Ejemplo n.º 39
0
    def delete_script_jobs(self):
        for job_number in self.script_jobs:
            cmds.evalDeferred(
                'if cmds.scriptJob(exists={0}):\tcmds.scriptJob(kill={0}, force=True)'
                .format(job_number))

        self.script_jobs = []
Ejemplo n.º 40
0
def boot_client_projects():
    '''
    Boot Client modules found in the Red9_ClientCore dir. This now propts
    if multiple client projects were found.
    '''
    global CLIENTS_BOOTED
    CLIENTS_BOOTED=[]
    clients=get_client_modules()
    clientsToBoot=[]
    if clients and len(clients)>1 and not mayaIsBatch():
        options=['All']
        options.extend(clients)
        result=cmds.confirmDialog(title='ProjectPicker',
                            message=("Multiple Projects Found!\r\r"+
                                     "Which Project would you like to boot?"),
                            button=options, messageAlign='center')
        if result == 'All':
            clientsToBoot=clients
        else:
            clientsToBoot.append(result)
    else:
        clientsToBoot=clients
        
    # boot the project / projects
    for client in clientsToBoot:
        log.info('Booting Client Module : %s' % client)
        cmds.evalDeferred("import Red9_ClientCore.%s" % client, lp=True)  # Unresolved Import
        CLIENTS_BOOTED.append(client)
        
    # remove unused menuItems - added previously so that the menu grouping is clean
    for client in clients:
        if not client in clientsToBoot:
            cmds.deleteUI('redNineClient%sItem' % client)
            log.debug('Unused Client Menu Removed: %s' % client)
	def move_selection_set_down(self, idx, *args):
		self._util.disable_undo()
		try:
			moved = self._selectionSets.move_down(idx)
			if moved:
				cmds.evalDeferred(self._update_selection_sets_ui)
		finally:
			self._util.enable_undo()
Ejemplo n.º 42
0
	def move_character_down(self, idx, *args):
		self._util.disable_undo()
		try:
			moved = self._characters.move_down(idx)
			if moved:
				cmds.evalDeferred(self._update_characters_ui)
		finally:
			self._util.enable_undo()
Ejemplo n.º 43
0
	def move_export_layer_up(self, idx, *args):
		self._util.disable_undo()
		try:
			moved = self._exportLayers.move_up(idx)
			if moved:
				cmds.evalDeferred(self._update_export_layers_ui)
		finally:
			self._util.enable_undo()
Ejemplo n.º 44
0
def startup():

    settings = getSettings()

    if settings['launchWindowAtStartup'] == True:
        cmd = 'import Tapp.Maya.window as win;'
        cmd += 'win.show()'
        cmds.evalDeferred(cmd)
Ejemplo n.º 45
0
def start(Menu=True, MayaUIHooks=True, MayaOverloads=True, parentMenu='MayaWindow'):
  
    #Run the main setups. If you DON'T want the Red9Menu set 'Menu=False'
    #cmds.evalDeferred("Red9.setup.start(Menu=%s)" % Menu)
    cmds.evalDeferred("import Red9;Red9.setup.start(Menu=%s,MayaUIHooks=%s,MayaOverloads=%s,parentMenu='%s')" % (Menu,MayaUIHooks,MayaOverloads,parentMenu))
    #Import the core, not this is on LowPriority to make sure it
    #happens after the main setups have finished above
    cmds.evalDeferred("import Red9.core", lp=True)
Ejemplo n.º 46
0
	def move_anim_sequence_down(self, idx, *args):
		self._util.disable_undo()
		try:
			moved = self._animSequences.move_down(idx)
			if moved:
				cmds.evalDeferred(self._update_anim_sequences_ui)
		finally:
			self._util.enable_undo()
	def delete_selection_set(self, idx, *args):
		selected_objs = cmds.ls(selection=True)
		self._util.disable_undo()
		try:
			self._selectionSets.remove(idx)
			cmds.evalDeferred(self._update_selection_sets_ui)
		finally:
			self._util.select_obj(selected_objs)
			self._util.enable_undo()
Ejemplo n.º 48
0
	def delete_export_layer(self, idx, *args):
		selected_objs = cmds.ls(selection=True)
		self._util.disable_undo()
		try:
			self._exportLayers.remove(idx)
			cmds.evalDeferred(self._update_export_layers_ui)
		finally:
			self._util.select_obj(selected_objs)
			self._util.enable_undo()
Ejemplo n.º 49
0
 def deleteDock(self):
     obscured = mc.dockControl('shotDock', q = True, io = True)
     docked = mc.dockControl('shotDock', q = True, fl = True)
     if obscured and not docked:
         try:
             mc.evalDeferred("mc.deleteUI('shotDock')")
             print "Cleared Dock"
         except:
             pass            
Ejemplo n.º 50
0
    def sendToQueue(self, function, priority=1, id="default"):            

        if priority not in self.queue:      self.queue[priority] = {}
        if id not in self.queue[priority]:  self.queue[priority][id] = []            
        self.queue[priority][id].append(function) 
            
        
        if not self.running: 
            self.running = True
            cmds.evalDeferred(self.runQueue)
Ejemplo n.º 51
0
 def __execute_deferred(self):
     """
     Execute the callback deferred to avoid
     potential problems with the command resulting
     in the menu being deleted, e.g. if the context
     changes resulting in an engine restart! - this
     was causing a segmentation fault crash on Linux
     """
     cb = lambda: self.__exception_trap_callback_wrapper(self.callback)
     cmds.evalDeferred(cb)
Ejemplo n.º 52
0
def group(objs=None):
    '''
    groups the selected objects but keeps the position in hierarchy and selection alive
    '''
    objs = getObjs(objs, tr=True)
    n = getOrder(objs[0])
    g = m.group()
    setOrder(g, n)
    m.select(m.listRelatives(g, children=True, type='transform'))
    m.evalDeferred("import maya.cmds as m;m.outlinerEditor('outlinerPanel1', edit=True, showSelected=True)")
Ejemplo n.º 53
0
def start(Menu=True, MayaUIHooks=True, MayaOverloads=True, parentMenu='MayaWindow'):
    '''
    <<<< Red9 Boot Entry call >>>>
    
    :param Menu: do we build the main Red9 menu
    :param MenuUIHooks: do we add all the additional menu hooks to the native Maya menus
    :param MayaOverloads: do we run the additional hacks to overload certain Maya base functions, allowing the menu hacks
    '''
    #Run the main setups. If you DON'T want the Red9Menu set 'Menu=False'
    cmds.evalDeferred("import Red9;Red9.setup.start(Menu=%s,MayaUIHooks=%s,MayaOverloads=%s,parentMenu='%s')" % (Menu,MayaUIHooks,MayaOverloads,parentMenu))
def channelbox_command_animCurve(box, menuItem, key, *args):
    with sysCmd.Undo(0):
        mel.eval("GraphEditor;")
        cmds.selectionConnection("graphEditor1FromOutliner", e=1, clear=1)
        # in case graph editor is open already, clear selection
        sel_attrs = channelBox_SelectedPlugs(box)
        if sel_attrs:
            for i in sel_attrs:
                cmds.evalDeferred(
                    "cmds.selectionConnection('graphEditor1FromOutliner', e = 1, select =\"" + i + "\")")
Ejemplo n.º 55
0
def deselectChannels():
    '''
    Deselect selected channels in the channelBox
    by clearing selection and then re-selecting
    '''
    
    if not getSelectedChannels():
        return
    sel = mc.ls(sl=True)
    mc.select(clear=True)
    mc.evalDeferred(partial(mc.select,sel))
Ejemplo n.º 56
0
def __reload_clients__():
    '''
    used in the main reload_Red9 call below to ensure that
    the reload sequence is correct for the MetaData registry
    '''
    for client in get_client_modules():
        try:
            path='Red9_ClientCore.%s' % client
            cmds.evalDeferred("import %s;%s._reload()" % (path,path), lp=True)  # Unresolved Import
            log.info('Reloaded Client : "%s"' % path)
        except:
            log.info('Client : "%s" : does not have a _reload func internally' % path)
Ejemplo n.º 57
0
	def add_character(self, namespace, *args):
		selected_objs = cmds.ls(selection=True)
		self._util.disable_undo()
		try:
			active = False
			character = self._characters.add(namespace, active)

			cmds.evalDeferred(self._update_characters_ui)

			return character
		finally:
			self._util.select_obj(selected_objs)
			self._util.enable_undo()