OpenUSD (Universal Scene Description) Tutorials and Examples

repository·main·Indexed 42 days ago

https://github.com/nvidia-omniverse/usd-tutorials-and-examples

A historical archive of educational materials and Jupyter Notebooks for learning OpenUSD fundamentals. Covers core concepts including stages, prims, attributes, hierarchy traversal, and composition arcs like references and variant sets. Includes practical guides on using the usd-core Python package and APIs such as Usd.Stage, UsdGeom, and Sdf.

Tokens
3.7K
Snippets
14
Records
16
Agent score
52%

What's inside OpenUSD

  1. Run OpenUSD tutorials in Google Colaboratory

    main

    You can run historical OpenUSD Jupyter Notebooks interactively in your browser using Google Colaboratory. This allows you to execute code snippets and run samples without installing OpenUSD locally.

    Available notebooks include:

    • Introduction to OpenUSD
    • Opening USD Stages
    • Prims, Attributes and Metadata
    • Hierarchy and Traversal
  2. How to work with typed Prims (Schemas)

    main

    While Usd.Prim is the base object, you often need to access type-specific properties (like transformations for an Xform). To do this, you can wrap a Usd.Prim in a Schema object using its constructor, or use the type's Define method to get the typed instance immediately.

    Pattern:

    1. prim = stage.DefinePrim(path, 'Xform') $\rightarrow$ returns Usd.Prim.
    2. xform = UsdGeom.Xform(prim) $\rightarrow$ converts Usd.Prim to UsdGeom.Xform.
    3. xform = UsdGeom.Xform.Define(stage, path) $\rightarrow$ returns UsdGeom.Xform directly (Faster/Better).
    # Converting a generic prim to a typed Xform
    prim = stage_ref.DefinePrim('/XformPrim', 'Xform')
    xform = UsdGeom.Xform(prim)
    
    # Direct definition (Preferred)
    xform_faster = UsdGeom.Xform.Define(stage_ref, '/AnotherXformPrim')
  3. Use USD References to compose scenes

    main

    A Reference allows you to compose smaller units of scene description into larger aggregates. You can add a reference to a Prim using GetReferences().AddReference(filePath, primPath). This allows you to pull in content from another USD file and then apply overrides (like changing color or clearing transforms) to that referenced content in the current stage.

    from pxr import Usd, UsdGeom
    
    stage = Usd.Stage.CreateInMemory('ReferenceExample.usda')
    
    # Create a place for the reference to live
    refSphere = stage.OverridePrim('/refSphere')
    
    # Add the reference to an existing file and prim
    refSphere.GetReferences().AddReference('./SampleLayer.usda', '/MySphere')
    
    # Override properties (e.g., clearing the transform order)
    refXform = UsdGeom.Xformable(refSphere)
    refXform.SetXformOpOrder([])
    
    # To see the final composed result, use stage.Flatten()
    print(stage.Flatten().ExportToString())
  4. Implement Variants and VariantSets

    main

    A VariantSet is a composition arc that acts like a 'switchable reference'. It allows a content creator to package discrete alternatives (e.g., different colors, materials, or shapes) that a consumer can switch between non-destructively.

    To use them:

    1. Create a VariantSet on a Prim using GetVariantSets().AddVariantSet(name).
    2. Add individual variants using AddVariant(name).
    3. Use SetVariantSelection(name) to choose the active variant.
    4. Use GetVariantEditContext() as a context manager to define the scene description that belongs to that specific variant.
    from pxr import Usd, UsdGeom
    
    stage = Usd.Stage.CreateInMemory('VariantExample.usda')
    variantSphere = stage.OverridePrim('/variantSphere')
    variantSphere.GetReferences().AddReference('./SampleLayer.usda', '/MySphere')
    
    # Access the prim to add variants
    variantXform = stage.GetPrimAtPath('/variantSphere')
    colorAttr = UsdGeom.Sphere.Get(stage, '/variantSphere/MeshData').GetDisplayColorAttr()
    
    # Add the VariantSet
    colorVariants = variantXform.GetVariantSets().AddVariantSet('ColorsRGB')
    
    # Define variants
    for color_name, color_val in [('red', [(1,0,0)]), ('green', [(0,1,0)]), ('blue', [(0,0,1)])]:
        colorVariants.AddVariant(color_name)
        colorVariants.SetVariantSelection(color_name)
        with colorVariants.GetVariantEditContext():
            colorAttr.Set(color_val)
    
    # Select a specific variant
    colorVariants.SetVariantSelection('green')
  5. Define Prims and manipulate attributes in USD

    main

    You can define geometric primitives (like transforms or spheres) on a stage using schema-specific Define methods. Once defined, you can manipulate them using APIs like UsdGeom.XformCommonAPI for transforms or by accessing specific attributes via GetAttribute() or schema-specific methods like GetDisplayColorAttr().

    from pxr import Usd, UsdGeom
    
    stage = Usd.Stage.CreateInMemory('SampleLayer.usda')
    
    # Create a transform and add a sphere as mesh data
    xformPrim = UsdGeom.Xform.Define(stage, '/MySphere')
    UsdGeom.XformCommonAPI(xformPrim).SetTranslate((7,8,9))
    
    spherePrim = UsdGeom.Sphere.Define(stage, '/MySphere/MeshData')
    
    # Access attributes
    radiusAttr = spherePrim.GetAttribute('radius')
    colorAttr = spherePrim.GetDisplayColorAttr()
    
    # Set values
    radiusAttr.Set(2)
    colorAttr.Set([(0,0,1)])  # Set color to blue
    
    # Export the layer
    stage.GetRootLayer().Export('SampleLayer.usda')
  6. Access and define Prims in a USD Stage

    main

    Prims (Primitive objects) are identified by their path in a stage (e.g., /Prim/ChildPrim).

    • Get a Prim by path: Use stage.GetPrimAtPath(path).
    • Define a generic Prim: Use stage.DefinePrim(path).
    • Define a typed Prim: Use stage.DefinePrim(path, type_name) or the type's specific Define(stage, path) method (which is more efficient as it returns the typed instance directly).
    • Delete a Prim: Use stage.RemovePrim(path). After removal, existing references to that prim become invalid; check prim.IsValid() to verify.
    from pxr import Sdf, Usd, UsdGeom
    
    # Open a stage
    stage_ref = Usd.Stage.Open('sphere_sample.usda')
    
    # Get a prim
    prim = stage_ref.GetPrimAtPath('/sphere')
    
    # Define a generic prim
    new_prim = stage_ref.DefinePrim('/UnTypedPrim')
    
    # Define a typed prim (Xform) using the type's Define method (Recommended)
    xform = UsdGeom.Xform.Define(stage_ref, '/AnotherXformPrim')
    
    # Remove a prim
    if stage_ref.RemovePrim('/UnTypedPrim'):
        print('Removed')
  7. Manage Attributes and their values

    main

    Attributes store data within a Prim. They are often part of a Schema (e.g., Purpose in Xform).

    • Accessing Attributes:
      • Generic: prim.GetAttribute('name') (requires knowing the string name).
      • Schema-based: schema_instance.Get<AttributeName>Attr() (provides IDE completion and type safety).
    • Creating Attributes: Use prim.CreateAttribute(name, type) where type is an Sdf.ValueTypeNames constant.
    • Getting/Setting Values: Use .Get() to retrieve the value and .Set(value) to update it.

    Note: For newly created attributes, .Get() returns None (or an empty value for specific types) until .Set() is called.

    from pxr import Usd, UsdGeom, Sdf
    
    stage = Usd.Stage.CreateInMemory()
    prim = stage.DefinePrim('/MyPrim')
    
    # Create a new attribute with a specific type
    weight_attr = prim.CreateAttribute('weight', Sdf.ValueTypeNames.Float)
    
    # Set and Get values
    weight_attr.Set(42.3)
    print(weight_attr.Get()) # 42.3
    
    # Schema-based access example
    xform = UsdGeom.Xform.Define(stage, '/XformPrim')
    purpose_attr = xform.GetPurposeAttr()
    print(purpose_attr.Get()) # Returns one of [default, render, proxy, guide]
  8. Open or create a USD Stage

    main

    In USD, a Stage is the primary container for a scene. You can load an existing USD file or create a new one using the Usd.Stage class.

    • To load an existing file: Use Usd.Stage.Open(path).
    • To create a new file: Use Usd.Stage.CreateNew(path).
    from pxr import Usd
    
    # Open an existing stage
    stage = Usd.Stage.Open('sphere_sample.usda')
    
    # Create a new stage
    stage = Usd.Stage.CreateNew('a_new_stage.usd')