Runtime Architecture#

This page of the Technical Guide explains how the two backends, the OpenUSD backend and the ovstage backend, which reads USD through the ovstage runtime, implement the canonical C ABI (application binary interface). It covers the pipeline steps, dynamic sample schedules, ovstage stage populations and transform reads, the ovstage lifecycle lock, and where overlap order comes from. The Architecture glossary defines the implementation terms, and Concepts the consumer vocabulary.

It is written for maintainers of source/. API consumers need the contracts that Canonical C ABI runtime links to, not this page.

Canonical C ABI runtime#

include/ovclash/ovclash.h declares the canonical C ABI. It is installed as <ovclash/ovclash.h>. Each build links exactly one backend. source/ovclash_capi_api.cpp defines the exported ovclash_* functions and forwards each one to that backend’s implementation in namespace omni::ovclash.

The consumer contract lives on these pages:

Topic

Canonical page

Status results, the three string getters, string views and input validation

C API conventions

Handles, report ownership, process-global state and threading rules

Threading and Ownership

The async guard, and the calls that stay legal while an async run is active

Asynchronous Pipelines

Behavior that differs by backend

Backends

Where each backend implements the ABI:

Backend

C ABI implementation

Detection work

OpenUSD

source/OpenUsdClashBackend.cpp

The shared clash engine, called through the IClashDetection2_* bridge (OpenUSD runtime path)

ovstage

source/OvstageClashBackend.cpp, source/OvstageClashBackendQueries.cpp, source/OvstageClashBackendReports.cpp

The ovclash-owned source/OvstageClash*.cpp units; every scene read goes through OvstageSceneReader (ovstage runtime path)

Pipeline steps#

Both backends build the same step plan and report the same step names. ovclash_create_pipeline returns the step count, and ovclash_get_pipeline_step_data fills an ovclash_step_data_t for one step (<ovclash/ovclash.h> declares both). The Python ClashRuntime.create_pipeline() returns one PipelineStepData per step, with step_index and name:

  • A static query (startTime == endTime) has 11 steps.

  • A dynamic query has one step per sample plus 7 fixed steps, so it has at least 8.

Steps 0 to 4 are the same for both query kinds. Step 5 differs: a static query computes global mesh data, and a dynamic query classifies meshes as static or dynamic. A dynamic query then runs one Running dynamic clash detection... step per sample and ends with Ending pipeline....

This example prints both plans for a stage with a time-sampled placement. It uses the test fixture tests/data/mesh_mesh_default_vs_time_zero_visibility_instanced.usda. Run it, like the other examples on this page, from tests/data/ with the ovclash packages importable, as Running the module from a source checkout shows. RunSettings lists the run-settings fields:

from ovclash import ClashRuntime, RunSettings

with ClashRuntime() as runtime:
    runtime.open_stage("mesh_mesh_default_vs_time_zero_visibility_instanced.usda")
    for label, end_time in (("static", 0.0), ("dynamic", 0.3)):
        runtime.set_run_settings(
            RunSettings(set_times=True, start_time=0.0, end_time=end_time, time_codes_per_second=10.0)
        )
        steps = runtime.create_pipeline()
        print(f"{label}: {len(steps)} steps")
        for step in steps:
            print(f"  {step.step_index:2d} {step.name}")

Output (the dynamic query has three samples; see Dynamic sample chronology):

static: 11 steps
   0 Releasing previous data...
   1 Finding meshes...
   2 Computing initial mesh data...
   3 Finding shared meshes...
   4 Cooking meshes...
   5 Computing global mesh data...
   6 Building BVH...
   7 Running broad-phase...
   8 Purging duplicates...
   9 Running narrow-phase...
  10 Processing results...
dynamic: 10 steps
   0 Releasing previous data...
   1 Finding meshes...
   2 Computing initial mesh data...
   3 Finding shared meshes...
   4 Cooking meshes...
   5 Static/dynamic classification...
   6 Running dynamic clash detection...
   7 Running dynamic clash detection...
   8 Running dynamic clash detection...
   9 Ending pipeline...

Two settings act at specific steps on both backends:

  • OVCLASH_SETTINGS_FLAG_PURGE_PERMANENT_STATIC_OVERLAPS acts only in dynamic queries. It enables the classification at step 5 and then drops mesh pairs whose meshes are both static. It does not filter a static query.

  • OVCLASH_SETTINGS_FLAG_IGNORE_REDUNDANT_OVERLAPS filters redundant pairs in the Purging duplicates... step of a static query.

OpenUSD runtime path#

The OpenUSD backend drives the shared clash engine through the IClashDetection2_* free functions. source/OpenUsdClashBackend.cpp declares them by hand. They are defined in source/usdclash/ClashDetection.cpp, which is part of the build-created view of the shared engine sources (Source tree). No header is shared, so each declaration must match its definition exactly.

This path never calls fillInterface. Only the internal C++ wrapper in source/NativeClash.cpp uses the omni::clashdetection::IClashDetection2 interface table that fillInterface fills (Internal OpenUSD C++ wrapper).

