コード例 #1
0
ファイル: HMerger_QT5.py プロジェクト: FredNov/HMerger
 def convToHip(self, pth):
     pth = pth.replace('\\', '/')
     pth = pth.replace(hou.getenv('HIP'), '$HIP')
     if hou.getenv('JOB'):
         if os.path.exists(hou.getenv('JOB')):
             pth = pth.replace(hou.getenv('JOB'), '$JOB')
     return pth
コード例 #2
0
    def _load_flipbooks(self):
        item_paths = []
        for item in self._tree_find_selected():
            item_paths.append(item.get_path())

        item_paths = ' '.join(item_paths)

        if item_paths:
            process = QtCore.QProcess(self)

            # order of arguments important!
            arguments = '-r {} {} -g -C'.format(hou.fps(), item_paths)

            system = sys.platform
            if system == "linux2":
                program = '%s/bin/mplay-bin' % hou.getenv('HFS')
            elif system == 'win32':
                program = '%s/bin/mplay.exe' % hou.getenv('HFS')
            else:
                msg = "Platform '%s' is not supported." % (system, )
                self._app.log_error(msg)
                hou.ui.displayMessage(msg)
                return

            process.startDetached(program, arguments.split(' '))
            process.close()
コード例 #3
0
def play_scrub(multiplier):
    import time
    from PySide2.QtGui import QCursor

    mouse_last = hou.getenv("mouse", "0")
    mouse_last = float(mouse_last)
    mouse_now = QCursor().pos()

    time_now = time.time()
    time_last = hou.getenv("time", "0")
    time_last = float(time_last)
    time_diff = time_now - time_last

    mouse_now = round(mouse_now.x() / 10)

    if time_diff > 0.1:
        mouse_last = mouse_now

    skip = mouse_last - mouse_now
    skip = skip * multiplier
    if abs(skip) > 20:
        skip = skip * 2

    frame_now = hou.frame()
    frame_now = hou.frame() - skip
    hou.setFrame(frame_now)

    hou.putenv("mouse", str(mouse_now))
    hou.putenv("time", str(time_now))
コード例 #4
0
ファイル: megaH.py プロジェクト: vinyvince/megaH
    def __init__(self):
        self.libPath = os.path.normpath(hou.getenv("MEGA_LIB"))
        self.libHierarchyJson = os.path.join(self.libPath, "index.json")
        self.shader = hou.getenv("MEGA_SHADER")

        with open(self.libHierarchyJson) as data:
            self.assetsIndex = json.load(data)
コード例 #5
0
ファイル: wf_network_utils.py プロジェクト: lex-ikoon/qq
def selection_switch():
    nodes = hou.selectedNodes()
    count = len(nodes)
    if count > 1:
        # if few nodes are selected, then initialize, save that selection
        selection_stack = ','.join(node.path() for node in nodes)
        hou.putenv('selection_stack', selection_stack)
        hou.putenv('selection_current', '0')
        hou.putenv('selection_count', str(count))
    else:
        # hou.ui.displayMessage("ikoon: select more than one node")
        # return
        pass

    # even if one node is selected...
    selection_stack = hou.getenv('selection_stack', 'none')
    selection_current = hou.getenv('selection_current', 'none')
    selection_count = hou.getenv('selection_count', 'none')

    # go to next node...
    stack = selection_stack.split(',')
    current = int(selection_current) + 1
    count = int(selection_count)
    if current == count:
        current = 0

    # update the saved variable
    hou.putenv('selection_current', str(current))

    # select that node in current pane
    target = hou.node(stack[current])
    parm_pane = wf_selection.pane_linkGroup(hou.paneTabType.Parm)
    parm_pane.setCurrentNode(target, True)
コード例 #6
0
def readNeedHideNode():
    deprecatedNodeList = []
    pathFeELib = hou.getenv('FeELib')
    if pathFeELib is not None:
        deprecatedSopDefinitionTXT = pathFeELib + '/scripts/deprecatedDefinition/needHideSopNode.txt'
        if os.path.exists(deprecatedSopDefinitionTXT):
            with open(deprecatedSopDefinitionTXT, "r") as TXT:
                fee_Utils.readTXTAsList(deprecatedNodeList, TXT)
    else:
        print('no found env FeELib which belongs to FeELib for Houdini')

    pathFeELib = hou.getenv('FeEProjectHoudini')
    if pathFeELib is not None:
        deprecatedSopDefinitionTXT = pathFeELib + '/scripts/deprecatedDefinition/needHideSopNode.txt'
        if os.path.exists(deprecatedSopDefinitionTXT):
            with open(deprecatedSopDefinitionTXT, "r") as TXT:
                fee_Utils.readTXTAsList(deprecatedNodeList, TXT)

    pathFeELib = hou.getenv('FeEworkHoudini')
    if pathFeELib is not None:
        deprecatedSopDefinitionTXT = pathFeELib + '/scripts/deprecatedDefinition/needHideSopNode.txt'
        if os.path.exists(deprecatedSopDefinitionTXT):
            with open(deprecatedSopDefinitionTXT, "r") as TXT:
                fee_Utils.readTXTAsList(deprecatedNodeList, TXT)

    deprecatedNodeList = tuple(set(deprecatedNodeList))
    return deprecatedNodeList
コード例 #7
0
def GetAbsoluteFileName(_title, _wildCard, _fileType):
    # launch a file select and get the data
    file = hou.ui.selectFile(None, _title, False, _fileType, _wildCard)
    # if it was empty bomb out and return none
    if file == "":
        return None
    else:
        # so we got some data we need to split it as we could have $JOB $HIP or $HOME prepended
        # to it  if we partition based on the / we get a tuple with "", "/","/....." where the
        # first element is going to be an environment var etc.
        file = file.partition("/")
        # we have $HOME so extract the full $HOME path and use it
        if file[0] == "$HOME":
            prefix = str(hou.getenv("HOME"))
        elif file[0] == "$HIP":
            #we have $HIP so extract the full $HIP path
            prefix = str(hou.getenv("HIP"))
        # we have a $JOB so extract the full $JOB path
        elif file[0] == "$JOB":
            prefix = str(hou.getenv("JOB"))
        # nothing so just blank the string
        else:
            prefix = str("")
    #now construct our new file name from the elements we've found
    return "%s/%s" % (prefix, file[2])
コード例 #8
0
ファイル: eg_FileSave.py プロジェクト: zhuo2015/egLib
def getDatafromCurrentFile():
    if hou.getenv("DEFAULTJOB") == hou.getenv("JOB"):
        getNewFile()
    else:
        #Get Data from Current File
        hip = hou.hipFile
        filename = hip.path()
        basename = hip.basename()
        pathname = re.sub(basename + "$", '', filename)

        #Save Old name for Later
        oldPath = pathname
        oldBasename = basename
        #Correct Date if necessary
        basename = addDate(basename)
        #Increase Version
        basename = increaseVersionNum(basename)
        #Concat again
        filename = pathname + basename
        #Save
        save(filename)
        #Move old File to discarded-Dir
        if moveOldFiles is True:
            moveOldFileToDir(oldPath, oldBasename)
        return
