示例#1
0
def _createMrLightShaderMenuItems(node):
    """
    Create node item marking menu items specific to mental ray light shader nodes
    """
    lightArray = cmds.listConnections(node,
                                      source=False,
                                      destination=True,
                                      type='light')
    if lightArray:
        selectObjString = maya.stringTable[
            'y_nodeEditorRendererMenus.kSelectObjectsIlluminated']
        frameObjString = maya.stringTable[
            'y_nodeEditorRendererMenus.kFrameObjectsIlluminated']

        for member in lightArray:

            def selectCB(light=member, *args):
                mel.eval('selectObjectsIlluminatedBy "%s"' % light)

            def frameCB(light=member, *args):
                mel.eval(
                    'selectObjectsIlluminatedBy "%s"; fitAllPanels -selected' %
                    light)

            selectObjStrFmt = cmds.format(selectObjString, stringArg=member)
            cmds.menuItem(label=selectObjStrFmt,
                          radialPosition='E',
                          c=selectCB)

            frameObjStrFmt = cmds.format(frameObjString, stringArg=member)
            cmds.menuItem(label=frameObjStrFmt, c=frameCB)

        cmds.menuItem(divider=True)
示例#2
0
def ProxyShapeFilePathRefresh(filePathAttr):
    # Function called from the MayaUsd Proxy Shape template when the refresh
    # button of the file path attribute custom control is clicked.
    #
    # Arguments:
    # - filePathAttr: string representing the file path attribute.
    #
    # Return Value:
    # - None
    #
    debugMessage('ProxyShapeFilePathRefresh(%s)' % filePathAttr)
    try:
        stageName, proxyStage = GetStageFromProxyShapeAttr(filePathAttr)

        # Is any layer in the layerstack dirty?
        # - If nothing is dirty, we simply reload.
        # - If any layer is dirty pop a confirmation dialog to reload.
        # Note: since we are file-backed, this will reload based on the file
        #       which could have changed on disk.
        if not IsProxyShapeLayerStackDirty(proxyStage):
            debugMessage('  No dirty layers, calling UsdStage.Reload()')
            proxyStage.Reload()
        else:
            kTitleFormat = getMayaUsdString("kDiscardStageEditsTitle")
            kMsgFormat = getMayaUsdString("kDiscardStageEditsReloadMsg")
            kYes = getMayaUsdString("kButtonYes")
            kNo = getMayaUsdString("kButtonNo")
            kTitle = cmds.format(kTitleFormat, stringArg=stageName)
            # Our title is a little long, and the confirmDialog command is not making the
            # dialog wide enough to show it all. So by telling the message string to not
            # word-wrap, the dialog is forced wider.
            filepath = cmds.getAttr(filePathAttr)
            if filepath:
                filename = os.path.basename(filepath)
                kMsg = "<p style='white-space:pre'>" + cmds.format(
                    kMsgFormat, stringArg=(filename, stageName))
                res = cmds.confirmDialog(title=kTitle,
                                         message=kMsg,
                                         messageAlign='left',
                                         button=[kYes, kNo],
                                         defaultButton=kYes,
                                         cancelButton=kNo,
                                         dismissString=kNo,
                                         icon='warning')
                if res == kYes:
                    debugMessage(
                        '  User confirmed reload action, calling UsdStage.Reload()'
                    )
                    proxyStage.Reload()
    except Exception as e:
        debugMessage('ProxyShapeFilePathRefresh() - Error: %s' % str(e))
        pass
def channelbox_command_break(box, menuItem, key, *args):
    with sysCmd.Undo():
        for plug in channelBox_SelectedPlugs(box):
            if cmds.connectionInfo(plug, isDestination=1):
                destination = cmds.connectionInfo(plug, getExactDestination=1)

                # when delete source conn from character, must remove from character set or set becomes inconsistent
                src_conn = cmds.listConnections(destination, s=1, d=0, type="character")
                if src_conn:
                    warn_msg = "Removed \'^1s\' from character \'^2s\'."
                    cmds.warning(cmds.format(warn_msg, s=(destination, src_conn[0])))
                    cmds.character(destination, e=1, rm=src_conn[0])

                # is tracking edits?
                import maya.api.OpenMaya as om
                obj = om.MSelectionList().add(destination).getDependNode(0)
                depend_fn = om.MFnDependencyNode(obj)
                tracking_edits = depend_fn.isTrackingEdits()
                del obj
                del depend_fn

                if tracking_edits:
                    src = cmds.connectionInfo(destination, sourceFromDestination=1)
                    cmds.disconnectAttr(src, destination)
                else:
                    cmds.delete(destination, icn=1)
示例#4
0
def _createPlace3dTextureMenuItems(node):
    """
    Create node item marking menu items specific to shader nodes
    """
    def fitCB(*args):
        mel.eval(
            'source "AEplace3dTextureTemplate.mel"; PSfitPlacementToGroup "%s";'
            % node)

    cmds.menuItem(
        label=maya.stringTable['y_nodeEditorMenus.kFitToGroupBoundingBox'],
        c=fitCB)

    selectionList = cmds.ls(selection=True)
    if len(selectionList) > 0:

        def parentCB(*args):
            cmds.parent(node, selectionList[0])

        parentPlacementString = cmds.format(
            maya.stringTable['y_nodeEditorMenus.kParentPlacement'],
            stringArg=selectionList[0])
        cmds.menuItem(label=parentPlacementString, c=parentCB)
    else:
        cmds.menuItem(
            label=maya.
            stringTable['y_nodeEditorMenus.kParentPlacementToSelection'],
            enable=False)

    cmds.menuItem(divider=True)
