def _collect_info():
    lines = []
    lines.append('Scene Info')
    lines.append('  Maya Scene: ' + pmc.sceneName())

    lines.append('Maya/Python Info')
    lines.append('  Maya Version: ' + pmc.about(version=True))
    lines.append('  Qt Version: ' + pmc.about(qtVersion=True))
    lines.append('  Maya64: ' + str(pmc.about(is64=True)))
    lines.append('  PyVersion: ' + sys.version)
    lines.append('  PyExe: ' + sys.executable)

    lines.append('Machine Info')
    lines.append('  OS: ' + pmc.about(os=True))
    lines.append('  Node: ' + platform.node())
    lines.append('  OSRelease: ' + platform.release())
    lines.append('  OSVersion: ' + platform.version())
    lines.append('  Machine: ' + platform.machine())
    lines.append('  Processor: ' + platform.processor())

    lines.append('Environment Info')
    lines.append('  EnvVars')
    for k in sorted(os.environ.keys()):
        lines.append('    %s: %s' % (k, os.environ[k]))
    lines.append('  SysPath')
    for p in sys.path:
        lines.append('    ' + p)
    return lines
예제 #2
0
def prepareEnv():
    
    log.debug("prepareEnv")
    if os.environ.has_key("MTM_ENVDONE"):
        if os.environ['MTM_ENVDONE'] == "TRUE":
            log.debug("Env already initialized, skipping.")
            return True

    if not os.environ.has_key('H'):
        if pm.about(batch=True):
            log.error("Environment variable 'H' not set. Cannot find houdini. Exiting.")
        else:
            pm.displayWarning("Environment variable 'H' not set. Cannot find houdini. Exiting.")
        return False
    
    if not os.environ.has_key("MTM_HOME"):
        if pm.about(batch=True):
            log.error("Environment variable 'MTM_HOME' not set. Cannot find installdir. Exiting.")
        else:
            pm.displayWarning("Environment variable 'MTM_HOME' not set. Cannot find installdir. Exiting.")
        return False

    tmpdir = ""
    if not os.environ.has_key('TMP'):
        if not os.environ.has_key('tmp'):
            # TODO: correct tmpdir
            pass
        else:
            tmpdir = os.environ['tmp']
    else:
        tmpdir = os.environ['TMP']
    basePath = os.environ['H']

    os.environ['HTB'] = basePath + "/toolkit/bin"     
    username = getpass.getuser()

    currentDir = pm.workspace.path
    sn = realSceneName()
        
    os.environ['HB'] = basePath + "/bin" 
    os.environ['HD'] = basePath + "/demo" 
    os.environ['HFS'] = basePath
    os.environ['HH'] = basePath + "/houdini" 
    os.environ['HHC'] = basePath + "/houdini/config" 
    os.environ['HIP'] = currentDir + "/mantra/" + sn
    os.environ['HIPNAME'] = "untitled.hip" 
    os.environ['HOUDINI_TEMP_DIR'] = tmpdir + "/houdini" 
    os.environ['HSITE'] = basePath + "/site" 
    os.environ['HT'] = basePath + "/toolkit" 
    os.environ['HTB'] = basePath + "/toolkit/bin" 
    #os.environ['HOUDINI_OTL_PATH'] = os.environ['HOUDINI_OTL_PATH'] + ";" + currentDir + "/mantra/" + sn + "/shaders"
    os.environ['HOUDINI_VEX_PATH'] = currentDir + "/mantra/" + sn + "/shaders" + ";&;"
    path = os.environ['PATH']
    if not (basePath + "/bin") in path:
        os.environ['PATH'] = basePath + "/bin;" + path     
    os.environ['MTM_ENVDONE'] = "TRUE"     
    log.debug("prepareEnv done")

    return True
def registerArnoldRenderer():
    try:
        alreadyRegistered = pm.renderer('arnold', exists=True)
        if not alreadyRegistered:

            pm.evalDeferred(_register)

            # AE Templates
            # the following must occur even in batch mode because they contain calls to registerDefaultTranslator
            pm.evalDeferred(aeUtils.loadAETemplates)
            import rendererCallbacks
            rendererCallbacks.registerCallbacks()
            import mtoa.ui.ae.customShapeAttributes
            import mtoa.ui.ae.customShaderTemplates
            if not pm.about(batch=True):
                # Reload the AE Window if it has already been opened
                pm.evalDeferred(aeUtils.rebuildAE)
                # create the Arnold menu
                createArnoldMenu()

            # version specific overrides or additions
            _overridePythonScripts()
            _overrideMelScripts()

            # Add option box for file translator
            utils.pyToMelProc(exportass.arnoldAssOpts,
                              [('string', 'parent'), ('string', 'action'),
                               ('string', 'initialSettings'),
                               ('string', 'resultCallback')],
                              useName=True)

            # callbacks
            import mtoa.core as core
            core.installCallbacks()
            core.MTOA_GLOBALS['COMMAND_PORT'] = None

            import maya.cmds as cmds
            if not pm.about(batch=True):
                commandPortBase = 4700
                try:
                    commandPortBase = int(os.environ['MTOA_COMMAND_PORT'])
                except:
                    commandPortBase = 4700
                # opening a command port for different tools and maya batch progress messages
                for port in range(commandPortBase, commandPortBase + 100):
                    commandPortName = ':%i' % port
                    try:
                        cmds.commandPort(name=commandPortName)
                        core.MTOA_GLOBALS['COMMAND_PORT'] = port
                        break
                    except:
                        pass
            if not pm.about(batch=True):
                pm.evalDeferred(arnoldShelf.createArnoldShelf)
    except:
        import traceback
        traceback.print_exc(file=sys.__stderr__)
        raise
예제 #4
0
def registerArnoldRenderer():
    try:
        alreadyRegistered = pm.renderer('arnold', exists=True)
        if not alreadyRegistered:

            pm.evalDeferred(_register)

            # AE Templates
            # the following must occur even in batch mode because they contain calls to registerDefaultTranslator
            pm.evalDeferred(aeUtils.loadAETemplates)
            import rendererCallbacks
            rendererCallbacks.registerCallbacks()
            import mtoa.ui.ae.customShapeAttributes
            import mtoa.ui.ae.customShaderTemplates
            if not pm.about(batch=True):
                # Reload the AE Window if it has already been opened
                pm.evalDeferred(aeUtils.rebuildAE)
                # create the Arnold menu
                createArnoldMenu()

            # version specific overrides or additions
            _overridePythonScripts()
            _overrideMelScripts()

            # Add option box for file translator
            utils.pyToMelProc(exportass.arnoldAssOpts,
                              [('string', 'parent'), ('string', 'action'),
                               ('string', 'initialSettings'), ('string', 'resultCallback')],
                               useName=True)
            
            # callbacks
            import mtoa.core as core
            core.installCallbacks()
            core.MTOA_GLOBALS['COMMAND_PORT'] = None

            import maya.cmds as cmds
            if not pm.about(batch=True):
                commandPortBase = 4700
                try:
                    commandPortBase = int(os.environ['MTOA_COMMAND_PORT'])
                except:
                    commandPortBase = 4700
                # opening a command port for different tools and maya batch progress messages
                for port in range(commandPortBase, commandPortBase + 100):
                    commandPortName = ':%i' % port
                    try:
                        cmds.commandPort(name=commandPortName)
                        core.MTOA_GLOBALS['COMMAND_PORT'] = port
                        break
                    except:
                        pass
            if not pm.about(batch=True):
                pm.evalDeferred(arnoldShelf.createArnoldShelf)
    except:
        import traceback
        traceback.print_exc(file=sys.__stderr__)
        raise
예제 #5
0
def _get_version_dirname():
    version = pm.about(version=True)

    version = version.split(" ")[0]
    version_dir = version
    if pm.about(is64=True):
        version_dir = "{0}-x64".format(version)

    return version_dir