コード例 #9
0
ファイル: eg_copyToFarm.py プロジェクト: zhuo2015/egLib
def changeMats(nodes, name, count):
    for n in nodes:
        if n.type().name() == "texture::2.0" or n.type().name() == "principledshader::2.0" or n.type().name() == "displacetexture" :
            for p in n.parms():
                if p.parmTemplate().type() == hou.parmTemplateType.String:
                    # Get Parm as String
                    s = p.evalAsString()
                    occur = s.rfind("/")
                    #Filter out non Files - go to next if none
                    if occur == -1:
                        continue
                    if s.startswith(hou.getenv("HSITE")):   #Leave if already in place
                        continue
                    if not os.path.exists(s):
                        #global errors
                        s = (s + " does not exist")
                        errors.append(s)
                        continue

                    filename = s[occur+1:]
                    path = s[:occur+1]

                    #Create Directories
                    matDir = hiptex+"/" + name 

                    if os.path.isdir(hip) is False:
                        os.makedirs(hip)
                        os.makedirs(hiptex)
                    elif os.path.isdir(hiptex) is False:
                        os.makedirs(hiptex)
                    if os.path.isdir(matDir) is False:
                        os.makedirs(matDir)

                    #Copy File to HSITE   
                    global overwrite
                    if overwrite:
                        if not s.startswith("op:/"):      
                            if not copy(s, matDir):
                                continue
                    else:
                        if os.path.exists(hou.getenv("HSITE") + "/" + project + "/" + hipname + "/" + tex + "/" + name + "/" + filename):
                            continue    
                        elif not copy(s, matDir):
                            continue

                    newPath = "$HSITE/" + project + "/" + hipname + "/" + tex + "/" + name + "/" + filename
                    #newPath to Parm
                    n.parm(p.name()).set(newPath)
                    count += 1

        if n.type().name() == "materialbuilder":
            children = n.children() 
            name = n.name()    
            count = changeMats(children, name, count)
            name = "materials"
    return count
コード例 #10
0
ファイル: eg_copyToFarm.py プロジェクト: zhuo2015/egLib
def changeGeo(nodes, count):
    for n in nodes:
        if n.type().name() == "subnet":
            count = changeGeo(n.children(), count)
        elif n.type().name() == "geo":
            #Iterate over Nodes on SOP Level
            for sop in n.children():
                if sop.type().name() == "file" or sop.type().name() == "filecache":
                    if sop.parm("filemode") != "write":
                        # Get Parm as String
                        s = sop.parm("file").evalAsString()
                        occur = s.rfind("/")
                        #Filter out non Files - go to next if none
                        if occur == -1:
                            continue
                        if s.startswith(hou.getenv("HSITE")):   #Leave if already in place
                            continue   
                        if not os.path.exists(s):
                            #global errors
                            s = (s + " does not exist")
                            errors.append(s)
                            continue 

                        filename = s[occur+1:]
                        path = s[:occur+1]

                        #Create Directories
                        geoDir = hipGeo + "/" + n.name()

                        if os.path.isdir(hip) is False:
                            os.makedirs(hip)
                            os.makedirs(hipGeo)
                        elif os.path.isdir(hipGeo) is False:
                            os.makedirs(hipGeo)
                        if os.path.isdir(geoDir) is False:
                            os.makedirs(geoDir)

                        #Copy File to HSITE   
                        global overwrite
                        if overwrite:      
                            if not s.startswith("op:/"):
                                if not copy(s, geoDir):
                                    continue
                        else:
                            if os.path.exists(hou.getenv("HSITE") + "/" + project + "/" + hipname + "/" + geo + "/" + n.name() + "/" + filename):
                                continue    
                            elif not copy(s, geoDir):
                                continue


                        newPath = "$HSITE/" + project + "/" + hipname + "/" + geo + "/" + n.name() + "/" + filename
                        #newPath to Parm
                        sop.parm("file").set(newPath)
                        sop.parm("loadtype").set("delayed")
                        count += 1
    return count
コード例 #11
0
ファイル: main.py プロジェクト: zmfovlr/Houdini
def cache_dir():
    root = hou.getenv('OUTPUT_PATH')
    if not root:
        root = hou.getenv('HIP')
        root = os.path.join(root, 'Output')
    root = util.fix_path(root)

    sub_folders = ['cache']
    path = util.fix_path(os.sep.join(root.split('/') + sub_folders))

    return path
コード例 #12
0
ファイル: hpipe.py プロジェクト: jtomori/hpipe
def flipBooker():
    viewer = tu.sceneViewer()
    settings = viewer.flipbookSettings().stash()

    path = hou.getenv("HIP") + "/prev/" + hou.getenv("VER") + "/"
    if not os.path.isdir(path):
        os.makedirs(path)
    path = path + "out_$F4.jpg"
    settings.output(path)

    viewer.flipbook(settings=settings)
コード例 #13
0
ファイル: projmanager.py プロジェクト: gui2one/HOUDINI_CONFIG
 def comboChanged(self, index):
     # print "combo changed, index : ", index
     if index == 0:
         self.rootPath = hou.getenv("JOB")
     elif index == 1:
         self.rootPath = hou.getenv("HIP")
     elif index == self.combo.count() - 1:
         chosenPath = hou.ui.selectFile("", "select a project folder")
         self.rootPath = chosenPath
         # print '!!!!!!!!!!!!!!', self.rootPath
     # print self.combo.count()
     self.createList()
コード例 #14
0
def onCreated(kwargs):
    node = kwargs['node']

    node.setName('SCENE_DATA')

    # node.setUserData('nodeshape', 'circle')
    node.setColor(hou.Color(0.58, 0.2, 0.48))
    node.setGenericFlag(hou.nodeFlag.Display, False)
    node.setGenericFlag(hou.nodeFlag.Selectable, False)

    node.parm('proj').set(hou.getenv('PROJECT'))
    node.parm('scene').set(hou.getenv('SCENE'))
コード例 #15
0
ファイル: hpipe.py プロジェクト: jtomori/hpipe
def saveInc():
    hipname = hou.getenv('HIPNAME')
    if hipname != 'untitled':
        v, num = verSplit(hipname.split("_")[-1])
        num = str(int(num) + 1).zfill(len(num))
        newName = hipname.split("_")
        newName[-1] = v + num
        newNameStr = hou.getenv('HIP') + "/" + "_".join(
            newName) + "." + hou.getenv('HIPFILE').split(".")[-1]
        hou.hipFile.save(newNameStr)
        initVars()
    else:
        print "cannot increment version name in untitled.hip"
コード例 #16
0
ファイル: HCollector_QT5.py プロジェクト: FredNov/HCollector
    def convToHip(self, pth):
        pth = os.path.normpath(os.path.normcase(pth))
        if self.chFile.isChecked():
            pth = pth.replace(self.ln_file.text(), '$HIP')
        else:
            pth = pth.replace(
                os.path.normpath(os.path.normcase(hou.getenv('HIP'))), '$HIP')
        pth = pth.replace('\\', '/')

        if hou.getenv('JOB'):
            if os.path.exists(hou.getenv('JOB')):
                pth = pth.replace(hou.getenv('JOB'), '$JOB')
        return pth
