def _init_tool():
    if not cmds.contextInfo(TOOLS.EDIT, exists=True):
        cmds.tcMotionPathEditContext(TOOLS.EDIT)
    if not cmds.contextInfo(TOOLS.DRAW, exists=True):
        cmds.tcMotionPathDrawContext(TOOLS.DRAW)

    _init_script_jobs()
Example #2
0
 def actuToolSettings(self):
     ctx = mc.currentCtx()
     ctxType = mc.contextInfo(ctx, c=True)
     # if self.wg_moveSettings.isVisible() or self.wg_rotateSettings.isVisible() or self.wg_scaleSettings.isVisible() or self.wg_nullSettings.isVisible():
     if ctxType == "manipMove":
         self.setIconTool("manipMove")
         mc.frameLayout(self.fl_tool, edit=True, label="Move Settings")
         mc.iconTextRadioButton(self.bt_tweakSelStyle, edit=True, enable=True)
         # self.wg_rotateSettings.setVisible(False)
         # self.wg_scaleSettings.setVisible(False)
         # self.wg_nullSettings.setVisible(False)
         # self.wg_moveSettings.setVisible(True)
         # self.initMoveSettings()
     if ctxType == "manipRotate":
         self.setIconTool("manipRotate")
         mc.frameLayout(self.fl_tool, edit=True, label="Rotate Settings")
         mc.iconTextRadioButton(self.bt_tweakSelStyle, edit=True, enable=True)
         # self.wg_moveSettings.setVisible(False)
         # self.wg_scaleSettings.setVisible(False)
         # self.wg_nullSettings.setVisible(False)
         # self.wg_rotateSettings.setVisible(True)
         # self.initRotateSettings()
     if ctxType == "manipScale":
         self.setIconTool("manipScale")
         mc.frameLayout(self.fl_tool, edit=True, label="Scale Settings")
         mc.iconTextRadioButton(self.bt_tweakSelStyle, edit=True, enable=True)
         # self.wg_moveSettings.setVisible(False)
         # self.wg_rotateSettings.setVisible(False)
         # self.wg_nullSettings.setVisible(False)
         # self.wg_scaleSettings.setVisible(True)
         # self.initScaleSettings()
     if ctxType == "selectTool":
         self.setIconTool("selectTool")
         mc.frameLayout(self.fl_tool, edit=True, label="Tool Settings")
         mc.iconTextRadioButton(self.bt_tweakSelStyle, edit=True, enable=False)
Example #3
0
def _disable():
    _delete_script_jobs()

    for t in TOOLS.all():
        if cmds.currentCtx() == t:
            cmds.setToolTo('selectSuperContext')
        if cmds.contextInfo(t, exists=True):
            cmds.deleteUI(t)

    tc_motion_path_widget.set_active_tool('selectSuperContext')
Example #4
0
    def press_selected(self, menu, **mod):
        self._is_open_menu = False
        self._current_node = self.EMPTY_NODE
        self._cleanMenu()
        context = cmds.currentCtx()     # context marking menu
        cmds.contextInfo(context, title=True)
        cmds.popupMenu('MMtoKey_MMB', b=2, aob=True, mm=True, p=self._getPanel(), pmc=self._openMarkingMenu, **mod)
        if context in self.DATA_TOOL and self.DATA_TOOL[context].menu:
            mel.eval('source "menu_%s";' % self.DATA_TOOL[context].menu)
        elif self.pref_special_1:
            mel.eval('source "menu_%s";' % self.pref_special_1)

        # common menu
        cmds.popupMenu('MMtoKey_LMB', b=1, aob=True, mm=True, p=self._getPanel(), pmc=self._openMarkingMenu, **mod)
        if menu:
            mel.eval('source "menu_%s";' % menu)
            return
        self._current_node = self._findNode()
        if self._current_node.menu:
            mel.eval('source "menu_%s";' % self._current_node.menu)
        elif self.pref_special_0:
            mel.eval('source "menu_%s";' % self.pref_special_0)
Example #5
0
    def set_context_index(self, context_string):

        index = 1
        context_condition = True
        while context_condition is True:
            context_name = context_string + str(index)
            context_condition = cmds.contextInfo(context_name, exists=True)
            index += 1

            if index > 100:
                print 'infinite loop'
                return

        return context_name
Example #6
0
def run():
    if cmds.contextInfo(ZOOM_TRANSLATE, exists=True):
        cmds.setToolTo(ZOOM_TRANSLATE)
        return

    cmds.draggerContext(ZOOM_TRANSLATE,
                        pressCommand='zoom_translate.start_translate()',
                        dragCommand='zoom_translate.do_translate()',
                        releaseCommand='zoom_translate.end_translate()',
                        cursor='hand',
                        undoMode='step')

    # Put it as the y-key slot
    mel.eval('$gNonSacredTool = "{}";'.format(ZOOM_TRANSLATE))
    cmds.setToolTo(ZOOM_TRANSLATE)
Example #7
0
    def __init__(self, dock=False, rebuild=False, tab="vertex-space"):
        # checks
        if not mnpr_info.environment:
            mnpr_info.loadRenderer()
        if not cmds.contextInfo("artAttrColorPerVertexContext", ex=True):
            mel.eval("PaintVertexColorToolOptions;")
            cmds.evalDeferred('maya.mel.eval("SelectTool;")')

        # initialize
        self.tab = tab
        super(MNPR_FX_UI,
              self).__init__(self.windowTitle,
                             dock=dock,
                             rebuild=rebuild,
                             brand=mnpr_info.brand,
                             tooltip="Paint local stylization effects")