예제 #6
0
def ar_displayDialogue(status, message, detailMessage=None):
    """
    create qt QMessageBox according to status.
    :param status: string
    :param message: string
    :param detailMessage: string
    :return: None
    """
    # exit if this function run in batch mode.
    if pm.about(batch=True):
        return False
    # set icon according to status mode.
    if status == 'warning':
        statusIcon = QtGui.QMessageBox.Warning
    elif status == 'error':
        statusIcon = QtGui.QMessageBox.Critical
    else:
        statusIcon = QtGui.QMessageBox.NoIcon
    # create QMessageBox.
    msgBox = QtGui.QMessageBox(ar_mayaMainWindow())
    msgBox.setIcon(statusIcon)
    msgBox.setText(status)
    msgBox.setInformativeText(message)
    msgBox.setWindowTitle(status)
    # set additional text.
    if detailMessage:
        msgBox.setDetailedText("The details are as follows:\n" + detailMessage)
    else:
        msgBox.setDetailedText("The details are as follows:")
    msgBox.setStandardButtons(QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
    msgBox.exec_()
예제 #7
0
def ar_displayMessage(status, message):
    """
    display message with different color in maya according to status.
    :param status: string
    :param message: string
    :return: message
    """
    # exit if this function run in batch mode.
    if pm.about(batch=True):
        return False
    # Base color    Text Color.
    statusColors = {
        'error': ((255, 40, 20), (0, 0, 0)),
        'warning': ((255, 177, 86), (0, 0, 0)),
        'success': ((140, 230, 140), (0, 0, 0))
    }
    # commandLine1 will be unique in maya in all cases.
    commandLinePtr = omui.MQtUtil.findControl('commandLine1')
    commandLine = wrapInstance(long(commandLinePtr), QtGui.QWidget)
    # get result Line.
    resultLine = commandLine.findChildren(QtGui.QLineEdit)[0]
    palette = resultLine.palette()
    palette.setBrush(QtGui.QPalette.Base,
                     QtGui.QColor(*statusColors[status][0]))
    palette.setColor(QtGui.QPalette.Text,
                     QtGui.QColor(*statusColors[status][1]))
    resultLine.setPalette(palette)
    resultLine.setText('[ ' + status + ' ] ' + message)
    pm.refresh()
예제 #8
0
def show( reset=False ):
    if pm.about(batch=True):
        print 'menu not available in batch mode.'
        return
    else:
        # -- get things ready for building the menu

        menu_name = "Impress Example"
        pm.setParent( MAYA_WINDOW )

        if pm.menu( menu_name, exists=True ):
            if reset:
                pm.deleteUI( menu_name )
            else:
                main_menu = pm.menu( menu_name, edit=True )
                return main_menu

        if not pm.menu( menu_name, exists=True ):
            main_menu = pm.menu( menu_name, tearOff=True )

        # -- build the menu

        with  main_menu:
            with pm.subMenuItem( 'Display', aob=True, tearOff=True ):
                ui.commandMenuItem( performExample )
예제 #9
0
    def _add_menu_item_internal(self, name, insert_sorted=False, *args, **kwargs):
        if 'optionBox' in kwargs:
            # Maya creates an option box by adding it as a separate menu item.  We do it
            # by passing optionBox=function when creating the menu item itself, since it
            # makes things simpler.
            option_box = kwargs['optionBox']
            del kwargs['optionBox']
        else:
            option_box = None

        # We always need a label, even for dynamic menu names, so we can tell where to
        # put the menu item when insert_sorted is true.
        assert 'label' in kwargs

        # Don't create menu items in batch mode.  It causes a warning.
        if pm.about(batch=True):
            return

        # In case this menu item has already been created, remove the old one.
        _delete_menu_item(name)

        if insert_sorted:
            assert 'insertAfter' not in kwargs
            kwargs['insertAfter'] = self._get_sorted_insertion_point(name=name, subMenu=kwargs.get('subMenu', False), parent=kwargs.get('parent'))

            # If insertAfter is '' then the insertion point is the beginning.  However, Maya prints
            # an incorrect warning if you say insertAfter='' and there are no items in the submenu,
            # so remove it in this case.
            if not pm.menu(kwargs.get('parent'), q=True, ia=True):
                del kwargs['insertAfter']

        elif 'insertAfter' in kwargs and kwargs['insertAfter'] is None:
            # insertAfter=None causes the menu item to be added at the beginning.  We want
            # that to add at the end, so remove the argument.  This way, if a search for
            # a menu insertion point fails and returns None, we put things at the end (putting
            # them at the beginning is obnoxious).
            del kwargs['insertAfter']

        item = pm.menuItem(name, *args, **kwargs)

        # Add the option box, if any.
        if option_box is not None:
            option_box_name = name + 'Options'
            _delete_menu_item(option_box_name)

            # Maya option boxes are weird: they're regular menu items, and they appear over the
            # previous menu item, so we need to add if after the above menu item.
            item_name = item.split('|')[-1]
            name = pm.menuItem(optionBox=True, command=option_box, insertAfter=item_name, parent=kwargs['parent'])
            self.menu_items.add(name)

        # self.menu_items is a list of items that we need to remove.  Don't add submenus
        # to this list.  Rather than deleting them directly when we're unloaded, we leave
        # them alone and use the empty menu cleanup down below to remove them, so if two
        # plugins create the same submenu and one is unloaded, it doesn't remove the other
        # plugin's menu with it.
        if not kwargs.get('subMenu'):
            self.menu_items.add(item)
        return item
예제 #10
0
 def renderProcedure(self, width, height, doShadows, doGlow, camera, options):
     self.createGlobalsNode()
     self.preRenderProcedure()
     self.setImageName()
     if pm.about(batch=True):
         pm.appleseedMaya()
     else:
         pm.appleseedMaya(width=width, height=height, camera=camera)
예제 #11
0
    def remove_menu_items(self):
        """
        Remove this menu's menu items.
        """
        if pm.about(batch=True):
            return

        self._remove_menu_items()
예제 #12
0
    def add_menu_items(self):
        """
        Add this menu's menu items.
        """
        # Don't try to register menus when in batch mode.  Maya should just ignore it, but
        # for some reason it prints errors.
        if pm.about(batch=True):
            return

        self._add_menu_items()
예제 #13
0
def initRenderer():
    try:
        theRenderer().registerRenderer()
        if not pm.about(batch=True):
            loadAETemplates()
            theRenderer().createRendererMenu()
        loadPlugins()
    except:
        traceback.print_exc(file=sys.__stderr__)
        log.error("Init renderer appleseed FAILED")
예제 #14
0
파일: aovs.py 프로젝트: Quazo/breakingpoint
def installCallbacks():
    _sgAliasesCallbacks = callbacks.SceneLoadCallbackQueue()
    _sgAliasesCallbacks.addCallback(createAliases, passArgs=True)
    callbacks.addNodeAddedCallback(_sgAliasesCallbacks, 'shadingEngine',
                                   applyToExisting=True, apiArgs=False)
    
    if not pm.about(batch=True):
        callbacks.addAttributeChangedCallback(_aovOptionsChangedCallbacks, 'aiOptions', 'aovList',
                                  context=pm.api.MNodeMessage.kConnectionMade | pm.api.MNodeMessage.kConnectionBroken,
                                  applyToExisting=True)
예제 #15
0
def loadPlugins():
    try:
        log.debug("Loading Appleseed maya plugins")
        version = pm.about(v=True).split(" ")[0]
        pluginName = "appleseedTools_maya{0}".format(version)
        log.debug("Trying to load appleseedTools: {0}".format(pluginName))
        if not pm.pluginInfo(pluginName, query=True, loaded=True):
            pm.loadPlugin(pluginName)
    except:
        traceback.print_exc(file=sys.__stderr__)
        log.error("Load plugins Appleseed FAILED")
예제 #16
0
 def renderProcedure(self, width, height, doShadows, doGlow, camera, options):
     log.debug("renderProcedure")
     self.createGlobalsNode()    
     self.preRenderProcedure()
     self.setImageName()
     
     if pm.about(batch=True):
         pm.mayatokray()
     else:
         pm.mayatokray(width=width, height=height, camera=camera)
         
     self.postRenderProcedure()
예제 #17
0
 def renderProcedure(self, width, height, doShadows, doGlow, camera, options):
     log.debug("renderProcedure")
     self.removeLogFile()
     print "renderProcedure", width, height, doShadows, doGlow, camera, options
     self.createGlobalsNode()    
     self.preRenderProcedure()
     self.setImageName()
     
     if pm.about(batch=True):
         pm.mayatoappleseed()
     else:
         pm.mayatoappleseed(width=width, height=height, camera=camera)
예제 #18
0
def initRenderer():
    """call this function during after initialisation of the mantra render plugin.
    From within the plugin.
    """
    log.debug("Init Mantra Renderer script.")
    
    #unloadAndUnregister()
    melGlobals()
    registerRenderer()
    
    if not pm.about(batch=True):
        mantraMainMenu()
예제 #19
0
def gui_test():
    '''
    This function will run the function that has the correct interface
    for the desired interface.
    '''
    os_type = pm.about(os=True)

    if os_type == 'nt':
        gui_win()
    elif os_type == 'mac':
        gui_osx()
    else:
        gui_linux()
예제 #20
0
def gui_test():
    '''
    This function will run the function that has the correct interface
    for the desired interface.
    '''
    os_type = pm.about(os=True)
    
    if os_type == 'nt':
        gui_win()
    elif os_type == 'mac':
        gui_osx()
    else:
        gui_linux()
예제 #21
0
파일: core.py 프로젝트: Quazo/breakingpoint
def installCallbacks():
    """
    install all callbacks
    """
    # certain scenes fail to execute this callback:
    #callbacks.addAttributeChangedCallback(_rendererChanged, 'renderGlobals', 'currentRenderer')
    if pm.about(batch=True):
        callbacks.addAttributeChangedCallback(_rendererChanged, 'renderGlobals', 'currentRenderer')
    else:
        pm.scriptJob(attributeChange=['defaultRenderGlobals.currentRenderer', _rendererChanged] )
        pm.scriptJob(event =['SceneOpened', _rendererChanged] )

    import mtoa.aovs as aovs
    aovs.installCallbacks()
예제 #22
0
def installCallbacks():
    _sgAliasesCallbacks = callbacks.SceneLoadCallbackQueue()
    _sgAliasesCallbacks.addCallback(createAliases, passArgs=True)
    callbacks.addNodeAddedCallback(_sgAliasesCallbacks,
                                   'shadingEngine',
                                   applyToExisting=True,
                                   apiArgs=False)

    if not pm.about(batch=True):
        callbacks.addAttributeChangedCallback(
            _aovOptionsChangedCallbacks,
            'aiOptions',
            'aovList',
            context=pm.api.MNodeMessage.kConnectionMade
            | pm.api.MNodeMessage.kConnectionBroken,
            applyToExisting=True)
예제 #23
0
 def create_widgets(self):
     self.control_field = shared_widgets.StringFieldWidget(
         "Control:", button_text="Set")
     self.space_obj_field = shared_widgets.StringFieldWidget(
         "Space object:", button_text="Set")
     self.space_name_field = shared_widgets.StringFieldWidget("Name:",
                                                              button=False)
     self.add_space_button = QtWidgets.QPushButton("Add")
     # Options
     self.use_offset_matrix_checkbox = QtWidgets.QCheckBox(
         'Use offset matrix')
     if int(pm.about(version=True)) < 2020:
         self.use_offset_matrix_checkbox.setChecked(False)
         self.use_offset_matrix_checkbox.setEnabled(False)
         self.use_offset_matrix_checkbox.setText(
             'Use offset matrix (Maya 2020+)')
예제 #24
0
 def renderProcedure(self, width, height, doShadows, doGlow, camera, options):
     log.debug("renderProcedure")
     self.removeLogFile()
     print "renderProcedure", width, height, doShadows, doGlow, camera, options
     self.createGlobalsNode()    
     self.preRenderProcedure()
     self.setImageName()
     
     if pm.about(batch=True):
         pm.mayatoCorona()
     else:
         pm.mayatoCorona(width=width, height=height, camera=camera)
         
     if not self.ipr_isrunning:
         self.showLogFile()
     self.postRenderProcedure()
예제 #25
0
import display
import dynamics
import modeling
import materials
import modify
import poses
import rigging
import scene
import menu
import skinning

import config


from pymel.core import about, evalDeferred, mel


try:
    _initialized
except:
    _initialized = False

if not _initialized:
    _initialized = True

    mel.python( 'import kinetifex' )

    if not about( batch=True ):
        evalDeferred( display._initHudElements )

예제 #26
0
파일: afanasy.py 프로젝트: eoyilmaz/anima
    def launch(self, *args, **kwargs):
        """launch renderer command
        """
        # do nothing if there is no window (called externally)
        if not self.window:
            return

        # warn the user about the ignore settings
        try:
            dAO = pm.PyNode('defaultArnoldRenderOptions')

            ignore_attrs = [
                'ignoreSubdivision',
                'ignoreDisplacement',
                'ignoreBump',
                'ignoreMotionBlur'
            ]

            attr_values = [
                (attr, dAO.getAttr(attr))
                for attr in ignore_attrs
                if dAO.getAttr(attr) is True
            ]

            if any(attr_values):
                msg_text = '<br>'.join(
                    map(
                        lambda x: '%s: %s' % (x[0], x[1]),
                        attr_values
                    )
                )

                response = pm.confirmDialog(
                    title='Ignore These Settings?',
                    message='You have ignored:<br><br>%s<br><br><b>Is that ok?</b>' % msg_text,
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No'
                )

                if response == 'No':
                    return
        except pm.MayaNodeError:
            # no Arnold
            pass

        # check if rendering with persp camera
        try:
            wrong_camera_names = [
                'perspShape',
                'topShape',
                'sideShape',
                'fontShape',

                'persp1Shape',
                'perspShape1',
            ]
            renderable_cameras = [node for node in pm.ls(type='camera') if node.getAttr('renderable')]
            if any(map(lambda x: x.name() in wrong_camera_names, renderable_cameras)):
                response = pm.confirmDialog(
                    title='Rendering with Persp?',
                    message='You are rendering with <b>Persp Camera<b><br><br>Is that ok?</b>',
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No'
                )

                if response == 'No':
                    return

            if len(renderable_cameras) > 1:
                response = pm.confirmDialog(
                    title='Rendering more than one Camera?',
                    message='You are rendering <b>more than one camera<b><br><br>Is that ok?</b>',
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No'
                )

                if response == 'No':
                    return
            elif len(renderable_cameras) == 0:
                pm.confirmDialog(
                    title='No <b>Renderable</b> camera!!!',
                    message='There is no <b>renderable camera<b>!!!',
                    button=['Ok'],
                    defaultButton='Ok',
                    cancelButton='Ok',
                    dismissString='Ok'
                )
                return

        except pm.MayaNodeError:
            # no default render globals node
            pass

        drg = pm.PyNode('defaultRenderGlobals')
        render_engine = drg.getAttr('currentRenderer')
        # RENDERER SPECIFIC CHECKS

        if render_engine == 'redshift':
            # if the renderer is RedShift
            # check if unifiedDisableDivision is 1 which will take too much time
            # to render
            dro = pm.PyNode('redshiftOptions')
            if dro.unifiedDisableDivision.get() == 1:
                response = pm.confirmDialog(
                    title="Enabled **Don't Automatically Reduce Samples of Other Effects**",
                    message='It is not allowed to render with the following option is enabled:<br>'
                            '<br>'
                            "Don't Automatically Reduce Samples of Other Effects: Enabled<br>"
                            "<br>"
                            "Please DISABLE it!",
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            # Check dome light backgrounds
            domes_to_fix = []
            rs_domes = pm.ls(type='RedshiftDomeLight')
            if rs_domes:
                for rs_dome in rs_domes:
                    if rs_dome.getAttr('background_enable') == 1 \
                       or rs_dome.getAttr('backPlateEnabled') == 1:
                        domes_to_fix.append(rs_dome.name())

            if domes_to_fix:
                message = 'Some DomeLights have <b>BackGround Render ' \
                          'Enabled</b>:' \
                          '<br><br>%s<br><br>' \
                          'Are you Sure?' % '<br>'.join(domes_to_fix)

                response = pm.confirmDialog(
                    title='Dome Lights with Background Enabled?',
                    message=message,
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No'
                )
                if response == 'No':
                    return

            # abort on license fail
            dro.abortOnLicenseFail.set(1)

        elif render_engine == 'arnold':
            # check if the samples are too high
            dAO = pm.PyNode('defaultArnoldRenderOptions')

            aa_samples = dAO.AASamples.get()
            diff_samples = dAO.GIDiffuseSamples.get()
            try:
                glossy_samples = dAO.GIGlossySamples.get()
            except AttributeError:
                glossy_samples = dAO.GISpecularSamples.get()
            if int(pm.about(v=1)) >= 2017:
                sss_samples = dAO.GISssSamples.get()
            else:
                sss_samples = dAO.sssBssrdfSamples.get()

            total_diff_samples = aa_samples**2 * diff_samples**2
            total_glossy_samples = aa_samples**2 * glossy_samples**2
            total_sss_samples = aa_samples**2 * sss_samples**2

            max_allowed_diff_samples = 225
            max_allowed_glossy_samples = 100
            max_allowed_sss_samples = 800

            if total_diff_samples > max_allowed_diff_samples:
                pm.confirmDialog(
                    title="Too Much Diffuse Samples!!!",
                    message='You are using too much DIFFUSE SAMPLES (>%s)<br>'
                            '<br>'
                            'Please either reduce AA samples of Diffuse '
                            'Samples!!!' % max_allowed_diff_samples,
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            if total_glossy_samples > max_allowed_glossy_samples:
                pm.confirmDialog(
                    title="Too Much Glossy Samples!!!",
                    message='You are using too much GLOSSY SAMPLES (>%s)<br>'
                            '<br>'
                            'Please either reduce AA samples of Glossy '
                            'Samples!!!' % max_allowed_glossy_samples,
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            if total_sss_samples > max_allowed_sss_samples:
                pm.confirmDialog(
                    title="Too Much SSS Samples!!!",
                    message='You are using too much SSS SAMPLES (>%s)<br>'
                            '<br>'
                            'Please either reduce AA samples of SSS '
                            'Samples!!!' % max_allowed_sss_samples,
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            # check Light Samples
            # check point lights with zero radius but more than one samples
            all_point_lights = pm.ls(type='pointLight')
            ridiculous_point_lights = []
            for point_light in all_point_lights:
                if point_light.aiRadius.get() < 0.1 and point_light.aiSamples.get() > 1:
                    ridiculous_point_lights.append(point_light)

            if ridiculous_point_lights:
                pm.confirmDialog(
                    title="Unnecessary Samples on Point Lights!!!",
                    message='You are using too much SAMPLES (>1)<br>'
                            '<br>'
                            'on <b>Point lights with zero radius</b><br>'
                            '<br>'
                            'Please reduce the samples to 1',
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            # Check area lights with more than 2 samples
            all_area_lights = pm.ls(type=['areaLight', 'aiAreaLight'])
            ridiculous_area_lights = []
            for area_light in all_area_lights:
                if area_light.aiSamples.get() > 2:
                    ridiculous_area_lights.append(area_light)

            if ridiculous_area_lights:
                pm.confirmDialog(
                    title="Unnecessary Samples on Area Lights!!!",
                    message='You are using too much SAMPLES (>2) on<br>'
                            '<br>'
                            '<b>Area Lights</b><br>'
                            '<br>'
                            'Please reduce the samples to 2',
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            # Check directional lights with angle == 0 and samples > 1
            all_directional_lights = pm.ls(type='directionalLight')
            ridiculous_directional_lights = []
            dir_sample_attr_name = 'aiSamples'
            # if pm.about(v=1) == "2014":
            #     dir_sample_attr_name = 'aiSamples'

            for directional_light in all_directional_lights:
                if directional_light.aiAngle.get() == 0 and directional_light.attr(dir_sample_attr_name).get() > 1:
                    ridiculous_directional_lights.append(directional_light)

            if ridiculous_directional_lights:
                pm.confirmDialog(
                    title="Unnecessary Samples on Directional Lights!!!",
                    message='You are using too much SAMPLES (>1) on <br>'
                            '<br>'
                            '<b>Directional lights with zero angle</b><br>'
                            '<br>'
                            'Please reduce the samples to 1',
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

        # get values
        start_frame = pm.intField('cgru_afanasy__start_frame', q=1, v=1)
        end_frame = pm.intField('cgru_afanasy__end_frame', q=1, v=1)
        frames_per_task = \
            pm.intField('cgru_afanasy__frames_per_task', q=1, v=1)
        by_frame = pm.intField('cgru_afanasy__by_frame', q=1, v=1)
        hosts_mask = pm.textField('cgru_afanasy__hosts_mask', q=1, text=True)
        hosts_exclude = pm.textField('cgru_afanasy__hosts_exclude', q=1, text=True)
        separate_layers = \
            pm.radioButtonGrp('cgru_afanasy__separate_layers', q=1, sl=1)
        pause = pm.checkBox('cgru_afanasy__paused', q=1, v=1)
        life_time = pm.intField('cgru_afanasy__life_time', q=1, v=1)
        annotation = pm.textField('cgru_afanasy__annotation', q=1, text=True)
        submit_multiple_times = pm.intField('cgru_afanasy__submit_multiple_times', q=1, v=1)
        errors_avoid_host = pm.intField('cgru_afanasy__errors_avoid_host', q=1, v=1)
        errors_retries = pm.intField('cgru_afanasy__errors_retries', q=1, v=1)
        errors_task_same_host = pm.intField('cgru_afanasy__errors_task_same_host', q=1, v=1)
        errors_forgive_time = pm.intField('cgru_afanasy__errors_forgive_time', q=1, v=1)

        # check values
        if start_frame > end_frame:
            temp = end_frame
            end_frame = start_frame
            start_frame = temp

        frames_per_task = max(1, frames_per_task)
        by_frame = max(1, by_frame)

        # store without quota sign
        hosts_mask = hosts_mask.replace('"', '')
        hosts_exclude = hosts_exclude.replace('"', '')

        # store field values
        pm.optionVar['cgru_afanasy__start_frame_ov'] = start_frame
        pm.optionVar['cgru_afanasy__end_frame_ov'] = end_frame
        pm.optionVar['cgru_afanasy__frames_per_task_ov'] = frames_per_task
        pm.optionVar['cgru_afanasy__by_frame_ov'] = by_frame
        pm.optionVar['cgru_afanasy__hosts_mask_ov'] = hosts_mask
        pm.optionVar['cgru_afanasy__hosts_exclude_ov'] = hosts_exclude
        pm.optionVar['cgru_afanasy__separate_layers_ov'] = separate_layers
        pm.optionVar['cgru_afanasy__life_time_ov'] = life_time
        pm.optionVar['cgru_afanasy__annotation_ov'] = annotation

        pm.optionVar['cgru_afanasy__submit_multiple_times_ov'] = submit_multiple_times
        pm.optionVar['cgru_afanasy__errors_avoid_host_ov'] = errors_avoid_host
        pm.optionVar['cgru_afanasy__errors_retries_ov'] = errors_retries
        pm.optionVar['cgru_afanasy__errors_task_same_host_ov'] = errors_task_same_host
        pm.optionVar['cgru_afanasy__errors_errors_forgive_time_ov'] = errors_forgive_time

        # get paths
        scene_name = pm.sceneName()
        datetime = '%s%s' % (
            time.strftime('%y%m%d-%H%M%S-'),
            str(time.time() - int(time.time()))[2:5]
        )

        filename = '%s.%s.mb' % (scene_name, datetime)

        project_path = pm.workspace(q=1, rootDirectory=1)

        # outputs = \
        #     pm.renderSettings(fullPath=1, firstImageName=1, lastImageName=1)

        # get output paths, set the RenderPass token to Beauty,
        # this will at least guarantee to get something
        outputs = \
            pm.renderSettings(
                fullPath=1, firstImageName=1, lastImageName=1,
                leaveUnmatchedTokens=1, customTokenString="RenderPass=Beauty"
            )

        # job_name = os.path.basename(scene_name)
        job_name = self.generate_job_name()

        logger.debug('%ss %se %sr' % (start_frame, end_frame, by_frame))
        logger.debug('scene                 = %s' % scene_name)
        logger.debug('file                  = %s' % filename)
        logger.debug('job_name              = %s' % job_name)
        logger.debug('project_path          = %s' % project_path)
        logger.debug('outputs               = %s' % outputs)
        logger.debug('annotation            = %s' % annotation)
        logger.debug('separate_layers       = %s' % separate_layers)
        logger.debug('errors_avoid_host     = %s' % errors_avoid_host)
        logger.debug('errors_retries        = %s' % errors_retries)
        logger.debug('errors_task_same_host = %s' % errors_task_same_host)
        logger.debug('errors_forgive_time   = %s' % errors_forgive_time)

        if pm.checkBox('cgru_afanasy__close', q=1, v=1):
            pm.deleteUI(self.window)

        stored_log_level = None
        if render_engine == 'arnold':
            # set the verbosity level to warning+info
            aro = pm.PyNode('defaultArnoldRenderOptions')
            stored_log_level = aro.getAttr('log_verbosity')
            aro.setAttr('log_verbosity', 2)
            # set output to console
            aro.setAttr("log_to_console", 1)
        elif render_engine == 'redshift':
            # set the verbosity level to detailed+info
            redshift = pm.PyNode('redshiftOptions')
            stored_log_level = redshift.logLevel.get()
            redshift.logLevel.set(2)

        # save file
        pm.saveAs(
            filename,
            force=1,
            type='mayaBinary'
        )

        # rename back to original name
        pm.renameFile(scene_name)

        # create the render command
        mrc = MayaRenderCommandBuilder(
            name=job_name,
            file_full_path=filename,
            render_engine=render_engine,
            project=project_path,
            by_frame=by_frame
        )

        # submit renders
        jobs = []
        blocks = []

        #
        # separate_layers:
        # 1 -> None  -> submit one job with a single block with all layers
        # 2 -> Block -> submit one job with multiple blocks
        # 3 -> Job   -> submit multiple jobs with a single block per layer
        #
        if separate_layers in [1, 2]:
            job = af.Job(job_name)
            jobs.append(job)

        if separate_layers in [2, 3]:
            # render each layer separately
            rlm = pm.PyNode('renderLayerManager')
            layers = [layer for layer in rlm.connections()
                      if layer.renderable.get()]

            for layer in layers:
                mrc_layer = copy.copy(mrc)
                layer_name = layer.name()
                mrc_layer.name = layer_name
                mrc_layer.render_layer = layer_name

                # create a new block for this layer
                block = af.Block(
                    layer_name,
                    renderer_to_block_type.get(render_engine, 'maya')
                )

                # Fix the output path for this layer
                # by replacing the "masterLayer" with the layer name
                # without rs_ at the beginning
                layer_outputs = outputs
                if layer_name != 'defaultRenderLayer':
                    layer_outputs[0] = outputs[0].replace(
                        'masterLayer',
                        layer_name.replace('rs_', '')
                    )
                    layer_outputs[1] = outputs[1].replace(
                        'masterLayer',
                        layer_name.replace('rs_', '')
                    )

                outputs_split = afcommon.patternFromDigits(
                    afcommon.patternFromStdC(
                        afcommon.patternFromPaths(
                            layer_outputs[0],
                            layer_outputs[1]
                        )
                    )
                ).split(';')

                block.setFiles(outputs_split)

                block.setNumeric(
                    start_frame, end_frame, frames_per_task, by_frame
                )
                command = mrc_layer.build_command()

                block.setErrorsAvoidHost(errors_avoid_host)
                block.setErrorsRetries(errors_retries)
                block.setErrorsTaskSameHost(errors_task_same_host)
                block.setErrorsForgiveTime(errors_forgive_time)

                block.setCommand(command)

                if separate_layers == 2:
                    blocks.append(block)
                else:
                    job = af.Job('%s - %s' % (job_name, layer_name))
                    # add blocks
                    job.blocks = [block]
                    jobs.append(job)

        else:
            # create only one block
            block = af.Block(
                'All Layers',
                renderer_to_block_type.get(render_engine, 'maya')
            )

            block.setFiles(
                afcommon.patternFromDigits(
                    afcommon.patternFromStdC(
                        afcommon.patternFromPaths(outputs[0], outputs[1])
                    )
                ).split(';')
            )
            block.setNumeric(
                start_frame, end_frame, frames_per_task, by_frame
            )
            command = mrc.build_command()
            block.setCommand(command)

            blocks.append(block)

        for job in jobs:
            job.setAnnotation(annotation)
            job.setFolder('input', os.path.dirname(filename))
            job.setFolder('output', os.path.dirname(outputs[0]))
            job.setHostsMask(hosts_mask)
            job.setHostsMaskExclude(hosts_exclude)
            if life_time > 0:
                job.setTimeLife(life_time * 3600)
            else:
                job.setTimeLife(240 * 3600)

            job.setCmdPost('deletefiles -s "%s"' % os.path.abspath(filename))
            if pause:
                job.offline()

            # add blocks
            if separate_layers in [1, 2]:
                job.blocks.extend(blocks)

            for i in range(submit_multiple_times):
                orig_job_name = job.data['name']
                job.setName('%s - %03i' % (orig_job_name, i + 1))
                status, data = job.send()

                # restore job name
                job.setName(orig_job_name)
                if not status:
                    pm.PopupError('Something went wrong!')

        # restore log level
        if render_engine == 'arnold':
            aro = pm.PyNode('defaultArnoldRenderOptions')
            aro.setAttr('log_verbosity', stored_log_level)
            # disable set output to console
            aro.setAttr("log_to_console", 0)
        elif render_engine == 'redshift':
            redshift = pm.PyNode('redshiftOptions')
            redshift.logLevel.set(stored_log_level)

            # disable abort on license fail
            redshift.abortOnLicenseFail.set(0)
예제 #27
0
파일: afanasy.py 프로젝트: sergeneren/anima
    def launch(self, *args, **kwargs):
        """launch renderer command
        """
        # do nothing if there is no window (called externally)
        if not self.window:
            return

        # warn the user about the ignore settings
        try:
            dAO = pm.PyNode('defaultArnoldRenderOptions')

            ignore_attrs = [
                'ignoreSubdivision',
                'ignoreDisplacement',
                'ignoreBump',
                'ignoreMotionBlur'
            ]

            attr_values = [
                (attr, dAO.getAttr(attr))
                for attr in ignore_attrs
                if dAO.getAttr(attr) is True
            ]

            if any(attr_values):
                msg_text = '<br>'.join(
                    map(
                        lambda x: '%s: %s' % (x[0], x[1]),
                        attr_values
                    )
                )

                response = pm.confirmDialog(
                    title='Ignore These Settings?',
                    message='You have ignored:<br><br>%s<br><br><b>Is that ok?</b>' % msg_text,
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No'
                )

                if response == 'No':
                    return
        except pm.MayaNodeError:
            # no Arnold
            pass

        # check if rendering with persp camera
        try:
            wrong_camera_names = [
                'perspShape',
                'topShape',
                'sideShape',
                'fontShape',

                'persp1Shape',
                'perspShape1',
            ]
            renderable_cameras = [node for node in pm.ls(type='camera') if node.getAttr('renderable')]
            if any(map(lambda x: x.name() in wrong_camera_names, renderable_cameras)):
                response = pm.confirmDialog(
                    title='Rendering with Persp?',
                    message='You are rendering with <b>Persp Camera<b><br><br>Is that ok?</b>',
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No'
                )

                if response == 'No':
                    return

            if len(renderable_cameras) > 1:
                response = pm.confirmDialog(
                    title='Rendering more than one Camera?',
                    message='You are rendering <b>more than one camera<b><br><br>Is that ok?</b>',
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No'
                )

                if response == 'No':
                    return
            elif len(renderable_cameras) == 0:
                pm.confirmDialog(
                    title='No <b>Renderable</b> camera!!!',
                    message='There is no <b>renderable camera<b>!!!',
                    button=['Ok'],
                    defaultButton='Ok',
                    cancelButton='Ok',
                    dismissString='Ok'
                )
                return

        except pm.MayaNodeError:
            # no default render globals node
            pass

        drg = pm.PyNode('defaultRenderGlobals')
        render_engine = drg.getAttr('currentRenderer')
        # RENDERER SPECIFIC CHECKS

        if render_engine == 'redshift':
            # if the renderer is RedShift
            # check if unifiedDisableDivision is 1 which will take too much time
            # to render
            dro = pm.PyNode('redshiftOptions')
            if dro.unifiedDisableDivision.get() == 1:
                response = pm.confirmDialog(
                    title="Enabled **Don't Automatically Reduce Samples of Other Effects**",
                    message='It is not allowed to render with the following option is enabled:<br>'
                            '<br>'
                            "Don't Automatically Reduce Samples of Other Effects: Enabled<br>"
                            "<br>"
                            "Please DISABLE it!",
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

        elif render_engine == 'arnold':
            # check if the samples are too high
            dAO = pm.PyNode('defaultArnoldRenderOptions')


            aa_samples = dAO.AASamples.get()
            diff_samples = dAO.GIDiffuseSamples.get()
            glossy_samples = dAO.GIGlossySamples.get()
            if int(pm.about(v=1)) >= 2017:
                sss_samples = dAO.GISssSamples.get()
            else:
                sss_samples = dAO.sssBssrdfSamples.get()

            total_diff_samples = aa_samples**2 * diff_samples**2
            total_glossy_samples = aa_samples**2 * glossy_samples**2
            total_sss_samples = aa_samples**2 * sss_samples**2

            max_allowed_diff_samples = 225
            max_allowed_glossy_samples = 100
            max_allowed_sss_samples = 450

            if total_diff_samples > max_allowed_diff_samples:
                pm.confirmDialog(
                    title="Too Much Diffuse Samples!!!",
                    message='You are using too much DIFFUSE SAMPLES (>%s)<br>'
                            '<br>'
                            'Please either reduce AA samples of Diffuse '
                            'Samples!!!' % max_allowed_diff_samples,
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            if total_glossy_samples > max_allowed_glossy_samples:
                pm.confirmDialog(
                    title="Too Much Glossy Samples!!!",
                    message='You are using too much GLOSSY SAMPLES (>%s)<br>'
                            '<br>'
                            'Please either reduce AA samples of Glossy '
                            'Samples!!!' % max_allowed_glossy_samples,
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            if total_sss_samples > max_allowed_sss_samples:
                pm.confirmDialog(
                    title="Too Much SSS Samples!!!",
                    message='You are using too much SSS SAMPLES (>%s)<br>'
                            '<br>'
                            'Please either reduce AA samples of SSS '
                            'Samples!!!' % max_allowed_sss_samples,
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            # check Light Samples
            # check point lights with zero radius but more than one samples
            all_point_lights = pm.ls(type='pointLight')
            ridiculous_point_lights = []
            for point_light in all_point_lights:
                if point_light.aiRadius.get() < 0.1 and point_light.aiSamples.get() > 1:
                    ridiculous_point_lights.append(point_light)

            if ridiculous_point_lights:
                pm.confirmDialog(
                    title="Unnecessary Samples on Point Lights!!!",
                    message='You are using too much SAMPLES (>1)<br>'
                            '<br>'
                            'on <b>Point lights with zero radius</b><br>'
                            '<br>'
                            'Please reduce the samples to 1',
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            # Check area lights with more than 2 samples
            all_area_lights = pm.ls(type=['areaLight', 'aiAreaLight'])
            ridiculous_area_lights = []
            for area_light in all_area_lights:
                if area_light.aiSamples.get() > 2:
                    ridiculous_area_lights.append(area_light)

            if ridiculous_area_lights:
                pm.confirmDialog(
                    title="Unnecessary Samples on Area Lights!!!",
                    message='You are using too much SAMPLES (>2) on<br>'
                            '<br>'
                            '<b>Area Lights</b><br>'
                            '<br>'
                            'Please reduce the samples to 2',
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

            # Check directional lights with angle == 0 and samples > 1
            all_directional_lights = pm.ls(type='directionalLight')
            ridiculous_directional_lights = []
            for directional_light in all_directional_lights:
                if directional_light.aiAngle.get() == 0 and directional_light.aiSample.get() > 1:
                    ridiculous_directional_lights.append(directional_light)

            if ridiculous_directional_lights:
                pm.confirmDialog(
                    title="Unnecessary Samples on Directional Lights!!!",
                    message='You are using too much SAMPLES (>1) on <br>'
                            '<br>'
                            '<b>Directional lights with zero angle</b><br>'
                            '<br>'
                            'Please reduce the samples to 1',
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK'
                )
                return

        # get values
        start_frame = pm.intField('cgru_afanasy__start_frame', q=1, v=1)
        end_frame = pm.intField('cgru_afanasy__end_frame', q=1, v=1)
        frames_per_task = \
            pm.intField('cgru_afanasy__frames_per_task', q=1, v=1)
        by_frame = pm.intField('cgru_afanasy__by_frame', q=1, v=1)
        hosts_mask = pm.textField('cgru_afanasy__hosts_mask', q=1, text=True)
        hosts_exclude = pm.textField('cgru_afanasy__hosts_exclude', q=1, text=True)
        separate_layers = \
            pm.checkBox('cgru_afanasy__separate_layers', q=1, v=1)
        pause = pm.checkBox('cgru_afanasy__paused', q=1, v=1)
        life_time = pm.intField('cgru_afanasy__life_time', q=1, v=1)

        # check values
        if start_frame > end_frame:
            temp = end_frame
            end_frame = start_frame
            start_frame = temp

        frames_per_task = max(1, frames_per_task)
        by_frame = max(1, by_frame)

        # store without quota sign
        hosts_mask = hosts_mask.replace('"', '')
        hosts_exclude = hosts_exclude.replace('"', '')

        # store field values
        pm.optionVar['cgru_afanasy__start_frame_ov'] = start_frame
        pm.optionVar['cgru_afanasy__end_frame_ov'] = end_frame
        pm.optionVar['cgru_afanasy__frames_per_task_ov'] = frames_per_task
        pm.optionVar['cgru_afanasy__by_frame_ov'] = by_frame
        pm.optionVar['cgru_afanasy__hosts_mask_ov'] = hosts_mask
        pm.optionVar['cgru_afanasy__hosts_exclude_ov'] = hosts_exclude
        pm.optionVar['cgru_afanasy__separate_layers_ov'] = separate_layers
        pm.optionVar['cgru_afanasy__life_time_ov'] = life_time

        # get paths
        scene_name = pm.sceneName()
        datetime = '%s%s' % (
            time.strftime('%y%m%d-%H%M%S-'),
            str(time.time() - int(time.time()))[2:5]
        )

        filename = '%s.%s.mb' % (scene_name, datetime)

        project_path = pm.workspace(q=1, rootDirectory=1)

        outputs = \
            pm.renderSettings(fullPath=1, firstImageName=1, lastImageName=1)

        # job_name = os.path.basename(scene_name)
        job_name = self.generate_job_name()

        logger.debug('%ss %se %sr' % (start_frame, end_frame, by_frame))
        logger.debug('scene        = %s' % scene_name)
        logger.debug('file         = %s' % filename)
        logger.debug('job_name     = %s' % job_name)
        logger.debug('project_path = %s' % project_path)
        logger.debug('outputs      = %s' % outputs)

        if pm.checkBox('cgru_afanasy__close', q=1, v=1):
            pm.deleteUI(self.window)



        job = af.Job(job_name)

        stored_log_level = None
        if render_engine == 'arnold':
            # set the verbosity level to warning+info
            aro = pm.PyNode('defaultArnoldRenderOptions')
            stored_log_level = aro.getAttr('log_verbosity')
            aro.setAttr('log_verbosity', 1)
            # set output to console
            aro.setAttr("log_to_console", 1)
        elif render_engine == 'redshift':
            # set the verbosity level to detailed+info
            redshift = pm.PyNode('redshiftOptions')
            stored_log_level = redshift.logLevel.get()
            redshift.logLevel.set(2)

        # save file
        pm.saveAs(
            filename,
            force=1,
            type='mayaBinary'
        )

        # rename back to original name
        pm.renameFile(scene_name)

        # create the render command
        mrc = MayaRenderCommandBuilder(
            name=job_name, file_full_path=filename,
            render_engine=render_engine, project=project_path,
            by_frame=by_frame
        )

        # submit renders
        blocks = []
        if separate_layers:
            # render each layer separately
            rlm = pm.PyNode('renderLayerManager')
            layers = [layer for layer in rlm.connections()
                      if layer.renderable.get()]

            for layer in layers:
                mrc_layer = copy.copy(mrc)
                layer_name = layer.name()
                mrc_layer.name = layer_name
                mrc_layer.render_layer = layer_name

                # create a new block for this layer
                block = af.Block(
                    layer_name,
                    renderer_to_block_type.get(render_engine, 'maya')
                )

                block.setFiles(
                    afcommon.patternFromDigits(
                        afcommon.patternFromStdC(
                            afcommon.patternFromPaths(outputs[0], outputs[1])
                        )
                    ).split(';')
                )
                block.setNumeric(
                    start_frame, end_frame, frames_per_task, by_frame
                )
                block.setCommand(mrc_layer.build_command())

                blocks.append(block)
        else:
            # create only one block
            block = af.Block(
                'All Layers',
                renderer_to_block_type.get(render_engine, 'maya')
            )

            block.setFiles(
                afcommon.patternFromDigits(
                    afcommon.patternFromStdC(
                        afcommon.patternFromPaths(outputs[0], outputs[1])
                    )
                ).split(';')
            )
            block.setNumeric(
                start_frame, end_frame, frames_per_task, by_frame
            )
            block.setCommand(mrc.build_command())

            blocks.append(block)

        job.setFolder('input', os.path.dirname(filename))
        job.setFolder('output', os.path.dirname(outputs[0]))
        job.setHostsMask(hosts_mask)
        job.setHostsMaskExclude(hosts_exclude)
        if life_time > 0:
            job.setTimeLife(life_time * 3600)

        job.setCmdPost('deletefiles "%s"' % os.path.abspath(filename))
        if pause:
            job.offline()

        # add blocks
        job.blocks.extend(blocks)

        status, data = job.send()
        if not status:
            pm.PopupError('Something went wrong!')
        print('data: %s' % data)

        # restore log level
        if render_engine == 'arnold':
            aro = pm.PyNode('defaultArnoldRenderOptions')
            aro.setAttr('log_verbosity', stored_log_level)
            # disable set output to console
            aro.setAttr("log_to_console", 0)
        elif render_engine == 'redshift':
            redshift = pm.PyNode('redshiftOptions')
            redshift.logLevel.set(stored_log_level)
예제 #28
0
import os
from pymel.core import Path, about, getMelGlobal


DIR_APP = Path( os.environ.get( 'MAYA_APP_DIR' ) )
DIR_VERSION = DIR_APP / about( version=True ).replace(' ','-')

DIR_PREFS = DIR_VERSION / 'prefs'
PREF_POSES = DIR_PREFS / 'poses.bin'

_runtime_suite = getMelGlobal( 'string', 'KINETIFEX_RUNTIME_SUITE' )

if _runtime_suite:
    RUNTIME_SUITE = _runtime_suite
else:
    RUNTIME_SUITE = 'Kinetifex'
예제 #29
0
def show( reset=False ):

    global scene_menu

    if pm.about( batch=True ):
        print 'menu not available in batch mode.'
        return
    else:
        # get things ready for building the menu

        menu_name = MENU_LABEL.replace( ' ', '' )

        if pm.menu( menu_name, exists=True ):
            if reset:
                pm.deleteUI( menu_name )
            else:
                main_menu = pm.menu( menu_name, edit=True )
                return main_menu

        pm.setParent( MAYA_WINDOW )

        if not pm.menu( menu_name, exists=True ):
            main_menu = pm.menu( menu_name, tearOff=True, familyImage='burst_family.xpm' )

        # build the menu
        with  main_menu:

            with pm.subMenuItem( 'Display', aob=True, tearOff=True ):
                commandMenuItem( kx.display.jointCountHUD,
                          checkBox=pm.optionVar.get( 'jointCountHUDVis', False ) ),
                '''
                commandMenuItem(kx.display.particleCountHUD,
                          checkBox=pm.optionVar.get('particleCountHUDVis', False)),
                commandMenuItem(kx.display.transformCountHUD,
                          checkBox=pm.optionVar.get('transformCountHUDVis', False)),
                commandMenuItem(kx.display.currentFrameHUD,
                          checkBox=pm.optionVar.get('currentFrameHUDVis', False)),
                '''
                commandMenuItem( kx.display.currentTimeHUD,
                          checkBox=pm.optionVar.get( 'currentTimeHUDVis', False ) ),

                pm.menuItem( divider=True ),
                # commandMenuItem(kx.display.cycleBackgroundColors),
                commandMenuItem( kx.display.cycleGridDisplay ),

                pm.menuItem( divider=True ),
                commandMenuItem( kx.display.togglePlaybackSpeed ),
                commandMenuItem( kx.display.togglePlaybackSnap ),

                pm.menuItem( divider=True ),
                commandMenuItem( kx.display.toggleIsolateSelected ),
                commandMenuItem( kx.display.toggleXRay ),
                commandMenuItem( kx.display.toggleWireframeOnShaded ),

                pm.menuItem( divider=True ),
                commandMenuItem( kx.display.closeWindows ),


            with pm.subMenuItem( 'Modify', tearOff=True ) as sub_modify:
                commandMenuItem( kx.modify.cycleMoveMode ),
                commandMenuItem( kx.modify.cycleRotateMode ),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.modify.unfreezeTranslation )

            pm.menuItem( divider=True )

            with pm.subMenuItem( 'Animation', tearOff=True ) as anim_menu:

                with pm.subMenuItem( 'Poses', tearOff=True ):
                    commandMenuItem( kx.poses.copyClipboardPose, label='Capture Pose' ),
                    commandMenuItem( kx.poses.applyClipboardPose, label='Apply Pose' ),
                    commandMenuItem( kx.poses.applyClipboardPoseToSelected, label='Apply Pose To Selected' ),
                    commandMenuItem( kx.poses.mirrorClipboardPose, label='Mirror Pose' ),
                    pm.menuItem( divider=True ),
                    commandMenuItem( kx.poses.openPoseManagerWindow, label='Pose Manager Window...' ),

                    pm.menuItem( divider=True )

                with pm.subMenuItem( 'Curves', tearOff=True ):
                    commandMenuItem( kx.animation.smoothTangentIn ),
                    commandMenuItem( kx.animation.smoothTangentOut ),

                    pm.menuItem( divider=True ),
                    commandMenuItem( kx.animation.flipCurve ),
                    commandMenuItem( kx.animation.mirrorCurve ),
                    commandMenuItem( kx.animation.reverseCurve ),
                    commandMenuItem( kx.animation.general.loopCurveFirst ),
                    commandMenuItem( kx.animation.general.loopCurveLast ),

                    pm.menuItem( divider=True ),
                    commandMenuItem( kx.animation.offsetKeyframesUp360 ),
                    commandMenuItem( kx.animation.offsetKeyframesDown360 ),

                    pm.menuItem( divider=True ),
                    commandMenuItem( kx.animation.toggleInfinityCycle ),

                    pm.menuItem( divider=True ),
                    commandMenuItem( kx.animation.keyTickSpecialOn ),
                    commandMenuItem( kx.animation.keyTickSpecialOff )


                with pm.subMenuItem( 'Reset IK', tearOff=True ):
                    commandMenuItem( kx.animation.resetIk, ( True, False ), label='T',
                                annotation='Reset translation of selected IK control(s)' ),
                    commandMenuItem( kx.animation.resetIk, ( False, True ), label='R',
                                annotation='Reset rotation of selected IK control(s)' ),
                    commandMenuItem( kx.animation.resetIk, ( True, True ), label='T/R',
                                annotation='Reset translation and rotation of selected IK control(s)' ),


                pm.menuItem( divider=True ),
                commandMenuItem( kx.animation.openSwitchParentWindow, label='Switch Parent...' ),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.animation.performTransferAnimation ),



            with pm.subMenuItem( 'Modeling', aob=True, tearOff=True ):
                # commandMenuItem(kx.modeling.attachObject),
                commandMenuItem( kx.modeling.performRandomTransform ),
                # commandMenuItem(kx.modeling.targetCombine),
                commandMenuItem( kx.modeling.performReplaceShape ),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.modeling.matchVertexNormals ),
                # pm.menuItem(divider=True),
                # commandMenuItem(kx.modeling.polyFaceProjection),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.modeling.reverseOppositeGeometry ),
                commandMenuItem( kx.modeling.cleanGroupCombine ),


            with pm.subMenuItem( 'Rigging', aob=True, tearOff=True ):
                # commandMenuItem(kx.rigging.modifyAttributes),
                commandMenuItem( kx.rigging.performLockObjects ),
                commandMenuItem( kx.rigging.performUnlockObjects ),

                pm.menuItem( divider=True ),
                commandMenuItem( kx.rigging.performSprintJoint ),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.rigging.performTweakJointOrient )

                pm.menuItem( divider=True ),
                commandMenuItem( kx.rigging.resetIkSetup ),
                commandMenuItem( kx.rigging.switchParentSetup )


                pm.menuItem( divider=True )

                with pm.subMenuItem( 'Curve Shapes', aob=False, tearOff=True ):
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'cube', ), label='Cube' ),
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'square', ), label='Square' ),
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'sphere', ), label='Sphere' ),
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'locator', ), label='Locator' ),
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'pointer', ), label='Pointer' ),
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'star', ), label='Star' ),
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'axis', ), label='Axis' ),
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'arrow', ), label='Arrow' ),
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'triangle', ), label='Triangle' ),
                    commandMenuItem( kx.rigging.createNurbsShape, ( '', 'circle', ), label='Circle' ),

                commandMenuItem( kx.rigging.performScaleCurveShape )


            with pm.subMenuItem( 'Skinning', aob=True, tearOff=True ):
                commandMenuItem( kx.skinning.copyVertexWeights ),
                commandMenuItem( kx.skinning.pasteVertexWeights ),
                commandMenuItem( kx.skinning.getOverInfluencedVerts ),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.skinning.matchSkinning )


            with pm.subMenuItem( 'Dynamics', tearOff=True ):
                commandMenuItem( kx.dynamics.loopDynamics ),
                commandMenuItem( kx.dynamics.restDynamics )


            with pm.subMenuItem( 'Materials', tearOff=True ):
                commandMenuItem( kx.materials.reloadTextures )

            pm.menuItem( divider=True )

            with pm.subMenuItem( 'Scene', tearOff=True ) as scene_menu:
                commandMenuItem( kx.scene.colorWireWindow ),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.scene.orderedRename ),
                commandMenuItem( kx.scene.suffixName ),
                commandMenuItem( kx.scene.removeNamespaces ),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.scene.setRelativeReferences ),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.scene.exploreSceneFolder ),
                pm.menuItem( divider=True ),
                commandMenuItem( kx.scene.addSelectedToSet ),
                commandMenuItem( kx.scene.removeSelectedFromSet ),


        return main_menu