コード例 #17
0
def assignEnvVars():
    import os

    sHipPath = hou.getenv('HIP').split('/')
    if sHipPath[2] == "karramba":
        pName = sHipPath[3]
        seqName = sHipPath[6]
        shName = sHipPath[8]
    else:
        pName = ""
        seqName = ""
        shName = ""

    scName = hou.getenv('HIPNAME').rsplit('.v')[0]

    vars = hou.ui.readMultiInput(
        "Input values. Project name and the names of the sequence and shot.",
        ("Project name", "Sequence name", "Shot name"),
        title="Assign environment variables",
        buttons=('Save', 'Cancel'),
        default_choice=0,
        close_choice=1,
        initial_contents=(str(pName), str(seqName), str(shName)))
    # if project was set
    if str(vars[1][0]) != "":
        env_project = "/mnt/karramba/" + str(vars[1][0])
        os.environ.update({"PROJECT": env_project})
        hou.hscript("set -g PROJECT = '" + env_project + "'")

        # if sequence was set
        if str(vars[1][1]) != "":
            env_sequence = env_project + "/film/sequences/" + str(vars[1][1])
            os.environ.update({"SEQUENCE": env_sequence})
            hou.hscript("set -g SEQUENCE = '" + env_sequence + "'")

            # if shot was set
            if str(vars[1][2]) != "":
                env_shot = env_sequence + "/shots/" + str(vars[1][2])
                os.environ.update({"SHOT": env_shot})
                hou.hscript("set -g SHOT = '" + env_shot + "'")
                env_data = env_shot + "/data"
                os.environ.update({"DATA": env_data})
                hou.hscript("set -g DATA = '" + env_data + "'")

        env_assets = env_project + "/film/assets"
        os.environ.update({"ASSETS": env_assets})
        hou.hscript("set -g ASSETS = '" + env_assets + "'")

        os.environ.update({"SCENENAME": str(scName)})
        hou.hscript("set -g SCENENAME = '" + str(scName) + "'")
コード例 #18
0
ファイル: eg_project.py プロジェクト: evgeni17/egLib
    def save(self, kwargs):

        s = eg_save.Save(kwargs['node'].parm('p_version'))
        path = s.get_path()

        filename = ''
        envs = ['P_DATE', 'P_NAME', 'P_USER', 'P_VERSION']

        for env in envs:
            if hou.getenv(env):
                filename += hou.getenv(env) + '_'

        filename = filename[:-1] + s.getLicenseType()
        s.save(path + filename)
コード例 #19
0
def set_scene(kwargs):
    node = kwargs['node']
    scene_name = node.evalParm('scene')

    # If null scene > unset all
    if scene_name == '':
        unset_all_scene_vars()
        node.cook(True)
        return


    # If no PROJECT_PATH var
    project_path = hou.getenv('PROJECT_PATH')
    if not project_path or not os.access(project_path, os.F_OK):
        util.error('Project path is invalid')
        return

    # If no SCENES_PATH var
    scenes_path = hou.getenv('SCENES_PATH')
    if not scenes_path or not os.access(scenes_path, os.F_OK):
        util.error('Scenes path is invalid')
        return

    # If SCENES_PATH var but no folder
    if not os.access(scenes_path, os.F_OK):
        os.makedirs(scenes_path)

    scene_path = util.fix_path(os.path.join(scenes_path, scene_name))
    if not os.access(scene_path, os.F_OK):
        message = 'Scene folder "{0}" does not exist\n'\
                  'Create this folder now?'.format(scene_name)
        choice = hou.ui.displayMessage(message, severity=hou.severityType.ImportantMessage, buttons=('Yes', 'No'))
        if choice == 0:
            os.makedirs(scene_path)
        else:
            unset_all_scene_vars()
            node.cook(True)
            return

    hou.putenv('SCENE', scene_name)
    hou.putenv('SCENE_PATH', scene_path)

    create_folder_and_var('SAVE_PATH', os.path.join(scene_path, 'working_files'))

    output_path = os.path.join(scene_path, 'output')
    create_folder_and_var('OUTPUT_PATH', output_path)
    create_folder_and_var('CACHE_PATH', os.path.join(output_path, 'cache'))
    create_folder_and_var('RENDER_PATH', os.path.join(output_path, 'render'))

    node.cook(True)
コード例 #20
0
ファイル: hou2vr.py プロジェクト: all-in-one-of/houdini2vr
def saveImageAsPng(img_data, path=None):
    """
    Saves incoming data as PNG in specified path, or in $HIP/tmp/tmp.png if not specified
    img_data is a dict which is returned from getImageData()
    path is a Path object
    """
    if not img_data:
        return

    if not path:
        folder_path = Path(hou.getenv("HIP"), "tmp")
        if not folder_path.exists():
            os.makedirs(str(folder_path))
        img_path = folder_path / "tmp.png"
    else:
        img_path = path

    pixels = img_data["pixels"]
    res = img_data["res"]

    pixels = np.array(pixels)
    pixels = pixels.reshape(res[1], res[0], 4)
    pixels = np.flipud(pixels)

    pixels *= 255
    pixels = np.clip(pixels, 0, 255)

    png_img = Image.fromarray(pixels.astype(np.uint8))
    png_img.save(str(img_path))
    log.info("Saving image into {}".format(str(img_path)))
コード例 #21
0
    def setproject(self):
        # #setjob = hou.ui.selectFromTree(tree_list, exclusive=True, message='Select a parameter to watch',
        #                                title='Watchlist Select', clear_on_cancel=True)

        getdir1 = "/Users/byungsoo/houdini_env/Work/sooway/"
        dirlist = []
        for subdir in os.listdir(getdir1):
            dirlist.append(subdir)
        users = hou.getenv('HIP') + "/"
        setjob = hou.ui.selectFromList(
            users,
            exclusive=True,
            message="Please select the Node's owner",
            title="Read User's nodes",
            column_header="Users")

        #setjob = hou.ui.selectFile(title='set project', file_type=hou.fileType.Directory)
        hou.hscript('setenv JOB' + setjob)

        print setjob

        # self.proj = hou.getenv('JOB') + '/'
        self.proj = setjob

        projname = setjob.split('/')[-2]
        setjob = os.path.dirname(setjob)
        projpath = os.path.split(setjob)[0]

        self.projname.setText(projname)
        self.projpath.setText(projpath + '/')
        self.onCreateInterface()
コード例 #22
0
def export_help_from_all_hda():
    output_text = index_text
    hda_files = hou.hda.loadedFiles()
    node_types = {}
    for hda_file in set(hda_files):
        if hou.getenv('HFS') in hda_file or 'packages' in hda_file:
            continue
        hda_defs = hou.hda.definitionsInFile(hda_file)
        for hda_def in hda_defs:
            node_type = hda_def.nodeType()
            node_def = node_type.definition()
            if not node_def:
                return
            context = node_type.category().name()
            node_label = node_type.description()
            node_name = get_node_name(node_type)
            node_list = node_types.get(context)
            if node_list:
                node_list.append([node_name, node_label])
            else:
                node_types[context] = [[node_name, node_label]]

    for context, node_list in node_types.items():
        output_text += category_text.format(context)
        for node_name, node_label in sorted(node_list):
            node_data = {
                'context': context,
                'node_label': node_label,
                'node_name': node_name
            }
            output_text += node_text.format(**node_data)

    help_file = 'J:/www/Phile/content/Environment/11_ENV_TECH/Houdini/HDA/All/HDA_index.md'
    with codecs.open(help_file, 'w', 'utf-8') as f:
        f.write(output_text)