Example #8
0
 def _addNode(self):
     context = cmds.currentCtx()
     cmds.contextInfo(context, title=True)
     self._addNodeName(context)
Example #9
0
def mvgDeleteContext():
    import maya.cmds as cmds
    cmds.setToolTo('selectSuperContext')
    if cmds.contextInfo('mayaMVGTool1', exists=True):
        cmds.deleteUI('mayaMVGTool1', toolContext=True)
Example #10
0
 def setTool(*args):
     if not cmds.contextInfo("createJointContext1", ex=1):
         mel.eval('createJointContext createJointContext1')
     cmds.setToolTo("createJointContext1")
Example #11
0
    def eventFilter(self, obj, event):
        #try:
            if event.type() == event.Enter:
                obj.grabKeyboard()

            if event.type() == event.Leave:
                obj.releaseKeyboard()
    
            if event.type() == event.KeyRelease:
                ctx = cmds.currentCtx()
                currentTool = cmds.contextInfo(ctx, c=True)
                if currentTool != self.currentTool or event.key() == QtCore.Qt.Key_Escape:
                    self.pickedObjects = None
                    self._quit(obj)
                if event.key() == QtCore.Qt.Key_Enter:
                    self._quit(obj)

            if event.type() == event.MouseButtonPress:
                modifier = 0
                qMod = event.modifiers()
                if qMod == QtCore.Qt.ShiftModifier:
                    modifier = 1
                elif qMod == QtCore.Qt.ControlModifier:
                    modifier = 2
                elif qMod == QtCore.Qt.AltModifier:
                    modifier = 3

                if event.button() == Qt.MouseButton.RightButton:
                    # Escape condition
                    if self.pickedObjects.isEmpty():
                        self.pickedObjects = None
                    self._quit(obj)
                    return True

                else:
                    pickedName = None

                    # Outliner picking
                    if obj.metaObject().className() == "TpanelDagOutliner":
                        pickedName = cmds.hitTest(
                            obj.objectName(), event.x(), event.y())[0]

                    # Viewport picking
                    self.hit = cmds.dagObjectHit(mn="dummyMenu")
                    if self.hit is True:
                        popChild = cmds.popupMenu(
                            "dummyMenu", q=True, itemArray=True)
                        mItem = cmds.menuItem(popChild[0], q=True, l=True)
                        pickedName = mItem.replace("...", "")
                        cmds.popupMenu("dummyMenu", edit=True,
                                       deleteAllItems=True)

                    if pickedName is not None:
                        picked = om.MSelectionList()
                        picked.add(pickedName)
                        node = self._getLastDagNode(picked)
                        if not picked.isEmpty() and (len(self.typeFilter) == 0 or node.apiTypeStr() in self.typeFilter):
                            self.pickedObjects.merge(picked)
                            self.hilite(picked)
                            views = omui.M3dView
                            for i in range(views.numberOf3dViews()):
                                view = views.get3dView(i)
                                view.refresh()
                            if event.button() == Qt.MouseButton.LeftButton:
                                self.buttonPressed.append(1)
                            elif event.button() == Qt.MouseButton.MidButton:
                                self.buttonPressed.append(2)
                            self.modifierPressed.append(modifier)

                        return True
                    if obj.metaObject().className() == "TpanelDagOutliner":
                        return False
                    return True
                #return False
            #if event.type() == event.MouseButtonRelease:
                #if self.hit == False:
                #return False

            """except:
            self.pickedObjects = None
            obj.releaseKeyboard()
            self.unHilite()
            self.event.quit()
            return False"""

            return False
Example #12
0
 def _addNode(self):
     context = cmds.currentCtx()
     cmds.contextInfo(context, title=True)
     self._addNodeName(context)
