Beispiel #1
0
	def houGetExternalFiles(self):
		hou.setFrame(hou.playbar.playbackRange()[0])
		whitelist = ['$HIP/$OS-bounce.rat', '$HIP/$OS-fill.rat', '$HIP/$OS-key.rat', '$HIP/$OS-rim.rat']
		houdeps = hou.fileReferences()
		extFiles = []
		extFilesSource = []
		for x in houdeps:
			if "/Redshift/Plugins/Houdini/" in x[1]:
				continue

			if x[0] is None:
				continue

			if x[1] in whitelist:
				continue

			if not os.path.isabs(hou.expandString(x[1])):
				continue

			if os.path.splitext(hou.expandString(x[1]))[1] == "":
				continue

			if x[0] is not None and x[0].name() in ["RS_outputFileNamePrefix", "vm_picture"]:
				continue

			if x[0] is not None and x[0].name() in ["filename", "dopoutput", "copoutput", "sopoutput"] and x[0].node().type().name() in ["rop_alembic", "rop_dop", "rop_comp", "rop_geometry"]:
				continue

			extFiles.append(hou.expandString(x[1]).replace("\\", "/"))
			extFilesSource.append(x[0])

		#return [extFiles, extFilesSource]
		return extFiles
Beispiel #2
0
    def parse_scene(self):
        """
        Goes through all file references and if a texture is found and it exists it is added to 'tex_list'
        Items in 'tex_list' are added to the 'QTreeWidget' and to the 'images_dict'
        """

        tex_list = []
        tex_parm_names = ["file", "fileName", "tex0", "env_map"]

        file_refs = hou.fileReferences()
        for parm, string in file_refs:
            if parm != None:
                if parm.name() in tex_parm_names:
                    tex = hou.expandString(string)
                    tex = self.convert_backslash(tex)
                    if tex.endswith(extensions):
                        if os.path.isfile(tex):
                            if tex not in images_dict.keys():
                                if tex not in tex_list:
                                    tex_list.append(tex)

        for tex in tex_list:
            # Add textures to QTreeWidget
            item = QTreeWidgetItem(treeview)
            item.setText(0, tex)

        self.append_tex_to_dict(tex_list)  # Add textures to 'images_dict'
        self.resetProgress()  # Reset progress bar to 0%
        self.check_status(tex_list)
 def load(self):
     '''Reads Parms from Houdini File '''
     self.clear_rows()
     for parm, path in hou.fileReferences():
         if parm:
             if not parm.node().isInsideLockedHDA():
                 if parm.node().type().name() != "inline":
                     refParm = parm.getReferencedParm()
                     if refParm == parm:
                         row = Row()
                         row.set_node(parm.node())
                         row.set_parm(parm)
                         # Check if string parm
                         if parm.parmTemplate().type(
                         ) == hou.parmTemplateType.String:
                             try:
                                 row.set_path(parm.unexpandedString())
                             except hou.OperationFailed:
                                 row.set_path(parm.expression())
                             try:
                                 row.set_new_path(parm.unexpandedString())
                             except hou.OperationFailed:
                                 row.set_new_path(parm.expression())
                         else:
                             row.set_path(parm.evalAsString())
                             row.set_new_path(parm.evalAsString())
                         row.set_id(self.ids)
                         self.ids += 1
                         self.rows.append(row)
  def get_dependencies(frame_begin, frame_end, step):
    """Finds all file dependencies in the project for specific range of frames.

    Args:
      frame_begin: First frame (inclusive) of range to render.
      frame_end: Last frame (inclusive) of range to render.
      step: Frame range step.

    Returns:
      set of str, List of detected dependencies.
    """
    refs = hou.fileReferences()
    frames = xrange(int(frame_begin), int(frame_end) + 1, int(step))

    result = set()
    for frame in frames:
      for parm, _ in refs:
        if parm:
          file_path = parm.evalAtFrame(frame)
          if file_path in result:
            continue
          try:
            if hou.findFile(file_path):
              result.add(file_path)
          except hou.OperationFailed:
            pass
    return result