コード例 #23
0
 def ocio_check(self):
     """Check if OCIO is enabled"""
     # Check against OCIO
     if not hou.getenv("OCIO"):
         hou.ui.displayMessage("Please set $OCIO to convert Textures")
         return False
     return True
コード例 #24
0
def isSideFXLabsNode(nodeType, detectName=True, detectPath=False):
    nodeType = convertNodeType(nodeType)

    if detectName:
        nameComponents = nodeType.nameComponents()
        if not 'labs' in nameComponents[1]:
            return False

    if detectPath:
        defi = nodeType.definition()
        if defi is None:
            libraryFilePath = 'None'
        else:
            libraryFilePath = defi.libraryFilePath()

        pathFeELib = hou.getenv('SIDEFXLABS')
        if pathFeELib is None:
            raise AttributeError('not found env: SIDEFXLABS')

        isInPathCondition = pathFeELib in libraryFilePath

        if not isInPathCondition:
            return False

    return True
コード例 #25
0
    def __init__(self, editor):
        super(NEMarkingMenu, self).__init__()

        self.rootpath = os.path.abspath(
            os.path.join(hou.getenv('HOUDINI_MARKINGMENU'), 'python3.7libs',
                         'houdini_markingmenu'))

        # add python folder to path for nodegraphactivewire context
        sys.path.insert(0, os.path.join(self.rootpath, 'python'))

        # UI fixed sizes
        self.HIGH_DPI = cmds.HIGH_DPI
        self.UISCALE = 2 if self.HIGH_DPI else 1  # scale factor for high DPI monitors, 2 should be enough.

        self.windowSize = 1300 * self.UISCALE  # invisible bounds size, too big may impact performance
        self.pad = 1.18 * self.UISCALE  # gap between buttons
        self.buttonWidth = 134 * self.UISCALE
        self.buttonHeight = 24 * self.UISCALE
        self.buttonIconSize = 12 * self.UISCALE

        # menu draw time offset
        self.visible = False
        self.startTime = time.time()
        self.origin = QtCore.QPoint(0, 0)

        self.editor = editor

        # storing widgets - mouse path
        self.mouseAnchorPositions = []
        self.mousePathGraphicsWidget = 0

        # storing widgets - menu widgets
        self.menuItemWidgets = []
        self.rectangles = []

        self.targetWidget = 0

        # relative positional offsets between buttons
        self.menuYOffsets = [
            70 * self.pad, 35 * self.pad, 0 * self.pad, -35 * self.pad,
            -70 * self.pad, -35 * self.pad, 0 * self.pad, 35 * self.pad
        ]

        self.menuXOffsets = [
            0 * self.pad, 45 * self.pad, 70 * self.pad, 45 * self.pad,
            0 * self.pad, 45 * self.pad, 70 * self.pad, 45 * self.pad
        ]

        # setup initial config file
        self.currentContext = utils.getContext(self.editor)
        self.baseCollection = '{}_baseCollection.json'.format(
            self.currentContext)

        self.inputConfigFile = {}
        self.collectionItemDescriptions = []

        self.collectionsDir = os.path.join(self.rootpath, 'menus',
                                           self.currentContext)
        self.storeCollection(self.baseCollection)
        self.__initUI()
コード例 #26
0
def change_str(path, mode):
	pattern1 = re.compile("\A\$JOB/|\A\$JOB$|\A\$JOB_S/|\A\$JOB_S$")
	new_str = path
	c = 0
	if pattern1.search(path) == None:
		hip = hou.getenv('HIP')
		pattern = re.compile("/3d/hip$|/3d/hip/")
		if pattern.search(hip):
			pat_hip = re.compile("\A\$HIP/|\A\$HIP$")
			if pat_hip.search(path):
				re_subn = re.subn(pat_hip, '$'+mode+'/3d/hip/', path)
				if re_subn[1]:
					new_str = re_subn[0]
					c = 1
			else:
				c_job = pattern.split(hip)[0]
				parm_job = pattern.split(path)[0]
				if c_job==parm_job:
					pattern = re.compile(c_job)
					re_subn = re.subn(pattern, "$"+mode, path)
					if re_subn[1]:
						new_str = re_subn[0]
						c = 1
	else:
		re_subn = re.subn(pattern1, "$"+mode+"/", path)
		if re_subn[1]:
			new_str = re_subn[0]
			c = 1
	return [new_str, c]
コード例 #27
0
    def add_spare_parameters(self, target):
        vtuple = hou.applicationVersion()
        rfhtree = hou.getenv("RFHTREE")
        renderobjnames = ["geo"]
        rendercamnames = ["cam"]

        if target.type().name() in renderobjnames:
            path = rfhtree + "/18.5.351/soho/parameters/geoparms.ds"
        elif target.type().name() in rendercamnames:
            path = rfhtree + "/18.5.351/soho/parameters/camparms.ds"
        else:
            return None

        grp = target.parmTemplateGroup()
        spareparms = hou.ParmTemplateGroup()
        with open(path) as file:
            ds = file.read()
            spareparms.setToDialogScript(ds)
        for template in spareparms.parmTemplates():
            grp.append(template)

        try:
            target.parmsInFolder(("RenderMan",))
        except:
            target.setParmTemplateGroup(grp)

        if target.type().name() == "geo":
            hou.hscript("opproperty %s prman23geo *" % target.path())
        elif target.type().name() == "cam":
            hou.hscript("opproperty %s prman23cam *" % target.path())
コード例 #28
0
ファイル: eg_FileSave.py プロジェクト: zhuo2015/egLib
def setProj(base):
    invalid = True
    while invalid:
        userdir = hou.ui.selectFile(title="Please choose a Project Directory",
                                    collapse_sequences=True,
                                    file_type=hou.fileType.Directory)
        #Search for ENVVARS
        reg = re.compile('(\${1})([A-Z]+)')
        match = reg.search(userdir)
        if match:
            first, second = match.groups()

            myPath = hou.getenv(second)
            length = len(second) + 1
            #Replace Them
            userdir = myPath + userdir[length:]

        if os.path.isdir(userdir):
            invalid = False
            #Create Direcotries
            ud = userdir
            makeDirs(userdir)
            userdir = userdir + base
        else:
            hou.ui.displayMessage("Please select a directory")
    hou.putenv("JOB", userdir)
    return ud