Call sequence:

  1. ovclash_create_context bootstraps Carbonite and carb.tasking. It then creates the engine instance with IClashDetection2_create. It seeds the engine from one default table: it fills an ovclash_settings_t with ovclash_reset_settings and applies it with ovclash_set_settings. That call drives every IClashDetection2_set* setter, including setSingleThreaded, and initializes the settings mirror that ovclash_get_settings reads.

  2. ovclash_open_stage drops the previous stage first and then calls pxr::UsdStage::Open. Reopening a path therefore reads the file again, unless another holder in the process keeps the layer open (Opening a stage). The call registers the new stage in StandaloneStageRegistry and pushes it to the engine with an empty scope.

  3. ovclash_set_scope_paths converts each path string to a pxr::SdfPath, encodes it as an engine path integer and passes both lists to IClashDetection2_setScope. A non-empty scope clears OVCLASH_SETTINGS_FLAG_FULL_SCENE.

  4. ovclash_create_pipeline checks the context and the async guard. It then calls IClashDetection2_createPipeline. Settings and scope reached the engine in the earlier calls.

  5. ovclash_run_pipeline_step runs one engine step.

  6. Result getters convert engine structs to the public C structs.

  7. Report calls let the engine fill an OverlapReport and copy its buffer pointers into the caller’s ovclash_overlap_report_t. ovclash_release_overlap_report hands the buffers back to the engine, which frees them.

StandaloneStageRegistry (source/StandaloneStageRegistry.h) is process-global. It maps generated uint64_t ids to pxr::UsdStageRefPtr values, so the shared engine resolves stages without Kit context services. Ids are never reused within a process.

Lifetime rules:

  • engineLifetimeMutex() serializes IClashDetection2_create and IClashDetection2_release across contexts. Each create initializes the process-global PhysX foundation and tasking state without a lock of its own. Concurrent OpenUSD contexts stay unsupported (What a context owns).

  • ovclash_release_context first finishes any active async handle, so it can block until the run ends (Releasing a context is not instant). It then unregisters the stage, releases the engine instance and deletes the context.

  • There is no context pooling or reuse. The Carbonite bootstrap stays for the process lifetime.

Dynamic sample chronology and ovstage schedule ownership#

Both backends compute dynamic sample times with the same recurrence:

  1. The first sample is exactly startTime.

  2. Each next time is the previous time plus 1.0 / rate, added in binary64 (IEEE 754 double precision).

  3. Sampling stops when the next time exceeds endTime.

There is no endpoint clamp and no epsilon correction. Rounding can exclude an endpoint that lies exactly on the grid in real arithmetic. Edge cases:

  • 0 to 0.3 at 10 samples per second has three samples. The third addition gives 0.30000000000000004, which exceeds 0.3.

  • A zero rate gives one startTime sample, because the step is infinite. A rate whose reciprocal overflows to infinity behaves the same.

  • A descending range (endTime < startTime) gives one startTime sample. The canonical C ABI accepts it; both Python packages reject it when they validate run settings.

This Python function reproduces the recurrence:

def sample_times(start: float, end: float, rate: float) -> list[float]:
    """Return the sample times of a dynamic query from start to end at rate samples per second."""
    step = float("inf") if rate == 0.0 else 1.0 / rate
    times = [start]
    current = start
    while current + step <= end:
        current += step
        times.append(current)
    return times


print(sample_times(0.0, 0.3, 10.0))  # [0.0, 0.1, 0.2]
print(sample_times(0.0, 1.0, 0.0))  # [0.0]

On OpenUSD, the shared clash engine builds the schedule in ClashDetectionContext::createPipeline. On ovstage, buildPipelineSamplingSchedule() in source/Sampling.h builds it once, when ovclash_create_pipeline succeeds:

  • The installed pipeline owns the schedule as an immutable snapshot of start, end and rate. A later settings change does not affect it. Only the next successful create replaces it.

  • Lookup by sample index takes constant time. Building and storing the schedule is linear in the sample count.

  • Step 0 clears results but keeps the schedule.

ovstage also rejects schedules it cannot represent:

  • Times must be finite and the rate must not be negative.

  • Conservative preflights reject schedules that provably need more steps than uint32_t holds. An append guard checks that the samples plus the 7 fixed steps fit.

  • A step that does not advance the time at binary64 precision fails the build.

  • No approximate count or resource limit decides which samples are included. Allocation can still fail for a very large valid schedule.

A failed create leaves the installed pipeline and the step-count output unchanged. It records a sticky error, and a later valid create recovers. The shared clash engine of the OpenUSD reference has none of these checks, so validation must not give it unbounded or non-progressing schedules.

The query rate is samples per second. It is not the stage’s time-code rate. Result times are seconds. On OpenUSD, the shared clash engine multiplies a sample time by the stage’s timeCodesPerSecond to read poses; ovstage populations take seconds directly. Time sampling has the consumer rules.

ovstage runtime path#

The ovstage backend is implemented by the source/OvstageClash*.cpp units. Its C ABI entry points are in OvstageClashBackend.cpp, OvstageClashBackendQueries.cpp and OvstageClashBackendReports.cpp. Every scene read goes through OvstageSceneReader (source/OvstageSceneReader*.cpp).

Call sequence:

  1. ovclash_open_stage checks that the file exists. It opens and keeps the selection population (Stage populations), and it records the stage timeline that ovclash_get_stage_timeline_data reports.

  2. ovclash_set_settings stores the ovclash_settings_t fields and clears the scope, as OpenUSD does.

  3. ovclash_set_scope_paths validates and stores the path strings (Scope matching). A non-empty scope clears OVCLASH_SETTINGS_FLAG_FULL_SCENE.

  4. ovclash_create_pipeline builds the sample schedule, sets the step count and marks the pipeline created. It does not clear previous results.

  5. ovclash_run_pipeline_step is truly incremental. Each index runs only its own work:

    • Step 0 clears the query results and the error text. It keeps the source populations.

    • Steps 1 to 4 select meshes, compute initial mesh data, search shared meshes (pose-free) and cook.

    • Static step 5 refreshes the transforms at the requested pose, finds duplicate meshes at that pose and computes global mesh data. Dynamic step 5 initializes the dynamic run, including the static/dynamic classification.

    • Static steps 6 to 10 build the BVH (bounding volume hierarchy), run the broad phase, purge duplicate pairs, run the narrow phase and publish the results. With OVCLASH_SETTINGS_FLAG_ONLY_FIND_DUPLICATES, step 6 ends the run.

    • Each dynamic sample step evaluates one sample. The final step consolidates the accumulated records.

  6. ovclash_run_pipeline_async runs the same work on a worker thread through executePipeline(). Only the async worker uses that whole-run function.

A direct step-1 selection advances the extraction generation. Aggregate counts survive. Old overlap and duplicate details, reports, depth, motion and depenetration then fail as stale until the current generation publishes its own results.

Dynamic runs refresh the selected transforms for every sample and consolidate time-keyed overlap records. Reusing transform setup and dynamic report storage describes how records share storage. Mesh face lists and outline segments are built only when a report call asks for them. Public reports expose context-owned buffers.

Scope matching#

Both backends assign a mesh that matches both scope lists to the first list only. A two-scope mesh query therefore compares A against B minus A. Identical scopes select their meshes once but produce no mesh-vs-mesh pairs.

ovstage matching:

  • A scope list of more than eight paths is matched through a prefix index (ScopePathIndex in source/ScopePathIndex.h). It does one hash probe per /-delimited path prefix, up to the length of the longest scope. Shorter lists use a linear scan.

  • The combined A+B population scopes are deduplicated with a hash set.

  • Source-layer population indexes include-scope lists of more than eight paths the same way, with scene_reader_detail::IncludeScopeIndex in source/OvstageSceneReaderInternal.h. It keeps the pathMatchesRoot semantics: empty, / and trailing-/ scopes are still scanned. It serves mesh collection, scoped visibility, instance-proxy expansion and the default-points candidate filter.

Source extraction and immediate queries#

OvstageSceneReader::populateFromFile and populateFromFileCached load the file into an ovstage instance with ovstage_population_open_usd_from_file_with_desc. They query Mesh and Points prims, resolve paths through the ovstage path dictionary, read the required attributes and produce ClashSourceMesh and point-cloud values. Then:

  • Points prims are read only when point clouds are active. Selection passes pointCloudsActive() as includePointClouds, so a malformed cloud cannot fail a mesh-only run.

  • Mesh collection also admits prototype-space meshes, which no caller scope can match. expandInstanceProxies() replaces each one with one mesh per instance root, under instance proxy paths. The pose is protoSpace(mesh) * world(instanceRoot), except that a reset (resetXformStack) in the prototype-space segment also drops the instance placement.

  • Point-cloud collection has no such expansion. It drops prototype-space clouds.

  • The runtime triangulates mesh faces, cooks or reuses PhysX triangle meshes, computes bounds and finds candidate mesh or point-cloud pairs.

ovstage source extraction internals describes the census, visibility and Earliest-topology recovery in detail.

The file-backed immediate queries ovclash_imm_compute_max_local_depth and ovclash_imm_depenetrate_meshes avoid a second population:

  1. They join the transform prefetch reader.

  2. They extract their two meshes from the default-time selection population that ovclash_open_stage keeps (readCachedImmediateMeshes). They leave the selection’s proxy identities, path handles and numeric state untouched.

  3. Only when no matching default-time population exists do they populate a temporary mesh-only source.

An attached stage serves them through readAttachedImmediateMeshes, from the owner’s Stage at the Default time, with or without a composition.

Async progress#

PipelineProgress (source/PipelineProgress.h) keeps one progress snapshot per context: the step index, an operation label and a fraction. The consumer view is in Asynchronous Pipelines.

  • Each phase reserves a fraction range. Retired work items (meshes, geometry, pairs or sampled frames) move the fraction within that range.

  • Workers count retirements in a stack-owned Batch and add them to the shared atomic counter at most 64 at a time. A range with fewer than 64 items publishes each item.

  • Partial batches flush on completion, cancellation and exceptions, before the next range starts.

  • Triangulation and cooking publish every retired item, because each item is expensive.

  • Opaque source reads, BVH creation and sorting publish an operation label only.

  • A mutex protects the snapshot metadata. Storage is constant per context plus one small counter per active worker. No thread-local state is retained.

The C API returns names as borrowed static literals. Planned step names (ovclash_get_pipeline_step_data) never change. An async step name can append the current operation, for example Running broad-phase... Querying bounds. The Suite forwards only the overall fraction, so a caller derives the step fraction as progress * nbSteps - stepIndex. The canonical Python binding exposes step_progress directly. OpenUSD gets work-item progress from its engine. Neither backend’s fraction estimates remaining time.

