Example #1
0
def createLCAArnoldShadingNodes():
    def getAllLCAArnoldShadingTypes():
        import RenderingAPI
        result = []
        # Obtain a list of names of available shaders from the renderer info plug-in
        renderer = RenderingAPI.RenderPlugins.GetDefaultRendererPluginName()
        rendererInfoPlugin = RenderingAPI.RenderPlugins.GetInfoPlugin(renderer)
        shaderType = RenderingAPI.RendererInfo.kRendererObjectTypeShader
        nodeTypes = rendererInfoPlugin.getRendererObjectNames(shaderType)

        for node_type in nodeTypes:
            if node_type.startswith("lc_"):
                result.append(node_type)
        return result

    from Katana import NodegraphAPI
    shader_type_list = getAllLCAArnoldShadingTypes()
    result = []
    i = 0
    for shader_type in shader_type_list:
        as_node = NodegraphAPI.GetNode(shader_type)

        if not as_node:
            as_node = NodegraphAPI.CreateNode('ArnoldShadingNode',
                                              NodegraphAPI.GetRootNode())
            width = 5
            NodegraphAPI.SetNodePosition(
                as_node, (150 * math.floor(i / width), -50 * (i % width)))
            i += 1

        as_node.getParameter('nodeType').setValue(shader_type, 0)
        as_node.checkDynamicParameters()
        as_node.getParameter('name').setValue(shader_type, 0)

        result.append(as_node)
    return result
Example #2
0
        def _populate():

            def createNodeParam(node,param_name):
                param = self.getParameters().createChildString(param_name,'')
                param.setExpressionFlag(True)
                param.setExpression('@%s'%node.getName())
            
            #===================================================================
            # CREATE NODES
            #===================================================================
            
            def AddGlobalGraphStateVariable(name, options):
                from Katana import  NodegraphAPI
                
                variablesGroup = NodegraphAPI.GetRootNode().getParameter('variables')
   
                variableParam = variablesGroup.createChildGroup(name)
                variableParam.createChildNumber('enable', 1)
                variableParam.createChildString('value', options[0])
                optionsParam = variableParam.createChildStringArray('options', len(options))
                for optionParam, optionValue in zip(optionsParam.getChildren(), options):
                    optionParam.setValue(optionValue, 0)
                return variableParam.getName()

    
            
            node_list = []
            self.addOutputPort('out')
            self.addInputPort('in')
            self.getSendPort('in').connect(self.getReturnPort('out'))
            self.sequence_lg = self.createBlockGroup(self, 'sequence')
            self.sequence_lg.getParameter('hash').setValue('master',0)
            self.shot_lg = NodegraphAPI.GetNode(self.sequence_lg.getParameter('nodeReference.shot_group').getValue(0))
            
            node_list.append(self.sequence_lg)

            
            Utils.EventModule.ProcessAllEvents()

            self.connectInsideGroup(node_list, self)
            
            
            #===================================================================
            # SET UP PARAMETERS
            #===================================================================
            self.createNodeReference(self,self.sequence_lg,'sequence_node',param=None)
            self.createNodeReference(self,self.shot_lg,'shot_node',param=None)
            self.gaffer_three_display_param = self.getParameters().createChildString('gaffer_display','')
            self.gaffer_three_display_param.setHintString(repr({'widget':'teleparam'}))
            
            self.publish_dir = self.getParameters().createChildString('publish_dir',settings.SEQUENCE_PATH)
            
            if NodegraphAPI.GetNode('rootNode').getParameter('variables.sequence'):
                self.sequence = NodegraphAPI.GetNode('rootNode').getParameter('variables.sequence.value').getValue(0)
            else:
                AddGlobalGraphStateVariable('sequence',['default'])
                self.sequence = 'default'
            if not os.path.exists(settings.SEQUENCE_PATH + '/%s'%self.sequence):
                #print 'not' , settings.SEQUENCE_PATH + '/%s'%sequence
                os.mkdir(settings.SEQUENCE_PATH + '/%s'%self.sequence)
                os.mkdir(settings.SEQUENCE_PATH + '/%s/blocks'%self.sequence)
                os.mkdir(settings.SEQUENCE_PATH + '/%s/shots'%self.sequence)
            self.publish_dir.setHintString(repr({'widget': 'fileInput'}))
            '''
            version_options = []
            if NodegraphAPI.GetNode('rootNode').getParameter('variables.sequence'):
                sequence = NodegraphAPI.GetNode('rootNode').getParameter('variables.sequence.value').getValue(0)
                if os.path.isdir('%s/%s/sequence/%s'%(settings.SEQUENCE_PATH,sequence,sequence)):
                    #print '%s/light/%s/sequence/%s'%(settings.SEQUENCE_PATH,sequence,sequence)
                    version_options = os.listdir('%s/%s/sequence/%s'%(settings.SEQUENCE_PATH,sequence,sequence))
                    
            self.sequence_param = self.getParameters().createChildString('version','v001')
            self.sequence_param.setHintString(repr({'widget': 'popup', 'options': version_options}))
            
            sequence_options = []
            #shot_options = []
            if NodegraphAPI.GetRootNode().getParameter('variables.sequence'):
                for child in NodegraphAPI.GetNode('rootNode').getParameter('variables.sequence.options').getChildren():
                    sequence_options.append(child.getValue(0))
            '''
            #if NodegraphAPI.GetRootNode().getParameter('variables.shot'):
                #for child in NodegraphAPI.GetNode('rootNode').getParameter('variables.shot.options').getChildren():
                    #shot_options.append(child.getValue(0))
                    
            self.sequence_param = self.getParameters().createChildString('sequence',self.sequence)
            self.sequence_param.setHintString(repr({'readOnly': 'True'}))
            #self.sequence_param.setHintString(repr({'widget': 'popup', 'options': sequence_options}))
            
            #self.sequence_param = self.getParameters().createChildString('shot','030')
            #self.sequence_param.setHintString(repr({'widget': 'popup', 'options': shot_options}))
            
            self.populateShots()
Example #3
0
def set_render_node():
	# TODO 接受用户输入数值
    node = NodegraphAPI.GetNode('Render1') # Render1 想做成用户直接拖拽渲染节点进来
	return node
Example #4
0
def set_camera():
	# TODO 接受用户输入数值
	cam = NodegraphAPI.GetNode('rootNode').getParameter('katanaSceneName').getValue(0)
	return cam
Example #5
0
def set_resolution():
	# TODO 接受用户输入数值
	res = NodegraphAPI.GetNode('rootNode').getParameter('resolution').getValue(0)
	# NodegraphAPI.GetNode('rootNode').getParameter('resolution').setValue("2000x2000",0)
	return res
 def getLocationData(self, usdPath):
     client = Nodes3DAPI.CreateClient(NodegraphAPI.GetNode('UsdIn'))
     return client.cookLocation('/root/world/geo%s' % usdPath)