示例#5
0
def displayEditsOn(owner, textScrollList, filterWidget, failedEditsMenuItem, unappliedEditsMenuItem, nonRemovableEditsMenuItem):
	""" Query edits that are stored on the owner node and add
		them to the 'List Assembly Edits' UI

		owner			= assembly the edits are stored on
		textScrollList	= 'List Assembly Edits' list widget
		filterWidget	= 'List Assembly Edits' filter widget
		unappliedEdits	= list to gather all the unapplied edits, they will be
						  displayed at the very end of the textScrollList
		failedEditsMenuItem = 'List Assembly Edits' show failed edit menu item
		unappliedEditsMenuItem = 'List Assembly Edits' show unapplied edit menu item
		nonRemovableEditsMenuItem = 'List Assembly Edits' show non-removable edit menu item

	"""
	err = maya.stringTable['y_editUtils.kInvalidOwner' ]

	try:
		ownerNode = makeDependNode(owner)
	except:
		msg = cmds.format(err, stringArg=owner)
		print msg
		raise

	index = 1
	unappliedEdits = []
	it = OpenMaya.MItEdits(ownerNode)
	index = displayEditsWithIter(it, textScrollList, filterWidget, index, unappliedEdits, failedEditsMenuItem, unappliedEditsMenuItem, nonRemovableEditsMenuItem)
	displayUnappliedEdits(unappliedEdits, textScrollList, index)
示例#6
0
    def createUI(self):
        self._extensionsMenu = cmds.optionMenuGrp(
            ad2=2,
            label=maya.stringTable['y_inputSpaceRulesUI.kExtensionsMenuLabel'],
            changeCommand=self.onExtensionChange)

        # Fill in the extensions.
        for extension in FilePathRule._extensionsList:
            cmds.menuItem(label=extension)

        # Using the command, the user could select a file extension
        # which does not exist.
        try:
            cmds.optionMenuGrp(self._extensionsMenu,
                               edit=True,
                               value=self.extension)
        except RuntimeError, err:
            cmds.optionMenuGrp(self._extensionsMenu,
                               edit=True,
                               value=FilePathRule._extensionsList[0])
            err = maya.stringTable['y_inputSpaceRulesUI.kInvalidNode']
            msg = cmds.format(err,
                              stringArg=(self.extension,
                                         FilePathRule._extensionsList[0]))
            cmds.warning(msg)
 def shapeLidPlank(plank,scale1,scale2,scale3): #ScalesPlankEdges
     i = 0
     while (i < 2):
         selectCube = cmds.format('pCube^1s.e', stringArg=(plank))
         cmds.select("{0}[{1}]".format(selectCube,8), "{0}[{1}]".format(selectCube,11), "{0}[{1}]".format(selectCube,14), "{0}[{1}]".format(selectCube,17))
         cmds.scale(1, 1, scale1, relative = True)
         cmds.select("{0}[{1}]".format(selectCube,9), "{0}[{1}]".format(selectCube,12), "{0}[{1}]".format(selectCube,15), "{0}[{1}]".format(selectCube,18))
         cmds.scale(1, 1, scale2, relative = True)
         cmds.select("{0}[{1}]".format(selectCube,10), "{0}[{1}]".format(selectCube,13), "{0}[{1}]".format(selectCube,16), "{0}[{1}]".format(selectCube,19))
         cmds.scale(1, 1, scale3, relative = True)
         i = i+1
示例#8
0
def displayEditsThatAffect(target, textScrollList, filterWidget,
                           failedEditsMenuItem, unappliedEditsMenuItem,
                           nonRemovableEditsMenuItem):
    """ Query edits that affect nodes in the target assembly and
		add to 'List Assembly Edits' UI.

		Will list edits stored on any level in the hierarchy that
		affect nodes in 'target'. So if you have a hierarchy like this:

		A_AR
		  |_ B_AR
		    |_ C_AR
			  |_ nodeInAssemblyC

		displayEditsThatAffect(C) will list...
		1) Edits made from C.ma that affect nodeInAssemblyC
		2) Edits made from B.ma that affect nodeInAssemblyC
		3) Edits made from A.ma that affect nodeInAssemblyC

		target			= list edits that affect nodes in this assembly
		textScrollList	= 'List Assembly Edits' list widget
		filterWidget	= 'List Assembly Edits' filter widget
		failedEditsMenuItem = 'List Assembly Edits' show failed edit menu item
		unappliedEditsMenuItem = 'List Assembly Edits' show unapplied edit menu item
		nonRemovableEditsMenuItem = 'List Assembly Edits' show non-removable edit menu item
	"""

    err = maya.stringTable['y_editUtils.kInvalidTarget']
    try:
        targetNode = makeDependNode(target)
    except:
        msg = cmds.format(err, stringArg=target)
        print msg
        raise

    index = 1
    curOwner = targetNode
    unappliedEdits = []
    while not curOwner.isNull():
        it = OpenMaya.MItEdits(curOwner, targetNode)
        index = displayEditsWithIter(it, textScrollList, filterWidget, index,
                                     unappliedEdits, failedEditsMenuItem,
                                     unappliedEditsMenuItem,
                                     nonRemovableEditsMenuItem)

        # check if we have any edits that affect target
        # that are stored on a parent assembly
        assemblyFn = OpenMaya.MFnAssembly(curOwner)
        curOwner = assemblyFn.getParentAssembly()

    # display any unapplied edits at the end
    displayUnappliedEdits(unappliedEdits, textScrollList, index)
示例#9
0
    def disconnectNode(self):
        #print "disconnectNode"
        nodeType = cmds.nodeType(self.droppedNode)
        self.isDesiredNode(nodeType)
        cmds.disconnectAttr('%s.%s' % (self.droppedNode, self.sourceAttr),
                            '%s.%s' % (self.node, self.attr))
        self.menu.clear()
        self.setText(kNotConnected)
        self.setBlankStyle()

        message = cmds.format(kDisconnectedNodes,
                              stringArg=(self.droppedNode, self.node))
        command = 'evalDeferred \"TN_InViewMessage(\\"' + message + '\\", \\"Info\\")\"'
        mel.eval(command)
        if (len(self.postCmd) > 0):
            self.runPostDisconnectCommand(self.postCmd)
def getPluginResource(pluginId, stringId):
    '''See getPluginResource.mel in Maya.

    Unfortunately there is no equivalent python version of this MEL proc
    so we created our own version of it here.'''

    # Form full id string.
    # Plugin string id's are prefixed with "p_".
    fullId = 'p_%s.%s' % (pluginId, stringId)
    if cmds.displayString(fullId, exists=True):
        dispStr = cmds.displayString(fullId, query=True, value=True)
        return dispStr
    else:
        msgFormat = mel.eval('uiRes("m_getPluginResource.kLookupFailed")')
        msg = cmds.format(msgFormat, stringArg=(pluginId, stringId))
        cmds.error(msg)
def cacheCommitUi(parent, selectedFile):
    # Read data to set up cache.

    # The following call will set _cacheOptions.  Initial settings not accessed
    # on "query", is therefore an empty string.
    mel.eval(
        'mayaUsdTranslatorExport("fileOptionsScroll", "query", "", "mayaUsdCacheMayaReference_setCacheOptions")'
    )

    # Regardless of UI, animation is always on.
    cacheOptionsText = re.sub(r'animation=.', 'animation=1', getCacheOptions())

    userArgs = mayaUsd.lib.Util.getDictionaryFromEncodedOptions(
        cacheOptionsText)

    primName = cmds.textFieldGrp('primNameText', query=True, text=True)
    defineInVariant = cmds.radioButtonGrp('variantRadioBtn',
                                          query=True,
                                          select=True)
    userArgs['rn_layer'] = selectedFile
    userArgs['rn_primName'] = primName
    userArgs['rn_defineInVariant'] = defineInVariant
    userArgs['rn_payloadOrReference'] = cmds.optionMenuGrp(
        'compositionArcTypeMenu', query=True, value=True)
    userArgs['rn_listEditType'] = cmds.optionMenu('listEditedAsMenu',
                                                  query=True,
                                                  value=True)

    if defineInVariant:
        userArgs['rn_variantSetName'] = cmds.optionMenu('variantSetMenu',
                                                        query=True,
                                                        value=True)
        variantName = cmds.optionMenu('variantNameMenu',
                                      query=True,
                                      value=True)
        if variantName == 'Create New':
            variantName = cmds.textField('variantNameText',
                                         query=True,
                                         text=True)
        userArgs['rn_variantName'] = variantName

    # Call push.
    if not mayaUsd.lib.PrimUpdaterManager.mergeToUsd(_mayaRefDagPath,
                                                     userArgs):
        errorMsgFormat = getMayaUsdLibString('kErrorCacheToUsdFailed')
        errorMsg = cmds.format(errorMsgFormat, stringArg=(_mayaRefDagPath))
        cmds.error(errorMsg)
def registerPluginResource(pluginId, stringId, resourceStr):
    '''See registerPluginResource.mel in Maya.

    Unfortunately there is no equivalent python version of this MEL proc
    so we created our own version of it here.'''

    fullId = 'p_%s.%s' % (pluginId, stringId)
    if cmds.displayString(fullId, exists=True):
        # Issue warning if the string is already registered.
        msgFormat = mel.eval('uiRes("m_registerPluginResource.kNotRegistered")')
        msg = cmds.format(msgFormat, stringArg=(pluginId, stringId))
        cmds.warning(msg)
        # Replace the string's value
        cmds.displayString(fullId, replace=True, value=resourceStr)
    else:
        # Set the string's default value.
        cmds.displayString(fullId, value=resourceStr)
示例#13
0
def getEdits(owner, target):
	"""
	Query edits that are stored on the given owner node.
	
	If target is not empty, we will only list
	edits that affect nodes in this assembly.
	
	If target is empty, we will list all edits
	stored on the given node
	"""
	
	editList = []
	useStringTarget = False
	err = maya.stringTable['y_editUtils.kInvalidNode' ]

	try:
		ownerNode = makeDependNode(owner)
	except:
		msg = cmds.format(err, stringArg=owner)
		print msg
		raise
	
	try:
		targetNode = makeDependNode(target)
	except:
		useStringTarget = True
		pass
	
	if useStringTarget:
		it = OpenMaya.MItEdits(ownerNode, target)
	else:
		it = OpenMaya.MItEdits(ownerNode, targetNode)

	while not it.isDone() :
		edit = it.edit()
		# if an edit was removed, it will be NULL
		if edit is not None:
			editList.append(it.edit())
		it.next()

	return editList 
示例#14
0
    def connectNode(self, selNode=""):
        #check if a node has been specified in the function call
        if len(selNode) > 0:
            self.droppedNode = selNode

        #to check if the pre connection command passes
        stat = True
        if (len(self.postCmd) > 0):
            stat = self.runPreCommand(self.postCmd)
        if not stat:
            return

        nodeType = cmds.nodeType(self.droppedNode)

        #if the user selected a transform (and that isn't what we want) then get it's shape node
        if (nodeType == "transform" and self.desiredNodeType != "transform"):
            shapes = cmds.listRelatives(self.droppedNode, pa=True)
            #print shapes
            self.droppedNode = shapes[0]  #get the first found shape
            nodeType = cmds.nodeType(self.droppedNode)

        isWanted = self.isDesiredNode(nodeType)

        if isWanted:
            self.setText(self.droppedNode)
            self.setConnectedStyle()
            cmds.connectAttr('%s.%s' % (self.droppedNode, self.sourceAttr),
                             '%s.%s' % (self.node, self.attr),
                             force=True)

            if (len(self.postCmd) > 0):
                self.runPostCommand(self.postCmd)
        else:
            message = cmds.format(kIncompatibleTypes,
                                  stringArg=(nodeType, self.desiredNodeType))
            command = 'evalDeferred \"TN_InViewMessage(\\"' + message + '\\", \\"Error\\")\"'
            mel.eval(command)
        self.menu.clear()
