Exemplo n.º 1
0
def get_re_texture_nodes():
    """ Get all Render Engine Katana Texture/File nodes

    Returns:
        dict: Dictionnary of {KatanaNode:[file_path value, file_path_parameter]}
    Raises:
        ValueError
    """
    retex_node_dict = {}

    all_node_list = NodegraphAPI.GetAllNodesByType('ArnoldShadingNode', includeDeleted=False, sortByName=True)
    for ktnnode in all_node_list:
        # check if you can get the type of the node
        try:
            node_type_value = ktnnode.getParameter("nodeType").getValue(0)
        except:
            continue

        if node_type_value == "image":
            # try to get the file_path in the TextureSampler
            ts_path_param = ktnnode.getParameter('parameters.filename')
            try:
                file_path = str(ts_path_param.getValue(0))
            except Exception as excp:
                logger.warning("Cannot get the filepath for node {}: {}".format(ktnnode, excp))
                continue  # skip to the next item

            if file_path:
                retex_node_dict[ktnnode] = [os.path.normpath(file_path), ts_path_param]

    if retex_node_dict:
        return retex_node_dict
    else:
        raise ValueError("No textures find in scene")
    def initialize(self):
        for item in NodegraphAPI.GetAllNodesByType("LiveGroup", ):
            itemSource = item.getParameterValue("source",
                                                NodegraphAPI.GetCurrentTime())
            if itemSource:
                if itemSource[0] != "$":
                    itemName = item.getName()
                    self.dLiveGroupList.append(str(itemName))
                    self.dLiveGroupSourceMap[str(itemName)] = str(itemSource)
            else:
                itemName = item.getName()
                self.dLiveGroupList.append(str(itemName))
                self.dLiveGroupSourceMap[str(itemName)] = str(itemSource)

        ###############################################################
        # tmpLiveGroupSource keeps all source value from LiveGroup Node
        tmpLiveGroupSource = self.dLiveGroupSourceMap.values()
        aLiveGroupSource = []
        for item in tmpLiveGroupSource:
            if item:
                Len = len(item.split("/")[-1])
                aLiveGroupSource.append(item[:-Len])
        if aLiveGroupSource:
            self.configPath = self.getMostCount(
                aLiveGroupSource)[0] + "config.json"

        #print "@@@@@@@@@@@@@@@@@@@@@"
        #print self.configPath
        #print os.path.abspath(self.configPath)
        if os.path.isfile(self.configPath):
            file = open(self.configPath, "rb")
            self.dLiveGroupData = json.load(file)
            file.close()
        else:
            self.configPath = ""
Exemplo n.º 3
0
def getRootPackage(node):
    group_nodes = NodegraphAPI.GetAllNodesByType("Group", includeDeleted=False)
    root_package_node = None
    for group_node in group_nodes:
        node_mark = group_node.getParameter('__gaffer.packageType')
        if node_mark and node_mark.getValue(0) == "RootPackage":
            parentNode = group_node.getParent()
            if parentNode is node:
                root_package_node = group_node;break
    return root_package_node
Exemplo n.º 4
0
def locationsToNodes(locations=[], time=0.0, return_top_node=False):
    if not isinstance(locations, list):
        locations = [locations]
    nodes = {}
    root_producer = getRootProducer()
    type_node_map = getLocationNodeMaps()
    for l in locations:
        location_producer = root_producer.getProducerByPath(l)
        location_type = location_producer.getType()
        if location_type not in type_node_map.keys():
            nodes.update({l: None})
            continue

        # find all the node types correspond to the location type
        node_types = type_node_map[location_type].keys()
        for nt in node_types:
            if nodes.has_key(l):
                break
            # get all nodes with specific type
            tmp = NodegraphAPI.GetAllNodesByType(nt)
            for n in tmp:
                isTarget = True
                # first check the conditions on the specific node
                conditions = type_node_map[location_type][nt]['others']
                for c in conditions:
                    if n.getParameter(c[0]).getValue(time) != c[1]:
                        isTarget = False
                        break
                if not isTarget:
                    continue
                # get the location path
                path = '/'
                params = type_node_map[location_type][nt]['parameters']
                for p in params:
                    value = n.getParameter(p).getValue(time)
                    if value.startswith('/'):
                        value = value[1:]
                    path = os.path.join(path, value)
                if path.strip() != l.strip():
                    isTarget = False

                if isTarget:
                    # this is the node we find
                    if return_top_node:
                        n = ng_traverseGroupUp(n)
                    nodes.update({l: n})
                    break
        if not nodes.has_key(l):
            nodes.update({l: None})

    return nodes
Exemplo n.º 5
0
def get_scene_typed_nodes(node_type):
    '''
    :description get all the nodes with the specified type.
    :param node_type <str>
    :example
        from core import nodegraph
        scene_nodes = nodegraph.get_scene_typed_nodes('Alembic_In')
        print scene_nodes        
    '''
    knodes = NodegraphAPI.GetAllNodesByType(node_type, includeDeleted=False)
    nodes = []
    for knode in knodes:
        nodes.append(knode.getName())
    return nodes
Exemplo n.º 6
0
def setParameterNodeGraph(parameter_name,
                          value,
                          time=1.0,
                          t='',
                          selected=False,
                          recursive=False):
    '''
    this method set the given paramter to the given value on all the nodes in the node graph,
    if selected is True, then only selected nodes will be affected,
    if recursive is True, then the group nodes will be expanded recursivly if any,
    
    By default, we set the value at time 1.0, this can be changed by specifying the time, and
    node with any type will be targeted. If you want to shrink the nodes down to the type of 'Alembic_In' 
    for instance, then you can specify t='Alembic_In'

    obsoleted:
    if strictly is True, then we use strict name matching rule to look up the given parameters,
    otherwise it will be true if the lower case of the given parameter name is included in the lower 
    case of the parameter name on the nodes.
    '''
    if t and isinstance(t, str):
        nodes = NodegraphAPI.GetAllNodesByType(t)
    else:
        nodes = NodegraphAPI.GetAllNodes()
    if selected:
        sel_nodes = NodegraphAPI.GetAllSelectedNodes()
        if recursive:
            sel_nodes = ng_traverseGroupDown(sel_nodes)
        nodes = list(set(nodes).intersection(sel_nodes))
    # set attribute
    log = ''
    for n in nodes:
        # lets try to access the parameter directly
        param = n.getParameter(parameter_name)
        if param:
            param.setUseNodeDefault(False)
            param.setValue(value, time)
            log += ('%s: %s at time %s\n') % (param.getFullName(), str(value),
                                              str(time))
            continue
        # get the parameters' objects
        params = setParameters({parameter_name: [value, time]}, n)
        if params:
            log += ('%s: %s at time %s\n') % (params[0].getFullName(),
                                              str(value), str(time))
    if log:
        print log
Exemplo n.º 7
0
    def _get_all_render_node_paths(self):
        """
        Get all the paths and their enabled state from all the render nodes.

        :rtype: `dict`
        """
        if not hasattr(self, "__render_paths"):
            def false_factory():
                return False
            render_paths = defaultdict(false_factory)
            render_nodes = NodegraphAPI.GetAllNodesByType("Render")
            for node in render_nodes:
                outputs = node.getParameter("outputs")
                locations = [x.getValue(0) for x in outputs.getChild("locations").getChildren()]
                enabled_flags = [x.getValue(0) for x in outputs.getChild("enabledFlags").getChildren()]
                for path, enabled in zip(locations, enabled_flags):
                    render_paths[path] |= bool(enabled)  # At least one enabled to make it enabled
            self.__render_paths = dict(render_paths)
        return self.__render_paths
Exemplo n.º 8
0
def addAllCamToRenderManager(layerName = 'ALL', camPattern = 'CameraLeftShape'):
    nodeSelected = NodegraphAPI.GetAllSelectedNodes()
    renderManagerNode = None
    for node in nodeSelected:
        if node.getType() != 'RenderManager':
            nodeSelected.remove(node)
    if len(nodeSelected) > 1:
        raise NameError('Select only 1 RenderManager node')
    elif len(nodeSelected) == 0:
        nodeRender = NodegraphAPI.GetAllNodesByType('RenderManager', includeDeleted=False)
        if len(nodeRender) == 0:
            raise NameError("there is no RenderManager in the scene, create one")
        elif len(nodeRender) > 1:
            raise NameError('Select  1 RenderManager node')
        else:
            renderManagerNode = nodeRender[0]
    else:
        renderManagerNode = nodeSelected[0]

    rndLayer = None
    for item in renderManagerNode.getRenderLayers():
        if item.getName() == layerName:
            rndLayer = item
        else:
            rndLayer = renderManagerNode.addRenderLayer(layerName)

    producer = Nodes3DAPI.GetGeometryProducer(renderManagerNode, 0)
    camproducer = producer.getProducerByPath("/root/world/cam")
    children = []
    allCameraPath =[]
    kAttr.walkChildrenProducer(camproducer, children)
    cameraPath = None
    for child in children :
         if child.getType() == "camera" and child.getFullName().find(camPattern ) > 0:
              allCameraPath.append(child.getFullName())
    for cam in sorted(allCameraPath):
        rendrOutput = renderManagerNode.addRenderOutput(cam,rndLayer)
        renderNode = rendrOutput.getRenderNode()
        start = renderNode.getParameter('user.start')
        end = renderNode.getParameter('user.end')
        start.setExpressionFlag(False)
        end.setExpressionFlag(False)
 def __getNetworkMaterials(self) :
     return NodegraphAPI.GetAllNodesByType('NetworkMaterial')
    def __getAllShadingNetworkNodes(self) :

        nodes = NodegraphAPI.GetAllNodesByType('ArnoldShadingNode')
        nodes.extend( NodegraphAPI.GetAllNodesByType('PrmanShadingNode') )
        return nodes 
Exemplo n.º 11
0
    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