Ejemplo n.º 1
0
 def export_pose(self):
     pose_manager = driven_pose.DrivenPoseManager()
     # Verify component selection
     if self.components_list.list.currentItem():
         current_component = self.components_list.list.currentItem().data(1)
     else:
         pm.displayError("Select a component to export pose for.")
         return
     if not isinstance(current_component, luna_rig.AnimComponent):
         pm.displayError(
             "Invalid component selection, must be of type: {0}".format(
                 luna_rig.AnimComponent))
         return
     # Get controls to export
     if not self.controls_list.list.selectedItems():
         export_controls = current_component.controls
     else:
         export_controls = [
             item.data(1)
             for item in self.controls_list.list.selectedItems()
         ]
     # Do export
     pose_manager.export_pose(current_component,
                              export_controls,
                              driver_ctl=self.driver_field.line_edit.text(),
                              pose_name=self.pose_name_field.text(),
                              driver_value=self.driver_value_field.value())
Ejemplo n.º 2
0
def connect(cnxDict, nsRig=None, nsSkin=None):
    for i, jnt in enumerate(cnxDict["joints"]):
        try:
            if nsSkin:
                oJnt = pm.PyNode(nsSkin + ":" + jnt)
            else:
                oJnt = pm.PyNode(jnt)
            for e, plug in enumerate([oJnt.translate, oJnt.rotate, oJnt.scale,
                                      oJnt.scale.scaleX, oJnt.scale.scaleY,
                                      oJnt.scale.scaleZ, oJnt.shear]):
                if cnxDict["attrs"][i][e]:
                    if nsRig:
                        pm.connectAttr(
                            nsRig + ":" + cnxDict["attrs"][i][e], plug, f=True)
                    else:
                        pm.connectAttr(cnxDict["attrs"][i][e], plug, f=True)

            if cnxDict["attrs"][i][7]:
                if nsRig:
                    pm.connectAttr(
                        oJnt.parentInverseMatrix[0], nsRig + ":" +
                        cnxDict["attrs"][i][7], f=True)
                else:
                    pm.connectAttr(
                        oJnt.parentInverseMatrix[0],
                        cnxDict["attrs"][i][7],
                        f=True)

        except Exception:
            pm.displayError("{} is not found in the scene".format(jnt))
Ejemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        self._isJointControl = kwargs.pop("jointControl", False) | kwargs.pop("jc", False)
        self._style = kwargs.pop

        self._translateLocked = kwargs.pop("translate", True) | kwargs.pop("t", True)
        self._rotateLocked = kwargs.pop("rotate", True) | kwargs.pop("r", True)
        self._scaleLocked = kwargs.pop("scale", True) | kwargs.pop("s", True)
        self.name = kwargs.pop("name", "Control")
        self.name = kwargs.pop("n", self.name)

        self.parent = None

        if type(args[0]) == int:
            self.node = pm.group(em=True, n=self.name)
            self.setStyle(args[0])

        # Wrap an existing node
        elif type(args[0]) == pm.nt.Transform:
            if type(args[0].getShape()) == pymel.core.nodetypes.NurbsCurve:
                self.node = args[0]
            else:
                if self._isJointControl:
                    pm.select(cl=True)
                    self.node = pm.joint(n=self.name)
                    self.node.drawStyle.set(2)
                else:
                    self.node = pm.group(em=True, n=self.name)

        else:
            pm.displayError("Invalid argument: {0}".format(args[0]))
Ejemplo n.º 4
0
def skinCopy(sourceMesh=None, targetMesh=None, *args):
    if not sourceMesh or not targetMesh:
        if len(pm.selected()) >=2:
            sourceMesh = pm.selected()[-1]
            targetMeshes = pm.selected()[:-1]
        else:
            pm.displayWarning("Please select target mesh/meshes and source mesh with skinCluster.")
            return
    else:
        targetMeshes = [targetMesh]

        #we check this here, because if not need to check when we work base on selection.
        if isinstance(sourceMesh, basestring):
            sourceMesh = pm.PyNode(sourceMesh)

    for targetMesh in targetMeshes:
        if  isinstance(targetMesh, basestring):
            sourceMesh = pm.PyNode(targetMesh)

        ss = getSkinCluster(sourceMesh)

        if ss:
            oDef = pm.skinCluster(sourceMesh, query=True, influence=True)
            skinCluster = pm.skinCluster(oDef, targetMesh, tsb=True, nw=2, n=targetMesh.name() + "_SkinCluster")
            pm.copySkinWeights( ss=ss.stripNamespace(), ds=skinCluster.name(), noMirror=True, ia="oneToOne", sm=True, nr=True)
        else:
            pm.displayError("Source Mesh :" + sourceMesh.name() + " Don't have skinCluster")
Ejemplo n.º 5
0
    def inspectSettings(self, *args):

        oSel = pm.selected()
        if oSel:
            root = oSel[0]
        else:
            pm.displayWarning(
                "please select one object from the componenet guide")
            return

        comp_type = False
        guide_root = False
        while root:
            if pm.attributeQuery("comp_type", node=root, ex=True):
                comp_type = root.attr("comp_type").get()
                break
            elif pm.attributeQuery("ismodel", node=root, ex=True):
                guide_root = root
                break
            root = root.getParent()
            pm.select(root)

        if comp_type:
            guide = shifter.importComponentGuide(comp_type)
            gqt.showDialog(guide.componentSettings)

        elif guide_root:
            module_name = "mgear.maya.shifter.guide"
            guide = __import__(module_name, globals(), locals(), ["*"], -1)
            gqt.showDialog(guide.guideSettings)

        else:
            pm.displayError(
                "The selected object is not part of component guide")
Ejemplo n.º 6
0
    def updateTabs(self):
        self.tabs.clear()
        defPath = os.environ.get("MGEAR_SYNOPTIC_PATH", None)

        tab_names = pm.ls(self.model_list.currentText())[0].getAttr("synoptic").split(",")

        for i, tab_name in enumerate(tab_names):
            try:
                if tab_name:
                    if not defPath or not os.path.isdir(defPath):
                        print "Loading default mGear synoptics"
                        module_name = "mgear.maya.synoptic.tabs."+tab_name
                    else:
                        print "Loading Project mGear synoptics"
                        sys.path.append(pm.dirmap(cd=project_synModule))
                        module_name = tab_name
                    module = __import__(module_name, globals(), locals(), ["*"], -1)
                    print tab_name
                    print module_name
                    SynopticTab = getattr(module , "SynopticTab")

                    tab = SynopticTab()
                    self.tabs.insertTab(i, tab, tab_name)
                else:
                    pm.displayWarning("No synoptic tabs for %s"%self.model_list.currentText())
            except:
                pm.displayError("Synoptic tab: %s Loading fail"%tab_name)
    def applyAssetAttribs(self):
        # TODO: set hair node attribs from asset

        index = self.assetAttribsListView.currentIndex()
        selectedAttribAsset = self.assetAttribsListModel.data(index, QtCore.Qt.EditRole)
        if not selectedAttribAsset:
            pmcore.displayError("You must select a asset item in the asset list.")
            return

        attribs = self.assetDict[selectedAttribAsset]
#        print(attribs)

        index = self.hairNodesListView.currentIndex()
        selectedHairNode = self.hairNodesListModel.data(index, QtCore.Qt.EditRole)
        if not selectedHairNode:
            pmcore.displayError("You must select a node in the hair node list.")
            return

        for attrib in hairAttribNameList:
            nodeAttrib = pmcore.general.PyNode(str(selectedHairNode + '.' + attrib))

            value = attribs[attrib]
#            print(value)
            # value type is int or float
            if type(value) is type(1) or type(value) is type(1.0):
                nodeAttrib.set(value)

            # value type is list
            if type(value) is type([]):
                nodeAttrib.set(value[0])
Ejemplo n.º 8
0
 def doIt(*args, **kwargs):
     try:
         ret = func(*args, **kwargs)
     except Exception, e:
         pm.displayError('< {0}.{1} > {2}.'.format(func.__module__,
                                                   func.__name__, str(e)))
         return
Ejemplo n.º 9
0
    def bake(self):

        opmTxt = self.hsysOPM.getValue()
        isAll = self.alhsCBX.getValue()

        if isAll:
            hsList = pm.ls(type='hairSystem')

        else:
            hsList = pm.ls(opmTxt, r=True)[0].getShapes()

        for hs in hsList:

            if isAll:
                topList = [self.getTopGroupFromHair(hs)]

            else:
                topList = self.getTopJointFromHair(hs, True)

            if not topList:
                pm.displayError('The top node not found.')
                return False

            else:
                dagList = pm.ls(topList, dag=True)
                allMixJntList = pm.ls('*mix*', type='joint', r=True)
                mixJntList = list(set(dagList) & set(allMixJntList))

                if not mixJntList:
                    continue

                ncls = hs.inputs(type='nucleus')[0]

                for mixJnt in mixJntList:
                    simJnt = mixJnt.attr('tx').inputs()
                    if simJnt:
                        simJnt = simJnt[0]
                        if simJnt.nodeType() == 'joint':
                            simJnt.attr('radius') >> mixJnt.attr(
                                'radius')  # This is for the unbaking

                if self.tmrgRBG.getSelect() == 1:
                    min = pm.env.getMinTime()
                    max = pm.env.getMaxTime()
                else:
                    min = self.stedIFG.getValue1()
                    max = self.stedIFG.getValue2()

                ncls.attr('enable').set(True)

                pm.bakeResults(mixJntList,
                               sm=True,
                               t=[min, max],
                               ral=False,
                               mr=True,
                               at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])

                ncls.attr('enable').set(False)

                pm.displayInfo('Successfully baked.')
Ejemplo n.º 10
0
def install(label, commands, parent=menuId):
    """Installer Function for sub menus

    Args:
        label (str): Name of the sub menu
        commands (list): List of commands to install
        parent (str, optional): Parent menu for the submenu
    """
    try:
        m = pm.menuItem(parent=parent, subMenu=True, tearOff=True, label=label)
        for label, command in commands:
            if not command:
                pm.menuItem(divider=True)
                continue
            if not label:
                command(m)
                pm.setParent(m, menu=True)
                continue

            pm.menuItem(label=label, command=command)

        return m

    except Exception as ex:
        template = ("An exception of type {0} occured. " "Arguments:\n{1!r}")
        message = template.format(type(ex).__name__, ex.args)
        pm.displayError(message)
Ejemplo n.º 11
0
    def do_baking(self):
        try:
            ctl_instance = luna_rig.Control(self.control_field.text())
        except Exception:
            Logger.exception(
                "Failed to create control instance from {0}".format(
                    self.control_field.text()))
            raise RuntimeError("Invalid control object")

        step = self.step_field.value()
        if self.spaces_combobox.currentText() == self.custom_space_item_text:
            custom_object = self.custom_space_object_field.text()
            if not custom_object or not pm.objExists(custom_object):
                pm.displayError(
                    "Invalid custom space object: {0}".format(custom_object))
                return
            ctl_instance.bake_custom_space(
                custom_object,
                time_range=self.range_widget.get_range(),
                step=step)
        else:
            ctl_instance.bake_space(
                space_name=self.spaces_combobox.currentText(),
                time_range=self.range_widget.get_range(),
                step=step)
Ejemplo n.º 12
0
 def doIt(*args, **kwargs):
     try:
         ret = func(*args, **kwargs)
     except Exception as e:
         pm.displayError(toStr(e))
         traceback.print_exc()
         return returns
     return ret
