Houdini 20.5 Nodes LOP nodes

Python Script

Lets you write Python code in the node to use the USD API to directly manipulate the stage.

On this page
Since 17.0

Overview

For technical or integration tasks that would be difficult to express using LOP nodes, you can use this node to access the full power of the USD API to read and modify the scene graph tree, the power of HOM to access and control the rest of Houdini, as well as the full power of Python and its libraries to access external data and integrate with your pipeline and other systems.

This node is often useful to script custom pipeline-specific tasks.

See Pixar’s Python API tutorials for help with the APIs.

Scripting the stage

  • Call hou.pwd() to get a reference to this node as a hou.Node. You can get either the current stage through this reference (see below). You can also use it to access spare parameters you might add to this node.

  • Call hou.pwd().editableStage() to get an editable pxr.Usd.Stage object. This represents the output of this node, including any changes you make using the API.

    (The USD Edit Target is automatically set to the active layer for you. Do not change the edit target. Doing so will have unpredictable negative consequences.)

  • Call hou.pwd().inputs()[0].stage() to read from an input stage, then stash any evaluated prim patterns or other values, **before** calling hou.pwd().editablestage(). When this happens in the wrong order, Houdini will still usually run the code, but will not be as efficient.

Examples

Add new prims to the stage

stage = hou.pwd().editableStage()
xform = stage.DefinePrim('/shapes', 'Xform')
cube = stage.DefinePrim('/shapes/cube1', 'Cube')

Loop over every prim in the scene graph tree

stage = hou.pwd().editableStage()
for prim in stage.Traverse():
    # Access or edit the prim
    pass

Use USD’s high-level APIs to manipulate complex attributes

from pxr import UsdGeom

stage = hou.pwd().editableStage()
cube = stage.GetPrimAtPath("/shapes/cube1")

# Change attributes directly
cube.GetAttribute("size").Set(1.5)

# APIs can have useful shortcuts
cube_api = UsdGeom.Cube(cube)
color = cube_api.GetDisplayColorAttr()
color.Set([(0, 0, 1.0)])

# Use the XformCommonAPI to manipulate transforms instead of messing
# with matrix attributes directly
UsdGeom.XformCommonAPI(cube).SetTranslate((4, 5, 6))

Loop over all lights, copying their exposure into their intensity and clearing the exposure

from pxr import UsdLux

stage = hou.pwd().editableStage()

# UsdLux has a special API for finding all lights in the scene efficiently
api = UsdLux.ListAPI(stage.GetPseudoRoot())
for lightprim in light api.ComputeLightList():
    exposure_attr = lightprim.GetAttribute("exposure")
    intensity_attr = lightprim.GetAttribute("intensity")

    intensity = intensity_attr.Get()
    exposure = exposure_attr.Get()
    if exposure:
        intensity_attr.Set(intensity * (exposure ** 2))
        exposure_attr.Set(0)

Reduce the intensity of all lights to half their current values, using a hou.LopSelectionRule.

node = hou.pwd()

# First, find all the light prims on our input.
# We must do this before getting our editable stage to
# avoid an expensive recook of the input node.
ls = hou.LopSelectionRule()
ls.setPathPattern('{ usd_istype(0, @primpath, "UsdLuxLight") }')
paths = ls.expandedPaths(node.inputs()[0])

# Now that we have our set of prim path, we can get the
# editable stage and start making changes.
stage = node.editableStage()
for path in paths:
    prim = stage.GetPrimAtPath(path)
    intensity = prim.GetAttribute('intensity')
    intensity.Set(intensity.Get() * 0.5)

Scripting the active layer instead

  • Instead of manipulating the stage using Usd APIs, you can edit the active layer using lower-level Sdf APIs. You cannot do both in the same script.

  • You probably only want to do this if you have a reason to prefer the lower-level APIs. pxr.Usd methods are higher level methods that can be much easier to use. They perform more error checking and data validation. However the pxr.Sdf APIs can be dramatically faster, especially when creating new USD primitives.

  • To get an editable pxr.Sdf.Layer reference to the active layer, call hou.pwd().editableLayer(). If you do this, do not also call hou.pwd().editableStage() in the same script (doing so will just return None).

  • The returned editable layer is not on any USD stage while the python LOP is cooking, so there is no need to use Sdf.ChangeBlock objects to batch change notifications when making edits.

  • After calling editableLayer, you may call hou.pwd().uneditableStage() to get access to a read-only Usd.Stage. This stage will be the output of the node connected to this node’s input. But unlike calling hou.pwd().stage() or hou.pwd().input(0).stage(), this approach will not trigger recursion errors or warnings about getting a read lock for an already locked stage. The returned stage can be used to access information about the current state of the stage to inform the edits being made to the editable layer. Because the editable layer is not composed onto this uneditable stage, changes made to the layer will not affect the content of this stage.

Tips

  • When you are editing code, the node will cook if you click outside the editor, or press Alt + Enter.

  • You can add spare parameters onto the node to give the node a graphical interface. For example, you could add a text box named primpath that takes a primitive path. Then you can access the parameter value in the script:

    node = hou.pwd()
    primpath = node.evalParm("primpath")
    
  • If you make a useful Python Script node you want to share, you can turn a node instance into a LOP digital asset. Right-click the node in the network editor and choose Create digital asset. The script is stored as part of the digital asset, and the node functions the same way, but as an asset that can be shared and versioned.

  • The pop-up menu button to the right of the editor pulls snippets from any PythonScripts.txt files in the Houdini path. You can create a $HOUDINI_USER_PREFS_DIR/PythonScripts.txt file and add snippets to have them appear in this menu. Read $HFS/houdini/PythonScripts.txt to see the required file format.

  • If your script needs to “find all prims that…”, instead of using the USD traversal methods, consider using hou.LopSelectionRule. This object implements Houdini’s USD prim pattern matching. It generates a list of Sdf.Path objects. You can turn an Sdf.Path into a Usd.Prim object using stage.GetPrimAtPath(pathstring). When using this approach you can either evaluate the selection rule on the input node, or directly on the Usd.Stage returned by pwd().editableStage(). If using the input node, evaluate the selection rule before getting this node’s editable stage to avoid an expensive duplication of the input stage.

  • It is almost always a bad idea to call hou.setContextOption() from within the script of a Python LOP. This causes a global context option to be created. Global context options are accessible anywhere in the hip file, which means cooking this LOP and running its script can potentially cause nodes anywhere else in the hip file to become dirty, if they use this context option. Further, the global context option will only be set when the node cooks, but changing the global context option value in the context option editor or using Python code (in a python shell or in another Python LOP) will not dirty this node, and so it will not recook and reset the option value as might be expected. Instead, setting context options locally within a LOP network should be done using the Edit Context Options LOP.

  • You must not edit the root layer of the stage. Although this root layer is accessible through the Python API, the LOP cooking architecture requires that it be free to manage that root layer free from interference from any single LOP node. The most common use case that leads to this mistake is wanting to add a sublayer to the root layer, which can instead be done using the hou.LopNode.addSubLayer method.

Parameters

Python Code

The Python code to run when cooking this node. See the main help above for tips and examples.

Maintain State

When enabled, the underlying Python interpreter will not be cleared between cooks. This may give some performance gains, but can also lead to unexpected behaviour. It is generally recommended to leave this disabled.

