Import usd-files with python code

Hi everyone,
I’m looking to import certain usd-files n times to put them into a box for a bin picking application. Regarding the automation of that task, I’d like to import and place the objects randomly using python. I already implemented the randomization of the positions, but unfortunatly I couldn’t find any examples/ functions to import objects with python code alone. Is there any function solving my problem?
Many thanks in advance!

Hi @christian.hoelzer

You can add usd-files assets n-times as a reference to your stage using the AddReference method.
For example

import omni

stage = omni.usd.get_context().get_stage()

for i in range(10):
    prim = stage.DefinePrim("/World/prim{}".format(i), "Xform")
    prim.GetReferences().AddReference("omniverse://localhost/example.usd")

Welcome to the forums @christian.hoelzer! @toni.sm has provided the right solution. Let me know if that works for you or if you run into any further trouble.

Hi @toni.sm
That helped a lot, but now I got a problem adding for example translation to the object. I’m using the following code:

When executing the code I get the error message:

It seems as if the given translation can’t be realised for that certain object. I can fix that error by going the parts properties and disable the xformOP:transform(matrix4d) option and replacing it with any option containing the xformOP:translate() parameter. Then my code works as I want it to.
My question: Is there any better way to change positions of an imported object? Because my code works perfectly on any part I create manually within Omniverse Create.

Many thanks in advance

Hi @christian.hoelzer

You can always remove all properties related to transformation and create and set those you need…
For example, for translation:

import omni
import random
from pxr import UsdGeom, Gf

stage = omni.usd.get_context().get_stage()

for i in range(10):
    prim = stage.DefinePrim("/World/prim{}".format(i), "Xform")
    prim.GetReferences().AddReference("omniverse://localhost/example.usd")

    xformable = UsdGeom.Xformable(prim)
    for name in prim.GetPropertyNames():
        if name == "xformOp:transform":
            prim.RemoveProperty(name)

    if "xformOp:translate" in prim.GetPropertyNames():
        xform_op_tranlsate = UsdGeom.XformOp(prim.GetAttribute("xformOp:translate"))
    else:
        xform_op_tranlsate = xformable.AddXformOp(UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.PrecisionDouble, "")
    xformable.SetXformOpOrder([xform_op_tranlsate])
    
    xform_op_tranlsate.Set(Gf.Vec3d([(2 * random.random() - 1) * 200 for _ in range(3)]))

This is a very good case! If in this already created scene, I want to change the size for “Prim1” “Prim3” “Prim5”, how to express it? How to assign values to multiple prims at the same time