Beispiel #5
0
  def get_dependencies(frame_begin, frame_end, step):
    """Finds all file dependencies in the project for specific range of frames.

    Args:
      frame_begin: First frame (inclusive) of range to render.
      frame_end: Last frame (inclusive) of range to render.
      step: Frame range step.

    Returns:
      set of str, List of detected dependencies.
    """
    refs = hou.fileReferences()
    frames = xrange(int(frame_begin), int(frame_end) + 1, int(step))

    result = set()

    wildcards = ['<udim>', '$SF']
    wildcard_regex = [re.compile(re.escape(wc), re.IGNORECASE)
                      for wc in wildcards]

    for frame in frames:
      for parm, _ in refs:
        if parm:
          file_path = parm.evalAtFrame(frame)
          if file_path in result:
            continue
          for wildcard in wildcard_regex:
            file_path = wildcard.sub('*', file_path)
          for file in glob.glob(file_path):
            try:
              if hou.findFile(file) and file not in result:
                result.add(file)
            except hou.OperationFailed:
              pass
    return result
Beispiel #6
0
 def load(self):
     '''Reads Parms from Houdini File '''
     self.clear_rows()
     for parm, path in hou.fileReferences():
         if parm:
             row = Row()
             row.set_node(parm.node())
             row.set_parm(parm)
             row.set_path(parm.evalAsString())
             row.set_new_path(parm.evalAsString())
             row.set_id(self.ids)
             self.ids += 1
             self.rows.append(row)
Beispiel #7
0
def _ref_parms(node):
    """All file parms except those on other job nodes.

    When submitting a job and there are other jobs in the
    scene, we don't want files referenced on those other
    nodes because they are not needed for this job. They are
    likely to be scripts or tools needed to make that other
    job run.
    """
    result = []
    refs = hou.fileReferences()
    for parm, _ in refs:
        if parm and _is_wanted(parm, node):
            result.append(parm)
    return result
def _ref_parms(node):
    """All file parms except those on other job nodes.

    When submitting a job and there are other jobs in the
    scene, we don't want files referenced on those other
    nodes because they are not needed for this job. They are
    likely to be scripts or tools needed to make that other
    job run.
    """
    result = []
    refs = hou.fileReferences()
    for parm, _ in refs:
        if parm and _is_wanted(parm, node):
            result.append(parm)
    return result
	def sm_getExternalFiles(self, origin):
	#	hou.setFrame(hou.playbar.playbackRange()[0])
		whitelist = ['$HIP/$OS-bounce.rat', '$HIP/$OS-fill.rat', '$HIP/$OS-key.rat', '$HIP/$OS-rim.rat']
		expNodes = [ x.ui.node for x in self.core.sm.states if x.ui.className in ["Export", "ImageRender"] and x.ui.node is not None and self.isNodeValid(origin, x.ui.node)]
		houdeps = hou.fileReferences()
		extFiles = []
		extFilesSource = []
		for x in houdeps:
			if "/Redshift/Plugins/Houdini/" in x[1]:
				continue

			if x[0] is None:
				continue

			if x[0].node() in expNodes:
				continue

			if x[0].node().parent() in expNodes and x[0].node().type().name() == "file":
				continue

			if x[1] in whitelist:
				continue

			if not os.path.isabs(hou.expandString(x[1])):
				continue

			if os.path.splitext(hou.expandString(x[1]))[1] == "":
				continue

			if x[0] is not None and x[0].name() in ["RS_outputFileNamePrefix", "vm_picture"]:
				continue

			if x[0] is not None and x[0].name() in ["filename", "dopoutput", "copoutput", "sopoutput"] and x[0].node().type().name() in ["rop_alembic", "rop_dop", "rop_comp", "rop_geometry"]:
				continue

			if x[0] is not None and x[0].name() in ["filename", "sopoutput"] and x[0].node().type().category().name() == "Driver" and x[0].node().type().name() in ["geometry", "alembic"]:
				continue

			extFiles.append(hou.expandString(x[1]).replace("\\", "/"))
			extFilesSource.append(x[0])

		return [extFiles, extFilesSource]
Beispiel #10
0
    def get_dependencies(frame_begin, frame_end, step):
        """Finds all file dependencies in the project for specific range of frames.

    Args:
      frame_begin: First frame (inclusive) of range to render.
      frame_end: Last frame (inclusive) of range to render.
      step: Frame range step.

    Returns:
      set of str, List of detected dependencies.
    """
        refs = hou.fileReferences()
        frames = xrange(int(frame_begin), int(frame_end) + 1, int(step))

        result = set()

        wildcards = ['<udim>', '$SF']
        wildcard_regex = [
            re.compile(re.escape(wc), re.IGNORECASE) for wc in wildcards
        ]

        for frame in frames:
            for parm, _ in refs:
                if parm:
                    file_path = parm.evalAtFrame(frame)
                    if file_path in result:
                        continue
                    for wildcard in wildcard_regex:
                        file_path = wildcard.sub('*', file_path)
                    for file in glob.glob(file_path):
                        try:
                            if hou.findFile(file) and file not in result:
                                result.add(file)
                        except hou.OperationFailed:
                            pass
        return result
Beispiel #11
0
def CollectSceneAssets(settings):
    IGNORE_BYPASSED = settings[0]
    IGNORE_PROXY = settings[1]
    IGNORE_NONDISPLAY = settings[2]
    FILTER_FILETYPES = settings[3]
    FILETYPES = settings[4]
    
    SceneAssets = []

    #Set to frame 0 and update to manual
    hou.setUpdateMode(hou.updateMode.Manual)        
    hou.setFrame(hou.playbar.playbackRange()[0])    
    #hou.hipFile.save()
    
    #collect all file references
    refs = hou.fileReferences():  
    
    # Find file caches and remove file references above in the same network   
    # We'll end up looping through twice for this
    for file_parm, file in refs:
        #IF file parameter is None, it's an HDA or something we shouldn't need to include
        if file_parm is None: 
            continue;
        if isinstance(file_parm.node(), hou.SopNode):
            if file_parm.name() == "file":
                p = file_parm.path().split("/")
                #SKIP IF WRITE OUT NODE - TWO FILES NODES EXISTS IN EACH FILE CACHE
                if "file_mode" in p:
                    continue;
                if file_parm
        
    
    string = "----\n\n"
    for file_parm, file in refs:
        #IF file parameter is None, it's an HDA or something we do not need to include
        if file_parm is None: 
            continue;
        
        #Remove ROP file references
        if type(file_parm.node()) == hou.RopNode:        
            continue;
        
        # Finding and ignoring referenced SOPs and not displayed
        # Hacky way, iterate 10 times; Returns the referenced parameter. If no parameter is referenced, returns this parameter.
        for i in xrange(10): 
            file_parm = file_parm.getReferencedParm()
            
        # Check and skip if node is disabled
        if IGNORE_BYPASSED and file_parm.isDisabled():
            continue;
        #Check if bypassed
        if IGNORE_BYPASSED and file_parm.node().isGenericFlagSet(hou.nodeFlag.Bypass):
            continue;
            
        # Testing for display flag. 
        # DOES NOT WORK because of assets objs are hidden
        """
        disp = True
        if isinstance(file_parm.node(), hou.SopNode):
            top = getObjParent(file_parm.node())
            if top:
                disp = top.isGenericFlagSet(hou.nodeFlag.Display)
        if IGNORE_NONDISPLAY and not disp:
            continue;
        """
        
        # GET FILE CACHE SOPS AND FILE RANGES
        if isinstance(file_parm.node(), hou.SopNode):
            if file_parm.name() == "file":
                p = file_parm.path().split("/")
                #SKIP IF WRITE OUT NODE - TWO FILES NODES EXISTS IN EACH FILE CACHE
                if "file_mode" in p:
                    continue;
                startFr = file_parm.node().parm("f1").eval()
                endFr = file_parm.node().parm("f2").eval()
                # Adjust frame ranges from which is smallest. Render or file cache range.
                if frameRange[0] > startFr:
                    startFr = frameRange[0]
                if frameRange[1] < endFr:
                    endFr = frameRange[1]
                files = CollectFrameRange(file_parm, startFr, endFr)
                for file in files:
                    SceneAssets.append(file)
                    continue;
        
        
        #Evaluate variables and expressions to the complete path
        expandedFile = file_parm.eval()
            
        #string += str(file_parm)
        #string += " :: " + expandedFile + "\n"
        
        SceneAssets.append(expandedFile)
        
    
    #Filter list and delete duplicates
    FilteredAssets = []
    for i in SceneAssets:
        if i not in FilteredAssets:
            FilteredAssets.append(i)
    
    return FilteredAssets