Ejemplo n.º 13
0
def uninitializePlugin(plugin):

    plugin_fn = ommpx.MFnPlugin(plugin)
    try:
        plugin_fn.deregisterNode(CarpetRoll.TYPE_ID)
    except:
        pm.displayError("Failed to deregister node {0}".format(
            CarpetRoll.TYPE_NAME))
Ejemplo n.º 14
0
 def emit(self, record):
     msg = self.format(record)
     if record.levelname in ["DEBUG", "INFO"]:
         pm.displayInfo(msg)
     elif record.levelname == "WARNING":
         pm.displayWarning(msg)
     elif record.levelname in ["ERROR", "CRITICAL"]:
         pm.displayError(msg)
Ejemplo n.º 15
0
    def readAssets(self, fileName):
        # TODO: read cache contents from specified file
        with open(fileName, mode='r') as cacheFile:
            self.assetDict = json.load(cacheFile)

        if not self.assetDict:
            pmcore.displayError("The cache file is empty...")
        pass
Ejemplo n.º 16
0
 def load_cvwrap(self):
     # wrap face to head rig
     try:
         if not pm.pluginInfo("cvwrap", q=True, loaded=True):
             pm.loadPlugin("cvwrap")
             pm.displayInfo("cvrap plugin loaded!")
     except RuntimeError:
         pm.displayError("You need the cvWrap plugin!")
         raise
Ejemplo n.º 17
0
def selectDeformers(*args):
    if pm.selected():
        try:
            oSel = pm.selected()[0]
            oColl = pm.skinCluster(oSel, query=True, influence=True)
            pm.select(oColl)
        except Exception:
            pm.displayError("Select one object with skinCluster")
    else:
        pm.displayWarning("Select one object with skinCluster")
Ejemplo n.º 18
0
 def set_custom_space(self):
     selection = pm.selected()
     if not selection:
         pm.warning("Select custom space object")
         return
     space_transform = selection[-1]
     if not isinstance(space_transform, luna_rig.nt.Transform):
         pm.displayError("Space object must be of type Transform")
         return
     self.custom_space_object_field.line_edit.setText(
         space_transform.name())
Ejemplo n.º 19
0
    def unbake(self):

        opmTxt = self.hsysOPM.getValue()
        isAll = self.alhsCBX.getValue()

        if isAll:
            hsList = pm.ls(type='hairSystem')

        else:
            hsList = pm.ls(opmTxt, r=True)[0].getShapes()

        for hs in hsList:

            if isAll:
                topList = [self.getTopGroupFromHair(hs)]

            else:
                topList = self.getTopJointFromHair(hs, False)

            if not topList:
                pm.displayError('The top node not found.')
                return False

            else:
                dagList = pm.ls(topList, dag=True)
                allMixJntList = pm.ls('*mix*', type='joint', r=True)
                mixJntList = list(set(dagList) & set(allMixJntList))

                if not mixJntList:
                    continue

                ncls = hs.inputs(type='nucleus')[0]

                for mixJnt in mixJntList:

                    ancvList = mixJnt.inputs(type='animCurve')
                    pm.delete(ancvList)
                    simJnt = mixJnt.attr('radius').inputs()

                    if simJnt:
                        simJnt = simJnt[0]
                        simJnt.attr('radius') // mixJnt.attr('radius')
                        simJnt.attr('tx') >> mixJnt.attr('tx')
                        simJnt.attr('ty') >> mixJnt.attr('ty')
                        simJnt.attr('tz') >> mixJnt.attr('tz')
                        simJnt.attr('rx') >> mixJnt.attr('rx')
                        simJnt.attr('ry') >> mixJnt.attr('ry')
                        simJnt.attr('rz') >> mixJnt.attr('rz')

                ncls.attr('enable').set(True)

                pm.displayInfo('Successfully unbaked.')
