Writing Values#

A write changes the simulation from your program. It can move a body, set its velocity, or push it with a force. This page shows how a write works and how long each kind of value lasts.

Open, Fill, Commit#

With a scene attached to your PhysX object, a write takes three steps:

Three panels show one write in order. Open: ovphysx returns a group with the object list /World/VelocityBox and an unfilled linearVelocity array. Fill: the program puts 1.000, 0.000, 0.000 into the array. Commit: a read now returns a velocity of 1.000 m/s, while the box is still at x = 0.000 m because no step has run.

  1. Open the write for one or more attributes. Like a read, it returns groups, each with an array that has one row per selected object.

  2. Fill every row of each array with the values you want.

  3. Commit each group. ovphysx applies the values at once, before the next step.

write_sync opens the write and returns it with every group in its groups list. commit_sync commits one group and waits. A loop that writes every step can keep a query and use physx.write instead, as Keeping a Query shows.

A commit writes every row of its group. The arrays do not start with the current values, so fill every row. A group that you do not commit is discarded.

To write only some rows of a group, commit it with a mask: session.commit_sync(group, mask=mask). The mask holds one bool or uint8 value per row, on the same device as the group’s arrays (group.tensors[0].device), and rows whose value is zero are not written. When you know the objects in advance, a pattern is simpler, as in the program in A Velocity and a Force.

A Velocity and a Force#

The following program, writing_values_push.py, writes only once: a velocity of 1 m/s to one box and a force of 30 N to another. Then it steps for 1 s:

Two 1 kg boxes start at rest with gravity off. A velocity write sets VelocityBox moving at 1 m/s at once. A 30 N force pushes ForceBox during step 1 only, after which its velocity stays at 0.5 m/s. After 30 steps, VelocityBox has moved 0.5 m and ForceBox 0.246 m.

The imports and the scene, in USD
import numpy as np
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

# Two 1 kg boxes side by side. Gravity is off, so only the writes move them.
SCENE = """#usda 1.0
(
    metersPerUnit = 1
    kilogramsPerUnit = 1
    upAxis = "Z"
)

def Xform "World"
{
    def PhysicsScene "PhysicsScene"
    {
        float physics:gravityMagnitude = 0
    }

    def Cube "VelocityBox" (
        prepend apiSchemas = ["PhysicsRigidBodyAPI", "PhysicsCollisionAPI",
                              "PhysicsMassAPI"]
    )
    {
        float physics:mass = 1
        double size = 0.2
        double3 xformOp:translate = (0, -0.5, 0)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }

    def Cube "ForceBox" (
        prepend apiSchemas = ["PhysicsRigidBodyAPI", "PhysicsCollisionAPI",
                              "PhysicsMassAPI"]
    )
    {
        float physics:mass = 1
        double size = 0.2
        double3 xformOp:translate = (0, 0.5, 0)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }
}
"""


def write_vector(physx, pattern, attribute, vector):
    """Write the same vector to every rigid body that the pattern selects."""
    with physx.write_sync(
        SimObjectType.RIGID_BODY, [attribute], pattern=pattern
    ) as session:
        for group in session.groups:
            rows = np.full((group.prim_count, 3), vector, dtype=np.float32)
            group.tensors[0].assign(rows)  # fill every row of the open array
            session.commit_sync(group)  # apply the values now


def print_motion(physx, step):
    """Print the x position and x velocity of both boxes."""
    x = {}
    with physx.read_sync(
        SimObjectType.RIGID_BODY, ["position", "linearVelocity"]
    ) as result:
        for group in result.groups:
            attribute = result.dictionary.token_to_string(group.attribute)
            paths = result.dictionary.get_path_strings(group.prim_list)
            for path, row in zip(paths, group.tensors[0].numpy()):
                x[path, attribute] = float(row[0])
    print(
        f"{step:4}   {x['/World/VelocityBox', 'position']:6.3f}"
        f"  {x['/World/VelocityBox', 'linearVelocity']:6.3f}"
        f"      {x['/World/ForceBox', 'position']:6.3f}"
        f"  {x['/World/ForceBox', 'linearVelocity']:6.3f}"
    )


ovstage.population.register_usd_schemas([str(p) for p in physx_schema_paths()])
stage = ovstage.Stage("writing_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))

# Set VelocityBox moving at 1 m/s. Push ForceBox with 30 N, once.
write_vector(physx, "/World/VelocityBox", "linearVelocity", [1.0, 0.0, 0.0])
write_vector(physx, "/World/ForceBox", "force", [30.0, 0.0, 0.0])

print("        VelocityBox         ForceBox")
print("step    x (m)  vx (m/s)     x (m)  vx (m/s)")
print_motion(physx, 0)
for step in range(1, 61):
    physx.step_sync(1.0 / 60.0)
    if step in (1, 2, 3, 30, 60):
        print_motion(physx, step)

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

It prints the x position and x velocity of both boxes, after the writes (step 0) and after some of the steps:

        VelocityBox         ForceBox
step    x (m)  vx (m/s)     x (m)  vx (m/s)
   0    0.000   1.000       0.000   0.000
   1    0.017   1.000       0.004   0.500
   2    0.033   1.000       0.013   0.500
   3    0.050   1.000       0.021   0.500
  30    0.500   1.000       0.246   0.500
  60    1.000   1.000       0.496   0.500

Notice the following:

  • VelocityBox moves at 1 m/s right after the commit, before the first step.

  • ForceBox speeds up during step 1 only: a force of 30 N on 1 kg for 1/60 s adds 0.5 m/s. To keep pushing, write the force before every step.

How Long Values Last#

Kind of Value

Examples

After the Commit

State

position, orientation, linearVelocity, angularVelocity

Changes at once. The simulation goes on from the new value, so gravity and collisions keep changing it.

Settings and targets

mass, friction, joint drive targets

Stay until you write them again.

Forces

force, and wrench, a force and a torque together

Act during the next step only.

Writing position keeps the body’s orientation, and writing orientation keeps its position.

What You Cannot Write#

Some attributes are read-only, such as linearAcceleration and isSleeping. Opening a write for a read-only or unknown name raises TaskError and writes nothing. Forces work the opposite way: you can write them, but a read returns no group for them.

In DirectGPU mode, step once before you write values that live in GPU memory, such as positions and velocities, as Data on the GPU explains.

More Detail#

  • Writable Data lists every writable attribute, with the exact rules for timing, row masks, and what each value overwrites.

  • Next: Data on the GPU keeps results in GPU memory for GPU libraries.