Stage populations#

An ovstage population is one load of the USD file into an ovstage instance. Its rows are written at an ordinal, ovstage’s ordering key for writes and reads. The selection population uses the RENDERING domain; some populations read at Earliest, USD’s earliest authored sample. A file-backed context uses several populations, each with one role:

Population

Opened by

Time

Contents

Lifetime

Selection

ovclash_open_stage

USD default time

RENDERING domain. Fixes mesh identity, geometry, selection-time visibility and synthesized instance-proxy paths. The first extraction with subcomponent filtering repopulates it with a kind-only selector at a newer ordinal, still at default time, when that adds no prims (Subcomponent kinds).

Until the source is invalidated (Source invalidation). Never advances in time.

Numeric transform

The first finite-time transform read, or a static run’s selection (at Earliest)

One exact finite time; advances forward

domains=NONE, selector IS_A(Mesh, Points) OR HAS_PROPERTY(xformOpOrder) with no property predicate. Never loads selection geometry.

Same as selection. Also reopened on a rewind or a failure (Numeric population state).

Raw-op classification

Dynamic step 5, when OVCLASH_SETTINGS_FLAG_PURGE_PERMANENT_STATIC_OVERLAPS is set

The query start

Raw xformOp:* properties and xformOpOrder

Destroyed after the classification (Raw authored-transform classification)

Earliest topology

Extraction, for meshes without default-time points, when the numeric population cannot serve them

Earliest

Topology of the affected meshes

Destroyed after the read (Earliest-topology recovery)

Subcomponent kinds

Extraction with subcomponent filtering, when the selection’s kind repopulation was rejected or the read is noncached

USD default time

domains=NONE, a HAS_KIND(subcomponent) selector with only the kind metadata

Destroyed after the read (Subcomponent kinds)

The selection population never advances in time. On the pinned runtime, applying a time to it can leave an invisible instance root at its stale default-time transform. Every finite-time read therefore uses the numeric population.

Keep the RENDERING selection recipe (requirement). Do not add selectors to the selection population to obtain local or reset columns: a selector populates every prim it selects, with its ancestors and instance links, but publishes no world rows for prims that the RENDERING domain skipped. In the pinned runtime, RENDERING publishes the reset metadata, and regression tests protect that. The pinned ovstage header ovstage/ovstage_population.h guarantees derived local and reset values only for PHYSICS or selector populations. The one selector the selection accepts is the kind-only repopulation, and only when it adds no prims or instance roots: on the pinned runtime it keeps the RENDERING prototype identities (testSubcomponentRepopulationPreservesInstancing, testInstancedKindsKeepPlacements), and the reader rejects any repopulation that grows the selection (testSubcomponentRepopulationRejectsAddedPrims).

Attached-stage populations#

An attached stage (ovclash_ovstage_attach_stage) replaces the selection population with the owner’s Stage. The Earliest-topology and subcomponent-kind populations never run for it. What serves finite times depends on the binding’s optional composition:

Attachment

Default time

Finite times

Raw-op classification

Owner-evaluated (no composition)

The owner’s Stage

The owner’s Stage, after evaluate_time publishes the time. ovclash creates no population.

From the owner’s update records, only with OVCLASH_OVSTAGE_CAP_AUTHORED_TRANSFORM_UPDATES (Existing-stage attachments)

Engine-evaluated (a composition)

The owner’s Stage at committed_ordinal

An engine numeric transform population, replayed from the composition, with the selectors and lifetime of the file-backed one

An engine classification population, replayed from the composition

populateStageFromComposition() in source/OvstageSceneReaderComposition.cpp replays a composition into a fresh instance, in one lifecycle-lock scope:

  1. A root without layers opens with the population’s description at ordinal 1, exactly as a file population does (open_usd_from_file_with_desc, or open_usd_from_string_with_desc for a USDA root), and seals ordinal 1.

  2. With layers, the root opens at ordinal 1 with no description. A row that the open wrote would survive the repopulation, which removes nothing, even after a layer deactivated its prim or blocked its operation. The open completes before the merges, which need its population state.

  3. Each layer merges with add_usd_reference_from_string(stage, text, "/"), in the composition’s order, so a later layer is stronger.

  4. One repopulate_usd_with_desc at ordinal 2 writes every selected row from the composed source and sets the scope of later apply_usd_time calls. Operations on one instance run in order, so one wait covers the merges and the repopulation. A failure names its step (ovstage composition root, layer <i> or repopulation) with ovstage’s text. The population seals ordinal 2.

The root counts as one file population in the diagnostics, and each merge in the white-box compositionLayerMerges metric. Engine populations also request the root stage metadata metersPerUnit, timeCodesPerSecond and framesPerSecond. The first one compares it with the binding once per attachment (checkCompositionStageMetadata(); Direct transform queries gives the rate rule).

