Transform Evaluation Internals#
This page of the Technical Guide explains how the
ovstage backend, which reads USD through the
ovstage runtime, turns USD
transforms into collision poses, and which rules keep its results identical to the
OpenUSD backend, the parity reference. It
is written for maintainers of the ovstage transform code (source/*MatrixDecomposition.h,
source/OvstageSceneReader*, source/OvstageClashTransforms.cpp) and of its tests. The
Architecture glossary defines the implementation terms.
Other pages own the neighboring topics:
Page |
What it owns |
|---|---|
Selecting the decomposition mode from Python and C. |
|
The matrix cache switch, the window sizes and the static purge that users see. |
|
The populations and the composition rules for numeric transform reads. |
|
The BVH split, the scheduler budgets and narrow-phase reuse. |
|
Populations, topology recovery and instancing identity. |
Requirement: these rules preserve result parity with the OpenUSD backend. Before you change one, run the tests named under it.
Transform decomposition is part of result parity#
The collision engine needs two values for every mesh: a float pose (a translation and a unit
quaternion) and a signed per-axis mesh scale. decomposeRowMajorMatrix() in
source/MatrixDecomposition.h computes both from the mesh’s 4x4 double world matrix.
Equal world matrices and equal cooked meshes are not enough for equal results:
Two decompositions of one matrix can both be correct and still round differently.
At zero tolerance, that rounding can change which triangle pairs touch.
The difference shows most with reflections. Gf, OpenUSD’s math library, puts the sign of a negative determinant on all three scales. The legacy mode, ovclash’s original decomposition, puts it on the X scale only. Both rebuild the same matrix, but their float operations differ, so a grazing triangle pair can change membership while the stage’s overlap count stays equal.
Requirement: ovstage reproduces the decomposition of the OpenUSD reference backend, whose
shared clash engine converts each matrix with GfTransform. A
representation that only looks equivalent is not sufficient.
Current decomposition modes and grazing contacts#
Each ovstage context selects one of two modes. Both read the scene through ovstage; the mode does not select a scene backend.
Mode |
C value |
Python name |
Implementation |
Purpose |
|---|---|---|---|---|
OpenUSD (default) |
|
|
|
Parity with the OpenUSD backend |
ovclash (legacy) |
|
|
|
Reproduces the results of ovclash 0.1.7 for comparisons |
source/GfMatrixDecomposition.h is an OpenUSD-free adaptation of GfTransform(matrix) from the
pinned OpenUSD v25.11. It keeps Gf’s arithmetic step by step:
The zero-pivot sandwich: identity times the matrix times an inverse pivot whose translation is
-0.0. It sets the signed-zero bits of the translation.The Jacobi eigensolver on
A * transpose(A), with the eigenvalues left in solver order (unsorted).Signed scales: the determinant’s sign goes on all three axes. An eigenvalue below
1e-10becomes a scale of±1e-10.Quaternion extraction, then the
GfRotationaxis-angle round trip through degrees and theGfQuatdnormalization.Narrowing to float only at the end, in
decomposeRowMajorMatrix().
The ovstage backend gains no OpenUSD dependency from this header.
ovclash compiles C and C++ with -ffp-contract=off on GCC and Clang
(cmake/modules/CompilerDefaults.cmake). The prebuilt OpenUSD Gf library uses GCC’s default
contraction, which fuses multiply-adds on AArch64. On GCC for AArch64,
source/GfMatrixDecomposition.h therefore switches its own code to fp-contract=fast, so it
matches Gf word for word. Baseline x86-64 has no FMA (fused multiply-add), so nothing changes
there.
source/OvclashMatrixDecomposition.h keeps the ovclash 0.1.7 arithmetic unchanged: Gram-Schmidt
orthonormalization, up to 16 polar-decomposition iterations, the reflection sign on the X scale
only, and no normalization of the final float quaternion.
Requirement: do not simplify either decomposition, reorder its operations or normalize the final float quaternion without the tests of Reference tests.
Example: one stage, two answers#
A sheared triangle above a large plane touches the plane in the legacy mode but not in the OPENUSD
mode. The script writes its own stage to a temporary directory, so it runs from any
directory with an ovstage build of the ovclash packages importable.
ovclash Python in the settings reference lists the
RunSettings fields:
import tempfile
from pathlib import Path
from ovclash import ClashRuntime, RunSettings
# A sheared triangle above a large plane. The two decompositions round the
# shear differently, so they disagree about this zero-tolerance contact.
STAGE = """#usda 1.0
(
metersPerUnit = 0.01
upAxis = "Z"
)
def Xform "World"
{
def Mesh "Tilted"
{
int[] faceVertexCounts = [3]
int[] faceVertexIndices = [0, 1, 2]
point3f[] points = [(1.31, 2.75, -0.125), (-2, 0.3, 0.7), (-0.1, -0.4, 2)]
matrix4d xformOp:transform = ((1, 0.5, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1))
uniform token[] xformOpOrder = ["xformOp:transform"]
}
def Mesh "Plane"
{
int[] faceVertexCounts = [3]
int[] faceVertexIndices = [0, 1, 2]
point3f[] points = [(-100, 0, -100), (-100, 0, 100), (100, 0, 0)]
double3 xformOp:translate = (0, 2.65, 0)
uniform token[] xformOpOrder = ["xformOp:translate"]
}
}
"""
with tempfile.TemporaryDirectory() as tmp:
stage = Path(tmp) / "sheared.usda"
stage.write_text(STAGE, encoding="utf-8")
with ClashRuntime() as runtime: # requires the ovstage backend
runtime.open_stage(str(stage))
runtime.set_run_settings(RunSettings(tolerance=0.0))
for mode in ("openusd", "ovclash"):
runtime.set_ovstage_matrix_decomposition(mode) # a change discards results and the pipeline
runtime.run_pipeline()
print(f"{mode}: {runtime.get_overlap_count()} overlap(s)")
openusd: 0 overlap(s)
ovclash: 1 overlap(s)
On the OpenUSD backend, set_ovstage_matrix_decomposition() raises RuntimeError.
What a mode change does#
setOvstageMatrixDecomposition() in source/OvstageClashBackend.cpp implements
ovclash_ovstage_set_matrix_decomposition():
It fails while an async handle is live. That includes a handle whose worker has completed but that
ovclash_finish_pipelinehas not released yet. This check runs before the same-mode check.Selecting the current mode changes nothing. Results, borrowed reports and the pipeline stay.
A new mode clears
pipeline_createdand the step counters, then callsclearQueryResults(). That drops the results, the selected meshes with their cooked geometry, poses and bounds, the point clouds and the dynamic caches. Borrowed reports become invalid.The mode is stored per context (
matrix_decomposition). It survivesovclash_reset_contextand stage replacement. New contexts start with OPENUSD.Immediate depth and depenetration queries use the selected mode too.
Raw reported world matrices and point-cloud row scaling involve no decomposition, so the mode does not change them.
The Suite API has no setter. Suite runtimes always use OPENUSD.
The Python wrapper ClashRuntime.set_ovstage_matrix_decomposition() closes its tracked reports
before a change. The next run_pipeline() or run_async() creates the pipeline again. The
Python package guide lists the
caller rules.
The C call is a one-liner on an ovstage context. Release every borrowed report first. This
function is a complete helper, not a program: put it in a C source file of your own that links
the ovclash CMake target of an ovstage build, and call it with a context from
ovclash_create_context():
#include <ovclash/ovclash_ovstage.h>
#include <stdio.h>
/* ctx is an ovstage context from ovclash_create_context(). */
static int select_legacy_decomposition(ovclash_context_t* ctx)
{
ovclash_ovstage_matrix_decomposition_t mode = OVCLASH_OVSTAGE_MATRIX_DECOMPOSITION_OPENUSD;
if (ovclash_ovstage_set_matrix_decomposition(ctx, OVCLASH_OVSTAGE_MATRIX_DECOMPOSITION_OVCLASH).status !=
OVCLASH_STATUS_SUCCESS) {
ovclash_string_t error = ovclash_get_last_error(ctx);
if (error.ptr != NULL) {
fprintf(stderr, "%.*s\n", (int)error.length, error.ptr);
}
return 0;
}
if (ovclash_ovstage_get_matrix_decomposition(ctx, &mode).status != OVCLASH_STATUS_SUCCESS) {
return 0;
}
printf("legacy math: %s\n", mode == OVCLASH_OVSTAGE_MATRIX_DECOMPOSITION_OVCLASH ? "on" : "off");
return 1; /* The old pipeline is gone: call ovclash_create_pipeline() before the next run. */
}
Input and output validation#
decomposeRowMajorMatrix() guards both modes. It writes the pose and scale only when every check
passes, and otherwise throws std::invalid_argument:
Check |
When |
Message |
|---|---|---|
The matrix pointer is null |
Before |
|
An element is not finite or exceeds the float range |
Before |
|
The length of one of the first three rows exceeds the float range |
Before |
|
OPENUSD only: a translation, scale or quaternion value is not finite or exceeds the float range |
After |
|
|
After |
|
The affected pipeline or immediate query fails with that message. The guards never normalize a
result, so they leave every valid result unchanged. Example: collinear source rows make the legacy
basis non-orthogonal, and its finite quaternion then has a squared norm of 5/6. Accepting it
would distort the geometry and could lose overlaps, so the guard rejects it.
Immediate depth and depenetration queries call validateImmediateMatrices()
(source/OvstageClashGeometry.cpp) before they read the stage or cook a mesh. An invalid caller
matrix is therefore reported as Matrix decomposition ..., even when a path would also fail to
load. On failure the canonical C depth and depenetration calls leave the caller-owned output
unchanged.
Scope of the guard:
The OpenUSD backend has its own validation policy.
Raw reported matrices and point clouds do not pass through this mesh guard.
Reference tests#
tests/native/TestMatrixDecomposition.cpp compares the OPENUSD mode with Gf on synthetic matrices:
Build |
Reference |
Comparison |
|---|---|---|
Windows |
Float words captured from the pinned OpenUSD v25.11 |
Exact |
OpenUSD backend, any platform |
The live platform |
Exact |
ovstage-only, not Windows |
The Windows captures |
Translations exact; scales within eight float epsilons (relative), quaternion components within eight float epsilons (absolute) |
The last row is a portable smoke check. It does not establish bit parity. Bit parity on a platform needs that platform’s pinned Gf build. The same program also pins the legacy unit-quaternion boundary and the collinear-rows rejection.
MirroredDecompositionTests in tests/python_tests/test_mirrored_decomposition.py runs the public
pipeline at zero tolerance on hand-made triangles:
A mirrored grazing contact pins the platform’s OpenUSD result: no overlap on x86-64, one on ARM64.
Intersecting and separated controls sit safely away from that boundary.
A sheared transform separates the two modes. It drives the runtime-switch, animated and concurrent-context cases and the OpenUSD-backend rejection.
These checks cover the factor representation and the clash membership. A full-stage comparison must also compare the pairs, the face indices and the report geometry.
License of the adaptation#
licenses/openusd-v25.11/ holds LICENSE.txt and NOTICE.txt for the adapted Gf code.
scripts/package_licenses.py always adds them to ovclash-LICENSES.zip under
source-adaptations/openusd-v25.11/, whether or not the build links OpenUSD. Every install tree,
and so every SDK archive and wheel, ships that archive.
Decomposition throughput and storage#
No heap, no shared state. Both helpers use fixed-size arrays on the call’s stack. A successful call allocates nothing and shares no scratch, so independent workers can call it in parallel.
Keep the full operation order. Gf multiplies full 4x4 matrices with four ordered products per element. An affine specialization is algebraically equal but can change rounding at grazing contacts.
One exact shortcut. When the 3x3 linear block is exactly the identity, the OPENUSD mode skips the eigensolver and the quaternion extraction. It still applies the zero-pivot sandwich, which sets the signed-zero translation bits. The comparison is exact, so nearby rotations, shears and scales still take the full path.
Tests for the shortcut. The native reference inputs include signed-zero translations, non-affine last columns and near-identity controls. The OpenUSD build also checks their final floats against the live pinned Gf.
Cost and measurement:
The default OPENUSD mode costs more per call than the legacy mode, most for rotated and sheared matrices. That cost buys OpenUSD’s representation and contact parity.
Do not select the legacy mode for speed: it can change clash results.
In whole pipelines, finding meshes and populating the stage usually cost far more than the decomposition.
benchmarks/matrix_decomposition/MatrixDecomposition.cppmeasures both modes with 1, 2, 4 and 8 workers.benchmarks/matrix_decomposition/README.mdgives its launchers, compiler flags, output format and baseline comparison.Never enable fast-math: the float words are part of parity.
Finite numeric transform reference#
The OpenUSD backend evaluates transforms with UsdGeomXformCache, in its direct prim-matrix query
(source/OpenUsdClashBackend.cpp) and in the shared clash engine’s transform workers. The cache
composes each prim’s local matrix with its parent’s cached world matrix, so the parent’s world is
always complete first.
The order matters in binary64. Take three translations along X: leaf 1e16, parent -1e16 and
grandparent 1:
leaf, parent, grandparent = 1e16, -1e16, 1.0
# OpenUSD and ovstage: compose the parent's world first, then apply the leaf.
parent_world = parent + grandparent # -1e16 + 1 rounds to -1e16
print(leaf + parent_world) # 0.0
# A child-first fold of the same three translations gives another result.
print((leaf + parent) + grandparent) # 1.0
ovstage composes numeric worlds in the same parent-first order, separately for every instance placement. It never reuses a completed prototype world for another placement, and it never relies on published world rows across identity ancestors. Numeric transform reads lists the full composition rules.
The same chain through ovclash returns the parent-first result on both backends:
import tempfile
from pathlib import Path
from ovclash_suite import ClashDetection
STAGE = """#usda 1.0
def Xform "Grand"
{
double3 xformOp:translate = (1, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate"]
def Xform "Parent"
{
double3 xformOp:translate = (-10000000000000000, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate"]
def Xform "Leaf"
{
double3 xformOp:translate = (10000000000000000, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate"]
}
}
}
"""
with tempfile.TemporaryDirectory() as tmp:
stage = Path(tmp) / "association.usda"
stage.write_text(STAGE, encoding="utf-8")
detection = ClashDetection()
try:
detection.open_stage(str(stage))
matrix = detection.get_prim_matrix("/Grand/Parent/Leaf", 0.0)
print("world x:", float(matrix[3][0])) # 0.0 on both backends
finally:
detection.destroy()
world x: 0.0
Regression coverage:
tests/python_tests/test_numeric_transform_association.pywith the fixturestests/data/numeric_transform_association.usdaandtests/data/numeric_transform_identity_association.usda: nested placements, nonuniform scales, identity ancestors, signed zeros and rewind.tests/python_tests/test_instance_reset_transforms.py: reset boundaries across instances.
Reusing transform setup and dynamic report storage#
The selected numeric read plan#
Numeric playback keeps a SelectedNumericTransformPlan (source/OvstageSceneReaderNumericPlan.cpp)
for the current population and selection. The plan holds:
the attribute query and its handles;
the mapping from every selected path to its numeric operand and instance-root chain;
the required-leaf slots and the indexed, slot-based composition plan;
dense local matrices, reset flags and presence bits.
The plan recognizes its path list by identity:
Playback and the prefetch job share one immutable path list for the whole run. A sample that passes that list matches the plan in constant time, without comparing or validating paths.
Another list is compared with the plan’s list once. An equal shared list replaces the plan’s list, so its later reads compare nothing. A different list rebuilds the plan.
Direct matrix queries use temporary full-read plans. They never replace the playback plan.
Incremental reads#
After a complete snapshot, a read at a later ordinal can request only the rows written since then,
as long as the runtime still retains that history. readPrepared() in
source/OvstageSceneReaderNumericMatrices.h decides:
Situation |
Read |
|---|---|
A later ordinal whose history is still retained |
Delta: only the newer rows |
The first read, a rewind, a repeated ordinal or expired history |
Full snapshot |
A path appears twice in one delta |
Full snapshot of the same sealed ordinal |
A delta row is masked or empty without a delete |
Full snapshot of the same sealed ordinal |
A direct query |
Always a full snapshot |
Rules for every read:
Returned values update the owned slots. A matrix or reset tombstone clears its slot.
Only a complete, validated read becomes the next reusable snapshot.
Every read invalidates the composed worlds. They are recomposed in the same parent-first order for each placement, so a delta read changes only how inputs refresh, not the arithmetic or the reset semantics.
Every present matrix row must hold exactly 16 finite doubles, in full and delta reads alike.
An absent optional ancestor row means identity. A selected Mesh or Points leaf still needs its numeric row.
The numeric population already derives the canonical local and reset rows. Reading them at the sealed ordinal skips an ovstage hierarchy pass whose world matrices nobody would use. Default selection still reads the world matrices that the runtime publishes.
Population replacement destroys the retained queries before their stage.
Read validation and cleanup#
A classification or numeric value group may carry an index map or a mask, but not both. A sparse group’s declared row count must match the logical row count. No group may have pending CUDA synchronization.
validateReadGroupMetadata()insource/OvstageSceneReaderQueries.cppchecks all three.Invalid metadata fails before any row is read. It is not an ambiguous delta, so it is never retried as a full snapshot.
readAttributeGroups()retires the read operation and the read handle independently, before it formats a caught exception. A diagnostic allocation failure cannot skip the remaining release, and a consumer failure stays the primary error.Instancing metadata extraction (
source/OvstageSceneReaderGeometryInstancing.cpp) applies the same rule to its three owners: the operation, the read handle and the query.
Native regressions exercise these paths against forwarded real runtime reads:
tests/native/InstancingGraphTransformMetadataCases.h, InstancingGraphBatchLifetimeCases.h and
InstancingGraphMetadataLifetimeCases.h. The graph lifetime regression counts every retirement and
rereads the same population successfully after a failed read or cleanup.
Matrix prefetch#
Time updates on one population stay sequential. Eligible playback can still read the next matrix window on a worker while the collision phases process the current one.
Prefetch runs only when all of these hold (transformPrefetchWindowSize() in
source/OvstageClashContext.h, startTransformPrefetch() in source/OvstageClashTransforms.cpp):
The stage is file-backed, or attached with a composition (
ownerEvaluatesTime()is false). An attached Stage without a composition never prefetches: each sample is the owner’s publication, which no reader may run ahead of. A composition’s reader keys its engine population on the composition, soTransformPrefetchInputs::stagePathstays empty.The raw classification is complete.
The matrix cache is on.
single_threadedis off, and the selected scheduler allows at least two workers.The 1 GiB budget holds at least two frames.
No retained synchronous window is larger than the prefetch window size; such a window must expire first.
No earlier submission in this run failed. If submission fails, the run continues with reads on the owner thread and does not retry.
Scheduling:
With the new scheduler (
new_task_manager=true), the job goes to Carbonite tasking.With the legacy scheduler (
new_task_manager=false), the collision phases reserve one slot of their effective CPU budget for the reader, but only while its callback runs. A completed window that waits to be consumed reserves nothing. Example: withnb_tasks = 8and two available CPUs (for example a container quota), the budget is 2, so collision phases get one worker while the reader runs. Scheduler and worker budget gives the budget formula.
Ownership (source/TransformMatrixPrefetch.h):
The job owns its copied sample times and its private output arrays. It shares the immutable inputs with the context: the stage path, the selected path list, the dynamic mesh indices and the point-cloud count.
Until the context joins it, the job alone uses the source, including the source’s metrics counters. Cached-frame collision work uses only copied matrices and runtime geometry.
The context stops and joins the job before a selection or population change, a reset, a memory release, destruction and every return from pipeline execution, including failure and cancellation.
A direct source query (
ovclash_get_prim_matrix, the immediate queries) only joins the job. The copied future window stays usable, even when the query reads an unrelated time.ovclash_cancel_pipelineonly sets the flag; it does not join.Results and captured exceptions are read only after the join.
The worker installs the floating-point controls of the thread that launched it and restores its own afterwards. A request for a different sample, or under different controls, discards the future window and refills it synchronously.
Broad-phase candidate order#
The tree split and the per-phase work items are on the performance page. This section covers the order of the candidate pairs of the broad phase.
Mesh broad-phase workers claim 64 meshes at a time and collect their pairs in local chunks, which they merge under a lock. The merged candidates arrive in scheduler order.
Only the exact whole-sample reuse key reads the candidate order. The duplicate purge does not depend on it, and the narrow phase and
sortOverlaps()restore the canonical result order.runBroadPhase()therefore sorts the candidates only when they can become that key: in a reuse-eligible dynamic run whose snapshot, per-mesh key inputs and candidates fit the 8 MiB reuse budget. With the duplicate purge on, which can only drop candidates, the snapshot and the per-mesh key inputs decide alone. Builds with the validation observer always sort.
Static meshes run no query of their own when all of these hold:
the static purge is armed;
the tolerance is zero;
every tree leaf is exact: finite extents and no subnormal coordinates.
The inclusive box test is then symmetric. A moving mesh’s query therefore also reports its hits on
lower-indexed static meshes, and the candidate set equals the full traversal’s. Observer builds keep
every query for their StaticPrune candidate events.
Sorting by path:
Each selection builds lexical path ranks (
source/MeshPathOrder.h). Equal paths share a rank.sortBoundsPairs()decorates each pair once with its rank key when the decorated copy fits in 1 MiB. Larger streams, or a failed scratch allocation, use in-place byte radix partitioning with bounded stack scratch.A missing rank table or an invalid index falls back to the original path comparator. Equal keys keep the numeric mesh-index tie-breaks.
Sorting keeps each pair’s orientation and multiplicity. Clearing or replacing the selection invalidates the ranks.
This keeps the internal order unchanged. It creates no public index-order contract across backends.
Previous-frame matrices for motion vectors use dense selection indices with a generation guard, so playback never rebuilds path maps.
Plan, prefetch and payload tests#
Behavior |
Test |
|---|---|
Exact nested and reset transforms, prepared leaf presence, delta and full snapshot transitions, plan reuse by path-list identity, retained-query lifetimes |
Native instancing-graph tests: |
Lexical rank ties, the radix cutoff, invalid indices |
|
Parallel matrix windows, lifecycle interruptions, serial-to-parallel transitions |
|
Full deferred reports and outstanding borrowed buffers |
|
One shared face payload for a repeated triangle stream |
|
Preparation scheduler budgets and complete results |
|
Floating-point restoration around matrix windows and deferred outlines |
|
Selection keys, transform binding and tensor residency#
Accumulator keys. The dynamic accumulator groups records by pair identity
(source/OvstageClashPipeline.cpp):
A mesh-vs-mesh pair uses the ordered
(rank0, rank1)path ranks packed into 64 bits.A point-cloud pair, and a mesh pair without a current rank table, uses an owned
overlapPathKey()string: the pair type and both paths.The in-place pair radix sort in
source/MeshPathOrder.hskips the leading high-rank bytes that the selection size proves are zero.
Transform binding. The selected numeric plan binds world nodes by dense parent slot, not by
path. After it has bound every node, it calls releaseBindingLookups(). Repeated reads keep only
the dense world graph, the required-leaf indices, the query handles and the row lookup they use.
Direct matrix queries keep their own path maps and bind on demand.
Tensor residency. Tensor validation lists the dtype rules. The
transform readers add these checks (source/OvstageSceneReaderInternal.h,
source/OvstageTensorValidation.h):
An attribute tensor must be CPU-resident (
kDLCPU). Any other device fails before the payload is dereferenced. An empty CUDA synchronization descriptor does not prove that a tensor is on the CPU.A negative tensor rank is invalid metadata.
Every present
omni:resetXformStackrow holds exactly one byte. Missing or masked reset rows, and tombstones, keep their meaning of absence.Sparse map and mask coverage, and pending CUDA synchronization, are checked as Read validation and cleanup describes.