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

Comparing ovstage matrix decompositions

Selecting the decomposition mode from Python and C.

Performance: Dynamic runs

The matrix cache switch, the window sizes and the static purge that users see.

Runtime architecture: Numeric transform reads

The populations and the composition rules for numeric transform reads.

Engine performance internals

The BVH split, the scheduler budgets and narrow-phase reuse.

ovstage source extraction internals

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)

OVCLASH_OVSTAGE_MATRIX_DECOMPOSITION_OPENUSD

"openusd"

source/GfMatrixDecomposition.h

Parity with the OpenUSD backend

ovclash (legacy)

OVCLASH_OVSTAGE_MATRIX_DECOMPOSITION_OVCLASH

"ovclash"

source/OvclashMatrixDecomposition.h

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:

  1. 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.

  2. The Jacobi eigensolver on A * transpose(A), with the eigenvalues left in solver order (unsorted).

  3. Signed scales: the determinant’s sign goes on all three axes. An eigenvalue below 1e-10 becomes a scale of ±1e-10.

  4. Quaternion extraction, then the GfRotation axis-angle round trip through degrees and the GfQuatd normalization.

  5. 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_pipeline has 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_created and the step counters, then calls clearQueryResults(). 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 survives ovclash_reset_context and 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

Matrix decomposition requires 16 doubles

An element is not finite or exceeds the float range

Before

Matrix decomposition requires finite values within float range

The length of one of the first three rows exceeds the float range

Before

Matrix decomposition row magnitude exceeds float range

OPENUSD only: a translation, scale or quaternion value is not finite or exceeds the float range

After

Matrix decomposition produced an invalid translation, ... invalid scale or ... invalid rotation

PxTransform::isValid() fails (this includes the unit-quaternion test of PhysX) or the scale is not finite

After

Matrix decomposition produced an invalid pose or scale

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 GfTransform(matrix) on Windows x64

Exact

OpenUSD backend, any platform

The live platform GfTransform

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.cpp measures both modes with 1, 2, 4 and 8 workers. benchmarks/matrix_decomposition/README.md gives 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.py with the fixtures tests/data/numeric_transform_association.usda and tests/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.

Raw authored-transform classification and deferred matrix batches#

A run of a dynamic query with the static purge on (OVCLASH_SETTINGS_FLAG_PURGE_PERMANENT_STATIC_OVERLAPS, the default) classifies every selected mesh once, before the first sample. Each mesh becomes one of three TransformAnimationState values:

State

Meaning

Effect

Static

Every active transform operation on the mesh and its ancestors has an initial value, and none has more than one effective sample.

Its static pairs are purged. Playback keeps its first numeric pose.

Dynamic

An active operation on the mesh or an ancestor has more than one effective sample.

Tested and read at every sample.

Unresolved

An active operation has no initial value, and no other operation proves the mesh dynamic.

Treated as non-static and tested at every sample.

With the static purge off, the run skips classification and evaluates every matrix at every sample.

How the classifier works#

OvstageSceneReader::classifyStaticMeshes() in source/OvstageSceneReaderClassification.cpp never evaluates the whole timeline. For a file-backed stage:

  1. It opens a short-lived population with no built-in domains and two selectors: every property in the xformOp namespace, and xformOpOrder with its USD-default (default) metadata.

  2. It reads the initial values at population ordinal 1. It records each prim’s active ordered operations and which raw operations have a value.

  3. It applies the same numeric time again at ordinal 2. The time must not change: a later time can block a previously valid operation and drop its row.

  4. It reads only the raw operation update records between the two ordinals. ovstage publishes an update exactly for an initially valued operation with more than one effective composed sample. That includes constant animation (equal samples) and excludes a single sample and a default that masks weaker samples.

  5. It classifies each mesh and destroys the population. Only the mesh-aligned states survive.

Updates of the derived omni:xform rows are never an animation signal; only raw xformOp:* update records count.

With logging on (RunSettings(enable_log=True)), a complete classification prints one line, and the population counter shows the single file open and time update:

--ovstage: classified 2 meshes from raw transform update records (1 dynamic)
--ovstage: classification transform population operations: 1 file, 1 time update

Classification rules#

The rules follow the unchanged OpenUSD reference:

  • Active operations only. The classifier inspects the operations in xformOpOrder on the mesh and on every ancestor. An authored but unused sampled operation does not make a mesh animated.

  • Inverse operations (!invert! prefix) refer to their underlying attribute.

  • Resets. !resetXformStack! removes the local operations before it. The ancestor walk still continues, so a mesh below a reset can only be misclassified away from Static.

  • Instances. Instance proxy paths resolve through the classification population’s own prototype map, never through another population’s synthetic /__Prototype_* names.

  • Dynamic wins. An updated operation makes the mesh Dynamic at once. A missing initial value makes it Unresolved only when no other active operation proves it dynamic.

  • Missing update rows prove nothing. They are never treated as proof of static behavior.

  • Errors stay errors. API failures, malformed rows and synchronization failures fail the run.

  • Arrays in the namespace. No transform operation holds an array. An array-valued attribute such as int[] xformOp:c = [] only shares the namespace, so an empty value reads as absent instead of failing the run.