예제 #30
0
파일: mkUtils.py 프로젝트: atvKumar/mkUtils
    "VRayCarPaintMtl",
    "VRayFastSSS2",
    "VRayMtlHair2",
    "VRayMtlHair3",
    "VRayMtl2Sided",
    "VRayBlendMtl",
    "VRayBumpMtl",
    "VRayLightMtl",
    "VRayMeshMaterial",
    "VRayFlakesMtl",
    "VRayMtlWrapper",
]

_pyVer = sys.version

maya_version = int(pm.about(v=1).split(" ")[0])

python_version = float(_pyVer.split(" ")[0][0:-2])

qt_version = pm.about(qt=1)

IS_OSX = pm.about(mac=1)

IS_WINDOWS = pm.about(win=1)
# Classes ----------------------------------------------------------------------
class SelectionError(Exception):
    """ Selection based errors """

    pass

예제 #31
0
 def getValues(self):
     """
     In this function we will get all values
     """
     renderer = cmds.getAttr('defaultRenderGlobals.currentRenderer')
     if not renderer == 'mentalRay' :
       cmds.confirmDialog( title='Renderer Not Supported', message='Render box only support mentalRay', button=['Exit'], cancelButton='Exit' )
       return 0
     app = pm.about(application =True)
     version = pm.about(version=True)
     appname = app+version
     apppath = os.environ["MAYA_LOCATION"]
     renderableLayerList = []
     date_time = strftime("%a, %d %b %Y %H:%M:%S")
     scene_file_path = str(pm.system.sceneName())
     scene_file_name = str(os.path.basename(scene_file_path))
     renderLayerList = cmds.ls(type='renderLayer')
     for renderLayerName in renderLayerList:
         renderableLayer = cmds.getAttr('%s.renderable' % renderLayerName)
         if renderableLayer:
             renderableLayerList.append(renderLayerName)
     # Get the name of the first and last image for the current layer
     first_frame = str(cmds.getAttr('defaultRenderGlobals.startFrame'))
     last_frame = str(cmds.getAttr('defaultRenderGlobals.endFrame'))
     newList = str(renderableLayerList).replace("u'", "").replace("'", "").replace("[", "").replace("]","")
     custom_path = ''
     custom_checkbox = pm.checkBox('custom_CB', query=True, value=True)
     if custom_checkbox:
         first_frame = pm.textField('start_frame_LE', query=True, text=True)
         try:
           val = int(first_frame)
         except ValueError:
           cmds.confirmDialog( title='invalid number', message='first frame is not valid', button=['Exit'], cancelButton='Exit' )
           return 0
         last_frame = pm.textField('end_frame_LE', query=True, text=True)
         try:
           val = int(last_frame)
         except ValueError:
           cmds.confirmDialog( title='invalid number', message='last frame is not valid', button=['Exit'], cancelButton='Exit' )
           return 0
         custom_path = pm.textField('output_path_LE', query=True, text=True)
     job_description = pm.textField('description_LE', query=True, text=True)
     priority = pm.optionMenu('priority_CB', query=True, value=True)
     #force_start = pm.checkBox('force_start_TB', query=True, value=True)
     command = ' -w ' \
               ' -app "%s" ' \
               ' -apppath "%s" ' \
               ' -priority "%s" ' \
               ' -description "%s" ' \
               ' -filename "%s" ' \
               ' -filepath "%s" ' \
               ' -custompath "%s" ' \
               ' -renderlayers "%s" ' \
               ' -startframe "%s" ' \
               ' -endframe "%s" ' \
               ' -starttime "%s" ' % (appname, apppath, priority, job_description, scene_file_name, scene_file_path, custom_path, newList , first_frame, last_frame, date_time)
     
     if custom_path:
       if os.path.exists(custom_path):
         return command
       else:
         cmds.confirmDialog( title='Path not exists', message='Output path provided by you is not exists', button=['Exit'], cancelButton='Exit' )
         return 0
     else:
       return command
예제 #32
0
import sys
import unittest
import maya.cmds as cmds
import pymel.core as pm
import pymel.core.uitypes as ui
import pymel.core.windows as windows

class TestMenu(unittest.TestCase):
    def setUp(self):
        cmds.setParent(None, menu=1)
        self.win = cmds.window()
    def tearDown(self):
        cmds.deleteUI(self.win, window=True)

    def testOptionMenuAsMenu(self):
        cmds.formLayout()
        om = ui.OptionMenu('someOptionMenu', create=True)
        cmds.menuItem( label='Yellow' )
        self.assertEqual(windows.menu(om, q=1, numberOfItems=1), 1)
        self.assertEqual(windows.menu(om.name(), q=1, numberOfItems=1), 1)
        self.assertEqual(windows.menu(om.shortName(), q=1, numberOfItems=1), 1)
        ui.Menu(om)
        ui.Menu(om.name())
        ui.Menu(om.shortName())

if not pm.about(batch=1):
    for key, obj in globals().items():
        if isinstance(obj, unittest.TestCase):
            del globals()[key]
            obj.__name__ = '_canceledTest_' + obj.__name__
예제 #33
0
 def __init__(self, rendererName, moduleName):
     Renderer.MayaToRenderer.__init__(self, rendererName, moduleName)
     self.rendererTabUiDict = {}
     if not pm.about(batch=True):
         mantraMainMenu()
예제 #34
0
# radioButtonGrp example
# -----------------------------------------------------------------------------

 
  
# -----------------------------------------------------------------------------  
# Cool Stuff
# -----------------------------------------------------------------------------

# Running terminal commands
# This is normally done through the subprocess module in python (Google subprocess)
# Pymel has a built in version
import pymel.core as pm
import pymel.internal as pyi

os_type = pm.about(os=True)

if os_type == 'nt':
    # Windows
    output = pyi.shellOutput('dir')
else:
    # Linux or Mac
    output = pyi.shellOutput('ls')

# Prints out of the contents of the current directory your in.
print output

# Try this instead
# Open and image (Yes, this can be done with pretty much any file.)
os_type = pm.about(os=True)
예제 #35
0
def createArnoldMenu():
    # Add an Arnold menu in Maya main window
    if not pm.about(b=1):
        pm.menu('ArnoldMenu', label='Arnold', parent='MayaWindow', tearOff=True )

        pm.menuItem('ArnoldStandIn', label='StandIn', parent='ArnoldMenu', subMenu=True, tearOff=True)
        pm.menuItem('ArnoldCreateStandIn', parent='ArnoldStandIn', label="Create",
                    c=lambda *args: createStandIn())
        pm.menuItem('ArnoldCreateStandInFile', parent='ArnoldStandIn', optionBox=True,
                    c=lambda *args: doCreateStandInFile())
        pm.menuItem('ArnoldExportStandIn', parent='ArnoldStandIn', label='Export',
                    c=lambda *args: doExportStandin())
        pm.menuItem('ArnoldExportOptionsStandIn', parent='ArnoldStandIn', optionBox=True,
                    c=lambda *args: doExportOptionsStandin())

        pm.menuItem('ArnoldLights', label='Lights', parent='ArnoldMenu', subMenu=True, tearOff=True)
        
        pm.menuItem('ArnoldAreaLights', parent='ArnoldLights', label="Area Light",
                    c=lambda *args: mutils.createLocator('aiAreaLight', asLight=True))
        pm.menuItem('SkydomeLight', parent='ArnoldLights', label="Skydome Light",
                    c=lambda *args: mutils.createLocator('aiSkyDomeLight', asLight=True))
        pm.menuItem('ArnoldMeshLight', parent='ArnoldLights', label='Mesh Light',
                    c=lambda *args: doCreateMeshLight())
        pm.menuItem('PhotometricLights', parent='ArnoldLights', label="Photometric Light",
                    c=lambda *args: mutils.createLocator('aiPhotometricLight', asLight=True))

        pm.menuItem(parent='ArnoldLights', divider=True)

        pm.menuItem('MayaDirectionalLight', parent='ArnoldLights', label="Maya Directional Light",
                    c=lambda *args: cmds.CreateDirectionalLight())
        pm.menuItem('MayaPointLight', parent='ArnoldLights', label="Maya Point Light",
                    c=lambda *args: cmds.CreatePointLight())
        pm.menuItem('MayaSpotLight', parent='ArnoldLights', label="Maya Spot Light",
                    c=lambda *args: cmds.CreateSpotLight())
        pm.menuItem('MayaQuadLight', parent='ArnoldLights', label="Maya Quad Light",
                    c=lambda *args: cmds.CreateAreaLight())
                    
        pm.menuItem('ArnoldVolume', label='Volume', parent='ArnoldMenu',
                    c=lambda *args: createVolume())
                    
        pm.menuItem('ArnoldFlush', label='Flush Caches', parent='ArnoldMenu', subMenu=True, tearOff=True)
        pm.menuItem('ArnoldFlushTexture', parent='ArnoldFlush', label="Textures",
                    c=lambda *args: cmds.arnoldFlushCache(textures=True))
        pm.menuItem('ArnoldFlushBackground', parent='ArnoldFlush', label="Skydome Lights",
                    c=lambda *args: cmds.arnoldFlushCache(skydome=True))
        pm.menuItem('ArnoldFlushQuads', parent='ArnoldFlush', label="Quad Lights",
                    c=lambda *args: cmds.arnoldFlushCache(quads=True))
        pm.menuItem('ArnoldFlushAll', parent='ArnoldFlush', label="All",
                    c=lambda *args: cmds.arnoldFlushCache(flushall=True))
                    
        pm.menuItem('ArnoldUtilities', label='Utilities', parent='ArnoldMenu', subMenu=True, tearOff=True)
        pm.menuItem('ArnoldBakeGeo', label='Bake Selected Geometry', parent='ArnoldUtilities',
                    c=lambda *args: arnoldBakeGeo())
        pm.menuItem('ArnoldRenderToTexture', label='Render Selection To Texture', parent='ArnoldUtilities',
                    c=lambda *args: arnoldRenderToTexture())
        pm.menuItem('ArnoldTxManager', label='Tx Manager', parent='ArnoldUtilities',
                    c=lambda *args: arnoldTxManager())                    
        pm.menuItem('ArnoldLightManager', label='Light Manager', parent='ArnoldUtilities',
                    c=lambda *args: arnoldLightManager())

        pm.menuItem('ArnoldHelpMenu', label='Help', parent='ArnoldMenu',
                    subMenu=True, tearOff=True)

        pm.menuItem('ArnoldUserGuide', label='User Guide', parent='ArnoldHelpMenu',
                    c=lambda *args: cmds.launch(webPage='https://support.solidangle.com/display/AFMUG/Arnold+for+Maya+User+Guide'))

        pm.menuItem('ArnoldTutorials', label='Tutorials', parent='ArnoldHelpMenu',
                    c=lambda *args: cmds.launch(webPage='https://support.solidangle.com/display/mayatut/Arnold+for+Maya+Tutorials'))

        pm.menuItem('ArnoldVideos', label='Videos', parent='ArnoldHelpMenu',
                    c=lambda *args: cmds.launch(webPage='https://support.solidangle.com/display/AFMV/Arnold+for+Maya+Videos'))

        pm.menuItem(divider=1, parent='ArnoldHelpMenu')

        pm.menuItem('ArnoldSolidAngle', label='Solid Angle', parent='ArnoldHelpMenu',
                    c=lambda *args: cmds.launch(webPage='https://www.solidangle.com'))

        pm.menuItem('ArnoldMailingLists', label='Mailing Lists', parent='ArnoldHelpMenu',
                    c=lambda *args: cmds.launch(webPage='https://subscribe.solidangle.com'))

        pm.menuItem('ArnoldAsk', label='Knowledge Base', parent='ArnoldHelpMenu',
                    c=lambda *args: cmds.launch(webPage='https://ask.solidangle.com'))

        pm.menuItem('ArnoldSupportBlog', label='Support Blog', parent='ArnoldHelpMenu',
                    c=lambda *args: cmds.launch(webPage='https://support.solidangle.com/blog/arnsupp'))

        pm.menuItem('ArnoldLicensing', label='Licensing', parent='ArnoldHelpMenu',
                    c=lambda *args: arnoldLicenseDialog())

        pm.menuItem(divider=1, parent='ArnoldHelpMenu')

        pm.menuItem('ArnoldDeveloperGuide', label='Developer Guide', parent='ArnoldHelpMenu',
                    c=lambda *args: cmds.launch(webPage='https://support.solidangle.com/display/ARP/Arnoldpedia'))

        pm.menuItem('ArnoldExperimentalMenu', label='Experimental', parent='ArnoldMenu', subMenu=True, tearOff=True)

        pm.menuItem('ArnoldRender', label='External RenderView', parent='ArnoldExperimentalMenu', subMenu=True, tearOff=True)
        pm.menuItem('ArnoldSelectCamera', label='Select Camera', parent='ArnoldRender', subMenu=True, tearOff=False, 
                    postMenuCommand=lambda *args: populateSelectCamera())
        populateSelectCamera()
        pm.menuItem('ArnoldStartRender', label='Render', parent='ArnoldRender',
                    c=lambda *args: startRender())
        pm.menuItem('ArnoldStartIPR', label='IPR', parent='ArnoldRender',
                    c=lambda *args: startIpr())
        pm.menuItem('ArnoldRefresh', label='Refresh', parent='ArnoldRender',
                    c=lambda *args: refreshRender())
        pm.menuItem('ArnoldStopRender', label='Stop Render', parent='ArnoldRender',
                    c=lambda *args: stopRender())
                    
        pm.menuItem('ArnoldAbout', label='About', parent='ArnoldMenu',
                    c=lambda *args: arnoldAboutDialog())
예제 #36
0
    import mtoa.ui.exportass as exportass
    import mtoa.ui.nodeTreeLister as nodeTreeLister
    import mtoa.ui.globals.common
    from mtoa.ui.globals.common import createArnoldRendererCommonGlobalsTab, updateArnoldRendererCommonGlobalsTab
    from mtoa.ui.globals.settings import createArnoldRendererGlobalsTab, updateArnoldRendererGlobalsTab, updateBackgroundSettings, updateAtmosphereSettings, createArnoldRendererOverrideTab, updateArnoldRendererOverrideTab
    from mtoa.ui.globals.settings import createArnoldRendererDiagnosticsTab, updateArnoldRendererDiagnosticsTab, createArnoldRendererSystemTab, updateArnoldRendererSystemTab
    from mtoa.ui.aoveditor import createArnoldAOVTab, updateArnoldAOVTab
    import mtoa.ui.ae.utils as aeUtils
    from mtoa.ui.arnoldmenu import createArnoldMenu
    import mtoa.cmds.arnoldRender as arnoldRender
except:
    import traceback
    traceback.print_exc(file=sys.__stderr__) # goes to the console
    raise

if not pm.about(batch=True):
    for nodeType in pm.pluginInfo('mtoa', q=1, dependNode=1):
        pm._factories.addMayaType(nodeType, 'kPluginDependNode')

