예제 #1
0
def findNodeByType(context, pattern):
    import fnmatch

    nodeTypeCategories = {}
    nodeTypeCategories['Object'] = hou.objNodeTypeCategory()
    nodeTypeCategories['Sop'] = hou.sopNodeTypeCategory()
    nodeTypeCategories['Vop'] = hou.vopNodeTypeCategory()
    nodeTypeCategories['Dop'] = hou.dopNodeTypeCategory()
    nodeTypeCategories['Cop2'] = hou.cop2NodeTypeCategory()
    nodeTypeCategories['Chop'] = hou.chopNodeTypeCategory()
    nodeTypeCategories['Shop'] = hou.shopNodeTypeCategory()
    nodeTypeCategories['Driver'] = hou.ropNodeTypeCategory()
    nodeTypeCategories['Top'] = hou.topNodeTypeCategory()
    nodeTypeCategories['Lop'] = hou.lopNodeTypeCategory()

    category = nodeTypeCategories[context]

    nodes = [
        nodetype for nodetypename, nodetype in category.nodeTypes().items()
        if fnmatch.fnmatch(nodetypename, pattern)
    ]

    if nodes:
        return nodes[0]
    else:
        return None
예제 #2
0
    def __init__(self,
                 node,
                 respect_bypass=True,
                 respect_lock=True,
                 ignore_hda_locked=True,
                 ignore_categories=None):
        """ Represents a node during a node traversal.
        Args:
            node (hou.Node): Node to operate on.
            respect_bypass (bool): Ignore references on nodes that are bypassed.
            respect_lock (bool): Ignore input nodes that are locked.
            ignore_hda_locked (bool): Ignore nodes locked in hdas.
            ignore_categories (list): Ignore categories of nodes.
        """
        self.node = node
        self.traversed = dict()
        try:
            bypassed = node.isBypassed()
        except AttributeError:
            bypassed = False
        self.inputs = [x for x in node.inputs() if x]
        if respect_lock:
            try:
                self.inputs = [x for x in self.inputs if not x.isHardLocked()]
            except AttributeError:
                pass
        self.outputs = [x for x in node.outputs() if x]
        self.connected = self.inputs + self.outputs
        self.ignore_hda_locked = ignore_hda_locked

        ignore_categories = ignore_categories or []
        if hou.vopNodeTypeCategory() not in ignore_categories:
            ignore_categories.append(hou.vopNodeTypeCategory())
        self.ignore_categories = ignore_categories

        if bypassed and respect_bypass:
            self.references = []
        else:
            self.references = self._get_references()

        self.child_output = []
        if not self.node.isLockedHDA():
            self.child_output = list(get_child_output(node))

        self.to_traverse = self.references + self.inputs + self.child_output
예제 #3
0
파일: megaH.py 프로젝트: vinyvince/megaH
    def getShaders(self, node):
        shaderInstances = []
        try:
            shaderInstances = hou.nodeType(hou.vopNodeTypeCategory(),
                                           self.shader).instances()
        except:
            pass

        shader = "--- shader not found ---"

        if len(shaderInstances) != 0:
            shader = shaderInstances[0].path()

        node.parm("shader").set(shader)
    def get_node_instances(self, type_name = ADDITIONAL_AOVS_NODE_TYPE):
        """
        Return list of all node instances in the scene with type type_name.
        """

        #node_type
        node_type = hou.nodeType(hou.vopNodeTypeCategory(), type_name)
        #check
        if not (node_type):
            #log
            self.logger.debug('Wrong node_type {0}. Could not set aov attributes.'.format(type_name))
            return []

        #node_instances_list
        node_instances_list = list(node_type.instances())

        #return
        return node_instances_list
예제 #5
0
def loadContents(network, ctx, type_ctx, filename):
    if type_ctx == hou.objNodeTypeCategory():
        hdaAsset(network, ctx, filename)

    if type_ctx == hou.objNodeTypeCategory():
        objGeom(network, ctx, filename)

    if type_ctx == hou.sopNodeTypeCategory():
        sopGeom(network, ctx, filename)

    if type_ctx == hou.vopNodeTypeCategory():
        shopImages(network, ctx, filename)

    if type_ctx == hou.chopNodeTypeCategory():
        chanFiles(network, ctx, filename)

    if type_ctx == hou.cop2NodeTypeCategory():
        copImages(network, ctx, filename)
예제 #6
0
    def get_node_instances(self, type_name=ADDITIONAL_AOVS_NODE_TYPE):
        """
        Return list of all node instances in the scene with type type_name.
        """

        #node_type
        node_type = hou.nodeType(hou.vopNodeTypeCategory(), type_name)
        #check
        if not (node_type):
            #log
            self.logger.debug(
                'Wrong node_type {0}. Could not set aov attributes.'.format(
                    type_name))
            return []

        #node_instances_list
        node_instances_list = list(node_type.instances())

        #return
        return node_instances_list
예제 #7
0
class PrincipledShader(_BaseTexture):
    """This class represents a texture of a principledshader in Houdini
    """

    # get principledshader node type
    _sType = hou.nodeType(hou.vopNodeTypeCategory(), "principledshader::2.0")
    # add supported texture attributes
    _attrNames = ["basecolor_texture", "ior_texture", "rough_texture"]

    def __init__(self, node, texAttr):
        """Initializer
        node -- a file node object in Maya
        texAttr -- texture attribute name
        """
        super(PrincipledShader, self).__init__()

        self._node = node
        self._texAttr = texAttr
    
    def setPath(self, filePath):
        """Sets the texture path to filePath
        """
        self._node.parm(self._texAttr).set(filePath.replace("\\", "/"))

    def getPath(self):
        """Returns the file path of the texture
        """
        return os.path.normpath(self._node.parm(self._texAttr).eval())
    
    @classmethod
    def getAllObjects(cls):
        """Returns all the objects of this texture type from the scene
        return -- list
        """

        # create of list textures objects to be returned
        return [
                cls(node, attrName) for node in cls._sType.instances()
                for attrName in cls._attrNames
                if node.parm(attrName).eval() # if it does have a texture
                ]
예제 #8
0
def find_file_references(node, inspect_hda=False, skip_vops=True):
    """ Find file references for specified node.
    Args:
        node (hou.Node): Node to operate on.
        inspect_hda (bool): Inspect child nodes of hdas.
        skip_vops (bool): Skip vop nodes, improving performance.

    Returns:
        tuple: List of file references found.
    """
    refs = set()
    if inspect_hda and not node.isEditable():
        nodes = [node]
        nodes.extend(node.allSubChildren())
    else:
        nodes = [node]
    if skip_vops:
        nodes = [
            n for n in nodes
            if n.type().category() != hou.vopNodeTypeCategory()
        ]
    for inode in nodes:
        inode.updateParmStates()
        for parm in inode.parms():
            if not parm.parmTemplate().dataType() == hou.parmData.String:
                continue
            elif parm.isDisabled():
                continue
            elif parm.getReferencedParm().node in nodes:
                continue
            val = parm.eval()
            if val in refs:
                continue
            elif inode.node(val):
                continue
            elif is_valid_file(val):
                refs.add(val)

    return tuple(refs)
    def generateTextures(objNode):
        print("OBJ: \"%s\"" % (objNode.path()))

        vopTypes = hou.vopNodeTypeCategory().nodeTypes()
        vrayVopTypes = sorted(
            [vopType for vopType in vopTypes if vrayVopFilter(vopType)])

        # FOR TESTS
        # vrayVopTypes = vrayVopTypes[:2]

        bbox = objNode.renderNode().geometry().boundingBox()
        bboxWidth = bbox.sizevec().x()
        bboxDepth = bbox.sizevec().z()

        col = 0
        row = 0
        bboxOffsetPerc = 2.0
        offsetX = bboxWidth * bboxOffsetPerc
        offsetY = bboxDepth * bboxOffsetPerc
        cellW = bboxWidth + offsetX
        cellD = bboxDepth + offsetY
        maxColCount = int(math.sqrt(len(vrayVopTypes)))

        matNet = getCreateEmpty(MAT, "vray_material", "TEXTURES_ALL_PER_FRAME")
        objNet = getCreateEmpty(OBJ, "subnet", "TEXTURES_ALL_PER_FRAME")

        fontMat = getCreate(MAT, "VRayNodeBRDFVRayMtl", "font")
        fontMat.setMaterialFlag(True)
        fontMat.parm("diffuser").set(0.05)
        fontMat.parm("diffuseg").set(0.05)
        fontMat.parm("diffuseb").set(0.05)

        uvw = matNet.createNode("VRayNodeUVWGenMayaPlace2dTexture",
                                node_name="channel_uv")
        uvw.parm("repeat_u").set(3)
        uvw.parm("repeat_v").set(3)

        for texType in vrayVopTypes:
            tex = None
            texName = texType.replace(PREFIX, "")

            try:
                mtl = matNet.createNode("VRayNodeBRDFVRayMtl",
                                        node_name="mtl%s" % texName)

                # Attach texture to "diffuse".
                tex = mtl.createInputNode(0, texType, node_name=texName)

                uvwGenIndex = tex.inputIndex("uvwgen")
                if uvwGenIndex >= 0:
                    tex.setNamedInput("uvwgen", uvw, 0)
            except:
                print("Failed: \"%s\"" % (texType))

            if tex:
                objForTex = getCreateEmpty(objNet, "geo", "obj%s" % texName)

                # Copy source geo.
                hou.copyNodesTo(objNode.children(), objForTex)

                testMtl = objForTex.createNode("material")
                testMtl.setNextInput(objForTex.renderNode())

                # Assign material
                objForTex.parm("shop_materialpath").set("")
                testMtl.parm("shop_materialpath1").set(mtl.path())

                # Add text
                font = objForTex.createNode("font")
                font.parm("file").set("Consolas")
                font.parm("text").set(texName)
                font.parm("fontsize").set(0.2)

                fontDivide = objForTex.createNode("divide")
                fontDivide.setNextInput(font)

                fontExt = objForTex.createNode("polyextrude")
                fontExt.parm("dist").set(0.02)
                fontExt.setNextInput(fontDivide)

                fontTm = objForTex.createNode("xform")
                fontTm.setNextInput(fontExt)
                fontTm.parm("tx").set(0.3)
                fontTm.parm("rx").set(-90.0)
                fontTm.parm("ry").set(90.0)

                fontMtl = objForTex.createNode("material")
                fontMtl.setNextInput(fontTm)
                fontMtl.parm("shop_materialpath1").set(fontMat.path())

                merge = objForTex.createNode("merge")
                merge.setNextInput(testMtl)
                merge.setNextInput(fontMtl)
                merge.setDisplayFlag(True)
                merge.setRenderFlag(True)

                objForTex.layoutChildren()

                pos = (row * cellD, 0, col * cellW)

                tm = hou.hmath.buildTranslate(pos)
                objForTex.setWorldTransform(tm)

                if col == maxColCount - 1:
                    col = 0
                    row += 1
                else:
                    col += 1

        matNet.layoutChildren()
        objNet.layoutChildren()
def handleEventCoroutine():
    visiblebounds = hou.BoundingRect()
    halfsize = utils.getNewNodeHalfSize()
    minsize = min(halfsize.x(), halfsize.y())
    maxsize = max(halfsize.x(), halfsize.y())
    inputnames = ('input', 'multiinput', 'dotinput')
    outputnames = ('output', 'indirectinputoutput', 'dotoutput')
    alignrects = []
    shapes = []
    nodecenter = None
    locatedconn = None
    locatedinput = None
    locatedoutput = None
    handler = None
    editor = None
    olddefaultcursor = None
 
    while True:
        uievent = yield
        if editor is None:
            editor = uievent.editor
            olddefaultcursor = editor.defaultCursor()
 
        if handler is not None:
            handler = sendEventToHandler(handler, uievent, shapes)
            if handler is None:
                editor.setDefaultCursor(olddefaultcursor)
            continue
 
        newvisiblebounds = editor.visibleBounds()
        if visiblebounds != newvisiblebounds:
            alignrects = editor.allVisibleRects([])
            visiblebounds = newvisiblebounds
 
        if (isinstance(uievent, KeyboardEvent) or \
            isinstance(uievent, MouseEvent)):
            if nodecenter is None:
                nodecenter = uievent.mousepos
                nodecenter = editor.posFromScreen(nodecenter)
 
            # Check for a wire to drop the node on, if that pref is enabled.
            # Don't update the target on a mouse up event. We want to keep
            # the located/selected target from the last mouse event, since the
            # selected value gets cleared on the mouseup event.
            if prefs.allowDropOnWire(editor) and uievent.eventtype != 'mouseup':
                target = None
                if isinstance(uievent, MouseEvent) and \
                   uievent.selected.item is not None:
                    target = uievent.selected
                elif uievent.located.item is not None:
                    target = uievent.located
                locatedconn = None
                locatedinput = None
                locatedoutput = None
                if target is not None:
                    if isinstance(target.item, hou.NodeConnection):
                        locatedconn = target
                    elif target.name in inputnames:
                        locatedinput = target
                    elif target.name in outputnames:
                        locatedoutput = target
                if locatedconn is None and \
                   locatedinput is None and \
                   locatedoutput is None:
                    editor.setDefaultCursor(None)
                else:
                    editor.setDefaultCursor(utils.theCursorDragDropOn)
 
        if isinstance(uievent, KeyboardEvent):
            if uievent.eventtype.endswith('keyhit') and \
               display.setKeyPrompt(editor, uievent.key,
                                    'h.pane.wsheet.cancel', uievent.eventtype):
                break
 
            if uievent.eventtype.endswith('keyhit') and \
               display.setKeyPrompt(editor, uievent.key,
                                    'h.pane.wsheet.add_op', uievent.eventtype):
                # Indicate that the keyboard event should be sent again, which
                # will allow it to be handled by the parent context (and open
                # up the tab menu).
                editor.handleCurrentKeyboardEvent(True)
                break
 
            elif uievent.eventtype == 'keyhit' and uievent.key == 'Enter':
                editor.eventContextData()['pos'] = nodecenter - halfsize
                setEventContextData(editor.eventContextData(),
                    locatedconn, locatedinput, locatedoutput)
                break
 
            elif uievent.eventtype == 'keyhit' and uievent.key == 'Shift+Enter':
                editor.eventContextData()['pos'] = None
                setEventContextData(editor.eventContextData(),
                    locatedconn, locatedinput, locatedoutput)
                break
 
        elif isinstance(uievent, MouseEvent):
            if uievent.eventtype == 'mousewheel':
                view.scaleWithMouseWheel(uievent)
 
            elif uievent.eventtype == 'mousedown':
                if uievent.selected.name.startswith('overview'):
                    handler = base.OverviewMouseHandler(uievent)
                elif base.isPanEvent(uievent):
                    handler = base.ViewPanHandler(uievent)
                elif base.isScaleEvent(uievent):
                    handler = base.ViewScaleHandler(uievent)
                if handler is not None:
                    editor.setDefaultCursor(olddefaultcursor)
                    handler = sendEventToHandler(handler, uievent, shapes)
 
            elif uievent.eventtype == 'mouseup':
                editor.eventContextData()['pos'] = nodecenter - halfsize
                setEventContextData(editor.eventContextData(),
                    locatedconn, locatedinput, locatedoutput)
                break
 
            else:
                nodecenter = uievent.mousepos
                nodecenter = editor.posFromScreen(nodecenter)
                category = editor.pwd().childTypeCategory()
                # If we are showing a preview of the node shape, we need to
                # pass a large square to ensure the shape draws at the
                # expected size.               
 
                if prefs.showNodeShapes(editor) and \
                   category != hou.vopNodeTypeCategory():
                    halfmaxsize = hou.Vector2(maxsize, maxsize)
                    rect = hou.BoundingRect(nodecenter - halfmaxsize,
                                            nodecenter + halfmaxsize)
                else:
                    rect = hou.BoundingRect(nodecenter - halfsize,
                                            nodecenter + halfsize)
                snapresult = snap.snap(editor, None, rect, alignrects)
                if snapresult.isValid():
                    nodecenter += snapresult.delta()
                    rect.translate(snapresult.delta())
                '''
                if prefs.showNodeShapes(editor):
                    nodeshape = ''
                    nodetypename = editor.eventContextData()['nodetypename']
                    if category is not None:
                        nodetype = category.nodeType(nodetypename)
                        if nodetype is not None:
                            nodeshape = nodetype.defaultShape()
                    shapes = [hou.NetworkShapeNodeShape(rect, nodeshape,
                                    hou.ui.colorFromName('GraphPreSelection'),
                                    0.5, True, False)]
                else:
                shapes = [hou.NetworkShapeBox(rect,
                                hou.ui.colorFromName('GraphPreSelection'),
                                0.5, True, False)]'''
                shapes = snapresult.shapes(editor)
                shapes.extend(buildPendingWires(editor, nodecenter, locatedconn, locatedinput, locatedoutput))
 
            editor.setOverlayShapes(shapes)
 
    if editor is not None:
        editor.setDefaultCursor(olddefaultcursor)
        editor.setOverlayShapes([])
        editor.popEventContext()