コード例 #29
0
    def __init__(self, editor):
        super(MarkingMenuEditor, self).__init__()
        self.setParent(hou.qt.mainWindow(), QtCore.Qt.Window)
        self.setWindowTitle('Marking Menu Editor')

        # UI fixed sizes
        self.HIGH_DPI = cmds.HIGH_DPI
        self.dpifactor = 2 if self.HIGH_DPI else 1

        self.setGeometry(300, 250, 900, 700)
        self.setStyleSheet('background-color: rgb(58,58,58);')
        self.setFixedSize(1150 * self.dpifactor, 850 * self.dpifactor)

        self._rootpath = os.path.join(
            os.path.abspath(hou.getenv('HOUDINI_USER_PREF_DIR')),
            'python2.7libs', 'houdini_markingmenu')

        self._contexts = sorted(
            ['SOP', 'OBJ', 'DOP', 'VOP', 'ROP', 'SHOP', 'CHOP', 'COP'])

        self._collections = []
        self._currentContext = 'SOP'
        self.editor = editor

        self._collectionsDir = os.path.join(self._rootpath, 'json',
                                            self._currentContext)

        self._fullcpath = ''  # full path to the current collection on disk
        self._menuPrefs = utils.loadMenuPreferences(
            os.path.join(self._rootpath, 'json', 'menuprefs.json'))
        self._detailIndices = []
        self._loadedCollection = []
        self._virtualCollection = []
        self._unfreezeVirtualUpdate = 0
        self._unsaved = 0
        self._prevCollection = ''

        self.legendmenus = []
        self.legendcollections = []
        self.legendactions = []
        self.legendHistory = 0

        # button functions auto completer
        readfile = []
        funcList = []
        with open(os.path.join(self._rootpath, 'buttonfunctions.py'),
                  'r') as f:
            readfile = f.readlines()

        for line in readfile:
            if '**kwargs' in line:
                funcList.append(line.split('def ')[-1].split('(')[0])
        funcList.append('launchEditor')
        funcList += hou.shelves.tools().keys()
        self._funcCompleter = QtWidgets.QCompleter(funcList)
        self._funcCompleter.popup().setStyleSheet(hou.qt.styleSheet())
        self._funcCompleter.setCompletionMode(
            QtWidgets.QCompleter.PopupCompletion)

        self.__initUI()
コード例 #30
0
ファイル: qlibutils.py プロジェクト: miaoyuanxi/qLib
def to_clipboard(contents="", env=None):
    """Copies the specified string to the system clipboard.

    @note
            - Linux only at the moment
            - requires xclip to be installed

    @todo
            Make it work under other OSs than linux?
    """
    try:
        contents = str(contents)
        if env:
            contents = str(hou.getenv(env))

        statmsg("(linux) to clipboard: '%s'" % contents)
        cmd = 'xclip'
        if is_windows():
            cmd = 'clip'
        if is_mac():
            cmd = 'pbcopy'
        hou.hscript('unix \'echo -n "%s" | %s\'' % (
            contents,
            cmd,
        ))
        # hackety hack
    except:
        pass
コード例 #31
0
    def __init__(self, rootpath, *args, **kwargs):
        super(DetailsPane, self).__init__()

        self.dpifactor = 2 if kwargs['highdpi'] else 1

        # build icon completer
        categories = hou.nodeTypeCategories()
        strlist = []
        for category in categories.keys():
            node_types = categories[category].nodeTypes()
            for node_type in node_types.keys():
                strlist.append(node_types[node_type].icon())

        jsondict = {}
        jsonfile = os.path.join(hou.getenv('HOUDINI_USER_PREF_DIR'),
                                'python2.7libs', 'houdini_markingmenu', 'json',
                                'icons.json')

        with open(jsonfile, 'r') as f:
            jsondict = json.load(f)

        for x in jsondict.keys():
            for item in jsondict[x]:
                if item not in strlist:
                    strlist.append(item)

        comp = QtWidgets.QCompleter(list(set(strlist)))
        comp.popup().setStyleSheet(hou.qt.styleSheet())
        comp.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
        self.iconCompleter = comp

        self.initUI()
コード例 #32
0
def _fixpath(path):
    if path.startswith('temp:'):
        # Strip off the leading 'temp:'
        path = path.replace('temp:', '')
        # Insert the houdini temp directory
        path = os.path.join(hou.getenv('HOUDINI_TEMP_DIR'), path)
    # "fix" any embedded quotes in the path
    return path.replace('"', '\\"')
コード例 #33
0
    def getFilePath(self, *args):
        file=hou.ui.selectFile(None,"Import kCamera",False,hou.fileType.Any,"*.kCamera","",False,False,hou.fileChooserMode.Write)
        
        if file =="":
            return None
        else :
            file=file.partition("/")

            if file[0]=="$HOME" :
                prefix=str(hou.getenv("HOME"))
            elif file[0] == "$HIP" :
                prefix=str(hou.getenv("HIP"))
            elif file[0] == "$JOB":
                prefix=str(hou.getenv("JOB"))
            else:
                prefix=str("")

            return "%s/%s" %(prefix,file[2])
コード例 #34
0
ファイル: quick_utils.py プロジェクト: horitin/pipeline
def assignEnvVars():
    import os
    
    sHipPath = hou.getenv('HIP').split('/')
    if sHipPath[2] == "karramba":
        pName = sHipPath[3]
        seqName = sHipPath[6]
        shName = sHipPath[8]
    else:
        pName = ""
        seqName = ""
        shName = ""

    scName = hou.getenv('HIPNAME').rsplit('.v')[0]

    vars = hou.ui.readMultiInput("Input values. Project name and the names of the sequence and shot.", ("Project name", "Sequence name", "Shot name"), title="Assign environment variables", buttons = ('Save', 'Cancel'), default_choice = 0, close_choice = 1, initial_contents = ( pName, seqName, shName ))
    # if project was set
    if str(vars[1][0]) != "":
        env_project = "/mnt/karramba/" + str(vars[1][0])
        os.environ.update({"PROJECT": env_project})
        hou.hscript("set -g PROJECT = '" + env_project + "'")

        # if sequence was set
        if str(vars[1][1]) != "":
            env_sequence = env_project + "/film/sequences/" + str(vars[1][1])
            os.environ.update({"SEQUENCE": env_sequence})
            hou.hscript("set -g SEQUENCE = '" + env_sequence + "'")

            # if shot was set
            if str(vars[1][2]) != "":
                env_shot = env_sequence + "/shots/" + str(vars[1][2])
                os.environ.update({"SHOT": env_shot})
                hou.hscript("set -g SHOT = '" + env_shot + "'")
                env_data = env_shot + "/data"
                os.environ.update({"DATA": env_data})
                hou.hscript("set -g DATA = '" + env_data + "'")


        env_assets = env_project + "/film/assets"
        os.environ.update({"ASSETS": env_assets})
        hou.hscript("set -g ASSETS = '" + env_assets + "'")

        os.environ.update({"SCENENAME": scName})
        hou.hscript("set -g SCENENAME = '" + scName + "'")
コード例 #35
0
ファイル: houdini.py プロジェクト: sergeneren/anima
    def set_render_filename(self, version):
        """sets the render file name
        """
        output_filename = \
            '{version.absolute_path}/Outputs/`$OS`/' \
            '{version.task.project.code}_{version.nice_name}_' \
            'v{version.version_number:03d}.$F4.exr'

        output_filename = \
            output_filename.format(version=version).replace('\\', '/')

        # compute a $JOB relative file path
        # which is much safer if the file is going to be render in multiple OSes
        # $HIP = the current asset path
        # $JOB = the current sequence path
        #hip = self._asset.path
        #hip = hou.getenv("HIP")
        job = hou.getenv("JOB")
        # eliminate environment vars
        while "$" in job:
            job = os.path.expandvars(job)

        job_relative_output_file_path = \
            "$JOB/%s" % utils.relpath(job, output_filename, "/", "..")

        output_nodes = self.get_output_nodes()
        for output_node in output_nodes:
            # get only the ifd nodes for now
            if output_node.type().name() == 'ifd':
                # set the file name
                try:
                    output_node.setParms(
                        {'vm_picture': str(job_relative_output_file_path)}
                    )
                except hou.PermissionError:
                    # node is locked
                    pass

                # set the compression to zips (zip, single scanline)
                output_node.setParms({"vm_image_exr_compression": "zips"})

                # also create the folders
                output_file_full_path = output_node.evalParm('vm_picture')
                output_file_path = os.path.dirname(output_file_full_path)

                flat_output_file_path = output_file_path
                while "$" in flat_output_file_path:
                    flat_output_file_path = os.path.expandvars(
                        flat_output_file_path
                    )

                try:
                    os.makedirs(flat_output_file_path)
                except OSError:
                    # dirs exists
                    pass
コード例 #36
0
def GetAbsoluteFileName(_title,_wildCard,_fileType) :
	# launch a file select and get the data
	file=hou.ui.selectFile(None,_title,False,_fileType,_wildCard)
	# if it was empty bomb out and return none
	if file =="" :
		return None
	else :
		# so we got some data we need to split it as we could have $JOB $HIP or $HOME prepended
		# to it  if we partition based on the / we get a tuple with "", "/","/....." where the
		# first element is going to be an environment var etc.
		file=file.partition("/")
		# we have $HOME so extract the full $HOME path and use it
		if file[0]=="$HOME" :
			prefix=str(hou.getenv("HOME"))
		elif file[0] == "$HIP" :
		#we have $HIP so extract the full $HIP path
			prefix=str(hou.getenv("HIP"))
		# we have a $JOB so extract the full $JOB path
		elif file[0] == "$JOB" :
コード例 #37
0
    def __init__(self):
        super(iconsWidgetClass, self).__init__()
        self.vLy = QVBoxLayout(self)

        self.fLy = QHBoxLayout()
        self.vLy.addLayout(self.fLy)
        label = QLabel('Filter: ')
        self.fLy.addWidget(label)

        self.clear_btn = QPushButton('')
        self.clear_btn.setIcon(hou.ui.createQtIcon('BUTTONS_remove'))
        self.clear_btn.clicked.connect(self.fill)
        self.clear_btn.setFixedSize(QSize(20,20))
        self.fLy.addWidget(self.clear_btn)
        @self.clear_btn.clicked.connect
        def clearFilter():
            if self.filter.text():
                self.filter.setText('')
                self.fill()

        self.filter = QLineEdit()
        self.filter.returnPressed.connect(self.fill)
        self.fLy.addWidget(self.filter)
        self.search_btn = QPushButton('Search')
        self.search_btn.clicked.connect(self.fill)
        self.fLy.addWidget(self.search_btn)

        # self.btn = QPushButton('Clear')
        # self.btn.clicked.connect(self.clearList)
        # self.vLy.addWidget(self.btn)

        self.scrollArea = QScrollArea(self)
        self.vLy.addWidget(self.scrollArea)
        self.scrollArea.setWidgetResizable(True)
        self.sawc = QFrame()
        self.ly = QVBoxLayout(self.sawc)
        self.scrollArea.setWidget(self.sawc)

        hfs = hou.getenv('HFS')
        if hou.applicationVersion()[0] < 15:
            path = os.path.join(hfs,'houdini/help/icons/large')
        else:
            path = os.path.join(hfs,'houdini/help/icons.zip')
        self.icons = {}
        self.content = None

        if os.path.exists(path):
            self.path = path
            self.findIcons()
            self.fill()
        else:
            err = QLabel('Icons not found!')
            err.setStyleSheet('font-size:25px;')
            err.setAlignment(Qt.AlignHCenter|Qt.AlignTop)
            self.ly.addWidget(err)
コード例 #38
0
ファイル: cache_utils.py プロジェクト: horitin/pipeline
def makeCachePath(object, mode):
    #get all path from HOUDINI VARIABLES

    sceneName = hou.getenv('HIPNAME').rsplit('.v',1)[0]
    #sceneName = hou.getenv('HIPNAME')
    print sceneName
    dataPath = hou.getenv('DATA')
    geoPath = os.path.join(dataPath, "geo")
    scenePath = os.path.join(geoPath, sceneName)
    nodePath = os.path.join(scenePath, object.name())

    startVersion = 0
    
    #get mode - get cache info
    if mode == 'get':
        cachesList = []
        if os.path.exists(nodePath):
            for n in sorted(os.listdir(nodePath)):
                cachesList.append(os.path.join(nodePath, n))
            return cachesList
    
    #add mode - add new cache path
    if mode == 'add':
        versionPath = ''
        #mkdir cache for current scene
        if not os.path.exists(scenePath): os.mkdir(scenePath)
        #mkdir cache for current node
        if not os.path.exists(nodePath): os.mkdir(nodePath)
        
        if not os.listdir(nodePath):
            versionPath = os.path.join(nodePath, str(startVersion).zfill(4))
            os.mkdir(versionPath)
        else:
            currentVersion = int(max(os.listdir(nodePath)))
            if os.path.exists(os.path.join(nodePath, str(startVersion).zfill(4))):
                versionPath = os.path.join(nodePath, str(currentVersion + 1).zfill(4))
                os.mkdir(versionPath)
        return versionPath
コード例 #39
0
def generate_completes(force=False):
    # check parsed functions
    cache_file = vex_settings.get_autocomplete_cache_file()
    if os.path.exists(cache_file) and not force:
        return True
    # get vcc
    vcc = os.path.join(hou.getenv('HFS'), 'bin', 'vcc').replace('/','\\')
    if os.name == 'nt':
        vcc = vcc + '.exe'
    if not os.path.exists(vcc):
        return False
    # generate new
    funcs = {}
    attrs = {}
    process = QProcess()
    process.start(' '.join([vcc, '-X']))
    process.waitForFinished()
    lines =  str(process.readAll()).split('\n')
    for context in lines:
        if context:
            process.start(' '.join([vcc, '-X', context]))
            process.waitForFinished()
            context_lines =  str(process.readAll())
            # variables
            variables = re.search(r'Global Variables:(.*)Control Statements:', context_lines, re.DOTALL)
            if variables:
                lines = variables.group(1).strip().split('\n')
                for l in lines:
                    s = l.split()
                    if len(s)==3:
                        attrs[s[-1]] = s[-2]
            # functions
            pat = r'^\s*(\w+\[?\]?)\s(\w+)(\(.+\))'
            for l in context_lines.split('\n'):
                func = re.findall(pat, str(l))
                if func:
                    if func[0][1] in funcs:
                        funcs[func[0][1]].append({'ret': func[0][0], 'args':func[0][2]})
                    else:
                        funcs[func[0][1]] = [{'ret': func[0][0], 'args':func[0][2]}]
    # save to cache
    if os.path.exists(cache_file):
        comp = json.load(open(cache_file))
    else:
        comp = {}
    comp['functions'] = funcs
    comp['attributes'] = attrs
    json.dump(comp, open(cache_file, 'w'), indent=4)
    return True
コード例 #40
0
ファイル: qlibutils.py プロジェクト: chunkified/qLib
def to_clipboard(contents="", env=None):
    """Copies the specified string to the system clipboard.

    @note
            - Linux only at the moment
            - requires xclip to be installed

    @todo
            Make it work under other OSs than linux?
    """
    try:
        contents = str(contents)
        if env:
            contents = str(hou.getenv(env))
        hou.ui.copyTextToClipboard(contents)
    except:
        pass
コード例 #41
0
ファイル: HDAManager.py プロジェクト: quyetdd/Houdini
	def findLoadedHDAs(self):
		'''
		Returns a list of loaded HDAs in Houdini scene.
		HDAs installed by default with Houdini are skipped.
		'''
		self.loadedHDAs = []
		# Scan all node categories
		for category in hou.nodeTypeCategories().values():
			# Scan all node types
			for nodeType in category.nodeTypes().values():
				nodeDef = nodeType.definition()
				# If its a valid and unique HDA
				if (nodeDef is not None) and \
					(nodeDef.libraryFilePath() not in self.loadedHDAs):
					# If not stored at "HFS" (Houdini Installation)
					if not nodeDef.libraryFilePath().startswith(hou.getenv("HFS")):
						self.loadedHDAs.append(nodeDef)

		self.populateHDALayout()
コード例 #42
0
ファイル: qlibutils.py プロジェクト: follyx/qLib
def open_dir(dir="", env=None):
	'''.'''
	dir=str(dir)

	if env:
		dir = str(hou.getenv(env))

	if not os.path.exists(dir):
		statmsg("Directory doesn't exist (%s)" % dir, warn=True)
		return

	if is_linux():
		statmsg("(linux) xdg-open %s" % dir)
		subprocess.call(["xdg-open", dir])

	if is_windows():
		dir = dir.replace('/', '\\')
		statmsg("(windows) start %s" % dir)
		subprocess.call(["start", dir])

	if is_mac():
		statmsg("(mac) open %s" % dir)
		subprocess.call(["open", dir])
コード例 #43
0
ファイル: houdiniEnv.py プロジェクト: dshlai/oyprojectmanager
    def set_render_filename(self, version):
        """sets the render file name
        """
        render_output_folder = version.output_path
        base_name = version.base_name
        take_name = version.take_name
        version_string = 'v%03d' % version.version_number
        user_initials = version.created_by.initials

        output_filename = os.path.join(
            render_output_folder, "`$OS`",
            base_name + "_" + take_name + "_`$OS`_" +
            version_string + "_" + user_initials + ".$F4.exr"
        )

        output_filename = output_filename.replace('\\', '/')

        # compute a $JOB relative file path
        # which is much safer if the file is going to be render in multiple OSes
        # $HIP = the current asset path
        # $JOB = the current sequence path
        #hip = self._asset.path
        #hip = hou.getenv("HIP")
        job = hou.getenv("JOB")
        # eliminate environment vars
        while "$" in job:
            job = os.path.expandvars(job)

        job_relative_output_file_path = "$JOB/" + utils.relpath(
            job, output_filename, "/", ".."
        )

        output_nodes = self.get_output_nodes()
        for output_node in output_nodes:
            # get only the ifd nodes for now
            if output_node.type().name() == 'ifd':
                # set the file name
                try:
                    output_node.setParms(
                        {'vm_picture': str(job_relative_output_file_path)}
                    )
                except hou.PermissionError:
                    # node is locked
                    pass

                # set the compression to zips (zip, single scanline)
                output_node.setParms({"vm_image_exr_compression": "zips"})

                # also create the folders
                output_file_full_path = output_node.evalParm('vm_picture')
                output_file_path = os.path.dirname(output_file_full_path)

                flat_output_file_path = output_file_path
                while "$" in flat_output_file_path:
                    flat_output_file_path = os.path.expandvars(
                        flat_output_file_path
                    )

                try:
                    os.makedirs(flat_output_file_path)
                except OSError:
                    # dirs exists
                    pass
コード例 #44
0
ファイル: qlibutils.py プロジェクト: follyx/qLib
def do_crash_recovery(calledFromUI=False):
	tmpdir = str( hou.getenv("TEMP") or hou.getenv("HOUDINI_TEMP_DIR") )
	files = glob.glob( os.path.join(tmpdir, '*.hip') )

	uicall = calledFromUI

	if hou.isUIAvailable() and len(files)>0:

		td = os.path.join(tmpdir, '') # dir with '/'
		files = [ (f, os.path.getmtime(f), ) for f in files ]
		files = sorted(files, key=lambda f: f[1], reverse=True)
		files = [ str(re.sub('^%s' % td, '', f[0])) for f in files ]
		
		sel = hou.ui.selectFromList(files, exclusive=True,
			title="Crash Recovery",
			message="Select .hip File to Recover")

		recovered = False
		if len(sel)>0:
			f = files[sel[0]]
			fn = os.path.join(tmpdir, f)

			# extract HIPNAME
			f = re.sub('^crash.', '', f)
			f = re.sub('\..+_[0-9]+\.hip', '.hip', f)

			# do recovery
			try:
				hou.hipFile.clear(True)
				hou.hipFile.load(fn, True)
				hou.setUpdateMode(hou.updateMode.Manual)
				recovered = True
			except:
				hou.ui.setStatusMessage("error while recovering file %s" % fn, hou.severityType.Error)
				print "ERROR: %s" % traceback.format_exc()

			hou.hipFile.setName(f)

		# delete crash file(s)

		msg = 'Cleanup: Delete all crash recovery hip files?'
		if recovered:
			msg = \
				'File recovered. Make sure to save it to a safe location.\n' \
				'NOTE: Update mode is set to "Manual" to avoid potential re-crashes.\n' \
				'\n%s' % msg

		d = hou.ui.displayMessage(msg, buttons=("DELETE", "Skip", ))
		if d==0:
			files = \
				glob.glob( os.path.join(tmpdir, 'crash.*') ) + \
				glob.glob( os.path.join(tmpdir, '*.hip') )
			for f in files:
			    try:
				os.remove(f)
			    except:
				pass

			hou.ui.setStatusMessage("crash recovery cleanup: deleted %d files" % len(files))
		else:
			pass # user cancelled

	else:
		# no crash files found
		#
		if uicall:
			hou.ui.setStatusMessage("  Crash Recovery:  No emergency-saved .hip file(s) found -- nothing to recover. (%s)" % tmpdir, hou.severityType.ImportantMessage)
			pass
コード例 #45
0
ファイル: zync_houdini.py プロジェクト: zync/zync-houdini
  def get_raw_params(self):
    """Collects submission parameters.

    Returns:
      {str, object}, Submission parameters.
    """
    source_data = self.fetch_data_from_source()

    if self.node.parm('override_frange').evalAsInt():
      frame_begin = int(self.node.parm('frame_rangex').evalAsInt())
      frame_end = int(self.node.parm('frame_rangey').evalAsInt())
      step = int(self.node.parm('frame_rangez').evalAsInt())
    else:
      frame_begin = source_data['frame_begin']
      frame_end = source_data['frame_end']
      step = source_data['step']

    project_name = get_project_name(self.node)

    if self.node.parm('override_filename').eval():
      output_filename = self.node.parm('output_filename').unexpandedString()
    else:
      output_filename = source_data['output_filename']

    machine_type = self.node.parm('machine_type').evalAsString()
    if not machine_type:
      raise ParameterError('Please select machine type again.')

    houdini_version = hou.applicationVersion()

    dependencies = self.get_dependencies(frame_begin, frame_end, step)
    if self.node.parm('auxiliary_files').evalAsInt():
      extra_assets = file_select_dialog.FileSelectDialog.get_extra_assets(project_name)
      if not extra_assets:
        raise ParameterError('Please select auxiliary files.')
      dependencies |= set(extra_assets)

    scene_info=dict(
      dependencies=list(dependencies),
      houdini_version='Houdini%d.%d' % (houdini_version[0], houdini_version[1]),
      houdini_build_version='%d.%d.%d' % houdini_version,
      renderer_version=source_data['renderer_version'],
      render_current_frame=source_data['render_current_frame']
    )

    if hou.getenv('HOUDINI_OTLSCAN_PATH'):
      scene_info['otlscan_path'] = hou.getenv('HOUDINI_OTLSCAN_PATH')
    if hou.getenv('HOUDINI_OTL_PATH'):
      scene_info['otl_path'] = hou.getenv('HOUDINI_OTL_PATH')

    params_to_send = dict(
      plugin_version=__version__,
      upload_only=self.node.parm('upload_only').evalAsInt(),
      skip_download=self.node.parm('skip_download').evalAsInt(),
      chunk_size=self.node.parm('chunk_size').evalAsInt(),
      instance_type=machine_type,
      num_instances=self.node.parm('num_instances').evalAsInt(),
      frame_begin=frame_begin,
      frame_end=frame_end,
      step=step,
      override_res=self.node.parm('override_resolution').evalAsInt(),
      xres=self.node.parm('resolutionx').evalAsInt(),
      yres=self.node.parm('resolutiony').evalAsInt(),
      notify_complete=self.node.parm('notify_completion').evalAsInt(),
      use_standalone=self.node.parm('use_standalone').evalAsInt(),
      priority=self.node.parm('job_priority').evalAsInt(),
      render_node=get_render_node(self.node).path(),
      output_dir=self.node.parm('output_dir').evalAsString(),
      output_filename=output_filename,
      proj_name=project_name,
      renderer=source_data['renderer'],
      scene_info=scene_info
    )

    if self.node.parm('has_parent').evalAsInt():
      params_to_send['parent_id'] = self.node.parm('parent_id').evalAsInt()

    return params_to_send
コード例 #46
0
ファイル: projmanager.py プロジェクト: gui2one/HOUDINI_CONFIG
            self.rootPath = chosenPath
            # print '!!!!!!!!!!!!!!', self.rootPath
        # print self.combo.count()
        self.createList()

    def reloadBtnClicked(self):
        # print "clicked", self.rootPath
        pass

    def createList(self):
        files = os.listdir(self.rootPath)

        self.listWidget.clear()
        for f in files:
            if not os.path.isdir(os.path.join(proj, f)):
                if f.endswith('.hiplc') or f.endswith('.hip') or f.endswith('hipnc'):
                    self.listWidget.addItem(f)

        self.listWidget.doubleClicked.connect(self.openHipFile)

    def openHipFile(self, _file):
        hou.hipFile.load(os.path.join(self.rootPath, _file.data()))


proj = hou.getenv('JOB')


def createInterface():
    custom = MyCustomWidget()
    return custom
コード例 #47
0
ファイル: debris_sim.py プロジェクト: gui2one/HOUDINI_CONFIG
import hou
import toolutils
import soptoolutils

import sys
import os

TOOLS_PATH = hou.getenv('CUSTOM_PYTHON_TOOLS')
sys.path.append(TOOLS_PATH)
from gui2one_utils import gui2one_utils
reload(gui2one_utils)

#print kwargs

activepane = toolutils.activePane(kwargs)
if activepane.type() != hou.paneTabType.SceneViewer:
    raise hou.Error("This tool cannot run in the current pane")

scene_viewer = toolutils.sceneViewer()
nodetypename = "delete"

# Obtain a geometry selection
geo_types = (hou.geometryType.Primitives, )
selection = scene_viewer.selectGeometry(
    "Select the primitives from which to create debris and press Enter to complete",
    geometry_types=geo_types,
    allow_obj_sel=True)
# The following will raise an exception if nothing was selected.
if len(selection.nodes()) == 0:
    raise hou.Error("Nothing was selected.")
コード例 #48
0
def generate_completes(force=False):
    # si = subprocess.STARTUPINFO()
    # si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    # check parsed functions
    cache_file = vex_settings.get_autocomplete_cache_file()
    if os.path.exists(cache_file) and not force:
        return True
    # get vcc
    vcc = os.path.join(hou.getenv('HFS'), 'bin', 'vcc')
    if os.name == 'nt':
        vcc = (vcc + '.exe').replace('/','\\')
        def get_output(cmd):
            if isinstance(cmd, list):
                cmd = ' '.join(cmd)
            process = QProcess()
            process.start(cmd)
            process.waitForFinished()
            return str(process.readAll())
    else:
        def get_output(cmd):
            return subprocess.check_output(cmd)#, startupinfo=si)

    if not os.path.exists(vcc):
        return False
    # generate new
    funcs = {}
    attrs = {}
    lines =  get_output([vcc, '-X']).split('\n')
    for context in lines:
        if context:
            # print 'Context: %s' % context
            context_lines = get_output([vcc, '-X', context])
            # variables
            variables = re.search(r'Global Variables:(.*)Control Statements:', context_lines, re.DOTALL)
            if variables:
                lines = variables.group(1).strip().split('\n')
                for l in lines:
                    s = l.split()
                    if len(s)==3:
                        attrs[s[-1]] = s[-2]
            # functions
            pat = r'^\s*(\w+\[?\]?)\s(\w+)(\(.+\))'
            for l in context_lines.split('\n'):
                func = re.findall(pat, str(l))
                if func:
                    f_name = func[0][1]
                    f_args = func[0][2]
                    if f_name in funcs:
                        if not f_args in funcs[f_name].get('args', []):
                            funcs[f_name]['args'].append(f_args)
                    else:
                        funcs[f_name] = {'args':  [f_args]}
    # parse help if Houdini 15
    if hou.applicationVersion()[0] >= 15:
        funcs = parse_help(funcs)
    # save to cache
    if os.path.exists(cache_file):
        comp = json.load(open(cache_file))
    else:
        comp = {}
    comp['functions'] = funcs
    comp['attributes'] = attrs
    json.dump(comp, open(cache_file, 'w'))
    return True
コード例 #49
0
	if file =="" :
		return None
	else :
		# so we got some data we need to split it as we could have $JOB $HIP or $HOME prepended
		# to it  if we partition based on the / we get a tuple with "", "/","/....." where the
		# first element is going to be an environment var etc.
		file=file.partition("/")
		# we have $HOME so extract the full $HOME path and use it
		if file[0]=="$HOME" :
			prefix=str(hou.getenv("HOME"))
		elif file[0] == "$HIP" :
		#we have $HIP so extract the full $HIP path
			prefix=str(hou.getenv("HIP"))
		# we have a $JOB so extract the full $JOB path
		elif file[0] == "$JOB" :
      prefix=str(hou.getenv("JOB"))
		# nothing so just blank the string
		else :
			prefix=str("")
	#now construct our new file name from the elements we've found
	return "%s/%s" %(prefix,file[2])


def createNull(parent,_name,x,y,z) :
	#create a null this will set loads of default values
	null = parent.createNode("null", _name, run_init_scripts=False, load_contents=True)
	# set the x,y,z values
	null.parm("tx").set(x)
	null.parm("ty").set(y)
	null.parm("tz").set(z)
	# now add a control to the null so we have something to visualise