Example #13
0
def setCamRotatePivots(oObjects=[]):
    global RitalinEnabled
    global RitalinHonorInfluenceJoints
    Units = cmds.currentUnit(query=True, linear=True)

    #Unfortunately Maya is too stupid to set the rotion pivot according to the currently set unit type in the scene.
    #It always uses cm internally, so we need a Unit Multiplier (UM) depending on the active unit type for correction in case units are not set to cm

    if Units == "mm":
        UM = 0.1
    elif Units == "cm":
        UM = 1.0
    elif Units == "m":
        UM = 100.0
    elif Units == "in":
        UM = 2.54
    elif Units == "ft":
        UM = 30.48
    elif Units == "yd":
        UM = 91.44

    Cams = cmds.ls(dag=true, cameras=True)
    if RitalinEnabled == True:
        CheckPaintTool = True
        Continue = False
        ComputeCenterAlreadyDone = False

        if len(oObjects) == 0:
            #print("No Objects given to compute BB for, using current selection instead!")
            Selec = cmds.ls(selection=True)
        else:
            Selec = oObjects
            CheckPaintTool = False  #In case there are objects given to compute BB center for we don't need to check for the paint tool, we already know what to compute BB for
        if len(Selec) > 0:  #We have objects to work with?
            X = 0.0
            Y = 0.0
            Z = 0.0
            if CheckPaintTool:
                #print ("Checking paint tool...")
                #Let's find out if we are in skin weights paint mode
                currCtx = cmds.currentCtx()
                #print ("Current Context is: " + str(currCtx))
                currTool = ""
                try:  #contextInfo operations are buggy in Maya 2011, we need to try.. :-(
                    currTool = cmds.contextInfo(currCtx, t=True)
                    #print ("Current Tool is: " + str(currTool))
                except:
                    #print ("Fail")
                    pass

                if RitalinHonorInfluenceJoints == True:  #In case we are painting skin weights we can ignore everything and just concentrate on the currently active skin joint
                    if currTool == "artAttrSkin" or currTool == "Paint Skin Weights Tool":
                        whichTool = cmds.artAttrSkinPaintCtx(currCtx,
                                                             query=True,
                                                             whichTool=True)
                        #print ("Tool name is: " + str(whichTool))
                        if whichTool == "skinWeights":  #Yes, we are in skin paint weights mode
                            #print ("We are in paint skin weights mode...")
                            influenceJoint = ""
                            #Find the currently active joint for which weights are being painted
                            influenceJoint = cmds.artAttrSkinPaintCtx(
                                currCtx, query=true, influence=true)
                            #print("Currently painting joint: " + str(influenceJoint))
                            if influenceJoint != "":
                                influenceJoint += (".rotatePivot")
                                BB = cmds.exactWorldBoundingBox(influenceJoint)
                                X = ((BB[0] + BB[3]) / 2)
                                Y = ((BB[1] + BB[4]) / 2)
                                Z = ((BB[2] + BB[5]) / 2)
                                ComputeCenterAlreadyDone = True
                                Continue = True

            if ComputeCenterAlreadyDone == False:  #Standard computation in case we are not in paintSkinWeights mode or don't care if we are
                Joints = []
                stdObjects = []

                specialTransformTypes = [
                    "selectHandle", "rotatePivot", "scalePivot", "Axis"
                ]
                for o in Selec:
                    if (cmds.nodeType(o) == "joint"):
                        #Maya can't compute BB of joints (API bug?) so we have to work around this by dealing with joint's rotatePivots instead
                        #print ("Selected node is of type joint")
                        isSpecialType = False
                        for Type in specialTransformTypes:
                            if o.find(Type) > -1:
                                #print ("Selected node is of a special Transform Type")
                                stdObjects.append(o)
                                isSpecialType = True
                                break

                        if isSpecialType == False:
                            #print ("Selected node is not of special TransformType, appending directly")
                            stdObjects.append(o + ".rotatePivot")

                    elif (cmds.nodeType(o) == "transform"):
                        #Maya does not take shape nodes of selected objects into account automatically, we must supply such nodes directly
                        #to compute BB of e.g. skinned objects or objects whose pivots have been moved far from their geometric centers
                        #print ("Selected node is of type transform")
                        Shapes = (
                            cmds.ls(o,
                                    dagObjects=True,
                                    shapes=True,
                                    noIntermediate=True)
                        )  #Lets get all the shape nodes associated with the transform
                        if len(Shapes) > 0:
                            for shp in Shapes:
                                #print ("Shape is of type " + cmds.nodeType(shp))
                                #print ("Shape name: " + shp)
                                shpName = str(shp)
                                stdObjects.append(shpName)
                        else:  #We have a transform without a shape?
                            stdObjects.append(o)

                    else:
                        #print ("Node must be a subcomponent")
                        stdObjects.append(o)

                if len(stdObjects) > 0:
                    BB = cmds.exactWorldBoundingBox(
                        stdObjects)  #Do standard BB computation
                    X = ((BB[0] + BB[3]) / 2)
                    Y = ((BB[1] + BB[4]) / 2)
                    Z = ((BB[2] + BB[5]) / 2)
                    Continue = True

        #Finally let'S do the actual tumble pivot setting on the cameras
        if Continue == True:
            cmds.tumbleCtx(
                "tumbleContext", edit=True, localTumble=0
            )  #Set the tumble tool to honor the cameras tumble pivot
            X = X * UM
            Y = Y * UM
            Z = Z * UM
            for cam in Cams:
                try:
                    #finally set the tumble pivot of the camera to the coordinates we have calculated before
                    cmds.setAttr(cam + ".tumblePivot", X, Y, Z)
                except:
                    Warning("Ritalin: Setting camera tumble pivot on " + cam +
                            "failed!")
Example #14
0
def mvgDeleteContext():
    import maya.cmds as cmds
    cmds.setToolTo('selectSuperContext')
    if cmds.contextInfo('mayaMVGTool1', exists=True):
        cmds.deleteUI('mayaMVGTool1', toolContext=True)
Example #15
0
def mvgCreateContext():
    import maya.cmds as cmds
    if cmds.contextInfo('mayaMVGTool1', exists=True):
        cmds.deleteUI('mayaMVGTool1', toolContext=True)
    cmds.mayaMVGTool('mayaMVGTool1')
Example #16
0
 def setTool( *args ):
     if not cmds.contextInfo( "createJointContext1", ex=1 ):
         mel.eval( 'createJointContext createJointContext1' )
     cmds.setToolTo( "createJointContext1" )