LOP nodes

  • Add Variant

    Adds one or more variants to a variant set on a primitive. This node creates the primitive if it doesn’t exist.

  • Additional Render Vars

    Create multiple render vars.

  • Asset Reference

    Reference, Transform, and select variants of a USD Asset.

  • Assign Material

    Assigns a material to one or more USD primitives. You can use also programmatically assign materials using VEX, programmatically override material settings for each assignment, and programmatically assign materials to geometry subsets.

  • Assign Prototypes

    Switch point instances or USD instanceable prims to instance a different prototype.

  • Attribute VOP

    Create/edit USD attribute values using a VOP network.

  • Attribute Wrangle

    Create/edit USD primitive attributes using a VEX snippet.

  • Auto Select LOD

    Automatically selects a level-of-detail variant based on the primitive’s distance from the camera.

  • Background Plate

    Sets up hold-out or matte objects that leave holes in the scene through which the background is visible. These prims still take shadows and contribute to reflections as if they were the background.

  • Bake Skinning

    Bakes animation driven by a UsdSkel into transforms and point positions.

  • Basis Curves

    Creates or edits a basis curves shape primitive.

  • Begin Context Options Block

    This node begins a block of LOP nodes, within which certain context options have certain values.

  • Blend

    Partially applies edits to a layer’s attributes based on a fractional weight.

  • Blend Constraint

    Blends transforms according to a list of weights specified as parameters.

  • Cache

    Caches the results of cooking the network at different times, increasing playback speed.

  • Camera

    Adds a USD camera to the scene.

  • Capsule

    Creates or edits a capsule (tube with hemispherical ends) shape primitive.

  • Collection

    Creates/edits collections using primitive patterns.

  • Component Geometry

    Geometry container or import source, in a network created by the Component Builder tool.

  • Component Geometry Variants

    Sets up geometry variants, in a network created by the Component Builder tool.

  • Component Material

    Assigns materials to geometry in a network created by the Component Builder tool.

  • Component Output

    Assembles the final Component prim, in a network created by the Component Builder tool.

  • Cone

    Creates or edits a cone shape primitive.

  • Configure Layer

    Edits metadata on a layer.

  • Configure Primitives

    Edits various metadata on one or more primitives.

  • Configure Properties

    Configures metadata on properties (relationships and attributes).

  • Configure Stage

    Configures metadata for how to load layers into the stage and asset resolution.

  • Coordinate System

    Define named coordinate systems used in shaders.

  • Copy Property

    Copy properties from one primitive to another, or renames properties on a primitive.

  • Create LOD

    Uses the PolyReduce SOP to automatically generate multiple levels of detail from a high-res model, and stores them as USD variants.

  • Cube

    Creates or edits a cube shape primitive.

  • Cylinder

    Creates or edits a cylinder shape primitive.

  • Distant Light

    Creates or edits a USD Distant Light, representing a far-off light source such as the sun. Adds some useful Karma-specific attributes.

  • Dome Light

    Creates or edits a USD Dome Light prim. A dome light emits light inward, simulating light coming from the sky/environment surrounding the scene.

  • Draw Mode

    Sets draw mode properties on USD model assets.

  • Drop

    Runs a simulation to drop primitives under gravity.

  • Duplicate

    Creates copies of a prim (and its descendants).

  • Edit

    Interactively transforms prims in the viewer. Can use physics collisions to position props realistically.

  • Edit Context Options

  • Edit Material

    Allows you to edit an existing USD material by modifying parameters and shader connections. This can be useful if the existing material is on a non-editable layer.

  • Edit Material Properties

    Lets you build a spare parameter interface that reflects material or shader input attributes to directly edit their values.

  • Edit Properties

    Lets you build a spare parameter interface to directly edit attribute and relationship values.

  • Edit Properties From Node

    Lets you refer to the parameter on another node to directly edit attribute and relationship values.

  • Edit Prototypes

    Modify the prototypes of native or point instances in-place, without disturbing the instancing setup.

  • Edit Target Layer

    Allows you to apply edits directly in a lower layer, instead of overriding prims and attributes in the active layer.

  • Error

    Generates a message, warning, or error, which can show up on a parent asset.

  • Explore Variants

    Visualize, set, or extract variants on primitives.

  • Extract Instances

    Converts (heroes) an instance into a real editable prim.

  • Fetch

    Grabs the output of another LOP, potentially in another LOP network.

  • File Cache

    Caches (writes out once and then reads from) USD layers (possibly animated) to disk.

  • Follow Path Constraint

    Constrains a prim to follow a path curve.

  • For Each

    The end node of a For-Each loop block.

  • Geometry Clip Sequence

  • Geometry Color

    Adds display color and display opacity primvars to geometry.

  • Geometry Sequence

    Imports a sequence of geometry files into LOPs as animated geometry.

  • Geometry Subset VOP

    Creates USD geometry subsets within geometry prims (similar to groups in SOPs) based on evaluating a VEXpression or VOP network.

  • Graft Branches

    Takes prims/branches from the second input and attaches them onto branches of the scene graph tree in the first input.

  • Graft Stages

    Takes scene graph trees from other inputs and attaches them onto branches of the scene graph tree in the first input.

  • HDA Dynamic Payload

    Cooks a OBJ or SOP asset on disk and imports the animated geometry output as a USD payload.

  • Hermite Curves

    Creates or edits a hermite curves shape primitive.

  • Houdini Feather Procedural

    Generates feathers for rendering.

  • Houdini Preview Procedurals

    Invokes Houdini Procedurals while working interactively.

  • Houdini Procedural: Crowd

    Houdini Crowd Procedural for Solaris.

  • Houdini Procedural: Hair

    Houdini Hair Procedural for Solaris.

  • Houdini Procedural: Ocean

    Houdini Ocean Procedural for Solaris.

  • Houdini Procedural: RBD

    Houdini RBD Procedural for Solaris.

  • Inline USD

    Parses usda code representing a layer and adds it to the layer stack.

  • Insertion Point

    Represents a point in the node graph where nodes can be inserted.

  • Instancer

    Instances or copies primitives onto points.

  • Isolate Scene

    Work in masked areas of the stage.

  • Karma

    Renders the USD scene using Houdini’s Karma renderer.

  • Karma Cryptomatte

    Setup Cryptomatte AOVs for Karma.

  • Karma Fog Box

    Creates a constant volume within a box.

  • Karma Physical Sky

    Creates a Karma Sky Dome and Sun Light rig.

  • Karma Render Products

    Create multiple render products sharing common settings.

  • Karma Render Properties

    Configure Render Properties for Karma.

  • Karma Sky Atmosphere

    Creates or edits a Karma Sky Atmosphere.

  • Karma Sky Dome Light

    Creates or edits a Karma Sky Dome Light.

  • Karma Standard Render Vars

    Create standard karma render vars (AOVs/Image Planes).

  • LPE Tag

    Manage Lights' LPE Tags.

  • Labs Karma AOVs for RenderMan Denoiser

    Generates AOVs for the Pixar RenderMan denoiser.

  • Layer Break

    Starts a new active sublayer that subsequent nodes will edit, and indicates all previous layers will be discarded when saving to disk.

  • Layer Replace

    Replaces all uses of a certain layer with a substitute layer from its second input.

  • Layout

    Provides tools for populating a scene with instanced USD assets. You can place individual components, paint/scatter components in different ways using customizable brushes, and edit existing instances.

  • Light

    Creates or edits a USD Light prim. This node also adds some useful Karma-specific attributes.

  • Light Filter Library

    Authors USD light filter primitives from VOP nodes.

  • Light Linker

    Creates USD light link properties based on rules.

  • Light Mixer

    Lets you interactively edit USD properties for multiple lights.

  • Load Layer for Editing

  • Loft Payload Info

    Adds basic information from inside a payload to the primitive that loads the payload.

  • Look At Constraint

    Constrains a prim to always point toward a target.

  • Mask from Bounds

    Sets a primvar based on whether/by how much selected prims are inside a bounding shape.

  • Match Size

    Resizes and recenters the input geometry to match a reference bounding box.

  • Material Library

    Authors USD material primitives from shader VOP nodes.

  • Material Linker

    Creates material assignments based on rules.

  • Material Variation

    Creates attributes/primvars to override material parameters per-prim/instance.

  • Merge LOP

    Merges the layers from incoming stages into a unified layer stack.

  • Merge Point Instancers

    Merges point instancers into a single consolidated point instancer.

  • Mesh

    Creates or edits a mesh shape primitive.

  • Modify Paths

    Modify asset path attribute values.

  • Modify Point Instances

    Modifies point transforms and property values for individual point instances.

  • Motion Blur

    Adds time samples to allow motion blur when rendering.

  • Null

    This node does nothing. It can be useful to insert a Null into a network as a fixed point in the network that you can refer to by name in expressions/scripts.

  • Output

    Represents the output of a subnetwork. Allows you to design a node asset with multiple outputs.

  • Parent Constraint

    Makes a primitive appear to inherit the transform hierarchy of another prim somewhere else in the tree.

  • Points

    Creates or edits a Points shape primitive.

  • Points Constraint

    Position and Orient primitives using point positions from a geometry.

  • Primitive

    Bulk-creates one or more attributes of a certain type.

  • Prune

    Hides or deactivates primitives and point instances.

  • Python Script

    Lets you write Python code in the node to use the USD API to directly manipulate the stage.

  • RBD Destruction

    An example for a fracturing simulation in USD, also useful as a canned effect.

  • Reference

    References the contents of a external USD files and/or layers created by other LOP nodes into a branch of the existing scene graph tree. Can also remove or replace existing references.

  • Render Geometry Settings

    Applies renderer-specific geometry settings to geometry in the scene graph.

  • Render Product

    Creates or edits a UsdRenderProduct prim, which represents an output of a renderer (such as a rendered image file or other file-like artifact produced by a renderer), with attributes configuring how to generate the product.

  • Render Settings

    Creates or edits a UsdRenderSettings prim, which holds the general settings for rendering the scene.

  • Render Var

    Specifies a custom variable computed by the renderer and/or shaders, either a shader output or a light path expression (LPE).

  • Resample Transforms

    Generates interpolated transform time samples from existing time samples on USD prims.

  • Restructure Scene Graph

    This node has various operations for editing prim paths, variant sets, and composition arcs.

  • Retime Instances

    Offsets and/or scales the timing of animation on selected instances.

  • SOP Character Import

    Imports a character or animation from a SOP network into the USD scene graph.

  • SOP Create

    Lets you create geometry in a SOP subnetwork inside this node, so you can create geometry in-place in the LOP network instead of needing a separate SOP network.

  • SOP Crowd Import

    Imports a crowd from a SOP network into the USD scene graph.

  • SOP Import

    Imports geometry from a SOP network into the USD scene graph.

  • SOP Modify

    Converts USD geometry into SOP geometry, runs the SOP subnet inside this node on the geometry, and converts the changes back to USD overrides.

  • Scene Doctor

    Validates primitives on a USD stage.

  • Scene Import

    Imports models, materials, and lights from the Object level into the LOP network.

  • Scope

    Creates a scope primitive. Scope is the simplest form of grouping, and does not have a transform. Scopes can be useful for organizing the scene tree.

  • Set Extents

    Sets the bounding box metadata of selected primitives.

  • Set Variant

    Selects (switches to) one of the variants stored in a variant set on a primitive.

  • Simulation Proxy

    Generates low-poly collison geometry suitable for physical simulation and creates a proxy relationship to the original model.

  • Sphere

    Creates or edits a sphere shape primitive.

  • Split Point Instancers

    Splits a point instancer into two or more instances, which divide up the original instances.

  • Split Primitive

    Splits USD geometry prims into child primitives based on geometry subsets or primvar values.

  • Split Scene

    This node splits a scene graph into two disjoint sets of primitives.

  • Stage Manager

    Provides a convenient interface to reference in many files at once and place them in the scene graph tree.

  • Store Parameter Values

    Lets you store temporary (unsaved) data in the stage.

  • Sublayer

    Imports from USD files or other LOP node chains into as sublayers, or removes/replaces/reorders existing sublayers.

  • Subnet

    Encapsulates a LOP subnetwork, allowing you to organize and hide parts of the network.

  • Surface Constraint

    Constrain a prim to stick to a surface.

  • Switch

    Passes through one of several inputs, based on a parameter choice or expression.

  • TimeShift

    Outputs the stage as it is at a different point in the timeline.

  • Transform

    Edits the transforms of selected USD primitives.

  • Transform UV

    Moves, rotates, and scales texture coordinates on USD primitives.

  • USD ROP

  • USD Render ROP

  • Unassign Material

    Unbinds a material from one or more USD primitives.

  • Value Clip

  • Vary Material Assignment

    Assign different materials across a number of prims to create variation.

  • Volume

    References volume data on disk into a volume prim containing field prims.

  • Xform

    Creates or edits an Xform prim. Xform (and its sub-classes) represents a transform in the scene tree.