def package():
    """
        First implementation of a packaging class for houdini files and assets.
        the function gets and packages all the OTL's and all in and outputs related to the scene.
        then it will package it as a ZIP file and store it in the home directory.
      
    """

    hou.hipFile.save()
    currentHip = hou.expandString(hou.hipFile.name())

    # create a temp directory we are going to fill with crap
    tempFilePath = tempfile.mkdtemp()

    otls = os.path.join(tempFilePath, "otls")
    os.mkdir(otls)
    files = os.path.join(tempFilePath, "files")
    os.mkdir(files)

    # Get all the external references to the hipfile
    fileOnDisk = hou.fileReferences()

    # loop and do what comes natural.
    for _file in fileOnDisk:

        parm = _file[0]
        filepath = _file[1]

        # if its a otl we need to store it.
        if filepath.endswith(".otl"):

            shutil.copy(hou.expandString(filepath), otls)

        else:

            if not os.path.isfile(hou.expandString(filepath)):

                continue

            # create a directory in files and save 1 file to that location
            tmpFileName = os.path.basename(hou.expandString(filepath))
            tmpFileDir = os.path.basename(
                os.path.dirname(hou.expandString(filepath)))
            path = os.path.join(files, tmpFileDir)

            if not os.path.isdir(path):

                os.mkdir(path)

            shutil.copy(
                hou.expandString(filepath),
                os.path.join(path,
                             os.path.basename(hou.expandString(filepath))))

            try:

                if not parm.node().isLocked():

                    parm.set(
                        os.path.join(path.replace(tempFilePath, "$HIP"),
                                     tmpFileName))

            except hou.PermissionError:

                logging.warning("Error hardening parm :" + str(parm.name()) +
                                "on node " + parm.node().path())

    hou.hipFile.save(
        os.path.join(tempFilePath,
                     os.path.basename(hou.expandString(hou.hipFile.name()))))
    # Load the source hipfile
    hou.hipFile.load(currentHip)

    # create a zipfile and package everything. then copy it to the home.
    zipfileLoc = zipdir(tempFilePath)
    shutil.move(zipfileLoc, os.path.join(hou.expandString("~"), "package.zip"))
    shutil.rmtree(tempFilePath)
Beispiel #13
0
    def GetAssets(self):
        if not self.runcode:
            self.runend = True
            sys.exit(886)
        ## eg. asset = {"Normal":{"node1":["filename",["files"]],"node2":["filename",["files"]]},
        ##                    "Miss":{"node1":["filename",["files"]],"node2":["filename",["files"]]}}
        Miss_adict = {}
        Normal_adict = {}
        folder_adict = {}
        search_adict = {}

        file_adict = hou.fileReferences()
        # print(file_adict)
        for elm in file_adict:
            if not elm[0] == None:
                if self.isFile(elm[0].eval()):
                    if not elm[0].name() in self._typelist and len(elm[-1]):
                        if not os.path.splitext(elm[-1])[-1] in self._ext:
                            HfsSql.insertToTable(self._sl, self._cur,
                                                 self._refer_table, ["TYPES"],
                                                 [elm[0].name()])
                            self._typelist.append(elm[0].name())

                    if self.isFile(elm[-1]):
                        file_split = os.path.split(elm[0].eval())
                        # print(file_split)
                        if elm[0].eval() not in search_adict:
                            if not file_split[0] in folder_adict:
                                is_sq, return_file, dif_files = self.issequence(
                                    file_split[0], self.TypeFit(file_split[1]))
                                folder_adict[file_split[0]] = dif_files
                            else:
                                is_sq, return_file, dif_files = self.issequence(
                                    file_split[0], self.TypeFit(file_split[1]),
                                    folder_adict[file_split[0]])
                                folder_adict[file_split[0]] = dif_files
                            ##
                            Normal_adict, Miss_adict = self.AssetEdit(
                                elm, is_sq, return_file, file_split[0],
                                Normal_adict, Miss_adict)
                            search_adict[elm[0].eval()] = [is_sq, return_file]
                        else:
                            ## find it in search_adict
                            returns = search_adict[elm[0].eval()]
                            Normal_adict, Miss_adict = self.AssetEdit(
                                elm, returns[0], returns[1], file_split[0],
                                Normal_adict, Miss_adict)

                    elif elm[-1] == None or elm[-1] == "":
                        ## check types
                        print(elm)
                        if elm[0].name() in self._typelist:
                            pass
                    else:
                        print("-" * 80)
                        print("DO FILT")
                        print_times(elm)

        self.asset_adict = {
            "Normal": Normal_adict,
            "Miss": Miss_adict,
            "camera": self.CheckCamera()
        }
        self.tips_adict = {}
        # print(self.asset_adict)
        self.TipsInfo()
        self.WriteFile(self.asset_adict, self._args.asset, 'json')
        self.WriteFile(self.tips_adict, self._args.tips, 'json')
Beispiel #14
0
    def parse_scene(self):
        """
        '_all_Files_List structure':
        Index | Parm
        0     | Path to node
        1     | Path to file
        2     | Node parm
        3     | Is UDIM boolean
        4     | Is Sequence boolean
        5     | Index
        """

        global _missing_Textures_Index_List
        global _all_Files_List
        global _amount_Missing_Textures

        _asset_List.clearContents()

        all_Files = hou.fileReferences()
        _all_Files_List_temp = []
        _all_Files_List = {}
        _missing_Textures_Index_List = []
        _amount_Missing_Textures = 0

        for parm, filePath in all_Files:
            if parm != None:
                if _include_out_CB.isChecked() == False:
                    parm_parent = parm.node().parent().type().name()

                    if parm_parent != "out":
                        if parm_parent != "ropnet":
                            if filePath.endswith(
                                    tex_extensions) | filePath.endswith(
                                        geo_extensions) | filePath.endswith(
                                            sim_extensions):
                                _all_Files_List_temp.append((parm, filePath))
                else:
                    if filePath.endswith(tex_extensions) | filePath.endswith(
                            geo_extensions) | filePath.endswith(
                                sim_extensions):
                        _all_Files_List_temp.append((parm, filePath))

        for index, parm_tuple in enumerate(_all_Files_List_temp):
            parm = parm_tuple[0]
            file = parm_tuple[1]

            if parm != None:
                if file.endswith(tex_extensions) | file.endswith(
                        geo_extensions) | file.endswith(sim_extensions):
                    nodePath = parm.node().path()
                    filePath = self.convert_backslash(file)

                    filePath_abs = hou.expandString(filePath)

                    _asset_List.setRowCount(len(_all_Files_List_temp))

                    filePath_item = QtWidgets.QTableWidgetItem()
                    filePath_item.setText(filePath)

                    nodePath_item = QtWidgets.QTableWidgetItem()
                    nodePath_item.setText(nodePath)

                    is_sequence = re.search(r"[$]F", filePath)
                    is_udim = re.search(r"<udim>", filePath)

                    _all_Files_List[index] = [
                        nodePath, filePath, parm, is_udim, is_sequence, index
                    ]

                    if is_udim != None:
                        filePath_abs = filePath_abs.replace("<udim>", "1001")
                    else:
                        filePath_abs = hou.expandString(filePath)

                    filePath_abs_item = QtWidgets.QTableWidgetItem()
                    filePath_abs_item.setText(filePath_abs)

                    _asset_List.setItem(index, 0, filePath_item)
                    _asset_List.setItem(index, 2, filePath_abs_item)
                    _asset_List.setItem(index, 3, nodePath_item)

                    if not os.path.exists(filePath_abs):
                        _amount_Missing_Textures += 1
                        _missing_Textures_Index_List.append(index)
                        filePath_item.setIcon(QtGui.QIcon(missing_Icon))
                    else:
                        filePath_item.setIcon(QtGui.QIcon(found_Icon))

        status_text = "Status: Found - " + str(
            len(_all_Files_List)) + " | " + "Missing - " + str(
                _amount_Missing_Textures) + " | "

        _status.setText(status_text)
