Exporting a prim to a new usd file

In python, given a prim in a stage, how can I export that to a new usd file?

That is the kind of question you could ask the new USD-code NIM from NVIDIA.

I just tried it and it seems to spew out something decent.
F

Offhand, I think you can try setting a population mask to only allow your prim, or set all other prims to inactive, and then export the stage.

However, with either approach, I’m not sure if you’re guaranteed that changing the population mask or setting other prims inactive won’t have knock-on effects on the prim you care about. Also, it would require altering the stage first, which may be a no-go if it’s in use by other things.

Alternatively, if the prim is only from a single layer with no opinions you care about composed on top, you could use create a new layer and use SdfCopySpec.

The surest approach might a combo - ie, export the stage first, which will also flatten it, then open your flattened export as an SdfLayer and use SdfCopySpec. That could be a potentially heavy solution for a very large scene that you only want a tiny piece of, though.

I’m curious to know what the NIM came up with… Or if there a better way to go about it, since all of my suggestions have downsides.

LLM results are full of red-herrings - functions and methods that don’t actually exist. There’s one that is close that I’ll share below but it’s a shallow export, doesn’t encompass materials or other relationships.

    export_stage = Usd.Stage.CreateInMemory()

    # Recursively export the prim and its children
    def export_prim_and_children(prim, export_prim):
        #export_materials(prim)
        for attr in prim.GetAttributes():
            if attr.IsAuthored():
                export_attr = export_prim.CreateAttribute(attr.GetName(), attr.GetTypeName())
                export_attr.Set(attr.Get())
        for child in prim.GetAllChildren():
            child_path = child.GetPath()
            child_export_prim = export_stage.DefinePrim(child_path, child.GetTypeName())
            export_prim_and_children(child, child_export_prim)

    export_prim_and_children(prim, export_prim)

    # Export the new stage to a file
    export_stage.GetRootLayer().Export(file_path)

Opening the Stage with a population mask set to the prim and then exporting (which will flatten) is the way I’d suggest, and does not require modifying the existing stage/layers. If you care about other prims “used by” your prim and its descendants (i.e. those to which relationships or connections target), you can, after opening the masked stage, forst call ExpandPopulationMask() before Exporting the stage - and if you’re interested in bound Materials, as it sounds like you are, this is the thing that will pull them in for you.

Cheers,
–spiff