Skip to content

Instantly share code, notes, and snippets.

@BigRoy
Created December 8, 2023 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BigRoy/ca87239ad0c2a493ec3d795ba1eecb15 to your computer and use it in GitHub Desktop.
Save BigRoy/ca87239ad0c2a493ec3d795ba1eecb15 to your computer and use it in GitHub Desktop.
USD Python API print Sdf.PrimSpec as text without children (e.g. somewhat like Maya LookdevX "Print selected as text")
from pxr import Usd, Sdf
def should_copy_children_fn(
children_field,
src_layer, src_path, field_in_src,
dest_layer, dest_path, field_in_dest
):
"""Filter function for Sdf.CopySpec to exclude children prims"""
if children_field == "primChildren":
# Never copy children
return False
return True
def get_prim_spec_as_text_without_children(spec: Sdf.PrimSpec) -> str:
"""Return Sdf.PrimSpec as text without children"""
tmp = Sdf.Layer.CreateAnonymous()
tmp_path = Sdf.Path(f"/{spec.name}")
Sdf.CopySpec(spec.layer, spec.path, tmp, tmp_path,
# Copy all values
lambda *args: True,
# Do not copy children
should_copy_children_fn
)
tmp_spec = tmp.GetPrimAtPath(tmp_path)
return tmp_spec.GetAsText()
# Example usages
prim: Usd.Prim # use your prim
for spec in prim.GetPrimStack():
print(get_prim_spec_as_text_without_children(spec))
@BigRoy
Copy link
Author

BigRoy commented Dec 8, 2023

Another approach provided by Dhruv Govil:

from pxr import Usd

def print_prim(prim: Usd.Prim):
    """
    Isolates a prim, and prints it out
    Args:
        prim (Usd.Prim)
    """
    assert isinstance(prim, Usd.Prim)
    prim_stage = prim.GetStage()
    prim_stage_id = prim_stage.GetRootLayer().identifier
    stage = Usd.Stage.CreateInMemory()
    target = stage.DefinePrim("/{}".format(prim.GetName()))
    target.GetReferences().AddReference(prim_stage_id, prim.GetPath())
    print(stage.ExportToString()) 

This does include the composed children - but unlike the Sdf.Spec approach in the original snippet this will provide you with a "composed" result instead of the opinion from a single layer.

Another approach could be using something like UsdUtils.StitchLayers to construct one composed stack to then print the Sdf.PrimSpec that will always be single layer opinion at that point, for example like prim duplicating is done here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment