Performance#
This guide helps when a clash run takes too long or uses too much memory. It shows what to measure
first and which settings to change. Each setting is named by its C setter on the
canonical API, in <ovclash/ovclash.h>. Setting names
maps those names to the Suite API and Python layers, and
Settings lists every setting with its default, unit and effect.
Two rules apply to every setting:
Configure settings before
ovclash_create_pipeline(), and keep them unchanged while its steps run. Changing a setting never alters results already computed.Some settings are read when the run selects or cooks meshes, such as
ignore_invisible_primsandtris_per_leaf. A change takes effect on the next run.
The threading settings also control report extraction and fetch-and-save
frame preparation after detection. To fetch with different threading, change them after detection
and before fetch-and-save begins (ovclash_suite_runtime_fetch_and_save_begin() or
ovclash_suite_runtime_fetch_and_save_async()). The Suite runtime rejects settings changes until
that operation is destroyed.
Setting names#
A field of ovclash_suite_run_settings_t is usually named after its canonical setter without the
ovclash_set_ prefix, for example any_hit and tris_per_leaf. The Suite Python SettingId
usually adds SETTING_ and uses upper case, for example SETTING_ANY_HIT.
Names in each API lists every name on each surface, including
the exceptions, such as SETTING_FILTER_TEST for subcomponent filtering and
the Suite’s offset
depth-mode scale.
The ovclash Python RunSettings models only a subset: the threading controls, tolerance,
max_local_depth_mode, the sample times and a few flags.
ovclash Python gives the type and default of each of its fields.
ClashRuntime.set_run_settings() resets every setting it does not model to its
ovclash_reset_settings() default. Most other settings on this page therefore need the C or Suite
API, and ovclash_set_broadphase_limit exists only in canonical C.
Measure first#
Before you begin: the Python scripts in this section need the ovclash package installed, as
Python Quickstart shows. Replace scene.usda with the path of your stage
file, and run each script with that Python.
Find the expensive phase before you tune. A static query has 11 pipeline steps, and their names are the phase list:
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...
A dynamic query, one that samples the stage at several times, keeps steps 0
to 4. It then runs Static/dynamic classification..., one Running dynamic clash detection... step
per sample, and Ending pipeline.... That is 7 steps plus one per sample. Each sample step updates
the poses and runs the bounding volume hierarchy (BVH) build, the
broad phase and the narrow phase for that time.
The BVH is a tree of nested bounding boxes over the meshes, and the broad phase queries it for
candidate pairs. The cost therefore grows with the sample count; see
Dynamic runs.
To time each step, run the steps yourself:
import time
from ovclash import ClashRuntime
with ClashRuntime() as runtime:
runtime.open_stage("scene.usda")
steps = runtime.create_pipeline()
for step in steps:
start = time.perf_counter()
runtime.run_pipeline_step(step.step_index)
print(f"{step.step_index:3} {step.name:40} {time.perf_counter() - start:8.3f} s")
The script prints one line per step: its index, its name from the phase list and its time in seconds. The step with the largest time is the one to tune.
In C, call ovclash_run_pipeline_step() for each step the same way. During an async run, poll
ovclash_get_pipeline_step_data_async() (Suite: ovclash_suite_async_get_step_data()). That poll
is the only progress source that moves while work runs. Its step name can append the current
operation, for example Running narrow-phase... Testing mesh pairs.
ovclash_get_pipeline_step_data() returns the static plan, not live progress.
ovclash_set_log(context, true) makes the library print its own per-phase timing to stdout. There
is no log callback or redirection, so capture the process’s stdout. python -m ovclash --log moves
these lines to stderr and keeps the JSON summary on stdout. The text is diagnostic output, not a
stable format, so do not parse it. For phase timing of the stage reads and of each Suite fetch,
see Collecting diagnostics for a bug report.
Then check the size of the problem with the query statistics of
ovclash_get_query_stats() or ovclash_suite_get_query_stats(). They report the selected
meshes, the shared instances among them, the cooked meshes and the selected point clouds. In
Python, get_query_stats() returns an ovclash.QueryStats of four int counters.
Detect dropped meshes gives the type and meaning of each
field, and Reading results the C form, ovclash_stats_t.
Read them after the run:
from ovclash import ClashRuntime
with ClashRuntime() as runtime:
runtime.open_stage("scene.usda")
runtime.set_run_settings(enable_log=True)
runtime.run_pipeline()
stats = runtime.get_query_stats()
print(stats.nb_meshes, stats.nb_shared_meshes, stats.nb_cooked_meshes, stats.nb_point_clouds)
The script prints the engine’s per-phase log lines and then the four counters on one line, in
the order of the print() call:
nb_cooked_meshesdrives the cooking cost.A high
nb_shared_meshesrelative tonb_meshesis the cheap case: instanced geometry is cooked once and reused.nb_cooked_meshescounts successful cooks. A value belownb_meshes - nb_shared_meshesmeans meshes that failed to cook are missing from the results; see Detect dropped meshes.
Scope before you tune#
Before you begin: your program builds against the SDK archive, as
C/C++ Quickstart shows, and holds a context from
ovclash_create_context() and an ovclash_settings_t that you filled, for example from
ovclash_reset_settings().
The largest lever is often not a setting: ask a smaller question. An explicit A/B
scope, two search sets of prim paths such as “does this assembly hit
that assembly”, removes meshes before cooking, the BVH build and the broad phase. Use
ovclash_set_scope_paths():
With only the first array populated, the engine tests that set against itself.
With both arrays populated, it tests the first set against the second.
From the command line, pass
--scope-aand--scope-btopython -m ovclash.
Order matters in C. ovclash_open_stage(), ovclash_ovstage_attach_stage(),
ovclash_set_settings() and ovclash_set_full_scene() all clear the scope paths. A scope set
before them is lost. The run then selects the whole stage, or nothing when
full-scene traversal is off. Set the scope last. This function belongs in
a C source file of your program, in place of your own open, settings and scope calls:
#include <ovclash/ovclash.h>
/* Opens the stage, applies the settings, scopes set A (a, a_count paths) against set B
* (b, b_count paths) and creates the pipeline. Returns 0 on success. */
static int create_scoped_pipeline(ovclash_context_t* ctx,
ovclash_string_t stage_path,
const ovclash_settings_t* settings,
const ovclash_string_t* a,
size_t a_count,
const ovclash_string_t* b,
size_t b_count)
{
uint32_t step_count = 0;
if (ovclash_open_stage(ctx, stage_path).status != OVCLASH_STATUS_SUCCESS) /* clears the scope */
return 1;
if (ovclash_set_settings(ctx, settings).status != OVCLASH_STATUS_SUCCESS) /* clears the scope */
return 1;
if (ovclash_set_scope_paths(ctx, a, a_count, b, b_count).status != OVCLASH_STATUS_SUCCESS)
return 1;
return ovclash_create_pipeline(ctx, &step_count).status == OVCLASH_STATUS_SUCCESS ? 0 : 1;
}
To confirm that the scope applied, read the query statistics after the run: nbMeshes counts
the selected meshes, so a scoped run reports fewer than an unscoped run over the same stage.
Python ClashRuntime and the Suite runtime cache the scope and apply it again just before they
build the pipeline. They therefore accept settings and scope in either order. A successful stage
open or attach of an ovstage Stage still drops the cached scope.
A non-empty scope clears full-scene traversal. In C and in ClashRuntime, clearing the scope does
not restore it. The Suite runtime restores it after an empty scope, a successful open or an
ovstage attach, when the settings in effect enable enable_full_scene. An empty Suite scope
therefore selects the whole stage. Setting a scope has the
full rules.
Threading#
Three settings select the scheduler and the worker budget: ovclash_set_single_threaded,
ovclash_set_new_task_manager and ovclash_set_nb_tasks. Threading
gives their defaults.
None of them changes which pairs overlap or what is reported about them, and the overlap order
stays the same under every setting. The index order is still not part of the contract: key
results on name0/name1 or clashHash, never on the index.
Threading controls and result order
lists the phases they cover and the ordering rules.
Setting |
Type |
Default |
Effect |
|---|---|---|---|
|
|
|
Forces serial execution of every parallel phase. Also disables sampled-matrix prefetch and the helper thread that populates static transforms. |
|
|
|
True selects the tasking of Carbonite, NVIDIA’s plugin and runtime framework, and its scheduler budget, and ignores |
|
|
|
Read only by the |
OVCLASH_SETTINGS_FLAG_NEW_TASK_MANAGER is part of OVCLASH_SETTINGS_FLAG_DEFAULT, so nb_tasks
has no effect until you turn the new task manager off.
After detection, the same settings choose the workers for native report extraction. They also
choose the workers for the frame preparation of a directory store or a
custom store, a store that your own serializer implements, during
fetch-and-save. new_task_manager=false selects std::thread workers bounded by nb_tasks.
Small work ranges run serially. These stay on the thread that drives the fetch: every callback
of a custom store’s serializer except prepare_frame, SQLite frame encoding, and all writes.
In Python, RunSettings.single_threaded defaults to False in both packages, as on a fresh native
context. Set it to True, or pass --single-threaded to python -m ovclash, to force serial
execution. To use a bounded std::thread pool and keep the other settings, add this line to
your script for a ClashRuntime named runtime, after open_stage() and before
create_pipeline() or run_pipeline():
runtime.set_run_settings(runtime.get_run_settings(), new_task_manager=False, nb_tasks=8)
With legacy multi-threading (single_threaded and new_task_manager both false),
ClashRuntime.set_run_settings() accepts nb_tasks only in 1..255. No setting pins execution to
a CPU core.
Broad phase and geometry limits#
These settings control how much geometry work the run does and how much of the result it records.
Setting |
Type |
Default |
Effect on cost |
|---|---|---|---|
|
|
|
Triangles per leaf of the BVH34, the midphase tree that PhysX cooks for each mesh ( |
|
|
|
Cooks quantized BVH34 trees ( |
|
|
|
|
|
|
|
Stops each mesh pair at its first colliding triangle pair. |
|
|
|
Caps the triangle pairs recorded per mesh pair. It truncates |
|
|
|
Cancels the run when the broad phase finds more candidate pairs than this. 0 is a real limit, not “unlimited”. |
any_hit forces the per-pair triangle limit to 1 and overrides triangle_limit. It cuts
narrow-phase work when you need only a yes/no answer per pair. Overlaps are still reported. Their
nbElements and their face and outline buffers then hold one representative hit, and derived
values such as maxLocalDepth come from that one triangle pair.
broadphase_limit guards against a combinatorial explosion:
The run compares the candidate-pair count with the limit after the broad phase has collected every pair. The limit does not bound the pair array itself.
When the count exceeds the limit, the run is cancelled before the duplicate purge, the
Purging duplicates...step that filters the candidate pairs, and before the narrow phase. Results are not truncated.A static stepped run then fails at the next step. A sample step of a dynamic run fails itself. An async run fails in
ovclash_finish_pipeline().In a stepped run, later steps of that context keep failing, even in a new pipeline, until
ovclash_reset_context()clears the cancellation.
ovclash_set_overlap_code picks the triangle-triangle intersection kernel: 0 is the regular
kernel, 1 a variant of Moller’s triangle-triangle test, 2 a separating-axis test (SAT) and 3 a
SAT that uses SIMD vector instructions (SIMD SAT). The default is 3. The kernels differ in speed and
can differ slightly in how they classify borderline hits. The value is not validated; anything
outside 0-3 behaves like 0.
Epsilons and cutoffs#
Setting |
Type |
Default |
Trade |
|---|---|---|---|
|
|
|
Per-element tolerance for comparing world transforms. It decides which meshes count as shared instances with identical poses and which pairs count as duplicates. It also lets the immediate-mode depth queries skip work for equal matrices. A larger value makes more transforms compare equal. |
|
|
|
Inflates each mesh’s world bounds, as an additive offset and as the scale factor |
|
|
|
|
|
|
|
Minimum penetration depth for an overlap to be reported. Active only when depth computation is on. It culls shallow overlaps and bounds the refinement search from below. |
|
|
|
Upper depth cutoff for the refined depth search. Applied only when |
|
|
|
Clearance distance: mesh pairs closer than this count as clashing. It inflates the broad-phase query boxes and is passed to the PhysX mesh-mesh queries. A positive value costs more and reports near misses as overlaps. The point-vs-mesh narrow phase ignores it. Negative values are clamped to 0. |
tolerance is often raised for modeling reasons and then blamed for a slow run. Every positive
value grows the broad-phase candidate set, and the narrow phase then resolves more pairs. A
positive tolerance also stops dynamic runs from skipping the broad-phase queries of static
meshes.
Depth computation costs#
ovclash_set_compute_max_local_depth() takes one of four ovclash_max_local_depth_mode_t values,
in increasing cost:
Mode |
Cost |
What it computes |
|---|---|---|
|
none |
No depth. |
|
fast |
The original fast estimate. |
|
slower |
A refined estimate. |
|
slowest |
MEDIUM plus 64 sampling directions. |
Leave it DISABLED unless you use the depth. Turning it on also activates contact_epsilon-based
culling, which the default contact_epsilon of -1 leaves off. With depth enabled and a positive
contact_epsilon, each pair costs more. The run can still be cheaper downstream, because fewer
overlaps survive.
To get depth for a few overlaps, call ovclash_compute_max_local_depth() (Suite:
ovclash_suite_compute_overlap_max_local_depth()) on those records after the run. Do not raise the
mode for the whole query. The call refines according to the current mode and returns the cheap
estimate when the mode is DISABLED.
Depth is mesh-only. A point-vs-mesh overlap reports 0.0f in every mode, which is not a measured
zero-depth contact.
Note The Suite’s
ovclash_suite_run_settings_t::max_local_depth_modeis offset by one fromovclash_max_local_depth_mode_t: 0 is minimal, 1 medium and 2 high, gated bycompute_max_local_depth. See Settings.
Dynamic runs#
ovclash_set_times(context, startTime, endTime, timeCodesPerSecond) sets the sampled range. When
startTime and endTime differ, the run is a dynamic run, the run of a dynamic query.
The range is in seconds, not USD time codes.
timeCodesPerSecondis the query’s sampling rate, not the stage’s. Read the stage’s own rate withovclash_get_stage_timeline_data().Sampling starts at
startTimeand adds1.0/timeCodesPerSeconduntil the next time exceedsendTime. Floating-point rounding can drop an exact endpoint.startTime == endTimeis a static query.timeCodesPerSecond == 0or a descending range yields one sample.The sample schedule is fixed when the pipeline is created, so a later
ovclash_set_times()call applies to the next pipeline.Times must be finite and the rate must not be negative.
ovclash_create_pipeline()also rejects a range whose sample count does not fit the pipeline, and a rate so high that adding1.0/timeCodesPerSecondno longer advances the time; see Pipeline creation rejects the sample range.
Every sample adds a pipeline step (see Measure first). Every sample in which a
pair overlaps adds one record to that pair’s overlap (nbRecords). For long ranges, halving
timeCodesPerSecond roughly halves the sample count and much of the cost.
A sample can reuse the previous sample’s narrow-phase work:
Both kinds of reuse require every setting and the floating-point controls to match bit for bit.
The sample reuses the whole result, including an empty one, when the geometry, matrices and candidate pairs also match.
Otherwise it reuses a single overlapping pair’s result when that pair’s meshes, scales and relative pose match.
Reuse applies only to dynamic runs with point clouds, duplicate-only search and maximum local depth all disabled. Each sample still gets its own records.
The reuse data has its own 8 MiB budget. When it does not fit, the sample does the normal collision work.
Two flags keep the result set from growing with the sample count. Neither affects a static query:
ovclash_set_purge_permanent_dynamic_overlaps()(default disabled) drops pairs present in every sampled frame. These are permanently interpenetrating modeling artifacts rather than motion-induced clashes.ovclash_set_purge_permanent_static_overlaps()(default enabled) drops pairs where both prims were classified static for the whole run. The results then show only motion-induced clashes.
The static purge also saves work. Every sample’s broad phase skips static-static pairs. With point clouds off, the per-sample BVH rebuild can cover only the moving meshes. Only a conclusive static classification counts:
A mesh whose authored transforms cannot be resolved counts as non-static, and its pairs are tested at every sample. Scene limits says how to avoid that.
On a stage attached without a composition, every mesh also stays non-static unless the binding declares
OVCLASH_OVSTAGE_CAP_AUTHORED_TRANSFORM_UPDATES. A stage attached with a composition is classified from a private population, as a file-backed stage is (Engine-evaluated time).
Duplicate-mesh search is disabled for dynamic runs. ovclash_set_only_find_duplicates() with an
ovclash_set_times() range whose start and end differ therefore yields nothing.
ovclash keeps sampled transform matrices in a cache with a fixed 1 GiB budget:
With authored-transform classification, it reads matrices in playback windows that hold at most 32 frames in total.
When the scheduler allows two workers, parallel playback splits them into a current and a prefetched window of at most 16 frames each. A stage attached with
ovclash_ovstage_attach_stage()without a composition gets no prefetch; one attached with a composition prefetches as a file-backed stage does.When classification is unresolved, the fallback caches the whole timeline only if its estimate fits the budget. The estimate is 128 bytes (one 4x4 double matrix) per selected mesh or point cloud per sample. Otherwise playback reads the matrices again.
The budget covers only this cache, not process memory. Prefetch does not relax the rule that application calls on one context are serialized (Threading and Ownership).
To save that memory at the cost of speed, turn the cache, and with it prefetch, off for one
ClashRuntime context. Playback then reads one frame at a time:
runtime.set_ovstage_dynamic_matrix_cache(False)
The cache is on for a new context. The call closes open reports and invalidates the pipeline, so make it before you build the pipeline. It changes neither the sample times nor the poses.
Dynamic runs on an attached stage#
How a borrowed ovstage Stage evaluates time decides most of the cost of a dynamic run on it (ovstage Integration):
Without a composition, the owner publishes every sample on its own Stage through
evaluate_time, under the owner-operation gate. The samples cannot be prefetched, and unless the owner declaresOVCLASH_OVSTAGE_CAP_AUTHORED_TRANSFORM_UPDATESno pair is pruned as static. Every sample also republishes the owner’s Stage at a new time.With a composition, ovclash samples private populations of the composition, as it samples a file-backed stage, with prefetch and static-pair pruning. The owner’s Stage is never evaluated or republished. Each private population pays for replaying the composition: the root opens and every layer merges, for the transform population and, when static pairs are purged, for the classification. A large root or many layers make the first finite-time read slower, and the private populations take memory as those of a file-backed run do.
Compare the two modes on one machine with the same stage and the same sample range; see Measure first.
Filtering noise#
Filtering is a performance lever as well as a correctness one. An overlap that is never produced costs nothing to store, persist or export.
Setting |
Type |
Default |
Effect |
|---|---|---|---|
|
|
|
Drops a broad-phase candidate pair when both meshes resolve to the same subcomponent root, the nearest ancestor prim with |
|
|
|
Drops pairs whose meshes and relative poses repeat a contact already recorded, typically instanced geometry laid out identically. It runs in the duplicate purge after the broad phase (the |
|
|
|
Excludes invisible prims during selection, so they never reach cooking or the broad phase. |
|
|
|
Runs the duplicate search only and skips the BVH, broad-phase and narrow-phase steps. |
On assembly-heavy stages, try subcomponent_filtering first: it removes pairs in the broad
phase, before any triangle work. In a dynamic run that purges permanent static overlaps,
redundant-overlap filtering also reduces a moving mesh’s contacts with identical static copies to
one representative contact.
Persisting many overlaps#
A SQLite store, an .ovclashdb file, keeps one clash_frame_info row per
overlap record, that is, per sampled frame in which a pair overlaps. The row count is the sum of
nbRecords across the result. Millions of rows for a long dynamic query are normal.
Save completed runtime results with ovclash_suite_runtime_fetch_and_save_async(), or in Python
with ClashDetection.fetch_and_save_overlaps(..., async_mode=True):
The operation preserves result order and commits once, at completion.
The frame preparation of a directory store or a custom store can use the configured workers (see Threading). SQLite frame encoding and every storage write stay on its one background worker. A SQLite database has one writer at a time, so more workers do not parallelize insertion.
Each fetch step (
ovclash_suite_runtime_fetch_and_save_next(), or one iteration of the async worker) bounds its work, not its time: at most 1,024 frame reports, 1,024 overlaps and about 8 MiB of report payload. One indivisible report can exceed the payload bound. Reconciliation of stored clashes scans at most 1,024 stored identifiers per step. Initialization enumerates every stored identifier and is not bounded.Finish and destroy the operation before you read or release the runtime or the data handle.
With state updates enabled, which maintain the clash state of each stored
clash, a previously APPROVED clash also reads back its stored header and frames for comparison.
State updates are resolve_stale in C and update_clash_states_after_detection in Python, which
is on by default. The Python serializer of a SQL-backed custom store should therefore implement
fetch_iter_saved_frames(identifier, first_frame_offset=0) with a forward cursor. The
compatibility default reads one frame per call, which an OFFSET query turns into a quadratic
scan over a long history. See
Fetching Suite runtime results for the iterator
contract, and Saving detection results for the
transaction rules.
If you write records yourself, batch them instead of committing per row:
Every
insert,updateandremovein the data API has a_with_commitvariant. Passcommit = 0(Python:commit=False) for the body of a bulk write, and commit once withovclash_suite_data_commit().For frames,
ovclash_suite_data_replace_frames_by_overlap_with_commit()replaces a whole frame array in one call.A write that fails inside a batch can roll back the handle’s whole pending transaction, including earlier writes that returned success. Validate inputs first; see CRUD.
If the per-frame geometry is not needed downstream, the cheapest fix is not to produce it. any_hit
or a triangle_limit shrinks each row, and a lower timeCodesPerSecond reduces the number of
rows.
HTML export#
Fetching and saving results and generating HTML are separate operations.
ovclash_suite_export_rows_html_text(), which Python’s export_to_html() wraps, builds the
document synchronously on the calling thread. It escapes the supplied rows and appends them in
order into one owned text handle; the caller writes the file. Fetch-and-save batch limits do not
speed it up. Peak export memory is the input rows plus the complete document, plus any binding or
caller copies. See Export for the text-handle API.
Memory#
ovclash_release_memory(context) frees the current query’s memory: source data, meshes, point
clouds, results, dynamic state and the broad-phase BVH. An attached stage stays attached. A stage
attached with a composition keeps it, but its private populations are freed, and the next
finite-time read replays the composition. The context stays usable and can be reconfigured, so
call it between queries in a long-lived process.
ovclash_reset_context() (Python ClashRuntime.reset(), Suite ovclash_suite_reset_runtime())
drops query state: meshes, cooked data, the BVH, candidate pairs, results and statistics.
Settings, scope, the opened stage and the built pipeline survive. It also drops the populated
scene, which the next run repopulates from the stage file, and releases a stage attached with
ovclash_ovstage_attach_stage(). An attached stage has no file to repopulate from, so attach it
again before the next run.
Both calls invalidate borrowed result views, so release your reports first; see Borrowed memory. Both are rejected while an async pipeline handle is active.
ovclash_is_out_of_memory(context, &flag) reports a recorded allocation failure of that context.
The call that hit the failure returns OVCLASH_STATUS_ERROR (for an async run,
ovclash_finish_pipeline()), and the last error ends in Out of memory (std::bad_alloc). Some
dependency allocation failures surface only as a status or error text and leave the flag unset, so
check those too.
A zero overlap count does not prove the scene is clash-free. After a cancelled run,
ovclash_get_overlap_count() can return 0 with a success status. After the run:
check every status, and
ovclash_is_out_of_memory();for an async run, check the
ovclash_finish_pipeline()status, and readovclash_async_is_cancelled()before finish clears the flag;compare the cooked-mesh count; see Measure first.
To stop a run whose candidate-pair count explodes before the narrow phase processes it, set
ovclash_set_broadphase_limit(); see
Broad phase and geometry limits.
See also#
Settings: every setting with its default, unit and effect.
Threading and Ownership: which phases the threading controls cover, and the ordering rules.
Saving detection results: the fetch-and-save transaction contract.
Troubleshooting: failures keyed by message, and the diagnostics to collect.