Example #17
0
def pickObject(leftMessage=None, middleMessage=None, buttonPressed=[], modifierPressed=[], filters=[]):
    """
    Form a complex number.

    Keyword arguments:
    leftMessage     --  Status bar message for the left mouse button
    middleMessage   --  Status bar message for the middle mouse button
    buttonPressed   --  Returns the mouse button clicked by the user.
                        Possible Values:
                            - 0: Right mouse button (or the Esc key), which means the user aborted the picking session
                            - 1: Left mouse button
                            - 2: Middle mouse button
    modifierPressed --  Returns the modifier key pressed by the user.
                        Possible Values:
                            - 0: None
                            - 1: Shift modifier key
                            - 2: Ctrl modifier key
                            - 3: Shift-Ctrl modifier key
    filter          --  a list of MFn.Type as strings. 
                        ie: ["kMesh", "kNurbsCurve", "kNurbsSurface", "kLocator", "kJoint"]

    return a MSelectionList, or None if nothing picked or escaped
    """

    # Init
    views = omui.M3dView
    viewCount = views.numberOf3dViews()
    outlinerPanels = cmds.getPanel(typ='outlinerPanel')
    ctx = cmds.currentCtx()
    currentTool = cmds.contextInfo(ctx, c=True)
    loop = QEventLoop()
    eventFilter = MouseEventFilter(loop, currentTool, filters)

    # Add the eventFilter to all the viewports
    widgets = []
    for i in range(viewCount):
        view = views.get3dView(i)
        widget_ptr = view.widget()
        widget = wrapInstance(long(widget_ptr), QWidget)
        widget.setCursor(QCursor(Qt.PointingHandCursor))
        widget.installEventFilter(eventFilter)
        widgets.append(widget)

    # Add the eventFilter to all the outliners
    for panel in outlinerPanels:
        ptr = mui.MQtUtil.findControl(panel)
        if ptr is not None:
            outPanel = wrapInstance(long(ptr), QObject)
            regex = QRegExp("outlinerPanel.*")
            outliners = outPanel.findChildren(QtGui.QWidget, regex)
            for outliner in outliners:
                if outliner.metaObject().className() == "TpanelDagOutliner":
                    outliner.installEventFilter(eventFilter)
                    widgets.append(outliner)

    # Add the help messages
    ptr = mui.MQtUtil.findControl("helpLine1")
    helpLine = wrapInstance(long(ptr), QStatusBar)
    lMessage = QLabel("L: " + leftMessage)
    lMessage.setMargin(helpLine.width() / 10)
    helpLine.addPermanentWidget(lMessage)
    mMessage = QLabel("M: " + middleMessage)
    mMessage.setMargin(helpLine.width() / 10)
    helpLine.addPermanentWidget(mMessage)
    rMessage = QLabel(" R: Exit")
    rMessage.setMargin(helpLine.width() / 10)
    helpLine.addPermanentWidget(rMessage)

    loop.exec_()

    # Get Outputs
    picked = eventFilter.pickedObjects
    buttonPressed.extend(eventFilter.buttonPressed)
    modifierPressed.extend(eventFilter.modifierPressed)

    # Cleanup
    for widget in widgets:
        widget.unsetCursor()
        widget.removeEventFilter(eventFilter)
        # widget.releaseKeyboard()
    eventFilter = None
    if cmds.popupMenu("dummyMenu", exists=True):
        cmds.deleteUI("dummyMenu")
    helpLine.removeWidget(lMessage)
    helpLine.removeWidget(mMessage)
    helpLine.removeWidget(rMessage)

    return picked
