Create Node
# The following is a scripting example of how to create shader nodes.
import ufe
import lookdevx as lx
if not shadingContainer:
raise Exception('This example requires a shading container i.e., a MaterialX document or a USD '
'material. Check the other examples to see how to create one.')
# Shading nodes are created from node definitions. Since both MaterialX and USD use the same nodes
# from the MaterialX standard library, UFE also has to know the runtime ID of the UFE runtime to
# differentiate between MaterialX and USD.
# The UFE runtime ID can be queried on each scene item or path object.
runTimeId = shadingContainer.runTimeId()
# Each runtime ID also has an associated name.
runTimeName = ufe.RunTimeMgr.instance().getName(runTimeId)
print(f'Running example to create nodes in the {runTimeName} runtime (UFE runtime ID: {runTimeId}).')
# To create a node, first create a `ufe.NodeDef` object. It takes the UFE runtime ID and the name
# of the MaterialX node definition.
nodeDef = ufe.NodeDef.definition(runTimeId, 'ND_standard_surface_surfaceshader')
# Finding the name of the node definition:
# In the UI, the name of a node definition can be found in the Parameter Editor. It's shown as
# "Type:" below the name of the node. It's also possible to toggle showing the node definition names
# above the node in the graph by switching on "Show Node Types" in the display menu or by using the
# hotkey 'T'. The type of nodes can also be fetched programmatically in a script, as shown further
# below.
# Usually, node definition names have the format `ND_<kindOfNode>_<outputType>`. The "ND" prefix
# stands for "node definition". E.g.:
# - ND_add_float
# - ND_add_color3
# - ND_subtract_color4
# - ND_image_color3
# The `ufe.NodeDef` object can now be used to create new nodes of that type. Simply specify the
# parent item and the desired name. Note that if the name is already taken, a number suffix will be
# added or incremented to make the name unique.
node1 = nodeDef.createNode(shadingContainer, ufe.PathComponent('node'))
node2 = nodeDef.createNode(shadingContainer, ufe.PathComponent('node'))
print(f'Created new node "{node1.nodeName()}" as a child of "{shadingContainer.nodeName()}".')
print(f'Created new node "{node2.nodeName()}" as a child of "{shadingContainer.nodeName()}".')
# Create a different node under a different parent.
compound = lx.createCompound(shadingContainer)
node3 = ufe.NodeDef.definition(runTimeId, 'ND_add_float').createNode(compound, ufe.PathComponent('add'))
print(f'Created new node "{node3.nodeName()}" as a child of "{compound.nodeName()}".')
# Get the node definition name of an existing node.
nodeDefHandler = ufe.RunTimeMgr.instance().nodeDefHandler(runTimeId)
nodeDef = nodeDefHandler.definition(node3)
print(f'The node "{node3.nodeName()}" is an instance of the node definition "{nodeDef.type()}".')