file_path
stringlengths 5
148
| content
stringlengths 0
526k
|
---|---|
ext_boom.md | # Boom Collision Audio
## Overview
The NVIDIA Omniverse™ Boom (omni.audio.boom) Extension adds audio material support to Kit Apps. With it, you can author audio materials on top of physics materials. These audio materials are used to play sounds based on simulation events, such as an impact, a roll, or a slide, or custom, script-based events with user-defined event names.
## Interface
The Boom window is divided into panels described in the following subsections.
### Debug Settings
With *Debug Settings*, you control the debug rendering features of the system.
#### Control
- **Debug Display**: Toggles debug rendering on/off. Colored spheres are drawn based on the type and magnitude of the event.
- **Red**: Impact
- **Green**: Rolling
- **Blue**: Sliding
- **Yellow**: Custom
- **Grey**: Suppressed
- **Show Suppressed Events**: Controls if events that were filtered out by containing events are rendered in black. This is off, by default, to prevent cluttering, but it can be useful to see how many events are attempting to play.
### Audio Material Definitions
With *Audio Material Definitions*, you define the audio material and its associated events.
#### Control
- **Add Event Type**: Defines a new event type for the audio material.
- **Simulation Events**: Created for both bodies involved.
- **Impact**: (One-shot) based on linear velocity in the normal direction when 2 bodies collide.
## Demo Scenes
Example demo scenes can be accessed through the physics demo scenes menu option (Window > Simulation > Demo Scenes). This will enable a Physics Demo Scenes window, which has a Boom Samples section.
## Tutorials
### Basic Setup Tutorial
### Step-by-step Walkthrough
In this tutorial, you learn how to set up a simple scene with collision-based audio.
First, enable the Boom extension (if it isn’t enabled already):
- Navigate to Window > Extensions.
- Enable the Boom extension.
You can check *Autoload* if you’ll be working with Boom frequently and don’t want to enable it every time you load the application.
Make sure it says “UP TO DATE” at the top of the extension details. If it doesn’t, update to the latest release of the extension.
Make sure there is something for the object to interact with:
> Navigate to *Create > Physics > Physics Scene*.
> And *Create > Physics > Ground Plane*.
Next, create a prim to interact with:
> Navigate to *Create > Mesh* or *Create > Shape*, and pick a primitive type to create (Cube, Sphere, etc).
> Alternatively, you can load a mesh from another USD source.
> Position the mesh above the plane.
Set up the mesh’s physics properties.
> Right-click the mesh, and navigate to *Add > Physics > Rigid Body with Colliders Preset* to make it dynamic and collidable.
> Right-click the mesh again, and navigate to *Add > Physics > Contact Reporter* if you want the system to auto-generate the simulation-based events.
> Make sure the *Contact Report Threshold* is low enough to generate contact events for the body. The default of 100 should be fine unless the mesh is very small.
> Only one object in a collision event needs to have the Contact Reporter set for sounds to play for both sides, but both having it won’t cause any problems.
The simulation events depend on the physics material. That can be applied in one of two ways:
> Assign a render material that has a physics material with it under *Materials on selected models* in the *Property* panel.
> Right click on a render material and select *Add > Physics > Rigid Body Material* to create add physics properties to it.
> Set the physics material directly under *Physics > Physics materials on selected models* in the Property panel, this one takes priority if both are set.
Now set up the audio material:
> The audio material needs to live on the same prim as the physics material.
> Select the prim that the physics material is defined on, and add the desired event type(s) to it via the *Boom* panel to define the audio material.
> Or, create the audio material in another scene and reference it (this method is useful if you want to create a library of audio materials in a single file).
> Create a *Scope* prim in another file, and add the event type(s) you want to it.
> Use *Add > Reference* on the physics material in the original file to point at it.
> Use the *Prim Path* field of the reference to target a single prim in the reference file.
Define as many threshold groups as you want.
> We recommend that you have the minimum attenuation for the lowest threshold group start at 0 so bodies settling don’t spam sounds.
> If you only have one set of sounds that you want to play, creating two threshold groups and adding the same sounds to both is useful in allowing the sounds to ramp in over the first range and play at full volume above the second threshold.
> If multiple audio assets are added to a threshold group, one will be picked at random to play when triggered by contact.
Repeat for all event types that you want to have play audio clips.
> It is not required to fill out all event types for an audio material to be valid.
> Creating complex sounds from interactions of multiple materials:
>
> - Unique material pair sounds are created by combining audio materials from both sides of a contact event.
> - Audio assets should be authored with as little audio contribution from external materials as possible.
> - Try the “Simple Example” demo to hear how sounds are combined based on materials involved in the contact.
> > - You can change the material on the box to hear how the sounds change when interacting with the two ground tiles.
>
> **Note**
>
> Run the simulation (by pressing *Play*), the rigid body falls to the ground and generates sounds from contact events. Use Shift + Left Mouse Button to toss the body to generate impact events or drag the body to generate sliding and rolling events. |
ext_omnigraph.md | # OmniGraph
OmniGraph is the visual scripting language of Omniverse. It allows the worlds in Omniverse to come alive with behavior and interactivity. OmniGraph addresses all sorts of computations, from deformers to particles to event-based graphs and more. OmniGraph is not a single type of graph, but a composition of many different types of graph systems under a single framework.
There are two types of graph types you can create in OmniGraph: **Action Graphs**, which allow event driven behaviors and **Push Graphs** which evaluate nodes continuously.
Additionally, there are node libraries for Particle System creation, Skeletal Animation and more.
## Getting Started
New to OmniGraph? These pages bring you up to speed with the concepts of OmniGraph and how to get up and running quickly.
- [Core Concepts](ext_omnigraph/getting-started/core_concepts.html)
- [Intro to OmniGraph](ext_omnigraph/tutorials/gentle_intro.html)
## OmniGraph Interface
Familiarize yourself with the OmniGraph Editor interface and view all available OmniGraph nodes.
- [The OmniGraph Interface](ext_omnigraph/interface.html)
- [Node Library](ext_omnigraph/node-library/node-library.html)
## OmniGraph Tutorials
To help you get started with OmniGraph, we’ve created a handful of hands-on tutorials:
- [Using Event Nodes](ext_omnigraph/tutorials/using_event_nodes.html)
- [Using Flow Control Nodes](ext_omnigraph/tutorials/using_flow_control_nodes.html)
- [Using Variant Nodes](ext_omnigraph/tutorials/using_variant_nodes.html)
- [Using Maneuver Nodes](ext_omnigraph/tutorials/using_maneuver_nodes.html)
## OmniGraph Developer Documentation
Interested in learning about OmniGraph development?
Open the OmniGraph developer portal |
ext_scene-optimizer.md | # Scene Optimizer
The Scene Optimizer is a Kit Extension that performs scene optimization at the USD level. This allows complex scenes to be converted into more lightweight representations which can be displayed and evaluated more quickly.
The tool provides various processes which can be used individually or in combination stack to optimize a scene.
## Topics
- [Using The Scene Optimizer](ext_scene-optimizer/user-manual.html)
- [Operations](ext_scene-optimizer/operations.html)
- [Scene Optimizer: What Options Should I Choose?](ext_scene-optimizer/howto.html)
- [White Papers](ext_scene-optimizer/white-papers.html)
- [Release Notes](ext_scene-optimizer/release-notes.html) |
ext_shaders.md | # Damage Shaders (NvBlastExtShaders)
The Blast damage shader extension provides basic implementations of programs generating fracture commands, the first step in breaking a Blast Actor, see [Damage and Fracturing](#splitting). These programs come as two shader functions (callbacks): one for Actors with a support graph, and one for Actors with just one chunk, respectively. The NvBlastDamageProgram containing both shaders can be used for low-level directly (NvBlastActorGenerateFracture) or for TkActor’s damage and fracture functions.
For example, one may construct a damage program using the “shear” damage shaders declared in NvBlastExtDamageShaders.h:
```
```c
NvBlastDamageProgram damageProgram = { NvBlastExtShearGraphShader, NvBlastExtShearSubgraphShader };
```
The appropriate shader (“graph” or “subgraph”) will be called for an Actor being processed, along with the Actor’s necessary geometry and program parameters. The parameters (NvBlastProgramParams) are set to contain:
1. Material, something that describes an Actor properties (e.g. mass, stiffness, fragility) which are not expected to be changed often.
2. Damage description, something that describes a particular damage event (e.g. position, radius and force of explosion).
For example:
```c
NvBlastExtMaterial material = { health, minDamageThreshold, maxDamageThreshold };
NvBlastExtRadialDamageDesc damageDesc = { compressive, posX, posY, posZ, minR, maxR };
```
When used with TkActor::damage() functions, TkActor will cache the necessary data for deferred processing through TkGroup. This includes accumulating damage requests for the same material and program parameter combination. A default material can be set for a TkFamily that all its Actors uses.
A Tk layer example follows.
```c
tkGroup->addActor(*tkActor);
tkActor->damage(damageProgram, damageDesc0, sizeof(NvBlastExtRadialDamageDesc), &material);
tkActor->damage(damageProgram, damageDesc1, sizeof(NvBlastExtRadialDamageDesc), &material);
tkGroup->process();
```
In contrast, the user is responsible for providing all the damage descriptions persisting through the low-level NvBlastActorGenerateFracture call when not using the Tk layer:
```c
NvBlastProgramParams programParams = { damageDescs, 2, &material };
NvBlastActorGenerateFracture(commandBuffers, actor, damageProgram, &programParams, nullptr, nullptr);
``` |
ext_stress.md | # Stress Solver (NvBlastExtStress)
The Blast stress solver extension provides an implementation of a fast and easy to use stress solver which works directly with the bond graph. It simulates iteratively spreading forces across bonds that connect nodes of the support graph (where nodes typically represent chunks) and allows bond limits to be specified for tension, compression, and shear independently.
The most common usage is applying gravity force on a static structure so that it will fall apart at some point when it cannot hold anymore. For gravity to work correctly there must be at least one node in the graph with 0 mass. That causes the system to treat the node as being fixed and having infinite mass so it can’t move to reach a converged state. You can use part of the destructible itself, or add a dummy node and bonds connecting it to the nodes that should support the structure. The other option is to add a supporting force to all nodes at the “base” of the graph (where the graph connects to the thing supporting it, normally the bottom, but could be the top for a hanging structure). Without this, the algorithm will stabilize with no internal force due to gravity, effectively treating it like the entire structure is in freefall.
It also can be used as another way to apply impact damage, which can give the visually pleasant result of an actor breaking in a weak place instead of the place of contact. This is accomplished by adding the impulse of collisions to the nearest node in the graph.
Dynamic actors are also supported, you could for example add centrifugal force so that rotating an object fast enough will break bonds. Keep in mind that for gravity to work with dynamic actors, an opposing force or static node(s) must be added to the system to provide resistance to the force.
## Features
- Requires only core a NvBlast
- Supports both static and dynamic actors
- Propagates both linear and angular momentum
- Graph complexity selection (reduces support graph to smaller size to trade-off speed for quality)
- Apply stress damage on Blast actor
- Debug Render
## Settings Tuning
Computation time is linearly proportional to the a maxSolverIterationsPerFrame setting. Higher values will converge to a solution sooner, but at processing cost. a graphReductionLevel should be considered experimental at this point, it has not been heavily tested.
Debug render can help a lot for tuning, consider using a stressSolver->fillDebugRender(…) for that.
## Usage
In order to use the stress solver, create an instance with a ExtStressSolver::create(…).
```cpp
ExtStressSolver* stressSolver = ExtStressSolver::create(family, settings);
```
a ExtStressSolverSettings are passed in create function, but also can be changed at any time with a stressSolver->setSettings(…).
It fully utilizes the fact that it knows the initial support graph structure and does a maximum of processing in the a create(…) method call. After that, all actor split calls are synchronized internally and efficiently so only the actual stress propagation takes most of computational time.
You need to provide physics specific information (mass, volume, position) for every node in support graph since Blast itself is physics agnostic. There are two ways to do it. One way is to call a stressSolver->setNodeInfo(…) for every graph node. The other way is to call stressSolver->setAllNodesInfoFromLL() once: all the data will be populated using NvBlastAsset chunk’s data, in particular a volume and a centroid. All ‘world’ nodes are considered static.
```cpp
stressSolver->setAllNodesInfoFromLL(density);
```
The stress solver needs to keep track for actor create/destroy events in order to update its internal stress graph accordingly. So you need to call a stressSolver->notifyActorCreated(actor) and a stressSolver->notifyActorDestroyed(actor) every time an actor is created or destroyed, including the initial actor the family had when the stress solver was created. There is no need to track actors which contain only one or less graph nodes. In that case a notifyActorCreated(actor) returns ‘false’ as a hint. It means that the stress solver will ignore them, as for those actors applying forces does not make any sense.
A typical update loop looks like this:
- Apply all forces, use a stressSolver->addForce(…), stressSolver->addGravity(…), a stressSolver->addCentrifugalAcceleration(…)
- Call a stressSolver->update(). This is where all expensive computation takes place.
- If a stressSolver->getOverstressedBondCount() > 0, use one of a stressSolver->generateFractureCommands() methods to get bond fracture commands and apply them on actors.
- If split happened, call relevant stressSolver->notifyActorCreated(actor) and stressSolver->notifyActorDestroyed(actor) |
ext_tkserialization.md | # BlastTk Serialization (NvBlastExtTkSerialization)
This extension contains serializers which can be loaded into the ExtSerialization manager defined in [Serialization (NvBlastExtSerialization)](ext_serialization.html#pageextserialization).
To use this extension, you must also load the ExtSerialization extension and create a serialization manager as described in [Serialization (NvBlastExtSerialization)](ext_serialization.html#pageextserialization).
We repeat this here (again, assuming we are in the Nv::Blast namespace):
```cpp
ExtSerialization* ser = NvBlastExtSerializationCreate();
```
Then, call the function NvBlastExtTkSerializerLoadSet, declared in **NvBlastExtTkSerialization.h**, passing in your TkFramework:
```cpp
TkFramework* framework = ... // We must have created a TkFramework
NvBlastExtTkSerializerLoadSet(*framework, *ser);
```
Now your serialization manager will have the serializers provided by this extension. Currently only TkAsset serializers exist, with object type ID given by
**TkObjectTypeID::Asset**
As with low-level assets, you can serialize using the serialization manager directly:
```cpp
const TkAsset* asset = ... // Given pointer to an Nv::Blast::TkAsset
void* buffer;
uint64_t size = ser->serializeIntoBuffer(buffer, asset, TkObjectTypeID::Asset);
```
or use the wrapper function defined in **NvBlastExtTkSerialization.h**:
```cpp
void* buffer;
uint64_t size = NvBlastExtSerializationSerializeTkAssetIntoBuffer(buffer, *ser, asset);
``` |
ext_viewport.md | # Viewport — Omniverse Extensions latest documentation
## Viewport
### Overview
The Viewport extension is the primary way you view 3D worlds in Omniverse Kit-based Apps. It’s the window through which you see and navigate your creative work.
### Viewport Tools
There are several tools that make up the functionality of the Viewport:
- Viewport Controls
- Viewport Settings
- Render Mode
- Interface Visibility
- Camera
- Persistent Menus
- Viewport Transform Manipulators
- Viewport Transform Context Menu
- Viewport Navigation
- Viewport Visor
- Viewport Turntable |
fabric-benchmark_Overview.md | # Fabric Benchmark
This extension runs a suite of performance tests on Fabric. |
fabric_hierarchy.md | # Fabric Transforms with Fabric Scene Delegate and IFabricHierarchy
## About
The Fabric Scene Delegate is the next-generation Omniverse scene delegate for Hydra. It leverages the power and performance of Fabric for a faster, more flexible, streamlined rendering pipeline.
Fabric Scene Delegate uses Fabric as its data source for all rendering operations. Starting in Kit 106, Fabric Scene Delegate also leverages the new Connectivity API in Fabric to store and query information about the scenegraph transform hierarchy via the new IFabricHierarchy interface. This adds the following functionality to Fabric Scene Delegate:
- All Boundable prims in Fabric now participate in the transform hierarchy - changes to the local transform of a Fabric prim will affect the world transform of all descendants of that prim in Fabric.
- Prims authored exclusively in Fabric now participate in the transform hierarchy for the scene - previously, participating in the transform hierarchy (to the extent that OmniHydra supported it) required a corresponding prim on the USD stage.
This document reviews the IFabricHierarchy interface and how the transform hierarchy is maintained in Fabric.
## Fabric Transforms Previously
Earlier iterations of the Omniverse rendering pipeline supported limited Fabric-based transforms in the Hydra scene delegate. These required Fabric prims to express their world transform on Fabric prims using these attributes:
- `_worldPosition`
- `_worldOrientation`
- `_worldScale`
You can read more about this here: Working with OmniHydra Transforms
Prims with these transform attributes authored in Fabric no longer participate in any transform hierarchy. This often causes unexpected behavior when manipulating transforms on ancestors or descendants of these prims.
OmniHydra also supports a `_localMatrix` attribute, which if it exists in Fabric is substituted in the world transform calculation for a given prim in place of the backing USD prim’s computed local-to-parent transform. However, this requires a valid backing USD hierarchy, and is superseded by the existence of any of the `_world*` attributes.
Earlier versions of Fabric Scene Delegate also leveraged the `_world*` attributes to drive rendered prim transforms. These attribute values could be updated directly in Fabric, and transform attribute changes to the underlying USD stage are reflected in Fabric by the Fabric population interface USD notice handler. Like with OmniHydra, these values in Fabric represent an absolute world-space transform for the prim, and any changes to these values in Fabric does not represent a hierarchical transform change. There is no transform change that can be made in Fabric that will affect transform descendants of that prim in a Fabric Scene Delegate powered render.
In summary, support for hierarchical transform changes in Fabric has been somewhat incomplete. IFabricHierarchy was created to add complete, Fabric-native transform hierarchy support with Fabric Scene Delegate.
## Fabric Transforms with Fabric Scene Delegate and IFabricHierarchy
Kit 106 adds a new interface for use with Fabric Scene Delegate called IFabricHierarchy. This interface is not supported with OmniHydra.
### New transform attributes
When Fabric is populated from the USD Stage while Fabric Scene Delegate is enabled, every Boundable prim has two new attributes created in Fabric:
- `omni:fabric:localMatrix` - the local-to-parent transform of the prim, as a `GfMatrix4d`
- `omni:fabric:worldMatrix` - the world transform of the prim, as a `GfMatrix4d`
- `omni:fabric:worldMatrix` - the local-to-world transform of the prim, as a `GfMatrix4d`
`omni:fabric:localMatrix` is the editable local transform of any prim in Fabric. `omni:fabric:worldMatrix` is the computed, cached, read-only ( * ) world transform of any prim in Fabric. Changes to the value of the `omni:fabric:localMatrix` attribute will cause the `omni:fabric:worldMatrix` attribute of that prim and all of its descendants to be recomputed before the next rendered frame. Fabric Scene Delegate uses the `omni:fabric:worldMatrix` attribute to set prim transform values in the Hydra rendering pipeline.
(*) All attributes in Fabric are writeable, but as a computed value, `omni:fabric:worldMatrix` is intended as a read-only attribute outside of updates from the IFabricHierarchy implementation.
## The IFabricHierarchy interface
IFabricHierarchy is a new interface defined in `includes/usdrt/hierarchy/IFabricHierarchy.h`
`usdrt::hierarchy::IFabricHierarchy`
IFabricHierarchy has a few simple APIs:
- `getFabricHierarchy(fabricId, stageId)` - Get the Fabric Hierarchy instance for a given FabricId and StageId
- `getLocalXform(path)` - Get the local-to-parent transform of a given prim - this just returns the value of the `omni:fabric:localMatrix` attribute in Fabric.
- `getWorldXform(path)` - Get the local-to-world transform of a given prim - note that this value will be computed, so the value returned will always be correct. To query the cached value, `omni:fabric:worldMatrix` can be read from Fabric directly.
- `setLocalXform(path, matrix)` - Update the `omni:fabric:localMatrix` attribute value in Fabric with the new matrix value.
- `setWorldXform(path, matrix)` - Compute a new local-to-parent transform value such that the resulting computed local-to-world transform matches the given transform matrix, and set that value on `omni:fabric:localMatrix`.
- `updateWorldXforms()` - Using Fabric change tracking, update all `omni:fabric:worldMatrix` values for any prim whose `omni:fabric:localMatrix` value has changed, as well as all transform hierarchy descendants of those prims, since the last time `updateWorldXforms()` was called.
These APIs assume a few things about the data stored in Fabric.
- All Boundable prims have an `omni:fabric:localMatrix` and `omni:fabric:worldMatrix` attribute authored. This is enforced for prims that originate from USD by the Fabric population interface that ships with Fabric Scene Delegate. For prims that are created and only exist in Fabric, these attributes may need to be created directly or by using the RtXformable API:
- `usdrt::RtXformable::CreateFabricHierarchyLocalMatrixAttr()`
- `usdrt::RtXformable::CreateFabricHierarchyWorldMatrixAttr()`
- All prims in Fabric have been registered with the Fabric Connectivity API. This happens automatically for prims originating from USD and prims created with `usdrt::UsdStage::DefinePrim()`. The Connectivity API enables Fabric to establish a transform hierarchy for prims that only exist in Fabric.
<span class="pre">
omni:fabric:localMatrix
</span>
</code>
always represents the correct and most recent local transform for the prim. This is enforced for changes on the USD stage by the Fabric Scene Delegate USD Notice handler - any transform change on any prim in USD is immediately reflected as an update in Fabric on the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
</span>
</code>
attribute for the corresponding Fabric prim.
</p>
</li>
</ul>
<p>
With IFabricHierarchy, the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:worldMatrix
</span>
</code>
attribute represents a cached value of the world transform of the prim. That value is only updated when
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
</span>
</code>
is called on the interface - this allows changes to
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
</span>
</code>
to happen quickly and at scale without the cost of recomputing potentially thousands of
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:worldMatrix
</span>
</code>
values that might otherwise be incurred in order to reflect changes inherited through the transform hierarchy every time a single prim transform is modified. Because of this, it is possible that the value for any
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:worldMatrix
</span>
</code>
attribute is stale or out of date unless
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
</span>
</code>
has been called recently. Within the Kit application,
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
</span>
</code>
is called immediately prior to rendering every frame, so that Fabric Scene Delegate and the RTX renderer pull the latest and correct world transform values directly from Fabric.
</p>
<p>
In order to discover the world transform of any prim at any time, regardless of when
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
</span>
</code>
was last called,
<code class="docutils literal notranslate">
<span class="pre">
getWorldXform()
</span>
</code>
will calculate the correct value using the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
</span>
</code>
values of the prim and its ancestors.
</p>
<p>
While
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
</span>
</code>
is always called just before rendering, this method may be called any time that it is desirable to have the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:worldMatrix
</span>
</code>
attribute values in Fabric reflect hierarchical transform changes from modifications to
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
</span>
</code>
since the last time
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
</span>
</code>
was called, such as at the start of a simulation step. If there have been no changes since the last call to
<code class="docutils literal notranslate">
<span class="pre">
updateWorldXforms()
</span>
</code>
, this call does nothing.
</p>
</section>
</section>
<section id="code-examples">
<h2>
Code Examples
</h2>
<section id="getting-and-changing-the-local-transform-of-a-prim">
<h3>
Getting and changing the local transform of a prim
</h3>
<p>
The local transform of a prim can be modified by directly changing the
<code class="docutils literal notranslate">
<span class="pre">
omni:fabric:localMatrix
</span>
</code>
attribute in Fabric, using USDRT APIs to change the value, or using the IFabricHierarchy interface.
</p>
<section id="using-usdprim-and-usdattribute-apis-in-usdrt">
<h4>
Using UsdPrim and UsdAttribute APIs in USDRT
</h4>
<div class="highlight-python notranslate">
<div class="highlight">
<pre><span></span><span class="kn">from</span> <span class="nn">usdrt</span> <span class="kn">import</span> <span class="n">Gf</span><span class="p">,</span> <span class="n">Sdf</span><span class="p">,</span> <span class="n">Usd</span>
<span class="n">stage</span> <span class="o">=</span> <span class="n">Usd</span><span class="o">.</span><span class="n">Stage</span><span class="o">.</span><span class="n">Open</span><span class="p">(</span><span class="n">scene_path</span><span class="p">)</span>
<span class="n">prim</span> <span class="o">=</span> <span class="n">stage</span><span class="o">.</span><span class="n">GetPrimAtPath</span><span class="p">(</span><span class="n">prim_path</span><span class="p">)</span>
<span class="n">attr</span> <span class="o">=</span> <span class="n">prim</span><span class="o">.</span><span class="n">GetAttribute</span><span class="p">(</span><span class="s2">"omni:fabric:localMatrix"</span><span class="p">)</span>
<span class="n">current_xform</span> <span class="o">=</span> <span class="n">attr</span><span class="o">.</span><span class="n">Get</span><span class="p">()</span>
<span class="n">new_xform</span> <span class="o">=</span> <span class="n">Gf</span><span class="o">.</span><span class="n">Matrix4d</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">new_xform</span><span class="o">.</span><span class="n">SetTranslateOnly</span><span class="p">((</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">15</span><span class="p">,</span> <span class="mi">200</span><span class="p">))</span>
<span class="n">attr</span><span class="o">.</span><span class="n">Set</span><span class="p">(</span><span class="n">new_xform</span><span class="p">)</span>
</pre>
</div>
</div>
</section>
<section id="using-rtxformable-api-in-usdrt">
<h4>
Using RtXformable API in USDRT
</h4>
<div class="highlight-python notranslate">
<div class="highlight">
<pre><span></span><span class="kn">from</span> <span class="nn">usdrt</span> <span class="kn">import</span> <span class="n">Gf</span><span class="p">,</span> <span class="n">Sdf</span><span class="p">,</span> <span class="n">Usd</span><span class="p">,</span> <span class="n">Rt</span>
<span class="n">stage</span> <span class="o">=</span> <span class="n">Usd</span><span class="o">.</span><span class="n">Stage</span><span class="o">.</span><span class="n">Open</span><span class="p">(</span><span class="n">scene_path</span><span class="p">)</span>
<span class="n">prim</span> <span class="o">=</span> <span class="n">stage</span><span class="o">.</span><span class="n">GetPrimAtPath</span><span class="p">(</span><span class="n">prim_path</span><span class="p">)</span>
<span class="n">xformable</span> <span class="o">=</span> <span class="n">Rt</span><span class="o">.</span><span class="n">Xformable</span><span class="p">(</span><span class="n">prim</span><span class="p">)</span>
<span class="n">attr</span> <span class="o">=</span> <span class="n">xformable</span><span class="o">.</span><span class="n">GetFabricHierarchyLocalMatrixAttr</span><span class="p">()</span>
<span class="n">current_xform</span> <span class="o">=</span> <span class="n">attr</span><span class="o">.</span><span class="n">Get</span><span class="p">()</span>
<span class="n">new_xform</span> <span class="o">=</span> <span class="n">Gf</span><span class="o">.</span><span class="n">Matrix4d</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">new_xform</span><span class="o">.</span><span class="n">SetTranslateOnly</span><span class="p">((</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">15</span><span class="p">,</span> <span class="mi">200</span><span class="p">))</span>
</pre>
</div>
</div>
</section>
## Using IFabricHierarchy Interface
```python
from usdrt import Gf, Sdf, Usd, hierarchy
stage = Usd.Stage.Open(scene_path)
stage_id = stage.GetStageIdAsStageId()
fabric_id = stage.GetFabricId()
hier = hierarchy.IFabricHierarchy().get_fabric_hierarchy(fabric_id, stage_id)
current_xform = hier.get_local_xform(prim_path)
new_xform = Gf.Matrix4d(1)
new_xform.SetTranslateOnly((10, -15, 200))
hier.set_local_xform(prim_path, new_xform)
```
## Getting the last computed world transform value
The last computed world transform value for a prim can be retrieved directly from Fabric using Fabric or USDRT APIs.
### Using UsdPrim and UsdAttribute APIs in USDRT
```python
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(scene_path)
prim = stage.GetPrimAtPath(prim_path)
attr = prim.GetAttribute("omni:fabric:worldMatrix")
cached_world_xform = attr.Get()
```
### Using RtXformable API in USDRT
```python
from usdrt import Gf, Sdf, Usd, Rt
stage = Usd.Stage.Open(scene_path)
prim = stage.GetPrimAtPath(prim_path)
xformable = Rt.Xformable(prim)
attr = xformable.GetFabricHierarchyWorldMatrixAttr()
cached_world_xform = attr.Get()
```
## Getting the computed world transform of a prim
The IFabricHierarchy interface can compute the correct world transform of any prim, regardless of when the last call to `updateWorldXforms()` was made.
```python
from usdrt import Gf, Sdf, Usd, hierarchy
stage = Usd.Stage.Open(scene_path)
stage_id = stage.GetStageIdAsStageId()
fabric_id = stage.GetFabricId()
hier = hierarchy.IFabricHierarchy().get_fabric_hierarchy(fabric_id, stage_id)
current_world_xform = hier.get_world_xform(prim_path)
```
## Set a computed local transform from a world transform value
The IFabricHierarchy interface can compute a local transform for a prim using the transforms of the ancestors of that prim, such that the new value transforms the prim to the desired transform in world space.
```python
from usdrt import Gf, Sdf, Usd, hierarchy
# Code block for setting computed local transform
```
stage = Usd.Stage.Open(scene_path)
stage_id = stage.GetStageIdAsStageId()
fabric_id = stage.GetFabricId()
hier = hierarchy.IFabricHierarchy().get_fabric_hierarchy(fabric_id, stage_id)
result = hier.get_world_xform(path)
expected = Gf.Matrix4d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 90, 0, 0, 1)
self.assertEqual(result, expected)
hier.set_world_xform(path, Gf.Matrix4d(1))
hier.update_world_xforms()
local_result = hier.get_local_xform(path)
local_expected = Gf.Matrix4d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, -90, 0, 0, 1)
self.assertEqual(local_result, local_expected)
```
### Timesampled Transforms
Fabric does not have native support for USD timesamples - the StageReaderWriter is a snapshot of composed data on the stage at a single point in time.
Fabric Scene Delegate builds on top of Fabric by adding limited timesample support. Fabric Scene Delegate’s population utilities will listen for changes to the timeline in Kit, and populate timesampled attributes into Fabric at the time selected in the playback timeline, overwriting any previously existing value in Fabric. This is the case for timesampled transforms as well.
IFabricHierarchy will update calculate and update `omni:fabric:worldMatrix` for transform hierarchy descendants of any prims with timesampled transforms whose values are updated by Fabric Scene Delegate population when `updateWorldXforms()` is called.
### Backward Compatibility Layer
In order to support existing OmniHydra applications, a degree of backwards compatibility has been added to help developers bridge the gap to the new interface and transform attributes.
If these attributes exist and have been modified since the last call to `updateWorldXforms()` …
- `_worldPosition`
- `_worldOrientation`
- `_worldScale`
…then their values will be used to calculate and set the corresponding `omni:fabric:localMatrix` value for the prim at the beginning of the next `updateWorldXforms()` call.
Similarly, if a `_localMatrix` attribute exists and was modified since the last call to `updateWorldXforms()`, then its value will be copied directly to `omni:fabric:localMatrix` for the prim.
This fallback behavior adds calculation overhead and will be more expensive than writing `omni:fabric:localMatrix` directly. It is recommended that developers update to the new interface for the best performance with transforms in Fabric.
### Behavior when writing `omni:fabric:worldMatrix`
While `omni:fabric:worldMatrix` is not intended to be modified outside the IFabricHierarchy implementation, Fabric does not provide attribute permissions or other concepts, so it is possible to write the `omni:fabric:worldMatrix` value at any time using USDRT or Fabric APIs. In the event that this happens, it will
be inferred that this is a new target world transform for the prim,
and IFabricHierarchy will compute a new
```code
omni:fabric:localMatrix
```
value at the start of the next
```code
updateWorldXforms()
```
call. In
addition to being expensive to compute, it is also potentially
incorrect in the event that several of these attributes were
modified in a hierarchically dependent way - there is no way to
unravel an intended order of operations for calculating the new
```code
omni:fabric:localMatrix
```
attributes. |
faq.md | # Frequently Asked Questions
## What’s the difference between a Python node and a C++ node?
From the user’s point of view there isn’t really a difference. They both behave the same way, have the same types of attributes, store their data in Fabric, and are backed by USD. The real difference is on the node writing side. C++ is generally more difficult to write as it has strong typing requirements and less flexible data structures. On the other hand it is much more performant. A C++ node will often be an order of magnitude faster than an equivalent Python node.
## Once I choose Python or C++ for my node am I stuck with it?
No indeed! The architecture is set up so that the definition of the authoring graph, described in the .ogn file, is independent of its implementation. You can quickly prototype a node using Python so that you can try out your ideas, and then later if you want to speed it up you can rewrite the node implementation in C++ without touching the .ogn file and anyone that uses that node will invisibly benefit from the faster performance. |
fat-package_packaging_app.md | # Package App
## Production Build
### Set Application Version
The Application version can be set in `.\tools\VERSION.md`. This version will be used in for example the Application title bar but also in places such as the Omniverse Launcher’s `description.toml` file where a launcher package created as detailed below.
### Cleaning up
Packages are created from the contents of the `_build` directory. The kit-app-template repo comes with some Application and Extension examples, and we have created a couple of new ones along the way. This is a tutorial so it’s okay if we have some extra files; however, for production development the project should only contain elements that are intended to be released. The following instructions are intended to help with creating a clean build - but not critical for the tutorial.
1. Assuming we want to package just the `my_company.usd_explorer` app, make sure the `.\premake5.lua` only has the `define_app("my_company.usd_explorer")` entry in the `-- Apps` section.
2. Make sure these dependencies are not part of the Application kit file:
- `omni.kit.window.extensions`
- `omni.kit.debug.vscode`
3. For any Extension that should NOT be included - such as `omni.hello.world` - the Extension specific `premake5.lua` file can be either deleted or fully commented out:
```c++
-- Use folder name to build Extension name and tag.
-- local ext = get_current_extension_info()
-- project_ext(ext)
-- Link only those files and folders into the Extension target directory
```
-- repo_build.prebuild_link {"docs", ext.target_dir.."/docs"}
-- repo_build.prebuild_link {"data", ext.target_dir.."/data"}
-- repo_build.prebuild_link {"omni", ext.target_dir.."/omni"}
4.
- Delete the `_build` directory - either manually or by running `build -c`.
- Run `build`.
Note that the build directory only has `.bat` and `.sh` files for the Application we’re wanting to package - with the addition of a few created by default.
Locking Extension Versions
=========================
The build command is used throughout this tutorial. Before creating a package for distribution of the app, it is recommended to lock the Extension versions. There’s no harm in doing this with iterative builds during development as well - but more important prior to releasing an app.
1. Open the `.\repo.toml` file.
2. Edit the kit file(s) that should have locked Extension versions in the `[repo_precache_exts]` section. For the `my_company.usd_explorer` app, change the `apps` setting to the below:
```c++
[repo_precache_exts]
# Apps to run and precache
apps = [
"${root}/source/apps/my_company.usd_explorer.kit"
]
```
3. Add Extension versions by running the command `repo precache_exts -u`.
4. Note the section labeled `BEGIN GENERATED PART` in `my_company.usd_explorer.kit` - this is where Extension versions are locked down.
We now have a clean version locked build ready to be packaged.
Note
====
Reference: [Building an App](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html)
Warmup Script
=============
When an end user installs an Application we can provide a `warmup procedure` that caches shaders and does a few other things to improve the Application startup performance. This is an optional step and is most relevant to packages published via an Omniverse Launcher.
1. Open `.\kit-app-template\premake5.lua`.
2. Note this section:
```lua
-- App warmup script for the Launcher
create_app_warmup_script("omni.usd_explorer", {
args = "--exec \"open_stage.py ${SCRIPT_DIR}exts/omni.usd_explorer.setup/data/BuiltInMaterials.usda\" --/app/warmupMode=1 --no-window --/app/extensions/excluded/0='omni.kit.splash' --/app/extensions/excluded/1='omni.kit.splash.carousel' --/app/extensions/excluded/2='omni.kit.window.splash' --/app/settings/persistent=0 --/app/settings/loadUserConfig=0 --/structuredLog/enable=0 --/app/hangDetector/enabled=0 --/crashreporter/skipOldDumpUpload=1 --/app/content/emptyStageOnStart=1 --/app/window/showStartup=false --/rtx/materialDb/syncLoads=1 --/omni.kit.plugin/syncUsdLoads=1 --/rtx/hydra/materialSyncLoads=1 --/app/asyncRendering=0 --/app/file/ignoreUnsavedOnExit=1 --/renderer/multiGpu/enabled=0 --/app/quitAfter=10"
})
```
3. By including this section for the app, an additional
```
[app name].warmup.bat\.sh
```
is added in the build. Go ahead and change
```
omni.usd_explorer
```
to
```
my_company.usd_explorer
```
(there’s two places):
```c++
-- App warmup script for the Launcher
create_app_warmup_script("my_company.usd_explorer", {
args = "--exec \"open_stage.py ${SCRIPT_DIR}exts/my_company.usd_explorer.setup/data/BuiltInMaterials.usda\" --/app/warmupMode=1 --no-window --/app/extensions/excluded/0='omni.kit.splash' --/app/extensions/excluded/1='omni.kit.splash.carousel' --/app/extensions/excluded/2='omni.kit.window.splash' --/app/settings/persistent=0 --/app/settings/loadUserConfig=0 --/structuredLog/enable=0 --/app/hangDetector/enabled=0 --/crashreporter/skipOldDumpUpload=1 --/app/content/emptyStageOnStart=1 --/app/window/showStartup=false --/rtx/materialDb/syncLoads=1 --/omni.kit.plugin/syncUsdLoads=1 --/rtx/hydra/materialSyncLoads=1 --/app/asyncRendering=0 --/app/file/ignoreUnsavedOnExit=1 --/renderer/multiGpu/enabled=0 --/app/quitAfter=10"
})
```
4. Run a build.
5. A
```
my_company.usd_explorer.warmup.bat\.sh
```
file was created in the build directory.
6. To prepare for a Launcher package, open
```
.kit-app-template\source\launcher\launcher.toml
```
.
7. Note the per platform
```
post-install = ""
```
entries. Edit these settings to provide the warmup script (the default has them commented out):
```toml
[defaults.windows-x86_64.install]
...
post-install = "${productRoot}/my_company.usd_explorer.warmup.bat"
...
[defaults.linux-x86_64.install]
...
post-install = "${productRoot}/my_company.usd_explorer.warmup.sh"
...
```
## Fat Package
A “fat” package includes **everything** to run the app: Kit Kernel and all Extensions. This package type should be used when the goal is to not require an end user to have to download anything at time of installation. This type of package is suitable for environments that do not have access to public repositories - such as air gapped organizations.
1. Create a production build.
2. Run `repo package` command (command cheat-sheet).
3. Package is created in `.\_build\packages`.
## Thin Package
A “thin” package contains the **bare minimum** required for an installation to be possible - but requires the ability to download Kit Kernel and Extensions when the app is installed.
Installed thin packaged apps make use of shared storage of Kit Kernel and Extensions. This approach optimizes the use of local storage - only downloading components that have not already been downloaded by other thin packaged apps. This package type is not suitable for air gapped environments.
1. Create a production build.
2. Run `repo package --thin` command (command cheat-sheet).
3. Package is created in `.\_build\packages`.
installation if they are not already installed from some prior installation.
The package can be renamed - nothing inside the package depends on the package name- and be
published.
## Launcher Package
Omniverse Launcher is an Application for distributing solutions to Omniverse users. This project has tools to create
an Application package that can be installed via the IT Managed Launcher. The package can be “fat” or “thin” as mentioned above -
but will also contain additional metadata so that end users can see it within the Launcher.
There are source files within this project that are used for this kind of a package - you’ll find them in `.\source\launcher`.
### Launcher Data
File: `.\source\launcher\launcher.toml`.
This file provides settings for the Launcher used at installation. Be sure to set the `entrypoint` and `command` fields
for Windows and/or for Linux to the `.bat` and `.sh` files launching your Application.
Example for `my_company.usd_explorer` app:
```toml
## install and launch instructions by environment
[defaults.windows-x86_64]
...
entrypoint = "${productRoot}/my_company.usd_explorer.bat"
...
[defaults.windows-x86_64.open]
command = "${productRoot}/my_company.usd_explorer.bat"
...
[defaults.windows-x86_64.install]
...
[defaults.linux-x86_64]
url = ""
entrypoint = "${productRoot}/my_company.usd_explorer.sh"
...
```
### Images
The following images inside `.\source\launcher` should be updated according to the intended branding:
- `background.png`
- `card.png`
- `icon.png`
- `icon_ovc.png`
- `image.png`
Do NOT change the resolution of these images.
### Metadata
File: `.\source\launcher\description.toml`.
#### Version
If you leave `version = "${version}"` then the version label will be injected automatically using
version mentioned in `.\tools\VERSION.md`. It could also be written “manually” here if that is desirable.
#### Slug
A critical entry in this file is the `slug`. The `slug` is an identifier that is not used by the UI.
Keep this the same for all versions of the app so that users can see updates and versions in a single place:
```toml
#unique identifier for component, all lower case, persists between versions
slug = "my_company.usd_explorer"
```
#### URL
Another critical entry is the `[url]`: only define the platform(s) supported by the package you are creating.
For example, remove the `windows-x86_64` entry if only Linux is supported by the given package.
```toml
[url]
```
windows-x86_64 = 'windows-x86_64/package.zip'
linux-x86_64 = 'linux-x86_64/package.zip'
```
## Launcher UI Data
Here are other metadata fields to use in
```toml
description.toml
```
which are used in the Launcher UI:
- The `Publisher` and `Developer` metadata are *sections* in the toml file; for example:
```toml
[developer]
#name of developer
name = 'My Company'
# hyperlink on developer name (can be left as empty string)
url = 'https://www.my-company.com/'
[publisher]
#name of publisher
name = 'My Company'
# hyperlink on publisher name (can be left as empty string)
url = 'https://www.my-company.com/'
```
- You can add as many `[[links]]` as you’d like.
```toml
[[links]]
title = "My Page"
url = "https://www.my-page.com/"
```
File:
```toml
.\source\launcher\requirements.toml
```
This defines the system requirements for your Application to be used. This metadata is shown
in the `EXCHANGE` section underneath the metadata provided by `description.toml`; for example:
## Command to Package
1. Create a production build.
2. Run `repo package --launcher` or `repo package --launcher --thin` command (command cheat-sheet).
3. Package is created in `.\_build\packages`.
The top level package structure is the same whether the `--thin` argument was used or not:
```
linux-x86_64
package.zip
windows-x86_64
package.zip
background.png
description.toml
icon.png
icon_ovc.png
image.png
requirements.toml
```
What varies is what is inside the `package.zip`. This is where the “thin” or “fat” packaged Application ends up.
The Linux and/or Windows version can be included in the same package. A workstation build can of course only
generate one or the other so if both are to be delivered together you’ll have to manually construct one archive from
two packages.
The package can be renamed - nothing inside the package depends on the package name- and be published.
## Preview in Launcher
Omniverse Launcher (both the *Workstation* and *IT Managed Launcher*) supports installing Applications via commands.
Here’s how to install the package to preview and make sure it is displayed correctly:
1. Make sure an Omniverse launcher is installed.
2. Open up a shell and execute the following (with the appropriate absolute filepath for the zip file):
- **Windows**: `start omniverse-launcher://install?path="C:\my_company.usd_explorer.zip"` command cheat-sheet
- **Linux**: `xdg-open omniverse-launcher://install?path="/home/my_username/my_company.usd_explorer.zip"` command cheat-sheet
3. The Launcher shows an installation progress bar.
4. Once installation is complete, the Application is listed in the `Library` tab’s `Apps` section.
**Note**
Reference: Workstation Launcher
Reference: IT Managed Launcher
## Omniverse Cloud
If you are not familiar with Omniverse Cloud (OVC) then you can read more here.
To package an Application for OVC, use the `repo package --launcher` command mentioned above. This will create the necessary “fat launcher” package. |
fat-package_publish_app.md | # Publish App
## Fat Package
1. Extract the package.
2. Run the appropriate `.bat` / `.sh` file for the app in the root directory of the extracted package.
## Thin Package
1. Extract the package.
2. Run `pull_kit_sdk.bat` / `pull_kit_sdk.sh` in the root directory of the extracted package (requires Internet access). **This only has to be done once** - not every time a user wants to start the app.
3. Run the optional Application warmup script `[app name].warmup.bat` / `[app name].warmup.sh` if it was created.
4. Run the appropriate `.bat` / `.sh` file for the app in the root directory of the extracted package.
## Launcher Package
Launcher packages can be installed via the Omniverse Launcher. The archive should NOT be unzipped prior to installation.
1. Make sure an Omniverse launcher is installed.
2. Open up a shell and execute the following (with the appropriate absolute filepath for the zip file):
- **Windows**: `start omniverse-launcher://install?path="C:\my_company.usd_explorer.zip"` [command cheat-sheet](commands.html#omniverse-launcher-installation)
- **Linux**: `xdg-open omniverse-launcher://install?path="/home/my_username/my_company.usd_explorer.zip"`
- **command cheat-sheet**
- The Launcher shows an installation progress bar.
- Once installation is complete, the Application is listed in the `Library` tab’s `Apps` section.
::: note
**Note**
Reference: IT Managed Launcher (installation instructions applies also to Workstation Launcher)
::: |
files.md | # Files
- [8fa04669143f4cb0/_build/target-deps/hoops_exchange_cad_converter_release/hoops_exchange_cad_converter/include/hoops_reader/CADConverterSpec.h](file_8fa04669143f4cb0__build_target-deps_hoops_exchange_cad_converter_release_hoops_exchange_cad_converter_include_hoops_reader_CADConverterSpec.h.html#c-a-d-converter-spec-8h) |
file_omni_avreality_rain_IPuddleBaker.h.md | # omni/avreality/rain/IPuddleBaker.h
In directory:
omni/avreality/rain
Source file:
omni/avreality/rain/IPuddleBaker.h
## Classes
- **omni::avreality::rain::IPuddleBaker**: Bakes puddle into dynamic textures.
## Namespaces
- **omni::avreality**
- **omni**
- **omni::avreality::rain** |
file_omni_avreality_rain_IWetnessController.h.md | # omni/avreality/rain/IWetnessController.h
In directory:
```
```
omni/avreality/rain
```
Source file:
```
omni/avreality/rain/IWetnessController.h
```
## Classes
- **omni::avreality::rain::IWetnessController**: Controller scene level wetness parameters.
## Namespaces
- **omni::avreality**
- **omni**
- **omni::avreality::rain** |
file_omni_avreality_rain_PuddleBaker.h.md | # omni/avreality/rain/PuddleBaker.h
In directory:
```
```
omni/avreality/rain
```
Source file:
```
omni/avreality/rain/PuddleBaker.h
```
## Classes
- **omni::avreality::rain::PuddleBaker**: Bake puddles into dynamic textures.
## Namespaces
- **omni::avreality**
- **omni**
- **omni::avreality::rain**
``` |
file_omni_avreality_rain_WetnessController.h.md | # omni/avreality/rain/WetnessController.h
In directory:
```
```
omni/avreality/rain
```
Source file:
```
omni/avreality/rain/WetnessController.h
```
## Classes
- **omni::avreality::rain::WetnessController**: Controller for scene level wetness parameters.
## Namespaces
- **omni::avreality**
- **omni**
- **omni::avreality::rain** |
fixed_CHANGELOG.md | # Changelog
This document records all notable changes to the **omni.kit.commands** extension.
The format is based on [Keep a Changelog](https://keepachangelog.com). The project adheres to [Semantic Versioning](https://semver.org).
## [1.4.8] - 2023-08-22
### Added
- Option to disallow Redo when calling Undo
## [1.4.9] - 2023-08-22
### Changed
- Removed Redo kwarg from Undo
## [1.4.8] - 2023-08-22
### Added
- Option to disallow Redo when calling Undo
## [1.4.7] - 2023-08-17
### Added
- OM-77258: New ChangeDraggableSettingCommand
## [1.4.6] - 2022-10-27
### Added
- Support for pre- and post-undo callbacks
## [1.4.5] - 2022-10-06
## Fixed
- Don’t assume that get_history_item() always returns a valid entry.
## [1.4.4] - 2022-08-30
### Added
- Support for specifying optional and required keyword arguments when registering commands from C++
## [1.4.3] - 2022-08-23
### Changed
- Removed check for kwargs default.
## [1.4.2] - 2022-08-02
### Fixed
- Ensure GIL when calling back into python functions.
## [1.4.1] - 2022-06-16
### Fixed
- Command groups now fire events to callbacks registered using ‘omni.kit.undo.subscribe_on_change’.
## [1.4.0] - 2022-06-02
### Added
- Support for repeating the last command that was executed or redone.
## [1.3.1] - 2022-06-01
### Added
- Support for specifying default keyword arguments to C++ commands.
## [1.3.0] - 2022-05-26
### Added
- C++ support for registering, deregistering, executing, and undoing/redoing commands.
- Support for preventing groups of commands from being added to the undo stack.
## [1.2.2] - 2022-05-05
### Changed
- Use relative import to avoid exposing _call_callbacks() to users.
## [1.2.1] - 2022-04-20
### Fixed
- Callbacks now fire on redo.
- Callbacks now fire within the command’s undo block.
## [1.2.0] - 2022-02-10
### Added
- Support for pre- and post-do callbacks
## [1.1.0] - 2021-12-30
### Added
- added @abstractmethod to ‘do()’ method
## [1.0.0] - 2019-06-18
### Added
- Initial Commands System |
flow-omniverse-fluid-dynamics_index.md | # flow: Omniverse Fluid Dynamics
## FlowUsd :package:
Repository created: 2022-06-24 by jcarius
This is the repository home for building FlowUSD and its USD schema in the same repository.
The `master` branch remains unchanged from the kit-extension template repository to allow for occasional merging.
This README file provides a quick overview. In-depth documentation can be found at:
📖 [FlowUSD Documentation](#)
Teamcity Project
## Building
To build everything run `.\build.bat` or `.\build.bat --rebuild`
To build the FlowUsd kit extensions run `.\buildExtensions.bat`
## Run
`.\_build\windows-x86_64\release\omni.app.flowusd.bat`
## Testing
`repo.bat test`
## Packaging and publishing
### Kit Extension Registry
To publish extension to the extension registry `.\repo.bat publish_exts`.
This will publish all extensions as configured in the repo.toml.
Note that existing versions should not be overridden, so increment the version in the respective `extension.toml` first before publishing.
More fine-grained control/manual publishing is possible with `.\_build\windows-x86_64\release\omni.app.flowusd.bat --publish omni.usd.schema.flow`.
Note that publishing needs to be run both from windows and linux.
The packages in the registry are automatically named with version and platform information, e.g., publishing `omni.flowusd` version `0.3.0` on windows yields `omni.flowusd-0.3.0+wx64.r.cp37`.
To list published packages execute `.`
```pre
.\_build\windows-x86_64\release\omni.app.flowusd.bat
```
```pre
--list-registry-exts
```
</code>
</p>
<p>
To un-publish (dangerous!) extensions:
<code class="docutils literal notranslate">
```pre
.\_build\windows-x86_64\release\omni.app.flowusd.bat
```
```pre
--unpublish
```
```pre
omni.usd.schema.flow
```
</code>
</p>
</section>
<section id="packman-packaging">
<h4>
Packman packaging
</h4>
<p>
<em>
Note: This is currently not used
</em>
</p>
<p>
<code class="docutils literal notranslate">
```pre
repo.bat
```
```pre
package
```
```pre
-m
```
```pre
omni.usd.schema.flow
```
</code>
,
<code class="docutils literal notranslate">
```pre
repo.bat
```
```pre
package
```
```pre
-m
```
```pre
omni.flowusd
```
</code>
</p>
<p>
This will place the packages in
<code class="docutils literal notranslate">
```pre
_build/packages
```
</code>
. Then
<code class="docutils literal notranslate">
```pre
repo.bat
```
```pre
publish
```
</code>
will upload them to packman. This allows other kit projects to include flowusd in their target dependencies with
</p>
<div class="highlight-c++ notranslate">
<div class="highlight">
<pre><span></span><span class="o"><</span><span class="n">dependency</span><span class="w"> </span><span class="n">name</span><span class="o">=</span><span class="s">"omni.flowusd"</span><span class="w"> </span><span class="n">linkPath</span><span class="o">=</span><span class="s">"../_build/$platform/$config/exts/omni.flowusd"</span><span class="o">></span><span class="w"></span>
<span class="w"> </span><span class="o"><</span><span class="n">package</span><span class="w"> </span><span class="n">name</span><span class="o">=</span><span class="s">"omni.flowusd"</span><span class="w"> </span><span class="n">version</span><span class="o">=</span><span class="s">"0.1.0"</span><span class="w"> </span><span class="o">/></span><span class="w"></span>
<span class="o"></</span><span class="n">dependency</span><span class="o">></span><span class="w"></span>
</pre>
</div>
</div>
</section>
<section id="updating">
<h3>
Updating
</h3>
<p>
This repo carries a number dependencies with fixed versions.
To update them proceed as follows:
</p>
<ul>
<li>
<p>
Packman.xml files in
<code class="docutils literal notranslate">
```pre
deps
```
</code>
: These should be updated by merging the newest version from
kit-template
.
Thanks to automatic repo mirroring the
<code class="docutils literal notranslate">
```pre
master
```
</code>
branch of this repository is synced with the kit-template repo. The commands for updating are hence
</p>
<div class="highlight-none notranslate">
<div class="highlight">
<pre><span></span> git checkout flowusd-master
git fetch origin master:master
git pull origin master:master
</pre>
</div>
</div>
<p>
If there are conflicts due to changes to files that have been deleted in
<code class="docutils literal notranslate">
```pre
flowusd-master
```
</code>
, e.g., example packages, just accept the deleted version.
</p>
</li>
<li>
<p>
Don’t forget to update the changelog!
</p>
</li>
</ul>
</section>
<section id="using-a-local-build-of-kit-sdk">
<h3>
Using a Local Build of Kit SDK
</h3>
<p>
By default packman downloads Kit SDK (from
<code class="docutils literal notranslate">
```pre
deps/kit-sdk.packman.xml
```
</code>
). For developing purposes local build of Kit SDK can be used.
</p>
<p>
To use your local build of Kit SDK, assuming it is located say at
<code class="docutils literal notranslate">
```pre
C:/projects/kit
```
</code>
.
</p>
<p>
Use
<code class="docutils literal notranslate">
```pre
repo_source
```
</code>
tool to link:
</p>
<blockquote>
<div>
<p>
<code class="docutils literal notranslate">
```pre
repo
```
```pre
source
```
```pre
link
```
```pre
c:/projects/kit/kit
```
</code>
</p>
</div>
</blockquote>
<p>
Or you can also do it manually: create a file:
<code class="docutils literal notranslate">
```pre
deps/kit-sdk.packman.xml.user
```
</code>
containing the following lines:
</p>
<div class="highlight-xml notranslate">
<div class="highlight">
<pre><span></span><span class="nt"><project</span> <span class="na">toolsVersion=</span><span class="s">"5.6"</span><span class="nt">></span>
<span class="nt"><dependency</span> <span class="na">name=</span><span class="s">"kit_sdk_${config}"</span> <span class="na">linkPath=</span><span class="s">"../_build/${platform}/${config}/kit"</span><span class="nt">></span>
<span class="nt"><source</span> <span class="na">path=</span><span class="s">"c:/projects/kit/kit/_build/$platform/$config"</span> <span class="nt">/></span>
<span class="nt"></dependency></span>
<span class="nt"></project></span>
</pre>
</div>
</div>
<p>
To see current source links:
</p>
<blockquote>
<div>
<p>
<code class="docutils literal notranslate">
```pre
repo
```
```pre
source
```
```pre
list
```
</code>
</p>
</div>
</blockquote>
<p>
To remove source link:
</p>
<blockquote>
<div>
<p>
<code class="docutils literal notranslate">
```pre
repo
```
```pre
source
```
```pre
unlink
```
```pre
kit-sdk
```
</code>
</p>
</div>
</blockquote>
<p>
To remove all source links:
</p>
<blockquote>
<div>
<p>
<code class="docutils literal notranslate">
```pre
repo
```
```pre
source
```
```pre
clear
```
</code>
</p>
</div>
</blockquote>
</section>
<section id="using-a-local-build-of-another-extension">
### Using a Local Build of another Extension
Other extensions can often come from the registry to be downloaded by kit at run-time or build-time (e.g.
```
\`\`\`
omni.app.my_app.kit
\`\`\`
example). Developers often want to use a local clone of their repo to develop across multiple repos simultaneously.
To do that additional extension search path needs to be passed into kit pointing to the local repo. There are many ways to do it. Recommended is using
```
\`\`\`
deps/user.toml
\`\`\`
. You can use that file to override any setting.
Create
```
\`\`\`
deps/user.toml
\`\`\`
file in this repo with the search to path to your repo added to
```
\`\`\`
app/exts/folders
\`\`\`
setting, e.g.:
```
\`\`\`toml
[app.exts]
folders."++" = [ "c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts" ]
\`\`\`
\`\`\`
repo source tool can also be used to create and edit
\`\`\`
user.toml
\`\`\`
. Provide a path to a repo or a direct path to an extension(s):
> \`\`\`
> repo source link [repo_path]
> \`\`\`
> - If repo produces kit extensions add them to
> \`\`\`
> deps/user.toml
> \`\`\`
> file.
> \`\`\`
> repo source link [ext_path]
> \`\`\`
> - If the path is a kit extension or folder with kit extensions add to
> \`\`\`
> deps/user.toml
> \`\`\`
> file.
Other options:
- Pass CLI arg to any app like this:
\`\`\`
--ext-folder c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts
\`\`\`
.
- Use *Extension Manager UI (Gear button)*.
- Use other
\`\`\`
user.toml
\`\`\`
(or other) configuration files, refer to Kit Documentation: Configuration.
You can always find out where an extension is coming from in *Extension Manager* by selecting an extension and hovering over the open button.
You can also find it in the log, by looking either for
\`\`\`
registered
\`\`\`
message for each extension or
\`\`\`
About to startup:
\`\`\`
when it starts.
### Other Useful Links
- See Kit Manual.
- See Kit Developer Documentation Index.
- See Anton’s Video Tutorials for Anton’s videos about the build systems. |
fonts.md | # Fonts
## Font style
It’s possible to set different font types with the style. The style key ‘font’ should point to the font file, which allows packaging of the font to the extension. We support both TTF and OTF formats. All text-based widgets support custom fonts.
```python
with ui.VStack():
ui.Label("Omniverse", style={"font":"${fonts}/OpenSans-SemiBold.ttf", "font_size": 40.0})
ui.Label("Omniverse", style={"font":"${fonts}/roboto_medium.ttf", "font_size": 40.0})
```
## Font size
It’s possible to set the font size with the style.
Drag the following slider to change the size of the text.
```python
def value_changed(label, value):
label.style = {"color": ui.color(0), "font_size": value.as_float}
slider = ui.FloatSlider(min=1.0, max=150.0)
slider.model.as_float = 10.0
label = ui.Label("Omniverse", style={"color": ui.color(0), "font_size": 7.0})
slider.model.add_value_changed_fn(partial(value_changed, label))
``` |
Framework.md | # Carbonite Framework
## Carbonite Framework
The key ingredient of Carbonite is what we call the Carbonite `carb::Framework`. It is the core entity which manages plugins and their interfaces. This guide describes the plugin management functionality of the Carbonite Framework. The Framework itself is versioned and when a plugin is loaded, the Framework ensures that its version is compatible with the Framework version that the plugin expects.
## Plugins
Plugins are dynamic libraries that provide one or more interfaces. An Interface is an API (with a versioned, stable ABI) that applications can use to access functionality in a plugin.
## About Interfaces and Authoring a Plugin
See the Guide for a walkthrough of authoring a plugin, and information about interfaces and versioning.
## Starting Carbonite
The Carbonite Framework is found in `carb.dll` (Windows), `libcarb.so` (Linux) or `libcarb.dylib` (Mac). You can either use the package-provided import library to import the functions from the Framework, or dynamically load and request the functions by name (rare).
### Declaration of Globals
The `OMNI_APP_GLOBALS` macro specifies the Carbonite application globals:
```c++
OMNI_APP_GLOBALS("example.windowing.native.app", "Native (C++) example app using example.windowing.");
```
This macro ensures that `g_carbClientName` is set to the Client name, and that the default logging channel is set up (the description provided is used as the description for the default logging channel).
Historically, this macro instantiated global variables such as `g_carbFramework` and `g_carbLogging`, but this was changed with Carbonite release v117.0 so that these variables are weakly-linked and need not be instantiated.
For backwards compatibility, older names of this macro exist: `CARB_GLOBALS_EX` (equivalent to `OMNI_APP_GLOBALS`).
## Starting the Framework
Starting the Framework is as easy as using the `OMNI_CORE_INIT` macro.
```cpp
int main(int argc, char** argv)
{
// Startup the Framework
OMNI_CORE_INIT(argc, argv);
carb::Framework* framework = carb::getFramework();
if (!framework)
return EXIT_FAILURE;
return runApp(framework);
}
```
Typically, command-line arguments are passed to the `OMNI_CORE_INIT` macro, but other options are available (see documentation).
This macro ensures that the Framework is acquired (calling `carb::acquireFramework()`), the Omniverse Native Interfaces subsystem is started (calling `omniCoreStart()`), and finally calls `carb::startupFramework()` to initialize the Framework.
The `carb::startupFramework()` function can potentially do a large amount of work. Based on parameters it can load the settings plugin, parse command-line options and environment variables, and register plugins indicated in the configuration file. Check the documentation for `carb::startupFramework()` for more information.
## Clients and Naming
Any entity which uses `carb::Framework` or is a plugin is a *Client*. This generally includes the Carbonite Application itself, as well as any plugins and other libraries (such as script bindings) that interact with the Carbonite Framework. All Clients must have **unique** Client Names as the Framework tracks usages and dependencies by these names. Carbonite Applications declare their Client Name in their Globals declaration. Plugins declare their Client Name in the `carb::PluginImplDesc` struct passed to the `CARB_PLUGIN_IMPL` macro. Script bindings declare their Client Name in their `CARB_BINDINGS` declaration.
If there are multiple definitions of the same interface, the general rule is to uniquely name each plugin by adding a qualifier after the interface name (e.g. *carb.profiler-cpu.plugin*, *carb.profiler-tracy.plugin*, etc.). This approach also means that you cannot have multiple implementations of the same interface in the same plugin (by design).
## 插件注册流程
插件在使用前必须先进行注册。当插件被注册时,会发生以下步骤:
- 使用 `carb::extras::loadLibrary()` 加载插件动态库。
- 如果动态库未被加载,这可能会导致静态初始化器的执行。
- 定位 `omniModuleGetExports()` 函数。如果找到此函数,该库是一个 Omniverse Native Interfaces 模块。插件加载停止,ONI 类型工厂接管。
- 定位并调用 `carbGetFrameworkVersion()` 函数(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)。这用于检查插件与框架之间的兼容性。
- 定位插件注册函数,按以下顺序检查:
1. `carbOnPluginRegisterEx2()`(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)
2. `carbOnPluginRegisterEx()`(已弃用)
3. `carbOnPluginRegister()`(已弃用)
- 定位可选的 `carbGetPluginDeps` 函数(由 `CARB_PLUGIN_IMPL_DEPS` 或 `CARB_PLUGIN_IMPL_NO_DEPS` 宏在插件中实现)。
- 如果注册库将保持库加载(典型情况),则定位以下可选函数:
- `carbOnPluginPreStartup()`(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)
- `carbOnPluginPostShutdown()`(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)
- `carbOnPluginStartupEx()` 或 `carbOnPluginStartup()`(必要时手动实现)
- `carbOnPluginShutdown()`(由 `CARB_PLUGIN_IMPL` 宏在插件中实现)
- **Shutdown Functions**
- `carbOnPluginShutdown()` (Manually implemented if necessary)
- `carbOnPluginQuickShutdown()` (Manually implemented if necessary)
- `carbOnReloadDependency()` (Manually implemented if necessary)
- **Plugin Registration**
- The plugin registration function found above (e.g. `carbOnPluginRegisterEx2`) is called, which gives the plugin information about the Framework and receives information about the plugin.
- The `carbGetPluginDeps` function is called if provided, informing the Framework about the Plugin’s dependencies.
- **Plugin Registration Methods**
- **Registered when starting the Framework**
- Plugins can be registered by `carb::startupFramework()`, typically called from `OMNI_CORE_INIT`.
- Parameters to `carb::startupFramework()` are passed in `carb::StartupFrameworkDesc` via `OMNI_CORE_INIT`.
- If a configuration file or string is passed to `carb::startupFramework()`, the function will attempt to register the specified plugins. See `carb::detail::loadPluginsFromConfig()` for a list of the settings keys and how they’re used.
- **Searching for Plugins Programmatically**
- The `carb::Framework::loadPlugins()` function uses `carb::PluginLoadingDesc` to describe how to search directories to locate and load plugins.
- This is the most common means of finding and loading plugins after startup.
- **Explicitly Registering a Plugin**
- The `carb::Framework::loadPlugin` function allows loading a specific plugin, given the path. This option is rarely used.
- **Registering a Static Plugin**
- In rare cases, an application can register a plugin that actually exists in the application or a plugin. This is accomplished through the `carb::Framework::registerPlugin` function. Plugins registered via this method are never unloaded when their interfaces are released; instead they must be explicitly unloaded with `carb::Framework::unregisterPlugin`.
## Loading Plugins
Typically when a plugin is found, it is loaded immediately. This means the dynamic library is loaded and static initializers within the library will run, and the Framework will locate and call functions exported by the plugin that the Framework uses to discover information about the plugin as described above.
However, if carb::PluginLoadingDesc::unloadPlugins is true, the plugin will be loaded to gather information, but immediately unloaded until an interface is requested. This is rare as it is not the default option. In some cases, the OS loader could choose to keep the library loaded, in which case a warning is logged.
## Acquiring Interfaces
Acquiring an interface gives you an ABI-stable API that you can use to access plugin functionality. Once a plugin is registered and loaded, the Framework will be able to provide interfaces from it.
The first time an interface is acquired from a registered plugin, the plugin is started. To do this, the Framework calls carbOnPluginStartupEx() (or carbOnPluginStartup()). If startup succeeds, the Framework will provide interfaces from the plugin back to the caller.
### getCachedInterface
This is the preferred means of acquiring an interface. Since carb::Framework::tryAcquireInterface does a lot of checking, it can be expensive when repeatedly called (plus, it produces log messages). In order to provide a very cheap way to cache an interface, carb::getCachedInterface() is provided. This is conceptually similar to:
```cpp
// NOTE: Do not actually do this; use carb::getCachedInterface<carb::dictionary::IDictionary>() instead.
static auto dictionary = carb::getFramework()->tryAcquireInterface<carb::dictionary::IDictionary>();
```
However, unlike static, getCachedInterface() will reset its internal pointer to nullptr when the interface (or the Framework) has been released; calling getCachedInterface() after this point will attempt to re-acquire the interface.
The interface acquired will be from the default plugin. A specific plugin name can be provided from which to acquire the interface (but this has caveats). Given the template nature of carb::getCachedInterface(), specifying a plugin requires some special handling in the form of a global char array:
```cpp
const char sGamma[] = "carb.frameworktest.gamma.plugin";
FrameworkScoped f;
f.loadPlugins({"carb.frameworktest.*.plugin"});
auto iface = carb::getCachedInterface<carb::frameworktest::FrameworkTest, sGamma>();
REQUIRE(iface);
CHECK_EQ(iface->getName(), "gamma");
```
## tryAcquireInterface
### tryAcquireInterface
The most common method of acquiring an interface (and the method used by `carb::getCachedInterface()`) is `carb::Framework::tryAcquireInterface`:
```cpp
// Acquire the IDictionary interface (typically this would be carb::getCachedInterface() instead):
carb::dictionary::IDictionary* dict = carb::getFramework()->tryAcquireInterface<carb::dictionary::IDictionary>();
```
If the interface is not available `nullptr` is returned. To debug why an interface cannot be acquired, use verbose logging.
The Framework provides the interface from the default plugin. A specific plugin name can be provided from which to acquire the interface (but this has caveats):
```cpp
auto profiler = carb::getFramework()->tryAcquireInterface<carb::profiler::IProfiler>("carb.profiler-cpu.plugin");
```
**Warning**
As `carb::Framework::tryAcquireInterface` does some level of work for each call with potential logging, it is highly recommended to instead use `carb::getCachedInterface()` instead.
## acquireInterface
### acquireInterface
**Warning**
This function should only be used within plugins and only for interfaces which are declared as dependencies (with `CARB_PLUGIN_IMPL_DEPS`). If it fails to acquire an interface, an error log is issued; this cannot happen for declared dependencies within a plugin as the plugin will fail to load if the dependencies cannot be acquired.
`carb::Framework::acquireInterface` is similar to `carb::Framework::tryAcquireInterface`, but will issue an error log message if the interface cannot be acquired. It will also warn if a Client requests an interface that is not declared as a dependency with `CARB_PLUGIN_IMPL_DEPS`.
Interfaces provided by the same plugin that is acquiring it will not result in any log or warning messages, and need not (nor can be) specified as a dependency.
Generally this method should be avoided unless it is guaranteed that the interface would be available, either by declared dependency or by also being provided by the same plugin.
The Framework provides the interface from the default plugin. A specific plugin name can be provided from which to acquire the interface (but this has caveats):
```cpp
auto profiler = carb::getFramework()->acquireInterface<carb::profiler::IProfiler>("carb.profiler-cpu.plugin");
```
## Acquiring an Interface
To acquire an interface, you can use either `carb::Framework::tryAcquireInterface` or `carb::getCachedInterface()`.
## Acquiring an Interface from a Specific Plugin
### Acquiring an Interface from a Specific Plugin
, `carb::Framework::tryAcquireInterface` and `carb::Framework::acquireInterface` all allow specifying the client name of a plugin (e.g. “carb.profiler-cpu.plugin”) to acquire the interface from a specific plugin.
In most cases, while multiple plugins may provide the same interface, there is nuance to usage. The Profiler example stands here as the profilers require external tools (carb.profiler-tracy.plugin or carb.profiler-nvtx.plugin), or in the case of the serializers (carb.dictionary.serializer-toml.plugin or carb.dictionary.serializer-json.plugin) read and write completely different file types. So while the contract specified by the interface definition is consistent, additional care and programming is generally necessary in using them.
The load order may be non-deterministic and seemingly random. It is generally considered good practice if multiple plugins provide a given interface to set a default plugin.
It is also possible to acquire an interface from the path to the dynamic library file itself. If the dynamic library is not a known plugin, it is registered as a new plugin and loaded. This is accomplished with the `carb::Framework::tryAcquireInterfaceFromLibrary()` function.
## Acquiring an Interface from the Same Plugin as Another Interface
### Acquiring an Interface from the Same Plugin as Another Interface
As a very rare case, it may be desirable to acquire an interface exported by the same plugin as a different interface. To accomplish this, alternate versions of `carb::Framework::acquireInterface` and `carb::Framework::tryAcquireInterface` exist that take any interface pointer.
## Client Spoofing
### Client Spoofing
This is very rarely needed.
Using internal functions, it is possible to “spoof” a plugin. That is, your plugin or application can instruct the Framework to acquire an interface as if it were a different plugin requesting. This is useful for modifying unload order by notifying the Framework of a dependency between two plugins:
```c++
// acquire beta as if we are alpha
auto beta2AsAlpha = static_cast<FrameworkTestSecond*>(f->acquireInterfaceWithClient(
"carb.frameworktest.alpha.plugin", interfaceDesc2, "carb.frameworktest.beta.plugin"));
CARB_UNUSED(beta2AsAlpha);
// acquire gamma2 as if we are beta
auto gamma2AsBeta = static_cast<FrameworkTestSecond*>(f->acquireInterfaceWithClient(
"carb.frameworktest.beta.plugin", interfaceDesc2, "carb.frameworktest.gamma.plugin"));
CARB_UNUSED(gamma2AsBeta);
// acquire gamma as if we are alpha
auto gammaAsAlpha = static_cast<FrameworkTest*>(f->acquireInterfaceWithClient(
"carb.frameworktest.alpha.plugin", interfaceDesc, "carb.frameworktest.gamma.plugin"));
CARB_UNUSED(gammaAsAlpha);
```
## Try Acquiring an Interface Without Loading
This is very rarely needed. It may be needed in circumstances where a circular dependency exists between interfaces and the Framework chooses to shut down a dependent interface prior to plugin shutdown (carbOnPluginShutdown()).
All of the above options will make an attempt to load the plugin in order to acquire the interface. Sometimes this is undesirable–the interface should only be acquired if its plugin is already loaded and the interface acquired elsewhere. This can be accomplished via the carb::Framework::tryAcquireExistingInterface() function.
This is the case in the Profiler system where Settings is used only if it is already available. This is necessary because the Profiler could be loading and it is dangerous to try to load Settings recursively.
```cpp
// Don't try to load settings, but if it's already available we will load settings from it.
auto settings = g_carbFramework->tryAcquireExistingInterface<settings::ISettings>();
```
## Default Plugins
In some cases, it is reasonable to have multiple options for interfaces. A typical example is carb::profiler::IProfiler which is provided by multiple Carbonite plugins: *carb.profiler-cpu.plugin*, *carb.profiler-tracy.plugin*, and *carb.profiler-nvtx.plugin*.
There are multiple ways of declaring the default plugin.
### Version
The *implicit* default plugin is the Framework’s earliest registered match for the highest compatible version for the requested interface. In order to be a compatible version, the *major* version of the plugin’s interface must match the major version of the requested interface, and the *minor* version of the plugin’s interface must be greater-than-or-equal to the minor version of the requested interface.
### Configuration
The configuration file may have a `/defaultPlugins` key that specifies plugin names. See carb::detail::setDefaultPluginsFromConfig() for more information. Note that a listed plugin will become the default for *all* interfaces that it provides.
### Programmatically
An application or plugin may specify a plugin to use as default with the carb::Framework::setDefaultPlugin() function.
For this function to be useful, it must be called to register a default plugin before the interface in question is acquired by *any* clients. This should be done as close to Framework startup as possible.
### Overriding
As mentioned above, the carb::Framework::tryAcquireInterface and carb::Framework::acquireInterface functions allow explicitly providing a plugin name to acquire the interface from that plugin. This will ignore any default plugin.
## Releasing Interfaces
When you acquired a particular interface, carb::Framework tracks this using client name. Usually you don’t need to explicitly release an interface you use. When the plugin is unloaded, all interfaces it acquired are released.
That being said, you can explicitly release with the carb::Framework::releaseInterface function.
When an interface is no longer needed, it can be released using the `releaseInterface` function.
When an interface was acquired by a client, this information is stored in `carb::Framework`. Multiple acquire calls do **not** add up. This means that:
```cpp
IFoo* foo = framework->acquireInterface<IFoo>();
IFoo* foo2 = framework->acquireInterface<IFoo>();
IFoo* foo3 = framework->acquireInterface<IFoo>();
framework->releaseInterface(foo);
```
will release all `foo`, `foo2`, `foo3`, which actually all contain the same pointer value.
Remember that a plugin can implement multiple interfaces. Every interface can be used by multiple clients. Once all interfaces are released by all clients (explicitly or automatically) the plugin is unloaded.
## Unloading Plugins
Once all interfaces to a plugin are released, the plugin is automatically unloaded. However, if a plugin never had any interfaces acquired from it, it remains loaded. It can be explicitly unloaded by plugin name with `carb::Framework::unregisterPlugin` or by library path with `carb::Framework::unloadPlugin`, but given the automatic unloading, this is typically not necessary for dynamic plugins.
Both of these functions also unregister the plugin, so attempting to acquire an interface from it again will not work without re-registering.
It is also possible to unload all plugins with `carb::Framework::unloadAllPlugins`. This is typically done automatically when the Framework is released.
## Plugin Dependencies
Plugins may declare dependencies on interfaces that are required to be available before the plugin. An example of this is *carb.settings.plugin* which is dependent upon *carb.dictionary.plugin*. These are specified with `CARB_PLUGIN_IMPL_DEPS` generally immediately following the `CARB_PLUGIN_IMPL` use:
```cpp
const struct carb::PluginImplDesc kPluginImpl = {"carb.settings.plugin", "Settings storage", "NVIDIA", carb::PluginHotReload::eDisabled, "dev" };
CARB_PLUGIN_IMPL(kPluginImpl, carb::settings::ISettings)
CARB_PLUGIN_IMPL_DEPS(carb::dictionary::IDictionary)
```
In this case, when `carb::getCachedInterface<carb::settings::ISettings>()` executes for the first time, before initializing *carb.settings.plugin*, the Framework will first try to acquire `carb::dictionary::IDictionary` from an available plugin (typically *carb.dictionary.plugin*). Missing dependencies will cause a plugin load to fail, and `nullptr` will be returned as the requested interface could not be acquired.
Carbonite provides a command-line tool, *plugin.inspector* which, given a particular plugin library, can list which interfaces it depends on. Example:
```bash
plugin.inspector.exe carb.assets.plugin.dll
```
Its output:
```json
{
}
```
Listing an interface as a dependency allows your plugin to use `carb::Framework::acquireInterface` (as opposed to `carb::Framework::tryAcquireInterface`) without any fear of error logging or `nullptr` returns.
A best practice is to only list interfaces as dependencies if your plugin cannot function without them. Other interfaces can be considered optional and your plugin can handle the case where the interface is not available. An example of this is `carb.settings.plugin` which requires `carb::dictionary::IDictionary` (and lists it as a dependency as seen above), but `carb.profiler-cpu.plugin` can function just fine without `carb::settings::ISettings`; it merely applies default settings. In this case, `carb::settings::ISettings` is not listed as a dependency in `CARB_PLUGIN_IMPL_DEPS` but the plugin uses `carb::Framework::tryAcquireInterface` and handles the case where `nullptr` is returned.
It’s important to note that dependencies are per plugin and set by the plugin author. Different plugins might implement the same interface, but have different dependencies.
Circular explicit dependencies are not allowed. Having two plugins that are dependent on interfaces from each other will result in an error log message and `nullptr` return from `carb::Framework::acquireInterface`. However, it is perfectly reasonable to allow circular use of interfaces that are acquired optionally upon first use. In this case, do not list the interface in `CARB_PLUGIN_IMPL_DEPS` and use `carb::Framework::tryAcquireInterface` when needed, sometime after startup (i.e. when `carbOnPluginStartup()` is called).
CARB_PLUGIN_IMPL_DEPS specifies explicit dependencies, but any use of carb::Framework::acquireInterface or carb::Framework::tryAcquireInterface (or any of the variations) notifies the Framework of an implicit dependency. The Framework uses this information to determine the order in which plugins should be unloaded.
In general, the Framework will try to unload dependencies after the plugin in which they’re required. In other words, given our example of carb.settings.plugin dependent on carb::dictionary::IDictionary (typically from carb.dictionary.plugin), the Framework would attempt to unload carb.settings.plugin before the plugin providing IDictionary. This allows carb.settings.plugin to continue using IDictionary until it is fully shut down, at which point IDictionary can be shut down.
Since circular usage is allowed (and therefore, circular implicit dependencies), the Framework may not be able to satisfy the above rule. In this case, the Framework will unload in reverse of load order (unload most recently loaded first).
Unload ordering is very complicated and requires that the Framework have an understanding of the explicit and implicit dependencies of all loading plugins. Because acquiring an interface is an implicit dependency, whenever an interface is acquired the Framework will re-evaluate the unload order and log it out (Verbose log level). Turning on Verbose logging can help diagnose unload ordering issues.
## Versioning
The Carbonite Framework uses the concept of semantic versioning to determine a plugin’s compatibility with the Framework, and whether an interface provided by a plugin is compatible with an interface request. Carbonite uses major and minor version numbers to do this:
- The major version number of the candidate must match the major version of the request.
- The minor version number of the candidate must be greater-than-or-equal to the minor version of the request.
Carbonite expresses its concept of a version with the carb::Version struct and checking with comparison operators and the carb::isVersionSemanticallyCompatible() function.
### Framework Compatibility
When a plugin is registered with the Framework, the Framework will find and execute the carbGetFrameworkVersion() function exported by the plugin. This is the version of the Framework that the plugin was built against. In this case, the plugin is considered the requestor and the Framework is considered the candidate. Therefore, the Framework minor version must be greater-than-or-equal the minor version returned by carbGetFrameworkVersion() (and the major versions must match exactly).
If the Framework determines that the plugin is not compatible with it, it will refuse to load.
In order to support plugins compiled at different times, the Carbonite dynamic library will honor multiple versions of the Carbonite Framework. The latest Carbonite version is available as carb::kFrameworkVersion.
### Interface Compatibility
For the many variations on acquiring an interface, a version check is also performed. The Client that calls carb::Framework::tryAcquireInterface (for example) is considered the requestor. The plugins that have been registered with the Framework provide interfaces that are considered the candidates. Every interface has a
InterfaceType::getInterfaceDesc()
function that is generated by the
CARB_PLUGIN_INTERFACE
or
CARB_PLUGIN_INTERFACE_EX
macros (example function:
carb::tasking::ITasking::getInterfaceDesc()
).
The
carb::Framework::tryAcquireInterface
(for example) is a templated inline function that takes the interface type as its template parameter
T
and will call
InterfaceType::getInterfaceDesc()
to provide the interface name and semantic version to the Framework at interface acquire time.
When a plugin or application is built, this inline function is written into a compilation unit and captures the name and version
that the plugin or application knew about when it was built. This information forms the
*request*.
At runtime, the plugin or application passes the interface name and version information that it was built with. If a specific
plugin was given, the Framework checks only that plugin; otherwise the
default plugin
is used (if
no default plugin has been specified or identified, the Framework will select the first registered plugin — in registration
order — with a greater-than-or-equal version to the interface version requested). From this plugin, the Framework will
check to see if an interface candidate is exported whose
*major*
version matches exactly and whose
*minor*
version is
greater-than-or-equal to the requested minor version.
If the version of the candidate has a higher
*major*
version, the Framework will ask the plugin if it can create an interface
for the requested version. This only happens if the plugin supports multiple interface versions.
If no matches are found,
nullptr
is returned to the caller. |
Function.md | # Omni Function
## Omni Function
The `omni::function` is an ABI safe, DLL boundary safe polymorphic function intended to be used in [Omniverse Native Interfaces](../OmniverseNativeInterfaces.html) that provides the functionality of `std::function`. An `omni::function` satisfies `std::is_standard_layout`.
Standard usage is identical to `std::function`:
```cpp
// Basic usage of binding to a lambda expression:
omni::function<int(int)> f = [](int x) { return x + 1; };
assert(f(1) == 2);
// Or bind to a free function:
int double_it(int x)
{
return x * 2;
};
f = double_it;
assert(f(5) == 10);
// Closures are automatically captured:
auto& output = std::cout;
omni::function<void(omni::string)> print =
[&output](omni::string s)
{
output << s << std::endl;
};
print("A message");
void (*printfn)(char const*) =
[](char const* msg)
```
{
output << msg << std::endl;
};
// use of std::bind will also work:
print = std::bind(printfn, "Hello again!");
print();
## omni::function Features
### Relocatable
An `omni::function` is trivially relocatable. This is similar to trivially move constructible, in that `std::memcpy` is an acceptable substitute for actual move-construction, but with the qualification that the moved-from location does not get the destructor called.
> Note
> The examples in this section are demonstration only. You should prefer using the language-specific bindings for working with `omni::function`, like `operator()`, the copy and move constructors and assignment operators, and the destructor in C++.
```cpp
using function_type = omni::function<void()>;
using function_buf = alignas(function_type) char[sizeof(function_type)];
function_buf buf1, buf2;
new static_cast<void*>(buf1) function_type([] { std::println("Hello world\n"); });
// Relocate through memcpy is safe
std::memcpy(buf2, buf1, sizeof buf2);
// buf2 now acts as a function_type
(*reinterpret_cast<function_type*>(buf2))();
// Destroy through the relocated-to position, not the relocated-from
reinterpret_cast<function_type*>(buf2)->~function_type();
```
This concept is useful when interacting with C, where concepts like copy and move construction do not exist. When shared with C, an `omni::function` can be used with a byte-for-byte copy; no wrapper indirection is needed. This allows for natural usage.
```c
/* signature: omni_function omni_foo(void); */
omni_function fn = omni_foo();
/* signature: void my_own_code(omni_function f);
The backing structure is copied into the target, which is safe. */
my_own_code(fn);
omni_function_free(fn);
```
### Interaction with `std::function` and `std::bind`
Despite the lack of ABI safety for `std::function` and `std::bind`, `omni::function`s created using these facilities are...
ABI
safe.
Because
the
Standard
Library
implementations
are
inlined,
the
`omni::function`
will call code which is compatible with the compilation parameters of the binding site.
Function binding requires that certain targets create an unbound function wrappers.
For example, a function pointer which is null (`omni::function<void()>{static_cast<void(*)()>(nullptr)}`) or a function wrapper which is unbound (`omni::function<void()>{omni::function<void()>{nullptr}}`) both yield unbound `omni::function`s.
The implementation also understands `std::function`s, so binding an `omni::function` to an unbound `std::function` works as you would expect.
```cpp
std::function<void()> std_fn; // <- unbound
// The omni::function will be created unbound
omni::function<void()> omni_fn = std_fn;
if (!omni_fn)
printf("It works!\n");
```
This property is not commutative.
Since `std::function` does not understand `omni::function`, an `std::function` binding to an unbound `omni::function` will successfully bind to a target that can never be successfully called.
```cpp
omni::function<void()> omni_fn; // <- unbound
// The std::function will be bound to call the unbound omni::function
std::function<void()> std_fn = omni_fn;
if (std_fn)
std_fn(); // <- calls the unbound omni_fn
```
If conversion from `omni::function` to `std::function` is required, the `omni::function` should be checked to see if it is bound first.
> Note
> This conversion can not be done implicitly because of the `std::function` constructor which accepts a universal reference to bind to (C++ Standard 2020, §22.10.17.3.2/8).
> Conversion operators on `omni::function` which target a `std::function<UReturn(UArgs...)>` will be ambiguous with the candidate constructor accepting `template F&&`.
### Missing Features from `std::function`
While `omni::function` is generally compatible with `std::function`, there are a few features that are not supported.
#### Allocators
The constructors for `std::function` support `std::allocator_arg_t`-accepting overloads which allows for a user-supplied allocator to be used when the binding needs to allocate.
This was inconsistently implemented and removed from the C++ Standard in the 2017 edition.
Because of this, `omni::function` does not support these allocator-accepting overloads. It will always use the `carbReallocate()` function for allocation on bindings.
## Target Access
The member functions `target_type()` and `target()` allow a caller to access the type information and value of the functor the `omni::function` is bound to. These are problematic because they require run-time type information, which Carbonite does not require and many builds disable. Even when RTTI is enabled, the `std::type_info` is not ABI safe, so attempting to use the types returned from these functions would not be safe, either.
These facilities are unhelpful in Omniverse at large, since the target of an `omni::function` might be implemented in another language; getting `PythonFunctionWrapper` or `RustTrampoline` is not all that useful. Developers are encouraged to find a safer facility instead of attempting to access the target function through the polymorphic wrapper. For example, you can keep the part you need to access in a `shared_ptr` and bind the function to access that:
```cpp
struct Foo
{
int value{};
int operator()(int x) const
{
return x + value;
}
};
int main()
{
// An std::function supports accessing the bound target:
std::function<int(int)> with_target{Foo{}};
with_target.target<Foo>()->value = 5;
assert(with_target(4) == 9);
// Instead, you can track Foo through a shared_ptr
auto foo_ptr = std::make_shared<Foo>();
omni::function<int(int)> omni_style = std::bind(&Foo::operator(), foo_ptr);
foo_ptr->value = 5;
assert(omni_style(4) == 9);
}
```
## Why not `std::function`?
There are two major reasons to have `omni::function` instead of relying on `std::function`. The primary reason is `std::function` is not guaranteed to be ABI stable, even across different compilation flags with the same compiler. Even if `std::function` guaranteed ABI stability, some binding targets require allocations, which need to go through the Omniverse `carbReallocate()` to support construction in one module and destruction in another.
## Details
### Data Layout
The core functionality of `omni::function` lives in `omni::detail::FunctionData`, a non-templated structure. An `omni::function` consists only of this `FunctionData`, the templated type only providing structural sugar for function calls and lifetime management in C++. Core data is designed to be used from other languages, with lifetime management and call syntax being left to language specific facilities.
```cpp
struct FunctionCharacteristics;
constexpr std::size_t kFUNCTION_BUFFER_SIZE = 16U;
constexpr std::size_t kFUNCTION_BUFFER_ALIGN = alignof(std::max_align_t);
union alignas(kFUNCTION_BUFFER_ALIGN) FunctionBuffer
{
char raw[kFUNCTION_BUFFER_SIZE];
void* pointer;
// other alternatives excluded
};
struct FunctionData
{
FunctionBuffer buffer;
void* trampoline;
FunctionCharacteristics const* characteristics;
};
```
The `trampoline` value is a pointer to a function with the signature `TReturn (*)(FunctionBuffer const*, TArgs...)`. It exists to restore context from the `FunctionBuffer`, which are user-defined additional details needed to perform the function call, covered in the next paragraph. If `trampoline` is `nullptr`, then the function is not active, regardless of any other value.
> **Note**
> Care must be taken to ensure the `FunctionData` for a function with one signature is not mixed with the signature of another. Type safety for this is maintained by language specific bindings (e.g.: in C++, a `omni::function<TReturn(TArgs...)>` cannot be mixed with a `omni::function<UReturn(UArgs...)>`).
The `buffer` field stores extra information for actually performing a function call. Exact structure is determined by the type `omni::function` is bound to. In the simplest case, a `omni::function<TReturn(TArgs...)>` might be bound to a `TReturn(*)(TArgs...)`, so the buffer would contain only this pointer. A more complex binding might be to a class type with an `operator()` overload, in which case the buffer will contain an object instance or pointer to a heap-allocated one.
The `characteristics` is meant for the management level operations of copying and destroying the function `buffer`. If this value is `nullptr`, then the function buffer is assumed to be trivially copyable and trivially destructible. It is discussed in detail in the [Function Characteristics](#function-characteristics) section.
Bringing this all together, the actual function call is performed by (error handling removed for brevity):
```cpp
template <typename TReturn, typename... TArgs>
TReturn function<TReturn(TArgs...)>::operator()(TArgs... args) const
```
{
auto real = reinterpret_cast<TReturn(*)(FunctionBuffer const*, TArgs...)>(this->trampoline);
return omni::invoke_r<TReturn>(&this->buffer, std::forward<TArgs>(args)...);
}
```
## Function Characteristics
```cpp
struct FunctionCharacteristics
{
size_t size;
void (*destroy)(FunctionBuffer* self);
omni::Result (*clone)(FunctionBuffer* target, FunctionBuffer const* source);
};
```
The `FunctionCharacteristics` structure is responsible for performing the special operations of destruction and copying of binding targets through the `destroy` and `clone` member functions. Either of these functions can be `nullptr`, which indicates the operation is trivial. A trivial `destroy` does nothing; a trivial `clone` means that `memcpy` is a valid replacement for copy. If both of these are trivial operations, then `FunctionData::characteristics` can be left as `nullptr`.
The instance must exist for the lifetime of the `omni::function`, but these live in the library-static space of where the function was created. A `function` instance does not make guarantees that the DLL/SO will remain loaded while it is callable. |
functions.md | # Functions
- **setParamFromArg(T *param, const std::string &arg)**
- **setParamFromValue(T *param, const pxr::VtValue &dictVal)** |
Garch.md | # Garch module
Summary: GL Architecture
## Module: pxr.Garch
garch
### Classes:
| Class | Description |
|-------|-------------|
| [GLPlatformDebugContext](#pxr.Garch.GLPlatformDebugContext) | Platform specific context (e.g. X11/GLX) which supports debug output. |
### Class: pxr.Garch.GLPlatformDebugContext
Platform specific context (e.g. X11/GLX) which supports debug output.
#### Methods:
| Method | Description |
|--------|-------------|
| [makeCurrent](#pxr.Garch.GLPlatformDebugContext.makeCurrent)() | |
#### Attributes:
| Attribute | Description |
|-----------|-------------|
| [expired](#pxr.Garch.GLPlatformDebugContext.expired) | True if this object has expired, False otherwise. |
#### Method: pxr.Garch.GLPlatformDebugContext.makeCurrent()
#### Attribute: pxr.Garch.GLPlatformDebugContext.expired
True if this object has expired, False otherwise.
---
title: 文章标题
author: 作者名
date: 2023-04-01
---
# 一级标题
## 二级标题
这是一段普通的文本。
### 三级标题
这里是代码块:
```python
print("Hello, World!")
```
这里是引用块:
> 引用内容
这里是列表:
- 列表项1
- 列表项2
这里是表格:
| 列1 | 列2 |
| --- | --- |
| 数据1 | 数据2 |
这里是链接文本,但没有实际链接:[链接文本]
这里是图片描述,但没有实际图片:![图片描述]
---
这里是页脚。 |
geforce-now-runtime-sdk-integration_Overview.md | # GeForce NOW Runtime SDK Integration
omni.kit.gfn links Omniverse Kit with the GFN runtime SDK.
It allows startup and shutdown of the SDK, retrieving GFN partner secure data,
and communicating with the client website containing the embedded GFN stream.
## Startup
Acquire the interface and call `startup` to initialize the GFN SDK.
```python
from omni.kit.gfn import get_geforcenow_interface
gfn = get_geforcenow_interface()
gfn.startup()
```
## Sending messages
Send messages to the GFN client by using the Kit application message bus.
Use `omni.kit.livestream.send_message` for the event type, and a `message` item for the event payload.
```python
import carb.events
import omni.kit.app
event_type = carb.events.type_from_string("omni.kit.livestream.send_message")
payload = {"message": "Hello GFN!"}
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(event_type, payload=payload)
```
## Receiving messages
Receive messages from the GFN client by using the Kit application message bus.
Use `omni.kit.livestream.receive_message` for the event type, and the message will be in the `message` item of the event payload.
```python
import carb.events
import omni.kit.app
def on_event(event: carb.events.IEvent):
message = event.payload["message"]
print("received", message)
event_type = carb.events.type_from_string("omni.kit.livestream.receive_message")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_pop_by_type(event_type, on_event)
```
We also support generic messages, if it doesn’t parse as json with those keys, use
```
```
omni.kit.gfn.receive_message
```
for the event type, and the raw message will be in the
```
message
```
item of the event payload. |
general-use-case_Overview.md | # Overview — Omniverse Kit 1.1.5 documentation
## Overview
This extension provides a collection of commands for managing and manipulating primitives within a Fabric stage using USDRT API. It includes commands for creating, copying, moving, deleting, and transforming primitives, as well as grouping, ungrouping, and changing properties and attributes of these primitives. They are designed to work with Fabric, a framework within NVIDIA Omniverse for real-time graphics and simulation.
### Important API List
- DeleteFabricPrimsCommand: Deletes specified primitives from a Fabric stage.
- MoveFabricPrimCommand: Moves a single Fabric prim to a new path within the same stage.
- MoveFabricPrimsCommand: Moves multiple Fabric prims to new locations within the stage.
- ToggleVisibilitySelectedFabricPrimsCommand: Toggles the visibility of selected Fabric primitives.
- CreateFabricPrimWithDefaultXformCommand: Creates a Fabric primitive with a default transform.
- CreateFabricPrimCommand: Creates a Fabric primitive.
- CopyFabricPrimsCommand: Creates multiple Fabric primitives.
- CreateDefaultXformOnFabricPrimCommand: Applies a default transform to a Fabric primitive.
- CopyFabricPrimCommand: Copies a Fabric primitive to a new location in the stage.
- CopyFabricPrimsCommand: Copies multiple Fabric primitives to new locations in the stage.
- GroupFabricPrimsCommand: Groups multiple Fabric primitives under a new Xform primitive.
- UngroupFabricPrimsCommand: Ungroups Fabric primitives from their common parent Xform primitive.
## Commands
- **TransformFabricPrimCommand**: Transforms a Fabric primitive with a given transformation matrix.
- **ChangeFabricPropertyCommand**: Changes a specified property on a Fabric primitive.
- **ChangeFabricAttributeCommand**: Changes a specified attribute on a Fabric primitive.
## General Use Case
Users can use this extension to perform various operations on primitives within a Fabric stage, such as creating, deleting, moving, grouping, and transforming primitives, as well as managing their properties and visibility. These commands facilitate the manipulation of scene elements in a programmatic and undoable manner, allowing for efficient scene management in the Omniverse Kit. For examples of how to use the APIs, please consult the Python usage pages.
## User Guide
- Settings
- Usage Examples
- Changelog |
genindex.md | # Index |
GeomUtil.md | # GeomUtil module
Summary: The GeomUtil module contains utilities to help image common geometry.
## Classes:
| Class | Description |
| --- | --- |
| `CapsuleMeshGenerator` | This class provides an implementation for generating topology and point positions on a capsule. |
| `ConeMeshGenerator` | This class provides an implementation for generating topology and point positions on a cone of a given radius and height. |
| `CuboidMeshGenerator` | This class provides an implementation for generating topology and point positions on a rectangular cuboid given the dimensions along the X, Y and Z axes. |
| `CylinderMeshGenerator` | This class provides an implementation for generating topology and point positions on a cylinder with a given radius and height. |
| `SphereMeshGenerator` | This class provides an implementation for generating topology and point positions on a sphere with a given radius. |
### CapsuleMeshGenerator
This class provides an implementation for generating topology and point positions on a capsule.
- The simplest form takes a radius and height and is a cylinder capped by two hemispheres that is centered at the origin.
- The generated capsule is made up of circular cross-sections in the XY plane.
- Each cross-section has numRadial segments.
- Successive cross-sections for each of the hemispheres are generated at numCapAxial locations along the Z and -Z axes respectively.
- The height is aligned with the Z axis and represents the height of just the cylindrical portion.
- An optional transform may be provided to GeneratePoints to orient the capsule as necessary (e.g., whose height is along the Y axis).
- An additional overload of GeneratePoints is provided to specify different radii and heights for the bottom and top caps, as well as the sweep angle for the capsule about the +Z axis.
- When the sweep is less than 360 degrees, the generated geometry is not closed.
Usage:
```
```markdown
```cpp
const size_t numRadial = 4, numCapAxial = 4;
const size_t numPoints =
GeomUtilCapsuleMeshGenerator::ComputeNumPoints(numRadial, numCapAxial);
const float radius = 1, height = 2;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilCapsuleMeshGenerator::GeneratePoints(
points.begin(), numRadial, numCapAxial, radius, height);
```
```
```markdown
**Methods:**
```
```markdown
| Method | Description |
| --- | --- |
| ComputeNumPoints | classmethod ComputeNumPoints(numRadial, numCapAxial, closedSweep) -> int |
| GeneratePoints | classmethod GeneratePoints(iter, numRadial, numCapAxial, radius, height, framePtr) -> None |
| GenerateTopology | classmethod GenerateTopology(numRadial, numCapAxial, closedSweep) -> MeshTopology |
```
```markdown
**Attributes:**
```
```markdown
| Attribute | Description |
| --- | --- |
| minNumCapAxial | |
| minNumRadial | |
```
```markdown
**ComputeNumPoints**
```
```markdown
classmethod ComputeNumPoints(numRadial, numCapAxial, closedSweep) -> int
```
```markdown
Parameters:
- numRadial (int) –
- numCapAxial (int) –
- closedSweep (bool) –
```
```markdown
**GeneratePoints**
```
```markdown
classmethod GeneratePoints(iter, numRadial, numCapAxial, radius, height, framePtr) -> None
```
```markdown
Parameters:
- iter (PointIterType) –
- numRadial (int) –
- numCapAxial (int) –
- radius (ScalarType) –
- height (ScalarType) –
- framePtr (Matrix4d) –
```
```markdown
<p>
GeneratePoints(iter, numRadial, numCapAxial, bottomRadius, topRadius, height, bottomCapHeight, topCapHeight, sweepDegrees, framePtr) -> None
</p>
<dl>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<p><strong>iter</strong> (<em>PointIterType</em>) –</p>
</li>
<li>
<p><strong>numRadial</strong> (<em>int</em>) –</p>
</li>
<li>
<p><strong>numCapAxial</strong> (<em>int</em>) –</p>
</li>
<li>
<p><strong>bottomRadius</strong> (<em>ScalarType</em>) –</p>
</li>
<li>
<p><strong>topRadius</strong> (<em>ScalarType</em>) –</p>
</li>
<li>
<p><strong>height</strong> (<em>ScalarType</em>) –</p>
</li>
<li>
<p><strong>bottomCapHeight</strong> (<em>ScalarType</em>) –</p>
</li>
<li>
<p><strong>topCapHeight</strong> (<em>ScalarType</em>) –</p>
</li>
<li>
<p><strong>sweepDegrees</strong> (<em>ScalarType</em>) –</p>
</li>
<li>
<p><strong>framePtr</strong> (<em>Matrix4d</em>) –</p>
</li>
</ul>
</dd>
</dl>
<hr>
<p>
GeneratePoints(iter, arg2) -> None
</p>
<dl>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<p><strong>iter</strong> (<em>PointIterType</em>) –</p>
</li>
<li>
<p><strong>arg2</strong> –</p>
</li>
</ul>
</dd>
</dl>
<dl>
<dt>classmethod GenerateTopology(numRadial, numCapAxial, closedSweep) -> MeshTopology</dt>
<dd>
<dl>
<dt>Parameters</dt>
<dd>
<ul>
<li>
<p><strong>numRadial</strong> (<em>int</em>) –</p>
</li>
<li>
<p><strong>numCapAxial</strong> (<em>int</em>) –</p>
</li>
<li>
<p><strong>closedSweep</strong> (<em>bool</em>) –</p>
</li>
</ul>
</dd>
</dl>
</dd>
</dl>
<dl>
<dt>minNumCapAxial = 1</dt>
</dl>
<dl>
<dt>minNumRadial = 3</dt>
</dl>
<dl>
<dt>class pxr.GeomUtil.ConeMeshGenerator</dt>
<dd>
<p>This class provides an implementation for generating topology and point positions on a cone of a given radius and height.</p>
<p>The cone is made up of circular cross-sections in the XY plane and is centered at the origin. Each cross-section has numRadial segments. The height is aligned with the Z axis, with the base of the object at Z = -h/2 and apex at Z = h/2.</p>
<p>An optional transform may be provided to GeneratePoints to orient the cone as necessary (e.g., whose height is along the Y axis).</p>
<p>An additional overload of GeneratePoints is provided to specify the sweep angle for the cone about the +Z axis. When the sweep is less than 360 degrees, the generated geometry is not closed.</p>
<p>Usage:</p>
<div class="highlight-text notranslate">
<div class="highlight">
```pre
const size_t numRadial = 8;
const size_t numPoints =
GeomUtilConeMeshGenerator::ComputeNumPoints(numRadial);
const float radius = 1, height = 2;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilConeMeshGenerator::GeneratePoints(
points.begin(), numRadial, radius, height);
</pre>
## Methods:
| Method | Description |
| --- | --- |
| `ComputeNumPoints` | `classmethod ComputeNumPoints(numRadial, closedSweep) -> int` |
| `GeneratePoints` | `classmethod GeneratePoints(iter, numRadial, radius, height, framePtr) -> None` |
| `GenerateTopology` | `classmethod GenerateTopology(numRadial, closedSweep) -> MeshTopology` |
## Attributes:
| Attribute | Description |
| --- | --- |
| `minNumRadial` | |
### ComputeNumPoints
```
classmethod ComputeNumPoints(numRadial, closedSweep) -> int
```
Parameters:
- `numRadial` (int) –
- `closedSweep` (bool) –
### GeneratePoints
```
classmethod GeneratePoints(iter, numRadial, radius, height, framePtr) -> None
```
Parameters:
- `iter` (PointIterType) –
- `numRadial` (int) –
- `radius` (ScalarType) –
- `height` (ScalarType) –
- `framePtr` (Matrix4d) –
GeneratePoints(iter, numRadial, radius, height, sweepDegrees, framePtr) -> None
Parameters:
- `iter` (PointIterType) –
- `numRadial` (int) –
- `radius` (ScalarType) –
- `height` (ScalarType) –
```
- **sweepDegrees** (`ScalarType`) –
- **framePtr** (`Matrix4d`) –
---
GeneratePoints(iter, arg2) -> None
- **Parameters**
- **iter** (`PointIterType`) –
- **arg2** –
---
- **classmethod** GenerateTopology(numRadial, closedSweep) -> MeshTopology
- **Parameters**
- **numRadial** (`int`) –
- **closedSweep** (`bool`) –
---
- **minNumRadial** = 3
---
- **class** pxr.GeomUtil.CuboidMeshGenerator
- This class provides an implementation for generating topology and point positions on a rectangular cuboid given the dimensions along the X, Y and Z axes.
- The generated cuboid is centered at the origin.
- An optional transform may be provided to GeneratePoints to orient the cuboid as necessary.
- Usage:
```cpp
const size_t numPoints = GeomUtilCuboidMeshGenerator::ComputeNumPoints();
const float l = 5, b = 4, h = 3;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilCuboidMeshGenerator::GeneratePoints(points.begin(), l, b, h);
```
- **Methods:**
- **classmethod** ComputeNumPoints() -> int
- **classmethod** GeneratePoints(iter, xLength, yLength, zLength, framePtr) -> None
- **classmethod** GenerateTopology() -> MeshTopology
- **classmethod** ComputeNumPoints() -> int
### GeneratePoints
**classmethod** GeneratePoints(iter, xLength, yLength, zLength, framePtr) -> None
#### Parameters
- **iter** (`PointIterType`) –
- **xLength** (`ScalarType`) –
- **yLength** (`ScalarType`) –
- **zLength** (`ScalarType`) –
- **framePtr** (`Matrix4d`) –
---
GeneratePoints(iter, arg2) -> None
#### Parameters
- **iter** (`PointIterType`) –
- **arg2** –
### GenerateTopology
**classmethod** GenerateTopology() -> MeshTopology
### CylinderMeshGenerator
This class provides an implementation for generating topology and point positions on a cylinder with a given radius and height.
The cylinder is made up of circular cross-sections in the XY plane and is centered at the origin. Each cross-section has numRadial segments. The height is aligned with the Z axis, with the base at Z = -h/2.
An optional transform may be provided to GeneratePoints to orient the cone as necessary (e.g., whose height is along the Y axis).
An additional overload of GeneratePoints is provided to specify different radii for the bottom and top discs of the cylinder and a sweep angle for cylinder about the +Z axis. When the sweep is less than 360 degrees, the generated geometry is not closed.
Setting one radius to 0 in order to get a cone is inefficient and could result in artifacts. Clients should use GeomUtilConeMeshGenerator instead. Usage:
```cpp
const size_t numRadial = 8;
const size_t numPoints = GeomUtilCylinderMeshGenerator::ComputeNumPoints(numRadial);
const float radius = 1, height = 2;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilCylinderMeshGenerator::GeneratePoints(
points.begin(), numRadial, radius, height);
```
**Methods:**
- **ComputeNumPoints** (`classmethod` ComputeNumPoints(numRadial, closedSweep) -> int)
- **GeneratePoints** (`classmethod` GeneratePoints(iter, numRadial, radius, height, framePtr) -> None)
- **GenerateTopology** (`classmethod` GenerateTopology(numRadial, closedSweep) -> MeshTopology)
**Attributes:**
- **minNumRadial**
## ComputeNumPoints
**classmethod** ComputeNumPoints(numRadial, closedSweep) -> int
### Parameters
- **numRadial** (int) –
- **closedSweep** (bool) –
## GeneratePoints
**classmethod** GeneratePoints(iter, numRadial, radius, height, framePtr) -> None
### Parameters
- **iter** (PointIterType) –
- **numRadial** (int) –
- **radius** (ScalarType) –
- **height** (ScalarType) –
- **framePtr** (Matrix4d) –
**classmethod** GeneratePoints(iter, numRadial, bottomRadius, topRadius, height, sweepDegrees, framePtr) -> None
### Parameters
- **iter** (PointIterType) –
- **numRadial** (int) –
- **bottomRadius** (ScalarType) –
- **topRadius** (ScalarType) –
- **height** (ScalarType) –
- **sweepDegrees** (ScalarType) –
- **framePtr** (Matrix4d) –
**classmethod** GeneratePoints(iter, arg2) -> None
### Parameters
- **iter** (PointIterType) –
- **arg2** –
## GenerateTopology
**classmethod** GenerateTopology(numRadial, closedSweep) -> MeshTopology
### Parameters
- **numRadial** (int) –
- **closedSweep** (bool) –
This class provides an implementation for generating topology and point positions on a sphere with a given radius.
The sphere is made up of circular cross-sections in the XY plane and is centered at the origin. Each cross-section has numRadial segments. Successive cross-sections are generated at numAxial locations along the Z axis, with the bottom of the sphere at Z = -r and top at Z = r.
An optional transform may be provided to GeneratePoints to orient the sphere as necessary (e.g., cross-sections in the YZ plane).
An additional overload of GeneratePoints is provided to specify a sweep angle for the sphere about the +Z axis. When the sweep is less than 360 degrees, the generated geometry is not closed.
Usage:
```cpp
const size_t numRadial = 4, numAxial = 4;
const size_t numPoints = GeomUtilSphereMeshGenerator::ComputeNumPoints(numRadial, numAxial);
const float radius = 5;
MyPointContainer<GfVec3f> points(numPoints);
GeomUtilSphereMeshGenerator::GeneratePoints(points.begin(), numRadial, numAxial, radius);
```
**Methods:**
| Method | Description |
|--------|-------------|
| `ComputeNumPoints` | **classmethod** ComputeNumPoints(numRadial, numAxial, closedSweep) -> int |
| `GeneratePoints` | **classmethod** GeneratePoints(iter, numRadial, numAxial, radius, framePtr) -> None |
| `GenerateTopology` | **classmethod** GenerateTopology(numRadial, numAxial, closedSweep) -> MeshTopology |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `minNumAxial` | |
| `minNumRadial` | |
**ComputeNumPoints**
**classmethod** ComputeNumPoints(numRadial, numAxial, closedSweep) -> int
Parameters:
- **numRadial** (int) –
- **numAxial** (int) –
- **closedSweep** (bool) –
**GeneratePoints**
**static** GeneratePoints(iter, numRadial, numAxial, radius, framePtr) -> None
### GeneratePoints
```python
classmethod GeneratePoints(iter, numRadial, numAxial, radius, framePtr) -> None
```
**Parameters**
- **iter** (`PointIterType`) –
- **numRadial** (`int`) –
- **numAxial** (`int`) –
- **radius** (`ScalarType`) –
- **framePtr** (`Matrix4d`) –
```python
classmethod GeneratePoints(iter, numRadial, numAxial, radius, sweepDegrees, framePtr) -> None
```
**Parameters**
- **iter** (`PointIterType`) –
- **numRadial** (`int`) –
- **numAxial** (`int`) –
- **radius** (`ScalarType`) –
- **sweepDegrees** (`ScalarType`) –
- **framePtr** (`Matrix4d`) –
```python
classmethod GeneratePoints(iter, arg2) -> None
```
**Parameters**
- **iter** (`PointIterType`) –
- **arg2** –
### GenerateTopology
```python
classmethod GenerateTopology(numRadial, numAxial, closedSweep) -> MeshTopology
```
**Parameters**
- **numRadial** (`int`) –
- **numAxial** (`int`) –
- **closedSweep** (`bool`) –
### minNumAxial
```python
minNumAxial = 2
```
### minNumRadial
```python
minNumRadial = 3
``` |
Gestures.md | # Gestures
Gestures handle all of the logic needed to process user-input events such as click and drag and recognize when those events happen on the shape. When recognizing it, SceneUI runs a callback to update the state of a view or perform an action.
## Add Gesture Callback
Each gesture applies to a specific shape in the scene hierarchy. To recognize a gesture event on a particular shape, it’s necessary to create and configure the gesture object. SceneUI provides the full state of the gesture to the callback using the `gesture_payload` object. The `gesture_payload` object contains the coordinates of the intersection of mouse pointer and the shape in world and shape spaces, the distance between last intersection and parametric coordinates. It’s effortless to modify the state of the shape using this data.
```python
def move(transform: sc.Transform, shape: sc.AbstractShape):
"""Called by the gesture"""
translate = shape.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Line(
[-1, 0, 0],
[1, 0, 0],
color=cl.blue,
thickness=5,
gesture=sc.DragGesture(
on_changed_fn=partial(move, transform)
)
)
```
## Reimplementing Gesture
Some gestures can receive the update in a different state. For example, DragGesture offers the update when the user presses the mouse, moves the mouse, and releases the mouse: `on_began`, `on_changed`, `on_ended`. It’s also possible to extend the gesture by reimplementing its class.
```python
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform):
# Implementation details here
```
```python
super().__init__()
self.__transform = transform
def on_began(self):
self.sender.color = cl.red
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
def on_ended(self):
self.sender.color = cl.blue
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(color=cl.blue, gesture=Move(transform))
```
## Gesture Manager
Gestures track incoming input events separately, but it’s normally necessary to let only one gesture be executed because it prevents user input from triggering more than one action at a time. For example, if multiple shapes are under the mouse pointer, normally, the only gesture of the closest shape should be processed. However, this default behavior can introduce unintended side effects. To solve those problems, it’s necessary to use the gesture manager.
GestureManager controls the priority of gestures if they are processed at the same time. It prioritizes the desired gestures and prevents unintended gestures from being executed.
In the following example, the gesture of the red rectangle always wins even if both rectangles overlap.
```python
class Manager(sc.GestureManager):
def __init__(self):
super().__init__()
def should_prevent(self, gesture, preventer):
# prime gesture always wins
if preventer.name == "prime":
return True
def move(transform: sc.Transform, shape: sc.AbstractShape):
"""Called by the gesture"""
translate = shape.gesture_payload.moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
mgr = Manager()
with scene_view.scene:
transform1 = sc.Transform()
with transform1:
sc.Rectangle(
color=cl.red,
gesture=sc.DragGesture(
name="prime",
manager=mgr,
on_changed_fn=partial(move, transform1)
)
)
transform2 = sc.Transform(
transform=sc.Matrix44.get_translation_matrix(2, 0, 0)
)
with transform2:
sc.Rectangle(
color=cl.blue,
gesture=sc.DragGesture(
manager=mgr,
on_changed_fn=partial(move, transform2)
)
)
``` |
Gf.md | # Gf module
Summary: The Gf (Graphics Foundations) library contains classes and functions for working with basic mathematical aspects of graphics.
## Graphics Foundation
This package defines classes for fundamental graphics types and operations.
### Classes:
| Class | Description |
|-------|-------------|
| `BBox3d` | Arbitrarily oriented 3D bounding box |
| `Camera` | |
| `DualQuatd` | |
| `DualQuatf` | |
| `DualQuath` | |
| `Frustum` | Basic view frustum |
| `Interval` | Basic mathematical interval class |
| `Line` | Line class |
| `LineSeg` | Line segment class |
| `Matrix2d` | |
| `Matrix2f` | |
- Matrix2f
- Matrix3d
- Matrix3f
- Matrix4d
- Matrix4f
- MultiInterval
- Plane
- Quatd
- Quaternion
- Quaternion class
- Quatf
- Quath
- Range1d
- Range1f
- Range2d
- Range2f
- Range3d
- Range3f
- Ray
- Rect2i
- Rotation
- 3-space rotation
- Size2
- A 2D size class
Size3
A 3D size class
Transform
Vec2d
Vec2f
Vec2h
Vec2i
Vec3d
Vec3f
Vec3h
Vec3i
Vec4d
Vec4f
Vec4h
Vec4i
class pxr.Gf.BBox3d
Arbitrarily oriented 3D bounding box
**Methods:**
Combine(b1, b2) -> BBox3d
classmethod
ComputeAlignedBox()
Returns the axis-aligned range (as a GfRange3d) that results from applying the transformation matrix to the axis-aligned box and aligning the result.
ComputeAlignedRange()
Returns the axis-aligned range (as a GfRange3d)
| Method | Description |
| --- | --- |
| `ComputeCentroid()` | Returns the centroid of the bounding box. |
| `GetBox()` | Returns the range of the axis-aligned untransformed box. |
| `GetInverseMatrix()` | Returns the inverse of the transformation matrix. |
| `GetMatrix()` | Returns the transformation matrix. |
| `GetRange()` | Returns the range of the axis-aligned untransformed box. |
| `GetVolume()` | Returns the volume of the box (0 for an empty box). |
| `HasZeroAreaPrimitives()` | Returns the current state of the zero-area primitives flag. |
| `Set(box, matrix)` | Sets the axis-aligned box and transformation matrix. |
| `SetHasZeroAreaPrimitives(hasThem)` | Sets the zero-area primitives flag to the given value. |
| `SetMatrix(matrix)` | Sets the transformation matrix only. |
| `SetRange(box)` | Sets the range of the axis-aligned box only. |
| `Transform(matrix)` | Transforms the bounding box by the given matrix, which is assumed to be a global transformation to apply to the box. |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `box` | |
| `hasZeroAreaPrimitives` | |
| `matrix` | |
### Combine
```python
classmethod Combine(b1, b2) -> BBox3d
```
Combines two bboxes, returning a new bbox that contains both.
This uses the coordinate space of one of the two original boxes as the space of the result; it uses the one that produces the smaller of the two resulting boxes.
#### Parameters
- **b1** (`BBox3d`) –
- **b2** (`BBox3d`) –
### ComputeAlignedBox
```python
ComputeAlignedBox() -> Range3d
```
Returns the axis-aligned range (as a `GfRange3d`) that results from applying the transformation matrix to the axis-aligned box and aligning the result.
This synonym for `ComputeAlignedRange` exists for compatibility purposes.
### ComputeAlignedRange
```python
ComputeAlignedRange() -> Range3d
```
Returns the axis-aligned range (as a `GfRange3d`) that results from applying the transformation matrix to the axis-aligned box and aligning the result.
### ComputeCentroid
```python
ComputeCentroid() -> Vec3d
```
Returns the centroid of the bounding box.
The centroid is computed as the transformed centroid of the range.
### GetBox
```python
GetBox() -> Range3d
```
Returns the range of the axis-aligned untransformed box.
This synonym of `GetRange` exists for compatibility purposes.
### GetInverseMatrix
```python
GetInverseMatrix() -> Matrix4d
```
Returns the inverse of the transformation matrix.
This will be the identity matrix if the transformation matrix is not invertible.
### GetMatrix
```python
GetMatrix() -> Matrix4d
```
Returns the transformation matrix.
Returns the transformation matrix.
Returns the range of the axis-aligned untransformed box.
Returns the volume of the box (0 for an empty box).
Returns the current state of the zero-area primitives flag.
Sets the axis-aligned box and transformation matrix.
Parameters:
- box (Range3d) –
- matrix (Matrix4d) –
Sets the zero-area primitives flag to the given value.
Parameters:
- hasThem (bool) –
Sets the transformation matrix only.
The axis-aligned box is not modified.
Parameters:
- matrix (Matrix4d) –
### pxr.Gf.BBox3d.SetRange
- **Description:** Sets the range of the axis-aligned box only. The transformation matrix is not modified.
- **Parameters:**
- **box** (Range3d) –
### pxr.Gf.BBox3d.Transform
- **Description:** Transforms the bounding box by the given matrix, which is assumed to be a global transformation to apply to the box. Therefore, this just post-multiplies the box’s matrix by matrix.
- **Parameters:**
- **matrix** (Matrix4d) –
### pxr.Gf.BBox3d.box
- **Description:** (property)
### pxr.Gf.BBox3d.hasZeroAreaPrimitives
- **Description:** (property)
### pxr.Gf.BBox3d.matrix
- **Description:** (property)
### pxr.Gf.Camera
- **Classes:**
- **FOVDirection:** Direction used for Field of View or orthographic size.
- **Projection:** Projection type.
- **Methods:**
- **GetFieldOfView(direction):** Returns the horizontal or vertical field of view in degrees.
- **SetFromViewAndProjectionMatrix(viewMatrix, ...):** Sets the camera from a view and projection matrix.
- **SetOrthographicFromAspectRatioAndSize:**
```code
SetOrthographicFromAspectRatioAndSize
```
(...)
```
Sets the frustum to be orthographic such that it has the given
```code
aspectRatio
```
and such that the orthographic width, respectively, orthographic height (in cm) is equal to
```code
orthographicSize
```
(depending on direction).
```
<a title="pxr.Gf.Camera.SetPerspectiveFromAspectRatioAndFieldOfView">
```code
SetPerspectiveFromAspectRatioAndFieldOfView
```
</a>
(...)
```
Sets the frustum to be projective with the given
```code
aspectRatio
```
and horizontal, respectively, vertical field of view
```code
fieldOfView
```
(similar to gluPerspective when direction = FOVVertical).
```
**Attributes:**
```
```
<a title="pxr.Gf.Camera.APERTURE_UNIT">
```code
APERTURE_UNIT
```
</a>
```
<a title="pxr.Gf.Camera.DEFAULT_HORIZONTAL_APERTURE">
```code
DEFAULT_HORIZONTAL_APERTURE
```
</a>
```
<a title="pxr.Gf.Camera.DEFAULT_VERTICAL_APERTURE">
```code
DEFAULT_VERTICAL_APERTURE
```
</a>
```
<a title="pxr.Gf.Camera.FOCAL_LENGTH_UNIT">
```code
FOCAL_LENGTH_UNIT
```
</a>
```
<a title="pxr.Gf.Camera.FOVHorizontal">
```code
FOVHorizontal
```
</a>
```
<a title="pxr.Gf.Camera.FOVVertical">
```code
FOVVertical
```
</a>
```
<a title="pxr.Gf.Camera.Orthographic">
```code
Orthographic
```
</a>
```
<a title="pxr.Gf.Camera.Perspective">
```code
Perspective
```
</a>
```
<a title="pxr.Gf.Camera.aspectRatio">
```code
aspectRatio
```
</a>
```
float
```
```
<a title="pxr.Gf.Camera.clippingPlanes">
```code
clippingPlanes
```
</a>
```
list[Vec4f]
```
```
<a title="pxr.Gf.Camera.clippingRange">
```code
clippingRange
```
</a>
```
Range1f
```
```
<a title="pxr.Gf.Camera.fStop">
```code
fStop
```
</a>
```
float
```
```
<a title="pxr.Gf.Camera.focalLength">
```code
focalLength
```
</a>
```
float
```
```
<a title="pxr.Gf.Camera.focusDistance">
```
| Property | Type |
|-------------------------|------------|
| focusDistance | float |
| frustum | Frustum |
| horizontalAperture | float |
| horizontalApertureOffset| float |
| horizontalFieldOfView | |
| projection | Projection |
| transform | Matrix4d |
| verticalAperture | float |
| verticalApertureOffset | float |
| verticalFieldOfView | |
### FOVDirection
**Description:** Direction used for Field of View or orthographic size.
**Methods:**
- GetValueFromName
**Attributes:**
- allValues
#### GetValueFromName
#### allValues
Projection type.
**Methods:**
- GetValueFromName
- allValues
**Attributes:**
- allValues
**GetValueFromName**
**allValues** = (Gf.Camera.Perspective, Gf.Camera.Orthographic)
**GetFieldOfView**
Returns the horizontal or vertical field of view in degrees.
Parameters:
- **direction** (FOVDirection) –
**SetFromViewAndProjectionMatrix**
Sets the camera from a view and projection matrix.
Note that the projection matrix does only determine the ratio of aperture to focal length, so there is a choice which defaults to 50mm (or more accurately, 50 tenths of a world unit).
Parameters:
- **viewMatrix** (Matrix4d) –
- **projMatix** (Matrix4d) –
- **focalLength** (float) –
### SetOrthographicFromAspectRatioAndSize
```python
SetOrthographicFromAspectRatioAndSize(aspectRatio, orthographicSize, direction) → None
```
Sets the frustum to be orthographic such that it has the given `aspectRatio` and such that the orthographic width, respectively, orthographic height (in cm) is equal to `orthographicSize` (depending on direction).
#### Parameters
- **aspectRatio** (float) –
- **orthographicSize** (float) –
- **direction** (FOVDirection) –
### SetPerspectiveFromAspectRatioAndFieldOfView
```python
SetPerspectiveFromAspectRatioAndFieldOfView(aspectRatio, fieldOfView, direction, horizontalAperture) → None
```
Sets the frustum to be projective with the given `aspectRatio` and horizontal, respectively, vertical field of view `fieldOfView` (similar to gluPerspective when direction = FOVVertical).
Do not pass values for `horionztalAperture` unless you care about DepthOfField.
#### Parameters
- **aspectRatio** (float) –
- **fieldOfView** (float) –
- **direction** (FOVDirection) –
- **horizontalAperture** (float) –
### APERTURE_UNIT
```python
APERTURE_UNIT = 0.1
```
### DEFAULT_HORIZONTAL_APERTURE
```python
DEFAULT_HORIZONTAL_APERTURE = 20.955
```
### DEFAULT_VERTICAL_APERTURE
```python
DEFAULT_VERTICAL_APERTURE =
```
=
15.290799999999999
FOCAL_LENGTH_UNIT = 0.1
FOVHorizontal = Gf.Camera.FOVHorizontal
FOVVertical = Gf.Camera.FOVVertical
Orthographic = Gf.Camera.Orthographic
Perspective = Gf.Camera.Perspective
property aspectRatio
- float
- Returns the projector aperture aspect ratio.
- Type: type
property clippingPlanes
- list[Vec4f]
- Returns additional clipping planes.
- type : None
- Sets additional arbitrarily oriented clipping planes.
- A vector (a,b,c,d) encodes a clipping plane that clips off points (x,y,z) with a * x + b * y + c * z + d * 1<0
- where (x,y,z) are the coordinates in the camera’s space.
- Type: type
property clippingRange
- Range1f
- Returns the clipping range in world units.
- type : None
- Sets the clipping range in world units.
- Type: type
property fStop
- float
- Returns the lens aperture.
- type : None
- Sets the lens aperture, unitless.
- Type: type
property focalLength
### focalLength
- **Type**: float
- **Description**: Returns the focal length in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
- **Details**:
- Together with the clipping range, they determine the camera frustum.
- Sets the focal length in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
### focusDistance
- **Type**: float
- **Description**: Returns the focus distance in world units.
- **Details**:
- Sets the focus distance in world units.
### frustum
- **Type**: Frustum
- **Description**: Returns the computed, world-space camera frustum.
- **Details**:
- The frustum will always be that of a Y-up, -Z-looking camera.
### horizontalAperture
- **Type**: float
- **Description**: Returns the width of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
- **Details**:
- Sets the width of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
### horizontalApertureOffset
- **Type**: float
- **Description**: Returns the horizontal offset of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
- **Details**:
- In particular, an offset is necessary when writing out a stereo camera with finite convergence distance as two cameras.
- Sets the horizontal offset of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
### horizontalFieldOfView
- **Type**: float
- **Description**: Returns the horizontal field of view.
### projection
- **Type**: Projection
- **Description**: Returns the projection type.
- **Details**:
- Sets the projection type.
### transform
- **Type**: Matrix4d
- **Description**: Returns the transform of the filmback in world space.
- **Details**:
- This is exactly the transform specified via SetTransform().
- Sets the transform of the filmback in world space to `val`.
Type
: type
property verticalAperture
: float
Returns the height of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
type : None
Sets the height of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
Type
: type
property verticalApertureOffset
: float
Returns the vertical offset of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
type : None
Sets the vertical offset of the projector aperture in tenths of a world unit (e.g., mm if the world unit is assumed to be cm).
Type
: type
property verticalFieldOfView
:
class pxr.Gf.DualQuatd
: Methods:
- GetConjugate()
Returns the conjugate of this dual quaternion.
- GetDual()
Returns the dual part of the dual quaternion.
- classmethod GetIdentity() -> DualQuatd
GetIdentity() -> DualQuatd
- GetInverse()
Returns the inverse of this dual quaternion.
- GetLength()
Returns geometric length of this dual quaternion.
- GetNormalized(eps)
Returns a normalized (unit-length) version of this dual quaternion.
- GetReal()
Returns the real part of the dual quaternion.
- GetTranslation()
Get the translation component of this dual quaternion.
| Method | Description |
| ------ | ----------- |
| `GetZero` | classmethod GetZero() -> DualQuatd |
| `Normalize(eps)` | Normalizes this dual quaternion in place. |
| `SetDual(dual)` | Sets the dual part of the dual quaternion. |
| `SetReal(real)` | Sets the real part of the dual quaternion. |
| `SetTranslation(translation)` | Set the translation component of this dual quaternion. |
| `Transform(vec)` | Transforms the row vector `vec` by the dual quaternion. |
**Attributes:**
| Attribute | Description |
| --------- | ----------- |
| `dual` | |
| `real` | |
**Methods:**
- `GetConjugate()` -> DualQuatd
- Returns the conjugate of this dual quaternion.
- `GetDual()` -> Quatd
- Returns the dual part of the dual quaternion.
- `GetIdentity()` -> DualQuatd
- Returns the identity dual quaternion, which has a real part of (1,0,0,0) and a dual part of (0,0,0,0).
- `GetInverse()` -> DualQuatd
- Returns the inverse of this dual quaternion.
### GetLength
Returns geometric length of this dual quaternion.
### GetNormalized
Returns a normalized (unit-length) version of this dual quaternion.
If the length of this dual quaternion is smaller than `eps`, this returns the identity dual quaternion.
**Parameters**
- **eps** (float) –
### GetReal
Returns the real part of the dual quaternion.
### GetTranslation
Get the translation component of this dual quaternion.
### GetZero
**classmethod** GetZero() -> DualQuatd
Returns the zero dual quaternion, which has a real part of (0,0,0,0) and a dual part of (0,0,0,0).
### Normalize
Normalizes this dual quaternion in place.
Normalizes this dual quaternion in place to unit length, returning the length before normalization. If the length of this dual quaternion is smaller than `eps`, this sets the dual quaternion to identity.
**Parameters**
- **eps** (float) –
### SetDual
)
→ None
Sets the dual part of the dual quaternion.
Parameters
----------
dual (Quatd) –
SetReal(real)
→ None
Sets the real part of the dual quaternion.
Parameters
----------
real (Quatd) –
SetTranslation(translation)
→ None
Set the translation component of this dual quaternion.
Parameters
----------
translation (Vec3d) –
Transform(vec)
→ Vec3d
Transforms the row vector `vec` by the dual quaternion.
Parameters
----------
vec (Vec3d) –
property dual
property real
class pxr.Gf.DualQuatf
Methods:
----------
GetConjugate()
Returns the conjugate of this dual quaternion.
- `GetDual()`
- Returns the dual part of the dual quaternion.
- `GetIdentity()`
- `classmethod GetIdentity() -> DualQuatf`
- `GetInverse()`
- Returns the inverse of this dual quaternion.
- `GetLength()`
- Returns geometric length of this dual quaternion.
- `GetNormalized(eps)`
- Returns a normalized (unit-length) version of this dual quaternion.
- `GetReal()`
- Returns the real part of the dual quaternion.
- `GetTranslation()`
- Get the translation component of this dual quaternion.
- `GetZero()`
- `classmethod GetZero() -> DualQuatf`
- `Normalize(eps)`
- Normalizes this dual quaternion in place.
- `SetDual(dual)`
- Sets the dual part of the dual quaternion.
- `SetReal(real)`
- Sets the real part of the dual quaternion.
- `SetTranslation(translation)`
- Set the translation component of this dual quaternion.
- `Transform(vec)`
- Transforms the row vector `vec` by the dual quaternion.
**Attributes:**
- `dual`
- `real`
( ) → DualQuatf
Returns the conjugate of this dual quaternion.
( ) → Quatf
Returns the dual part of the dual quaternion.
static GetIdentity() → DualQuatf
Returns the identity dual quaternion, which has a real part of (1,0,0,0) and a dual part of (0,0,0,0).
( ) → DualQuatf
Returns the inverse of this dual quaternion.
( ) → tuple[float, float]
Returns geometric length of this dual quaternion.
( eps ) → DualQuatf
Returns a normalized (unit-length) version of this dual quaternion. If the length of this dual quaternion is smaller than `eps`, this returns the identity dual quaternion.
Parameters:
- eps (float) –
( ) → Quatf
Returns the real part of the dual quaternion.
( ) → Vec3f
Returns the translation part of the dual quaternion.
### Get the translation component of this dual quaternion.
### GetZero
```markdown
classmethod GetZero() -> DualQuatf
```
Returns the zero dual quaternion, which has a real part of (0,0,0,0) and a dual part of (0,0,0,0).
### Normalize
```markdown
Normalize(eps) -> tuple[float, float]
```
Normalizes this dual quaternion in place to unit length, returning the length before normalization. If the length of this dual quaternion is smaller than `eps`, this sets the dual quaternion to identity.
**Parameters**
- **eps** (float) –
### SetDual
```markdown
SetDual(dual) -> None
```
Sets the dual part of the dual quaternion.
**Parameters**
- **dual** (Quatf) –
### SetReal
```markdown
SetReal(real) -> None
```
Sets the real part of the dual quaternion.
**Parameters**
- **real** (Quatf) –
### SetTranslation
```markdown
SetTranslation(translation) -> None
```
Set the translation component of this dual quaternion.
**Parameters**
- **translation** (Vec3f) –
### pxr.Gf.DualQuatf.Transform
Transforms the row vector `vec` by the dual quaternion.
#### Parameters
- **vec** (`Vec3f`) –
### pxr.Gf.DualQuatf.dual
property dual
### pxr.Gf.DualQuatf.real
property real
### pxr.Gf.DualQuath
Methods:
| Method | Description |
|--------|-------------|
| `GetConjugate()` | Returns the conjugate of this dual quaternion. |
| `GetDual()` | Returns the dual part of the dual quaternion. |
| `GetIdentity()` | **classmethod** GetIdentity() -> DualQuath |
| `GetInverse()` | Returns the inverse of this dual quaternion. |
| `GetLength()` | Returns geometric length of this dual quaternion. |
| `GetNormalized(eps)` | Returns a normalized (unit-length) version of this dual quaternion. |
| `GetReal()` | Returns the real part of the dual quaternion. |
| `GetTranslation()` | Get the translation component of this dual quaternion. |
| `GetZero()` | **classmethod** GetZero() -> DualQuath |
| `Normalize(eps)` | |
Normalizes this dual quaternion in place.
SetDual (dual)
: Sets the dual part of the dual quaternion.
SetReal (real)
: Sets the real part of the dual quaternion.
SetTranslation (translation)
: Set the translation component of this dual quaternion.
Transform (vec)
: Transforms the row vector `vec` by the dual quaternion.
**Attributes:**
dual
:
real
:
GetConjugate()
: Returns the conjugate of this dual quaternion.
GetDual()
: Returns the dual part of the dual quaternion.
GetIdentity()
: **classmethod** GetIdentity() -> DualQuath
Returns the identity dual quaternion, which has a real part of (1,0,0,0) and a dual part of (0,0,0,0).
GetInverse()
: Returns the inverse of this dual quaternion.
GetLength()
: Returns the length of this dual quaternion.
### Returns geometric length of this dual quaternion.
### GetNormalized
```python
GetNormalized(eps)
```
Returns a normalized (unit-length) version of this dual quaternion.
If the length of this dual quaternion is smaller than `eps`, this returns the identity dual quaternion.
**Parameters**
- **eps** (`GfHalf`) –
### GetReal
```python
GetReal()
```
Returns the real part of the dual quaternion.
### GetTranslation
```python
GetTranslation()
```
Get the translation component of this dual quaternion.
### GetZero
```python
classmethod GetZero() -> DualQuath
```
Returns the zero dual quaternion, which has a real part of (0,0,0,0) and a dual part of (0,0,0,0).
### Normalize
```python
Normalize(eps)
```
Normalizes this dual quaternion in place.
Normalizes this dual quaternion in place to unit length, returning the length before normalization. If the length of this dual quaternion is smaller than `eps`, this sets the dual quaternion to identity.
**Parameters**
- **eps** (`GfHalf`) –
### SetDual
```python
SetDual(dual)
```
Sets the dual part of the dual quaternion.
**Parameters**
- **dual** (`Quath`) –
### SetReal
Sets the real part of the dual quaternion.
**Parameters**
- **real** (`Quath`) –
### SetTranslation
Set the translation component of this dual quaternion.
**Parameters**
- **translation** (`Vec3h`) –
### Transform
Transforms the row vector `vec` by the dual quaternion.
**Parameters**
- **vec** (`Vec3h`) –
### dual
### real
### Frustum
Basic view frustum
**Classes:**
- **ProjectionType**
This enum is used to determine the type of projection represented by a frustum.
**Methods:**
- **ComputeAspectRatio** ()
Returns the aspect ratio of the frustum, defined as the width of the window divided by the height.
- **ComputeCorners** ()
- `ComputeCorners()`
- Returns the world-space corners of the frustum as a vector of 8 points, ordered as:
- `ComputeCornersAtDistance(d)`
- Returns the world-space corners of the intersection of the frustum with a plane parallel to the near/far plane at distance d from the apex, ordered as:
- `ComputeLookAtPoint()`
- Computes and returns the world-space look-at point from the eye point (position), view direction (rotation), and view distance.
- `ComputeNarrowedFrustum(windowPos, size)`
- Returns a frustum that is a narrowed-down version of this frustum.
- `ComputePickRay(windowPos)`
- Builds and returns a `GfRay` that can be used for picking at the given normalized (-1 to +1 in both dimensions) window position.
- `ComputeProjectionMatrix()`
- Returns a GL-style projection matrix corresponding to the frustum's projection.
- `ComputeUpVector()`
- Returns the normalized world-space up vector, which is computed by rotating the y axis by the frustum's rotation.
- `ComputeViewDirection()`
- Returns the normalized world-space view direction vector, which is computed by rotating the -z axis by the frustum's rotation.
- `ComputeViewFrame(side, up, view)`
- Computes the view frame defined by this frustum.
- `ComputeViewInverse()`
- Returns a matrix that represents the inverse viewing transformation for this frustum.
- `ComputeViewMatrix()`
- Returns a matrix that represents the viewing transformation for this frustum.
- `FitToSphere(center, radius, slack)`
- Modifies the frustum to tightly enclose a sphere with the given center and radius, using the current view direction.
- `GetFOV()`
- Returns the horizontal fov of the frustum.
- `GetNearFar()`
- Returns the near/far interval.
- `GetOrthographic()`
- Returns whether the frustum is orthographic.
- `GetOrthographic(left, right, bottom, top, ...)`
- Returns the current frustum in the format used by `SetOrthographic()`.
- `GetPerspective`
- Returns the current perspective frustum values suitable for use by SetPerspective.
- `GetPosition()`
- Returns the position of the frustum in world space.
- `GetProjectionType()`
- Returns the projection type.
- `GetReferencePlaneDepth()`
- `classmethod` GetReferencePlaneDepth() -> float
- `GetRotation()`
- Returns the orientation of the frustum in world space as a rotation to apply to the -z axis.
- `GetViewDistance()`
- Returns the view distance.
- `GetWindow()`
- Returns the window rectangle in the reference plane.
- `Intersects(bbox)`
- Returns true if the given axis-aligned bbox is inside or intersecting the frustum.
- `IntersectsViewVolume(bbox, vpMat)`
- `classmethod` IntersectsViewVolume(bbox, vpMat) -> bool
- `SetNearFar(nearFar)`
- Sets the near/far interval.
- `SetOrthographic(left, right, bottom, top, ...)`
- Sets up the frustum in a manner similar to `glOrtho()`.
- `SetPerspective(fieldOfViewHeight, ...)`
- Sets up the frustum in a manner similar to `gluPerspective()`.
- `SetPosition(position)`
- Sets the position of the frustum in world space.
- `SetPositionAndRotationFromMatrix(camToWorldXf)`
- Sets the position and rotation of the frustum from a camera matrix (always from a y-Up camera).
| Method | Description |
| --- | --- |
| `SetProjectionType(projectionType)` | Sets the projection type. |
| `SetRotation(rotation)` | Sets the orientation of the frustum in world space as a rotation to apply to the default frame: looking along the -z axis with the +y axis as "up". |
| `SetViewDistance(viewDistance)` | Sets the view distance. |
| `SetWindow(window)` | Sets the window rectangle in the reference plane that defines the left, right, top, and bottom planes of the frustum. |
| `Transform(matrix)` | Transforms the frustum by the given matrix. |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `Orthographic` | |
| `Perspective` | |
| `nearFar` | |
| `position` | |
| `projectionType` | |
| `rotation` | |
| `viewDistance` | |
| `window` | |
**pxr.Gf.Frustum.ProjectionType**
This enum is used to determine the type of projection represented by a frustum.
**Methods:**
| Method | Description |
| --- | --- |
| `GetValueFromName` | |
**Attributes:**
| allValues |
|-----------|
| allValues |
### GetValueFromName
- **Type**: static
- **Name**: GetValueFromName
### allValues
- **Type**: static
- **Value**: (Gf.Frustum.Orthographic, Gf.Frustum.Perspective)
### ComputeAspectRatio
- **Name**: ComputeAspectRatio
- **Returns**: float
- **Description**: Returns the aspect ratio of the frustum, defined as the width of the window divided by the height. If the height is zero or negative, this returns 0.
### ComputeCorners
- **Name**: ComputeCorners
- **Returns**: list[Vec3d]
- **Description**: Returns the world-space corners of the frustum as a vector of 8 points, ordered as:
- Left bottom near
- Right bottom near
- Left top near
- Right top near
- Left bottom far
- Right bottom far
- Left top far
- Right top far
### ComputeCornersAtDistance
- **Name**: ComputeCornersAtDistance
- **Parameters**:
- d (float)
- **Returns**: list[Vec3d]
- **Description**: Returns the world-space corners of the intersection of the frustum with a plane parallel to the near/far plane at distance d from the apex, ordered as:
- Left bottom
- Right bottom
- Left top
- Right top
- In particular, it gives the partial result of ComputeCorners when given near or far distance.
### ComputeLookAtPoint
- **Name**: ComputeLookAtPoint
- **Returns**: float
## pxr.Gf.Frustum.ComputeLookAtPoint
- **Description**: Computes and returns the world-space look-at point from the eye point (position), view direction (rotation), and view distance.
## pxr.Gf.Frustum.ComputeNarrowedFrustum
- **Description**: Returns a frustum that is a narrowed-down version of this frustum.
- **Parameters**:
- `windowPos` (Vec2d)
- `size` (Vec2d)
- **Details**:
- The new frustum has the same near and far planes, but the other planes are adjusted to be centered on `windowPos` with the new width and height obtained from the existing width and height by multiplying by `size` [0] and `size` [1], respectively.
- `windowPos` is given in normalized coords (-1 to +1 in both dimensions).
- `size` is given as a scalar (0 to 1 in both dimensions).
- If the `windowPos` or `size` given is outside these ranges, it may result in returning a collapsed frustum.
- This method is useful for computing a volume to use for interactive picking.
## pxr.Gf.Frustum.ComputePickRay
- **Description**: Builds and returns a Ray.
- **Parameters**:
- `windowPos`
- **Return**: Ray
<code class="docutils literal notranslate">
<span class="pre">
GfRay
</span>
</code>
that can be used for picking at the
given normalized (-1 to +1 in both dimensions) window position.
Contrasted with ComputeRay() , that method returns a ray whose origin
is the eyepoint, while this method returns a ray whose origin is on
the near plane.
Parameters
----------
windowPos
(Vec2d) –
ComputePickRay(worldSpacePos) -> Ray
Builds and returns a
<code class="docutils literal notranslate">
<span class="pre">
GfRay
</span>
</code>
that can be used for picking that
connects the viewpoint to the given 3d point in worldspace.
Parameters
----------
worldSpacePos
(Vec3d) –
ComputeProjectionMatrix() -> Matrix4d
-----------------------------
Returns a GL-style projection matrix corresponding to the frustum’s
projection.
ComputeUpVector() -> Vec3d
--------------------------
Returns the normalized world-space up vector, which is computed by
rotating the y axis by the frustum’s rotation.
ComputeViewDirection() -> Vec3d
-------------------------------
Returns the normalized world-space view direction vector, which is
computed by rotating the -z axis by the frustum’s rotation.
ComputeViewFrame(side, up, view) -> None
-----------------------------------------
Computes the view frame defined by this frustum.
The frame consists of the view direction, up vector and side vector,
as shown in this diagram.
up
^ ^
| /
| / view
|/
+- - - - > side
Parameters
----------
side
(Vec3d) –
up
(Vec3d) –
view
(Vec3d) –
ComputeViewInverse() -> Matrix4d
--------------------------------
Returns the inverse of the view matrix.
### ComputeViewInverse
Returns a matrix that represents the inverse viewing transformation for this frustum.
That is, it returns the matrix that converts points from eye (frustum) space to world space.
### ComputeViewMatrix
Returns a matrix that represents the viewing transformation for this frustum.
That is, it returns the matrix that converts points from world space to eye (frustum) space.
### FitToSphere
Modifies the frustum to tightly enclose a sphere with the given center and radius, using the current view direction.
The planes of the frustum are adjusted as necessary. The given amount of slack is added to the sphere’s radius is used around the sphere to avoid boundary problems.
**Parameters**
- **center** (Vec3d) –
- **radius** (float) –
- **slack** (float) –
### GetFOV
Returns the horizontal fov of the frustum. The fov of the frustum is not necessarily the same value as displayed in the viewer. The displayed fov is a function of the focal length or FOV avar. The frustum’s fov may be different due to things like lens breathing.
If the frustum is not of type GfFrustum::Perspective, the returned FOV will be 0.0.
### GetNearFar
Returns the near/far interval.
### GetOrthographic
Returns the current frustum in the format used by SetOrthographic().
If the current frustum is not an orthographic projection, this returns false and leaves the parameters untouched.
Parameters
----------
- **left** (`float`) –
- **right** (`float`) –
- **bottom** (`float`) –
- **top** (`float`) –
- **nearPlane** (`float`) –
- **farPlane** (`float`) –
GetPerspective
---------------
Returns the current perspective frustum values suitable for use by SetPerspective. If the current frustum is a perspective projection, the return value is a tuple of (fieldOfView, aspectRatio, nearDistance, farDistance). If the current frustum is not perspective, the return value is None.
GetPosition
-----------
Returns the position of the frustum in world space.
GetProjectionType
------------------
Returns the projection type.
GetReferencePlaneDepth
-----------------------
**classmethod** GetReferencePlaneDepth() -> float
Returns the depth of the reference plane.
GetRotation
-----------
Returns the orientation of the frustum in world space as a rotation to apply to the -z axis.
GetViewDistance
----------------
Returns the view distance.
GetWindow
---------
Returns the window rectangle in the reference plane.
Returns true if the given axis-aligned bbox is inside or intersecting the frustum.
Otherwise, it returns false. Useful when doing picking or frustum culling.
Parameters
----------
bbox
(BBox3d) –
Intersects(point) -> bool
--------------------------
Returns true if the given point is inside or intersecting the frustum.
Otherwise, it returns false.
Parameters
----------
point
(Vec3d) –
Intersects(p0, p1) -> bool
---------------------------
Returns true if the line segment formed by the given points is inside or intersecting the frustum.
Otherwise, it returns false.
Parameters
----------
p0
(Vec3d) –
p1
(Vec3d) –
Intersects(p0, p1, p2) -> bool
-------------------------------
Returns true if the triangle formed by the given points is inside or intersecting the frustum.
Otherwise, it returns false.
Parameters
----------
p0
(Vec3d) –
p1
(Vec3d) –
p2
(Vec3d) –
classmethod IntersectsViewVolume(bbox, vpMat) -> bool
-------------------------------------------------------
Returns true if the bbox volume intersects the view volume given by the view-projection matrix, erring on the side of false positives for efficiency.
This method is intended for cases where a GfFrustum is not available or when the view-projection matrix yields a view volume that is not expressable as a GfFrustum.
Because it errs on the side of false positives, it is suitable for early-out tests such as draw or intersection culling.
Parameters
----------
bbox
(BBox3d) –
vpMat
(Matrix4d) –
SetNearFar(nearFar) -> None
----------------------------
Sets the near/far interval.
### Parameters
- **nearFar** (Range1d) –
### SetOrthographic
```python
SetOrthographic(left, right, bottom, top, nearPlane, farPlane) -> None
```
Sets up the frustum in a manner similar to `glOrtho()`.
Sets the projection to `GfFrustum::Orthographic` and sets the window and near/far specifications based on the given values.
#### Parameters
- **left** (float) –
- **right** (float) –
- **bottom** (float) –
- **top** (float) –
- **nearPlane** (float) –
- **farPlane** (float) –
### SetPerspective
```python
SetPerspective(fieldOfViewHeight, aspectRatio, nearDistance, farDistance) -> None
```
Sets up the frustum in a manner similar to `gluPerspective()`.
It sets the projection type to `GfFrustum::Perspective` and sets the window specification so that the resulting symmetric frustum encloses an angle of `fieldOfViewHeight` degrees in the vertical direction, with `aspectRatio` used to figure the angle in the horizontal direction. The near and far distances are specified as well. The window coordinates are computed as:
```
top = tan(fieldOfViewHeight / 2)
bottom = -top
right = top \* aspectRatio
left = -right
near = nearDistance
far = farDistance
```
#### Parameters
- **fieldOfViewHeight** (float) –
- **aspectRatio** (float) –
- **nearDistance** (float) –
- **farDistance** (float) –
SetPerspective(fieldOfView, isFovVertical, aspectRatio, nearDistance, farDistance) -> None
Sets up the frustum in a manner similar to gluPerspective().
It sets the projection type to `GfFrustum::Perspective` and sets the window specification so that:
If *isFovVertical* is true, the resulting symmetric frustum encloses an angle of `fieldOfView` degrees in the vertical direction, with `aspectRatio` used to figure the angle in the horizontal direction.
If *isFovVertical* is false, the resulting symmetric frustum encloses an angle of `fieldOfView` degrees in the horizontal direction, with `aspectRatio` used to figure the angle in the vertical direction.
The near and far distances are specified as well. The window coordinates are computed as follows:
> - if isFovVertical:
> - top = tan(fieldOfView / 2)
> - right = top * aspectRatio
> - if NOT isFovVertical:
> - right = tan(fieldOfView / 2)
> - top = right / aspectRatio
> - bottom = -top
> - left = -right
> - near = nearDistance
> - far = farDistance
Parameters:
- **fieldOfView** (float) –
- **isFovVertical** (bool) –
- **aspectRatio** (float) –
- **nearDistance** (float) –
- **farDistance** (float) –
SetPosition(position) -> None
Sets the position of the frustum in world space.
Parameters:
- **position** (Vec3d) –
SetPositionAndRotationFromMatrix(camToWorldXf) -> None
Sets the position and rotation of the frustum from a camera matrix (always from a y-Up camera).
The resulting frustum’s transform will always represent a right-handed and orthonormal coordinate system (scale, shear, and projection are removed from the given `camToWorldXf`).
Parameters:
- **camToWorldXf** (Matrix4d) –
SetProjectionType(projectionType) -> None
Sets the projection type of the frustum.
Parameters:
- **projectionType** (GfFrustum::ProjectionType) –
### SetProjectionType
Sets the projection type.
**Parameters**
- **projectionType** (`Frustum.ProjectionType`) –
### SetRotation
Sets the orientation of the frustum in world space as a rotation to apply to the default frame: looking along the -z axis with the +y axis as "up".
**Parameters**
- **rotation** (`Rotation`) –
### SetViewDistance
Sets the view distance.
**Parameters**
- **viewDistance** (`float`) –
### SetWindow
Sets the window rectangle in the reference plane that defines the left, right, top, and bottom planes of the frustum.
**Parameters**
- **window** (`Range2d`) –
### Transform
Transforms the frustum by the given matrix.
The transformation matrix is applied as follows: the position and the direction vector are transformed with the given matrix. Then the length of the new direction vector is used to rescale the near and far plane and the view distance. Finally, the points that define the reference plane are transformed by the matrix. This method assures that the frustum will not be sheared or perspective-projected.
Note that this definition means that the transformed frustum does not preserve scales very well. Do **not** use this function to transform a frustum that is to be used for precise operations such as intersection testing.
**Parameters**
- **matrix** (`Matrix4d`) –
### Orthographic
```
```markdown
### Perspective
```
```markdown
### property nearFar
```
```markdown
### property position
```
```markdown
### property projectionType
```
```markdown
### property rotation
```
```markdown
### property viewDistance
```
```markdown
### property window
```
```markdown
### class Interval
Basic mathematical interval class
**Methods:**
- **Contains**
Returns true if x is inside the interval.
- **GetFullInterval**
`classmethod GetFullInterval() -> Interval`
- **GetMax**
Get the maximum value.
- **GetMin**
Get the minimum value.
- **GetSize**
The width of the interval
- **In**
(Description not provided in the HTML snippet)
```
Returns true if x is inside the interval.
Intersects(i)
Return true iff the given interval i intersects this interval.
IsEmpty
True if the interval is empty.
IsFinite()
Returns true if both the maximum and minimum value are finite.
IsMaxClosed()
Maximum boundary condition.
IsMaxFinite()
Returns true if the maximum value is finite.
IsMaxOpen()
Maximum boundary condition.
IsMinClosed()
Minimum boundary condition.
IsMinFinite()
Returns true if the minimum value is finite.
IsMinOpen()
Minimum boundary condition.
SetMax
Set the maximum value.
SetMin
Set the minimum value.
Attributes:
finite
isEmpty
True if the interval is empty.
max
The maximum value.
maxClosed
maxFinite
maxOpen
| Property | Description |
|----------|-------------|
| `maxOpen` | |
| `min` | The minimum value. |
| `minClosed` | |
| `minFinite` | |
| `minOpen` | |
| `size` | The width of the interval. |
### Contains()
Returns true if x is inside the interval.
### GetFullInterval()
**classmethod** GetFullInterval() -> Interval
Returns the full interval (-inf, inf).
### GetMax()
Get the maximum value.
### GetMin()
Get the minimum value.
### GetSize()
The width of the interval
### In()
Returns true if x is inside the interval.
### Intersects(i)
Return true iff the given interval i intersects this interval.
**Parameters**
- **i** (Interval) –
### IsEmpty()
- True if the interval is empty.
- **IsFinite**()
- Returns true if both the maximum and minimum value are finite.
- **IsMaxClosed**()
- Maximum boundary condition.
- **IsMaxFinite**()
- Returns true if the maximum value is finite.
- **IsMaxOpen**()
- Maximum boundary condition.
- **IsMinClosed**()
- Minimum boundary condition.
- **IsMinFinite**()
- Returns true if the minimum value is finite.
- **IsMinOpen**()
- Minimum boundary condition.
- **SetMax**()
- Set the maximum value.
- Set the maximum value and boundary condition.
- **SetMin**()
- Set the minimum value.
- Set the minimum value and boundary condition.
- **property finite**
- **property isEmpty**
- True if the interval is empty.
### pxr.Gf.Interval.max
**property**
**max**
The maximum value.
### pxr.Gf.Interval.maxClosed
**property**
**maxClosed**
### pxr.Gf.Interval.maxFinite
**property**
**maxFinite**
### pxr.Gf.Interval.maxOpen
**property**
**maxOpen**
### pxr.Gf.Interval.min
**property**
**min**
The minimum value.
### pxr.Gf.Interval.minClosed
**property**
**minClosed**
### pxr.Gf.Interval.minFinite
**property**
**minFinite**
### pxr.Gf.Interval.minOpen
**property**
**minOpen**
### pxr.Gf.Interval.size
**property**
**size**
The width of the interval.
### pxr.Gf.Line
**class**
**pxr.Gf.Line**
Line class
**Methods:**
- **FindClosestPoint(point, t)**
Returns the point on the line that is closest to `point`.
- **GetDirection()**
Return the normalized direction of the line.
- **GetPoint(t)**
Return the point on the line at `( p0 + t * dir)`.
- **Set(p0, dir)**
param p0
<dd class="field-odd">
<p>
</p>
</dd>
</dl>
</p>
</td>
</tr>
</tbody>
</table>
<p>
<strong>
Attributes:
</strong>
</p>
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>
<tbody>
<tr class="row-odd">
<td>
<p>
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
direction
</span>
</code>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
</tbody>
</table>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Line.FindClosestPoint">
<span class="sig-name descname">
<span class="pre">
FindClosestPoint
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
point
</span>
</span>
</em>
,
<em class="sig-param">
<span class="n">
<span class="pre">
t
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
Vec3d
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Line.FindClosestPoint" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Returns the point on the line that is closest to
<code class="docutils literal notranslate">
<span class="pre">
point
</span>
</code>
.
</p>
<p>
If
<code class="docutils literal notranslate">
<span class="pre">
t
</span>
</code>
is not
<code class="docutils literal notranslate">
<span class="pre">
None
</span>
</code>
, it will be set to the parametric distance along the line of the returned point.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
point
</strong>
(
Vec3d
) –
</p>
</li>
<li>
<p>
<strong>
t
</strong>
(
float
) –
</p>
</li>
</ul>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Line.GetDirection">
<span class="sig-name descname">
<span class="pre">
GetDirection
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
Vec3d
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Line.GetDirection" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return the normalized direction of the line.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Line.GetPoint">
<span class="sig-name descname">
<span class="pre">
GetPoint
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
t
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
Vec3d
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Line.GetPoint" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return the point on the line at `` ( p0 + t * dir).
</p>
<p>
Remember dir has been normalized so t represents a unit distance.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
t
</strong>
(
float
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Line.Set">
<span class="sig-name descname">
<span class="pre">
Set
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
p0
</span>
</span>
</em>
,
<em class="sig-param">
<span class="n">
<span class="pre">
dir
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
float
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Line.Set" title="Permalink to this definition">
</a>
</dt>
<dd>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
p0
</strong>
(
Vec3d
) –
</p>
</li>
<li>
<p>
<strong>
dir
</strong>
(
Vec3d
) –
</p>
</li>
</ul>
</dd>
</dl>
</dd>
</dl>
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Line.direction">
<em class="property">
<span class="pre">
property
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
## pxr.Gf.LineSeg
Line segment class
### Methods:
| Method | Description |
| --- | --- |
| `FindClosestPoint(point, t)` | Returns the point on the line that is closest to `point`. |
| `GetDirection()` | Return the normalized direction of the line. |
| `GetLength()` | Return the length of the line. |
| `GetPoint(t)` | Return the point on the segment specified by the parameter t. |
### Attributes:
| Attribute | Description |
| --- | --- |
| `direction` | |
| `length` | |
#### FindClosestPoint(point, t)
Returns the point on the line that is closest to `point`.
If `t` is not `None`, it will be set to the parametric distance along the line of the closest point.
**Parameters:**
- **point** (`Vec3d`) –
- **t** (`float`) –
#### GetDirection()
Return the normalized direction of the line.
#### GetLength()
Return the length of the line.
(float)
Return the length of the line.
GetPoint(t) → Vec3d
Return the point on the segment specified by the parameter t.
p = p0 + t * (p1 - p0)
Parameters:
- t (float) –
property direction
property length
class pxr.Gf.Matrix2d
Methods:
- GetColumn(i) - Gets a column of the matrix as a Vec2.
- GetDeterminant() - Returns the determinant of the matrix.
- GetInverse(det, eps) - Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- GetRow(i) - Gets a row of the matrix as a Vec2.
- GetTranspose() - Returns the transpose of the matrix.
- Set(m00, m01, m10, m11) - Sets the matrix from 4 independent double values, specified in row-major order.
- SetColumn(i, v) - Sets a column of the matrix from a Vec2.
- SetDiagonal(s) - Sets the matrix to
<em>s</em> times the identity matrix.
```python
SetIdentity()
```
Sets the matrix to the identity matrix.
```python
SetRow(i, v)
```
Sets a row of the matrix from a Vec2.
```python
SetZero()
```
Sets the matrix to zero.
**Attributes:**
```python
dimension
```
```python
GetColumn(i) → Vec2d
```
Gets a column of the matrix as a Vec2.
Parameters:
- **i** (int) –
```python
GetDeterminant() → float
```
Returns the determinant of the matrix.
```python
GetInverse(det, eps) → Matrix2d
```
Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
(FLT_MAX is the largest value a `float` can have, as defined by the system.) The matrix is considered singular if the determinant is less than or equal to the optional parameter `eps`. If `det` is non-null, `*det` is set to the determinant.
Parameters:
- **det** (float) –
- **eps** (float) –
```python
GetRow(i) → Vec2d
```
Gets a row of the matrix as a Vec2.
Parameters:
- **i** (int) –
```
### Parameters
- **i** (`int`) –
### GetTranspose
```
GetTranspose() -> Matrix2d
```
Returns the transpose of the matrix.
### Set
```
Set(m00, m01, m10, m11) -> Matrix2d
```
Sets the matrix from 4 independent `double` values, specified in row-major order.
For example, parameter *m10* specifies the value in row 1 and column 0.
#### Parameters
- **m00** (`float`) –
- **m01** (`float`) –
- **m10** (`float`) –
- **m11** (`float`) –
### SetColumn
```
SetColumn(i, v) -> None
```
Sets a column of the matrix from a Vec2.
#### Parameters
- **i** (`int`) –
- **v** (`Vec2d`) –
### SetDiagonal
```
SetDiagonal(s) -> Matrix2d
```
Sets the matrix to *s* times the identity matrix.
#### Parameters
- **s** (`float`) –
### Matrix2d Methods
#### SetDiagonal(arg1) -> Matrix2d
Sets the matrix to have diagonal `v[0], v[1]`.
**Parameters:**
- **arg1** (`Vec2d`) –
#### SetIdentity() -> Matrix2d
Sets the matrix to the identity matrix.
#### SetRow(i, v) -> None
Sets a row of the matrix from a Vec2.
**Parameters:**
- **i** (`int`) –
- **v** (`Vec2d`) –
#### SetZero() -> Matrix2d
Sets the matrix to zero.
### Matrix2d Attribute
#### dimension = (2, 2)
### Matrix2f Methods
- **GetColumn(i)** – Gets a column of the matrix as a Vec2.
- **GetDeterminant()** – Returns the determinant of the matrix.
- **GetInverse(det, eps)** – Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- **GetRow(i)** – Gets a row of the matrix as a Vec2.
| Method | Description |
|--------|-------------|
| GetRow (i) | Gets a row of the matrix as a Vec2. |
| GetTranspose () | Returns the transpose of the matrix. |
| Set (m00, m01, m10, m11) | Sets the matrix from 4 independent float values, specified in row-major order. |
| SetColumn (i, v) | Sets a column of the matrix from a Vec2. |
| SetDiagonal (s) | Sets the matrix to s times the identity matrix. |
| SetIdentity () | Sets the matrix to the identity matrix. |
| SetRow (i, v) | Sets a row of the matrix from a Vec2. |
| SetZero () | Sets the matrix to zero. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| dimension | |
**Methods:**
- **GetColumn (i) → Vec2f**
- Gets a column of the matrix as a Vec2.
- Parameters:
- **i** (int) –
- **GetDeterminant () → float**
- Returns the determinant of the matrix.
- **GetInverse (det, eps) → Matrix2f**
- Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the
matrix is singular.
The matrix is considered singular if the determinant is less than or equal to the optional parameter `eps`. If `det` is non-null, `\*det` is set to the determinant.
### Parameters
- **det** (`float`) –
- **eps** (`float`) –
### GetRow
```python
GetRow(i) -> Vec2f
```
Gets a row of the matrix as a Vec2.
#### Parameters
- **i** (`int`) –
### GetTranspose
```python
GetTranspose() -> Matrix2f
```
Returns the transpose of the matrix.
### Set
```python
Set(m00, m01, m10, m11) -> Matrix2f
```
Sets the matrix from 4 independent `float` values, specified in row-major order.
For example, parameter `m10` specifies the value in row 1 and column 0.
#### Parameters
- **m00** (`float`) –
- **m01** (`float`) –
- **m10** (`float`) –
- **m11** (`float`) –
Set(m) -> Matrix2f
Sets the matrix from a 2x2 array of `float` values, specified in row-major order.
#### Parameters
- **m** (`float`) –
### SetColumn
```python
SetColumn(i, v) -> Matrix2f
```
Sets a column of the matrix.
#### Parameters
- **i** (`int`) –
- **v** (`float`) –
### SetColumn
Sets a column of the matrix from a Vec2.
**Parameters**
- **i** (int) –
- **v** (Vec2f) –
### SetDiagonal
Sets the matrix to `s` times the identity matrix.
**Parameters**
- **s** (float) –
SetDiagonal(arg1) -> Matrix2f
Sets the matrix to have diagonal (`v[0]`, `v[1]`).
**Parameters**
- **arg1** (Vec2f) –
### SetIdentity
Sets the matrix to the identity matrix.
### SetRow
Sets a row of the matrix from a Vec2.
**Parameters**
- **i** (int) –
- **v** (Vec2f) –
### SetZero
Sets the matrix to zero.
### dimension
dimension = (2, 2)
## pxr.Gf.Matrix3d
### Methods:
| Method | Description |
|--------|-------------|
| `ExtractRotation()` | Returns the rotation corresponding to this matrix. |
| `GetColumn(i)` | Gets a column of the matrix as a Vec3. |
| `GetDeterminant()` | Returns the determinant of the matrix. |
| `GetHandedness()` | Returns the sign of the determinant of the matrix, i.e. |
| `GetInverse(det, eps)` | Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular. |
| `GetOrthonormalized(issueWarning)` | Returns an orthonormalized copy of the matrix. |
| `GetRow(i)` | Gets a row of the matrix as a Vec3. |
| `GetTranspose()` | Returns the transpose of the matrix. |
| `IsLeftHanded()` | Returns true if the vectors in matrix form a left-handed coordinate system. |
| `IsRightHanded()` | Returns true if the vectors in the matrix form a right-handed coordinate system. |
| `Orthonormalize(issueWarning)` | Makes the matrix orthonormal in place. |
| `Set(m00, m01, m02, m10, m11, m12, m20, m21, m22)` | Sets the matrix from 9 independent double values, specified in row-major order. |
| `SetColumn(i, v)` | Sets a column of the matrix from a Vec3. |
| `SetDiagonal(s)` | Sets the matrix to s times the identity matrix. |
| Method | Description |
|--------|-------------|
| `SetIdentity()` | Sets the matrix to the identity matrix. |
| `SetRotate(rot)` | Sets the matrix to specify a rotation equivalent to `rot`. |
| `SetRow(i, v)` | Sets a row of the matrix from a Vec3. |
| `SetScale(scaleFactors)` | Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector `scaleFactors`. |
| `SetZero()` | Sets the matrix to zero. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
**Methods:**
- **ExtractRotation()** → `Rotation`
- Returns the rotation corresponding to this matrix. This works well only if the matrix represents a rotation. For good results, consider calling Orthonormalize() before calling this method.
- **GetColumn(i)** → `Vec3d`
- Gets a column of the matrix as a Vec3.
- Parameters:
- **i** (int) –
- **GetDeterminant()** → float
- Returns the determinant of the matrix.
- **GetHandedness()** → float
- Returns the sign of the determinant of the matrix, i.e., 1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a singular matrix.
- **GetInverse(det)** → `Matrix3d`
- Returns the inverse of the matrix.
- Parameters:
- **det** (float) – The determinant of the matrix.
### GetInverse
Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
(FLT_MAX is the largest value a `float` can have, as defined by the system.) The matrix is considered singular if the determinant is less than or equal to the optional parameter `eps`. If `det` is non-null, `\*det` is set to the determinant.
#### Parameters
- **det** (`float`) –
- **eps** (`float`) –
### GetOrthonormalized
Returns an orthonormalized copy of the matrix.
#### Parameters
- **issueWarning** (`bool`) –
### GetRow
Gets a row of the matrix as a Vec3.
#### Parameters
- **i** (`int`) –
### GetTranspose
Returns the transpose of the matrix.
### IsLeftHanded
Returns true if the vectors in matrix form a left-handed coordinate system.
### IsRightHanded
Returns true if the vectors in the matrix form a right-handed coordinate system.
### Orthonormalize
### Orthonormalize
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous cross/cross method. If the iterative method does not converge, a warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any translation part of the matrix unchanged. If `issueWarning` is true, this method will issue a warning if the iteration does not converge, otherwise it will be silent.
#### Parameters
- **issueWarning** (`bool`) –
### Set
Sets the matrix from 9 independent `double` values, specified in row-major order.
For example, parameter `m10` specifies the value in row 1 and column 0.
#### Parameters
- **m00** (`float`) –
- **m01** (`float`) –
- **m02** (`float`) –
- **m10** (`float`) –
- **m11** (`float`) –
- **m12** (`float`) –
- **m20** (`float`) –
- **m21** (`float`) –
- **m22** (`float`) –
Set(m) -> Matrix3d
Sets the matrix from a 3x3 array of `double` values, specified in row-major order.
#### Parameters
- **m** (`float`) –
### SetColumn
Sets a column of the matrix from a Vec3.
#### Parameters
- **i** (`int`) –
- **v** (`Vec3`) –
### SetDiagonal
```SetDiagonal```
Sets the matrix to `s` times the identity matrix.
**Parameters**
- **s** (`float`) –
SetDiagonal(arg1) -> Matrix3d
Sets the matrix to have diagonal (`v[0], v[1], v[2]`).
**Parameters**
- **arg1** (`Vec3d`) –
### SetIdentity
```SetIdentity```
Sets the matrix to the identity matrix.
### SetRotate
```SetRotate```
Sets the matrix to specify a rotation equivalent to `rot`.
**Parameters**
- **rot** (`Quatd`) –
SetRotate(rot) -> Matrix3d
Sets the matrix to specify a rotation equivalent to `rot`.
**Parameters**
- **rot** (`Rotation`) –
### SetRow
```SetRow```
Sets a row of the matrix from a Vec3.
**Parameters**
- **i** (`int`) –
- **v** (`Vec3d`) –
### SetScale
(scaleFactors) → Matrix3d
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector `scaleFactors`.
**Parameters**
- **scaleFactors** (`Vec3d`) –
---
SetScale(scaleFactor) -> Matrix3d
Sets matrix to specify a uniform scaling by `scaleFactor`.
**Parameters**
- **scaleFactor** (`float`) –
---
### SetZero
() → Matrix3d
Sets the matrix to zero.
---
### dimension
= (3, 3)
---
### class pxr.Gf.Matrix3f
**Methods:**
- **ExtractRotation**() - Returns the rotation corresponding to this matrix.
- **GetColumn**(i) - Gets a column of the matrix as a Vec3.
- **GetDeterminant**() - Returns the determinant of the matrix.
- **GetHandedness**() - Returns the sign of the determinant of the matrix, i.e.
- **GetInverse**(det, eps) - Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- **GetOrthonormalized**(issueWarning) - Returns an orthonormalized copy of the matrix.
- **GetRow**(i) - Gets a row of the matrix as a Vec3.
<p>
GetTranspose()
</p>
<p>
Returns the transpose of the matrix.
</p>
<p>
IsLeftHanded()
</p>
<p>
Returns true if the vectors in matrix form a left-handed coordinate system.
</p>
<p>
IsRightHanded()
</p>
<p>
Returns true if the vectors in the matrix form a right-handed coordinate system.
</p>
<p>
Orthonormalize(issueWarning)
</p>
<p>
Makes the matrix orthonormal in place.
</p>
<p>
Set(m00, m01, m02, m10, m11, m12, m20, m21, m22)
</p>
<p>
Sets the matrix from 9 independent float values, specified in row-major order.
</p>
<p>
SetColumn(i, v)
</p>
<p>
Sets a column of the matrix from a Vec3.
</p>
<p>
SetDiagonal(s)
</p>
<p>
Sets the matrix to s times the identity matrix.
</p>
<p>
SetIdentity()
</p>
<p>
Sets the matrix to the identity matrix.
</p>
<p>
SetRotate(rot)
</p>
<p>
Sets the matrix to specify a rotation equivalent to rot.
</p>
<p>
SetRow(i, v)
</p>
<p>
Sets a row of the matrix from a Vec3.
</p>
<p>
SetScale(scaleFactors)
</p>
<p>
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector scaleFactors.
</p>
<p>
SetZero()
</p>
<p>
Sets the matrix to zero.
</p>
<p>
<strong>
Attributes:
</strong>
</p>
<p>
dimension
</p>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Matrix3f.ExtractRotation">
<span class="sig-name descname">
<span class="pre">
ExtractRotation
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Rotation" title="pxr.Gf.Rotation">
<span class="pre">
Rotation
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Matrix3f.ExtractRotation" title="Permalink to this definition">
</a>
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling this method.
GetColumn
(
i
)
→ Vec3f
Gets a column of the matrix as a Vec3.
Parameters
----------
i (int) –
GetDeterminant
(
)
→ float
Returns the determinant of the matrix.
GetHandedness
(
)
→ float
Returns the sign of the determinant of the matrix, i.e.
1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a singular matrix.
GetInverse
(
det,
eps
)
→ Matrix3f
Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
(FLT_MAX is the largest value a float can have, as defined by the system.) The matrix is considered singular if the determinant is less than or equal to the optional parameter eps. If det is non-null, *det is set to the determinant.
Parameters
----------
det (float) –
eps (float) –
GetOrthonormalized
(
issueWarning
)
→ Matrix3f
Returns an orthonormalized copy of the matrix.
Parameters
----------
issueWarning (bool) –
GetRow
(
i
)
→ Vec3f
Gets a row of the matrix as a Vec3.
### GetRow
Gets a row of the matrix as a Vec3.
#### Parameters
- **i** (int) –
### GetTranspose
Returns the transpose of the matrix.
### IsLeftHanded
Returns true if the vectors in matrix form a left-handed coordinate system.
### IsRightHanded
Returns true if the vectors in the matrix form a right-handed coordinate system.
### Orthonormalize
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous cross/cross method. If the iterative method does not converge, a warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any translation part of the matrix unchanged. If `issueWarning` is true, this method will issue a warning if the iteration does not converge, otherwise it will be silent.
#### Parameters
- **issueWarning** (bool) –
### Set
Sets the matrix from 9 independent float values, specified in row-major order.
For example, parameter `m10` specifies the value in row 1 and column 0.
#### Parameters
- **m00** (float) –
- **m01** (float) –
- **m02** (float) –
- **m10** (float) –
- **m11** (float) –
- **m12** (float) –
- **m20** (float) –
- **m21** (float) –
- **m22** (float) –
**m01** (**float**) –
**m02** (**float**) –
**m10** (**float**) –
**m11** (**float**) –
**m12** (**float**) –
**m20** (**float**) –
**m21** (**float**) –
**m22** (**float**) –
Set(m) -> Matrix3f
Sets the matrix from a 3x3 array of `float` values, specified in row-major order.
**Parameters**
- **m** (**float**) –
**SetColumn** (i, v) -> None
Sets a column of the matrix from a Vec3.
**Parameters**
- **i** (**int**) –
- **v** (**Vec3f**) –
**SetDiagonal** (s) -> Matrix3f
Sets the matrix to s times the identity matrix.
**Parameters**
- **s** (**float**) –
SetDiagonal(arg1) -> Matrix3f
Sets the matrix to have diagonal (`v[0], v[1], v[2]`).
**Parameters**
- **arg1** (**Vec3f**) –
**SetIdentity** () -> Matrix3f
Sets the matrix to the identity matrix.
**SetRotate** (rot) -> None
Sets the matrix to represent a rotation.
**Parameters**
- **rot** (**Gf.Rotation**) –
### SetRotate Method
Sets the matrix to specify a rotation equivalent to `rot`.
#### Parameters
- **rot** (`Quatf`) –
---
SetRotate(rot) -> Matrix3f
Sets the matrix to specify a rotation equivalent to `rot`.
#### Parameters
- **rot** (`Rotation`) –
### SetRow Method
Sets a row of the matrix from a Vec3.
#### Parameters
- **i** (`int`) –
- **v** (`Vec3f`) –
### SetScale Method
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector `scaleFactors`.
#### Parameters
- **scaleFactors** (`Vec3f`) –
---
SetScale(scaleFactor) -> Matrix3f
Sets matrix to specify a uniform scaling by `scaleFactor`.
#### Parameters
- **scaleFactor** (`float`) –
### SetZero Method
Sets the matrix to zero.
### dimension Attribute
dimension = (3, 3)
## Methods:
| Method | Description |
| --- | --- |
| `ExtractRotation()` | Returns the rotation corresponding to this matrix. |
| `ExtractRotationMatrix()` | Returns the rotation corresponding to this matrix. |
| `ExtractRotationQuat()` | Return the rotation corresponding to this matrix as a quaternion. |
| `ExtractTranslation()` | Returns the translation part of the matrix, defined as the first three elements of the last row. |
| `Factor(r, s, u, t, p, eps)` | Factors the matrix into 5 components: |
| `GetColumn(i)` | Gets a column of the matrix as a Vec4. |
| `GetDeterminant()` | Returns the determinant of the matrix. |
| `GetDeterminant3()` | Returns the determinant of the upper 3x3 matrix. |
| `GetHandedness()` | Returns the sign of the determinant of the upper 3x3 matrix, i.e. |
| `GetInverse(det, eps)` | Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular. |
| `GetOrthonormalized(issueWarning)` | Returns an orthonormalized copy of the matrix. |
| `GetRow(i)` | Gets a row of the matrix as a Vec4. |
| `GetRow3(i)` | Gets a row of the matrix as a Vec3. |
| `GetTranspose()` | Returns the transpose of the matrix. |
| `HasOrthogonalRows3()` | Returns true, if the row vectors of the upper 3x3 matrix form an orthogonal basis. |
IsLeftHanded()
Returns true if the vectors in the upper 3x3 matrix form a left-handed coordinate system.
IsRightHanded()
Returns true if the vectors in the upper 3x3 matrix form a right-handed coordinate system.
Orthonormalize(issueWarning)
Makes the matrix orthonormal in place.
RemoveScaleShear()
Returns the matrix with any scaling or shearing removed, leaving only the rotation and translation.
Set(m00, m01, m02, m03, m10, m11, m12, m13, ...)
Sets the matrix from 16 independent double values, specified in row-major order.
SetColumn(i, v)
Sets a column of the matrix from a Vec4.
SetDiagonal(s)
Sets the matrix to s times the identity matrix.
SetIdentity()
Sets the matrix to the identity matrix.
SetLookAt(eyePoint, centerPoint, upDirection)
Sets the matrix to specify a viewing matrix from parameters similar to those used by gluLookAt(3G).
SetRotate(rot)
Sets the matrix to specify a rotation equivalent to rot, and clears the translation.
SetRotateOnly(rot)
Sets the matrix to specify a rotation equivalent to rot, without clearing the translation.
SetRow(i, v)
Sets a row of the matrix from a Vec4.
SetRow3(i, v)
Sets a row of the matrix from a Vec3.
SetScale(scaleFactors)
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector scaleFactors.
SetTransform()
| Method | Description |
|--------|-------------|
| `SetTransform(rotate, translate)` | Sets matrix to specify a rotation by `rotate` and a translation by `translate`. |
| `SetTranslate(trans)` | Sets matrix to specify a translation by the vector `trans`, and clears the rotation. |
| `SetTranslateOnly(t)` | Sets matrix to specify a translation by the vector `trans`, without clearing the rotation. |
| `SetZero()` | Sets the matrix to zero. |
| `Transform(vec)` | Transforms the row vector `vec` by the matrix, returning the result. |
| `TransformAffine(vec)` | Transforms the row vector `vec` by the matrix, returning the result. |
| `TransformDir(vec)` | Transforms row vector `vec` by the matrix, returning the result. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
**Methods:**
- **ExtractRotation()**
- Returns the rotation corresponding to this matrix.
- This works well only if the matrix represents a rotation.
- For good results, consider calling Orthonormalize() before calling this method.
- **ExtractRotationMatrix()**
- Returns the rotation corresponding to this matrix.
- This works well only if the matrix represents a rotation.
- For good results, consider calling Orthonormalize() before calling this method.
- **ExtractRotationQuat()**
- Return the rotation corresponding to this matrix as a quaternion.
- This works well only if the matrix represents a rotation.
- For good results, consider calling Orthonormalize() before calling this method.
### ExtractTranslation
Returns the translation part of the matrix, defined as the first three elements of the last row.
### Factor
Factors the matrix into 5 components:
- *M* = r \* s \* -r \* u \* t where
- t is a translation.
- u and r are rotations, and -r is the transpose (inverse) of r. The u matrix may contain shear information.
- s is a scale. Any projection information could be returned in matrix p, but currently p is never modified.
Returns `false` if the matrix is singular (as determined by eps).
In that case, any zero scales in s are clamped to eps to allow computation of u.
#### Parameters
- **r** (Matrix4d) –
- **s** (Vec3d) –
- **u** (Matrix4d) –
- **t** (Vec3d) –
- **p** (Matrix4d) –
- **eps** (float) –
### GetColumn
## pxr.Gf.Matrix4d.GetColumn
- **Description**: Gets a column of the matrix as a Vec4.
- **Parameters**:
- **i** (int) –
## pxr.Gf.Matrix4d.GetDeterminant
- **Description**: Returns the determinant of the matrix.
## pxr.Gf.Matrix4d.GetDeterminant3
- **Description**: Returns the determinant of the upper 3x3 matrix.
- **Additional Info**: This method is useful when the matrix describes a linear transformation such as a rotation or scale because the other values in the 4x4 matrix are not important.
## pxr.Gf.Matrix4d.GetHandedness
- **Description**: Returns the sign of the determinant of the upper 3x3 matrix, i.e. 1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a singular matrix.
## pxr.Gf.Matrix4d.GetInverse
- **Description**: Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- **Additional Info**: The matrix is considered singular if the determinant is less than or equal to the optional parameter `eps`. If `det` is non-null, `*det` is set to the determinant.
- **Parameters**:
- **det** (float) –
- **eps** (float) –
## pxr.Gf.Matrix4d.GetOrthonormalized
- **Description**: Returns an orthonormalized copy of the matrix.
- **Parameters**:
- **issueWarning** (bool) –
## pxr.Gf.Matrix4d.GetRow
- **Description**: Gets a row of the matrix as a Vec4.
- **Parameters**:
- **i** (int) –
### GetRow
Gets a row of the matrix as a Vec4.
**Parameters**
- **i** (int) –
### GetRow3
Gets a row of the matrix as a Vec3.
**Parameters**
- **i** (int) –
### GetTranspose
Returns the transpose of the matrix.
### HasOrthogonalRows3
Returns true, if the row vectors of the upper 3x3 matrix form an orthogonal basis.
Note they do not have to be unit length for this test to return true.
### IsLeftHanded
Returns true if the vectors in the upper 3x3 matrix form a left-handed coordinate system.
### IsRightHanded
Returns true if the vectors in the upper 3x3 matrix form a right-handed coordinate system.
### Orthonormalize
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous cross/cross method. If the iterative method does not converge, a warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any translation part of the matrix unchanged. If issueWarning is true, this method will issue a warning if the iteration does not converge, otherwise it will be silent.
**Parameters**
- **issueWarning** (bool) –
### RemoveScaleShear
Returns a matrix with scale and shear removed.
Returns the matrix with any scaling or shearing removed, leaving only the rotation and translation.
If the matrix cannot be decomposed, returns the original matrix.
Set
(
m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33
) -> Matrix4d
Sets the matrix from 16 independent double values, specified in row-major order.
For example, parameter m10 specifies the value in row 1 and column 0.
Parameters:
- m00 (float) –
- m01 (float) –
- m02 (float) –
- m03 (float) –
- m10 (float) –
- m11 (float) –
- m12 (float) –
- m13 (float) –
- m20 (float) –
- m21 (float) –
- m22 (float) –
- m23 (float) –
- m30 (float) –
- m31 (float) –
- m32 (float) –
- m33 (float) –
Set(m) -> Matrix4d
Sets the matrix from a 4x4 array of double
values, specified in row-major order.
### Parameters
**m** (*float*) –
### Parameters
- **i** (*int*) –
- **v** (*Vec4d*) –
Sets a column of the matrix from a Vec4.
### Parameters
**s** (*float*) –
Sets the matrix to *s* times the identity matrix.
SetDiagonal(arg1) -> Matrix4d
Sets the matrix to have diagonal (*v*[0], *v*[1], *v*[2], *v*[3]).
### Parameters
**arg1** (*Vec4d*) –
### Parameters
- **eyePoint** (*Vec3d*) –
- **centerPoint** (*Vec3d*) –
- **upDirection** (*Vec3d*) –
Sets the matrix to specify a viewing matrix from parameters similar to those used by `gluLookAt(3G)`.
*eyePoint* represents the eye point in world space.
*centerPoint* represents the world-space center of attention.
*upDirection* is a vector indicating which way is up.
- **centerPoint** (Vec3d) –
- **upDirection** (Vec3d) –
SetLookAt(eyePoint, orientation) -> Matrix4d
Sets the matrix to specify a viewing matrix from a world-space `eyePoint` and a world-space rotation that rigidly rotates the orientation from its canonical frame, which is defined to be looking along the `-z` axis with the `+y` axis as the up direction.
- **Parameters**
- **eyePoint** (Vec3d) –
- **orientation** (Rotation) –
- **SetRotate**
- **Parameters**
- **rot** (Quatd) –
SetRotate(rot) -> Matrix4d
Sets the matrix to specify a rotation equivalent to `rot`, and clears the translation.
- **Parameters**
- **rot** (Rotation) –
- **SetRotate**
- **Parameters**
- **mx** (Matrix3d) –
SetRotate(mx) -> Matrix4d
Sets the matrix to specify a rotation equivalent to `mx`, and clears the translation.
- **SetRotateOnly**
- **Parameters**
- **rot** (Quatd) –
SetRotateOnly(rot) -> Matrix4d
Sets the matrix to specify a rotation equivalent to `rot`, without clearing the translation.
- **Parameters**
- **rot** (Rotation) –
- **SetRotateOnly**
- **Parameters**
- **mx** (Matrix3d) –
SetRotateOnly(mx) -> Matrix4d
Sets the matrix to specify a rotation equivalent to `mx`, without clearing the translation.
### SetRow
Sets a row of the matrix from a Vec4.
**Parameters**
- **i** (int) –
- **v** (Vec4d) –
### SetRow3
Sets a row of the matrix from a Vec3.
The fourth element of the row is ignored.
**Parameters**
- **i** (int) –
- **v** (Vec3d) –
### SetScale
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector scaleFactors.
**Parameters**
- **scaleFactors** (Vec3d) –
SetScale(scaleFactor) -> Matrix4d
Sets matrix to specify a uniform scaling by scaleFactor.
**Parameters**
- **scaleFactor** (float) –
### SetTransform
Sets matrix to specify a rotation by rotate and a translation by translate.
**Parameters**
- **rotate** (Rotation) –
- **translate** (Vec3d) –
- **rotate** (**Vec3d**) –
- **translate** (**Vec3d**) –
---
SetTransform(rotmx, translate) -> Matrix4d
Sets matrix to specify a rotation by **rotmx** and a translation by **translate**.
- **rotmx** (**Matrix3d**) –
- **translate** (**Vec3d**) –
---
SetTranslate(trans) -> Matrix4d
Sets matrix to specify a translation by the vector **trans**, and clears the rotation.
- **trans** (**Vec3d**) –
---
SetTranslateOnly(t) -> Matrix4d
Sets matrix to specify a translation by the vector **trans**, without clearing the rotation.
- **t** (**Vec3d**) –
---
SetZero() -> Matrix4d
Sets the matrix to zero.
---
Transform(vec) -> Vec3d
Transforms the row vector **vec** by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1.
- **vec** (**Vec3d**) –
---
Transform(vec) -> Vec3f
Transforms the row vector **vec** by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1. This is an overloaded method; it differs from the other version in that it returns a different value type.
- **vec** (**Vec3f**) –
### TransformAffine Method
```python
TransformAffine(vec)
```
Transforms the row vector `vec` by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1 and ignores the fourth column of the matrix (i.e. assumes it is (0, 0, 0, 1)).
**Parameters:**
- **vec** (Vec3d) –
---
```python
TransformAffine(vec) -> Vec3f
```
Transforms the row vector `vec` by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1 and ignores the fourth column of the matrix (i.e. assumes it is (0, 0, 0, 1)).
**Parameters:**
- **vec** (Vec3f) –
### TransformDir Method
```python
TransformDir(vec)
```
Transforms row vector `vec` by the matrix, returning the result.
This treats the vector as a direction vector, so the translation information in the matrix is ignored. That is, it treats the vector as a 4-component vector whose fourth component is 0.
**Parameters:**
- **vec** (Vec3d) –
---
```python
TransformDir(vec) -> Vec3f
```
Transforms row vector `vec` by the matrix, returning the result.
This treats the vector as a direction vector, so the translation information in the matrix is ignored. That is, it treats the vector as a 4-component vector whose fourth component is 0. This is an overloaded method; it differs from the other version in that it returns a different value type.
**Parameters:**
- **vec** (Vec3f) –
### dimension Attribute
```python
dimension = (4, 4)
```
### Matrix4f Class
**Methods:**
- `ExtractRotation()` - Returns the rotation corresponding to this matrix.
- `ExtractRotationMatrix()` - Returns the rotation corresponding to this matrix.
```
- `ExtractRotationQuat()`
- Return the rotation corresponding to this matrix as a quaternion.
- `ExtractTranslation()`
- Returns the translation part of the matrix, defined as the first three elements of the last row.
- `Factor(r, s, u, t, p, eps)`
- Factors the matrix into 5 components:
- `GetColumn(i)`
- Gets a column of the matrix as a Vec4.
- `GetDeterminant()`
- Returns the determinant of the matrix.
- `GetDeterminant3()`
- Returns the determinant of the upper 3x3 matrix.
- `GetHandedness()`
- Returns the sign of the determinant of the upper 3x3 matrix, i.e.
- `GetInverse(det, eps)`
- Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
- `GetOrthonormalized(issueWarning)`
- Returns an orthonormalized copy of the matrix.
- `GetRow(i)`
- Gets a row of the matrix as a Vec4.
- `GetRow3(i)`
- Gets a row of the matrix as a Vec3.
- `GetTranspose()`
- Returns the transpose of the matrix.
- `HasOrthogonalRows3()`
- Returns true, if the row vectors of the upper 3x3 matrix form an orthogonal basis.
- `IsLeftHanded()`
- Returns true if the vectors in the upper 3x3 matrix form a left-handed coordinate system.
- `IsRightHanded()`
- Returns true if the vectors in the upper 3x3 matrix form a right-handed coordinate system.
- `Orthonormalize(issueWarning)`
- Orthonormalizes the matrix.
Makes the matrix orthonormal in place.
RemoveScaleShear()
Returns the matrix with any scaling or shearing removed, leaving only the rotation and translation.
Set(m00, m01, m02, m03, m10, m11, m12, m13, ...)
Sets the matrix from 16 independent float values, specified in row-major order.
SetColumn(i, v)
Sets a column of the matrix from a Vec4.
SetDiagonal(s)
Sets the matrix to s times the identity matrix.
SetIdentity()
Sets the matrix to the identity matrix.
SetLookAt(eyePoint, centerPoint, upDirection)
Sets the matrix to specify a viewing matrix from parameters similar to those used by gluLookAt(3G).
SetRotate(rot)
Sets the matrix to specify a rotation equivalent to rot, and clears the translation.
SetRotateOnly(rot)
Sets the matrix to specify a rotation equivalent to rot, without clearing the translation.
SetRow(i, v)
Sets a row of the matrix from a Vec4.
SetRow3(i, v)
Sets a row of the matrix from a Vec3.
SetScale(scaleFactors)
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector scaleFactors.
SetTransform(rotate, translate)
Sets matrix to specify a rotation by rotate and a translation by translate.
SetTranslate(trans)
Sets matrix to specify a translation by the vector trans, and clears the rotation.
SetTranslateOnly(t)
| Method | Description |
|--------|-------------|
| `SetZero()` | Sets the matrix to zero. |
| `Transform(vec)` | Transforms the row vector `vec` by the matrix, returning the result. |
| `TransformAffine(vec)` | Transforms the row vector `vec` by the matrix, returning the result. |
| `TransformDir(vec)` | Transforms row vector `vec` by the matrix, returning the result. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
### ExtractRotation()
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling this method.
### ExtractRotationMatrix()
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling this method.
### ExtractRotationQuat()
Return the rotation corresponding to this matrix as a quaternion.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling this method.
### ExtractTranslation()
Returns the translation part of the matrix, defined as the first three elements of the last row.
### Factor Method
Factors the matrix into 5 components:
> - *M* = r \* s \* -r \* u \* t where
> - t is a translation.
> - u and r are rotations, and -r is the transpose (inverse) of r. The u matrix may contain shear information.
> - s is a scale. Any projection information could be returned in matrix p, but currently p is never modified.
> - Returns `false` if the matrix is singular (as determined by eps). In that case, any zero scales in s are clamped to eps to allow computation of u.
#### Parameters
- **r** (Matrix4f) –
- **s** (Vec3f) –
- **u** (Matrix4f) –
- **t** (Vec3f) –
- **p** (Matrix4f) –
- **eps** (float) –
### GetColumn Method
Gets a column of the matrix as a Vec4.
#### Parameters
- **i** (int) –
### GetDeterminant Method
Returns the determinant of the matrix.
### GetDeterminant3
Returns the determinant of the upper 3x3 matrix.
This method is useful when the matrix describes a linear transformation such as a rotation or scale because the other values in the 4x4 matrix are not important.
### GetHandedness
Returns the sign of the determinant of the upper 3x3 matrix, i.e. 1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a singular matrix.
### GetInverse
Returns the inverse of the matrix, or FLT_MAX * SetIdentity() if the matrix is singular.
(FLT_MAX is the largest value a float can have, as defined by the system.) The matrix is considered singular if the determinant is less than or equal to the optional parameter eps. If det is non-null, *det is set to the determinant.
**Parameters**
- **det** (float) –
- **eps** (float) –
### GetOrthonormalized
Returns an orthonormalized copy of the matrix.
**Parameters**
- **issueWarning** (bool) –
### GetRow
Gets a row of the matrix as a Vec4.
**Parameters**
- **i** (int) –
### GetRow3
Gets a row of the matrix as a Vec3.
**Parameters**
- **i** (int) –
<p>Gets a row of the matrix as a Vec3.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd">
<p><strong>i</strong> (<em>int</em>) –</p>
</dd>
</dl>
<p>Returns the transpose of the matrix.</p>
<p>Returns true, if the row vectors of the upper 3x3 matrix form an orthogonal basis.</p>
<p>Note they do not have to be unit length for this test to return true.</p>
<p>Returns true if the vectors in the upper 3x3 matrix form a left-handed coordinate system.</p>
<p>Returns true if the vectors in the upper 3x3 matrix form a right-handed coordinate system.</p>
<p>Makes the matrix orthonormal in place.</p>
<p>This is an iterative method that is much more stable than the previous cross/cross method. If the iterative method does not converge, a warning is issued.</p>
<p>Returns true if the iteration converged, false otherwise. Leaves any translation part of the matrix unchanged. If <em>issueWarning</em> is true, this method will issue a warning if the iteration does not converge, otherwise it will be silent.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd">
<p><strong>issueWarning</strong> (<em>bool</em>) –</p>
</dd>
</dl>
<p>Returns the matrix with any scaling or shearing removed, leaving only the rotation and translation.</p>
<p>If the matrix cannot be decomposed, returns the original matrix.</p>
<p>Set</p>
<p>Sets the matrix to the specified values.</p>
Sets the matrix from 16 independent `float` values, specified in row-major order.
For example, parameter *m10* specifies the value in row1 and column 0.
**Parameters**
- **m00** (*float*) –
- **m01** (*float*) –
- **m02** (*float*) –
- **m03** (*float*) –
- **m10** (*float*) –
- **m11** (*float*) –
- **m12** (*float*) –
- **m13** (*float*) –
- **m20** (*float*) –
- **m21** (*float*) –
- **m22** (*float*) –
- **m23** (*float*) –
- **m30** (*float*) –
- **m31** (*float*) –
- **m32** (*float*) –
- **m33** (*float*) –
Set(m) -> Matrix4f
Sets the matrix from a 4x4 array of `float` values, specified in row-major order.
**Parameters**
- **m** (*float*) –
SetColumn(i, v) -> None
### Sets a column of the matrix from a Vec4.
#### Parameters
- **i** (`int`) –
- **v** (`Vec4f`) –
### SetDiagonal(s) -> Matrix4f
Sets the matrix to `s` times the identity matrix.
#### Parameters
- **s** (`float`) –
---
SetDiagonal(arg1) -> Matrix4f
Sets the matrix to have diagonal (`v[0], v[1], v[2], v[3]`).
#### Parameters
- **arg1** (`Vec4f`) –
### SetIdentity() -> Matrix4f
Sets the matrix to the identity matrix.
### SetLookAt(eyePoint, centerPoint, upDirection) -> Matrix4f
Sets the matrix to specify a viewing matrix from parameters similar to those used by `gluLookAt(3G)`.
#### Parameters
- **eyePoint** (`Vec3f`) –
- **centerPoint** (`Vec3f`) –
- **upDirection** (`Vec3f`) –
---
SetLookAt(eyePoint, orientation) -> Matrix4f
Sets the matrix to specify a viewing matrix from a world-space `eyePoint` and a world-space rotation that rigidly rotates the orientation from its canonical frame, which is defined to be looking along the `-z` axis with the `+y` axis as the up direction.
- **eyePoint** (**Vec3f**) –
- **orientation** (**Rotation**) –
### SetRotate
SetRotate(rot) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **rot**, and clears the translation.
#### Parameters
- **rot** (**Quatf**) –
SetRotate(rot) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **rot**, and clears the translation.
#### Parameters
- **rot** (**Rotation**) –
SetRotate(mx) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **mx**, and clears the translation.
#### Parameters
- **mx** (**Matrix3f**) –
### SetRotateOnly
SetRotateOnly(rot) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **rot**, without clearing the translation.
#### Parameters
- **rot** (**Quatf**) –
SetRotateOnly(rot) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **rot**, without clearing the translation.
#### Parameters
- **rot** (**Rotation**) –
SetRotateOnly(mx) → **Matrix4f**
Sets the matrix to specify a rotation equivalent to **mx**, without clearing the translation.
#### Parameters
- **mx** (**Matrix3f**) –
### SetRow
SetRow(i, v) → **None**
Sets a row of the matrix from a Vec4.
#### Parameters
- **i**
- **v**
- **i** (`int`) –
- **v** (`Vec4f`) –
- **i** (`int`) –
- **v** (`Vec3f`) –
### SetRow3
```python
SetRow3(i, v) -> None
```
Sets a row of the matrix from a Vec3.
The fourth element of the row is ignored.
#### Parameters
- **i** (`int`) –
- **v** (`Vec3f`) –
### SetScale
```python
SetScale(scaleFactors) -> Matrix4f
```
Sets the matrix to specify a nonuniform scaling in x, y, and z by the factors in vector `scaleFactors`.
#### Parameters
- **scaleFactors** (`Vec3f`) –
```python
SetScale(scaleFactor) -> Matrix4f
```
Sets matrix to specify a uniform scaling by `scaleFactor`.
#### Parameters
- **scaleFactor** (`float`) –
### SetTransform
```python
SetTransform(rotate, translate) -> Matrix4f
```
Sets matrix to specify a rotation by `rotate` and a translation by `translate`.
#### Parameters
- **rotate** (`Rotation`) –
- **translate** (`Vec3f`) –
```python
SetTransform(rotmx, translate) -> Matrix4f
```
Sets matrix to specify a rotation by `rotmx` and a translation by `translate`.
#### Parameters
- **rotmx** (`Matrix3f`) –
- **translate** (`Vec3f`) –
### SetTranslate
```python
SetTranslate(trans)
```
- **Parameters**:
- **trans** (Vec3f) –
Sets matrix to specify a translation by the vector `trans`, and clears the rotation.
### SetTranslateOnly
```python
SetTranslateOnly(t)
```
- **Parameters**:
- **t** (Vec3f) –
Sets matrix to specify a translation by the vector `trans`, without clearing the rotation.
### SetZero
```python
SetZero()
```
Sets the matrix to zero.
### Transform
```python
Transform(vec)
```
- **Parameters**:
- **vec** (Vec3d) –
Transforms the row vector `vec` by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1.
### TransformAffine
```python
TransformAffine(vec)
```
- **Parameters**:
- **vec** (Vec3d) –
Transforms the row vector `vec` by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1 and ignores the fourth column of the matrix (i.e. assumes it is (0, 0, 0, 1)).
**vec** (**Vec3d**) –
TransformAffine(vec) -> Vec3f
Transforms the row vector **vec** by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component is 1 and ignores the fourth column of the matrix (i.e. assumes it is (0, 0, 0, 1)).
**Parameters**
- **vec** (**Vec3f**) –
**TransformDir**(vec) -> Vec3d
Transforms row vector **vec** by the matrix, returning the result.
This treats the vector as a direction vector, so the translation information in the matrix is ignored. That is, it treats the vector as a 4-component vector whose fourth component is 0.
**Parameters**
- **vec** (**Vec3d**) –
TransformDir(vec) -> Vec3f
Transforms row vector **vec** by the matrix, returning the result.
This treats the vector as a direction vector, so the translation information in the matrix is ignored. That is, it treats the vector as a 4-component vector whose fourth component is 0. This is an overloaded method; it differs from the other version in that it returns a different value type.
**Parameters**
- **vec** (**Vec3f**) –
**dimension** = (4, 4)
**class** pxr.Gf.**MultiInterval**
**Methods:**
- **Add**(i)
- Add the given interval to the multi-interval.
- **ArithmeticAdd**(i)
- Uses the given interval to extend the multi-interval in the interval arithmetic sense.
- **Clear**()
- Clear the multi-interval.
- **Contains**
- Returns true if x is inside the multi-interval.
- **GetBounds**()
- Returns an interval bounding the entire multi-interval.
- **GetComplement**()
- Returns an interval that is the complement of the multi-interval.
### Methods
- **GetComplement()**
- Return the complement of this set.
- **GetFullInterval()**
- `classmethod` GetFullInterval() -> MultiInterval
- **GetSize()**
- Returns the number of intervals in the set.
- **Intersect(i)**
- param i
- **IsEmpty()**
- Returns true if the multi-interval is empty.
- **Remove(i)**
- Remove the given interval from this multi-interval.
### Attributes
- **bounds**
- **isEmpty**
- **size**
### Methods
- **Add(i)**
- Add the given interval to the multi-interval.
- Parameters:
- **i** (Interval) –
- Add(s) -> None
- Add the given multi-interval to the multi-interval.
- Sets this object to the union of the two sets.
- Parameters:
- **s** (MultiInterval) –
- **ArithmeticAdd(i)**
- Uses the given interval to extend the multi-interval in the interval arithmetic sense.
- Parameters:
- **i** (Interval) –
<strong>i</strong> (**Interval**) –
### Clear
```python
Clear() -> None
```
Clear the multi-interval.
### Contains
```python
Contains() -> bool
```
Returns true if x is inside the multi-interval.
Returns true if x is inside the multi-interval.
Returns true if x is inside the multi-interval.
### GetBounds
```python
GetBounds() -> Interval
```
Returns an interval bounding the entire multi-interval.
Returns an empty interval if the multi-interval is empty.
### GetComplement
```python
GetComplement() -> MultiInterval
```
Return the complement of this set.
### GetFullInterval
```python
@classmethod
GetFullInterval() -> MultiInterval
```
Returns the full interval (-inf, inf).
### GetSize
```python
GetSize() -> int
```
Returns the number of intervals in the set.
### Intersect
```python
Intersect(i: Interval) -> None
```
Parameters:
- **i** (**Interval**) –
```python
Intersect(s: MultiInterval) -> None
```
Parameters:
- **s** (**MultiInterval**) –
### IsEmpty
```python
IsEmpty() -> bool
```
```
### pxr.Gf.MultiInterval.IsEmpty
- **Description:** Returns true if the multi-interval is empty.
### pxr.Gf.MultiInterval.Remove
- **Function:** Remove(i) -> None
- **Description:** Remove the given interval from this multi-interval.
- **Parameters:**
- **i** (Interval) –
- **Description:** Remove(s) -> None
- **Description:** Remove the given multi-interval from this multi-interval.
- **Parameters:**
- **s** (MultiInterval) –
### pxr.Gf.MultiInterval.bounds
- **Property:** bounds
### pxr.Gf.MultiInterval.isEmpty
- **Property:** isEmpty
### pxr.Gf.MultiInterval.size
- **Property:** size
### pxr.Gf.Plane
- **Methods:**
- **GetDistance(p):** Returns the distance of point from the plane.
- **GetDistanceFromOrigin():** Returns the distance of the plane from the origin.
- **GetEquation():** Give the coefficients of the equation of the plane.
- **GetNormal():** Returns the unit-length normal vector of the plane.
- **IntersectsPositiveHalfSpace(box):** Returns true if the given aligned bounding box is at least partially on the positive side (the one the normal points into) of the plane.
| Method | Description |
| --- | --- |
| `GetDistance(p)` | Returns the distance of point `p` from the plane. This distance will be positive if the point is on the side of the plane containing the normal. |
| `GetDistanceFromOrigin()` | Returns the distance of the plane from the origin. |
| `GetEquation()` | Give the coefficients of the equation of the plane. Suitable to OpenGL calls to set the clipping plane. |
| `GetNormal()` | Returns the unit-length normal vector of the plane. |
| `IntersectsPositiveHalfSpace()` | |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `distanceFromOrigin` | |
| `normal` | |
### IntersectsPositiveHalfSpace
Returns `true` if the given aligned bounding box is at least partially on the positive side (the one the normal points into) of the plane.
**Parameters**
- **box** (`Range3d`) –
---
IntersectsPositiveHalfSpace(pt) -> bool
Returns true if the given point is on the plane or within its positive half space.
**Parameters**
- **pt** (`Vec3d`) –
### Project
Return the projection of `p` onto the plane.
**Parameters**
- **p** (`Vec3d`) –
### Reorient
Flip the plane normal (if necessary) so that `p` is in the positive halfspace.
**Parameters**
- **p** (`Vec3d`) –
### Set
Sets this to the plane perpendicular to `normal` and at `distance` units from the origin. The passed-in normal is normalized to unit length first.
**Parameters**
- **normal** (`Vec3d`) –
- **distanceToOrigin** (`float`) –
---
Set(normal, point) -> None
This constructor sets this to the plane perpendicular to `normal` and that passes through `point`.
The passed-in normal is normalized to unit length first.
Parameters
----------
- **normal** (`Vec3d`) –
- **point** (`Vec3d`) –
Set(p0, p1, p2) -> None
-----------------------
This constructor sets this to the plane that contains the three given points.
The normal is constructed from the cross product of (p1 - p0) and (p2 - p0). Results are undefined if the points are collinear.
Parameters
----------
- **p0** (`Vec3d`) –
- **p1** (`Vec3d`) –
- **p2** (`Vec3d`) –
Set(eqn) -> None
----------------
This method sets this to the plane given by the equation eqn[0] * x + eqn[1] * y + eqn[2] * z + eqn[3] = 0.
Parameters
----------
- **eqn** (`Vec4d`) –
Transform(matrix) -> Plane
--------------------------
Transforms the plane by the given matrix.
Parameters
----------
- **matrix** (`Matrix4d`) –
property distanceFromOrigin
---------------------------
property normal
---------------
class pxr.Gf.Quatd
------------------
Methods:
- **GetConjugate** ()
| Method | Description |
| --- | --- |
| `GetConjugate()` | Return this quaternion's conjugate, which is the quaternion with the same real coefficient and negated imaginary coefficients. |
| `GetIdentity` | classmethod GetIdentity() -> Quatd |
| `GetImaginary()` | Return the imaginary coefficient. |
| `GetInverse()` | Return this quaternion's inverse, or reciprocal. |
| `GetLength()` | Return geometric length of this quaternion. |
| `GetNormalized(eps)` | If length of this quaternion is smaller than `eps`, return the identity quaternion. |
| `GetReal()` | Return the real coefficient. |
| `GetZero` | classmethod GetZero() -> Quatd |
| `Normalize(eps)` | Normalizes this quaternion in place to unit length, returning the length before normalization. |
| `SetImaginary(imaginary)` | Set the imaginary coefficients. |
| `SetReal(real)` | Set the real coefficient. |
| `Transform(point)` | Transform the GfVec3d point. |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `imaginary` | |
| `real` | |
### GetConjugate()
Return this quaternion’s conjugate, which is the quaternion with the same real coefficient and negated imaginary coefficients.
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
GetIdentity
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<a class="headerlink" href="#pxr.Gf.Quatd.GetIdentity" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
<strong>
classmethod
</strong>
GetIdentity() -> Quatd
</p>
<p>
Return the identity quaternion, with real coefficient 1 and an imaginary coefficients all zero.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetImaginary">
<span class="sig-name descname">
<span class="pre">
GetImaginary
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec3d" title="pxr.Gf.Vec3d">
<span class="pre">
Vec3d
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatd.GetImaginary" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return the imaginary coefficient.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetInverse">
<span class="sig-name descname">
<span class="pre">
GetInverse
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quatd" title="pxr.Gf.Quatd">
<span class="pre">
Quatd
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatd.GetInverse" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return this quaternion’s inverse, or reciprocal.
</p>
<p>
This is the quaternion’s conjugate divided by it’s squared length.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatd.GetLength" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return geometric length of this quaternion.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
eps
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quatd" title="pxr.Gf.Quatd">
<span class="pre">
Quatd
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatd.GetNormalized" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
</span>
</code>
, return the identity quaternion.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
float
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetReal">
<span class="sig-name descname">
<span class="pre">
GetReal
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatd.GetReal" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return the real coefficient.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.GetZero">
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
GetZero
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<a class="headerlink" href="#pxr.Gf.Quatd.GetZero" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
<strong>
classmethod
</strong>
GetZero() -> Quatd
</p>
<p>
Return the zero quaternion, with real coefficient 0 and an imaginary coefficients all zero.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatd.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
eps
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatd.Normalize" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Normalizes this quaternion in place to unit length, returning the length before normalization.
</p>
<p>
If the length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
</span>
</code>
, this sets the quaternion to identity.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
float
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
### eps (float) –
### SetImaginary
Set the imaginary coefficients.
**Parameters**
- **imaginary** (Vec3d) –
SetImaginary(i, j, k) -> None
Set the imaginary coefficients.
**Parameters**
- **i** (float) –
- **j** (float) –
- **k** (float) –
### SetReal
Set the real coefficient.
**Parameters**
- **real** (float) –
### Transform
Transform the GfVec3d point.
If the quaternion is normalized, the transformation is a rotation. Given a GfQuatd q, q.Transform(point) is equivalent to: (q * GfQuatd(0, point) * q.GetInverse()).GetImaginary() but is more efficient.
**Parameters**
- **point** (Vec3d) –
### property imaginary
### property real
### class pxr.Gf.Quaternion
Quaternion class
**Methods:**
- **GetIdentity**
| Method | Description |
| --- | --- |
| `classmethod GetIdentity()` | Returns the identity quaternion, which has a real part of 1 and an imaginary part of (0,0,0). |
| `GetImaginary()` | Returns the imaginary part of the quaternion. |
| `GetInverse()` | Returns the inverse of this quaternion. |
| `GetLength()` | Returns geometric length of this quaternion. |
| `GetNormalized(eps)` | Returns a normalized (unit-length) version of this quaternion. |
| `GetReal()` | Returns the real part of the quaternion. |
| `classmethod GetZero()` | Returns the zero quaternion. |
| `Normalize(eps)` | Normalizes this quaternion in place to unit length, returning the length before normalization. |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `imaginary` | None |
| `real` | None |
**Methods:**
**GetIdentity**
```python
classmethod GetIdentity() -> Quaternion
```
Returns the identity quaternion, which has a real part of 1 and an imaginary part of (0,0,0).
**GetImaginary**
```python
GetImaginary() -> Vec3d
```
Returns the imaginary part of the quaternion.
**GetInverse**
```python
GetInverse() -> Quaternion
```
Returns the inverse of this quaternion.
**GetLength**
```python
GetLength()
```
Returns geometric length of this quaternion.
### pxr.Gf.Quaternion.GetLength
- **Returns**: geometric length of this quaternion.
### pxr.Gf.Quaternion.GetNormalized
- **Returns**: a normalized (unit-length) version of this quaternion.
- **Parameters**:
- **eps** (float) –
### pxr.Gf.Quaternion.GetReal
- **Returns**: the real part of the quaternion.
### pxr.Gf.Quaternion.GetZero
- **Returns**: the zero quaternion, which has a real part of 0 and an imaginary part of (0,0,0).
### pxr.Gf.Quaternion.Normalize
- **Returns**: the length before normalization.
- **Parameters**:
- **eps** (float) –
### pxr.Gf.Quaternion.imaginary
- **Type**: type
### pxr.Gf.Quaternion.real
- **Type**: type
| Method | Description |
|--------|-------------|
| `GetConjugate()` | Return this quaternion's conjugate, which is the quaternion with the same real coefficient and negated imaginary coefficients. |
| `GetIdentity` | `classmethod GetIdentity() -> Quatf` |
| `GetImaginary()` | Return the imaginary coefficient. |
| `GetInverse()` | Return this quaternion's inverse, or reciprocal. |
| `GetLength()` | Return geometric length of this quaternion. |
| `GetNormalized(eps)` | If the length of this quaternion is smaller than `eps`, return the identity quaternion. |
| `GetReal()` | Return the real coefficient. |
| `GetZero` | `classmethod GetZero() -> Quatf` |
| `Normalize(eps)` | Normalizes this quaternion in place to unit length, returning the length before normalization. |
| `SetImaginary(imaginary)` | Set the imaginary coefficients. |
| `SetReal(real)` | Set the real coefficient. |
| `Transform(point)` | Transform the GfVec3f point. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `imaginary` | |
| `real` | |
<p>
Return this quaternion’s conjugate, which is the quaternion with the
same real coefficient and negated imaginary coefficients.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetIdentity">
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
GetIdentity
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<a class="headerlink" href="#pxr.Gf.Quatf.GetIdentity" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
<strong>
classmethod
</strong>
GetIdentity() -> Quatf
</p>
<p>
Return the identity quaternion, with real coefficient 1 and an
imaginary coefficients all zero.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetImaginary">
<span class="sig-name descname">
<span class="pre">
GetImaginary
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec3f" title="pxr.Gf.Vec3f">
<span class="pre">
Vec3f
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatf.GetImaginary" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return the imaginary coefficient.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetInverse">
<span class="sig-name descname">
<span class="pre">
GetInverse
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quatf" title="pxr.Gf.Quatf">
<span class="pre">
Quatf
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatf.GetInverse" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return this quaternion’s inverse, or reciprocal.
</p>
<p>
This is the quaternion’s conjugate divided by it’s squared length.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatf.GetLength" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return geometric length of this quaternion.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
eps
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quatf" title="pxr.Gf.Quatf">
<span class="pre">
Quatf
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatf.GetNormalized" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
</span>
</code>
, return the
identity quaternion.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
float
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetReal">
<span class="sig-name descname">
<span class="pre">
GetReal
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatf.GetReal" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return the real coefficient.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.GetZero">
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
GetZero
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<a class="headerlink" href="#pxr.Gf.Quatf.GetZero" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
<strong>
classmethod
</strong>
GetZero() -> Quatf
</p>
<p>
Return the zero quaternion, with real coefficient 0 and an imaginary
coefficients all zero.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
eps
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quatf.Normalize" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Normalizes this quaternion in place to unit length, returning the
length before normalization.
</p>
<p>
If the length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
</span>
</code>
</p>
</dd>
</dl>
<p>
<code>
<span>
</span>
</code>
, this sets
the quaternion to identity.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
float
</em>
) –
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.SetImaginary">
<span class="sig-name descname">
<span class="pre">
SetImaginary
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
imaginary
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
None
</span>
</span>
</span>
</dt>
<dd>
<p>
Set the imaginary coefficients.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
imaginary
</strong>
(
<em>
Vec3f
</em>
) –
</p>
</dd>
</dl>
<hr />
<p>
SetImaginary(i, j, k) -> None
</p>
<p>
Set the imaginary coefficients.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
i
</strong>
(
<em>
float
</em>
) –
</p>
</li>
<li>
<p>
<strong>
j
</strong>
(
<em>
float
</em>
) –
</p>
</li>
<li>
<p>
<strong>
k
</strong>
(
<em>
float
</em>
) –
</p>
</li>
</ul>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.SetReal">
<span class="sig-name descname">
<span class="pre">
SetReal
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
real
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
None
</span>
</span>
</span>
</dt>
<dd>
<p>
Set the real coefficient.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
real
</strong>
(
<em>
float
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.Transform">
<span class="sig-name descname">
<span class="pre">
Transform
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
point
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
Vec3f
</span>
</span>
</span>
</dt>
<dd>
<p>
Transform the GfVec3f point.
</p>
<p>
If the quaternion is normalized, the transformation is a rotation.
Given a GfQuatf q, q.Transform(point) is equivalent to: (q *
GfQuatf(0, point) * q.GetInverse()).GetImaginary()
</p>
<p>
but is more efficient.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
point
</strong>
(
<em>
Vec3f
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.imaginary">
<em class="property">
<span class="pre">
property
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
imaginary
</span>
</span>
</dt>
<dd>
</dd>
</dl>
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Quatf.real">
<em class="property">
<span class="pre">
property
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
real
</span>
</span>
</dt>
<dd>
</dd>
</dl>
</dd>
</dl>
<dl class="py class">
<dt class="sig sig-object py" id="pxr.Gf.Quath">
<em class="property">
<span class="pre">
class
</span>
<span class="w">
</span>
</em>
<span class="sig-prename descclassname">
<span class="pre">
pxr.Gf.
</span>
</span>
<span class="sig-name descname">
<span class="pre">
Quath
</span>
</span>
</dt>
<dd>
<p>
<strong>
Methods:
</strong>
</p>
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>
<tbody>
<tr class="row-odd">
<td>
<p>
</p>
</td>
</tr>
</tbody>
</table>
</dd>
</dl>
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetConjugate
</span>
</code>
</a>
()
</p>
<p>
Return this quaternion's conjugate, which is the quaternion with the same real coefficient and negated imaginary coefficients.
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetIdentity" title="pxr.Gf.Quath.GetIdentity">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetIdentity
</span>
</code>
</a>
</p>
<p>
<strong>
classmethod
</strong>
GetIdentity() -> Quath
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetImaginary" title="pxr.Gf.Quath.GetImaginary">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetImaginary
</span>
</code>
</a>
()
</p>
<p>
Return the imaginary coefficient.
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetInverse" title="pxr.Gf.Quath.GetInverse">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetInverse
</span>
</code>
</a>
()
</p>
<p>
Return this quaternion's inverse, or reciprocal.
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetLength" title="pxr.Gf.Quath.GetLength">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetLength
</span>
</code>
</a>
()
</p>
<p>
Return geometric length of this quaternion.
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetNormalized" title="pxr.Gf.Quath.GetNormalized">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetNormalized
</span>
</code>
</a>
(eps)
</p>
<p>
length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
</span>
</code>
, return the identity quaternion.
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetReal" title="pxr.Gf.Quath.GetReal">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetReal
</span>
</code>
</a>
()
</p>
<p>
Return the real coefficient.
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.GetZero" title="pxr.Gf.Quath.GetZero">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetZero
</span>
</code>
</a>
</p>
<p>
<strong>
classmethod
</strong>
GetZero() -> Quath
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.Normalize" title="pxr.Gf.Quath.Normalize">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
Normalize
</span>
</code>
</a>
(eps)
</p>
<p>
Normalizes this quaternion in place to unit length, returning the length before normalization.
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.SetImaginary" title="pxr.Gf.Quath.SetImaginary">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
SetImaginary
</span>
</code>
</a>
(imaginary)
</p>
<p>
Set the imaginary coefficients.
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.SetReal" title="pxr.Gf.Quath.SetReal">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
SetReal
</span>
</code>
</a>
(real)
</p>
<p>
Set the real coefficient.
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.Transform" title="pxr.Gf.Quath.Transform">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
Transform
</span>
</code>
</a>
(point)
</p>
<p>
Transform the GfVec3h point.
</p>
<p>
<strong>
Attributes:
</strong>
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.imaginary" title="pxr.Gf.Quath.imaginary">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
imaginary
</span>
</code>
</a>
</p>
<p>
</p>
<p>
<a class="reference internal" href="#pxr.Gf.Quath.real" title="pxr.Gf.Quath.real">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
real
</span>
</code>
</a>
</p>
<p>
</p>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetConjugate">
<span class="sig-name descname">
<span class="pre">
GetConjugate
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Quath" title="pxr.Gf.Quath">
<span class="pre">
Quath
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quath.GetConjugate" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return this quaternion’s conjugate, which is the quaternion with the
same real coefficient and negated imaginary coefficients.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetIdentity">
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
GetIdentity
</span>
</span>
<span class="sig-paren">
()</span>
<a class="headerlink" href="#pxr.Gf.Quath.GetIdentity" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
<strong>
classmethod
</strong>
GetIdentity() -> Quath
</p>
<p>
Return the identity quaternion, with real coefficient 1 and an
imaginary coefficients all zero.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetImaginary">
<span class="sig-name descname">
<span class="pre">
GetImaginary
</span>
</span>
<span class="sig-paren">
()</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
Vec3h
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quath.GetImaginary" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return the imaginary coefficient.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetInverse">
<span class="sig-name descname">
<span class="pre">
GetInverse
</span>
</span>
<span class="sig-paren">
()</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
Quath
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quath.GetInverse" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return this quaternion’s inverse, or reciprocal.
</p>
<p>
This is the quaternion’s conjugate divided by it’s squared length.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
</span>
</span>
<span class="sig-paren">
()</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
GfHalf
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quath.GetLength" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return geometric length of this quaternion.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
</span>
</span>
<span class="sig-paren">
(eps)</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
Quath
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quath.GetNormalized" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
</span>
</code>
, return the
identity quaternion.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
GfHalf
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetReal">
<span class="sig-name descname">
<span class="pre">
GetReal
</span>
</span>
<span class="sig-paren">
()</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
GfHalf
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quath.GetReal" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Return the real coefficient.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.GetZero">
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
GetZero
</span>
</span>
<span class="sig-paren">
()</span>
<a class="headerlink" href="#pxr.Gf.Quath.GetZero" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
<strong>
classmethod
</strong>
GetZero() -> Quath
</p>
<p>
Return the zero quaternion, with real coefficient 0 and an imaginary
coefficients all zero.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
</span>
</span>
<span class="sig-paren">
(eps)</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
GfHalf
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Quath.Normalize" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Normalizes this quaternion in place to unit length, returning the
length before normalization.
</p>
<p>
If the length of this quaternion is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
</span>
</code>
</p>
</dd>
</dl>
<p>
<code>
<span>
SetIdentity
</span>
</code>
, this sets
the quaternion to identity.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
GfHalf
</em>
) –
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.SetImaginary">
<span class="sig-name descname">
<span class="pre">
SetImaginary
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
imaginary
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
None
</span>
</span>
</dt>
<dd>
<p>
Set the imaginary coefficients.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
imaginary
</strong>
(
<em>
Vec3h
</em>
) –
</p>
</dd>
</dl>
<hr />
<p>
SetImaginary(i, j, k) -> None
</p>
<p>
Set the imaginary coefficients.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
i
</strong>
(
<em>
GfHalf
</em>
) –
</p>
</li>
<li>
<p>
<strong>
j
</strong>
(
<em>
GfHalf
</em>
) –
</p>
</li>
<li>
<p>
<strong>
k
</strong>
(
<em>
GfHalf
</em>
) –
</p>
</li>
</ul>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.SetReal">
<span class="sig-name descname">
<span class="pre">
SetReal
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
real
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
None
</span>
</span>
</dt>
<dd>
<p>
Set the real coefficient.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
real
</strong>
(
<em>
GfHalf
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Quath.Transform">
<span class="sig-name descname">
<span class="pre">
Transform
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
point
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
Vec3h
</span>
</span>
</dt>
<dd>
<p>
Transform the GfVec3h point.
</p>
<p>
If the quaternion is normalized, the transformation is a rotation.
Given a GfQuath q, q.Transform(point) is equivalent to: (q *
GfQuath(0, point) * q.GetInverse()).GetImaginary()
</p>
<p>
but is more efficient.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
point
</strong>
(
<em>
Vec3h
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Quath.imaginary">
<em class="property">
<span class="pre">
property
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
imaginary
</span>
</span>
</dt>
<dd>
</dd>
</dl>
<dl class="py property">
<dt class="sig sig-object py" id="pxr.Gf.Quath.real">
<em class="property">
<span class="pre">
property
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
real
</span>
</span>
</dt>
<dd>
</dd>
</dl>
</dd>
</dl>
<dl class="py class">
<dt class="sig sig-object py" id="pxr.Gf.Range1d">
<em class="property">
<span class="pre">
class
</span>
<span class="w">
</span>
</em>
<span class="sig-prename descclassname">
<span class="pre">
pxr.Gf.
</span>
</span>
<span class="sig-name descname">
<span class="pre">
Range1d
</span>
</span>
</dt>
<dd>
<p>
<strong>
Methods:
</strong>
</p>
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>
<tbody>
<tr class="row-odd">
<td>
<p>
</p>
</td>
</tr>
</tbody>
</table>
</dd>
</dl>
| Method | Description |
| ------ | ----------- |
| Contains(point) | Returns true if the point is located inside the range. |
| GetDistanceSquared(p) | Compute the squared distance from a point to the range. |
| GetIntersection(a, b) -> Range1d | classmethod GetIntersection(a, b) -> Range1d |
| GetMax() | Returns the maximum value of the range. |
| GetMidpoint() | Returns the midpoint of the range, that is, 0.5*(min+max). |
| GetMin() | Returns the minimum value of the range. |
| GetSize() | Returns the size of the range. |
| GetUnion(a, b) -> Range1d | classmethod GetUnion(a, b) -> Range1d |
| IntersectWith(b) | Modifies this range to hold its intersection with b and returns the result. |
| IsEmpty() | Returns whether the range is empty (max<min). |
| SetEmpty() | Sets the range to an empty interval. |
| SetMax(max) | Sets the maximum value of the range. |
| SetMin(min) | Sets the minimum value of the range. |
| UnionWith(b) | Extend this to include b. |
**Attributes:**
- dimension
| max |
| --- |
| min |
### Contains
`Contains(point)` -> bool
Returns true if the `point` is located inside the range.
As with all operations of this type, the range is assumed to include its extrema.
**Parameters**
- **point** (float) –
---
Contains(range) -> bool
Returns true if the `range` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include their extrema.
**Parameters**
- **range** (Range1d) –
### GetDistanceSquared
`GetDistanceSquared(p)` -> float
Compute the squared distance from a point to the range.
**Parameters**
- **p** (float) –
### GetIntersection
`classmethod GetIntersection(a, b)` -> Range1d
Returns a `GfRange1d` that describes the intersection of `a` and `b`.
**Parameters**
- **a** (Range1d) –
- **b** (Range1d) –
### GetMax
`GetMax()` -> float
Returns the maximum value of the range.
### GetMidpoint
`GetMidpoint()` -> float
### GetMidpoint
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin
Returns the minimum value of the range.
### GetSize
Returns the size of the range.
### GetUnion
**classmethod** GetUnion(a, b) -> Range1d
Returns the smallest `GfRange1d` which contains both `a` and `b`.
Parameters:
- **a** (`Range1d`) –
- **b** (`Range1d`) –
### IntersectWith
Modifies this range to hold its intersection with `b` and returns the result.
Parameters:
- **b** (`Range1d`) –
### IsEmpty
Returns whether the range is empty (max<min).
### SetEmpty
Sets the range to an empty interval.
### SetMax
→ None
Sets the maximum value of the range.
Parameters
----------
max (float) –
SetMin(min)
→ None
Sets the minimum value of the range.
Parameters
----------
min (float) –
UnionWith(b)
→ Range1d
Extend `this` to include `b`.
Parameters
----------
b (Range1d) –
UnionWith(b) -> Range1d
Extend `this` to include `b`.
Parameters
----------
b (float) –
dimension = 1
property max
property min
class pxr.Gf.Range1f
Methods:
---------
Contains(point)
Returns true if the `point` is located inside the range.
| Method | Description |
|--------|-------------|
| `GetDistanceSquared()` | Compute the squared distance from a point to the range. |
| `GetIntersection(a, b) -> Range1f` | classmethod GetIntersection(a, b) -> Range1f |
| `GetMax()` | Returns the maximum value of the range. |
| `GetMidpoint()` | Returns the midpoint of the range, that is, 0.5*(min+max). |
| `GetMin()` | Returns the minimum value of the range. |
| `GetSize()` | Returns the size of the range. |
| `GetUnion(a, b) -> Range1f` | classmethod GetUnion(a, b) -> Range1f |
| `IntersectWith(b)` | Modifies this range to hold its intersection with b and returns the result. |
| `IsEmpty()` | Returns whether the range is empty (max<min). |
| `SetEmpty()` | Sets the range to an empty interval. |
| `SetMax(max)` | Sets the maximum value of the range. |
| `SetMin(min)` | Sets the minimum value of the range. |
| `UnionWith(b)` | Extend this to include b. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
| `max` | |
| `min` | |
```code
min
```
```code
Contains
(
point
)
→
bool
```
Returns true if the `point` is located inside the range.
As with all operations of this type, the range is assumed to include its extrema.
Parameters
----------
point (float) –
```code
Contains(range) -> bool
```
Returns true if the `range` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include their extrema.
Parameters
----------
range (Range1f) –
```code
GetDistanceSquared
(
p
)
→
float
```
Compute the squared distance from a point to the range.
Parameters
----------
p (float) –
```code
static
GetIntersection
(
)
```
```code
classmethod
GetIntersection(a, b) -> Range1f
```
Returns a `GfRange1f` that describes the intersection of `a` and `b`.
Parameters
----------
a (Range1f) –
b (Range1f) –
```code
GetMax
(
)
→
float
```
Returns the maximum value of the range.
```code
GetMidpoint
(
)
→
float
```
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
```code
GetMin
```
### GetMin
Returns the minimum value of the range.
### GetSize
Returns the size of the range.
### GetUnion
**classmethod** GetUnion(a, b) -> Range1f
Returns the smallest `GfRange1f` which contains both `a` and `b`.
Parameters:
- **a** (`Range1f`) –
- **b** (`Range1f`) –
### IntersectWith
Modifies this range to hold its intersection with `b` and returns the result.
Parameters:
- **b** (`Range1f`) –
### IsEmpty
Returns whether the range is empty (max<min).
### SetEmpty
Sets the range to an empty interval.
### SetMax
Sets the maximum value of the range.
Parameters:
- **max** –
**max** (**float**) –
**SetMin**(min) → None
Sets the minimum value of the range.
**Parameters**
- **min** (**float**) –
**UnionWith**(b) → Range1f
Extend `this` to include `b`.
**Parameters**
- **b** (**Range1f**) –
UnionWith(b) -> Range1f
Extend `this` to include `b`.
**Parameters**
- **b** (**float**) –
**dimension** = 1
**property max**
**property min**
**class pxr.Gf.Range2d**
**Methods:**
- **Contains**(point)
Returns true if the `point` is located inside the range.
- **GetCorner**(i)
Returns the ith corner of the range, in the following order: SW, SE, NW, NE.
| Method | Description |
|--------|-------------|
| `GetDistanceSquared()` | Compute the squared distance from a point to the range. |
| `GetIntersection(a, b) -> Range2d` | classmethod GetIntersection(a, b) -> Range2d |
| `GetMax()` | Returns the maximum value of the range. |
| `GetMidpoint()` | Returns the midpoint of the range, that is, 0.5*(min+max). |
| `GetMin()` | Returns the minimum value of the range. |
| `GetQuadrant(i)` | Returns the ith quadrant of the range, in the following order: SW, SE, NW, NE. |
| `GetSize()` | Returns the size of the range. |
| `GetUnion(a, b) -> Range2d` | classmethod GetUnion(a, b) -> Range2d |
| `IntersectWith(b)` | Modifies this range to hold its intersection with b and returns the result. |
| `IsEmpty()` | Returns whether the range is empty (max<min). |
| `SetEmpty()` | Sets the range to an empty interval. |
| `SetMax(max)` | Sets the maximum value of the range. |
| `SetMin(min)` | Sets the minimum value of the range. |
| `UnionWith(b)` | Extend this to include b. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
| `max` | |
### max
### min
### unitSquare
### Contains
```
Returns true if the `point` is located inside the range.
As with all operations of this type, the range is assumed to include its extrema.
**Parameters**
- **point** (`Vec2d`) –
Contains(range) -> bool
Returns true if the `range` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include their extrema.
**Parameters**
- **range** (`Range2d`) –
### GetCorner
```
Returns the ith corner of the range, in the following order: SW, SE, NW, NE.
**Parameters**
- **i** (`int`) –
```
### GetDistanceSquared
```
Compute the squared distance from a point to the range.
**Parameters**
- **p** (`Vec2d`) –
```
### GetIntersection
```
classmethod GetIntersection(a, b) -> Range2d
Returns a `GfRange2d` that describes the intersection of `a` and `b`.
**Parameters**
- **a** (`Range2d`) –
- **b** (`Range2d`) –
```
**Range2d**
- **b** (Range2d) –
### GetMax()
Returns the maximum value of the range.
### GetMidpoint()
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin()
Returns the minimum value of the range.
### GetQuadrant(i)
Returns the ith quadrant of the range, in the following order: SW, SE, NW, NE.
Parameters:
- **i** (int) –
### GetSize()
Returns the size of the range.
### GetUnion(a, b)
Returns the smallest GfRange2d which contains both a and b.
Parameters:
- **a** (Range2d) –
- **b** (Range2d) –
### pxr.Gf.Range2d.IntersectWith
- **Description**: Modifies this range to hold its intersection with `b` and returns the result.
- **Parameters**:
- **b** (Range2d) –
### pxr.Gf.Range2d.IsEmpty
- **Description**: Returns whether the range is empty (max<min).
### pxr.Gf.Range2d.SetEmpty
- **Description**: Sets the range to an empty interval.
### pxr.Gf.Range2d.SetMax
- **Description**: Sets the maximum value of the range.
- **Parameters**:
- **max** (Vec2d) –
### pxr.Gf.Range2d.SetMin
- **Description**: Sets the minimum value of the range.
- **Parameters**:
- **min** (Vec2d) –
### pxr.Gf.Range2d.UnionWith
- **Description**: Extend `this` to include `b`.
- **Parameters**:
- **b** (Range2d) –
- **Example**: UnionWith(b) -> Range2d
### Parameters
**b** (Vec2d) –
### Attributes
- **dimension** = 2
- **max** property
- **min** property
- **unitSquare** = Gf.Range2d(Gf.Vec2d(0.0, 0.0), Gf.Vec2d(1.0, 1.0))
### Class: pxr.Gf.Range2f
**Methods:**
- **Contains**(point) - Returns true if the point is located inside the range.
- **GetCorner**(i) - Returns the ith corner of the range, in the following order: SW, SE, NW, NE.
- **GetDistanceSquared**(p) - Compute the squared distance from a point to the range.
- **GetIntersection**(a, b) -> Range2f - **classmethod**
- **GetMax**() - Returns the maximum value of the range.
- **GetMidpoint**() - Returns the midpoint of the range, that is, 0.5*(min+max).
- **GetMin**() - Returns the minimum value of the range.
- **GetQuadrant**(i) - Returns the ith quadrant of the range.
Returns the ith quadrant of the range, in the following order: SW, SE, NW, NE.
GetSize()
Returns the size of the range.
GetUnion
classmethod GetUnion(a, b) -> Range2f
IntersectWith(b)
Modifies this range to hold its intersection with b and returns the result.
IsEmpty()
Returns whether the range is empty (max<min).
SetEmpty()
Sets the range to an empty interval.
SetMax(max)
Sets the maximum value of the range.
SetMin(min)
Sets the minimum value of the range.
UnionWith(b)
Extend this to include b.
Attributes:
dimension
max
min
unitSquare
Contains(point) -> bool
Returns true if the point is located inside the range.
As with all operations of this type, the range is assumed to include its extrema.
Parameters:
point (Vec2f)
### Contains(range) -> bool
Returns true if the `range` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include their extrema.
#### Parameters
- **range** (Range2f) –
### GetCorner(i) -> Vec2f
Returns the ith corner of the range, in the following order: SW, SE, NW, NE.
#### Parameters
- **i** (int) –
### GetDistanceSquared(p) -> float
Compute the squared distance from a point to the range.
#### Parameters
- **p** (Vec2f) –
### GetIntersection(a, b) -> Range2f
Returns a `GfRange2f` that describes the intersection of `a` and `b`.
#### Parameters
- **a** (Range2f) –
- **b** (Range2f) –
### GetMax() -> Vec2f
Returns the maximum value of the range.
### GetMidpoint() -> Vec2f
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin() -> Vec2f
Returns the minimum value of the range.
(→ Vec2f)
Returns the minimum value of the range.
(i→ Range2f)
Returns the ith quadrant of the range, in the following order: SW, SE, NW, NE.
Parameters
----------
i (int) –
()→ Vec2f
Returns the size of the range.
classmethod GetUnion(a, b) -> Range2f
Returns the smallest GfRange2f which contains both a and b.
Parameters
----------
a (Range2f) –
b (Range2f) –
IntersectWith(b) -> Range2f
Modifies this range to hold its intersection with b and returns the result.
Parameters
----------
b (Range2f) –
IsEmpty() -> bool
Returns whether the range is empty (max<min).
SetEmpty() -> None
### SetEmpty
Sets the range to an empty interval.
### SetMax
Sets the maximum value of the range.
- **Parameters**
- **max** (Vec2f) –
### SetMin
Sets the minimum value of the range.
- **Parameters**
- **min** (Vec2f) –
### UnionWith
Extend `this` to include `b`.
- **Parameters**
- **b** (Range2f) –
UnionWith(b) -> Range2f
Extend `this` to include `b`.
- **Parameters**
- **b** (Vec2f) –
### dimension
= 2
### max
property max
### min
property min
### unitSquare
= Gf.Range2f(Gf.Vec2f(0.0,
### pxr.Gf.Range3d
**Methods:**
- **Contains**(point)
- Returns true if the `point` is located inside the range.
- **GetCorner**(i)
- Returns the ith corner of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
- **GetDistanceSquared**(p)
- Compute the squared distance from a point to the range.
- **GetIntersection**(a, b) -> Range3d
- **classmethod** GetIntersection(a, b) -> Range3d
- **GetMax**()
- Returns the maximum value of the range.
- **GetMidpoint**()
- Returns the midpoint of the range, that is, 0.5*(min+max).
- **GetMin**()
- Returns the minimum value of the range.
- **GetOctant**(i)
- Returns the ith octant of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
- **GetSize**()
- Returns the size of the range.
- **GetUnion**(a, b) -> Range3d
- **classmethod** GetUnion(a, b) -> Range3d
- **IntersectWith**(b)
- Modifies this range to hold its intersection with `b` and returns the result.
- **IsEmpty**()
- Returns whether the range is empty (max<min).
- **SetEmpty**()
- Sets the range to be empty.
| | |
|---|---|
| Sets the range to an empty interval. | |
| `SetMax` (max) | Sets the maximum value of the range. |
| `SetMin` (min) | Sets the minimum value of the range. |
| `UnionWith` (b) | Extend `this` to include `b`. |
**Attributes:**
| | |
|---|---|
| `dimension` | |
| `max` | |
| `min` | |
| `unitCube` | |
**Contains**
(point) → bool
- Returns true if the `point` is located inside the range.
- As with all operations of this type, the range is assumed to include its extrema.
- **Parameters**
- **point** (Vec3d) –
- Contains(range) -> bool
- Returns true if the `range` is located entirely inside the range.
- As with all operations of this type, the ranges are assumed to include their extrema.
- **Parameters**
- **range** (Range3d) –
**GetCorner**
(i) → Vec3d
- Returns the ith corner of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
- Where L/R is left/right, D/U is down/up, and B/F is back/front.
- **Parameters**
- **i** (int) –
### GetDistanceSquared
Compute the squared distance from a point to the range.
#### Parameters
- **p** (Vec3d) –
### GetIntersection
classmethod GetIntersection(a, b) -> Range3d
Returns a `GfRange3d` that describes the intersection of `a` and `b`.
#### Parameters
- **a** (Range3d) –
- **b** (Range3d) –
### GetMax
Returns the maximum value of the range.
### GetMidpoint
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin
Returns the minimum value of the range.
### GetOctant
Returns the ith octant of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
Where L/R is left/right, D/U is down/up, and B/F is back/front.
#### Parameters
- **i** (int) –
### pxr.Gf.Range3d.GetSize
- **Returns the size of the range.**
### pxr.Gf.Range3d.GetUnion
- **classmethod** GetUnion(a, b) -> Range3d
- Returns the smallest `GfRange3d` which contains both `a` and `b`.
- **Parameters**
- **a** (`Range3d`) –
- **b** (`Range3d`) –
### pxr.Gf.Range3d.IntersectWith
- Modifies this range to hold its intersection with `b` and returns the result.
- **Parameters**
- **b** (`Range3d`) –
### pxr.Gf.Range3d.IsEmpty
- Returns whether the range is empty (max<min).
### pxr.Gf.Range3d.SetEmpty
- Sets the range to an empty interval.
### pxr.Gf.Range3d.SetMax
- Sets the maximum value of the range.
- **Parameters**
- **max** (`Vec3d`) –
### pxr.Gf.Range3d.SetMin
- Sets the minimum value of the range.
- **Parameters**
- **min** (`Vec3d`) –
### pxr.Gf.Range3d.SetMin
- **Description:** Sets the minimum value of the range.
- **Parameters:**
- **min** (Vec3d) –
### pxr.Gf.Range3d.UnionWith
- **Description:** Extend `this` to include `b`.
- **Parameters:**
- **b** (Range3d) –
- **Function Signature:** UnionWith(b) -> Range3d
- **Description:** Extend `this` to include `b`.
- **Parameters:**
- **b** (Vec3d) –
### pxr.Gf.Range3d.dimension
- **Description:** (Property) dimension = 3
### pxr.Gf.Range3d.max
- **Description:** (Property) max
### pxr.Gf.Range3d.min
- **Description:** (Property) min
### pxr.Gf.Range3d.unitCube
- **Description:** (Property) unitCube = Gf.Range3d(Gf.Vec3d(0.0, 0.0, 0.0), Gf.Vec3d(1.0, 1.0, 1.0))
### pxr.Gf.Range3f
- **Methods:**
- **Contains** (point) - Returns true if the `point` is located inside the range.
- **GetCorner** (i) -
| Method | Description |
|--------|-------------|
| `GetDistanceSquared(p)` | Compute the squared distance from a point to the range. |
| `GetIntersection(a, b) -> Range3f` | classmethod GetIntersection(a, b) -> Range3f |
| `GetMax()` | Returns the maximum value of the range. |
| `GetMidpoint()` | Returns the midpoint of the range, that is, 0.5*(min+max). |
| `GetMin()` | Returns the minimum value of the range. |
| `GetOctant(i)` | Returns the ith octant of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF. |
| `GetSize()` | Returns the size of the range. |
| `GetUnion(a, b) -> Range3f` | classmethod GetUnion(a, b) -> Range3f |
| `IntersectWith(b)` | Modifies this range to hold its intersection with `b` and returns the result. |
| `IsEmpty()` | Returns whether the range is empty (max<min). |
| `SetEmpty()` | Sets the range to an empty interval. |
| `SetMax(max)` | Sets the maximum value of the range. |
| `SetMin(min)` | Sets the minimum value of the range. |
| `UnionWith(b)` | Extend `this` to include `b`. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
dimension
</span>
</code>
</a>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Range3f.max" title="pxr.Gf.Range3f.max">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
max
</span>
</code>
</a>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Range3f.min" title="pxr.Gf.Range3f.min">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
min
</span>
</code>
</a>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Range3f.unitCube" title="pxr.Gf.Range3f.unitCube">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
unitCube
</span>
</code>
</a>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
</tbody>
</table>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Range3f.Contains">
<span class="sig-name descname">
<span class="pre">
Contains
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
point
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
bool
</span>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Range3f.Contains" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Returns true if the
<code class="docutils literal notranslate">
<span class="pre">
point
</span>
</code>
is located inside the range.
</p>
<p>
As with all operations of this type, the range is assumed to include
its extrema.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
point
</strong>
(
<em>
Vec3f
</em>
) –
</p>
</dd>
</dl>
<hr class="docutils"/>
<p>
Contains(range) -> bool
</p>
<p>
Returns true if the
<code class="docutils literal notranslate">
<span class="pre">
range
</span>
</code>
is located entirely inside the range.
</p>
<p>
As with all operations of this type, the ranges are assumed to include
their extrema.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
range
</strong>
(
<em>
Range3f
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Range3f.GetCorner">
<span class="sig-name descname">
<span class="pre">
GetCorner
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
i
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec3f" title="pxr.Gf.Vec3f">
<span class="pre">
Vec3f
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Range3f.GetCorner" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Returns the ith corner of the range, in the following order: LDB, RDB,
LUB, RUB, LDF, RDF, LUF, RUF.
</p>
<p>
Where L/R is left/right, D/U is down/up, and B/F is back/front.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
i
</strong>
(
<em>
int
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Range3f.GetDistanceSquared">
<span class="sig-name descname">
<span class="pre">
GetDistanceSquared
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
p
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Range3f.GetDistanceSquared" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Compute the squared distance from a point to the range.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
p
</strong>
(
<em>
Vec3f
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Range3f.GetIntersection">
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
GetIntersection
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<a class="headerlink" href="#pxr.Gf.Range3f.GetIntersection" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
<strong>
classmethod
</strong>
GetIntersection(a, b) -> Range3f
</p>
<p>
Returns a
<code class="docutils literal notranslate">
<span class="pre">
GfRange3f
</span>
</code>
that describes the intersection of
<code class="docutils literal notranslate">
<span class="pre">
a
</span>
and
```
```
b
```
.
### Parameters
- **a** (Range3f) –
- **b** (Range3f) –
### GetMax
```
GetMax() → Vec3f
```
Returns the maximum value of the range.
### GetMidpoint
```
GetMidpoint() → Vec3f
```
Returns the midpoint of the range, that is, 0.5*(min+max).
Note: this returns zero in the case of default-constructed ranges, or ranges set via SetEmpty().
### GetMin
```
GetMin() → Vec3f
```
Returns the minimum value of the range.
### GetOctant
```
GetOctant(i) → Range3f
```
Returns the ith octant of the range, in the following order: LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF.
Where L/R is left/right, D/U is down/up, and B/F is back/front.
#### Parameters
- **i** (int) –
### GetSize
```
GetSize() → Vec3f
```
Returns the size of the range.
### GetUnion
```
classmethod GetUnion(a, b) → Range3f
```
Returns the smallest GfRange3f which contains both a and b.
#### Parameters
- **a** (Range3f) –
- **b** (Range3f) –
(
**Range3f**
) –
### IntersectWith
```python
IntersectWith(b)
```
Returns: **Range3f**
Modifies this range to hold its intersection with `b` and returns the result.
**Parameters**
- **b** (**Range3f**) –
### IsEmpty
```python
IsEmpty()
```
Returns: **bool**
Returns whether the range is empty (max<min).
### SetEmpty
```python
SetEmpty()
```
Returns: **None**
Sets the range to an empty interval.
### SetMax
```python
SetMax(max)
```
Returns: **None**
Sets the maximum value of the range.
**Parameters**
- **max** (**Vec3f**) –
### SetMin
```python
SetMin(min)
```
Returns: **None**
Sets the minimum value of the range.
**Parameters**
- **min** (**Vec3f**) –
### UnionWith
```python
UnionWith(b)
```
Returns: **Range3f**
Extend `this` to include `b`.
**Parameters**
- **b** –
**b** (**Range3f**) –
---
UnionWith(b) -> Range3f
Extend `this` to include `b`.
---
**Parameters**
**b** (**Vec3f**) –
---
**dimension** = 3
**max** property
**min** property
**unitCube** = Gf.Range3f(Gf.Vec3f(0.0, 0.0, 0.0), Gf.Vec3f(1.0, 1.0, 1.0))
---
**class** **pxr.Gf.Ray**
**Methods:**
- **FindClosestPoint**(point, rayDistance)
- Returns the point on the ray that is closest to `point`.
- **GetPoint**(distance)
- Returns the point that is `distance` units from the starting point along the direction vector, expressed in parametric distance.
- **Intersect**(p0, p1, p2)
- float, barycentric = GfVec3d, frontFacing = bool
- **SetEnds**(startPoint, endPoint)
- Sets the ray by specifying a starting point and an ending point.
- **SetPointAndDirection**(startPoint, direction)
- Sets the ray by specifying a starting point and a direction.
- **Transform**(matrix)
- Transforms the ray by the given matrix.
## Attributes:
| Attribute | Description |
|-----------|-------------|
| `direction` | Vec3d |
| `startPoint` | Vec3d |
## Methods
### FindClosestPoint(point, rayDistance) → Vec3d
Returns the point on the ray that is closest to `point`.
If `rayDistance` is not `None`, it will be set to the parametric distance along the ray of the closest point.
**Parameters:**
- **point** (Vec3d) –
- **rayDistance** (float) –
### GetPoint(distance) → Vec3d
Returns the point that is `distance` units from the starting point along the direction vector, expressed in parametric distance.
**Parameters:**
- **distance** (float) –
### Intersect(p0, p1, p2) → tuple<intersects=bool, dist=float, barycentric=GfVec3d, frontFacing=bool>
Intersects the ray with the triangle formed by points p0, p1, and p2. The first item in the tuple is true if the ray intersects the triangle. dist is the parametric distance to the intersection point, the barycentric coordinates of the intersection point, and the front-facing flag. The barycentric coordinates are defined with respect to the three vertices taken in order. The front-facing flag is True if the intersection hit the side of the triangle that is formed when the vertices are ordered counter-clockwise (right-hand rule).
**Barycentric coordinates are defined to sum to 1 and satisfy this relationship:**
```
intersectionPoint = (barycentricCoords[0] * p0 +
barycentricCoords[1] * p1 +
barycentricCoords[2] * p2);
```
**Intersect( plane ) → tuple<intersects = bool, dist = float, frontFacing = bool>**
Intersects the ray with the Gf.Plane. The first item in the returned tuple is true if the ray intersects the plane. dist is the parametric distance to the intersection point.
and frontfacing is true if the intersection is on the side
of the plane toward which the plane’s normal points.
Intersect( range3d ) -> tuple<intersects = bool, enterDist
= float, exitDist = float>
Intersects the plane with an axis-aligned box in a
Gf.Range3d. intersects is true if the ray intersects it at
all within bounds. If there is an intersection then enterDist
and exitDist will be the parametric distances to the two
intersection points.
Intersect( bbox3d ) -> tuple<intersects = bool, enterDist
= float, exitDist = float>
Intersects the plane with an oriented box in a Gf.BBox3d.
intersects is true if the ray intersects it at all within
bounds. If there is an intersection then enterDist and
exitDist will be the parametric distances to the two
intersection points.
Intersect( center, radius ) -> tuple<intersects = bool,
enterDist = float, exitDist = float>
Intersects the plane with an sphere. intersects is true if
the ray intersects it at all within the sphere. If there is
an intersection then enterDist and exitDist will be the
parametric distances to the two intersection points.
Intersect( origin, axis, radius ) -> tuple<intersects = bool,
enterDist = float, exitDist = float>
Intersects the plane with an infinite cylinder. intersects
is true if the ray intersects it at all within the
sphere. If there is an intersection then enterDist and
exitDist will be the parametric distances to the two
intersection points.
Intersect( origin, axis, radius, height ) ->
tuple<intersects = bool, enterDist = float, exitDist = float>
Intersects the plane with an cylinder. intersects
is true if the ray intersects it at all within the
sphere. If there is an intersection then enterDist and
exitDist will be the parametric distances to the two
intersection points.
SetEnds( startPoint, endPoint ) -> None
Sets the ray by specifying a starting point and an ending point.
Parameters:
- startPoint (Vec3d) –
- endPoint (Vec3d) –
SetPointAndDirection( startPoint, direction ) -> None
Sets the ray by specifying a starting point and a direction.
Parameters:
- startPoint (Vec3d) –
- direction (Vec3d) –
Transform( matrix ) -> Ray
Transforms the ray by the given matrix.
Parameters:
- matrix (Matrix4d) –
## Vec3d
Returns the direction vector of the segment.
This is not guaranteed to be unit length.
### Type
type
## startPoint
Returns the starting point of the segment.
### Type
type
## pxr.Gf.Rect2i
### Methods:
- **Contains(p)** - Returns true if the specified point is in the rectangle.
- **GetArea()** - Return the area of the rectangle.
- **GetCenter()** - Returns the center point of the rectangle.
- **GetHeight()** - Returns the height of the rectangle.
- **GetIntersection(that)** - Computes the intersection of two rectangles.
- **GetMax()** - Returns the max corner of the rectangle.
- **GetMaxX()** - Return the X value of the max corner.
- **GetMaxY()** - Return the Y value of the max corner.
- **GetMin()** - Returns the min corner of the rectangle.
- **GetMinX()** - Return the X value of min corner.
- **GetMinY()** - Return the Y value of the min corner.
- **GetNormalized()** - Returns a normalized rectangle, i.e.
- `GetSize()`
- Returns the size of the rectangle as a vector (width,height).
- `GetUnion(that)`
- Computes the union of two rectangles.
- `GetWidth()`
- Returns the width of the rectangle.
- `IsEmpty()`
- Returns true if the rectangle is empty.
- `IsNull()`
- Returns true if the rectangle is a null rectangle.
- `IsValid()`
- Return true if the rectangle is valid (equivalently, not empty).
- `SetMax(max)`
- Sets the max corner of the rectangle.
- `SetMaxX(x)`
- Set the X value of the max corner.
- `SetMaxY(y)`
- Set the Y value of the max corner.
- `SetMin(min)`
- Sets the min corner of the rectangle.
- `SetMinX(x)`
- Set the X value of the min corner.
- `SetMinY(y)`
- Set the Y value of the min corner.
- `Translate(displacement)`
- Move the rectangle by `displ`.
**Attributes:**
- `max`
- `maxX`
- `maxY`
<p>
min
</p>
<p>
minX
</p>
<p>
minY
</p>
<dl>
<dt>
Contains (p) → bool
<a href="#pxr.Gf.Rect2i.Contains" title="Permalink to this definition"></a>
</dt>
<dd>
<p>Returns true if the specified point in the rectangle.</p>
<dl>
<dt>Parameters</dt>
<dd>
<p><strong>p</strong> (Vec2i) –</p>
</dd>
</dl>
</dd>
</dl>
<dl>
<dt>
GetArea () → int
<a href="#pxr.Gf.Rect2i.GetArea" title="Permalink to this definition"></a>
</dt>
<dd>
<p>Return the area of the rectangle.</p>
</dd>
</dl>
<dl>
<dt>
GetCenter () → Vec2i
<a href="#pxr.Gf.Rect2i.GetCenter" title="Permalink to this definition"></a>
</dt>
<dd>
<p>Returns the center point of the rectangle.</p>
</dd>
</dl>
<dl>
<dt>
GetHeight () → int
<a href="#pxr.Gf.Rect2i.GetHeight" title="Permalink to this definition"></a>
</dt>
<dd>
<p>Returns the height of the rectangle.</p>
<p>If the min and max y-coordinates are coincident, the height is one.</p>
</dd>
</dl>
<dl>
<dt>
GetIntersection (that) → Rect2i
<a href="#pxr.Gf.Rect2i.GetIntersection" title="Permalink to this definition"></a>
</dt>
<dd>
<p>Computes the intersection of two rectangles.</p>
<dl>
<dt>Parameters</dt>
<dd>
<p><strong>that</strong> (Rect2i) –</p>
</dd>
</dl>
</dd>
</dl>
<dl>
<dt>
GetMax () → Vec2i
<a href="#pxr.Gf.Rect2i.GetMax" title="Permalink to this definition"></a>
</dt>
<dd>
<p>Returns the max corner of the rectangle.</p>
</dd>
</dl>
<dl>
<dt>
GetMaxX () → int
<a href="#pxr.Gf.Rect2i.GetMaxX" title="Permalink to this definition"></a>
</dt>
<dd>
<p>Returns the max x-coordinate of the rectangle.</p>
</dd>
</dl>
### GetMaxX
Return the X value of the max corner.
### GetMaxY
Return the Y value of the max corner.
### GetMin
Returns the min corner of the rectangle.
### GetMinX
Return the X value of min corner.
### GetMinY
Return the Y value of the min corner.
### GetNormalized
Returns a normalized rectangle, i.e. one that has a non-negative width and height.
```
```markdown
GetNormalized() swaps the min and max x-coordinates to ensure a non-negative width, and similarly for the y-coordinates.
```
### GetSize
Returns the size of the rectangle as a vector (width,height).
### GetUnion
Computes the union of two rectangles.
#### Parameters
- **that** (Rect2i) –
### GetWidth
Returns the width of the rectangle. If the min and max x-coordinates are coincident, the width is one.
### IsEmpty
```python
IsEmpty() -> bool
```
Returns true if the rectangle is empty.
An empty rectangle has one or both of its min coordinates strictly greater than the corresponding max coordinate.
An empty rectangle is not valid.
### IsNull
```python
IsNull() -> bool
```
Returns true if the rectangle is a null rectangle.
A null rectangle has both the width and the height set to 0, that is
```python
GetMaxX() == GetMinX() - 1
and
GetMaxY() == GetMinY() - 1
```
Remember that if `GetMinX()` and `GetMaxX()` return the same value then the rectangle has width 1, and similarly for the height.
A null rectangle is both empty, and not valid.
### IsValid
```python
IsValid() -> bool
```
Return true if the rectangle is valid (equivalently, not empty).
### SetMax
```python
SetMax(max) -> None
```
Sets the max corner of the rectangle.
**Parameters**
- **max** (`Vec2i`) –
### SetMaxX
```python
SetMaxX(x) -> None
```
Set the X value of the max corner.
**Parameters**
- **x** (`int`) –
### SetMaxY
```python
SetMaxY(y) -> None
```
Set the Y value of the max corner.
**Parameters**
- **y** (`int`) –
### SetMin
```python
SetMin(min) -> None
```
Sets the min corner of the rectangle.
**Parameters**
- **min** (`Vec2i`) –
### SetMin
Sets the min corner of the rectangle.
**Parameters**
- **min** (Vec2i) –
### SetMinX
Set the X value of the min corner.
**Parameters**
- **x** (int) –
### SetMinY
Set the Y value of the min corner.
**Parameters**
- **y** (int) –
### Translate
Move the rectangle by `displ`.
**Parameters**
- **displacement** (Vec2i) –
### max
### maxX
### maxY
### min
### minX
### minY
## pxr.Gf.Rotation
class
3-space rotation
### Methods:
- **Decompose(axis0, axis1, axis2)**
Decompose rotation about 3 orthogonal axes.
- **DecomposeRotation**
classmethod DecomposeRotation(rot, TwAxis, FBAxis, LRAxis, handedness, thetaTw, thetaFB, thetaLR, thetaSw, useHint, swShift) -> None
- **DecomposeRotation3**
- **GetAngle()**
Returns the rotation angle in degrees.
- **GetAxis()**
Returns the axis of rotation.
- **GetInverse()**
Returns the inverse of this rotation.
- **GetQuat()**
Returns the rotation expressed as a quaternion.
- **GetQuaternion()**
Returns the rotation expressed as a quaternion.
- **MatchClosestEulerRotation**
classmethod MatchClosestEulerRotation(targetTw, targetFB, targetLR, targetSw, thetaTw, thetaFB, thetaLR, thetaSw) -> None
- **RotateOntoProjected(v1, v2, axis)**
classmethod RotateOntoProjected(v1, v2, axis) -> Rotation
- **SetAxisAngle(axis, angle)**
Sets the rotation to be `angle` degrees about `axis`.
- **SetIdentity()**
Sets the rotation to an identity rotation.
- **SetQuat()**
Sets the rotation to a quaternion.
| Method | Description |
| ------ | ----------- |
| `SetQuat(quat)` | Sets the rotation from a quaternion. |
| `SetQuaternion(quat)` | Sets the rotation from a quaternion. |
| `SetRotateInto(rotateFrom, rotateTo)` | Sets the rotation to one that brings the `rotateFrom` vector to align with `rotateTo`. |
| `TransformDir(vec)` | Transforms row vector `vec` by the rotation, returning the result. |
**Attributes:**
| Attribute | Description |
| --------- | ----------- |
| `angle` | |
| `axis` | |
### Decompose
```python
Decompose(axis0, axis1, axis2) -> Vec3d
```
Decompose rotation about 3 orthogonal axes. If the axes are not orthogonal, warnings will be spewed.
**Parameters:**
- **axis0** (Vec3d) –
- **axis1** (Vec3d) –
- **axis2** (Vec3d) –
### DecomposeRotation
```python
@staticmethod
DecomposeRotation(rot, TwAxis, FBAxis, LRAxis, handedness, thetaTw, thetaFB, thetaLR, thetaSw, useHint, swShift) -> None
```
**classmethod** DecomposeRotation(rot, TwAxis, FBAxis, LRAxis, handedness, thetaTw, thetaFB, thetaLR, thetaSw, useHint, swShift) -> None
**Parameters:**
- **rot** (Matrix4d) –
- **TwAxis** (Vec3d) –
- **FBAxis** (Vec3d) –
- **LRAxis** (Vec3d) –
- **handedness** (int) –
- **thetaTw** (float) –
- **thetaFB** (float) –
- **thetaLR** (float) –
- **thetaSw** (float) –
- **useHint** (bool) –
- **swShift** (float) –
**LRAxis** (**Vec3d**) –
**handedness** (**float**) –
**thetaTw** (**float**) –
**thetaFB** (**float**) –
**thetaLR** (**float**) –
**thetaSw** (**float**) –
**useHint** (**bool**) –
**swShift** (**float**) –
**DecomposeRotation3**()
**GetAngle**() → float
- Returns the rotation angle in degrees.
**GetAxis**() → Vec3d
- Returns the axis of rotation.
**GetInverse**() → Rotation
- Returns the inverse of this rotation.
**GetQuat**() → Quatd
- Returns the rotation expressed as a quaternion.
**GetQuaternion**() → Quaternion
- Returns the rotation expressed as a quaternion.
**MatchClosestEulerRotation**(targetTw, targetFB, targetLR, targetSw, thetaTw, thetaFB, thetaLR, thetaSw) -> None
- Replace the hint angles with the closest rotation of the given rotation to the hint.
- Each angle in the rotation will be within Pi of the corresponding hint
angle and the sum of the differences with the hint will be minimized.
If a given rotation value is null then that angle will be treated as
0.0 and ignored in the calculations.
All angles are in radians. The rotation order is Tw/FB/LR/Sw.
### Parameters
- **targetTw** (`float`) –
- **targetFB** (`float`) –
- **targetLR** (`float`) –
- **targetSw** (`float`) –
- **thetaTw** (`float`) –
- **thetaFB** (`float`) –
- **thetaLR** (`float`) –
- **thetaSw** (`float`) –
### classmethod RotateOntoProjected(v1, v2, axis) -> Rotation
#### Parameters
- **v1** (`Vec3d`) –
- **v2** (`Vec3d`) –
- **axis** (`Vec3d`) –
### SetAxisAngle(axis, angle) -> Rotation
Sets the rotation to be `angle` degrees about `axis`.
#### Parameters
- **axis** (`Vec3d`) –
- **angle** (`float`) –
### SetIdentity() -> Rotation
Sets the rotation to an identity rotation.
(This is chosen to be 0 degrees around the positive X axis.)
### SetQuat(quat) -> Rotation
### SetQuat
Sets the rotation from a quaternion.
Note that this method accepts GfQuatf and GfQuath since they implicitly convert to GfQuatd.
**Parameters**
- **quat** (Quatd) –
### SetQuaternion
Sets the rotation from a quaternion.
**Parameters**
- **quat** (Quaternion) –
### SetRotateInto
Sets the rotation to one that brings the `rotateFrom` vector to align with `rotateTo`.
The passed vectors need not be unit length.
**Parameters**
- **rotateFrom** (Vec3d) –
- **rotateTo** (Vec3d) –
### TransformDir
Transforms row vector `vec` by the rotation, returning the result.
**Parameters**
- **vec** (Vec3f) –
TransformDir(vec) -> Vec3d
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
**Parameters**
- **vec** (Vec3d) –
### angle
### axis
### pxr.Gf.Size2
**A 2D size class**
**Methods:**
| Method | Description |
|--------|-------------|
| `Set(v)` | Set to the values in a given array. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
#### pxr.Gf.Size2.Set
**Set to the values in a given array.**
**Parameters:**
- **v** (int) –
**Set(v0, v1) -> Size2**
Set to values passed directly.
**Parameters:**
- **v0** (int) –
- **v1** (int) –
#### pxr.Gf.Size2.dimension
**dimension = 2**
### pxr.Gf.Size3
**A 3D size class**
**Methods:**
| Method | Description |
|--------|-------------|
| `Set(v)` | Set to the values in `v`. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
#### pxr.Gf.Size3.Set
**Set to the values in `v`.**
**Parameters:**
- **v** (int) –
#### pxr.Gf.Size3.dimension
### Size3
Set to the values in `v`.
#### Parameters
- **v** (`int`) –
---
Set(v0, v1, v2) -> Size3
Set to values passed directly.
#### Parameters
- **v0** (`int`) –
- **v1** (`int`) –
- **v2** (`int`) –
### Size3.dimension
= 3
### pxr.Gf.Transform
**Methods:**
- **GetMatrix**()
Returns a `GfMatrix4d` that implements the cumulative transformation.
- **GetPivotOrientation**()
Returns the pivot orientation component.
- **GetPivotPosition**()
Returns the pivot position component.
- **GetRotation**()
Returns the rotation component.
- **GetScale**()
Returns the scale component.
- **GetTranslation**()
Returns the translation component.
- **Set**()
Set method used by old 2x code.
- **SetIdentity**()
Sets the transformation to the identity transformation.
- **SetMatrix**(m)
Sets the transform components to implement the transformation represented by matrix `m`.
| Method | Description |
| ------ | ----------- |
| SetPivotOrientation(pivotOrient) | Sets the pivot orientation component, leaving all others untouched. |
| SetPivotPosition(pivPos) | Sets the pivot position component, leaving all others untouched. |
| SetRotation(rotation) | Sets the rotation component, leaving all others untouched. |
| SetScale(scale) | Sets the scale component, leaving all others untouched. |
| SetTranslation(translation) | Sets the translation component, leaving all others untouched. |
**Attributes:**
| Attribute | Description |
| --------- | ----------- |
| pivotOrientation | |
| pivotPosition | |
| rotation | |
| scale | |
| translation | |
**Methods:**
- **GetMatrix() -> Matrix4d**
- Returns a `GfMatrix4d` that implements the cumulative transformation.
- **GetPivotOrientation() -> Rotation**
- Returns the pivot orientation component.
- **GetPivotPosition() -> Vec3d**
- Returns the pivot position component.
Returns the pivot position component.
```
```markdown
GetRotation
()
→ Rotation
Returns the rotation component.
```
```markdown
GetScale
()
→ Vec3d
Returns the scale component.
```
```markdown
GetTranslation
()
→ Vec3d
Returns the translation component.
```
```markdown
Set
()
Set method used by old 2x code. (Deprecated)
```
```markdown
SetIdentity
()
→ Transform
Sets the transformation to the identity transformation.
```
```markdown
SetMatrix
(m)
→ Transform
Sets the transform components to implement the transformation represented by matrix m, ignoring any projection.
This tries to leave the current center unchanged.
Parameters
----------
m (Matrix4d) –
```
```markdown
SetPivotOrientation
(pivotOrient)
→ None
Sets the pivot orientation component, leaving all others untouched.
Parameters
----------
pivotOrient (Rotation) –
```
```markdown
SetPivotPosition
(pivPos)
Sets the pivot position component.
```
### SetPivotPosition
Sets the pivot position component, leaving all others untouched.
**Parameters**
- **pivPos** (Vec3d) –
### SetRotation
Sets the rotation component, leaving all others untouched.
**Parameters**
- **rotation** (Rotation) –
### SetScale
Sets the scale component, leaving all others untouched.
**Parameters**
- **scale** (Vec3d) –
### SetTranslation
Sets the translation component, leaving all others untouched.
**Parameters**
- **translation** (Vec3d) –
### pivotOrientation
### pivotPosition
### rotation
### scale
### translation
## pxr.Gf.Vec2d
### Methods:
| Method | Description |
|--------|-------------|
| Axis(i) -> Vec2d | classmethod Axis(i) -> Vec2d |
| GetComplement(b) | Returns the orthogonal complement of this->GetProjection(b). |
| GetDot | |
| GetLength() | Length. |
| GetNormalized(eps) | param eps |
| GetProjection(v) | Returns the projection of this onto v. |
| Normalize(eps) | Normalizes the vector in place to unit length, returning the length before normalization. |
| XAxis() -> Vec2d | classmethod XAxis() -> Vec2d |
| YAxis() -> Vec2d | classmethod YAxis() -> Vec2d |
### Attributes:
| Attribute | Description |
|-----------|-------------|
| dimension | |
### static Axis
classmethod Axis(i) -> Vec2d
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if i is greater than or equal to 2.
Parameters
- i: |
<p>
<strong>
i
</strong>
(
<em>
int
</em>
) –
</p>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetComplement">
<span class="sig-name descname">
<span class="pre">
GetComplement
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
b
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
Vec2d
</span>
</span>
</span>
</dt>
<dd>
<p>
Returns the orthogonal complement of
<code class="docutils literal notranslate">
<span class="pre">
this->GetProjection(b)
</span>
</code>
.
</p>
<p>
That is:
</p>
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span></span>\*this - this->GetProjection(b)
</pre>
</div>
</div>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
b
</strong>
(
<em>
Vec2d
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetDot">
<span class="sig-name descname">
<span class="pre">
GetDot
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
</dt>
<dd>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
</dt>
<dd>
<p>
Length.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
eps
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
Vec2d
</span>
</span>
</span>
</dt>
<dd>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
float
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.GetProjection">
<span class="sig-name descname">
<span class="pre">
GetProjection
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
v
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
Vec2d
</span>
</span>
</span>
</dt>
<dd>
<p>
Returns the projection of
<code class="docutils literal notranslate">
<span class="pre">
this
</span>
</code>
onto
<code class="docutils literal notranslate">
<span class="pre">
v
</span>
</code>
.
</p>
<p>
That is:
</p>
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span></span>v \* (\*this \* v)
</pre>
</div>
</div>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
v
</strong>
(
<em>
Vec2d
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2d.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
eps
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
</dt>
<dd>
<p>
Normalizes the vector in place to unit length, returning the length
before normalization.
</p>
<p>
If the length of the vector is smaller than
<code class="docutils literal notranslate">
<span class="pre">
eps
</span>
</code>
, then the vector
is set to vector/
<code class="docutils literal notranslate">
<span class="pre">
eps
</span>
</code>
. The original length of the vector is
returned. See also GfNormalize() .
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
float
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
### eps (float) –
### classmethod XAxis() -> Vec2d
Create a unit vector along the X-axis.
### classmethod YAxis() -> Vec2d
Create a unit vector along the Y-axis.
### dimension = 2
### class Vec2f
Methods:
- **classmethod Axis(i) -> Vec2f**
- **GetComplement(b)**
Returns the orthogonal complement of this->GetProjection(b).
- **GetDot**
- **GetLength()**
Length.
- **GetNormalized(eps)**
param eps
- **GetProjection(v)**
Returns the projection of this onto v.
- **Normalize(eps)**
Normalizes the vector in place to unit length, returning the length before normalization.
- **classmethod XAxis() -> Vec2f**
```html
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
YAxis
</span>
</code>
</a>
</p>
</td>
<td>
<p>
<strong>
classmethod
</strong>
YAxis() -> Vec2f
</p>
</td>
</tr>
</tbody>
</table>
<p>
<strong>
Attributes:
</strong>
</p>
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>
<tbody>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec2f.dimension" title="pxr.Gf.Vec2f.dimension">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
dimension
</span>
</code>
</a>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
</tbody>
</table>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.Axis">
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
Axis
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<a class="headerlink" href="#pxr.Gf.Vec2f.Axis" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
<strong>
classmethod
</strong>
Axis(i) -> Vec2f
</p>
<p>
Create a unit vector along the i-th axis, zero-based.
</p>
<p>
Return the zero vector if
<code class="docutils literal notranslate">
<span class="pre">
i
</span>
</code>
is greater than or equal to 2.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
i
</strong>
(
<em>
int
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetComplement">
<span class="sig-name descname">
<span class="pre">
GetComplement
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
b
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec2f" title="pxr.Gf.Vec2f">
<span class="pre">
Vec2f
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Vec2f.GetComplement" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Returns the orthogonal complement of
<code class="docutils literal notranslate">
<span class="pre">
this->GetProjection(b)
</span>
</code>
.
</p>
<p>
That is:
</p>
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span></span>\*this - this->GetProjection(b)
</pre>
</div>
</div>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
b
</strong>
(
<a class="reference internal" href="#pxr.Gf.Vec2f" title="pxr.Gf.Vec2f">
<em>
Vec2f
</em>
</a>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetDot">
<span class="sig-name descname">
<span class="pre">
GetDot
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<a class="headerlink" href="#pxr.Gf.Vec2f.GetDot" title="Permalink to this definition">
</a>
</dt>
<dd>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Vec2f.GetLength" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Length.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
eps
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec2f" title="pxr.Gf.Vec2f">
<span class="pre">
Vec2f
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Vec2f.GetNormalized" title="Permalink to this definition">
</a>
</dt>
<dd>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
float
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec2f.GetProjection">
<span class="sig-name descname">
<span class="pre">
GetProjection
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
v
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<a class="reference internal" href="#pxr.Gf.Vec2f" title="pxr.Gf.Vec2f">
<span class="pre">
Vec2f
</span>
</a>
</span>
</span>
<a class="headerlink" href="#pxr.Gf.Vec2f.GetProjection" title="Permalink to this definition">
</a>
</dt>
<dd>
<p>
Returns the projection of
<code class="docutils literal notranslate">
<span class="pre">
this
</span>
</code>
onto
<code class="docutils literal notranslate">
.
That is:
```
```
v \* (\*this \* v)
```
Parameters
----------
v (Vec2f) –
Normalize
---------
(eps) → float
Normalizes the vector in place to unit length, returning the length before normalization.
If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
Parameters
----------
eps (float) –
XAxis
-----
() → Vec2f
Create a unit vector along the X-axis.
YAxis
-----
() → Vec2f
Create a unit vector along the Y-axis.
dimension
---------
= 2
Vec2h
-----
Methods:
- Axis(i) → Vec2h
- GetComplement(b)
- GetDot()
- GetLength()
- GetNormalized(eps)
| 方法 | 描述 |
| --- | --- |
| `GetProjection(v)` | Returns the projection of `this` onto `v`. |
| `Normalize(eps)` | Normalizes the vector in place to unit length, returning the length before normalization. |
| `XAxis()` | `classmethod` XAxis() -> Vec2h |
| `YAxis()` | `classmethod` YAxis() -> Vec2h |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `dimension` | |
**classmethod Axis(i) -> Vec2h**
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if `i` is greater than or equal to 2.
**Parameters**
- **i** (int) –
**GetComplement(b) -> Vec2h**
Returns the orthogonal complement of `this->GetProjection(b)`.
That is:
```
*this - this->GetProjection(b)
```
**Parameters**
- **b** (Vec2h) –
**GetLength() -> GfHalf**
Length.
### GetNormalized
- **Parameters**
- **eps** (GfHalf) –
### GetProjection
- Returns the projection of `this` onto `v`.
- **Parameters**
- **v** (Vec2h) –
### Normalize
- Normalizes the vector in place to unit length, returning the length before normalization.
- **Parameters**
- **eps** (GfHalf) –
### XAxis
- **classmethod** XAxis() -> Vec2h
- Create a unit vector along the X-axis.
### YAxis
- **classmethod** YAxis() -> Vec2h
- Create a unit vector along the Y-axis.
### dimension
- **dimension** = 2
### Methods:
| Description | Method |
|-------------|--------|
| classmethod Axis(i) -> Vec2i | Axis |
| classmethod XAxis() -> Vec2i | XAxis |
| classmethod YAxis() -> Vec2i | YAxis |
| classmethod GetDot() -> Vec2i | GetDot |
### Attributes:
| Attribute | Description |
|-----------|-------------|
| dimension (int) = 2 | dimension |
### Details:
#### Axis
- **classmethod** Axis(i) -> Vec2i
- Create a unit vector along the i-th axis, zero-based.
- Return the zero vector if `i` is greater than or equal to 2.
- **Parameters:**
- **i** (int) –
#### XAxis
- **classmethod** XAxis() -> Vec2i
- Create a unit vector along the X-axis.
#### YAxis
- **classmethod** YAxis() -> Vec2i
- Create a unit vector along the Y-axis.
#### GetDot
- **classmethod** GetDot() -> Vec2i
#### dimension
- **attribute** dimension = 2
| Row | Content |
| --- | --- |
| Even | `BuildOrthonormalFrame(v1, v2, eps)` - Sets `v1` and `v2` to unit vectors such that v1, v2 and *this are mutually orthogonal. |
| Odd | `GetComplement(b)` - Returns the orthogonal complement of `this->GetProjection(b)`. |
| Even | `GetCross` |
| Odd | `GetDot` |
| Even | `GetLength()` - Length. |
| Odd | `GetNormalized(eps)` - param eps |
| Even | `GetProjection(v)` - Returns the projection of `this` onto `v`. |
| Odd | `Normalize(eps)` - Normalizes the vector in place to unit length, returning the length before normalization. |
| Even | `OrthogonalizeBasis` - `classmethod` OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool |
| Odd | `XAxis` - `classmethod` XAxis() -> Vec3d |
| Even | `YAxis` - `classmethod` YAxis() -> Vec3d |
| Odd | `ZAxis` - `classmethod` ZAxis() -> Vec3d |
**Attributes:**
| Attribute | Description |
| --- | --- |
| `dimension` | |
### Axis(i) -> Vec3d
- **classmethod**
- Create a unit vector along the i-th axis, zero-based.
- Return the zero vector if `i` is greater than or equal to 3.
- **Parameters**
- **i** (`int`) –
### BuildOrthonormalFrame(v1, v2, eps) -> None
- Sets `v1` and `v2` to unit vectors such that v1, v2 and *this are mutually orthogonal.
- If the length L of *this is smaller than `eps`, then v1 and v2 will have magnitude L/eps.
- **Parameters**
- **v1** (`Vec3d`) –
- **v2** (`Vec3d`) –
- **eps** (`float`) –
### GetComplement(b) -> Vec3d
- Returns the orthogonal complement of `this->GetProjection(b)`.
- That is: \*this - this->GetProjection(b)
- **Parameters**
- **b** (`Vec3d`) –
### GetCross()
### GetDot()
### GetLength() -> float
- Length.
### GetNormalized(eps)
### GetNormalized
- Parameters
- **eps** (float) –
### GetProjection
- Returns the projection of `this` onto `v`.
- That is:
```
v * (this * v)
```
- Parameters
- **v** (Vec3d) –
### Normalize
- Normalizes the vector in place to unit length, returning the length before normalization.
- If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
- Parameters
- **eps** (float) –
### OrthogonalizeBasis
- **classmethod** OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
- Orthogonalize and optionally normalize a set of basis vectors.
- This uses an iterative method that is very stable even when the vectors are far from orthogonal (close to colinear). The number of iterations and thus the computation time does increase as the vectors become close to colinear, however. Returns a bool specifying whether the solution converged after a number of iterations. If it did not converge, the returned vectors will be as close as possible to orthogonal within the iteration limit. Colinear vectors will be unaltered, and the method will return false.
- Parameters
- **tx** (Vec3d) –
- **ty** (Vec3d) –
- **tz** (Vec3d) –
- **normalize** (bool) –
- **eps** (float) –
### XAxis
## XAxis
```python
classmethod XAxis() -> Vec3d
```
Create a unit vector along the X-axis.
## YAxis
```python
classmethod YAxis() -> Vec3d
```
Create a unit vector along the Y-axis.
## ZAxis
```python
classmethod ZAxis() -> Vec3d
```
Create a unit vector along the Z-axis.
## dimension
```python
dimension = 3
```
## Vec3f
### Methods:
- `Axis(i) -> Vec3f`
- `BuildOrthonormalFrame(v1, v2, eps)`
Sets `v1` and `v2` to unit vectors such that v1, v2 and *this are mutually orthogonal.
- `GetComplement(b)`
Returns the orthogonal complement of `this->GetProjection(b)`.
- `GetCross()`
- `GetDot()`
- `GetLength()`
Length.
- `GetNormalized(eps)`
- param eps
- `GetProjection(v)`
Returns the projection of `this`.
onto
```
```markdown
v
```
```markdown
Normalize (eps)
```
```markdown
Normalizes the vector in place to unit length, returning the length before normalization.
```
```markdown
OrthogonalizeBasis
```
```markdown
classmethod
OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
```
```markdown
XAxis
```
```markdown
classmethod
XAxis() -> Vec3f
```
```markdown
YAxis
```
```markdown
classmethod
YAxis() -> Vec3f
```
```markdown
ZAxis
```
```markdown
classmethod
ZAxis() -> Vec3f
```
```markdown
Attributes:
```
```markdown
dimension
```
```markdown
static
Axis
```
```markdown
classmethod
Axis(i) -> Vec3f
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if i is greater than or equal to 3.
Parameters
----------
i (int) –
```
```markdown
BuildOrthonormalFrame
```
```markdown
BuildOrthonormalFrame(v1, v2, eps)
Sets v1 and v2 to unit vectors such that v1, v2 and *this are mutually orthogonal.
If the length L of *this is smaller than eps, then v1 and v2 will have magnitude L/eps. As a result, the function delivers a continuous result as *this shrinks in length.
Parameters
----------
v1 (Vec3f) –
v2 (Vec3f) –
eps (float) –
```
### GetComplement
```python
GetComplement(b)
```
Returns the orthogonal complement of `this->GetProjection(b)`.
That is:
```python
*this - this->GetProjection(b)
```
#### Parameters
- **b** (`Vec3f`) –
### GetCross
```python
GetCross()
```
### GetDot
```python
GetDot()
```
### GetLength
```python
GetLength()
```
Returns: `float`
Length.
### GetNormalized
```python
GetNormalized(eps)
```
Returns: `Vec3f`
#### Parameters
- **eps** (`float`) –
### GetProjection
```python
GetProjection(v)
```
Returns the projection of `this` onto `v`.
That is:
```python
v * (*this * v)
```
#### Parameters
- **v** (`Vec3f`) –
### Normalize
```python
Normalize(eps)
```
Returns: `float`
Normalizes the vector in place to unit length, returning the length before normalization.
If the length of the vector is smaller than `eps`, then the vector is set to vector/
```
`eps`. The original length of the vector is returned. See also GfNormalize().
### Parameters
- **eps** (`float`) –
## OrthogonalizeBasis
```python
classmethod OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
```
Orthogonalize and optionally normalize a set of basis vectors.
This uses an iterative method that is very stable even when the vectors are far from orthogonal (close to colinear). The number of iterations and thus the computation time does increase as the vectors become close to colinear, however. Returns a bool specifying whether the solution converged after a number of iterations. If it did not converge, the returned vectors will be as close as possible to orthogonal within the iteration limit. Colinear vectors will be unaltered, and the method will return false.
### Parameters
- **tx** (`Vec3f`) –
- **ty** (`Vec3f`) –
- **tz** (`Vec3f`) –
- **normalize** (`bool`) –
- **eps** (`float`) –
## XAxis
```python
classmethod XAxis() -> Vec3f
```
Create a unit vector along the X-axis.
## YAxis
```python
classmethod YAxis() -> Vec3f
```
Create a unit vector along the Y-axis.
## ZAxis
```python
classmethod ZAxis() -> Vec3f
```
Create a unit vector along the Z-axis.
## dimension
```python
dimension = 3
```
## Vec3h
### Methods:
- **Axis**
```python
classmethod Axis(i) -> Vec3h
```
```
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
BuildOrthonormalFrame
</span>
</code>
</a>
(v1, v2, eps)
</p>
</td>
<td>
<p>
Sets
<code class="docutils literal notranslate">
<span class="pre">
v1
</span>
</code>
and
<code class="docutils literal notranslate">
<span class="pre">
v2
</span>
</code>
to unit vectors such that v1, v2 and *this are mutually orthogonal.
</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetComplement" title="pxr.Gf.Vec3h.GetComplement">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetComplement
</span>
</code>
</a>
(b)
</p>
</td>
<td>
<p>
Returns the orthogonal complement of
<code class="docutils literal notranslate">
<span class="pre">
this->GetProjection(b)
</span>
</code>
.
</p>
</td>
</tr>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetCross" title="pxr.Gf.Vec3h.GetCross">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetCross
</span>
</code>
</a>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetDot" title="pxr.Gf.Vec3h.GetDot">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetDot
</span>
</code>
</a>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetLength" title="pxr.Gf.Vec3h.GetLength">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetLength
</span>
</code>
</a>
()
</p>
</td>
<td>
<p>
Length.
</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetNormalized" title="pxr.Gf.Vec3h.GetNormalized">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetNormalized
</span>
</code>
</a>
(eps)
</p>
</td>
<td>
<p>
<dl class="field-list simple">
<dt class="field-odd">
param eps
</dt>
<dd class="field-odd">
<p>
</p>
</dd>
</dl>
</p>
</td>
</tr>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.GetProjection" title="pxr.Gf.Vec3h.GetProjection">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
GetProjection
</span>
</code>
</a>
(v)
</p>
</td>
<td>
<p>
Returns the projection of
<code class="docutils literal notranslate">
<span class="pre">
this
</span>
</code>
onto
<code class="docutils literal notranslate">
<span class="pre">
v
</span>
</code>
.
</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.Normalize" title="pxr.Gf.Vec3h.Normalize">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
Normalize
</span>
</code>
</a>
(eps)
</p>
</td>
<td>
<p>
Normalizes the vector in place to unit length, returning the length before normalization.
</p>
</td>
</tr>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.OrthogonalizeBasis" title="pxr.Gf.Vec3h.OrthogonalizeBasis">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
OrthogonalizeBasis
</span>
</code>
</a>
</p>
</td>
<td>
<p>
<strong>
classmethod
</strong>
OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.XAxis" title="pxr.Gf.Vec3h.XAxis">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
XAxis
</span>
</code>
</a>
</p>
</td>
<td>
<p>
<strong>
classmethod
</strong>
XAxis() -> Vec3h
</p>
</td>
</tr>
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.YAxis" title="pxr.Gf.Vec3h.YAxis">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
YAxis
</span>
</code>
</a>
</p>
</td>
<td>
<p>
<strong>
classmethod
</strong>
YAxis() -> Vec3h
</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.ZAxis" title="pxr.Gf.Vec3h.ZAxis">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
ZAxis
</span>
</code>
</a>
</p>
</td>
<td>
<p>
<strong>
classmethod
</strong>
ZAxis() -> Vec3h
</p>
</td>
</tr>
</tbody>
</table>
<p>
<strong>
Attributes:
</strong>
</p>
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>
<tbody>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.Gf.Vec3h.dimension" title="pxr.Gf.Vec3h.dimension">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
dimension
</span>
</code>
</a>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
</tbody>
</table>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec3h.Axis">
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
Axis
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<a class="headerlink" href="#pxr.Gf.Vec3h.Axis" title="Permalink to this definition">
## classmethod Axis(i) -> Vec3h
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if `i` is greater than or equal to 3.
### Parameters
- **i** (int) –
## BuildOrthonormalFrame(v1, v2, eps) -> None
Sets `v1` and `v2` to unit vectors such that v1, v2 and *this are mutually orthogonal.
If the length L of *this is smaller than `eps`, then v1 and v2 will have magnitude L/eps. As a result, the function delivers a continuous result as *this shrinks in length.
### Parameters
- **v1** (Vec3h) –
- **v2** (Vec3h) –
- **eps** (GfHalf) –
## GetComplement(b) -> Vec3h
Returns the orthogonal complement of `this->GetProjection(b)`.
That is:
```
*this - this->GetProjection(b)
```
### Parameters
- **b** (Vec3h) –
## GetLength() -> GfHalf
Length.
### GetNormalized
- **Parameters**
- **eps** (GfHalf) –
### GetProjection
- Returns the projection of `this` onto `v`.
- That is:
```
v * (this * v)
```
- **Parameters**
- **v** (Vec3h) –
### Normalize
- Normalizes the vector in place to unit length, returning the length before normalization.
- If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
- **Parameters**
- **eps** (GfHalf) –
### OrthogonalizeBasis
- **classmethod** OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
- Orthogonalize and optionally normalize a set of basis vectors.
- This uses an iterative method that is very stable even when the vectors are far from orthogonal (close to colinear). The number of iterations and thus the computation time does increase as the vectors become close to colinear, however. Returns a bool specifying whether the solution converged after a number of iterations. If it did not converge, the returned vectors will be as close as possible to orthogonal within the iteration limit. Colinear vectors will be unaltered, and the method will return false.
- **Parameters**
- **tx** (Vec3h) –
- **ty** (Vec3h) –
- **tz** (Vec3h) –
- **normalize** (bool) –
- **eps** (float) –
### XAxis
- **static** XAxis()
### XAxis
```python
classmethod
XAxis() -> Vec3h
```
Create a unit vector along the X-axis.
### YAxis
```python
classmethod
YAxis() -> Vec3h
```
Create a unit vector along the Y-axis.
### ZAxis
```python
classmethod
ZAxis() -> Vec3h
```
Create a unit vector along the Z-axis.
### dimension
```python
dimension = 3
```
### Vec3i
```
class pxr.Gf.Vec3i
```
Methods:
| Method | Description |
|--------|-------------|
| Axis(i) -> Vec3i | Create a unit vector along the i-th axis, zero-based. Return the zero vector if i is greater than or equal to 3. |
| GetDot | |
| XAxis() -> Vec3i | |
| YAxis() -> Vec3i | |
| ZAxis() -> Vec3i | |
Attributes:
| Attribute | Description |
|-----------|-------------|
| dimension | |
## pxr.Gf.Vec3i Methods
### XAxis
**classmethod** XAxis() -> Vec3i
Create a unit vector along the X-axis.
### YAxis
**classmethod** YAxis() -> Vec3i
Create a unit vector along the Y-axis.
### ZAxis
**classmethod** ZAxis() -> Vec3i
Create a unit vector along the Z-axis.
### dimension
dimension = 3
## pxr.Gf.Vec4d Methods
### Axis
**classmethod** Axis(i) -> Vec4d
### GetComplement
Returns the orthogonal complement of this->GetProjection(b).
### GetDot
### GetLength
Length.
### GetNormalized
param eps
### GetProjection
Returns the projection of this onto v.
### Normalize
| Method | Description |
|--------|-------------|
| `WAxis()` | classmethod WAxis() -> Vec4d |
| `XAxis()` | classmethod XAxis() -> Vec4d |
| `YAxis()` | classmethod YAxis() -> Vec4d |
| `ZAxis()` | classmethod ZAxis() -> Vec4d |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `dimension` | |
**static** `Axis()`
- **classmethod** Axis(i) -> Vec4d
- Create a unit vector along the i-th axis, zero-based.
- Return the zero vector if `i` is greater than or equal to 4.
- **Parameters**
- **i** (int) –
`GetComplement(b)`
- Returns the orthogonal complement of `this->GetProjection(b)`.
- That is: `*this - this->GetProjection(b)`
- **Parameters**
- **b** (Vec4d) –
`GetDot()`
`GetLength()`
- Length.
`GetNormalized(eps)`
### Vec4d.GetNormalized
- **Parameters**
- **eps** (float) –
### Vec4d.GetProjection
- **Parameters**
- **v** (Vec4d) –
### Vec4d.Normalize
- **Parameters**
- **eps** (float) –
### Vec4d.WAxis
- **classmethod** WAxis() -> Vec4d
- Create a unit vector along the W-axis.
### Vec4d.XAxis
- **classmethod** XAxis() -> Vec4d
- Create a unit vector along the X-axis.
### Vec4d.YAxis
- **classmethod** YAxis() -> Vec4d
- Create a unit vector along the Y-axis.
### Vec4d.ZAxis
- **classmethod** ZAxis() -> Vec4d
- Create a unit vector along the Z-axis.
### Vec4d.dimension
- **property** dimension
## pxr.Gf.Vec4f
### Methods:
| Method | Description |
| ------ | ----------- |
| Axis(i) -> Vec4f | classmethod |
| GetComplement(b) | Returns the orthogonal complement of this->GetProjection(b). |
| GetDot | |
| GetLength() | Length. |
| GetNormalized(eps) | param eps |
| GetProjection(v) | Returns the projection of this onto v. |
| Normalize(eps) | Normalizes the vector in place to unit length, returning the length before normalization. |
| WAxis() -> Vec4f | classmethod |
| XAxis() -> Vec4f | classmethod |
| YAxis() -> Vec4f | classmethod |
| ZAxis() -> Vec4f | classmethod |
### Attributes:
| Attribute | Description |
| --------- | ----------- |
| dimension | |
<em class="property">
<span class="pre">
static
</span>
<span class="w">
</span>
</em>
<span class="sig-name descname">
<span class="pre">
Axis
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
</dt>
<dd>
<p>
<strong>
classmethod
</strong>
Axis(i) -> Vec4f
</p>
<p>
Create a unit vector along the i-th axis, zero-based.
</p>
<p>
Return the zero vector if
<code class="docutils literal notranslate">
<span class="pre">
i
</span>
</code>
is greater than or equal to 4.
</p>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
i
</strong>
(
<em>
int
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetComplement">
<span class="sig-name descname">
<span class="pre">
GetComplement
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
b
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
Vec4f
</span>
</span>
</span>
</dt>
<dd>
<p>
Returns the orthogonal complement of
<code class="docutils literal notranslate">
<span class="pre">
this->GetProjection(b)
</span>
</code>
.
</p>
<p>
That is:
</p>
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span></span>\*this - this->GetProjection(b)
</pre>
</div>
</div>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
b
</strong>
(
<em>
Vec4f
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetDot">
<span class="sig-name descname">
<span class="pre">
GetDot
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
</dt>
<dd>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetLength">
<span class="sig-name descname">
<span class="pre">
GetLength
</span>
</span>
<span class="sig-paren">
(
</span>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
float
</span>
</span>
</span>
</dt>
<dd>
<p>
Length.
</p>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetNormalized">
<span class="sig-name descname">
<span class="pre">
GetNormalized
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
eps
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
Vec4f
</span>
</span>
</span>
</dt>
<dd>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
eps
</strong>
(
<em>
float
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.GetProjection">
<span class="sig-name descname">
<span class="pre">
GetProjection
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
v
</span>
</span>
</em>
<span class="sig-paren">
)
</span>
<span class="sig-return">
<span class="sig-return-icon">
→
</span>
<span class="sig-return-typehint">
<span class="pre">
Vec4f
</span>
</span>
</span>
</dt>
<dd>
<p>
Returns the projection of
<code class="docutils literal notranslate">
<span class="pre">
this
</span>
</code>
onto
<code class="docutils literal notranslate">
<span class="pre">
v
</span>
</code>
.
</p>
<p>
That is:
</p>
<div class="highlight-text notranslate">
<div class="highlight">
<pre><span></span>v \* (\*this \* v)
</pre>
</div>
</div>
<dl class="field-list simple">
<dt class="field-odd">
Parameters
</dt>
<dd class="field-odd">
<p>
<strong>
v
</strong>
(
<em>
Vec4f
</em>
) –
</p>
</dd>
</dl>
</dd>
</dl>
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Gf.Vec4f.Normalize">
<span class="sig-name descname">
<span class="pre">
Normalize
</span>
</span>
<span class="sig-paren">
(
</span>
<em class="sig-param">
<span class="n">
<span class="pre">
eps
</span>
)
→ float
Normalizes the vector in place to unit length, returning the length before normalization.
If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
**Parameters**
**eps** (**float**) –
classmethod WAxis() -> Vec4f
Create a unit vector along the W-axis.
classmethod XAxis() -> Vec4f
Create a unit vector along the X-axis.
classmethod YAxis() -> Vec4f
Create a unit vector along the Y-axis.
classmethod ZAxis() -> Vec4f
Create a unit vector along the Z-axis.
dimension = 4
class pxr.Gf.Vec4h
Methods:
- Axis(i) -> Vec4h
- GetComplement(b)
Returns the orthogonal complement of this->GetProjection(b).
- GetDot()
- GetLength()
Length.
```
```
GetNormalized (eps)
```
```
param eps
```
```
GetProjection (v)
```
Returns the projection of `this` onto `v`.
```
Normalize (eps)
```
Normalizes the vector in place to unit length, returning the length before normalization.
```
WAxis
```
```
classmethod WAxis() -> Vec4h
```
```
XAxis
```
```
classmethod XAxis() -> Vec4h
```
```
YAxis
```
```
classmethod YAxis() -> Vec4h
```
```
ZAxis
```
```
classmethod ZAxis() -> Vec4h
```
```
dimension
```
```
static classmethod Axis(i) -> Vec4h
```
Create a unit vector along the i-th axis, zero-based. Return the zero vector if `i` is greater than or equal to 4.
Parameters:
- **i** (int) –
```
GetComplement (b) -> Vec4h
```
Returns the orthogonal complement of `this->GetProjection(b)`.
That is:
```
*this - this->GetProjection(b)
```
Parameters:
- **b** (Vec4h) –
```
### GetDot
```
### GetLength
```
Length.
```
### GetNormalized
```
Parameters
----------
eps (GfHalf) –
```
### GetProjection
```
Returns the projection of `this` onto `v`.
That is:
```
v * (*this * v)
```
Parameters
----------
v (Vec4h) –
```
### Normalize
```
Normalizes the vector in place to unit length, returning the length before normalization.
If the length of the vector is smaller than `eps`, then the vector is set to vector/`eps`. The original length of the vector is returned. See also GfNormalize().
```
Parameters
----------
eps (GfHalf) –
```
### WAxis
```
classmethod WAxis() -> Vec4h
Create a unit vector along the W-axis.
```
### XAxis
```
classmethod XAxis() -> Vec4h
Create a unit vector along the X-axis.
```
### YAxis
```
```
### YAxis
- **classmethod** YAxis() -> Vec4h
- Create a unit vector along the Y-axis.
### ZAxis
- **classmethod** ZAxis() -> Vec4h
- Create a unit vector along the Z-axis.
### dimension
- **Attribute** dimension = 4
### Vec4i
- **Methods:**
- **classmethod** Axis(i) -> Vec4i
- **classmethod** WAxis() -> Vec4i
- **classmethod** XAxis() -> Vec4i
- **classmethod** YAxis() -> Vec4i
- **classmethod** ZAxis() -> Vec4i
- **Attributes:**
- **Attribute** dimension
### Axis
- **classmethod** Axis(i) -> Vec4i
- Create a unit vector along the i-th axis, zero-based.
- Return the zero vector if `i` is greater than or equal to 4.
- **Parameters**
- **i** (int) –
### GetDot
```
```markdown
### WAxis
```
```markdown
### XAxis
```
```markdown
### YAxis
```
```markdown
### ZAxis
```
```markdown
### dimension
``` |
Glf.md | # Glf module
Summary: The Glf module contains Utility classes for OpenGL output.
## Classes:
- **DrawTarget**
- A class representing a GL render target with multiple image attachments.
- **GLQueryObject**
- Represents a GL query object in Glf.
- **SimpleLight**
- (No description provided)
- **SimpleMaterial**
- (No description provided)
- **Texture**
- Represents a texture object in Glf.
### DrawTarget
- **Methods:**
- **AddAttachment(name, format, type, internalFormat)**
- Add an attachment to the DrawTarget.
| Method | Description |
| --- | --- |
| Bind() | Binds the framebuffer. |
| Unbind() | Unbinds the framebuffer. |
| WriteToFile(name, filename, viewMatrix, ...) | Write the Attachment buffer to an image file (debugging). |
**Attributes:**
| Attribute | Description |
| --- | --- |
| expired | True if this object has expired, False otherwise. |
**AddAttachment(name, format, type, internalFormat)**
- **Parameters**
- **name** (str)
- **format** (GLenum)
- **type** (GLenum)
- **internalFormat** (GLenum)
**Bind()**
- Binds the framebuffer.
**Unbind()**
- Unbinds the framebuffer.
**WriteToFile(name, filename, viewMatrix, projectionMatrix)**
- Write the Attachment buffer to an image file (debugging).
### Parameters
- **name** (`str`) –
- **filename** (`str`) –
- **viewMatrix** (`Matrix4d`) –
- **projectionMatrix** (`Matrix4d`) –
### Property: expired
- True if this object has expired, False otherwise.
### Class: pxr.Glf.GLQueryObject
Represents a GL query object in Glf
#### Methods:
| Method | Description |
|--------|-------------|
| `Begin` (target) | Begin query for the given target. Target has to be one of GL_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED_CONSERVATIVE, GL_PRIMITIVES_GENERATED, GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, GL_TIME_ELAPSED, GL_TIMESTAMP. |
| `BeginPrimitivesGenerated` () | Equivalent to Begin(GL_PRIMITIVES_GENERATED). |
| `BeginSamplesPassed` () | Equivalent to Begin(GL_SAMPLES_PASSED). |
| `BeginTimeElapsed` () | Equivalent to Begin(GL_TIME_ELAPSED). |
| `End` () | End query. |
| `GetResult` () | Return the query result (synchronous) stalls CPU until the result becomes available. |
| `GetResultNoWait` () | Return the query result (asynchronous) returns 0 if the result hasn't been available. |
#### Method: Begin
- Begin query for the given target. Target has to be one of GL_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED_CONSERVATIVE, GL_PRIMITIVES_GENERATED, GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, GL_TIME_ELAPSED, GL_TIMESTAMP. Returns None.
GL_TRANSFORM_FEITBACK_PRIMITIVES_WRITTEN GL_TIME_ELAPSED,
GL_TIMESTAMP.
### Parameters
**target** (GLenum) –
### BeginPrimitivesGenerated
equivalent to Begin(GL_PRIMITIVES_GENERATED).
The number of primitives sent to the rasterizer by the scoped drawing command will be returned.
### BeginSamplesPassed
equivalent to Begin(GL_SAMPLES_PASSED).
The number of samples that pass the depth test for all drawing commands within the scope of the query will be returned.
### BeginTimeElapsed
equivalent to Begin(GL_TIME_ELAPSED).
The time that it takes for the GPU to execute all of the scoped commands will be returned in nanoseconds.
### End
End query.
### GetResult
Return the query result (synchronous) stalls CPU until the result becomes available.
### GetResultNoWait
Return the query result (asynchronous) returns 0 if the result hasn’t been available.
### SimpleLight
**Attributes:**
- ambient
- attenuation
| 属性 | 描述 |
| --- | --- |
| `diffuse` | None |
| `hasShadow` | None |
| `id` | |
| `isCameraSpaceLight` | None |
| `isDomeLight` | None |
| `position` | None |
| `shadowBias` | None |
| `shadowBlur` | None |
| `shadowIndexEnd` | None |
| `shadowIndexStart` | None |
| `shadowMatrices` | None |
| `shadowResolution` | None |
| `specular` | None |
| `spotCutoff` | None |
| `spotDirection` | None |
| `spotFalloff` | None |
| `transform` | None |
## Properties
### ambient
- **Type**: Vec4f
### attenuation
- **Type**: Vec3f
### diffuse
- **Type**: Vec4f
### hasShadow
- **Type**: type
### id
### isCameraSpaceLight
- **Type**: bool
### isDomeLight
- **Type**: bool
### position
- **Type**: Vec4f
### shadowBias
- **Type**: float
### shadowBlur
- **Type**: float
### shadowIndexEnd
- **Type**: int
### shadowIndexStart
- **Type**: int
### shadowMatrices
- **Type**: list[Matrix4d]
### shadowResolution
- **Type**: int
### specular
- **Type**: Vec4f
### spotCutoff
- **Type**: float
### spotDirection
- **Type**: Vec3f
### spotFalloff
- **Type**: float
### transform
- **Type**: Matrix4d
### SimpleMaterial
- **Type**: class
## SimpleMaterial
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| `ambient` | None |
| `diffuse` | None |
| `emission` | None |
| `shininess` | None |
| `specular` | None |
### ambient
**Type:** Vec4f
### diffuse
**Type:** Vec4f
### emission
**Type:** Vec4f
### shininess
**Type:** float
### specular
**Type:** Vec4f
## Texture
Represents a texture object in Glf.
A texture is typically defined by reading texture image data from an image file but a texture might also represent an attachment of a draw target.
**Methods:**
| 属性 | 描述 |
| --- | --- |
| `GetTextureMemoryAllocated` | `classmethod GetTextureMemoryAllocated() -> int` |
| `magFilterSupported` | bool |
| `memoryRequested` | None |
| `memoryUsed` | int |
| `minFilterSupported` | bool |
**Attributes:**
```python
classmethod GetTextureMemoryAllocated() -> int
```
static reporting function
```python
property magFilterSupported
```
bool
Type: type
```python
property memoryRequested
```
None
Specify the amount of memory the user wishes to allocate to the texture.
type: int
Amount of memory the user wishes to allocate to the texture.
Type: type
```python
property memoryUsed
```
int
Amount of memory used to store the texture.
Type: type
```python
property minFilterSupported
```
bool
Type: type |
global-simulation-commands_structcarb_1_1blast_1_1_blast.md | # carb::blast::Blast
Defined in [Blast.h](file_Blast.h)
## Destructible Authoring Commands
Plugin interface for the omni.blast extension.
### combinePrims
### DamageParameters
* damageParameters,
* float defaultMaxContactImpulse)
Main entry point to combine a existing prims into a single destructible.
#### Parameters
- **Param paths**
- [in] Full USD paths to prims that should be combined.
- **Param numPaths**
- [in] How many prims are in the paths array.
- **Param defaultContactThreshold**
- [in] How hard the prim needs to be hit to register damage during simulation.
- **Param damageParameters**
- [in] See DamageParameters description.
- **Param defaultMaxContactImpulse**
- [in] How much force can be used to push other prims away during a collision For kinematic prims only, used to allow heavy objects to continue moving through brittle destructible prims.
#### Return
- true iff the prims were combined successfully.
### fracturePrims
- const char * (const char ** paths, size_t numPaths, const char * defaultInteriorMaterial, uint32_t numVoronoiSites, float defaultContactThreshold, const DamageParameters * damageParameters)
Main entry point to fracture an existing prim.
### Parameters
- **Param paths [in]**
Full USD path(s) to prim(s) that should be fractured. They need to all be part of the same destructible if there are more than one.
- **Param numPaths [in]**
How many prims are in the paths array.
- **Param defaultInteriorMaterial [in]**
Material to set on newly created interior faces. (Ignored when re-fracturing and existing interior material is found.)
- **Param numVoronoiSites [in]**
How many pieces to split the prim into.
- **Param defaultContactThreshold [in]**
How hard the prim needs to be hit to register damage during simulation.
- **Param damageParameters [in]**
See [DamageParameters](structcarb_1_1blast_1_1_damage_parameters.html#structcarb_1_1blast_1_1_damage_parameters) description.
- **Param defaultMaxContactImpulse [in]**
How much force can be used to push other prims away during a collision. For kinematic prims only, used to allow heavy objects to continue moving through brittle destroyable prims.
- **Param interiorUvScale [in]**
Scale to apply to UV frame when mapping to interior face vertices.
### Return
path to the new prim if the source prim was fractured successfully, nullptr otherwise.
### Function: setRandomSeed
Set the random number generator seed for fracture operations.
#### Parameters
- **Param seed [in]**
the new seed.
### Function: resetBlastData
Reset the [Blast](#structcarb_1_1blast_1_1_blast) data (partial or full hierarchy) starting at the given path.
#### Parameters
- **Param path [in]**
the path to reset.
The destructible will be rebuilt with only appropriate data remaining.
- **Param path**
- **[in]** The path to a chunk, instance, or base destructible prim.
- **Return**
- true iff the operation could be performed on the prim at the given path.
- **Param path**
- **[in]** The USD path of the blast container.
- **Param defaultMaxContactImpulse**
- **[in]** Controls how much force physics can use to stop bodies from penetrating.
- **Param relativePadding**
- **[in]** A relative amount to grow chunk bounds in order when calculating world attachment.
- **Return**
- true if the destructible’s NvBlastAsset was modified (or if path == NULL).
- **Param path**
- **[in]** The USD path of the blast container.
- **Return**
- true if the destructible’s NvBlastAsset was modified (or if path == NULL).
Recalculates the areas of bonds.
This may be used when a destructible is scaled.
**Param path**
- **[in]** Path to the chunk, instance, or base destructible prim.
**Return**
- true iff the operation was successful.
Finds all children of the chunks in the given paths, and sets kit’s selection set to the paths of those children.
**Param paths**
- **[in]** Full USD path(s) to chunks.
**Param numPaths**
- **[in]** How many paths are in the paths array.
**Return**
- true iff the operation was successful.
### Function: selectParent
Finds all parents of the chunks in the given paths, and sets kit’s selection set to the paths of those parents.
#### Parameters
- **paths** [in]: Full USD path(s) to chunks.
- **numPaths** [in]: How many paths are in the paths array.
#### Return
true iff the operation was successful.
### Function: selectSource
Finds all source meshes for chunks in the given paths, and sets kit’s selection set to the paths of those meshes.
#### Parameters
- **paths** [in]: Full USD path(s) to chunks.
- **numPaths** [in]: How many paths are in the paths array.
#### Return
true iff the operation was successful.
### Function: setInteriorMaterial
Sets the material for the interior facets of the chunks at the given paths.
#### Parameters
- **paths** [in]: Full USD path(s) to chunks.
- **numPaths** [in]: How many paths are in the paths array.
- **interiorMaterial** [in]: The material to set for the interior facets.
### Description
#### Param paths
- **[in]** Full USD path(s) to chunks.
#### Param numPaths
- **[in]** How many paths are in the paths array.
#### Return
- the material path if all meshes found at the given paths have the same interior materials. If more than one interior material is found among the meshes found, the empty string (“”) is returned. If no interior material is found, nullptr is returned.
### Description
#### Param path
- **[in]** Path to the chunk, instance, or base destructible prim.
#### Param interiorUvScale
- **[in]** the scale to use to calculate UV coordinates. A value of 1 will cause the texture to map to a region in space roughly the size of the whole destructible’s largest width.
#### Return
- true iff the operation was successful.
### Function: createDestructibleInstance
```cpp
void createDestructibleInstance(
const char *path,
DamageParameters *damageParameters,
float defaultContactThreshold,
float defaultMaxContactImpulse
)
```
Creates a destructible instance with default values from the given destructible base.
**Parameters:**
- **path** [in] Path to the destructible base to instance.
- **damageParameters** [in] The damage characteristics to assign to the instance (see DamageParameters).
- **defaultContactThreshold** [in] Rigid body parameter to apply to actors generated by the instance. The minimum impulse required for a rigid body to generate a contact event, needed for impact damage.
- **defaultMaxContactImpulse** [in] Rigid body parameter to apply to actors generated by the instance. The maximum impulse that a contact constraint on a kinematic rigid body can impart on a colliding body.
### Function: setSimulationParams
```cpp
void setSimulationParams(int32_t maxNewActorsPerFrame)
```
Sets the maximum number of actors which will be generated by destruction each simulation frame.
**Parameters:**
- **maxNewActorsPerFrame** [in] The maximum number of actors generated per frame.
### Damage Application
```
```
```cpp
void createDamageEvent(const char *hitPrimPath, DamageEvent *damageEvents, size_t numDamageEvents);
```
Create a destruction event during simulation.
**Parameters:**
- **hitPrimPath [in]** - The full path to the prim to be damaged (may be a blast actor prim or its collision shape).
- **damageEvents [in]** - An array of DamageEvent structs describing the damage to be applied.
- **numDamageEvents [in]** - The size of the damageEvents array.
---
```cpp
void setExplodeViewRadius(const char *path, float radius);
```
Set the cached explode view radius for the destructible prim associated with the given path.
**Parameters:**
- **path [in]** - Full USD path to a destructible instance.
- **radius [in]** - The distance to move apart the instance’s rendered chunks.
```
Gives the cached explode view radius for the destructible instances associated with the given paths, if the cached value for all instances is the same.
**Param paths**
- **[in]** Array of USD paths to destructible instances.
**Param numPaths**
- **[in]** The length of the paths array.
**Return**
- The cached explode view radius for all valid destructible instances at the given paths, if that value is the same for all instances. If there is more than one radius found, this function returns -1.0f. If no valid instances are found, this function returns 0.0f.
Calculate the maximum depth for all chunks in the destructible prim associated with the given paths.
**Param paths**
- **[in]** Array of USD paths to destructible prims.
**Param numPaths**
- **[in]** The length of the paths array.
**Return**
- the maximum chunk depth for all destructibles associated with the given paths. Returns 0 if no destructibles are found.
### getViewDepth
Calculates what the view depth should be, factoring in internal override if set.
/return return what the view depth should be.
#### Parameters
- **Param paths [in]** Array of USD paths to destructible prims.
- **Param numPaths [in]** The length of the paths array.
### setViewDepth
Set the view depth for explode view functionality.
#### Parameters
- **Param paths [in]** Array of USD paths to destructible prims.
- **Param numPaths [in]** The length of the paths array.
- **Param depth [in]** Either a string representation of the numerical depth value, or “Leaves” to view leaf chunks.
### setDebugVisualizationInfo
Set the debug visualization info.
#### Parameters
- **Param mode [in]** The mode for debug visualization.
- **Param value [in]** The value for the debug visualization mode.
Set the debug visualization mode & type.
If mode != debugVisNone, an anonymous USD layer is created which overrides the render meshes for blast objects which are being visualized.
- **Param mode [in]**
- Supported modes: “debugVisNone”, “debugVisSelected”, “debugVisAll”
- **Param type [in]**
- Supported modes: “debugVisSupportGraph”, “debugVisMaxStressGraph”, “debugVisCompressionGraph”, “debugVisTensionGraph”, “debugVisShearGraph”, “debugVisBondPatches”
- **Return**
- true iff a valid mode is selected.
Debug Damage Functions
Set parameters for the debug damage tool in kit.
This is applied using Shift + B + (Left Mouse). A ray is cast from the camera position through the screen point of the mouse cursor, and intersected with scene geometry. The intersection point is used to find nearby destructibles using to damage.
- **Param amount [in]**
- The base damage to be applied to each destructible, as an acceleration in m/s^2.
- **Param impulse [in]**
- An impulse to apply to rigid bodies within the given radius, in kg*m/s. (This applies to non-destructible rigid bodies too.)
- **Param radius [in]**
- The distance in meters from the ray hit point to search for rigid bodies to affect with this function.
### Apply Debug Damage
Apply debug damage at the position given, in the direction given.
The damage parameters set by setDebugDamageParams will be used.
#### Parameters
- **Param worldPosition [in]**
The world position at which to apply debug damage.
- **Param worldDirection [in]**
The world direction of the applied damage.
### Notice Handler Functions
These can be called at any time to enable or disable notice handler monitoring.
When enabled, use BlastUsdMonitorNoticeEvents to catch unbuffered Usd/Sdf commands. It will be automatically cleaned up on system shutdown if enabled.
- **blastUsdEnableNoticeHandlerMonitor()**
- **blastUsdDisableNoticeHandlerMonitor()**
### Destructible Path Utilities
These functions find destructible base or instance prims from any associated prim path.
- **getDestructibleBasePath(const char* path)**
- **Param path [in]**
Any path associated with a destructible base prim.
- **Return**
the destructible prim’s path if found, or nullptr otherwise.
## getDestructibleInstancePath
```
```markdown
## blastCachePushBinaryDataToUSD
```
```markdown
## Blast SDK Cache
```
```markdown
This function pushes the Blast SDK data that is used during simulation back to USD so it can be saved and then later restored in the same state.
This is also the state that will be restored to when sim stops.
```
```markdown
## Blast Stress
```
```markdown
This function modifies settings used to drive stress calculations during simulation.
```
```markdown
Param path
```
```markdown
[in] Any path associated with a destructible instance prim.
```
```markdown
Param gravityEnabled
```
```markdown
[in] Controls if gravity should be applied to stress simulation of the destructible instance.
```
```markdown
Param rotationEnabled
```
```markdown
[in] Controls if rotational acceleration should be applied to stress simulation of the destructible instance.
```
```markdown
Param residualForceMultiplier
```
```markdown
[in] Multiplies the residual forces on bodies after connecting bonds break.
```
```markdown
Param settings
```
```markdown
[in] Values used to control the stress solver.
```
```markdown
Return
```
```markdown
true if stress settings were updated, false otherwise.
```
```markdown
char * path, bool gravityEnabled, bool rotationEnabled, float residualForceMultiplier, const StressSolverSettings & settings) |
Glossary.md | # Glossary
## “Any” Attribute Type
An [Extended Attribute](#term-Extended-Attribute) that can accept values or connections with any legal attribute type, with a few exceptions.
## Action Graph
An [OmniGraph](#term-OmniGraph) that triggers actions in response to a particular event.
## Attribute
A property of a node or node type that consists of a name, a data type, and a set of metadata that defines further properties.
## Attribute Data
The actual value an attribute has been given for a specific node and [Graph Context](#term-Graph-Context).
## Attribute Type
A description of the data type an attribute can hold. In many cases it is a simple piece of data such as float, int, or double, but it can also be more complicated data like a [“Union” Attribute Type](#term-Union-Attribute-Type) or a [Bundle](#term-Bundle).
## Authoring Graph
Refers to the definition of an [OmniGraph](#term-OmniGraph) structure, including nodes, attributes, and connections.
## Bundle
A Bundle is an attribute comprising of a set of named attributes, including other bundles.
## C++ ABI
The backwards-compatible interface surface defined by an extension. It consists of a set of interface classes, each of which comprise a set of static functions that are defined by an interface implementation.
## C++ API
A layer on top of the [C++ ABI](#term-C-ABI) that provides a higher level interface on top of the low level ABI interface functions to make it easier to interact with the C++ code.
## Compound Node
A compound node is a [Node](#term-Node) whose execution is defined by the evaluation of a [Graph](#term-Graph).
## Compound Graph
A compound graph is a [Graph](#term-Graph) that defines the execution of a [Graph](#term-Graph).
## Compound Node
## Compute Graph
“Compute graph” is a synonym for OmniGraph, an engine for programmatically manipulating scenes with a graph-based visual scripting interface.
## Connection
An edge in the Graph that joins two Nodes, indicating a relationship between the two Nodes, usually that the downstream Node cannot evaluate until the upstream Node has completed evaluation. Generally speaking the connections are formed between two Attributes on the Nodes, not between the Nodes directly.
## Dynamic Attribute
A Dynamic Attribute is an Attribute that is added to a node at runtime, as opposed to the ones that are predefined as part of the node’s ogn definition.
## Execution Graph
The intermediate representation of an OmniGraph that has been optimized for fast evaluation, and which follows the business logic needs of a specifically defined Authoring Graph.
## Extended Attribute
A type of attribute that is allowed to accept or produce more than one type of data.
## Fabric
The underlying data model that houses the data used by the Execution Graph during evaluation. It also provides the synchronizing of data between the CPU, GPU, USD, and external processes.
## Generic Graph
The term Generic Graph is also referred to as a Push Graph, which evaluates every node at every system update, or “tick”.
## Graph
The abstract concept that comprises nodes and connections which could be referring to either the Authoring Graph, the Execution Graph, or the combination of both.
## Graph Context
Each time a Graph is evaluated it is done so using specific evaluation context, represented concretely by the graph context. Different contexts maintain their own separate data models with unique values for every node and attribute evaluated in their context.
## Instance
An instance is a virtual copy of a Graph that can be replicated multiple times without actual replication of the Nodes within the Graph. Used for optimization of computation for duplicate subsections of a Graph by avoiding having multiple copies of the Authoring Graph and Execution Graph.
## Lazy Graph
A Lazy Graph is an OmniGraph that only evaluates nodes whose inputs have changed since the last evaluation.
## Metadata
Metadata is named general data that describes traits of either attributes or node types. It is a more flexible representation of object traits as it can have any data type and any name so that it can be attached to these objects at runtime.
### Node
A node is the basic vertex type in a Graph. It implements a single unit of computation and provides a location for attribute data storage and endpoints for graph edges, or Connections.
### ogn
### .ogn
### OGN
### OmniGraph
An engine for programmatically manipulating scenes with a graph-based visual scripting interface. It provides a platform for building graph types that potentially have very different types of authoring and evaluation representations. OmniGraph can represent such diverse graph types as state machines, AI training, and extension updates within Kit. It can be thought of more concretely as a graph of graphs that comprise the entirety of the graph authoring and evaluation system. Also used as the Prim schema type used for the USD representation of a graph.
### OmniGraphNode
The Prim schema type used for the USD representation of a node in a graph.
### Prim
### USD Prim
### Property
A USD term indicating a namespace object in USD, like a Prim, but with real data. Roughly equivalent to the OmniGraph node Attribute.
### Push Graph
A Push Graph is an OmniGraph that evaluates every node at every system update, or “tick”. It is convenient to use, but potentially inefficient as values are recomputed even when they are not changing.
### Python API
The Python modules that are officially supported as the interface between OmniGraph and the rest of the development environment. Generally speaking if a Python symbol can be imported and its name does not begin with an underscore (_) or dunder (__), then it is part of the supported Python API. Otherwise it is unsupported and subject to change without backward compatibility.
### Python Bindings
A subset of the Python API that is a Python wrapper on top of the C++ ABI. For the most part the functions that appear in it will be similar, other than following Python naming conventions, with a few extra additions that make a function more “Pythonic”, e.g. by supporting a generator.
### “Union” Attribute Type
An Attribute Type that can assume a fixed set of types, as opposed to the “Any” Attribute Type, which can assume any type at all.
### USD
Universal Scene Description (USD) is the fundamental representation for assets in Omniverse, and the persistent backing for OmniGraph nodes.
### Variable
A variable in this context is a value that is globally available at any location in a Graph without requiring an explicit Connection.
### Connection
### Vectorization
The process of evaluating an algorithm in parallel on multiple data sets of the same type. In a
**Node** you can see the difference between regular evaluation and vectorized evaluation as the difference between implementing
the `compute` function versus implementing the `computeVectorized` function. |
goal_Overview.md | # Introduction — Omniverse Kit 1.0.12 documentation
## Introduction
**Extension** : omni.kit.collaboration.channel_manager-1.0.12
**Documentation Generated** : May 08, 2024
### Introduction
Extension `omni.kit.collaboration.channel_manager` provides interfaces for creating/managing the Nucleus Channel easily and defines standard protocol for multiple users to do communication in the same channel. At the same time, users can be aware of each other.
### Goal
The Nucleus Channel only provides a way to pub/sub messages from the channel. It does not provide APIs to manage user states, nor complete application protocol for all clients to understand each other. It’s transient and stateless, so that messages that were sent before user has joined will not be sent again. It does not support P2P message, so that messages sent to the channel are broadcasted to all users. Therefore, we made the following extensions:
- It’s able to query user states from the API, and gets notified when users joined/left.
- It defines application protocol for all clients that support it to communicate with each other.
Currently, no P2P communication is supported still.
### Programming Guide
Here is an async function that joins a channel and sends a string message `hello, world` to the channel.
```python
import omni.kit.collaboration.channel_manager as cm
async def join_channel_async(channel_url, on_message: Callable[[cm.Message], None]):
# Joins the channel, and adds subscriber to subsribe messages.
channel = await cm.join_channel_async(channel_url)
if channel:
channel.add_subscriber(on_message)
# Sends message in dict
await channel.send_message_async({"test": "hello world"})
```
As you can see, the first step is to join a channel with `omni.kit.collaboration.channel_manager.join_channel_async()`, which will return a handle of the channel, through which you can query its connection states, other users that joined the same channel, and send messages (see `omni.kit.collaboration.channel_manager.Channel.send_message_async()`) specific to your application in the format of Python dict.
Also, it supports adding subscribers through
```python
omni.kit.collaboration.channel_manager.Channel.add_subscriber()
```
to subscribe to messages received from the channel. Messages received from other users are in type
```python
omni.kit.collaboration.channel_manager.Message
```
, and depends on the value of its
```python
message_type
```
property, message can be categorized into the following types (see
```python
omni.kit.collaboration.channel_manager.MessageType
```
for details):
- ```python
JOIN
```
: New user joined this channel.
- ```python
HELLO
```
: Someone said hello to me. Normally, it’s received when a new user joined the channel, and other users exist in the channel will reply HELLO so new user could be aware of them.
- ```python
LEFT
```
: Someone left the channel.
- ```python
GET_USERS
```
: Ping message to find out who joined this channel. Clients received this message should reply HELLO.
- ```python
MESSAGE
```
: Application specific message sent through API
```python
omni.kit.collaboration.channel_manager.Channel.send_message_async()
```
. |
Graph%20Core.md | # Graph Core
## Graph View
Following the model-view-delegate pattern, we’ve introduced the model and delegate. Now we are looking at the `GraphView`. It’s the visualisation layer of omni.kit.widget.graph. It behaves like a regular widget and displays nodes and their connections.
Since we mostly just want to use the defined GraphView for all the graphs, we define a core graph widget where you can just focus on building the model and delegate for your customized graph, while reusing the common graph stuff as much as possible.
## Omni.kit.graph.editor.core
We design Omni.kit.graph.editor.core to be the common framework for graph editor in Kit. It is a generic graph widget platform with a standard tree-view panel on the left to show all the available nodes in a list view, with a search bar on the top left. There is the graph editor on the right where we can view and edit the graph. There is also a breadcrumb in the graph view as the navigation of the graph.
We use it as the kit graph core to ensure all standard UI/UX widgets and windows for all our graph nodes are standardized with a common framework.
An example of material graph using omni.kit.graph.editor.core
## Create a graph widget
When you want to create your own graph widget, you can build your GraphWidget (`MyGraphWidget`) based on GraphEditorCoreWidget, define your graph (`self.__graph_model`) and catalog model (`self.__catalog_model`) to manage the graph data, customize graph (`self.__graph_delegate`) and catalog delegate (`self.__catalog_delegate`) look to suit your application.
![Code Result](Graph Core_0.png)
```python
class MyGraphWidget(GraphEditorCoreWidget):
def __init__(self, **kwargs):
self.__graph_model = None
self.__graph_delegate = None
self.__catalog_model = None
self.__catalog_delegate = None
toolbar_items = []
super().__init__(
model=self.__graph_model,
delegate=self.__graph_delegate,
view_type=GraphView,
style=None,
catalog_model=self.__catalog_model,
catalog_delegate=self.__catalog_delegate,
toolbar_items=toolbar_items,
has_catalog=True,
**kwargs,
)
```
# Navigation
To navigate between different subgraphs, we use `set_current_compound` which changes the current view to show the subgraph of the input item.
# Add right click menu on canvas
To add a right click context menu on the graph canvas, we should call `on_right_mouse_button_pressed` to override the function in the base class.
Use `ui.Menu` to create the menu and `ui.MenuItem` to add menu items. `ui.Separator()` is useful to create a separator between categories of menus.
An example of `on_right_mouse_button_pressed` is as below:
```python
def on_right_mouse_button_pressed(self, items):
self.__context_menu = ui.Menu("Context menu")
with self.__context_menu:
ui.MenuItem("Delete Selection", triggered_fn=lambda: self._graph_model.delete_selection())
ui.Separator()
ui.MenuItem("Open All", triggered_fn=lambda: self._graph_view.set_expansion(GraphModel.ExpansionState.OPEN))
ui.MenuItem(
"Minimize All", triggered_fn=lambda: self._graph_view.set_expansion(GraphModel.ExpansionState.MINIMIZED)
)
```
# Add button to the ToolBar
To add a toolbar on the top of the graph, one way is to define the `toolbar_items` as the code above before calling GraphEditorCoreWidget’s constructor. `toolbar_items` is a list of dictionaries containing the button name, icon and `on_clicked` callback.
An example of `toolbar_items` is as below:
```python
toolbar_items = [
{"name": "open", "icon": "open.svg", "on_clicked": open, "tooltip": "Open a graph"},
{"name": "-"},
{"name": "save", "icon": "save.svg", "on_clicked": save},
{"name": "new", "icon": "new.svg", "on_clicked": new},
]
```
`{"name": "open", "icon": "open.svg", "on_clicked": open(), "tooltip": "Open a graph"}` create a button named open with the icon as “open.svg”. When you hover over the button, it will show the tooltip of “Open a graph”, and when you click on the button, it will call the callable `open` function. `{"name": "-"}` is to create a separator.
Another way to define the toolbar, is to call `set_toolbar_items` to override the function from `GraphEditorCoreWidget`. This is useful if you want to change the toolbar items when you have already created your
```
GraphEditorCoreWidget
```
. The input attribute is the same type as the above example.
--- |
Graph%20Delegate.md | # Graph Delegate
Graph delegate describes how the graph looks, including the nodes, ports, connections and the editor itself. We have three different delegates available at the moment: omni.kit.delegate.default, omni.kit.delegate.modern and omni.kit.delegate.neo.
The delegate looks are shown below:
**Modern delegate:**
**Default delegate:**
**Neo delegate:**
The modern delegate will be the new standard look for our tools going forward. But please feel free to modify or build your own from any of those examples.
The omni.kit.graph.editor.example provides the example of switching between different delegates from the top right dropdown list. Each delegate is an extension, you can create your customized delegate by forking one of them and starting from there.
## GraphNodeDelegateRouter
From the above images, we can tell that the backdrop node looks quite different from other nodes. Also when the expansion states of nodes are closed (Render Mesh nodes on the right), it also looks very different from when the nodes are open (FullNode on the left) or minimized (Noise Deformer in the middle). Therefore, we need more than one look for the nodes for just one style of delegate. We use `GraphNodeDelegateRouter` to manage that. It is the base class of graph node delegate. It keeps multiple delegates and picks them depending on the routing conditions, e.g. expansion state of Closed or Open, node type of backdrop or compound.
We use `add_route` to add routing conditions. And the conditions could be a type or a lambda expression. The latest added routing is stronger than previously added. Routing added without conditions is the default delegate. We can use type routing to make the specific kind of nodes unique, and also we can use the lambda function to make the particular state of nodes unique (ex. full/collapsed).
It’s possible to use type and lambda routing at the same time. Here are the usage examples:
```python
delegate.add_route(TextureDelegate(), type="Texture2d")
delegate.add_route(CollapsedDelegate(), expression=is_collapsed)
```
## Delegate API
Each delegate added to the router is derived from `AbstractGraphNodeDelegate`. The delegate generates widgets that together form the node using the model. The following figure shows the LIST layout of the node.
COLUMNS layout allows for putting input and output ports on the same line:
```
[A] node_header_input
[B] node_header_output
[C] port_input
[D] port_output
[E] node_footer_input (TODO)
[F] node_footer_output (TODO)
```
For every zone, there is a method that is called to build this zone. For example, `port_input` is the API to be called to create the left part of the port that will be used as input.
# Node Background
`node_background` is the API to be called to create widgets of the entire node background.
# Customized Delegate
If you find that `omni.kit.graph.delegate.modern` is the look you like, you want to use it, but there are some special things that don’t exist in the delegate, how can you tweak that to create a variant modern look?
We can create a new delegate which is derived from GraphNodeDelegate of omni.kit.graph.delegate.modern. Then you can override the `port_input`, `port_input` or `connection` to obtain a different look for a special type of port and connections. Or you can override the `node_background` or `node_header` to achieve a different style for nodes.
You can potentially override any functions from the delegate class to customize your own delegate. Mix and match delegates from different delegate extensions to create your own. Feel free to fork the code and explore your artistic side to create the delegate that fulfills your needs.
# Add right click action on Nodes/Ports
For example, if I want to use `omni.kit.graph.delegate.modern`, but I need to add a drop down menu to enable some actions when I right click on output ports, how can I do that?
Firstly, we are going to inherit the delegate from the modern extension. Then we can override the `port_output` method from the modern delegate. Create a new frame layer, draw the base class output port within the frame, and add `set_mouse_pressed_fn` callback on the frame to add a right click menu for the output port.
```python
from omni.kit.graph.delegate.modern.delegate import GraphNodeDelegate
from typing import Any
class MyDelegate(GraphNodeDelegate):
"""
The delegate for the input/output nodes of the compound.
"""
def __init__(self):
super().__init__()
def __on_menu(self, model, node: Any, port: Any):
# create menu
pass
def port_output(self, model, node_desc, port_desc):
node = node_desc.node
port = port_desc.port
frame = ui.Frame()
with frame:
super().port_output(model, node_desc, port_desc)
frame.set_mouse_pressed_fn(lambda x, y, b, _ , m=model, n=node, p=port: b == 1 and self.__on_menu(m, n, p))
```
# Curve Anchors
BezierCurves and Lines have the ability to display a curve anchor, or decoration, that is bound to a specific parametric value on the curve. The widgets that are drawn in the anchor are created in the `anchor_fn` on the FreeBezierCurve or Line. The current parametric (0-1) value where the anchor decoration will be attached is specified with `anchor_position`.
Because there is an interest in attaching some widgets to the curve and drawing them just on top of the curve (a dot, for example), but drawing other widgets, like a floating label decoration, on top of all nodes, the graph drawing is broken up so that connection components can draw into 2 different layers.
## Graph Drawing Layers
The graph is drawn using a ZStack which goes from back to front. It contains these layers:
- **__backdrops_stack** (For backdrops, because they are behind everything.)
- **__connections_under_stack** (All connection curves and anchors directly connected to curves - all above backdrops, but behind nodes. This layer is always used, regardless of the value of `draw_curve_top_layer`.)
- **__nodes_stack** (all nodes)
- **__connections_over_stack** (Meant for floating anchor decorations that should draw above all nodes. Curves drawn here should be transparent, so you don’t see two copies of them - you only see the floating anchor decoration. Only used when `draw_curve_top_layer` is True.)
A `connection()` method in the delegate is equipped with a `foreground` arg, like:
```python
def connection(self, model: GraphModel, source: GraphConnectionDescription, target: GraphConnectionDescription, foreground: bool = False)
```
Using the above drawing layer order as a guide, the design is that in the non-`foreground` mode, the connection curve is drawn normally, and any anchor widgets that should be directly on top of the curve should be drawn with the `anchor_fn` (see `draw_anchor_dot` in the code below). These elements will all show up behind nodes in the graph. In the `foreground` pass, the curve should be drawn transparently (using the style) and any floating widgets that should live in front of all nodes should be drawn with a different `anchor_fn` (see `draw_value_display` in the code below). It should be noted that the `foreground=True` pass of `connection()` doesn’t run at all unless the GraphView has its `draw_curve_top_layer` arg set to True (it’s False by default).
There are 2 things you may have to keep in sync, when using curve anchors in a graph:
1. If you have a FreeBezierCurve representation of a connection when zoomed in, but a FreeLine representation when zoomed out, you will have to make sure any changes to the `anchor_position` in one representation also carry over to the other.
2. If you have both a “dot” anchor widget that is on the curve, as well as a floating decoration, that should stay bound to where the dot is, you need to keep the `anchor_position` for both elements in sync.
Here is some example code from `build_connection` to help with implementing curve anchor decorations:
```python
ANCHOR_ALIGNMENT = ui.Alignment.CENTER
ANCHOR_POS = .25
decoration_label = None
def drag_anchor(curve, x: float, y: float, button, mod):
global ANCHOR_POS
global decoration_label
if curve:
t = curve.get_closest_parametric_position(x, y)
curve.anchor_position = ANCHOR_POS = t
if decoration_label:
decoration_label.text = f"Anchor {ANCHOR_POS:.2f}"
def remove_anchor(curve, x: float, y: float, button, mod):
async def wait_and_turn_off_anchor_frame():
await omni.kit.app.get_app().next_update_async()
curve.set_anchor_fn(None)
if button == 2:
asyncio.ensure_future(wait_and_turn_off_anchor_frame())
def draw_anchor_dot(curve=None):
global ANCHOR_POS
global decoration_label
if curve:
curve.anchor_position = ANCHOR_POS
with ui.VStack(style={"margin": 0}):
```
```python
with ui.VStack(content_clipping=1, style={"margin_height": 22}):
dot = ui.Circle(
# Make sure this alignment is the same as the anchor_alignment
# or this circle won't stick to the curve correctly.
alignment=ANCHOR_ALIGNMENT,
radius=6,
style={"background_color": cl.orange},
size_policy=ui.CircleSizePolicy.FIXED,
)
dot.set_mouse_pressed_fn(partial(remove_anchor, curve))
dot.set_mouse_moved_fn(partial(drag_anchor, curve))
def draw_value_display(curve=None):
global ANCHOR_POS
global decoration_label
if curve:
curve.anchor_position = ANCHOR_POS
with ui.VStack(style={"margin": 0}):
with ui.Placer(stable_size=0, draggable=True, offset_x=0, offset_y=-50):
with ui.ZStack(content_clipping=1):
rect = ui.Rectangle(style={
"background_color": 0xFF773322,
"border_color": cl.white,
"border_width": 2,
})
decoration_label = ui.Label(f"Anchor {ANCHOR_POS:.2f}",
style={"margin": 8, "color": cl.white})
if foreground:
style["color"] = cl.transparent
curve_container_widget = ui.ZStack()
with curve_container_widget:
freeline_widget = ui.FreeLine(
target.widget,
source.widget,
alignment=ui.Alignment.UNDEFINED,
style=style,
name=port_type,
anchor_position=ANCHOR_POS, # both line and curve will use the same value
anchor_alignment=ANCHOR_ALIGNMENT,
visible_max=PORT_VISIBLE_MIN,
style_type_name_override=override_style_name,
)
curve_widget = ui.FreeBezierCurve(
target.widget,
source.widget,
start_tangent_width=ui.Percent(-CONNECTION_CURVE * source_reversed_tangent),
end_tangent_width=ui.Percent(CONNECTION_CURVE * target_reversed_tangent),
name=port_type,
style=style,
anchor_position=ANCHOR_POS,
anchor_alignment=ANCHOR_ALIGNMENT,
visible_min=PORT_VISIBLE_MIN,
style_type_name_override=override_style_name,
)
# Doing this outside the curve creation to be able to pass the curve_widget in as an arg.
if foreground:
freeline_widget.set_anchor_fn(partial(draw_value_display, freeline_widget))
```
```python
if True:
curve_widget.set_anchor_fn(partial(draw_value_display, curve_widget))
else:
freeline_widget.set_anchor_fn(partial(draw_anchor_dot, freeline_widget))
curve_widget.set_anchor_fn(partial(draw_anchor_dot, curve_widget))
freeline_widget.set_tooltip_fn(tooltip)
curve_widget.set_tooltip_fn(tooltip)
return curve_container_widget, freeline_widget, curve_widget
```
This is what that might look like visually: |
Graph%20Model.md | # Graph Model
The graph model is the central component of the graph widget. It is the application’s dynamic data structure, independent of the user interface. It directly manages the data and closely follows the model-view pattern. It defines the interface to be able to interoperate with the components of the model-view architecture.
## GraphModel
GraphModel is the base class for graph model which provides the standard API. It is not supposed to be instantiated directly. Instead, the user subclasses it to create a new model.
The model manages two kinds of data elements. Nodes and Ports are the atomic data elements of the model.
There is no specific Python type for the elements of the model. Since Python has dynamic types, the model can return any object as a node or a port. When the widget needs to get a property of the node, it provides the given node back to the model, e.g.
```python
model[port].name
```
in the delegate to query a port’s name.
Here is a simple model, defining the nodes and ports which are the key elements for a graph, as well as the properties for the element: connections, name and type:
```python
# define the graph root
graph_root = GraphNode("MyGraph")
# define two nodes with different types under the graph root
nodeA = EventNode("Event", graph_root)
graph_root.add_child(nodeA)
nodeB = AnimationNode("Animation", graph_root)
graph_root.add_child(nodeB)
class MyModel(GraphModel):
"""
A simple model derived from GraphModel
"""
@property
def nodes(self, item=None):
# when the node is None, we return the graph level node
if item is None:
return graph_root
# when the input item root, we return all the nodes exist on the current graph
# the return type is a Node list, so the graph nodes are Node type in MyModel
if item == graph_root:
return [child for child in graph_root.children()]
return []
@property
def ports(self, item=None):
# if input is a Node type we return the ports
if isinstance(item, Node):
return item.in_ports + item.out_ports
# if input is a Port type we return the subports of the input port
elif isinstance(item, Port):
return item.children
return []
@property
def name(self, item=None):
# name of the item, item here could either be Node or Port
```
```python
return item.name
@property
def type(self, item):
"""type of the item, the item here could be Node or Port"""
return item.type
@property
def inputs(self, item):
# Node type doesn't have connection
if isinstance(item, Node):
return None
# return all the input port's inputs
if item.is_input:
return item.inputs
return None
@property
def outputs(self, item):
# Node type doesn't have connection
if isinstance(item, Node):
return None
# return all the output port's outputs
if not item.is_input:
return item.outputs
return None
@inputs.setter
def inputs(self, value, item):
# disconnection
if len(value) == 0:
if isinstance(item, Port):
if len(item.inputs) > 0:
item.inputs.clear()
elif len(item.outputs) > 0:
item.outputs.clear()
else:
# when the item is not a Port, but a CompoundNode, it means that we are connecting a port to the Output node of
# a compoundNode. In this case, we need to create a new output port for the node
source = value[0]
if isinstance(item, CompoundNode):
ports = [port.name for port in item.out_ports]
new_port_name = self.get_next_free_name(item, ports, source.name)
new_port = Port(new_port_name, source.type, item)
item.out_ports.append(new_port)
# We are connecting to the new Port
new_port.outputs.append(source)
new_port.node = item
# if the source is a CompoundNode, then we are connection a port to the Input node of a CompoundNode.
# we need to create a new input port
elif isinstance(source, CompoundNode):
ports = [port.name for port in source.in_ports]
new_port_name = self.get_next_free_name(source, ports, item.name)
new_port = Port(new_port_name, item.type, source)
source.in_ports.append(new_port)
# add connection
item.inputs.append(new_port)
new_port.node = source
else:
# do the connection
if item.is_input:
item.inputs.append(source)
else:
item.outputs.append(source)
self._item_changed(None)
# Accessing nodes and properties example
model = MyModel()
```
# query the graph
# The graph/node/port is accessed through evaluation of model[key]. It will
# return the proxy object that redirects its properties back to
# model. So the following line will call MyModel.nodes(None).
graph = model[None].nodes
nodes = model[graph].nodes
for node in nodes:
node_name = model[node].name
node_type = model[node].type
print(f"The model has node {node_name} with type {node_type}")
ports = model[node].ports
for port in ports:
# this will call MyModel.name(port)
port_name = model[port].name
port_type = model[port].type
print(f"The node {node_name} has port {port_name} with type {port_type}")
# prepare data for connection
if port_name == "output:time":
source_port = port
elif port_name == "input:time":
target_port = port
subports = model[port].ports
if subports:
for subport in subports:
subport_name = model[subport].name
subport_type = model[subport].type
print(f"The port {port_name} has subport {subport_name} with type {subport_type}")
# do the connection
if source_port and target_port:
model[target_port].inputs = [source_port]
print(f"There is a connection between {target_port.path} and {source_port.path}")
Here is the result by running the above script in the script editor:
The model has node Event with type Event
The node Event has port input:Default Input with type str
The node Event has port input:Group Input with type group
The port input:Group Input has subport input:child1 with type int
The port input:Group Input has subport input:child2 with type int
The node Event has port output:time with type float
The model has node Animation with type Animation
The node Animation has port input:asset with type asset
The node Animation has port input:time with type float
The node Animation has port output:num_frames with type int
The node Animation has port output:num_skeletons with type int
The node Animation has port output:is_live with type bool
There is a connection between MyGraph:Animation:time and MyGraph:Event:time
Here is a visual representation of the graph in the above example.
Define node and port
===================
The above example is using Node and Port type from
\`\`\`
omni.kit.graph.editor.example.nodes
\`\`\`
. You can of course define your own type of node and port. For example, you can use Usd.Prim as the node type and Usd.Attribute as the port type (e.g. the node and port in
\`\`\`
omni.kit.window.material_graph
\`\`\`
) or you can use Sdf.Path for both node and port types.
The return type from the API of
\`\`\`
def nodes
\`\`\`
defines the node type and
\`\`\`
def ports
\`\`\`
defines the port type. You can map your own class of nodes and ports to graph’s node and port type. A graph can have any number of nodes and a node can have any number of ports. The port can have any number of subports, and further on, subports can have subsubports and so on.
For the above example,
\`\`\`
def nodes
\`\`\`
will return
\`\`\`
MyGraph
\`\`\`
GraphNode when input item is
\`\`\`
None
\`\`\`
, and when the input item is
\`\`\`
MyGraph
\`\`\`
, it will return a list containing
\`\`\`
Event
\`\`\`
and
\`\`\`
Animation
\`\`\`
Nodes.
\`\`\`
def ports
\`\`\`
will return a list containing
\`\`\`
Default Input
\`\`\`
and
\`\`\`
Group Input
\`\`\`
when input item is an
\`\`\`
Event
\`\`\`
node and return a list containing
\`\`\`
child1
\`\`\`
and
\`\`\`
child2
\`\`\`
when input item is
\`\`\`
Group Input
\`\`\`
.
Define connections
===================
The property of inputs and outputs define the connections for graphs. At the moment most of our graphs only support connections between one input and one output. The one side connection (two inputs or two outputs) is also available with more details in the future docs. Let’s take the common case of one input and one output connection as an example: connect Event node’s output time port (source port) with Animation’s input time port (destination port).
When we execute the connection using code (
\`\`\`
model[target_port].inputs = [source_port]
\`\`\`
) or edit the graph to click and drag the source port to connect to the target port,
\`\`\`
inputs.setter
\`\`\`
is called with the input item as the Animation’s input time port and value as a list containing Event node’s output time port in this case. The same happens when we right click to disconnect the connection. During the disconnection, the input value will be empty list
\`\`\`
[]
\`\`\`
During connection, the first thing we do is to check whether it is a disconnection or connection. Then we execute necessary data changes to cache this connection/disconnection.
How does the delegate know that we should have a connection at a port? The answer is the return value from
\`\`\`
inputs
\`\`\`
and
\`\`\`
outputs
\`\`\`
.
# Graph Connections
The `inputs` property returns the input source port for the item port and `outputs` returns the target port for the item port. Take the above connection as an example. Looking at the `MyGraph:Animation:time` port as the input item, `inputs` returns a list containing the Event node’s output time port. And there are no outputs for Animation’s time port, so `outputs` will return None for Animation’s time port. That’s enough to describe a connection between two ports. One might want to define `outputs` for `MyGraph:Event:time` as [MyGraph:Animation:time] and None for `inputs`. Keep your graph upstream or downstream through the whole graph to be consistent.
So if we are using upstream connections, we will see most of the time `outputs` will return None. There are exceptions for the subgraph.
# Subgraph and IsolationGraphModel
To create a subgraph node, just drag and drop a subgraph node into the graph (named Scene Graph in the example). When you double click the subgraph node, you enter the subgraph graph editor, you will see that the navigation bar on the top left has updated to your current graph location. More details about navigation in the Graph Core session.
When you want to expose some attributes from the subgraph and connect to nodes outside of the subgraph, firstly, you need to expose the attributes to the subgraph node. You can create Input nodes to expose inputs and Output nodes to expose outputs. The creation of Input and Output nodes is dealt with by IsolationGraphModel. You can create Inputs/Outputs using `add_input_or_output`.
Once Input/Output nodes are created, you can connect the port you want to expose to the EmptyPort of the Input/Output node. During that, `inputs.setter` is called as a normal connection. The only difference is when you connect to EmptyPort, the port doesn’t exist on the subgraph node, so we need to create the port first then do the connection. That’s the code path of `isinstance(item, CompoundNode)` and `isinstance(source, CompoundNode)` in `inputs.setter`.
Once the attributes are exposed (Default input and child1 from Event as inputs, is_live from Animation as output), you can go back to the MyGraph level by clicking `MyGraph` on the navigation bar. You will see that three ports are created on the Compound node, and then finally, we can connect the exposed port to other nodes, e.g. Debug.is_debug in the above image.
The connection between Animation’s is_live and Compound’s is_live is reflected as the `outputs` return value for Animation’s is_live, since we have no idea about Compound’s is_live attribute until that’s created by the connection.
# GraphModel with batch position
We created a `GraphModelBatchPositionHelper` class to manage batch position processing. For example, moving a backdrop node, multi-selecting a few nodes and moving them together, or moving the current node’s upstream nodes all together, where we need to deal with a collection of positions at the same time.
That’s the reason our SimpleGraphModel from the example extension is inherited both from the GraphModel and GraphModelBatchPositionHelper. GraphModel defines the basic graph data structure and GraphModelBatchPositionHelper allows us to deal with batch position processing much more easily.
## Backdrop
A Backdrop is used to group nodes together to make the graph more organized. Different from subgraphs, it lives on the same level of the nodes placed in the given backdrop. A Backdrop just gives a visual UI group to the nodes. When we move the backdrop, the nodes which are placed in the given backdrop will move together. We leverage GraphModelBatchPositionHelper to do that.
BackdropGetter is defined in `omni.kit.widget.graph` as a helper to get the nodes that are placed in the given backdrop. `BackdropGetter(self, lambda item: self[item].type == "Backdrop")` defines the drive item to be the one has the type of “Backdrop” and returns all the nodes which are placed in the drive item.
We add the function to GraphModelBatchPositionHelper using `self.add_get_moving_items_fn(BackdropGetter(...))` for `batch_position_begin_edit` later to determine which items to move. And `batch_position_end_edit` is used to end the position editing.
## Multi-selection move
This is similar to Backdrop, but the group scheme is using multi-selection instead of Backdrop.
## SelectionGetter
provides a `SelectionGetter` to get all the selected nodes of the given model, corresponding to BackdropGetter.
## Moving Upstream Nodes Together
We provide an example in the `omni.kit.graph.editor.example` such that when you press D and move a node, all the upstreams of the current nodes will move together. This could be useful for organizing your graph faster. It is similar to backdrops and multi-selection, but we need to create a customized `DescendantGetter` ourselves by deriving it from `AbstractBatchPositionGetter`. Again it just returns back all the upstream nodes for the drive node. It acts the same as Backdrop or multi-selection by calling `batch_position_begin_edit` and `batch_position_end_edit`. |
GraphConcepts.md | # Graph Concepts
This article covers core graph concepts found in EF. Readers are encouraged to review the [Execution Framework Overview](#ef-framework) before diving into this article.
![Figure 7: The Execution Framework pipeline. This article covers concepts found in the Execution Graph (IR).](#id1)
The core data structure Execution Framework (EF) uses to describe execution is a *graph of graphs*. Each *graph* contains a [root node](#ef-root-node). The root node can connect to zero or many downstream [nodes](#ef-nodes) via directed [edges](#ef-edges).
Nodes represent work to be executed. Edges represent ordering dependencies between nodes.
![Figure 8: A simple graph.](#ef-fig-simple)
The work each node represents is encapsulated in a [definition](#ef-definition). Each node in the graph may have a pointer to a definition. There are two categories of definitions: [opaque](#ef-opaque-definition) and [graph](#ef-graph-definition).
An *opaque definition* is a work implementation hidden from the framework. An example would be a function pointer.
The second type of definition is another *graph*. Allowing a node’s work definition to be yet another graph is why we say EF’s core execution data structure is a *graph of graphs*.
The top-level container of the *graph of graphs* is called the [execution graph](#ef-execution-graph). The graphs to which individual nodes point are called [graph definitions](#ef-graph-definition) or simply [graphs](#ef-graph-definition).
The following sections dive into each of the topics above with the goal of providing the reader with a general understanding of each of the core concepts in EF’s *graph of graphs*.
## Nodes
Nodes in a [graph](#ef-graph-definition) represent work to be executed. The actual work to be performed is stored in a [definition](#ef-definition), to which a node points.
Nodes can have both parent and child nodes. This relationship between parent and child defines an ordering dependency.
The interface for interacting with nodes is `INode`. EF contains the `NodeT`.
## Nodes
Node implementation of INode for instantiation when constructing graph definitions.
Each node is logically contained within a single graph definition (i.e. INodeGraphDef).
## Edges
Edges represent ordering between nodes in a graph definition. Edges are represented in EF with simple raw pointers between nodes. These pointers can be accessed with INode::getParents() to list nodes that are before a node, and INode::getChildren() to list nodes that are after the node.
## Definitions
Definitions define the work each node represents.
Definitions can be opaque, meaning EF has no visibility into the actual work being performed. Opaque definitions implement the INodeDef interface. Helper classes, like NodeDefLambda exists to easily wrap chunks of code into an opaque definition.
Definitions can also be defined with a graph, making the definitions transparent. The transparency of graph definitions enables EF to perform many optimizations such as:
- Execute nodes in the graph in parallel
- Optimize the graph for the current hardware environment
- Reorder/Defer execution of nodes to minimize lock contention
Many of these optimizations are enabled by writing custom passes and executors. See Pass Creation and Executor Creation for details.
Graph definitions are defined by the INodeGraphDef interface. During graph construction, it is common for IPass authors to instantiate custom graph definitions to bridge EF with the authoring layer. The NodeGraphDef class is designed to help implement these custom definitions.
Definition instances are not unique to each node. Definitions are designed to be shared between multiple nodes. This means two different INode instances are free to point to the same definition instance. This not only saves space, it also decreases graph construction time.
Above we see the graph from Figure 8, but now with pointers to definitions (dashed lines). Notice how definitions are shared between nodes. Furthermore, notice that nodes in graph definitions can point to other graph definitions.
Both INodeDef and NodeGraphDef classes are designed to help implement these custom definitions.
## Definitions
`INodeDef` (i.e. opaque definitions) and `INodeGraphDef` (i.e. graph definitions) inherit from the `IDef` interface. All user definitions must implement either `INodeDef` or `INodeGraphDef`.
Definitions are attached to nodes and can be accessed with `INode::getDef()`. Note, a node is not required to have a definition. In fact, each graph’s root node will not have an attached definition.
## Execution Graph
The top-level container for execution is the *execution graph*. The execution graph is special. It is the only entity, other than a node, that can contain a definition. In particular, the execution graph always contains a single graph definition. It is this graph definition that is the actual *graph of graphs*. The execution graph does not contain nodes, rather, it is the execution graph’s definition that contains nodes.
In addition to containing the top-level graph definition, the execution graph’s other jobs are to track:
- If the graph is currently being constructed
- Gross changes to the topologies in the execution graph. See invalidation for details.
The execution graph is defined by the `IGraph` interface. EF contains the `Graph` implementation of `IGraph` for applications to instantiate.
## Topology
Each graph definition owns a *topology* object. Each topology object is owned by a single graph definition.
The topology object has several tasks:
- Owns and provides access to the root node
- Assigns each node in the graph definition an unique index
- Handles and tracks invalidation of the topology (via stamps)
Topology is defined by the `ITopology` interface and accessed via `INodeGraphDef::getTopology()`.
## Root Nodes
Each graph definition contains a topology which owns a *root node*. The root node is where traversal in a graph definition starts. Only descendants of the root node will be traversed.
The root node is accessed with `INodeGraphDef::getTopology()`.
# 图概念概述
`ITopology::getRoot()` 的使用在图定义的构建过程中经常被观察到。
根节点在图定义中是特殊的,因为它们没有附带的定义,尽管图定义的执行器可能会赋予根节点特殊的含义。
根节点通过 `INode` 接口定义,就像任何其他节点一样。
每个图定义(实际上是图定义的拓扑)都有一个根节点。这意味着在EF中存在许多根节点(即EF是一个图的图)。
# 下一步
本文提供了图概念的概述。要了解这些概念如何在图构建过程中被利用,请继续阅读关于 [Pass Concepts](#ef-pass-concepts) 的文章。 |
GraphEditors.md | # Visual Graph Editors
After creating an OmniGraph through scripting or Create -> Visual Scripting you can open up an editor in which you can view and edit the graph through the Window -> Visual Scripting.
The difference between the editors offered is that each is tailored to a graph with a specific type of evaluation; one for an Action Graph and the Generic Graph which applies to either a Push Graph or a Lazy Graph. The basic authoring operations in either one are very similar.
After opening the graph editor you will be offered the choice of editing an existing graph or creating a new one.
After selecting or creating a new graph you can edit it in a variety of ways. The basic view of a graph with nodes will look something like this:
See the online documentation for more details on how you can further interact with the graph editor. |
GraphInvalidation.md | # Graph Invalidation
This is an advanced Execution Framework topic. It is recommended you first review the
Execution Framework Overview along with basic topics such as Graphs Concepts, Pass Concepts, and Execution Concepts.
EF employs a fast, efficient, and lazy invalidation scheme to detect changes in the execution graph. In this article, we cover how a graph is invalidated, how it is marked valid, and the various entities used for invalidation.
## Stamps
The heart of the invalidation system are EF’s stamps.
Stamps track the state/version of a resource. Stamps are implemented as an unsigned number. If the state of a resource changes, the stamp is incremented.
Stamps are broken into two parts.
The first part is implemented by the `Stamp` class. As a resource changes, `Stamp::next()` is called to denote the new state of the resource. `Stamp` objects are owned by the resource they track.
The second part of stamps is implemented by the `SyncStamp` class. `SyncStamp` tracks/synchronizes to the state of a `Stamp`. `SyncStamp` objects are owned by the entities that wish to utilize the mutating resource.
See `Stamp`’s documentation for further details.
EF makes extensive use of stamps to detect changes in pass registration, graph topology, and graph construction.
## Invalidating a Graph
## Graph invalidation starts with a call to
`ITopology::invalidate()`
.
`ITopology`
objects are owned by
graph definitions
. Therefore, a call to
`ITopology::invalidate()`
is equivalent to saying “this
definition
is no longer valid.”
Unlike some other invalidation schemes, the call to
`ITopology::invalidate()`
is cheap. If the
topology
is already invalid (i.e.
`ITopology::invalidate()`
has previously been called and the
topology
has not yet be rebuilt), invalidation exits early. Otherwise, the topology’s
stamps
is incremented and the invalidation is “forwarded” to a list of registered listeners.
This forwarding process may sound expensive. In practice, it is not for the following reasons:
- As previously mentioned,
`ITopology::invalidate()`
detects spurious invalidations and performs an early exit.
- Invalidation forwarders do not immediately react to the invalidation (i.e. they do not immediately rebuild the
graph
). Rather, they are designed to note the invalidation and handle it later. For example, rebuilding a graph definition is delayed until the start of the next execution of the
execution graph
.
- Usually only a single listener is registered per-
graph definition
. That listener does not forward the invalidation.
The single invalidation forwarder mentioned above notifies the top-level execution graph (e.g.
`IGraph`
) that something within the graph has become invalid. It does this by incrementing the execution graph’s
global topology stamp
via
`IGraph::getGlobalTopologyStamp()`
.
## Global Topology Stamp
The top-level
`IGraph`
object’s global topology
stamps
tracks the validity of all
topologies
within all
graph definitions
in the
execution graph
. The
stamps
is incremented each time a graph definition’s topology is invalidated.
Use of this stamp usually falls into two categories.
The first category is cache invalidation. As an example,
`IExecutionContext`
uses the global topology stamp to determine if its cached list of traversed node paths is still valid.
The second category is detecting if the execution graph should be rebuilt.
`IPassPipeline`
uses the global topology
stamp to determine if the
pipeline’s passes should run. These passes traverse the entire execution graph, looking for graph definition’s whose topology is invalid.
This rebuild process is not a full rebuild of the execution graph. Rather, because invalidation is tracked at the graph definition level, only those definitions that have been invalidated need to be rebuilt.
Graph construction is covered in detail in Pass Concepts.
## Making a Graph Valid
The ITopology object stored in each graph definition (e.g. INodeGraphDef) has the concept of validity. The topology is marked invalid with ITopology::invalidate(). ITopology::invalidate() is often called by the authoring layer. For example, OmniGraph will call ITopology::invalidate() when a user connects two nodes.
The validity of a topology can be checked with ITopology::isValid(). ITopology::isValid() is often used during graph construction to determine if a graph definition needs to be rebuilt.
One of the ITopology object’s jobs is to store and provide access to the root node of the definition. ITopology::isValid() works by checking if the root node’s SyncStamp is synchronized with the topology’s Stamp.
Once ITopology::invalidate() is called, the topology’s root node stamp will be out-of-sync until INode::validateOrResetTopology() is called on the root node. INode::validateOrResetTopology() is called during graph construction, usually by IGraphBuilder::connect.
```cpp
IGraphBuilder::connect(INode*,
INode*)
```
when the root node is connected to a downstream node. In some cases, nothing connects to the root node and it is up to the IPass (usually via the constructed graph definition) to call INode::validateOrResetTopology() on the root node.
Graph construction is covered in detail in Pass Concepts. |
GraphTraversalAdvanced.md | # Graph Traversal In-Depth
This is an advanced Execution Framework topic. It is recommended you first review the [Execution Framework Overview](Overview.html#ef-framework) along with basic topics such as [Graphs Concepts](GraphConcepts.html#ef-graph-concepts), [Pass Concepts](PassConcepts.html#ef-pass-concepts), and [Execution Concepts](ExecutionConcepts.html#ef-execution-concepts).
As was mentioned in the [Graph Traversal Guide](GraphTraversalGuide.html#ef-graph-traversal-guide), **graph traversal** is an essential component of EF. It brings dynamism to an otherwise-static representation of a runtime environment, allowing for fine-tuned decision-making when it comes to how the IR is constructed, populated, transformed, and eventually evaluated. Although traversals can occur at any point in time, typically (and perhaps most importantly) they are employed during graph construction (see [Pass Concepts](PassConcepts.html#ef-pass-concepts)) and execution (see [Execution Concepts](ExecutionConcepts.html#ef-execution-concepts)).
In order to form a practical and functional understanding of how graph traversal works, especially in regards to its applications in EF, this document will build upon the example traversals highlighted in the [Graph Traversal Guide](GraphTraversalGuide.html#ef-graph-traversal-guide) by introducing various key definitions and methodologies underpinning the subject as a whole and tying the learnings together to explore their most significant utilizations in EF.
> For the purposes of this discussion, we will only deal with connected, cyclic, directed, simple graphs permitting loops – since those are the IR’s characteristics – and whenever the term graph is used generally one can assume that the aforementioned qualifiers apply, unless explicitly stated otherwise.
## Core Search Algorithms
Although there exist myriad different approaches to graph traversal, this section will focus on the so-called **depth-first search (DFS)** and **breadth-first search (BFS)** techniques, which tend to be the most popular thanks to their versatility and relative simplicity.
As can be seen in [Getting Started with Writing Graph Traversals](GraphTraversalGuide.html#getting-started-with-writing-graph-traversals) and [Serial vs. Parallel Graph Traversal](#graph-traversal-apis), EF fully implements and exposes these algorithms on the API level to external developers so that the root logic doesn’t have to be rewritten on a per-user basis. These methods also come wrapped with [other important functionality related to visit strategies](#visitation-strategies) that will be explained later; for this reason, we relegate highlighting the API methods themselves for [a later section](#graph-traversal-apis), after [Visitation Strategies](#visitation-strategies).
are covered. For the time being, we’ll instead delve into a more conceptual, non-EF-specific overview of these algorithms.
To facilitate this higher-level conversation, here we introduce the following connected, directed, acyclic graph \(G_2\):
Note
====
1. The individual edge members are ordered from tail to head, e.g. \(\{a, b\}\) is directed from the upstream node \(a\) to the downstream node \(b\).
2. For clarity’s sake, edges are ordered based on the node letterings’ place in the alphabet (similar to \(G_1\)), e.g. \(\{a, b\}\) and \(\{a, c\}\) are the first and second edges protruding off of node \(a\). This in turn implies that nodes \(b\) and \(c\) are the first and second children of \(a\), respectively. These orders are also numbered explicitly on the figure itself.
Depth-First Search (DFS)
========================
Starting at a given node, DFS will recursively visit all of the node’s children. This effectively leads to DFS exploring as far as possible downstream along a connected branch, marking nodes along the way as having been visited, until it hits a dead end (usually defined as either reaching a node with no children or a node that has already been visited), before backtracking to a previous node that still has open avenues for exploration. The search continues until all nodes in the graph have been visited.
As an example, suppose that we were to start a DFS at node \(a \in G_2\) and chose to enter nodes along the first available edge (an important distinction to make, which is more fully addressed in Visitation Strategies). For simplicity’s sake, let us further assume that we perform the search in a serial fashion. Play through the following interactive animation to see what the resultant traversal and ordered set of visited nodes/edges (which, when combined, form a depth-first search tree, highlighted in blue at the end) would look like:
Note
====
Spread throughout this document are a series of interactive animations that show different traversals over various graphs in a step-by-step fashion. Some key points to consider:
1. To move forward one step, press the `>` button. To move back one step, press the `<` button.
2. To fast-forward to the final, fully-traversed graph, press the `>>` button. To go back to the start, press the `<<` button.
3. The nodes/edges that have not been visited are colored in black.
4. The nodes/edges that are currently being attempted to be visited are colored in yellow.
5. The nodes/edges that have been successfully visited are colored in blue.
6. The nodes that fail to be visited along a specific edge will glow red momentarily before returning to their initial color, while the corresponding edge will remain red (highlighting that we were not able to enter said node along that now-red edge).
1
2
1
2
1
3
1
2
1
2
a
b
c
d
e
f
g
h
i
𝐺
2
<!--Buttons-->
<g onclick=" onClickGoToStart1(this)" onmousedown="onMouseDown1(this)" onmouseleave="onMouseLeave1(this)" onmouseover="onMouseOver1(this)" onmouseup="onMouseUp1(this)">
<path d="M508 800C508 795.582 511.582 792 516 792L548 792C552.418 792 556 795.582 556 800L556 832C556 836.418 552.418 840 548 840L516 840C511.582 840 508 836.418 508 832Z" fill="#FFFFFF" fill-rule="evenodd" stroke="#C55A11" stroke-miterlimit="8" stroke-width="4" transform="translate(-206.15 0)">
</path>
<text class="noselect" fill="#C55A11" font-family="NVIDIA Sans,NVIDIA Sans_MSFontService,sans-serif" font-size="16" font-weight="700" transform="translate(316.183 821)">
<<
</text>
</g>
<g onclick=" onClickBackward1(this)" onmousedown="onMouseDown1(this)" onmouseleave="onMouseLeave1(this)" onmouseover="onMouseOver1(this)" onmouseup="onMouseUp1(this)">
<path d="M580 800C580 795.582 583.582 792 588 792L620 792C624.418 792 628 795.582 628 800L628 832C628 836.418 624.418 840 620 840L588 840C583.582 840 580 836.418 580 832Z" fill="#FFFFFF" fill-rule="evenodd" stroke="#C55A11" stroke-miterlimit="8" stroke-width="4" transform="translate(-206.15 0)">
</path>
<text class="noselect" fill="#C55A11" font-family="NVIDIA Sans,NVIDIA Sans_MSFontService,sans-serif" font-size="16" font-weight="700" transform="translate(393.017 821)">
<
</text>
</g>
<g onclick=" onClickForward1(this)" onmousedown="onMouseDown1(this)" onmouseleave="onMouseLeave1(this)" onmouseover="onMouseOver1(this)" onmouseup="onMouseUp1(this)">
<path d="M652 800C652 795.582 655.582 792 660 792L692 792C696.418 792 700 795.582 700 800L700 832C700 836.418 696.418 840 692 840L660 840C655.582 840 652 836.418 652 832Z" fill="#FFFFFF" fill-rule="evenodd" stroke="#C55A11" stroke-miterlimit="8" stroke-width="4" transform="translate(-206.15 0)">
</path>
<text class="noselect" fill="#C55A11" font-family="NVIDIA Sans,NVIDIA Sans_MSFontService,sans-serif" font-size="16" font-weight="700" transform="translate(465.017 821)">
>
</text>
</g>
<g onclick=" onClickGoToEnd1(this)" onmousedown="onMouseDown1(this)" onmouseleave="onMouseLeave1(this)" onmouseover="onMouseOver1(this)" onmouseup="onMouseUp1(this)">
<path d="M724 800C724 795.582 727.582 792 732 792L764 792C768.418 792 772 795.582 772 800L772 832C772 836.418 768.418 840 764 840L732 840C727.582 840 724 836.418 724 832Z" fill="#FFFFFF" fill-rule="evenodd" stroke="#C55A11" stroke-miterlimit="8" stroke-width="4" transform="translate(-206.15 0)">
</path>
<text class="noselect" fill="#C55A11" font-family="NVIDIA Sans,NVIDIA Sans_MSFontService,sans-serif" font-size="16" font-weight="700" transform="translate(532.183 821)">
>>
</text>
</g>
<style id="dynamicStyles1">
/*Center the SVG*/
#efGraphTraversalAnim01 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
</style>
<script type="text/javascript">
//<![CDATA[
let dynamicStyle1 = document.getElementById("dynamicStyles1");
// Dynamic CSS. Allows us to alter certain CSS parameters
// at runtime by completely rebuilding it.
function createCssDynamicTextContent1(nodeIdx, edgeIdx, colors, fillMode, animDir) {
return `
:root {
--node-fill-default-color: ${colors["nodeDefaultFillColor"]};
--node-stroke-default-color: ${colors["nodeDefaultStrokeColor"]};
--edge-default-color: ${colors["edgeDefaultColor"]};
--visit-try-color: ${colors["visitTryColor"]};
--visit-success-color: ${colors["visitSuccessColor"]};
--visit-failure-color: ${colors["visitFailureColor"]};
}
/*Edge Animation Keyframes*/
@keyframes edge_visit_try {
0% {
fill: var(--edge-default-color);
}
100% {
fill: var(--visit-try-color);
}
}
@keyframes edge_visit_success {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes edge_visit_failure {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-failure-color);
}
}
/*Edge Animations*/
.edges1:nth-child(${edgeIdx}).visitTry>path {
animation: edge_visit_try 0.5s ease ${fillMode} ${animDir};
}
.edges1:nth-child(${edgeIdx}).visitSuccess>path {
animation: edge_visit_success 0.5s ease ${fillMode} ${animDir};
}
.edges1:nth-child(${edgeIdx}).visitFailure>path {
animation: edge_visit_failure 1s ease ${fillMode} ${animDir};
}
/*Node Animation Keyframes*/
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--visit-success-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes1.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes1.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes1.visitSuccess:nth-child(${nodeIdx})>path {
animation: node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes1.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes1.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim01 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
}
</script>
```javascript
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
```
```javascript
// Establishes the exact node/edge traversal ordering.
const nodesAndEdgesOrdering1 = [
[["a1", "node", "try"]],
[["a1", "node", "success"]],
[["ab1", "edge", "try"], ["b1", "node", "try"]],
[["ab1", "edge", "success"], ["b1", "node", "success"]],
[["bd1", "edge", "try"], ["d1", "node", "try"]],
[["bd1", "edge", "success"], ["d1", "node", "success"]],
[["df1", "edge", "try"], ["f1", "node", "try"]],
[["df1", "edge", "success"], ["f1", "node", "success"]],
[["fi1", "edge", "try"], ["i1", "node", "try"]],
[["fi1", "edge", "success"], ["i1", "node", "success"]],
[["dg1", "edge", "try"], ["g1", "node", "try"]],
[["dg1", "edge", "success"], ["g1", "node", "success"]],
[["dh1", "edge", "try"], ["h1", "node", "try"]],
[["dh1", "edge", "success"], ["h1", "node", "success"]],
[["ac1", "edge", "try"], ["c1", "node", "try"]],
[["ac1", "edge", "success"], ["c1", "node", "success"]],
[["cd1", "edge", "try"], ["d1", "node", "try"]],
[["cd1", "edge", "failure"], ["d1", "node", "failure"]],
[["ce1", "edge", "try"], ["e1", "node", "try"]],
[["ce1", "edge", "success"], ["e1", "node", "success"]],
[["eh1", "edge", "try"], ["h1", "node", "try"]],
[["eh1", "edge", "failure"], ["h1", "node", "failure"]],
[["ei1", "edge", "try"], ["i1", "node", "try"]],
[["ei1", "edge", "failure"], ["i1", "node", "failure"]],
];
// Node + edge colors.
const nodeAndEdgeColors1 = {
"nodeDefaultFillColor": "#000000",
"nodeDefaultStrokeColor": "#000000",
"edgeDefaultColor": "#000000",
"visitTryColor": "#FFD100",
"visitSuccessColor": "#005593",
"visitFailureColor": "#BB1E10",
};
// Button state colors.
const buttonDefaultColor1 = "#FFFFFF";
const buttonHoverColor1 = "#BFBFBF";
const buttonDownColor1 = "#7F7F7F";
let cnt1 = -1;
function onClickGoToStart1(buttonElement) {
// Reset counter to start.
cnt1 = -1;
// Reset all edges to their initial state color, and remove all anim-related classes.
const edges = document.getElementById("edges1");
for (const edge of edges.children) {
edge.classList.value = "edges1";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
}, { once: true });
}
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes1");
for (const node of nodes.children) {
node.classList.value = "nodes1";
const path = node.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}, { once: true });
}
}
function onClickBackward1(buttonElement) {
if (cnt1 < 0) {
return;
}
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering1[cnt1];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges1" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges1" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges1");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle1.innerHTML = createCssDynamicTextContent1(0, edgeIdx, nodeAndEdgeColors1, "backwards", "reverse");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing from "try", we want to go back to the default edge color
// (since no single edge will be traversed more than once, so it's guaranteed
// that this is the first time that the current edge was iterated over).
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
// When reversing from "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["edgeDefaultColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
}
}
}
```
```javascript
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes1" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes1" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes1");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle1.innerHTML = createCssDynamicTextContent1(nodeIdx, prevEdgeIdx, nodeAndEdgeColors1, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// "try" was the first-ever for the given node (i.e. checking the
// node's fill color).
if (status == "try") {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
node.classList.add("visitTryAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes1";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
node.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
node.classList.add("visitFailureAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
node.classList.add("visitFailureUnfilled");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
```
```javascript
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
}
}
}
cnt1 -= 1;
}
function onClickForward1(buttonElement) {
if (cnt1 >= nodesAndEdgesOrdering1.length - 1) {
return;
}
cnt1 += 1;
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering1[cnt1];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges1" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges1" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges1");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle1.innerHTML = createCssDynamicTextContent1(0, edgeIdx, nodeAndEdgeColors1, "both", "normal");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitTryColor"]);
edge.classList.value = "edges1";
}, { once: true });
} else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
edge.classList.value = "edges1";
}, { once: true });
} else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
edge.classList.value = "edges1";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
edge.classList.value = "edges1";
}, { once: true });
}
} else if (type == "node") {
// Get the "nodes1" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes1" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes1");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle1.innerHTML = createCssDynamicTextContent1(nodeIdx, prevEdgeIdx, nodeAndEdgeColors1, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
// Set the node animation based on whether or not it has already
// been successfully visited (i.e. its fill color).
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
node.classList.add("visitTryAlreadyVisited");
} else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitTryColor"]);
node.classList.value = "nodes1";
}, { once: true });
} else if (status == "success") {
node.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
node.classList.value = "nodes1";
}, { once: true });
}
}
}
}
```
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
node.classList.value = "nodes1";
}, { once: true });
}
else if (status == "failure") {
// Set the node's stroke color based on whether or not it has already
// been successfully visited (i.e. its fill color).
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
node.classList.add("visitFailureAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
node.classList.add("visitFailureUnfilled");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes1";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors1["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors1["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors1["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes1";
}, { once: true });
}
}
function onClickGoToEnd1(buttonElement) {
// Set counter to end.
cnt1 = nodesAndEdgesOrdering1.length - 1;
for (let i = 0; i < nodesAndEdgesOrdering1.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering1[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
if (status == "try") {
continue;
}
// Set all elements to their final colors.
if (type == "edge") {
element.classList.add("edges1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
}
}, { once: true });
element.addEventListener("animationcancel", () => {
if (type == "edge") {
element.classList.add("edges1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors1["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes1");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors1["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors1["visitSuccessColor"]);
}
}
}, { once: true });
}
}
}
function onMouseDown1(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor1);
}
function onMouseUp1(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
```javascript
buttonPathElement.setAttribute("fill", buttonHoverColor1);
}
function onMouseOver1(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor1);
}
function onMouseLeave1(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDefaultColor1);
}
//]]>
</script>
```
Make sure to read
- Print all Node Names
- Print all Node Traversal Paths Recursively
- Print all Node Names Recursively in Topological Order
- Using Custom NodeUserData
- Store and Print all Node Names Concurrently
for traversal samples that utilize
- DFS.
## Breadth-First Search (BFS)
Starting at a given node, BFS will first visit all children of the current node before exploring any other nodes that lie further downstream. Like DFS, this process will continue until all nodes in the graph have been discovered.
As an example, suppose that we were to start a BFS at node \(a \in G_2\) and chose to enter nodes along the first available edge (similar to the DFS example above). As in the previous example, we’ll be assuming a serial traversal. The resultant exploration and ordered set of visited nodes/edges (which, when combined, form a breadth-first search tree, highlighted in blue at the end) would look like this:
𝐺
2
a
b
c
d
e
f
g
h
i
<<
<
>
>>
```javascript
// Dynamic CSS. Allows us to alter certain CSS parameters
// at runtime by completely rebuilding it.
function createCssDynamicTextContent2(nodeIdx, edgeIdx, colors, fillMode, animDir) {
return `
:root {
--node-fill-default-color: ${colors["nodeDefaultFillColor"]};
--node-stroke-default-color: ${colors["nodeDefaultStrokeColor"]};
--edge-default-color: ${colors["edgeDefaultColor"]};
--visit-try-color: ${colors["visitTryColor"]};
--visit-success-color: ${colors["visitSuccessColor"]};
--visit-failure-color: ${colors["visitFailureColor"]};
}
/*Edge Animation Keyframes*/
@keyframes edge_visit_try {
0% {
fill: var(--edge-default-color);
}
100% {
fill: var(--visit-try-color);
}
}
@keyframes edge_visit_success {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes edge_visit_failure {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-failure-color);
}
}
/*Edge Animations*/
.edges2:nth-child(${edgeIdx}).visitTry>path {
animation: edge_visit_try 0.5s ease ${fillMode} ${animDir};
}
.edges2:nth-child(${edgeIdx}).visitSuccess>path {
animation: edge_visit_success 0.5s ease ${fillMode} ${animDir};
}
.edges2:nth-child(${edgeIdx}).visitFailure>path {
animation: edge_visit_failure 1s ease ${fillMode} ${animDir};
}
/*Node Animation Keyframes*/
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--visit-success-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes2.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes2.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes2.visitSuccess:nth-child(${nodeIdx})>path {
animation: node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes2.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes2.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim02 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
`;
}
// Establishes the exact node/edge traversal ordering.
const nodesAndEdgesOrdering2 = [
[["a2", "node", "try"]],
[["a2", "node", "success"]],
[["ab2", "edge", "try"], ["b2", "node", "try"]],
[["ab2", "edge", "success"], ["b2", "node", "success"]],
[["ac2", "edge", "try"], ["c2", "node", "try"]],
[["ac2", "edge", "success"], ["c2", "node", "success"]],
[["bd2", "edge", "try"], ["d2", "node", "try"]],
[["bd2", "edge", "success"], ["d2", "node", "success"]],
[["cd2", "edge", "try"], ["d2", "node", "try"]],
[["cd2", "edge", "failure"], ["d2", "node", "failure"]],
[["ce2", "edge", "try"], ["e2", "node", "try"]],
[["ce2", "edge", "success"], ["e2", "node", "success"]],
[["df2", "edge", "try"], ["f2", "node", "try"]],
[["df2", "edge", "success"], ["f2", "node", "success"]],
[["dg2", "edge", "try"], ["g2", "node", "try"]],
[["dg2", "edge", "success"], ["g2", "node", "success"]],
[["dh2", "edge", "try"], ["h2", "node", "try"]],
[["dh2", "edge", "success"], ["h2", "node", "success"]],
[["eh2", "edge", "try"], ["h2", "node", "try"]],
[["eh2", "edge", "failure"], ["h2", "node", "failure"]],
[["ei2", "edge", "try"], ["i2", "node", "try"]],
[["ei2", "edge", "success"], ["i2", "node", "success"]],
[["fi2", "edge", "try"], ["i2", "node", "try"]],
[["fi2", "edge", "failure"], ["i2", "node", "failure"]],
];
// Node + edge colors.
const nodeAndEdgeColors2 = {
"nodeDefaultFillColor": "#000000",
"nodeDefaultStrokeColor": "#000000",
"edgeDefaultColor": "#000000",
"visitTryColor": "#FFD100",
"visitSuccessColor": "#005593",
"visitFailureColor": "#BB1E10",
};
// Button state colors.
const buttonDefaultColor2 = "#FFFFFF";
const buttonHoverColor2 = "#BFBFBF";
const buttonDownColor2 = "#7F7F7F";
let cnt2 = -1;
function onClickGoToStart2(buttonElement) {
// Reset counter to start.
cnt2 = -1;
// Reset all edges to their initial state color, and remove all anim-related classes.
const edges = document.getElementById("edges2");
for (const edge of edges.children) {
edge.classList.value = "edges2";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
}, { once: true });
}
}
```
```javascript
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes2");
for (const node of nodes.children) {
node.classList.value = "nodes2";
const path = node.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}, { once: true });
}
function onClickBackward2(buttonElement) {
if (cnt2 < 0) {
return;
}
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering2[cnt2];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges2" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges2" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges2");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle2.innerHTML = createCssDynamicTextContent2(0, edgeIdx, nodeAndEdgeColors2, "backwards", "reverse");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing from "try", we want to go back to the default edge color
// (since no single edge will be traversed more than once, so it's guaranteed
// that this is the first time that the current edge was iterated over).
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["edgeDefaultColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
// When reversing from "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes2" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes2" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes2");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle2.innerHTML = createCssDynamicTextContent2(nodeIdx, prevEdgeIdx, nodeAndEdgeColors2, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// "try" was the first-ever for the given node (i.e. checking the
// node's fill color).
if (status == "try") {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
node.classList.add("visitTryAlreadyVisited");
}
}
}
}
}
```
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes2";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
node.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
node.classList.add("visitFailureAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
node.classList.add("visitFailureUnfilled");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
}
}
cnt2 -= 1;
function onClickForward2() {
if (cnt2 >= nodesAndEdgesOrdering2.length - 1) {
return;
}
cnt2 += 1;
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering2[cnt2];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges2" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges2" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges2");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle2.innerHTML = createCssDynamicTextContent2(0, edgeIdx, nodeAndEdgeColors2, "both", "normal");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["nodeDefaultFillColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
}
}
}
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
edge.classList.value = "edges2";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
edge.classList.value = "edges2";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes2" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes2" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes2");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle2.innerHTML = createCssDynamicTextContent2(nodeIdx, prevEdgeIdx, nodeAndEdgeColors2, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
// Set the node animation based on whether or not it has already
// been successfully visited (i.e. its fill color).
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
node.classList.add("visitTryAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-relatad classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors2["visitTryColor"]);
node.classList.value = "nodes2";
}, { once: true });
}
else if (status == "success") {
node.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
node.classList.value = "nodes2";
}, { once: true });
}
else if (status == "failure") {
// Set the node's stroke color based on whether or not it has already
// been successfully visited (i.e. its fill color).
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
node.classList.add("visitFailureAlreadyVisited");
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
node.classList.add("visitFailureUnfilled");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes2";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (path.getAttribute("fill") == nodeAndEdgeColors2["visitSuccessColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
else if (path.getAttribute("fill") == nodeAndEdgeColors2["nodeDefaultFillColor"]) {
path.setAttribute("stroke", nodeAndEdgeColors2["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes2";
}, { once: true });
```javascript
function onClickGoToEnd2(buttonElement) {
// Set counter to end.
cnt2 = nodesAndEdgesOrdering2.length - 1;
for (let i = 0; i < nodesAndEdgesOrdering2.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering2[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
if (status == "try") {
continue;
}
// Set all elements to their final colors.
if (type == "edge") {
element.classList.add("edges2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
}
}, { once: true });
element.addEventListener("animationcancel", () => {
if (type == "edge") {
element.classList.add("edges2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors2["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes2");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors2["visitSuccessColor"]);
path.setAttribute("stroke", nodeAndEdgeColors2["visitSuccessColor"]);
}
}
}, { once: true });
}
}
}
function onMouseDown2(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor2);
}
function onMouseUp2(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor2);
}
function onMouseOver2(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor2);
}
function onMouseLeave2(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDefaultColor2);
}
```
Make sure to read
Print all Edges Recursively
for traversal samples that utilize
BFS
.
## Visitation Strategies
Thus far many of our examples have asserted that we’d enter
nodes
on the
first available
edge
, i.e. we would always visit a
node
via the first connected
edge
that we happened to traverse over, regardless of whether or not the
node
in question also has other entrance avenues. This doesn’t always have to be the case, however, and some situations will
force
us to utilize different sets of criteria when determining when a
node
should be entered during exploration (see
Print all Node Names Recursively in Topological Order
for a concrete example). The relevant decision-making logic is encoded in so-called
visitation strategies
, which are policies passed down to traversal algorithms that inform the latter of specific conditions that must be met prior to entering a
node
. Although developers are free to write their own visit strategies, the three most commonly-used ones –
```
VisitFirst, VisitLast, and VisitAll – have already been implemented and made available through the API.
Note that the visit strategies presented below are templated to utilize a transient set of per-node-specific data `NodeData` that, among other information, tracks the number of node visits via a `visitCount` variable. This data structure is only meant to exist for the duration of the graph traversal.
### VisitFirst Strategy
The VisitFirst strategy allows for a given node to be entered the first time that it is discovered, i.e., along the first available edge. This is the formal name given to the strategy employed in the DFS and BFS examples in the Next Steps section.
The implementation looks like this:
#### Listing 50
VisitFirst strategy implementation.
```cpp
//! Traversal strategy that enters the node when it was first time discovered
struct VisitFirst
{
//! Call to traverse the graph with a strategy to visit only when first time discovered
template <typename Node, typename NodeData>
static VisitOrder tryVisit(Node* node, NodeData& nodeData)
{
auto lastVisit = nodeData.visitCount++; // read+increment only once. other threads can be doing the same.
return (lastVisit == 0) ? VisitOrder::eFirst : VisitOrder::eUnknown;
}
};
```
Here’s an animated example of a serial DFS through graph \(G_1\) that employs the VisitFirst strategy:
Execution Graph
NodeGraphDef
𝐺
1
has associated executor type
a
b
0/1
c
0/1
d
0/1
e
Node e
NodeGraphDef
X
0/1
Node f
NodeGraphDef
Y
0/1
g
0/1
h
i
0/1
j
0/1
k
l
0/1
Node m
NodeGraphDef
X
0/1
h
i
0/1
j
0/1
Root is a special node used to discover the entire topology.
Root
Node
Def
NodeGraph
Def
Each node in topology has one of two execution definition types.
<!--Buttons-->
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes filled_node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success {
0% {
stroke: var(--visit-try-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success_text {
0% {
fill: var(--node-stroke-default-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes3.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes3.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes3.filledVisitSuccess:nth-child(${nodeIdx})>path {
animation: filled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
/*Apply animation to the path that draws the circle*/
.nodes3.unfilledVisitSuccess:nth-child(${nodeIdx})>path {
animation: unfilled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
/*Apply animation to all other child elements of the node, which is just text.*/
.nodes3.unfilledVisitSuccess:nth-child(${nodeIdx})>text {
animation: unfilled_node_visit_success_text 0.5s ease ${fillMode} ${animDir};
}
.nodes3.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes3.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim03 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
```
// Establishes the exact node/edge traversal ordering.
const nodesAndEdgesOrdering = [
[["a3", "node", "try", "1"]],
[["a3", "node", "success"]],
[["ab3", "edge", "try"], ["b3", "node", "try", "1"]],
[["ab3", "edge", "success"], ["b3", "node", "success"]],
[["be3", "edge", "try"], ["e3", "node", "try", "1"]],
[["be3", "edge", "success"], ["e3", "node", "success"]],
[["h13", "node", "try", "1"]],
[["h13", "node", "success"]],
[["h1i13", "edge", "try"], ["i13", "node", "try", "1"]],
[["h1i13", "edge", "success"], ["i13", "node", "success"]],
[["i1j13", "edge", "try"], ["j13", "node", "try", "1"]],
[["i1j13", "edge", "success"], ["j13", "node", "success"]],
[["j1i13", "edge", "try"], ["i13", "node", "try", "2"]],
[["j1i13", "edge", "failure"], ["i13", "node", "failure"]],
[["eg3", "edge", "try"], ["g3", "node", "try", "1"]],
[["eg3", "edge", "success"], ["g3", "node", "success"]],
[["ac3", "edge", "try"], ["c3", "node", "try", "1"]],
[["ac3", "edge", "success"], ["c3", "node", "success"]],
[["cf3", "edge", "try"], ["f3", "node", "try", "1"]],
[["cf3", "edge", "success"], ["f3", "node", "success"]],
[["k3", "node", "try", "1"]],
[["k3", "node", "success"]],
[["kl3", "edge", "try"], ["l3", "node", "try", "1"]],
[["kl3", "edge", "success"], ["l3", "node", "success"]],
[["lm3", "edge", "try"], ["m3", "node", "try", "1"]],
[["lm3", "edge", "success"], ["m3", "node", "success"]],
[["h23", "node", "try", "1"]],
[["h23", "node", "success"]],
[["h2i23", "edge", "try"], ["i23", "node", "try", "1"]],
[["h2i23", "edge", "success"], ["i23", "node", "success"]],
[["i2j23", "edge", "try"], ["j23", "node", "try", "1"]],
[["i2j23", "edge", "success"], ["j23", "node", "success"]],
[["j2i23", "edge", "try"], ["i23", "node", "try", "2"]],
[["j2i23", "edge", "failure"], ["i23", "node", "failure"]],
[["fd3", "edge", "try"], ["d3", "node", "try", "1"]],
[["fd3", "edge", "success"], ["d3", "node", "success"]],
[["df3", "edge", "try"], ["f3", "node", "try", "2"]],
[["df3", "edge", "failure"], ["f3", "node", "failure"]],
[["fg3", "edge", "try"], ["g3", "node", "try", "2"]],
[["fg3", "edge", "failure"], ["g3", "node", "failure"]],
[["ad3", "edge", "try"], ["d3", "node", "try", "2"]],
[["ad3", "edge", "failure"], ["d3", "node", "failure"]],
];
// Node + edge colors.
const nodeAndEdgeColors3 = {
"nodeDefaultFillColor": "#000000",
"nodeDefaultStrokeColor": "#000000",
"edgeDefaultColor": "#000000",
"visitTryColor": "#FFD100",
"visitSuccessColor": "#005593",
"visitFailureColor": "#BB1E10",
};
// Button state colors.
const buttonDefaultColor3 = "#FFFFFF";
const buttonHoverColor3 = "#BFBFBF";
const buttonDownColor3 = "#7F7F7F";
let cnt3 = -1;
function onClickGoToStart3(buttonElement) {
// Reset counter to start.
cnt3 = -1;
// Reset all edges to their initial state color, and remove all anim-related classes.
const edges = document.getElementById("edges3");
for (const edge of edges.children) {
edge.classList.value = "edges3";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
}, { once: true });
}
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes3");
for (const node of nodes.children) {
node.classList.value = "nodes3";
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
node.setAttribute("successful-past-visit", "false");
// Reset the visit counter. Note that the visit counter element will always
// be the last element in a node since I've structured the svg in that manner
// (for convenience's sake).
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = "0/" + vcnt3[1];
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}, { once: true });
}
}
function onClickBackward3(buttonElement) {
if (cnt3 < 0) {
return;
}
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering[cnt3];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges3" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges3" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges3");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle3.innerHTML = createCssDynamicTextContent3(0, edgeIdx, nodeAndEdgeColors3, "backwards", "reverse");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing from "try", we want to go back to the default edge color
// (since no single edge will be traversed more than once, so it's guaranteed
// that this is the first time that the current edge was iterated over).
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["edgeDefaultColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
// When reversing from "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
```javascript
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitTryColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitTryColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitTryColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitTryColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
else if (type == "node") {
// Get the "nodes3" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes3" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes3");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle3.innerHTML = createCssDynamicTextContent3(nodeIdx, prevEdgeIdx, nodeAndEdgeColors3, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// node has already been visited previously.
if (status == "try") {
const visitCount = elementAttrs[3];
// Decrement the visit counter immediately.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
vcnt3[0] = String(Number(visitCount) - 1);
visitCounter.textContent = vcnt3[0] + "/" + vcnt3[1];
}
}
// If we have a visit counter to reach, then compare against
// the denominator.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3[0] >= vcnt3[1]) {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// If no visit counter exists, then just check if this is
// the first visit.
else {
if (visitCount != "1") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3[0] >= vcnt3[1]) {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
}
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3[0] >= vcnt3[1]) {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
}
}, { once: true });
}
}
```
// When reversing a "try", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a try).
else if (status == "try") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitTry");
}
else {
node.classList.add("unfilledVisitTry");
}
node.setAttribute("visited-past-try", "false");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
node.setAttribute("successful-past-visit", "false");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
}
else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
node.classList.value = "nodes3";
}, { once: true });
}
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
edge.classList.value = "edges3";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
edge.classList.value = "edges3";
}, { once: true });
}
else if (type == "node") {
// Get the "nodes3" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes3" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes3");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
let numCallbacks = 0;
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle3.innerHTML = createCssDynamicTextContent3(nodeIdx, prevEdgeIdx, nodeAndEdgeColors3, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
const g_node = document.getElementById("g");
// Get the current visit count.
const visitCount = elementAttrs[3];
// Set the node animation based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitTryAlreadyVisited");
} else {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
// Set the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt3[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors3["visitTryColor"]);
// Increment the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt3[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes3";
}, { once: true });
} else if (status == "success") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
} else {
node.classList.add("unfilledVisitSuccess");
}
node.setAttribute("successful-past-visit", "true");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
// ...
}, { once: true });
}
}
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
node.classList.value = "nodes3";
}, { once: true });
} else if (status == "failure") {
// Set the node's stroke color based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
} else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("successful-past-visit") == "true") {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes3";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("successful-past-visit") == "true") {
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
path.setAttribute("stroke", nodeAndEdgeColors3["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes3";
}, { once: true });
}
}
function onClickGoToEnd3(buttonElement) {
// Set counter to end.
cnt3 = nodesAndEdgesOrdering.length - 1;
// First iterate over all nodes and set their visit counts to zero.
for (const child of document.getElementById("nodes3").children) {
const textElements = child.getElementsByTagName("text");
if (textElements.length <= 1) {
continue;
}
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = "0/" + vcnt3[1];
}
}
for (let i = 0; i < nodesAndEdgesOrdering.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
// Set all elements to their final colors/states.
if (type == "edge") {
element.classList.add("edges3");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes3");
const textElements = element.getElementsByTagName("text");
if (status == "try") {
// Get the visit count.
const visitCount = elementAttrs[3];
// Set the visit counter.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt3 = visitCounter.textContent;
vcnt3 = vcnt3.split("/");
if (vcnt3.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt3[1];
}
}
} else if (status == "success") {
element.setAttribute("successful-past-visit", "true");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges3");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
}
}
});
}
}
}
```javascript
else if (type == "node") {
element.classList.add("nodes3");
if (status == "success") {
const textElements = element.getElementsByTagName("text");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
}, { once: true });
element.addEventListener("animationcancel", () => {
if (type == "edge") {
element.classList.add("edges3");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors3["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes3");
if (status == "success") {
const textElements = element.getElementsByTagName("text");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
} else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors3["visitSuccessColor"]);
}
}
}, { once: true });
}
}
function onMouseDown3(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor3);
}
function onMouseUp3(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor3);
}
function onMouseOver3(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor3);
}
function onMouseLeave3(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDefaultColor3);
}
//]]>
</script>
</svg>
<p>
Make sure to read
<span class="std std-ref">
Print all Node Names
</span>
,
<span class="std std-ref">
Print all Node Traversal Paths Recursively
</span>
, and
<span class="std std-ref">
Store and Print all Node Names Concurrently
</span>
for traversal samples that utilize the
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitFirst
</span>
</code>
strategy.
</p>
</section>
<section id="visitlast-strategy">
<span id="visit-last-strategy">
</span>
<h3>
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
</span>
</code>
Strategy
</h3>
<p>
The
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
</span>
</code>
strategy allows for a given
<span class="std std-ref">
node
</span>
to be entered only when the
<em>
entirety
</em>
of its upstream/parent
<span class="std std-ref">
nodes
</span>
have already been visited, thereby implying that this is the last opportunity to enter the
<span class="std std-ref">
node
</span>
. We sometimes refer to the ordering of
<span class="std std-ref">
node
</span>
visits produced by using
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
</span>
</code>
as being the
<em>
topographical
</em>
traversal order (as was seen in
<span class="std std-ref">
Getting Started with Writing Graph Traversals
</span>
, for example).
</p>
<p>
To justify the need and merit of this strategy, suppose we had the following IR
<span class="std std-ref">
graph
</span>
<span class="math notranslate nohighlight">
\(G_3\)
</span>
:
</p>
<figure class="align-center" id="ef-graph-traversal-03">
Figure 26 Example IR graph \(G_3\) which contains a fan in/out flow pattern. Assume that \(\{r,a\}\) and \(\{r,b\}\) are root node \(r\)’s first and second edges, respectively.
As has been discussed in previous articles, connections between \(c\) and the parents represent upstream execution dependencies for \(c\), i.e. in order to successfully compute \(c\), we first need the results of \(a\)’s and \(b\)’s executions. Now, suppose that we tried traversing this graph in a serial, DFS manner using the same policy of entering any node on the first available edge, and immediately executing each node that we visit. Based on what has already been presented, the traversal path (and subsequently the order of node executions) would look like this (assuming we begin from \(r\)):
\[r \rightarrow a \rightarrow c \rightarrow b\]
This is problematic because \(c\) was evaluated before all of its parents; more specifically, not all of the requisite upstream information for \(c\)’s compute were passed down prior to triggering its evaluation, since \(b\) was executed after \(c\). To remedy this, we’d need to specify in the traversal implementation that nodes are only to be entered once all of their parents have been executed. Said differently, we should only enter on the last available edge, which implies that all other parents have already executed, and now that the final parent is also done computing we can safely continue flowing downstream since we have the necessary upstream inputs to perform subsequent calculations. In the above example, rather than directly entering \(c\) from \(a\), we’d actually first bounce to the other branch to evaluate \(b\), and only then enter \(c\) from \(b\). The amended traversal path would thus be:
\[r \rightarrow a \rightarrow b \rightarrow c\]
The implementation for VisitLast looks like this:
```cpp
//! Traversal strategy that enters the node when entire upstream was already visited and this is the last
//! opportunity to enter the node.
//!
//! In case of cycles, this algorithm is relying on knowledge of number of parents that are causing cycles.
struct VisitLast
{
//! Call to traverse the graph with a strategy to visit only when no more visits are possible
template <typename Node, typename NodeData>
static VisitOrder tryVisit(Node& node, NodeData& nodeData)
{
```
```
Listing 51 VisitLast strategy implementation.
```
```
- The root node (which doesn’t get counted as the parent of any node) and no parent cycles, so `requiredCount == 0`. This is also the first time we’ve attempted to enter \(a\), so `currentVisit == 1`. By these two conditions, the node can be entered.
- From \(a\) we try to visit all of its children. Since \(b\) is its only child, we attempt to visit \(b\).
- \(b\) has 2 parents (\(a\) and \(c\), since both have directed edges pointing from themselves to \(b\)) and 1 parent cycle (formed thanks to \(c\)). Since this is the first time that we’ve visited \(b\), `currentVisit == 1`. Now, suppose that we only computed `requiredCount` based exclusively off of the number of parents, i.e. `auto requiredCount = node->getParents().size()`. In this case `requiredCount == 2`, which implies that we’d need to visit both \(a\) and \(c\) first before entering \(c\). But, \(c\) also lies downstream of \(b\) in addition to being upstream (such is the nature of cycles), and the only way to enter \(c\) is through \(b\). So we’d need to enter \(b\) before \(c\), which can only be done if \(c\) is visited, and on-and-on goes the circular logic. In short, using this specific rule we’d never be able to enter either \(b\) or \(c\) (as evidenced by the fact that our `requiredCount` of 2 is not equal to the `currentVisit` value of 1). While this could be viable visitation behavior for situations where we want to prune cycles from traversal, the VisitLast strategy was written with the goal of making all nodes in a cyclic graph be reachable. This is why we ultimately subtract the parent cycle count from the required total – we essentially stipulate that it is not necessary for upstream nodes that are members of the same cycle(s) that the downstream node in question is in to be computed prior to entering the latter. Using this ruleset, `requiredCount` for \(b\) becomes 1, and thus `currentVisit == requiredCount` is satisfied.
- We skip the rest of the traversal steps since they’re not relevant to the present discussion.
DFS through graph \(G_1\) that employs the `VisitLast` strategy:
Execution Graph
NodeGraphDef
\(G_1\)
has associated executor type
a
b
0/1
c
0/1
d
0/1
Node e
NodeGraphDef X
0/1
Node f
NodeGraphDef Y
0/2
g
0/2
h
i
0/1
j
0/1
k
l
0/1
Node m
NodeGraphDef X
0/1
h
i
Root is a special node used to
discover the entire topology.
Each node in topology has
one of two execution
definition types.
Root
Node
Def
NodeGraph
Def
<<
<
>
>>
@keyframes edge_visit_failure {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-failure-color);
}
}
/*Edge Animations*/
.edges4:nth-child(${edgeIdx}).visitTry>path {
animation: edge_visit_try 0.5s ease ${fillMode} ${animDir};
}
.edges4:nth-child(${edgeIdx}).visitSuccess>path {
animation: edge_visit_success 0.5s ease ${fillMode} ${animDir};
}
.edges4:nth-child(${edgeIdx}).visitFailure>path {
animation: edge_visit_failure 1s ease ${fillMode} ${animDir};
}
/*Node Animation Keyframes*/
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--visit-success-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes filled_node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success {
0% {
stroke: var(--visit-try-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success_text {
0% {
fill: var(--node-stroke-default-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes4.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes4.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes4.filledVisitSuccess:nth-child(${nodeIdx})>path {
animation: filled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes4.unfilledVisitSuccess:nth-child(${nodeIdx})>path {
animation: unfilled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes4.unfilledVisitSuccess:nth-child(${nodeIdx})>text {
animation: unfilled_node_visit_success_text 0.5s ease ${fillMode} ${animDir};
}
.nodes4.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes4.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim04 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
```javascript
const edges = document.getElementById("edges4");
for (const edge of edges.children) {
edge.classList.value = "edges4";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors4["edgeDefaultColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["edgeDefaultColor"]);
}, { once: true });
}
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes4");
for (const node of nodes.children) {
node.classList.value = "nodes4";
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
node.setAttribute("successful-past-visit", "false");
// Reset the visit counter. Note that the visit counter element will always
// be the last element in a node since I've structured the svg in that manner
// (for convenience's sake).
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = "0/" + vcnt4[1];
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}, { once: true });
}
```
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
else if (type == "node") {
// Get the "nodes4" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes4" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes4");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle4.innerHTML = createCssDynamicTextContent4(nodeIdx, prevEdgeIdx, nodeAndEdgeColors4, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// node has already been visited previously.
if (status == "try") {
const visitCount = elementAttrs[3];
// Decrement the visit counter immediately.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
vcnt4[0] = String(Number(visitCount) - 1);
visitCounter.textContent = vcnt4[0] + "/" + vcnt4[1];
}
}
// If we have a visit counter to reach, then compare against
// the denominator.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4[0] >= vcnt4[1]) {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// If no visit counter exists, then just check if this is
// the first visit.
else {
if (visitCount != "1") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4[0] >= vcnt4[1]) {
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
}
node.classList.value = "nodes4";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4[0] >= vcnt4[1]) {
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
}
}, { once: true });
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors4["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes4";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
node.setAttribute("successful-past-visit", "false");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
node.classList.value = "nodes4";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors4["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
node.classList.value = "nodes4";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
}
else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
node.classList.value = "nodes4";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
node.classList.value = "nodes4";
}, { once: true });
}
}
cnt4 -= 1;
}
function onClickForward4(buttonElement) {
if (cnt4 >= nodesAndEdgesOrdering4.length - 1) {
return;
}
cnt4 += 1;
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering4[cnt4];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges4" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges4" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges4");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle4.innerHTML = createCssDynamicTextContent4(0, edgeIdx, nodeAndEdgeColors4, "both", "normal");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitTryColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitFailureColor"]);
edge.classList.value = "edges4";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors4["visitFailureColor"]);
edge.classList.value = "edges4";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes4" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes4" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes4");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
let numCallbacks = 0;
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle4.innerHTML = createCssDynamicTextContent4(nodeIdx, prevEdgeIdx, nodeAndEdgeColors4, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
const g_node = document.getElementById("g");
// Get the current visit count.
const visitCount = elementAttrs[3];
// Set the node animation based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-relatad classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
// Set the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt4[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes4";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors4["visitTryColor"]);
// Increment the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt4[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes4";
}, { once: true });
}
else if (status == "success") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
node.setAttribute("successful-past-visit", "true");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
}
else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
}
}
}, { once: true });
}
}
function onClickGoToEnd4(buttonElement) {
// Set counter to end.
cnt4 = nodesAndEdgesOrdering4.length - 1;
// First iterate over all nodes and set their visit counts to zero.
for (const child of document.getElementById("nodes4").children) {
const textElements = child.getElementsByTagName("text");
if (textElements.length <= 1) {
continue;
}
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = "0/" + vcnt4[1];
}
}
for (let i = 0; i < nodesAndEdgesOrdering4.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering4[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
// Set all elements to their final colors/states.
if (type == "edge") {
element.classList.add("edges4");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors4["visitFailureColor"]);
}
} else if (type == "node") {
element.classList.add("nodes4");
const textElements = element.getElementsByTagName("text");
if (status == "try") {
// Get the visit count.
const visitCount = elementAttrs[3];
// Set the visit counter.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt4 = visitCounter.textContent;
vcnt4 = vcnt4.split("/");
if (vcnt4.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt4[1];
}
}
} else if (status == "success") {
element.setAttribute("successful-past-visit", "true");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
} else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors4["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges4");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors4["visitSuccessColor"]);
} else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors4["visitFailureColor"]);
}
}
});
}
}
}
```javascript
// ... (JavaScript code related to SVG element manipulation)
```
```javascript
function onMouseDown4(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor4);
}
function onMouseUp4(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor4);
}
function onMouseOver4(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonHoverColor4);
}
function onMouseLeave4(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDefaultColor4);
}
```
```html
<!-- ... (HTML code related to SVG and script tags) -->
```
<p>
Make sure to read
<span class="std std-ref">
Print all Node Names Recursively in Topological Order
</span>
for a traversal sample that utilizes the
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
</span>
</code>
strategy.
</p>
<section id="visitall-strategy">
<h3>
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitAll
</span>
</code>
Strategy
</h3>
<p>
The
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitAll
</span>
</code>
strategy allows for all
<span class="std std-ref">
edges
</span>
in an EF
<span class="std std-ref">
graph
</span>
to be explored. While the previous two strategies are meant to be used with specific traversal continuation logic in mind (i.e. continuing traversal along the first/last
<span class="std std-ref">
edge
</span>
in the
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitFirst
</span>
</code>
/
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitLast
</span>
</code>
strategies, respectively),
<code class="xref cpp cpp-struct docutils literal notranslate">
<span class="pre">
VisitAll
</span>
</code>
is more open-ended in that it encourages the user to establish how traversal continuation should proceed (this is touched on in more detail
<span class="std std-ref">
here
</span>
).
</p>
<p>
The implementation looks like this:
</p>
<div class="literal-block-wrapper docutils container" id="ef-listing-visit-all">
<!-- ... (code block content) -->
</div>
### Listing 52
VisitAll strategy implementation.
```c++
//! Traversal strategy that allows discovering all the edges in the graph. Traversal continuation is controlled by user code.
//! struct VisitAll
struct VisitAll
{
//! Call to traverse the graph with a strategy to visit all edges of the graph
template <typename Node, typename NodeData>
static VisitOrder tryVisit(Node& node, NodeData& nodeData)
{
auto parentCount = node->getParents().size();
auto requiredCount = parentCount - node->getCycleParentCount();
auto currentVisit = ++nodeData.visitCount; // increment+read only once. other threads can be doing the same.
if (requiredCount == 0 && currentVisit == 1)
{
return (VisitOrder::eFirst | VisitOrder::eLast);
}
VisitOrder ret = VisitOrder::eUnknown;
if (currentVisit > requiredCount)
{
ret = VisitOrder::eCycle;
}
else if (currentVisit == requiredCount)
{
ret = (currentVisit == 1) ? (VisitOrder::eFirst | VisitOrder::eLast) : VisitOrder::eLast;
}
else if (currentVisit == 1)
{
ret = VisitOrder::eFirst;
}
else
{
ret = VisitOrder::eNext;
}
return ret;
}
};
```
Note how we’re outputting the specific type of visit that gets made when processing a given node (i.e. did we visit a node along its first edge, last edge, a cyclic edge, or something in between), unlike VisitFirst.
VisitFirst
and
VisitLast
which only check whether their own respective visit conditions have been met (and output a
VisitOrder::eUnknown
result if those conditions aren’t satisfied).
Here’s an animated example of a
serial
DFS
through
graph
\(G_1\)
that employs the
VisitAll
strategy and continues traversal along the first discovered
edge
:
b
0/1
c
0/1
d
0/1
Node e
NodeGraphDef
X
0/1
Node f
NodeGraphDef
Y
0/1
g
0/1
h
i
0/1
j
0/1
k
l
0/1
Node m
NodeGraphDef
X
0/1
h
0/1
i
0/1
j
0/1
Root is a special node used to
discover the entire topology.
Root
Node
Def
NodeGraph
Def
Each node in topology has
one of two execution
definition types.
<<
<
>
>>
```html
let dynamicStyle5 = document.getElementById("dynamicStyles5");
// Dynamic CSS. Allows us to alter certain CSS parameters
// at runtime by completely rebuilding it.
function createCssDynamicTextContent5(nodeIdx, edgeIdx, colors, fillMode, animDir) {
return `
:root {
--node-fill-default-color: ${colors["nodeDefaultFillColor"]};
--node-stroke-default-color: ${colors["nodeDefaultStrokeColor"]};
--edge-default-color: ${colors["edgeDefaultColor"]};
--visit-try-color: ${colors["visitTryColor"]};
--visit-success-color: ${colors["visitSuccessColor"]};
--visit-failure-color: ${colors["visitFailureColor"]};
}
/*Edge Animation Keyframes*/
@keyframes edge_visit_try {
0% {
fill: var(--edge-default-color);
}
100% {
fill: var(--visit-try-color);
}
}
@keyframes edge_visit_success {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes edge_visit_failure {
0% {
fill: var(--visit-try-color);
}
100% {
fill: var(--visit-failure-color);
}
}
/*Edge Animations*/
.edges5:nth-child(${edgeIdx}).visitTry>path {
animation: edge_visit_try 0.5s ease ${fillMode} ${animDir};
}
.edges5:nth-child(${edgeIdx}).visitSuccess>path {
animation: edge_visit_success 0.5s ease ${fillMode} ${animDir};
}
.edges5:nth-child(${edgeIdx}).visitFailure>path {
animation: edge_visit_failure 1s ease ${fillMode} ${animDir};
}
/*Node Animation Keyframes*/
@keyframes node_visit_try_already_visited {
0% {
stroke: var(--visit-success-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes node_visit_try_never_visited {
0% {
stroke: var(--node-stroke-default-color);
}
100% {
stroke: var(--visit-try-color);
}
}
@keyframes filled_node_visit_success {
0% {
fill: var(--node-fill-default-color);
stroke: var(--visit-try-color);
}
100% {
fill: var(--visit-success-color);
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success {
0% {
stroke: var(--visit-try-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes unfilled_node_visit_success_text {
0% {
fill: var(--node-stroke-default-color);
}
100% {
fill: var(--visit-success-color);
}
}
@keyframes node_visit_failure_already_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--visit-success-color);
}
}
@keyframes node_visit_failure_never_visited {
0% {
stroke: var(--visit-try-color);
}
50% {
stroke: var(--visit-failure-color);
}
100% {
stroke: var(--node-stroke-default-color);
}
}
/*Node Animations*/
.nodes5.visitTryAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_already_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes5.visitTryNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_try_never_visited 0.5s ease ${fillMode} ${animDir};
}
.nodes5.filledVisitSuccess:nth-child(${nodeIdx})>path {
animation: filled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
/*Apply animation to the path that draws the circle*/
.nodes5.unfilledVisitSuccess:nth-child(${nodeIdx})>path {
animation: unfilled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
/*Apply animation to all other child elements of the node, which is just text.*/
.nodes5.unfilledVisitSuccess:nth-child(${nodeIdx})>text {
animation: unfilled_node_visit_success_text 0.5s ease ${fillMode} ${animDir};
}
.nodes5.visitSuccessWithPrevSuccesses:nth-child(${nodeIdx})>path {
animation: unfilled_node_visit_success 0.5s ease ${fillMode} ${animDir};
}
.nodes5.visitFailureAlreadyVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_already_visited 1s ease ${fillMode} ${animDir};
}
.nodes5.visitFailureNeverVisited:nth-child(${nodeIdx})>path {
animation: node_visit_failure_never_visited 1s ease ${fillMode} ${animDir};
}
/*Center the SVG*/
#efGraphTraversalAnim05 {
margin-left: auto;
margin-right: auto;
display: block;
}
.noselect {
/* iOS Safari */
-webkit-touch-callout: none;
/* Safari */
-webkit-user-select: none;
/* Konqueror HTML */
-khtml-user-select: none;
/* Old versions of Firefox */
-moz-user-select: none;
/* Internet Explorer/Edge */
-ms-user-select: none;
/* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
user-select: none;
}
`;
}
// Establishes the exact node/edge traversal ordering.
const nodesAndEdgesOrdering5 = [
[["a5", "node", "try", "1"]],
[["a5", "node", "success", "1"]],
[["ab5", "edge", "try"], ["b5", "node", "try", "1"]],
[["ab5", "edge", "success"], ["b5", "node", "success", "1"]],
[["be5", "edge", "try"], ["e5", "node", "try", "1"]],
[["be5", "edge", "success"], ["e5", "node", "success", "1"]],
[["h15", "node", "try", "1"]],
[["h15", "node", "success", "1"]],
[["h1i15", "edge", "try"], ["i15", "node", "try", "1"]],
[["h1i15", "edge", "success"], ["i15", "node", "success", "1"]],
[["i1j15", "edge", "try"], ["j15", "node", "try", "1"]],
[["i1j15", "edge", "success"], ["j15", "node", "success", "1"]],
[["j1i15", "edge", "try"], ["i15", "node", "try", "2"]],
[["j1i15", "edge", "success"], ["i15", "node", "success", "2"]],
`;
[["eg5", "edge", "try"], ["g5", "node", "try", "1"]],
[["eg5", "edge", "success"], ["g5", "node", "success", "1"]],
[["ac5", "edge", "try"], ["c5", "node", "try", "1"]],
[["ac5", "edge", "success"], ["c5", "node", "success", "1"]],
[["cf5", "edge", "try"], ["f5", "node", "try", "1"]],
[["cf5", "edge", "success"], ["f5", "node", "success", "1"]],
[["k5", "node", "try", "1"]],
[["k5", "node", "success", "1"]],
[["kl5", "edge", "try"], ["l5", "node", "try", "1"]],
[["kl5", "edge", "success"], ["l5", "node", "success", "1"]],
[["lm5", "edge", "try"], ["m5", "node", "try", "1"]],
[["lm5", "edge", "success"], ["m5", "node", "success", "1"]],
[["h25", "node", "try", "1"]],
[["h25", "node", "success", "1"]],
[["h2i25", "edge", "try"], ["i25", "node", "try", "1"]],
[["h2i25", "edge", "success"], ["i25", "node", "success", "1"]],
[["i2j25", "edge", "try"], ["j25", "node", "try", "1"]],
[["i2j25", "edge", "success"], ["j25", "node", "success", "1"]],
[["j2i25", "edge", "try"], ["i25", "node", "try", "2"]],
[["j2i25", "edge", "success"], ["i25", "node", "success", "2"]],
[["fd5", "edge", "try"], ["d5", "node", "try", "1"]],
[["fd5", "edge", "success"], ["d5", "node", "success", "1"]],
[["df5", "edge", "try"], ["f5", "node", "try", "2"]],
[["df5", "edge", "success"], ["f5", "node", "success", "2"]],
[["fg5", "edge", "try"], ["g5", "node", "try", "2"]],
[["fg5", "edge", "success"], ["g5", "node", "success", "2"]],
[["ad5", "edge", "try"], ["d5", "node", "try", "2"]],
[["ad5", "edge", "success"], ["d5", "node", "success", "2"]]
// Node + edge colors.
const nodeAndEdgeColors5 = {
"nodeDefaultFillColor": "#000000",
"nodeDefaultStrokeColor": "#000000",
"edgeDefaultColor": "#000000",
"visitTryColor": "#FFD100",
"visitSuccessColor": "#005593",
"visitFailureColor": "#BB1E10",
};
// Button state colors.
const buttonDefaultColor5 = "#FFFFFF";
const buttonHoverColor5 = "#BFBFBF";
const buttonDownColor5 = "#7F7F7F";
let cnt5 = -1;
function onClickGoToStart5(buttonElement) {
// Reset counter to start.
cnt5 = -1;
// Reset all edges to their initial state color, and remove all anim-related classes.
const edges = document.getElementById("edges5");
for (const edge of edges.children) {
edge.classList.value = "edges5";
const path = edge.getElementsByTagName("path").item(0);
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
}, { once: true });
}
// Reset all nodes to their initial state color, and remove all anim-related classes.
const nodes = document.getElementById("nodes5");
for (const node of nodes.children) {
node.classList.value = "nodes5";
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
node.setAttribute("successful-past-visit", "false");
// Reset the visit counter. Note that the visit counter element will always
// be the last element in a node since I've structured the svg in that manner
// (for convenience's sake).
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = "0/" + vcnt5[1];
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Reset the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
} else {
path.setAttribute("fill", "#FFFFFF");
// Reset all text color.
for (let i = 0; i < textElements.length; ++i) {
const text = textElements.item(i);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}, { once: true });
}
}
function onClickBackward5(buttonElement) {
if (cnt5 < 0) {
return;
}
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering5[cnt5];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges5" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges5" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges5");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle5.innerHTML = createCssDynamicTextContent5(0, edgeIdx, nodeAndEdgeColors5, "backwards", "reverse");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing from "try", we want to go back to the default edge color
// (since no single edge will be traversed more than once, so it's guaranteed
// that this is the first time that the current edge was iterated over).
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["edgeDefaultColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
// When reversing from "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success).
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
// When reversing from "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure).
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
else if (type == "node") {
// Get the "nodes5" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes5" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes5");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle5.innerHTML = createCssDynamicTextContent5(nodeIdx, prevEdgeIdx, nodeAndEdgeColors5, "backwards", "reverse");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
// When reversing a "try", we need to check whether the current
// node has already been visited previously.
if (status == "try") {
const visitCount = elementAttrs[3];
// Decrement the visit counter immediately.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
vcnt5[0] = String(Number(visitCount) - 1);
visitCounter.textContent = vcnt5[0] + "/" + vcnt5[1];
}
}
// If we have a visit counter to reach, then compare against
// the denominator.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5[0] >= vcnt5[1]) {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// If no visit counter exists, then just check if this is
// the first visit.
else {
if (visitCount != "1") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5[0] >= vcnt5[1]) {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
}
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5[0] >= vcnt5[1]) {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
}
else {
if (visitCount != "1") {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
}
node.classList.value = "nodes5";
}, { once: true });
}
// When reversing a "success", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a success). We do need to check if the node has been
// successfully visited in the past though (e.g. with the VisitAll strategy).
else if (status == "success") {
const visitCount = elementAttrs[3];
// Check if the node has been successfully visited in previous steps,
// not counting the current step that's about to be reversed.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (visitCount <= vcnt5[1]) {
node.setAttribute("successful-past-visit", "false");
}
}
else if (visitCount == "1") {
node.setAttribute("successful-past-visit", "false");
}
// Set the appropriate animation depending on whether or not
// we're reversing the very first successfull visit.
if (node.getAttribute("successful-past-visit") == "false") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
}
else {
node.classList.add("visitSuccessWithPrevSuccesses");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("successful-past-visit") == "false") {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("successful-past-visit") == "false") {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
else {
path.setAttribute("fill", "#FFFFFF");
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors5["nodeDefaultFillColor"]);
}
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
node.classList.value = "nodes5";
}, { once: true });
}
// When reversing a "failure", it's guaranteed that the previous state
// was "try" (i.e. we had to try and visit the element before being able to
// declare that visit a failure). We do, however, need to check whether or not
// the node has already been visited successfully (i.e. the fill color) in order
// to play the correct reverse animation.
else if (status == "failure") {
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
}
else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
node.classList.value = "nodes5";
}, { once: true });
}
}
cnt5 -= 1;
function onClickForward5(buttonElement) {
if (cnt5 >= nodesAndEdgesOrdering5.length - 1) {
return;
}
cnt5 += 1;
// Get a list of the current elements that need to undergo animation.
const listOfElements = nodesAndEdgesOrdering5[cnt5];
let prevEdgeIdx = 0;
for (let i = 0; i < listOfElements.length; ++i) {
// Unpack the element attributes.
const elementAttrs = listOfElements[i];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
if (type == "edge") {
// Get the "edges5" element (which contains all edges), the actual current
// edge's html element (which is a child of the "edges5" element as well) and
// the corresponding path element.
const edges = document.getElementById("edges5");
const edge = document.getElementById(name);
const path = edge.getElementsByTagName("path").item(0);
// Rebuild the CSS stylesheet.
const edgeIdx = Array.prototype.indexOf.call(edges.children, edge) + 1;
prevEdgeIdx = edgeIdx;
dynamicStyle5.innerHTML = createCssDynamicTextContent5(0, edgeIdx, nodeAndEdgeColors5, "both", "normal");
// Depending on the edge status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
edge.classList.add("visitTry");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitTryColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
else if (status == "success") {
edge.classList.add("visitSuccess");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
else if (status == "failure") {
edge.classList.add("visitFailure");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
edge.addEventListener("animationend", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
edge.classList.value = "edges5";
}, { once: true });
edge.addEventListener("animationcancel", () => {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
edge.classList.value = "edges5";
}, { once: true });
}
}
else if (type == "node") {
// Get the "nodes5" element (which contains all nodes), the actual current
// nodes's html element (which is a child of the "nodes5" element as well) and
// the corresponding path element.
const nodes = document.getElementById("nodes5");
const node = document.getElementById(name);
const path = node.getElementsByTagName("path").item(0);
const textElements = node.getElementsByTagName("text");
let numCallbacks = 0;
// Rebuild the CSS stylesheet.
const nodeIdx = Array.prototype.indexOf.call(nodes.children, node) + 1;
dynamicStyle5.innerHTML = createCssDynamicTextContent5(nodeIdx, prevEdgeIdx, nodeAndEdgeColors5, "both", "normal");
// Depending on the node status, add the corresponding name
// to the class and set the colors to their final values
// after the animation finishes.
if (status == "try") {
const g_node = document.getElementById("g");
// Get the current visit count.
const visitCount = elementAttrs[3];
// Set the node animation based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitTryAlreadyVisited");
}
else {
node.classList.add("visitTryNeverVisited");
}
}
}
}
}
```javascript
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-relatad classes.
node.addEventListener("animationend", () => {
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
// Set the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt5[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
path.setAttribute("stroke", nodeAndEdgeColors5["visitTryColor"]);
// Increment the visit counter.
if (textElements.length > 1 && numCallbacks == 0) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt5[1];
}
numCallbacks += 1;
}
node.classList.value = "nodes5";
}, { once: true });
}
else if (status == "success") {
if (node.getAttribute("successful-past-visit") == "false") {
if (node.getAttribute("is-filled") == "true") {
node.classList.add("filledVisitSuccess");
}
else {
node.classList.add("unfilledVisitSuccess");
}
}
else {
node.classList.add("visitSuccessWithPrevSuccesses");
}
node.setAttribute("successful-past-visit", "true");
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let j = 0; j < textElements.length; ++j) {
const text = textElements.item(j);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
node.classList.value = "nodes5";
}, { once: true });
}
else if (status == "failure") {
// Set the node's stroke color based on whether or not it has already
// been successfully visited.
if (node.getAttribute("successful-past-visit") == "true") {
node.classList.add("visitFailureAlreadyVisited");
}
else {
node.classList.add("visitFailureNeverVisited");
}
// Add event listeners for the current animation ending/cancelling early
// that will correctly set the final color(s) on the element at hand, since
// the colors set by the CSS animations are transient and won't stick around
// if the element's class changes (which is necessary for triggering other
// animations as well). Also remove all anim-related classes.
node.addEventListener("animationend", () => {
if (node.getAttribute("successful-past-visit") == "true") {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes5";
}, { once: true });
node.addEventListener("animationcancel", () => {
if (node.getAttribute("successful-past-visit") == "true") {
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
path.setAttribute("stroke", nodeAndEdgeColors5["nodeDefaultStrokeColor"]);
}
node.classList.value = "nodes5";
}, { once: true });
}
```
```javascript
function onClickGoToEnd5(buttonElement) {
// Set counter to end.
cnt5 = nodesAndEdgesOrdering5.length - 1;
// First iterate over all nodes and set their visit counts to zero.
for (const child of document.getElementById("nodes5").children) {
const textElements = child.getElementsByTagName("text");
if (textElements.length <= 1) {
```
continue;
}
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = "0/" + vcnt5[1];
}
for (let i = 0; i < nodesAndEdgesOrdering5.length; ++i) {
// Get a list of the current elements that need to be set to their end state.
const listOfElements = nodesAndEdgesOrdering5[i];
let prevEdgeIdx = 0;
for (let j = 0; j < listOfElements.length; ++j) {
// Unpack the element attributes.
const elementAttrs = listOfElements[j];
const name = elementAttrs[0];
const type = elementAttrs[1];
const status = elementAttrs[2];
const element = document.getElementById(name);
const path = element.getElementsByTagName("path").item(0);
// Clear the element class list.
element.setAttributeNS(null, "class", "");
// Set all elements to their final colors/states.
if (type == "edge") {
element.classList.add("edges5");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes5");
const textElements = element.getElementsByTagName("text");
if (status == "try") {
// Get the visit count.
const visitCount = elementAttrs[3];
// Set the visit counter.
if (textElements.length > 1) {
const visitCounter = textElements.item(textElements.length - 1);
let vcnt5 = visitCounter.textContent;
vcnt5 = vcnt5.split("/");
if (vcnt5.length == 2) {
visitCounter.textContent = visitCount + "/" + vcnt5[1];
}
}
}
else if (status == "success") {
element.setAttribute("successful-past-visit", "true");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
// Listen for any animations that may have been playing that just
// ended and/or got cancelled by this action, and make sure to
// overwrite the final colors with the correct values after the
// fact.
element.addEventListener("animationend", () => {
if (type == "edge") {
element.classList.add("edges5");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes5");
if (status == "success") {
const textElements = element.getElementsByTagName("text");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
}, { once: true });
element.addEventListener("animationcancel", () => {
if (type == "edge") {
element.classList.add("edges5");
if (status == "success") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else if (status == "failure") {
path.setAttribute("fill", nodeAndEdgeColors5["visitFailureColor"]);
}
}
else if (type == "node") {
element.classList.add("nodes5");
if (status == "success") {
const textElements = element.getElementsByTagName("text");
if (element.getAttribute("is-filled") == "true") {
path.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
// Set the visit count text color.
const text = textElements.item(textElements.length - 1);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
else {
for (let k = 0; k < textElements.length; ++k) {
const text = textElements.item(k);
text.setAttribute("fill", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
path.setAttribute("stroke", nodeAndEdgeColors5["visitSuccessColor"]);
}
}
}, { once: true });
}
}
function onMouseDown5(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
buttonPathElement.setAttribute("fill", buttonDownColor5);
}
function onMouseUp5(buttonElement) {
let buttonPathElement = buttonElement.getElementsByTagName("path").item(0);
}
Make sure to read
- **Print all Edges Recursively**
- **Using Custom NodeUserData**
for traversal samples that utilize the **VisitAll** strategy.
## Serial vs. Parallel Graph Traversal
In the previous traversal examples we alluded to the fact that many of the searches were performed **serially**, as opposed to in **parallel**. The difference between the two is presented below:
### Serial Graph Traversal
- **Serial**: A **single** thread is utilized to perform the **graph** traversal. As a consequence, **node** visitation ordering will be deterministic, and depends entirely on the order of the corresponding connecting **edges**. This is why, in both the **DFS** and **BFS** examples shown in **Next Steps**, we visited **node** \(b\) before **node** \(c\) when kickstarting the search from **node** \(a\). While such **serial** traversal is usually easier to conceptualize – hence their liberal use in this article – it will also be much slower to traverse through a **graph** than an equivalent **parallel** search.
### Parallel Graph Traversal
- **Parallel**: **Multiple** threads are utilized to perform the **graph** traversal. As a consequence, **node** visitation ordering will **not** be deterministic, since different threads will begin and end their explorations at varying times depending on a number of external factors (the sizes of the subgraphs that are rooted at each child **node**, fluctuations in how the OS dispatches threads, etc.); this in turn implies that the generated depth/breadth-first search trees can differ between different concurrent traversals of the same **graph**. **Parallel** traversals will typically take **significantly** less time to complete than their **serial** counterparts.
Below is an example parallel graph traversal implementation using the APIs.
## Store and Print all Node Names **Concurrently**
**Listing 53** is similar to **Listing 26**, except that we now print the **node** names in **parallel** by performing the traversal in a multi-threaded fashion and store the results in an external data container.
tbb refers to Intel's Threading Building Blocks library.
### Listing 53
#### Parallel DFS using the VisitFirst strategy to print and store all top-level visited node names.
```cpp
tbb::task_group taskGroup;
tbb::concurrent_vector<INode*> nodes;
{
auto traversal =
traverseDepthFirstAsync<VisitFirst>(myGraph->getRoot(),
[&nodes, &taskGroup](auto info, INode* prev, INode* curr)
{
taskGroup.run(
[&nodes, info, prev, curr]() mutable
{
nodes.emplace_back(curr);
// Increase the chance for race conditions to arise by
// sleeping.
std::this_thread::sleep_for(std::chrono::milliseconds(10));
info.continueVisit(curr);
});
});
taskGroup.wait(); // Wait for all the parallel work to complete.
// Traversal object now is safe to destroy (which will happen when leaving the scope).
}
for (INode* const nodeName : nodes)
{
std::cout << nodeName->getName() << std::endl;
}
```
Applying this concurrent traversal to \(G_1\) would produce a list containing \(b\), \(e\), \(g\), \(c\), \(f\), and \(d\), although the exact ordering is impossible to determine thanks to some inherent non-determinisms associated with multi-threaded environments (variability when threads are spawned to perform work, distribution of tasks amongst threads, etc.).
## Traversal APIs
Now that we’ve covered DFS / BFS and Visitation Strategies, let’s bring our attention to the various traversal API helper methods. Currently there are 4 such traversal functions, all of which can be found in
```
# Traversal Methods
## Overview
The following traversal methods are available:
- **traverseDepthFirst()** can be used to perform serial DFS.
- **traverseBreadthFirst()** can be used to perform serial BFS.
- **traverseDepthFirstAsync()** can be used to perform both serial and parallel DFS.
- **traverseBreadthFirstAsync()** can be used to perform both serial and parallel BFS.
## Additional Details
It is worth mentioning that:
1. These methods are templated to include a `Strategy` type, which refers to the Visitation Strategies from before. This allows users to pass in custom-defined policies for graph exploration.
2. The traversal methods are also templated to include an optional `NodeUserData` type struct, which can be useful for passing in more sophisticated per-node data.
3. All four of the traversal methods accept a user-defined callback as part of their arguments, which gets evaluated whenever a node is able to be visited.
4. Technically, **traverseDepthFirstAsync()** and **traverseBreadthFirstAsync()** don’t implement parallel versions of these algorithms from the start; they simply allocate an internal `Traversal` object to the heap for concurrent access. The actual multithreaded search mechanism needs to be added by the user in the callback.
. Note that this also means that one could technically use
traverseDepthFirstAsync()/traverseBreadthFirstAsync() for
serial searches by writing the appropriate callbacks, although this is discouraged since
traverseDepthFirst() and traverseBreadthFirst() already exist to fulfill that functionality. |
Helpers.md | # Menu Helpers
Requires omni.kit.menu.utils version 1.5.8 or above
## MenuHelperExtension
This helper assists with menu creation but minimal window creation help, adds menu_startup(), menu_shutdown() & menu_refresh() functions by MenuHelperExtension subclass. Allowing user to control window open/closing. But does require ui.Workspace.set_show_window_fn to be set as it uses this to open/close/get state for the window
```python
from omni.kit.menu.utils import MenuHelperExtension
class ActionsExtension(omni.ext.IExt, MenuHelperExtension):
def on_startup(self):
self._actions_window = None
ui.Workspace.set_show_window_fn(ActionsExtension.WINDOW_NAME, self.show_window)
self.menu_startup(ActionsExtension.WINDOW_NAME, ActionsExtension.WINDOW_NAME, ActionsExtension.MENU_GROUP)
ui.Workspace.show_window(ActionsExtension.WINDOW_NAME, False)
def on_shutdown(self):
self.menu_shutdown()
ui.Workspace.set_show_window_fn(ActionsExtension.WINDOW_NAME, None)
if self._actions_window:
self._actions_window.destroy()
self._actions_window = None
def show_window(self, visible: bool):
if visible:
self._actions_window = ui.Window(ActionsExtension.WINDOW_NAME)
self._actions_window.set_visibility_changed_fn(self._visiblity_changed_fn)
self.menu_refresh()
elif self._actions_window:
self._actions_window.visible = False
def _visiblity_changed_fn(self, visible):
# tell omni.kit.menu.utils that actions window menu open/close state needs updating
self.menu_refresh()
```
Building window widgets can be done by sub-classing _show function, although it’s recommended that this should be done by sub-classing ui.Window and adding a frame build_fn via self.frame.set_build_fn(self._build_ui)
```python
def _show(self):
super()._show()
if self._window:
with self._window.frame:
with ui.VStack(height=0, spacing=8):
with ui.HStack(height=460):
ui.Label("myWindow")
```
## MenuHelperExtensionFull
- This helper assists with menu creation and window creation, handles show/hide and menu state updating. Adds menu_startup(), menu_shutdown() & menu_refresh() functions by MenuHelperExtensionFull subclass, all user has-to provide a function call to create the window.
```python
from omni.kit.menu.utils import MenuHelperExtensionFull
class OscilloscopeWindowExtension(omni.ext.IExt, MenuHelperExtensionFull):
def on_startup(self):
self.menu_startup(lambda: ui.Window("Audio Oscilloscope", width=512, height=540), "Audio Oscilloscope", "Oscilloscope", "Window")
ui.Workspace.show_window("Audio Oscilloscope", True)
def on_shutdown(self):
self.menu_shutdown()
```
or
```python
from omni.kit.menu.utils import MenuHelperExtensionFull, MenuHelperWindow
class OscilloscopeWindowExtension(omni.ext.IExt, MenuHelperExtensionFull):
def on_startup(self):
self.menu_startup(lambda: MenuHelperWindow("Audio Oscilloscope", width=512, height=540), "Audio Oscilloscope", "Oscilloscope", "Window")
ui.Workspace.show_window("Audio Oscilloscope", True)
def on_shutdown(self):
self.menu_shutdown()
``` |
high-level-code-overview_Overview.md | # Usage
## Usage
To enable this extension, go to the Extension Manager menu and enable omni.importer.urdf extension.
## High Level Code Overview
### Python
The URDF Importer extension sets attributes of `ImportConfig` on initialization, along with the UI giving the user options to change certain attributes. The complete list of configs can be found in `bindings/BindingsUrdfPython.cpp`.
When the import button is pressed, the `URDFParseAndImportFile` command from `python/commands.py` is invoked; this first calls `URDFParseFile` command, which binds to `parseUrdf` in `plugins/Urdf.cpp`. It then runs `import_robot` which binds to `importRobot` in `plugins/Urdf.cpp`.
### C++
#### `parseUrdf` in `plugins/Urdf.cpp`
Calls `parseUrdf` in `plugins/UrdfParser.cpp`, which parses the URDF file using tinyxml2 and calls `parseRobot` in the same file. `parseRobot` writes to the `urdfRobot` class, which is an the internal data structure that contains the name, the links, the joints, and the materials of the robot. It first parses materials, which are stored in a map between material name and `UrdfMaterial` class that contains the material name, the color, and the texture file path. It then parses the links, which are stored in a map between the link name and `UrdfLink` class containing the name, the inertial, visual mesh, and collision mesh. It finally parses the joints and store each joint in `UrdfJoint`. Note that for joints, if there is no axis specified, the axis defaults to (1,0,0). If there is no origin, it defaults to the identity transformation.
#### `importRobot` in `plugins/Urdf.cpp`
```
# Import Robot in plugins/Urdf.cpp
Initializes `urdfImporter` class defined in `plugins/UrdfImporter.h`. Calls `urdfImporter.addToStage`, which does the following:
- Creates a physics scene if desired in the config
- Creates a new prim that represents the robot and applies Articulation API, enables self-collision is set in the config, and sets the position and velocity iteration count to 32 and 16 by default.
- Sets the robot prim as the default prim if desired in the config
- Initializes a `KinematicChain` object from `plugins/KinematicChain.h` and calls `computeKinematicChain` given the `urdfRobot`. `computeKinematicChain` first finds the base link and calls `computeChildNodes` recursively to populate the entire kinematic chain.
- If the asset needs to be made instanceable, it will create a new stage, go through every link in the kinematic chain, import the meshes onto the new stage, and save the new stage as a USD file at the specified path.
- Recursively calls `addLinksAndJoints` along the entire kinematic chain to add the link and joint prims on stage.
# Limitations
- The URDF importer can only import robots that can be represented with a kinematic tree and hence cannot handle parallel robots. However, this is a limitation of the URDF format itself as opposed to a limitation of the URDF importer. For parallel robots, please consider switching to using MJCF along with the MJCF importer.
- The URDF importer does not currently support the `planar` joint type. In order to achieve a planar movement, please define two prismatic joints in tandem in place of a planar joint.
- The URDF importer does not support `<mimic>` for joints. However, a mimicing joint effect can be achieved manually in code by setting the joint target value to `multiplier * other_joint_value + offset`. |
hoops-converter_Overview.md | # Hoops Converter
## Overview
The Hoops Converter extension enables conversion for many common CAD file formats to USD.
USD Explorer includes the Hoops Converter extension enabled by default.
## Supported CAD file formats
The following file formats are supported by Hoops Converter:
- CATIA V5 Files (`*.CATPart`, `*.CATProduct`, `*.CGR`)
- CATIA V6 Files (`*.3DXML`)
- IFC Files (`*.ifc`, `*.ifczip`)
- Siemens NX Files (`*.prt`)
- Parasolid Files (`*.xmt`, `*.x_t`, `*.x_b`, `*.xmt_txt`)
- SolidWorks Files (`*.sldprt`, `*.sldasm`)
- STL Files (`*.stl`)
- Autodesk Inventor Files (`*.IPT`, `*.IAM`)
- AutoCAD 3D Files (`*.DWG`, `*.DXF`)
- Creo - Pro/E Files (`*.ASM`, `*.PRT`)
- Revit Files (`*.RVT`, `*.RFA`)
- Solid Edge Files (`*.ASM`, `*.PAR`, `*.PWD`, `*.PSM`)
- Step/Iges (`*.STEP`, `*.IGES`)
- JT Files (`*.jt`)
- DGN (`*.DGN`)
The file formats *.fbx, *.obj, *.gltf, *.glb, *.lxo, *.md5, *.e57 and *.pts are supported by Asset Converter and also available by default.
### Note
If expert tools such as Creo, Revit or Alias are installed, we recommend using the corresponding connectors. These provide more extensive options for conversion.
### Note
CAD Assemblies may not work when converting files from Nucleus. When converting assemblies with external references we recommend either working with local files or using Omniverse Drive.
## Converter Options
This section covers options for configuration of conversions of Hoops file formats to USD.
## Related Extensions
These related extensions make up the Hoops Converter. This extension provides import tasks to the extensions through their interfaces.
### Core Converter
- Hoops Core: :doc:`omni.kit.converter.hoops_core<omni.kit.converter.hoops_core:Overview>
### Services
- CAD Converter Service: :doc:`omni.services.convert.cad`
### Utils
- Converter Common: :doc:`omni.kit.converter.common` |
hotkey-registry_Overview.md | # Overview — Omniverse Kit 1.3.5 documentation
## Overview
The Omni Kit Hotkeys Core extension is a framework for creating, registering, and discovering hotkeys. Hotkeys are programmable objects include key binding, action and focus window. A hotkey can be created in one extension and then binded action can be executed when binded key pressed/released in desired window.
### Hotkeys
Hotkeys can be:
- Created, registered and discovered from any extension
- Edited, exported, imported
### Terms
- Local hotkey: Hotkey is executed in reference to an context rather that the application as a whole.
- Global hotkey: Hotkey will be executed no matter what “context” user is in
- Context: What window/tool/area the user is in. This is determined by Where the user’s mouse is hover
Local Hotkeys can override (Global) Hotkeys. If same key binding defined in both local hotkey and global hotkey, it will trigger in order:
- Local hotkey if special window focused
- Otherwise global hotkey
### Hotkey Registry
The Hotkey Registry maintains a collection of all registered hotkeys and allows any extension to:
- Register new hotkeys.
- Deregister existing hotkeys.
- Discover registered hotkeys.
- Edit existing hotkeys to change key binding or associated window name
Here is an example of registering a global hokey from Python that execute action “omni.kit.window.file::new” to create a new file when CTRL + N pressed:
```cpp
hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry()
hotkey_registry.register_hotkey(
"your_extension_id",
"CTRL + N",
"omni.kit.window.file",
"new",
filter=None,
)
```
For more examples, please consult the usage pages. |
how-can-i-extend-precense-layer-to-share-data-not-listed_Overview.md | # Introduction — Omniverse Kit 1.0.9 documentation
## Introduction
Presence Layer works for providing storage to exchange persistent data for all users in the same Live Session (see module `omni.kit.usd.layers`). The theory is that it uses .live layer as transport layer, on top of which all user data is structured as USD prim. It provides easy API to access the data without using raw USD API, and also event stream to subscribe the data changes. Currently, it’s used for spatial awareness, which includes the following applications:
- Bound Camera.
- Selections.
- User Following.
User can exchange and synchronize their local states of the above applications into the Presence Layer for other users to be aware of.
## Limitation
Currently, Presence Layer is created only when Root Layer enters a Live Session, no support for other layers in the layer stack.
## How can I Extend Precense Layer to Share Data not Listed?
Presence Layer currently exposes the raw underlying storage, which is a USD stage, so it shares all the benefits of USD and you can operate the stage with USD API to extend your own functionality. You can see `omni.kit.collaboration.presence_layer.PresenceAPI` for reference.
## Programming Guide
### Subscribe Spatial Awareness Events
Here is an example to subscribe spatial awareness events with Presence Layer, in a stage (specifically the Root Layer) that has already joined a Live Session (see `omni.kit.usd.layers.LiveSyncing`):
```python
import omni.usd
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
def _on_layers_event(event):
nonlocal payload
p = pl.get_presence_layer_event_payload(event)
if not p.event_type:
return
if p.event_type == pl.PresenceLayerEventType.SELECTIONS_CHANGED:
... # Peer Client's selections changed.
elif p.event_type == pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED:
... # Local Client enters into following mode.
elif p.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED:
```
```
# Peer Client changes its bound camera.
elif p.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED:
... # Peer Client changes the properties of its bound camera.
elif p.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_RESYNCED:
... # Peer Client's bound camera resynced.
usd_context = omni.usd.get_context()
layers_interface = layers.get_layers(usd_context)
subscription = layers_interface.get_event_stream().create_subscription_to_pop(
_on_layers_event, name="xxxxxxxxx"
)
...
</pre>
</div>
</div>
<p>
As you can see above, all events from Presence Layer are sent through event stream from
<code>
omni.kit.usd.layers.Layers
</code>
as Presence Layer is part of Live Syncing workflow.
</p>
</section>
<section id="send-spatial-awareness-events-with-scripting">
<h2>
Send Spatial Awareness Events with Scripting
</h2>
<div class="highlight-python notranslate">
<div class="highlight">
<pre><span></span><span class="kn">import</span> <span class="nn">omni.usd</span>
<span class="kn">import</span> <span class="nn">omni.kit.collaboration.presence_layer</span> <span class="k">as</span> <span class="nn">pl</span>
...
usd_context = omni.usd.get_context()
# Gets instance of Presence Layer bound to an UsdContext.
presence_layer = pl.get_presence_layer_interface(usd_context)
# Boradcasts local bound camera to other clients
your_bound_camera_path = ...
presence_layer.broadcast_local_bound_camera(your_local_camera_path)
# Enters into following mode
following_user_id = ...
presence_layer.enter_follow_mode(following_user_id)
...
# Quits following mode
presence_layer.quit_follow_mode()
</pre>
</div>
</div>
<p>
You can refer
<code>
omni.kit.usd.layers.LiveSyncing
</code>
and
<code>
omni.kit.usd.layers.LiveSession
</code>
about how to get the current Live Session and all of its joined users.
</p>
</section>
</section>
</div>
</div>
<footer>
<hr/>
</footer>
</div>
</div>
</section>
</div> |
how-it-works.md | # How It Works
The main `AutoNode` decorator, `@og.create_node_type`, wraps a Python function by creating a node type definition that allows that function to act as a node type’s `compute()` function. The logistics involve three phases - Analysis, which analyzes the function signature to define the input and output attributes that will be part of the node type definition as well as the node type’s critical definition information, `compute()` Definition, which wraps the decorated function in some code that interfaces with the OmniGraph `NodeType` ABI, and Runtime Registration/Deregistration, which manages the lifetime of the node types the decorator creates.
## Analysis
The analysis of the decorated function is triggered by import of the decorator `@og.create_node_type`. When it is encountered it uses both the parameters passed to the decorator itself and the signature of the function it is decorating to extract the information necessary to define an OmniGraph node type.
`AutoNode` generates node signatures by extracting type annotations stored in function signatures. In order for node types to be generated, type annotations are used in order to relate Python arguments to their OmniGraph attribute type equivalents.
The OmniGraph type annotations are imported from the module `omni.graph.core.types`. They encompass all of the legal attribute data type definitions, and are used as build-time identifiers for the data types being used in `AutoNode` definitions. To see the full list of data types available for use see Data Types.
Under the hood, annotation extraction is done with the python `__annotations__` (PEP 3107) dictionary in every class. In particular, it makes use of the `inspect` module’s function `inspect.get_annotations()` to retrieve and parse that information.
The annotations used have a table of correspondence between them and their .ogn attribute type names. The table is found in the build file `exts/omni.graph.tools/ogn/DataTypeNameConversions.json`. It contains the type name conversions between various representations, such as USD, SDF, Python annotations, and .ogn file text.
The decorator uses this table plus the extracted function signature to map the inputs and outputs to equivalent attribute definitions. (This mapping has some shortcomings, some of which can be worked around.)
Here is a map describing the various pieces of a simple decorator and what they are used for:
![AutoNodeDecoratorMap](_images/AutoNodeDecoratorMap.png)
# 文档标题
## 节点类型定义的额外信息
There is one more piece of information that will be extracted from the definition and used if possible and that is the name of the extension in which the node type was defined. For definitions executed through an extension-neutral location such as the script editor a special internal name will be applied in lieu of the extension name.
The extension name is discovered using inspection of the Python module top which the decorated function belongs and a lookup of extensions by module provided by the Kit extension manager. This extension information might be used in the **registration/deregistration management**.
## compute() Definition
As you can see from the decorator example above there is no requirement for the Python function being decorated to look anything like a regular OmniGraph **compute()** function, however there must be such a function in order for the node type to successfully integrate into OmniGraph.
The **AutoNode** implementation makes use of the internal runtime node type definition utility, which will create a new node type definition when given a few of the standard parameters. These include the attributes, which **AutoNode** parses from the function signature, any node type metadata, gleaned from the docstring and optional decorator arguments, and implementations for functions required for the node type to operate. The minimal set of such functions is the **compute()** function, and that is what **AutoNode** generates.
The function is a standalone function so there is not problem with trying to hook it into an existing object. The standard **compute()** function takes two parameters and returns a boolean indicating success:
```python
def compute(node: og.Node, context: og.GraphContext) -> bool:
return True
```
Note that this is also the magic that enables the **inspection trick** to find the node and context from within the decorated function.
A local function with this signature is instantiated by the decorator, with the interior of the function filled in with a very simple algorithm:
1. Walk the list of input attributes extracted by the analysis and use **node.get_attribute(NAME).get()** to get its current value
2. Call the decorated function with the retrieved values as parameters, in the order the function expects them
3. Walk the list of output attributes extracted by the analysis and use **node.get_attribute(NAME).set()** to set each of the values using the tuple or single value returned from the function call
4. Surround the function call with a try/except that will log an error and return False if an **og.OmniGraphError** is raised
## Runtime Registration/Deregistration
The last detail to be handled is the registration and deregistration of the node types, which can also be thought of as the node type life cycle management.
For convenience the node type will always be registered by the decorator so the start of the life cycle is well defined. Once a node type has been created and registered these are the events and reactions that will manage the end of the node type’s life cycle. It roughly follows the cycle of any Python object defined where it was defined.
**User executes the same decorated function, or another with the same unique name**
The existing node type with that name is deregistered and the new one is registered in its place. This enables the workflow of iterating on a node type definition in the script editor.
**User uses the og.deregister_node_type() API to manually deregister the node type**
The internal database is watching those events and updates itself so that it knows the node type is no longer registered.
**The omni.graph extension unloads**
While there is firewall code that deregisters any existing node types when the extension is disabled it also expects that through the extension dependencies that list should already be empty. That expectation is no longer valid and any still-active **AutoNode** node type definitions must be deregistered with any internal registries and callbacks being removed at that time as well. |
how-to-create-a-new-hydratexture_Overview.md | # Overview
## Introduction
A very low level extension for receiving renderer output as texture, which is usually then piped into the UI or captured directly. {py:mod}omni.kit.widget.viewport uses this extension to start a render and begin receiving its output.
Generally it is better to use higher level extensions like `omni.kit.widget.viewport` or `omni.kit.viewport.window`.
## How to create a new HydraTexture
### Python
1. Import the relevant module and function.
```python
from omni.kit.hydra_texture import acquire_hydra_texture_factory_interface
```
2. Get the HydraTexture factory interface to start creating HydraTextures
```python
texture_factory = acquire_hydra_texture_factory_interface()
# Make sure to run any initialization/startup that must occur
texture_factory.startup()
```
3. Make sure the engine-type is attached to the UsdContext
```python
engine_name = "rtx"
usd_context_name = ""
usd_context = omni.usd.get_context(usd_context_name)
if not usd_context:
raise RuntimeError(f"UsdContext named '{usd_context_name}' does not exist")
if engine_name not in usd_context.get_attached_hydra_engine_names():
omni.usd.add_hydra_engine(engine_name, usd_context)
```
4. Create a HydraTexture object rendering with RTX at 1280x720, for a UsdGeom.Camera named “/OmniverseKit_Persp” on the default omni.usd.UsdContext (named “”)
```python
hydra_texture = texture_factory.create_hydra_texture(
name="your_unique_name",
width=1280,
height=720,
engine_name="rtx",
camera_path="/OmniverseKit_Persp"
)
```
```python
height = 720,
usd_context_name = "usd_context_name",
usd_camera_path = "/OmniverseKit_Persp",
hydra_engine_name = "engine_name"
```
5. Subscribe to the event with a callback when a new frame is delivered
```python
# Import carb for logging and type-hinting support with the callback
import carb
def renderer_completed(event: carb.events.IEvent):
if event.type != omni.kit.hydra_texture.EVENT_TYPE_DRAWABLE_CHANGED:
carb.log_error("Wrong event captured for EVENT_TYPE_DRAWABLE_CHANGED!")
return
# Get a handle to the result
result_handle = event.payload['result_handle']
# And pass that to the HydraTexture instance to get the AOV's that are available
aov_info = hydra_texture.get_aov_info(result_handle)
print(f"Available AOVs: {aov_info}")
# Get an object for a specific AOV and include the GPU texture in the info
ldr_info_array = hydra_texture.get_aov_info(result_handle, 'LdrColor', include_texture=True)
print(f"LdrColor AOVs are: {ldr_info_array}")
ldr_texture = ldr_info_array[0].get("texture", None)
assert ldr_texture is not None
ldr_color_res = ldr_texture.get("rp_resource")
ldr_color_gpu_tex = ldr_texture.get("rp_resource")
print(f"LdrColor[0]: {ldr_color_res}, {ldr_color_gpu_tex}")
# YOU CANNOT USE THE RESOURCE OUTSIDE OF THIS FUNCTION/SCOPE
# ldr_color_gpu_tex must be consumed now or passed to another object
# that will use / add-ref the underlying GPU-texture.
event_sub = hydra_texture.get_event_stream().create_subscription_to_push_by_type(
omni.kit.hydra_texture.EVENT_TYPE_DRAWABLE_CHANGED,
renderer_completed,
name="Your unique event name for profiling/debug purposes"
)
# When event_sub object is destroyed (from going out of scope or being re-assigned)
# then the callback will stop being triggered.
# event_sub = None
```
``` |
how-to-create-a-new-viewportwidget_Overview.md | # Overview
## Introduction
A low level implementation of an `omni.ui.Widget` that displays rendered output. The `omni.kit.widget.viewport.ViewportWidget` does not include any additional features (such as menu-items or manipulators). It is used by `omni.kit.viewport.window.ViewportWindow` to provide a higher level, default Viewport experience in Kit based apps.
## How to create a new ViewportWidget
### Python
1. Import `omni.ui` so the `ViewportWidget` can be created inside an `omni.ui.Window`
```python
import omni.ui as ui
```
2. Import the class from the package:
```python
from omni.kit.widget.viewport import ViewportWidget
```
3. Choose the resolution and camera this instance will start rendering with.
```python
resolution = (512, 512)
camera_path = "/OmniverseKit_Persp"
```
4. Create an empty `omni.ui.Window` and instantiate a new `ViewportWidget` in its `omni.ui.Frame`
```python
window = ui.Window("Demo ViewportWidget", width=resolution[0], height=resolution[1])
```
```python
with window.frame:
vp_widget = ViewportWidget(camera_path=camera_path, resolution=resolution)
```
3. Get the active ViewportAPI attached to the
```python
ViewportWidget
```
and inspect some properties.
```python
viewport_api = vp_widget.viewport_api
usd_context = viewport_api.usd_context
usd_context_name = viewport_api.usd_context_name
usd_stage = viewport_api.stage
camera_path = viewport_api.camera_path
resolution = viewport_api.resolution
```
## Further reading
- Viewport Documentation
- Tutorials |
how-to-create-a-new-viewportwindow_Overview.md | # Overview
## Introduction
A high level implementation of a Window that contains a Viewport and variety of menus and manipulators for interacting and controlling a `pxr.usd.UsdStage` attached to a specific `omni.usd.UsdContext`.
## How to create a new ViewportWindow
### Python
1. Import the class from the package:
```python
from omni.kit.viewport.window import ViewportWindow
```
2. Create a ViewportWindow instance named “Demo”, attached to the default UsdContext
```python
viewport_window = ViewportWindow("Demo", width=640, height=480)
```
3. Get the active ViewportAPI attached to the ViewportWindow and inspect some properties.
```python
viewport_api = viewport_window.viewport_api
usd_context = viewport_api.usd_context
usd_context_name = viewport_api.usd_context_name
usd_stage = viewport_api.stage
camera_path = viewport_api.camera_path
resolution = viewport_api.resolution
```
## Further reading
- Viewport Documentation
- Tutorials |
HowTo.md | # OmniGraph How-To Guide
Find the area of interest here and click through to get the implementation details.
## Table of Contents
- [Node Categories](Categories.html)
- [Controller Class](Controller.html)
- [Initializing Attributes to Non-Default Values](RuntimeInitialize.html)
- [Writing a `computeVectorized` function](VectorizedCompute.html)
- [Set Up OmniGraph Tests](Testing.html)
- [Running Minimal Kit With OmniGraph](RunningOneScript.html)
## Additional Resources
- [How To Use The Script Node](../../../omni.graph.scriptnode/1.18.2/GeneratedNodeDocumentation/OgnScriptNode.html#omni-graph-scriptnode-scriptnode) |
http-api.md | # HTTP API
Launcher uses port 33480 to provide the HTTP API that can be used by other programs to retrieve information about the current session or get the list of installed apps.
This document describes all available HTTP endpoints supported by Launcher.
## Authentication
### [GET] /auth
Returns Starfleet information about the current user session.
**Method**: GET
**Content type**: `application/json`
#### Response
| Property | Type | Description |
|----------|--------|-----------------------------------------------------------------------------|
| `email` | string | Email used for authentication. Can be used to uniquely identify a user. |
| `username` | string | Preferred username displayed in the UI. This field should not be used for unique user identification. Use `email` field instead. |
| `accessToken` | string | The access token returned from Starfleet. |
| `idToken` | string | The ID token used in Starfleet for retrieving user’s information. |
| `expires` | Date | The access token expiration date in ISO format. |
#### Errors
| Error Code | Description |
|------------|-----------------------------------------------------------------------------|
| | |
# Installed apps and connectors
Launcher classifies all installed apps and connectors as `_components_`.
## [GET] /components
Returns the list of all installed apps and connectors.
**Method**: GET
**Content type**: `application/json`
### Response
Returns a list with the following **Component** objects (`?` means that the property is optional):
| Property | Type | Description |
|----------|--------|-----------------------------------------------------------------------------|
| `slug` | string | The unique component name. |
| `name` | string | The full displayed component name. |
| `version`| string | The latest version of this component available for download. Use `installedVersions` to check installed versions. |
| `shortName` | string | The short name used in the side menu. |
| `kind` | string | Specifies the component kind: `apps` or `connectors`. |
| `category` | string | The category used for grouping this component in the library. |
| `productArea` | _string?_ | Represents the product area – one product area can include multiple components that can be installed separately. Displayed in the component card title. |
| `installedVersions` | InstalledVersions | Lists versions of this component installed by the user. |
| `description` | string[] | Paragraphs with component description, supports markdown and HTML. |
| Property | Type | Description |
|----------|------|-------------|
| platforms | string[] | Represents OSs where this component can be installed. |
| settings | Settings[] | Represents settings used for installing this component. |
| image | _URL?_ | The image displayed on the detailed page. |
| card | _URL?_ | The image displayed on the card on the Exchange tab. |
| icon | _URL?_ | The icon displayed in the component card title. |
| tags | string[] | Tags shown below the component description. |
| featured | boolean | Defines if this component is shown in the featured section. |
| featuredImage | _URL?_ | The image displayed in the featured section. |
| links | string[] | Hyperlinks displayed in the library and in the component details. |
### Installed Versions
###### [](#installed-versions)
| Property | Type | Description |
|----------|------|-------------|
| all | string[] | All installed versions of this component. |
| current | string | The current installed version that is used for launching the component. |
| latest | string | The latest version of this component installed by the user. |
### Settings
###### [](#settings)
| Property | Type | Description |
|----------|------|-------------|
| Key | Type | Description |
|-----------------|------------|-----------------------------------------------------------------------------|
| slug | string | The unique component name. |
| version | string | The installed component version associated with these settings. |
| packages | Package[] | Thin packages used by this version. |
| path | string | The path to the main package. |
| base | string | The base path for the component that contains all packages. |
| showInLibrary | boolean | Defines whether this component should be displayed in the library. |
| sideBySide | boolean | Defines whether this component supports side-by-side installations. |
| runWithLauncher | boolean | Specifies whether this component should be started automatically with Launcher. |
| launch | _Script?_ | The script used for launching the component. |
| open | _Script?_ | The script used for opening omniverse:// links. |
| preInstall | _Script?_ | The script used before the installation starts. |
| install | _Script?_ | The main script for installing the component. |
| postInstall | _Script?_ | The script used after the installation. |
| register | _Script?_ | The script used when the user selects this component version. |
| unregister | _Script?_ | The script used to clean up the system when uses selects another component version. |
## Script
### Property
| Property | Type | Description |
|----------|------|-------------|
| path | string | Path to the script. |
| root | string | Defines where the component is installed. |
| args | _string[]?_ | Specifies all command line arguments used for the script. |
| environment | Map<string, string> | Specifies all predefined environment variables used for the script. |
## Package
### Property
| Property | Type | Description |
|----------|------|-------------|
| name | string | The unique package name. |
| url | string | The unsigned URL for downloading the package. Can’t be used directly, must be signed first. |
| hash | string | The package hash. Used to deduplicate installed packages. |
| main | _boolean?_ | Specifies if this package is the main package of the component. Main packages contain launcher.toml files and installation scripts. |
## [GET] /components/:slug
Returns information about the installed component with the specified slug.
Method: GET
Content type: application/json
Response
Returns a Component object. See details in Installed apps and connectors.
### Errors
| Status | Description |
|--------|-------------|
| HTTP404 | Component with the specified slug is not installed. | |
id100_CHANGELOG.md | # Changelog
## [105.1.13] - 2024-01-30
Version 209a1158b0bd45cfd5b6e41f2e7d4841c510e33e
- Updated Kit SDK
- Locked version for omni.localcache and omni.usd.schema.physx
## [105.1.11] - 2023-12-01
Version a836d8ed45fae75202dbb77aecfa7cb3cfa7e3df
### Core
**General**
- Changed
- The physxScene:gpuTempBufferCapacity parameter on the physics scene is now interpreted as a user-provided initial size, and will resize automatically if more memory is needed.
- Fixed
- Possible crash when triggers were deleted
- Possible crash when creating fixed tendons
- Crash when a PhysX SDK scene failed to be created
- Articulation arggregate number of shapes computed correctly
- Fix Inspector incorrect rounding of prismatic joint values ignoring meters to units
- A bug that led to a memory corruption in the GPU solver when using joints connected to both rigid bodies and articulations has been fixed.
- Issues with collision detection on articulations have been fixed that could have led to missed or phantom collisions.
- Spherical articulation joint limit behavior is fixed for links with nonidentity principal axis transform
- A bug causing slower convergence and potentially unstable collision responses between rigids and articulations.
- Articulation joint velocity limits are respected when articulation joint drives are configured to push past the limit.
- Particle - Convex Shape collisions failing with spread out particles.
- D6 Joint angular, Revolute Joint and Spherical Joint Limits close to 180deg behave correctly for TGS solver and GPU dynamics.
- Sphere-Triangle Mesh collisions for GPU Dynamics have been improved
- Cylinder and cone simulated with custom/analytic geometry did not respect the restOffset parameter
- Small improvements to SDF collisions, especially when objects with wildly different size collide
- Fix crashes when resampling a mesh with the particle sampler if the point count of the target particle prim has been changed externally.
- Fix crash in particle sampling when cooking is not initialized
- More USD parsing checks for deformables and particles
- Fix crash when updating deformable simulation positions/velocties at runtime with inconsistent element counts
- Fix crash when updating kinematic deformable mesh points with inconsistent element counts
- Fix crash when cooking deformable tet meshes for kinematic deformables in the presence of near degenerate triangles in the original mesh.
**Fabric**
- Fixed
- Fix crash when releasing fabric buffers due to stale cuda context
## [105.1.10] - 2023-10-19
Version ce837e9cd730d260af3968409c69fbdd98242273
### Core
**General**
- Added
- License for omni.usd.schema.physx
## [105.1.9] - 2023-09-23
Version abcecd407bfa5cd0f2c2f5a749faf0eaaba4aaf9
### Core
**General**
- Fixed
- Physics demos have wrong hitbox colors
- Defensive programming: making sure ZG sweep thread is disabled immediately at ZG shutdown
- PhysX replicator fix
# [105.1.8] - 2023-09-20
## Core
### General
- Fixed
- Filtered pairs removal crash.
- Issue with point instancer orientation update.
## Vehicles
### General
- Fixed
- Crash when setting rigidBodyEnabled to false on a body that is part of a vehicle. This is an illegal operation and will now be ignored and an error message will get sent.
- Undefined behavior when setting kinematicEnabled to true on a body that is part of an enabled vehicle. This is an illegal operation and will now result in the vehicle being disabled and an error message will get sent.
## UI
### General
- Fixed
- Joint visualization respects parent visibility toggle.
# [105.1.7] - 2023-09-11
## Core
### General
- Fixed
- Update Trigger and Contact OmniGraph nodes inputs using the new target type instead of deprecated bundle type for USD Path inputs
- Get App window and mapping set nullptr checks
- Fix prismatic joint alignment utility
- Fix issue with PhysxPropertyQuery return wrong data for instanced prims and reading garbage data for convex decompositions used in Simready assets (affects Mass Visualization Gizmo)
# [105.1.6] - 2023-09-07
## Core
### General
- Fixed
- Fixed crash with particle creation
- Crash with material delete for convex decomposition primitives
- Mass computation for rigid bodies without specified mass
- Fix property query tests
- Reduce physics cooking blocking of main thread on very large meshes and stages
- Physics cooking will reuse active tasks when matching mesh crc
- Fix crash with async simulation stepping
- Cleanup previous instance on Character controller OG node double activation
- CharacterController OG node's Done pin is executed after either activation or deactivation is finished
## UI
### General
- Fixed
- Zero Gravity Resync for instanceable change
- Instanced meshes cooking caching is correctly triggered
# [105.1.5] - 2023-08-21
## Core
### General
- Fixed
- Demos nucleus path.
# [105.1.4] - 2023-08-14
## Core
### General
- Fixed
- A bug that led to incorrect, missing and phantom collisions in convex-trianglemesh collisions has been fixed.
# [105.1.3] - 2023-08-07
## Core
### General
- Fixed
- Clear custom joints billboard instances when simulation play starts
- Incorrectly reported articulation object on fixed joint path
- A bug that led to incorrect and nondeterministic behaviour for trianglemesh-trianglemesh collisions on GPU has been fixed.
- Fix potential crash on OmniGraph Immediate nodes with empty meshes or meshes failing to cook. Improve performance on very large loads for Compute Mesh Intersecting Faces node.
# [105.1.2] - 2023-08-01
## Core
### General
- Changed
- Improved stage load time by switching stage traversal to USDRT
- Improved synchronization between simulation and mouse physics interaction for enhanced precision and responsiveness.
- Fixed
- Safety checks for multi material, SDF approximation correctly uses just one material
- Fixes a crash when moving a prim with PhysxParticleSamplingAPI to a new path while simulating.
- A bug that led to incorrect and nondeterministic behaviour for convex-trianglemesh, convex-heightfield, sphere-trianglemesh, capsule-trianglemesh, sphere-heightfield and capsule-heightfield collisions on GPU has been fixed.
## [105.1.1] - 2023-07-27
Version 89299bc58e60b0f7cf130575a8143259606fc391
### Core
**General**
```
- Changed
- Default contactOffset computation for convex decomposition shapes
- Fixed
- Only half the expected friction force was applied in certain articulation scenarios when using physxScene:solverType="TGS", physxScene:frictionType="patch", physxMaterial:improvePatchFriction=true and running on CPU.
- Joint align for misalligned joints when right clicking on joint poses
```
**Zero Gravity**
```
- Fixed
- Zero Gravity crash with simulation node unregister
```
## [105.1.0] - 2023-07-19
Version 0e189763accd3b7f1cd1e25c617f58cdc7e507a6
### Core
**General**
```
- Added
- Demos can be filtered through tags.
- Added support for SDF collision approximation to Physics Authoring Toolbar
- Integrate SRE (SimReady assets Explorer) drag and drop with ZeroGravity opt-in integration for easy and physically correct placement of assets.
- Toolbar have new option to not force collider type change when changing static<>dynamic
- Support for attachment mask shapes. Optionally defines a volume in which attachment points are generated, using UsdGeomSphere, UsdGeomCube and UsdGeomCapsule. Also includes better support for world space attachments which can now be specified using mask shapes.
- Support for hair attachments, including ability to specify how many hair root vertices should be minimally attached per hair strand.
- Changed
- Merge OmniGraph Physics Trigger Enter and Leave nodes in a single one with multiple execution pins
- The TGS solver on CPU and GPU now computes the number of position and velocity iteration according to the requested numbers by the actors in each island, matching the behavior of the PGS solver. Previously TGS velocity iterations in excess of 4 were silently converted to position iterations. To preserve the old behavior any actor requesting more than 4 velocity iterations should convert excess velocity iteration counts to position iteration counts, e.g., formerly 10 position and 10 velocity iterations should become 16 position and 4 velocity iterations.
- Fixed
- added 'sdf' as a valid approximation param for omni.physx.utils.setCollider
- Entering zeroG creates physics scene that is visible in the stage window
- Create ground plane with zeroG on issues PhysX SDK errors
- Starting application and enabling zeroG does not enter sweep mode
- The torsionalPatchRadius parameter of PhysxCollisionAPI was not working as expected with GPU simulation.
- Fixed crash when adding particle cloth component to meshes with non-referenced vertices
- Error when Physics Authoring toolbar feature "Remove Physics" was used and prims had certain vehicle API schemas applied.
```
**USD Schemas**
```
- Deprecated
- The friction type "oneDirectional" has been deprecated (see PhysxSceneAPI, attribute frictionType).
```
**Python Bindings API**
```
- Added
- Added point instancer variants of several simulation interface functions.
```
**C++ API**
```
- Added
- Added point instancer variants of several simulation interface functions.
```
### Vehicles
**General**
```
- Added
- Vehicle creation wizard: when selecting a wheel attachment prim, there will be a check to avoid assigning the same prim to multiple wheels.
- Changed
- The vehicle creation wizard does now only allow Xform prims to be chosen as vehicle prim.
- Fixed
- The vehicle creation wizard did not take vehicle prim scale into account for created wheel geometry collision and render prims.
- The vehicle creation wizard was not computing correct center of mass or wheel attachment positions if there was an offset between vehicle prim and bounding box center of scanned chassis prims (and if the wheel attachment prims were not defined by the user).
```
**USD Schemas**
```
- Added
- The option to limit the suspension expansion velocity has been added (see attribute limitSuspensionExpansionVelocity of PhysxVehicleAPI).
- The response to brake, steer and accelerator commands can now be described through nonlinear graphs (see the new API schema PhysxVehicleNonlinearCommandResponseAPI for details).
- Changed
- PhysxVehicleTankDifferentialAPI: it is now legal to define tank tracks with 1 or 0 wheels (entries in attribute numberOfWheelsPerTrack)
```
**Python Bindings API**
```
- Removed
- The following deprecated APIs have been removed: IPhysxVehicle.set_wheel_rotation_speed, IPhysxVehicle.set_wheel_rotation_angle, IPhysxVehicle.get_wheel_query_results, IPhysxVehicle.get_wheel_data, IPhysxVehicle.get_drive_data, IPhysxVehicle.compute_wheel_simulation_transforms. The following methods can be used instead: IPhysx.set_wheel_rotation_speed, IPhysx.set_wheel_rotation_angle, IPhysx.get_wheel_state, IPhysx.get_vehicle_drive_state of the omni.physx extension and IPhysxVehicle.compute_suspension_frame_transforms of the omni.physx.vehicle extension.
```
**C++ API**
```
- Removed
- The following deprecated APIs have been removed: IPhysxVehicle.setWheelRotationSpeed, IPhysxVehicle.setWheelRotationAngle, struct WheelQueryResults, struct WheelDynData, struct DriveDynData, IPhysxVehicle.getWheelQueryResults, IPhysxVehicle.getWheelDynData, IPhysxVehicle.getDriveDynData, IPhysx.getVehicleDriveData, IPhysxVehicle.computeWheelSimulationTransforms. The following methods can be used instead: IPhysx.setWheelRotationSpeed, IPhysx.setWheelRotationAngle, IPhysx.getWheelState, IPhysx.getVehicleDriveState of the omni.physx extension and IPhysxVehicle.computeSuspensionFrameTransforms of the omni.physx.vehicle extension.
```
### UI
**General**
```
- Added
- Collision visualizers are now being replaced by dimmed AABBs at user configurable distance (the distance is saved separately within each stage).
- Option to enable synchronous CUDA kernel launches in the Physics Debug panel. Synchronous CUDA kernel launches are needed to correctly report CUDA errors.
- Fixed
- Fix error spew when query mesh/shapes overlap with room for Overlap Mesh/Shape demos
```
# Omni PhysX Bundle 105.0.15 2023-06-23
## Core
### General
- Fixed
- Issue with start up error when omni.usd.readable_usd_file_exts() is removed at startup from file importer
## [105.0.14] - 2023-06-22
### Core
### General
- Fixed
- Usd context is checked for validity when refreshing stage
- Fixed crash occuring when particles interact with deformable bodies
- Potential material removal crash fix
- Removed
- Fluid Isosurface Glass Box Demo - same feature is showcased by Particle Postprocessing
## [105.0.13] - 2023-06-09
### Core
### General
- Fixed
- omni.physx.ui has its dependency on the hotkey.core extension changed to optional
- Crash occuring when having anisotropy or smoothing on particle system with no fluid particle sets
- Crash occuring when going from pause to stop with anisotropy or smoothing on particle system
- Extremely-high-mass (~1e7 mass units) articulation links would not collide with other actors
- An issue affecting PGS CPU simulation determinacy
- A crash affecting scenes with deformable-rigid attachments
- Character controller camera stability when at a larger distance from zero
### Vehicles
### General
- Fixed
- Crash when a wheel attachment prim of a vehicle with a tank differential was deleted while the simulation was running
## [105.0.12] - 2023-06-01
### Core
### General
- Added
- Exposed mouse and gamepad sensitivity on the ControlsSettings character controller graph node.
- Fixed
- Clear buffered updates for recomputing localPos on joint body paths change if new localPos is received
- The voxel mesh for soft bodies will now be more symmetric to avoid lateral ghost forces. This applies to soft bodies that get a new deformable API applied. Existing APIs in older files keep their mesh.
- Hotkeys conflicting with active character controller inputs are disabled during simulation.
- Character controller camera computes its transformation correctly when in a hierarchy with a parent transformation.
## [105.0.11] - 2023-05-30
### Core
### General
- Fixed
- Joint error icons refresh
- Crash when body enabled was toggled in runtime, while a forceAPI has been active
- Remove cooking button removes cooking API and checks for orphaned cooked data too
### Zero G
### General
- Fixed
- Collision filtering issues
### Vehicles
### General
- Fixed
- Vehicle Creation Wizard triggering UI errors on second page
- Broken camera setup in vehicle Ackermann steering sample
## [105.0.10] - 2023-05-17
### Core
### General
- Fixed
- CPU/GPU difference for articulation joint drives in high-iteration-count simulation steps.
- Fixed joints involving an articulation did not properly lock the rotational degrees of freedom
## [105.0.9] - 2023-05-10
### Core
### General
- Fixed
- Simulation minFramerate accepts 0 as unlimited substepping
- ShapeDebug draw crash
### UI
### General
- Fixed
- Zero G improvements
## [105.0.8] - 2023-05-03
Version 2a6aed5f0b832d51ccbaeb609db1a047fc321f6d
### Core
**General**
- Fixed
- Added 'sdf' as a valid approximation param for omni.physx.utils.setCollider
### UI
**General**
- Fixed
- Zero G improvements
## [105.0.7] - 2023-04-25
Version ccd31c93bdd2d7bd72a50210db2aa2521869d56c
### Core
**General**
- Fixed
- SDK: Fixes convex hull cooking such that coplanar faces are more consistently merged when the GPU polygon limit is hit
- SDK: Fixes crash when all collision geometry is removed from an articulation
- A crash that appeared when deleting a particle set/cloth after the parent particle system has been fixed.
- Crash when cudaContextManager failed to be initialized
## [105.0.6] - 2023-04-14
Version 20a8bc3c8fc04e57724fd96418bfd2c2ccd48ff0
### Core
**General**
- Added
- Support for other simulation engines, omni.physx does not anymore always create bodies if the simulationOwner is not known
- Fixed
- Fixed kind change notification, fixed articulation collider resync notification
- Fixed a crash with when deleting all the colliders from an articulation.
## [105.0.5] - 2023-04-04
Version b16f7d6bbbdd50657f1b2a08dc3982cc270c1aea
### Core
**General**
- Fixed
- Support for MetricsAssembler
## [105.0.4] - 2023-03-29
Version 52d6c8f7efc5f820d4c52da30827e1b736390d12
### Core
**General**
- Added
- CUDA device is now picked as the first device from the assigned displayGroup, if available and not overriden by the cudaDevice setting.
- Fixed
- Kinematic bodies update correctly matches animation
- Prismatic joint body check also checks for position based on the joint's axis.
- Point instancer will group shapes under a static body when no body is present in a prototype.
- Reset camera if a Character controller in first person mode changed it (only when using Python utilities).
- Multiple materials fixes
- Rack and pinion and gear joint delete fixes
- Multiple scenes contact report fix
## [105.0.3] - 2023-03-16
Version 4f9811339a014bdb46748f82a54bf79a3947cd07
### Core
**General**
- Fixed
- FilteredPairs between two articulation roots
- Changed
- USD updated to 22.11
- PhysxSchema.PhysicsPlane replaced by UsdGeom.Plane
## [105.0.2] - 2023-03-09
Version 4669bbbd8b08409081211f5d59ae203538a1c0c7
### Core
**General**
- Added
- Character controller Action Graph nodes.
- Add trigger nodes OmniGraph demos
- Add immediate nodes OmniGraph demos
- Added Contact Event OmniGraph nodes.
- Add immediate OmniGraph node "Compute Mesh Intersecting Faces"
- Add immediate OmniGraph node "Generate Geometry Contacts"
- Add museum demo and HSOV testbed
- Limit to a number of prims in subtrees of selected prims for which the Add menu is fully refreshed to avoid hangs, currently defaults to 100000. This limit is settable in Preferences.
- Changed
- Procedural Cameras are now added using the Add > Cameras right click menu.
- The Update All Cameras button was replaced with an Alwyas Update property in the procedural camera Properties.
- Fixed
- Cooking triangulization fix
- Fix articulation root pose not being properly updated on USD transform change
- Material density update for convex decomposition shapes
- Update kinematics flag
- Properly update joint local poses connected to articulations root links during simulation (accounting also for scaling)
- Fix using "Compute Bounds Overlap" OmniGraph node without any other Immediate mode node
- Deprecated
- Deprecated articulation force sensor
### Vehicles
**General**
- Added
- Many parameters are now recorded by the PhysX Visual Debugger (OmniPVD)
- Fixed
- The vehicle creation wizard falsely stated that chassis and wheel mass were in kilograms. These labels have been removed now since the units of the mass values are actually based on the stage kilogramsPerUnit setting.
# [105.0.1] - 2023-02-27
Version 309e1f29ba9555b67cdb528f2dce051e0d23e8d3
## Core
### General
- Added
- Create python bindings for callback system to detect object changes
- Add Collider Trigger Enter / Leave OmniGraph nodes
- Add Immedate OmniGraph nodes (Compute Geometry Bounds, Compute Geometry Intersection, Compute Geometry Penetration, Compute Bounds Overlaps)
- Changed
- Add omni.physx.graph extension to omni.physx.bundle to make it available by default
- Parsing of transform hierarchy now queries transforms at earliest time instead of default
- Fixed
- Fixed collision-behavior issue when using GPU tensor API to update joint positions and root poses of articulations with links with no collision geometry.
- omni.physx will not crash during startup when CUDA libraries are not present
- Visibility of SDF Mesh and Sphere Fill approximation properties in the Collider widget.
## Vehicles
### General
- Added
- Vehicle Creation Wizard: there is now support to have the wizard work directly on an existing prim hierarchy instead of creating all prims from scratch. All the necessary API schemas will then get applied to the user specified prims.
- Changed
- Vehicle Creation Wizard: UsdGeomScope instead of UsdGeomXform is now used for prims where transforms are irrelevant.
- Fixed
- The wheel positions potentially got flipped if the order of the PhysxVehicleWheelAttachmentAPI prims did not match the order of the corresponding wheel indices.
- Removed
- Vehicle Creation Wizard: the option to adjust the vehicle position has been removed. It can be easily done after the vehicle has been created.
## Force Fields
### General
- Added
- Add a Surface Detection feature that applies forces on the surface along the surface normal. This induces rotation into the resulting motion.
- Added an option to scale forces by the cross sectional area of the Rigid Body facing the applied force. This is on by default and may require retuning previous Force Field coefficients or turning this scaling off.
# [105.0.0] - 2023-02-06
Version 27128a7963e0a6a98d0fece2c3225e97794e5115
## Core
### General
- Added
- Allows the user to approximate a triangle mesh as a collection of spheres
- IPhysxCooking precook function to populate cooking data
- Shift+double-click now triggers force push during simulation. Keep the button down for continued application.
- Added new display option for rigid body mass properties in the view menu.
- Add collision audio to physics demos.
- Support for using animated meshes as kinematic deformable bodies
- Limit to a number of selected prims for which the Add menu is fully refreshed to avoid hangs, currently defaults to 1000. If this limit is reached the Add menu will show all options and a warning on top. This limit is settable in Preferences.
- Changed
- Add menu will now list all options for large selections regardless of the type of prims selected or APIs applied to avoid hangs. The selection prim limit for filtering of the Add menu can be changed in Physics Preferences.
- Most demos now use a room-scale scene and have been scaled or modified to fit it
- Selecting multiple rigid bodies when the mass distribution manipulator is enabled now shows combined mass properties.
- Added Deformable Visualization option to hide attached actors
- Heavy rework of zerog and zerog sweep: improved zerogravity sweep algorithm, automatic precooking, rendering improvements, colliders reusing, UX improvements.
- Fixed
- ZeroGravity sweep mode improvements - solved point instancing issues, small movements now don't reset the sweeping area entirely and greatly enhanced user experience moving bvh construction/refit/hit scans/selection updates to pooled lower priority secondary threads. Plus a bunch of other bugfixes to make it more stable.
- Disallow usage of force grab during inspector simulation, that can potentially cause crash.
- Makes custom cone and cylinder more stable when colliding with much bigger objects (a cylinder rolling on a very long rail)
- Attachment visualization works with animated kinematic rigid bodies
- Fix crash on updating joint state for joint that has been removed during simulation
- Improve performance on colliders solid meshes visualization (Physics Debug->Colllision Mesh Debug Visualization->Explode View Distance)
- Removed
- Removed deprecated simulation event stream
## Vehicles
### General
- Changed
- The attributes suspensionFramePosition, wheelFramePosition, wheelCenterOfMassOffset, suspensionForceAppPointOffset, tireForceAppPointOffset (see PhysxVehicleWheelAttachmentAPI) and suspensionForceAppPoint, tireForceAppPoint (see PhysxVehicleSuspensionComplianceAPI) now take the total scale of the vehicle prim into account. Note that it is still recommended to stick to identity scale when using vehicles since not all attributes are scale aware.
- Fixed
- Crash on invalid USD setup, having no physics scene prim with the PhysxVehicleContextAPI API schema applied.
### USD Schemas
- Added
- The custom metadata physxVehicle:referenceFrameIsCenterOfMass has been introduced to define in what space certain wheel attachment properties are interpreted in. If set to True, the reference frame will be the vehicle center of mass frame. If set to False, the reference frame will be the vehicle prim frame. The affected properties are: suspensionTravelDirection, suspensionFramePosition, suspensionFrameOrientation, suspensionForceAppPointOffset, wheelCenterOfMassOffset and tireForceAppPointOffset (see PhysxVehicleWheelAttachmentAPI). This custom metadata can be set on the prim that has PhysxVehicleAPI applied. Note that using the center of mass frame as reference frame (=True) is deprecated and will not be supported for much longer.
- Deprecated
- The PhysxVehicleWheelAttachmentAPI properties suspensionTravelDirection, suspensionFramePosition, suspensionFrameOrientation, suspensionForceAppPointOffset, wheelCenterOfMassOffset and tireForceAppPointOffset were interpreted as being relative to the vehicle center of mass coordinate frame. In the future, these properties will be interpreted as being relative to the vehicle prim coordinate frame. For backwards compatibility reasons, the old interpretation is still used as the default but it is highly recommended to switch to the new interpretation as soon as possible. See the section about the new custom metadata physxVehicle:referenceFrameIsCenterOfMass which can be used to enable the new interpretation.
### Python Bindings API
- Changed
- The IPhysx.get_wheel_state function will use a different coordinate frame for the provided wheel transforms depending on the value of the custom metadata physxVehicle:referenceFrameIsCenterOfMass. See the API documentation of this function for details.
- Removed
- The deprecated IPhysxVehicle.set_to_rest_state method has been removed. Please use IPhysx.set_vehicle_to_rest_state of the omni.physx extension instead.
## C++ API
- Changed
- The IPhysx.getWheelState and IPhysx.getWheelTransformations functions will use a different coordinate frame for the provided wheel transforms depending on the value of the custom metadata physxVehicle:referenceFrameIsCenterOfMass. See the API documentation of these functions for details.
- Removed
- The deprecated IPhysxVehicle.setToRestState method has been removed. Please use IPhysx.setVehicleToRestState of the omni.physx extension instead.
## Force Fields
### General
- Added
- A new Conical Force Field can push objects from a central point. Fall off and angular limits can be set to control the magnitude of the force. A new OmniGraph demo is provided to illustrate how it works.
- Fixed
- The OmniGraph Force Field demo works again. Press Control-C to grab barrels and release to throw them.
### USD Schemas
- Added
- Added a new schema for a cone shaped Force Field.
## [104.2.4-5.1] - 2023-02-03
Version df874d67738df98835b6b5cf36ecec49a1207446
### Core
- Fixed
- Bug involving GPU simulation where newly created actors could miss collisions against existing actors.
- Debug visualization for point instancer with indices out of prototypes.
## [104.2.3-5.1] - 2023-01-30
Version 0baa322e1d6882284a50903e3ceba85f38df8ab3
### Core
- Fixed
- Softbody attachments visualization crash.
- Joint visualization crash fix with invalid descriptors.
- Apply force error to disabled bodies.
- Filtering pairs crash.
- Added
- Fabric change tracking pause exposed to python bindings.
## [104.2.2-5.1] - 2023-01-24
Version 71c501e407fb45cc3469c30af271c804801b7f26
### Core
- Fixed
- Crashes where CudaContextManager failed to be created.
- Demo text draw.
- Contact report call when no scene exists.
- Contact report crash when no points are reported.
- Trigger reporting if either trigger or the other collider is deleted.
- Race condition in omni physx cooking.
- Fixed issue on CentOS7 with incorrect math library.
- Crash in create D6 joint if the input parameters are illegal.
- Sending correctly create/destroy object notification if a body changes from dynamic to static.
## [104.2.1-5.1] - 2023-01-17
Version bfc1e042528ccf11058577e0438464b4d5be6db0
### Core
- Fixed
- Material property updates when using GPU simulation with omni.physics.tensors.
- Create of an external joint.
- Unregister custom log channel for supportui.
- Articulation Force Sensor delete issues.
- Changed
- Toggling whether to use convex mesh or custom geometry for cube and cylinder geometry is now a general setting found under Physics Settings. The default is using custom geometry.
- Added
- Missing is_sleeping/wake_up/put_to_sleep functionality for articulations.
### Vehicles
- Fixed
- Some auto-running samples could cause the application to freeze up when the running sequence ended.
## Core
- Fixed
- Custom cone and custom cylinder behavior.
- Bounce threshold minimal value, cant be zero.
- Crash in error reporting when CUDA initialization failed.
- Contact report issue when zero gravity was disabled.
- Crash when articulation root got deleted while rest of the hierarchy was still present.
- JointState update if the joint was removed during simulation.
- Crash when shape was enabled but not yet inserted into a scene.
- Changed
- Improved demos scope usage.
## [104.1.6-5.1] - 2022-12-09
Version c8bc89fe7a83d2121fb0d171e8cedd980c351d2d
## Core
- Fixed
- Hierarchy delete with rigid bodies and joints.
- Demo categories.
- Shift click mouse gesture dragging.
## [104.1.5-5.1] - 2022-12-05
Version c6c19ec941a4d2a69f24014744e13f108a02bffa
## Core
- Fixed
- Missed collisions with convex hull colliders.
- Cooking data save for not writable prims.
- ForceAPI applied to a static or kinematic body.
- Material creation with invalid parameters.
- Replicator materials.
- Crash when multiple deformable bodies were deleted.
## Vehicles
**General**
- Fixed
- Suspension compliance sample.
## [104.1.4-5.1] - 2022-12-01
Version 05c0c29247ae0f2c83e5d73139f3e527f249cfd5
## Core
- Fixed
- Mass distribution and physics inspector combined usage crash.
- Physics demo closing script fix.
- Contact reporting crash when zero gravity extension was unloaded.
- Rope demo fix.
- Articulation parsing crash fix.
- Picking crash when a link was deleted.
- Supportui crash when new stage was loaded.
- Added
- Force grab override.
## Vehicles
**General**
- Fixed
- Crash on invalid USD setup (attribute rigidBodyEnabled being set to false on PhysicsRigidBodyAPI API schema or attribute kinematicEnabled being set to true together with vehicleEnabled being set to true).
## [104.1.3-5.1] - 2022-11-25
Version 15b4f133baae15b16bde5fa7df5fb130fe8867e6
## Core
- Fixed
- Particle cloth rendering with flatcache and tensor API.
- Crash when flatache extension was closed during simulation.
- Get scene pointer crash fix when physics toolbar was used.
- PhysX SDK binary compatibility.
- Deformable debug visualization.
- Changed
- Demos category reorganization.
## Vehicles
**General**
- Fixed
- Crash on invalid USD setup, having no physics scene prim with the PhysxVehicleContextAPI API schema applied.
## [104.1.2-5.1] - 2022-11-21
Version 013b7d61a0d0bb7c7c75cd21ae998c920469dfc5
### Core
- Added
- IPhysxReplicator interface for physics replication.
- physics/disableContactProcessing setting to skip onContact processing in omni.physx.
- physics/saveCookedData setting to skip saving cooked data into USD.
- Changed
- Zero gravity sweep mode improvements.
- Physics toolbar improvements for auto collision mode on scenes with existing physics.
- Fixed
- Flatcache reset on stop functionality.
## [104.1.1-5.1] - 2022-11-16
Version e864c1d0c486956db1d4b4448fe52beb923d390b
### Core
- Added
- PhysxSDFMeshCollisionAPI for SDF properties. “sdf” is an additional valid token for the physics:approximation property. Setting it in the UI applies the new API.
- Support angular surface velocity on kinematic bodies.
- Changed
- ResetOnStop persistent setting was changed to non-persistent.
- SDF properties from PhysxTriangleMeshCollisionAPI were moved into the new PhysxSDFMeshCollisionAPI.
- Improved physics toolbar work with scene graph instancing.
- Mass manipulation improvements.
- Fixed
- Floating articulation root joint determinism.
- RigidBody manipulator with kinematic bodies.
## [104.1.0-5.1] - 2022-11-09
Version 575f53e707ad3b2cfdfa1af2c735dc3f3b6952fb
### Core
- Added
- Shape volume into IPhysxPropertyQuery.
- Physics Authoring toolbar supports instanced assets.
- Changed
- Dynamic rigid bodies that do have animated xformOp are converted automatically to kinematic bodies. Warning is issued.
- Mass distribution manipulator enhancements.
- Simulation info window cleanup.
- Fixed
- SDF collisions contact report.
- Physics Authoring toolbar disappears when layout window is used to reset windows.
- Range traversal fix for prims with only overs.
### Vehicles
- General
- Added
- Extra wheel authoring helpers to configure steer/brake/differential multipliers on a wheel attachment prim.
- Fixed
- IPhysXPropertyQuery: Report aabbLocalMin / aabbLocalMax with correct local scaling instead of global scaling
## [104.0.4-5.1] - 2022-10-27
Version 01507652991331a3f20d04bbcf5bc81df3f9f51e
### Core
- Changed
- Simulation output window warns if scene graph instancing is used without omni hydra support enabled.
- Fixed
- IPhysXPropertyQuery: return valid bounding box for capsule shape
- Correct updates to mass properties at runtime
- Spherical joint position/-target user input check correctness
### Graph
- Changed
- Scene query graph demo now checks for omni graph flags that are required for the demo to work properly.
## [104.0.3-5.1] - 2022-10-21
Version 31957463
### Core
- Fixed
- Docking of Physics Authoring Toolbar to the main Viewport does not show Viewport tab (unless it was shown before).
- Physics Authoring Toolbar: Collider creation: if existing collider on a prim matches the collider simplification target type, it is skipped and no notification message is shown.
- Physics Authoring Toolbar: When auto. collision creation mode is enabled, any prim which has any physics or physx schema applied, is skipped. When collision creation is requested manually by clicking appropriate button on the toolbar, only allowed existing physics components on selected prim are CookedDataAPI, CollisionApi and RigidBodyAPI, otherwise coll. creation is skipped.
- Physics Inspector button removed from Physics Authoring Toolbar (can be found under Settings submenu of the toolbar itself)
- Crash if cuda context manager was not created correctly and GPUExtensions tried to initialize.
- Mass visualization improvements, you can enable the feature via new button that was added to the Physics Authoring Toolbar.
## [104.0.2-5.1] - 2022-10-14
Version 31932187
### Core
- Fixed
- Reset rigid body for referenced prims when xformOp order was not overridden.
- ForceField extension loading/unloading.
- Fixed articulation crash when deleted.
- Pressing play does not reset the property window scroll position.
- OmniPVD OVD recording bug fixed
- Added
- Enable/Disable Solve Contact for a rigid body.
### Vehicles
**General**
- Fixed
- Tank snippet sending wrong warning messages about using deprecated attributes when running more than once.
- Friction vs. slip graph not showing up in the property window and not updating limits correctly when changing the values interactively.
- Assert when collision geometry childed to a wheel attachment was using non unit scale.
- Error message showing up when opening filter window for adding tire friction table target.
## [104.0.1-5.1] - 2022-10-04
Version
### Core
**General**
- Fixed
- Gravity magnitude changes when starting at 0.
- SupportUI physics inspector treeview issues and joint authoring for joints without limits.
- IPhysxFlatcache interface release.
- Removed
- Deprecated event stream V1 usage.
- Added
- Disable for omni.physx.ui USD notice handling.
## [104.0.0-5.1] - 2022-10-01
Version 31867423
### Core
**General**
- Fixed
- Transform gizmo is disabled when pressing Shift to prevent it colliding with the mouse push or drag functionality.
- Angular velocity now properly adjusts the “Velocities in Local Space” setting.
- Some advanced properties for spherical and distance joints now appear correctly in the UI.
- Collision filtering for triggers.
- Invisible prims are no longer grabbed in simulation mode.
- Parsing of Improve Patch Friction attribute: The fallback (i.e. if unauthored) is now correctly parsed to enabled.
- Crashes when articulations miss contacts due to inadequate contact offsets.
- Debug visualization for asynchronous simulation is now working correctly.
- Triggers work correctly with convex decomposition colliders.
- Typo in particle debug visualization setting /persistent/physics/visualizationDisplayParticlesShowFluidSurface.
- Made OmniPVD sampling more robust.
- Joint helpers respect correctly visibility attribute.
- Point instancers parsing with timesampled values.
- Mass inertia when set back to 0,0,0 autocomputation gets correctly triggered.
- Fixed incorrect assignment of PDB material
- Changed
- Local cache path moved out from Documents folder to local OV cache folder. Example: C:\Users${username}\Documents\Kit\apps${appname}\cookedmeshcache -> C:\Users${username}\AppData\Local\ov\cache\Kit${kitversion}${hexnumber}\cookedmeshcache
## Vehicles
### General
#### Changed
- The vehicle simulation code has been refactored and changes in vehicle dynamics behavior are expected, especially with respect to the suspension force and tire slip.
- Many USD attributes of various vehicle components have been deprecated and will not be shown in the corresponding property widgets any longer. They can still be found in the Raw USD Properties view though.
- Previously, it was possible to configure the suspension to create an asymmetric and physically questionable spring behavior. This was the case when having the maxDroop attribute value largely diverge from the recommended value of: ((sprungMass x gravity) / springStrength). Now it is not possible to create such an asymmetry any longer but as a consequence, the rest state of the suspension can change significantly and adjustments to the maxDroop value will be required (for example, if a larger value than the recommended one was used, the vehicle will end up sitting higher above ground than previously).
- Vehicle rigid bodies should set the disableGravity attribute of the PhysxRigidBodyAPI API schema to true or else a warning will get triggered.
- The computation of tire slip does not any longer try to artificially keep the slip low for cases where the longitudinal speed is low but wheel rotation speed is high. As a consequence, vehicles might accelerate more aggressively than previously in which case the tire longitudinal stiffness (longitudinalStiffness attribute of the PhysxVehicleTireAPI API schema) can be reduced to get closer to the legacy behavior. Furthermore, there is also a higher probability to encounter instabilities if a large tire longitudinal stiffness is chosen and at the same time a large simulation timestep is used. In such a case two options can be considered: either reducing the stiffness or increasing the number of vehicle simulation substeps (lowForwardSpeedSubStepCount and highForwardSpeedSubStepCount vehicle attributes). It is also possible to decrease the overall simulation timestep size (increasing timeStepsPerSecond of the physics scene), this, however, affects the whole simulation, thus increasing the vehicle simulation substep count is preferable as a first thing to try.
- Using sweeps to detect collisions of the wheels with the ground does not require the wheels to have a collider any longer. The wheel radius and width will define the collision geometry that is used internally for the sweep.
- **Changed**
- The lowForwardSpeedSubStepCount and highForwardSpeedSubStepCount vehicle attributes are limited to a max number of 255.
- The Vehicle Creation Wizard will set the targetGear attribute of the PhysxVehicleControllerAPI API schema to 1 for basic drive vehicles and to 255 (automatic gear change mode) for standard drive vehicles now (previously, 0 was used for those types).
- The vehicle autobox will no longer kick in unless the target gear is set to automatic gear change mode (often referred to as “DRIVE” in automatic transmissions. Use the special value 255 for this purpose). If the transmission is in reverse or neutral gear, switching to automatic mode will have the same effect as switching to first gear.
- Vehicles with basic drive will not accelerate any longer if the target gear is set to 0. Use a positive value for target gear to have a forward torque being applied to the wheels.
- Part of the vehicle update logic will now run in parallel on multiple threads if available and if there are enough vehicles to simulate.
- The local pose of the wheel collision shape prim with respect to its parent wheel prim will be accounted for in the computation of the local pose given to the PxShape instance that represents the wheel’s collision shape.
- **Fixed**
- The effect of camber was not implemented properly. If the effect should be ignored, it is now important to set the camberStiffness attribute to 0.
- **Added**
- Many new features and parameters have been added. See the USD Schemas section for more details.
- Wheel based tank vehicles are now available (see USD API schemas PhysxVehicleTankDifferentialAPI and PhysxVehicleTankControllerAPI). The Vehicle Creation Wizard has an additional option “Tank Mode” to create such a vehicle type.
- The Vehicle Creation Wizard has now an option to make use of Ackermann correction for a pair of steered wheels.
- **USD Schemas**
- **Changed**
- PhysxVehicleTireAPI API schema
- The longitudinalStiffnessPerUnitGravity attribute will now be set to 500 if not specified.
- The longitudinalStiffnessPerUnitGravity attribute has been deprecated and will be removed in the future. Please use the new attribute longitudinalStiffness instead. When migrating code/assets, multiply the old value by the gravitational acceleration.
- The camberStiffnessPerUnitGravity attribute will now be set to 0 if not specified.
- The camberStiffnessPerUnitGravity attribute has been deprecated and will be removed in the future. Please use the new attribute camberStiffness instead. When migrating, multiply the old value by the gravitational acceleration.
- The latStiffX and latStiffY attributes have been deprecated and will be removed in the future. Please use the new lateralStiffnessGraph attribute instead. When migrating code/assets, latStiffX can be used as the first entry of lateralStiffnessGraph. The second entry can be approximated using (latStiffY x sprung mass x gravitational acceleration).
- PhysxVehicleAutoGearBoxAPI API schema
- The upRatios attribute must not contain an entry for neutral gear any longer (there will be no automatic shift from neutral to first gear anymore).
- PhysxVehicleSuspensionAPI API schema
- The maxDroop attribute can now be set to a negative number to indicate that the value should be computed automatically.
- The maxDroop and maxCompression attributes have been deprecated and will be removed in the future. Please use the new travelDistance attribute instead (set it to maxDroop + maxCompression when migrating your code/assets).
- The camberAtRest, camberAtMaxCompression and camberAtMaxDroop attributes have been deprecated and will be removed in the future. Please use the new PhysxVehicleSuspensionComplianceAPI API schema instead to specify a non-zero camber angle.
- PhysxVehicleDriveBasicAPI API schema
- The peakTorque attribute will now be set to 1000 if not specified. Furthermore, 0 is now a valid value too.
- PhysxVehicleWheelAttachmentAPI API schema
- The driven attribute will be removed in the future. Please use the new PhysxVehicleMultiWheelDifferentialAPI API schema instead to describe the wheels that are driven by the engine.
- The wheelCenterOfMassOffset attribute is deprecated and will be removed in the future. Please use the new attributes suspensionFramePosition and suspensionFrameOrientation instead. For more details see the entry in the “Added” section about these new attributes.
- The suspensionForceAppPointOffset and tireForceAppPointOffset attributes have been deprecated and will be removed in the future. Please use the new PhysxVehicleSuspensionComplianceAPI API schema instead to specify the force application points or else leave it up to omni.physx to choose the points.
- PhysxVehicleWheelAPI API schema
- The maxBrakeTorque and maxHandBrakeTorque attributes have been deprecated and will be removed in the future. Please use the new PhysxVehicleBrakesAPI API schema instead to specify the wheels that encounter a brake torque and to define the maximum torque that can be applied. See entry about PhysxVehicleBrakesAPI for more details.
- The maxSteerAngle attribute has been deprecated and will be removed in the future. Please use the new PhysxVehicleSteeringAPI API schema instead to specify the wheels that are steerable and to define the maximum steer angle that can be applied. See entry about PhysxVehicleSteeringAPI for more details.
- The toeAngle attribute has been deprecated and will be removed in the future. Please use the new PhysxVehicleSuspensionComplianceAPI API schema instead to specify a non-zero toe angle.
- PhysxVehicleControllerAPI API schema
- The brake and handbrake attributes have been deprecated and will be removed in the future. Please use the attributes brake0/brake1 instead. See entry about PhysxVehicleBrakesAPI for more details.
- The steerLeft and steerRight attributes have been deprecated and will be removed in the future. Please use the attribute steer instead (see corresponding entry under the Added section).
- PhysxVehicleContextAPI API schema
- The upAxis and forwardAxis attributes have been deprecated and will be removed in the future. Please use the new attributes verticalAxis and longitudinalAxis instead. Note that these new attributes expect token values instead of vectors to make it very explicit that only the main axis directions are supported.
- PhysxVehicleAPI API schema
- The minLongitudinalSlipDenominator attribute has been deprecated and will be removed in the future. Please use the new attribute minPassiveLongitudinalSlipDenominator instead.
- PhysxVehicleEngineAPI API schema
- The attributes peakTorque, maxRotationSpeed, dampingRateFullThrottle, dampingRateZeroThrottleClutchEngaged and dampingRateZeroThrottleClutchDisengaged now also accept 0 as a valid value.
- Added
- PhysxVehicleEngineAPI API schema
- Has a new attribute idleRotationSpeed to define the minimum rotation speed of the engine.
- PhysxVehicleTireAPI API schema
- Has a new attribute restLoad that allows to explicitly specify the rest load of the tire. The attribute has a default value of zero which means it gets computed automatically using (sprungMass x gravity) as an approximation.
- Has a new attribute lateralStiffnessGraph which replaces the deprecated attributes latStiffX and latStiffY.
- Has a new attribute longitudinalStiffness which replaces the deprecated attribute longitudinalStiffnessPerUnitGravity.
- Has a new attribute camberStiffness which replaces the deprecated attribute camberStiffnessPerUnitGravity.
- PhysxVehicleAPI API schema
- Has a new set of attributes to give some control over the sticky tire mode. See attributes longitudinalStickyTireThresholdSpeed, longitudinalStickyTireThresholdTime, longitudinalStickyTireDamping, lateralStickyTireThresholdSpeed, lateralStickyTireThresholdTime, lateralStickyTireDamping.
- Has new attributes minPassiveLongitudinalSlipDenominator, minActiveLongitudinalSlipDenominator and minLateralSlipDenominator to define minimum values for the denominator when computing tire slip. The attribute minPassiveLongitudinalSlipDenominator replaces the deprecated attribute minLongitudinalSlipDenominator.
- PhysxVehicleWheelAttachmentAPI API schema
- Has new attributes suspensionFramePosition and suspensionFrameOrientation to define the transform of the suspension at max compression relative to the vehicle’s center of mass frame. These attributes replace the deprecated wheelCenterOfMassOffset attribute. Note that as mentioned, these new attributes define the suspension transform at max compression while wheelCenterOfMassOffset used to define the local space wheel position at rest. For migrating old assets/code, the suspensionFramePosition can be set to: wheelCenterOfMassOffset - (suspensionTravelDirection x physxVehicleSuspension:maxCompression).
- Has new attributes wheelFramePosition and wheelFrameOrientation to define an additional transform of the wheel relative to the suspension frame. This allows to, for example, have the steering axis not go through the wheel center or to introduce a fixed toe angle.
- Has a new attribute “index” which will be used to reference wheel attachments as well as to order the wheel attachments within a vehicle.
- PhysxVehicleMultiWheelDifferentialAPI API schema (new)
- This new API schema has been introduced to define which wheels are driven by the engine. It also allows to specify how torque should be distributed among the driven wheels. This API schema is meant to replaces the “driven” attribute of the PhysxVehicleWheelAttachmentAPI API schema and will take precedence if used.
- PhysxVehicleTankDifferentialAPI and PhysxVehicleTankControllerAPI API schemas (new)
- These new API schemas have been introduced to set up a vehicle as a wheel based tank.
- PhysxVehicleBrakesAPI API schema (new)
- This new API schema has been introduced to specify the wheels that will encounter a brake torque when the brake control fires. The maximum brake torque as well as wheel specific multipliers can be defined too. To allow for up to two sets of brake configurations, PhysxVehicleBrakesAPI has been defined as a multiple apply API schema. The instance names “brakes0” and “brakes1” are used to distinguish between the two configurations. This is a generalization of the previous brake/handbrake split that was rather rigid. As a consequence, the brake controls that go with the two configurations are called brake0 and brake1 and can be found in the PhysxVehicleControllerAPI API schema.
- PhysxVehicleControllerAPI API schema
- Has two new attributes brake0/brake1 that replace the deprecated brake/handbrake attributes. See previous entry for more info.
- Has a new attribute steer that replaces the deprecated steerLeft/steerRight attributes. The equivalent of a steerLeft/steerRight value pair of 1/0 is steer=1 and the equivalent of 0/1 is steer=-1.
- PhysxVehicleSteeringAPI API schema (new)
- This API schema has been introduced to specify the wheels that are affected by the steer control (see PhysxVehicleControllerAPI). The maximum steer angle as well as wheel specific multipliers can be defined too.
- PhysxVehicleAckermannSteeringAPI API schema (new)
- This API schema can be used to steer a pair of wheels with Ackermann correction applied.
- PhysxVehicleSuspensionAPI API schema
- Has a new attribute travelDistance to define the distance the suspension can travel from max compression to max droop. This attribute replaces the deprecatd maxDroop, maxCompression attributes.
- PhysxVehicleSuspensionComplianceAPI API schema (new)
- This API schema has been introduced to specify toe angle, camber angle and force application points. These properties can either be set to fixed values or denote fixed sized graphs where the values depend on the suspension jounce.
- **PhysxVehicleTireFrictionTable IsA schema**
- Has a new attribute `defaultFrictionValue` to specify what friction value to use if the material of the ground surface is not listed in `physxVehicleTireFrictionTable:groundMaterials`.
- **PhysxVehicleContextAPI API schema**
- Has two new attributes `verticalAxis` and `longitudinalAxis` that replace the deprecated `upAxis` and `forwardAxis` attributes.
- **PhysxCharacterControllerAPI API schema**
- All CharacterControllerAPI properties were moved to PhysxCharacterControllerAPI.
- **PhysxTriangleMeshCollisionAPI API schema**
- Added new attributes to set up and control sparse SDFs. The new attributes are `sdfResolution`, `sdfSubgridResolution`, `sdfBitsPerSubgridPixel`, `sdfNarrowBandThickness` and `sdfMargin`.
- **Removed**
- **PhysxVehicleControllerAPI API schema**
- The `automatic` attribute has been removed. To enable automatic gear change mode, the `targetGear` attribute has to be set to the special value 255 instead. Note that a vehicle still needs PhysxVehicleAutoGearBoxAPI configured to enable automatic mode.
- **PhysxVehicleContextAPI API schema**
- The `sweepRadiusScale` and `sweepWidthScale` attributes are not supported any longer and have been removed.
- **CharacterControllerAPI API schema**
- CharacterControllerAPI was removed and its properties moved to PhysxCharacterControllerAPI.
- **PhysxTriangleMeshCollisionAPI API schema**
- Custom attribute `physxsdfcollision:resolution` got removed and replaced by `physxTriangleMeshCollision:sdfSubgridResolution`
- **Python Bindings API**
- **Changed**
- The `IPhysxVehicle.get_drive_data` method has been deprecated and will be removed in the future. Please use `IPhysx.get_vehicle_drive_state` of the omni.physx extension instead.
- The `IPhysxVehicle.set_wheel_rotation_speed` and `IPhysxVehicle.set_wheel_rotation_angle` methods have been deprecated and will be removed in the future. Please use `IPhysx.set_wheel_rotation_speed` and `IPhysx.set_wheel_rotation_angle` of the omni.physx extension instead.
- The `IPhysxVehicle.get_wheel_query_results` and `IPhysxVehicle.get_wheel_data` methods have been deprecated and will be removed in the future. Please use `IPhysx.get_wheel_state` of the omni.physx extension instead.
- The `IPhysxVehicle.compute_sprung_masses` method now returns an empty list if the computation failed.
- The `IPhysxVehicle.compute_wheel_simulation_transforms` method has been deprecated and will be removed in the future. Please use `IPhysxVehicle.compute_suspension_frame_transforms` instead.
- **Added**
- The variable `VEHICLE_AUTOMATIC_TRANSMISSION_GEAR_VALUE` (import from omni.physx.bindings._physx) can be used to avoid hardcoding the special value for automatic gear change mode.
- The `IPhysxVehicle.compute_suspension_frame_transforms` method has been added as a replacement for `compute_wheel_simulation_transforms`.
- **C++ API**
- **Changed**
- The `IPhysxVehicle.getDriveDynData` and `IPhysx.getVehicleDriveData` methods have been deprecated and will be removed in the future. Please use `IPhysx.getVehicleDriveState` of the omni.physx extension instead.
- The `IPhysxVehicle.setWheelRotationSpeed` and `IPhysxVehicle.setWheelRotationAngle` methods have been deprecated and will be removed in the future. Please use `IPhysx.setWheelRotationSpeed` and `IPhysx.setWheelRotationAngle` of the omni.physx extension instead.
- The `IPhysxVehicle.getWheelQueryResults` and `IPhysxVehicle.getWheelDynData` methods have been deprecated and will be removed in the future. Please use `IPhysx.getWheelState` of the omni.physx extension instead.
- The `IPhysxVehicle.computeSprungMasses` method now returns a boolean to denote success or failure.
- If `IPhysx.getWheelTransformations` is used with `addVehicleTransform=false`, then the transforms will now be relative to the vehicle rigid body center of mass frame and not the vehicle frame.
- The `IPhysxVehicle.computeWheelSimulationTransforms` method has been deprecated and will be removed in the future. Please use `IPhysxVehicle.computeSuspensionFrameTransforms` instead.
- **Added**
- The constant expression `VehicleControllerDesc::automaticGearValue` in the `PhysxUsd` header file can be used to avoid hardcoding the special value for automatic gear change mode.
- The `IPhysxVehicle.computeSuspensionFrameTransforms` method has been added as a replacement for `computeWheelSimulationTransforms`. It computes and sets the newly introduced `suspensionFramePosition` and `suspensionFrameOrientation` USD attributes of the `PhysxVehicleWheelAttachmentAPI` API schema.
## [1.4.19-5.1] - 2022-09-02
Version: 31722217
### Core
**General**
- Fixed
- Transformation reset for referenced rigid bodies.
- Physics material assignment issues.
- Prismatic joint visualization clipping issue.
## [1.4.18.2-5.1] - 2022-08-16
Version: 31691169
### Core
**General**
- Update to include optimizations for pairs filtering.
## [1.4.18.1-5.1] - 2022-08-08
Version: 31655032
### Core
**General**
- Fixed
- Crash in simulation for stages without a PhysicsScene and with CollisionGroups.
- Exclusive shape error when PointInstancer is used.
- Cloth wireframe fix for visualization in debug viz.
- Added
- Lego buggy and teddy on ice demo.
## [1.4.17.1-5.1] - 2022-07-28
Version: 31624704
### Core
**General**
- Fixed
- Transformation xformOp stack reset with a suffix xformOp.
- Transformation xformOp stack and velocities attributes are cleared on stop if simulated in a layer without an opinion.
- Viewport2 and viewport legacy physics compatibility fixes.
## [1.4.16.1-5.1] - 2022-07-25
Version: 31602073
### Core
**General**
- Added
- Support for viewport2.
- Visualization for physics picking while simulation is running.
## [1.4.15.1-5.1] - 2022-07-20
Version: 31588921
### Core
**General**
- Added
- Exposed armature for articulated joints through PhysxJointAPI.
- Exposed constraint-force-mixing scale term for articulated bodies through PhysxRigidBodyAPI.
- Support for setting particle cloth points and velocities during simulation (to implement reset)
- TensorAPI updates
## [1.4.14-5.1] - 2022-06-20
Version 31475809
### Core
**General**
- Fixed
- Joint localPose parsing fix.
- Point instancer debug visualization.
- Particle post processing enable/disable fix.
- Mass computation for rigid bodies with triggers.
- Changed
- Zero gravity button is disabled when simulation is running.
## [1.4.13-5.1] - 2022-06-01
Version 31412806
### Core
**General**
- Fixed
- (No specific issues listed under this version)
## [1.4.12-5.1] - 2022-05-27
### Core
**General**
- **Fixed**
- Materials assigned to instanced colliders
- Fixed performance issues with collision groups on linux
- **Added**
- Setting physics/cudaDevice to define preferred cudaDevice for PhysX SDK
## [1.4.11-5.1] - 2022-05-20
Version 31370036
### Core
**General**
- **Fixed**
- Crashes when articulations miss contacts due to inadequate contact offsets
## [1.4.10-5.1] - 2022-05-17
Version 31350991
### Core
**General**
- **Fixed**
- Crash when setting transform scale to zero on attached deformable body
- Attachment debug visualization out of sync with updated attachments
- Tensor API error logging code
## [1.4.9-5.1] - 2022-05-11
Version 31325511
### Core
**General**
- **Fixed**
- Crash when adding particles to an empty particle system while sim is running
- Memory leak in isosurface generation
- Bug causing inaccurate particle-solid collisions
- Crash in poisson sampling
- Crash when using contact reports with SDF tri-mesh collision preview feature
- Articulation force sensors force reporting uninitialized memory forces on first stage update after timeline play when no sim steps were run
- Spherical joint hard vs soft limit.
- Static collider transformation for instanced prims.
- **Added**
- Spherical and Prismatic joints with disjointed body transforms will simulate and produce a warning.
- NaN validation check for USD transformation writes.
## [1.4.8-5.1] - 2022-05-04
Version 31296124
### Core
**General**
- **Fixed**
- Removed assumptions in the code that particles will always be rendered using USD spheres.
- Rigid static and kinematic bodies transforms are not reset on simulation stop/reset.
- Fixes in particle debug visualization.
- Fix mass computation for scaled particle cloth
- Fix crash when adding deformable body component to mesh with time sampled points. Added warings for collider, particle cloth, particle sampler components.
- **Added**
- OverlapShape/OverlapShapeAny added, takes arbitrary UsdGeomGPrim and uses that for overlap queries.
## [1.4.7-5.1] - 2022-04-27
version 31270438
### Core
**General**
- **Fixed**
- CollisionAPI applied to a prim in a hierarchy creates correctly static bodies.
- Fix maximal-coordinate joints limits being clamped inside [-90, 90] range
### Fixes and Improvements
- Joint icons will refresh properly when omni.physx.ui is enabled after a stage was already loaded.
- Joint error icons selection fix.
- Joint localPose computation if bodies had scale.
- When creating joints with createJoint(s) util with two selected prims the prim that was selected first is assigned to body 0 and the one selected second to body 1 instead of vice versa.
- Parsing optimizations and runtime update loop optimizations.
- Added
- Use PhysX unwrapped joints on revolute joints without limits to avoid infinite spinning with drive targets outside [-360, 360]
- JointStateAPI - support for saving and restoring joint states (articulated joints are supported only atm). Changes to joint state position and velocities is possible only during simulation.
## [1.4.6-5.1] - 2022-04-19
Version 31229710
### Core
**General**
- Fixed
- Attribute arrays dimension mismatch crash for user manually instanced actors.
- Particle cloth pulled to orgin bug
- Changed
- Detected closed articulation loops will print all looped joints and will not create the loop joint by default.
- Show warning when the particle cloth contains vertices with too many adjacent triangles to fully support lift and drag
- Revolute and Fixed joints with disjointed body transforms will simulate and produce a warning.
## [1.4.5-5.1] - 2022-04-08
Version 31184222
### Core
**General**
- Fixed
- Tensor API fixes.
- Joint visualization for invisible joints.
- Particle cloth cooking crash fix.
- Changed
- Improved behavior of particle fluids near solid boundaries.
- Reduced default collision filtering radius for deformable body and particle cloth attachments.
- Increased welding tolerance for particle cloth cooking to support default mesh primitives.
- Added
- Revolute and Fixed joints with disjointed body transforms will not simulate. Error marker will appear over joint helpers of joint with such body transforms.
- Added interface and Python bindings for physics interaction API.
- “Particle Postprocessing” and “Particle Sampler” tutorial snippets.
## [1.4.4-5.1] - 2022-04-04
Version 31161611
### Core
**General**
- Added
- Particles debug visualization: Debug-window option to display render-geometry radius in addition to offsets.
- Per Rigid Body local velocity / global velocity switch.
- Changed
- Deformables brush: Disabled by default.
- Attachments: Only support two targets, attaching to world not supported
- Active actors available only if required.
- Fixed
- Gizmo UID free fix.
- CPU Dispatcher can be now correctly created with zero threads.
- Joint helpers visibility fix after start/stop has been pressed.
- Local space velocities fixed.
- PhysXSDK fixes for custom geometries.
- Transform standardization of physics objects on simulation start correctly handles presence of a scale attribute in case there is no scale op in the XformOps stack.
- Particle Sampler:
- No more crash when removing particles relationship
- Improved feature behavior when editing particles relationship
- No more resampling when a stage is saved or loaded from file
- Fixes for particle system surface extraction and anisotropy with multiple particle systems.
- Asynchronous deformable body cooking is now triggered when changing the scale of a mesh with deformable body component.
- Fix crash when removing a particle system referenced by a primitive with particle cloth component.
- Support on a physics scene to disable scene queries.
- Debug visualization does not anymore toggle async rendering flag.
- Fixed
- Flatcache extension proper shutdown.
- PhysXSDK fixes for gyroscopic forces.
## [1.4.2-5.1] - 2022-03-14
Internal Version 31077407
### Core
**General**
- Added
- New items in Demos/Particles and Tutorials: Cloth Deck Chair, Fluid Isosurface Glass Box, Paint Ball Emitter demos; and Particle Cloth and Particle Inflatable tutorials
- Demos extension defines demo asset server base URL in extension toml, see physics.demoAssetsPath
- Fixed
- Kinematic body target velocity fix, the inertia is not set to infinity during contact
- Corrected visualization for Spherical Joint Axis on Y and Z
- Fixes for particle debug visualization
- Fix visibility issues for non-fluid particle sets when surface extraction is on
- Changed
- PhysXDevice update
- Particle System: change default particleContactOffset to 5cm instead of autocomputation
- Particle Cloth: Mesh welding is enabled on by default. Mesh welding ensures that duplicate vertices and triangle indices are removed to enable the correct simulation of a piece of cloth. This option can be turned off if the mesh is deliberately designed to have duplicate vertices or triangle indices. For example, simulating a broken or torn particle cloth.
- Fixed Tendon: Dynamics were updated and a new attribute was added that can be used to tune the tendon response per axis
## [1.4.1-5.1] - 2022-03-07
Internal Version 31050168
### Core
**General**
- Changed
- Removed PhysxParticleSystem.MaxParticles attribute.
- Renamed PhysxSchema.PhysxParticlePoissonSamplingAPI to PhysxSchema.PhysxParticleSamplingAPI.
- Improved PhysxParticleSystem property UI.
- Fixed
- Xform reset for RigidBody, CCT, DeformableBody and ParticleCloth.
- Duplication of UsdGeom.Mesh with PhysxSchema.PhysxParticleSamplingAPI, and other particle sampling fixes.
- Issues and crashes with Particle Isosurface, Smoothing and Anisotropy components.
- Mass/density parsing for DeformableBodyAPI.
- Attachment of ParticleCloth (with UsdGeom.Mesh that requires welding for simulation).
### Vehicles
**General**
- Fixed
- A regression in the Vehicle Creation Wizard caused the second page of the wizard to be inaccessible.
## [1.4.0-5.1] - 2022-02-21
Internal Version 31013585
### Core
**General**
- Added
- Support for flat cache change tracking mechanism.
- IPhysxSimulation:flushChanges function to flush pending physics updates.
- Physics Debug Window now has buttons to remove UsdPhysics and PhysxSchema from selected prims.
- Exposed isReadbackSuppressed and /physics/suppressReadback setting for direct GPU access functionality.
- Exposed PhysX SDK profile data into carb profiler, can be disabled through a physics setting.
- Exposed raycast_any, sphere_sweep_any and overlap_any functions on IPhysxSceneQuery interface.
- Exposed raycast/sphere cast collider material information
- Button to Physics debug window - Save scene to PhysX SDK RepX format.
- Kinematic vs Kinematic contact reporting, enabled when Report Kinematic Kinematic Pairs attribute on a PhysicsScene is set to True (default False)
- Kinematic vs Static contact reporting, enabled when Report Kinematic Static Pairs attribute on a PhysicsScene is set to True (default False)
- Exposed transformationUpdateFn for IPhysxSimulation callback structure. The function is called right after fetchResults.
- Exposed maxBiasCoefficient used in the constraint solver on physics scene.
- Exposed Mass Information section into Physics Debug Window.
- Joint selection will now outline the rigid bodies it connects to (dynamic body is green, static is red).
- Exposed resume flatcache change tracking through IPhysxSimulation callback.
- All physics attributes hooked up for runtime changes are now registered automatically to flatcache change tracking mechanism.
- Exposed material0 and material1 in contact data event stream.
- Added PhysxSchemaPhysxArticulationAPI::ArticulationEnabled attribute that does enable/disable articulation definition.
- Added an option to the Visibility (Eye Icon) > Physics > Show By Type > Colliders > Normals that toggles the surface normals.
- Added Gear and Rack and Pinion joints to the Create menu.
- Added Physics default material binding UI for PhysicsScene prims.
- Added stage_id to contact notification events.
- Added batched contact reporting through a callback system (IPhysxSimulation::subscribePhysicsContactReportEvents) or through immediate API (IPhysxSimulation::getContactReport) in both cases python binding exist.
- Added protoIndex support for raycasts/sweeps/overlaps.
- PhysicsScene min/maxIterationCount that limits individual actors (rigidbody, softbody, particles) iteration counts.
- Added support for point instancer scale indices.
- Added support for UsdGeom hole indices.
- Added PhysX CPU dispatcher setting, by default carbonite CPU dispatcher is used, its possible to override this behavior through a physics preferences setting.
- Added new attachment type which can be used to attach deformable bodies to colliders, rigid bodies or other deformable bodies or the world frame.
- New Menu option Create > Physics > Attachment (based on the selection of one or two suitable primitives)
- New visualization option (Eye Icon) > Physics > Show By Type > Attachments
- New property window to control the auto generation of attachment points and filters based on two geometrically overlapping primitives
- New deformable brush extension for erasing, painting attachment points and collision filters
- Added new position based dynamics particle system type - supporting fluid, granular, cloth and inflatable simulations
- New Menu option Create > Physics > Particle System (particle system creation is automatic on addition of corresponsing components)
- New Option in Create > Physics > Physics Material: PBD Particle Material
- New visualization option (Eye Icon) > Physics > Show By Type > Particles
- New Particle Cloth component that can be added to mesh prims.
- New Particle Set component that can be added to points or point instancer prims.
- New Particle Sampler component that can be added to mesh prims. (Autogeneration of points or point instancer).
- New Anisotropy, Smoothing and Isosurface components that can be added to a Particle System prim.
- New Diffuse Particles component that can be added to a Particle System prim.
- Added IPhysxSceneQuery::reportCollisionShapes functions to query created collision shapes in PhysX.
- Added support for surface velocity for kinematic bodies. If a kinematic body does have linear velocity set, it is converted into surface velocity. This is useful for example for conveyor belt.
- Added custom logging channel omni.physx.logging.robotic. Turned off by default and togglable through /physics/logRobotics setting.
- Added support for joint drives on D6 joints that are part of articulations.
- Added Attach/Detach StageUpdateNode into Physics debug window, this allows omni.physx simulation attach/detach.
- Changed
- IPhysxSimulation:simulate: the elapsedTime parameter gets passed to the PhysX simulation directly, no substepping happens anymore. It’s the caller’s responsibility to provide reasonable elapsedTime.
- Gear joint GearRatio can be now a negative value and can be changed in runtime.
- Rack and Pinion joint Ratio can be now a negative value and can be changed in runtime.
- Backward compatibility will check for deprecated schema also after the processing is done and advise if there’s still some deprecated schema found.
- Convex hull vertex limit maximum changed from 60 to 64.
- IPhysx:getObjectId will now return a valid ID even if there is no directly accessible internal physics representation available (since these IDs might still be used to indirectly access internal data and state through other APIs).
- Character controller extension was heavily rewritten on both the python and C++ side. Please see docs and the Character Controller/Arena demo for details on the new usage and utils.
- Grouped physics-related widgets in the Property window under a common “Physics” frame.
- IPhysx::getSimulationEventStream is deprecated and getSimulationEventStreamV2 should be used instead. For contact reports please use IPhysxSimulation::subscribePhysicsContactReportEvents
- For omni.physx release configuration PhysX SDK Checked configuration is used instead of Profile
- For elapsed time less or equal to zero, physics update step is skipped completely.
- D6 joint definition in articulation hierarchy will have by default all rotation DOF free.
- The following Physics settings originally residing in the Preferences window were changed from persistent to per-stage and are now saved to USD and changeable through the Physics Settings window: whole Update group, whole Mouse interaction group and Zero Gravity speed, Min Simulation Frame Rate and Enable Anisotropy for Fluid Rendering settings. Convex decomposition and mesh simplification settings were deprecated alltogether.
- If a parent xform of a PhysicsJoint changes scale, linear limits (PrismaticJoint limits for example) are scaled too.
- When a joint is created from single selection the prim will be set as body1. A drive target added to it will then define a world to body transformation instead of vice versa when body0 was used. Changed for all joint types to keep consistency.
- Joints, presets and rigid body and collider component Add menu options are now always shown, but disabled whenever the prim has already applied any conflicting APIs (instead of not being shown at all).
- Options in the Add menu are now shown/enabled whenever that menu option is usable for at least one of the prims in the current selection and not only when usable for all the prims in the selection.
- SimulationOwner property for Rigid Bodies and Colliders is hidden until multiscene support is implemented.
- Joint helper 3d models replaced with billboards.
- Default rigid body maximum depenetration velocity has been changed to 5 m/s.
- Fixed
- USD physics resync operation on rigid bodies will restore joints connections.
- All joint widgets will now properly include properties from PhysxJointAPI.
- PhysxPhysicsRackAndPinionJoint ratio attribute is now in deg/distance (from incorrect rad/distance)
- UI widgets limits for physxConvexHullCollision:hullVertexLimit and physxConvexHullCollision:minThickness.
- Detecting closed circuits in articulations.
- Properties that are authored on a prim, present in UsdPhysics or PhysxSchema schemas, but without these being applied to that prim, will produce a warning. Fixed crashes in property widgets.
- Raycast/sweep sphere cast report correct USD face index
- Materials are taken correctly if applied within a hierarchy
- Rigid body with Colliders Preset or Colliders Preset added to a selection will now undo correctly in one undo step.
- Contact report for meshes with convex decomposition approximation does now correctly send only one report per collider.
- Gear joint and Rack and Pinion joint are now compatible with articulations.
- Removed limits for prismatic joint’s lower and upper limit property widgets.
- Distance limit API applied to a D6 joint will now get correctly applied.
- Fixed point instancer transformations when point instancer prims did have additional transformation.
- Revolute joint Y axis transformation.
- Revolute joint velocity drive sign.
- Joint authoring rotate gizmo fix.
- Random crash during property changes in runtime.
- Debug Stop resets time to start time instead of zero when timeline is stopped.
- Rigid body with Colliders Preset and Colliders Preset use only one command now and can be safely used on large selections.
- Reset transformation non determinism issue.
- Articulation drives and limits respect the USD joints body order.
- Articulation spherical joint is 3DOF instead of 2DOF to be consistent with max. coordinate spherical joint.
- D6 joint limits can be udpated after simulation is started.
- Point instancer prototype parsing, if the prototype was outside of the point instancer scope.
- Point instancer prototype parsing, if the prototype was scene instanced and nested.
- Kinematic rigid bodies compute correctly their mass properties.
- Rigid bodies transformation reset now resets correctly if structural changes were made during simulation.
- Scaling of rotational joint drive damping and stiffness (Revolute and D6) not part of articulations.
- Spherical joint limit order when joint axis is not X, and updating joint limits for spherical joints in articulations from USD after simulation start.
- Sign of maximal-coordinate revolute and D6 rotational velocity drive targets to be consistent with articulation directions
- Body order assignment when creating a joint on two prims fixed back to first prim to Body 0 rel and second to Body 1.
- Refreshing Create main menu on selection change to properly refresh the Joint submenu.
**C++ API**
- Added
- The IPhysicsObjectChangeCallback structure has been added to get notifications about internal object creation and destruction.
- New IPhysxAttachment interface with attachment functionality needed by attachment visualization and brush, for example.
- New IPhysxParticles interface for particle authoring, currently exposing functionality for isosurface, anisotropy and smoothed positions pre-view.
**Vehicles**
**General**
- Fixed
- Having a vehicle camera in a layer with a stronger opinion than the authoring layer could cause a crash.
- The Vehicle Creation Wizard did not compute the chassis mass correctly for very small vehicles if the stage meters per unit value was not set to 1.
- Removing the PhysicsRigidBodyAPI on a vehicle prim while the simulation is running could cause a crash.
- The Vehicle Creation Wizard did not properly scale camber stiffness for small sized vehicles.
- The gamepad triggers had to potentially be pressed twice to go into auto-reverse.
- Changed
- All cameras were removed from the Vehicle extension and moved into a new Camera extension.
- **Python Bindings API**
- Changed
- The IPhysxVehicle.set_to_rest_state method has been deprecated and will be removed in the future. Please use IPhysx.set_vehicle_to_rest_state of the omni.physx extension instead.
- The get_update_all_cameras, set_update_all_cameras, add_follow_camera, add_drone_camera and process_pending_usd_changes methods were removed. Use the new Camera extension and the get_camera_interface to create and setup cameras that track vehicles.
- The method IPhysx.compute_vehicle_velocity has been added as a helper to compute the vehicle speed along a given local direction.
- **C++ API**
- Added
- The method IPhysx.getWheelTransformations has been added to read wheel transformations after the simulation has started.
- The method IPhysx.computeVehicleVelocity has been added as a helper to compute the vehicle speed along a given local direction.
- Changed
- The IPhysxVehicle.setToRestState method has been deprecated and will be removed in the future. Please use IPhysx.setVehicleToRestState of the omni.physx extension instead.
- The getUpdateAllCameras, setUpdateAllCameras, addFollowCamera, addDroneCamera and processPendingUsdChanges methods were removed. Please use the methods in IPhysxCamera.h to create and setup cameras that also track vehicles.
- **Force Field**
- **General**
- Added
- New Force Field extensions that applies forces to Rigid Body objects that make them move in interesting ways. Available force fields include, Planar, Linear, Spherical, Spin, Wind, Drag and Noise. Additional force fields can be added upon request. Refer to the app_create/prod_extensions/ext_force-fields.html documentation for additional details and implementation instructions.
- **Python Bindings API**
- Added
- Use acquire_physx_force_fields_interface() to acquire the interface and the CreateForceFieldCommand, AddPrimsToForceFieldCommand and RemovePrimsFromForceFieldCommand to add force fields to prims and Rigid Bodies they affect. Use the add_force_field, remove_force_field, set_force_field_xxx, and enable_force_field methods to add, remove and set up the force fields. The prefered method is to create prims and use the GUI. The attach_stage and detach_stage methods are used to set up the force fields without pressing Play in Kit.
- **C++ API**
- Added
- The IPhysxForceFields.h header lists all of the interface methods.
- **Camera**
- **General**
- Added
- New camera extension created that provides three cameras to track Rigid Body objects and animated Xforms. A Look Follow Camera follows objects that always stay upright, like vehicles, and points along the look vector direction. A Velocity Follow Camera follows behind any object that can tumble aligns with the velocity vector. A Drone Camera tracks objects from above.
- **Python Bindings API**
- Added
- Use the PhysXAddFollowCameraCommand, PhysXAddVelocityCameraCommand and PhysXAddDroneCameraCommand to add cameras that respond the Undo and Redo commands. Use the get_camera_interface to get the camera interface, get_update_all_cameras, set_update_all_cameras, add_follow_camera and add_drone_camera methods to add cameras in Python along with the attach_stage, detach_stage, update_controllers and process_pending_usd_changes methods to run the camera without pressing Play in Kit.
- **C++ API**
- Added
- Use the getUpdateAllCameras, setUpdateAllCameras, addFollowCamera, addVelocityCamera and addDroneCamera methods to add cameras in Python along with the attachStage, detachStage, updateControllers and processUSDNotifyUpdates methods to run the camera without pressing Play in Kit.
- **Character Controller**
- **General**
- Fixed
- Character capsule pose does reset correctly when stop is pressed.
- **[1.3.15-5.1] - 2021-12-??**
- **Core**
- **General**
- Fixed
- Omni.physx.ui initialization if viewport window failed to be initialized.
- Pseudoroot resync USD notification results in a full physics reparse, fixes save as functionality while simulation is running.
- CCT requirement check prim validation check added.
- Physics debug view synchronization of visualization flags fixed.
- **[1.3.14-5.1] - 2021-11-05**
## Core
### General
- Fixed
- Two way coupling between softbodies and articulations.
- Removed slowdown of stage update by Fixed-Tendon Debug Visualizer on stages with many prims
- Possible asynchronous cooking threading issue.
## [1.3.13-5.1] - 2021-10-15
### Core
### General
- Fixed
- RigidBody Max linear velocity default value was changed to infinity.
- Kinematic rigid bodies without shapes dont trigger mass related warnings.
- ArticulationRootAPI defined on a static rigid body will get ignored and a warning is send to the user.
- Removed incorrect layer check for transformation sanitation.
- Added Deformable Hand and Deformable Poisson Ratio demo into omni.physx.preview extension.
- Fixed mass computation for convex decomposition approximation.
## [1.3.12-5.1] - 2021-10-05
### Core
### General
- Fixed
- Fixed PhysX SDK debug visualization for articulations.
- Setting joint body rel will recompute joint poses.
- Fixed collider being applied to bodies hidden from the stage window.
- Rigid body transformation setup on prims in a layer without edit spec will issue warning.
- Exposed new triangle mesh collision parameter - Weld tolerance used for PhysX Cooking welding.
## [1.3.11-5.1] - 2021-09-22
### Core
### General
- Fixed
- PhysX SDK issue related to aggregates broadphase.
- PhysX SDK issue related to articulations sleeping.
- Added validity check for newly added prims before they are processed in physics update.
## [1.3.10-5.1] - 2021-09-01
### Core
### General
- Changed
- PhysX GPU Cuda context manager crash will stop the simulation. Next simulation will attempt to recreate the Cuda context manager or fall back to CPU.
- Fixed joint authoring visualization when joint gizmos were disabled.
- Articulation D6 joint is not anymore internally decomposed into several revolute joints, one spherical joint is used instead. Translate DOF is not supported in the D6 joint.
- Physics flatcache update fixed a crash with a scene reload.
- Fixed crash in Softbody debug visualization when stage got released.
## [1.3.9-5.1] - 2021-08-22
### Core
### General
- Fixed
- Fixed crash bug when deformable bodies come in contact with kinematic rigid bodies.
- Improved deformable body collision behavior at small scales.
- Crash if point instancer index was out of prototype bounds.
- Improved PhysX SDK determinism.
- Clamping values in physics preferences after ctrl+clicking a slider and entering a value outside of valid range.
- Changed
- Convex hull mesh thickness now does not produce a large hull if the original mesh was very tiny.
## [1.3.8-5.1] - 2021-08-10
### Core
### General
- Added
- Backward compatibility on a folder GUI improvements.
- Fixed
- Backward compatibility on a folder now supports paths on a nucleus server and will not crash on read-only files.
## [1.3.7-5.1] - 2021-08-05
### Core
**General**
- **Fixed**
- Added missing IPhysXCooking interface dependency for omni.physx.ui extension.
- Any prim can be now chosen as a Filtered pairs target.
- Physics numeric property widgets will not call listeners on each digit change.
- Added additional prim validation for range traversals.
- CCT’s MoveTarget attribute is now reset to its initial value when simulation stops.
- Fixed articulation parsing for disabled joints.
- Property widgets min/max and step values are now scaled with stage’s metersPerUnit value where appropriate.
- Default state UI will now reset to metersPerUnit scaled value instead of the original one and show correctly when the value is changed from default.
- **Changed**
- Triangle mesh collisions are not supported for dynamic rigid bodies by PhysX simulation. Current error was replaced by a warning and collision approximation will fall back to a convexHull approximation.
- Physics debug visualization does temporary disable async rendering.
- **Added**
- Exposed convex mesh cooking functions to python. Its now possible to get resulting convex cooking data in runtime to python. Added sample for this functionality.
- Improved collision between deformable bodies, self-collision, and collision versus articulations.
- **Changed**
- Replaced mesh simplification approximation for colliders with better algorithm, and simplified parameters.
### Vehicles
**General**
```
```markdown
## [1.3.6-5.1] - 2021-07-16
### Core
**General**
- **Added**
- Process backward compatibility on a folder. Access from Preferences/Physics.
### Vehicles
**General**
- **Fixed**
- Deleting a prim with PhysxVehicleWheelAttachmentAPI applied while in play mode could cause a crash.
- Vehicles referenced into a stage during play did not work properly if the referenced prim was an ascendant of the vehicle prim (device input to control the vehicle was ignored, for example).
- **Changed**
- For vehicles with standard drive, setting the transmission to automatic will be ignored if no auto gear box has been defined. In addition, an error message will get sent.
- The property window will hide certain relationships if the corresponding API schemas have been applied instead.
```
```markdown
## [1.3.5-5.1] - 2021-07-08
### Core
**General**
- **Added**
- Improved Deformable Body collision mesh simplification. Better mesh simplification algorithm and parameterization, support for remeshing and faster tetrahedral mesh generation.
### Vehicles
**General**
- **Fixed**
- The Vehicle Creation Wizard kept the forward axis option locked even if an undo removed the PhysxVehicleContextAPI from the physics scene prim.
- **Changed**
- Negative max steer angles are supported now. This allows to create vehicles with a very small turning radius, for example.
### Character Controller
**General**
```
```markdown
## [1.3.4-5.1] - 2021-07-02
### Core
**General**
- **Added**
- Improved Deformable Body collision mesh simplification. Better mesh simplification algorithm and parameterization, support for remeshing and faster tetrahedral mesh generation.
- Adding Deformable Body component during play
- Backward compatibility check now reports a list of deprecated attributes and types. This is shown either in the backward compatibility dialog or in console, depending on settings.
- IPhysxCooking interface - moved cooking related function from IPhysx and marked them deprecated on IPhysx.
- Exposed CreateConvexMesh function on IPhysxCooking.
- Changed
- Joint visualization is disabled on play and reappear when stopped is pressed (did appear on pause before).
- Removed “Command” from command execution strings.
- Fixed
- Gear joint and rack and pinion joint create order. If the joint was created before the required revolute/prismatic joint, application would crash.
- Issue with single body articulation.
- Property window refresh when APIApply commands were processed was not working sometimes (e.g. when some components were added or removed).
- Crash when material prim did not existed.
## Vehicles
### General
- Fixed
- The Vehicle Creation Wizard did not position the wheels correctly if the scan feature was used for the chassis dimensions but not for the wheel dimensions.
- Small scale vehicles generated via the Vehicle Creation Wizard did fall asleep too easily.
- Changed
- The Vehicle Creation Wizard now adjusts the contact offset values for collision geometry based on the vehicle size.
## [1.3.3-5.1] - 2021-06-22
### Core
### General
- Changed
- Using custom PhysxSchemaTokens->physxCollisionCustomGeometry for custom geometry definition.
- Default restOffset is -inf - value is computed automatically, its 0.0f for rigid bodies and 2.0cm for deformables (For small deformables, tweaking the rest offset might be required).
- Default solver iteration count for rigid bodies was increased from 4 to 16.
- Improved bounding sphere for symmetric objects.
- Fixed
- Issue with materials and convexDecomposition colliders.
- RigidBody enabled attribute can be changed in runtime and joints will correctly update.
- Added
- Deformable CCD (enabled by default when a mesh is set as a deformable)
- Adding Deformable Body component during play
### Vehicles
### General
- Fixed
- The auto-reverse logic could fail due to the vehicle rigid body falling asleep and it looked like the vehicle got stuck.
- Changed
- The Vehicle Creation Wizard command does not open message dialog windows anymore to provide warning or error feedback. Instead, a list of message strings is returned.
- The Vehicle Creation Wizard has changed thresholds such that it will warn more aggressively about setups that will likely need more simulation steps per second to be stable.
## [1.3.2-5.1] - 2021-06-15
### Core
### General
- Added
- Overlap mesh query with a python demo.
- Omni.physx.preview extension to showcase PhysX SDK technology that is not yet fully integrated.
- Deformable Body collision mesh simiplification. Can be controlled through Deformable Body property widget.
- Changed
- Tendons authoring improvements.
- Physics material does search for purpose physics token, then it falls back to non purpose binding.
- Deformable Body collision and simulation mesh visualization improvements.
- Fixed
- Debug visualization for triangle meshes with various scales was incorrect.
- Debug visualization for triangle mesh normals with a negative scale was incorrect.
- Point instancer reset transformations when velocities arrays were not provided.
- Articulation definition now takes a joint to world correctly as a fixed based articulation.
- Create Deformable Body dialog. Use component add button instead.
- Create Deformable Material, was replaced by create physics material.
**Python API**
- Changed
- omni.physx.utils
- setCollider will correct approximation shape from none (trimesh) to convexHull when the prim is a part of a rigid body.
## Vehicles
**General**
- Added
- Revolutions per minute can now be specified in the Vehicle Creation Wizard for standard drive vehicles. This gives a bit more control over top speed of the created vehicle.
- Fixed
- The wheel mass field in the Vehicle Creation Wizard discarded changes unless some other fields were changed first.
- Changed
- The Vehicle Creation Wizard has been modified to avoid some instabilities if small vehicles are created. As a consequence, the generated parameters might vary a lot compared to the previous version.
- The tire prims generated by the Vehicle Creation Wizard are now placed under the vehicle root prim instead of under the shared data root prim.
**USD Schemas**
- Changed
- The required APIs that need to be applied to prims such that they can be used as vehicle components have changed.
- vehicle prim: instead of PhysxRigidBodyAPI, the existence of UsdPhysics RigidBodyAPI is verified.
- vehicle wheel collision prim: instead of PhysxCollisionAPI, the existence of UsdPhysics CollisionAPI is verified.
- tire friction table material prims: instead of PhysxMaterialAPI, the existence of UsdPhysics MaterialAPI is verified.
**Python Bindings API**
- Changed
- The helper method compute_wheel_simulation_transforms() (computeWheelSimulationTransforms() in C++) sets the tire force application point offset close to the wheel center now.
## Character Controller
**General**
- Fixed
- Character controller capsule orientation fix
## [1.3.1-5.1] - 2021-06-04
### Core
**General**
- Changed
- Raycast/Sweep all demo does create three pyramids by default, the number of pyramids and the size was added as a parameter
- Character controller API takes move target as a parameter. Improved Character controller snippet.
- PhysxScene solver type TGS is now default.
- PhysxCookedDataAPI was changed to be multiple applied API. This changed together with the PhysxMeshCollisionAPI changes ensure that multiple mesh approximations can be authored and precomputed resulting in fast collision switch in runtime.
- Added
- Added RigidBody Enabled Gyroscopic Force flag, it is enabled by default. (flag is in advanced section).
- Softbodies
- Articulation tendons
- Joint break event into simulation event stream, added a snippet Joint Break to showcase feature.
- Default material can be applied to PhysicsScene, Restitution Demo was modified to showcase this usage.
- Removed
- PhysxMeshCollisionAPI was removed. It was replaced by PhysxConvexHullCollisionAPI, PhysxConvexDecompositionCollisionAPI and PhysxTriangleMeshSimplificationCollisionAPI. Based on the UsdPhysicsMeshCollisionAPI:approximation attribute the matching schema is used. Base on the approximation only those relevant attributes show in the property window. The irrelevant attributes are in the inactive group.
### Vehicles
**General**
- Fixed
- The vehicle creation wizard transformed the horsepower field to values of engine peak torque that were too high.
### Character Controller
**General**
- Added
- Character controller collision event steam.
## [1.3.0-5.1] - 2021-05-28
### Core
## General
### Added
- Reset Physics Settings button to reset all physics settings to their default values.
- Joint localPose can be changed in runtime, time varied attribute changes are supported.
- Added support for articulation force sensors.
- Omni.physx.flatcache extension for fast rigid body transformation updates.
### Fixed
- ConvexDecomposition collision removal in runtime does now correctly trigger mass recomputation.
### Remove
- Fast cache option was removed. It was replaced by omni.physx.flatcache extension.
## Python API
### Added
- omni.physx.utils
- addDeformableBodyMaterial, addDeformableSurfaceMaterial.
- omni.physxcommands
- AddDeformableBodyMaterialCommand, AddDeformableSurfaceMaterialCommand.
### Changed
- omni.physx.utils
- addMaterial renamed to addRigidBodyMaterial, material params are now optional.
## Vehicles
### General
### Fixed
- Optional USD relationships were falsely treated as an invalid setup, if they were authored but set to an empty list.
- On simulation stop, attribute values of PhysxVehicleControllerAPI and PhysxVehicleWheelControllerAPI prims were not reset to the pre-simulation-start values.
### USD Schemas
### Added
- The attribute sprungMass has been added to the PhysxVehicleSuspensionAPI API schema and allows the user to set custom values if desired (by default, the values will be computed automatically based on vehicle mass and wheel center-of-mass offsets).
## Core
### General
### Added
- RigidBody CCD demo.
- RigidBody Kinematics demo.
- Error message if a distance joint should be a part of an articulation.
- Rigid Body and Collider to Sub-tree in the Property window’s Add menu.
- RigidBody retain accelerations flag exposed. Rigid body carry over forces/accelerations between frames, rather than clearing them.
- Option to explicitly create a D6 joint.
- Support for transformation changes through flat cache.
- TimeStepsPerSeconds simulation parameter per scene. The final number of steps is based on this per scene value and simulation min frame rate persistent setting.
- Setting to automatically create a temporary default PhysicsScene when simulation is started and none is available.
- Support for RigidBody point instancer position/orientation/velocity/angularVelocity changes in runtime.
- Multiple materials per triangle mesh support through UsdGeomSubset - demo added.
### Fixed
- StartAsleep was not working correctly.
- ContactOffset, restOffset runtime changes were not correctly updated.
- Joint authoring X trans axis was not visible.
- Joints/Articulation are now created with consistent order.
- RackAndPinionJoint and GearJoint are now properly created.
- ArticulationJoint changes in runtime.
- Soft vs hard joint limits.
- Static rigid body with a triangle mesh.
- Point instanced rigid bodies initial velocity reset.
- Static body is considered for joint creation.
- Articulation parsing optimizations.
- Physics objects are correctly removed when a prim is deleted in runtime.
- Contact reports for Point Instancers.
- Joint helpers movement when parent xform moved.
- Debug visualization now respects collisionEnabled attribute.
### Changed
- Physics demos are now in a separate extension.
- Physics commands are now in a separate extension.
- Physics schema is now in a separate extension.
- Hidden “Asynchronous Simulate/Render” setting UI if not in Physics Development Mode.
- Applying/adding colliders (through components, presets or scripting) now also work with instanced prims.
- Issue warning and not create rigid body on an instance proxy.
- Optimized NoticeHandler in favor of Flat Cache integration.
- Physics Settings (except PVD) moved to the main Preferences window. PVD settings moved to the Physics Debug window.
- Joint helpers are displayed only for 100 closest joints.
- Instead of running a full upgrade process a backward compatibility check on scene open is now enabled by default and a prompt will be presented to run the upgrade on demand. This check can be disabled, only warn or run the upgrade without prompting in Preferences.
- /persistent/physics/backwardCompatibilityCheck setting has been renamed to backwardCompatibilityCheckMode to indicate the aforementioned change in functionality.
**Python API**
- Added
- omni.physx
- reset_settings() will reset all physics settings to their default values.
- Changed
- omni.physx.utils
- setCollider, setColliderSubtree and removeCollider now also work with instanced prims.
**C++ API**
- Added
- IPhysx.h
- resetSettings() will reset all physics settings to their default values.
## Vehicles
**General**
- Added
- Some debug visualization for vehicle suspension has been added. See the new option in the Physics Debug window.
- Sample for how to use vehicles to set up a semi-trailer truck.
- The PhysxVehicleContextAPI schema can be applied to a UsdPhysicsScene prim through the Add button in the property window.
- Tire friction tables (PhysxVehicleTireFrictionTable) can now be added through the Create menu.
- The Vehicle Creation Wizard scales physics settings so smaller vehicles are stable down to centimeter scales.
- Fixed
- Deletion of vehicles after simulation start can now happen through a parent prim (so far, explicit deletion of the vehicle prims was required).
- Changed
- The API schemas of the vehicle USD representation have undergone some major changes. Please read the USD Schemas section.
- Due to the changes mentioned above, the vehicle creation wizard outputs are more compact representation by default now. To get the previous output, where all vehicle components have their own prim, an option has been added to the first page (Create Shareable Components).
- It is now allowed to add tire friction tables (PhysxVehicleTireFrictionTable) after the simulation has started.
- The Vehicle Creation Wizard reads the forward and up vehicle axes from the VehicleContextAPI prim, if one exists. Otherwise, the up axis is read from the stage and the forward axis can be specified in the wizard.
**USD Schemas**
- Changed
- Many IsA schemas have been converted to API schemas. This allows for a more compact (fewer prims) vehicle setup for cases where there is no intent to share vehicle components among vehicle instances. Please have a look at the vehicle setup samples for examples. The following IsA schemas have been converted to API schemas:
- PhysxVehicleGlobalSettings => PhysxVehicleContextAPI. In addition, this API has to be applied to a PhysicsScene prim.
- The following changes add the option to apply the APIs directly to the prim that has PhysxVehicleWheelAttachmentAPI applied. The relationships to wheel, tire and suspension prim can then be omitted.
- PhysxVehicleWheel => PhysxVehicleWheelAPI
- PhysxVehicleTire => PhysxVehicleTireAPI
- PhysxVehicleSuspension => PhysxVehicleSuspensionAPI
- The following changes add the option to apply the APIs directly to the prim that has PhysxVehicleDriveStandardAPI applied. The relationships to engine, gears, auto-gear-box and clutch prim can then be omitted.
- PhysxVehicleEngine => PhysxVehicleEngineAPI
- PhysxVehicleGears => PhysxVehicleGearsAPI
- PhysxVehicleAutoGearBox => PhysxVehicleAutoGearBoxAPI
- PhysxVehicleClutch => PhysxVehicleClutchAPI
- The following changes add the option to apply the APIs directly to the prim that has PhysxVehicleAPI applied. The relationship to the drive prim can then be omitted.
- PhysxVehicleDriveBasic => PhysxVehicleDriveBasicAPI
- PhysxVehicleDriveStandard => PhysxVehicleDriveStandardAPI
- It is now legal to not define a tire friction table relationship in PhysxVehicleTireAPI. In such a case, any available table will be used (and if none exists, a default will be provided). It is still highly recommended to define a tire friction table and set the relationship but this change allows to reference a vehicle asset after the simulation has started and postpone the tire friction table setup.
## [1.1.0-5.1] - 2021-03-17
### General
- **Fixed**
- Fixed RigidBody CCD
## [1.1.0-5.1] - 2021-02-05
### General
- **Added**
- IPhysxSceneQuery::raycastAll function to support multiple hits per raycast, hits are reported through a hit callback. RaycastAll demo was added to the physics samples. Python bindings for this function are exposed.
- IPhysxSceneQuery::sweepSphereAll function to support multiple hits per sphere sweep, hits are reported through a hit callback. SweepSphereAll demo was added to the physics samples. Python bindings for this function are exposed.
- ISimulationCallback and SimulationFlag were added to the IPhysxSimulation interface. It is possible to register a callback and get notified about physics transformations. (C++ code only)
- Point instancer support for shapes only, while rigid body API is on the instancer itself or above in hierarchy
- Support for mesh winding orientation, please check debug visualization for triangle normal orientation
- PhysX PVD connection settings exposed in Physics setting menu
- Disable button in the character controller (CCT) window to disable CCT on a Capsule without the need to remove it
- Pair Collision Filter removal added to stage and viewport context menus under Physics/Remove Preset
- **Fixed**
- Removing convexDecomposition approximation, shapes are properly released from PhysX SDK.
- Async simulation when provided timestep was smaller than 1.0/60.0
- Point instancer with static rigid bodies
- Articulation parsing fixes - better determination of articulation root, fixes when bodies 0,1 were in different order
- Joint visibility fixed
- Primitives under joints can be now selected
- Triggers with script buffer type dont try to preload a script
- Simulation events are not send from async thread, resolves issues when stepping manually from python
- Issues with transformation matrix and scale during physics simulation initialization
- KaplaArena sample does not collapse anymore
- Removing shapes from compounds in runtime properly
- Removing a character controller (CCT) enabled Capsule will properly remove it from the CCT manager and disable CCT camera
- **Changed**
- IPhysx::subscribeToPhysicsStepEvents and IPhysx::unsubscribeToPhysicsStepEvents were renamed to subscribePhysicsStepEvents/unsubscribePhysicsStepEvents to match python names
- IPhysx::subscribeToPhysicsSimulationEvents and IPhysx::unsubscribeToPhysicsSimulationEvents were renamed to subscribePhysicsSimulationEvents/unsubscribePhysicsSimulationEvents
- omni.physx.core renamed to omni.physx.bundle
- Centralized base geometry creation utilities into the omni.physx.scripts.physicsUtils module
- Physics/Create main menu items moved to stage and viewport context menus under Create/Physics and to the Create/Physics main menu
- Physics/Set and Physics/Remove main menu items moved to stage and viewport context menus under Physics/Apply Preset and Physics/Remove Preset
### Vehicle changes
#### General
- **Added**
- Vehicles can be added and removed while the simulation is running using a script. There are certain restrictions about how this is done. Please refer to the documentation for details.
- Support for sweep queries has been added to detect collision with the ground surface.
- **Changed**
- The auto-reverse feature will not get applied anymore if accelerator and brake are controlled through USD directly. The brake value will always be treated as brake and the accelerator value always as accelerator. If a vehicle is controlled through device input (keyboard, gamepad etc.), auto-reverse should behave the same way as before.
## [1.0.0-5.1] - 2020-10-28
### General
#### Changed:
- PhysX SDK 5.1 integrated
- Update UsdPhysics and PhysxSchema to use default values
- Physics menu Add was renamed to Create
- Physics settings updated to new omni.ui
- Physics properties window replaced by omni.kit.property.physx
- Update USD velocities is enabled by default
- Interfaces renamed:
- carb::physics::usd::Physics.h –> omni::physx::PhysxUsd.h
- carb::physics::IPhysicsAuthoring.h –> omni::physx::IPhysicsAuthoring.h
- carb::physics::IPhysicsSimulation.h –> omni::physx::IPhysicsSimulation.h
- carb::physics::IPhysicsUsdLoad.h –> omni::physx::IPhysxUsdLoad.h
- carb::physics::physx.h –> omni::physx::IPhysx.h
- carb::physics::physxInternal.h –> omni::physx::IPhysxCooking.h
- carb::physics::physxSceneQuery.h –> omni::physx::IPhysxSceneQuery.h
- carb::physics::physxSceneQueryHit.h –> omni::physx::IPhysxSceneQuery.h
- carb::physics::physxUI.h –> omni::physx::IPhysxUI.h
- Python bindings moved to a subfolder bindings
#### Added:
- Addeed IPhysicsSimulation
- Physics cooked meshes local cache
- Asynchronous mesh cooking
- Cached getters for omni.physx interfaces
- Physics demos can be now opened with a double click
- Exposed rigid body transformation through an API, exposed to Python
- Added overlap_box and overlap_sphere functions, exposed to Python though new PhysXSceneQuery interface, demos added.
- Pvd IP settings and profile/debug/memory instrumentation checkbox
#### Fixed:
- Regression in USD notice handlers when an API was applied in runtime
- Fixed traversal to support scene graph instancing
#### Removed:
- Raycast_closest and sweep_closest from physx interface, moved into PhysXSceneQuery interface
- PSCL demos were removed, separate extension with these demos was created, they will be published to extension repository
### Python Bindings API
#### Added:
- New PhysXSceneQuery interface. Overlap_sphere, overlap_box together with existing raycast_closest and sweep_closest (the query functions on PhysX interface were marked as deprecated).
### Vehicle changes
#### General
- Added
- The recommended way to fetch the python vehicle interface is now to use omni.physxvehicle.get_physx_vehicle_interface().
- Changed
- Fixed a bug which reset vehicle Inputs Enabled every time the simulation started.
- Fixed a bug that made the vehicle properties window unresponsive in certain cases while in play mode.
## C++ API
- Changed:
- The vehicle object ID parameter has been removed from getWheelIndex() as it is no longer needed.
## USD Schemas
- Added:
- The attribute vehicleEnabled has been added to the PhysxVehicleAPI. If false, the vehicle simulation update loop will not run for a vehicle.
- Removed
- The sprungMass parameter of PhysxVehicleSuspension has been removed. The values will be automatically computed based on the mass parameter of the MassAPI schema as well as the wheelCenterOfMassOffset parameters of the PhysxVehicleWheelAttachmentAPI schema.
## Vehicle Creation Wizard
- Added:
- Added a Scan button to each page of the Vehicle Wizard that fits a bounding box around the selected prims in order to measure the Length, Width and Height of the mesh or shape. This information is used on the Basic page to find the dimensions of the chassis and compute the forward direction and vehicle mass. On the Axles page, the dimensions are used to position each of the tires and measure their width and radius. This feature makes it much faster to set up a vehicle.
- Added a forward axis drop down to make it easier to orient the vehicle.
- Added position inputs for the chassis so it can be positioned around the vehicle mesh. The Scan button will set the position to the center of the bounding box.
- Added a third page of documentation to provide some of the “Next Steps” to be completed to finish setting up a vehicle.
- Changed:
- All of the vehicle components are now created as children of the defaultPrim.
- Fixed the calculation of the tire and suspension force positions and position the center of mass as a function of the weight distribution settings.
- Moved the default locations of the tires inboard from the edge of the vehicle.
- Tires can now be positioned, and tire radii and widths can be set for each tire individually instead of on a per axle basis.
- Initialized the tire radii and width as a function of the chassis length so tires are not too large or small.
## Python Bindings API
- Added:
- Two new methods, get_update_all_cameras and set_update_all_cameras(bool updateAllCameras) were added. When updateAllCameras is true, all vehicle cameras are updated continuously, which allows seamless cuts from camera to camera. However, this can lower performance for stages with many cameras. To increase performance, set updateAllCameras to false. In this state, only the active vehicle camera is updated, but switching to a new camera will cause the new camera to reinitialize.
- attach_stage(), detach_stage() and update_controllers() have been added to the vehicle interface and can be used to update the vehicle controllers explicitly (instead of being triggered by the stage update loop)
- Changed:
- The compute_wheel_simulation_transforms API call now positions the tire forces at the bottom of the tire, where the rubber meets the road, instead of at the center of the tire. Since the Vehicle Authoring transforms autocompute tool calls this API function, it also takes advantage of this change.
- Removed:
- create_controllers() and update_controllers() have been removed from the vehicle testing interface. The new attach_stage(), update_controllers() etc. on the vehicle interface can be used as a replacement.
## Omni PhysX Vehicle pre 1.0.0
### General
- Added:
- Support for PhysX vehicles
- Default input device support to drive a vehicle
- Custom camera types
- Special property windows
- Vehicle creation wizard
- Samples
### Python Bindings API
- Changed:
- add_follow_camera() and add_drone_camera() now require a second argument specifying the USD path for the camera to create. Furthermore, True/False is returned to indicate success/failure of the operation. |
id10_CHANGELOG.md | # Changelog
## [0.5.2] - 2024-03-07
### Fixed
- Fix the version of omni_client_library to 2.43 for forward compatibility.
## [0.5.1] - 2024-02-26
### Changed
- Bump kit-sdk up from 105.2.137506 to 106.0.137667.
## [0.5.0] - 2024-02-09
### Changed
- Bump kit-sdk up from 105.1.123866 to 105.2.137506.
### Tool [0.5.0]
#### Added
- compare_volume()
### NeuralVDB [0.5.0]
#### Added
- batch_encode_grids()
- batch_encode_grids_from_buffer()
- batch_encode_grids_with_auto_config()
- batch_encode_grids_from_buffer_with_auto_config()
## [0.4.1] - 2024-01-10
### Tool [0.4.1]
#### Fixed
- Reference count issue in pybind functions
### NeuralVDB [0.3.9]
#### Fixed
- Reference count issue in pybind functions (decode_grids)
## [0.4.0] - 2023-11-14
### Tool [0.4.0]
#### Fixed
- Replace broken sphere.mvdb files
- Remove stl (std::vector) for ABI safety
#### Changed
- Move test files from neuralvdb to vdbtool
- Change `GridData` in internal function names to `Volume`
- Update docs
## [0.3.8] - 2023-11-06
### NeuralVDB [0.3.8]
- Changed
- Move test files from neuralvdb to vdbtool
- Change `GridData` in internal function names to `Volume`
## [0.3.7] - 2023-11-06
- NeuralVDB: RGBA8 min/max fix
## [0.3.6] - 2023-10-19
- Tool: Add `create_volume_from_coord_value_pairs` API
- NeuralVDB: Support for RGBA8 NanoVDB grid
## [0.3.5] - 2023-10-12
- NeuralVDB: Adding carb.settings to control default logging/decode behavior
## [0.3.4] - 2023-10-10
- NeuralVDB: Adding device type and backend options for encoding and decoding
## [0.3.3] - 2023-09-20
- NeuralVDB: Pruning support for level-1 tiles
- NeuralVDB: Fix non-deterministic pruning
- NeuralVDB: Empty grid handling while encoding and decoding
## [0.3.2] - 2023-08-02
### Changed
- Add documentation
- Fix invalid test VDB files |
id11_CHANGELOG.md | # Changelog
## [0.5.2] - 2024-03-07
### Fixed
- Fix the version of omni_client_library to 2.43 for forward compatibility.
## [0.5.1] - 2024-02-26
### Changed
- Bump kit-sdk up from 105.2.137506 to 106.0.137667.
## [0.5.0] - 2024-02-09
### Changed
- Bump kit-sdk up from 105.1.123866 to 105.2.137506.
### Tool [0.5.0]
#### Added
- compare_volume()
### NeuralVDB [0.5.0]
#### Added
- batch_encode_grids()
- batch_encode_grids_from_buffer()
- batch_encode_grids_with_auto_config()
- batch_encode_grids_from_buffer_with_auto_config()
## [0.4.1] - 2024-01-10
### Tool [0.4.1]
#### Fixed
- Reference count issue in pybyind functions
### NeuralVDB [0.3.9]
#### Fixed
- Reference count issue in pybyind functions (decode_grids)
## [0.4.0] - 2023-11-14
### Tool [0.4.0]
#### Fixed
- Replace broken sphere.mvdb files
- Remove stl (std::vector) for ABI safety
#### Changed
- Move test files from neuralvdb to vdbtool
- Change `GridData` in internal function names to `Volume`
- Update docs
## Added
- clip_volume()
- composite_volume()
- compute_volume()
- expand_levelset()
- flood_levelset()
- levelset_to_fog()
- offset_levelset()
- points_to_levelset()
- points_to_point_volume()
- point_volume_to_points()
- prune_levelset()
- resample_volume()
- scatter_points_to_volume()
- corresponding docs
## NeuralVDB [0.3.8]
- Changed
- Move test files from neuralvdb to vdbtool
- Change `GridData` in internal function names to `Volume`
## [0.3.7] - 2023-11-06
- NeuralVDB: RGBA8 min/max fix
## [0.3.6] - 2023-10-19
- Tool: Add `create_volume_from_coord_value_pairs` API
- NeuralVDB: Support for RGBA8 NanoVDB grid
## [0.3.5] - 2023-10-12
- NeuralVDB: Adding carb.settings to control default logging/decode behavior
## [0.3.4] - 2023-10-10
- NeuralVDB: Adding device type and backend options for encoding and decoding
## [0.3.3] - 2023-09-20
- NeuralVDB: Pruning support for level-1 tiles
- NeuralVDB: Fix non-deterministic pruning
- NeuralVDB: Empty grid handling while encoding and decoding
## [0.3.2] - 2023-08-02
### Changed
- Add documentation
- Fix invalid test VDB files |
id1_api_ll_users_guide.md | # Low Level API (NvBlast)
## Introduction
The low-level API is the core of Blast destruction. It is designed to be a minimal API that allows an experienced user to incorporate destruction into their application. Summarizing what the low-level API has, and doesn’t have:
- There is no physics representation. The low-level API is agnostic with respect to any physics engine, and furthermore does not have any notion of collision geometry. The NvBlastActor is an abstraction which is intended to correspond to a rigid body. However, it is up to the user to implement that connection. The NvBlastActor references a list of visible chunk indices, which correspond to NvBlastChunk data in the asset. The NvBlastChunk contains a userData field which can be used to associate collision geometry with the actor based upon the visible chunks. The same is true for constraints created between actors. Bonds contain a userData field that can be used to inform the user that actors should have joints created at a particular location, but it is up to the user to create and manage physical joints between two actors.
- There is no graphics representation. Just as there is no notion of collision geometry, there is also no notion of graphics geometry. The NvBlastChunk userData field (see the item above) can be used to associate graphics geometry with the actor based upon the visible chunks.
- There is no notion of threading. The API is a collection of free functions which the user may call from appropriate threads. Blast guarantees that it is safe to operate on different actors from different threads.
- There is no global memory manager, message handler, etc. All low-level API functions take an optional message function pointer argument in order to report warnings or errors. Memory is managed by the user, and functions that build objects require an appropriately-sized memory block to be passed in. A corresponding utility function that calculates the memory requirements is always present alongside such functions. Temporary storage needed by a function is always handled via user-supplied scratch space. For scratch, there is always a corresponding “RequiredScratch” function or documentation which lets the user know how much scratch space is needed based upon the function arguments.
- Backwards-compatible, versioned, device-independent serialization is not handled by Blast. There is, however, a Blast extension which does, see Serialization (NvBlastExtSerialization). However, a simple form of serialization may be performed on assets and families (see Definitions) via simple memory copy. The data associated with these objects is available to the user, and may be copied and stored by the user. Simply casting a pointer to such a block of memory to the correct object type will produce a usable object for Blast. (The only restriction is that the block must be 16-byte aligned.) Families contain a number of actors and so this form of deserialization recreates all actors in the family. This form of serialization may be used between two devices which have the same endianness, and contain Blast SDKs which use the same object format.
- Single-actor serialization and deserialization is, however, supported. This is not as light-weight as family serialization, but may be a better serialization model for a particular application. To deserialize a single actor, one must have a family to hold the actor, created from the appropriate asset. If none exists already, the user may create an empty family. After that, all actors that had been in that family may be deserialized into it one-at-a-time, in any order.
## Linking and Header Files
## To use the low-level Blast SDK
The application need only include the header NvBlast.h, found in the top-level `include` folder, and link against the appropriate version of the NvBlast library. Depending on the platform and configuration, various suffixes will be added to the library name. The general naming scheme is:
- NvBlast(config)(arch).(ext)
- (config) is DEBUG, CHECKED, OR PROFILE for the corresponding configurations. For a release configuration, there is no (config) suffix.
- (arch) is _x86 or _x64 for Windows 32- and 64-bit builds, respectively, and empty for non-Windows platforms.
- (ext) is .lib for static linking and .dll for dynamic linking on Windows.
## Creating an Asset from a Descriptor (Authoring)
The NvBlastAsset is an opaque type pointing to an object constructed by Blast in memory allocated by the user. To create an asset from a descriptor, use the function `NvBlastCreateAsset`. See the function documentation for a description of its parameters.
N.B., there are strict rules for the ordering of chunks with an asset, and also conditions on the chunks marked as “support” (using the NvBlastChunkDesc::SupportFlag). See the function documentation for these conditions. `NvBlastCreateAsset` does *not* reorder chunks or modify support flags to meet these conditions. If the conditions are not met, `NvBlastCreateAsset` fails and returns NULL. However, Blast provides helper functions to reorder chunk descriptors and modify the support flags within those descriptors so that they are valid for asset creation. The helper functions return a mapping from the original chunk ordering to the new chunk ordering, so that corresponding adjustments or mappings may be made for graphics and other data the user associates with chunks.
Example code is given below. Throughout, we assume the user has defined a logging function called `logFn`, with the signature of NvBlastLog. In all cases, the log function is optional, and NULL may be passed in its place.
```cpp
// Create chunk descriptors
std::vector<NvBlastChunkDesc> chunkDescs;
chunkDescs.resize( chunkCount ); // chunkCount > 0
chunkDescs[0].parentChunkIndex = UINT32_MAX; // invalid index denotes a chunk hierarchy root
chunkDescs[0].centroid[0] = 0.0f; // centroid position in asset-local space
chunkDescs[0].centroid[1] = 0.0f;
chunkDescs[0].centroid[2] = 0.0f;
chunkDescs[0].volume = 1.0f; // Unit volume
chunkDescs[0].flags = NvBlastChunkDesc::NoFlags;
chunkDescs[0].userData = 0; // User-supplied ID. For example, this can be the index of the chunkDesc.
// The userData can be left undefined.
chunkDescs[1].parentChunkIndex = 0; // child of chunk described by chunkDescs[0]
chunkDescs[1].centroid[0] = 2.0f; // centroid position in asset-local space
chunkDescs[1].centroid[1] = 4.0f;
chunkDescs[1].centroid[2] = 6.0f;
chunkDescs[1].volume = 1.0f; // Unit volume
chunkDescs[1].flags = NvBlastChunkDesc::SupportFlag; // This chunk should be represented in the support graph
chunkDescs[1].userData = 1;
// ... etc. for all chunks
// Create bond descriptors
std::vector<NvBlastBondDesc> bondDescs;
bondDescs.resize( bondCount ); // bondCount > 0
bondDescs[0].chunkIndices[0] = 1; // chunkIndices refer to chunk descriptor indices for support chunks
bondDescs[0].chunkIndices[1] = 2;
bondDescs[0].bond.normal[0] = 1.0f; // normal in the +x direction
bondDescs[0].bond.normal[1] = 0.0f;
bondDescs[0].bond.normal[2] = 0.0f;
bondDescs[0].bond.area = 1.0f; // unit area
bondDescs[0].bond.centroid[0] = 1.0f; // centroid position in asset-local space
bondDescs[0].bond.centroid[1] = 2.0f;
bondDescs[0].bond.centroid[2] = 3.0f;
bondDescs[0].userData = 0; // this can be used to tell the user more information about this
// bond for example to create a joint when this bond breaks
bondDescs[1].chunkIndices[0] = 1;
bondDescs[1].chunkIndices[1] = ~0; // ~0 (UINT32_MAX) is the "invalid index." This creates a world bond
// ... etc. for bondDescs[1], all other fields are filled in as usual
// ... etc. for all bonds
// Set the fields of the descriptor
NvBlastAssetDesc assetDesc;
assetDesc.chunkCount = chunkCount;
assetDesc.chunkDescs = chunkDescs.data();
assetDesc.bondCount = bondCount;
assetDesc.bondDescs = bondDescs.data();
// Now ensure the support coverage in the chunk descriptors is exact, and the chunks are correctly ordered
std::vector<char> scratch( chunkCount * sizeof(NvBlastChunkDesc) ); // This is enough scratch for both NvBlastEnsureAssetExactSupportCoverage and NvBlastReorderAssetDescChunks
NvBlastEnsureAssetExactSupportCoverage( chunkDescs.data(), chunkCount, scratch.data(), logFn );
std::vector<uint32_t> map(chunkCount); // Will be filled with a map from the original chunk descriptor order to the new one
NvBlastReorderAssetDescChunks( chunkDescs.data(), chunkCount, bondDescs.data(), bondCount, map, true, scratch.data(), logFn );
// Create the asset
scratch.resize( NvBlastGetRequiredScratchForCreateAsset( &assetDesc ) ); // Provide scratch memory for asset creation
void* mem = malloc( NvBlastGetAssetMemorySize( &assetDesc ) ); // Allocate memory for the asset object
NvBlastAsset* asset = NvBlastCreateAsset( mem, &assetDesc, scratch.data(), logFn );
```
It should be noted that the geometric information (centroid, volume, area, normal) in chunks and bonds is only used by damage shader functions. Depending on the shader, some, all, or none of the geometric information will be needed. The user may write damage shader functions that interpret this data in any way they wish.
## Cloning an Asset
To clone an asset, one only needs to copy the memory associated with the NvBlastAsset.
```cpp
uint32_t assetSize = NvBlastAssetGetSize( asset );
NvBlastAsset* newAsset = (NvBlastAsset*)malloc(assetSize); // NOTE: the memory buffer MUST be 16-byte aligned!
memcpy( newAsset, asset, assetSize ); // this data may be copied into a buffer, stored to a file, etc.
```
N.B. the comment after the malloc call above. NvBlastAsset memory **must** be 16-byte aligned.
## Releasing an Asset
Blast low-level does no internal allocation; since the memory is allocated by the user, one simply has to free the memory they’ve allocated. The asset pointer returned by NvBlastCreateAsset has the same numerical value as the mem block passed in (if the function is successful, or NULL otherwise). So releasing an asset with memory allocated by `malloc` is simply done with a call to `free`:
```cpp
free( asset );
```
## Creating Actors and Families
Actors live within a family created from asset data. To create an actor, one must first create a family. This family is used by the initial actor created from the asset, as well as all of the descendant actors created by recursively fracturing the initial actor. As with assets, family allocation is done by the user.
The family will
*not*
be automatically released when all actors within it are invalidated using NvBlastActorDeactivate. However, the user may query the number of active actors in a family using
```cpp
uint32_t actorCount = NvBlastFamilyGetActorCount( family, logFn );
```
## Damage and Fracturing
Damaging and fracturing is a staged process.
In a first step, a **NvBlastDamageProgram** creates lists of Bonds and Chunks to damage - so called Fracture Commands.
The lists are created from input specific to the NvBlastDamageProgram.<br>
NvBlastDamagePrograms are composed of a **NvBlastGraphShaderFunction** and a **NvBlastSubgraphShaderFunction** operating on support graphs (support chunks and bonds) and disconnected subsupport chunks respectively.
An implementer can freely define the shader functions and parameters.
Different functions can have the effect of emulating different physical materials.<br>
Blast provides reference implementations of such functions in **Damage Shaders (NvBlastExtShaders)**, see also NvBlastExtDamageShaders.h.
The NvBlastDamageProgram is used through **BlastActorGenerateFracture** that will provide the necessary internal data for the NvBlastActor being processed.
The shader functions see the internal data as **BlastGraphShaderActor** and **BlastSubgraphShaderActor** respectively.
The second stage is carried out with **BlastActorApplyFracture**. This function takes the previously generated Fracture Commands and applies them to the NvBlastActor.
The result of every applied command is reported as a respective Fracture Event if requested.
Fracture Commands and Fracture Events both are represented by a **NvBlastFractureBuffer**.
The splitting of the actor into child actors is not done until the third stage, **BlastActorSplit**, is called.
Fractures may be repeatedly applied to an actor before splitting.
The **NvBlastActorGenerateFracture**, **NvBlastActorApplyFracture** and **NvBlastActorSplit** functions are profiled in Profile configurations.
This is done through a pointer to a NvBlastTimers struct passed into the functions.
If this pointer is not NULL, then timing values will be accumulated in the referenced struct.
The following example illustrates the process:
```cpp
// Step one: Generate Fracture Commands
// Damage programs (shader functions), material properties and damage description relate to each other.
// Together they define how actors will break by generating the desired set of Fracture Commands for Bonds and Chunks.
NvBlastDamageProgram damageProgram = { GraphShader, SubgraphShader };
NvBlastProgramParams programParams = { damageDescs, damageDescCount, materialProperties };
// Generating the set of Fracture Commands does not modify the NvBlastActor.
NvBlastActorGenerateFracture( fractureCommands, actor, damageProgram, &programParams, logFn, &timers );
// Step two: Apply Fracture Commands
// Applying Fracture Commands does modify the state of the NvBlastActor.
// The Fracture Events report the resulting state of each Bond or Chunk involved.
// Chunks fractured hard enough will also fracture their children, creating Fracture Events for each.
NvBlastActorApplyFracture( fractureEvents, actor, fractureCommands, logFn, &timers );
// Step three: Splitting
// The Actor may be split into all its smallest pieces.
uint32_t maxNewActorCount = NvBlastActorGetMaxActorCountForSplit( actor, logFn );
std::vector<NvBlastActor*> newActors( maxNewActorCount );
// Make this memory available to NvBlastSplitEvent.
NvBlastActorSplitEvent splitEvent;
splitEvent.newActors = newActors.data();
// Some temporary memory is necessary as well.
std::vector<char> scratch( NvBlastActorGetRequiredScratchForSplit( actor, logFn ) );
// New actors created are reported in splitEvent.newActors.
// If newActorCount != 0, then the old actor is deleted and is reported in splitEvent.deletedActor.
size_t newActorCount = NvBlastActorSplit( &splitEvent, actor, maxNewActorCount, scratch.data(), logFn, &timers );
``` |
id1_changes.md | # Omniverse Wrapp Change Log
## 1.0.0
- **Initial Omniverse Nucleus WRAPP release.** |
id2_index.md | # Execution Framework
The Omniverse ecosystem enjoys a bevy of software components (e.g. PhysX, RTX, USD, OmniGraph, etc). These software components can be assembled together to form domain specific applications and services. One of the powerful concepts of the Omniverse ecosystem is that the assembly of these components is not limited to compile time. Rather, **users** are able to assemble these components **on-the-fly** to create tailor-made tools, services, and experiences.
With this great power comes challenges. In particular, many of these software components are siloed and monolithic. Left on their own, they can starve other components from hardware resources, and introduce non-deterministic behavior into the system. Often the only way to integrate these components together was with a model “don’t call me, I’ll call you”.
For such a dynamic environment to be viable, an intermediary must be present to guide these different components in a composable way. The **Execution Framework** is this intermediary.
The Omniverse Execution Framework’s job is to orchestrate, at runtime, computation across different software components and logical application stages by decoupling the description of the compute from execution.
## Architecture Pillars
The Execution Framework (i.e. EF) has three main architecture pillars.
The first pillar is **decoupling** the authoring format from the computation back end. Multiple authoring front ends are able to populate EF’s intermediate representation (IR). EF calls this intermediate representation the [execution graph](#ef-execution-graph). Once populated by the front end, the execution graph is transformed and refined, taking into account the available hardware resources. By decoupling the authoring front end from the computation back end, developers are able to assemble software components without worrying about multiple hardware configurations. Furthermore, the decoupling allows EF to optimize the computation for the current execution environment (e.g. HyperScale).
The second pillar is **extensibility**. Extensibility allows developers to augment and extend EF’s capabilities without changes to the core library. Graph [transformations](#ef-pass-concepts), [traversals](#ef-graph-traversal-guide), [execution behavior](#ef-execution-concepts), computation logic, and [scheduling](#ef-execution-concepts) are examples of EF features that can be [extended](#ef-plugin-creation) by developers.
# Composable architecture
The third pillar of EF is **composability**. Composability is the principle of constructing novel building blocks out of existing smaller building blocks. Once constructed, these novel building blocks can be used to build yet other larger building blocks. In EF, these building blocks are nodes (i.e. `Node`).
Nodes stores two important pieces of information. The first piece they store is connectivity information to other nodes (i.e. topology edges). Second, they stores the **computation definition**. Computation definitions in EF are defined by the `NodeDef` and `NodeGraphDef` classes. `NodeDef` defines opaque computation while `NodeGraphDef` contains an entirely new graph. It is via `NodeGraphDef` that EF derives its composibility power.
The big picture of what EF is trying to do is simple: take all of the software components that wish to run, generate nodes/graphs for the computation each component wants to perform, add edges between the different software components’ nodes/graphs to define execution order, and then optimize the graph for the current execution environment. Once the **execution graph** is constructed, an **executor** traverses the graph (in parallel when possible) making sure each software component gets its chance to compute.
## Practical Examples
Let’s take a look at how Omniverse USD Composer, built with Omniverse Kit, handles the the update of the USD stage.
Kit maintains a list of extensions (i.e. software components) that either the developer or user has requested to be loaded. These extensions register callbacks into Kit to be executed at fixed points in Kit’s update loop. Using an empty scene, and USD Composer’s default extensions, the populated execution graph looks like this:
CurveManipulator
OmniSkel
SkeletonsCombo
SingletonCurveEditor
CurveCreator
AnimationGraph
Stage Recorder
SequencePlayer
PhysXCameraPrePhysics
PhysXSupportUI
PhysxInspector Before Update Physics
PhysXVehiclePrePhysics
PhysxInspector After Update Physics
UsdPhysicsUI
PhysXUI
PhysXCameraPostPhysics
PhysxInspector Debug visualization
SkelAnimationAnnotation
PhysXVehiclePostPhysics
PhysX
SceneVisualization
PhysXFabric
DebugDraw
<text fill="#ffffff" font-family="Times, serif" font-size="14px" id="text414" text-anchor="middle" x="6216.4199" y="-535.79999">
WarpKernelAttach
</text>
<text fill="#ffffff" font-family="Times, serif" font-size="14px" id="text432" text-anchor="middle" x="7164.7598" y="-535.79999">
FlowUsd
</text>
<text fill="#ffffff" font-family="Times, serif" font-size="14px" id="text444" text-anchor="middle" x="7349.98" y="-535.79999">
PhysXStageUpdateLast
</text>
<span class="caption-text">
USD Composer's execution graph used to update the USD stage.
</span>
Notice in the picture above that each node in the graph is represented as an opaque node, except for the OmniGraph (OG) front-end. The OmniGraph node further refines the compute definition by expressing its update pipeline with *pre-simulation*, *simulation*, and *post-simulation* nodes. This would not be possible without EF’s **composable architecture**.
Below, we illustrate an example of a graph authored in OG that runs during the simulation stage of the OG pipeline. This example runs as part of Omniverse Kit, with a limited number of extensions loaded to increase the readability of the graph and to illustrate the dynamic aspect of the execution graph population.
<text font-family="Times, serif" font-size="14px" id="text759" text-anchor="middle" x="1479.3" y="-1087.4">
EXECUTION GRAPH | kit.def.execution(8412328473570437098)
</text>
<text font-family="Times, serif" font-size="14px" id="text765" text-anchor="middle" x="2137.3899" y="-778.40002">
/World/ActionGraph(1) | og.def.graph_execution(1354986524710330633)
</text>
<text font-family="Times, serif" font-size="14px" id="text771" text-anchor="middle" x="1596.3" y="-1054.4">
kit.legacyPipeline(2) | kit.def.legacyPipeline(14601541822497998125)
</text>
<text font-family="Times, serif" font-size="14px" id="text777" text-anchor="middle" x="1743.0601" y="-897.40002">
OmniGraph(2) | OmniGraphDef(13532122613264624703)
</text>
<text fill="#ffffff" font-family="Times, serif" font-size="14px" id="text783" text-anchor="middle" x="138.78999" y="-844.79999">
kit.customPipeline
</text>
<text font-family="Times, serif" font-size="14px" id="text789" text-anchor="middle" x="830.34003" y="-837.40002">
og.pre_simulation(1) | og.def.pre_simulation(18371527843990822053)
</text>
<text font-family="Times, serif" font-size="14px" id="text795" text-anchor="middle" x="2008.09" y="-811.40002">
og.simulation(2) | og.def.simulation(2058752528039269071)
</text>
<text font-family="Times, serif" font-size="14px" id="text807" text-anchor="middle" x="1366.47" y="-864.40002">
og.post_simulation(3) | og.def.post_simulation(12859070463537551084)
</text>
<figure class="align-center">
<figcaption>
<p>
<span class="caption-text">
An example of the OmniGraph definition
</span>
</p>
</figcaption>
</figure>
Generating more fine-grained execution definitions allows OG to scale performance with available CPU resources. Leveraging **extensibility** allows implementation of executors for different graph types outside of the core OG library. This joined
**composability** creates a foundation for executing compound graphs.
The final example in this overview focuses on execution pipelines in Omniverse Kit. Leveraging all of the architecture pillars, we can start customizing per application (and/or per scene) execution pipelines. There is no longer a need to base execution ordering only on a fixed number or keep runtime components siloed. In the picture below, as a proof-of-concept, we define at runtime a new custom execution pipeline. This new pipeline runs before the “legacy” one ordered by a magic number and introduces fixed and variable update times. Extending the ability of OG to choose the pipeline stage in which it runs, we are able to place it anywhere in this new custom pipeline. Any other runtime component can do the same thing and leverage the EF architecture to orchestrate executions in their application.
custom.async
custom.syncMain
omni_graph_nodes_constantdouble3
CubeReadAttrib_02
on_playback_tick
og.customPipelineToUsd
make_transformation_matrix_from_trs_01
PhysX
matrix_multiply
SkelAnimationAnnotation
get_translation
<figure class="align-center">
<figcaption>
<p>
<span class="caption-text">
The customizable execution pipeline in Kit - POC
</span>
</p>
</figcaption>
</figure>
## Next Steps
Above we provided a brief overview of EF’s philosophy and capabilities. Readers are encouraged to continue learning about EF by first reviewing Graph Concepts. |
id5_CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.5.2] - 2024-03-07
- Fix the version of omni_client_library to 2.43 for forward compatibility.
## [0.5.1] - 2024-02-26
- Bump kit-sdk up from 105.2.137506 to 106.0.137667.
## [0.5.0] - 2024-02-09
- Bump kit-sdk up from 105.1.123866 to 105.2.137506.
### Tool [0.5.0]
- Added
- compare_volume()
### NeuralVDB [0.5.0]
- Added
- batch_encode_grids()
- batch_encode_grids_from_buffer()
- batch_encode_grids_with_auto_config()
- batch_encode_grids_from_buffer_with_auto_config()
## [0.4.1] - 2024-01-10
### Tool [0.4.1]
- Fixed
- Reference count issue in pybind functions
### NeuralVDB [0.3.9]
- Fixed
- Reference count issue in pybind functions (decode_grids)
## [0.4.0] - 2023-11-14
### Tool [0.4.0]
- Fixed
- Replace broken sphere.mvdb files
- Remove stl (std::vector) for ABI safety
- Changed
- Move test files from neuralvdb to vdbtool
- Change GridData in internal function names to Volume
- Update docs
## Added
- clip_volume()
- composite_volume()
- compute_volume()
- expand_levelset()
- flood_levelset()
- levelset_to_fog()
- offset_levelset()
- points_to_levelset()
- points_to_point_volume()
- point_volume_to_points()
- prune_levelset()
- resample_volume()
- scatter_points_to_volume()
- corresponding docs
## NeuralVDB [0.3.8]
- Changed
- Move test files from neuralvdb to vdbtool
- Change `GridData` in internal function names to `Volume`
## [0.3.7] - 2023-11-06
- NeuralVDB: RGBA8 min/max fix
## [0.3.6] - 2023-10-19
- Tool: Add `create_volume_from_coord_value_pairs` API
- NeuralVDB: Support for RGBA8 NanoVDB grid
## [0.3.5] - 2023-10-12
- NeuralVDB: Adding carb.settings to control default logging/decode behavior
## [0.3.4] - 2023-10-10
- NeuralVDB: Adding device type and backend options for encoding and decoding
## [0.3.3] - 2023-09-20
- NeuralVDB: Pruning support for level-1 tiles
- NeuralVDB: Fix non-deterministic pruning
- NeuralVDB: Empty grid handling while encoding and decoding
## [0.3.2] - 2023-08-02
### Changed
- Add documentation
- Fix invalid test VDB files |
Imgui.md | # IMGUI
This extension adds support for setup imgui StyleColor and StyleVar on demand.
Imgui settings can be specified in `[[settings.exts."omni.app.setup".imgui]]` sections.
For example:
```toml
[settings.exts."omni.app.setup".imgui.color]
ScrollbarGrab = 0.4
ScrollbarGrabHovered = [0.1, 0.2, 0.3]
ScrollbarGrabActive = [0.4, 0.5, 0.6, 0.7]
[settings.exts."omni.app.setup".imgui.float]
DockSplitterSize = 2
```
This equals to
```c++
import carb.imgui as _imgui
imgui = _imgui.acquire_imgui()
imgui.push_style_color(_imgui.StyleColor.ScrollbarGrab, carb.Float4(0.4, 0.4, 0.4, 1))
imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabHovered, carb.Float4(0.1, 0.2, 0.3, 1))
imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabActive, carb.Float4(0.4, 0.5, 0.6, 0.7))
imgui.push_style_var_float(_imgui.StyleVar.DockSplitterSize, 2)
``` |
index.md | # omni.simready.cadtools: SimReady CAD Tools
## omni.simready.cadtools
- [Simready CAD Tools [omni.simready.cadtools]](Overview.html)
- [API (python)](API.html)
- [Changelog](Changelog.html)
- [1.0.0-alpha.1] - 2024-03-13](Changelog.html#alpha-1-2024-03-13) |
indices-and-tables_index.md | # Omni.VDB API Documentations and Tutorials
## Contents
- [Omni.VDB](README.html)
- [Extensions](source/extensions/index.html)
- [omni.vdb.neuralvdb](source/extensions/omni.vdb.neuralvdb/docs/index.html)
- [omni.vdb.tool](source/extensions/omni.vdb.tool/docs/index.html)
- [Changelog](CHANGELOG.html)
- [0.5.2] - 2024-03-07
- [0.5.1] - 2024-02-26
- [0.5.0] - 2024-02-09
- [0.4.1] - 2024-01-10
- [0.4.0] - 2023-11-14
- [0.3.7] - 2023-11-06
- [0.3.6] - 2023-10-19
- [0.3.5] - 2023-10-12
- [0.3.4] - 2023-10-10
- [0.3.3] - 2023-09-20
- [0.3.2] - 2023-08-02
## Indices and tables
- [Index](genindex.html)
- [Module Index](py-modindex.html)
- [Search Page](search.html) |
Input.md | # Carbonite Input Plugin
## Overview
Carbonite input plugin acts like an input hub, the goal is to make it easy for the input providers to register input devices and events in the input plugin and input users to consume input events or states, abstracting away the underlying mechanisms.
### Input users
Any plugin or client that only cares about consuming the inputs are called input users. Input could be consumed either by registering event listeners or directly polling the input state. Input users should use the `carb::input::IInput` interface.
The main idea behind the user interface design is to unify discrete and analog controls, and assign any type of controls to the user-specified action mapping. More information about the specifics of such unification is presented in the [Values] and [Button flags] sections, and how to set up a user-specified action mapping is described in the [Action mapping] section.
### Input states
Alternatively, it is possible to poll the input device state using functions like `carb::input::IInput::getKeyboardValue` and `carb::input::IInput::getKeyboardButtonFlags`. Similar functions are present for mouse and gamepad input devices. The difference between `get*Value` and `get*ButtonFlags` functions is in how the device button states are treated, and the reasoning behind having two types of interpretations of the same underlying input states is allowing the user to assign any kind of input state, whether it is discrete or analog, to the specific actions. For example, this approach allows to interpret gamepad analog stick as D-pad, assigning discrete actions to analog controls–e.g. analog stick driven up or trigger pressed above specified threshold, can trigger a certain menu to pop up. This works as well if a user wants to move a slider for a determined amount when a discrete keyboard key is pressed.
It is important to note, that there are two input states mapped to any single axis–negative and positive, e.g. `carb::input::MouseInput::eMoveLeft` / `carb::input::MouseInput::eMoveRight` corresponding to mouse move on the X axis, or `GamepadInput::eLeftStickLeft` / `GamepadInput::eLeftStickRight` corresponding to the same axis of a left gamepad stick–this is done for consistency and finer action mapping control; user can set up one actions on the negative stick/mouse axis move and a different one for the positive stick/mouse axis move, thus effectively turning them into d-pads. Or allow to rebind camera pitch and yaw control to the keyboard keys.
## Values
The `get*Value` functions return floating point numbers representing the current button state–for discrete device inputs (like keyboard keys, mouse or gamepad buttons) it is either 0.0 or 1.0, and for analog inputs (e.g. mouse axes or gamepad sticks) the returned number can take values between 0.0 and 1.0.
## Frames
`carb.input` transfers the current state to a previous state in the `update*()` functions: `carb::input::InputProvider::updateKeyboard`, `carb::input::InputProvider::updateMouse`, and `carb::input::InputProvider::updateGamepad`. When these functions are called it is considered the beginning of the next frame of the device.
## Button flags
The `get*ButtonFlags` functions return interpreted state flags that tell the user whether particular device input can be considered activated or deactivated for the discrete actions. It also allows callers to distinguish between states when the input was just activated/deactivated, or if they were in that particular state for more than one frame. In other words, mouse button could be just pressed or is held for a while. List describing flags combination and their meaning:
1. `carb::input::kButtonFlagStateUp`: Button is up and was up on a previous frame–basically a default, “null” state.
2. `kButtonFlagStateUp | kButtonFlagTransitionUp`: Button is up, but was just released (i.e. on the previous “frame” it was down)–for the single-time events which typically go on the `onMouseButtonPress`
3. `carb::input::kButtonFlagStateDown`: Button is down, and was down on a previous frame–for the cases when you make the action while the button is pressed (think drawing using pencil in paint or dragging something).
4. `kButtonFlagStateDown | kButtonFlagTransitionDown`: Button is down, but was just pressed (i.e. on the previous “frame” it was up)–for the cases when you need to set some state only once per button down event.
Button flags expressed this way decrease user-side code verbosity and improve usability versus other approaches. For example, if button flags were expressed as four distinct states: `Held`, `Up`, `Pressed`, `Released` – if user only cares about the case when the device input is in the “down” state, the code becomes:
```c++
if (input->getMouseButtonFlags(mouse, MouseInput::eLeftButton) == kButtonFlagPressed ||
input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftButton) == kButtonFlagHeld)
```
i.e. it is now required to check for both `Held` and `Pressed` states, because both mean that the actual state is `Down`. With the button flags approach, it is easy to check for the mouse down event:
```c++
if (input->getMouseButtonFlags(mouse, MouseInput::eLeftButton) & kButtonFlagStateDown)
```
## Input events
### Input events
carb::input::IInput interface provides ways to subscribe and unsubscribe to the input event streams with functions like carb::input::IInput::subscribeToKeyboardEvents / carb::input::IInput::unsubscribeToKeyboardEvents (similar events present for mouse and gamepads).
## Action mapping
### Action mapping
User interface for the input plugin allows to assign any kind of device input to a named action. Each named action can have several device inputs assigned to it. Actions support both state polling and event subscription, similar to the regular device inputs: carb::input::IInput::getActionValue returns floating point value for the named action, carb::input::IInput::getActionButtonFlags returns discrete button flag, and carb::input::IInput::subscribeToActionEvents / carb::input::IInput::unsubscribeToActionEvents allow to manage named action event stream subscriptions.
In case when several inputs are assigned, a prioritizing logic determines the exact action value or flag. Typically, when queried for the continuous action value, maximum absolute value of the assigned inputs is determined–i.e. if two axes of different sticks are assigned to the same action, the stick with maximum deviation from the initial state is prioritized. Alternatively, when queried for the discrete action flag, the following logic determines the prioritized button flag (in the order of decreasing priority):
1. The device input is “held” for some time.
2. The device input was just “pressed”.
3. The device input was just “released”.
4. The device input is in idle state.
This list of priorities for the button flag was designed to make sure that different device inputs assigned to the same action do not conflict with each other–for example if two inputs assigned to the same action were “held”, and then one of the inputs gets released, the action is not interrupted.
**NOTE**: the prioritization logic described is only a recommendation for the input plugin implementation, and is true for the default Carbonite input plugin (carb.input.plugin). Other input plugin implementations may implement different logic to determine action flags or values.
## Input providers
### Input providers
Plugins that aim to feed the input events and states use carb::input::InputProvider interface. |
installing_launcher.md | # Installing Launcher
Please watch the following video for instructions on installing Omniverse Launcher.
## Administrator Rights
Local Admin Rights on the installed computer is recommended for full use and capability of the Omniverse Launcher. Though the launcher will install without admin rights, some tools, connectors, apps, etc. may require admin rights (UAC) to complete the installation.
## First Run
When first running the launcher after install, you will be presented with a series of options.
### Data Collection
Users must agree to allow NVIDIA to collect data regarding usage of the Omniverse Platform.
### Paths
Next you will be presented with a series of path selections.
#### Option
| Option | Description |
|--------------|-----------------------------------------------------------------------------|
| Library Path | This location specifies where apps, connectors and tools are installed when installed from Launcher. |
| Data Path | Displays and allows selection of the Data Path. The data path is where all content on the local Nucleus is stored. |
| Cache Path | This is the location the Cache Database will use to store its cache files. (if installed) |
### Install cache
Though Omniverse Cache is optional, it is highly recommended for users who plan to collaborate with other Omniverse users on your network. This option does require Administrator Privileges on the installed machine and can be installed at a later time if necessary.
Once the installation is complete, please refer to the [User Guide](workstation-launcher.html) for additional help and information on using Launcher. |
install_guide_linux.md | # Installation on Linux
## Prerequisites for Installation
There are two elements that you need to have prior to starting the installation process. Both components are available within the NVIDIA Licensing Portal (NLP).
It’s important to note that the entitlements themselves are provided to the person at the company who makes the purchase, and that person can add others (including the IT Managers) to the Licensing Portal so that they can grab the components listed below. You can read more about this process as part of [Enterprise Quick Start Guide](https://docs.omniverse.nvidia.com/enterprise/latest/enterprise_quickstart-guide.html).
- **Download the IT Managed Launcher Installer.**
- (.AppImage) AppImage since you’re running Linux
- Your Organization Name Identifier (org-name).
To find the IT Managed Launcher executable on the NLP:
1. Once you’ve logged into the Portal, go to the Software Downloads section and look for the NVIDIA Omniverse IT Managed Launcher for your platform of choice (Linux in this case).
2. Click Download to initiate the download process of the installer.
**Note**
Once the installer is downloaded, you should place it onto your designated staging hardware inside of your company firewall.
Next you’ll grab your Organization’s Name Identifier (org-name).
1. To do this, at the top of the portal, hover your mouse over your user account until you see a **View Settings** message pop up. (See image below)
2. Within the resulting My Info dialog, under the Organization area, you will see an **org-name** section. The information that is presented there represents your Organization Name and will be required later.
**View Settings:**
![nlp_license_setting](_images/nlp_license_setting.png)
Be sure to capture this information **before** you begin the installation process. You will need it to install the IT Managed Launcher as well as configure your enterprise enablement.
**Organization Name**
![nlp_cust_id](_images/nlp_cust_id.png)
Once you have this information, it’s time to install the **IT Managed Launcher**.
There are two ways to install the IT Managed Launcher on Linux.
- **Manually**: You can install the Launcher manually on a user’s workstation directly (e.g. Terminal / Bash)
- **Deployment**: You can pre-configure the Launcher to be installed as part of a deployment software strategy (e.g. SaltStack).
## Terminal / Bash
### Deploying Launcher
To install the IT Managed Launcher on Linux (Ubuntu 20.04 and 22.04), follow these steps:
Run the IT Managed Launcher by launching the AppImage you downloaded from the Licensing Portal locally on users workstations.
#### Important
On Linux, instead of running the IT Managed Launcher installer, you first need to set the AppImage as an **executable program** and launch it. This will register the app as the default handler for `omniverse-launcher://` custom URLs described elsewhere in this document that installs the applications themselves.
For Ubuntu users, make sure you have done the following so that the AppImage will launch.
From the Terminal, first run:
```
> sudo apt install libfuse2
```
Then make sure you check the permissions of the downloaded AppImage file to verify that it can be run as a program.
Using the UI, right-click on the AppImage and choose Properties. Go to the Permissions section and ensure that the Allow executing file as program checkbox is checked.
Or, from the Terminal, in the directory where the AppImage was saved:
```
> chmod +x omniverse-launcher-linux-enterprise.AppImage
```
Once those items are completed, you should be able to double-click on the AppImage package and have it run. Or, run it from the Terminal:
```
> ./omniverse-launcher-linux-enterprise.AppImage
```
### Setting up TOML Files
( Learn more about TOML syntax: https://toml.io/en/ )
1) When the AppImage launches, you’ll immediately be prompted to set a number of default locations for Omniverse. These paths determine where Omniverse will place the installed applications (Library Path), data files (Data Path), content files (Content Path) and Cache information.
All of the paths set here will be recorded and stored within an `omniverse.toml` file for later editing as needed. It’s important to note that all of the paths can be changed as per preference and/or IT Policy at a later time. By default, the installer takes all of your path preferences and stores them in the following folder structure:
```
~/Home/.nvidia-omniverse/config
```
2) Once you’ve set the default paths for Omniverse to use, click on the **Continue Button**.
You should now be presented with a blank Library window inside of the launcher.
3) Close the IT Managed Launcher.
At this point, the IT Managed Launcher is installed. However, before you start to install Omniverse applications, you’ll need to add two additional, important configuration files.
When you look at the default configuration location in Linux (`~/Home/.nvidia-omniverse/config`), you should see the `omniverse.toml` file that the installer added as shown below.
This `omniverse.toml` file is the primary configuration file for the IT Managed Launcher. Within this configuration file, the following paths are described, and they should match the selections you made in step 1. Be aware that you can set these after the installation to different paths as needed for security policy at any time.
```
[paths]
library_root = "/home/myuser/.local/share/ov/pkg" # Path where to install all applications
data_root = "/home/myuser/.local/share/ov/data" # Folder where Launcher and Omniverse apps store their data files
cache_root = "/home/myuser/.cache/ov" # Folder where Omniverse apps store their cache and temporary files
logs_root = "/home/myuser/.nvidia-omniverse/logs" # Folder where Launcher and Omniverse apps store their logs
extension_root = /home/myuser/Documents/kit/shared/exts # Folder where all Omniverse shared extensions are stored
content_root = "/home/myuser/Downloads" # Folder where Launcher saves downloaded content packs
confirmed = true # Confirmation that all paths are set correctly, must be set to `true`
```
#### Note
If a system administrator doesn’t want to allow users to change these paths, the omniverse.toml file can be marked as read-only.
Also, if a System Administrator plans to install the IT Managed Launcher to a shared location like `~/Home/Shared` on Linux, they need to specify a shared folder for `library_root` and `logs_root` path in the `omniverse.toml` file.
```
```toml
omniverse.toml
```
```code
file.
```
```markdown
You’re now going to add two additional files to this
```code
/config
```
folder in addition to the
```code
omniverse.toml
```
file.
```
```markdown
- ```code
privacy.toml
```
file to record consent choices for data collection and capture of crash logs.
- ```code
license.toml
```
to provide your license details.
```
```markdown
**Important**
By opting into telemetry, you can help improve the performance & stability of the software. For more details on what data is collected and how it is processed see this section.
```
```markdown
**4)**
Within the /config folder, create a text file named privacy.toml, which is the configuration file for Omniverse telemetry. Within this privacy file, specify the following:
```
```toml
[privacy]
performance = true
personalization = true
usage = true
```
```markdown
Once this file contains these four lines, save the file.
```
```markdown
**Note**
If your IT or Security Policy prohibits the collection of telemetry, set all of these values to **false**.
```
```markdown
**5)**
For the last file needed in this folder, create a text file named license.toml, which is the licensing configuration file for Omniverse. Within this licensing file, specify the **Organization Name Identifier** (org-name) you retrieved from the Licensing Portal:
```
```toml
[ovlicense]
org-name = "<insert-your-org-name-here>"
```
```markdown
Once this file contains these two lines, save the file.
```
```markdown
When you’ve completed these steps, your ```code
~/Home/.nvidia-omniverse/config
``` folder should have the directory and ```code
.toml
``` files like the screenshot below:
```
```markdown
That completes the IT Managed Launcher installation for Linux and Omniverse applications can now be installed to users’ workstations.
```
```markdown
**Setting Up Packages**
Once the Omniverse IT Managed Launcher is installed and configured, you’re ready to install the Omniverse foundation applications for your users.
```
```markdown
As an IT Manager, you now need to download the various Omniverse foundation applications from the Omniverse Enterprise Web Portal. Each application will come in the form of an archived **.zip** file that you can take to a user’s machine and install either manually, or via your internal deployment framework.
```
```markdown
**1)**
To begin, log into the Omniverse Enterprise Web Portal.
```
```markdown
**2)**
In the left-hand navigation area, select **Apps**, and from the resulting view, click on the tile of the Omniverse foundation application you want to install.
```
```markdown
**3)**
Available releases are categorized by release channel. A release is classified as **Beta**, **Release**, or **Enterprise**, depending on its maturity and stability.
```
```markdown
- **Beta**
- Beta builds may or may not be feature complete or fully stable. These are good for testing new Omniverse functionality, but aren’t guaranteed to be ready for production.
- **Release**
- Release builds (also known as GA or General Availability) are feature complete and stable builds ready for production.
- **Enterprise**
- Enterprise builds are provided for Enterprise customers and represent supported production versions of Omniverse software.
```
```markdown
**4)**
Select a package version in the dropdown list and click **Download**.
```
```markdown
**5)**
Clicking the download button will prompt you to select the Windows or Linux version of the application to install. Choose the OS version that matches the user’s workstation’s OS.
```
## Deploying the Apps
Installation of the Omniverse applications is handled via a custom protocol URL on the user’s machine or using a deployment framework like SaltStack to manage the process and trigger the IT Managed Launcher to run and install the chosen application.
The most basic way to install Omniverse foundation applications is to open a custom protocol URL directly on the user’s machine. The simple command below will trigger the IT Managed Launcher to run the installation routine for the given Omniverse application .zip archive.
The format of the custom protocol can vary depending on the command line interface used, but as a general rule of thumb, the settings are as follows:
```
omniverse-launcher://install?path=<package.zip>
```
Where `<package.zip>` represents the name and path where the downloaded application archive is on the local workstation. Be aware that it does not matter where you place the archive, the custom protocol will install the application to its default location based on the `library_root` path in the `omniverse.toml` file that you configured earlier as part of the IT Managed Launcher installation process.
Example:
```
xdg-open omniverse-launcher://install?path=/var/packages/usd_explorer.zip
```
When the command is run, it will trigger the IT Managed Launcher to open and it will begin the installation process. You should see a screen similar to the one below that shows the progress bar for the application being installed in the upper right of the Launcher window.
Once the installation is complete, the Omniverse application will appear in the **Library** section of the Launcher window and these steps can be repeated for any additional applications you want to make available to your users.
## SaltStack
To deploy the IT Managed Launcher executable file to users’ Linux workstations you will need to perform several tasks.
You’ll need to download and stage the IT Managed Launcher .AppImage file and place it on the Salt master under the file storage location listed under `files_roots` in `/etc/salt/master`. For example:
```
file_roots:
base:
- /srv/salt
```
Next, you’ll create and pre-configure a user’s `omniverse.toml`, `policy.toml`, and `license.toml` files and stage them in the same shared network location.
After that, you’ll create an `omniverse.SLS` template Salt file to control the installation process and reference `.toml` files you’ve set up.
Finally, you’ll configure the `top.sls` Salt file within the Windows Local Group Policy to execute at user logon to trigger the installation and configuration of the IT Managed Launcher for the user on their local workstation.
As per the prerequisite section of this document, you should have already downloaded the Linux version of the IT Managed Launcher install file from the **Enterprise Web Portal**. If not, please do that first and place it in the Salt master under the file storage location as described above.
### Setting up TOML Files
The first step is to create and stage the three `.toml` files for deployment.
**omniverse.toml**: Copy the following information into a new text document, replacing the path information with the location you want Omniverse and its data installed on each user’s workstation. Once done, save it to the Salt master file storage location (`/srv/salt`).
```
[paths]
library_root = "/home/myuser/.local/share/ov/pkg" # Path where to install all applications
data_root = "/home/myuser/.local/share/ov/data" # Folder where Launcher and Omniverse apps store their data files
cache_root = "/home/myuser/.cache/ov" # Folder where Omniverse apps store their cache and temporary files
logs_root = "/home/myuser/.nvidia-omniverse/logs" # Folder where Launcher and Omniverse apps store their logs
extension_root = /home/myuser/Documents/kit/shared/exts # Folder where all Omniverse shared extensions are stored
content_root = "/home/myuser/Downloads" # Folder where Launcher saves downloaded content packs
confirmed = true # Confirmation that all paths are set correctly, must be set to `true`
```
Where `/myuser/` represents the local user’s account.
- **privacy.toml**: Copy the following information into a new text document. This is the configuration file for Omniverse telemetry capture for each user’s workstation. Once done, save it to the Salt master file storage location (`/srv/salt`).
```toml
[privacy]
performance = true
personalization = true
usage = true
```
- **Note**: If your IT or Security Policy prohibits the collection of telemetry on a user’s workstation, set all of the values in the file to **false**.
- **license.toml**: This is the licensing configuration file for Omniverse. Within this licensing file, specify the **Organization Name Identifier** (org-name) you retrieved from the Licensing Portal in the prerequisites section. Once done, save it to the staging location (`/srv/salt`).
```toml
[ovlicense]
org-name = "<insert-your-org-name-here>"
```
- Once you’ve saved all three `.toml` files, it’s time to build the script file that will be used to help deploy the files to each user’s workstation.
## Deploying Launcher
1. Create a new `omniverse.SLS` Salt template in `/srv/salt` with the following information:
```yaml
omniverse_enterprise_launcher:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/Omniverse/launcher.AppImage
- source: salt://Launcher.AppImage
omniverse_config_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/omniverse.toml
- source: salt://omniverse.toml
omniverse_privacy_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/privacy.toml
- source: salt://privacy.toml
omniverse_license_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/license.toml
- source: salt://license.toml
omniverse_dirs:
file.directory:
- user: ubuntu
- group: ubuntu
- mode: 777
- names:
- /home/ubuntu/Omniverse
- /home/ubuntu/Omniverse/logs
- /home/ubuntu/Omniverse/data
- /home/ubuntu/Omniverse/cache
- /home/ubuntu/.nvidia-omniverse/logs
```
2. With that ready, you now need to add this omniverse template to your top.sls file.
```yaml
base:
'omni*': # All minions with a minion_id that begins with "omni"
- omniverse
```
3. Apply the Salt state: `salt 'omni*' state.apply`
4. When the user logs into their desktop, have them run `./Omniverse/launcher.AppImage` from a terminal. This will open the **IT Managed Launcher**.
## Setting up Packages
Once the Omniverse IT Managed Launcher is installed and configured, you’re ready to install the Omniverse foundation applications for your users.
1. To begin, log into the Omniverse Enterprise Web Portal.
2. In the left-hand navigation area, select **Apps**, and from the resulting view, click on the tile of the Omniverse foundation application you want to install.
Available releases are categorized by release channel. A release is classified as **Beta**, **Release**, or **Enterprise**, depending on its maturity and stability.
- **Beta**: Beta builds may or may not be feature complete or fully stable. These are good for testing new Omniverse functionality, but aren’t guaranteed to be ready for production.
- **Release**: Release builds (also known as GA or General Availability) are feature complete and stable builds ready for production.
- **Enterprise**: Enterprise builds are the most stable and secure builds, optimized for large-scale deployments.
| Enterprise | Enterprise builds are provided for Enterprise customers and represent supported production versions of Omniverse software. |
|-----------|------------------------------------------------------------------------------------------------------------------------|
**3)** Select a package version in the dropdown list and click **Download**.
**4)** Clicking the download button will prompt you to select the Windows or Linux version of the application to install. Choose the OS version that matches the user’s workstation.
**5)** Once downloaded, the application archive must then be transferred to the user’s machine or hosted on your chosen local network staging hardware so it can be accessed and installed on a user’s workstation.
Once you’ve downloaded the various Omniverse foundation applications, you are ready to proceed to the installation.
## Deploying the Apps
**1)** To deploy usd_explorer in your SaltStack, update your `omniverse.SLS` Salt template in `/srv/salt` to include the following information:
```text
omniverse_enterprise_launcher:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/Omniverse/launcher.AppImage
- source: salt://Launcher.AppImage
omniverse_usd_explorer_zip:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/Omniverse/usd_explorer.zip
- source: salt://usd_explorer.zip
omniverse_config_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/omniverse.toml
- source: salt://omniverse.toml
omniverse_privacy_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/privacy.toml
- source: salt://privacy.toml
omniverse_license_toml:
file.managed:
- user: ubuntu
- group: ubuntu
- mode: 777
- name: /home/ubuntu/.nvidia-omniverse/config/license.toml
- source: salt://license.toml
omniverse_dirs:
file.directory:
- user: ubuntu
- group: ubuntu
- mode: 777
- names:
- /home/ubuntu/Omniverse
- /home/ubuntu/Omniverse/logs
- /home/ubuntu/Omniverse/data
- /home/ubuntu/Omniverse/cache
- /home/ubuntu/.nvidia-omniverse/logs
```
**2)** Apply the Salt state: `salt ‘omni*’ state.apply`.
**3)** When the user logs in to the desktop, have them run:
```text
> ./Omniverse/launcher.AppImage
```
This will open the launcher.
**4)** From a separate terminal, have them run:
```text
> xdg-open omniverse-launcher://install?path=./Omniverse/code.zip
```
When it completes, they will have the code extension installed in their launcher. |
install_guide_win.md | # Installation on Windows
## Prerequisites for Installation
There are two elements that you need to have prior to starting the installation process. Both components are available within the NVIDIA Licensing Portal (NLP).
It’s important to note that the entitlements themselves are provided to the person at the company who makes the purchase, and that person can add others (including the IT Managers) to the Licensing Portal so that they can grab the components listed below. You can read more about this process as part of our Enterprise Quick Start Guide.
- **Download the IT Managed Launcher Installer.**
- (.exe) Executable since you’re running Windows.
- Your Organization Name Identifier (org-name).
To find the IT Managed Launcher executable on the NLP:
1. Once you’ve logged into the Portal, go to the Software Downloads section (left nav) and look for the NVIDIA Omniverse IT Managed Launcher for your platform of choice (Windows in this case).
2. Click Download to initiate the download process of the installer.
**Note**
Once the installer is downloaded, you should place it onto your designated staging hardware inside of your company firewall.
Next you’ll grab your Organization’s Name Identifier (org-name).
1. To do this, at the top of the portal, hover your mouse over your user account until you see a **View Settings** message pop up. (See image below)
2. Within the resulting My Info dialog, under the Organization area, you will see an **org-name** section. The information that is presented there represents your Organization Name and will be required later.
**View Settings:**
![nlp_license_setting](_images/nlp_license_setting.png)
Be sure to capture this information **before** you begin the installation process. You will need it to install the IT Managed Launcher as well as configure your enterprise enablement.
**Organization Name**
![nlp_cust_id](_images/nlp_cust_id.png)
Once you have this information, it’s time to install the **IT Managed Launcher**.
There are two ways to install the IT Managed Launcher on Windows:
- **Manually**: You can install the Launcher manually on a user’s workstation directly (e.g. using CMD or PowerShell).
- **Deployment**: You can pre-configure the Launcher to be installed as part of a deployment software strategy (e.g. SCCM / Group Policy)
## PowerShell
### Deploying Launcher
1. Run the IT Managed Launcher installer you downloaded from the Licensing Portal locally on a user’s workstation. This can be done in the UI by double-clicking `omniverse-launcher-win-enterprise.exe` or via the PowerShell terminal, by typing:
```
./omniverse-launcher-win-enterprise.exe
```
2. Follow the prompts until the installer finishes. At the end of the install process, the option to immediately run the IT Managed Launcher will be checked by default.
3. Leave that option checked, then click **Finish** to finish the install process.
**Note:**
You can install the IT Managed Launcher silently by adding the /S parameter to the end of the filename. Example:
```
./omniverse-launcher-win-enterprise.exe /S
```
**Note:**
You can install the IT Managed Launcher to a specific location by adding the /D parameter to the end of the filename. Example:
```
./omniverse-launcher-win-enterprise.exe /S /D="C:\Program Files\NVIDIA Corporation\NVIDIA Omniverse Launcher"
```
### Setting Up TOML Files
(Learn more about TOML syntax: https://toml.io/en/)
**1)** When the IT Managed Launcher first opens, you’ll immediately be prompted to set a number of default locations for Omniverse data. These paths determine where Omniverse will place the installed applications (Library Path), data files (Data Path), content files (Content Path) and Cache information.
All of the paths set here will be recorded and stored within an `omniverse.toml` file for later editing as needed. It’s important to note that all of the paths set here can be changed as per preference and IT Policy at a later time. By default, the installer takes all of these path preferences and stores them in the omniverse.toml under the following folder structure:
```
c:\Users\[username]\.nvidia-omniverse\config
```
Where **[username]** represents the local user’s account.
**2)** Once you’ve set the default paths for Omniverse to use, click on the **Continue Button**.
You should now be presented with a blank Library window inside of the launcher.
**3)** Close the IT Managed Launcher.
At this point, the IT Managed Launcher is installed. However, before you start to install Omniverse applications, you’ll need to add two additional, important configuration files.
When you look at the default configuration location in Windows (`c:\Users\[username]\.nvidia-omniverse\config`), you should see the `omniverse.toml` file that the installer added as shown below.
This `omniverse.toml` file is the primary configuration file for the IT Managed Launcher. Within this configuration file, the following paths are described, and they should match the selections you made in step **1**. Be aware that you can set these after the installation to different paths as needed for security policy at any time.
```
[paths]
library_root = "C:\\Omniverse\\library" # Path where to install all Omniverse applications
data_root = "C:\\Omniverse\\data" # Folder where Launcher and Omniverse apps store their data files
cache_root = "C:\\Omniverse\\cache" # Folder where Omniverse apps store their cache and temporary files
logs_root = "C:\\Users\\[username]\\.nvidia-omniverse\\logs" # Folder where Launcher and Omniverse apps store their logs
content_root = “C:\\Users\\[username]\\Downloads” # Folder where Launcher saves downloaded content packs
extension_root = “C:\\Users\\[username]\\Documents\\kit\\shared\\exts” # Folder where all Omniverse shared extensions are stored
confirmed = true # Confirmation that all paths are set correctly, must be set to `true`
```
**Important:**
Also be aware that all paths on Windows require a **double backslash** (\) for proper operation.
**Note:**
If a system administrator doesn’t want to allow users to change these paths, the `omniverse.toml` file can be marked as read-only. Also, if a System Administrator plans to install the IT Managed Launcher to a shared location like Program Files on Windows, they need to specify a shared folder for **library_root** and logs_root path in `omniverse.toml`.
# Setting Up the IT Managed Launcher
You’re now going to add two additional files to this `/config` folder in addition to the `omniverse.toml` file.
- `privacy.toml` file to record consent choices for data collection and capture of crash logs.
- `license.toml` to provide your license details.
## Note
When creating or editing these configuration files, use a text editor such as Windows Notepad. Do **not** use a rich-text editor such as **Wordpad** or **Microsoft Word**.
## Important
By opting into telemetry within the privacy.toml, you can help improve the performance & stability of the software. For more details on what data is collected and how it is processed see this section.
**4)** Within the `/config` folder, create a text file named `privacy.toml`. This is the configuration file for Omniverse telemetry. Within this privacy file, copy the following information:
```toml
[privacy]
performance = true
personalization = true
usage = true
```
Once this file contains these four lines, save the file.
## Note
If your IT or Security Policy prohibits the collection of telemetry on a user’s workstation, set all of the values in the file to false.
**5)** For the last file needed in your `/config` folder, create a text file named `license.toml`. This is the licensing configuration file for Omniverse. Within this licensing file, specify the **Organization Name Identifier** (org-name) you retrieved from the **Licensing Portal** in the prerequisites section:
```toml
[ovlicense]
org-name = "<insert-your-org-name-here>"
```
Once this file contains these two lines, save the file.
Once you’ve completed these steps, your `/.nvidia-omniverse/config` folder should have the directory and required .toml files.
That completes the IT Managed Launcher manual installation for Windows and Omniverse applications can now be installed to users’ workstations.
# Setting Up Packages
Once the Omniverse IT Managed Launcher is installed and configured, you’re ready to install the Omniverse foundation applications for your users.
As an IT Manager, you now need to download the various Omniverse foundation applications from the Omniverse Enterprise Web Portal. Each application will come in the form of an archived **.zip** file that you can take to a user’s machine and install either manually, or via your internal deployment framework.
**1)** To begin, log into the Omniverse Enterprise Web Portal.
**2)** In the left-hand navigation area, select **Apps**, and from the resulting view, click on the tile of the Omniverse foundation application you want to install.
**3)** Available releases are categorized by release channel. A release is classified as **Beta**, **Release**, or **Enterprise**, depending on its maturity and stability.
| Release Type | Description |
|--------------|-------------|
| Beta | Beta builds may or may not be feature complete or fully stable. These are good for testing new Omniverse functionality, but aren’t guaranteed to be ready for production. |
| Release | Release builds (also known as GA or General Availability) are feature complete and stable builds ready for production. |
| Enterprise | Enterprise builds are provided for Enterprise customers and represent supported production versions of Omniverse software. |
**4)** Select a package version in the dropdown list and click **Download**.
## Downloading the Apps
5) Clicking the download button will prompt you to select the Windows or Linux version of the application to install. Choose the OS version that matches the user’s workstation.
6) Once downloaded, the application archive must then be transferred to the user’s machine or hosted on your chosen local network staging hardware so it can be accessed and installed on a user’s workstation.
Once you’ve downloaded the various Omniverse foundation applications, you are ready to proceed to the installation.
## Deploying the Apps
The most basic way to install Omniverse foundation applications is to open a custom protocol URL directly on the user’s machine. The simple command below will trigger the IT Managed Launcher to run the installation routine for the given Omniverse application .zip archive.
The format of the custom protocol can vary depending on the command line interface used, but as a general rule of thumb, the settings are as follows:
```markdown
```
omniverse-launcher://install?path=<package.zip>
```
Where `<package.zip>` represents the name and path where the downloaded application archive is on the local workstation. Be aware that it does not matter where you place the archive, the custom protocol will install the application to its default location based on the `library_root` path in the `omniverse.toml` file that you configured earlier as part of the IT Managed Launcher installation process.
Example:
```markdown
start omniverse-launcher://install?path=C:/temp/usd_explorer.zip
```
Example:
```markdown
start omniverse-launcher://install?path=//Mainframe/temp/usd_explorer.zip
```
When the command is run, it will trigger the IT Managed Launcher to open and it will begin the installation process. You should see a screen similar to the one below that shows the progress bar for the application being installed in the upper right of the Launcher window.
Once the installation is complete, the Omniverse application will appear in the **Library** section of the Launcher window and these steps can be repeated for any additional applications you want to make available to your users.
## SCCM
To deploy the IT Managed Launcher executable file to users’ Windows workstations you will need to perform several tasks.
- You’ll need to download and stage the IT Managed Launcher .EXE file to a shared network location inside your firewall that all of the users’ workstations can see and access.
- Next, you’ll create and pre-configure a user’s `omniverse.toml`, `policy.toml`, and `license.toml` files and stage them in the same shared network location.
- After that, you’ll create a .bat file to control the installation process and reference .toml files you’ve set up.
- Finally, you’ll configure another .bat file within the Windows Local Group Policy to execute at user logon to trigger the installation and configuration of the IT Managed Launcher for the user on their local workstation.
As per the prerequisite section of this document, you should have already downloaded the Windows version of the IT Managed Launcher install file from the **Enterprise Web Portal**. If not, please do that first.
### Setting up TOML Files
(Learn more about TOML syntax: https://toml.io/en/)
The first step is to create and stage the three **.toml** files for deployment.
- `omniverse.toml`: Copy the following information into a new text document, replacing the path information with the location you want Omniverse and its data installed on each user’s workstation. Once done, save it to the staging location.
```toml
[paths]
library_root = "C:\\Omniverse\\library" # Path where to install all Omniverse applications
data_root = "C:\\Omniverse\\data" # Folder where Launcher and Omniverse apps store their data files
cache_root = "C:\\Omniverse\\cache" # Folder where Omniverse apps store their cache and temporary files
logs_root = "C:\\Users\\[username]\\.nvidia-omniverse\\logs" # Folder where Launcher and Omniverse apps store their logs
content_root = "C:\\Users\\[username]\\Downloads" # Folder where Launcher saves downloaded content packs
extension_root = "C:\\Users\\[username]\\Documents\\kit\\shared\\exts" # Folder where all Omniverse shared extensions are stored
```
```
confirmed = true # Confirmation that all paths are set correctly, must be set to `true`
```
| Path | Description |
| --- | --- |
| library_root = “C:\Omniverse\library” | Path where to install all Omniverse applications |
| data_root = “C:\Omniverse\data” | Folder where Launcher and Omniverse apps store their data files |
| cache_root = “C:\Omniverse\cache” | Folder where Omniverse apps store their cache and temporary files |
| logs_root = “C:\Users\[username]\.nvidia-omniverse\logs” | Folder where Launcher and Omniverse apps store their logs |
| content_root = “C:\Users\[username]\Downloads” | Folder where Launcher saves downloaded content packs |
| extension_root = “C:\Users\[username]\Documents\kit\shared\exts” | Folder where all Omniverse shared extensions are stored |
| confirmed = true | Confirmation that all paths are set correctly, must be set to `true` |
### Important
Also be aware that all paths on Windows require a double backslash (\) for proper operation.
- `privacy.toml`: Copy the following information into a new text document. This is the configuration file for Omniverse telemetry capture for each user’s workstation. Once done, save it to the staging location.
```toml
[privacy]
performance = true
personalization = true
usage = true
```
### Note
If your Security Policy prohibits the collection of telemetry on a user’s workstation, set all of the values in the file to **false**.
- `license.toml`: This is the licensing configuration file for Omniverse. Within this licensing file, specify the Organization Name Identifier (org-name) you retrieved from the Licensing Portal in the prerequisites section. Once done, save it to the staging location.
```toml
[ovlicense]
org-name = "<insert-your-org-name-here>"
```
Once you’ve saved all three `.toml` files, it’s time to build a .bat file that will be used to help deploy the files to each user’s workstation.
## Deploying Launcher
1) Create a new .bat file (you can name the file as needed, e.g. `deployment-omniverse.bat`). In that batch file, add the following information:
```bat
@echo off
SETLOCAL EnableDelayedExpansion
set CONFIG_PATH=%USERPROFILE%\.nvidia-omniverse\config\
set INSTALL_PATH=%ProgramFiles%\NVIDIA Corporation\NVIDIA Omniverse Launcher\
set SCRIPT_PATH=%~dp0
set REG_QUERY=Reg Query "HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\ddd216ee-cf6c-55b0-9ca8-733b2ef622a0" /v "DisplayName"
:CONFIGURATION
:: Test for existing omniverse.toml config file.
if exist "%CONFIG_PATH%\omniverse.toml" GOTO INSTALLLAUNCHER
:: Copy.toml files to user's configuration.
xcopy /y "%SCRIPT_PATH%\omniverse.toml" "%CONFIG_PATH%"
xcopy /y "%SCRIPT_PATH%\privacy.toml" "%CONFIG_PATH%"
xcopy /y "%SCRIPT_PATH%\license.toml" "%CONFIG_PATH%"
:: Substitute [username] with %USERNAME%.
del "%CONFIG_PATH%\omniverse.txt" 2>NUL
for /f "usebackq tokens=*" %%a in ("%CONFIG_PATH%\omniverse.toml") do (
set LINE=%%a
set LINE=!LINE:[username]=%USERNAME%!
echo !LINE! >> "%CONFIG_PATH%\omniverse.txt"
)
```
```shell
del "%CONFIG_PATH%\omniverse.toml" 2>NUL
ren "%CONFIG_PATH%\omniverse.txt" "omniverse.toml"
:: Set the readonly flag to prevent users from changing the configured paths
attrib +r "%CONFIG_PATH%"\*.toml
::INSTALLLAUNCHER
:: Test if Launcher is already installed.
%REG_QUERY% 1>NUL 2>&1
if %ERRORLEVEL%==0 GOTO STARTLAUNCHER
:: Run the installer and wait until Launcher is installed (silent).
start /WAIT %SCRIPT_PATH%\omniverse-launcher-win-enterprise.exe /S /D="%INSTALL_PATH%"
::STARTLAUNCHER
:: Start the Launcher.
start "" "%INSTALL_PATH%\NVIDIA Omniverse Launcher.exe"
timeout /T 5 1>NUL 2>&1
::END
ENDLOCAL
```
- The .bat script above copies the .toml files and installs Launcher.
- All files must be located in the root directory of the script. (.toml / omniverse-launcher-win-enterprise.exe).
- Install into a public folder, example C:NVIDIA.
**2)** Save this file to the same location as the pre-configured .toml files on the staging hardware.
In order to run the .bat file as part of a deployment strategy, you need to set up a local group policy for your users’ workstations.
**3)** Open the Local Group Policy Editor on the GPO manager machine.
**4)** Double-click to choose **Logon**.
**5)** From the Logon Properties dialog, choose **Add**.
**6)** Then point to the .bat file you created earlier and click **OK**.
The file should appear in the Logon Properties dialog.
**7)** Click OK to close the dialog
**8)** The scripts will run on the remote machines during the next Logon.
## Setting Up Packages
Once the Omniverse IT Managed Launcher is installed and configured, you’re ready to install the Omniverse foundation applications for your users.
As an IT Manager, you now need to download the various Omniverse foundation applications from the Omniverse Enterprise Web Portal. Each application will come in the form of an archived **.zip** file that you can take to a user’s machine and install either manually, or via your internal deployment framework.
**1)** To begin, log into the Omniverse Enterprise Web Portal.
**2)** In the left-hand navigation area, select **Apps**, and from the resulting view, click on the tile of the Omniverse foundation application you want to install.
Available releases are categorized by release channel. A release is classified as **Beta**, **Release**, or **Enterprise**, depending on its maturity and stability.
| Release | Description |
|---------|-------------|
| Beta | Beta builds may or may not be feature complete or fully stable. These are good for testing new Omniverse functionality, but aren’t guaranteed to be ready for production. |
| Release | Release builds (also known as GA or General Availability) are feature complete and stable builds ready for production. |
| Enterprise | Enterprise builds are provided for Enterprise customers and represent supported production versions of Omniverse software. |
**3)** Select a package version in the dropdown list and click **Download**.
**4)** Clicking the download button will prompt you to select the Windows or Linux version of the application to install. Choose the OS version that matches the user’s workstation.
**5)** Once downloaded, the application archive must then be transferred to the user’s machine or hosted on your chosen local network staging hardware so it can be accessed and installed on a user’s workstation.
Once you’ve downloaded the various Omniverse foundation applications, you are ready to proceed to the installation.
# 部署 Omniverse 应用到用户 Windows 工作站
## 步骤概览
1. 下载并准备 Omniverse 应用的 .zip 文件到内部网络共享位置。
2. 创建一个 .bat 文件来控制下载的安装过程。
3. 配置另一个 .bat 文件,通过 Windows 本地组策略在用户登录时触发安装和配置。
## 详细步骤
### 下载和准备
根据本文件的前提条件部分,您应该已经从 **企业网络门户** 下载了每个要部署的 Omniverse 应用的 Windows .zip 文件。如果没有,请先进行下载。
### 创建安装脚本
下一步是创建处理本地用户工作站安装过程的 .bat 文件。
#### 步骤 1
创建一个新的 .bat 文件用于应用安装(您可以根据需要命名文件,例如 deploy_OV<AppName>.bat)。在该批处理文件中,添加以下信息:
```bat
@echo off
SETLOCAL EnableDelayedExpansion
set CONFIG_PATH=%USERPROFILE%\.nvidia-omniverse\config\
set SCRIPT_PATH=%~dp0
:INSTALLAPPS
:: Find library_root from omniverse.toml
for /f "usebackq tokens=*" %%a in ("%CONFIG_PATH%\omniverse.toml") do (
set LINE=%%a
echo !LINE!|find "library_root" 1>NUL 2>&1
if !ERRORLEVEL!==0 (
for /f tokens^=^2^ delims^=^" %%i in ("!LINE!") do set LIBRARY_ROOT_PATH=%%i
set LIBRARY_ROOT_PATH=!LIBRARY_ROOT_PATH:\\=\!
)
)
:: Find .zip files
for /f "tokens=*" %%a in ('dir /B "%SCRIPT_PATH%\*.zip"') do (
set ZIP_FILE=%%a
set ZIP_FILE_SUB=!ZIP_FILE:.windows-x86_64-ent-package.zip=!
:: Check if ZIP_FILE_SUB is a folder in LIBRARY_ROOT_PATH. If not, install.
dir /B "!LIBRARY_ROOT_PATH!"| findstr "!ZIP_FILE_SUB!" 1>NUL 2>&1
if !ERRORLEVEL!==1 (
start omniverse-launcher://install?path="%SCRIPT_PATH%\!ZIP_FILE!"
timeout /T 600 1>NUL 2>&1
)
)
:END
ENDLOCAL
```
您可以串联尽可能多的自定义协议命令来安装所有您想要安装的 Omniverse 应用。
### 注意事项
您也可以选择将此信息添加到用于安装 IT 管理启动器的现有 .bat 文件中。
### 安装要求
- 上述 .bat 脚本从 .zip 文件安装应用。
- 所有文件必须位于脚本的根目录中(例如 “App”.zip)。
- 安装到之前安装启动器的同一目录。
### 配置组策略
#### 步骤 2
将此 .bat 文件保存到暂存硬件。
#### 步骤 3
在 GPO 管理机器上打开本地组策略编辑器。
#### 步骤 4
双击选择登录。
#### 步骤 5
在登录属性对话框中选择添加。
#### 步骤 6
指向您之前创建的 .bat 文件并点击确定。
#### 步骤 7
点击确定关闭对话框。
#### 步骤 8
脚本将在下次登录时在远程机器上运行。 |
intro.md | # Getting Started
## What is Slang
Slang is a shading language backward compatible with HLSL that makes it easier to build and maintain large shader codebases in a modular and extensible fashion, while also maintaining the highest possible performance on modern GPUs and graphics APIs. Slang is based on years of collaboration between researchers at NVIDIA, Carnegie Mellon University, and Stanford.
For better understanding of language usage and features, please refer to the User’s Guide provided by Slang developers.
## What is Slang Node
Slang nodes can be placed in all types of OmniGraph. Slang node, when executed, runs a compute Slang function. Node’s *input*, *output*, and *state* attributes define variables that can be referenced in the Slang code. The code of the node’s function can be edited in the Code editor and is saved in the USDA file as a node’s token attribute.
The current implementation only runs the Slang code single-threaded on the CPU target. Multithreaded and GPU support will be added in future releases.
## When should I use Slang Node
The node allows users to write their own functions executed in OmniGraph. Slang code is compiled once during the stage load or on user request in the Code Editor. The node execution does not bring any additional overhead during the OmniGraph updates.
Detail usage of the Slang node is covered in the tutorial How to use Slang node in OmniGraph.
## Future work
1. Multithreading and GPU target support
2. COM interface support to allow C++ functions callbacks from Slang code
3. Code editor UX improvements |
introduction_index.md | # Omni Asset Validator (Tutorial)
## Introduction
The `Omniverse Asset Validator` is an extensible framework to validate [USD](https://graphics.pixar.com/usd/release/index.html). Initially inspired from [Pixar Compliance Checker](https://graphics.pixar.com/usd/release/toolset.html#usdchecker), it extends upon these ideas and adds more validation rules applicable throughout Omniverse, as well as adding the ability to automatically fix issues.
Currently, there are two main components:
1. [Omni Asset Validator (Core)](../index.html): Core components for Validation engine. Feel free to use this component to implement programmatic functionality or extend Core functionality through its framework.
2. [Omni Asset Validator (UI)](../../../omni.asset_validator.ui/docs/index.html): Convenient UI for Omniverse. Used for daily tasks with Omniverse tools as Create.
The following tutorial will help you to:
1. Run basic operations for Asset Validator, `ValidationEngine`, and `IssueFixer`.
2. Get familiar with existing Rules to diagnose and fix problems.
3. Create your custom Rules.
## Tutorials
### Testing assets
In order to run Asset Validator, we need to enable the extension `Omni asset validator (Core)`. Optionally we can also enable `Omni asset validator (UI)` to perform similar operations using the user interface. Through this tutorial we will use `Script Editor`, enable it under the `Window` menu.
The following tutorial uses the file `BASIC_TUTORIAL_PATH` which is bundled together with `omni.asset_validator.core`. We can see its contents with the following snippet:
```python
import omni.asset_validator.core
from pxr import Usd
stage = Usd.Stage.Open(omni.asset_validator.core.BASIC_TUTORIAL_PATH)
```
```python
print(stage.ExportToString())
```
The contents should be equivalent to:
```usda
#usda 1.0
(
doc="""Generated from Composed Stage of root layer C:\\some\\location\\exts\\omni.asset_validator.core\\omni\\asset_validator\\core\\resources\\tutorial.usda"""
)
def Xform "Hello"
{
def Sphere "World"
{
}
}
```
To run a simple asset validation, with `Script Editor`, execute the following code.
```python
import omni.asset_validator.core
engine = omni.asset_validator.core.ValidationEngine()
print(engine.validate(omni.asset_validator.core.BASIC_TUTORIAL_PATH))
```
> **Note**
> For more information about ValidationEngine together with more examples can be found at the ValidationEngine API.
The above code would produce similar results to.
```text
Results(
asset="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda",
issues=[
Issue(
message="Stage does not specify an upAxis.",
severity=IssueSeverity.FAILURE,
rule=StageMetadataChecker,
at=None,
suggestion=None
),
Issue(
message="Stage does not specify its linear scale in metersPerUnit.",
severity=IssueSeverity.FAILURE,
rule=StageMetadataChecker,
at=None,
suggestion=None
),
Issue(
message="Stage has missing or invalid defaultPrim.",
severity=IssueSeverity.FAILURE,
rule=StageMetadataChecker,
at=None,
suggestion=None
),
Issue(
message="Stage has missing or invalid defaultPrim.",
severity=IssueSeverity.FAILURE,
rule=OmniDefaultPrimChecker,
at=StageId(
identifier="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda"
),
suggestion=Suggestion(
callable=UpdateDefaultPrim,
message="Updates the default prim"
)
)
]
)
```
The main result of validation engine is called an `Issue`. The main task of Asset validation is to detect and fix issues.
An `Issue` has important information on how to achieve both tasks.
- **Detect**. Once an issue has been found it offers a description of the problem (through a human-readable message), its severity, the `Rule` that found the issue and its location (i.e. the `Usd.Prim`).
- **Fix**. If a suggestion is available, it will help to address the `Issue` found. Information on the `Rule` and the location of the issue will be used to address it.
In the following section we will walk you through on how to identify and fix issues.
> **Note**
> For more information see the Issue API.
## Understanding Rules
Omni asset validator (Core) ships with multiple rules, in the previous example we already covered two:
- `StageMetadataChecker`: All stages should declare their `upAxis` and `metersPerUnit`. Stages that can be consumed as referencable assets should furthermore have a valid `defaultPrim` declared, and stages meant for consumer-level packaging should always have upAxis set to `Y`.
- `OmniDefaultPrimChecker`: Omniverse requires a single, active, `Xformable` root prim, also set to the layer’s defaultPrim.
Refer to [Rules](../rules.html) for the rest of rules. In the previous example when calling `ValidationEngine`
we invoked
all rules available.
```
```html
<code class="docutils literal notranslate">
<span class="pre">
ValidationRulesRegistry
</span>
</code>
```
has a registry of all rules to be used by
```html
<code class="docutils literal notranslate">
<span class="pre">
ValidationEngine
</span>
</code>
```
.
```python
import omni.asset_validator.core
for category in omni.asset_validator.core.ValidationRulesRegistry.categories():
for rule in omni.asset_validator.core.ValidationRulesRegistry.rules(category=category):
print(rule.__name__)
```
If we want to have finer control of what we can execute, we can also specify which rules to run, for example:
```python
import omni.asset_validator.core
engine = omni.asset_validator.core.ValidationEngine(initRules=False)
engine.enableRule(omni.asset_validator.core.OmniDefaultPrimChecker)
print(engine.validate(omni.asset_validator.core.BASIC_TUTORIAL_PATH))
```
There are two new elements present here:
- `initRules`: By default set to `true`. if set to `false`, no rules will be automatically loaded.
- `enableRule`: A method of `ValidationEngine` to add rules.
The above would produce the following result:
```python
Results(
asset="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda",
issues=[
Issue(
message="Stage has missing or invalid defaultPrim.",
severity=IssueSeverity.FAILURE,
rule=OmniDefaultPrimChecker,
at=StageId(
identifier="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda"
),
suggestion=Suggestion(
callable=UpdateDefaultPrim,
message="Updates the default prim"
)
)
]
)
```
In this particular case, `OmniDefaultPrimChecker` has implemented a suggestion for this specific issue. The second important class in `Core` we want to cover is `IssueFixer`, the way to invoke it is quite straightforward.
```python
import omni.asset_validator.core
fixer = omni.asset_validator.core.IssueFixer(asset=omni.asset_validator.core.BASIC_TUTORIAL_PATH)
fixer.fix([])
```
`fixer.fix` will receive the list of issues that should be addressed. The list of issues to address can be accessed through `issues` method in `Results` class.
**Note**
For more information about IssueFixer see [IssueFixer API](../api.html#omni.asset_validator.core.IssueFixer).
By combining the previous two examples we can now, detect and fix issues for a specific rule.
```python
import omni.asset_validator.core
# Detect issues
engine = omni.asset_validator.core.ValidationEngine(initRules=False)
engine.enableRule(omni.asset_validator.core.OmniDefaultPrimChecker)
result = engine.validate(omni.asset_validator.core.BASIC_TUTORIAL_PATH)
# Fix issues
fixer = omni.asset_validator.core.IssueFixer(asset=omni.asset_validator.core.BASIC_TUTORIAL_PATH)
```python
import omni.asset_validator.core
from pxr import Usd
stage = Usd.Stage.Open(omni.asset_validator.core.BASIC_TUTORIAL_PATH)
print(stage.ExportToString())
```
We can find the issue reported by `OmniDefaultPrimChecker` is fixed:
```usda
#usda 1.0
(
defaultPrim="Hello"
doc="""Generated from Composed Stage of root layer C:\\some\\location\exts\\omni.asset_validator.core\\omni\\asset_validator\\core\\resources\\tutorial.usda"""
)
def Xform "Hello"
{
def Sphere "World"
{
}
}
```
```python
import omni.asset_validator.core
from pxr import Usd
class MyRule(omni.asset_validator.core.BaseRuleChecker):
def CheckPrim(self, prim: Usd.Prim) -> None:
if prim.GetPath() == "/Hello/World":
self._AddFailedCheck(
message="Goodbye!",
at=prim,
)
engine = omni.asset_validator.core.ValidationEngine(initRules=False)
```
```text
Results(
asset="C:\some\location\exts\omni.asset_validator.core\omni\asset_validator\core\resources\tutorial.usda",
issues=[
]
)
```
```python
from pxr import Usd
class MyRule(omni.asset_validator.core.BaseRuleChecker):
def Callable(self, stage: Usd.Stage, location: Usd.Prim) -> None:
raise NotImplementedError()
def CheckPrim(self, prim: Usd.Prim) -> None:
if prim.GetPath() == "/Hello/World":
self._AddFailedCheck(
message="Goodbye!",
at=prim,
suggestion=omni.asset_validator.core.Suggestion(
message="Avoids saying goodbye!",
callable=self.Callable,
)
)
engine = omni.asset_validator.core.ValidationEngine(initRules=False)
engine.enableRule(MyRule)
result = engine.validate(omni.asset_validator.core.BASIC_TUTORIAL_PATH)
fixer = omni.asset_validator.core.IssueFixer(asset=omni.asset_validator.core.BASIC_TUTORIAL_PATH)
result = fixer.fix(result.issues())
print(result)
```
Notice how the `NotImplementedError` error was not thrown during `fixer.fix`. However, we can access the result of execution by inspecting `result`:
```
[
FixResult(
issue=Issue(
message='Goodbye!',
severity=FAILURE,
rule=<class '__main__.MyRule'>,
at=PrimId(
stage_ref=StageId(identifier='C:\\sources\\asset-validator\\_build\\windows-x86_64\\release\\exts\\omni.asset_validator.core\\omni\\asset_validator\\core\\resources\\tutorial.usda'),
path='/Hello/World'
),
suggestion=Suggestion(callable=Callable, message='Avoids saying goodbye!')
),
status=FAILURE,
exception=NotImplementedError()
)
]
```
Finally, if you decide to run your custom `Rule` with the rest of the rules, it may be useful to register it in `ValidationRulesRegistry`, this can be done using `registerRule`.
```python
import omni.asset_validator.core
from pxr import Usd
@omni.asset_validator.core.registerRule("MyCategory")
class MyRule(omni.asset_validator.core.BaseRuleChecker):
def CheckPrim(self, prim: Usd.Prim) -> None:
pass
for rule in omni.asset_validator.core.ValidationRulesRegistry.rules(category="MyCategory"):
print(rule.__name__)
```
### Custom Rule: Locations
For this section, let us use LAYERS_TUTORIAL_PATH. We proceed like in the previous section:
```python
import omni.asset_validator.core
from pxr import Usd
stage = Usd.Stage.Open(omni.asset_validator.core.LAYERS_TUTORIAL_PATH)
print(stage.ExportToString())
```
The contents should be equivalent to:
```usda
#usda 1.0
(
doc="Generated from Composed Stage of root layer C:\\some\\location\\exts\\omni.asset_validator.core\\omni\\asset_validator\\core\\resources\\tutorial2.usda"
)
def Xform "Hello"
{
def Sphere "World"
{
double3 xformOp:translate = (-250, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate"]
}
}
```
What we are doing is adding an opinion to the prim “/Hello/World”. In the previous section we learned how to create a
```
Rule
```
and issue a
```
Failure
```
.
The data model is similar to the following code snippet:
```python
from pxr import Usd
import omni.asset_validator.core
# We open the stage
stage = Usd.Stage.Open(omni.asset_validator.core.LAYERS_TUTORIAL_PATH)
# We inspect a specific prim
prim = stage.GetPrimAtPath("/Hello/World")
# We create the data model for the issue
def Callable(stage: Usd.Stage, location: Usd.Prim) -> None:
raise NotImplementedError()
issue = omni.asset_validator.core.Issue(
message="Goodbye!",
at=prim,
severity=omni.asset_validator.core.IssueSeverity.FAILURE,
suggestion=omni.asset_validator.core.Suggestion(
message="Avoids saying goodbye!",
callable=Callable
),
)
# Inspect the fixing points for the suggestion
for fix_at in issue.all_fix_sites:
layer_id = fix_at.layer_id
path = fix_at.path
print(layer_id, path)
```
The output of the above snippet should show first the path of layers tutorial (i.e. `LAYERS_TUTORIAL_PATH`) and second the basic tutorial (i.e. `BASIC_TUTORIAL_PATH`).
While this may be correct for above issue, different issues may need to override this information.
Every issue, has associated fixing sites (i.e. property `all_fix_sites`). The fixing sites are all places that contribute opinions to the prim from `strongest` to `weakest` order. When no layer is provided to fix, by default will be the `strongest`. If no indicated (as above) the preferred site will be the `Root` layer.
To change the preferred site to fix, we can add the `at` attribute to `Suggestion`.
```python
from pxr import Usd, Sdf
import omni.asset_validator.core
# We open the stage
stage = Usd.Stage.Open(omni.asset_validator.core.LAYERS_TUTORIAL_PATH)
# We inspect a specific prim
prim = stage.GetPrimAtPath("/Hello/World")
# We create the data model for the issue
def Callable(stage: Usd.Stage, location: Usd.Prim) -> None:
raise NotImplementedError()
```
```python
raise NotImplementedError()
issue = omni.asset_validator.core.Issue(
message="Goodbye!",
at=prim,
severity= omni.asset_validator.core.IssueSeverity.FAILURE,
suggestion=omni.asset_validator.core.Suggestion(
message="Avoids saying goodbye!",
callable=Callable,
at=[Sdf.Layer.FindOrOpen(omni.asset_validator.core.BASIC_TUTORIAL_PATH)]
),
)
# Inspect the fixing points for the suggestion
for fix_at in issue.all_fix_sites:
layer_id = fix_at.layer_id
path = fix_at.path
print(layer_id, path)
```
The output will change the order now, and you should see basic tutorial path
**first** (i.e. `BASIC_TUTORIAL_PATH`).
The previous tutorial should have helped you to:
- Create a custom Rule, generating an error and a suggestion to fix it.
- Run ValidationEngine with a specific rule.
- Run IssueFixer to fix specific issues and review the response.
### Frequently Asked Questions
**Are there any guards to make sure fixes are still relevant / don’t collide?**
In our general practice we have noticed:
- **Fixing an issue may solve another issue**. If a consecutive suggestion may fail to be applied, we just keep the exception in `FixResult` and continue execution. You will then decide the steps to take with `FixResult`.
- **Fixing an issue may generate another issue**. For the second case it is recommended to run `ValidationEngine` again, to discover those cases. Think of it as an iterative process with help of an automated tool.
**Are fixes addressed in the root layer? strongest layer?**
Currently, some Issues would perform the suggestion on the strongest layer, while many on the root layer. We are working into offer flexibility to decide in which layer aim the changes, while also offering a default layer for automated workflows. |
introduction_Overview.md | # omni.syntheticdata
## Introduction
This extension provides low level OmniGraph nodes for preparing synthetic data AOVs and annotator outputs for the higher level Omniverse Replicator extension. End user applications should use the Replicator APIs, rather than using this extension directly.
The extension also includes support for older deprecated Omniverse Synthetic Data APIs. If you are currently using these older APIs, we suggest reviewing the newer Replicator APIs and switching to these.
A preview visualization component is also included - this is accessible from the viewport synthetic data icon when the extension is installed.
### OmniGraph Nodes In This Extension
- Sd Fabric Time Range Execution
- Sd Frame Identifier
- Sd Instance Mapping
- Sd Instance Mapping Ptr
- Sd Linear Array To Texture
- Sd No Op
- Sd On New Frame
- Sd On New Render Product Frame
- Sd Post Comp Render Var Textures
- Sd Post Instance Mapping
- Sd Post Render Var Display Texture
- Sd Post Render Var Host To Disk
- Sd Post Render Var Texture To Buffer
- Sd Post Render Var To Host
- Sd Post Semantic3d Bounding Box Camera Projection
- Sd Post Semantic3d Bounding Box Filter
- Sd Post Semantic Bounding Box
- Sd Post Semantic Filter Segmentation Map
- Sd Render Product Camera
- Sd Render Var Display Texture
- Sd Render Var Ptr
- Sd Render Var To Raw Array
- Sd Semantic Filter
- Sd Semantic Labels Map
- Sd Sim Instance Mapping
- Sd Sim Render Product Camera
- Sd Test Instance Mapping
- Sd Test Print Raw Array
- Sd Test Rational Time Sync Gate
- Sd Test Render Product Camera
- Sd Test Sim Fabric Time Range
- Sd Test Stage Manipulation Scenarii
- Sd Test Stage Synchronization
- Sd Texture To Linear Array
- Sd Time Change Execution
- Sd Update Sw Frame Number |
isaac-sim-command-tool_ext_omni_kit_commands.md | <!-- redirect file --> |
isaac-sim-conventions_reference_conventions.md | # Isaac Sim Conventions
This section provides a reference for the units, representations, and coordinate conventions used within Omniverse Isaac Sim.
## Default Units
| Measurement | Units | Notes |
|-------------|----------|-------|
| Length | Meter | |
| Mass | Kilogram | |
| Time | Seconds | |
| Physics Time-Step | Seconds | Configurable by User. Default is 1/60. |
| Force | Newton | |
| Frequency | Hertz | |
| Linear Drive Stiffness | \(kg/s^2\) | |
| Angular Drive Stiffness | \((kg*m^2)/(s^2*angle)\) | |
| Linear Drive Damping | \(kg/s\) | |
| Angular Drive Damping | \((kg*m^2)/(s*angle)\) | |
| Diagonal of Inertia | \((kg*m^2)\) | |
## Default Rotation Representations
### Quaternions
| API | Representation |
|--------------|----------------|
```
# Isaac Sim Core
## Angles
### API
### Representation
| API | Representation |
|----------------|---------------|
| Isaac Sim Core | Radians |
| USD | Degrees |
| PhysX | Radians |
| Dynamic Control| Radians |
## Matrix Order
### API
### Representation
| API | Representation |
|----------------|---------------|
| Isaac Sim Core | Row Major |
| USD | Row Major |
## World Axes
Omniverse Isaac Sim follows the right-handed coordinate conventions.
| Direction | Axis | Notes |
|-----------|------|-------|
| Up | +Z | |
| Forward | +X | |
## Default Camera Axes
| Direction | Axis | Notes |
|-----------|------|-------|
| Up | +Y | |
| Forward | -Z | |
### Note
**Isaac Sim to ROS Conversion**: To convert from Isaac Sim Camera Coordinates to ROS Camera Coordinates, rotate 180 degrees about the X-Axis.
## Image Frames (Synthetic Data)
| Coordinate | Corner |
|------------|------------|
| (0,0) | Top Left | |
it-managed-installation-overview.md | # IT Managed Launcher Overview
The **IT Managed Launcher** is an enterprise user’s front end to all of the Omniverse applications that their company makes available to them on their local workstation.
Its main use is to allow a company more control over deployment of Omniverse to its users. Some of the features included:
- Support for deployment tools such as PowerShell, Group Policy, SCCM, as well as Linux deployment tools.
- Does not require an Nvidia Account login for the end users.
- Can be used in an a firewalled environment.
- End users cannot download, install, or update Apps.
It is designed to be installed by IT department personnel given many corporate networks have strict security policies in place. The IT Managed Launcher is available for both Windows and Linux operating systems.
This launcher and its interface differ from the standard Omniverse Workstation Launcher in that it is **not** designed to allow an end user to install anything directly on their own workstation or update installed applications themselves. It is therefore missing the top-level _Exchange_ and _Nucleus_ sections of the Workstation Launcher **by design**.
These sections are not present within the IT Managed Launcher as these elements are intended to be installed and configured by the IT Managers and Systems Administrators within your organization.
The other major difference between the IT Managed Launcher and the normal Workstation Launcher is that the IT Managed Launcher does **not** require a developer account login for it to function.
The IT Managed Launcher is a critical component for accessing the Omniverse foundation apps for your organization and users, so as a first step, your initial task is to install this component to your local users’ workstations.
## IT Managed Launcher components
### IT Managed Launcher Installer
This is the main application that will be installed on each users machine. Installers are available for Windows and Linux.
### TOML File
The TOML ml files control the setting for the install. There are three TOML files.
`Omniverse.toml` Used to define all the main path and options for the launcher. file is the primary configuration file for the IT Managed Launcher. Within this configuration file, the following paths are described, and they should match the selections you made in step 1. Be aware that you can set these after the installation to different paths as needed for security policy at any time.
| Path | Description |
|-------------------------------|--------------------------------------------------|
| library_root = “C:\Omniverse\library” | Path where to install all Omniverse applications |
| data_root = “C:\Omniverse\data” | Folder where Launcher and Omniverse apps store their data files |
<section id="config-folder">
<h2>
Config Folder
<a class="headerlink" href="#config-folder" title="Permalink to this headline">
</a>
</h2>
<table>
<tbody>
<tr class="row-even">
<td>
<p>
cache_root = “C:\Omniverse\cache”
</p>
</td>
<td>
<p>
Folder where Omniverse apps store their cache and temporary files
</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p>
logs_root = “C:\Users\[username]\.nvidia-omniverse\logs”
</p>
</td>
<td>
<p>
Folder where Launcher and Omniverse apps store their logs
</p>
</td>
</tr>
<tr class="row-even">
<td>
<p>
content_root = “C:\Users\[username]\Downloads”
</p>
</td>
<td>
<p>
Folder where Launcher saves downloaded content packs
</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p>
extension_root = “C:\Users\[username]\Documents\kit\shared\exts”
</p>
</td>
<td>
<p>
Folder where all Omniverse shared extensions are stored
</p>
</td>
</tr>
<tr class="row-even">
<td>
<p>
confirmed = true
</p>
</td>
<td>
<p>
Confirmation that all paths are set correctly, must be set to
<cite>
true
</cite>
</p>
</td>
</tr>
</tbody>
</table>
<div class="admonition important">
<p class="admonition-title">
Important
</p>
<p>
Also be aware that all paths on Windows require a double backslash (\) for proper operation.
</p>
</div>
<div class="admonition note">
<p class="admonition-title">
Note
</p>
<p>
If a system administrator doesn’t want to allow users to change these paths, the omniverse.toml file can be marked as
<strong>
read-only
</strong>
. Also, if a System Administrator plans to install the IT Managed Launcher to a shared location like Program Files on Windows, they need to specify a shared folder for
<strong>
library_root
</strong>
and
<strong>
logs_root
</strong>
path in omniverse.toml file.
</p>
</div>
<p>
You’re now going to add two additional files to this /config folder in addition to the omniverse.toml file.
</p>
</section>
<section id="auth-toml">
<h3>
Auth.toml
</h3>
</section>
<section id="license-toml">
<h3>
License.toml
</h3>
<p>
File to provide your license details and Customer ID.
</p>
<div class="highlight-toml notranslate">
<div class="highlight">
<pre><span></span><span class="k">[ovlicense]</span><span class="w"></span>
<span class="n">org-name</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">"<organization_id>"</span><span class="w"></span>
</pre>
</div>
</div>
</section>
<section id="privacy-toml">
<h3>
Privacy.toml
</h3>
<p>
file to record consent choices for data collection and capture of crash logs
Within the
<code class="docutils literal notranslate">
<span class="pre">
/config
</span>
<span class="pre">
folder
</span>
</code>
, then create a text file named
<strong>
privacy.toml
</strong>
. This is the configuration file for Omniverse telemetry. The file contains following information:
</p>
<div class="highlight-toml notranslate">
<div class="highlight">
<pre><span></span><span class="k">[privacy]</span><span class="w"></span>
<span class="n">performance</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>
<span class="n">personalization</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>
<span class="n">usage</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>
</pre>
</div>
</div>
<div class="admonition important">
<p class="admonition-title">
Important
</p>
<p>
By opting into telemetry within the
<code class="docutils literal notranslate">
<span class="pre">
privacy.toml
</span>
</code>
, you can help improve the performance & stability of the software. For more details on what data is collected and how it is processed see this
<em>
section
</em>
.
</p>
</div>
</section>
<section id="packages">
<h3>
Packages
</h3>
<p>
Packages are what get deployed to each user. The packages are available here. Applications and Contents Packs are available to download for linux and windows to deploy to users.
</p>
</section> |
it-managed-launcher.md | # Installation Guide
This guide is designed for IT Managers and Systems Administrators who need to install and configure Omniverse Enterprise within a firewalled, air-gapped environment (i.e., limited or no Internet access), or want to prevent users from installing unapproved Omniverse applications.
The instructions and information provided covers the installation and functional use of Omniverse Foundation applications and 3D sample content.
There are four primary steps involved in setting up a user’s workstation in a firewalled environment, and we encourage you to fully read the instructions before proceeding.
1. Downloading, installing, and configuring the **IT Managed Launcher** on a user’s workstation.
2. Downloading and Installing one or more **Omniverse Foundation Applications** on a user’s workstation.
3. Optional download Installation and configuration of Omniverse **Sample 3D Content** which can be stored in one of two locations:
- Users’ workstations local hard disk.
- Stored on a shared Enterprise Nucleus Server that the users’ workstations can access through a local network.
## Planning Your Installation
## Installation on Windows
## Installation on Linux
## Uninstalling Apps (Win & Linux) |
jt-converter_Overview.md | # JT Converter
## Overview
The JT Converter extension enables conversion for JT file formats to USD.
USD Explorer includes the JT Converter extension enabled by default.
## Supported CAD file formats
The following file formats are supported by JT Converter:
- JT Files (`*.jt`)
**Note:**
The file formats *.fbx, *.obj, *.gltf, *.glb, *.lxo, *.md5, *.e57 and *.pts are supported by Asset Converter and also available by default.
**Note:**
If expert tools such as Creo, Revit or Alias are installed, we recommend using the corresponding connectors. These provide more extensive options for conversion.
**Note:**
CAD Assemblies may not work when converting files from Nucleus. When converting assemblies with external references we recommend either working with local files or using Omniverse Drive.
## Converter Options
This section covers options for configuration of conversions of JT file formats to USD.
## Related Extensions
These related extensions make up the JT Converter. This extension provides import tasks to the extensions through their interfaces.
### Core Converter
- JT Core: `omni.kit.converter.jt_core:Overview`
### Services
- CAD Converter Service: `omni.services.convert.cad:Overview`
### Utils
- Converter Common: `omni.kit.converter.common:Overview` |
Kind.md | # Kind module
Summary: The Kind library provides a runtime-extensible taxonomy known as “kinds”. Useful for classifying scenegraph objects.
## Python bindings for libKind
**Classes:**
| Class | Description |
| --- | --- |
| `Registry` | A singleton that holds known kinds and information about them. |
| `Tokens` | |
### KindRegistry Threadsafty
KindRegistry serves performance-critical clients that operate under the stl threading model, and therefore itself follows that model in order to avoid locking during HasKind() and IsA() queries.
To make this robust, KindRegistry exposes no means to mutate the registry. All extensions must be accomplished via plugInfo.json files, which are consumed once during the registry initialization (See Extending the KindRegistry)
**Methods:**
| Method | Description |
| --- | --- |
| `GetAllKinds()` | **classmethod** GetAllKinds() -> list[str] |
| `GetBaseKind(kind)` | **classmethod** GetBaseKind(kind) -> str |
| `HasKind(kind)` | **classmethod** HasKind(kind) -> bool |
## IsA
### classmethod
IsA(derivedKind, baseKind) -> bool
## Attributes:
### expired
True if this object has expired, False otherwise.
## GetAllKinds
### classmethod
GetAllKinds() -> list[str]
Return an unordered vector of all kinds known to the registry.
## GetBaseKind
### classmethod
GetBaseKind(kind) -> str
Return the base kind of the given kind.
If there is no base, the result will be an empty token. Issues a coding error if kind is unknown to the registry.
#### Parameters
- **kind** (str) –
## HasKind
### classmethod
HasKind(kind) -> bool
Test whether kind is known to the registry.
#### Parameters
- **kind** (str) –
## IsA
### classmethod
IsA(derivedKind, baseKind) -> bool
Test whether derivedKind is the same as baseKind or has it as a base kind (either directly or indirectly).
It is not required that derivedKind or baseKind be known to the registry: if they are unknown but equal, IsA will return true; otherwise if either is unknown, we will simply return false.
Therefore this method will not raise any errors.
#### Parameters
- **derivedKind** (str) –
- **baseKind** (str) –
## expired
### property
expired
True if this object has expired, False otherwise.
<dl class="py">
<dt>
<p>
<strong>
Attributes:
</strong>
</p>
<table>
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>
<tbody>
<tr>
<td>
<p>
<code>
assembly
</code>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code>
component
</code>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code>
group
</code>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code>
model
</code>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code>
subcomponent
</code>
</p>
</td>
<td>
<p>
</p>
</td>
</tr>
</tbody>
</table>
<dl class="py attribute">
<dt>
<span>
assembly
</span>
<em>
=
'assembly'
</em>
</dt>
<dd>
</dd>
</dl>
<dl class="py attribute">
<dt>
<span>
component
</span>
<em>
=
'component'
</em>
</dt>
<dd>
</dd>
</dl>
<dl class="py attribute">
<dt>
<span>
group
</span>
<em>
=
'group'
</em>
</dt>
<dd>
</dd>
</dl>
<dl class="py attribute">
<dt>
<span>
model
</span>
<em>
=
'model'
</em>
</dt>
<dd>
</dd>
</dl>
<dl class="py attribute">
<dt>
<span>
subcomponent
</span>
<em>
=
'subcomponent'
</em>
</dt>
<dd>
</dd>
</dl>
</dt>
</dl> |
kit-apps-extensions_kit_sdk_overview.md | # Kit SDK Overview
Omniverse is a developer platform. It provides Nucleus for collaboration and data storage. Connector API provides USD conversion capabilities. The Omniverse developer platform provides the Kit SDK for developing Applications, Extensions, and Services.
This tutorial is focused on creating Applications and Extensions on top of Kit SDK.
## Kit Apps & Extensions
The Kit SDK Extension Architecture allow developers to define Extensions and Applications. An Extension is defined by a `.toml` file and most commonly has a set of directories with Python or C++ code. Extensions can also bundle resources such as images. An Application is a single `.kit` file. These modules can state each other as dependencies to combine small capabilities into a greater whole providing complex solutions.
Throughout this document you will encounter many Extensions and Applications. You will start to think of Extensions as “pieces of capabilities” and of Applications as “the collection of Extensions”.
### Extension
- Defined by an `extension.toml` file
- Contains code (Python or C++) and/or resource files.
- Provides a user interface and/or runtime capability.
### App
- Defined by a `.kit` file.
- Combines dependencies into an end user workflow.
## Extension Architecture
At the foundation of Kit SDK, the Kit Kernel provides the ability to bootstrap Applications and execute code. All capability on top of the Kernel is provided by Extensions. Kit SDK contains hundreds of Extensions providing runtime functionality such as USD, rendering, and physics - and other Extensions providing workflow solutions such as USD Stage inspectors, viewport, and content browsers. By combining the Kit SDK Extensions with one or more custom Extensions, new workflow and service based solutions can be created. The Extension Architecture of Kit has been designed for extreme modularity - enabling rapid development of reusable modules:
- Extensions are lego pieces of functionality.
- One Extension can state any number of other Extensions as dependencies.
- Applications provide a complete solution by combining many Extensions.
- Any Omniverse developer can create more Extensions.
Here’s another way to conceptualize the stack of an Application. At the foundation level of an app we have the Kit Kernel. There are runtime Extensions such as USD, RTX, and PhysX. Also behind the scene, there are framework Extensions that enable interfaces to be created, Extension management, and so on. Finally, we have the Extensions that provide end users with interfaces - such as the Viewport, Content Browser, and Stage inspector.
Applications you create will have the same stack - the only difference is what Extensions the Application makes use of and how they are configured.
We will explore the Extensions available in Kit SDK, how to create Applications, and how to get started with Extension development.
# Getting Started with Python Development
## Introduction
Welcome to the Python development tutorial. In this tutorial, we will cover various aspects of Python programming, from basic syntax to advanced topics like web development and data analysis.
## Setting Up the Developer Environment
Before we dive into coding, let's ensure our development environment is properly set up. This includes installing Python, setting up a code editor, and configuring a terminal or command prompt.
### Installing Python
Python can be installed from the official website. Make sure to download the latest version for your operating system.
### Choosing a Code Editor
A good code editor can significantly improve your coding experience. Some popular choices include Visual Studio Code, PyCharm, and Atom.
### Configuring the Terminal
For running Python scripts and managing packages, a well-configured terminal is essential. On Windows, you can use PowerShell or Command Prompt. On macOS and Linux, the default terminal is usually sufficient.
## Conclusion
Setting up a proper development environment is crucial for efficient coding. Once you have your environment ready, you're all set to start learning Python.
--- |
kit-architecture.md | # Kit Architecture
## Kit Manual and Overview
Omniverse Kit is the SDK for building Omniverse Applications like Omniverse USD Composer and Omniverse USD Presenter. It can also be used to develop your own Omniverse Applications
- [Kit Manual and Overview](http://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/kit_overview.html)
## Kit Architecture
A breakdown of the Kit architecture and infrastructure
- [Architecture](http://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/kit_architecture.html) |
kit-derived-data-cache-populator-service_overview.md | # Kit Derived Data Cache Populator Service
Open a USD stage and perform validation and optionally autofixes using omni.asset_validator. |
kit-execution-orchestration_index.md | # Kit Execution Orchestration
Kit is like a highway without rules. Everyone is welcome to travel on it: sleek sedans, race cars, cyclist, trains, inline skaters, etc. Such a diverse set of travelers can lead to disaster on the road. The `omni.kit.exec.core` extension’s job is to rein in the chaos. This wrangling is done by orchestrating Kit’s execution pipeline such that travelers get to their destination quickly, collisions are avoided, and lane usage is maximized.
`omni.kit.exec.core` uses the [OmniGraph Execution Framework](../../omni.graph.exec/0.9.4/Overview.html#ef-framework) to facilitate execution orchestration. |
kit-extension-registry_index.md | # flow: Omniverse Fluid Dynamics
## FlowUsd :package:
Repository created: 2022-06-24 by jcarius
This is the repository home for building FlowUSD and its USD schema in the same repository.
The `master` branch remains unchanged from the kit-extension template repository to allow for occasional merging.
This README file provides a quick overview. In-depth documentation can be found at:
📖 [FlowUSD Documentation](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/flow-usd)
Teamcity Project
## Building
To build everything run `.\build.bat` or `.\build.bat --rebuild`
To build the FlowUsd kit extensions run `.\buildExtensions.bat`
## Run
`.\_build\windows-x86_64\release\omni.app.flowusd.bat`
## Testing
`repo.bat test`
## Packaging and publishing
### Kit Extension Registry
To publish extension to the extension registry `.\repo.bat publish_exts`.
This will publish all extensions as configured in the repo.toml.
Note that existing versions should not be overridden, so increment the version in the respective `extension.toml` first before publishing.
More fine-grained control/manual publishing is possible with `.\_build\windows-x86_64\release\omni.app.flowusd.bat --publish omni.usd.schema.flow`.
Note that publishing needs to be run both from windows and linux.
The packages in the registry are automatically named with version and platform information, e.g., publishing `omni.flowusd` version `0.3.0` on windows yields `omni.flowusd-0.3.0+wx64.r.cp37`.
To list published packages execute `
```pre
.\_build\windows-x86_64\release\omni.app.flowusd.bat
```
```pre
--list-registry-exts
```
To un-publish (dangerous!) extensions:
```pre
.\_build\windows-x86_64\release\omni.app.flowusd.bat
```
```pre
--unpublish
```
```pre
omni.usd.schema.flow
```
### Packman packaging
Note: This is currently not used
```pre
repo.bat
```
```pre
package
```
```pre
-m
```
```pre
omni.usd.schema.flow
```
,
```pre
repo.bat
```
```pre
package
```
```pre
-m
```
```pre
omni.flowusd
```
This will place the packages in `_build/packages`. Then
```pre
repo.bat
```
```pre
publish
```
will upload them to packman. This allows other kit projects to include flowusd in their target dependencies with
```c++
<dependency name="omni.flowusd" linkPath="../_build/$platform/$config/exts/omni.flowusd">
<package name="omni.flowusd" version="0.1.0" />
</dependency>
```
### Updating
This repo carries a number dependencies with fixed versions. To update them proceed as follows:
- Packman.xml files in `deps`: These should be updated by merging the newest version from kit-template. Thanks to automatic repo mirroring the `master` branch of this repository is synced with the kit-template repo. The commands for updating are hence
```
git checkout flowusd-master
git fetch origin master:master
git pull origin master:master
```
If there are conflicts due to changes to files that have been deleted in `flowusd-master`, e.g., example packages, just accept the deleted version.
- Don’t forget to update the changelog!
### Using a Local Build of Kit SDK
By default packman downloads Kit SDK (from `deps/kit-sdk.packman.xml`). For developing purposes local build of Kit SDK can be used.
To use your local build of Kit SDK, assuming it is located say at `C:/projects/kit`.
Use `repo_source` tool to link:
```pre
repo source link c:/projects/kit/kit
```
Or you can also do it manually: create a file: `deps/kit-sdk.packman.xml.user` containing the following lines:
```xml
<project toolsVersion="5.6">
<dependency name="kit_sdk_${config}" linkPath="../_build/${platform}/${config}/kit">
<source path="c:/projects/kit/kit/_build/$platform/$config" />
</dependency>
</project>
```
To see current source links:
```pre
repo source list
```
To remove source link:
```pre
repo source unlink kit-sdk
```
To remove all source links:
```pre
repo source clear
```
### Using a Local Build of another Extension
Other extensions can often come from the registry to be downloaded by kit at run-time or build-time (e.g.
```
`omni.app.my_app.kit`
```
example). Developers often want to use a local clone of their repo to develop across multiple repos simultaneously.
To do that additional extension search path needs to be passed into kit pointing to the local repo. There are many ways to do it. Recommended is using
```
`deps/user.toml`
```
. You can use that file to override any setting.
Create
```
`deps/user.toml`
```
file in this repo with the search to path to your repo added to
```
`app/exts/folders`
```
setting, e.g.:
```toml
[app.exts]
folders."++" = ["c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts"]
```
`repo source link [repo_path]` - If repo produces kit extensions add them to
```
`deps/user.toml`
```
file.
`repo source link [ext_path]` - If the path is a kit extension or folder with kit extensions add to
```
`deps/user.toml`
```
file.
Other options:
- Pass CLI arg to any app like this:
```
`--ext-folder c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts`
```
.
- Use *Extension Manager UI (Gear button)*
- Use other
```
`user.toml`
```
(or other) configuration files, refer to Kit Documentation: Configuration.
You can always find out where an extension is coming from in *Extension Manager* by selecting an extension and hovering over the open button.
You can also find it in the log, by looking either for
```
`registered`
```
message for each extension or
```
`About to startup:`
```
when it starts.
### Other Useful Links
- See Kit Manual
- See Kit Developer Documentation Index
- See Anton’s Video Tutorials for Anton’s videos about the build systems. |
kit-programming-manual_index.md | # Kit Programming Manual
## Contents
- [Bundled Extensions](source/extensions/index.html)
- [carb.graphics_optional](source/extensions/carb.graphics_optional-internal/docs/index.html)
- [omni.activity.freeze_monitor](source/extensions/omni.activity.freeze_monitor/docs/index.html)
- [omni.activity.usd_resolver](source/extensions/omni.activity.usd_resolver/docs/index.html)
- [omni.appwindow](source/extensions/omni.appwindow/docs/index.html)
- [omni.client](source/extensions/omni.client/docs/index.html)
- [omni.fabric.fabric_inspector](source/extensions/omni.fabric.fabric_inspector/docs/index.html)
- [omni.hydra.engine.stats](source/extensions/omni.hydra.engine.stats/docs/index.html)
- [omni.inspect](source/extensions/omni.inspect/docs/index.html)
- [omni.kit.actions.core](source/extensions/omni.kit.actions.core/docs/index.html)
- [omni.kit.actions.window](source/extensions/omni.kit.actions.window/docs/index.html)
- [omni.kit.app_snippets](source/extensions/omni.kit.app_snippets/docs/index.html)
- [omni.kit.audio.test.usd](source/extensions/omni.kit.audio.test.usd/docs/index.html)
- [omni.kit.clipboard](source/extensions/omni.kit.clipboard/docs/index.html)
- [omni.kit.compatibility_checker](source/extensions/omni.kit.compatibility_checker/docs/index.html)
- [omni.kit.context_menu](source/extensions/omni.kit.context_menu/docs/index.html)
- [omni.kit.debug.python](source/extensions/omni.kit.debug.python/docs/index.html)
- [omni.kit.exec.debug](source/extensions/omni.kit.exec.debug/docs/index.html)
- [omni.kit.extpath.git](source/extensions/omni.kit.extpath.git/docs/index.html)
- [omni.kit.helper.file_utils](source/extensions/omni.kit.helper.file_utils/docs/index.html)
- [omni.kit.hotkeys.core](source/extensions/omni.kit.hotkeys.core/docs/index.html)
- [omni.kit.hotkeys.window](source/extensions/omni.kit.hotkeys.window/docs/index.html)
- [omni.kit.mainwindow](source/extensions/omni.kit.mainwindow/docs/index.html)
- [omni.kit.manipulator.selector](source/extensions/omni.kit.manipulator.selector/docs/index.html)
- [omni.kit.material.library](source/extensions/omni.kit.material.library/docs/index.html)
- [omni.kit.menu.aov](source/extensions/omni.kit.menu.aov/docs/index.html)
- [omni.kit.notification_manager](source/extensions/omni.kit.notification_manager/docs/index.html)
- omni.kit.notification_manager: Notification Manager Extension
- omni.kit.property.render
- omni.kit.property.usd_clipboard_test: USD Property Clipboard Test Extension
- omni.kit.renderer.capture
- omni.kit.renderer.core
- omni.kit.renderer.cuda_interop
- omni.kit.renderer.imgui
- omni.kit.scene_view.opengl
- omni.kit.stage.mdl_converter
- omni.kit.stage_templates
- omni.kit.test
- omni.kit.test_app_compat
- omni.kit.test_app_full_nonrtx
- omni.kit.test_helpers_gfx
- omni.kit.test_suite.browser
- omni.kit.test_suite.helpers
- omni.kit.test_suite.layer_window
- omni.kit.test_suite.layout
- omni.kit.test_suite.menu
- omni.kit.test_suite.stage_window
- omni.kit.test_suite.viewport
- omni.kit.ui_test
- omni.kit.usd.layers
- omni.kit.viewport.actions
- omni.kit.viewport.scene_camera_model
- omni.kit.viewport_widgets_manager
- omni.kit.welcome.about
- omni.kit.welcome.extensions
- omni.kit.welcome.learn
- omni.kit.welcome.open
- omni.kit.welcome.whats_new
- omni.kit.welcome.window
- omni.kit.widget.browser_bar
- omni.kit.widget.filebrowser
- omni.kit.widget.filter
- omni.kit.widget.nucleus_connector
- omni.kit.widget.nucleus_info
- omni.kit.widget.opengl
- omni.kit.widget.options_menu
- omni.kit.widget.path_field
- omni.kit.widget.search_delegate
- omni.kit.widget.searchable_combobox
- omni.kit.widget.text_editor
- omni.kit.widget.toolbar
- omni.kit.window.content_browser
- omni.kit.window.content_browser_registry
- omni.kit.window.drop_support
- omni.kit.window.file
- omni.kit.window.file_exporter
- omni.kit.window.file_importer
- omni.kit.window.filepicker
- omni.kit.debug.windows module
- omni.kit.window.popup_dialog
- omni.kit.window.preferences
- omni.kit.window.property: Property Window Extension
- omni.mdl.neuraylib
- omni.mdl.pymdlsdk
- omni.rtx.ovtextureconverter
- omni.timeline
- omni.ui_query
- omni.usd module
- usdrt.scenegraph: USDRT Scenegraph API for Kit
# Indices and tables
- Index
- Module Index
- Search Page |
kit-template-omniverse-kit-extension-app-template_index.md | # kit-template: Omniverse Kit Extension & App Template
## Kit Extensions & Apps Example :package:
This repo is a gold standard for building Kit extensions and applications.
The idea is that you fork it, trim down parts you don’t need and use it to develop your extensions and applications. Which then can be packaged, shared, reused.
This README file provides a quick overview. In-depth documentation can be found at:
📖 omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-template
Teamcity Project
## Extension Types
- **python**
- `__init__.py + python code`
- **cpp**
- `omni.ext-example_cpp_ext.plugin.dll`
- **mixed**
- `__init__.py + python code`
- `example.mixed_ext.python`
- `example.mixed_ext.plugin.dll`
Kit --> A1
Kit --> A2
Kit --> A3
## Getting Started
1. build:
```
build.bat -r
```
2. run:
```
_build\windows-x86_64\release\omni.app.new_exts_demo_mini.bat
```
3. notice enabled extensions in “Extension Manager Window” of Kit. One of them brought its own test in “Test Runner” window.
To run tests:
```
repo.bat test
```
To run from python:
```
_build\windows-x86_64\release\example.pythonapp.bat
```
## Using a Local Build of Kit SDK
By default packman downloads Kit SDK (from `deps/kit-sdk.packman.xml`). For developing purposes local build of Kit SDK can be used.
To use your local build of Kit SDK, assuming it is located say at `C:/projects/kit`.
Use `repo_source` tool to link:
```
repo source link kit-sdk c:/projects/kit/kit
```
Or use GUI mode to do source linking:
```
```
</p>
> <div>
> <p>
> ```
> repo
> source
> gui
> ```
> </p>
> </div>
> </blockquote>
<p>
Or you can also do it manually: create a file:
```
deps/kit-sdk.packman.xml.user
```
containing the following lines:
</p>
<div class="highlight-xml notranslate">
<div class="highlight">
<pre><span></span><span class="nt"><project</span> <span class="na">toolsVersion=</span><span class="s">"5.6"</span><span class="nt">></span>
<span class="nt"><dependency</span> <span class="na">name=</span><span class="s">"kit_sdk_${config}"</span> <span class="na">linkPath=</span><span class="s">"../_build/${platform}/${config}/kit"</span><span class="nt">></span>
<span class="nt"><source</span> <span class="na">path=</span><span class="s">"c:/projects/kit/kit/_build/$platform/$config"</span> <span class="nt">/></span>
<span class="nt"></dependency></span>
<span class="nt"></project></span>
</pre>
</div>
</div>
<p>
To see current source links:
</p>
> <div>
> <p>
> ```
> repo
> source
> list
> ```
> </p>
> </div>
> </blockquote>
<p>
To remove source link:
</p>
> <div>
> <p>
> ```
> repo
> source
> unlink
> kit-sdk
> ```
> </p>
> </div>
> </blockquote>
<p>
To remove all source links:
</p>
> <div>
> <p>
> ```
> repo
> source
> clear
> ```
> </p>
> </div>
> </blockquote>
</section>
<section id="using-a-local-build-of-another-extension">
<h3>
Using a Local Build of another Extension
</h3>
<p>
Other extensions can often come from the registry to be downloaded by kit at run-time or build-time (e.g.
```
omni.app.my_app.kit
```
example). Developers often want to use a local clone of their repo to develop across multiple repos simultaneously.
</p>
<p>
To do that additional extension search path needs to be passed into kit pointing to the local repo. There are many ways to do it. Recommended is using
```
deps/user.toml
```
. You can use that file to override any setting.
</p>
<p>
Create
```
deps/user.toml
```
file in this repo with the search to path to your repo added to
```
app/exts/folders
```
setting, e.g.:
</p>
<div class="highlight-toml notranslate">
<div class="highlight">
<pre><span></span><span class="k">[app.exts]</span><span class="w"></span>
<span class="n">folders</span><span class="p">.</span><span class="s">"++"</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="s">"c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts"</span><span class="p">]</span><span class="w"></span>
</pre>
</div>
</div>
<p>
Other options:
</p>
<ul>
<li>
<p>
Pass CLI arg to any app like this:
```
--ext-folder
c:/projects/extensions/kit-converters/_build/windows-x86_64/release/exts
```
.
</p>
</li>
<li>
<p>
Use
<em>
Extension Manager UI (Gear button)
</em>
</p>
</li>
<li>
<p>
Use other
```
user.toml
```
files, refer to
Kit Documentation: Configuration.
</p>
</li>
</ul>
<p>
You can always find out where extension is coming from in
<em>
Extension Manager
</em>
by selecting an extension and hovering over open button or in the log (search for e.g.
```
[ext:
omni.kit.tool.asset_importer
```
).
</p>
</section>
<section id="other-useful-links">
<h3>
Other Useful Links
</h3>
<ul>
<li>
<p>
See
Kit Manual
</p>
</li>
<li>
<p>
See
Kit Developer Documentation Index
</p>
</li>
<li>
<p>
See
Anton’s Video Tutorials
for Anton’s videos about the build systems.
</p>
</li>
</ul>
</section>
</section> |
kit-usd-asset-validator-service_overview.md | # Kit USD Asset Validator Service
Open a USD stage and perform validation and optionally autofixes using omni.asset_validator. |
kit-usd-service-omni-services-usd-base_OVERVIEW.md | # Kit USD service [omni.services.usd.base]
The base for USD services. Not intended to be used directly.
Provides:
- Base Class for USD Processing Services
- Multi Processing Queue Processor (to use with the service). Overwrite the `process_task` method in your subclass.
- omni.client Helpers to help services to interact with resources served from omni.client |
kit_architecture.md | # Architecture
## Extensions
An Extension is a uniquely named and versioned package loaded at runtime. It can have any or all of the following properties:
1. Contain python code.
2. Contain shared libraries and/or Carbonite plugins.
3. Provide a C++ API.
4. Provide a python API.
5. Depend on other extensions.
6. Be reloadable (can be unloaded, changed and loaded again at runtime).
It is the basic building block of Kit-based Applications like Create. More info in the [Extensions](extensions_advanced.html) part of the guide.
## Kit Kernel (`kit.exe` / `IApp`)
Is a minimal core required to run an extension. It is an entry point for any Kit-based Application. It includes extension manager and basic interface. It is the core which holds everything together.
## omni.kit.app (`omni::kit::IApp`)
omni.kit.app is the basic interface that can be used by any extension, and provides a minimal set of Carbonite plugins to load and set up extensions. It is the main front part of Kit Kernel.
C++: `omni::kit::IApp`
python: `omni.kit.app`
It contains:
- Carbonite framework startup
- Extension manager
- Event system
- Update loop
- Settings
- Python context / runtime (edited)
It can run from either a Kit executable (`kit.exe` / `kit`) or from python.
## Bundled Extensions
The Kit SDK comes with a lot of included extensions. Even more extensions are developed outside of Kit SDK and delivered using Extension Registry.
> **Note**
> Try `kit.exe --list-exts`
# Different Modes Example
## CLI utility
Note
----
Arrows are extension dependencies.
1. User writes an extension `user.tool`, which depends only on `omni.kit.usd` and `omni.kit.app`.
2. User runs Kit `kit.exe --enable user.tool`.
Notice that only one extension is specified. `omni.kit.app` will automatically figure out which extensions are required by resolving dependencies and will load and start them up in the correct order.
`user.tool` can for instance parse command-line args, do some processing and then exit.
## GUI CLI utility
The dependency on the UI unrolls the whole tree of required extensions. |
kit_core_iapp_interface.md | # Omniverse Kit Core IApp interface
## Loop runners
Loop runner is something that drives the application loop, more specifically - pushes update events into corresponding update event streams and pumps the event streams, thus allowing the modular bits and pieces to tick.
In the simplest scenario, the loop runner is a piece of logic that ensures that core event streams are being pumped periodically. Pseudocode of the simplest loop runner:
```cpp
void update()
{
preUpdateEventStream->push(...);
preUpdateEventStream->pump();
updateEventStream->push(...);
updateEventStream->pump();
postUpdateEventStream->push(...);
postUpdateEventStream->pump();
messageBus->pump();
}
```
This is the most straightforward way to drive the Kit app, and it is possible to implement a custom version of `IRunLoopRunner` and provide it for the app to use. The default loop runner is close to the straightforward implementation outlined in the pseudocode with the small additions of rate limiter logic and other minor pieces of maintenance logic.
## Extension manager
Extension manager controls the extensions execution flow, maintains the extension registry, and does other related things. Extensions subsystem will be detailed separately, as this is the main entry point for all the modular pieces that make up the Kit app. The extension manager interface can be accessed via the Kit Core app interface.
## Scripting
The Kit Core app sets up Python scripting environment required to support Python extensions and execute custom Python scripts and code snippets. `IAppScripting` provides a simple interface to this scripting environment, which can be used to execute files and strings, as well as manage script search folders, and subscribe to the event stream that will broadcast all the scripting events (such as script command events, script output events and script error events, all bucketed into corresponding event types).
# General message bus
General message bus is a simple yet powerful concept. This is simply an event stream, which is pumped once a frame after all updates, and anybody can use the bus to send and listen to events. This is useful in cases where event stream ownership is inconvenient, or when app-wide events are established (for example, displaying a popup, or things like that) - which can be used by many consumers across all the extensions. According to the event stream guidelines, it is recommended to derive an event type from a string hash. Simple example of message bus usage:
```
```python
import carb.events
import omni.kit.app
BUS_EVENT_TYPE = carb.events.type_from_string("my_ext.SOME_EVENT")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
subscription = message_bus.create_subscription_to_pop_by_type(BUS_EVENT_TYPE, on_change)
# Store subscription somewhere so it doesn't get deleted immediately
subs.append(subscription)
```
# Shutdown sequence
The application receives shutdown requests via the post quit queries. Queries will be recorded and the app will proceed as usual, until the shutdown query will be processed at a defined place in the update logic.
Prior to the real shutdown initiation, the post query event will be injected into the shutdown event stream. Consumers subscribed to the event stream will have a chance to request a shutdown request cancellation. If it will be requested, the shutdown will not happen. This is needed for example to show the dialog popups confirming exit when there is unsaved work pending. If the shutdown wasn’t cancelled - another event will be injected into the shutdown event stream, this time telling it that the real shutdown is about to start.
However, it is possible to post an uncancellable quit request - as an emergency measure in case the application needs to be shut down without interruptions.
# Hang detector
The app core also incorporates a simple hang detector, which is designed to receive periodic nudges, and if there are no nudges for some defined amount of time - it will notify the user that a hang is detected and can crash the application if user chooses. This is helpful because crashes generates crash dumps, allowing developers understand what happened, and what the callstack was at the time of this hang. Things like the timeout, if it is enabled - and other things - can be tweaked via the settings. |
kit_sdk_overview.md | # Kit SDK Overview
Omniverse is a developer platform. It provides Nucleus for collaboration and data storage. Connector API provides USD conversion capabilities. The Omniverse developer platform provides the Kit SDK for developing Applications, Extensions, and Services.
This tutorial is focused on creating Applications and Extensions on top of Kit SDK.
## Kit Apps & Extensions
The Kit SDK Extension Architecture allow developers to define Extensions and Applications. An Extension is defined by a `.toml` file and most commonly has a set of directories with Python or C++ code. Extensions can also bundle resources such as images. An Application is a single `.kit` file. These modules can state each other as dependencies to combine small capabilities into a greater whole providing complex solutions.
Throughout this document you will encounter many Extensions and Applications. You will start to think of Extensions as “pieces of capabilities” and of Applications as “the collection of Extensions”.
### Extension
- Defined by an `extension.toml` file
- Contains code (Python or C++) and/or resource files.
- Provides a user interface and/or runtime capability.
### App
- Defined by a `.kit` file.
- Combines dependencies into an end user workflow.
## Extension Architecture
At the foundation of Kit SDK, the Kit Kernel provides the ability to bootstrap Applications and execute code. All capability on top of the Kernel is provided by Extensions. Kit SDK contains hundreds of Extensions providing runtime functionality such as USD, rendering, and physics - and other Extensions providing workflow solutions such as USD Stage inspectors, viewport, and content browsers. By combining the Kit SDK Extensions with one or more custom Extensions, new workflow and service based solutions can be created. The Extension Architecture of Kit has been designed for extreme modularity - enabling rapid development of reusable modules:
- Extensions are lego pieces of functionality.
- One Extension can state any number of other Extensions as dependencies.
- Applications provide a complete solution by combining many Extensions.
- Any Omniverse developer can create more Extensions.
Here’s another way to conceptualize the stack of an Application. At the foundation level of an app we have the Kit Kernel. There are runtime Extensions such as USD, RTX, and PhysX. Also behind the scene, there are framework Extensions that enable interfaces to be created, Extension management, and so on. Finally, we have the Extensions that provide end users with interfaces - such as the Viewport, Content Browser, and Stage inspector.
Applications you create will have the same stack - the only difference is what Extensions the Application makes use of and how they are configured.
We will explore the Extensions available in Kit SDK, how to create Applications, and how to get started with Extension development.
# Getting Started with Flask
## Introduction
Flask is a lightweight and flexible Python web framework that allows you to build web applications with ease. It's designed to make getting started quick and easy, with the ability to scale up to complex applications.
## Installation
To install Flask, you need to have Python installed on your system. You can download Python from the official website: [Python Downloads](https://www.python.org/downloads/).
After installing Python, you can install Flask using pip:
```bash
pip install Flask
```
## Getting Started
In this tutorial, we will cover the basics of Flask, including how to set up a simple web application.
### Setting Up the Developer Environment
In this tutorial, let's get the developer environment setup. |
known-issues.md | # Known issues
## CentOS and Red Hat Enterprise Linux
There is a known issue using CentOS and Red Hat Enterprise Linux using Omniverse Launcher. Include the `--no-sandbox` flag when launching from the terminal.
## Launcher (General)
- Internet Access is required to use the Workstation Launcher (Internet Access is not required when using the IT Managed Launcher.)
- Occasional graphical artifacts and errors in Launcher UI for certain driver OS combinations
- Some Connectors may be installed without the associated Application on Linux systems
- Launcher may show errors after downloading content on Linux systems |
launcher-package_publish_app.md | # Publish App
## Important
For end users of your custom App or Extension, users must accept the NVIDIA Omniverse License Agreement.
## Fat Package
1. Extract the package.
2. Run the appropriate `.bat` / `.sh` file for the app in the root directory of the extracted package.
## Thin Package
1. Extract the package.
2. Run `pull_kit_sdk.bat` / `pull_kit_sdk.sh` in the root directory of the extracted package (requires Internet access). **This only has to be done once** - not every time a user wants to start the app.
3. Run the optional Application warmup script `[app name].warmup.bat` / `[app name].warmup.sh` if it was created.
4. Run the appropriate `.bat` / `.sh` file for the app in the root directory of the extracted package.
## Launcher Package
Launcher packages can be installed via the Omniverse Launcher. The archive should NOT be unzipped prior to installation.
1. Make sure an Omniverse launcher is installed.
2. Open up a shell and execute the following (with the appropriate absolute filepath for the zip file):
- **Windows**: `start omniverse-launcher://install?path="C:\my_company.usd_explorer.zip"` [command cheat-sheet](commands.html#omniverse-launcher-installation)
- **Linux**: `xdg-open omniverse-launcher://install?path="/home/my_username/my_company.usd_explorer.zip"`
- **Installation Process:**
- The Launcher initiates the installation process by downloading the required files.
- A command cheat-sheet is available [command cheat-sheet](#id4).
- The Launcher shows an installation progress bar.
- Once installation is complete, the Application is listed in the `Library` tab’s `Apps` section.
- **Note:**
- **Note**
- Reference: IT Managed Launcher (installation instructions applies also to Workstation Launcher) |
Layout.md | # Layouts & Hooks
## Hooks
Hooks – This is low level function that modifies the menu dictionary directly. Its recommend to use Layout method below
- For an example of this in action see omni.example.menu_hook
## Layout
Layout – This allows the menus to be moved/removed and renamed
- This is meant for apps to change how menus are presented
## Example layout
```c++
from omni.kit.menu.utils import MenuLayout
self._menu_layout = [
MenuLayout.Menu("Window", [
MenuLayout.Item("Viewport", source="Window/Viewport/Viewport 1"),
MenuLayout.Item("Playlist", remove=True),
MenuLayout.Item("Layout", remove=True),
MenuLayout.Sort(exclude_items=["Extensions"], sort_submenus=True),
])
]
omni.kit.menu.utils.add_layout(self._menu_layout)
```
What does this do?
- Menu item “Window” menu is changed;
- Menu item “Window/Viewport/Viewport 1” is moved to “Window/Viewport”
- Menu item “Window/Playlist” is removed
- Menu item “Window/Layout” is removed
- Menu item “Window” menu is then alphabetically sorted except “Extensions” which is not moved
## Another Example Layout
```c++
from omni.kit.menu.utils import MenuLayout
self._menu_file_layout = [
MenuLayout.Menu(
"File",
[
[
MenuLayout.Menu(
"File",
[
MenuLayout.Item("New"),
MenuLayout.Item("New From Stage Template"),
MenuLayout.Item("Open"),
MenuLayout.Item("Open Recent"),
MenuLayout.Seperator(),
MenuLayout.Item("Re-open with New Edit Layer"),
MenuLayout.Seperator(),
MenuLayout.Item("Share"),
MenuLayout.Seperator(),
MenuLayout.Item("Save"),
MenuLayout.Item("Save As..."),
MenuLayout.Item("Save With Options"),
MenuLayout.Item("Save Selected"),
MenuLayout.Item("Save Flattened As...", remove=True),
MenuLayout.Seperator(),
MenuLayout.Item("Collect As..."),
MenuLayout.Item("Export"),
MenuLayout.Seperator(),
MenuLayout.Item("Import"),
MenuLayout.Item("Add Reference"),
MenuLayout.Item("Add Payload"),
MenuLayout.Seperator(),
MenuLayout.Item("Exit"),
]
)
]
omni.kit.menu.utils.add_layout(self._menu_file_layout)
```
What does this do?
- Menu item “File” menu is changed;
- Menu is now in order listed above
- Menu item “Save Flattened As” is removed
NOTES:
- Any other File menu items not covered in list, like “Export” will appear after layout list
- You can include items that get added only when specific extension is enabled, and missing items will be ignored
- You cannot add menu items, this will have to be done 1st by omni.kit.menu.utils.add_menu_items
# omni.app.setup
With omni.app.setup, user could define menu layout in .kit file to do similar as menu layout in omni.kit.menu.utils.
```python
layout_menu = [
MenuLayout.Menu(
"Layout",
[
MenuLayout.Item("Default", source="Reset Layout"),
MenuLayout.Item("Viewport Only"),
MenuLayout.Seperator(),
MenuLayout.Item("Save Layout", source="Window/Layout/Save Layout..."),
MenuLayout.Item("Load Layout", source="Window/Layout/Load Layout..."),
MenuLayout.Seperator(),
MenuLayout.Seperator(),
MenuLayout.SubMenu(
"Utilities",
[
MenuLayout.Group("Viewport", source="Window/Viewport"),
]
),
]
)
]
[
MenuLayout.Menu("Window",
[
MenuLayout.SubMenu("Layout", [
MenuLayout.Item("Quick Save", remove=True),
MenuLayout.Item("Quick Load", remove=True),
]),
MenuLayout.Sort(exclude_items=["Extensions"], sort_submenus=True),
]
)
]
This could be replaced by settings in .kit file:
[settings.exts."omni.app.setup".menu_layout.Layout]
items = [
"Default=Reset Layout",
"Viewport Only",
"",
"Save Layout=Window/Layout/Save Layout...",
"Load Layout=Window/Layout/Load Layout...",
"",
"Utilities",
]
Utilities.type = "SubMenu"
Utilities.items = ["Viewport=Window/Viewport"]
Utilities.Viewport.type = "Group"
[settings.exts."omni.app.setup".menu_layout.Window]
items = ["Layout", "sort"]
Layout.type = "SubMenu"
Layout.items = ["-Quick Save", "-Quick Load"]
sort.type = "Sort"
sort.exclude_items = ["Extensions"]
sort.sort_submenus = true |
layout_Overview.md | # Overview
## Introduction
Stage window is the frontend UI that presents the hierarchy of the stage in the default `omni.usd.UsdContext`. And it dynamically tracks the changes to the stage and updates the hierarchy in an efficient way. User can also adjust the hierarchy of the stage through the UX. Stage window is built on top of the core widget `omni.kit.widget.stage` with customized settings.
## Layout
Following is an image of the stage window, which presents the default layout with 3 default columns: name, visibility, and type.
For each prim in the stage, it’s presented as a row in the window with several columns, and the hierarchy of the stage is presented as a collapsible tree. The columns are customizable except the default name column through the settings button. Developers can implement new column delegate to add a new column for each row also. You can refer to `omni.kit.widget.stage` for reference. |
LazyLoading.md | # Lazy Loading Extensions
This extension adds support for lazy loading extensions on demand.
Typically extensions implement a window that is opened using the menu. Until the menu is clicked extension is not required. A user doesn’t have to wait for the extension to load as part of app startup.
Extensions can specify `[[trigger]]` sections in `extension.toml`:
```toml
[[trigger]]
menu.name = "Windows/My Window" # menu path
menu.window = "MyWindow" # window name
menu.priority = 100 # menu priority
```
`omni.app.setup` finds all extensions with `[[trigger]]` section and adds a menu entry to the menu specified in `menu.name`. When the menu is clicked the extension is loaded and the window is opened using `ui.Workspace.show_window` API.
Also this extension could setup include list and exclude list for “lazy” menus.
```toml
[settings.exts."omni.app.setup".lazy_menu]
include_list = []
exclude_list = []
```
A “lazy” menu path will not be added if:
- white list is not empty and menu path NOT in white list
- black list is not empty and menu path IN black list |
Learn.md | # Welcome screen: LEARN
Show user manual of this application.
<img alt="" src="_images/Learn.png"/>
- **VIEW ON THE WEB** to launch default web browser and look at the documentation there. |
line.md | # Lines and Curves
## Common Style of Lines and Curves
Here is a list of common styles you can customize on all the Lines and Curves:
> color (color): the color of the line or curve
> border_width (float): the thickness of the line or curve
## Line
Line is the simplest shape that represents a straight line. It has two points, color and thickness. You can use Line to draw line shapes. Line doesn’t have any other style besides the common styles for Lines and Curves.
Here are some of the properties you can customize on Line:
> alignment (enum): the Alignment defines where the line is in parent defined space. It is always scaled to fit.
Here is a list of the supported Alignment value for the line:
```python
from omni.ui import color as cl
style = {
"Rectangle::table": {"background_color": cl.transparent, "border_color": cl(0.8), "border_width": 0.25},
"Line::demo": {"color": cl("#007777"), "border_width": 3},
"ScrollingFrame": {"background_color": cl.transparent},
}
alignments = {
"ui.Alignment.LEFT": ui.Alignment.LEFT,
"ui.Alignment.RIGHT": ui.Alignment.RIGHT,
"ui.Alignment.H_CENTER": ui.Alignment.H_CENTER,
"ui.Alignment.TOP": ui.Alignment.TOP,
"ui.Alignment.BOTTOM": ui.Alignment.BOTTOM,
"ui.Alignment.V_CENTER": ui.Alignment.V_CENTER,
}
with ui.ScrollingFrame(
height=100,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style=style,
):
with ui.HStack(height=100):
for key, value in alignments.items():
with ui.ZStack():
```
```python
from omni.ui import color as cl
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": 10}}, spacing=10):
ui.Line(name="demo", alignment=value)
ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER)
```
By default, the line is scaled to fit.
Users can define the color and border_width to make customized lines.
```python
from omni.ui import color as cl
style = {"Line::default": {"color": cl.red, "border_width": 1}}
with ui.Frame(height=50, style=style):
ui.Line(name="default")
```
```python
from omni.ui import color as cl
with ui.Frame(height=50):
with ui.ZStack(width=200):
ui.Rectangle(style={"background_color": cl(0.4)})
ui.Line(alignment=ui.Alignment.H_CENTER, style={"border_width":5, "color": cl("#880088")})
```
## FreeLine
FreeLine is a line whose length will be determined by other widgets. The supported style list is the same as Line.
Here is an example of a FreeLine with style, driven by two draggable circles. Notice the control widgets are not the start and end points of the line. By default, the alignment of the line is `ui.Alighment.V_CENTER`, and the line direction won’t be changed by the control widgets.
```python
from omni.ui import color as cl
with ui.Frame(height=200):
with ui.ZStack():
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Circle(width=10, height=10)
with ui.Placer(draggable=True, offset_x=150, offset_y=200):
control2 = ui.Circle(width=10, height=10)
# The rectangle that fits to the control points
ui.FreeLine(control1, control2, style={"color":cl.yellow})
```
## BezierCurve
BezierCurve is a smooth mathematical curve defined by a set of control points, used to create curves and shapes that can be scaled indefinitely. BezierCurve doesn’t have any other style except the common styles for Lines and Curves.
Here is a BezierCurve with style:
```
```python
from omni.ui import color as cl
style = {"BezierCurve": {"color": cl.red, "border_width": 2}}
ui.Spacer(height=2)
with ui.Frame(height=50, style=style):
ui.BezierCurve()
ui.Spacer(height=2)
```
## FreeBezierCurve
FreeBezierCurve uses two widgets to get the position of the curve endpoints. This is super useful to build graph connections. The supported style list is the same as BezierCurve.
Here is an example of a FreeBezierCurve which is controlled by 4 control points.
```python
from omni.ui import color as cl
with ui.ZStack(height=400):
# The Bezier tangents
tangents = [(50, 50), (-50, -50)]
# Four draggable rectangles that represent the control points
placer1 = ui.Placer(draggable=True, offset_x=0, offset_y=0)
with placer1:
rect1 = ui.Rectangle(width=20, height=20)
placer2 = ui.Placer(draggable=True, offset_x=50, offset_y=50)
with placer2:
rect2 = ui.Rectangle(width=20, height=20)
placer3 = ui.Placer(draggable=True, offset_x=100, offset_y=100)
with placer3:
rect3 = ui.Rectangle(width=20, height=20)
placer4 = ui.Placer(draggable=True, offset_x=150, offset_y=150)
with placer4:
rect4 = ui.Rectangle(width=20, height=20)
# The bezier curve
curve = ui.FreeBezierCurve(rect1, rect4, style={"color": cl.red, "border_width": 5})
curve.start_tangent_width = ui.Pixel(tangents[0][0])
curve.start_tangent_height = ui.Pixel(tangents[0][1])
curve.end_tangent_width = ui.Pixel(tangents[1][0])
curve.end_tangent_height = ui.Pixel(tangents[1][1])
# The logic of moving the control points
def left_moved(_):
x = placer1.offset_x
y = placer1.offset_y
tangent = tangents[0]
placer2.offset_x = x + tangent[0]
```
placer2.offset_y = y + tangent[1]
def right_moved(_):
x = placer4.offset_x
y = placer4.offset_y
tangent = tangents[1]
placer3.offset_x = x + tangent[0]
placer3.offset_y = y + tangent[1]
def left_tangent_moved(_):
x1 = placer1.offset_x
y1 = placer1.offset_y
x2 = placer2.offset_x
y2 = placer2.offset_y
tangent = (x2 - x1, y2 - y1)
tangents[0] = tangent
curve.start_tangent_width = ui.Pixel(tangent[0])
curve.start_tangent_height = ui.Pixel(tangent[1])
def right_tangent_moved(_):
x1 = placer4.offset_x
y1 = placer4.offset_y
x2 = placer3.offset_x
y2 = placer3.offset_y
tangent = (x2 - x1, y2 - y1)
tangents[1] = tangent
curve.end_tangent_width = ui.Pixel(tangent[0])
curve.end_tangent_height = ui.Pixel(tangent[1])
# Callback for moving the control points
placer1.set_offset_x_changed_fn(left_moved)
placer1.set_offset_y_changed_fn(left_moved)
placer2.set_offset_x_changed_fn(left_tangent_moved)
placer2.set_offset_y_changed_fn(left_tangent_moved)
placer3.set_offset_x_changed_fn(right_tangent_moved)
placer3.set_offset_y_changed_fn(right_tangent_moved)
placer4.set_offset_x_changed_fn(right_moved)
placer4.set_offset_y_changed_fn(right_moved)
```
# Curve Anchors
Curve Anchors and Line Anchors allow for decorations to be placed on a curve or line, such that when the shape is moved, the decoration will stay attached to it at the same parametric position. The anchor has 2 properties for its alignment and position (0-1), and an anchor_fn to supply a callback function which draws the decoration that will be attached to the curve.
Here is an example of an Anchor on a FreeBezierCurve. The decoration can be dragged along the curve with the left mouse button.
```python
from functools import partial
import asyncio
params = [None, None, None, None]
def moved(x, y, b, m):
x1 = params[0].screen_position_x + params[0].computed_width / 2
x2 = params[1].screen_position_x + params[1].computed_width / 2
anchor_position = (x - x1) / (x2 - x1)
anchor_position = max(min(anchor_position, 1), 0)
params[2].anchor_position = anchor_position
params[3].text = f"{params[2].anchor_position:.1f}"
def bound(curve=None):
with ui.ZStack(content_clipping=1):
params[3] = ui.Label(f"{params[2].anchor_position:.1f}", mouse_moved_fn=moved)
with ui.ZStack():
with ui.Placer(draggable=1):
r1 = ui.Rectangle(width=10, height=10, style={"background_color": ui.color.blue})
with ui.Placer(draggable=1, offset_x=100, offset_y=100):
r2 = ui.Rectangle(width=10, height=10, style={"background_color": ui.color.green})
with ui.Frame(separate_window=True):
curve = ui.FreeBezierCurve(r1, r2, anchor_position=0.25)
curve.set_anchor_fn(partial(bound, curve))
params[0] = r1
params[1] = r2
params[2] = curve |
linux-troubleshooting.md | # Linux Troubleshooting
Instructions for resolving issues when running Omniverse-kit or Omniverse-Create on Linux.
## Q1) How to install a driver.
- Always install `.run` executable driver files, e.g., downloaded from:
- Do **NOT** install **PPA** drivers. PPA drivers are packaged with Linux distribution, and installed with `add-apt` or `Software & Updates`. These drivers are not easy to uninstall or clean up. It requires purging them and cleaning up Vulkan ICD files manually.
- **Driver installation steps**:
- Go to TTYs mode `(CRL + ALT + F3)`, or use `systemctl` approach.
- Uninstall all previous drivers:
```
sudo nvidia-uninstall
```
- The following clean-up steps are `only` required if you have leftovers from PPA drivers:
```
sudo apt-get remove --purge nvidia-*
sudo apt autoremove
sudo apt autoclean
```
- Reboot your machine and then go to TTYs mode from the login screen:
```
sudo chmod +x NVIDIA-Linux-x86_64-460.67.run
sudo ./NVIDIA-Linux-x86_64-460.67.run
```
- If the kernel could not be compiled, make sure to download headers and image files related to your Linux kernel before the driver installation.
- Ignore errors related to missing 32-bit libraries, and build any missing library if it required a confirmation.
### Q1) How to install NVIDIA driver on Ubuntu 18.04
1. Stop X, install the driver with NVIDIA driver installer, and restart X.
2. On Ubuntu 18.04 to stop X, run the following command, then wait a bit, and ensure X is not running. e.g.: run
```
ps auxfw
```
and verify no X or Window manager process is running.
```
sudo systemctl isolate multi-user.target
```
3. To restart X, run:
```
sudo systemctl isolate graphical.target
```
### Installing a driver on a system with HP Anyware already configured should work just the same. Installing HP Anyware however requires following their instructions the first time around, before installing the NVIDIA driver.
### Q2) Omniverse kit logs only listed one of my GPUs, but `nvidia-smi` shows multiple GPUs.
How to support enumeration of multiple GPUs in Vulkan:
- **xserver-xorg-core 1.20.7** or newer is required for multi-GPU systems. Otherwise, Vulkan applications cannot see multiple GPUs.
- **Ubuntu 20.04** ships with Xorg 1.20.8 by default. Ubuntu 20 is known to work, but not exhaustively tested by Omniverse QA
- **Ubuntu 16** is not supported.
- **How to update xorg**:
- Update `Ubuntu 18.04.x LTS` through software update to the latest `Ubuntu 18.04.5 LTS`.
- Install `LTS Enablement Stacks` to upgrade xorg.
### Q3) How to verify a correct Vulkan setup with `vulkaninfo` or `vulkaninfoSDK` utility
- Download the latest Vulkan SDK `tar.gz` and unzip it.
- Do **NOT** install Vulkan SDK through `apt-install`, unless you know what exact version Omniverse supports and you need validation layers for debugging (refer to `readme.md`). Just simply download the zip file.
- Execute the following utility from the unzipped pack.
```
bin/vulkaninfo
```
- It should enumerate all the GPUs. If it failed, your driver or the required xorg is not installed properly. Do **NOT** install `vulkan-utils` or other `MESA` tools to fix your driver, as they might install old incompatible validation layers.
- `nvidia-smi` GPU table is unrelated to the list of GPUs that Vulkan driver reports.
### Q4) I have a single GPU, but I see multiple GPUs of the same type reported in Omniverse kit logs.
- You likely have leftover components from other PPA drivers in addition to the one you installed from the .run driver packages.
- You can confirm this by checking that `vulkaninfo` only shows a single GPU. These extra ICD files should be cleaned up.
- These extra files will not affect the output of `nvidia-smi`, as it is a Vulkan driver issue.
# Steps to clean up duplicate ICD files
- If you see both of the following folders have some json files, such as `nvidia_icd.json`, then delete the duplicate `icd.d` folder from `/usr/share/vulkan/` path.
```
"/etc/vulkan/icd.d": Location of ICDs installed from non-Linux-distribution-provided packages
"/usr/share/vulkan/icd.d": Location of ICDs installed from Linux-distribution-provided packages
```
- Run `vulkaninfo` to verify the fix, instead of `nvidia-smi`.
# Q5) Startup failure with:
```
VkResult: ERROR_DEVICE_LOST
```
A startup device lost is typically a system setup bug. Potential bugs:
1. A bad driver installation.
- Uninstall and re-install it.
2. Driver bugs prior to the 460.67 driver when you have different GPU models. e.g. `Turing + Ampere` GPUs.
- **Solution**: Install driver `460.67` or higher, which has the bug fix.
- **Workaround** on older drivers: Remove non-RTX cards, and re-install the driver after removing any GPU.
- This issue has been known to crash other raytracing applications. However, regular raster vulkan applications won’t be affected.
- If you have multiple GPUs, `--/renderer/activeGpu=1` setting **cannot** change this behavior.
3. Old Shader caches are left in the folder
- Delete the contents of folder `/home/USERNAME/.cache/ov/Kit/101.0/rendering`
- It is known with omniverse-kit SDK packages that are not built from the source, or not using the omniverse installer to remove the caches.
# Q6) Startup failure with:
```
GLFW initialization failed
```
This is a driver or display issue:
- A physical display must be connected to your GPU, unless you are running kit/Create headless with `--no-window` for streaming. No visual rendering can happen on the X11 window without a display and presentable swapchain.
- Test the display setup with the following command.
```
echo $DISPLAY
```
If nothing is returned, set the environment.
- Set the display environment as following persistently
```
export DISPLAY=:0.0
```
Reboot upon completion.
- `echo $DISPLAY` to verify again after the reboot.
- Re-install the driver if above steps did not help.
# Q7) Startup failure with:
```
Failed to find a graphics and/or presenting queue.
```
- Your GPU is **not** connected to a physical display. Required, except when running Kit/Create headless in `--no-windows` mode
- Your GPU is connected to a physical display, however, it is not set as the default GPU in xorg for Ubuntu’s GUI rendering:
- Choose what GPU to use for both Ubuntu UI and Omniverse rendering to present the output to the screen.
- Set its busid as follows and reboot:
```
<code class="docutils literal notranslate">
<span class="pre">
```
# Q7) How to set busid for NVIDIA GPUs
- **Step 1:** Run the following command to set the bus ID:
```
sudo
nvidia-xconfig
--busid
PCI:103:0:0
```
- **Note:** The `busid` is in decimal format, taken from NVIDIA X Server Settings.
- **Step 2:** Connect the physical display to that GPU and boot up.
- **Important:** If you have multiple GPUs, the `--/renderer/activeGpu=1` setting cannot change what GPU to run on. `busid` must be set in the xorg config, and then `activeGpu` should be set to the same device if it is not zero.
- **NVIDIA Colossus:** This involves a lot more work. Refer to Issac setup.
# Q8) Startup failure for carb::glinterop with X Error of failed request: GLXBadFBConfig
- **Issue:** OpenGL Interop support is optional for RTX renderer in the latest build, and is only needed for Storm renderer. However, such failures typically reveal other system setup issues that might also affect Vulkan applications.
- **Potential issues:**
- Unsupported driver or hardware. Currently, OpenGL 4.6 is the minimum required.
- Uninstall OpenGL utilities such as Mesa-utils and re-install your NVIDIA driver.
# Q9) How to specify what GPUs to run Omniverse apps on
- **Single-GPU mode:** Follow Q8 instructions to set the desired main GPU for presentation, and then set index of that GPU with the following option during launch if it is not zero.
```
--/renderer/activeGpu=1
```
- **Multi-GPU mode:** Follow Q8 instructions and then set indices of the desired GPUs with the following option during launch. The first device in the list performs the presentation and should be set in Xorg config.
```
--/renderer/multiGpu/activeGpus='1,2'
```
- **Note:**
- Always verify that your desired GPUs are set as Active with a “Yes” in the GPU table of omniverse .log file under [gpu.foundation]. GPU index in above options are from this table and not from nvidia-smi.
- `CUDA_VISIBLE_DEVICES` and other CUDA commands cannot change what GPUs to run on for Vulkan applications.
# Q10) Viewport is gray and nothing is rendered
This means that RTX renderer has failed and the reason of the failure will be printed in the full `.log` file as errors, such as an unsupported driver, hardware or etc. The log file is typically located at `/home/USERNAME/**/logs/**/*.log`
# Q11) Getting many failures similar to: Failed to create change watch for xxx: errno=28, No space left on device
This is a file change watcher limitation on Linux which is usually set to 8k. Either close other applications that use watchers, or increase `max_user_watches` to 512k. Note that this will increase your system RAM usage.
## To view the current watcher limit:
```
cat /proc/sys/fs/inotify/max_user_watches
```
## To update the watcher limit:
```
# This section needs to be completed in the original HTML
```
## Q11) How to increase the inotify watchers limit on Linux
> - **Edit** ` /etc/sysctl.conf` and add `fs.inotify.max_user_watches=524288` line.
> - **Load the new value:** `sudo sysctl -p`
You may follow the full instructions listed for **Visual Studio Code Watcher limit**
## Q12) How to increase the file descriptor limit on Linux to render on more than 2 GPUs
If you are rendering with multiple GPUs, file descriptor limit is required to be increased. The default limit is `1024`, but we recommend a higher value, like `65535`, for systems with more than 2 GPUs. Without that, Omniverse applications will fail during the creation of shared resources, such as Vulkan fences, and will lead to crash at startup.
### To increase the file descriptor limit
> - **Modify** ` /etc/systemd/user.conf` and ` /etc/systemd/system.conf` with the following line. This takes care of graphical login: `DefaultLimitNOFILE=65535`
> - **Modify** ` /etc/security/limits.conf` with the following lines. This takes care of non-GUI console login:
> - `hard nofile 65535`
> - `soft nofile 65535`
> - **Reboot your computer for changes to take effect.** |
linux_commands.md | # Command Cheat-Sheet
## Windows
### build
Creates a release build in `.\kit-app-template\_build` directory.
Execute command in root directory of kit-app-template.
```shell
# Release build
build
# Help
build -h
```
### repo package
Creates a package in `.\kit-app-template\_build\packages` directory.
Execute command in root directory of kit-app-template.
```shell
# Fat Package
repo package
# Thin Package
repo package --thin
# Fat Launcher Package
repo package --launcher
# Thin Launcher Package
repo package --launcher --thin
# Help
repo package -h
```
**Note**
Reference: [Fat Package](packaging_app.html#fat-package)
Reference: [Thin Package](packaging_app.html#thin-package)
### repo template new
Creates an Extension in `.\kit-app-template\source\extensions` directory.
Execute command in root directory of kit-app-template.
Once command is executed additional options are presented.
```shell
# Create a new item from a template
repo template new
# Help
repo template -h
```
### Omniverse Launcher Installation
Installs a package via Omniverse Launcher.
Execute command anywhere.
```shell
# Install Launcher Package
start omniverse-launcher://install?path=[absolute path to package]
```
## Linux
### build
Creates a release build in `./kit-app-template/_build` directory.
Execute command in root directory of kit-app-template.
```shell
# Release build
build
# Help
build -h
```
## Release build
./build.sh
## Help
./build.sh -h
## repo package
Creates a package in `./kit-app-template/_build/packages` directory.
Execute command in root directory of kit-app-template.
## Fat Package
./repo.sh package
## Thin Package
./repo.sh package --thin
## Fat Launcher Package
./repo.sh package --launcher
## Thin Launcher Package
./repo.sh package --launcher --thin
## Help
./repo.sh package -h
### Note
Reference: Fat Package
Reference: Thin Package
## repo template new
Creates an Extension in `./kit-app-template/source/extensions` directory.
Execute command in root directory of kit-app-template.
Once command is executed additional options are presented.
## Create a new item from a template
./repo.sh template new
## Help
./repo.sh template -h
## Omniverse Launcher Installation
Installs a package via Omniverse Launcher.
Execute command anywhere.
## May need to run these first
sudo apt-get update
sudo apt-get install xdg-utils
## Install Launcher Package
xdg-open omniverse-launcher://install?path=[absolute path to package] |
live-layers-data.md | # Live Layer Data
OmniUsdLiveData implements SdfAbstractData which is how USD reads/writes layer data.
The object data contains 2 copies of the tree:
- Current Tree: This is the tree as the local USD library sees it.
- Base Tree: This is the tree as-of the latest update from the server.
## Authoring a structural change
When USD calls either CreateSpec, MoveSpec, or EraseSpec we consider this to be a structural modification.
1. First we apply the modification as directed to the “current tree”
2. Next we append structural command to the currently pending “delta buffer”
3. The delta buffer is sent during the next SendDeltas (which is called when the application calls one of the Processing Live Updates functions).
4. Once the server acknowledges the update, we apply the same delta to the “base tree”
## Authoring a field change
When USD calls one of the functions to set a field or a timesample, that is not considered a structural modification.
1. First we store the modified field in a map of modified fields.
2. Next we store the modified field value in the “current tree”.
3. We set the “save count” on the field to indicate when we have modified this field. This save count is conceptually similar to the sequence number. All fields modified during the same “frame” will have the same “save count”, which is incremented every time we send a delta. We will not apply remote updates to fields which have a “save count” higher than our “most recently acknowledged update”.
4. During the next SendDeltas we collect all the modified fields and add them to the pending “delta buffer”
5. Once the server acknowledges our change, we set our “most recently acknowledged update” value to this update, so the fields may be updated by remote clients again.
Field values are only stored in memory once. The map of modified fields, as well as “current tree” all just point to the same underlying data.
We don’t build the delta buffer while setting fields because a field may be changed mulitple times prior to calling SendDeltas and we only want to store the most recent value in the delta buffer.
## Authoring child list changes
When USD modifies one of the special “children list” fields, the process is different from other field updates.
1. We set a flag on the spec indicating that it has a changed children list.
2. We set a flag on the entire object indicating that there is a changed children list.
3. During the next SendDeltas we iterate through all the specs with changed children lists and create “ReorderChildren” commands for them.
We don’t generate the reorder structural commands at the time the field is set because a children list may be modified many times per frame. We only want to generate a single “ReorderChildren” command, regardless of how many times it was modified. For example, adding 4 children in one frame will modify the field 4 times.
## Receiving updates
1. Apply the update to the “base tree”
2. Save the “current tree” as “old tree”
1. Reset the “current tree” to “base tree”
2. Re-apply any unacknowledged structural changes to “current tree”
3. Diff the “current tree” against the “old tree” to generate notices.
4. Apply reorder commands to child list fields and generate notices.
5. Apply field & timesample updates and generate notices. Remember, we ignore field & timesample changes if we have an unacknowledged change to the same field.
Steps 1-6 are skipped if the update doesn’t contain any structural changes.
We can receive updates out of order, so we store received updates in a queue and only process them in sequence. There should be no gaps, so if our current sequence number is 12, we will not process anything until we receive sequence number 13.
Receiving updates prior to “OkLatest” also skips a lot of steps, because we know that there cannot be any local changes, and we also don’t generate notices because USD doesn’t consider the layer to have been loaded yet.
## Flood Control
If there are more than 16 unacknowledged updates, we will stop sending any more updates until we have less than 8 unacknowledged updates. This is to prevent flooding the server with updates faster than it can process them. |
live-layers-details.md | # Live Layer Details
Omniverse Live Layers allow multiple people on multiple different machines to edit the same USD layer at the same time, and be able to see each others edits in real time.
The goals of live layers, in order of importance, are:
1. **Support the full USD feature set**. Anything that can be done in USD is supported with live layers.
2. **Multiple simultaneous editors**. This includes being able to edit the same prims, and even the same attributes, at the exact same time.
3. **High performance**. The power of live layers comes from their interactive speeds. However, performance must not come at the cost of correctness.
A USD layer is essentially a hierarchy of key/value pairs. If you were to represent it in JSON, a simple layer with a cube in it might look like this:
```json
{
"SdfSpecType": "PseudoRoot",
"upAxis": "Z",
"defaultPrim": "cube",
"primChildren": [
{
"SdfSpecType": "Prim",
"name": "cube",
"typeName": "Cube",
"properties": [
{
"SdfSpecType": "Attribute",
"name": "extent",
"default": [(-50, -50, -50), (50, 50, 50)]
},
{
"SdfSpecType": "Attribute",
"name": "size",
"default": 100
},
{
"SdfSpecType": "Attribute",
"name": "primvars:displayColor",
"default": [(1, 0, 0)]
},
]
}
]
}
```
Given the above layer definition, one can easily imagine a system where you send commands between clients such as, “set /cube.size = 75” and that definitely works in simple cases. Indeed, that is exactly what the original prototype for live layers did.
Now let’s consider the various edge cases and how we solved them.
### Simultaneous Updating of Fields
Consider the following, where Alice and Bob both update the color of the cube at the same time:
This will work, in the sense that all participants have the same state at the end, but it results in an undesirable flicker for Bob. First his cube turns blue, then red, then back to blue.
We handle this case by ignoring field updates caused by other users until the server has acknowledged our own field update. This is done per-field, so we do still apply updates to fields made by other users as long as we have not also updated that same field.
### Receiving Updates Out of Order
It’s possible to receive updates from the server out of order. To prevent the chaos that would ensue, the server includes a sequence number with each update (both remote updates and acknowledgements of your own updates). If a client has update N, then receives update N+2, it will hold that update in a queue until it receives update N+1 (at which point it will process both updates). This is handled by OmniUsdLiveData.
### Handling Deleted Nodes
Sometimes a user may be editing a node that another user has simultaneously deleted. In this case, all participants ignore the edit to the deleted node. Note the server still sends an acknowledgement and forwards the edit to the other clients because there can be many different edits in the same message, and they are probably not all going to be ignored.
### Handling Renamed Nodes
If a user edits a node that another user has renamed, we could handle that the same way we handle deleting nodes (by ignoring it), however that’s not a great user experience. More importantly, it can cause divergent state: one user does an edit then a rename, the other user does a rename then ignores the edit. Handling that divergent state is not impossible, but it’s much easier to just handle renames by referring to nodes by a unique ID number rather than by name. We store node parents by ID number as well, so we can also handle moving nodes the same way.
#### Initial State
| Node ID | Parent Node | Name |
|---------|-------------|--------|
| 1 | 0 | / |
| 843 | 1 | cube1 |
| 257 | 843 | color |
| 726 | 843 | size |
Remember from the example above that attributes are themselves nodes, and the attribute value is named “default” because the attribute may have timesamples. See the documentation on
## UsdAttribute::Get() for more information about this.
## Creating Nodes
### Creating Nodes
In this example, Bob creates a node as a child of cube, and immediately sets a value. At the same time Alice has deleted the cube.
| Node ID | Parent Node | Name |
|---------|-------------|------|
| 1 | 0 | / |
| 843 | 1 | cube |
In this case, we see that Bob needs to refer to the node by ID (to set the color) even before the server has acknowledged that he has created it. It’s obvious then that the server cannot assign node IDs.
We considered many different solutions to this problem, including referring to nodes with temporary IDs until the server assigns a permanent one, but ultimately we decided to go a much simpler route of selecting a random 64 bit number. The chance of collision may appear to be N/4 billion (where N is the number of nodes in the layer), however since the client knows which IDs are already in-use, if the selected random number is in-use, we select a new one. This means the real risk of collision is for two different clients to create nodes with the same ID at the exact same time.
## Name Collisions
### Name Collisions
The problem with referring to nodes by number rather than by name is it opens up the possibility that two clients can create different nodes with the same name.
Reconciling this case is easy on the server (just ignore the second node creation), and is also easy to handle on the client that “won” (the client whose node was created first). The client who “lost” (the one whose node creation was ignored by the server) must recognize this case when it receives the remote update for a node creation with the same name, and delete his own node prior to creating the new node.
## Children Order
### Children Order
In USD, the order of children nodes matters. USD stores them as a list of names in special fields. For example:
```cpp
primChildren = ["cube", "sphere", "cone"]
properties = ["size", "color"]
```
If we just sent that list over like we do with all other attributes, we could easily get into a situation where two clients add child prims at the same time and set the `primChildren` field to include their own new child prim. Since the server does not merge attributes (it only keeps the most recently set one), the list would be missing a child. Additionally, renaming would also cause problems with this approach.
To solve this, we added an explicit “reorder” command to change the order of child nodes. When USD sets one of the special children fields, we convert that to a `reorder` command which references the child nodes by ID. The server (and other clients) reorder the child nodes which are listed, and leave any child nodes which are unlisted in the same place they originally were. Child nodes listed in the reorder command which don’t exist are assumed to have been deleted and ignored. |
live-layers-multithread.md | # OmniUsdLiveFileFormat (Multi-threaded) Overview
## OmniUsdLiveFileFormat
OmniUsdLiveFileFormat is a SdfFileFormat plugin that represents “live” SdfLayer`s. The `OmniUsdLiveFileFormat implements the required SdfFileFormat API to properly translate “live” data into Sdf data structures.
As such, the vast majority of the code actually lives in OmniUsdLiveData.
> The OmniUsdLiveFileFormat plugin is being transitioned to a new multi-threaded implementation. Within the code-base this new multi-threaded implementation is being referred to as “live v2” whereas this original OmniUsdLiveFileFormat is considered “live v1”. “v1” and “v2” do not refer to a new version of the “live” protocol on Nucleus but an iteration on the actual OmniUsdLiveFileFormat plugin. |
live-layers-wire-format.md | # Live Layer Wire Format
Omniverse live layers encode their data in a format we refer to as a “wire format” rather than “file format” because the layers are not actually stored as files on disk on either the server (they’re stored in a database) or the clients (they’re stored in memory).
You could of course write the data to disk (and we do for unit tests), but live layers are not intended to be stored as regular files.
## Header
The first 4 bytes are a “FourCC” of either “OMPF” or “OODF”:
- OMPF is the “Omniverse Multi-Part Format”
- OODF is the “Omniverse Object Delta Format”
## Omniverse Object Delta Format
The Omniverse Object Delta Format is encoded as a flatbuffer with the schema defined here and a compiled version in packman at omniverse.nucleus-objects.schema.linux-x86_64 (note: depsite having “linux-x86_64” in the name, that package works on all platforms because it is code only).
The schema looks like this:
![OmniObjectDelta-fbs.drawio.svg](../_images/OmniObjectDelta-fbs.drawio.svg)
### OmniObjectDelta
This is the “root” of the flatbuffer, which contains:
- isDiff: True indicates that this is a “diff” rather than a “delta”. A “diff” only contains the “Diff” structural commands, which allows for some optimizations. This is used when you initially request an object from the server.
- baseVersion: Only valid if “isDiff” is true. This is the version (sequence number) that the diff was based on. This is 0 if the diff was generated “from scratch” and there is no base version. This can also be sent mid-session to indicate that a user cleared the entire layer (by calling `layer->Clear()`).
- structCommands: An array of commands that modify the structure of the tree itself. These must be applied in order.
- setFields: An array of fields to set after applying structural commands.
- timeSamples: An array of timesamples to set after applying structural commands.
- sourceFormat: No longer used. We previously used this if you created a live layer by calling “Export” from a non-live layer. This field stored the original format of the non-live layer, but we determined that it was not actually important. It’s left here for backwards compatibility.
### Structural Commands
Nodes in the flatbuffer schema are are named sections for historical reasons that nobody can remember. This document (and the code itself) uses “node” and “section” interchangeably.
#### CreateSection
This creates a new “section” which is a node in the live layer tree. This is a no-op if the parent does not exist. If there already exists a node with the same parentId and the same sectionName, this is ignored (and the node will not be created).
- parentId: The ID of the parent node. This is 0 when creating the root node (which is always sectionId 1).
- sectionId: The ID of this node. This is randomly generated (as described in [Creating Nodes](live-layers-details.html#creating-nodes)). It must not be 0, or previously used. It must be 1 for the root node.
- sectionName: The relative name of this section.
- sectionType: This maps directly to SdfSpecType
## DeleteSection
Deletes a node from the tree. This is a no-op if the node has already been deleted.
- parentId: The ID of the parent node. This is no longer used, but left in for backwards compatibility.
- sectionId: The ID of the node to delete.
## MoveSection
Moves or renames a node in the tree. This is a no-op if the node has been deleted. This node is deleted if the new parent node has been deleted. This node is also deleted if there already exists a node with the same newParentId and newName.
- oldParentId: The ID of the old parent node.
- newParentId: The ID of the new parent node (could be the same as the oldParentId).
- sectionId: The ID of the node which is getting moved/renamed.
- newName: The new name of the node (could be the same as the existing node name).
The reason we send both the old parent id and the new parent id is to determine if this was intended to be a move or a rename. For example if you just want to rename the node, you set `newParentId = oldParentId`, then if another client simultaneously moves the node, so it has a different parent id, we still apply the rename, even though the parent id no longer matches. In retrospect, we should have created an explicit “RenameSection” command to handle this case, but it is not worth changing now because that would break backwards compatibilty.
## ReorderChildren
As described in Children Order, the order of child nodes matters in USD. Child nodes are stored in the database (and in memory, for that matter) in unordered maps, and USD uses special “children” fields to define the order of the child nodes. This command is used to change the order of the child nodes, which implicitly sets those “children” fields.
- sectionId: The parent node for which we are changing the child node order
- childrenListId: Some spec types may have up to 3 different children lists. This indicates which one we are changing. The exact index depends on sectionType (specType). The mapping is in `ChildrenHelper::GetChildrenIndex`.
- childrenList: An array of children node IDs in the desired order.
If a child node in `childrenList` no longer exists, it is ignored. If a child node exists which is not in `childrenList`, its position remains unchanged.
For example if a node has the children “ABCDEFG” and childrenList indicates “GCHDB”, the new list will be “AGCDEFB”. The “H” is ignored, because it no longer exists. The nodes ‘A’, ‘E’ and ‘F’ stay in their same place because they are not in “childrenList”. The other nodes are rearranged to match the order in “childrenList”.
## DiffChangeSection
This command is only valid if `isDiff` is true. This allows for directly setting all the values of a node (and creates it if necessary).
- parentId: ID of the parent node.
- sectionId: ID of the node we are changing.
- sectionName: New name of the node.
- sectionType: New type of the node.
- sectionOrder: Order of this node in the parent list. For example if a node has 2 children, one of the children will have `sectionOrder=0`, the next will have `sectionOrder=1`
Values are set even if unchanged. For example, `sectionName` must always be set, even if the node was not renamed.
## DiffDeleteSection
This command is only valid if `isDiff` is true. Delete a node.
- sectionId: ID of the node to delete.
## SetFields & TimeSamples
The `setFields` and `timesamples` arrays are both used to set the values of fields of nodes in the tree.
They are very similar to each other, but `SetField` uses a string as the key name, and `TimeSample` uses a double.
- sectionId: The parent node ID
- keyName: (SetField) The field name.
- time: (TimeSample) The timesample key.
- valueOrExtHash: For small values (less than 64KB) this is the value itself. For large values this is the SHA1 hash of the value.
- extValueSize: Size of the value, only for values stored outside the flatbuffer.
- extValueIndex: Index of the value in the parts array (see Omniverse Multi-Part Format).
- setOrder: This is used to instruct clients to set the fields in a particular order. This was added to ensure all clients receive notices in the same order. We store this explicitly rather than relying on the order of the `setFields` array itself because fields are stored internally in an unordered map.
## Multi-part Format
The multi-part format is used whenever there are large values. Currently “large” is defined as 65,535 bytes.
The reason the multi-part format exists is because flatbuffers uses 32 bit signed offsets, so the total size cannot be larger than 2GB. Ideally nobody would create a live layer which is larger than 2GB, but our top goal is to support anything that USD can do, and USD can create layers which are larger than 2GB.
After the 4 byte identifier, there is a 32 bit unsigned integer which stores the number of parts, followed by a table of 64 bit unsigned integers which are offsets to each part.
The first part is a flatbuffer of the same format as “OODF”. The other parts are the actual values (one part per large value).
## Value Format
Field values are VtValues encoded using a method similar to how USD crate values pack data. The code is in `OmniUsdValueHelper.cpp`.
The packing format is purely a client to client contract. The server doesn’t unpack values at all.
Each value starts with a header:
* 7 bit type
* 1 bit `isArray` flag
* 8 bit version number.
* 64 bit count (only if `isArray` is set)
* 32 bit count (only for string types)
Following the header is the packed data blob. The packing algorithm depends on the type of value, and the version number.
Currently all types are at version 0. Adding a new version should be done with caution because it is not a backwards compatible change. The safest way to roll this out is to add support for reading the new version, but always write the old version. After enough time has elapsed, and you are sure that all clients have been updated, you can switch to writing the new version. An example of adding a new version is if you want to add compression to a type.
Similarly, adding a new type is not a backwards compatible change. There is not really a safe way to roll out a new type, but USD itself has the same issue with crate files. For this reason it’s safe to assume that new types are unlikely to be added (hopefully).
The list of types is defined in `UsdTypes.h` and is currently:
```c++
// Array types.
USD_TYPE(Bool, 1, bool, 0)
USD_TYPE(UChar, 2, uint8_t, 0)
USD_TYPE(Int, 3, int, 0)
USD_TYPE(UInt, 4, unsigned int, 0)
USD_TYPE(Int64, 5, int64_t, 0)
USD_TYPE(UInt64, 6, uint64_t, 0)
USD_TYPE(Half, 7, GfHalf, 0)
USD_TYPE(Float, 8, float, 0)
USD_TYPE(Double, 9, double, 0)
USD_TYPE(String, 10, std::string, 0)
USD_TYPE(Token, 11, TfToken, 0)
USD_TYPE(AssetPath, 12, SdfAssetPath, 0)
USD_TYPE(Matrix2d, 13, GfMatrix2d, 0)
USD_TYPE(Matrix3d, 14, GfMatrix3d, 0)
USD_TYPE(Matrix4d, 15, GfMatrix4d, 0)
USD_TYPE(Quatd, 16, GfQuatd, 0)
USD_TYPE(Quatf, 17, GfQuatf, 0)
USD_TYPE(Quath, 18, GfQuath, 0)
USD_TYPE(Vec2d, 19, GfVec2d, 0)
```
USD_TYPE(Vec2f, 20, GfVec2f, 0)
USD_TYPE(Vec2h, 21, GfVec2h, 0)
USD_TYPE(Vec2i, 22, GfVec2i, 0)
USD_TYPE(Vec3d, 23, GfVec3d, 0)
USD_TYPE(Vec3f, 24, GfVec3f, 0)
USD_TYPE(Vec3h, 25, GfVec3h, 0)
USD_TYPE(Vec3i, 26, GfVec3i, 0)
USD_TYPE(Vec4d, 27, GfVec4d, 0)
USD_TYPE(Vec4f, 28, GfVec4f, 0)
USD_TYPE(Vec4h, 29, GfVec4h, 0)
USD_TYPE(Vec4i, 30, GfVec4i, 0)
// Non-array types.
USD_TYPE(Dictionary, 31, VtDictionary, 0)
USD_TYPE(TokenListOp, 32, SdfTokenListOp, 0)
USD_TYPE(StringListOp, 33, SdfStringListOp, 0)
USD_TYPE(PathListOp, 34, SdfPathListOp, 0)
USD_TYPE(ReferenceListOp, 35, SdfReferenceListOp, 0)
USD_TYPE(IntListOp, 36, SdfIntListOp, 0)
USD_TYPE(Int64ListOp, 37, SdfInt64ListOp, 0)
USD_TYPE(UIntListOp, 38, SdfUIntListOp, 0)
USD_TYPE(UInt64ListOp, 39, SdfUInt64ListOp, 0)
USD_TYPE(PathVector, 40, SdfPathVector, 0)
USD_TYPE(TokenVector, 41, std::vector<TfToken>, 0)
USD_TYPE(Specifier, 42, SdfSpecifier, 0)
USD_TYPE(Permission, 43, SdfPermission, 0)
USD_TYPE(Variability, 44, SdfVariability, 0)
USD_TYPE(VariantSelectionMap, 45, SdfVariantSelectionMap, 0)
USD_TYPE(TimeSamples, 46, SdfTimeSampleMap, 0)
USD_TYPE(Payload, 47, SdfPayload, 0)
USD_TYPE(DoubleVector, 48, std::vector<double>, 0)
USD_TYPE(LayerOffsetVector, 49, std::vector<SdfLayerOffset>, 0)
USD_TYPE(StringVector, 50, std::vector<std::string>, 0)
USD_TYPE(ValueBlock, 51, SdfValueBlock, 0)
USD_TYPE(Value, 52, VtValue, 0)
USD_TYPE(UnregisteredValue, 53, SdfUnregisteredValue, 0)
USD_TYPE(UnregisteredValueListOp, 54, SdfUnregisteredValueListOp, 0)
USD_TYPE(Path, 55, SdfPath, 0)
USD_TYPE(SpecType, 56, SdfSpecType, 0)
// Crate version 0.8.0
USD_TYPE(PayloadListOp, 57, SdfPayloadListOp, 0)
// Crate version 0.9.0
USD_TYPE(TimeCode, 58, SdfTimeCode, 0)
// USD Resolver 2.0
USD_TYPE(Range1d, 59, GfRange1d, 0)
USD_TYPE(Range2d, 60, GfRange2d, 0)
USD_TYPE(Range3d, 61, GfRange3d, 0)
USD_TYPE(Range1f, 62, GfRange1f, 0)
USD_TYPE(Range2f, 63, GfRange2f, 0)
USD_TYPE(Range3f, 64, GfRange3f, 0) |