Ejemplo n.º 20
0
    def getJointChainList(self, top):

        selList = pm.selected()
        pm.select(top, hi=True)
        chainList = pm.selected(type='joint')
        pm.select(selList, r=True)

        for chain in chainList:
            if len(chain.getChildren()) > 1:
                pm.displayError('%s has more than one child.' % chain)
                return False

        return chainList
Ejemplo n.º 21
0
def initializePlugin(plugin):
    vendor = "AJ"
    version = "b.1.0.0"

    plugin_fn = ommpx.MFnPlugin(plugin, vendor, version)

    try:
        plugin_fn.registerNode(CarpetRoll.TYPE_NAME, CarpetRoll.TYPE_ID,
                               CarpetRoll.creator, CarpetRoll.initialize,
                               ommpx.MPxNode.kDeformerNode)
    except:
        pm.displayError("Failed to register node {0}".format(
            CarpetRoll.TYPE_NAME))
Ejemplo n.º 22
0
    def conditionBranch(self):

        self.selList = pm.selected(type='joint')
        self.topName = 'hairSystem'

        if not self.selList:
            pm.displayError('Select joints.')
            return False

        if pm.ls(type='hairSystem'):
            self.dialog(self.selList[0])
        else:
            self.makeJointHair(self.selList[0], None)
Ejemplo n.º 23
0
    def export_pose(self):
        pose_manager = sdk_corrective.SDKCorrectiveManager()
        # Verify component selection
        if self.components_list.list.currentItem():
            current_component = self.components_list.list.currentItem().data(1)
        else:
            pm.displayError("Select a component to export pose for.")
            return
        if not isinstance(current_component, luna_rig.components.CorrectiveComponent):
            pm.displayError("Invalid component selection, must be of type: {0}".format(luna_rig.components.CorrectiveComponent))
            return

        ctl_filter = [item.data(0) for item in self.controls_list.list.selectedItems()]
        pose_manager.export_pose(current_component, self.pose_name_field.text(), self.driver_field.text(), control_filter_list=ctl_filter)
Ejemplo n.º 24
0
    def create(self):
        if self.name == '':
            pm.displayError('No name specified for creating the controller')
            return

        if 'circle' in self.visual:
            self.circle_ctrl()
        elif self.visual == 'box':
            self.box_ctrl()
        elif self.visual == 'square':
            self.square_ctrl()
        elif self.visual == 'joint':
            self.joint_ctrl()

        pm.addAttr(self.ctrl, ln="anim_ctrl", dt="string", k=0)
        self.ctrl.attr('anim_ctrl').set('body')
Ejemplo n.º 25
0
    def getAttribsDictFromSelectedHairNode(self):
        # TODO: create a dict from Selected Hair Node
        attibDict = {}
        index = self.hairNodesListView.currentIndex()
        selectedItem = self.hairNodesListModel.data(index, QtCore.Qt.EditRole)
        if not selectedItem:
            pmcore.displayError("You must select a item in the hair node list.")
            return

        for attrib in hairAttribNameList:
            attribValue = cmds.getAttr(selectedItem + "." + attrib)
            attibDict[attrib] = attribValue

#        print(dict)
        return attibDict
        pass
Ejemplo n.º 26
0
def openScene(sScenePath, **kwargs):

    bAddToRecent = kwargs.pop("addToRecent", False)

    if kwargs.pop("noFileCheck", True):
        pmu.putEnv("DAVOS_FILE_CHECK", "")

    bFail = kwargs.pop("fail", True)

    res = None
    try:
        res = pm.openFile(sScenePath, **kwargs)
    except RuntimeError, e:
        if bFail:
            raise
        else:
            pm.displayError(toStr(e.message))
Ejemplo n.º 27
0
 def set_driver(self):
     selection = pm.selected()
     # Get valid selection
     if not selection:
         selection = self.controls_list.list.selectedItems()
     if not selection:
         pm.displayWarning(
             "Select control in the scene or from controls list.")
         return
     selection = selection[-1]
     # Get controls transform if list selection
     if isinstance(selection, QtWidgets.QListWidgetItem):
         selection = selection.data(1).transform
     if luna_rig.Control.is_control(selection):
         self.driver_field.line_edit.setText(selection.name())
     else:
         pm.displayError("{0} is not a valid control.".format(selection))
Ejemplo n.º 28
0
def openScene(sScenePath, **kwargs):

    bAddToRecent = kwargs.pop("addToRecent", False)

    if kwargs.pop("noFileCheck", True):
        pmu.putEnv("DAVOS_FILE_CHECK", "")

    bFail = kwargs.pop("fail", True)

    res = None
    try:
        res = pm.openFile(sScenePath, **kwargs)
    except RuntimeError, e:
        if bFail:
            raise
        else:
            pm.displayError(toStr(e.message))
Ejemplo n.º 29
0
def inspect_settings(tabIdx=0, *args):
    """Open the component or root setting UI.

    Args:
        tabIdx (int, optional): Tab index to be open when open settings
        *args: None

    Returns:
        None: None if nothing is selected
    """
    oSel = pm.selected()
    if oSel:
        root = oSel[0]
    else:
        pm.displayWarning("please select one object from the componenet guide")
        return

    comp_type = False
    guide_root = False
    while root:
        if pm.attributeQuery("comp_type", node=root, ex=True):
            comp_type = root.attr("comp_type").get()
            break
        elif pm.attributeQuery("ismodel", node=root, ex=True):
            guide_root = root
            break
        root = root.getParent()
        pm.select(root)

    if comp_type:
        guide = shifter.importComponentGuide(comp_type)
        wind = pyqt.showDialog(guide.componentSettings, dockable=True)
        wind.tabs.setCurrentIndex(tabIdx)
        return wind

    elif guide_root:
        module_name = "mgear.shifter.guide"
        level = -1 if sys.version_info < (3, 3) else 0
        guide = __import__(module_name, globals(), locals(), ["*"], level)
        wind = pyqt.showDialog(guide.guideSettings, dockable=True)
        wind.tabs.setCurrentIndex(tabIdx)
        return wind

    else:
        pm.displayError("The selected object is not part of component guide")
Ejemplo n.º 30
0
def selectObjectInUserRootPivot(*args):
    """Selects the object under the group transform contrapart of a user pivot

    Args:
        *args: Maya dummy

    Returns:
        list of dagNode: The objects under the user pivot group
    """
    oSel = pm.selected()[0]
    try:
        pgrp = pm.PyNode(oSel.name().split('_')[0] + "_" + PGROUP_EXTENSION)
        objList = pgrp.listRelatives(ad=True, type="transform")
        pm.select(objList)
    except TypeError:
        pm.displayError("The selected pivot dont have the group contrapart."
                        " Review your rig structure")
        return False
Ejemplo n.º 31
0
def skinCopy(sourceMesh=None, targetMesh=None, *args):
    if not sourceMesh or not targetMesh:
        if len(pm.selected()) >= 2:
            sourceMesh = pm.selected()[-1]
            targetMeshes = pm.selected()[:-1]
        else:
            pm.displayWarning("Please select target mesh/meshes and source "
                              "mesh with skinCluster.")
            return
    else:
        targetMeshes = [targetMesh]

        # we check this here, because if not need to check when we work
        # base on selection.
        if isinstance(sourceMesh, basestring):
            sourceMesh = pm.PyNode(sourceMesh)

    for targetMesh in targetMeshes:
        if isinstance(targetMesh, basestring):
            sourceMesh = pm.PyNode(targetMesh)

        ss = getSkinCluster(sourceMesh)

        if ss:
            skinMethod = ss.skinningMethod.get()
            oDef = pm.skinCluster(sourceMesh, query=True, influence=True)
            # strip | from longName, or skinCluster command may fail.
            skinName = targetMesh.name().replace('|','') + "_SkinCluster"
            skinCluster = pm.skinCluster(oDef,
                                         targetMesh,
                                         tsb=True,
                                         nw=1,
                                         n=targetMesh.name() + "_SkinCluster")
            pm.copySkinWeights(sourceSkin=ss.stripNamespace(),
                               destinationSkin=skinCluster.name(),
                               noMirror=True,
                               influenceAssociation="oneToOne",
                               smooth=True,
                               normalize=True)
            skinCluster.skinningMethod.set(skinMethod)
        else:
            errorMsg = "Source Mesh : {} doesn't have a skinCluster."
            pm.displayError(errorMsg.format(sourceMesh.name()))
Ejemplo n.º 32
0
def addToUserPivot(*args):
    """Add the selected objects to a user pivot.

    First select the objects and last the pivot

    Args:
        *args: Maya dummy

    Returns:
        None: None
    """
    oSel = pm.selected()[:-1]
    pivot = pm.selected()[-1]
    try:
        pgrp = pm.PyNode(pivot.name().split('_')[0] + "_" + PGROUP_EXTENSION)
        pm.parent(oSel, pgrp)
    except TypeError:
        pm.displayError("The selected pivot dont have the group contrapart. "
                        "Review your rig structure")
        return False
Ejemplo n.º 33
0
    def get_component_list(self):
        comp_list = []
        compDir = shifter.getComponentDirectories()
        trackLoadComponent = []
        for path, comps in compDir.items():
            pm.progressWindow(title='Loading Components',
                              progress=0,
                              max=len(comps))
            for comp_name in comps:
                pm.progressWindow(e=True,
                                  step=1,
                                  status='\nLoading: %s' % comp_name)
                if comp_name == "__init__.py":
                    continue
                elif comp_name in trackLoadComponent:
                    pm.displayWarning(
                        "Custom component name: %s, already in default "
                        "components. Names should be unique. This component is"
                        " not loaded" % comp_name)
                    continue
                else:
                    trackLoadComponent.append(comp_name)

                if not os.path.exists(
                        os.path.join(path, comp_name, "__init__.py")):
                    continue
                try:
                    module = shifter.importComponentGuide(comp_name)
                    if PY2:
                        reload(module)
                    else:
                        importlib.reload(module)
                    comp_list.append(module.TYPE)
                except Exception as e:
                    pm.displayWarning(
                        "{} can't be load. Error at import".format(comp_name))
                    pm.displayError(e)
                    pm.displayError(traceback.format_exc())

        pm.progressWindow(e=True, endProgress=True)
        return comp_list
Ejemplo n.º 34
0
    def updateTabs(self):

        self.tabs.clear()

        currentModelName = self.model_list.currentText()
        currentModels = pm.ls(currentModelName)
        if not currentModels:
            return

        tab_names = currentModels[0].getAttr("synoptic").split(",")

        max_h = None
        max_w = None
        for i, tabName in enumerate(tab_names):
            try:
                if tabName:
                    tab, h, w = self.instantiateTab(tabName, currentModels[0])
                    max_h = h if max_h < h else max_h
                    max_w = w if max_w < w else max_w

                    self.tabs.insertTab(i, tab, tabName)

                else:
                    mes = "No synoptic tabs for %s" % \
                          self.model_list.currentText()

                    pm.displayWarning(mes)

            except Exception as e:
                import traceback
                traceback.print_exc()

                mes = "Synoptic tab: %s Loading fail {0}\n{1}".format(
                    tabName, e)

                pm.displayError(mes)

        max_h = max_h or self.default_height
        max_w = max_w or self.default_width
        header_space = 45
        self.resize(max_w + self.margin, max_h + self.margin + header_space)
Ejemplo n.º 35
0
    def newTweak(self):
        name = self.stUIInst.name_lineEdit.text()
        if not name:
            pm.displayWarning("please define the name before create "
                              "the softTweak.")
            return
        grp = self.stUIInst.ctlGrp_lineEdit.text()
        parent = self.stUIInst.parent_lineEdit.text()
        if parent:
            try:
                p = pm.PyNode(parent)
                trans = p.getMatrix(worldSpace=True)

            except pm.MayaNodeError:
                pm.displayWarning("{} is not a valid parent or doesn't "
                                  "exist".format(parent))
                return
        else:
            trans = datatypes.Matrix()
        try:
            oSel = [
                x for x in pm.selected()
                if x.getShape().type() in ["mesh", "nurbsSurface"]
            ]
        except pm.MayaNodeError:
            pm.displayError("Some objects on the current selection are "
                            "not valid. Please review the selection")
            return

        is_asset, nameExt, size = self._getIsAssetNameExtSize()
        createSoftTweak(name,
                        targets=oSel,
                        parent=parent,
                        t=trans,
                        grp=grp,
                        size=size,
                        nameExt=nameExt,
                        is_asset=is_asset)
        self._refreshList()
        pm.select(oSel, r=True)
Ejemplo n.º 36
0
    def doIt(*args, **kwargs):

        bUnload = kwargs.pop("unloadBefore", False)
        bAllIfNoSel = kwargs.pop("allIfNoSelection", False)
        sProcessLabel = kwargs.pop("processLabel", "Process")
        bSelMode = kwargs.pop("selected", kwargs.pop("sl", True))
        bConfirm = kwargs.pop("confirm", True)

        bSelected = bSelMode
        if bSelMode and bAllIfNoSel:
            if not mc.ls(sl=True):
                bSelected = False

        oFileRefList = listReferences(sl=bSelected, **kwargs)

        if not oFileRefList:
            if bSelected:
                pm.displayError("No referenced objects selected !")
            else:
                pm.displayError("No referenced objects to {} !".format(sProcessLabel.lower()))
            return [], []

        if bSelMode:
            if bSelected:
                sConfirmText = sProcessLabel + " {} Selected References ?".format(len(oFileRefList))
                sRefNames = "  ".join(oFileRef.namespace for oFileRef in oFileRefList)
            else:
                sConfirmText = sProcessLabel + " All References ?"
                sRefNames = ""

            if bConfirm:
                sConfirmMsg = (sConfirmText + "\n\n" + sRefNames) if sRefNames else sConfirmText

                sConfirm = pm.confirmDialog(title="WARNING !", message=sConfirmMsg, button=["OK", "Cancel"])

                if sConfirm == "Cancel":
                    logMsg("Cancelled !", warning=True)
                    return [], []

        if bUnload:
            for oFileRef in oFileRefList:
                oFileRef.unload()

        try:
            resultList = []
            kwargs.update(processResults=resultList)
            for oFileRef in oFileRefList:
                func(oFileRef, *args, **kwargs)
        finally:
            if bUnload:
                for oFileRef in oFileRefList:
                    try:
                        oFileRef.load()
                    except Exception, e:
                        pm.displayError(e)
Ejemplo n.º 37
0
import itertools as itr

import pymel.core as pm
import pymel.util as pmu
import maya.cmds as mc

from pytd.util.logutils import logMsg
from pytd.util.fsutils import pathResolve
from pytd.util.sysutils import listForNone, argToTuple, toStr
from pytd.util.strutils import upperFirst
from pytaya.core.general import iterAttrsUsedAsFilename

try:
    pm.mel.source("exportAnimSharedOptions")
except pm.MelError as e:
    pm.displayError(toStr(e))

try:
    pm.mel.source("importAnimSharedOptions")
except pm.MelError as e:
    pm.displayError(toStr(e))

def importFile(sFilePath, **kwargs):

    if not isinstance(sFilePath, basestring):
        raise TypeError, 'Wrong type passed to file path argument: {0}'.format(type(sFilePath))

    if ("%" in sFilePath) or ("$" in sFilePath):
        sResolvedPath = pathResolve(sFilePath)
    else:
        sResolvedPath = sFilePath