Existing-stage attachments#

A Stage attached with ovclash_ovstage_attach_stage() and a composition is classified like a file-backed stage, from a classification population of its own:

  • populateStageFromComposition() replays the composition into a fresh instance at the query start, with the two selectors of How the classifier works plus the root stage metadata. The population seals ordinal 1 for a root alone and 2 after merges (Attached-stage populations).

  • The prototype map is read at that sealed ordinal from the population itself, and the proxy-root check applies as for a file.

  • applyPopulationTime() applies the same time again at the sealed ordinal plus one, and the classifier reads the update records between the two ordinals.

  • The capability is never consulted and the owner is never called. Layer opinions take part as in a file: a layer Default that masks weaker samples leaves an operation with no update, and a layer xformOpOrder that activates an animated operation makes its mesh Dynamic.

  • A complete result enables the static purge and prefetch, as for a file.

Without a composition, the attached Stage is classified without another population, but only when its binding sets OVCLASH_OVSTAGE_CAP_AUTHORED_TRANSFORM_UPDATES (Python: attach_ovstage(..., authored_transform_updates=True)). The capabilities field of ovclash_ovstage_binding_t carries that bit; The binding descriptor lists the binding fields, and Authored transform updates gives the owner’s side.

  • The owner guarantees complete raw-operation and USD-default-order coverage, and update provenance that the population generated and nobody modified. ovclash_ovstage.h states the full contract.

  • The classifier records the attached committed ordinal and calls evaluate_time once more at the identical finite seconds. It then reads the retained update interval.

  • It fails when that interval is no longer retained, or when the prototype associations changed in between.

  • Canonical local and reset writes by the owner do not take part.

  • Without the capability, every attached mesh is Unresolved, so it stays non-static.

tests/sample_app_tests/test_attached_authored_transform_classification.py runs the literal file-path corpus through one real borrowed owner. Python OpenUSD (pxr) imports are blocked, and each owner opens its source exactly once.

Fallback for unresolved meshes#

When any mesh is Unresolved, the run prints this line with logging on:

--ovstage: an active transform op has no initial value; sampling validated numeric matrices while unresolved meshes remain non-static

prepareValidatedFallbackMatrices() in source/OvstageClashPipeline.cpp then works like this:

  • It samples the matrices of every selected mesh and point cloud at every sample and validates them.

  • It keeps the whole timeline in the matrix cache when the cache is on and the estimate fits the 1 GiB budget. The estimate is (meshes + point clouds) x samples x 128 bytes. Otherwise playback reads the matrices again.

  • It never decides that a mesh is static. Meshes with a conclusive raw Static state stay static, so a blocked sibling cannot undo another mesh’s classification. All other meshes stay non-static.

  • It does not use the bounded playback windows of Matrix windows during playback.

The fallback prevents false-negative purging. It does not claim complete authored-animation parity for every composed input.

Matrix windows during playback#

After a complete raw classification, playback reads matrices in bounded windows:

  • First sample. It reads the numeric pose of every selected mesh. Even a static mesh with one authored sample can differ from its USD-default pose. The context keeps this first pose once (dynamic_first_mesh_matrices).

  • Later samples. One numeric read covers the dynamic meshes and then all selected point clouds. Each frame stores the dynamic mesh matrices and, in a separate vector, the point-cloud matrices. Applying a frame scatters the dynamic rows through the immutable selection indices.

  • Static meshes. They keep their first numeric world matrix together with the pose, geometry scale and bounds computed from it.

Window sizes come from source/DynamicMatrixCacheLimit.h and source/OvstageClashContext.h:

Playback

Windows

Frames per window

Synchronous

One

Up to 32

With prefetch

Current and future

Up to 16 each, at most 32 together

Cache off, or the budget holds less than one frame

One working frame

1

Both windows share the fixed 1 GiB budget (kDynamicMatrixCacheDefaultByteLimit). One frame costs (dynamic meshes + point clouds) x 128 bytes, one ClashMatrix4d per prim. The first poses and the current working data are outside that budget.

Worked example: 2,000 meshes, all dynamic, over 1,000 samples.

Storage

Size

The whole timeline, as the fallback would cache it

2,000 x 1,000 x 128 bytes = about 244 MiB

One 32-frame window

2,000 x 32 x 128 bytes = about 7.8 MiB

The first poses

2,000 x 128 bytes = 250 KiB

These are matrix-array sizes, not process peak memory.

More rules:

  • No tuning channel. No environment variable changes the budget. Sentinel (scripts/run_sentinel.py) and the benchmark harness benchmarks.backend_timings remove OVCLASH_DYNAMIC_MATRIX_CACHE_MB from their child environments, so an inherited value never reaches a checked or measured child. The harness builds that environment with build_child_environment() in benchmarks/backend_timings/child.py. Only Sentinel’s private engine program (ovclash.sentinel_engine.test, built with OVCLASH_ENGINE_VALIDATION_OBSERVER) selects smaller budgets.

  • Reset. A query reset or a new selection clears the states and the windows.

  • Direct queries. A direct numeric matrix query joins the prefetch reader before it uses the source. It cannot change frames that were already copied, and it keeps the joined future window unless a source failure retires the selection population.

  • Measuring. Raw classification replaces the whole-timeline classification walk, and the matrix reads move into playback. Measure classification and playback together. The windows bound memory; they are not a speedup.

Floating-point controls and cached matrices#

A copied matrix window remembers the floating-point controls (rounding mode, denormal handling) it was composed under:

  • Changing the controls between sample steps invalidates a playback window. The whole-timeline fallback skips its saved matrices while the controls differ.

  • Accrued floating-point exception flags alone do not invalidate a cache.

  • Applying refreshed matrices keeps each raw-classified static mesh’s first numeric world matrix, pose, geometry scale and bounds. Unresolved and Dynamic meshes and point clouds use the current sampled matrices.

Cached and uncached evaluation therefore stay equivalent when a caller changes the controls.

Classification and window tests#

Behavior

Test

Sample thresholds, stronger defaults, constant samples, unused, inverse and reset operations, ancestors, instances, mixed conclusive and blocked selections, an empty array in the operation namespace, clip sample counts

tests/python_tests/test_authored_transform_classification.py

Window boundaries, the cache switch, exact poses, motion vectors, point clouds and interleaved direct queries

tests/python_tests/test_dynamic_matrix_batches.py

Compact scalar group decoding

tests/native/InstancingGraphReadCases.h

The same corpus through a real borrowed owner

tests/sample_app_tests/test_attached_authored_transform_classification.py

These predicates are qualified against the pinned ovstage runtime. Run these tests before you upgrade it.

Limitation: no test cancels deterministically inside a partially filled matrix window. The existing cancellation tests and the failed direct-query and retry tests during buffered playback cover the adjacent paths.

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() in source/OvstageSceneReaderQueries.cpp checks 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, so TransformPrefetchInputs::stagePath stays empty.

  • The raw classification is complete.

  • The matrix cache is on.

  • single_threaded is 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: with nb_tasks = 8 and 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_pipeline only 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.

Shared dynamic report payloads#

In a dynamic run, a pair’s new record shares the previous record’s immutable triangle payload when the ordered triangle pairs and the hard-contact membership are identical. Each record keeps its own time, counts, distances, depth and current and previous matrices.

  • Face indices are built once per shared payload, on first request.

  • Intersection outlines contain hard intersections only. Tolerance (soft) hits add face indices but no outline segments.

  • Outlines are built per record, from that record’s saved matrices.

  • The OPENUSD mode builds an outline under the floating-point controls of the thread that requests the report, because the OpenUSD reference recomputes every report. The legacy mode replays the complete controls saved at detection. The shared triangle-triangle test is sensitive to the rounding direction and to subnormal flushing on touching geometry. Replaying detection-time controls in the OPENUSD mode would therefore disagree with OpenUSD whenever the two sets of controls differ.

  • The previous controls are restored afterwards, also on exceptional exits (makeOverlapSegments() in source/OvstageClashTypes.h).

  • Each outline is cached in stable context-owned storage together with its controls. A report under other controls builds and keeps another outline, so earlier borrowed buffers stay valid. Callers must still release their reports.

Cost:

  • Counts-only runs build no outlines and no repeated face arrays.

  • ovclash_get_overlap_count reads the size of the accumulated groups between samples. It neither copies nor sorts the record history. Indexed detail reads publish that history on demand.

  • While the context’s cancellation flag is set, ovclash_get_overlap_count returns 0. ovclash_finish_pipeline and ovclash_reset_context clear the flag. A cancellation that arrives after the worker completed makes ovclash_finish_pipeline report an error, but it does not delete the results already produced.

  • Requesting every outline still costs work for every distinct record. Include that deferred report work when you measure such a client.

  • Payload sharing is exact and per pair. Rapidly changing triangle membership therefore keeps more storage than a stationary overlap.

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: tests/native/TestInstancingGraph.cpp and its InstancingGraph*Cases.h

Lexical rank ties, the radix cutoff, invalid indices

tests/native/TestMeshPathOrder.h (run by tests/native/TestNativeClash.cpp)

Parallel matrix windows, lifecycle interruptions, serial-to-parallel transitions

tests/python_tests/test_dynamic_matrix_batches.py

Full deferred reports and outstanding borrowed buffers

tests/python_tests/test_dynamic_report_payload_reuse.py

One shared face payload for a repeated triangle stream

tests/python_tests/test_result_payload_storage.py

Preparation scheduler budgets and complete results

tests/python_tests/test_parallel_phase_results.py

Floating-point restoration around matrix windows and deferred outlines

tests/native/TestOverlapReportFloatingPoint.cpp, tests/native/TestSamplingFloatingPoint.h

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.h skips 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:resetXformStack row 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.