def package():
    """
        First implementation of a packaging class for houdini files and assets.
        the function gets and packages all the OTL's and all in and outputs related to the scene.
        then it will package it as a ZIP file and store it in the home directory.
      
    """
      
    hou.hipFile.save()
    currentHip = hou.expandString(hou.hipFile.name())

    # create a temp directory we are going to fill with crap
    tempFilePath = tempfile.mkdtemp()
      
    otls = os.path.join(tempFilePath, "otls")
    os.mkdir(otls)
    files = os.path.join(tempFilePath, "files")
    os.mkdir(files)
    
    # Get all the external references to the hipfile
    fileOnDisk = hou.fileReferences()

    # loop and do what comes natural.
    for _file in fileOnDisk:

        parm = _file[0]
        filepath = _file[1]
    
        # if its a otl we need to store it.
        if filepath.endswith(".otl"):
    
            shutil.copy(hou.expandString(filepath), otls)
            
        else:
              
            if not os.path.isfile(hou.expandString(filepath)): 
                
                continue
                
            # create a directory in files and save 1 file to that location
            tmpFileName = os.path.basename(hou.expandString(filepath))
            tmpFileDir = os.path.basename(os.path.dirname(hou.expandString(filepath)))
            path = os.path.join(files, tmpFileDir)
              
            if not os.path.isdir(path):
              
                os.mkdir(path)

            shutil.copy(hou.expandString(filepath), os.path.join(path, os.path.basename(hou.expandString(filepath))))

            try:
                      
                if not parm.node().isLocked():
                      
                    parm.set(os.path.join(path.replace(tempFilePath, "$HIP"), tmpFileName))
                      
            except hou.PermissionError: 
                  
                logging.warning("Error hardening parm :" + str(parm.name()) + "on node " +parm.node().path())

    hou.hipFile.save(os.path.join(tempFilePath, os.path.basename(hou.expandString(hou.hipFile.name()))))
    # Load the source hipfile
    hou.hipFile.load(currentHip)
      
    # create a zipfile and package everything. then copy it to the home.
    zipfileLoc = zipdir(tempFilePath)
    shutil.move(zipfileLoc, os.path.join(hou.expandString("~"), "package.zip"))
    shutil.rmtree(tempFilePath)