def _overrideMelScripts():
    # for those procedures that we could not simply define overrides interactively, we keep edited files
    # per version of maya
    root = mtoaPackageRoot()
    maya_version = versions.shortName()
    meldir = os.path.join(root, maya_version, 'mel')
    meldir = mtoa.utils.convertToUnicode(meldir)
    pathsep = mtoa.utils.convertToUnicode(os.pathsep)
    maya_script_path = mtoa.utils.convertToUnicode(mtoa.utils.getEnvironmentVariable(u'MAYA_SCRIPT_PATH'))
    mtoa.utils.setEnvironmentVariable(u'MAYA_SCRIPT_PATH', meldir + pathsep + maya_script_path)
    for f in glob.glob(os.path.join(meldir, '*.mel')):
        print>>sys.__stdout__, "Maya %s sourcing MEL override %s" % (maya_version, f)
예제 #37
0
from turret.plugins import UnsupportedPluginError

try:
    import pymel.core as pm
    from turret.mayautils import MayaNodeData
except ImportError:
    raise UnsupportedPluginError()

# requires the 3delight plugin
mayaVersion = pm.about(version=True).split()[0]
plugin = '3delight_for_maya' + mayaVersion
if not pm.pluginInfo(plugin, query=True, loaded=True):
    raise UnsupportedPluginError()


class Data(MayaNodeData):
    def __init__(self, name=None, path=None, node=None):
        super(Data, self).__init__(type="DLFMFile",
                                   attrib_name="textureName",
                                   name=name,
                                   path=path,
                                   node=node)

    def _createNode(self):
        assert self.node is None
        assert self.name is not None
        # create a new dl_textureMap node with our name and path
        # need to call shadingNode, as the File constructor calls createNode instead of shadingNode
        # this results in a node that can't be seen in the hypershade
        return pm.shadingNode("dl_textureMap", name=self.name, asTexture=True)