Example #7
0
 def getNode(self):
     return NodegraphAPI.GetNode(self.__nodeName)
    def __evaluateScriptForItem(self, item, persistentData ):
        if not item.parent():
            return
        
        node = NodegraphAPI.GetNode(item.parent().getItemData()['name'])
        param = node.getParameter('parameters.'+item.getItemData()['name'])
        
        hints = self.__getHints(param)
        
        if 'dstName' in hints:
            dstName = hints['dstName']
            del hints['dstName']
        else:
            dstName = ''
        
        if 'dstPage' in hints:
            dstPage = hints['dstPage']
            del hints['dstPage']
        else:
            dstPage = ''
        

        localsDict = {
            'Katana':Katana,
            'nodeName': node.getName(),
            'paramName': param.getName(),
            'dstName':dstName,
            'dstPage':dstPage,
            'hints':copy.deepcopy(hints), #this is mutable so we must copy it
            'persistentData': persistentData,
            '__builtins__':__builtins__,
        }
        
        exec str(self.__scriptText.toPlainText()) in localsDict
        
        changed = False
        
        for key in ('dstName', 'dstPage', 'hints'):
            if localsDict[key] != locals()[key]:
                changed = True
                break
        
        if changed:
            self.__changed = True
            dstName = localsDict['dstName']
            dstPage = localsDict['dstPage']
            hints = localsDict['hints']
            
            hintsParam = param.getChild('hints')
            
            if not dstName and not dstPage:
                if hintsParam:
                    hintsParam.setValue('', 0)
                    param.deleteChild(hintsParam)
            else:
                if not hintsParam:
                    hintsParam = param.createChildString('hints', '')
                
                if dstName:
                    hints['dstName'] = dstName
                
                if dstPage:
                    hints['dstPage'] = dstPage
                
                hintsParam.setValue(repr(hints), 0)
            
            self.__updateParamItem(item, param)
Example #9
0
KEYBOARD_SHORTCUT: Alt+Shift+Q
SCOPE:
Opens a Graph State Variables editor
"""
from PyQt5 import QtWidgets, QtGui, QtCore

from Katana import UI4, NodegraphAPI

# ----------------------------------------------------------------- create menu
katana_main = UI4.App.MainWindow.CurrentMainWindow()
menu = QtWidgets.QMenu(katana_main)
menu_layout = QtWidgets.QVBoxLayout()
menu.setLayout(menu_layout)

# -------------------------------------------------- set up graph state variables
gsv_param = NodegraphAPI.GetNode('rootNode').getParameter('variables')
param_policy = UI4.FormMaster.CreateParameterPolicy(None, gsv_param)
gsv_widget = UI4.FormMaster.KatanaFactory.ParameterWidgetFactory.buildWidget(
    None, param_policy)
menu_layout.addWidget(gsv_widget)

# ------------------------------------------------------- menu display settings
# setup transparency
menu.setAttribute(QtCore.Qt.WA_NoSystemBackground
                  | QtCore.Qt.WA_TranslucentBackground)
menu.setWindowFlags(menu.windowFlags() | QtCore.Qt.FramelessWindowHint)
menu.setStyleSheet("background-color:rgba(50,50,50, 128);")
menu.setMinimumWidth(400)

# ---------------------------------------------------------- display and position
# show menu
Example #10
0
def recoverScript(katanaFile=None, logsFile=None, jsonFile):
    from Katana import KatanaFile, NodegraphAPI
    if katanaFile is not None:
        KatanaFile.Load(katanaFile)
    katana_file = katanaFile
    logs_file = logsFile
    file_name = NodegraphAPI.GetRootNode().getParameter(
        'katanaSceneName').getValue(0)
    katana_file = os.path.join(getVersoonUpKatanaDir(katana_file), file_name)
    #~ version up
    katana_file = katana_path[:-3] + "{:03}".format(int(katana_path[-3:]) + 1)
    infile = open(jsonFile, 'r')
    json_data = json.load(infile)
    infile.close()

    #~ loops all nodes
    for node_name in json_data:
        node = NodegraphAPI.GetNode(node_name)
        node_data = json_data[node_name]
        mx_shader_name = node_data[0]
        mx_shader_data = node_data[1]
        #~ loops all parameters
        for para_data in mx_shader_data:
            #~ read data from json data
            enable = para_data[0]
            name = para_data[1]
            connected = para_data[2]
            value = para_data[3]

            #~ translate data
            translate_shader = SHADERMAPPING[mx_shader_name][0]
            translate_para_list = SHADERMAPPING[mx_shader_name][1]
            translate_name = translate_para_list[name]

            #~ set new shader type
            node.checkDynamicParameters()
            if translate_shader != mx_shader_name:
                node.getParameter('nodeType').setValue(translate_shader, 0)
                node.checkDynamicParameters()
                if translate_shader != mx_shader_name:
                    from Katana import CacheManager
                    CacheManager.flush(isNodeGraphLoading=False)

            #~ if node connected to other
            if connected:
                if not mx_shader_name in SHADERMAPPING:
                    continue
                connected_node = NodegraphAPI.GetNode(value)
                out_port = connected_node.getOutputPorts()[0]

                in_port = node.getInputPort(translate_name)
                node.getInputPort(translate_name).connect(out_port)
            #~ recover parameter value
            else:
                if not enable:
                    continue
                node.checkDynamicParameters()
                para_enable = node.getParameter('parameters.%s.enable' %
                                                translate_name)
                para_enable.setValue(1, 0)
                para_value = node.getParameter('parameters.%s.value' %
                                               translate_name)
                node.checkDynamicParameters()
                if para_value.getType() == "numberArray":
                    children = para_value.getChildren()
                    for i in range(0, len(value)):
                        children[i].setValue(value[i], 0)
                elif para_value.getType() == "number":
                    para_value.setValue(float(value[0]), 0)
                else:
                    para_value.setValue(str(value[0]), 0)

    KatanaFile.Save(katana_path)
    if logsFile is not None:
        JobRecord(logs_file, katana_file)
Example #11
0
    def accept(self, settings, item):
        """
        Method called by the publisher to determine if an item is of any
        interest to this plugin. Only items matching the filters defined via the
        item_filters property will be presented to this method.

        A publish task will be generated for each item accepted here. Returns a
        dictionary with the following booleans:

            - accepted: Indicates if the plugin is interested in this value at
                all. Required.
            - enabled: If True, the plugin will be enabled in the UI, otherwise
                it will be disabled. Optional, True by default.
            - visible: If True, the plugin will be visible in the UI, otherwise
                it will be hidden. Optional, True by default.
            - checked: If True, the plugin will be checked in the UI, otherwise
                it will be unchecked. Optional, True by default.

        :param settings: Dictionary of Settings. The keys are strings, matching
            the keys returned in the settings property. The values are `Setting`
            instances.
        :param item: Item to process

        :returns: dictionary with boolean keys accepted, required and enabled
        """
        settings["node"].value = item.name
        node = NodegraphAPI.GetNode(item.name)
        path_param = node.getParameter("sg_saveTo")
        path = path_param.getValue(0)
        item.properties["path"] = path
        work_param = node.getParameter("sg_work_template")
        work_template_name = work_param.getValue(0)
        work_template = self._get_template(work_template_name)
        item.properties["work_template"] = work_template

        fields = work_template.validate_and_get_fields(path)
        if not fields:
            self.logger.debug("'{}': '{}', is not a valid path".format(
                item.name, path))
            return {
                "accepted": False,
                "visible": False,
                "enabled": False,
                "checked": False
            }
        del fields["version"]

        work_paths = self.sgtk.abstract_paths_from_template(
            work_template, fields)
        if not work_paths:
            self.logger.debug("'{}': No generated work files".format(
                item.name))
            return {
                "accepted": False,
                "visible": True,
                "enabled": True,
                "checked": False
            }

        publish_param = node.getParameter("sg_publish_template")
        publish_template_name = publish_param.getValue(0)
        publish_template = self._get_template(publish_template_name)
        item.properties["publish_template"] = publish_template
        publish_paths = self.sgtk.abstract_paths_from_template(
            publish_template, fields)

        work_paths_to_publish = sorted(work_paths, reverse=True)
        publish_fields = {}
        for work_path in work_paths:
            work_fields = work_template.get_fields(work_path)
            self.logger.debug("Checking '{}'".format(work_path))
            for publish_path in publish_paths:
                # cache result as this might be slow
                if publish_path not in publish_fields:
                    publish_fields[publish_path] = publish_template.get_fields(
                        publish_path)
                publish_fields = publish_fields[publish_path]
                if os.path.exists(publish_path) and publish_fields[
                        "version"] == work_fields["version"]:
                    self.logger.debug(
                        "'{}' already published".format(work_path))
                    # publish version exists
                    work_paths_to_publish.remove(work_path)
                    break

        if not work_paths_to_publish:
            self.logger.debug("'{}': All versions published".format(item.name))
            return {
                "accepted": False,
                "visible": True,
                "enabled": True,
                "checked": False
            }

        settings_dict = {
            "work_paths": work_paths_to_publish,
            "to_publish": work_paths_to_publish[0],
        }
        self._set_item_settings(settings_dict, settings)

        return {"accepted": True, "checked": True}
Example #12
0
def updateParameters(node):
    def copyParam(param, params_list):
        param_name = param.getName()
        param_enable = param.getChild("enable")
        for p in params_list:
            if p.getName() == param_name and param_enable is not None:
                master_param_enable = p.getChild("enable").getValue(0)
                input_param_enable = param.getChild("enable").getValue(0)
                if master_param_enable and not input_param_enable:
                    children = p.getChild("value").getChildren()
                    if children is None:
                        value = p.getChild("value").getValue(0)
                        param.getChild("enable").setValue(1.0, 0)
                        param.getChild("value").setValue(value, 0)
                    else:
                        for child in children:
                            name = child.getName()
                            value = child.getValue(0)
                            param.getChild("enable").setValue(1.0, 0)
                            param_child = param.getChild("value").getChild(name)
                            if param_child is not None:
                                param_child.setValue(value, 0)

    gaffer_three_node = getGafferThreeNode(node)
    root_locations = node.getParameter('rootLocations').getChildren()
    producer = Nodes3DAPI.GetRenderProducer(node, 0, False, 0)
    if not gaffer_three_node:
        message = "GafferThree node have not be connected to GafferThreeRigs!"
        setMessage(message)
        log.warning(message)
        return

    if not root_locations:
        message = "GafferThreeRigs node has no rootLocation!"
        setMessage(message)
        log.warning(message)
        return
    else:
        if root_locations and root_locations[0].getValue(0) is "":
            message = "GafferThreeRigs has no rootLocation"
            log.warning(message)
            return

    master_chr_name = root_locations[0].getValue(0).split("/")[-1]
    chr_layer_rig_node = getRootRig(gaffer_three_node, cRigLayers[0])
    master_chr_rig = None
    rest_rig_set = []
    for chr_rig in chr_layer_rig_node.getChildren():
        if chr_rig.getType() != "Group":
            continue
        location = chr_rig.getParameter('__gaffer.location').getValue(0)
        current_chr_name = location.split("/")[-1]
        if current_chr_name == master_chr_name:
            master_chr_rig = chr_rig
        elif current_chr_name == "common":
            pass
        else:
            rest_rig_set.append(chr_rig)

    master_params_map = {}
    for light_group in master_chr_rig.getChildren():
        material_node_param = light_group.getParameter('node_material')
        location = light_group.getParameter('__gaffer.location')
        if material_node_param is not None:
            light_name = location.getValue(0).split("/")[-1]
            material_node_name = material_node_param.getValue(0)
            material_node = NodegraphAPI.GetNode(material_node_name)
            params_list = material_node.getParameter\
                ('shaders.arnoldLightParams').getChildren()
            master_params_map[light_name] = params_list

    for rig in rest_rig_set:
        for light_group in rig.getChildren():
            material_node_param = light_group.getParameter('node_material')
            location = light_group.getParameter('__gaffer.location')
            if material_node_param is not None:
                light_name = location.getValue(0).split("/")[-1]
                material_node_name = material_node_param.getValue(0)
                material_node = NodegraphAPI.GetNode(material_node_name)
                params_list = material_node.getParameter\
                    ('shaders.arnoldLightParams').getChildren()
                for param in params_list:
                    param_enable = param.getChild("enable")
                    if param_enable is not None:
                        # if this material param is not enable, we copy master 
                        # params to here and set it enable.
                        if light_name in master_params_map:
                            master_params_list = master_params_map[light_name]
                            copyParam(param, master_params_list)
    message = "Parameters in {%s} node have been updated!"%gaffer_three_node.getName()

    setMessage(message)
Example #13
0
def createLight(node, name, material, 
                usage = None, linkTarget = None, 
                annotation=None, lightAov=None, 
                parent=None):
    if not parent: parent = getRootPackage(node)

    merge_node_para = parent.getParameter("node_merge")
    merge_node = NodegraphAPI.GetNode(merge_node_para.getValue(0))
    
    location_path = parent.getParameter("__gaffer.location").getValue(0) + "/" + "light"
    package_class = cArnoldGafferPackages[material].create(node, location_path)
    package_class.setName(name, queueEvent=False, selectLocation=False, makeUnique=True)
    package_node = package_class._Package__packageNode
    
    package_node.setParent(parent)    
    
    connect(package_node, merge_node)

    #########################
    # set light preview color
    if usage is not None:
        node_name = package_node.getParameter('node_create').getValue(0)
        light_create_node = NodegraphAPI.GetNode(node_name)
        preview_color = light_create_node.getParameter('previewColor')
        if preview_color:
            para_list = preview_color.getChildren()
            for para in para_list:
                i = para_list.index(para)
                para.setValue(cLightObject[usage]["color"][i],0)
    
    ###########################
    # set light annotation text
    if annotation is not None:
        node_name = package_node.getParameter('node_viewerObjectSettings').getValue(0)
        viewerObjectSettings_node = NodegraphAPI.GetNode(node_name)
        viewerObjectSettings_node.getParameter('args.viewer.default.annotation.text.enable').setValue(1,0)
        viewerObjectSettings_node.getParameter('args.viewer.default.annotation.text.value').setValue(annotation,0)

    #####################
    # set light transform
    if usage is not None:
        node_name = package_node.getParameter('node_create').getValue(0)
        light_create_node = NodegraphAPI.GetNode(node_name)
        translate_list = light_create_node.getParameter('transform.translate').getChildren()
        rotate_list = light_create_node.getParameter('transform.rotate').getChildren()
        scale_list = light_create_node.getParameter('transform.scale').getChildren()
        for para in translate_list:
            i = translate_list.index(para)
            para.setValue(cLightObject[usage]["translate"][i],0)
        for para in rotate_list:
            i = rotate_list.index(para)
            para.setValue(cLightObject[usage]["rotate"][i],0)        
        for para in scale_list:
            i = scale_list.index(para)
            para.setValue(cLightObject[usage]["scale"][i],0)

    ####################
    # set light aov name
    if lightAov is not None:
        node_name = package_node.getParameter('node_material').getValue(0)
        material_node = NodegraphAPI.GetNode(node_name)
        material_node.checkDynamicParameters()
        material_node.getParameter('shaders.arnoldLightParams.aov.enable').setValue(1,0)
        material_node.getParameter('shaders.arnoldLightParams.aov.value').setValue(str(lightAov),0)

    #################
    # set light links
    light_link_node_name = package_node.getParameter('node_lightLink_illumination').getValue(0)
    light_create_node_name = package_node.getParameter('node_create').getValue(0)
    light_link_node = NodegraphAPI.GetNode(light_link_node_name)
    light_create_node = NodegraphAPI.GetNode(light_create_node_name)
    if linkTarget is not None:
        light_link_node.getParameter("on").setValue(linkTarget,0)
    initial_state = light_create_node.getParameter('initialState')
    if initial_state:
        initial_state.setValue(0,0)


    return package_node
Example #14
0
def GetRefNode(gnode, key):
    p = gnode.getParameter('node_'+key)
    if not p:
        return None
    
    return NodegraphAPI.GetNode(p.getValue(0))
Example #15
0
class MainWindow(QtGui.QDialog):
    _instances = {}

    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.submit_to_farm)
        self.ui.pushButton_2.clicked.connect(self.showAllLeft)
        self.ui.pushButton_3.clicked.connect(self.hideAllLeft)
        self.ui.pushButton_5.clicked.connect(self.showAllRight)
        self.ui.pushButton_4.clicked.connect(self.hideAllRight)
        self.output_directory = ''
        self.ui.checkBox_3.stateChanged.connect(self.changeCheckState)
        self.__class__._instances[id(self)] = self
        return

    def closeEvent(self, event):
        del self.__class__._instances[id(self)]
        return QtGui.QMainWindow.closeEvent(self, event)

    def showAllLeft(self):
        for i in xrange(0, self.ui.tableWidget.rowCount()):
            self.ui.tableWidget.item(i, 0).setCheckState(2)
        return

    def hideAllLeft(self):
        for i in xrange(0, self.ui.tableWidget.rowCount()):
            self.ui.tableWidget.item(i, 0).setCheckState(0)
        return

    def showAllRight(self):
        for i in xrange(0, self.ui.tableWidget_2.rowCount()):
            self.ui.tableWidget_2.item(i, 0).setCheckState(2)
        return

    def hideAllRight(self):
        for i in xrange(0, self.ui.tableWidget_2.rowCount()):
            self.ui.tableWidget_2.item(i, 0).setCheckState(0)
        return

    def changeCheckState(self, state):
        if state == QtCore.Qt.Checked:
            self.ui.lineEdit.setEnabled(0)
            self.ui.lineEdit_2.setEnabled(0)
            self.ui.lineEdit_3.setEnabled(0)
            for i in xrange(0, self.ui.tableWidget.rowCount()):
                self.ui.tableWidget.item(i, 1).setCheckState(0)
            for i in xrange(0, self.ui.tableWidget_2.rowCount()):
                self.ui.tableWidget.item(i, 1).setCheckState(0)
        else:
            self.ui.lineEdit.setEnabled(1)
            self.ui.lineEdit_2.setEnabled(1)
            self.ui.lineEdit_3.setEnabled(1)

    def setup_ui(self):
        l_nodes_raw = NodegraphAPI.GetAllNodesByType('Render')
        l_nodes = []
        for n in l_nodes_raw:
            np = n.getInputPortByIndex(0)
            if np.getNumConnectedPorts():
                l_nodes.append(n)
        l_renders = FarmAPI.GetSortedDependencyList(l_nodes)
        l_aovs = []
        for render_node in l_renders:
            if len(render_node['outputs']) > 0:
                for aov in render_node['outputs']:
                    l_aovs.append([render_node['name'], aov[
                                  'name'], aov['outputLocation']])
        # setting output directory to display in label
        if len(l_renders) > 0:
            if len(l_renders[0]['outputs']) > 1:
                output_location_of_some_layer = l_renders[
                    0]['outputs'][1]['outputLocation']
                self.output_directory, layer = os.path.split(
                    output_location_of_some_layer)
                self.ui.label_5.setText(self.output_directory)
        else:
            self.ui.label_5.setText("Output path not found. Contact TD.")
        checkboxList = []
        nodes_L, nodes_R = [], []
        for item in l_aovs:
            title = item[0]
            checkboxList.append(title)
        checkboxList = sorted(list(set(checkboxList)))
        for i in range(len(checkboxList)):
            name = checkboxList[i]
            if name[len(name) - 1] == "L":
                nodes_L.append(name)
            else:
                nodes_R.append(name)
        # Add to list showing L nodes
        self.ui.tableWidget.setRowCount(len(nodes_L))
        for i in range(len(nodes_L)):
            name = nodes_L[i]
            item = QtGui.QTableWidgetItem('%s' % name)
            check = Qt.Checked
            item.setCheckState(check)
            self.ui.tableWidget.setItem(i, 0, item)

            sf_mode = QTableWidgetItem(u"*双击编辑")
            check = Qt.Unchecked
            sf_mode.setCheckState(check)
            self.ui.tableWidget.setItem(i, 1, sf_mode)

       # Add to list showing R and other nodes
        self.ui.tableWidget_2.setRowCount(len(nodes_R))
        for i in range(len(nodes_R)):
            name = nodes_R[i]
            item = QtGui.QTableWidgetItem('%s' % name)
            check = Qt.Checked
            item.setCheckState(check)
            self.ui.tableWidget_2.setItem(i, 0, item)

            sf_mode = QTableWidgetItem(u"*双击编辑")
            check = Qt.Unchecked
            sf_mode.setCheckState(check)
            self.ui.tableWidget_2.setItem(i, 1, sf_mode)

        f_range = FarmAPI.GetSceneFrameRange()
        self.ui.lineEdit.setText(str(f_range['start']))
        self.ui.lineEdit_2.setText(str(f_range['end']))
        return

    def passedLgtShotSimplifyNode(self):
        lgtsimplifynode=NodegraphAPI.GetNode('LgtShotSimplify_')
        if lgtsimplifynode:
            lgtsimplifynode.setBypassed(True)
            KatanaFile.Save(FarmAPI.GetKatanaFileName())
            print "setBypassed ok"

    def passedlsfnodework(self,katanafile):
        katana_exc = ckc.katanaApp_xiaos
        #katanafile="'/mnt/work/home/wangbin/Wb2015/CodeWork/lgtsmp/test.katana'"
        #runscript="/mnt/work/home/wangbin/Wb2015/CodeWork/lgtsmp/runpassedlsfnode.py"
        runscript=lctools_env+"/tools/set/runlgt/runpassedlsfnode.py"
        cmd="%s --script=%s %s"%(katana_exc,runscript,katanafile)
        pp = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
        line="start passedlsfnode"
        while line != "":
            line = pp.stdout.readline()
            print line,
        print "passedlsfnode ok"

    #@production.errorhandling.BaseHandler
    def submit_to_farm(self):
        sg = Connection('get_project_info').get_sg()
        file_path = FarmAPI.GetKatanaFileName()
        file_name = os.path.basename(file_path)
        userdata = getUserFullFromDB()
        muster_connection = MusterSubmit(userdata)
        shot_name = file_name.split('.')[0]
        listOfJobsToSubmit = []
        #~ this map would write the render node which one need to render single frame with frame number dowm!
        aSingleFrameNodeMap = {}
        # copy tmp file
        base_dir = os.path.dirname(file_path).replace('/work/', '/projcache/')
        user_tmp = os.path.join(base_dir, getpass.getuser() + '_tmp')
        try:
            #katanafile='/mnt/work/home/wangbin/Wb2015/CodeWork/lgtsmp/test.katana'
            self.passedLgtShotSimplifyNode()
        except Exception, e:
            print e
        # get quality
        if not os.path.isdir(user_tmp):
            os.system('mkdir -p ' + user_tmp)
            os.system('chmod -R 777' + user_tmp)
        file_tmp = user_tmp + "/" + "t" + dt.datetime.now().strftime("%s") + "." + \
            os.path.basename(file_path)
        shutil.copyfile(file_path, file_tmp)
        # try:
        #     #katanafile='/mnt/work/home/wangbin/Wb2015/CodeWork/lgtsmp/test.katana'
        #     self.passedlsfnodework(file_tmp)
        # except Exception, e:
        #     print e
        # get quality
        resolution_node = NodegraphAPI.GetNode('AGS_and_RS_Lgt')
        if resolution_node:
            quality = resolution_node.getParameter('user.Resolution').getValue(0).split('_')[1]
            print 'file quality: ', quality
        else:
            resolution_node = NodegraphAPI.GetNode('AGS_and_RS')
            if resolution_node:
                quality = resolution_node.getParameter('user.Resolution').getValue(0).split('_')[1]
                print 'file quality: ', quality
            else:
                msgBox = QtGui.QMessageBox()
                msgBox.setText(u"没有找到AGS_and_RS节点,请检查!")
                msgBox.exec_()
                return

        # get proj name
        lgtshotmaker_node = cku.get_lgt_shot_maker_node()
        if lgtshotmaker_node:
            proj_name = lgtshotmaker_node.getParameter('user.proj').getValue(0).upper()
            print 'project name: ', proj_name
        else:
            msgBox = QtGui.QMessageBox()
            msgBox.setText(u"没有找到lgtshotmaker节点,请检查!")
            msgBox.exec_()
            return

        # find shot sequence and batch eg. p30-2
        seq_name = get_shot_sequence_and_priority(
            shotgun_instance=sg, project_name=proj_name, shot_name=shot_name)

        # camera check
        if not cku.is_camera_latest():
            QtGui.QMessageBox.critical(
                self, 'ERROR', u'摄像机不是最新,请检查', QtGui.QMessageBox.Abort)
            return

        # frame fix
        if self.ui.checkBox_3.checkState() == 2:
            l_renders = []
            # collecting nodes to render
            for i in xrange(0, self.ui.tableWidget.rowCount()):
                if self.ui.tableWidget.item(i, 0).checkState() == 2:
                    l_renders.append(self.ui.tableWidget.item(i, 0).text())
            for i in xrange(0, self.ui.tableWidget_2.rowCount()):
                if self.ui.tableWidget_2.item(i, 0).checkState() == 2:
                    l_renders.append(self.ui.tableWidget_2.item(i, 0).text())
            l_renders = list(set(l_renders))
            if len(l_renders) > 1:
                print u'ERROR:渲染层数大于1'
                return

            render_node = str(l_renders[0])

            # get frame clips
            frame_clips_string = str(self.ui.lineEdit_4.text())
            frame_clips = convert_frames_string_to_frame_list(
                frame_clips_string)

            if frame_clips != None:

                for frame_clip in frame_clips:

                    if re.match('\d{1,4}$', frame_clip) != None:  # type a: ####, no '-'

                        job = {}
                        job['department'] = userdata['department']
                        job['name'] = file_name + '-' + render_node + "-" + \
                            frame_clip + "-" + frame_clip + ' by ' + getpass.getuser()
                        job['outputpath'] = self.output_directory
                        job['file'] = file_tmp
                        job['node'] = render_node
                        job['shot'] = file_name.split(".")[0]
                        job['project'] = proj_name
                        job['f_chunk'] = '1'
                        job['f_start'] = frame_clip
                        job['f_end'] = frame_clip
                        if render_node[-1] == "R":
                            job["isR"] = 1
                        else:
                            job["isR"] = 0
                        job['fix'] = True

                        listOfJobsToSubmit.append(job)
                print listOfJobsToSubmit
        else:

            l_renders = []
            l_renders_sf = []

            # collecting nodes to render
            for i in xrange(0, self.ui.tableWidget.rowCount()):
                if self.ui.tableWidget.item(i, 0).checkState() == 2:
                    if self.ui.tableWidget.item(i, 1).checkState() == 2:
                        l_renders_sf.append(
                            self.ui.tableWidget.item(i, 0).text())
                        aSingleFrameNodeMap[str(self.ui.tableWidget.item(i, 0).text())] = self.ui.tableWidget.item(i, 1).text()
                    else:
                        l_renders.append(self.ui.tableWidget.item(i, 0).text())

            for i in xrange(0, self.ui.tableWidget_2.rowCount()):
                if self.ui.tableWidget_2.item(i, 0).checkState() == 2:
                    if self.ui.tableWidget_2.item(i, 1).checkState() == 2:
                        l_renders_sf.append(
                            self.ui.tableWidget_2.item(i, 0).text())
                        aSingleFrameNodeMap[str(self.ui.tableWidget_2.item(i, 0).text())] = self.ui.tableWidget_2.item(i, 1).text()
                    else:
                        l_renders.append(
                            self.ui.tableWidget_2.item(i, 0).text())

            l_renders = list(set(l_renders))
            l_renders_sf = list(set(l_renders_sf))
            f_start = str(self.ui.lineEdit.text())
            f_end = str(self.ui.lineEdit_2.text())
            f_chunk = str(self.ui.lineEdit_3.text())
            if f_chunk != '1':
                frame_interval_flag = True
            else:
                frame_interval_flag = False

        
            #
            #   Main Section for submit to render
            #

            for render in l_renders:
                render = str(render)

                job = {}
                job['department'] = userdata['department']
                job['name'] = file_name + '-' + render + "-" + \
                    f_start + "-" + f_end + ' by ' + getpass.getuser()
                job['outputpath'] = self.output_directory
                job['fix'] = False
                job['file'] = file_tmp
                job['node'] = render
                job['shot'] = shot_name
                job['project'] = proj_name
                job['f_chunk'] = f_chunk
                job['f_start'] = f_start
                job['f_end'] = f_end
                job['seq_batch'] = seq_name
                job['resolution'] = quality
                if render[-1] == "R":
                    job["isR"] = 1
                else:
                    job["isR"] = 0
                listOfJobsToSubmit.append(job)

            # TODO: optimize code
            for render in l_renders_sf:
                render = str(render)
                
                #~ add single frame number into job map
                if render in aSingleFrameNodeMap:
                    try:
                        print str(aSingleFrameNodeMap[render])
                        single_frame = str(aSingleFrameNodeMap[render])
                    except ValueError:
                        print "Please enter a number instand of string!"
                        single_frame = f_start
                else:
                    single_frame = f_start

                job = {}
                job['department'] = userdata['department']
                job['name'] = file_name + '-' + render + "-" + single_frame + \
                    "-" + single_frame + ' by ' + getpass.getuser()  # single frame
                job['outputpath'] = self.output_directory
                job['file'] = file_tmp
                job['node'] = render
                job['shot'] = file_name.split(".")[0]
                job['project'] = proj_name
                job['f_chunk'] = f_chunk
                job['f_start'] = single_frame
                job['f_end'] = single_frame  # single frame
                job['fix'] = False
                job['seq_batch'] = seq_name
                job['resolution'] = quality
                if render[-1] == "R":
                    job["isR"] = 1
                else:
                    job["isR"] = 0
                listOfJobsToSubmit.append(job)


            # check if the shot is a light rig
            lgt_rig = check_lightrig_shot(sg, proj_name, shot_name) and (userdata['full_name'] in ['liyidong','wulili','xurui'])

            # farm cache random
            cf = ConfigParser.ConfigParser()
            cf.read("/mnt/public/Share/chengshun/conf/farm_cache.conf")
            percentage = cf.getint("random_value", "percentage")
            cymat_flag = os.getenv('CRYPTOMATTE')
            if random.randint(1, 10) < percentage and proj_name in ['TPR', 'CAT'] and shot_name != 'e60560' and userdata['department'] == 'LGT' and not lgt_rig and not cymat_flag:
                print 'using farm cache...'

                # prepare job setup
                p_job = {}
                p_job['file'] = file_tmp
                p_job['name'] = '[prepare]' + \
                    file_name + ' by ' + getpass.getuser()
                p_job['project'] = proj_name
                p_job['cache'] = 'farm-cache'

                err = muster_connection.send_prepare_job(p_job)
                if err == -1:
                    msg_box = QtGui.QMessageBox()
                    msg_box.setText(u"提交prepare任务失败!!! ")
                    msg_box.exec_()
                    return
                p_jobid = str(err)
                print 'prepare job send! ', p_jobid
                muster_IDs = []
                for job in listOfJobsToSubmit:

                    job['dep_id'] = p_jobid
                    err = muster_connection.sendJob_lgt(job)
                    muster_IDs.append(str(err))

                    if err == -1:
                        msg_box = QtGui.QMessageBox()
                        msg_box.setText(u"提交任务失败!!! 层级:" + str(job['node']))
                        msg_box.exec_()
                        return

            else:
                print 'not farm cache...'
                muster_IDs = []
                for job in listOfJobsToSubmit:
                    job['dep_id'] = None
                    err = muster_connection.sendJob_lgt(job)
                    muster_IDs.append(str(err))

                    if err == -1:
                        msg_box = QtGui.QMessageBox()
                        msg_box.setText(u"提交任务失败!!! 层级:" + str(job['node']))
                        msg_box.exec_()

                        return

            # remark & log
            if ((userdata['department'] == 'LGT') | (userdata['department'] == 'administrators')) and self.ui.checkBox_3.checkState() != 2:
                '''
                make symlink after lgt render
                '''
                try:
                    symlink_id=ppj.send_job('/mnt/utility/toolset/tools/lgt/katanta_render_symlink/make_render_symlink.py',
                        proj=proj_name,
                        step='LGT',
                        args=proj_name.lower()+' '+file_name.split(".")[0],
                        job_name_prefix='Make Render Symlink '+file_name,
                        user='******',
                        depends=','.join(muster_IDs))
                    print 'Send farm job to make symlink',symlink_id
                except:
                    raise Exception( traceback.format_exc())

                filters = [
                    ['project', 'name_is', proj_name],
                    ['entity', 'type_is', 'shot'],
                    ['entity', 'name_is', shot_name],
                    ['step', 'name_is', 'lgt'],
                    ['content', 'is', 'lighting'],
                ]

                fields = [
                    'sg_remark'  # remark
                ]

                task = sg.find_one('Task', filters, fields)
                remark = task['sg_remark']
                today = str(dt.date.today().month) + \
                    '/' + str(dt.date.today().day)
                today_isoformat = dt.date.today().isoformat()
                sub_type = quality
                for job in listOfJobsToSubmit:
                    if '_R' in job['node']:
                        sub_type = 'R'
                        break
                if remark == None:
                    remark = today + ' ' + sub_type
                else:
                    if remark.split('\n')[0].split(' ')[0] == today and remark.split('\n')[0].split(' ')[1] != 'COMP':
                        remark = today + ' ' + sub_type + \
                            remark[len(remark.split('\n')[0]):]
                    else:
                        remark = today + ' ' + sub_type + '\n' + remark
                print remark
                sg.update('Task', entity_id=task[
                          'id'], data={'sg_remark': remark})
                # write to log file
                # check if there is a file matchs matchs date
                if os.path.exists('/mnt/public/Share/chengshun/log/lgt/submit_remark/' + today_isoformat):
                    with open('/mnt/public/Share/chengshun/log/lgt/submit_remark/' + today_isoformat, 'r') as f:
                        data = f.read()
                    data = dt.datetime.now().isoformat() + ' ' + getpass.getuser() + \
                        ' ' + shot_name + ' ' + sub_type + '\n' + data
                    with open('/mnt/public/Share/chengshun/log/lgt/submit_remark/' + today_isoformat, 'w') as f:
                        f.write(data)
                else:
                    with open('/mnt/public/Share/chengshun/log/lgt/submit_remark/' + today_isoformat, 'w') as f:
                        f.write(dt.datetime.now().isoformat() + ' ' +
                                getpass.getuser() + ' ' + shot_name + ' ' + sub_type)
                    os.system(
                        'chmod -R 777 ' + '/mnt/public/Share/chengshun/log/lgt/submit_remark/' + today_isoformat)

        msgBox = QtGui.QMessageBox()
        msgBox.setText(u"提交成功. 任务id: " + str(muster_IDs))
        msgBox.exec_()
        muster_connection.disconnect()

        self.close()

        return
Example #16
0
def createKatanaNodes(fileOut = '/tmp/fileDispFromLua.txt'):
    # check if there is a node ('Attribute_Disp') existing if yes delete it
    # existingNode = NodegraphAPI.GetNode('Attribute_Disp')
    # if existingNode :
    #     inputNodePort = existingNode.getInputPortByIndex(0)
    #     outputNodePort = existingNode.getOutputPortByIndex(0)
    #     inputNodePort.connect(outputNodePort)
    #     existingNode.delete()
    inputFile = open(fileOut,'a')
    node = NodegraphAPI.GetAllSelectedNodes()[0] # select the node
    nodePos = NodegraphAPI.GetNodePosition(node) # get the position of node
    nodeOutPort = node.getOutputPortByIndex(0) # get the output port
    nextPort = nodeOutPort.getConnectedPorts()[0] # get the first connected port from the previous node

    # create the opscript node
    root = NodegraphAPI.GetRootNode()
    opscriptFindDisp = NodegraphAPI.CreateNode('OpScript',root)
    opscriptFindDisp.setName('findDisp')
    opscriptFindDisp.getParameter('CEL').setValue('/root/world//*{hasattr("materialOverride.parameters.dsp_map")}',0)
    opscriptFindDispUserParam = opscriptFindDisp.getParameters().createChildGroup('user')
    opscriptFindDispUserParamFileOut = opscriptFindDispUserParam.createChildString('fileOut',fileOut)
    opscriptFindDisp.getParameter('script.lua').setValue("local getdispMap = require 'dispFunc'\ngetdispMap.getDispMap()",0)
    opscriptFindDispInPort = opscriptFindDisp.getInputPort('i0')
    opscriptFindDispOutPort = opscriptFindDisp.getOutputPort('out')
    nodeOutPort.connect(opscriptFindDispInPort)
    opscriptFindDispOutPort.connect(nextPort)
    NodegraphAPI.SetNodePosition(opscriptFindDisp, (nodePos[0]+50,nodePos[1]-50))
    opscriptFindDispPos = NodegraphAPI.GetNodePosition(opscriptFindDisp)
    # set the view and the edit on the opscript node
    NodegraphAPI.SetNodeViewed(opscriptFindDisp, True, exclusive=True)
    NodegraphAPI.SetNodeEdited(opscriptFindDisp, True, exclusive=True)

    # dummy functions to run the opscript and create the file
    sg = ScenegraphManager.getActiveScenegraph()
    node = NodegraphAPI.GetNode( 'root' )
    time = NodegraphAPI.GetCurrentTime()
    producer = Nodes3DAPI.GetGeometryProducer( node, time)
    prod = producer.getProducerByPath('/root')
    WalkBoundAttrLocations(prod)

    # extract the dip for each map
    assetWithDisp = findDispHeight(fileOut)

    # create a stack of AttributeSet to set the disp if there is element in the dict
    if len(assetWithDisp.keys()):
        stack = NodegraphAPI.CreateNode("GroupStack", NodegraphAPI.GetRootNode())
        stack.setName('Attribute_Disp')
        stack.setChildNodeType("AttributeSet")
        listWord = ['/location/','/prop/','/location/','/character/']
        for key in assetWithDisp.keys():
            path = ''
            attributSet = stack.buildChildNode()
            attributSet.getParameter('mode').setValue('CEL',0)
            attrPath = attributSet.getParameter('celSelection')
            attributSet.getParameter('attributeType').setValue('float',0)
            # replace the word from listWord by the wildcard '/*' so to work in lighting scene
            for word in listWord:
                if key.find(word) > 1:
                    path = key.replace(word,'//*/')
                    attrPath.setValue(path,0)
                    break
                else:
                    attrPath.setValue(key,0)
            attributSet.setName(key[key.rfind('/')+1:]) # set name to the _hi
            attrValue = attributSet.getParameter('numberValue.i0')
            attrValue.setValue(assetWithDisp[key],0)
            attrName = attributSet.getParameter('attributeName')
            attrName.setValue('arnoldStatements.disp_padding',0)
        NodegraphAPI.SetNodePosition(stack,opscriptFindDispPos)
        stackInPort = stack.getInputPort('in')
        stackOutPort = stack.getOutputPort('out')
        nodeOutPort.connect(stackInPort)
        stackOutPort.connect(nextPort)
        NodegraphAPI.SetNodeViewed(stack, True, exclusive=True)
        NodegraphAPI.SetNodeEdited(stack, True, exclusive=True)
    else:  # reconnect the nodes
        nodeOutPort.connect(nextPort)
        NodegraphAPI.SetNodeViewed(node, True, exclusive=True)
        NodegraphAPI.SetNodeEdited(node, True, exclusive=True)

    # delete the opscript and the file
    opscriptFindDisp.delete()
    os.remove(fileOut)
    print 'finished'
Example #17
0
 def passedLgtShotSimplifyNode(self):
     lgtsimplifynode=NodegraphAPI.GetNode('LgtShotSimplify_')
     if lgtsimplifynode:
         lgtsimplifynode.setBypassed(True)
         KatanaFile.Save(FarmAPI.GetKatanaFileName())
         print "setBypassed ok"
    def waitConnect(self):
        informationTuple = self.depthDigger()
        surfaceNodeList = informationTuple[0].keys()

        connectionList = []
        shadingNodeMap = self.shadingNodeMap
        for shadingNode in shadingNodeMap:
            nodeType = self.translateMayaType(
                shadingNodeMap[shadingNode]["__NodeType"])
            self.shadingNodeTypeMap[shadingNode] = nodeType
        """Get connectionList"""
        for shadingNode in shadingNodeMap:
            for attr in shadingNodeMap[shadingNode]:
                if type(shadingNodeMap[shadingNode][attr]) is dict:
                    attrPort = shadingNodeMap[shadingNode][attr]["connection"]
                    tempMap = {
                        "downstream": [shadingNode, attr],
                        "upstream":
                        [attrPort.split(".")[0],
                         attrPort.split(".")[-1]]
                    }
                    connectionList.append(tempMap)
        """Connect Surface to NetworkMaterial"""
        for surface in surfaceNodeList:
            downstreamName = "%s_%s" % (surface, self.suffixNetworkMaterial)
            downstreamNode = NodegraphAPI.GetNode(str(downstreamName))
            upstreamName = surface
            upstreamNode = NodegraphAPI.GetNode(upstreamName)
            downstreamNode.getInputPort("arnoldSurface").connect(
                upstreamNode.getOutputPort("out"))
        """Connect attributes"""
        for connection in connectionList:
            downstream = connection["downstream"]
            upstream = connection["upstream"]
            downstreamNode = NodegraphAPI.GetNode(downstream[0])
            upstreamNode = NodegraphAPI.GetNode(upstream[0])
            input = self.translateMayaAttr(
                self.shadingNodeTypeMap[downstream[0]], downstream[1])
            output = self.translateMayaAttr(
                self.shadingNodeTypeMap[upstream[0]], upstream[1])
            "Connect normal map"
            if input == "normalCamera":
                materialName = "%s_%s" % (downstream[0],
                                          self.suffixNetworkMaterial)
                input = 'arnoldBump'
                downstreamNode = NodegraphAPI.GetNode(str(materialName))
            try:
                downstreamNode.getInputPort(input).connect(
                    upstreamNode.getOutputPort(output))
            except AttributeError:
                #print input,output
                node = NodegraphAPI.GetNode(str(downstream[0]))
                paraList = self.getParameterList(upstream[0])
                name = downstream[0]
                self.setParameter(node, name, paraList)
                #print downstream,upstream
                #print "--------------"
        #print "############################"
        for connection in connectionList:
            downstream = connection["downstream"]
            attrName = self.translateMayaAttr(
                self.shadingNodeTypeMap[downstream[0]], downstream[1])
            try:
                activeNode = NodegraphAPI.GetNode(str(downstream[0]))
                activeNode.getParameter('parameters.%s.enable' %
                                        attrName).setValue(2, 0)
            except AttributeError:
                #print downstream[0],attrName
                pass
Example #19
0
def set_file_path():
	# TODO 接受用户输入数值
	path = NodegraphAPI.GetNode('RenderOutputDefine').getParameter('args.renderSettings.outputs.outputName.locationSettings.renderLocation.value').getValue(0)
		return path
Example #20
0
def load_asset_data(knode):
    pipe_parameter = knode.getParameter('studio_pipe')
    asset_node = pipe_parameter.getChild('asset_node').getValue(1.0) 
    message = None
    if not asset_node:
        message = 'Not fond any valid lookdev asset nodes'
    kasset_node = NodegraphAPI.GetNode(asset_node)
    if not kasset_node:
        message = 'current node not valid'
    if message:
        QtGui.QMessageBox.warning(
            None, 'warning', message, QtGui.QMessageBox.Ok)
        return      
    show_path = kasset_node.getParameter('show_path').getValue(1.0)
    category = kasset_node.getParameter('model_category').getValue(1.0)
    name = kasset_node.getParameter('model_name').getValue(1.0)
    location = os.path.join(
        studio_nodes.SCENE_GRAPH_LOCATION, category, name)
    producer = scenegraph.get_producer(kasset_node, location=location)
    if not producer:
        message = 'not found any asset categories'
        QtGui.QMessageBox.warning(
            None, 'warning', message, QtGui.QMessageBox.Ok)
        return   
    input_attributes = [
        'name',
        'category',
        'type',
        'version',
        'model',
        'lookdev'
        ]
    attributes = []
    for input_attribute in input_attributes:    
        attributes.append('geometry.arbitrary.%s.value' % input_attribute)
    attribute_values = scenegraph.get_attribute_values(producer, attributes)
    input_values = {}
    for k, v in attribute_values.items():
        current_attribute = k.rsplit('.', 2)[1]
        input_values.setdefault(current_attribute, v)       
    pipe_parameter.getChild('show_path').setValue(show_path, 1.0)    
    pipe_parameter.getChild('name').setValue(input_values['name'], 1.0)
    pipe_parameter.getChild('category').setValue(input_values['category'], 1.0)
    pipe_parameter.getChild('type').setValue('lookdev', 1.0)
    pipe_parameter.getChild('model').setValue(input_values['version'], 1.0)
    pipe_parameter.getChild('lookdev').setValue('None', 1.0)    
    camera_location = os.path.join(
        studio_nodes.SCENE_GRAPH_LOCATION, 'camera')
    camera_producer = scenegraph.get_producer(kasset_node, location=camera_location)
    camera_producers = scenegraph.list_specific_producer(camera_producer, 'camera')
    if not camera_producers:
        message = 'not found camera in the scene'
        QtGui.QMessageBox.warning(
            None, 'warning', message, QtGui.QMessageBox.Ok)
        return   
    pipe_parameter.getChild('render_camera').setValue(camera_producers[0].getFullName(), 1.0) 
    render_path = os.path.join(
        show_path,
        'dumps',
        'render',
        'lookdev',
        input_values['name'],
        'render.exr'
        )
    pipe_parameter.getChild('render_location').setValue(render_path, 1.0) 
Example #21
0
#This script will create a Transform3D for each location selected in the
#scenegraph below the selected node.
import sys
from Katana import Nodes3DAPI
from Katana import NodegraphAPI
from Katana import ScenegraphManager
#Get scenegraph seletion.
selectedGroups = ScenegraphManager.getActiveScenegraph().getSelectedLocations()
#Get seleted node
try:
    baseNode = NodegraphAPI.GetNode(
        NodegraphAPI.GetAllSelectedNodes()[0].getName())
except:
    sys.exit("Select a node on the nodegraph")

for i in selectedGroups:
    y = 50  #inital node position on nodegraph
    try:
        previousNode = NodegraphAPI.GetNode(
            NodegraphAPI.GetAllSelectedNodes()[0].getName())
    except IndexError:
        break
    previousNodePosition = NodegraphAPI.GetNodePosition(previousNode)
    xpos = previousNodePosition[0]
    ypos = previousNodePosition[1] - y
    t3d = NodegraphAPI.CreateNode("Transform3D", NodegraphAPI.GetRootNode())
    t3d.getParameter("path").setValue(i, 0)
    t3d.getParameter("makeInteractive").setValue("Yes", 0)
    NodegraphAPI.SetNodePosition(t3d, [xpos, ypos])
    #ports change names so trying more than one.
    try: