def get_output_nodes(self): """returns the rop nodes in the scene """ ropContext = hou.node('/out') # get the children outNodes = ropContext.children() exclude_node_types = [ hou.nodeType(hou.nodeTypeCategories()["Driver"], "wedge") ] # remove nodes in type in exclude_node_types list new_out_nodes = [node for node in outNodes if node.type() not in exclude_node_types] return new_out_nodes
def remove(): import hou remove_types = [] cat_list = [ hou.nodeTypeCategories()['Vop'], hou.nodeTypeCategories()['Shop'], hou.nodeTypeCategories()['Object'], hou.nodeTypeCategories()['Driver'], hou.nodeTypeCategories()['VopNet'] ] for m in cat_list: for i, j in m.nodeTypes().items(): if i.find('redshift') != -1 or i.find('rs_') != -1 or i.find( 'Redshift') != -1 or i.find('rslight') != -1 or i.find( 'PP18_RSLight') != -1: remove_types.append(j) nodes = [] for i in remove_types: for j in i.instances(): nodes.append(j) if len(nodes) > 0: print "nodes: ", len(nodes) new = [] for i in nodes: par = i.parent() if not i.isInsideLockedHDA() and not par.isInsideLockedHDA( ) and par not in nodes: new.append(i) print "actual nodes: ", len(new) for i in new: i.destroy() else: print "No RS nodes found"
def createNode(**kwargs): """Create a node, place it, and pick input wire if activeWire is set.""" if kwargs is not None: network_editor = kwargs['editor'] try: scriptargs = {} scriptargs['pane'] = network_editor nodenames = [] nodetypenames = [] categories = hou.nodeTypeCategories() for category in categories.keys(): node_types = categories[category].nodeTypes() for node_type in node_types.keys(): nodenames.append(node_types[node_type].nameComponents()[2]) nodetypenames.append(node_types[node_type].name()) # for whatever reason, I had to call two functions to get the correct # interactions to pick up, so the first call to selectPosition() doesn't do anything network_editor.selectPosition() node = toolutils.genericTool( scriptargs, nodetypename=nodetypenames[nodenames.index( kwargs['nodetype'])]) if kwargs['activeWire'] and len(network_editor.allVisibleRects( ())): pickWire(node, network_editor) except hou.OperationInterrupted: pass
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()
def allPossibleRHDANodeTypeNamesInScene(name, node_type_category_name='Sop'): ''' hou.nodeTypeCategories().keys() ['Shop', 'Cop2', 'CopNet', 'ChopNet', 'Object', 'Driver', 'Chop', 'Sop', 'Manager', 'Vop', 'Director', 'Dop', 'VopNet'] ''' types_dict = {} for category in hou.nodeTypeCategories().values(): if category.name() == node_type_category_name: for node_type in category.nodeTypes().values(): name_components = node_type.nameComponents() if name_components[ 2] == name: # finds all similar node types like noise, noise::2.0, user::dev::noise::1.0 version = name_components[3] if name_components[ 1] == '': # NOT A VHDA, only keep the none VHDA types if version == '': # first versions do not have version numbering version = '1.0' types_dict[float(version)] = node_type.name() type_names = [] if len(types_dict ) == 0: # if no type found (probably this is a brand new vhda node) type_names.append(name) else: for key in sorted(types_dict.keys()): type_names.append(types_dict[key]) # Add an extra increased version item type_names.append(name + '::' + str(types_dict.keys()[-1] + 1.0)) return type_names
def populateWithAllNodes(): categories = hou.nodeTypeCategories() i = 0 parent = hou.node("/obj/geo1") #if len(parent.allItems())>0: #parent.deleteItems(parent.allItems()) #removes all children #print "Children deleted..." for category in categories.values(): node_types = category.nodeTypes() #print "NODE TYPES:"+node_types for node_type in node_types.keys(): #print "Creating: "+node_type if node_type == "v_constant": continue try: node = parent.createNode(node_type) i = i + 1 except hou.OperationFailed: print "error creating:" + node_type #print ("PARENT:"+parent.name()) hou.ui.displayMessage(str(i) + " nodes created.")
def installCpio(cpioPath, userFirstName, name, iconPath=''): shelf = initializeShelf() toolName = name try: netWork = hou.nodeTypeCategories()[network] except: nett = cpioPath.split('.cpio.')[-1] netWork = hou.ndoeTypeCategories()[nett] cpioTitle = user if cpioTitle == 'untitled': toolLabel = userFirstName + '_' + name else: toolLabel = name #iconPath=getIcon(netWork) tool = hou.shelves.newTool(pathShelf, name=toolName, label=toolLabel, icon='', script=cpioInstaller % { 'file': cpioPath, 'tt': toolName }) tool.setToolMenuCategories(hou.paneTabType.NetworkEditor, (netWork, )) tool.setToolLocations((user, )) shelf.setTools(shelf.tools() + (tool, ))
def createNode(**kwargs): """Create a node, place it, and pick input wire if activeWire is set.""" if kwargs is not None: network_editor = kwargs['editor'] try: scriptargs = {} scriptargs['pane'] = network_editor context = utils.getContext(network_editor) mapping = { 'Sop': 'Sop', 'Object': 'Obj', 'Driver': 'Rop', 'Vop': 'Vop' } # BUG 22, 27 - create latest version of node if multiples exist version = 0 categories = hou.nodeTypeCategories() nodes = [] for category in categories.keys(): compare = category if category in mapping: compare = mapping[category] if compare.lower() == context.lower(): node_types = categories[category].nodeTypes() for node_type in node_types.keys(): components = node_types[node_type].nameComponents() checklist = [kwargs['nodetype']] matches = set(checklist).intersection(set(components)) if matches: nodes.append(node_type) tmp = {} if len(nodes) > 1: for x in nodes: tokens = x.split('::') idx = 0 if len(tokens) > 1: digits = tokens[-1] to_int = int(float(digits)) idx = to_int tmp[x] = idx { k: v for k, v in sorted(tmp.items(), key=lambda item: item[1]) } nodes = list(tmp) network_editor.selectPosition() node = toolutils.genericTool(scriptargs, nodetypename=nodes[-1]) if kwargs['activeWire'] and len(network_editor.allVisibleRects( ())): pickWire(node, network_editor) except hou.OperationInterrupted: pass
def get_all_choreofx_node_types(): choreofx_node_types = [] for node_type_category in hou.nodeTypeCategories().values(): for node_type in node_type_category.nodeTypes().values(): if node_type.nameComponents()[1] == "choreofx": choreofx_node_types.append(node_type) return choreofx_node_types
def removeEmbeded(displayConfirmation=False): if displayConfirmation: fee_Utils.displayConfirmation() nodeTypeCategories = hou.nodeTypeCategories() for nodeTypeCategoryKey in nodeTypeCategories: nodeTypeCategory = nodeTypeCategories[nodeTypeCategoryKey] removeCategoryEmbeded(nodeTypeCategory=nodeTypeCategory)
def get_output_nodes(cls): """returns the rop nodes in the scene """ rop_context = hou.node('/out') # get the children out_nodes = rop_context.children() exclude_node_types = [ hou.nodeType(hou.nodeTypeCategories()["Driver"], "wedge"), hou.nodeType(hou.nodeTypeCategories()["Driver"], "fetch") ] # remove nodes in type in exclude_node_types list new_out_nodes = [node for node in out_nodes if node.type() not in exclude_node_types] return new_out_nodes
def getOutputDrivers(path=False): ''' Returns a list of all output driver names ''' rops = hou.nodeType(hou.nodeTypeCategories()['Driver'], 'arnold').instances() if path: return [i.path() for i in rops] return rops
def getAllCameras(path=False): ''' Returns a list of all camera names ''' cameras = hou.nodeType(hou.nodeTypeCategories()['Object'], 'cam').instances() if path: return [i.path() for i in cameras] return cameras
def get_all_hda_definitions(): result = [] for category in hou.nodeTypeCategories().values(): for node_type in category.nodeTypes().values(): definition = node_type.definition() if definition is None: continue if definition not in result: result.append(definition) return result
def _get_used_libraries(): """Introspect session to find library paths for used node types.""" result = [] for category in hou.nodeTypeCategories().values(): for node_type in category.nodeTypes().values(): used = node_type.instances() if used: definition = node_type.definition() if definition: result.append(definition.libraryFilePath()) return result
def allInstalledDefinitionsInScene(node_type_category_name='Sop'): ''' hou.nodeTypeCategories().keys() ['Shop', 'Cop2', 'CopNet', 'ChopNet', 'Object', 'Driver', 'Chop', 'Sop', 'Manager', 'Vop', 'Director', 'Dop', 'VopNet'] ''' definitions = [] for category in hou.nodeTypeCategories().values(): if category.name() == node_type_category_name: for node_type in category.nodeTypes().values(): for definition in node_type.allInstalledDefinitions(): definitions.append(definition) return definitions
def convertAllTextures(kwargs=None): """ finds specified texture parameters in the scene, extracts paths and runs batch convert tool with pre-filled paths alt-clicking on the shelf button enables debug mode which will print more information it finds all instances of nodes specified in node_dict, e.g. "redshift::NormalMap" : "Vop", "redshift::TextureSampler" : "Vop" where Vop is name of hou.NodeTypeCategory object this depends on batch_textures_convert tool: https://github.com/jtomori/batch_textures_convert/ """ debug = False if kwargs: if kwargs["altclick"]: debug = True parm_name = "tex0" node_dict = { "redshift::NormalMap": "Vop", "redshift::TextureSampler": "Vop" } found_nodes = [] for key, value in node_dict.iteritems(): node_type = hou.nodeType(hou.nodeTypeCategories()[value], key) if node_type: instances = list(node_type.instances()) found_nodes.extend(instances) found_parms = [] for node in found_nodes: found_parms.append(node.parm(parm_name)) found_texture_dirs = [] for parm in found_parms: parm_value = parm.eval() if parm_value != "": dir_path = os.path.dirname(os.path.abspath(parm_value)) found_texture_dirs.append(dir_path) if debug: print("{} : {}".format(parm, dir_path)) found_texture_dirs = list(set(found_texture_dirs)) try: import batch_convert batch_convert.runGui( path=batch_convert.paths_separator.join(found_texture_dirs)) except ImportError: log.error("batch_convert module could not be imported")
def removeCategoryEmbeded(nodeTypeCategory=hou.nodeTypeCategories()['Sop'], displayConfirmation=False): if displayConfirmation: fee_Utils.displayConfirmation() dictNodeTypes = nodeTypeCategory.nodeTypes() for nodeTypeDictsKey in dictNodeTypes: nodeType = dictNodeTypes[nodeTypeDictsKey] defi = nodeType.definition() if not defi: continue if defi.libraryFilePath() == 'Embedded': defi.destroy()
def _get_hdadef(table, scopeop, ns, name, version): import hou # HOM doesn't like unicode :( scopeop = str(scopeop) if scopeop else None ns = str(ns) if ns else None name = str(name) version = str(version) if version else '' fullname = hou.hda.fullNodeTypeNameFromComponents( scopeop, ns, name, version ) type_cat = hou.nodeTypeCategories()[table] nodetype = hou.nodeType(type_cat, str(fullname)) if nodetype: return nodetype.definition()
def find_definition(cls): """Find the houdini definition for a plugin. Look at all node types that have instances in the scene and check the name of the otl against the name of this plugin, defined in the derived class. """ otl = "/%s.otl" % cls.plugin_name for category in hou.nodeTypeCategories().values(): for node_type in category.nodeTypes().values(): if node_type.instances(): definition = node_type.definition() if definition: path = definition.libraryFilePath() if path.endswith(otl): return definition.libraryFilePath() return None
def update_all_node_login(node_type): """Updates login data in all instances of the type. Args: node_type: hou.NodeType, Type of the nodes to be updated """ zync_node_types = dict(zync_render='Driver', zync_sim='Dop', zync_sim_sop='Sop') for zync_node_name in zync_node_types.keys(): category_name = zync_node_types[zync_node_name] category = hou.nodeTypeCategories()[category_name] node_type = hou.nodeType(category, zync_node_name) if node_type: for node in node_type.instances(): update_node_login(node)
def get_plugin_definitions(): """Get third party digital assets in use. Uses node_type.instances() to check that node is used in the scene, and path.startswith(os.environ["HFS"]) to filter out stuff that comes with Houdini. The return value is a list of houdini definitions. """ result = [] for category in hou.nodeTypeCategories().values(): for node_type in category.nodeTypes().values(): if node_type.instances(): definition = node_type.definition() if definition: path = definition.libraryFilePath() if path and not path.startswith(os.environ["HFS"]): result.append(definition) return result
def update_all_node_login(node_type): """Updates login data in all instances of the type. Args: node_type: hou.NodeType, Type of the nodes to be updated """ zync_node_types = dict( zync_render='Driver', zync_sim='Dop', zync_sim_sop='Sop' ) for zync_node_name in zync_node_types.keys(): category_name = zync_node_types[zync_node_name] category = hou.nodeTypeCategories()[category_name] node_type = hou.nodeType(category, zync_node_name) if node_type: for node in node_type.instances(): update_node_login(node)
def getAllToolSubmenus(node_type_category_name='Sop'): ''' hou.nodeTypeCategories().keys() ['Shop', 'Cop2', 'CopNet', 'ChopNet', 'Object', 'Driver', 'Chop', 'Sop', 'Manager', 'Vop', 'Director', 'Dop', 'VopNet'] ''' tool_submenus = [] for category in hou.nodeTypeCategories().values(): if category.name() == node_type_category_name: for node_type in category.nodeTypes().values(): for definition in node_type.allInstalledDefinitions(): submenus = getToolSubmenu(definition) if submenus is not None: for submenu in submenus: if submenu not in tool_submenus: tool_submenus.append(submenu) tool_submenus.sort() return tool_submenus
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()
def main(): node_data = {} categories = hou.nodeTypeCategories() for category_name, category in categories.items(): category_data = [] nodes = category.nodeTypes() for node_name, node_type in nodes.items(): node_info = {} node_info['node_name'] = node_name node_info['node_label'] = node_type.description() all_parms = get_all_parm_templates([], node_type) node_info['parms'] = [parm.name() for parm in all_parms] category_data.append(node_info) node_data[category_name] = category_data print(node_data) return node_data
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()
def compare(old_node_data): new_node_data = {} new_parm_node_data = {} categories = hou.nodeTypeCategories() for category, type_category in categories.items(): new_nodes = [] new_parm_nodes = [] nodes = type_category.nodeTypes() old_nodes = old_node_data.get(category) #カテゴリ自体が存在しない場合の処理 if not old_nodes: for node_name, node_type in sorted(nodes.items()): node_label = node_type.description() node_info = get_node_info(node_name, node_label) new_nodes.append(node_info) if new_nodes: new_node_data[category] = new_nodes continue #カテゴリは存在する場合 old_node_names = [node_info['node_name'] for node_info in old_nodes] for node_name, node_type in sorted(nodes.items()): node_label = node_type.description() node_info = get_node_info(node_name, node_label) if node_name in old_node_names: all_parms = get_all_parm_templates([], node_type) index = old_node_names.index(node_name) parm_sets = set(old_nodes[index]['parms']) new_parms = [ parm.name() for parm in all_parms if not parm.name() in parm_sets ] if new_parms: node_info['parms'] = new_parms new_parm_nodes.append(node_info) else: new_nodes.append(node_info) if new_nodes: new_node_data[category] = new_nodes if new_parm_nodes: new_parm_node_data[category] = new_parm_nodes return new_node_data, new_parm_node_data
def path_to_nodetype(path): try: import hou except ImportError: return None info = path_to_components(path) if info is None: return None # In the NodeInfo tuple, version=None means there was no version specified # in the path, whereas version='' means the version is the empty string version = info.version type_cat = hou.nodeTypeCategories()[info.table] typedict = type_cat.nodeTypes() # Get a node type fullname = hou.hda.fullNodeTypeNameFromComponents( info.scopeop, info.namespace, info.corename, version or '' ) nodetype = typedict.get(str(fullname)) # If a path doesn't explicitly specify a version, it means "use the latest # version". Unfortunately finding the latest version is not easy in HOM. if nodetype and version is None: # namespaceOrder() returns a list of node type full names that have the # same core name, but potentially different namespaces. So we have to # look at each one to find the first that matches our criteria for fullname in nodetype.namespaceOrder(): # Break the fullname into components ( this_scope, this_ns, this_corename, this_version ) = hou.hda.componentsFromFullNodeTypeName(fullname) if this_scope == info.scopeop and this_ns == info.namespace: nodetype = typedict.get(fullname) return nodetype
def stringToNodes(s, hou_parent=None, ne=None, ignore_hdas_if_already_defined=None, force_prefer_hdas=None, override_network_position=None, key=None): """ TODO: here to be a docstring :param s: :param hou_parent: :param ne: :param ignore_hdas_if_already_defined: :param force_prefer_hdas: :override_network_position: hou.Vector2 - position in networkview pane :return: """ if ignore_hdas_if_already_defined is None: ignore_hdas_if_already_defined = True if opt is not None: ignore_hdas_if_already_defined = opt.getOption( 'hpaste.ignore_hdas_if_already_defined', ignore_hdas_if_already_defined) if force_prefer_hdas is None: force_prefer_hdas = False if opt is not None: force_prefer_hdas = opt.getOption('hpaste.force_prefer_hdas', force_prefer_hdas) s = str(s) # ununicode. there should not be any unicode in it anyways try: data = json.loads(bz2.decompress(base64.urlsafe_b64decode(s))) except Exception as e: raise RuntimeError( "input data is either corrupted or just not a nodecode: " + str(e.message)) houver1 = hou.applicationVersion() paste_to_position = ne is not None or override_network_position is not None if hou_parent is None: if ne is None: nes = [ x for x in hou.ui.paneTabs() if x.type() == hou.paneTabType.NetworkEditor and getChildContext(x.pwd(), houver1) == data['context'] ] if len(nes) == 0: nes = [ x for x in hou.ui.paneTabs() if x.type() == hou.paneTabType.NetworkEditor ] if len(nes) == 0: raise RuntimeError( "this snippet has '{0}' context. cannot find opened network editor with context '{0}' to paste in" .format(data['context'])) ne = nes[0] hou_parent = ne.pwd() # check version formatVersion = data['version'] if formatVersion > current_format_version[0]: raise RuntimeError( "unsupported version of data format. Try updating hpaste to the latest version" ) if data.get('version.minor', 0) > current_format_version[1]: print( 'HPaste: Warning!! snippet has later format version than hpaste. Consider updating hpaste to the latest version' ) if data.get('signed', False): print( 'HPaste: Warning!! this snippet seem to be signed, but this version of HPaste has no idea how to check signatures! so signature check will be skipped!' ) # check accepted algtypes supportedAlgs = set() if houver1[0] == 15: supportedAlgs.add(0) supportedAlgs.add(1) supportedAlgs.add(2) # WITH BIG WARNING!!! if houver1[0] >= 16: supportedAlgs.add(0) supportedAlgs.add(1) supportedAlgs.add(2) algtype = data['algtype'] if algtype not in supportedAlgs: raise RuntimeError( "algorithm type is not supported by this houdini version, :( ") # check hou version houver2 = data['houver'] if not opt.getOption('hpaste.ignore_houversion_warning', False) and ( houver1[0] != houver2[0] or houver1[1] != houver2[1]): print( "HPaste: WARNING!! nodes were copied from a different houdini version: " + str(houver2)) # check context context = getChildContext(hou_parent, houver1) if context != data['context']: raise InvalidContextError( hou_parent, data['context'] ) # RuntimeError("this snippet has '%s' context" % data['context']) # check sum code = data['code'] if hashlib.sha1(code).hexdigest() != data['chsum']: raise RuntimeError("checksum failed!") if paste_to_position: if houver1[0] >= 16: olditems = hou_parent.allItems() else: olditems = hou_parent.children() deserialize = getDeserializer(enctype=data.get('encryptionType', None), key=key, **(data.get('encryptionData', None) or {})) # do the work for hdaitem in data.get('hdaList', []): # added in version 2.1 hdacode = deserialize(hdaitem['code']) ntype = hdaitem['type'] ncategory = hdaitem['category'] if ignore_hdas_if_already_defined: nodeType = hou.nodeType(hou.nodeTypeCategories()[ncategory], ntype) if nodeType is not None: # well, that's already a bad sign, means it is installed continue fd, temppath = tempfile.mkstemp() try: with open(temppath, 'wb') as f: f.write(hdacode) for hdadef in hou.hda.definitionsInFile(temppath): hdadef.copyToHDAFile('Embedded') # hdadef.save('Embedded') finally: os.close(fd) if force_prefer_hdas: embhdas = [ x for x in hou.hda.definitionsInFile("Embedded") if (x.nodeType().name() == ntype and x.nodeTypeCategory().name() == ncategory) ] if len(embhdas) == 1: embhdas[0].setIsPreferred(True) # now nodes themselves if formatVersion == 1: code = binascii.a2b_qp(code) elif formatVersion >= 2: code = deserialize(code) else: raise RuntimeError( "Very unexpected format version in a very unexpected place!") load_warnings = [] if algtype == 0: # high security risk!! if hou.isUiAvailable(): ok = hou.ui.displayMessage( "WARNING! The algorithm type used by the pasted snipped is legacy and present HIGH SECURITY RISK!\n be sure you TRUST THE SOURCE of the snippet!", ("CANCEL", "ok"), severity=hou.severityType.Warning, close_choice=0, title="SECURITY WARNING") else: ok = 0 print( "for now u cannot paste SECURITY RISK snippets in non-interactive mode" ) if ok != 1: return exec(code, {}, {'hou': hou, 'hou_parent': hou_parent}) elif algtype == 1 or algtype == 2: # get temp file fd, temppath = tempfile.mkstemp() try: with open(temppath, "wb") as f: f.write(code) try: if algtype == 1: hou_parent.loadChildrenFromFile(temppath) if algtype == 2: try: hou_parent.loadItemsFromFile(temppath) except AttributeError: print( "WARNING!!! your hou version does not support algorithm used for copying, TRYING possibly partly backward-INCOMPATIBLE method!" ) print("CHECK SCENE INTEGRITY") hou_parent.loadChildrenFromFile(temppath) except hou.LoadWarning as e: msg = e.instanceMessage() print(msg) # truncate just for display with random number 253 msgtrunc = False if len(msg) > 253: msgtrunc = True msg = msg[:253] + "..." load_warnings.append("There were warnings during load" + ( "(see console for full message)" if msgtrunc else "") + "\n" + msg) finally: os.close(fd) else: raise RuntimeError( "algorithm type is not supported. Try updating hpaste to the latest version" ) if paste_to_position: # now collect pasted nodes if houver1[0] >= 16: newitems = [x for x in hou_parent.allItems() if x not in olditems] else: newitems = [x for x in hou_parent.children() if x not in olditems] if len(newitems) == 0: return # calc center cpos = hou.Vector2() bbmin = hou.Vector2() bbmax = hou.Vector2() cnt = 0 for item in newitems: cnt += 1 pos = item.position() cpos += pos for i in [0, 1]: if pos[i] > bbmax[i] or cnt == 1: bbmax[i] = pos[i] if pos[i] < bbmin[i] or cnt == 1: bbmin[i] = pos[i] cpos = cpos / cnt cpos[1] = bbmax[1] if override_network_position is None: offset = ne.cursorPosition() - cpos else: offset = override_network_position - cpos for item in newitems: if houver1[0] >= 16 and item.parentNetworkBox() in newitems: continue item.move(offset) if len(load_warnings) > 0: raise RuntimeWarning('snippet loaded with following warnings:\n' + '\n'.join(load_warnings))
def get_definition(self, name): for key in hou.nodeTypeCategories().keys(): for k in hou.nodeTypeCategories()[key].nodeTypes().keys(): if name == k: return hou.nodeTypeCategories()[key].nodeTypes()[k].definition()
def __contextAction(self): # self._prevCollection = self._menuToolbar.collectionComboBox.currentText() self.__updateLegendHistory() if self._unsaved: self.__unsavedPrompt( self._menuToolbar.collectionComboBox.currentText()) # if context is changed, update collectionComboBox and ModifierComboBoxes self._currentContext = self._menuToolbar.contextComboBox.currentText() self._collectionsDir = os.path.join(self._rootpath, 'json', self._currentContext) if self._currentContext in [ 'SOP', 'VOP', 'DOP', 'COP', 'CHOP', 'OBJ', 'ROP' ]: # build completer based on current context strlist = [] jsondict = {} # add HDAs to strlist context2 = self._currentContext[0] + self._currentContext[ 1:].lower() all_types = [] categories = hou.nodeTypeCategories() for category in categories.keys(): node_types = categories[category].nodeTypes() for node_type in node_types.keys(): all_types.append(node_types[node_type].nameWithCategory()) # split off version and namespace temp = [] for a in all_types: asplit = a.split('::') if len(asplit) == 1: temp.append(asplit[0]) elif len(asplit) == 2: if len(asplit[0]) > len(asplit[1]): temp.append(asplit[0]) else: temp.append(asplit[1]) elif len(asplit) == 3: temp.append(asplit[1]) all_types = temp alltypeset = set(all_types) contextHDAs = [a.split('/')[-1] for a in alltypeset] strlist = strlist + list(set(contextHDAs) - set(strlist)) # assign completer self.nodeCompleter = QtWidgets.QCompleter(strlist) self.nodeCompleter.popup().setStyleSheet(hou.qt.styleSheet()) self.nodeCompleter.setCompletionMode( QtWidgets.QCompleter.PopupCompletion) # refilter collections by context self._collections = utils.filterCollections(self._collectionsDir, self._currentContext) self.collectionsLabels = [ os.path.splitext(a)[0] for a in self._collections ] self._menuToolbar.collectionComboBox.clear() self._menuToolbar.collectionComboBox.insertItems( 0, self.collectionsLabels) # modifier combo boxes self._menuPrefs = utils.loadMenuPreferences( os.path.join(self._rootpath, 'json', 'menuprefs.json')) try: shiftItem = self._menuPrefs[self._currentContext]['Shift'] self._modifierComboBoxes.shift.comboBox.clear() self._modifierComboBoxes.shift.comboBox.insertItems( 0, self.collectionsLabels) self._modifierComboBoxes.shift.comboBox.setCurrentIndex( self._collections.index(shiftItem)) controlItem = self._menuPrefs[self._currentContext]['Control'] self._modifierComboBoxes.ctrl.comboBox.clear() self._modifierComboBoxes.ctrl.comboBox.insertItems( 0, self.collectionsLabels) self._modifierComboBoxes.ctrl.comboBox.setCurrentIndex( self._collections.index(controlItem)) except ValueError: pass
curve.parm('type').set(1) # empty list of vertices vertices = [] for vertex in path: x = vertex.find('x') y = vertex.find('y') z = vertex.find('z') coord = x.text + ',' + y.text + ',' + z.text vertices.append(coord) coords = ' '.join(vertices) curve.parm('coords').set(coords) sopcategory = hou.nodeTypeCategories()["Sop"] curvetype = hou.nodeType(sopcategory, "curve") i = 0 sweep_expr = str("ch('../ths')*(1-pow($" + "PT/$" + "NPT, ch('../beta'))) + ch('../thf')*pow($" + "PT/$" + "NPT, ch('../beta'))") circle = skeleton_node.createNode('circle') circle.parm('type').set(1) for child in skeleton_node.children(): if child.type() == curvetype: sweep = skeleton_node.createNode('sweep') sweep.setInput(0, circle) sweep.setInput(1, child) sweep.parm('skin').set(1) sweep.parm('xformbyattribs').set(False)
def checkHideFeENode(keepHide=True, detectName=True, detectPath=False): ############### keepHide is False 用于切换hide模式 TEMP_path = hou.getenv('TEMP') isHidingTXT_path = TEMP_path + '/isHidingFeENode.txt' if os.path.exists(isHidingTXT_path): with open(isHidingTXT_path, "r") as isHidingTXT: isHiding = int(isHidingTXT.read(1)) == 1 #print(isHiding) if not keepHide: with open(isHidingTXT_path, "w") as isHidingTXT: isHidingTXT.write('0' if isHiding else '1') else: isHiding = False if not keepHide: #os.makedirs(isHidingTXT_path) with open(isHidingTXT_path, "w") as isHidingTXT: isHidingTXT.write('1') deprecatedNodeList = list(readDeprecatedNode()) deprecatedNodeList.extend(readNeedHideNode()) #print(deprecatedNodeList) nodeTypeCategories = hou.nodeTypeCategories() for nodeTypeCategoriesKey in nodeTypeCategories: # run over all nodeType dictNodeTypes = nodeTypeCategories[nodeTypeCategoriesKey].nodeTypes() for nodeTypeDictsKey in dictNodeTypes: nodeType = dictNodeTypes[nodeTypeDictsKey] nodeTypeName = nodeType.name() if nodeTypeName in deprecatedNodeList: #print(nodeTypeName) nodeType.setHidden(True) continue if keepHide: if isHiding: hideToggle = True else: return else: hideToggle = not isHiding for nodeTypeCategoriesKey in nodeTypeCategories: # run over all nodeType dictNodeTypes = nodeTypeCategories[nodeTypeCategoriesKey].nodeTypes() for nodeTypeDictsKey in dictNodeTypes: nodeType = dictNodeTypes[nodeTypeDictsKey] nodeTypeName = nodeType.name() if nodeTypeName in deprecatedNodeList: nodeType.setHidden(True) continue ''' defi = nodeType.definition() if not defi: continue ''' if not isFeENode( nodeType, detectName=detectName, detectPath=detectPath): continue nodeType.setHidden(hideToggle) """
def get_definition(self, name): for key in hou.nodeTypeCategories().keys(): for k in hou.nodeTypeCategories()[key].nodeTypes().keys(): if name == k: return hou.nodeTypeCategories()[key].nodeTypes( )[k].definition()
def __contextAction(self): self.__updateLegendHistory() if self._unsaved: self.__unsavedPrompt( self._menuToolbar.collectionComboBox.currentText()) # if context is changed, update collectionComboBox and ModifierComboBoxes self._currentContext = self._menuToolbar.contextComboBox.currentText() self._collectionsDir = os.path.join(self._rootpath, 'menus', self._currentContext) if self._currentContext in self._contexts: # build completer based on current context strlist = [] jsondict = {} # add HDAs to strlist context2 = self._currentContext[0] + self._currentContext[ 1:].lower() all_types = [] categories = hou.nodeTypeCategories() for category in categories.keys(): node_types = categories[category].nodeTypes() for node_type in node_types.keys(): all_types.append(node_types[node_type].nameWithCategory()) # split off version and namespace temp = [] for a in all_types: name = max(a.split('::'), key=len) con = name.split('/')[0] if con == context2: temp.append(name.split('/')[-1]) # all_types = temp strlist = list(set(temp)) # assign completer self.nodeCompleter = QtWidgets.QCompleter(strlist) self.nodeCompleter.popup().setStyleSheet(hou.qt.styleSheet()) self.nodeCompleter.setCompletionMode( QtWidgets.QCompleter.PopupCompletion) # refilter collections by context self._collections = utils.filterCollections(self._collectionsDir, self._currentContext) self.collectionsLabels = [ os.path.splitext(a)[0] for a in self._collections ] self._menuToolbar.collectionComboBox.clear() self._menuToolbar.collectionComboBox.insertItems( 0, self.collectionsLabels) # modifier combo boxes self._menuPrefs = utils.loadMenuPreferences( os.path.join(self._rootpath, 'menus', 'menu_prefs.json')) try: self.freezeUpdate = 1 shiftItem = self._menuPrefs[self._currentContext]['Shift'] self._modifierComboBoxes.shift.comboBox.clear() self._modifierComboBoxes.shift.comboBox.insertItems( 0, self.collectionsLabels) self._modifierComboBoxes.shift.comboBox.setCurrentIndex( self._collections.index(shiftItem)) controlItem = self._menuPrefs[self._currentContext]['Control'] self._modifierComboBoxes.ctrl.comboBox.clear() self._modifierComboBoxes.ctrl.comboBox.insertItems( 0, self.collectionsLabels) self._modifierComboBoxes.ctrl.comboBox.setCurrentIndex( self._collections.index(controlItem)) self.freezeUpdate = 0 except ValueError: pass