示例#15
0
def _createShaderMenuItems(ned, node):
    """
    Create node item marking menu items specific to shader nodes
    """
    def refreshCB(*args):
        mel.eval('updateFileNodeSwatch("%s")' % (node))

    layer = mel.eval('currentRenderLayerLabel()')
    if len(layer) > 0 and layer != 'masterLayer':

        def assignCB(*args):
            mel.eval('hookShaderOverride("%s", "", "%s")' % (layer, node))

        assignMaterialOverString = cmds.format(
            maya.stringTable['y_nodeEditorMenus.kAssignMaterialOverride'],
            stringArg=layer)
        cmds.menuItem(label=assignMaterialOverString,
                      radialPosition='W',
                      c=assignCB)

    cmds.menuItem(
        label=maya.stringTable['y_nodeEditorMenus.kShaderGenSwatch'],
        radialPosition='SW',
        ann=maya.stringTable['y_nodeEditorMenus.kShaderGenSwatchAnnot'],
        c=refreshCB)

    shadingGroupArray = cmds.listConnections(node,
                                             source=False,
                                             destination=True,
                                             type='shadingEngine')
    groupSize = 0
    if shadingGroupArray:
        if len(shadingGroupArray) > 1:
            # Remove any duplicates by making the list a set
            shadingGroupArray = list(set(shadingGroupArray))
            shadingGroupArray.sort()
        groupSize = len(shadingGroupArray)
    if groupSize <= 1:
        removeMenuItem = '%sROMMI' % (ned)

        def assignCB(*args):
            cmds.hyperShade(assign=node)

        def assignOceanCB(*args):
            mel.eval('assignOceanShader "%s"' % (node))

        def paintCB(*args):
            mel.eval('shaderPaintTool "%s"' % (node))

        def selectCB(*args):
            cmds.hyperShade(objects=node)

        def soloCB(*args):
            cmds.soloMaterial(node="%s" % (node))

        def unSoloCB(*args):
            cmds.soloMaterial(unsolo=True)

        def frameCB(*args):
            cmds.hyperShade(objects=node)
            mel.eval('fitAllPanels -selected')

        def removeCB(*args):
            mel.eval('buildMaterialRemoveOverrideMenu -shader "%s" "%s"' %
                     (node, removeMenuItem))

        assignMaterialSelString = maya.stringTable[
            'y_nodeEditorMenus.kAssignMaterialToViewportSelection']
        type = cmds.nodeType(node)
        if type == 'oceanShader':
            cmds.menuItem(label=assignMaterialSelString,
                          radialPosition='N',
                          c=assignOceanCB)
        else:
            cmds.menuItem(label=assignMaterialSelString,
                          radialPosition='N',
                          c=assignCB)

            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kPaintAssignShader'],
                radialPosition='NE',
                c=paintCB)

        cmds.menuItem(
            label=maya.
            stringTable['y_nodeEditorMenus.kSelectObjectsWithMaterial'],
            radialPosition='E',
            c=selectCB)

        inLookDev = (nEd(ned, q=True, editorMode=True) == "lookdev")
        if inLookDev:
            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kSoloMaterial'],
                radialPosition='S',
                c=soloCB,
                version='2016')
            cmds.menuItem(
                label=maya.
                stringTable['y_nodeEditorMenus.kRemoveMaterialSoloing'],
                radialPosition='SE',
                c=unSoloCB,
                version='2016')

        cmds.menuItem(
            label=maya.
            stringTable['y_nodeEditorMenus.kFrameObjectsWithMaterial'],
            c=frameCB)

        cmds.menuItem(divider=True)

        cmds.menuItem(removeMenuItem,
                      label=maya.
                      stringTable['y_nodeEditorMenus.kRemoveMaterialOverride'],
                      subMenu=True,
                      pmc=removeCB)

        cmds.setParent('..', menu=True)

        cmds.menuItem(divider=True)
    else:
        assignToSelectionString = maya.stringTable[
            'y_nodeEditorMenus.kAssignToViewportSelection']
        selectObjString = maya.stringTable['y_nodeEditorMenus.kSelectObjects']
        frameObjString = maya.stringTable['y_nodeEditorMenus.kFrameObjects']

        radialItemIndex = groupSize - 1
        for member in shadingGroupArray:
            shader = member

            def assignCB(*args):
                cmds.hyperShade(assign=shader)

            def selectCB(*args):
                cmds.hyperShade(objects=shader)

            def frameCB(*args):
                cmds.hyperShade(objects=shader)
                mel.eval('fitAllPanels -selected')

            assignToSelectionStrFmt = cmds.format(assignToSelectionString,
                                                  stringArg=member)
            assignToSelMenuItem = cmds.menuItem(label=assignToSelectionStrFmt,
                                                c=assignCB)

            selectObjStrFmt = cmds.format(selectObjString, stringArg=member)
            selectObjMenuItem = cmds.menuItem(label=selectObjStrFmt,
                                              c=selectCB)

            if member == shadingGroupArray[radialItemIndex]:
                cmds.menuItem(assignToSelMenuItem, e=True, radialPosition='N')
                cmds.menuItem(selectObjMenuItem, e=True, radialPosition='E')

            frameObjStrFmt = cmds.format(frameObjString, stringArg=member)
            cmds.menuItem(label=frameObjStrFmt, c=frameCB)

        cmds.menuItem(divider=True)