Example #18
0
def setTool_curveEditBrush(evt=0):

    import maya.cmds as cmds
    import maya.mel as mel

    if not cmds.pluginInfo("sgTools", q=1, l=1):
        cmds.loadPlugin('sgTools')

    melScript = '''
    proc int isGreasePencilContext()
    //
    //    Description:
    //        Returns true if this is Grease Pencil context.
    //
    {
        string $tc = currentToolClass();
        return ($tc == "greasePencil");
    }
    
    
    global proc artActivateScreenSlider(
        string $sliderName
    )
    //
    //    Description:
    //        Global procs for activating screen sliders
    //        - sets the flag to activate them.
    //
    {
        // New Artisan Tools.
        if ( isArtisanCtx() ) {
            string $artisanCmd = artisanCommand();
            if( $sliderName == "upper_radius" ) {
                artBaseCtx -e -dragSlider "radius" `currentCtx`;
            } else if( $sliderName == "lower_radius" ) {
                artBaseCtx -e -dragSlider "lowradius" `currentCtx`;
            } else if( $sliderName == "opacity" ) {
                artBaseCtx -e -dragSlider "opacity" `currentCtx`;
            } else if( $sliderName == "value" ) {
                artBaseCtx -e -dragSlider "value" `currentCtx`;
            } else if( $sliderName == "stamp_depth" ) {
                artBaseCtx -e -dragSlider "depth" `currentCtx`;
            } else if( $sliderName == "displacement" ) {
                artBaseCtx -e -dragSlider "displacement" `currentCtx`;
            } else if( $sliderName == "uv_vector" ) {
                artBaseCtx -e -dragSlider "uvvector" `currentCtx`;
            }
        }
        else if ( isGreasePencilContext() )
        {
            if( $sliderName == "upper_radius" )
            {
                // Map B to radius
                artBaseCtx -e -dragSlider "radius" greasePencilContext;
            }
            else if( $sliderName == "displacement" )
            {
                // Map m to opacity rather than value but not for the eraser
                // as this has no effect
                if ( 4 != `greasePencilCtx -query -greasePencilType greasePencilContext` )
                {
                    artBaseCtx -e -dragSlider "opacity" greasePencilContext;
                }
            }
        }
        // UV Smudge Tool
        else if ( isSmudgeCtx() ) {
            texSmudgeUVContext -edit -dragSlider "radius" texSmudgeUVCtx;
        }
        // Soft Mod
        else if ( size( getActiveSoftMod() ) > 0 )
        {
            string $ctx = `currentCtx`;
            if( `contextInfo -c $ctx` != "softMod" )
                $ctx = "softModContext";
            softModCtx -e -dragSlider "radius" $ctx;
        }
        // Paint Effects.
        else if ((`isTrue "MayaCreatorExists"`) && isDynPaint())
        {
            if( $sliderName == "displacement" ) {
                dynPaintResize("offset");
            } else if( $sliderName == "lower_radius" ) {
                dynPaintResize("width");
            } else {
                dynPaintResize("size");
            }
        }
        else if ($sliderName == "upper_radius")
        {
            // upper_radius is the "b" key by default.  We only want to use that one
            // for soft select.  The "n" and "m" keys can also come in here so we want
            // to filter those out.
            global string $gSoftSelectOptionsCtx;
            softSelectOptionsCtx -edit -buttonDown $gSoftSelectOptionsCtx;
            if( `currentCtx` == "sgCurveEditBrushContext1" )
            {
                sgCurveEditBrushContext -e -radiusEditOn 1 sgCurveEditBrushContext1;
            }
        }
    }
    
    global proc artDeactivateScreenSlider()
    //
    //    Description:
    //        Global procs for deactivating screen sliders - sets the flag to
    //        deactivate them.
    //
    {
        // New Artisan Tools.
        if ( isArtisanCtx() ) {
            artBaseCtx -e -dragSlider "none" `currentCtx`;
        }
        else if ( isGreasePencilContext() )
        {
            artBaseCtx -e -dragSlider "none" greasePencilContext;
        }
        // UV Smudge
        else if ( isSmudgeCtx() ) {
            texSmudgeUVContext -e -dragSlider "none" texSmudgeUVCtx;
        }
        // Soft Mod
        else if ( size( getActiveSoftMod() ) > 0 )
        {
            string $ctx = `currentCtx`;
            if( `contextInfo -c $ctx` != "softMod" )
                $ctx = "softModContext";
            softModCtx -e -dragSlider "none" $ctx;
        }
        // Paint Effects.
        else if (`isTrue "MayaCreatorExists"` && isDynPaint())
        {
            dynPaintResize("none");
        }
        else
        {
            // We filter out the "n" and "m" keys in the activate call
            // but don't here because there isn't a slider name passed
            // in for deactivate.  To soft select context is smart
            // enough to know that it didn't start and edit so we are
            // ok to just call this in case we did.
            global string $gSoftSelectOptionsCtx;
            softSelectOptionsCtx -edit -buttonUp $gSoftSelectOptionsCtx;
        }
        if( `currentCtx` == "sgCurveEditBrushContext1" )
        {
            sgCurveEditBrushContext -e -radiusEditOn 0 sgCurveEditBrushContext1;
        }
    }
    
    global proc sgCurveEditBrush_contextProperties()
    {
    }
    
    global proc sgCurveEditBrush_contextValues( string $context )
    {
    }
    '''

    mel.eval(melScript)
    if not cmds.contextInfo("sgCurveEditBrushContext1", ex=1):
        mel.eval('sgCurveEditBrushContext sgCurveEditBrushContext1')
    cmds.setToolTo("sgCurveEditBrushContext1")
Example #19
0
def setCamRotatePivots(oObjects = []):
	global RitalinEnabled
	global RitalinHonorInfluenceJoints
	Units = cmds.currentUnit(query = True, linear = True)

	#Unfortunately Maya is too stupid to set the rotion pivot according to the currently set unit type in the scene. 
	#It always uses cm internally, so we need a Unit Multiplier (UM) depending on the active unit type for correction in case units are not set to cm

	if Units == "mm":
		UM = 0.1
	elif Units == "cm":
		UM = 1.0
	elif Units == "m":
		UM = 100.0
	elif Units == "in":
		UM = 2.54
	elif Units == "ft":
		UM = 30.48
	elif Units == "yd":
		UM = 91.44

	Cams = cmds.ls( dag = true, cameras = True )
	if RitalinEnabled == True:
		CheckPaintTool = True
		Continue = False
		ComputeCenterAlreadyDone = False
		
		if len(oObjects) == 0:
			#print("No Objects given to compute BB for, using current selection instead!")
			Selec = cmds.ls( selection = True )
		else:
			Selec = oObjects
			CheckPaintTool = False #In case there are objects given to compute BB center for we don't need to check for the paint tool, we already know what to compute BB for
		if len(Selec) > 0: #We have objects to work with?
			X = 0.0; Y = 0.0; Z = 0.0
			if CheckPaintTool:
				#print ("Checking paint tool...")
				#Let's find out if we are in skin weights paint mode
				currCtx = cmds.currentCtx(); 
				#print ("Current Context is: " + str(currCtx))
				currTool = ""
				try: #contextInfo operations are buggy in Maya 2011, we need to try.. :-(
					currTool = cmds.contextInfo (currCtx, t = True);
					#print ("Current Tool is: " + str(currTool))
				except: 
					#print ("Fail")
					pass
				
				if RitalinHonorInfluenceJoints == True: #In case we are painting skin weights we can ignore everything and just concentrate on the currently active skin joint
					if currTool == "artAttrSkin" or currTool == "Paint Skin Weights Tool":
						whichTool = cmds.artAttrSkinPaintCtx (currCtx, query = True, whichTool = True)
						#print ("Tool name is: " + str(whichTool))
						if whichTool == "skinWeights": #Yes, we are in skin paint weights mode
							#print ("We are in paint skin weights mode...")
							influenceJoint = ""
							#Find the currently active joint for which weights are being painted
							influenceJoint = cmds.artAttrSkinPaintCtx  (currCtx, query = true, influence = true) 
							#print("Currently painting joint: " + str(influenceJoint))
							if influenceJoint != "":
								influenceJoint += (".rotatePivot")
								BB = cmds.exactWorldBoundingBox (influenceJoint)
								X = ((BB[0] + BB[3])/2)
								Y = ((BB[1] + BB[4])/2)
								Z = ((BB[2] + BB[5])/2)
								ComputeCenterAlreadyDone = True
								Continue = True			
			
			if ComputeCenterAlreadyDone == False:  #Standard computation in case we are not in paintSkinWeights mode or don't care if we are
				Joints = []
				stdObjects = []
				
				specialTransformTypes = ["selectHandle", "rotatePivot", "scalePivot", "Axis"]
				for o in Selec: 						
					if (cmds.nodeType (o) == "joint"): 
						#Maya can't compute BB of joints (API bug?) so we have to work around this by dealing with joint's rotatePivots instead
						#print ("Selected node is of type joint")
						isSpecialType = False
						for Type in specialTransformTypes:
							if o.find (Type) > -1:
								#print ("Selected node is of a special Transform Type")
								stdObjects.append(o)
								isSpecialType = True
								break
							
						if isSpecialType == False:
							#print ("Selected node is not of special TransformType, appending directly")
							stdObjects.append(o + ".rotatePivot")
							
					
					elif (cmds.nodeType (o) == "transform"):
						#Maya does not take shape nodes of selected objects into account automatically, we must supply such nodes directly
						#to compute BB of e.g. skinned objects or objects whose pivots have been moved far from their geometric centers
						#print ("Selected node is of type transform")
						Shapes = (cmds.ls(o, dagObjects = True, shapes = True, noIntermediate = True)) #Lets get all the shape nodes associated with the transform
						if len(Shapes) > 0:
							for shp in Shapes:
								#print ("Shape is of type " + cmds.nodeType(shp))
								#print ("Shape name: " + shp)
								shpName = str(shp)
								stdObjects.append(shpName)
						else: #We have a transform without a shape?
							stdObjects.append(o)
					
					else: 
						#print ("Node must be a subcomponent")
						stdObjects.append(o)

				if len(stdObjects) > 0:
					BB = cmds.exactWorldBoundingBox (stdObjects) #Do standard BB computation 
					X = ((BB[0] + BB[3])/2)
					Y = ((BB[1] + BB[4])/2)
					Z = ((BB[2] + BB[5])/2)
					Continue = True	
		
				
		#Finally let'S do the actual tumble pivot setting on the cameras
		if Continue == True : 
			cmds.tumbleCtx ("tumbleContext", edit = True, localTumble = 0) #Set the tumble tool to honor the cameras tumble pivot
			X = X * UM
			Y = Y * UM
			Z = Z * UM
			for cam in Cams:
				try:
					#finally set the tumble pivot of the camera to the coordinates we have calculated before
					cmds.setAttr (cam + ".tumblePivot", X, Y, Z)
				except: 
					Warning("Ritalin: Setting camera tumble pivot on " + cam + "failed!")
Example #20
0
def pickObject(leftMessage=None,
               middleMessage=None,
               buttonPressed=[],
               modifierPressed=[],
               filters=[]):
    """
    Form a complex number.

    Keyword arguments:
    leftMessage     --  Status bar message for the left mouse button
    middleMessage   --  Status bar message for the middle mouse button
    buttonPressed   --  Returns the mouse button clicked by the user.
                        Possible Values:
                            - 0: Right mouse button (or the Esc key), which means the user aborted the picking session
                            - 1: Left mouse button
                            - 2: Middle mouse button
    modifierPressed --  Returns the modifier key pressed by the user.
                        Possible Values:
                            - 0: None
                            - 1: Shift modifier key
                            - 2: Ctrl modifier key
                            - 3: Shift-Ctrl modifier key
    filter          --  a list of MFn.Type as strings. 
                        ie: ["kMesh", "kNurbsCurve", "kNurbsSurface", "kLocator", "kJoint"]

    return a MSelectionList, or None if nothing picked or escaped
    """

    # Init
    views = omui.M3dView
    viewCount = views.numberOf3dViews()
    outlinerPanels = cmds.getPanel(typ='outlinerPanel')
    ctx = cmds.currentCtx()
    currentTool = cmds.contextInfo(ctx, c=True)
    loop = QEventLoop()
    eventFilter = MouseEventFilter(loop, currentTool, filters)

    # Add the eventFilter to all the viewports
    widgets = []
    for i in range(viewCount):
        view = views.get3dView(i)
        widget_ptr = view.widget()
        widget = wrapInstance(long(widget_ptr), QWidget)
        widget.setCursor(QCursor(Qt.PointingHandCursor))
        widget.installEventFilter(eventFilter)
        widgets.append(widget)

    # Add the eventFilter to all the outliners
    for panel in outlinerPanels:
        ptr = mui.MQtUtil.findControl(panel)
        if ptr is not None:
            outPanel = wrapInstance(long(ptr), QObject)
            regex = QRegExp("outlinerPanel.*")
            outliners = outPanel.findChildren(QtGui.QWidget, regex)
            for outliner in outliners:
                if outliner.metaObject().className() == "TpanelDagOutliner":
                    outliner.installEventFilter(eventFilter)
                    widgets.append(outliner)

    # Add the help messages
    ptr = mui.MQtUtil.findControl("helpLine1")
    helpLine = wrapInstance(long(ptr), QStatusBar)
    lMessage = QLabel("L: " + leftMessage)
    lMessage.setMargin(helpLine.width() / 10)
    helpLine.addPermanentWidget(lMessage)
    mMessage = QLabel("M: " + middleMessage)
    mMessage.setMargin(helpLine.width() / 10)
    helpLine.addPermanentWidget(mMessage)
    rMessage = QLabel(" R: Exit")
    rMessage.setMargin(helpLine.width() / 10)
    helpLine.addPermanentWidget(rMessage)

    loop.exec_()

    # Get Outputs
    picked = eventFilter.pickedObjects
    buttonPressed.extend(eventFilter.buttonPressed)
    modifierPressed.extend(eventFilter.modifierPressed)

    # Cleanup
    for widget in widgets:
        widget.unsetCursor()
        widget.removeEventFilter(eventFilter)
        # widget.releaseKeyboard()
    eventFilter = None
    if cmds.popupMenu("dummyMenu", exists=True):
        cmds.deleteUI("dummyMenu")
    helpLine.removeWidget(lMessage)
    helpLine.removeWidget(mMessage)
    helpLine.removeWidget(rMessage)

    return picked
Example #21
0
def setTool_curveEditBrush( evt=0 ):
    
    import maya.cmds as cmds
    import maya.mel as mel
    
    appendPluginPath()
    if not cmds.pluginInfo( "sgTools", q=1, l=1 ):
        cmds.loadPlugin( 'sgTools' )
    
    melScript = '''
    proc int isGreasePencilContext()
    //
    //    Description:
    //        Returns true if this is Grease Pencil context.
    //
    {
        string $tc = currentToolClass();
        return ($tc == "greasePencil");
    }
    
    
    global proc artActivateScreenSlider(
        string $sliderName
    )
    //
    //    Description:
    //        Global procs for activating screen sliders
    //        - sets the flag to activate them.
    //
    {
        // New Artisan Tools.
        if ( isArtisanCtx() ) {
            string $artisanCmd = artisanCommand();
            if( $sliderName == "upper_radius" ) {
                artBaseCtx -e -dragSlider "radius" `currentCtx`;
            } else if( $sliderName == "lower_radius" ) {
                artBaseCtx -e -dragSlider "lowradius" `currentCtx`;
            } else if( $sliderName == "opacity" ) {
                artBaseCtx -e -dragSlider "opacity" `currentCtx`;
            } else if( $sliderName == "value" ) {
                artBaseCtx -e -dragSlider "value" `currentCtx`;
            } else if( $sliderName == "stamp_depth" ) {
                artBaseCtx -e -dragSlider "depth" `currentCtx`;
            } else if( $sliderName == "displacement" ) {
                artBaseCtx -e -dragSlider "displacement" `currentCtx`;
            } else if( $sliderName == "uv_vector" ) {
                artBaseCtx -e -dragSlider "uvvector" `currentCtx`;
            }
        }
        else if ( isGreasePencilContext() )
        {
            if( $sliderName == "upper_radius" )
            {
                // Map B to radius
                artBaseCtx -e -dragSlider "radius" greasePencilContext;
            }
            else if( $sliderName == "displacement" )
            {
                // Map m to opacity rather than value but not for the eraser
                // as this has no effect
                if ( 4 != `greasePencilCtx -query -greasePencilType greasePencilContext` )
                {
                    artBaseCtx -e -dragSlider "opacity" greasePencilContext;
                }
            }
        }
        // UV Smudge Tool
        else if ( isSmudgeCtx() ) {
            texSmudgeUVContext -edit -dragSlider "radius" texSmudgeUVCtx;
        }
        // Soft Mod
        else if ( size( getActiveSoftMod() ) > 0 )
        {
            string $ctx = `currentCtx`;
            if( `contextInfo -c $ctx` != "softMod" )
                $ctx = "softModContext";
            softModCtx -e -dragSlider "radius" $ctx;
        }
        // Paint Effects.
        else if ((`isTrue "MayaCreatorExists"`) && isDynPaint())
        {
            if( $sliderName == "displacement" ) {
                dynPaintResize("offset");
            } else if( $sliderName == "lower_radius" ) {
                dynPaintResize("width");
            } else {
                dynPaintResize("size");
            }
        }
        else if ($sliderName == "upper_radius")
        {
            // upper_radius is the "b" key by default.  We only want to use that one
            // for soft select.  The "n" and "m" keys can also come in here so we want
            // to filter those out.
            global string $gSoftSelectOptionsCtx;
            softSelectOptionsCtx -edit -buttonDown $gSoftSelectOptionsCtx;
            if( `currentCtx` == "sgCurveEditBrushContext1" )
            {
                sgCurveEditBrushContext -e -radiusEditOn 1 sgCurveEditBrushContext1;
            }
        }
    }
    
    global proc artDeactivateScreenSlider()
    //
    //    Description:
    //        Global procs for deactivating screen sliders - sets the flag to
    //        deactivate them.
    //
    {
        // New Artisan Tools.
        if ( isArtisanCtx() ) {
            artBaseCtx -e -dragSlider "none" `currentCtx`;
        }
        else if ( isGreasePencilContext() )
        {
            artBaseCtx -e -dragSlider "none" greasePencilContext;
        }
        // UV Smudge
        else if ( isSmudgeCtx() ) {
            texSmudgeUVContext -e -dragSlider "none" texSmudgeUVCtx;
        }
        // Soft Mod
        else if ( size( getActiveSoftMod() ) > 0 )
        {
            string $ctx = `currentCtx`;
            if( `contextInfo -c $ctx` != "softMod" )
                $ctx = "softModContext";
            softModCtx -e -dragSlider "none" $ctx;
        }
        // Paint Effects.
        else if (`isTrue "MayaCreatorExists"` && isDynPaint())
        {
            dynPaintResize("none");
        }
        else
        {
            // We filter out the "n" and "m" keys in the activate call
            // but don't here because there isn't a slider name passed
            // in for deactivate.  To soft select context is smart
            // enough to know that it didn't start and edit so we are
            // ok to just call this in case we did.
            global string $gSoftSelectOptionsCtx;
            softSelectOptionsCtx -edit -buttonUp $gSoftSelectOptionsCtx;
        }
        if( `currentCtx` == "sgCurveEditBrushContext1" )
        {
            sgCurveEditBrushContext -e -radiusEditOn 0 sgCurveEditBrushContext1;
        }
    }
    
    global proc sgCurveEditBrush_contextProperties()
    {
    }
    
    global proc sgCurveEditBrush_contextValues( string $context )
    {
    }
    '''
    
    mel.eval( melScript )
    if not cmds.contextInfo( "sgCurveEditBrushContext1", ex=1 ):
        mel.eval( 'sgCurveEditBrushContext sgCurveEditBrushContext1' )
    cmds.setToolTo( "sgCurveEditBrushContext1" )
