Debugging#

When something goes wrong, ovphysx tells you in two places: the exceptions that your program receives, and the messages on the console. When the numbers alone do not explain a problem, draw what PhysX sees, or record the simulation and replay it step by step.

Three panels. On the left, ovphysx simulates the falling box while a REC label shows that recording is on. In the middle, each step adds to the timeline of the file falling_box.ovd, which holds 60 steps in 82 KB. On the right, a drawing of the replay: a playhead scrubs along the timeline, and the box appears at that step with its bounding box and its downward velocity.

Where Errors Appear#

ovphysx reports errors as Python exceptions. When one appears depends on the call:

Call

When the Error Appears

Exception

A call that ovphysx rejects, such as one with a wrong argument

During the call

Usually RuntimeError, or ValueError or TypeError from checks in Python

A call that waits for its work, such as step_sync or read_sync

During the call

RuntimeError or TaskError

Queued work: attach_ovstage, detach_ovstage, step, and update_from_ovstage

When you wait for its task with wait_task, or at the next wait_all() if nothing waited for it

TaskError

TaskError is a kind of RuntimeError, so except RuntimeError catches both. A TaskError lists each failed task with its message in error.errors.

ovphysx also prints its warnings and errors on the console, in lines that start with [Warning] or [Error]. They often explain the exception that follows.

Common Mistakes#

Mistake

What You See

Fix

Registering the PhysX schemas after loading a scene, or never

OvstageError: “USD schema definitions were already built”, or RuntimeError: “the PhysX USD schema families were not both registered with ovstage”

Register the schemas before loading any scene, then restart the process. An attach that succeeds after the first error can still be missing physics settings.

Attaching before sealing the ordinal

TaskError: “Physics scan backend failed”

Call stage.advance_write_floor(ordinal=1).wait() before attach_ovstage

Misspelling an attribute name

IndexError: “list index out of range” at result.groups[0]

The read returns no groups and no error. Check the name in Reading Values.

Keeping a read’s arrays after its with block

RuntimeError: “Cannot destroy PhysX while output-read arrays or downstream views are alive”

Read inside a function and return plain numbers

Waiting for the same task twice

RuntimeError: “Task was never issued or was already collected”

Wait for each task once

Turn Up the Log Level#

By default, ovphysx prints messages of level WARNING and above. To see more, set a more detailed level at any point in your program:

import ovphysx

ovphysx.set_global_config(ovphysx.GlobalConfigKey.LOG_LEVEL, ovphysx.LogLevel.INFO)

LogLevel.VERBOSE shows even more, and LogLevel.NONE silences the messages of ovphysx itself. The level applies to the whole process.

See What PhysX Sees#

The debug view shows what PhysX works with, such as the collision shape of every object and every contact. Use it when an object floats, sinks, or hits something you cannot see: the lines show the shapes and contacts that PhysX actually uses. PhysX returns the lines, and your renderer draws them over the scene:

Two panels joined by an arrow. On the left, a read of DEBUG_RENDER returns lines grouped by color: 912 collision-shape lines and, after the box lands, 12 contact-point lines and 4 contact-normal lines. On the right, a renderer draws those lines in their colors: the falling box's magenta wireframe and a magenta circle of the ground plane. After the landing, it adds a red cross at each bottom corner of the box and four blue normals pointing up.

To turn it on, write to the DEBUG_RENDER target: set enabled to 1, and each flag you want to a value above 0. For some flags, such as contactNormal, the value is also the length of each line, so a value of 1.5 draws 1.5 m normals. scale, 1 by default, multiplies every size. These flags help most:

Flag

What It Draws

collisionShapes

The collision shape of every collider. A ground plane appears as circles.

collisionAABBs

The box, aligned with the world axes, that encloses each collider

contactPoint

A small cross at each point where two shapes touch

contactNormal

A line from each contact point in the direction that it pushes

bodyAxes

The x, y, and z axes of each rigid body

bodyLinearVelocity

A line along the velocity of each rigid body

jointLocalFrames

The local axes of each joint

A read of the same target returns lines: linePosition holds the two ends of each line in world space, and lineColor a 0xAARRGGBB color for each end. Points and triangles come the same way. This program, debugging_debug_view.py, turns on three flags for the falling box and counts the lines by color:

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