Requirements on engine populations:

  • Never touch owner state from a selected-geometry, classification or matrix-prefetch read. Such a read of an engine population never writes the owner’s stage pointer, its Default ordinal, its population time or its prototype map, and never calls evaluateAttachedStage() or ensureSelectionPrototypeAssociations(). The prefetch worker therefore reads only engine numeric state, the read-only instance-proxy sources and the immutable shared composition.

  • A finite direct query (PrimMatrixReadRole::DirectExistingPrim) is the one exception. Before it reads the engine population, the calling thread calls evaluateAttachedStage(NaN) and ensureSelectionPrototypeAssociations(). They revalidate that the owner still retains committed_ordinal and read its prototype associations, which prove identity leaves (Direct transform queries). The prefetch worker never makes these calls.

  • Keep owner and engine plans apart. A plan holds query handles of one stage. Default reads on the owner use their own plan slot (mOwnerDefaultPlan), which reset() retires while the owner is still attached.

  • Join populations only through scene-path instance roots. Prototype maps stay population-local, as between file-backed populations, and validateInstanceRoots still checks the owner’s expansion.

  • Keep the composition immutable once shared. reset() keeps it, so ovclash_release_memory replays it again; detach, replacement and a context reset drop it. After a reset, the next Default read revalidates that the owner still retains committed_ordinal.

The replay relies on ovstage behavior that the pinned header does not document: an open without descriptions that accepts root merges, the time-application scope that the repopulation sets, merge strength, the survival of root stage metadata across merges, raw-op update records under a layer Default that masks weaker samples, and no row or write-floor change in another instance. testCompositionReplayProbe in tests/native/InstancingGraphAttachedCompositionCases.h pins each of them on the pinned runtime. Run it first after an ovstage upgrade.

Default-time transform reads#

Reads from the default-time selection population follow these rules:

  • A world matrix comes from the published world rows: omni:fabric:worldMatrix first, then worldMatrix. A path without a world row composes its local rows: omni:fabric:localMatrix first, then omni:xform.

  • The row readers apply the ovstage prims.index_map and data.index_map mappings before they associate matrices with paths.

  • Instance roots use the tolerant PublishedWorldTolerant read. An identity root may legitimately have no matrix row.

  • Default queries resolve proxy ownership before they choose a row, whether or not selection ran. The pinned RENDERING population can publish a proxy world row that omits prototype-internal ancestors. Reading the real prototype operand and resolving its instance root avoids that row. The default population keeps only its root/prototype identity map for this.

Numeric transform reads#

One lazy numeric transform population serves all finite-time reads:

  • static transform refresh;

  • dynamic playback;

  • the sampled-classification fallback;

  • finite-time ovclash_get_prim_matrix calls.

Its selector publishes the complete ancestor chain of every Mesh and Points prim, including typed, typeless and Scope ancestors. Numeric population covers the optional topology selectors and when they force a reopen.

A transform refresh reads every matrix it needs, for meshes and point clouds alike, in one batched call. Never populate the stage again to read one prim’s matrix: that costs a full stage population per prim. A path missing from the batch is an identity or time mismatch; fix it in the batched reader.

Composition rules:

  • Mesh and Points reads use the canonical local row omni:xform and omni:resetXformStack. They never use authored or derived world-matrix aliases. Reason: the pinned runtime can leave a Mesh world row stale when a non-xformable identity ancestor interrupts hierarchy traversal.

  • Batched reads cover the ancestor closure.

  • Each parent world is complete before the child’s local is multiplied in. Each element is the sum of the four ordered products of Gf, OpenUSD’s math library, with no leading zero accumulator, so signed zeros survive. Finite numeric transform reference shows why this association matters.

  • Real identity ancestors stay in the product sequence. The pseudo-root and the synthetic prototype root add no identity multiplication.

  • A reset replaces the accumulated parent world.

  • A completed world belongs to one logical instance placement. A nested suffix starts from its enclosing placement’s world.

  • A selected Mesh or Points operand without a valid canonical local row is a strict error. Malformed or non-finite numeric canonical rows fail closed.

  • Local matrices, reset flags and prototype metadata are read at the sealed population ordinal. Numeric playback skips the hierarchy pass that would only produce unused world-matrix columns.

Instance roots and proxies:

  • Real and nested-prototype instance roots use the same canonical-local and reset composition. Their leaf policy is identity-tolerant: a root without its own local row inherits its valid ancestor transforms instead of failing. A stale published root world row therefore cannot drop a transform above typed, typeless or Scope identity links.

  • The numeric population associates the retained real instance roots with its own prototype roots. It rebases stable proxy suffixes and resolves nested roots shortest-first. Each prototype-to-root join keeps any reset found within the child segment.

  • Synthesized /__Prototype_* paths are population-local. Numeric reads never use them in another population, and they never move or reopen the default selection population.

  • Never use default-time published-world operands in numeric composition.

TransformSegment keeps a matrix together with a flag that says whether the segment reset the transform stack. joinTransformSegments() in source/OvstageSceneReaderTransforms.cpp joins a child segment to its parent:

TransformSegment joinTransformSegments(const TransformSegment& child, const TransformSegment& parent)
{
    if (child.resetsAncestorStack)
    {
        return child; // a reset below the join ignores everything above it
    }
    return { multiplyMatrices(child.matrix, parent.matrix), parent.resetsAncestorStack };
}

Reset flags are read at the matrix’s own population ordinal and are never cached by path. The same rule applies to the initial mesh expansion, default queries, numeric direct queries and the selected-geometry refresh.

Direct transform queries#