def collectProject(settings):
    IGNORE_BYPASSED = settings[0]
    COPY_NON_RELATIVE = settings[1]
    IGNORE_PROXY = settings[2]
    IGNORE_NONDISPLAY = settings[3]
    DISABLE_ARCHIVE = settings[4]
    FILETYPE_FILTER = settings[5]
    FILETYPES = settings[6]
    
    # save the file, then save it to the collection dir later?
    hou.setUpdateMode(hou.updateMode.Manual)        
    hou.setFrame(hou.playbar.playbackRange()[0])    
    
    hou.hipFile.save()
    hipname = hou.hipFile.basename()    
    refs = hou.fileReferences()
    
    if DISABLE_ARCHIVE:
        collectDir = '$HIP'
    else:
        collectDir = createCollectionDir()
    
    # ignore archived/proxy files
    proxy = ['.ifd', '.ass', '.rs']
    # ignore refs with these extensions for refs not in $HIP or $JOB
    ignoredExt = ['.hda', '.hdalc', '.hdanc', '.otl', '.pc', '.pmap']       
    # filetype whitelist 
    if FILETYPE_FILTER:
        extfilter = ['.' + x for x in FILETYPES.split()]
        
    # TODO Also delete non-displayed OBJ nodes when they are ignored?
    toDel = []
    # Get refs to be copied
    toCopy = []
    toCopyMisc = [] # for non-HIP/JOB files to sort out
    for ref in refs:
        parm = ref[0]
        r = ref[1]
        if parm:
            for i in xrange(10): # hack to get referenced parm since isRef is not implemented?
                parm = parm.getReferencedParm()                
            bypassed = parm.node().isGenericFlagSet(hou.nodeFlag.Bypass)
            # Testing for display flag. Could also apply to DOPs but maybe a bad idea..
            disp = True
            if isinstance(parm.node(), hou.SopNode):
                top = getObjParent(parm.node())
                if top:
                    disp = top.isGenericFlagSet(hou.nodeFlag.Display)  
            #
            if IGNORE_NONDISPLAY and not disp:
                toDel.append(top)
            # copy ref if bypass option is off or node isnt bypassed                  
            elif IGNORE_BYPASSED and bypassed:
                pass
            # copy ref if proxy filter off or ref extension isnt a render proxy                
            elif IGNORE_PROXY and os.path.splitext(r)[1] in proxy:
                pass
            else:
                fname, fext = os.path.splitext(ref[1])
                # check for file extension filter
                if extfilter and fext in extfilter:
                    if not (r.startswith('$HIP') or r.startswith('$JOB')):
                        if COPY_NON_RELATIVE and fext not in ignoredExt:
                            # Ignore Dop Nodes for now? Also ignore op: refs?
                            if not isinstance(parm.node(), hou.DopNode) and not r.startswith('op'):
                                toCopyMisc.append(ref)    
                    elif not DISABLE_ARCHIVE:
                        toCopy.append(ref) 
    
    # Delete Non-Displayed
    if IGNORE_NONDISPLAY:
        randomNode = hou.node("/").children()[0]
        randomNode.deleteItems(toDel)
                    
    # Create Progress Bar
    numToCopy = len(toCopy) + len(toCopyMisc)
    pbar = QProgressDialog("Copying Files", "Abort", 0, numToCopy);
    pbar.setWindowTitle("Collect Progress")  
    pbar.setWindowModality(Qt.WindowModal);        
    pbar.setStyleSheet(hou.ui.qtStyleSheet())
    l = pbar.layout()
    if l:
        l.setSizeConstraint(QLayout.SetMaximumSize)
    pbar.setValue(0)        
    pbar.forceShow()
                       
    # ==============================================================
    # Copy Relative files HIP/JOB
    # ==============================================================
    if not DISABLE_ARCHIVE:
        for ref in toCopy:
            r = ref[1]
            
            # Increment Progress bar. This seems to show the previous item??
            pbar.setValue(pbar.value()+1)
            pbar.setLabelText(r)
            if pbar.wasCanceled():
                break        
            
            # Check if the the ref is linked to another channel. If so, expand that channel value instead (to fix $OS references?)
            parm = ref[0]
            for i in xrange(10): # hack since isRef is not implemented?
                parm = parm.getReferencedParm() 
            r = re.sub('\$OS', parm.node().name(), r)
            
            p = r[4:]
            collectedPath = collectDir + p  
            # ensure the subdir exists in the collect dir        
            collectedDir = os.path.dirname(hou.expandString(collectedPath))
            if not os.path.exists(collectedDir):
                os.makedirs(collectedDir)       
                     
            # Copy Sequences
            if re.search('\$F', r):
                s = re.sub('\$F\d+', '*', r)
                s = re.sub('\$F', '*', s)
                print "$HIP/$JOB Sequence found:" + hou.expandString(s) 
                seqFiles = glob.glob(hou.expandString(s))
                if seqFiles:
                    for f in seqFiles:
                        try:
                            copiedFilePath = collectedDir + '/' + os.path.basename(f)                    
                            if not os.path.exists(copiedFilePath):
                                shutil.copy(hou.expandString(f), copiedFilePath) 
                        except:
                            pass
                else:
                    print "Error Finding File Sequence - No items copied"
            # Copy Single Files
            else:
                try:
                    print "$HIP/$JOB File found:" + str(r)
                    if not os.path.exists(collectedPath):
                        shutil.copy(hou.expandString(r), collectedPath)             
                except Exception as e:
                    pass
                    # print(e)   
    
    # save to new loc and sort the non-HIP/JOB refs after saving?   
    hou.hipFile.save(collectDir+'/'+hipname)        
        
    # ==============================================================
    # Copy NON Relative files and adjust their parms
    # ==============================================================   
    if COPY_NON_RELATIVE:
        # Create misc dir
        collectedMisc = ""
        if toCopyMisc:
            collectedMisc = collectDir + '/misc'
            if not os.path.exists(collectedMisc):
                    os.makedirs(collectedMisc)         
    
        for ref in toCopyMisc:
            r = ref[1]

            # Increment Progress bar. This seems to show the previous item??
            pbar.setValue(pbar.value()+1)
            pbar.setLabelText(r)
            if pbar.wasCanceled():
                break        
            
            # Check if the the ref is linked to another channel. If so, expand that channel value instead (to fix $OS references?)
            parm = ref[0]
            for i in xrange(10): # hack since isRef is not implemented?
                parm = parm.getReferencedParm() 
            r = re.sub('\$OS', parm.node().name(), r)
                         
            # Copy Sequences
            if re.search('\$F', r):                
                s = re.sub('\$F\d+', '*', r)
                s = re.sub('\$F', '*', s)
                print "Non-$HIP/$JOB Sequence found:" + hou.expandString(s) 
                seqFiles = glob.glob(hou.expandString(s))
                if seqFiles:
                    # set new parm value (with correct unexpanded $F string?)
                    try:
                        parm.set('$HIP/misc/'+ os.path.basename(r))                
                    except:
                        print "unable to change parm: "+parm.path()
                    for f in seqFiles:
                        try:
                            copiedFilePath = collectedMisc + '/' + os.path.basename(f)                    
                            if not os.path.exists(copiedFilePath):
                                shutil.copy(hou.expandString(f), copiedFilePath) 
                        except:
                            pass
                else:
                    print "Error Finding File Sequence - No items copied"
            # Copy Single Files
            else:
                filename = os.path.basename(hou.expandString(r))
                collectedMiscTemp = collectedMisc + '/' + filename  
                # try to set new parm value
                try:
                    parm.set('$HIP/misc/'+filename)
                except:
                    print "unable to change parm: "+parm.path()
                try:
                    print "Non-$HIP/$JOB File found:" + str(r)                 
                    if not os.path.exists(collectedMiscTemp):
                        print collectedMiscTemp
                        shutil.copy(hou.expandString(r), collectedMiscTemp)             
                except Exception as e:
                    pass
                    # print(e)          
    # set JOB to new HIP loc
    hou.putenv('$JOB', collectDir)
Beispiel #17
0
try:
    if not os.path.exists(sys.argv[1]):
        sys.exit("ERROR - Scene File does not exist - " + sys.argv[1])

    writeLog("load Scene")
    hou.hipFile.load(sys.argv[1], ignore_load_warnings=True)

    frameStart = int(sys.argv[2])
    frameEnd = int(sys.argv[3])

    jobData = eval(sys.argv[4])

    localSlavePath = eval(sys.argv[5])[0]

    depFiles = os.listdir(os.path.dirname(sys.argv[1]))
    for i in hou.fileReferences():
        try:
            fseq = False
            if "$F" in i[1]:
                countExp = os.path.basename(i[1]).count('`')
                startExp = os.path.basename(i[1]).find("`")
                endExp = os.path.basename(i[1]).rfind("`")
                if countExp == 2:
                    startName = os.path.basename(i[1])[:startExp]
                    endName = os.path.basename(i[1])[endExp + 1:]
                else:
                    startName = os.path.basename(
                        i[1])[:os.path.basename(i[1]).find("$F")]
                    endName = os.path.basename(
                        i[1])[os.path.basename(i[1]).find("$F") + 3:]
Beispiel #18
0
 def getAllLinkedFiles(self):
     self.files = hou.fileReferences()
     return self.files