# The scene from Your First Simulation: a ground plane and a 1 m box whose
# center starts 2 m above it.
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 "Box" (
        prepend apiSchemas = ["PhysicsRigidBodyAPI", "PhysicsCollisionAPI"]
    )
    {
        double size = 1
        double3 xformOp:translate = (0, 0, 2)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }
}
"""


def set_debug(physx, name, value):
    """Set one debug visualization setting, such as "collisionShapes"."""
    with physx.write_sync(SimObjectType.DEBUG_RENDER, [name]) as session:
        for group in session.groups:
            dtype = np.uint8 if name == "enabled" else np.float32
            group.tensors[0].assign(np.array([value], dtype=dtype))
            session.commit_sync(group)


def lines_by_color(physx):
    """Read the debug lines and count them by color (0xAARRGGBB)."""
    with physx.read_sync(SimObjectType.DEBUG_RENDER, ["lineColor"]) as result:
        colors = result.groups[0].tensors[0].numpy()[:, 0]  # first end of each line
        values, counts = np.unique(colors, return_counts=True)
        return ", ".join(f"{n} in {int(v):08x}" for v, n in zip(values, counts))


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

# Turn on the debug view, then three of its flags.
set_debug(physx, "enabled", 1)
set_debug(physx, "collisionShapes", 1.0)
set_debug(physx, "contactPoint", 1.0)
set_debug(physx, "contactNormal", 1.5)  # 1.5 m long normals, past the 1 m box

for step in range(1, 46):
    physx.step_sync(1.0 / 60.0)
    if step in (30, 45):  # still falling, then resting on the ground
        print(f"step {step}: lines {lines_by_color(physx)}")

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

It prints:

step 30: lines 912 in ffff00ff
step 45: lines 4 in ff0000ff, 12 in ffff0000, 912 in ffff00ff

Notice the following:

  • The 912 magenta lines, ffff00ff, are collision shapes: 12 for the box and 900 for the ground plane. After the landing, 12 red lines, ffff0000, draw a cross at each of the four contact points, and 4 blue lines, ff0000ff, draw the 1.5 m contact normals.

  • Contact lines appear only while the box is awake. Soon after it rests, it falls asleep, and they disappear.

Debug Render lists every flag. Its scope and cullingBox settings limit drawing to some objects or to a region.

Record and Replay With OmniPVD#

OmniPVD, the PhysX Omniverse Visual Debugger, records what PhysX simulates at every step into a .ovd file. A viewer replays the file, so you can stop at any step and look at shapes, contacts, and velocities. This program, debugging_recording.py, records the falling box:

import os

import ovstage
from ovphysx.population import physics_population_descs
from ovphysx import GlobalConfigKey, OmniPvdDestination, PhysX, set_global_config
from ovphysx.samples.python_samples.schema_support import physx_schema_paths

# The scene from Your First Simulation: a ground plane and a 1 m box whose
# center starts 2 m above it.
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 "Box" (
        prepend apiSchemas = ["PhysicsRigidBodyAPI", "PhysicsCollisionAPI"]
    )
    {
        double size = 1
        double3 xformOp:translate = (0, 0, 2)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }
}
"""

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

# Allow recording. This must happen before the first PhysX object exists.
set_global_config(GlobalConfigKey.OVD_RECORDING_CAPABLE, True)
physx = PhysX()
physx.wait_task(physx.attach_ovstage(stage, read_ordinal=1))

# Record one second of simulation, starting before the first step.
physx.start_recording(OmniPvdDestination.file("falling_box.ovd"))
for step in range(60):
    physx.step_sync(1.0 / 60.0)
physx.stop_recording()  # finishes the file

physx.wait_task(physx.detach_ovstage())
physx.destroy()
stage.destroy()
size_kb = os.path.getsize("falling_box.ovd") / 1024
print(f"Recorded 60 steps to falling_box.ovd ({size_kb:.0f} KB)")

It prints:

Recorded 60 steps to falling_box.ovd (82 KB)

Notice the following:

  • OVD_RECORDING_CAPABLE records nothing by itself, but it costs some speed, so turn it on only when you record.

  • Call stop_recording before you detach.

  • A path that ends in .ovd names the file. Any other path names a folder, where each recording gets a new file named after the date and time.

To view the file, open an Omniverse Kit application such as Isaac Sim, enable its OmniPVD extension (omni.physx.pvd), and import the .ovd file. The viewer must support the recording’s version, as Capture Format and Compatibility explains.

More Detail#