ovclash_get_prim_matrix takes a USD time code. Its contract is in Reading a transform. On ovstage:

  • The call joins any running matrix-prefetch callback before it reads the source.

  • A finite time reads the numeric population through a separate internal read role. The default selection population does not change, and the normal numeric transitions apply (Numeric population state).

  • A non-finite time reads the default-time selection population.

  • On an attachment with a composition, a non-finite time reads the owner’s Stage at committed_ordinal through the owner’s Default plan, and a finite time reads the engine numeric population. Before a finite read, the calling thread prepares the owner’s Default snapshot and its prototype associations. That snapshot then proves identity leaves, as the selection population does for a file. The prefetch worker never prepares it.

The USD time code is converted to population seconds with the effective stage rate that the selection population keeps:

  1. authored timeCodesPerSecond;

  2. otherwise authored framesPerSecond;

  3. otherwise 24.

ovstage’s generic metadata includes schema defaults, so timeCodesPerSecond = 24 cannot tell an authored 24 from the fallback. When the metadata reports 24 together with a different framesPerSecond, opening the selection population also opens a separate RENDERING probe population at one second. The probe’s lastGlobalTime on /__Fabric_StageInfo is the resolved rate.

Conversion rules:

  • The resolved rate must be positive and finite.

  • The conversion fails when a finite time code overflows population seconds, or when a nonzero time code underflows to zero seconds. The error is USD time code cannot be represented as finite population seconds.

  • It works for text and binary stages. It never infers metadata by scanning root-layer text.

  • When the numeric population’s time multiplied by the rate equals the requested time code exactly, the query reuses that time. Dividing the time code again could round backward and reopen the population needlessly.

  • An attached stage uses the rate that its binding supplies.

  • An attachment with a composition checks the binding once, at its first engine population, against that population’s root stage metadata. metersPerUnit (authored, or the 0.01 fallback) must equal the binding’s exactly, and so must a rate other than 24. A rate of 24 with framesPerSecond 24 requires 24. A rate of 24 with a framesPerSecond F other than 24 is ambiguous: the check accepts 24 or F and marks the attachment. Sampling passes seconds and needs no rate. Before the first finite direct query by time code on a marked attachment, proveCompositionTimeCodesPerSecond() resolves the rate with a RENDERING rate probe, as for a selection population, opened on the composition root alone, and fails unless it equals the binding’s. The error reads Attached ovstage composition resolves <field> <value>, but the binding reports <value>.

  • A mismatch from either check is latched with that message for the composition. Every later finite-time read, time-code conversion and classification on the attachment then fails with the same message before it creates an instance or replays anything, so a disproved ambiguous rate fails sampling and classification too. ovclash_release_memory() keeps the latch; detaching clears it, and the next attach checks its own composition. A failed replay or metadata read, which may be transient, such as an unreachable network root, is not latched, and the next finite-time read replays again.

ovclash_get_stage_timeline_data and its Suite and Python wrappers report the same effective rate. They read the snapshot taken when the stage was opened, which costs no stage read or population.

This example reads the rate and a nested instance-proxy transform at USD time code 1, again on tests/data/mesh_mesh_default_vs_time_zero_visibility_instanced.usda. Run it from tests/data/:

from ovclash_suite import ClashDetection

clash = ClashDetection()
try:
    clash.open_stage("mesh_mesh_default_vs_time_zero_visibility_instanced.usda")
    rate = clash.get_stage_timeline().time_codes_per_second
    matrix = clash.get_prim_matrix("/World/PlacementB/Group/Nested/Cube", 1.0)  # a USD time code
    print(f"stage rate: {rate}; translation x at time code 1: {matrix[3][0]}")
finally:
    clash.destroy()
stage rate: 1.0; translation x at time code 1: 25.0

A finite direct query proves that the requested prim exists, including identity and instance-proxy prims:

  • An exact usd-prim-type row in the numeric population, or in the already-open default population, proves existence.

  • Empty instance-proxy Scope prims and typeless leaves can be absent from the numeric selectors. Their default-population counterparts are found through the authored instance root and that population’s own prototype map.

  • Sparse typeless exception: when both type rows are absent, only a valid, finite, complete identity omni:xform row at the exact default counterpart proves existence. That row never supplies the pose; the numeric canonical locals and resets still compose the requested sample. Missing paths, malformed or non-finite rows and non-identity default rows never qualify.

  • A Mesh or Points type in either population always requires a valid numeric leaf row.

  • Before selection runs, a direct proxy path is resolved by a slash-delimited nearest-root lookup in the current numeric root/prototype associations. Every required root must pass the real-root or one-hop prototype-content check that extraction uses, and the rebased target must pass the existence rules of this list. This lookup does not populate or change the selection-owned proxy map and adds no population operations.

A missing prim fails with Failed to query prim transform: <path> and leaves both populations intact. A read or resource failure that retires the selection population also invalidates its selected-table details and the installed pipeline.

Numeric population state#

The numeric population is keyed by the exact stored stage path, the source generation and the exact finite double time. There is no epsilon equivalence. An attachment with a composition keys it by the composition’s generation instead of a path.

Request

Effect

File / time operations

First read

Opens and seals population ordinal 1 at the requested time (ordinal 2 for a composition with layers; see Attached-stage populations)

1 file, 0 time update

The same exact time

No operation

0 file, 0 time update

A strictly later time

Applies the time at the previous read ordinal plus one

0 file, 1 time update

An earlier time (rewind)

Destroys the population and reopens it at the requested time

1 file, 0 time update

Open, apply or read failure

Destroys only the numeric population. The selection population stays for diagnostics and retry.

–

A later finite advance can also reopen the population when its topology selectors observed geometry updates (Numeric population).

Population diagnostics#

With OVCLASH_SETTINGS_FLAG_LOG (RunSettings.enable_log in Python), ovstage prints three separate counters per run:

  • selection-population file and time operations;

  • transform-population file and time operations;

  • successful geometry-extraction passes.

The transform counter is labelled transform for pipeline reads, classification transform for the raw-op classification, and prim-matrix selection or prim-matrix transform for direct queries.

This example runs a static query four times on one context: first run, the same time, a later time, then a rewind. Run it from tests/data/ on an ovstage build:

from ovclash import ClashRuntime, RunSettings

with ClashRuntime() as runtime:
    runtime.open_stage("mesh_mesh_default_vs_time_zero_visibility_instanced.usda")
    for time in (0.0, 0.0, 1.0, 0.0):
        runtime.set_run_settings(
            RunSettings(enable_log=True, set_times=True, start_time=time, end_time=time, time_codes_per_second=1.0)
        )
        runtime.set_scope(["/World/PlacementA"], ["/World/PlacementB"])
        runtime.run_pipeline()

The population lines of the output:

--ovstage: selection population operations: 0 file, 0 time update
--ovstage: geometry extraction operations: 1
--ovstage: transform population operations: 0 file, 1 time update
--ovstage: selection population operations: 0 file, 0 time update
--ovstage: geometry extraction operations: 1
--ovstage: transform population operations: 0 file, 0 time update
--ovstage: selection population operations: 0 file, 0 time update
--ovstage: geometry extraction operations: 1
--ovstage: transform population operations: 0 file, 1 time update
--ovstage: selection population operations: 0 file, 0 time update
--ovstage: geometry extraction operations: 1
--ovstage: transform population operations: 1 file, 0 time update

Expected counts (selection, then transform):

Situation

Selection

Transform

First static run after ovclash_open_stage

0/0

0/1. Selection already opened the numeric population at Earliest (Earliest-topology recovery), so the transform read only advances it.

First static run with single_threaded, when selection needs no Earliest recovery

0/0

1/0. The first transform read opens the population.

Static run again at the same time

0/0

0/0

Scope or visibility change at the same time

0/0

0/0

First run after ovclash_reset_context or ovclash_release_memory

1/0

0/1

Raw-op classification of a dynamic run

–

classification transform 1/1, for any timeline length

Fresh two-sample dynamic run, dynamic matrix cache on

–

1/1, then 0/0

Fresh two-sample dynamic run, dynamic matrix cache off

–

1/0, then 0/1

Every run performs exactly one extraction, also after a scope or visibility change. A later query can reuse an existing numeric population at the same start time.

On an attachment with a composition, the engine transform and classification populations count as file populations, and the selection counter stays 0/0: the owner’s Stage is read, never populated or advanced. No selection-time Earliest population runs, so the first transform read of a static run opens (replays) the engine population and logs 1 file, 0 time update, as in the single_threaded row. ovclash_release_memory keeps the composition, so the first static run after it logs the same; ovclash_reset_context detaches the Stage. Dynamic-run and classification counts match the file-backed rows. Python switches the dynamic matrix cache with ClashRuntime.set_ovstage_dynamic_matrix_cache().

Source invalidation#

These operations destroy both the selection and the numeric population, and clear the extraction and proxy state:

  • a stage replacement, successful or failed, including the same path spelling;

  • ovclash_reset_context;

  • ovclash_release_memory;

  • an explicit source clear;

  • context destruction.

Reset and release keep the logical stage path: the ovclash_reset_context entry of the C API reference states it, and its ovclash_release_memory entry leaves the context ready to run again. The next use reopens the source. A replacement keeps the aggregate counts, but its extraction-generation change makes every retained table-indexed detail stale. A failed replacement cannot expose old details or matrices. A successful run stamps overlap and duplicate results separately, so newly published duplicates never revalidate older overlaps.

Runtime compatibility check#

OvstageSceneReader checks the loaded ovstage runtime once per process (checkOvstageCompatibilityOnce()):

  1. It creates a probe instance.

  2. It requires the ovstage API major and minor version that ovclash was built against. The version is compared before any vtable slot appended after get_version is read, because a runtime of another minor version may end its vtable earlier.

  3. It requires the ovstage v2 data-plane slots that an attached stage must also provide, plus advance_write_floor, which only owned populations use.

  4. It requires a path dictionary.

An incompatible runtime fails every file-backed population. The message names the reason, for example a version mismatch:

incompatible ovstage runtime <major>.<minor>.<patch>: API version is not <major>.<minor>. ovclash requires the ovstage v2 population, query/read, and path dictionary APIs.

The result is cached for the process. A failed probe-instance creation is not cached, so a later call retries.

Lifecycle lock#

ovstage guarantees thread safety only for calls on one instance. Lifecycle operations on different instances share process-global state: OpenUSD layer-change notices, the USDRT population notice handler, and the Fabric and USDRT registries. Running them concurrently corrupts the heap.

The process-wide ovstageLifecycleMutex() therefore serializes these operations across contexts:

  • ovstage_create_instance and ovstage_destroy_instance;

  • every population (selection, subcomponent-kind, classification, numeric and the rate probe), including the wait for the operation and the write-floor advance;

  • the replay of an attached composition: the open, every layer merge, the repopulation, their wait and the write-floor advance, in one lock scope;

  • ovstage_population_apply_usd_time;

  • owner operations (ovclash_ovstage_run_owner_operation) and the opt-in retained-source read_snapshot requests;

  • the one-time retry configuration of the omni client.

Ordinary queries and attribute reads on a populated instance are not serialized.

Rules for maintainers:

  • Never call destroyStage(), or a reset that reaches it, while you hold the lock. It takes the lock itself.

  • Do not pin the runtime with ovstage_initialize() instead. It only counts a reference and does not touch the shared state.

  • Population destruction is slow and runs under this lock (ovstage static source extraction).

ovstage integration describes what the lock means for a caller that owns its stage.

Tensor validation#

Before it converts any data, the reader validates each tensor’s dtype:

Attribute

Required dtype

Mesh points

float32

faceVertexIndices, faceVertexCounts, holeIndices

int32

World and local matrix attributes

float64, 16 values per row

omni:resetXformStack

8-bit bool

A tensor must also be CPU-resident and have compact strides. A mismatch fails the load with an attribute-specific message, and the data is never reinterpreted as another element type:

ovstage attribute has unexpected tensor dtype for <attribute> (code=<DLPack type code>, bits=<bits>, lanes=<lanes>)

Regression coverage#

Behavior

Test

Population operation counts for static reuse, dynamic playback, direct reads and the source lifecycle

tests/python_tests/test_static_population_reuse.py and the population cases of ovclash.instancing_graph.test

Resets across instance boundaries: times 0 -> 1 -> 0, reset-only identity roots, three nested instance levels, moving collision witnesses below a reset

tests/python_tests/test_instance_reset_transforms.py

Default-time instance identity during numeric playback, on the fixture mesh_mesh_default_vs_time_zero_visibility_instanced.usda

testDynamicNumericPopulationPreservesDefaultTimeInstanceIdentity in tests/native/TestNativeTransforms.cpp

The lifecycle lock under parallel contexts

testStageTimelineDataFromParallelContexts in tests/native/TestNativePipeline.cpp

The fixture tests/data/mesh_mesh_default_vs_time_zero_visibility_instanced.usda authors the same Tx=25 sample at times 0 and 1 on a placement whose default-time value is Tx=500. The second sample keeps OpenUSD’s one-authored-sample static classification out of the way without changing the default-time value, the numeric pose or the visibility case. The native test requires one group with two records, stable PlacementA and PlacementB proxy names, and Tx=25 for PlacementB. It checks this for both visibility settings, both static-purge settings, and the ovstage dynamic matrix cache on and off.

Error handling, ownership and threading#

Status codes and error channels are documented in the C API conventions, and Python exceptions in Python exceptions. Threading and Ownership covers handle ownership, the threading controls and the borrowed-memory rules. This section explains where the overlap order comes from.

Overlap report ordering#

The overlap-group index passed to ovclash_get_overlap_data is an identifier, not a rank. The consumer contract is Overlap index order is not contractual. Threading controls and result order lists what stays invariant under the threading controls.

These operations can change which group occupies an index: dynamic publication, hash growth, permanent-overlap purge, reset and a separate run. After any of them, find a group again by its normalized name0/name1, pair type and hash. Do not keep an index as a group’s identity.

On ovstage, both schedulers keep one index order. Workers collect sparse narrow-phase results in any order. Canonical path-rank sorts then restore the same order under every scheduler:

  • MeshPathOrder::sortPairsInPlace for mesh pairs;

  • the candidate order for point-cloud hits;

  • sortOverlaps() before publication.

Parallel cooking and narrow phase describes the schedulers.

On OpenUSD, the new scheduler (new_task_manager on) gives a run-dependent order when multithreading is on and the runtime tasking interface is available. OVCLASH_SETTINGS_FLAG_DEFAULT selects it. The engine parts involved:

Engine part

Effect on order

ClashDetectionCore::processResults

Concatenates the per-thread reports in report order. It stores a sortMode key with each overlap, but the engine never sorts by it.

Legacy scheduler (MultiThreader)

Gives each task a contiguous range of the broad-phase pair array and creates its report up front. Concatenation rebuilds broad-phase order for any nb_tasks.

New scheduler (runTasks)

Every Carbonite worker pulls pair indices from one shared PxAtomicIncrement counter, so the concatenation follows thread scheduling. It never reads MultithreadParams::mNbTasks.

Do not sort in OpenUsdClashBackend.cpp (requirement):

  • The parity reference would become more ordered than the engine it mirrors.

  • It would not give cross-backend determinism either. ovstage reports its own order, which OpenUSD does not reproduce pair for pair, even single-threaded.

A deterministic order, if it is ever required, belongs in ClashDetectionCore behind an explicit setting. It must apply to both backends and be specified in the header.

testThreadingControlsDoNotChangeOverlapSet (tests/native/TestNativeContracts.cpp) pins the counts, the membership and the per-pair payload for every threading configuration on both backends. It also pins the index order where it is guaranteed: on both backends with the legacy scheduler at any task count, and on ovstage always. It asserts nothing about OpenUSD order under the new scheduler. A membership or payload difference is a defect; a change in that order is not.