def deleteBlocker(blockerName='Blocker1', root=NodegraphAPI.GetRootNode()): #get the node to delete blockerToDelete = NodegraphAPI.GetNode(blockerName) #get the position of the node blockerToDeletePos = NodegraphAPI.GetNodePosition(blockerToDelete) #get the connected node ports to the blocker to delete and reconnect those ports together outPort = blockerToDelete.getInputPort('in').getConnectedPort(0) inPort = blockerToDelete.getOutputPort('out').getConnectedPort(0) outPort.connect(inPort) #delete the blocker node blockerToDelete.delete() #delete the param of the blocker paramToDelete = root.getParameter(blockerName) param = root.getParameters() param.deleteChild(paramToDelete) #reposition the node inside the blockerGroup nodeType = 'Group' portToFind = inPort nodeToMove = portToFind.getNode() pos = blockerToDeletePos while (nodeType != 'Dot'): oldPos = NodegraphAPI.GetNodePosition(nodeToMove) nodeType = nodeToMove.getType() NodegraphAPI.SetNodePosition(nodeToMove, pos) if nodeType != 'Dot': portToFind = nodeToMove.getOutputPort('out').getConnectedPort(0) nodeToMove = portToFind.getNode() pos = oldPos
def addLayer(self, aovName, filter='gaussian_filter'): Utils.UndoStack.OpenGroup('Add "%s" AOV' % aovName) try: mergeGrp = SA.getMergeGrp(self) returnPort = mergeGrp.getInputPortByIndex(0) lastPort = returnPort.getConnectedPort(0) lastNode = lastPort.getNode() if '_MERGE_SETUP_' in lastNode.getName(): pos = (0, 0) else: pos = NodegraphAPI.GetNodePosition(lastNode) aovLayer = self.__createAOVgroup(aovName, filter) aovLayer.getInputPortByIndex(0).connect(lastPort) aovLayer.getOutputPortByIndex(0).connect(returnPort) NodegraphAPI.SetNodePosition(aovLayer, (pos[0], pos[1] - 50)) p1 = NodegraphAPI.GetNodePosition(aovLayer) NodegraphAPI.SetNodePosition(mergeGrp, (p1[0], p1[1] - 80)) mergeRod = mergeGrp.getChildByIndex(2) aovList = [] for aov in self.getChildren(): if '_MERGE_SETUP_' not in aov.getName(): name = str(aov.getName()).replace('_AOV_', '') aovList.append(name) aovList.append('primary') names = ",".join(aovList) mergeRod.getParameter( 'args.renderSettings.outputs.outputName.mergeOutputs.enable' ).setValue(1, 0) mergeRod.getParameter( 'args.renderSettings.outputs.outputName.mergeOutputs.value' ).setValue(names, 0) finally: Utils.UndoStack.CloseGroup()
def addSampleBlock(root = NodegraphAPI.GetRootNode(),name = 'sample',task='Object'): children = root.getChildren() nbChildren = root.getNumChildren() dotNode = None for child in children: if child.getType() == 'Dot': dotNode = child dotNodePos = NodegraphAPI.GetNodePosition(dotNode) newSampleNode = createOpScriptSample(root,name,task) paramUI(root,name,task) #reorder the button to be the last param newSampleParam = root.getParameters() paramAddBlocker = newSampleParam.getChild('addSampleNode') numberOfChild = newSampleParam.getNumChildren() -1 newSampleParam.reorderChild(paramAddBlocker,numberOfChild) if nbChildren == 1: sendGroup = root.getSendPort('in') newSampleNode.getInputPort('i0').connect(sendGroup) newSampleNode.getOutputPort('out').connect(dotNode.getInputPort('input')) NodegraphAPI.SetNodePosition(dotNode,(dotNodePos[0],dotNodePos[1]-50)) else: inputDotNodeProducer = dotNode.getInputSource('input',NodegraphAPI.GetCurrentGraphState())[0] inputDotNodeProducer.connect(newSampleNode.getInputPort('i0')) newSampleNode.getOutputPort('out').connect(dotNode.getInputPort('input')) NodegraphAPI.SetNodePosition(newSampleNode,dotNodePos) NodegraphAPI.SetNodePosition(dotNode,(dotNodePos[0],dotNodePos[1]-50))
def LayoutInputNodes(node): spacing = (200, 100) pos = NodegraphAPI.GetNodePosition(node) x = pos[0] - (spacing[0] * (node.getNumInputPorts() - 1)) / 2 y = pos[1] + spacing[1] for port in node.getInputPorts(): if port.getNumConnectedPorts(): inputNode = port.getConnectedPort(0).getNode() NodegraphAPI.SetNodePosition(inputNode, (x, y)) x += spacing[0]
def createMasterBlocker(name='BlockerGroup', parent=NodegraphAPI.GetRootNode()): rootNode = parent #create the groupNode groupNode = NodegraphAPI.CreateNode('Group', rootNode) groupNode.setName(name) #add in and out port groupNode.addInputPort('in') groupNode.addOutputPort('out') #add attribute to switch the display of group node to normal node groupNodeAttrDict = {'ns_basicDisplay': 1, 'ns_iconName': ''} groupNode.setAttributes(groupNodeAttrDict) blockerName = 'Blocker1' #create a first blocker blocker = createSingleBlocker(groupNode, 'getParent().getParent().', False) paramui(groupNode, blocker.getName(), True) #reorder the button addBlocker to be the last param blockerParam = groupNode.getParameters() paramAddBlocker = blockerParam.getChild('addBlocker') numberOfChild = blockerParam.getNumChildren() - 1 blockerParam.reorderChild(paramAddBlocker, numberOfChild) #create a dot node dotNode = NodegraphAPI.CreateNode('Dot', groupNode) dotNode.setName('outDot') #connection sendGroup = groupNode.getSendPort('in') returnGroup = groupNode.getReturnPort('out') blocker.getInputPort('in').connect(sendGroup) blocker.getOutputPort('out').connect(dotNode.getInputPort('input')) dotNode.getOutputPort('output').connect(returnGroup) #set position of nodes centralPos = NodegraphAPI.GetNodePosition(blocker) NodegraphAPI.SetNodePosition(dotNode, (centralPos[0], centralPos[1] - 50)) #put the node under the mouse currentSelection = NodegraphAPI.GetAllSelectedNodes() for node in currentSelection: NodegraphAPI.SetNodeSelected(node, False) NodegraphAPI.SetNodeSelected(groupNode, True) # Get list of selected nodes nodeList = NodegraphAPI.GetAllSelectedNodes() # Find Nodegraph tab and float nodes nodegraphTab = UI4.App.Tabs.FindTopTab('Node Graph') if nodegraphTab: nodegraphTab.floatNodes(nodeList)
def setMasterMaterial(self, masterMaterialPath): self.setLookFileMaterialEnabled(False) n = self.getNode() mmOs = SA.GetRefNode(n, 'mmOs') if not mmOs: if not masterMaterialPath: return # TODO: switch this to OpScript and upgrade existing Gaffer nodes mmOs = NodegraphAPI.CreateNode('OpScript', n) mmOs.setName('mmos') SA.AddNodeReferenceParam(n, 'node_mmOs', mmOs) material = SA.GetRefNode(n, 'material') x, y = NodegraphAPI.GetNodePosition(material) NodegraphAPI.SetNodePosition(mmOs, (x - 100, y)) mmOs.getInputPortByIndex(0).connect( material.getInputPortByIndex(0).getConnectedPort(0)) material.getInputPortByIndex(0).connect( mmOs.getOutputPortByIndex(0)) mmOs.getParameter('CEL').setExpression( """str(getParent().pathName) + '/master'""") mmOs.getParameter('script.lua').setValue( Resources.MASTERMATERIAL_OPSCRIPT, 0) NodegraphAPI.UserParameters.CreateString(mmOs, 'mmOs') if not masterMaterialPath: mmOs.setBypassed(True) return gp = self.getGafferPro() mmItem = gp.getScriptItemForPath(masterMaterialPath) mmScriptItemClass = ScriptItems.GetGafferScriptItemClass( 'GafferProMasterMaterialPackage') if not isinstance(mmItem, mmScriptItemClass): raise TypeError("%r doesn't exist as master material" % (masterMaterialPath)) mmOs.getParameter('user.mmOs').setExpression( """getNode(%r).pathName""" % mmItem.getNode().getName()) mmOs.setBypassed(False)
def set_parent(self): selected_nodes = NodegraphAPI.GetAllSelectedNodes() if not selected_nodes: return output_ports = selected_nodes[-1].getOutputPorts() outport = None inputport = None for output_port in output_ports: connected_port = output_port.getConnectedPorts() outport = output_port if not connected_port: continue inputport = connected_port[-1] break if outport: outport.connect(self.getInputPort('input')) dx, dy = 0, 0 if inputport: self.getOutputPort('output').connect(inputport) dx, dy = NodegraphAPI.GetNodePosition(inputport.getNode()) ux, uy = NodegraphAPI.GetNodePosition(selected_nodes[-1]) mx = (ux + dx) / 2 my = (uy + dy) / 2 NodegraphAPI.SetNodePosition(self, [mx, my])
def setup_render_node(node): """ """ module_logger.debug("PassResolve - setup_render_node()") render_node = node.get_existing_render_node() if not render_node: render_node = NodegraphAPI.CreateNode("Render", node.getParent()) render_node.getParameter("passName").setExpression(( """str(getNode("{node_name}").activePassLocation).split("/")[-1]""" .format(node_name=node.getName()))) node.getOutputPortByIndex(0).connect(render_node.getInputPortByIndex(0)) node_pos_x, node_pos_y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(render_node, (node_pos_x, node_pos_y - 150))
def addBlocker(root=NodegraphAPI.GetRootNode()): children = root.getChildren() dotNode = None for child in children: if child.getType() == 'Dot': dotNode = child dotNodePos = NodegraphAPI.GetNodePosition(dotNode) newBlocker = createSingleBlocker(root, 'getParent().getParent().', False) paramui(root, newBlocker.getName(), False, True) #reorder the button to be the last param newBlockerParam = root.getParameters() paramAddBlocker = newBlockerParam.getChild('addBlocker') numberOfChild = newBlockerParam.getNumChildren() - 1 newBlockerParam.reorderChild(paramAddBlocker, numberOfChild) inputDotNodeProducer = dotNode.getInputSource( 'input', NodegraphAPI.GetCurrentGraphState())[0] inputDotNodeProducer.connect(newBlocker.getInputPort('in')) newBlocker.getOutputPort('out').connect(dotNode.getInputPort('input')) NodegraphAPI.SetNodePosition(newBlocker, dotNodePos) NodegraphAPI.SetNodePosition(dotNode, (dotNodePos[0], dotNodePos[1] - 50))
def change_node_layout(node, x_spacing=200, y_spacing=100): """ """ pos_x, pos_y = NodegraphAPI.GetNodePosition(node) # Start far enough to the left to leave room for all the node's inputs new_pos_x = pos_x - (x_spacing * (node.getNumInputPorts() - 1)) / 2 new_pos_y = pos_y + y_spacing for input_port in node.getInputPorts(): if input_port.getNumConnectedPorts(): input_node = input_port.getConnectedPort(0).getNode() # Stop if we hit our own parent - this means the connection leaves # the GroupNode we're in if input_node != node.getParent(): NodegraphAPI.SetNodePosition(input_node, (new_pos_x, new_pos_y)) # Recursively call this function change_node_layout(input_node, x_spacing, y_spacing) new_pos_x += x_spacing
def createSingleBlocker( root=NodegraphAPI.GetRootNode(), celExp='getParent().', topNode=True): #open the file contening the lua file #fileLua = open(__LUA_FILE_PATH,'r') #luaText = fileLua.read() # root node rootNode = root #create the groupNode groupNode = NodegraphAPI.CreateNode('Group', rootNode) groupNode.setName('Blocker1') name = groupNode.getName() #add in and out port groupNodeIn = groupNode.addInputPort('in') groupNodeOut = groupNode.addOutputPort('out') #add attribute to switch the display of group node to normal node groupNodeAttrDict = {'ns_basicDisplay': 1, 'ns_iconName': ''} groupNode.setAttributes(groupNodeAttrDict) #add the disable param disableParam = groupNode.getParameters().createChildNumber('disable', 0) newCelExp = celExp[:celExp.rfind( 'getParent().')] # this is a hack it work but not safe disableParam.setExpression(newCelExp + name + '.disable', True) #create user param on the groupNode if use as a single entity if topNode: paramui(groupNode, name) #create the opNode who create the primitive primitiveOpNode = NodegraphAPI.CreateNode('OpScript', parent=groupNode) primitiveOpNode.setName('primitiveType') primitiveOpNode.getParameter('applyWhere').setValue( 'at specific location', 0) primitiveOpNode.getParameter('location').setExpression( celExp + name + '.path_Name', True) #create parameter primitiveOpNodeParam = primitiveOpNode.getParameters().createChildGroup( 'user') #param for message primitiveOpNodeParamDisplay = primitiveOpNodeParam.createChildNumber( 'message', 1) primitiveOpNodeParamDisplay.setExpression(celExp + name + '.message', True) #param to get the color primitiveOpNodeParamColor = primitiveOpNodeParam.createChildNumberArray( 'color', 3) primitiveOpNodeParamColor.setExpression(celExp + name + '.color', True) #param to get the light primitiveOpNodeParamLight = primitiveOpNodeParam.createChildString( 'light', '') primitiveOpNodeParamLight.setExpression(celExp + name + '.CEL', True) #param to get the shape primitiveOpNodeParamShape = primitiveOpNodeParam.createChildString( 'shape', 'box') primitiveOpNodeParamShape.setExpression(celExp + name + '.blocker_Type', True) #this part is to use if you want the "printed script" in the lua script tab #filePrimitiveStart = luaText.find('--PrimitiveModule') #filePrimitiveEnd = luaText.find('--endPrimitiveModule') #primitiveOpNode.getParameter('script.lua').setValue(luaText[filePrimitiveStart:filePrimitiveEnd],0) #this is using a lua script as reference which mean you need to set the LUA_PATH correctly to point at the script(i.eos.environ['LUA_PATH'] = "/homes/duda/.katana/LuaScript/?.lua") primitiveOpNode.getParameter('script.lua').setValue( "local createPrimitive = require 'blocker'\ncreatePrimitive.primitive()", 0) #create the transform Node transformNode = NodegraphAPI.CreateNode('Transform3D', parent=groupNode) transformNode.setName('Transform_Blocker') #set the path expression transformNode.getParameter('path').setExpression( celExp + name + '.path_Name', True) #set the interactive to Yes transformNode.getParameter('makeInteractive').setValue('Yes', 0) #create the opScriptNode for the primitive and set it's lua text to get the transform matrix opscriptPrimNode = NodegraphAPI.CreateNode('OpScript', parent=groupNode) opscriptPrimNode.setName('MatrixPrim') opscriptPrimNode.getParameter('CEL').setExpression( celExp + name + '.path_Name', True) #this part is to use if you want the "printed script" in the lua script tab #fileMatrixTextStart = luaText.find('--MatrixModule') #fileMatrixTextEnd = luaText.find('--endMatrixModule') #opscriptPrimNode.getParameter('script.lua').setValue(luaText[fileMatrixTextStart:fileMatrixTextEnd],0) #this is using a lua script as reference which mean you need to set the LUA_PATH correctly to point at the script(i.eos.environ['LUA_PATH'] = "/homes/duda/.katana/LuaScript/?.lua") opscriptPrimNode.getParameter('script.lua').setValue( "local createMatrix = require 'blocker'\ncreateMatrix.getMatrix()", 0) #create the opscript for the light opscriptLightNode = NodegraphAPI.CreateNode('OpScript', groupNode) opscriptLightNode.getParameter('CEL').setExpression( celExp + name + ".CEL", True) opscriptLightNode.setName('MatrixLight') opscriptLightUserParam = opscriptLightNode.getParameters( ).createChildGroup('user') opscriptLightUserParamBlocker = opscriptLightUserParam.createChildString( 'blocker', 'blk01') opscriptLightUserParamBlocker.setExpression( celExp + name + '.blocker_Number', True) opscriptLightUserParamPrim = opscriptLightUserParam.createChildString( 'primitive', '') opscriptLightUserParamPrim.setExpression(celExp + name + '.path_Name', True) listParam = ['density', 'roundness', 'width_edge', 'height_edge', 'ramp'] for param in listParam: paramCreated = opscriptLightUserParam.createChildNumber(param, 0.0) paramCreated.setExpression(celExp + name + '.' + param, True) opscriptLightUserParamShape = opscriptLightUserParam.createChildString( 'geometry_type', 'box') opscriptLightUserParamShape.setExpression(celExp + name + '.blocker_Type', True) opscriptLightUserParamAxis = opscriptLightUserParam.createChildString( 'axis', 'x') opscriptLightUserParamAxis.setExpression(celExp + name + '.axis', True) opscriptLightUserParamFileIn = opscriptLightUserParam.createChildString( 'fileIn', '') opscriptLightUserParamFileIn.setExpression(celExp + name + '.fileIn', True) opscriptLightUserParamUseProj = opscriptLightUserParam.createChildNumber( 'use_projection', 0) opscriptLightUserParamUseProj.setExpression( celExp + name + '.use_projection', True) opscriptLightUserParamFileType = opscriptLightUserParam.createChildNumber( 'file_type', 0) opscriptLightUserParamFileType.setExpression(celExp + name + '.file_type', True) #noise user param dictParamNoise = { 'noise_octaves': 'number', 'noise_distortion': 'number', 'noise_lacunarity': 'number', 'noise_amplitude': 'number', 'noise_scale': 'array', 'noise_offset': 'array', 'noise_coord_space': 'string' } for param in dictParamNoise.keys(): paramToCreate = None if dictParamNoise[param] == 'number': paramToCreate = opscriptLightUserParam.createChildNumber( param, 0.0) elif dictParamNoise[param] == 'array': paramToCreate = opscriptLightUserParam.createChildNumberArray( param, 3) else: paramToCreate = opscriptLightUserParam.createChildString(param, '') paramToCreate.setExpression(celExp + name + '.noise.' + param, True) #this part is to use if you want the "printed script" in the lua script tab #fileLightStart = luaText.find('--MatrixLight') #fileLightEnd = luaText.find('--endMatrixLight') #opscriptLightNode.getParameter('script.lua').setValue(luaText[fileLightStart:fileLightEnd],0) #this is using a lua script as reference which mean you need to set the LUA_PATH correctly to point at the script(i.eos.environ['LUA_PATH'] = "/homes/duda/.katana/LuaScript/?.lua") opscriptLightNode.getParameter('script.lua').setValue( "local paramLight = require 'blocker'\nparamLight.applyBlockerParam()", 0) #create the mergeNode mergeNode = NodegraphAPI.CreateNode('Merge', groupNode) mergeNode.setName('MergePrim') mergeNode.addInputPort('i0') mergeNode.addInputPort('i1') #connection sendGroup = groupNode.getSendPort('in') returnGroup = groupNode.getReturnPort('out') mergeNode.getInputPort('i0').connect(sendGroup) primitiveOpNode.getOutputPort('out').connect( transformNode.getInputPort('in')) transformNode.getOutputPort('out').connect(mergeNode.getInputPort('i1')) mergeNode.getOutputPort('out').connect(opscriptPrimNode.getInputPort('i0')) opscriptPrimNode.getOutputPort('out').connect( opscriptLightNode.getInputPort('i0')) opscriptLightNode.getOutputPort('out').connect(returnGroup) #placement of Nodes centralPos = NodegraphAPI.GetNodePosition(mergeNode) NodegraphAPI.SetNodePosition(primitiveOpNode, (centralPos[0] + 100, centralPos[1] + 200)) NodegraphAPI.SetNodePosition(transformNode, (centralPos[0] + 100, centralPos[1] + 100)) NodegraphAPI.SetNodePosition(opscriptPrimNode, (centralPos[0], centralPos[1] - 100)) NodegraphAPI.SetNodePosition(opscriptLightNode, (centralPos[0], centralPos[1] - 200)) #close the lua file #fileLua.close() #put the node under the mouse if single node if topNode: currentSelection = NodegraphAPI.GetAllSelectedNodes() for node in currentSelection: NodegraphAPI.SetNodeSelected(node, False) NodegraphAPI.SetNodeSelected(groupNode, True) # Get list of selected nodes nodeList = NodegraphAPI.GetAllSelectedNodes() # Find Nodegraph tab and float nodes nodegraphTab = UI4.App.Tabs.FindTopTab('Node Graph') if nodegraphTab: nodegraphTab.floatNodes(nodeList) return groupNode
def createKatanaNodes(fileOut = '/tmp/fileDispFromLua.txt'): # check if there is a node ('Attribute_Disp') existing if yes delete it # existingNode = NodegraphAPI.GetNode('Attribute_Disp') # if existingNode : # inputNodePort = existingNode.getInputPortByIndex(0) # outputNodePort = existingNode.getOutputPortByIndex(0) # inputNodePort.connect(outputNodePort) # existingNode.delete() inputFile = open(fileOut,'a') node = NodegraphAPI.GetAllSelectedNodes()[0] # select the node nodePos = NodegraphAPI.GetNodePosition(node) # get the position of node nodeOutPort = node.getOutputPortByIndex(0) # get the output port nextPort = nodeOutPort.getConnectedPorts()[0] # get the first connected port from the previous node # create the opscript node root = NodegraphAPI.GetRootNode() opscriptFindDisp = NodegraphAPI.CreateNode('OpScript',root) opscriptFindDisp.setName('findDisp') opscriptFindDisp.getParameter('CEL').setValue('/root/world//*{hasattr("materialOverride.parameters.dsp_map")}',0) opscriptFindDispUserParam = opscriptFindDisp.getParameters().createChildGroup('user') opscriptFindDispUserParamFileOut = opscriptFindDispUserParam.createChildString('fileOut',fileOut) opscriptFindDisp.getParameter('script.lua').setValue("local getdispMap = require 'dispFunc'\ngetdispMap.getDispMap()",0) opscriptFindDispInPort = opscriptFindDisp.getInputPort('i0') opscriptFindDispOutPort = opscriptFindDisp.getOutputPort('out') nodeOutPort.connect(opscriptFindDispInPort) opscriptFindDispOutPort.connect(nextPort) NodegraphAPI.SetNodePosition(opscriptFindDisp, (nodePos[0]+50,nodePos[1]-50)) opscriptFindDispPos = NodegraphAPI.GetNodePosition(opscriptFindDisp) # set the view and the edit on the opscript node NodegraphAPI.SetNodeViewed(opscriptFindDisp, True, exclusive=True) NodegraphAPI.SetNodeEdited(opscriptFindDisp, True, exclusive=True) # dummy functions to run the opscript and create the file sg = ScenegraphManager.getActiveScenegraph() node = NodegraphAPI.GetNode( 'root' ) time = NodegraphAPI.GetCurrentTime() producer = Nodes3DAPI.GetGeometryProducer( node, time) prod = producer.getProducerByPath('/root') WalkBoundAttrLocations(prod) # extract the dip for each map assetWithDisp = findDispHeight(fileOut) # create a stack of AttributeSet to set the disp if there is element in the dict if len(assetWithDisp.keys()): stack = NodegraphAPI.CreateNode("GroupStack", NodegraphAPI.GetRootNode()) stack.setName('Attribute_Disp') stack.setChildNodeType("AttributeSet") listWord = ['/location/','/prop/','/location/','/character/'] for key in assetWithDisp.keys(): path = '' attributSet = stack.buildChildNode() attributSet.getParameter('mode').setValue('CEL',0) attrPath = attributSet.getParameter('celSelection') attributSet.getParameter('attributeType').setValue('float',0) # replace the word from listWord by the wildcard '/*' so to work in lighting scene for word in listWord: if key.find(word) > 1: path = key.replace(word,'//*/') attrPath.setValue(path,0) break else: attrPath.setValue(key,0) attributSet.setName(key[key.rfind('/')+1:]) # set name to the _hi attrValue = attributSet.getParameter('numberValue.i0') attrValue.setValue(assetWithDisp[key],0) attrName = attributSet.getParameter('attributeName') attrName.setValue('arnoldStatements.disp_padding',0) NodegraphAPI.SetNodePosition(stack,opscriptFindDispPos) stackInPort = stack.getInputPort('in') stackOutPort = stack.getOutputPort('out') nodeOutPort.connect(stackInPort) stackOutPort.connect(nextPort) NodegraphAPI.SetNodeViewed(stack, True, exclusive=True) NodegraphAPI.SetNodeEdited(stack, True, exclusive=True) else: # reconnect the nodes nodeOutPort.connect(nextPort) NodegraphAPI.SetNodeViewed(node, True, exclusive=True) NodegraphAPI.SetNodeEdited(node, True, exclusive=True) # delete the opscript and the file opscriptFindDisp.delete() os.remove(fileOut) print 'finished'
def ActionCallback(value): """ Callback for the layered menu, which creates a ShadingNode node and sets its B{nodeType} parameter to the given C{value}, which is the name of a shader as set for the menu entry in L{PopulateCallback()}. @type value: C{str} @rtype: C{object} @param value: An arbitrary object that the menu entry that was chosen represents. In our case here, this is the name of a dl shader as passed to the L{LayeredMenuAPI.LayeredMenu.addEntry()} function in L{PopulateCallback()}. @return: An arbitrary object. In our case here, we return the created ShadingNode node, which is then placed in the B{Node Graph} tab because it is a L{NodegraphAPI.Node} instance. """ # Use the entered Group node of the largest Node Graph tab as the parent # node for the new nodes import UI4 nodeGraphTab = UI4.App.Tabs.FindTopTab('Node Graph') parentNode = nodeGraphTab.getEnteredGroupNode() nodes = [] def CreateArnoldShadingNode(nodeType, parentNode): """ Helper function to create a DlShadingNode under the given parent node with its nodeType parameter set to the given node type name, and its name set to the given node type name, possibly followed by a numeric index to make the name unique in the node graph document. """ result = NodegraphAPI.CreateNode('ArnoldShadingNode', parentNode) result.getParameter('nodeType').setValue(nodeType, 0) result.setName(nodeType) result.getParameter('name').setValue(result.getName(), 0) return result def CreatePrmanShadingNode(nodeType, parentNode): """ Helper function to create a DlShadingNode under the given parent node with its nodeType parameter set to the given node type name, and its name set to the given node type name, possibly followed by a numeric index to make the name unique in the node graph document. """ result = NodegraphAPI.CreateNode('PrmanShadingNode', parentNode) result.getParameter('nodeType').setValue(nodeType, 0) result.setName(nodeType) result.getParameter('name').setValue(result.getName(), 0) return result def CreateDlShadingNode(nodeType, parentNode): """ Helper function to create a DlShadingNode under the given parent node with its nodeType parameter set to the given node type name, and its name set to the given node type name, possibly followed by a numeric index to make the name unique in the node graph document. """ result = NodegraphAPI.CreateNode('DlShadingNode', parentNode) result.getParameter('nodeType').setValue(nodeType, 0) result.setName(nodeType) result.getParameter('name').setValue(result.getName(), 0) return result renderer = RenderingAPI.RenderPlugins.GetDefaultRendererPluginName() if renderer == 'dl': shadingNodeType = 'DlShadingNode' # Create a shading node with its name and node type parameters set to the # chosen shader type name as given in `value` node = CreateDlShadingNode(value, parentNode) # Ensure that the input and output parameters are shown when the user opens # the input or output parameter popup by clicking the triangle on the left # or right side of the shading node node.checkDynamicParameters() # Define a list to collect all nodes created in this function, starting # with the main shading node we created above nodes = [] nodes.append(node) # Check if the chosen type of shading node requires additional nodes in # order to be useful # First case A: surface shader connected to NetworkMaterial if value == 'anisotropic' or value == 'blinn' or value == 'lambert' or value == 'dl3DelightMaterial' or value == 'dlGlass' or value == 'dlMetal' or value == 'dlSkin' or value == 'dlHairAndFur' or value == 'surfaceShader': # Create a NetworkMaterial node networkMaterialNode = NodegraphAPI.CreateNode( 'NetworkMaterial', parentNode) # Make sure to call RendererInfo::fillRendererShaderTypeTags networkMaterialNode.addShaderInputPort('dl', 'Surface') nodes.append(networkMaterialNode) # Connect the outColor output of the value node to the # input port dlSurface of the networkMaterialNode node.getOutputPort('outColor').connect( networkMaterialNode.getInputPort('dlSurface')) # Move the networkMaterialNode node to the right of the shading node x, y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(networkMaterialNode, (x + 250, y)) # First case B: volume shader connected to NetworkMaterial elif value == 'dlAtmosphere': # Create a NetworkMaterial node networkMaterialNode = NodegraphAPI.CreateNode( 'NetworkMaterial', parentNode) # Make sure to call RendererInfo::fillRendererShaderTypeTags networkMaterialNode.addShaderInputPort('dl', 'Volume') nodes.append(networkMaterialNode) # Connect the outColor output of the value node to the # input port dlVolume of the networkMaterialNode node.getOutputPort('outColor').connect( networkMaterialNode.getInputPort('dlVolume')) # Move the networkMaterialNode node to the right of the shading node x, y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(networkMaterialNode, (x + 250, y)) # Second case: displacement shader connected to NetworkMaterial elif value == 'displacementShader': # Create a NetworkMaterial node networkMaterialNode = NodegraphAPI.CreateNode( 'NetworkMaterial', parentNode) # Make sure to call RendererInfo::fillRendererShaderTypeTags networkMaterialNode.addShaderInputPort('dl', 'Displacement') nodes.append(networkMaterialNode) # Connect the outDisplacement output of the value node to the # input port dlDisplacement of the networkMaterialNode node.getOutputPort('outDisplacement').connect( networkMaterialNode.getInputPort('dlDisplacement')) # Move the networkMaterialNode node to the right of the shading node x, y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(networkMaterialNode, (x + 250, y)) # Third case: 2D texture shader connected to place2dTexture with a single # connection elif value == 'bulge' or value == 'checker' or value == 'cloth' or value == 'fractal' or value == 'grid' or value == 'noise' or value == 'ocean' or value == 'ramp' or value == 'stencil': # Create a place2dTexture shading node place2dTextureNode = CreateDlShadingNode('place2dTexture', parentNode) nodes.append(place2dTextureNode) # Connect the UV Coordinates output of the place2dTexture node to the # input of the same name on the respective main shading node place2dTextureNode.checkDynamicParameters() place2dTextureNode.getOutputPort('outUV').connect( node.getInputPort('uvCoord')) # Move the place2dTexture node to the left of the main shading node x, y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(place2dTextureNode, (x - 250, y)) # Fourth case: 2D texture shader connected to place2dTexture with a lot # of connections (if file and psdFileTex had the correct input ports) elif value == 'file' or value == 'psdFileTex': # Create a place2dTexture shading node place2dTextureNode = CreateDlShadingNode('place2dTexture', parentNode) nodes.append(place2dTextureNode) # Connect the UV Coordinates output of the place2dTexture node to the # input of the same name on the respective main shading node place2dTextureNode.checkDynamicParameters() place2dTextureNode.getOutputPort('outUV').connect( node.getInputPort('uvCoord')) # Move the place2dTexture node to the left of the main shading node x, y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(place2dTextureNode, (x - 250, y)) # Fifth case: 3D texture shader connected to locationMatrix with single # connection elif value == 'brownian' or value == 'cloud' or value == 'granite' or value == 'leather' or value == 'marble' or value == 'rock' or value == 'snow' or value == 'solidFractal' or value == 'stucco' or value == 'volumeNoise' or value == 'wood': # Create a locationMatrix shading node locationMatrix = CreateDlShadingNode('locationMatrix', parentNode) nodes.append(locationMatrix) # Connect the output world inverse matrix of the locationMatrix node to # the placement matrix input on the respective main shading node locationMatrix.checkDynamicParameters() locationMatrix.getOutputPort('o_worldInverseMatrix').connect( node.getInputPort('placementMatrix')) # Move the locationMatrix node to the left of the main shading node x, y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(locationMatrix, (x - 250, y)) elif renderer == 'arnold': shadingNodeType = 'ArnoldShadingNode' closure_list = [ 'standard_surface', 'standard_hair', 'standard_volume', 'utility' ] light_list = [ 'cylinder_light', 'disk_light', 'distant_light', 'mesh_light', 'photometric_light', 'point_light', 'quad_light', 'skydome_light', 'spot_light' ] operater_list = ['materialx'] # Create a shading node with its name and node type parameters set to the # chosen shader type name as given in `value` node = CreateArnoldShadingNode(value, parentNode) # Ensure that the input and output parameters are shown when the user opens # the input or output parameter popup by clicking the triangle on the left # or right side of the shading node node.checkDynamicParameters() # Define a list to collect all nodes created in this function, starting # with the main shading node we created above nodes.append(node) # surface shader connected to NetworkMaterial if value in closure_list: # Create a NetworkMaterial node networkMaterialNode = NodegraphAPI.CreateNode( 'NetworkMaterial', parentNode) # Make sure to call RendererInfo::fillRendererShaderTypeTags networkMaterialNode.addShaderInputPort('arnold', 'surface') nodes.append(networkMaterialNode) # Connect the outColor output of the value node to the # input port dlSurface of the networkMaterialNode node.getOutputPort('out').connect( networkMaterialNode.getInputPort('arnoldSurface')) # Move the networkMaterialNode node to the right of the shading node x, y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(networkMaterialNode, (x + 250, y)) # light shader connected to NetworkMaterial elif value in light_list: networkMaterialNode = NodegraphAPI.CreateNode( 'NetworkMaterial', parentNode) networkMaterialNode.addShaderInputPort('arnold', 'light') nodes.append(networkMaterialNode) node.getOutputPort('out').connect( networkMaterialNode.getInputPort('arnoldLight')) x, y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(networkMaterialNode, (x + 250, y)) # operater shader connected to NetworkMaterial elif value in operater_list: networkMaterialNode = NodegraphAPI.CreateNode( 'NetworkMaterial', parentNode) networkMaterialNode.addShaderInputPort('arnold', 'operater') nodes.append(networkMaterialNode) node.getOutputPort('out').connect( networkMaterialNode.getInputPort('arnoldOperater')) x, y = NodegraphAPI.GetNodePosition(node) NodegraphAPI.SetNodePosition(networkMaterialNode, (x + 250, y)) elif renderer == 'prman': shadingNodeType = 'PrmanShadingNode' # Create the node, set its shader, and set the name with the shader name node = CreatePrmanShadingNode(value, parentNode) node.checkDynamicParameters() nodes.append(node) elif renderer == 'vray': shadingNodeType = 'VrayShadingNode' elif renderer == 'Redshift': shadingNodeType = 'RedshiftShadingNode' else: node = NodegraphAPI.CreateNode("NetworkMaterial") # Check if more than one node has been created, and if so, make them move # along with the pointer in the Node Graph tab # TODO: Once it's possible to return a list of nodes by an action callback # of a layered menu (instead of a single node only), we can change # this function here to simply return the list of `nodes` we built if len(nodes) > 1: nodeGraphTab.floatNodes(nodes) # Return nothing as we're done here return None else: # Return the single node that was created, which is then made to move # along with the pointer in the Node Graph tab by the code that calls # this action callback return node
selectedGroups = ScenegraphManager.getActiveScenegraph().getSelectedLocations() #Get seleted node try: baseNode = NodegraphAPI.GetNode( NodegraphAPI.GetAllSelectedNodes()[0].getName()) except: sys.exit("Select a node on the nodegraph") for i in selectedGroups: y = 50 #inital node position on nodegraph try: previousNode = NodegraphAPI.GetNode( NodegraphAPI.GetAllSelectedNodes()[0].getName()) except IndexError: break previousNodePosition = NodegraphAPI.GetNodePosition(previousNode) xpos = previousNodePosition[0] ypos = previousNodePosition[1] - y t3d = NodegraphAPI.CreateNode("Transform3D", NodegraphAPI.GetRootNode()) t3d.getParameter("path").setValue(i, 0) t3d.getParameter("makeInteractive").setValue("Yes", 0) NodegraphAPI.SetNodePosition(t3d, [xpos, ypos]) #ports change names so trying more than one. try: previousNodePort = previousNode.getOutputPort('out') t3d.getInputPort('in').connect(previousNodePort) except: previousNodePort = previousNode.getOutputPort('default') t3d.getInputPort('in').connect(previousNodePort) NodegraphAPI.SetAllSelectedNodes('') NodegraphAPI.SetNodeSelected(t3d, True)