Reading Values#

A read copies values out of the simulation, such as where each body is and how fast it moves. This page reads several attributes at once and shows how to tell which row belongs to which object.

Three boxes move for 0.5 s: BoxA rests on the ground, BoxB flies in an arc, and BoxC falls. A read_sync call for position and linearVelocity then returns two groups, one per attribute, and each row of both groups lights up together with its box.

One Read, Several Attributes#

Pass a list of attribute names to read them together. The following program, reading_values_three_boxes.py, simulates three boxes for 0.5 s, reads position and linearVelocity of every rigid body, and prints them by path:

The imports and the scene, in USD
import ovstage
from ovphysx.population import physics_population_descs
from ovphysx import PhysX
from ovphysx.samples.python_samples.schema_support import physx_schema_paths
from ovphysx.types import SimObjectType

# BoxA rests on the ground, BoxB is thrown up and to the side, and BoxC falls.
SCENE = """#usda 1.0
(
    metersPerUnit = 1
    kilogramsPerUnit = 1
    upAxis = "Z"
)

def Xform "World"
{
    def PhysicsScene "PhysicsScene" {}

    def Plane "Ground" (
        prepend apiSchemas = ["PhysicsCollisionAPI"]
    )
    {
        uniform token axis = "Z"
    }

    def Cube "BoxA" (
        prepend apiSchemas = ["PhysicsRigidBodyAPI", "PhysicsCollisionAPI"]
    )
    {
        double size = 0.4
        double3 xformOp:translate = (-1, 0, 0.2)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }

    def Cube "BoxB" (
        prepend apiSchemas = ["PhysicsRigidBodyAPI", "PhysicsCollisionAPI"]
    )
    {
        double size = 0.4
        vector3f physics:velocity = (1, 0, 3)
        double3 xformOp:translate = (0, 0, 1)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }

    def Cube "BoxC" (
        prepend apiSchemas = ["PhysicsRigidBodyAPI", "PhysicsCollisionAPI"]
    )
    {
        double size = 0.4
        double3 xformOp:translate = (1.5, 0, 3)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }
}
"""


def read_bodies(physx):
    """Return {path: {attribute: [x, y, z]}} for every rigid body."""
    bodies = {}
    with physx.read_sync(
        SimObjectType.RIGID_BODY, ["position", "linearVelocity"]
    ) as result:
        names = result.dictionary  # turns ids into attribute names and paths
        for group in result.groups:
            attribute = names.token_to_string(group.attribute)
            paths = names.get_path_strings(group.prim_list)
            for path, row in zip(paths, group.tensors[0].numpy()):
                bodies.setdefault(path, {})[attribute] = row.tolist()  # a copy
    return bodies


ovstage.population.register_usd_schemas([str(p) for p in physx_schema_paths()])
stage = ovstage.Stage("reading_values")
ovstage.population.open_usd_from_string_with_desc(
    stage, SCENE, ordinal=1, time=ovstage.population.DEFAULT_TIME, descs=physics_population_descs(rendering=True)
)
stage.advance_write_floor(ordinal=1).wait()

physx = PhysX()
physx.wait_task(physx.attach_ovstage(stage, read_ordinal=1))

for step in range(30):  # simulate 0.5 s
    physx.step_sync(1.0 / 60.0)

print("object       position (m)            linear velocity (m/s)")
for path, values in read_bodies(physx).items():
    x, y, z = values["position"]
    vx, vy, vz = values["linearVelocity"]
    print(f"{path}  {x:6.3f} {y:6.3f} {z:6.3f}    {vx:6.3f} {vy:6.3f} {vz:6.3f}")

physx.wait_task(physx.detach_ovstage())
physx.destroy()
stage.destroy()

It prints:

object       position (m)            linear velocity (m/s)
/World/BoxC   1.500  0.000  1.771     0.000  0.000 -4.905
/World/BoxB   0.500  0.000  1.271     1.000  0.000 -1.905
/World/BoxA  -1.000  0.000  0.200     0.000  0.000  0.000

Notice the following:

  • Each group’s tensors hold the values of one attribute, and row i belongs to object i of its prim_list.

  • result.dictionary turns the group’s numeric IDs into text: token_to_string gives the attribute name, and get_path_strings gives the path of each row.

  • The rows come back as BoxC, BoxB, BoxA, not in the order of the scene file. The program stores the values by path, so it can combine the two groups safely.

  • row.tolist() copies each row. The end of the with block closes the read, and its arrays are no longer valid after that, so copy what you keep.

read_sync waits for the result before it returns. A loop that reads every step can keep a query and use physx.read instead, as Keeping a Query shows.

Common Rigid Body Attributes#

Attribute

Values

Unit

position

x, y, z of the body in world space

Scene length unit, such as m

orientation

Rotation as a quaternion, in x, y, z, w order

None

linearVelocity

x, y, z velocity of the center of mass

Length unit per second

angularVelocity

x, y, z rotation speed

Radians per second

mass

The body’s mass

Scene mass unit, such as kg

Angular velocity is in radians per second, even though USD files write it in degrees per second. A body that has not turned has the orientation (0, 0, 0, 1).

Finding Attribute Names#

Each object type has its own attributes. The ovphysx.attributes module lists them, with their units and frames, without a scene. The following program, reading_values_attribute_names.py, prints the names that a RIGID_BODY read accepts:

import textwrap

from ovphysx import attributes

# The names that a RIGID_BODY read accepts. This needs no scene.
names = attributes.list_attributes(
    "RIGID_BODY", readable=True, representation="default"
)
print(textwrap.fill(", ".join(a.name for a in names), width=80))

# The unit and frame of one of them.
spin = attributes.get_attribute("RIGID_BODY", "angularVelocity")
print(f"{spin.name}: {spin.unit['display']}, {spin.frame} frame")

It prints:

angularAcceleration, angularVelocity, centerOfMassOrientation,
centerOfMassPosition, contactOffset, disableGravity, disableSimulation,
dynamicFriction, inertia, inverseInertia, inverseMass, isSleeping,
kinematicTargetOrientation, kinematicTargetPosition, linearAcceleration,
linearVelocity, mass, orientation, position, restOffset, restitution,
shapeCount, staticFriction
angularVelocity: rad / sec, world frame

representation="default" limits the list to names that a read accepts. The attribute reference has the same information for every type, and Discovering Attribute Metadata shows more of the module.

A name that the type does not have is not an error. The read returns no group for it, so check that each group you expect arrived.

More Detail#