示例#16
0
def ProxyShapeFilePathChanged(filePathAttr, newFilePath=None):
    # Function called from the MayaUsd Proxy Shape template when the file path
    # text field of the file path attibute custom control is modified or interacted with.
    #
    # Arguments:
    # - filePathAttr: string representing the file path attribute.
    # - newFilePath : If None, the user clicked the file browser button.
    #                 - In this case a file dialog will be opened to allow user to pick USD file.
    #                 Otherwise when a string, the user entered a filename directly in the field.
    #                 - In this case simply try and load the file.
    #
    # Return Value:
    # - True:  The input file path attribute was updated with a new value.
    # - False: No update to file path attribute was done.
    #
    debugMessage('ProxyShapeFilePathChanged(%s, %s)' % (filePathAttr, newFilePath))
    try:
        stageName, proxyStage = GetStageFromProxyShapeAttr(filePathAttr)

        # Does the filepath attribute contain a valid file?
        currFilePath = cmds.getAttr(filePathAttr)
        dirtyStack = False
        openFileDialog = False
        if currFilePath:
            # We have a current file path, so check if any layer in the layerstack is dirty?
            dirtyStack = IsProxyShapeLayerStackDirty(proxyStage)
            if not dirtyStack:
                openFileDialog = True
        else:
            # No current file path, so do we just have an empty stage or was something added to
            # this anon layer?
            rootLayer = proxyStage.GetRootLayer()
            if rootLayer and not rootLayer.empty:
                dirtyStack = True
            elif newFilePath is None:
                debugMessage('  Empty stage, opening file dialog...')
                openFileDialog = True

        # If we have a dirty layer stack, display dialog to confirm new loading.
        if dirtyStack:
            kTitleFormat = getMayaUsdString("kDiscardStageEditsTitle")
            kMsgFormat = getMayaUsdString("kDiscardStageEditsLoadMsg")
            kYes = getMayaUsdString("kButtonYes")
            kNo = getMayaUsdString("kButtonNo")
            kTitle = cmds.format(kTitleFormat, stringArg=stageName)
            # Our title is a little long, and the confirmDialog command is not making the
            # dialog wide enough to show it all. So by telling the message string to not
            # word-wrap, the dialog is forced wider.
            kMsg = "<p style='white-space:pre'>" + cmds.format(kMsgFormat, stringArg=stageName)
            res = cmds.confirmDialog(title=kTitle,
                                     message=kMsg, messageAlign='left', 
                                     button=[kYes, kNo], defaultButton=kYes, cancelButton=kNo, dismissString=kNo,
                                     icon='warning')
            if res == kYes:
                debugMessage('  User confirmed load action, opening file dialog...')
                openFileDialog = True
            else:
                # User said NO to update, so don't proceed any farther.
                return False

        if openFileDialog and newFilePath is None:
            # Pop the file open dialog for user to load new usd file.
            title = getMayaUsdString("kLoadUSDFile")
            okCaption = getMayaUsdString("kLoad")
            fileFilter = getMayaUsdLibString("kAllUsdFiles") + ' (*.usd *.usda *.usdc *.usdz );;*.usd;;*.usda;;*.usdc;;*.usdz';
            res = cmds.fileDialog2(caption=title, fileMode=1, ff=fileFilter, okc=okCaption)
            if res and len(res) == 1:
                debugMessage('    User picked USD file, setting file path attribute')
                # Simply set the file path attribute. The proxy shape will load the file.
                usdFileToLoad = res[0]
                cmds.setAttr(filePathAttr, usdFileToLoad, type='string')
                return True
        elif newFilePath is not None:
            # Instead of opening a file dialog to get the USD file, simply
            # use the one provided as input.
            # Note: it is important to check "not None" since the new file path can be
            #       an empty string.
            debugMessage('  New file to load provided, setting filepath="%s"' % newFilePath)
            cmds.setAttr(filePathAttr, newFilePath, type='string')
            return True
    except Exception as e:
        debugMessage('ProxyShapeFilePathChanged() - Error: %s' % str(e))
        pass
    return False
def executeDroppedPythonFile(droppedFile, obj):
    """
    Called by Maya when you Drag and Drop a Python (.py) file onto the viewport.

    Here we load the input python file and try and execute the function:
    onMayaDroppedPythonFile()

    Note: Any main code inside the Python file will also be executed, but since
          it's being imported into another module (__name__ != "__main__")

    Parameters:
        droppedFile - The Python file dropped onto the viewport
        obj - The object under the mouse

    \return True if we sucessfully called function: onMayaDroppedPythonFile()

    Example:
    - An example of a DnD Python file would be:

    MayaDropPythonTest.py:
        import maya

        def onMayaDroppedPythonFile(obj):
            print('onMayaDroppedPythonFile(' + obj + ')')
            if obj:
                maya.mel.eval('createAndAssignShader blinn ' + obj)

        if __name__ == "__main__":
            print("MayaDropPythonTest.py is being run directly")
        else:
            print("MayaDropPythonTest.py is being imported into another module")

    When we DnD this file onto an object in the viewport the output would be:
        MayaDropPythonTest.py is being imported into another module
        onMayaDroppedPythonFile(pSphere1)

    """

    ret = False

    # Add the path of the dropped file to the Python path, so we can import it.
    theDirName = os.path.dirname(droppedFile)
    theBaseName = os.path.basename(droppedFile)
    theModuleName = os.path.splitext(theBaseName)[0]

    # Add the path of the input dropped file, so we can load it.
    addedPath = False
    if theDirName not in sys.path:
        addedPath = True
        sys.path.insert(0, theDirName)

    # Try to load the module.
    loadedModule = None
    try:
        import imp
        (fp, pathname, desc) = imp.find_module(theModuleName)
        loadedModule = imp.load_module(theModuleName, fp, pathname, desc)
    finally:
        if fp:
            fp.close()

    # If we successfully loaded the module, call the dropped function.
    if loadedModule:
        if (hasattr(loadedModule, MY_DROP_FUNC)):
            ret = loadedModule.onMayaDroppedPythonFile(obj)
        else:
            str = cmds.format(
                maya.
                stringTable['y_executeDroppedPythonFile.kDropFuncMissing'],
                stringArg=(theModuleName, MY_DROP_FUNC))
            cmds.warning(str)
            ret = False
    else:
        str = cmds.format(
            maya.stringTable['y_executeDroppedPythonFile.kLoadModuleError'],
            stringArg=(theModuleName))
        cmds.warning(str)
        ret = False

    # Remove the path we added above.
    if addedPath:
        sys.path.pop(0)

    return ret
示例#18
0
def createMayaReferencePrim(
        ufePathStr,
        mayaReferencePath,
        mayaNamespace,
        mayaReferencePrimName=mayaRefUtils.defaultMayaReferencePrimName(),
        groupPrim=None,
        variantSet=None,
        mayaAutoEdit=kDefaultEditAsMayaData):
    '''Create a Maya reference prim and optional group prim parented to the argument path.
    Optionally create a variant set and name and placed the edits inside that variant.

    Naming of Maya Reference prim is supported, otherwise default name is used.

    The group prim is optional.

    The variant set and name are optional

    Parameters:
    -----------
    ufePathStr : str : Ufe PathString of parent prim to add Maya Reference
    mayaReferencePath : str : File path of Maya Reference (for attribute)
    mayaNamespace : str : Namespace (for attribute)
    mayaReferencePrimName : str [optional] : Name for the Maya Reference prim
    groupPrim : tuple(str,str,str) [optional] : The Group prim Name, Type & Kind to create
                                                Note: the name is optional and will be auto-computed
                                                      if empty or not provided.
                                                Note: Type and Kind are both mandatory, but Kind is
                                                      allowed to be empty string.
    variantSet : tuple(str,str) [optional] : The Variant Set Name and Variant Name to create

    Return:
    -------
    The Usd prim of the newly created Maya Reference or an invalid prim if there is an error.
    '''

    # Make sure the prim name is valid and doesn't already exist.
    parentPrim = mayaUsd.ufe.ufePathToPrim(ufePathStr)

    # There are special conditions when we are given the ProxyShape gateway node.
    ufePath = ufe.PathString.path(ufePathStr)
    isGateway = (ufePath.nbSegments() == 1)

    # Were we given a Group prim to create?
    groupPrimName = None
    groupPrimType = None
    groupPrimKind = None
    if groupPrim:
        if (len(groupPrim) == 2):
            groupPrimType, groupPrimKind = groupPrim
        elif (len(groupPrim) == 3):
            groupPrimName, groupPrimType, groupPrimKind = groupPrim

            # Make sure the input Group prim name doesn't exist already
            # and validate the input name.
            # Note: it is allowed to be input as empty in which case a default is used.
            if groupPrimName:
                checkGroupPrimName = mayaUsd.ufe.uniqueChildName(
                    parentPrim, groupPrimName)
                if checkGroupPrimName != groupPrimName:
                    errorMsgFormat = getMayaUsdLibString(
                        'kErrorGroupPrimExists')
                    errorMsg = cmds.format(errorMsgFormat,
                                           stringArg=(groupPrimName,
                                                      ufePathStr))
                    om.MGlobal.displayError(errorMsg)
                    return Usd.Prim()
                groupPrimName = Tf.MakeValidIdentifier(checkGroupPrimName)

        # If the group prim was either not provided or empty we use a default name.
        if not groupPrimName:
            groupPrimName = getDefaultGroupPrimName(parentPrim, mayaNamespace)

    # When the input is a gateway we cannot have in variant unless group is also given.
    if isGateway and variantSet and not groupPrimName:
        errorMsg = getMayaUsdLibString('kErrorCannotAddToProxyShape')
        om.MGlobal.displayError(errorMsg)
        return Usd.Prim()

    # Make sure the input Maya Reference prim name doesn't exist already
    # and validate the input name.
    # Note: if we are given a group prim to create, then we know that the
    #       Maya Reference prim name will be unique since it will be the
    #       only child (of the newly created group prim).
    checkName = mayaUsd.ufe.uniqueChildName(
        parentPrim,
        mayaReferencePrimName) if groupPrim is None else mayaReferencePrimName
    if checkName != mayaReferencePrimName:
        errorMsgFormat = getMayaUsdLibString('kErrorMayaRefPrimExists')
        errorMsg = cmds.format(errorMsgFormat,
                               stringArg=(mayaReferencePrimName, ufePathStr))
        om.MGlobal.displayError(errorMsg)
        return Usd.Prim()
    validatedPrimName = Tf.MakeValidIdentifier(checkName)

    # Extract the USD path segment from the UFE path and append the Maya
    # reference prim to it.
    parentPath = str(ufePath.segments[1]) if ufePath.nbSegments() > 1 else ''

    stage = mayaUsd.ufe.getStage(ufePathStr)

    # Optionally insert a Group prim as a parent of the Maya reference prim.
    groupPrim = None
    if groupPrimName:
        groupPath = Sdf.AssetPath(parentPath + '/' + groupPrimName)
        try:
            groupPrim = stage.DefinePrim(groupPath.path, groupPrimType)
        except (Tf.ErrorException):
            groupPrim = Usd.Prim()
        if not groupPrim.IsValid():
            errorMsgFormat = getMayaUsdLibString('kErrorCreatingGroupPrim')
            errorMsg = cmds.format(errorMsgFormat, stringArg=(ufePathStr))
            om.MGlobal.displayError(errorMsg)
            return Usd.Prim()
        if groupPrimKind:
            model = Usd.ModelAPI(groupPrim)
            model.SetKind(groupPrimKind)

    if groupPrim:
        primPath = Sdf.AssetPath(groupPrim.GetPath().pathString + '/' +
                                 validatedPrimName)
    else:
        primPath = Sdf.AssetPath(parentPath + '/' + validatedPrimName)

    # Were we given a Variant Set to create?
    variantSetName = None
    variantName = None
    if variantSet and (len(variantSet) == 2):
        variantSetName, variantName = variantSet
    if variantSetName and variantName:
        validatedVariantSetName = Tf.MakeValidIdentifier(variantSetName)
        validatedVariantName = Tf.MakeValidIdentifier(variantName)

        # If we created a group prim add the variant set there, otherwise add it
        # to the prim that corresponds to the input ufe path.
        variantPrim = groupPrim if groupPrim else mayaUsd.ufe.ufePathToPrim(
            ufePathStr)
        vset = variantPrim.GetVariantSet(validatedVariantSetName)
        vset.AddVariant(validatedVariantName)
        vset.SetVariantSelection(validatedVariantName)
        with vset.GetVariantEditContext():
            # Now all of our subsequent edits will go "inside" the
            # 'variantName' variant of 'variantSetName'.
            prim = createPrimAndAttributes(stage, primPath, mayaReferencePath,
                                           mayaNamespace, mayaAutoEdit)
    else:
        prim = createPrimAndAttributes(stage, primPath, mayaReferencePath,
                                       mayaNamespace, mayaAutoEdit)
    if prim is None or not prim.IsValid():
        errorMsgFormat = getMayaUsdLibString('kErrorCreatingMayaRefPrim')
        errorMsg = cmds.format(errorMsgFormat, stringArg=(ufePathStr))
        om.MGlobal.displayError(errorMsg)
        return Usd.Prim()

    return prim
示例#19
0
def doRemoveSelectedEdits( assemblyName, selection_model, listEditsOnSelectedAssembly ):
	""" 
	This function does the work described for the "removeSelectedEdits"
	method below.
	"""
	allRemovable = 1
	err = maya.stringTable['y_editUtils.kInvalidAssembly' ]
	try:
		selectedAssembly = makeDependNode(assemblyName)
	except:
		msg = cmds.format(err, stringArg=assemblyName)
		print msg
		raise

	# compare selected edits to edits stored on the specified
	# assembly, or any other assembly in the hierarchy above
	# and try to remove them.
        

        """
        Process the top most assembly first so it matches the order of the list edits window.
        This will allow us to  use the index to safely delete the current edit. We process the indexes
        in reverse order so start with the number of edit rows and decrement. The combination
        of processing the top most assembly first, processing the edits in reverse and decrementing the index
        means the iterator is perfectly aligned with the UI selection
        This is to solve MAYA-45020
        """
        index = selection_model.edit_count()
        assemblies = deque()
        
        if listEditsOnSelectedAssembly:
                assemblies.appendleft( selectedAssembly )
        else:
                curAssembly = selectedAssembly
                while not curAssembly.isNull():
                        assemblies.appendleft( curAssembly )
                        assemblyMFn = OpenMaya.MFnAssembly(curAssembly)
                        curAssembly = assemblyMFn.getParentAssembly()

	# while there are assemblies in the deque
	while assemblies:
		# If curAssembly is the selectedAssembly, we want to get
		# all edits that are stored on it.
		# But if it's not, then we only want edits stored on
		# curAssembly that affect selectedAssembly (since this
		# is all that the list edits ui will display -- and
		# all that could potentially have been selected).
		#
		# We use a reverse iterator to improve the final state of the 
		# "remove edits" operation, just like assemblies always
		#  unapply their edits in the reverse order they were 
		
		# deque from front which is the top most assembly which edits are the bottom
		# of the UI
		curAssembly = assemblies.popleft()
		if( listEditsOnSelectedAssembly ):
			# The dialog is currently listing all the edits stored on the selected assembly (current tab)
			edits = PyEditItr ( OpenMaya.MItEdits(curAssembly, '', OpenMaya.MItEdits.ALL_EDITS, OpenMaya.MItEdits.kReverse) )
		else:
			# The dialog is currently listing all the edits affecting the selected assembly (current tab)
			edits = PyEditItr ( OpenMaya.MItEdits(curAssembly, selectedAssembly, OpenMaya.MItEdits.ALL_EDITS, OpenMaya.MItEdits.kReverse) )

                
		for edit in edits :
			"""
			wanted to check only the index but checking the string that the string matches
			is safer in case someone deleted a relevant edit with the API without refreshing
			the UI
			""" 
			if selection_model.has_index(index) and selection_model.has_edit( edit.getString() ):
				# If we have a top-level edit, it can be removed. If not,
				# need to raise a warning
				if edit.isTopLevel():
					edits.removeCurrentEdit()
				else:
					allRemovable = 0
			index = index - 1
		
	
	return allRemovable
示例#20
0
def createNodeItemMarkingMenu(ned, node):
    """
    Build node item marking menu
    """

    inContainer = nEd(ned, q=True, inContainerView=True)
    isContainerNode = nEd(ned, q=True, isContainerNode=node)

    inputsMenuItem = '%sIMMI' % (ned)
    outputsMenuItem = '%sOMMI' % (ned)
    editCustomAttrListMenuItem = '%sCALMMI' % (ned)
    if inContainer:
        type = node
    else:
        type = cmds.nodeType(node)

    def openContainerViewCB(*args):
        nEd(ned, e=True, openContainerView=[node, False])

    def openContainerViewInNewTabCB(*args):
        nEd(ned, e=True, openContainerView=[node, True])

    def graphUpDownstreamCB(*args):
        mel.eval('NodeEditorGraphUpDownstream')

    def graphUpstreamCB(*args):
        mel.eval('NodeEditorGraphUpstream')

    def graphDownstreamCB(*args):
        mel.eval('NodeEditorGraphDownstream')

    def removeUnselectedCB(*args):
        nEd(ned, e=True, removeUnselected=True)

    def removeSelectedCB(*args):
        mel.eval('NodeEditorGraphRemoveSelected')

    def removeUpstreamCB(*args):
        nEd(ned, e=True, removeUpstream=True)

    def removeDownstreamCB(*args):
        nEd(ned, e=True, removeDownstream=True)

    def selectUpDownstreamCB(*args):
        nEd(ned, e=True, selectUpstream=True, selectDownstream=True)

    def selectUpstreamCB(*args):
        nEd(ned, e=True, selectUpstream=True)

    def selectDownstreamCB(*args):
        nEd(ned, e=True, selectDownstream=True)

    def nodeCB(*args):
        mel.eval('showEditorExact "%s"' % (node))

    def inputsCB(*args):
        mel.eval(
            'source "dagMenuProc.mel"; createHistoryMenuItems("%s", "%s");' %
            (inputsMenuItem, node))

    def outputsCB(*args):
        mel.eval(
            'source "dagMenuProc.mel"; createFutureMenuItems("%s", "%s");' %
            (outputsMenuItem, node))

    def renameCB(*args):
        nEd(ned, e=True, renameNode=node)

    def toggleSwatchCB(*args):
        nEd(ned, e=True, toggleSwatchSize=node)

    def toggleSelectedSwatchCB(*args):
        nEd(ned, e=True, toggleSwatchSize="")

    def editCustomAttributeListCB(*args):
        editMode = cmds.menuItem(editCustomAttrListMenuItem,
                                 q=True,
                                 checkBox=True)
        if editMode:
            nEd(ned, e=True, customAttributeListEdit=[node])
        else:
            nEd(ned, e=True, customAttributeListEdit=[""])

    def showCB(*args):
        nEd(ned, e=True, showAllNodeAttributes=node)

    def addCB(*args):
        mel.eval('dynAddAttrWin( { "%s" } )' % node)

    def deleteCB(*args):
        mel.eval('dynDeleteAttrWin( { "%s" } )' % node)

    def createCB(*args):
        selectionList = cmds.ls(selection=True)
        if len(selectionList) > 0:
            mel.eval('createContainerWithNodes(`ls -sl`)')
        else:
            mel.eval('createContainerWithNodes({ "%s" })' % node)

    def createTransCB(*args):
        selectionList = cmds.ls(selection=True)
        if len(selectionList) > 0:
            cmds.container(type='dagContainer',
                           includeHierarchyBelow=True,
                           includeTransform=True,
                           force=True,
                           addNode=selectionList)
        else:
            cmds.container(type='dagContainer',
                           includeHierarchyBelow=True,
                           includeTransform=True,
                           force=True,
                           addNode=[node])

    def removeCB(*args):
        selectionList = cmds.ls(selection=True)
        if len(selectionList) > 0:
            mel.eval('removeNodesFromContainer(`ls -sl`, "", 0)')
        else:
            mel.eval('removeNodesFromContainer({ "%s" }, "", 0)' % node)

    def helpCB(*args):
        cmds.showHelp('Nodes/%s.html' % type, docs=True)

    if not inContainer:
        nameSplit = node.rpartition('|')
        cmds.menuItem(label=('%s...' % nameSplit[2]), c=nodeCB)

        cmds.menuItem(divider=True)

        _addCustomNodeItemMenus(ned, node)

    customEditNode = nEd(ned, q=True, customAttributeListEdit=True)
    editMode = (node == customEditNode)

    if not editMode:
        if inContainer:
            if isContainerNode:
                cmds.menuItem(
                    label=maya.stringTable['y_nodeEditorMenus.kOpenContents'],
                    radialPosition='N',
                    ann=maya.
                    stringTable['y_nodeEditorMenus.kOpenContentsAnnot'],
                    c=openContainerViewCB)

                cmds.menuItem(
                    label=maya.
                    stringTable['y_nodeEditorMenus.kOpenContentsInNewTab'],
                    radialPosition='E',
                    ann=maya.stringTable[
                        'y_nodeEditorMenus.kOpenContentsInNewTabAnnot'],
                    c=openContainerViewInNewTabCB)
        else:
            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kRegraphStream'],
                radialPosition='N',
                subMenu=True)

            cmds.menuItem(
                label=maya.
                stringTable['y_nodeEditorMenus.kRegraphUpDownStream'],
                radialPosition='W',
                ann=(mel.eval(
                    'getRunTimeCommandAnnotation ("NodeEditorGraphUpDownstream")'
                )),
                c=graphUpDownstreamCB)

            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kRegraphUpStream'],
                radialPosition='N',
                ann=(mel.eval(
                    'getRunTimeCommandAnnotation ("NodeEditorGraphUpstream")')
                     ),
                c=graphUpstreamCB)

            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kRegraphDownStream'],
                radialPosition='S',
                ann=(mel.eval(
                    'getRunTimeCommandAnnotation ("NodeEditorGraphDownstream")'
                )),
                c=graphDownstreamCB)

            cmds.setParent('..', menu=True)

            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kRemoveStream'],
                radialPosition='E',
                subMenu=True)

            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kRemoveUnselected'],
                radialPosition='W',
                ann=maya.
                stringTable['y_nodeEditorMenus.kRemoveUnselectedAnnot'],
                c=removeUnselectedCB)

            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kRemoveSelected'],
                radialPosition='E',
                ann=(mel.eval(
                    'getRunTimeCommandAnnotation ("NodeEditorGraphRemoveSelected")'
                )),
                c=removeSelectedCB)

            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kRemoveUpStream'],
                radialPosition='N',
                ann=maya.stringTable['y_nodeEditorMenus.kRemoveUpStreamAnnot'],
                c=removeUpstreamCB)

            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kRemoveDownStream'],
                radialPosition='S',
                ann=maya.
                stringTable['y_nodeEditorMenus.kRemoveDownStreamAnnot'],
                c=removeDownstreamCB)

            cmds.setParent('..', menu=True)

        nedSelectionList = nEd(ned, q=True, selectNode=True)

        if cmds.ls(node, selection=True) or (nedSelectionList
                                             and node in nedSelectionList):
            parent = cmds.setParent(q=True, menu=True)

            cmds.menuItem(label=_loadUIString('kSelectStream'),
                          radialPosition='W',
                          subMenu=True)

            cmds.menuItem(label=_loadUIString('kSelectUpDownstream'),
                          radialPosition='W',
                          ann=_loadUIString('kSelectUpDownstreamAnnot'),
                          c=selectUpDownstreamCB)

            cmds.menuItem(label=_loadUIString('kSelectUpstream'),
                          radialPosition='N',
                          ann=_loadUIString('kSelectUpstreamAnnot'),
                          c=selectUpstreamCB)

            cmds.menuItem(label=_loadUIString('kSelectDownstream'),
                          radialPosition='S',
                          ann=_loadUIString('kSelectDownstreamAnnot'),
                          c=selectDownstreamCB)

            cmds.setParent('..', menu=True)

        parent = cmds.setParent(q=True, menu=True)

        if not inContainer:
            cmds.menuItem(inputsMenuItem,
                          label=maya.stringTable['y_nodeEditorMenus.kInputs'],
                          subMenu=True)
            cmds.menu(inputsMenuItem, e=True, pmc=inputsCB)
            cmds.setParent(parent, menu=True)

            cmds.menuItem(outputsMenuItem,
                          label=maya.stringTable['y_nodeEditorMenus.kOutputs'],
                          subMenu=True)
            cmds.menu(outputsMenuItem, e=True, pmc=outputsCB)
            cmds.setParent(parent, menu=True)

            cmds.menuItem(divider=True)

        cmds.menuItem(label=maya.stringTable['y_nodeEditorMenus.kRename'],
                      c=renameCB)

        cmds.menuItem(
            label=maya.stringTable['y_nodeEditorMenus.kToggleSwatchSize'],
            ann=maya.stringTable['y_nodeEditorMenus.kToggleSwatchSizeAnnot'],
            c=toggleSwatchCB)

        cmds.menuItem(label=_loadUIString('kToggleSelectedSwatch'),
                      ann=_loadUIString('kToggleSelectedSwatchAnnot'),
                      c=toggleSelectedSwatchCB)

        cmds.menuItem(divider=True)

    if not inContainer:
        cmds.menuItem(editCustomAttrListMenuItem,
                      label=_loadUIString('kEditCustomAttrList'),
                      ann=_loadUIString('kEditCustomAttrListAnnot'),
                      checkBox=(node == customEditNode),
                      c=editCustomAttributeListCB)

    if not editMode:
        cmds.menuItem(
            label=maya.stringTable['y_nodeEditorMenus.kShowAllAttributes'],
            ann=maya.stringTable['y_nodeEditorMenus.kShowAllAttributesAnnot'],
            c=showCB)

        if not inContainer:
            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kAddAttributes'],
                c=addCB)

            cmds.menuItem(
                label=maya.stringTable['y_nodeEditorMenus.kDeleteAttributes'],
                c=deleteCB)

    if not inContainer:
        cmds.menuItem(divider=True)

        helpString = cmds.format(
            maya.stringTable['y_nodeEditorMenus.kHelpMenuLabel'],
            stringArg=type)
        cmds.menuItem(label=helpString, enableCommandRepeat=False, c=helpCB)