Create Compound

# The following is an example on how to create a compound within a shading container.
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.')

# Create and connect some nodes for demonstration purposes.
runTimeId = shadingContainer.runTimeId()
items = []
for _ in range(5):
    items.append(ufe.NodeDef.definition(runTimeId, 'ND_add_float').createNode(shadingContainer, ufe.PathComponent('add')))
for i in range(1, 5):
    srcInfo = ufe.AttributeInfo(items[i - 1].path(), 'outputs:out')
    dstInfo = ufe.AttributeInfo(items[i].path(), 'inputs:in1')
    ufe.RunTimeMgr.instance().connectionHandler(runTimeId).connect(srcInfo, dstInfo)

# Compounds can be created using the LookdevX API. It can be used to create empty compounds or to
# group a set of existing items into a compound.
compound1 = lx.createCompound(shadingContainer,                    # parent item
                              ufe.PathComponent("emptyCompound1"), # name of the compound
                              [],                                  # list of items to group
                              ufe.Vector2f(-1, -1))                # position in the graph
print(f'Created a new empty compound "{compound1.path()}".')

# All arguments except the parent item are optional.
compound2 = lx.createCompound(shadingContainer)
print(f'Created a new empty compound "{compound2.path()}".')

# The arguments can also be reordered.
compound3 = lx.createCompound(shadingContainer,
                              position=ufe.Vector2f(2, 2),
                              items=[items[1], items[2], items[3]],
                              name=ufe.PathComponent("groupExistingNodes"))
print(f'Grouped a set of nodes under "{compound3.path()}".')

# Note that when grouping nodes into a compound, connections to other nodes outside of the compound
# are maintained across the compound boundary.