Example #22
0
    def eventFilter(self, obj, event):
        #try:
        if event.type() == event.Enter:
            obj.grabKeyboard()

        if event.type() == event.Leave:
            obj.releaseKeyboard()

        if event.type() == event.KeyRelease:
            ctx = cmds.currentCtx()
            currentTool = cmds.contextInfo(ctx, c=True)
            if currentTool != self.currentTool or event.key(
            ) == QtCore.Qt.Key_Escape:
                self.pickedObjects = None
                self._quit(obj)
            if event.key() == QtCore.Qt.Key_Enter:
                self._quit(obj)

        if event.type() == event.MouseButtonPress:
            modifier = 0
            qMod = event.modifiers()
            if qMod == QtCore.Qt.ShiftModifier:
                modifier = 1
            elif qMod == QtCore.Qt.ControlModifier:
                modifier = 2
            elif qMod == QtCore.Qt.AltModifier:
                modifier = 3

            if event.button() == Qt.MouseButton.RightButton:
                # Escape condition
                if self.pickedObjects.isEmpty():
                    self.pickedObjects = None
                self._quit(obj)
                return True

            else:
                pickedName = None

                # Outliner picking
                if obj.metaObject().className() == "TpanelDagOutliner":
                    pickedName = cmds.hitTest(obj.objectName(), event.x(),
                                              event.y())[0]

                # Viewport picking
                self.hit = cmds.dagObjectHit(mn="dummyMenu")
                if self.hit is True:
                    popChild = cmds.popupMenu("dummyMenu",
                                              q=True,
                                              itemArray=True)
                    mItem = cmds.menuItem(popChild[0], q=True, l=True)
                    pickedName = mItem.replace("...", "")
                    cmds.popupMenu("dummyMenu", edit=True, deleteAllItems=True)

                if pickedName is not None:
                    picked = om.MSelectionList()
                    picked.add(pickedName)
                    node = self._getLastDagNode(picked)
                    if not picked.isEmpty() and (len(self.typeFilter) == 0
                                                 or node.apiTypeStr()
                                                 in self.typeFilter):
                        self.pickedObjects.merge(picked)
                        self.hilite(picked)
                        views = omui.M3dView
                        for i in range(views.numberOf3dViews()):
                            view = views.get3dView(i)
                            view.refresh()
                        if event.button() == Qt.MouseButton.LeftButton:
                            self.buttonPressed.append(1)
                        elif event.button() == Qt.MouseButton.MidButton:
                            self.buttonPressed.append(2)
                        self.modifierPressed.append(modifier)

                    return True
                if obj.metaObject().className() == "TpanelDagOutliner":
                    return False
                return True
            #return False
        #if event.type() == event.MouseButtonRelease:
        #if self.hit == False:
        #return False
        """except:
            self.pickedObjects = None
            obj.releaseKeyboard()
            self.unHilite()
            self.event.quit()
            return False"""

        return False
Example #23
0
def getCurrentCtxName():
    ctx = cmds.currentCtx()
    className = ""
    if True == cmds.contextInfo(ctx, exists=True):
        className = cmds.contextInfo(ctx, c=True)
    return className
Example #24
0
def mvgCreateContext():
    import maya.cmds as cmds
    if cmds.contextInfo('mayaMVGTool1', exists=True):
        cmds.deleteUI('mayaMVGTool1', toolContext=True)
    cmds.mayaMVGTool('mayaMVGTool1')