Skip to content

Instantly share code, notes, and snippets.

@BigRoy
Created November 28, 2023 12:15
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/4af0ad42dfdb7bc6f868cd51126274e5 to your computer and use it in GitHub Desktop.
Save BigRoy/4af0ad42dfdb7bc6f868cd51126274e5 to your computer and use it in GitHub Desktop.
USD Python API import layer into an existing layer at given path
from collections.abc import Callable
from pxr import Sdf
def import_layer(
path: str,
target_layer: Sdf.Layer,
target_path: Sdf.Path,
copy_spec_fn: Callable[[Sdf.Layer, Sdf.Path, Sdf.Layer, Sdf.Path], bool] = Sdf.CopySpec
):
"""Merge layer into target layer at path using Sdf.CopySpec.
You can pass in a custom `copy_spec_fn` to allow different copying
behavior where e.g. existing child prims are not removed but merged
into instead.
"""
layer = Sdf.Layer.FindOrOpen(path)
if not target_layer.GetPrimAtPath(target_path):
Sdf.CreatePrimInLayer(target_layer, target_path)
for root_prim in layer.rootPrims:
root_prim_path = Sdf.Path(f"/{root_prim.name}")
target_prim_path = target_path.AppendChild(root_prim.name)
copy_spec_fn(layer, root_prim_path, target_layer, target_prim_path)
# Example usage
target = Sdf.Layer.CreateAnonymous()
path = Sdf.Path("/hello/world")
import_layer(r"C:\Users\User\Desktop\asset.usd", target, path)
@BigRoy
Copy link
Author

BigRoy commented Nov 28, 2023

To perform more like a merge instead of a full "replace" of target prims you might need to specify the custom copy_spec_fn:

import_layer("file.usd", target_layer, Sdf.Path("/preset"), copy_spec_fn=copy_spec_merge)

For example using copy_spec_merge from usd_qtpy

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