file_path
stringlengths 5
148
| content
stringlengths 150
498k
| size
int64 150
498k
|
---|---|---|
omni.usd.editor.set_hide_in_ui.md | # set_hide_in_ui
## set_hide_in_ui
```python
def set_hide_in_ui(prim: Prim, value: bool)
```
Sets metadata for the prim to instruct UI whether it should be hidden in the UI or not.
``` | 186 |
omni.usd.editor.set_no_delete.md | # set_no_delete
## set_no_delete
```python
omni.usd.editor.set_no_delete(prim: Prim, no_delete: bool)
```
Sets metadata for prim to instruct UI whether the prim can be removed or not. | 185 |
omni.usd.EngineCreationConfig.md | # EngineCreationConfig
## EngineCreationConfig
```python
class omni.usd.EngineCreationConfig(pybind11_object)
```
EngineCreationConfig structure.
### Methods
| Method | Description |
|--------|-------------|
| `__init__(self)` | |
### Attributes
| Attribute | Description |
|-----------|-------------|
| `device_mask` | |
| `flags` | |
| `tickrate_in_hz` | |
```python
def __init__(self: omni.usd._usd.EngineCreationConfig) -> None:
pass
```
---
title: "示例文档"
author: "作者姓名"
date: "2023-01-01"
---
# 引言
这是一个示例文档,用于展示如何将HTML格式转换为Markdown格式。
## 目录
1. [简介](#简介)
2. [正文](#正文)
3. [结论](#结论)
## 简介
这里是简介部分,介绍文档的主要内容和目的。
## 正文
### 代码示例
```python
def example_function():
print("这是一个代码示例")
```
### 表格
| 列1 | 列2 | 列3 |
| --- | --- | --- |
| 数据1 | 数据2 | 数据3 |
| 数据4 | 数据5 | 数据6 |
## 结论
这里是结论部分,总结文档的主要发现和建议。
---
## 参考文献
- [参考文献1](#)
- [参考文献2](#)
## 致谢
感谢所有贡献者。
---
## 附录
这里是附录部分,包含额外的信息和数据。
---
## 联系信息
- 邮箱: example@example.com
- 电话: 123-456-7890
---
## 版权信息
© 2023 示例文档. All rights reserved.
---
## 脚注
这里是脚注信息。
---
## 底部信息
这里是底部信息。
---
## 页脚
这里是页脚信息。
--- | 1,100 |
omni.usd.EngineCreationFlags.md | # EngineCreationFlags
## Class Definition
```python
class omni.usd.EngineCreationFlags(pybind11_object)
```
### Description
Specifies the flags for the hydra engine creation.
### Members
- NONE
- MOTION_RAYTRACING_ENABLED
- SKIP_ON_WORKER_PROCESS
### Methods
- `__init__(self, value)`
### Attributes
- `MOTION_RAYTRACING_ENABLED`
- `NONE`
- `SKIP_ON_WORKER_PROCESS`
- `name`
- `value`
(
self: omni.usd._usd.EngineCreationFlags,
value: int
) → None
property name | 467 |
omni.usd.find_path_in_nodes.md | # find_path_in_nodes — Omniverse Kit 1.10.39 documentation
## find_path_in_nodes
```python
omni.usd.find_path_in_nodes(node, set_fn)
```
- **node**:
- **set_fn**:
```
``` | 175 |
omni.usd.find_spec_on_session_or_its_sublayers.md | # find_spec_on_session_or_its_sublayers
## find_spec_on_session_or_its_sublayers
```
```python
omni.usd.find_spec_on_session_or_its_sublayers(stage: Stage, path: Path, predicate: Optional[Callable[[Spec], bool]] = None)
```
- **Description:**
Finds spec in the session layer or its sublayers.
- **Parameters:**
- **stage** (`Usd.Stage`) – Stage instance.
- **path** (`Sdf.Path`) – Spec path to find.
- **predicate** (`Callable[[Sdf.Spec], bool]`) – Optional predicate function to filter specs. Default is `None`.
## Description
### Parameters
#### predicate
- **Type**: `(Sdf.Path, Sdf.Spec) -> bool`
- **Description**: If it’s provided, the spec to find must pass the predicate.
### Returns
- **Description**: Layer that the spec resides in, and the spec handle. Or (None, None) if it cannot be found.
- **Return type**: (Sdf.Layer, Sdf.Spec) | 859 |
omni.usd.Functions.md | # omni.usd Functions
## Functions Summary:
- [attr_has_timesample_on_key](#)
- [can_be_copied](#)
- [can_prim_have_children](#)
- [check_ancestral](#)
- [clear_attr_val_at_time](#) - Clears attribute at specified timecode.
- [copy_timesamples_from_weaker_layer](#)
- [correct_filename_case](#)
- [create_material_input](#)
- [duplicate_prim](#) - Duplicate prim.
- [find_path_in_nodes](#)
- [find_spec_on_session_or_its_sublayers](#) - Finds spec in the session layer or its sublayers.
- [gather_default_attributes](#)
- [get_all_sublayers](#) - Gets all sublayers from local layer stack of the stage ranking from strongest to weakest.
get_attribute_effective_defaultvalue_layer_info
get_attribute_effective_timesample_layer_info
get_attribute_effective_value_layer_info
get_authored_prim
get_composed_payloads_from_prim
get_composed_references_from_prim
get_context_from_stage
get_dirty_layers
get_edit_target_identifier
get_frame_time
get_frame_time_code
get_geometry_standard_prim_list
get_introducing_layer
get_light_prim_list
get_local_transform_SRT
get_local_transform_matrix
get_prim_at_path
get_prim_descendents
get_prop_at_path
get_prop_auto_target_session_layer
get_sdf_layer
get_shader_from_material
get_stage_next_free_path
get_subidentifier_from_material
<p>
get_subidentifier_from_mdl
<p>
get_timesamples_count_in_authoring_layer
<p>
get_url_from_prim
<p>
Returns url of Prim when authored reference or None
<p>
get_world_transform_matrix
<p>
handle_exception
<p>
Decorator to print exception in async functions
<p>
is_ancestor_prim_type
<p>
is_child_type
<p>
is_hidden_type
<p>
is_layer_locked
<p>
Checks if layer is locked or not in this usd context. Layer lock is a customized
<p>
is_layer_writable
<p>
Checks if layer is writable on file system.
<p>
is_path_valid
<p>
is_prim_material_supported
<p>
is_usd_readable_filetype
<p>
Whether the given file path is a supported readable USD file or not.
<p>
is_usd_writable_filetype
<p>
Whether the given file path is a supported writable USD file or not.
<p>
make_path_relative_to_current_edit_target
<p>
on_layers_saved_result
<p>
on_stage_result
<p>
readable_usd_dotted_file_exts
<p>
Gets a list of file extensions about readable USD formats.
<p>
readable_usd_file_exts
<p>
Gets a list of file extensions (without dots) about readable USD formats.
<p>
readable_usd_file_exts_str
<p>
Gets a string that includes all readable USD file formats supported by Kit.
<p>
readable_usd_files_desc
<p>
Gets a description of all readable USD file formats.
<p>
readable_usd_re
<p>
Gets the regex that matches readable USD files.
<p>
remove_property
<p>
Removes specified property from the prim.
<p>
set_attr_val
Deprecated. See :func:`.set_prop_val` instead.
set_edit_target_by_identifier
Sets the edit target of stage by layer identifier.
set_prop_val
Sets the value of property.
stitch_prim_specs
Sitches prim specs specified by path scattered in all sublayers
writable_usd_dotted_file_exts
Gets a list of file extensions about writable USD formats.
writable_usd_file_exts
Gets a list of file extensions (without dots) about writable USD formats.
writable_usd_file_exts_str
Gets a string that includes all writable USD file formats supported by Kit.
writable_usd_files_desc
Gets a description of all writable USD file formats.
writable_usd_re
Gets the regex that matches writable USD files.
add_hydra_engine
add_hydra_engine(name: str, context: omni.usd._usd.UsdContext) -> omni.usd._usd.OpaqueSharedHydraEngineContext
attach_all_hydra_engines
attach_all_hydra_engines(context: omni.usd._usd.UsdContext) -> None
create_context
create_context(name: str = '') -> omni.usd._usd.UsdContext
destroy_context
destroy_context(name: str = '') -> bool
get_context
get_context(name: str = '') -> omni.usd._usd.UsdContext
get_context_from_stage_id
get_context_from_stage_id(stage_id: int) -> omni.usd._usd.UsdContext
get_or_create_hydra_engine
get_or_create_hydra_engine(arg0: str, arg1: omni.usd._usd.UsdContext, arg2: omni.usd._usd.EngineCreationConfig) -> omni.usd._usd.OpaqueSharedHydraEngineContext
merge_layers
merge_layers(dst_layer_identifier: str, src_layer_identifier: str, dst_is_stronger_than_src: bool = True, src_layer_offset: float = 0.0, src_layer_scale: float = 1.0) -> bool
merge_prim_spec
merge_prim_spec(dst_layer_identifier: str, src_layer_identifier: str, prim_spec_path: str, dst_is_stronger_than_src: bool = True, target_prim_path: str = '') -> None
release_all_hydra_engines
release_all_hydra_engines(context: omni.usd._usd.UsdContext = None) -> None
release_hydra_engine
release_hydra_engine(arg0: omni.usd._usd.UsdContext, arg1: omni.usd._usd.OpaqueSharedHydraEngineContext) -> bool
resolve_paths
resolve_paths(src_layer_identifier: str, dst_layer_identifier: str, store_relative_path: bool = True, relative_to_src_layer: bool = False, copy_sublayer_offsets: bool = False) -> None
| resolve_prim_path_references | resolve_prim_path_references(layer: str, old_prim_path: str, new_prim_path: str) -> None |
|-------------------------------|-----------------------------------------------------------------------------------------------|
| resolve_prim_paths_references | resolve_prim_paths_references(layer: str, old_prim_paths: List[str], new_prim_paths: List[str]) -> None |
| shutdown_usd | shutdown_usd() -> None | | 5,452 |
omni.usd.get_attribute_effective_defaultvalue_layer_info.md | # get_attribute_effective_defaultvalue_layer_info
## get_attribute_effective_defaultvalue_layer_info
```python
omni.usd.get_attribute_effective_defaultvalue_layer_info(stage, attr: Attribute)
```
```
``` | 206 |
omni.usd.get_attribute_effective_timesample_layer_info.md | # get_attribute_effective_timesample_layer_info
## get_attribute_effective_timesample_layer_info
### omni.usd.get_attribute_effective_timesample_layer_info
```python
omni.usd.get_attribute_effective_timesample_layer_info(stage, attr: Attribute)
``` | 255 |
omni.usd.get_attribute_effective_value_layer_info.md | # get_attribute_effective_value_layer_info
## get_attribute_effective_value_layer_info
```python
omni.usd.get_attribute_effective_value_layer_info(stage, attr: Attribute)
```
--- | 181 |
omni.usd.get_composed_payloads_from_prim.md | # get_composed_payloads_from_prim
## get_composed_payloads_from_prim
### omni.usd.get_composed_payloads_from_prim
#### omni.usd.get_composed_payloads_from_prim
##### omni.usd.get_composed_payloads_from_prim
###### omni.usd.get_composed_payloads_from_prim
####### omni.usd.get_composed_payloads_from_prim
###### omni.usd.get_composed_payloads_from_prim
##### omni.usd.get_composed_payloads_from_prim
#### omni.usd.get_composed_payloads_from_prim
### omni.usd.get_composed_payloads_from_prim
## omni.usd.get_composed_payloads_from_prim
# get_composed_payloads_from_prim
| 593 |
omni.usd.get_composed_references_from_prim.md | # get_composed_references_from_prim
## get_composed_references_from_prim
```python
omni.usd.get_composed_references_from_prim(prim: Prim, fix_slashes: bool = True) -> List[Tuple[Reference, Layer]]
```
Gets composed reference list from prim.
**Parameters:**
- **prim** (Usd.Prim) – Handle of Usd.Prim.
**Returns:**
- List of reference items. Each item is a tuple that includes reference handle, and the layer it’s from.
``` | 427 |
omni.usd.get_context_from_stage.md | # get_context_from_stage
## get_context_from_stage
```python
omni.usd.get_context_from_stage(stage)
```
Gets corresponding UsdContext of the stage if it’s found.
```
``` | 172 |
omni.usd.get_context_from_stage_id.md | # get_context_from_stage_id
## get_context_from_stage_id
- **Function**: `omni.usd.get_context_from_stage_id(stage_id: int) -> omni.usd._usd.UsdContext`
- **Description**: Finds UsdContext instance with specified stage id. | 223 |
omni.usd.get_dirty_layers.md | # get_dirty_layers
## get_dirty_layers
```python
omni.usd.get_dirty_layers(stage: Stage, include_root_layer=True)
```
Gets all dirty layers that have unsaved changes.
``` | 173 |
omni.usd.get_edit_target_identifier.md | # get_edit_target_identifier
## get_edit_target_identifier
```python
omni.usd.get_edit_target_identifier(stage: Stage) -> str
```
Gets the layer identifier of current edit target.
**Parameters**
- **stage** (Usd.Stage) – Stage handle
**Returns**
- Layer identifier or empty string if edit target is not set. | 311 |
omni.usd.get_introducing_layer.md | # get_introducing_layer
## get_introducing_layer
This function will find the local layer that defines this prim, or the first introducing layer that introduces the prim into the local layer stack if prim is defined in a reference or payload. An introducting layer is the layer that adds the prim into the composition graph.
The difference of this function to Usd.PrimCompositionQuery is that it will return the first local layer where the prim is defined. If it’s not defined locally, it will find the reference or payload arcs with Usd.PrimCompositionQuery to find the first introducing layer and its introducing prim path in the local layer stack.
### Parameters
- **prim** (Usd.Prim) – Prim handle
### Returns
- Introducing layer and its introducing prim path.
### Return type
- Tuple[Sdf.Layer, Sdf.Path] | 814 |
omni.usd.get_local_transform_matrix.md | # get_local_transform_matrix
## get_local_transform_matrix
```
```python
omni.usd.get_local_transform_matrix(prim: Prim, time_code: TimeCode = Usd.TimeCode.Default()) | 168 |
omni.usd.get_local_transform_SRT.md | # get_local_transform_SRT
## get_local_transform_SRT
```python
omni.usd.get_local_transform_SRT(prim, time=Usd.TimeCode.Default())
```
- **Parameters**:
- `prim`:
- `time`: (default is `Usd.TimeCode.Default()`)
- **Returns**:
- Tuple[
pxr.Gf.Vec3d | pxr.Gf.Vec3f | pxr.Gf.Vec3h,
pxr.Gf.Vec3d | pxr.Gf.Vec3f | pxr.Gf.Vec3h,
Vec3i,
pxr.Gf.Vec3d | pxr.Gf.Vec3f | pxr.Gf.Vec3h
]
- **Description**:
Return a tuple of [scale, rotation, rotation_order, translate] for given prim. | 504 |
omni.usd.get_or_create_hydra_engine.md | # get_or_create_hydra_engine
## get_or_create_hydra_engine
```python
omni.usd.get_or_create_hydra_engine(arg0: str, arg1: omni.usd._usd.UsdContext, arg2: omni.usd._usd.EngineCreationConfig) -> omni.usd._usd.OpaqueSharedHydraEngineContext
```
``` | 248 |
omni.usd.get_prim_at_path.md | # get_prim_at_path
## get_prim_at_path
### omni.usd.get_prim_at_path
omni.usd.get_prim_at_path(path: Path, usd_context_name: Union[str, Stage] = '') → Prim
| 161 |
omni.usd.get_prop_at_path.md | # get_prop_at_path
## get_prop_at_path
### omni.usd.get_prop_at_path
#### Parameters
- `path`: Path
- `usd_context_name`: Union[str, Stage] = ''
#### Returns
- Property | 175 |
omni.usd.get_prop_auto_target_session_layer.md | # get_prop_auto_target_session_layer
## get_prop_auto_target_session_layer
Get property auto retarget layer.
### Parameters
- **stage** (`Usd.Stage`) – Usd stage
- **prop_path** (`Sdf.Path`) – property path | 209 |
omni.usd.get_stage_next_free_path.md | # get_stage_next_free_path
## get_stage_next_free_path
### Function Signature
```python
omni.usd.get_stage_next_free_path(stage: Stage, path: Union[str, Path], prepend_default_prim: bool)
```
### Description
Gets a new prim path that doesn’t exist in the stage given a base path. If the given path doesn’t exist in the stage already, it returns the given path directly. Otherwise, it appends a suffix with number index to the given path until it finds a path that’s not taken.
### Parameters
- **stage** (Usd.Stage) – The stage handle.
- **path** (Union[str, Sdf.Path]) – Base prim path.
- **prepend_default_prim** (bool) – Whether it should prepend default prim name to the path or not.
### Raises
- **ValueError** – Path is not a valid prim path.
### Returns
- prim path that doesn’t exist in the stage.
### Return type
- Sdf.Path
# 标题
这是一些文本内容,其中包含了一些特殊字符,比如:<、>、&。
## 子标题
这里是更多的文本内容,可能包含一些代码示例:
```python
print("Hello, world!")
```
还有一些列表:
- 列表项1
- 列表项2
- 列表项3
以及一些引用:
> 这是一个引用。
还有一些链接,但链接本身已被删除,只保留了链接文本:
- 链接文本1
- 链接文本2
还有一些图片,但图片本身已被删除:
![图片描述](图片链接)
还有一些表格:
| 表头1 | 表头2 |
|-------|-------|
| 内容1 | 内容2 |
| 内容3 | 内容4 |
还有一些分割线:
---
还有一些脚注:
--- | 1,175 |
omni.usd.get_subidentifier_from_material.md | # get_subidentifier_from_material
## get_subidentifier_from_material
```markdown
async omni.usd.get_subidentifier_from_material(prim: Prim, on_complete_fn: Optional[Callable] = None)
```
Deprecated. Use `omni.kit.material.library.get_subidentifier_from_material` instead.
``` | 276 |
omni.usd.get_subidentifier_from_mdl.md | # get_subidentifier_from_mdl
## get_subidentifier_from_mdl
```python
async omni.usd.get_subidentifier_from_mdl(mdl_file: str, on_complete_fn: Optional[Callable] = None)
```
This function retrieves subidentifiers from a Material Definition Library (MDL) file.
- **mdl_file**: The path to the MDL file.
- **on_complete_fn**: An optional callback function to be executed after the operation completes.
``` | 405 |
omni.usd.get_timesamples_count_in_authoring_layer.md | # get_timesamples_count_in_authoring_layer
## get_timesamples_count_in_authoring_layer
```python
omni.usd.get_timesamples_count_in_authoring_layer(stage, attr_path: Path)
```
```
``` | 185 |
omni.usd.get_world_transform_matrix.md | # get_world_transform_matrix
## get_world_transform_matrix
```python
omni.usd.get_world_transform_matrix(prim: Prim, time_code: TimeCode = Usd.TimeCode.Default())
```
--- | 172 |
omni.usd.is_ancestor_prim_type.md | # is_ancestor_prim_type
## is_ancestor_prim_type
```python
omni.usd.is_ancestor_prim_type(stage: Stage, prim_path: Path, prim_type: SchemaBase)
```
This function checks if the specified prim type is an ancestor of the given prim path in the stage. | 249 |
omni.usd.is_layer_locked.md | # is_layer_locked
## is_layer_locked
```python
omni.usd.is_layer_locked(usd_context, layer_identifier: str) -> bool
```
Checks if layer is locked or not in this usd context. Layer lock is a customized concept in Kit that’s not from USD. It’s used to complement the concept of file permission. Unlike the writable permission on file system, lock is bound to stage. So a layer may be locked in this stage, but not for other stages. Lock status is persistent across sessions, and saved as a flag inside the custom data of root layer. | 532 |
omni.usd.is_layer_writable.md | # is_layer_writable
Checks if layer is writable on file system.
## Description
```python
omni.usd.is_layer_writable(layer_identifier: str) -> bool
```
Checks if the specified layer is writable on the file system.
``` | 220 |
omni.usd.is_usd_readable_filetype.md | # is_usd_readable_filetype
## is_usd_readable_filetype
```python
omni.usd.is_usd_readable_filetype(filepath: str) -> bool
```
Whether the given file path is a supported readable USD file or not.
``` | 200 |
omni.usd.is_usd_writable_filetype.md | # is_usd_writable_filetype
## is_usd_writable_filetype
```python
omni.usd.is_usd_writable_filetype(filepath: str) -> bool
```
Whether the given file path is a supported writable USD file or not.
``` | 200 |
omni.usd.make_path_relative_to_current_edit_target.md | # make_path_relative_to_current_edit_target
## make_path_relative_to_current_edit_target
`omni.usd.make_path_relative_to_current_edit_target(url_path, stage=None)` | 164 |
omni.usd.md | # Omni.USD
Omni.USD is one of the core Kit APIs, and provides access to USD and USD-related application services such as:
- Events/Listeners
- Selection handling
- Access to the Omniverse USD Audio subsystem
- Access to the Omniverse Client Library, and handling of Omniverse Assets/URIs
- USD Layer handling
- A USDContext which provides convenient access to the main USDStage and its layers, as well as various Hydra, Renderer and Viewport related services
- MDL (Material Definition Language)
## More info
See omni.usd API Docs (part of Kit API Docs)
Note that we often refer to the Pixar USD Reference documentation - it’s docs describe the C++ API, not the Python API, but in most cases they are similar. For more information, it is often worthwhile to look at the USD source code - particularly unit tests and examples - for more specific guidance
Extensions - most of Kit is written as Python-based extensions. The source code for each of these is available by clicking on the folder icon in the Extension Manager when a specific extension is selected. For the most part, these can be modified on the fly and hot-reloaded. You can also step through them with a debugger (see Kit-SDK API Docs)
## omni.usd Commands
The USD-related functionality exposed in the Kit UI is partially implemented using Commands - for example most of the Viewport Interaction, Create/Edit Menus, right-click (Contextual) functionality available in the Stage and Layer widgets is command-based and using these will generate commands for most or all actions performed.
Example of Command to create a new prim on the current stage/layer (unlike USD itself, Kit will assume a certain context when working with USD Objects):
```python
import omni.kit.commands
ret = omni.kit.commands.execute('CreatePrim', prim_type='DistantLight', attributes={'angle': 1.0, 'intensity': 3000})
print(f"return value: {ret}")
```
Note that some of these operations are asynchronous, so you can’t necessarily execute a command and expect the result to be available in the next line of code (but maybe it will be…depending on how quickly it executes)
```python
# Synchronous creation of multiple prims
import omni.kit.commands
omni.usd.get_context().new_stage()
for x in range(0, 50):
ret = omni.kit.commands.execute('CreatePrim', prim_type='DistantLight', attributes={'angle': 1.0, 'intensity': 3000})
```
```python
stage = omni.usd.get_context().get_stage()
num_prims = len([p for p in stage.Traverse()])
print(f"num_prims: {num_prims}")
```
```python
# Asynchronous creation of multiple prims
import omni.kit.commands
import asyncio
async def create_many_lights():
omni.usd.get_context().new_stage()
for x in range(0, 50):
ret = omni.kit.commands.execute('CreatePrim', prim_type='DistantLight', attributes={'angle': 1.0, 'intensity': 3000})
await omni.kit.app.get_app().next_update_async()
stage = omni.usd.get_context().get_stage()
num_prims = len([p for p in stage.Traverse()])
print(f"num_prims: {num_prims}")
asyncio.ensure_future(create_many_lights())
```
There are a wide selection of other USD related commands, which you can inspect by using the `omni.kit.window.commands` extension.
This extension has a very primitive search functionality you can access by pressing the “Search commands” button.
Any commands invoked by running scripts, interactive use of Kit etc will be reflected in this window, and can all be copied and pasted into the script editor or your IDE and executed again.
Here’s an example which was pasted from an interactive session which creates a cone, duplicates it, moves one of the cones, then groups them under a single Xform node:
```python
import omni.kit.commands
from pxr import Gf, Usd
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform', prim_type='Cone')
omni.kit.commands.execute('SelectPrimsCommand', old_selected_paths=['/World/Cone'], new_selected_paths=[], expand_in_stage=True)
omni.kit.commands.execute('SelectPrimsCommand', old_selected_paths=[], new_selected_paths=['/World/Cone'], expand_in_stage=True)
omni.kit.commands.execute('CopyPrims', paths_from=['/World/Cone'], duplicate_layers=False, combine_layers=False)
omni.kit.commands.execute('TransformPrimCommand', path='/World/Cone_01', old_transform_matrix=Gf.Matrix4d(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0), new_transform_matrix=Gf.Matrix4d(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0))
```
0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 46.5615, 36.3054, -82.8669, 1.0),
time_code=Usd.TimeCode(),
had_transform_at_key=False
omni.kit.commands.execute('SelectPrimsCommand',
old_selected_paths=['/World/Cone_01'],
new_selected_paths=[],
expand_in_stage=True)
omni.kit.commands.execute('SelectPrimsCommand',
old_selected_paths=[],
new_selected_paths=['/World/defaultLight', '/World/Cone', '/World/Cone_01'],
expand_in_stage=True)
omni.kit.commands.execute('GroupPrims',
prim_paths=['/World/defaultLight', '/World/Cone', '/World/Cone_01'])
There are a large number of USD-related commands registered as part of various Kit extensions such as omni.usd, omni.usd.commands, omni.kit.property.transform etc….
These commands have a few things in common:
- They operate either on existing scene state (e.g the usdContext, selection state etc.) or take a set of input arguments
- Input arguments are generally POD type data which is easily serialisable/deserialisable and has a string representation
- Most are undoable
- Some have a “multiples” flavour e.g TransformPrim, TransformPrims which are similar except the multiples command often takes a list of prim paths as input rather than a single prim path, and executes the basic version of the Command multiple times
- They are written in python and the source code for each of them can be found in the extension that registered them, including any class/method documentation
- Some of them are “composite” commands that are a series of other commands grouped together in order e.g CreateAndBindMaterialFromLibrary
## omni.usd.Context and Stages
The `context` provides access to the application stage and layers, file i/o and other functionality
A Kit session has a single main USD Stage associated with it, which can be accessed like so:
```python
import omni.usd
main_stage = omni.usd.get_context().get_stage()
print(f"main_stage {type(main_stage)}, {main_stage}")
```
The returned stage is a pxr.Usd.Stage as defined in [Pixar USD Docs - Stage](https://graphics.pixar.com/usd/release/api/class_usd_stage.html)
so you can perform all of the same USD API operations as you would on any USD stage, such as:
```python
import omni.usd
main_stage = omni.usd.get_context().get_stage()
rootLayer = main_stage.GetRootLayer()
print(f"root_layer {rootLayer}")
```
see [User Docs - Stage](https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_stage.html)
## Async Operations
Kit works asynchronously for the most part, and the omni.usd API reflects this…..much of omni.usd functionality related to long-running/blocking operations like opening stages can be called asynchronously.
This uses standard Python 3.6 asyncio semantics, see [Python 3.6 asyncio docs](https://docs.python.org/3.6/library/asyncio.html)
For example here is how to open a stage using the async API
```python
import omni.usd
import asyncio
from omni.kit.usd_docs import variant_example_usd_scene
usd_context = omni.usd.get_context()
async def open_stage():
(result, error) = await omni.usd.get_context().open_stage_async(variant_example_usd_scene)
#Now that we've waited for the scene to open, we should be able to get the stage
```
```python
stage = omni.usd.get_context().get_stage()
print(f"opened stage {stage} with result {result}")
asyncio.ensure_future(open_stage())
```
For comparison, the following snippet will do the same, but synchronously
```python
import omni.usd
from omni.kit.usd_docs import variant_example_usd_scene
usd_context = omni.usd.get_context()
result = omni.usd.get_context().open_stage(variant_example_usd_scene)
stage = omni.usd.get_context().get_stage()
print(f"opened stage {stage} with result {result}")
```
## omni.usd Events
Once you want to start building USD related extensions in Kit, it can be very useful to know when certain things happen. Kit has an event-based model that allows you to to subscribe to specific events
To get a list of available stage events:
```python
import omni.usd
print(dir(omni.usd.StageEventType))
```
To register a callback that gets called when a new scene is created (This might be useful if you want your UI to refresh when the new scene is created)
```python
import carb.events
import omni.usd
context = omni.usd.get_context()
def on_stage_event(e: carb.events.IEvent):
print("event type", e.type)
if e.type == int(omni.usd.StageEventType.OPENED):
print("Stage Opened!")
stage_event_sub = (
omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(on_stage_event, name="My Subscription Name")
)
print(f"stage_event_sub {stage_event_sub}")
#Creating a new stage will trigger the callback above
context.new_stage()
```
## omni.usd Selection
Kit (via omni.usd) has native selection of USD prims, which is understood by USD-aware extensions such as:
- Kit Viewport
- Stage Widget
- Layer Widgets
- USD Property Windows
All of these Widgets/Windows will allow you to maniuplate the USD selection, and will reflect any existing selection
```python
import omni.kit
import omni.kit.commands
import omni.usd
import asyncio
async def create_then_select_cone():
'''
we need to create an async function if we need to await anywhere
'''
result, prim_path = omni.kit.commands.execute('CreateMeshPrimWithDefaultXform', prim_type='Cone')
print(f"Prim Path: {prim_path}")
# If you remove this, there's no guarantee that the mesh will be created before the next line is
# executed
await omni.kit.app.get_app().next_update_async()
selection = omni.usd.get_context().get_selection()
selection.clear_selected_prim_paths()
selection.set_selected_prim_paths([prim_path], False)
```
```python
print(f"selected prim paths are {selection.get_selected_prim_paths()}")
```
```python
import asyncio
asyncio.ensure_future(create_then_select_cone())
```
There is other selection related functionality, you can see some of it in the Edit->Select Menu
## Selection Commands
- SelectAll - Select all prims
- SelectHierarchy - Select the children (recursively) of any selected Prims
- SelectInvert - Select the Inverse of what’s currently selected
- SelectLeaf - Select the Leaf nodes of any currently selected USD prims
- SelectNone - Nullify the selection
- SelectParent - Select the parents nodes of any currently selected USD prims
- SelectSimilar - Select prims of the same prim type as any selected prims
- SelectPrimsCommand Select primitives
- SelectList - Set the selection based off a supplied list (This command requires a python list as it’s input)
## omni.usd Layers
See: User Docs - Layer Widget
the layer API allows you to get access to Layer related state e.g which layers are muted, locked etc.
This snippet shows if any of the layers used are locked
```python
import omni.usd
layers = omni.usd.get_context().get_layers()
used = layers.get_used_sublayers()
for u in used:
lock = layers.is_layer_locked(u)
print(f"{u} locked? {lock}")
``` | 11,497 |
omni.usd.merge_layers.md | # merge_layers
## merge_layers
```python
omni.usd.merge_layers(dst_layer_identifier: str, src_layer_identifier: str, dst_is_stronger_than_src: bool = True, src_layer_offset: float = 0.0, src_layer_scale: float = 1.0) -> bool
```
Merge source layer into target layer according to the strength order.
``` | 304 |
omni.usd.merge_prim_spec.md | # merge_prim_spec
## merge_prim_spec
```python
def merge_prim_spec(dst_layer_identifier: str, src_layer_identifier: str, prim_spec_path: str, dst_is_stronger_than_src: bool = True, target_prim_path: str = ''):
"""
Merge prim specs between layers.
"""
```
--- | 273 |
omni.usd.on_layers_saved_result.md | # on_layers_saved_result
## on_layers_saved_result
omni.usd.on_layers_saved_result(result: bool, err_msg: str, saved_layers: List[str], future: Future) | 152 |
omni.usd.OpaqueSharedHydraEngineContext.md | # OpaqueSharedHydraEngineContext
## OpaqueSharedHydraEngineContext
```python
class omni.usd.OpaqueSharedHydraEngineContext
```
Bases: `pybind11_object`
### Methods
```python
__init__(*args, **kwargs)
```
```python
def __init__(*args, **kwargs)
```
``` | 253 |
omni.usd.PickingMode.md | # PickingMode
## Class Overview
The `PickingMode` class is based on `pybind11_object`. It defines several members and methods related to selection modes in a user interface.
### Members
- **NONE**
- **RESET_AND_SELECT**
- **MERGE_SELECTION**
- **INVERT_SELECTION**
- **TRACK**
### Methods
- `__init__(self, value)`
### Attributes
- `INVERT_SELECTION`
- `MERGE_SELECTION`
- `NONE`
- `RESET_AND_SELECT`
- `TRACK`
- `name`
- `value`
| Method | Description |
| --- | --- |
| `__init__(self: omni.usd._usd.PickingMode, value: int) -> None` | |
| `property name` | | | 570 |
omni.usd.PrimCaching.md | # PrimCaching
## Methods
- `__init__(usd_type, stage[, on_changed])`
- `destroy()`
- `get_cache_state()`
- `get_stage()`
- `set_cache_state(state)`
on_changed = None | 167 |
omni.usd.readable_usd_dotted_file_exts.md | # readable_usd_dotted_file_exts
## omni.usd.readable_usd_dotted_file_exts
```python
def readable_usd_dotted_file_exts():
→ List[str]
```
Gets a list of file extensions about readable USD formats.
### Returns
A list of file extensions, like (‘usd’, ‘usda’, ‘usdc’, ‘live’).
### Return type
List[str] | 310 |
omni.usd.readable_usd_files_desc.md | # readable_usd_files_desc
## readable_usd_files_desc
Gets a description of all readable USD file formats.
### Returns
A description string, like “USD Files (`.usd; .usda;*.usdc;*.live)`
### Return type
str | 209 |
omni.usd.readable_usd_file_exts.md | # readable_usd_file_exts
## readable_usd_file_exts
Gets a list of file extensions (without dots) about readable USD formats.
### Returns
A list of file extensions (without dots), like (‘usd’, ‘usda’, ‘usdc’, ‘live’).
### Return type
List[str] | 246 |
omni.usd.readable_usd_file_exts_str.md | # readable_usd_file_exts_str
## readable_usd_file_exts_str
```python
omni.usd.readable_usd_file_exts_str() -> str
```
Gets a string that includes all readable USD file formats supported by Kit.
**Returns:**
A string includes all file extensions of readable USD formats, and is separated by “|”, like “usd|usda|usdc|live”.
**Return type:**
str
``` | 351 |
omni.usd.release_all_hydra_engines.md | # release_all_hydra_engines
## release_all_hydra_engines
```
## release_all_hydra_engines
```python
omni.usd.release_all_hydra_engines(context: omni.usd._usd.UsdContext = None) -> None | 186 |
omni.usd.remove_property.md | # remove_property
## remove_property
Removes specified property from the prim.
### Parameters
- **prim_path** (Union[str, Sdf.Path]) – Prim path.
- **property_name** (str) – Specified property name.
- **usd_context_or_stage** (Union[str, Stage] = '') –
# Usd.Stage
- Stage or UsdContext applies the changes to.
- It can be instance of Usd.Stage or context name. By default, it will apply the changes to the stage in default UsdContext. | 439 |
omni.usd.resolve_paths.md | # resolve_paths
## resolve_paths
```python
omni.usd.resolve_paths(src_layer_identifier: str, dst_layer_identifier: str, store_relative_path: bool = True, relative_to_src_layer: bool = False, copy_sublayer_offsets: bool = False) -> None
```
Resolve external paths in dst layer against base layer specified by src_layer_identifier.
``` | 335 |
omni.usd.resolve_prim_paths_references.md | # resolve_prim_paths_references
## resolve_prim_paths_references
```python
omni.usd.resolve_prim_paths_references(layer: str, old_prim_paths: List[str], new_prim_paths: List[str]) -> None
```
Resolve all prim paths reference to use new path. This is mainly used to remapping prim path reference after structure change of original prim.
### Parameters
- **layer** (`Sdf.Layer`) – Layer to resolve.
- **old_prim_paths** (`List[str]`) – Old prim paths.
- **new_prim_paths** (`list[str]`) – New prim paths that all old prim paths references will be replaced to. | 560 |
omni.usd.resolve_prim_path_references.md | # resolve_prim_path_references
## resolve_prim_path_references
Resolve all prim path reference to use new path. This is mainly used to remapping
prim path reference after structure change of original prim.
### Parameters
- **layer** (Sdf.Layer) – Layer to resolve.
- **old_prim_path** (str) – Old prim path.
- **new_prim_path** (str) – New prim path that all old prim path references will be replaced to. | 407 |
omni.usd.Selection.md | # Selection
## Class: omni.usd.Selection
**Bases:** `pybind11_object`
**Description:**
omni.usd.Selection manages all stage selections and provides APIs for querying/setting selections.
### Methods
- **`__init__(*args, **kwargs)`**
- Description:
- **`clear_selected_prim_paths(self, source)`**
- Description: Clears all selections.
- **`get_selected_prim_paths(self, source)`**
- Description: Gets selected prim paths.
- **`is_prim_path_selected(self, path, source)`**
- Description: Checks if a prim is selected or not.
- **`select_all_prims(self[, type_names])`**
- Description: Selects all prims with specific prim types.
- **`select_inverted_prims(self)`**
- Description: Selects all prims without the current selections.
| 方法名 | 描述 |
| --- | --- |
| `set_prim_path_selected` | Selects/Unselects single prim. |
| `set_selected_prim_paths` | Sets selected prim paths. |
### `__init__`
(self, *args, **kwargs)
### `SourceType`
Bases: `pybind11_object`
Selection source stage.
Members:
- USD : Selections from native USD stage.
- FABRIC : Selections from Fabric.
- ALL : Selections from both native USD stage and Fabric.
### `name`
property
### `clear_selected_prim_paths`
(self, source: omni.usd._usd.Selection.SourceType = <SourceType.USD: 1>) -> bool
Clears all selections.
Parameters:
- source (omni.usd.Selection.SourceType) – The source to be cleared. Selections are stored differently for Fabric. By default, it will check selections from native USD stage.
### `get_selected_prim_paths`
(self, source: omni.usd._usd.Selection.SourceType = <SourceType.USD: 1>) -> List[str]
Gets selected prim paths.
Parameters:
- source (omni.usd.Selection.SourceType) – The source to be cleared. Selections are stored differently for Fabric. By default, it will check selections from native USD stage.
<em>omni.usd.Selection.SourceType
) – The source to get selections. Selections are stored differently for Fabric. By default, it will check selections from native
USD stage.
<dt class="field-even">
Returns
<dd class="field-even">
<p>
List of selected prim paths.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.is_prim_path_selected">
<span class="sig-name descname">
<span class="pre">is_prim_path_selected
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">self:
<span class="pre">omni.usd._usd.Selection
,
<em class="sig-param">
<span class="n">
<span class="pre">path:
<span class="pre">str
,
<em class="sig-param">
<span class="n">
<span class="pre">source:
<span class="pre">omni.usd._usd.Selection.SourceType
<span class="pre">=
<span class="pre"><SourceType.USD:
<span class="pre">1>
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">→
<span class="sig-return-typehint">
<span class="pre">bool
<dd>
<p>Checks if a prim is selected or not.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>path
(<em>str
<li>
<p>
<strong>source
(<em>omni.usd.Selection.SourceType
USD stage.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.select_all_prims">
<span class="sig-name descname">
<span class="pre">select_all_prims
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">self:
<span class="pre">omni.usd._usd.Selection
,
<em class="sig-param">
<span class="n">
<span class="pre">type_names:
<span class="pre">object
<span class="pre">=
<span class="pre">None
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">→
<span class="sig-return-typehint">
<span class="pre">None
<dd>
<p>Selects all prims with specific prim types.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.select_inverted_prims">
<span class="sig-name descname">
<span class="pre">select_inverted_prims
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">self:
<span class="pre">omni.usd._usd.Selection
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">→
<span class="sig-return-typehint">
<span class="pre">None
<dd>
<p>Selects all prims without the current selections.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.set_prim_path_selected">
<span class="sig-name descname">
<span class="pre">set_prim_path_selected
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">self:
<span class="pre">omni.usd._usd.Selection
,
<em class="sig-param">
<span class="n">
<span class="pre">path:
<span class="pre">str
,
<em class="sig-param">
<span class="n">
<span class="pre">selected:
<span class="pre">bool
,
<em class="sig-param">
<span class="n">
<span class="pre">forcePrim:
<span class="pre">bool
,
<em class="sig-param">
<span class="n">
<span class="pre">clearSelected:
<span class="pre">bool
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">→
<span class="sig-return-typehint">
<span class="pre">None
<dd>
<p>Sets the selection status of a prim path.
### omni.usd.Selection.set_prim_path_selected
```python
set_prim_path_selected(
path: str,
selected: bool,
forcePrim: bool,
clearSelected: bool,
expandInStage: bool = True,
source: omni.usd._usd.Selection.SourceType = <SourceType.USD: 1>
) -> bool
```
Selects/Unselects single prim.
#### Parameters
- **path** (str) – Prim path to be selected.
- **selected** (bool) – Selected or unselected.
- **forcePrim** (bool) – Force it to be Prim Mode. When this option is false, it depends on the selection mode to decide the prim to be selected.
- **clearSelected** (bool) – Clears existing selections or not before selection.
- **expandInStage** (bool) – DEPRECATED.
- **source** (omni.usd.Selection.SourceType) – The source to be set. Selections are stored differently for Fabric. By default, it will check selections from native USD stage.
### omni.usd.Selection.set_selected_prim_paths
```python
set_selected_prim_paths(
self: omni.usd._usd.Selection,
paths: List[str],
expandInStage: bool = True,
source: omni.usd._usd.Selection.SourceType = <SourceType.USD: 1>
) -> bool
```
Sets selected prim paths.
#### Parameters
- **paths** (List[str]) – The list of prim paths to be selected.
- **expandInStage** (bool) – DEPRECATED.
- **source** (omni.usd.Selection.SourceType) – The source to be set. Selections are stored differently for Fabric. By default, it will check selections from native USD stage. | 6,618 |
omni.usd.Selection_omni.usd.Selection.md | # Selection
## Class: omni.usd.Selection
**Bases:** `pybind11_object`
omni.usd.Selection manages all stage selections and provides APIs for querying/setting selections.
### Methods
- **`__init__(*args, **kwargs)`**
- **`clear_selected_prim_paths(self, source)`**
- Clears all selections.
- **`get_selected_prim_paths(self, source)`****
- Gets selected prim paths.
- **`is_prim_path_selected(self, path, source)`**
- Checks if a prim is selected or not.
- **`select_all_prims(self[, type_names])`**
- Selects all prims with specific prim types.
- **`select_inverted_prims(self)`**
- Selects all prims without the current selections.
<table>
<tbody>
<tr class="row-odd">
<td>
<p>
<code>set_prim_path_selected
(self, path, selected, ...)
<td>
<p>
Selects/Unselects single prim.
<tr class="row-even">
<td>
<p>
<code>set_selected_prim_paths
(self, paths, ...)
<td>
<p>
Sets selected prim paths.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.__init__">
<span class="sig-name descname">
<span class="pre">
__init__
<span class="sig-paren">
(
<em class="sig-param">
<span class="o">
<span class="pre">
*
<span class="n">
<span class="pre">
args
,
<em class="sig-param">
<span class="o">
<span class="pre">
**
<span class="n">
<span class="pre">
kwargs
<span class="sig-paren">
)
<dd>
<dl class="py class">
<dt class="sig sig-object py" id="omni.usd.Selection.SourceType">
<em class="property">
<span class="pre">
class
<span class="w">
<span class="sig-name descname">
<span class="pre">
SourceType
<dd>
<p>
Bases:
<code>pybind11_object
<blockquote>
<div>
<p>
Selection source stage.
<p>
Members:
<blockquote>
<div>
<p>
USD : Selections from native USD stage.
<p>
FABRIC : “Selections from Fabric.
<p>
ALL : Selections from both native USD stage and Fabric.
<dl class="py property">
<dt class="sig sig-object py" id="omni.usd.Selection.SourceType.name">
<em class="property">
<span class="pre">
property
<span class="w">
<span class="sig-name descname">
<span class="pre">
name
<dd>
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.clear_selected_prim_paths">
<span class="sig-name descname">
<span class="pre">
clear_selected_prim_paths
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self:
<span class="pre">
omni.usd._usd.Selection
,
<em class="sig-param">
<span class="n">
<span class="pre">
source:
<span class="pre">
omni.usd._usd.Selection.SourceType
<span class="pre">
=
<span class="pre">
<SourceType.USD:
<span class="pre">
1>
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
bool
<dd>
<p>
Clears all selections.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
source
(
<em>
omni.usd.Selection.SourceType
) – The source to be cleared. Selections are stored differently for Fabric. By default, it will check selections from native
USD stage.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.get_selected_prim_paths">
<span class="sig-name descname">
<span class="pre">
get_selected_prim_paths
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self:
<span class="pre">
omni.usd._usd.Selection
,
<em class="sig-param">
<span class="n">
<span class="pre">
source:
<span class="pre">
omni.usd._usd.Selection.SourceType
<span class="pre">
=
<span class="pre">
<SourceType.USD:
<span class="pre">
1>
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
List
<span class="p">
<span class="pre">
[
<span class="pre">
str
<span class="p">
<span class="pre">
]
<dd>
<p>
Gets selected prim paths.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
source
(
<em>
omni.usd.Selection.SourceType
) – The source to be cleared. Selections are stored differently for Fabric. By default, it will check selections from native
USD stage.
<em>
omni.usd.Selection.SourceType
) – The source to get selections. Selections are stored differently for Fabric. By default, it will check selections from native
USD stage.
<dt class="field-even">
Returns
<dd class="field-even">
<p>
List of selected prim paths.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.is_prim_path_selected">
<span class="sig-name descname">
<span class="pre">
is_prim_path_selected
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self:
<span class="pre">
omni.usd._usd.Selection
,
<em class="sig-param">
<span class="n">
<span class="pre">
path:
<span class="pre">
str
,
<em class="sig-param">
<span class="n">
<span class="pre">
source:
<span class="pre">
omni.usd._usd.Selection.SourceType
<span class="pre">
=
<span class="pre">
<SourceType.USD:
<span class="pre">
1>
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
bool
<a class="headerlink" href="#omni.usd.Selection.is_prim_path_selected" title="Permalink to this definition">
<dd>
<p>
Checks if a prim is selected or not.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
path
(<em>str
<li>
<p>
<strong>
source
(<em>omni.usd.Selection.SourceType
USD stage.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.select_all_prims">
<span class="sig-name descname">
<span class="pre">
select_all_prims
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<a class="reference internal" href="#omni.usd.Selection" title="omni.usd._usd.Selection">
<span class="pre">
omni.usd._usd.Selection
,
<em class="sig-param">
<span class="n">
<span class="pre">
type_names
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
object
<span class="w">
<span class="o">
<span class="pre">
=
<span class="w">
<span class="default_value">
<span class="pre">
None
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<a class="headerlink" href="#omni.usd.Selection.select_all_prims" title="Permalink to this definition">
<dd>
<p>
Selects all prims with specific prim types.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.select_inverted_prims">
<span class="sig-name descname">
<span class="pre">
select_inverted_prims
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<a class="reference internal" href="#omni.usd.Selection" title="omni.usd._usd.Selection">
<span class="pre">
omni.usd._usd.Selection
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<a class="headerlink" href="#omni.usd.Selection.select_inverted_prims" title="Permalink to this definition">
<dd>
<p>
Selects all prims without the current selections.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.Selection.set_prim_path_selected">
<span class="sig-name descname">
<span class="pre">
set_prim_path_selected
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self:
<span class="pre">
omni.usd._usd.Selection
,
<em class="sig-param">
<span class="n">
<span class="pre">
path:
<span class="pre">
str
,
<em class="sig-param">
<span class="n">
<span class="pre">
selected:
<span class="pre">
bool
,
<em class="sig-param">
<span class="n">
<span class="pre">
forcePrim:
<span class="pre">
bool
,
<em class="sig-param">
<span class="n">
<span class="pre">
clearSelected:
<span class="pre">
bool
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<a class="headerlink" href="#omni.usd.Selection.set_prim_path_selected" title="Permalink to this definition">
<dd>
<p>
Sets the selection status of a prim path.
### set_prim_path_selected
```python
set_prim_path_selected(
path: str,
selected: bool,
forcePrim: bool,
clearSelected: bool,
expandInStage: bool = True,
source: omni.usd._usd.Selection.SourceType = <SourceType.USD: 1>
) -> bool
```
Selects/Unselects single prim.
**Parameters**
- **path** (str) – Prim path to be selected.
- **selected** (bool) – Selected or unselected.
- **forcePrim** (bool) – Force it to be Prim Mode. When this option is false, it depends on the selection mode to decide the prim to be selected.
- **clearSelected** (bool) – Clears existing selections or not before selection.
- **expandInStage** (bool) – DEPRECATED.
- **source** (omni.usd.Selection.SourceType) – The source to be set. Selections are stored differently for Fabric. By default, it will check selections from native USD stage.
### set_selected_prim_paths
```python
set_selected_prim_paths(
self: omni.usd._usd.Selection,
paths: List[str],
expandInStage: bool = True,
source: omni.usd._usd.Selection.SourceType = <SourceType.USD: 1>
) -> bool
```
Sets selected prim paths.
**Parameters**
- **paths** (List[str]) – The list of prim paths to be selected.
- **expandInStage** (bool) – DEPRECATED.
- **source** (omni.usd.Selection.SourceType) – The source to be set. Selections are stored differently for Fabric. By default, it will check selections from native USD stage. | 9,969 |
omni.usd.set_attr_val.md | # set_attr_val
## set_attr_val
```python
omni.usd.set_attr_val(attr: Attribute, val: Any, time_code = Usd.TimeCode.Default(), auto_target_layer: bool = True)
```
Deprecated. See `set_prop_val()` instead. | 212 |
omni.usd.set_edit_target_by_identifier.md | # set_edit_target_by_identifier
## set_edit_target_by_identifier
```python
omni.usd.set_edit_target_by_identifier(stage: Stage, layer_identifier: str)
```
Sets the edit target of stage by layer identifier.
### Parameters
- **stage** (`Usd.Stage`) – Stage handle
- **layer_identifier** (`str`) – Layer identifier
### Returns
True if success, false if layer cannot be found, or layer is not in the layer stack of stage. | 420 |
omni.usd.set_prop_val.md | # set_prop_val
## set_prop_val
Sets the value of property.
### Parameters
- **prop** (`Usd.Property`) – Property handle.
- **val** (`Any`) – Value of property.
- **time_code** (`Usd.TimeCode`) – Time code to set, and it’s Usd.TimeCode.Default() by default.
- **auto_target_layer** (`bool`) – Default is True. If it’s true, it will be authored into the sesison layer if
the prim of the property is defined in the session layer. If it’s not defined in the session layer,
it will find the property inside the session layer to check if there are overrides.
If overrides are found, the value will be authored into the found layer instead.
Otherwise, it will be authored into the current edit target. | 696 |
omni.usd.StageEventType.md | # StageEventType
## StageEventType
```python
class omni.usd.StageEventType(pybind11_object)
```
Stage Event Type.
Members:
- SAVING : Starting to save stage.
- SAVED : Stage saved successfully.
- SAVE_FAILED : Stage save failed.
- OPENING : Starting to open stage.
- OPENED : Stage open finished.
- OPEN_FAILED : Stage open failed.
- CLOSING : Starting to close stage.
- CLOSED : Stage closed successfully.
- SELECTION_CHANGED : Stage selections changed.
- ASSETS_LOADED : Assets (textures or materials) loaded successfully.
- ASSETS_LOAD_ABORTED : Assets (textures or materials) load aborted.
- GIZMO_TRACKING_CHANGED : DEPRECATED.
- MDL_PARAM_LOADED : Some MDL materials finish its params loading by material watcher.
- SETTINGS_LOADED : Render settings loaded.
- SETTINGS_SAVING : Starting to save render settings.
- OMNIGRAPH_START_PLAY : OmniGraph is starting to play.
- OMNIGRAPH_STOP_PLAY : OmniGraph is stopped to play.
- SIMULATION_START_PLAY : Physx Simulation starts playing.
- SIMULATION_STOP_PLAY : Physx Simulation stopped.
- ANIMATION_START_PLAY : Timeline starts playing.
- ANIMATION_STOP_PLAY : Timeline stopped.
- DIRTY_STATE_CHANGED : Stage dirtiness state is changed. It’s sent when stage adds the first unsaved change, or after stage finishes it saving.
- ASSETS_LOADING : Assets are in progress of loading (textures or materials).
- ACTIVE_LIGHT_COUNTS_CHANGED : Count of active lights is changed.
- HIERARCHY_CHANGED : Some prims are resynced in the stage.
- HYDRA_GEOSTREAMING_STARTED
- HYDRA_GEOSTREAMING_STOPPED
- HYDRA_GEOSTREAMING_STOPPED_NOT_ENOUGH_MEM
- HYDRA_GEOSTREAMING_STOPPED_AT_LIMIT
### Methods
- `__init__(self, value)`
### Attributes
| ACTIVE_LIGHT_COUNTS_CHANGED |
|-----------------------------|
| ANIMATION_START_PLAY |
|-----------------------------|
| ANIMATION_STOP_PLAY |
|-----------------------------|
| ASSETS_LOADED |
|-----------------------------|
| ASSETS_LOADING |
|-----------------------------|
| ASSETS_LOAD_ABORTED |
|-----------------------------|
| CLOSED |
|-----------------------------|
| CLOSING |
|-----------------------------|
| DIRTY_STATE_CHANGED |
|-----------------------------|
| GIZMO_TRACKING_CHANGED |
|-----------------------------|
| HIERARCHY_CHANGED |
|-----------------------------|
| HYDRA_GEOSTREAMING_STARTED |
|-----------------------------|
| HYDRA_GEOSTREAMING_STOPPED |
|-----------------------------|
| HYDRA_GEOSTREAMING_STOPPED_AT_LIMIT |
|-----------------------------|
| HYDRA_GEOSTREAMING_STOPPED_NOT_ENOUGH_MEM |
|-----------------------------|
| MDL_PARAM_LOADED |
|-----------------------------|
| OMNIGRAPH_START_PLAY |
|-----------------------------|
| OMNIGRAPH_STOP_PLAY |
|-----------------------------|
| OPENED |
|-----------------------------|
| OPENING |
|-----------------------------|
| OPEN_FAILED |
|-----------------------------|
| SAVED |
|-----------------------------|
| SAVE_FAILED |
|-----------------------------|
| SAVING |
|-----------------------------|
| Selection Changed |
| --- |
| SETTINGS_LOADED |
| SETTINGS_SAVING |
| SIMULATION_START_PLAY |
| SIMULATION_STOP_PLAY |
| name |
| value |
### omni.usd.StageEventType.__init__
```python
__init__(self: omni.usd._usd.StageEventType, value: int) -> None
```
### omni.usd.StageEventType.name
```
property name
``` | 3,549 |
omni.usd.StageRenderingEventType.md | # StageRenderingEventType
## StageRenderingEventType
Bases: `pybind11_object`
Rendering Events.
Members:
- NEW_FRAME
### Methods
- `__init__(self, value)`
### Attributes
- `NEW_FRAME`
- `name`
- `value`
#### `__init__(self, value)`
- `self : omni.usd._usd.StageRenderingEventType`
- `value`
:
int
)
→ None
property
name | 330 |
omni.usd.StageState.md | # StageState
## Overview
Stage states.
### Members
- CLOSED : Stage is closed.
- CLOSING : Stage is in progress of closing.
- OPENING : Stage is in progress of opening.
- OPENED : Stage is opened.
### Methods
- `__init__(self, value)`
### Attributes
- `CLOSED`
- `CLOSING`
- `OPENED`
- `OPENING`
- `name`
- `value`
| | |
|---|---|
| | |
```
```markdown
### omni.usd.StageState.__init__
__init__(self: omni.usd._usd.StageState, value: int) -> None
```
```markdown
### omni.usd.StageState.name
property name
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
---
```
```markdown
--- | 11,037 |
omni.usd.stitch_prim_specs.md | # stitch_prim_specs
## stitch_prim_specs
```python
omni.usd.stitch_prim_specs(stage: Stage, prim_path: Union[str, Path], target_layer: Layer, target_prim_path: str = None, include_references_or_payloads = False)
```
Sitches prim specs specified by path scattered in all sublayers and all its children to target layer.
### Parameters
- **stage** (Usd.Stage) – Stage handle.
- **prim_path** (str) – Prim path to be stitched.
- **target_layer** (Sdf.Layer) – Target layer to save the stitching results.
## 参数说明
- **target_prim_path** (`str`) – Target prim path. If it’s empty or none, it will be the prim_path.
- **include_references_or_payloads** – If prim is defined inside references or payloads, and this is True, it will also stitch the defs from references or payloads, too. | 782 |
omni.usd.TransformHelper.md | # TransformHelper
## Methods
- `__init__()`
- `add_to_attr_order(attr_order, path[, ...])`
- `get_transform_attr(attrs)`
- `is_common_attr(source_attr)`
- `is_transform(source_path)`
- `order_attrs(attrs, order)` | 214 |
omni.usd.UsdContext.get_stage_event_stream_omni.usd.UsdContext.md | # UsdContext
## UsdContext
```python
class omni.usd.UsdContext
```
### Methods
| Method | Description |
|--------|-------------|
| `__init__(*args, **kwargs)` | |
| `add_to_pending_creating_mdl_paths(self [, ...])` | Internal. |
| `attach_stage_async(stage)` | Asynchronous version of `omni.usd.UsdContext.attach_stage_with_callback()`. |
| `attach_stage_with_callback(self, stage_id [, ...])` | Attaches an existing stage asynchronously. |
| `can_close_stage(self)` | Whether the current stage can be closed or not. |
| `can_open_stage(self)` | |
| Method | Description |
| ------ | ----------- |
| can_open_stage (self) | Whether a new stage can be opened or not. |
| can_save_stage (self) | Whether the current stage can be saved or not. |
| close_stage (self[, on_finish_fn]) | Closes the current stage synchronously. |
| close_stage_async () | Asynchronous version of omni.usd.UsdContext.close_stage_with_callback(). |
| close_stage_with_callback (self, on_finish_fn) | Closes the current stage asynchronously. |
| compute_path_world_bounding_box (self, arg0) | Compute world bound box for specified prim. |
| compute_path_world_transform (self, arg0) | Compute world transform for specified prim. |
| disable_save_to_recent_files (self) | |
| enable_save_to_recent_files (self) | |
| export_as_stage (self, url[, on_finish_fn]) | Export stage with all prims flattened synchronously, and it will include contents from session layer also. |
| export_as_stage_async (url) | Asynchronous version of omni.usd.UsdContext.export_as_stage_with_callback(). |
| export_as_stage_with_callback (self, url, ...) | Export stage with all prims flattened asynchronously, and it will include contents from session layer also. |
| get_attached_hydra_engine_names (self) | |
| get_geometry_instance_path (self, arg0) | |
| get_name (self) | |
- `get_name(self)`
- Gets the name of the context.
- `get_rendering_event_stream(self)`
- Gets the rendering event stream.
- `get_selection(self)`
- Gets the selection interface.
- `get_stage()`
- Gets current opened `pxr.Usd.Stage`.
- `get_stage_audio_manager(self)`
-
- `get_stage_event_stream(self)`
- Gets the stage event stream.
- `get_stage_id(self)`
- Gets the UsdStage Id that can be queried with Usd.StageCache.
- `get_stage_loading_status(self)`
- Gets the stage loading status.
- `get_stage_state(self)`
- Gets the current stage state.
- `get_stage_url(self)`
- Gets the Stage url.
- `get_timeline(self)`
- Gets the timeline interface.
- `get_timeline_name(self)`
- Gets current timeline used in this context.
- `has_pending_edit(self)`
- Whether it has unsaved edits or not.
- `is_new_stage(self)`
- Whether the current stage (root layer) is anonymous or not.
- `is_omni_stage(self)`
- Whether the URL of the current stage (root layer) is prefixed with 'omniverse:'.
- `is_writable(self)`
-
| Method | Description |
| ------ | ----------- |
| `load_mdl_parameters_for_prim_async(prim[, ...])` | Internal. |
| `load_render_settings_from_stage(self, arg0)` | Loads render settings from stage. |
| `new_stage([load_set])` | |
| `new_stage_async([load_set])` | Asynchronous version of `omni.usd.UsdContext.new_stage_with_callback()`. |
| `new_stage_with_callback([fn, load_set])` | Asynchronous version of `omni.usd.UsdContext.new_stage()` that supports to customize load set of new stage. |
| `next_frame_async([inViewportId])` | Wait for frame complete event from Kit for specific viewport. |
| `next_stage_event_async()` | Wait for next stage event of omni.usd. |
| `next_usd_async([inViewportId])` | Wait for frame complete event from Kit for specific viewport. |
| `open_stage(self, url, on_finish_fn, str], ...)` | Opens a stage synchronously. |
| `open_stage_async(url[, load_set, ...])` | Asynchronous version of `omni.usd.UsdContext.open_stage_with_callback()`. |
| `open_stage_with_callback(self, url, ...)` | Opens a stage asynchronously. |
| `open_stage_with_session_layer(self, url, ...)` | Opens a stage asynchronously with specified session layer. |
| `register_selection_group(self)` | Registers a selection group. |
| `remove_all_hydra_engines(self)` | |
remove_all_hydra_engines (self)
reopen_stage (self, on_finish_fn, str, ...)
Re-opens the current stage synchronously.
reopen_stage_async ([load_set])
Asynchronous version of omni.usd.UsdContext.reopen_stage_with_callback().
reopen_stage_with_callback (self, ...)
Re-opens the current stage asynchronously.
save_as_stage (self, url[, on_finish_fn])
Saves the current stage to another location synchronously.
save_as_stage_async (url)
Asynchronous version of omni.usd.UsdContext.save_as_stage_with_callback().
save_as_stage_with_callback (self, url, ...)
Saves the current stage to another location asynchronously.
save_layers (self, new_root_layer_path, ...)
Saves specified layers (only ones in the local layer stack) synchronously.
save_layers_async (new_root_layer_path, ...)
Asynchronous version of omni.usd.UsdContext.save_layers_with_callback().
save_layers_with_callback (self, ...)
Saves specified layers (only ones in the local layer stack) asynchronously.
save_render_settings_to_current_stage (self)
Saves render settings into the current stage.
save_stage (self[, on_finish_fn])
Saves the current stage (only layers in the local layer stack) synchronously.
save_stage_async ()
Asynchronous version of omni.usd.UsdContext.save_stage_with_callback().
save_stage_with_callback (self, ...)
Saves the current stage asynchronously.
| Method | Description |
| ------ | ----------- |
| `save_stage_with_callback(self, on_finish_fn)` | Saves the current stage asynchronously. |
| `selection_changed_async()` | Wait for selection to be changed. |
| `set_pending_edit(self, arg0)` | Set or clear the stage dirtiness state manually no matter if it has pending edits to save. |
| `set_pickable(self, arg0, arg1)` | Sets the pickable state for a prim. |
| `set_selection_group(self, groupId, path)` | Assigns the prim to specified selection group. |
| `set_selection_group_outline_color(self, ...)` | Sets the outline color of the selection group. |
| `set_selection_group_shade_color(self, ...)` | Sets the shade color of the selection group. |
| `set_timeline(self[, name])` | Sets the timeline for this context. |
| `try_cancel_save(self)` | Try to cancel the saving process. |
### omni.usd.UsdContext.__init__(*args, **kwargs)
- Initializes the UsdContext.
### omni.usd.UsdContext.add_to_pending_creating_mdl_paths(self, path: str = '', recreate: bool = False)
- Adds a path to the pending creation list for MDL paths.
### add_to_pending_creating_mdl_paths
Internal.
### attach_stage_async
Asynchronous version of `omni.usd.UsdContext.attach_stage_with_callback()`. Attaches an opened stage to the context.
#### Parameters
- **stage** (`pxr.Usd.Stage`) – The instance of UsdStage.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, and
- the second one tells the error message if the operation is failed.
#### Return type
- (bool, str)
### attach_stage_with_callback
Attaches an existing stage asynchronously.
Parameters
----------
- **stage_id** (`long int`) – The stage id that can be queried with pxr.UsdUtils.StageCache.Get().Find.
- **on_finish_fn** (`Callable[[bool, str], None]`) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
can_close_stage(self: omni.usd._usd.UsdContext) -> bool
------------------------------------------------------
Whether the current stage can be closed or not.
can_open_stage(self: omni.usd._usd.UsdContext) -> bool
-----------------------------------------------------
Whether a new stage can be opened or not.
can_save_stage(self: omni.usd._usd.UsdContext) -> bool
-----------------------------------------------------
Whether the current stage can be saved or not.
close_stage(self: omni.usd._usd.UsdContext, on_finish_fn: Callable[[bool, str], None] = None)
--------------------------------------------------------------------------------------------
### close_stage
Closes the current stage synchronously.
#### Parameters
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
#### Returns
- Successful or not.
### close_stage_async
Asynchronous version of `omni.usd.UsdContext.close_stage_with_callback()`. Closes the current stage.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, and
- the second one tells the error message if the operation is failed.
#### Return type
- (bool, str)
### close_stage_with_callback
Closes the current stage asynchronously.
#### Parameters
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
### compute_path_world_bounding_box
## omni.usd._usd.UsdContext
### compute_path_world_bounding_box(self: omni.usd._usd.UsdContext, arg0: str) -> Tuple[carb::Double3, carb::Double3]
- Compute world bound box for specified prim. Unlike using USD API directly, it speeds up bound box computation with cache or Fabric when it’s enabled.
### compute_path_world_transform(self: omni.usd._usd.UsdContext, arg0: str) -> Annotated[List[float], FixedSize(16)]
- Compute world transform for specified prim. Unlike using USD API directly, it speeds up transform computation with cache.
### disable_save_to_recent_files(self: omni.usd._usd.UsdContext) -> None
### enable_save_to_recent_files(self: omni.usd._usd.UsdContext) -> None
### export_as_stage(self: omni.usd._usd.UsdContext, url: str, on_finish_fn: Callable[[bool], None]) -> None
### export_as_stage
Export stage with all prims flattened synchronously, and it will include contents from session layer also.
#### Parameters
- **url** (str) – New location to save the exported stage.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
#### Returns
- Successful or not.
### export_as_stage_async
Asynchronous version of `omni.usd.UsdContext.export_as_stage_with_callback()`. Flattens and exports the current stage.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, and the second one tells the error message if the operation is failed.
- Return type: (bool, str)
### export_as_stage_with_callback
### omni.usd.UsdContext.export_as_stage_with_callback
**Parameters**
- **url** (`str`) – New location to save the exported stage.
- **on_finish_fn** (`Callable[[bool, str], None]`) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
### omni.usd.UsdContext.get_attached_hydra_engine_names
### omni.usd.UsdContext.get_geometry_instance_path
### omni.usd.UsdContext.get_name
Gets the name of the context.
### omni.usd.UsdContext.get_rendering_event_stream
- **StageRenderingEventType**
- Gets the rendering event stream. See [StageRenderingEventType](#) for more details.
- **get_selection**
- Gets the selection interface. See [Selection](#) for more details.
- **get_stage**
- Gets current opened `pxr.Usd.Stage`.
- **get_stage_audio_manager**
- Gets the stage audio manager.
- **get_stage_event_stream**
- Gets the stage event stream. See [StageEventType](#) for more details.
- **get_stage_id**
- Gets the UsdStage Id that can be queried with Usd.StageCache.
- **get_stage_loading_status**
- Gets the stage loading status.
### get_stage_loading_status
Gets the stage loading status.
#### Returns
A tuple that the first element tells the current loading message, the second element tells how many files are loaded already, and the third one tells the total files to be loaded.
#### Return type
(str, int, int)
### get_stage_state
Gets the current stage state. See `StageState` for more details.
### get_stage_url
Gets the Stage url. The URL can be used as layer identifier to query layer handle from USD Layer Registry.
### get_timeline
Gets the timeline interface. See `omni.timeline` for more details.
### get_timeline_name
Gets current timeline used in this context.
### has_pending_edit
### omni.usd.UsdContext.has_pending_edit
```python
has_pending_edit(self: omni.usd._usd.UsdContext) -> bool
```
Whether it has unsaved edits or not.
### omni.usd.UsdContext.is_new_stage
```python
is_new_stage(self: omni.usd._usd.UsdContext) -> bool
```
Whether the current stage (root layer) is anonymous or not.
### omni.usd.UsdContext.is_omni_stage
```python
is_omni_stage(self: omni.usd._usd.UsdContext) -> bool
```
Whether the URL of the current stage (root layer) is prefixed with ‘omniverse:’.
### omni.usd.UsdContext.is_writable
```python
is_writable(self: omni.usd._usd.UsdContext) -> bool
```
### omni.usd.UsdContext.load_mdl_parameters_for_prim_async
```python
async load_mdl_parameters_for_prim_async(prim, recreate: bool = False)
```
Internal.
### omni.usd.UsdContext.load_render_settings_from_stage
```python
load_render_settings_from_stage(self: omni.usd._usd.UsdContext, arg0: int)
```
### omni.usd.UsdContext.load_render_settings_from_stage
Loads render settings from stage.
### omni.usd.UsdContext.new_stage_async
Asynchronous version of `omni.usd.UsdContext.new_stage_with_callback()`. Creates a new stage with anonymous root layer.
#### Parameters
- **load_set** (`omni.usd.UsdContextInitialLoadSet`) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, and the second one tells the error message if the operation is failed.
#### Return type
(bool, str)
### omni.usd.UsdContext.new_stage_with_callback
Asynchronous version of `omni.usd.UsdContext.new_stage()` that supports to customize load set of new stage.
### omni.usd.UsdContext.next_frame_async
Wait for frame complete event from Kit for specific viewport.
### omni.usd.UsdContext.next_stage_event_async
### omni.usd.UsdContext.next_stage_event_async
Wait for next stage event of omni.usd.
### omni.usd.UsdContext.next_usd_async
async next_usd_async(inViewportId = 0) → None
Wait for frame complete event from Kit for specific viewport.
### omni.usd.UsdContext.open_stage
open_stage(self: omni.usd._usd.UsdContext, url: str, on_finish_fn: Callable[[bool, str], None] = None, load_set: omni.usd._usd.UsdContextInitialLoadSet = <UsdContextInitialLoadSet.LOAD_ALL: 0>) → bool
Opens a stage synchronously.
#### Parameters
- **url** (str) – The stage URL that can be resolved.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (omni.usd.UsdContextInitialLoadSet) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
#### Returns
Successful or not.
### omni.usd.UsdContext.open_stage_async
async open_stage_async(url: str, load_set: ~omni.usd._usd.UsdContextInitialLoadSet = <UsdContextInitialLoadSet.LOAD_ALL: 0>, session_layer_url: ~typing.Optional[str] = None) → Tuple[bool]
### open_stage_async
Asynchronous version of `omni.usd.UsdContext.open_stage_with_callback()`. Opens a new stage.
#### Parameters
- **url** (str) – Stage URL to open.
- **load_set** (omni.usd.UsdContextInitialLoadSet) – If it’s to open all payloads or none.
- **session_layer_url** (str) – Specified session layer.
#### Returns
A tuple where the first element tells whether the operation is successful or not, and the second one tells the error message if the operation is failed.
#### Return type
(bool, str)
### open_stage_with_callback
Opens a stage asynchronously.
#### Parameters
- **url** (str) – The stage URL that can be resolved.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (omni.usd.UsdContextInitialLoadSet) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
### open_stage_with_session_layer
Opens a stage asynchronously with specified session layer.
#### Parameters
- **url** (str) – The stage URL that can be resolved.
- **session_layer_url** (str) – Specified session layer.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (omni.usd.UsdContextInitialLoadSet) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
## Parameters
- **url** (`str`) – The stage URL that can be resolved.
- **session_layer_url** (`str`) – The specified session layer URL.
- **on_finish_fn** (`Callable[[bool, str], None]`) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (`omni.usd.UsdContextInitialLoadSet`) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
## register_selection_group
```python
def register_selection_group(self: omni.usd._usd.UsdContext) -> int:
```
Registers a selection group. Prims can be assigned to selection group with customized outline colors than the default. It supports 255 selection groups at most.
## remove_all_hydra_engines
```python
def remove_all_hydra_engines(self: omni.usd._usd.UsdContext) -> None:
```
## reopen_stage
```python
def reopen_stage(self: omni.usd._usd.UsdContext, on_finish_fn: Callable[[bool, str], None] = None, load_set: omni.usd._usd.UsdContextInitialLoadSet = <UsdContextInitialLoadSet.LOAD_ALL: 0>) -> bool:
```
Re-opens the current stage synchronously.
### Parameters
- **on_finish_fn** (`Callable[[bool, str], None]`) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (`omni.usd.UsdContextInitialLoadSet`) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
Successful or not.
### reopen_stage_async
```python
async reopen_stage_async(load_set: ~omni.usd._usd.UsdContextInitialLoadSet = <UsdContextInitialLoadSet.LOAD_ALL: 0>) -> Tuple[bool, str]
```
Asynchronous version of `omni.usd.UsdContext.reopen_stage_with_callback()`. Re-opens the current stage.
#### Parameters
- **load_set** (`omni.usd.UsdContextInitialLoadSet`) – If it’s to open all payloads or none.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, and
- the second one tells the error message if the operation is failed.
#### Return type
- (bool, str)
### reopen_stage_with_callback
```python
reopen_stage_with_callback(self: omni.usd._usd.UsdContext, on_finish_fn: Callable[[bool, str], None], load_set: omni.usd._usd.UsdContextInitialLoadSet = <UsdContextInitialLoadSet.LOAD_ALL: 0>) -> bool
```
Re-opens the current stage asynchronously.
#### Parameters
- **on_finish_fn** (`Callable[[bool, str], None]`) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (`omni.usd.UsdContextInitialLoadSet`) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
### save_as_stage
```python
async def save_as_stage(
url: str,
on_finish_fn: Callable[[bool, str, List[str]], None] = None
) -> bool:
```
Saves the current stage to another location synchronously.
#### Parameters
- **url** (str) – New location to save the current stage.
- **on_finish_fn** (Callable[[bool, str, List[str]], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
#### Returns
Successful or not.
### save_as_stage_async
```python
async def save_as_stage_async(url: str) -> Tuple[bool, str]:
```
Asynchronous version of `omni.usd.UsdContext.save_as_stage_with_callback()`. Saves the current stage to a new location.
#### Parameters
- **url** (str) – New location to save the current stage.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, and
- the second one tells the error message if the operation is failed.
#### Return type
(bool, str)
### save_as_stage_with_callback
```python
def save_as_stage_with_callback(self: omni.usd._usd.UsdContext, url: str, on_finish_fn: Callable[[bool, str, List[str]], None] = None) -> Tuple[bool, str]:
```
Saves the current stage to a new location with a callback.
#### Parameters
- **self** (omni.usd._usd.UsdContext) – The context object.
- **url** (str) – New location to save the current stage.
- **on_finish_fn** (Callable[[bool, str, List[str]], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, and
- the second one tells the error message if the operation is failed.
### save_as_stage_with_callback
Saves the current stage to another location asynchronously.
**Parameters:**
- **url** (str) – New location to save the current stage.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
```
### save_layers
Saves the current stage to another location asynchronously.
**Parameters:**
- **new_root_layer_path** (str) – New location to save the current stage.
- **layer_identifiers** (List[str]) – List of layer identifiers.
- **on_finish_fn** (Callable[[bool, str, List[str]], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
```
<dt>
<p>
Saves specified layers (only ones in the local layer stack) synchronously.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
new_root_layer_path
(
<em>
str
) – New location for root layer if it’s to save-as the current stage. If it’s empty, it will save specified layers only.
<li>
<p>
<strong>
layer_identifiers
(
<em>
List
<em>
[
<em>
str
<em>
]
) – List of layer identifiers to be saved.
<li>
<p>
<strong>
on_finish_fn
(
<em>
Callable
<em>
[
<em>
[
<em>
bool
<em>
,
<em>
str
<em>
,
<em>
List
<em>
[
<em>
str
<em>
]
<em>
]
<em>
,
<em>
None
<em>
]
) – Finish callback that the first param is to tell if the operation is successful, the second one tells the error message if it’s faled and
the third param is the list of layer identifiers that are saved successfully.
<dt class="field-even">
Returns
<dd class="field-even">
<p>
Successful or not.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.save_layers_async">
<p>
Asynchronous version of
<code>
omni.usd.UsdContext.save_layers_with_callback()
. Saves specified layers.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
new_root_layer_path
(
<em>
str
) – New location for root layer if it’s to save-as the current stage. If it’s empty, it will save specified layers only.
<li>
<p>
<strong>
layer_identifiers
(
<em>
List
<em>
[
<em>
str
<em>
]
) – List of layer identifiers to be saved.
<dt class="field-even">
Returns
<dd class="field-even">
<p>
<dl class="simple">
<dt>
A tuple where the first element tells whether the operation is successful or not, the second one tells the error message if it’s faled and
<dd>
<p>
the third param is the list of layer identifiers that are saved successfully.
<dt class="field-odd">
Return type
<dd class="field-odd">
<p>
(bool, str, List[str])
Saves specified layers (only ones in the local layer stack) asynchronously.
Parameters:
- **new_root_layer_path** (str) – New location for root layer if it’s to save-as the current stage. If it’s empty, it will save specified layers only.
- **layer_identifiers** (List[str]) – List of layer identifiers to be saved.
- **on_finish_fn** (Callable[[bool, str, List[str]], None]) – Finish callback that the first param is to tell if the operation is successful, the second one tells the error message if it’s failed and the third param is the list of layer identifiers that are saved successfully.
Saves render settings into the current stage. Render settings will be serialized into the custom layer data of root layer.
### omni.usd._usd.UsdContext.save_stage
**Parameters**
- `on_finish_fn` (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
**Returns**
- Successful or not.
### omni.usd._usd.UsdContext.save_stage_async
**Returns**
- A tuple where the first element tells whether the operation is successful or not, and the second one tells the error message if the operation is failed.
**Return type**
- (bool, str)
### omni.usd._usd.UsdContext.save_stage_with_callback
**Parameters**
- `self` (omni.usd._usd.UsdContext)
- `on_finish_fn` (Callable[[bool, str], None])
### save_stage_with_callback
Saves the current stage asynchronously.
**Parameters**
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
### selection_changed_async
async selection_changed_async() → List[str]
Wait for selection to be changed. Return a list of newly selected paths.
### set_pending_edit
set_pending_edit(self: omni.usd._usd.UsdContext, arg0: bool) → None
Set or clear the stage dirtiness state manually no matter if it has pending edits to save.
### set_pickable
set_pickable(self: omni.usd._usd.UsdContext, arg0: str, arg1: bool) → None
Sets the pickable state for a prim.
### omni.usd.UsdContext.set_selection_group
```python
set_selection_group(self: omni.usd._usd.UsdContext, groupId: int, path: str) -> None
```
Assigns the prim to specified selection group.
### omni.usd.UsdContext.set_selection_group_outline_color
```python
set_selection_group_outline_color(self: omni.usd._usd.UsdContext, groupId: int, color: carb::Float4) -> None
```
Sets the outline color of the selection group.
### omni.usd.UsdContext.set_selection_group_shade_color
```python
set_selection_group_shade_color(self: omni.usd._usd.UsdContext, groupId: int, color: carb::Float4) -> None
```
Sets the shade color of the selection group.
### omni.usd.UsdContext.set_timeline
```python
set_timeline(self: omni.usd._usd.UsdContext, name: str = '') -> None
```
Sets the timeline for this context.
### omni.usd.UsdContext.try_cancel_save
```python
try_cancel_save(self: omni.usd._usd.UsdContext) -> None
```
→
None
Try to cancel the saving process. It only take effects when it’s called immediately after receiving event StageEventType::eSaving or StageEventType::eSettingsSaving.
--- | 27,557 |
omni.usd.UsdContext.md | # UsdContext
## Class Definition
```python
class omni.usd.UsdContext(pybind11_object)
```
### Methods
- **`__init__(*args, **kwargs)`**
- **`add_to_pending_creating_mdl_paths(self[, ...])`**
- Internal.
- **`attach_stage_async(stage)`**
- Asynchronous version of `omni.usd.UsdContext.attach_stage_with_callback()`.
- **`attach_stage_with_callback(self, stage_id[, ...])`**
- Attaches an existing stage asynchronously.
- **`can_close_stage(self)`**
- Whether the current stage can be closed or not.
- **`can_open_stage(self)`**
- Whether a stage can be opened.
```
| Method | Description |
| ------ | ----------- |
| can_open_stage (self) | Whether a new stage can be opened or not. |
| can_save_stage (self) | Whether the current stage can be saved or not. |
| close_stage (self[, on_finish_fn]) | Closes the current stage synchronously. |
| close_stage_async () | Asynchronous version of omni.usd.UsdContext.close_stage_with_callback(). |
| close_stage_with_callback (self, on_finish_fn) | Closes the current stage asynchronously. |
| compute_path_world_bounding_box (self, arg0) | Compute world bound box for specified prim. |
| compute_path_world_transform (self, arg0) | Compute world transform for specified prim. |
| disable_save_to_recent_files (self) | |
| enable_save_to_recent_files (self) | |
| export_as_stage (self, url[, on_finish_fn]) | Export stage with all prims flattened synchronously, and it will include contents from session layer also. |
| export_as_stage_async (url) | Asynchronous version of omni.usd.UsdContext.export_as_stage_with_callback(). |
| export_as_stage_with_callback (self, url, ...) | Export stage with all prims flattened asynchronously, and it will include contents from session layer also. |
| get_attached_hydra_engine_names (self) | |
| get_geometry_instance_path (self, arg0) | |
| get_name (self) | |
- `get_name(self)`
- Gets the name of the context.
- `get_rendering_event_stream(self)`
- Gets the rendering event stream.
- `get_selection(self)`
- Gets the selection interface.
- `get_stage()`
- Gets current opened `pxr.Usd.Stage`.
- `get_stage_audio_manager(self)`
- (No description provided)
- `get_stage_event_stream(self)`
- Gets the stage event stream.
- `get_stage_id(self)`
- Gets the UsdStage Id that can be queried with Usd.StageCache.
- `get_stage_loading_status(self)`
- Gets the stage loading status.
- `get_stage_state(self)`
- Gets the current stage state.
- `get_stage_url(self)`
- Gets the Stage url.
- `get_timeline(self)`
- Gets the timeline interface.
- `get_timeline_name(self)`
- Gets current timeline used in this context.
- `has_pending_edit(self)`
- Whether it has unsaved edits or not.
- `is_new_stage(self)`
- Whether the current stage (root layer) is anonymous or not.
- `is_omni_stage(self)`
- Whether the URL of the current stage (root layer) is prefixed with 'omniverse:'.
- `is_writable(self)`
- (No description provided)
- `load_mdl_parameters_for_prim_async(prim[, ...])`
- Internal.
- `load_render_settings_from_stage(self, arg0)`
- Loads render settings from stage.
- `new_stage([load_set])`
-
- `new_stage_async([load_set])`
- Asynchronous version of `omni.usd.UsdContext.new_stage_with_callback()`.
- `new_stage_with_callback([fn, load_set])`
- Asynchronous version of `omni.usd.UsdContext.new_stage()` that supports to customize load set of new stage.
- `next_frame_async([inViewportId])`
- Wait for frame complete event from Kit for specific viewport.
- `next_stage_event_async()`
- Wait for next stage event of omni.usd.
- `next_usd_async([inViewportId])`
- Wait for frame complete event from Kit for specific viewport.
- `open_stage(self, url, on_finish_fn, str], ...)`
- Opens a stage synchronously.
- `open_stage_async(url[, load_set, ...])`
- Asynchronous version of `omni.usd.UsdContext.open_stage_with_callback()`.
- `open_stage_with_callback(self, url, ...)`
- Opens a stage asynchronously.
- `open_stage_with_session_layer(self, url, ...)`
- Opens a stage asynchronously with specified session layer.
- `register_selection_group(self)`
- Registers a selection group.
- `remove_all_hydra_engines(self)`
-
remove_all_hydra_engines (self)
reopen_stage (self, on_finish_fn, str, ...)
Re-opens the current stage synchronously.
reopen_stage_async ([load_set])
Asynchronous version of omni.usd.UsdContext.reopen_stage_with_callback().
reopen_stage_with_callback (self, ...)
Re-opens the current stage asynchronously.
save_as_stage (self, url[, on_finish_fn])
Saves the current stage to another location synchronously.
save_as_stage_async (url)
Asynchronous version of omni.usd.UsdContext.save_as_stage_with_callback().
save_as_stage_with_callback (self, url, ...)
Saves the current stage to another location asynchronously.
save_layers (self, new_root_layer_path, ...)
Saves specified layers (only ones in the local layer stack) synchronously.
save_layers_async (new_root_layer_path, ...)
Asynchronous version of omni.usd.UsdContext.save_layers_with_callback().
save_layers_with_callback (self, ...)
Saves specified layers (only ones in the local layer stack) asynchronously.
save_render_settings_to_current_stage (self)
Saves render settings into the current stage.
save_stage (self[, on_finish_fn])
Saves the current stage (only layers in the local layer stack) synchronously.
save_stage_async ()
Asynchronous version of omni.usd.UsdContext.save_stage_with_callback().
| Method Name | Description |
|-------------|-------------|
| save_stage_with_callback(self, on_finish_fn) | Saves the current stage asynchronously. |
| selection_changed_async() | Wait for selection to be changed. |
| set_pending_edit(self, arg0) | Set or clear the stage dirtiness state manually no matter if it has pending edits to save. |
| set_pickable(self, arg0, arg1) | Sets the pickable state for a prim. |
| set_selection_group(self, groupId, path) | Assigns the prim to specified selection group. |
| set_selection_group_outline_color(self, ...) | Sets the outline color of the selection group. |
| set_selection_group_shade_color(self, ...) | Sets the shade color of the selection group. |
| set_timeline(self[, name]) | Sets the timeline for this context. |
| try_cancel_save(self) | Try to cancel the saving process. |
### __init__(self, *args, **kwargs)
- Initializes the UsdContext.
### add_to_pending_creating_mdl_paths(self, path: str = '', recreate: bool = False)
- Adds a path to the pending creating MDL paths.
### omni.usd.UsdContext.add_to_pending_creating_mdl_paths
- **Parameters:**
- `loadInputs : bool = True`
- `False`
- **Returns:**
- `bool`
- **Description:**
- Internal.
### omni.usd.UsdContext.attach_stage_async
- **Parameters:**
- `stage : Stage`
- **Returns:**
- `Tuple[bool, str]`
- **Description:**
- Asynchronous version of `omni.usd.UsdContext.attach_stage_with_callback()`. Attaches an opened stage to the context.
- **Parameters:**
- **stage** (pxr.Usd.Stage) – The instance of UsdStage.
- **Returns:**
- A tuple where the first element tells whether the operation is successful or not, and the second one tells the error message if the operation is failed.
- **Return type:**
- `(bool, str)`
### omni.usd.UsdContext.attach_stage_with_callback
- **Parameters:**
- `self : omni.usd._usd.UsdContext`
- `stage_id : int`
- `on_finish_fn : Callable[[bool, str], None] = None`
- **Returns:**
- `bool`
- **Description:**
- Attaches an existing stage asynchronously.
Parameters
----------
- **stage_id** (`long int`) – The stage id that can be queried with `pxr.UsdUtils.StageCache.Get().Find`.
- **on_finish_fn** (`Callable[[bool, str], None]`) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
can_close_stage(self: omni.usd._usd.UsdContext) -> bool
--------------------------------------------------------
Whether the current stage can be closed or not.
can_open_stage(self: omni.usd._usd.UsdContext) -> bool
------------------------------------------------------
Whether a new stage can be opened or not.
can_save_stage(self: omni.usd._usd.UsdContext) -> bool
------------------------------------------------------
Whether the current stage can be saved or not.
close_stage(self: omni.usd._usd.UsdContext, on_finish_fn: Callable[[bool, str], None] = None)
----------------------------------------------------------------------------------------------
### close_stage
Closes the current stage synchronously.
#### Parameters
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
#### Returns
- Successful or not.
### close_stage_async
Asynchronous version of `omni.usd.UsdContext.close_stage_with_callback()`. Closes the current stage.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, and the second one tells the error message if the operation is failed.
- Return type: (bool, str)
### close_stage_with_callback
Closes the current stage asynchronously.
#### Parameters
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
### compute_path_world_bounding_box
### omni.usd._usd.UsdContext
#### compute_path_world_bounding_box
```python
compute_path_world_bounding_box(self: omni.usd._usd.UsdContext, arg0: str) -> Tuple[carb::Double3, carb::Double3]
```
Compute world bound box for specified prim. Unlike using USD API directly, it speeds up bound box computation with cache or Fabric when it’s enabled.
#### compute_path_world_transform
```python
compute_path_world_transform(self: omni.usd._usd.UsdContext, arg0: str) -> Annotated[List[float], FixedSize(16)]
```
Compute world transform for specified prim. Unlike using USD API directly, it speeds up transform computation with cache.
#### disable_save_to_recent_files
```python
disable_save_to_recent_files(self: omni.usd._usd.UsdContext) -> None
```
#### enable_save_to_recent_files
```python
enable_save_to_recent_files(self: omni.usd._usd.UsdContext) -> None
```
#### export_as_stage
```python
export_as_stage(self: omni.usd._usd.UsdContext, url: str, on_finish_fn: Callable[[bool], None]) -> None
```
### export_as_stage
Export stage with all prims flattened synchronously, and it will include contents from session layer also.
#### Parameters
- **url** (str) – New location to save the exported stage.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
#### Returns
- Successful or not.
### export_as_stage_async
Asynchronous version of `omni.usd.UsdContext.export_as_stage_with_callback()`. Flattens and exports the current stage.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, and
- the second one tells the error message if the operation is failed.
#### Return type
- (bool, str)
### export_as_stage_with_callback
#### Parameters
- **self** (`omni.usd._usd.UsdContext`)
- **url** (str)
- **on_finish_fn** (Callable[[bool, str], None])
### omni.usd.UsdContext.export_as_stage_with_callback
Export stage with all prims flattened asynchronously, and it will include contents from session layer also.
#### Parameters
- **url** (`str`) – New location to save the exported stage.
- **on_finish_fn** (`Callable[[bool, str], None]`) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
### omni.usd.UsdContext.get_attached_hydra_engine_names
### omni.usd.UsdContext.get_geometry_instance_path
### omni.usd.UsdContext.get_name
Gets the name of the context.
### omni.usd.UsdContext.get_rendering_event_stream
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.get_rendering_event_stream">
<span class="sig-name descname">
<span class="pre">
get_rendering_event_stream
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
omni.usd._usd.UsdContext
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
omni::usd::IEventStream
<dd>
<p>
Gets the rendering event stream. See
<code class="xref py py-class docutils literal notranslate">
<span class="pre">
StageRenderingEventType
for more details.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.get_selection">
<span class="sig-name descname">
<span class="pre">
get_selection
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
omni.usd._usd.UsdContext
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
omni::usd::Selection
<dd>
<p>
Gets the selection interface. See
<code class="xref py py-class docutils literal notranslate">
<span class="pre">
Selection
for more details.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.get_stage">
<span class="sig-name descname">
<span class="pre">
get_stage
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
Gets current opened
<code class="xref py py-class docutils literal notranslate">
<span class="pre">
pxr.Usd.Stage
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.get_stage_audio_manager">
<span class="sig-name descname">
<span class="pre">
get_stage_audio_manager
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
omni.usd._usd.UsdContext
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
omni.usd._usd.AudioManager
<dd>
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.get_stage_event_stream">
<span class="sig-name descname">
<span class="pre">
get_stage_event_stream
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
omni.usd._usd.UsdContext
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
carb::events::IEventStream
<dd>
<p>
Gets the stage event stream. See
<code class="xref py py-class docutils literal notranslate">
<span class="pre">
StageEventType
for more details.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.get_stage_id">
<span class="sig-name descname">
<span class="pre">
get_stage_id
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
omni.usd._usd.UsdContext
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
int
<dd>
<p>
Gets the UsdStage Id that can be queried with Usd.StageCache.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.get_stage_loading_status">
<span class="sig-name descname">
<span class="pre">
get_stage_loading_status
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
omni.usd._usd.UsdContext
<span class="sig-paren">
)
<dd>
### omni.usd.UsdContext.get_stage_loading_status
**Returns**
- A tuple that the first element tells the current loading message, the second element tells how many files are loaded already, and the third one tells the total files to be loaded.
- Return type: (str, int, int)
### omni.usd.UsdContext.get_stage_state
Gets the current stage state. See `StageState` for more details.
### omni.usd.UsdContext.get_stage_url
Gets the Stage url. The URL can be used as layer identifier to query layer handle from USD Layer Registry.
### omni.usd.UsdContext.get_timeline
Gets the timeline interface. See `omni.timeline` for more details.
### omni.usd.UsdContext.get_timeline_name
Gets current timeline used in this context.
### omni.usd.UsdContext.has_pending_edit
### has_pending_edit
```python
def has_pending_edit(self: omni.usd._usd.UsdContext) -> bool:
```
Whether it has unsaved edits or not.
### is_new_stage
```python
def is_new_stage(self: omni.usd._usd.UsdContext) -> bool:
```
Whether the current stage (root layer) is anonymous or not.
### is_omni_stage
```python
def is_omni_stage(self: omni.usd._usd.UsdContext) -> bool:
```
Whether the URL of the current stage (root layer) is prefixed with ‘omniverse:’.
### is_writable
```python
def is_writable(self: omni.usd._usd.UsdContext) -> bool:
```
### load_mdl_parameters_for_prim_async
```python
async def load_mdl_parameters_for_prim_async(prim, recreate: bool = False):
```
Internal.
### load_render_settings_from_stage
```python
def load_render_settings_from_stage(self: omni.usd._usd.UsdContext, arg0: int):
```
## omni.usd.UsdContext.load_render_settings_from_stage
- **Description**: Loads render settings from stage.
## omni.usd.UsdContext.new_stage_async
- **Description**: Asynchronous version of `omni.usd.UsdContext.new_stage_with_callback()`. Creates a new stage with anonymous root layer.
- **Parameters**:
- **load_set** (omni.usd.UsdContextInitialLoadSet) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
- **Returns**:
- A tuple where the first element tells whether the operation is successful or not, and the second one tells the error message if the operation is failed.
- **Return type**: (bool, str)
## omni.usd.UsdContext.new_stage_with_callback
- **Description**: Asynchronous version of `omni.usd.UsdContext.new_stage()` that supports to customize load set of new stage.
## omni.usd.UsdContext.next_frame_async
- **Description**: Wait for frame complete event from Kit for specific viewport.
## omni.usd.UsdContext.next_stage_event_async
- **Description**: Asynchronous method to get the next stage event.
- **Returns**:
- A tuple where the first element is the stage event type and the second element is a dictionary.
### omni.usd.UsdContext.next_stage_event_async
Wait for next stage event of omni.usd.
### omni.usd.UsdContext.next_usd_async
Wait for frame complete event from Kit for specific viewport.
### omni.usd.UsdContext.open_stage
Opens a stage synchronously.
**Parameters**
- **url** (str) – The stage URL that can be resolved.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (omni.usd.UsdContextInitialLoadSet) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
**Returns**
- Successful or not.
### omni.usd.UsdContext.open_stage_async
Opens a stage asynchronously.
**Parameters**
- **url** (str) – The stage URL that can be resolved.
- **load_set** (~omni.usd._usd.UsdContextInitialLoadSet = <UsdContextInitialLoadSet.LOAD_ALL: 0>) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
- **session_layer_url** (~typing.Optional[str] = None) – The URL of the session layer.
**Returns**
- Tuple[bool, Optional[str]] – A tuple containing a boolean indicating success and an optional string for error message.
## omni.usd.UsdContext.open_stage_async
Asynchronous version of `omni.usd.UsdContext.open_stage_with_callback()`. Opens a new stage.
### Parameters
- **url** (str) – Stage URL to open.
- **load_set** (omni.usd.UsdContextInitialLoadSet) – If it’s to open all payloads or none.
- **session_layer_url** (str) – Specified session layer.
### Returns
A tuple where the first element tells whether the operation is successful or not, and the second one tells the error message if the operation is failed.
### Return type
(bool, str)
## omni.usd.UsdContext.open_stage_with_callback
Opens a stage asynchronously.
### Parameters
- **url** (str) – The stage URL that can be resolved.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (omni.usd.UsdContextInitialLoadSet) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
## omni.usd.UsdContext.open_stage_with_session_layer
Opens a stage asynchronously with specified session layer.
### Parameters
- **url** (str) – The stage URL that can be resolved.
- **session_layer_url** (str) – Specified session layer.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (omni.usd.UsdContextInitialLoadSet) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
### Parameters
- **url** (`str`) – The stage URL that can be resolved.
- **session_layer_url** (`str`) – The specified session layer URL.
- **on_finish_fn** (`Callable[[bool, str], None]`) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (`omni.usd.UsdContextInitialLoadSet`) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
### register_selection_group
```python
def register_selection_group(self: omni.usd._usd.UsdContext) -> int:
```
Registers a selection group. Prims can be assigned to selection group with customized outline colors than the default. It supports 255 selection groups at most.
### remove_all_hydra_engines
```python
def remove_all_hydra_engines(self: omni.usd._usd.UsdContext) -> None:
```
### reopen_stage
```python
def reopen_stage(self: omni.usd._usd.UsdContext, on_finish_fn: Callable[[bool, str], None] = None, load_set: omni.usd._usd.UsdContextInitialLoadSet = <UsdContextInitialLoadSet.LOAD_ALL: 0>) -> bool:
```
Re-opens the current stage synchronously.
#### Parameters
- **on_finish_fn** (`Callable[[bool, str], None]`) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (`omni.usd.UsdContextInitialLoadSet`) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
```
Successful or not.
### reopen_stage_async
Asynchronous version of `omni.usd.UsdContext.reopen_stage_with_callback()`. Re-opens the current stage.
**Parameters**
- **load_set** (omni.usd.UsdContextInitialLoadSet) – If it’s to open all payloads or none.
**Returns**
- A tuple where the first element tells whether the operation is successful or not, and
- the second one tells the error message if the operation is failed.
**Return type**
- (bool, str)
### reopen_stage_with_callback
Re-opens the current stage asynchronously.
**Parameters**
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **load_set** (omni.usd.UsdContextInitialLoadSet) – Whether it should open stage with payloads loaded or not. By default, it loads all payloads.
```python
async
```
```python
def save_as_stage_async(url: str) -> Tuple[bool, str]:
"""
Asynchronous version of `omni.usd.UsdContext.save_as_stage_with_callback()`. Saves the current stage to a new location.
Parameters:
url (str) – New location to save the current stage.
Returns:
A tuple where the first element tells whether the operation is successful or not, and
the second one tells the error message if the operation is failed.
Return type:
(bool, str)
"""
```python
def save_as_stage_with_callback(self: omni.usd._usd.UsdContext) -> None:
"""
Saves the current stage to another location synchronously.
Parameters:
url (str) – New location to save the current stage.
on_finish_fn (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
Returns:
Successful or not.
"""
### save_as_stage_with_callback
Saves the current stage to another location asynchronously.
#### Parameters
- **url** (str) – New location to save the current stage.
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
### save_layers
Saves the current stage to another location asynchronously.
#### Parameters
- **new_root_layer_path** (str) – Path to the new root layer.
- **layer_identifiers** (List[str]) – Identifiers of the layers to save.
- **on_finish_fn** (Callable[[bool, str, List[str]], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
### save_layers
Saves specified layers (only ones in the local layer stack) synchronously.
#### Parameters
- **new_root_layer_path** (str) – New location for root layer if it’s to save-as the current stage. If it’s empty, it will save specified layers only.
- **layer_identifiers** (List[str]) – List of layer identifiers to be saved.
- **on_finish_fn** (Callable[[bool, str, List[str]], None]) – Finish callback that the first param is to tell if the operation is successful, the second one tells the error message if it’s failed and the third param is the list of layer identifiers that are saved successfully.
#### Returns
- Successful or not.
### save_layers_async
Asynchronous version of `omni.usd.UsdContext.save_layers_with_callback()`. Saves specified layers.
#### Parameters
- **new_root_layer_path** (str) – New location for root layer if it’s to save-as the current stage. If it’s empty, it will save specified layers only.
- **layer_identifiers** (List[str]) – List of layer identifiers to be saved.
#### Returns
- A tuple where the first element tells whether the operation is successful or not, the second one tells the error message if it’s failed and the third param is the list of layer identifiers that are saved successfully.
#### Return type
- (bool, str, List[str])
### omni.usd._usd.UsdContext.save_layers_with_callback
**Parameters**
- **new_root_layer_path** (str) – New location for root layer if it’s to save-as the current stage. If it’s empty, it will save specified layers only.
- **layer_identifiers** (List[str]) – List of layer identifiers to be saved.
- **on_finish_fn** (Callable[[bool, str, List[str]], None]) – Finish callback that the first param is to tell if the operation is successful, the second one tells the error message if it’s failed and the third param is the list of layer identifiers that are saved successfully.
**Description**
Saves specified layers (only ones in the local layer stack) asynchronously.
### omni.usd._usd.UsdContext.save_render_settings_to_current_stage
**Description**
Saves render settings into the current stage. Render settings will be serialized into the custom layer data of root layer.
### omni.usd._usd.UsdContext.save_stage
**Description**
Saves the stage.
## omni.usd._usd.UsdContext
### save_stage
```python
save_stage(on_finish_fn: Callable[[bool, str, List[str]], None] = None) -> bool
```
- **Description**: Saves the current stage (only layers in the local layer stack) synchronously.
- **Parameters**:
- **on_finish_fn** (Callable[[bool, str, List[str]], None]): Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **Returns**: Successful or not.
### save_stage_async
```python
async save_stage_async() -> Tuple[bool, str]
```
- **Description**: Asynchronous version of `omni.usd.UsdContext.save_stage_with_callback()`. Saves the current stage.
- **Returns**:
- A tuple where the first element tells whether the operation is successful or not, and
- the second one tells the error message if the operation is failed.
- **Return type**: (bool, str)
### save_stage_with_callback
```python
save_stage_with_callback(self: omni.usd._usd.UsdContext, on_finish_fn: Callable[[bool, str, List[str]], None] = None) -> None
```
- **Description**: Saves the current stage with a callback.
- **Parameters**:
- **self** (omni.usd._usd.UsdContext): The context instance.
- **on_finish_fn** (Callable[[bool, str, List[str]], None]): Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
- **Returns**: None
```
### save_stage_with_callback
Saves the current stage asynchronously.
#### Parameters
- **on_finish_fn** (Callable[[bool, str], None]) – Finish callback that the first param is to tell if the operation is successful, and the second one tells the error message if it’s failed.
### selection_changed_async
async selection_changed_async() → List[str]
Wait for selection to be changed. Return a list of newly selected paths.
### set_pending_edit
set_pending_edit(self: omni.usd._usd.UsdContext, arg0: bool) → None
Set or clear the stage dirtiness state manually no matter if it has pending edits to save.
### set_pickable
set_pickable(self: omni.usd._usd.UsdContext, arg0: str, arg1: bool) → None
Sets the pickable state for a prim.
<dt class="sig sig-object py" id="omni.usd.UsdContext.set_selection_group">
<span class="sig-name descname">
<span class="pre">
set_selection_group
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
omni.usd._usd.UsdContext
,
<em class="sig-param">
<span class="n">
<span class="pre">
groupId
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
int
,
<em class="sig-param">
<span class="n">
<span class="pre">
path
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
str
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<dd>
<p>
Assigns the prim to specified selection group.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.set_selection_group_outline_color">
<span class="sig-name descname">
<span class="pre">
set_selection_group_outline_color
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self:
<span class="pre">
omni.usd._usd.UsdContext
,
<em class="sig-param">
<span class="n">
<span class="pre">
groupId:
<span class="pre">
int
,
<em class="sig-param">
<span class="n">
<span class="pre">
color:
<span class="pre">
carb::Float4
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<dd>
<p>
Sets the outline color of the selection group.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.set_selection_group_shade_color">
<span class="sig-name descname">
<span class="pre">
set_selection_group_shade_color
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self:
<span class="pre">
omni.usd._usd.UsdContext
,
<em class="sig-param">
<span class="n">
<span class="pre">
groupId:
<span class="pre">
int
,
<em class="sig-param">
<span class="n">
<span class="pre">
color:
<span class="pre">
carb::Float4
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<dd>
<p>
Sets the shade color of the selection group.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.set_timeline">
<span class="sig-name descname">
<span class="pre">
set_timeline
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
omni.usd._usd.UsdContext
,
<em class="sig-param">
<span class="n">
<span class="pre">
name
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
str
<span class="w">
<span class="o">
<span class="pre">
=
<span class="w">
<span class="default_value">
<span class="pre">
''
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<dd>
<p>
Sets the timeline for this context.
<dl class="py method">
<dt class="sig sig-object py" id="omni.usd.UsdContext.try_cancel_save">
<span class="sig-name descname">
<span class="pre">
try_cancel_save
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
self
<span class="p">
<span class="pre">
:
<span class="w">
<span class="n">
<span class="pre">
omni.usd._usd.UsdContext
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<dd>
<p>
Attempts to cancel a save operation.
→
None
Try to cancel the saving process. It only take effects when it’s called immediately after receiving event StageEventType::eSaving or StageEventType::eSettingsSaving. | 37,122 |
omni.usd.UsdContextInitialLoadSet.md | # UsdContextInitialLoadSet
## UsdContextInitialLoadSet
- Bases: `pybind11_object`
### Description
Specifies the initial set of prims to load when opening a UsdStage.
### Members
- LOAD_ALL : Load all payloads
- LOAD_NONE : Unload all payloads
### Methods
- `__init__(self, value)`
### Attributes
- `LOAD_ALL`
- `LOAD_NONE`
- `name`
- `value`
<section>
<dl class="py function">
<dt class="sig sig-object py" id="omni.usd.UsdContextInitialLoadSet.__init__">
<em class="sig-object">
<span class="pre">
omni.usd._usd.UsdContextInitialLoadSet
,
<em class="sig-param">
<span class="pre">
value
<span class="pre">
:
<span class="pre">
int
<span class="pre">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
None
<dd>
<dl class="py property">
<dt class="sig sig-object py" id="omni.usd.UsdContextInitialLoadSet.name">
<em class="property">
<span class="pre">
property
<span class="sig-name descname">
<span class="pre">
name
<dd>
<footer>
<hr/>
| 1,385 |
omni.usd.UsdWatcher.md | # UsdWatcher
## UsdWatcher
```python
class omni.usd.UsdWatcher
```
### Methods
| Method | Description |
|--------|-------------|
| `__init__()` | |
| `destroy()` | |
| `subscribe_to_change_info_path(path, on_change)` | |
| `subscribe_to_resync_path(path, on_change)` | |
```python
def __init__():
pass
```
``` | 321 |
omni.usd.writable_usd_dotted_file_exts.md | # writable_usd_dotted_file_exts
## writable_usd_dotted_file_exts
Gets a list of file extensions about writable USD formats.
**Returns:**
A list of file extensions, like (‘usd’, ‘usda’, ‘usdc’, ‘live’).
**Return type:**
List[str] | 232 |
omni.usd.writable_usd_files_desc.md | # writable_usd_files_desc
## writable_usd_files_desc
Gets a description of all writable USD file formats.
### Returns
A description string, like “USD Files (`.usd; .usda;*.usdc;*.live)`
### Return type
str | 209 |
omni.usd.writable_usd_file_exts.md | # writable_usd_file_exts
## writable_usd_file_exts
Gets a list of file extensions (without dots) about writable USD formats.
**Returns:**
A list of file extensions (without dots), like (‘usd’, ‘usda’, ‘usdc’, ‘live’).
**Return type:**
List[str] | 248 |
omni.usd.writable_usd_file_exts_str.md | # writable_usd_file_exts_str
## writable_usd_file_exts_str
```python
omni.usd.writable_usd_file_exts_str()
```
Gets a string that includes all writable USD file formats supported by Kit.
**Returns:**
A string includes all file extensions of writable usd formats, and is separated by “|”, like “usd|usda|usdc|live”.
**Return type:**
str
``` | 343 |
omni.usd.writable_usd_re.md | # writable_usd_re
## writable_usd_re
```python
omni.usd.writable_usd_re()
```
Gets the regex that matches writable USD files.
**Returns:**
A compiled regex.
**Return type:**
re.Pattern
``` | 192 |
omni.usd_api.md | # Omniverse Kit API
## Class Hierarchy
- namespace omni
- namespace usd
- struct HydraEngineDesc
- class Selection
- class UsdContext
- enum StageEventType
- enum StageRenderingEventType
- enum StageState
- enum UsdContextInitialLoadSet
## File Hierarchy
- Directory omni
- Directory usd
- File Selection.h
- File UsdContext.h
- File UsdTypes.h
## Namespaces
- carb
- carb::renderer
- carb::scenerenderer
## Namespaces
- carb::scenerenderer
- carb::settings
- omni
- omni::timeline
- omni::usd
- omni::usd::audio
- omni::usd::hydra
- rtx
- rtx::resourcemanager
## Classes and Structs
- omni::usd::HydraEngineDesc
- omni::usd::Selection
- omni::usd::UsdContext
## Enums
- omni::usd::StageEventType
- omni::usd::StageRenderingEventType
- omni::usd::StageState
- omni::usd::UsdContextInitialLoadSet
## Functions
- omni::usd::hydra::OMNI_DECLARE_INTERFACE
## Typedefs
- carb::scenerenderer::SceneId
- omni::timeline::TimelinePtr
- omni::usd::hydra::OpaqueSharedHydraEngineContextPtr
- omni::usd::OnLayersSavedResultFn
- omni::usd::OnPickingCompleteFn
- omni::usd::OnStageResultFn
- omni::usd::SdfPathGroupIdVector
- omni::usd::SdfPathUSet
- omni::usd::SubscriptionId
- rtx::resourcemanager::SyncScopeId
# Main Heading
This is a paragraph with a link.
- Item 1
- Item 2
--- | 1,322 |
omni.volume.acquire_volume_interface.md | # acquire_volume_interface
## acquire_volume_interface
```
- **Function**: `omni.volume.acquire_volume_interface(plugin_name: str = None, library_path: str = None) -> omni.volume._volume.IVolume`
- **Parameters**:
- `plugin_name`: A string representing the plugin name, default is `None`.
- `library_path`: A string representing the library path, default is `None`.
- **Returns**: An instance of `omni.volume._volume.IVolume`.
```
--- | 451 |
omni.volume.Functions.md | # omni.volume Functions
## Functions Summary
- **lru_cache**
- Least-recently-used cache decorator.
- **acquire_volume_interface**
- acquire_volume_interface(plugin_name: str = None, library_path: str = None) -> omni.volume._volume.IVolume | 246 |
omni.volume.GridData.md | # GridData
## GridData
```
class omni.volume.GridData
```
Bases:
```
pybind11_object
```
### Methods
| Method | Description |
|--------|-------------|
| `__init__(*args, **kwargs)` | |
```
__init__(self, *args, **kwargs)
``` | 229 |
omni.volume.IVolume.md | # IVolume
## IVolume
```python
class omni.volume.IVolume
```
Bases: `pybind11_object`
### Methods
| Method | Description |
|--------|-------------|
| `__init__(*args, **kwargs)` | |
| `create_from_dense(self, arg0, arg1, arg2, ...)` | |
| `create_from_file(self, arg0)` | |
| `get_grid_class(self, arg0, arg1)` | |
| `get_grid_data(self, arg0, arg1)` | |
| `get_grid_type(self, arg0, arg1)` | |
| `get_index_bounding_box(self, arg0, arg1)` | |
- `get_num_grids(self, arg0)`
- `get_short_grid_name(self, arg0, arg1)`
- `get_world_bounding_box(self, arg0, arg1)`
- `mesh_to_level_set(self, arg0, arg1, arg2, ...)`
- `save_volume(self, gridData, path, ...)`
### `__init__(self, *args, **kwargs)`
### `create_from_dense(self: omni.volume._volume.IVolume, arg0: float, arg1: buffer, arg2: float, arg3: buffer, arg4: str) -> omni.volume._volume.GridData`
### `create_from_file(self: omni.volume._volume.IVolume, arg0: ...)`
`str`
`(`
`→`
`omni.volume._volume.GridData`
`get_grid_class`
`(`
`self : omni.volume._volume.IVolume,`
`arg0 : omni.volume._volume.GridData,`
`arg1 : int`
`)`
`→`
`int`
`get_grid_data`
`(`
`self : omni.volume._volume.IVolume,`
`arg0 : omni.volume._volume.GridData,`
`arg1 : int`
`)`
`→`
`List[int]`
`get_grid_type`
`(`
`self : omni.volume._volume.IVolume,`
`arg0 : omni.volume._volume.GridData,`
`arg1 : int`
`)`
`→`
`int`
`get_index_bounding_box`
`(`
**omni.volume.IVolume.get_index_bounding_box**(self: omni.volume._volume.IVolume, arg0: omni.volume._volume.GridData, arg1: int) -> list
**omni.volume.IVolume.get_num_grids**(self: omni.volume._volume.IVolume, arg0: omni.volume._volume.GridData) -> int
**omni.volume.IVolume.get_short_grid_name**(self: omni.volume._volume.IVolume, arg0: omni.volume._volume.GridData, arg1: int) -> str
**omni.volume.IVolume.get_world_bounding_box**(self: omni.volume._volume.IVolume, arg0: omni.volume._volume.GridData, arg1: int) -> ...
### mesh_to_level_set
```python
mesh_to_level_set(self: omni.volume._volume.IVolume, arg0: numpy.ndarray[numpy.float32], arg1: numpy.ndarray[numpy.int32], arg2: numpy.ndarray[numpy.int32], arg3: float, arg4: numpy.ndarray[numpy.int32]) -> omni.volume._volume.GridData
```
### save_volume
```python
save_volume(self: omni.volume._volume.IVolume, gridData: omni.volume._volume.GridData, path: str, saveVolumeParameters: omni.volume._volume.SaveVolumeParameters = <omni.volume._volume.SaveVolumeParameters object at 0x7f182d65fcb0>) -> bool
``` | 2,459 |
omni.volume.md | # omni.volume
## Classes Summary:
- **GridData**
- **IVolume**
- **SaveVolumeParameters**
## Functions Summary:
- **lru_cache**: Least-recently-used cache decorator.
- **acquire_volume_interface**: acquire_volume_interface(plugin_name: str = None, library_path: str = None) -> omni.volume._volume.IVolume | 305 |
omni.volume.SaveVolumeParameters.md | # SaveVolumeParameters
## SaveVolumeParameters
```
class omni.volume.SaveVolumeParameters
```
### Methods
- `__init__(self)`
### Attributes
- `flags`
```
def __init__(self: omni.volume._volume.SaveVolumeParameters) -> None
``` | 233 |
omnigraph-autonode_AutoNode.md | # AutoNode - Node Type Definition
## Warning
This feature is currently only a prototype. While in development it must be enabled explicitly by defining the Carbonite setting `/omnigraph/autonode/enabled` as 1, e.g. by using the command line option “–/omnigraph/autonode/enabled=1”.
Interfaces, behavior, and documentation for this feature are subject to change without notice.
AutoNode is the terminology used for the general process of generating node type definitions directly from Python code. `AutoNode` enables creation of OmniGraph node type definitions from a simple decorated Python function. There is no need to create .ogn or .py implementation files.
It turns this:
```python
import omni.graph.core as og
import omni.graph.core.types as ot
@og.node_type(add_execution_pins=True)
def dot(vec1: ot.float3, vec2: ot.float3) -> ot.float:
return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2]
```
## How it Works
AutoNode generates node signatures by extracting type annotations stored in functions and variables. 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.tools.data_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.
Under the hood, annotation extraction is done with the python `__annotations__` (PEP 3107) dictionary in every class.
### Decorators
`omni.graph.core` exposes the AutoNode function `node_type` which is used to decorate Python functions to generate node type definitions.
```
## node_type()
This function can be used as a decorator or as a free function call.
### Python Code Example
```python
import omni.graph.core as og
@og.node_type()
def say_hi() -> str:
return "hi, everybody!"
def say_hello() -> str:
return "Hello, World!"
```
## Wrapping Functions
### Wrapping a Free Function
Here’s an example of wrapping a free function:
### Python Code Example
```python
import omni.graph.core as og
import omni.graph.tools.ogn.data_types as ogdt
@og.node_type()
def one_up(input: ogdt.Int = 0) -> ogdt.Token:
"""this documentation will appear in the node's help"""
return f"one up! {input + 1}"
```
### Important
The type annotations really matter. Without them, AutoNode can’t define node inputs and outputs.
### Multiple Output Attributes
You can also create multiple output attributes by making your return type a tuple:
### Python Code Example
```python
import omni.graph.core as og
import omni.graph.tools.ogn.data_types as ogdt
@og.node_type()
def break_vector(input: ogdt.Float3) -> tuple[ogdt.Float, ogdt.Float, ogdt.Float]:
return (input[0], input[1], input[2])
```
## Decorator Parameters
### unique_name
Specifies the full name of the node type definition. If it is not specified then the name will be a combination of the extension from which it was defined and the function name.
### Python Code Example
```python
import omni.graph.core as og
import MyModule
@og.node_type(module_name="test_module")
def add_one(input: int) -> int:
return input + 1
```
### Note
Anything executed in the script editor or as a standalone file will not have a default module and so one must be provided or an exception will be raised. The `module_name` value should be such that the node type name is unique.
### ui_name
Specifies the onscreen name of the function.
### categories
Array of text tags to be added to the node. This is special metadata on the node that can be used to group common node types together or to provide an easily searchable term.
### metadata
Other metadata to pass through AutoNode, such as icon information, whether the node should be hidden, or the set of categories attached to the node.
## Supported Types
This list of types supported by AutoNode corresponds to the list of types supported by OmniGraph.
```python
import omni.graph.core as og
import omni.graph.tools.ogn.data_types as ogdt
print(f"List of all data types: {dir(ogdt.ALL_DATA_TYPES)}")
# Generic Vectors
[ogdt.Vector3d, ogdt.Vector3h, ogdt.Vector3f]
# ...and their corresponding array types
[ogdt.Vector3dArray, ogdt.Vector3hArray, ogdt.Vector3fArray]
# Scalar and Vector types
[ogdt.Float, ogdt.Float2, ogdt.Float3, ogdt.Float4]
[ogdt.Half, ogdt.Half2, ogdt.Half3, ogdt.Half4]
[ogdt.Double, ogdt.Double2, ogdt.Double3, ogdt.Double4]
[ogdt.Int, ogdt.Int2, ogdt.Int3, ogdt.Int4]
# ...and their corresponding array types
[ogdt.FloatArray, ogdt.Float2Array, ogdt.Float3Array, ogdt.Float4Array]
[ogdt.HalfArray, ogdt.Half2Array, ogdt.Half3Array, ogdt.Half4Array]
[ogdt.DoubleArray, ogdt.Double2Array, ogdt.Double3Array, ogdt.Double4Array]
[ogdt.IntArray, ogdt.Int2Array, ogdt.Int3Array, ogdt.Int4Array]
# Matrix Types
[ogdt.Matrix2d, ogdt.Matrix3d, ogdt.Matrix4d]
# ...and their corresponding array types
[ogdt.Matrix2dArray, ogdt.Matrix3dArray, ogdt.Matrix4dArray]
# Vector Types with roles
[ogdt.Normal3d, ogdt.Normal3f, ogdt.Normal3h]
[ogdt.Point3d, ogdt.Point3f, ogdt.Point3h]
[ogdt.Quatd, ogdt.Quatf, ogdt.Quath]
[ogdt.TexCoord2d, ogdt.TexCoord2f, ogdt.TexCoord2h]
[ogdt.TexCoord3d, ogdt.TexCoord3f, ogdt.TexCoord3h]
[ogdt.Color3d, ogdt.Color3f, ogdt.Color3h, ogdt.Color4d, ogdt.Color4f, ogdt.Color4h]
# ...and their corresponding array types
[ogdt.Normal3dArray, ogdt.Normal3fArray, ogdt.Normal3hArray]
[ogdt.Point3dArray, ogdt.Point3fArray, ogdt.Point3hArray]
[ogdt.QuatdArray, ogdt.QuatfArray, ogdt.QuathArray]
[ogdt.TexCoord2dArray, ogdt.TexCoord2fArray, ogdt.TexCoord2hArray]
```
[ogdt.TexCoord3dArray, ogdt.TexCoord3fArray, ogdt.TexCoord3hArray]
[ogdt.Color3dArray, ogdt.Color3fArray, ogdt.Color3hArray, ogdt.Color4dArray, ogdt.Color4fArray, ogdt.Color4hArray]
# Other simple value types
[ogdt.Timecode, ogdt.UInt, ogdt.UChar, ogdt.UInt64, ogdt.Token]
# ... and their corresponding array types
[ogdt.TimecodeArray, ogdt.UIntArray, ogdt.UCharArray, ogdt.UInt64Array, ogdt.TokenArray]
# Specialty Types
[ogdt.Any, ogdt.Bundle, ogdt.Execution, ogdt.ObjectId, ogdt.Path, ogdt.String, ogdt.Target]
# Mapping of specific Python types
[(str, ogdt.String), (int, ogdt.Int64), (float, ogdt.Double), (bool, ogdt.Bool)]
Note
Not all python typing types are supported. | 6,344 |
omnigraph-user-interfaces_UserInterface.md | # User Interfaces
The extension `omni.graph.ui` contains the user interface elements for interacting with the elements of an OmniGraph.
You can find the various UI elements through the *Visual Scripting Menus*. The main components that comprise the OmniGraph user interfaces are:
- **Property Panel** will show you the contents of your OmniGraph or an OmniGraph node and allow you to edit their attribute values.
- **Visual Graph Editors** are the visual editors through which you can create and connect nodes.
- **Settings Editor** is a window that provides access to the user configuration settings for OmniGraph.
- **Node Description Editor** is an experimental editor through which you can create a Python node and the accompanying files that deliver it as an extension.
- **Toolkit** is a window containing various debugging and inspection features for OmniGraph. Not for the casual user but very useful to help technical users see behind the scenes. | 958 |
omnihydra_xforms.md | # Working with OmniHydra Transforms
Omniverse apps ship with a custom Hydra scene delegate named OmniHydra that augments the functionality of the UsdImaging scene delegate. This enables Omniverse to extend Hydra with high-performance scene editing, simulation, and proceduralism not otherwise available in an off-the-shelf USD build. The key to runtime performance in OmniHydra is Fabric, which is now accessible via the USDRT Scenegraph API.
## The RtXformable schema
OmniHydra leverages a special set of attributes for reasoning about prim transforms in Fabric. To help create and query these attributes, USDRT provides the RtXformable schema.
There are two ways to set transform data with the RtXformable schema:
- world transform
- local transform
If any world transform attribute is set on a prim in Fabric, it will take precedence over any other transform data from USD or Fabric. The world transform is specified in three parts.
| Name | Fabric Attribute Name | Type | APIs |
|------------|-----------------------|----------|---------------------|
| position | _worldPosition | Double3 | Create/GetWorldPositionAttr |
| orientation| _worldOrientation | Quatf | Create/GetWorldOrientationAttr |
| scale | _worldScale | Vector3f | Create/GetWorldScaleAttr |
If only one or two of the world transform attributes exist in Fabric, OmniHydra will use default values for the remaining attributes.
If no world transform attributes are set in Fabric, a local transform may be specified for a prim. (If any world transform attribute is specified, the local transform is ignored). This local transform will take precedence over local transform data from USD for the prim, but otherwise continue to participate in the transform hierarchy - changes to parent prims will continue to affect the overall transform of the prim.
| Name | Fabric Attribute Name | Type | APIs |
|---------------|----------------------|------------|-------------------|
| localMatrix | _localMatrix | Matrix4d | Create/GetLocalMatrixAttr |
Helper methods are provided to set either the world-space transform attribute values or the local transform value in Fabric using the computed values from the USD prim:
- SetWorldXformFromUsd()
- SetLocalXformFromUsd()
Important to note that only OmniHydra XForm attributes in Fabric will drive the rendered prims. Any USD-style xformOps in Fabric are ignored by OmniHydra.
## Examples
### A cube in world space
# Section 1
## A cube with a world-space transform
Let’s start with the simplest USD scene, a cube at the origin:
Now, let’s use USDRT and the RtXformable schema to apply an OmniHydra world-space transform in Fabric.
```python
import omni.usd
from usdrt import Usd, Rt, Gf, Sdf
stage = Usd.Stage.Attach(omni.usd.get_context().get_stage_id())
prim = stage.GetPrimAtPath(Sdf.Path("/World/Cube"))
xformable = Rt.Xformable(prim)
xformable.CreateWorldPositionAttr(Gf.Vec3d(0, 200, 0))
```
As expected, the cube is now elevated:
But note, if you inspect the cube properties in the Property window, it has no transforms set in USD:
Fabric is a transient data store on top of USD, so values set in Fabric are not automatically pushed back to the USD stage.
# Section 2
## A cylinder with a local transform
Let’s start over with a new USD scene, a cylinder at the origin:
Unlike the cube in the last example, the cylinder has two Xform prim ancestors:
Using the RtXformable schema, the local transform for the cylinder prim can be set:
```python
import omni.usd
from usdrt import Usd, Rt, Gf, Sdf
stage = Usd.Stage.Attach(omni.usd.get_context().get_stage_id())
prim = stage.GetPrimAtPath(Sdf.Path("/World/Xform_A/Xform_B/Cylinder"))
xformable = Rt.Xformable(prim)
xformable.CreateLocalMatrixAttr(Gf.Matrix4d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 200, 0, 0))
```
As expected, the cylinder is translated along the X axis:
Like with the cube example, this data is only stored in Fabric - inspecting the USD data of the cylinder will show no transform overrides in USD:
When using the local transform property with OmniHydra, the prim will still participate in the overall transform hierarchy, including changes to the USD scene and Fabric. For example, if the `/World/Xform_A` prim is selected in the Stage window and dragged in the Viewport (in this case 300 units along the Z axis), updating the USD transform of the Xform prim, the cylinder prim will inherit that ancestral transform in OmniHydra:
Likewise, if a local transform is authored in Fabric for the `/World/Xform_A/Xform_B` ancestor of the cylinder prim, the cylinder will inherit that transform in OmniHydra as well:
```python
prim = stage.GetPrimAtPath(Sdf.Path("/World/Xform_A/Xform_B"))
xformable = Rt.Xformable(prim)
xformable.CreateWorldPositionAttr(Gf.Vec3d(0, 0, -200))
``` | 4,875 |
omniverse-cloud_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
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:
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. | 9,999 |
omniverse-kit-app-template_intro.md | # Omniverse Kit App Template
This documentation is a tutorial for creating and publishing Applications on the Omniverse platform. It’ll guide you from the starting point of setting up a project, through creating apps, adding functionality, debug code, write tests and documentation, all the way to the finish line of packaging and publishing to end users.
The tutorial is based on using the kit-app-template repo which is designed to be used for any Kit SDK based development - not just this tutorial. It is focused around two Applications: a Simple App that presents important foundational steps around Application creation, and a USD Explorer App that has us dive deeper into the developer workflow.
Tip: You may want to put the Command Cheat-Sheet in an extra tab. It lists the details of commands you’ll be executing frequently.
## Prerequisites
This tutorial is aimed at developers with a background in Python and/or C++. Prior knowledge of Omniverse developer platform is not required. Tutorial is based on using Visual Studio Code on Windows or Linux. Internet access is required to download Kit SDK and project files.
To follow along with the tutorial and develop on the platform a user will need access to these domains:
- Project repo: github.com/NVIDIA-Omniverse
- Kit Kernel: d4i3qtqj3r0z5.cloudfront.net
- Extension Registry: ovextensionsprod.blob.core.windows.net | 1,384 |
omniverse-physics-programming-manual_index.md | # Omniverse Physics Programming Manual
## Contents
- [Physics Extensions](#physics-extensions)
- [Omni PhysX](#omni-physx)
- [Omni PhysX Commands](#omni-physx-commands)
- [Omni PhysX Graph](#omni-physx-graph)
- [Omni PhysX Vehicle](#omni-physx-vehicle)
- [Omni PhysX Character Controller](#omni-physx-character-controller)
- [Omni PhysX Force Fields](#omni-physx-force-fields)
- [Changelog](#changelog)
- [105.1.13 - 2024-01-30](#105113---2024-01-30)
- [105.1.11 - 2023-12-01](#105111---2023-12-01)
- [105.1.10 - 2023-10-19](#105110---2023-10-19)
- [105.1.9 - 2023-09-23](#10519---2023-09-23)
- [105.1.8 - 2023-09-20](#10518---2023-09-20)
- [105.1.7 - 2023-09-11](#10517---2023-09-11)
- [105.1.6 - 2023-09-07](#10516---2023-09-07)
- [105.1.5 - 2023-08-21](#10515---2023-08-21)
- [105.1.4 - 2023-08-14](#10514---2023-08-14)
- [105.1.3 - 2023-08-07](#10513---2023-08-07)
- [105.1.2 - 2023-08-01](#10512---2023-08-01)
- [105.1.1 - 2023-07-27](#10511---2023-07-27)
- [105.1.0 - 2023-07-19](#10510---2023-07-19)
- [Omni PhysX Bundle 105.0.15 2023-06-23](#omni-physx-bundle-105015-2023-06-23)
- [Core](#core)
- [105.0.14 - 2023-06-22](#105014---2023-06-22)
- [105.0.13 - 2023-06-09](#105013---2023-06-09)
- [105.0.12 - 2023-06-01](#105012---2023-06-01)
- [105.0.11 - 2023-05-26](#105011---2023-05-26)
- [105.0.11] - 2023-05-30
- [105.0.10] - 2023-05-17
- [105.0.9] - 2023-05-10
- [105.0.8] - 2023-05-03
- [105.0.7] - 2023-04-25
- [105.0.6] - 2023-04-14
- [105.0.5] - 2023-04-04
- [105.0.4] - 2023-03-29
- [105.0.3] - 2023-03-16
- [105.0.2] - 2023-03-09
- [105.0.1] - 2023-02-27
- [105.0.0] - 2023-02-06
- [104.2.4-5.1] - 2023-02-03
- [104.2.3-5.1] - 2023-01-30
- [104.2.2-5.1] - 2023-01-24
- [104.2.1-5.1] - 2023-01-17
- [104.2.0-5.1] - 2023-01-05
- [104.1.6-5.1] - 2022-12-09
- [104.1.5-5.1] - 2022-12-05
- [104.1.4-5.1] - 2022-12-01
- [104.1.3-5.1] - 2022-11-25
- [104.1.2-5.1] - 2022-11-21
- [104.1.1-5.1] - 2022-11-16
- [104.1.0-5.1] - 2022-11-09
- [104.0.4-5.1] - 2022-10-27
- [104.0.3-5.1] - 2022-10-21
- [104.0.2-5.1] - 2022-10-14
- [104.0.1-5.1] - 2022-10-04
- [104.0.0-5.1] - 2022-10-01
- [1.4.19-5.1] - 2022-09-02
- [1.4.18.2-5.1] - 2022-08-16
- [1.4.18.1-5.1] - 2022-08-08
- [1.4.17.1-5.1] - 2022-07-28
- [1.4.16.1-5.1] - 2022-07-25
- [1.4.15.1-5.1] - 2022-07-20
- [1.4.14-5.1] - 2022-06-20
- [1.4.13-5.1] - 2022-06-01
- [1.4.12-5.1] - 2022-05-27
- [1.4.11-5.1] - 2022-05-20
- [1.4.10-5.1] - 2022-05-17
- [1.4.9-5.1] - 2022-05-11
- [1.4.8-5.1] - 2022-05-04
- [1.4.7-5.1] - 2022-04-27
- [1.4.6-5.1] - 2022-04-19
- [1.4.5-5.1] - 2022-04-08
- [1.4.4-5.1] - 2022-04-04
- [1.4.3-5.1] - 2022-03-25
- [1.4.2-5.1] - 2022-03-14
- [1.4.1-5.1] - 2022-03-07
- [1.4.0-5.1] - 2022-02-21
- [1.3.15-5.1] - 2021-12-??
- [1.3.14-5.1] - 2021-11-05
- [1.3.13-5.1] - 2021-10-15
- [1.3.12-5.1] - 2021-10-05
- [1.3.11-5.1] - 2021-09-22
- [1.3.10-5.1] - 2021-09-01
- [1.3.9-5.1] - 2021-08-22
- [1.3.8-5.1] - 2021-08-10
- [1.3.7-5.1] - 2021-08-05
- [1.3.6-5.1] - 2021-07-16
- [1.3.5-5.1] - 2021-07-08
- [1.3.4-5.1] - 2021-07-02
- [1.3.3-5.1] - 2021-06-22
- [1.3.2-5.1] - 2021-06-15
- [1.3.1-5.1] - 2021-06-04
- [1.3.0-5.1] - 2021-05-28
- [1.2.0-5.1] - 2021-05-05
- [1.1.0-5.1] - 2021-03-17
- [1.1.0-5.1] - 2021-02-05
- [1.0.0-5.1] - 2020-10-28 | 3,273 |
omniverse-wrapp_index.md | # Omniverse WRAPP
## Workflow for Reproducible Asset Packaging and Publishing
WRAPP provides a command line tool execute a set of useful packaging and distribution functions to define sets of versioned files, label them, and distribute and consume versions in a safe manner.
### Table of Contents
- [WRAPP CLI usage](manual.html)
- [Design](manual.html#design)
- [Layer 1 commands - Files & Folders and their metadata](manual.html#layer-1-commands-files-folders-and-their-metadata)
- [Layer 2 commands - Packages](manual.html#layer-2-commands-packages)
- [Changes](changes.html)
- [1.0.0](changes.html#id1) | 618 |
OmniverseNativeInterfaces.md | # Omniverse Native Interfaces
## Warning
A common misconception is that Omniverse Native Interfaces can be changed over time, but this is **not correct**. Once created, Omniverse Native Interfaces are **immutable**. To add functionality, an Interface can be inherited into a new Interface that adds functionality, or a new separate Interface can be created.
## Warning
Omniverse Native Interfaces are Beta software and can be difficult to use. Active development by the Carbonite team has paused. If other contributors wish to develop improvements, the Carbonite team is willing to evaluate Merge Requests.
Carbonite Interfaces are actively supported.
## Overview
This document provides a deep-dive into the design and philosophy of Omniverse Native Interfaces. For a guide to quickly start using Omniverse Native Interfaces, see [ONI Walkthrough](OniWalkthrough.html). For a guide on extending an existing released Omniverse Native Interface, see [Extending an Omniverse Native Interface](ExtendingOniInterfaces.html).
## Interfaces at a Glance
The Omniverse SDK has three types of native interfaces: “Carbonite Interfaces”, “Kit Interfaces”, and “Omniverse Native Interfaces”. All three types of interfaces are ABI-safe.
### Carbonite Interfaces
Carbonite interfaces follow a C-style approach to interfaces. Interfaces are broken into two parts:
- A struct of function pointers. This struct essentially represents the “methods” of the interface.
- A pointer to an opaque “context” object. The context object stores data needed by the interface’s function pointers to operate correctly.
The context pointer is optional. Some interfaces rely on private, globally stored data. On rare occasions, some interfaces require no data to operate correctly.
Another way to think of Carbonite interfaces is a convenient way to import multiple implementations of a C API into your process.
Here’s an example of a simple Carbonite interface:
```c++
struct Window; // opaque "context"
struct IWindowing
{
CARB_PLUGIN_INTERFACE("carb::windowing::IWindowing", 1, 0)
Window*(CARB_ABI* createWindow)(uint32_t w, uint32_t h);
void(CARB_ABI* destroyWindow)(Window* window);
void(CARB_ABI* showWindow)(Window* window);
};
```
```c++
void(CARB_ABI* setTitle)(Window* window, const char* title);
Keyboard*(CARB_ABI* getKeyboard)(Window* window);
};
```
```
To instantiate the `IWindowing` interface, call `carb::tryAcquireInterface`:
```c++
IWindowing* windowing = carb::tryAcquireInterface<IWindowing>();
```
With the interface instantiated, you can now create and use windows:
```c++
Window* window = windowing->createWindow(640, 480);
windowing->setTitle(window, "My Window");
// you must keep track of both the window ("context") and windowing ("interface") pointers
windowing->showWindow(window);
// interface/context memory must be explicitly managed
windowing->destroyWindow(window);
```
Since the interface function tables and opaque “context” data are separate, you must keep track of both pointers.
Care must also be taken to ensure that the context data passed to interface functions are compatible.
Carbonite interfaces are semantically versioned, meaning that at compile time the expected binary layout of the data pointed to by the `IWindowing` struct may differ than the actual binary layout of struct at runtime. It is up to the user, at runtime via version checks, to ensure `IWindowing` has a compatible binary layout. A detailed explanation of the implications of using semantically version interfaces can be found in [Semantic Versioning](#semantic-versioning).
Because interfaces are described as a table of function pointers using C, C++ like inheritance is not possible.
Finally, like C, it’s up to the user explicitly manage the interface function table’s and opaque pointer’s memory.
### Kit Interfaces
Kit interfaces follow a more C++ approach to interfaces and improve upon Carbonite interfaces:
```c++
// a carbonite interface is needed to act as a factory for the kit interface
struct IWindowing
{
CARB_PLUGIN_INTERFACE("windowing::IWindowing", 1, 0);
IWindow*(CARB_ABI* createWindowPtr)(uint32_t w, uint32_t h);
// smart pointer wrapper to createWindowPtr
carb::ObjectPtr<IWindow> createWindow(uint32_t w, uint32_t h)
{
return stealObject(this->createWindowPtr(w, h));
}
};
// this is the kit interface
struct IWindow : public carb::IObject
{
CARB_PLUGIN_INTERFACE("windowing::IWindow", 1, 0);
virtual void showWindow() = 0;
virtual void setTitle(const char* title) = 0;
virtual IKeyboard* getKeyboardPtr() = 0;
};
```
```cpp
// smart pointer wrapper to getKeyboardPtr
carb::ObjectPtr<IKeyboard>& getKeyboard()
{
return stealObject(this->getKeyboardPtr());
}
};
```
Kit interfaces have the following properties:
- **Abstract base classes**: Because Kit interfaces are classes, single inheritance is possible: interfaces can inherit from other interfaces. We’ll see later that interface implementations can even inherit from existing implementations. This greatly reduces duplicated code and increases code reuse. All Kit interfaces inherit from `carb::IObject` (or an interface that inherits from `carb::IObject`).
- **Reference counted**: Intrusive reference counting makes memory management and binding to other languages easier.
- **Semantically versioned**: Like Carbonite interfaces, runtime version checks are still required.
- **Hand-written**: Interface authors are expected to ensure the interface is ABI-safe and properly versioned.
To use a Kit interface:
```cpp
IWindowing* windowing = carb::tryAcquireInterface<IWindowing>();
if (windowing)
{
auto window = windowing->createWindow(640, 480); // window is reference counted
window->setTitle("My Window");
window->showWindow();
}
```
Kit interfaces do not have separate interface and context pointers. There’s a single pointer (like C++) that stores both the interface and data. As such, the user no longer has to worry about mixing the wrong context pointer with the wrong interface pointer.
Above, we never called a “destroy” method. This is because Kit interfaces are reference counted and in the code above managed by smart pointers. This greatly simplifies memory management at a low cost.
Kit interfaces rely on the same plugin framework designed for Carbonite interfaces. As such, it inherits some of that framework’s legacy:
- That framework assumes interfaces are plain-old-data. Therefore, a Carbonite interface (which is plain-old-data) must be registered to act as a factory for the plugin’s Kit interfaces.
- Interfaces are semantically versioned, meaning runtime version checks are required.
- Multiple implementations of an interface cannot coexist within a DLL.
- Multiple versions of an implementation cannot coexist within a DLL.
- Plugin loading is serial.
- Carbonite interface instantiation via the framework is expensive (though instantiation of the actual Kit interface via the Carbonite interface factory can be relatively cheap).
### Omniverse Interfaces
Omniverse interfaces follow a C++ style approach (really a COM-lite approach). Interfaces are abstract base classes that inherit from `omni::core::IObject` (or another interface that inherits from `omni::core::IObject`):
```cpp
OMNI_DECLARE_INTERFACE(IWindow);
OMNI_DECLARE_INTERFACE(IWindowSystem);
class IWindow_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("windowing.IWindow")>
{
protected:
virtual void show_abi(bool shouldShow) noexcept = 0;
virtual void setTitle_abi(OMNI_ATTR("c_str, not_null") const char* title) noexcept = 0;
virtual IKeyboard* getKeyboard_abi() noexcept = 0;
};
```
};
class IWindowSystem_abi :
public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("windowing.IWindowSystem")>
{
protected:
virtual IWindow* createWindow_abi(uint32_t w, uint32_t h) noexcept = 0;
};
To instantiate an interface:
```cpp
auto windowSystem = omni::core::createType<IWindowSystem>();
```
Not all interfaces can be instantiated by `omni::core::createType`. For example, to create and use an `IWindow`:
```cpp
auto window = windowSystem->createWindow(640, 480);
window->setTitle(640, 480);
window->show(true);
```
In the case above, `IWindowSystem` is essentially a factory for `IWindow` (and any other interfaces related to the window system). More information on object instantiation can be found in [Instantiating an Interface](#instantiating-an-interface).
Omniverse and Kit interfaces have several things in common:
- **Abstract base class**: This allows for C++ single inheritance (multiple inheritance is not ABI-safe).
- **Reference counted**: This allows for easier memory management and language bindings.
There are several large differences between Kit and Omniverse interfaces:
- Omniverse interfaces are not semantically versioned. Rather, Omniverse interfaces rely on a customer oriented versioning scheme that does not require runtime checks and encourages many small interfaces rather than large monolithic interfaces. More on versioning Omniverse interfaces can be found in [Interface Versioning](#versioning).
- Omniverse interfaces rely heavily on code generation. Omniverse interfaces are specified in a subset of C++ which the `omni.bind` tool is able to consume and generate a user friendly modern C++ wrapper and various language bindings (such as Python). Additionally, `omni.bind` is used to validate that the interface is ABI-safe. In essence, Omniverse interfaces are much like an interface definition language (IDL) that is also valid C++. More on code generation can be found in [API: omni.bind](#api-omni-bind).
- There are strict rules about how to design an interface. These rules cover thread safety, memory ownership, reference count management, and naming conventions. The `omni.bind` tool helps to enforce these rules. The end-result is less guessing by the user on how an interface works and less confusion from the interface author on how to design an interface.
- Omniverse interfaces eschew the Carbonite plugin framework in favor of a new type system. This type system has several improvements over the Carbonite framework:
- Optimized for concurrent plugin loading and type instantiation
- DLLs can contain multiple implementations of a given interface
- DLLs can contain multiple versions of an implementation
- Interfaces are not assumed to be plain-old-data
More information on the type system can be found in [Instantiating an Interface](#instantiating-an-interface).
- Omniverse interface have an ABI-safe dynamic cast-like mechanism.
At this point you probably have questions like, “Why is everything postfixed with `_abi`?” and “What’s `OMNI_TYPE_ID`, `OMNI_ATTR`, and `OMNI_BIND`?”
Inherits<>
```
The remainder of this document is dedicated to answering these and other questions about Omniverse Native Interfaces.
```markdown
Note
```
: In order to better fit docs on the page, assume the following code exists:
```c++
namespace omni {
using namespace omni::core;
}
```
This means objects like `omni::IObject` and `omni::core::IObject` are the same thing.
### ABI vs. API
Omniverse interfaces have two parts: the ABI and the API. These two parts serve two different audiences:
- The API is intended for users of the interface. The API consist of easy-to-use inline code designed to hide the gory semantics of the ABI.
- The ABI is intended for implementation authors. Implementation authors only need to override the ABI methods and can completely ignore the API.
In the following sections, we’ll cover how interface designers should approach designing the ABI and API of an interface.
#### ABI Interface Design
Omniverse interfaces inherit from `omni::core::IObject` or another interface that inherits from `omni::core::IObject`. Interfaces do not support multiple inheritance (see Multiple Inheritance for details on how implementations can use multiple inheritance).
Methods in the ABI are denoted with an `_abi` postfix. Users should never call methods in the ABI. There are several reasons for this:
- The `_abi` methods exist to generate ABI-safe code. The rules for `_abi` methods are designed such that the code generated by the compiler is useable across multiple compilers chains.
- In order to achieve ABI-safety, `_abi` methods are greatly limited in the types of data they can produce and consume. Mainly, primitive types like `const char*`, `uint32_t`, and structs/unions that meet the requirements of standard layout types.
- Omniverse interfaces are reference counted. When using `_abi` methods, you must manually manage the reference count. This is error-prone.
ABI methods in an interface should be `protected` to discourage their use by users.
The ordering of methods in the ABI has a direct impact on the binary representation of the interface. Rearranging methods in the ABI will break the ABI.
#### ABI: Data Types
Methods in the ABI are limited to consuming and producing the following data types:
- Pointers. For example: `float*`, `const char**`.
- Primitive types with known sizes. This include types like `uint32_t`, `float`, etc. Types with ABI dependent sizes, such as `int` are not allowed. An exception to this rule is `char` which is assumed to be 8-bits.
- Pointers can point to one of three types of data:
- Primitive types. For example, `float*`.
- Interfaces. For example, `IWindow*`.
- Structs or unions. For example, `WindowDesc*`.
- All members in the struct/union must meet the rules above.
- The struct/union must meet the requirements of a standard layout type.
- The struct/union must not be opaque.
### ABI: C++ Features Not Allowed
The following C++ features are not allowed in the ABI of an interface:
- Constructor / Destructors
- Exceptions. All ABI methods must be declared `noexcept`.
- Overloaded operators
- Overloaded methods
- Data members
- Non-virtual methods
- Non-pure virtual methods
- Static methods
- Templated methods
- Default arguments
- References
- `final`
- `= default`
- `= delete`
Essentially, the ABI is limited to C’s feature set. The only C++ feature allowed is pure virtual methods.
The limits above may seem overly restrictive. One might say, “Every compiler implements references as const pointers, we should allow references.” While that’s a true statement today, it may not be true in the future as new language features are added.
Our goal is to define a set of ABI rules that will minimize the risk of external parties, such as compiler authors, breaking the Omniverse ABI. As a result, we’ve tied ourself to well-known and stable “standards”: the C-ABI and the virtual function table layout defined by Microsoft’s Component Object Model (COM). Both specifications have avoided breaking changes for decades.
While the ABI layer is quite restrictive, we’ll see in [API Interface Design](#api-interface-design) that most of these restrictions are lifted in the API layer.
### ABI: Handling Interface Pointers
Pointers to Omniverse interfaces are allowed within the ABI portion of an interface. As previously mentioned, interfaces are internally reference counted, and as such rules must be established as to when the internal reference count should be incremented and decremented. Incrementing and decrementing the internal reference count of an interface is handled by `IObject::acquire_abi()` and `IObject::release_abi()`. The general rules are:
- When duplicating (or creating) a pointer to an interface, call `acquire_abi()`.
- When no longer using a pointer to an interface, call `release_abi()`.
Practically:
- Return: When returning an interface pointer via a return statement, the callee must call `acquire_abi()`.
- Out Parameters: When returning an interface pointer via a pointer to an interface pointer (e.g. `IFoo**`), the callee must call `acquire_abi()`.
- InOut Parameters: When accepting an interface pointer via a pointer to an interface pointer (e.g. `IFoo**`), the callee must call `release_abi()` on the incoming pointer and...
1. **Out Parameters**: The caller must call `acquire_abi()` on the outgoing pointer. Functions with in-out pointers are rare.
2. **In Parameters**: The caller does not need to call `acquire_abi()` when passing a pointer to a method.
One exception to the rules above are **getter** methods:
- **Getter** (optional/discouraged): If a method returns an interface pointer, it may choose to not call `acquire_abi`, breaking the **Return** rule. Such a method must be postfixed with `WithoutAcquire`. For example, `getWindowWithoutAcquire_abi()`.
The **Getter** rule is designed to avoid excessive increments and decrements of the reference count when chaining calls together. This technique is strongly discouraged, as it is easily possible for the returned pointer to become invalidated (for example, by another thread).
### API Interface Design
To ease the ABI restrictions, interface authors implement “API” methods. These methods are designed to alleviate the restrictions of the ABI:
- API methods can produce and consume complex data types such as `std::vector`.
- API methods make heavy use of “smart” pointers (e.g. `omni::core::ObjectPtr<>` ) that manage reference counts for the user.
The end result for users is that using an interface’s API will feel like using any other C++ class.
An interface’s API has few restrictions and is designed to provide a user friendly surface to the underlying ABI. The main restriction is that all API code must be inlined.
Let’s look at a small chunk of the `IWindow` ABI:
```c++
OMNI_DECLARE_INTERFACE(IWindow);
class IWindow_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("windowing.IWindow")>
{
protected:
// abi /////////////////////////////////////////////////////////////////////////////////
// simple method which accepts a bool
virtual void show_abi(bool shouldShow) noexcept = 0;
// returns an interface pointer. getKeyboard_abi() will have called acquire_abi()
// on the returned pointer (see *Return* rule)
virtual IKeyboard* getKeyboard_abi() noexcept = 0;
// accepts an interface pointer. the caller does not need to call acquire_abi() on
// cursor before calling this method (see *In Parameter* rule)
virtual void setCursor_abi(ICursor* cursor) noexcept = 0;
};
```
While simple, the ABI above assumes the caller will properly increment/decrement the reference count of the `IKeyboard` and `ICursor` interfaces used in the ABI. The goal of the API is to provide a layer above the ABI that makes using the ABI easier. In this case, we’d like the API layer to handle properly incrementing and decrementing the interfaces’ reference counts.
To define the API, we use the `OMNI_DEFINE_INTERFACE_API()` macro:
```c++
OMNI_DEFINE_INTERFACE_API(omni::windowing::IWindow)
{
public:
void show(bool shouldShow) noexcept
{
show_abi(showShow);
}
omni::core::ObjectPtr<IKeyboard> getKeyboard() noexcept;
};
```
```{code-block} c++
:linenos:
return omni::core::steal(getKeyboard_abi());
```
```{code-block} c++
:linenos:
void setCursor(omni::core::ObjectParam<ICursor>& cursor) noexcept
{
setCursor_abi(cursor.get());
}
```
Above, notice:
- The `_abi` postfix has been stripped.
- All code is inlined.
- Smart wrappers (such as `omni::core::ObjectPtr` and `omni::core::ObjectParam`) are used to manage interface reference counts.
### API: omni.bind
The code above is mainly boiler-plate. To make authoring API code easier, the *omni.bind* tool can be used to generate the API layer for the interface author:
```bash
python omni.bind.py IWindow.h --api IWindow.gen.h
```
The interface author then only needs to include the generated file into their interface header:
```c++
OMNI_DECLARE_INTERFACE(IWindow);
class IWindow_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("windowing.IWindow")>
{
protected:
// abi /////////////////////////////////////////////////////////////////////////////////
// simple method which accepts a bool
virtual void show_abi(bool shouldShow) noexcept = 0;
// returns an interface pointer. getKeyboard_abi() will have called acquire_abi()
// on the returned pointer (see *Return* rule)
virtual IKeyboard* getKeyboard_abi() noexcept = 0;
// accepts an interface pointer. the caller does not need to call acquire_abi() on
// cursor before calling this method (see *In Parameter* rule)
virtual void setCursor_abi(ICursor* cursor) noexcept = 0;
};
#include "IWindow.gen.h" // new: include API layer generated code
```
Using *omni.bind* is not an all or nothing proposition. The interface author can both use *omni.bind* and also define custom API code via `OMNI_DEFINE_INTERFACE_API`:
```c++
OMNI_DECLARE_INTERFACE(IWindow);
class IWindow_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("windowing.IWindow")>
{
protected:
// abi /////////////////////////////////////////////////////////////////////////////////
// simple method which accepts a bool
virtual void show_abi(bool shouldShow) noexcept = 0;
// returns an interface pointer. getKeyboard_abi() will have called acquire_abi()
// on the returned pointer (see *Return* rule)
virtual IKeyboard* getKeyboard_abi() noexcept = 0;
// accepts an interface pointer. the caller does not need to call acquire_abi() on
// cursor before calling this method (see *In Parameter* rule)
virtual void setCursor_abi(ICursor* cursor) noexcept = 0;
};
```
// cursor before calling this method (see *In Parameter* rule)
virtual void setCursor_abi(ICursor* cursor) noexcept = 0;
};
#include "IWindow.gen.h" // include API layer generated code
OMNI_DEFINE_INTERFACE_API(omni::windowing::IWindow)
{
// new: in addition to having omni.bind generate API boiler-plate code for us, we can add our
// own API methods (like pushKey).
void pushKey(KeyboardKey key)
{
getKeyboard()->addKeyPress(key);
}
};
The user is unaware of the details of the ABI or that the API is a combination of hand-written and auto-generated code:
```c++
#include <IWindow.h>
// ...
auto windowSystem = omni::core::createType<IWindowSystem>();
// createWindow returns an ObjectPtr which manages window's reference count
auto window = windowSystem->createWindow(640, 480);
window->pushKey(KeyboardKey::eA); // hand-written api wrapper (that calls auto-generated wrapper)
window->show(true); // auto-generated wrapper
```
The *omni.bind* tool is the recommended way to generate API code. In addition to generating efficient and safe API code, the tool is also able to generate bindings for other languages such as Python.
When using *omni.bind*, interface authors can annotate constructs within interfaces with the `OMNI_ATTR` macro. This macro describes to *omni.bind* the intended usage of different elements. For example, if a const pointer member function parameter is marked with the `not_null` attribute, the API layer generator will generate a method wrapper that accepts a const reference. Advanced annotations, like denoting that a pointer is really a multi-dimensional array or that a method accepts a callback that would like to capture data, are supported. See the *omni.bind User Guide* for more details.
The following is recommended when using *omni.bind*:
- The build system should be used to dynamically update bindings. *omni.bind*’s `-M` flag can be used to generate dependency information.
- Generated code should be checked in. This enables useful debugging features such as Source Linking to work.
API: Method Naming
-----------------
When wrapping ABI methods in the API by hand, the `_abi` postfix should be stripped. For example, `setCursor_abi` becomes `setCursor`.
API methods do not have to have a 1-to-1 correspondence with ABI methods. An API method may choose to call 0 to many ABI calls.
API: Data Types
---------------
There are no restrictions on data types in the API. This can be used to great effect. For example, in *example.windowing.cpp*, lambdas with captures are passed to `IWindow` to listen to keyboard events:
```c++
omni::ObjectPtr<IWindow> window = /* ... */;
omni::ObjectPtr<ICursor> customCursor = /* ... */;
auto consumer = window->addOnKeyboardEventConsumer(
[&](IKeyboard* /*keyboard*/, const KeyboardEvent* event)
{
// ...
});
```
{
if (isKeyRelease(event, KeyboardKey::eKey1))
{
// window and customCursor we're captured
window->setCursor(customCursor.get());
}
});
```
## API: C++ Features Not Allowed
- Constructors / Destructors
- Exceptions
- Data members
- Virtual methods
- Pure virtual methods
In general, most of C++ is allowed in the API except features that should be used only in the ABI (e.g. virtual methods) or features that would expose implementation details (like constructors).
Exceptions could technically be allowed, but as a group we’ve decided to not use exceptions.
## API: Handling Interface Pointers
Raw interface pointers are highly discouraged in the API. Rather, interface pointers should be wrapped in smart pointers like `omni::core::ObjectPtr<>`. The following rules will help guide API authors:
- **Return**: When returning an interface pointer, API methods should return `omni::core::ObjectPtr<>`. Since most API calls are simply wrappers around ABI calls and the ABI calls will internally call `acquire_abi()` on the returned pointer, API methods should call `omni::core::steal()` to create an `ObjectPtr` that correctly manages the pointers reference count.
- **In Parameters**: Interface pointers passed to a method should be wrapped in `omni::core::ObjectParam<>`. This is a zero-overhead wrapper that allows the passage of both raw interface pointers and `omni::core::ObjectPtr<>`.
When writing API wrappers by hand, and in doubt as to how to handle interface pointers, see the output of `omni.bind`.
## omni::core::IObject
All interfaces must inherit from `omni::core::IObject`:
```c++
class IObject_abi
{
protected:
enum : TypeId { kTypeId = OMNI_TYPE_ID("omni.core.IObject") };
virtual void* cast_abi(TypeId id) noexcept = 0;
virtual void acquire_abi() noexcept = 0;
virtual void release_abi() noexcept = 0;
};
```
`IObject` defines several types of functionality desirable on every Omniverse interface:
- Reference counting via `acquire_abi()` and `release_abi()`.
- C++’s `dynamic_cast<>` relies on runtime type information (RTTI) which is not ABI-safe. `IObject::cast_abi()` provides an ABI-safe way to get `dynamic_cast` like functionality.
Interfaces should also identify themselves with a unique `omni::core::TypeId`. This isn’t strictly required by the ABI but in practice is required by other chunks of Omniverse code.
```cpp
omni::core::TypeId
```
is simply a
```cpp
uint64_t
```
and
the
```cpp
OMNI_TYPE_ID()
```
function is a compile time expression that hashes the given string to a unique value.
## Designing an Interface
Philosophically, an interface’s ABI should be as minimal as possible. Design towards many interfaces with few methods instead of few interfaces with many methods. As we’ll see later, many small interfaces helps with interface “versioning”.
All interfaces must directly inherit from
```cpp
omni::core::IObject
```
or inherit from an interface that inherits from
```cpp
omni::core::IObject
```
. When inheriting from an interface, inherit from the interface’s API, not it’s ABI. For example, inherit from
```cpp
omni::core::IObject
```
instead of
```cpp
omni::core::IObject_abi
```
.
Interfaces do not support multiple inheritance as multiple inheritance is not ABI-safe. Interfaces only support single inheritance, which is ABI-safe.
**Implementations**, however, do support multiple inheritance. See [Multiple Inheritance](#multiple-inheritance) for details.
Interfaces should be classes.
While not strictly required (as it does not affect the ABI), interfaces should utilize the
```cpp
omni::core::Inherits
```
template:
```cpp
OMNI_DECLARE_INTERFACE(IFoo);
OMNI_DECLARE_INTERFACE(IFooBar);
class IFoo_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("example.IFoo")>
{
protected:
virtual void doFooStuff_abi() noexcept = 0;
};
class IFooBar_abi : public omni::core::Inherits<IFooBar, OMNI_TYPE_ID("example.IFooBar")>
{
protected:
virtual void doFooBarStuff_abi() noexcept = 0;
};
```
```cpp
Inherits<>
```
is designed to work well with
```cpp
Implements<>
```
, which we’ll cover later. In short,
```cpp
Inherits<>
```
:
- Defines the interface’s
```cpp
BaseType
```
which is used by
```cpp
Implements<>
```
’s casting code.
- Defines the interface’s
```cpp
kTypeId
```
, which is used by
```cpp
Implements<>
```
’s casting code and helper functions such as
```cpp
omni::core::createType<>
```
.
ABI methods (pure virtual methods) should be postfixed with
```cpp
_abi
```
. The order in which ABI methods appear in the struct matters, as it affects the binary layout of the class. Since reordering methods in the interface breaks the ABI, make sure you’re happy with their order before releasing.
API methods should not be virtual (or pure virtual). API methods can be reordered since they don’t affect the ABI.
**omni.bind** can be used to ensure your interface is ABI-safe. When **omni.bind** encounters an interface (i.e., a class that inherits from
```cpp
omni::core::IObject
```
), it performs a series of checks to see if the interface meets ABI requirements.
## Implementing an Interface
Interface implementations can appear as inlined header code or deep within private .cpp file. Implementing an interface is similar to implementing a pure virtual base class in C++.
A simple example of how to implement an interface is the concrete
```cpp
Mouse
```
class that implements
```cpp
IMouse
```
(see [glfw.cpp](#)).
We can see that `Mouse` is just an unexciting C++ class. It has a constructor, non-virtual helper methods, and several data members, some of which are complex C++ data types like `std::vector`. The magic of `Mouse` is that all of these implementation details are essentially hidden. All the `Mouse` class has to do to be useful to the rest of the world is implement the ABI portion of the `IMouse` interface. In C++, this boils down to overriding all of the pure virtual methods in `IMouse`.
### Implements<>
Looking at `Mouse`, we see that all of `IMouse`’s ABI functions are overridden. However, `IMouse` inherits from `IObject` which has ABI functions such as `cast_abi()`, `release_abi()`, etc. Where are the implementations for those methods?
The answer is in the `omni::core::Implements<>` class:
```cpp
class Mouse : public omni::core::Implements<omni::input::IMouse>
{
/* ... */
};
```
#### Multiple Inheritance
The `omni::core::Implements<>` template generates efficient implementations of all of the methods in `IObject`. The template even allows for multiple inheritance. For example, let’s say we have a concrete class that implements both the `IKeyboard` and `IMouse` interfaces:
```cpp
class KeyboardMouse: public omni::core::Implements<input::IKeyboard, input::IMouse>
{
/* ... */
};
```
This demonstrates an important concept, while interfaces cannot use multiple inheritance, implementations can. The `Implements<>::cast_abi()` handles all of the mundane details of ensuring the returned interface pointers are ABI-safe.
Implementations are free to use the full gamut of C++ features. The only truly important thing an implementation does is implement the ABI portion of an interface and not let exceptions escape any ABI methods.
Implementations do not need to use `Implements<>` to implement an interface. `Implements<>` is the right answer 99% of the time, but there will be cases where `Implements<>`’s implementation of `IObject`’s ABI will not make sense.
### Instantiating an Interface
We previously saw that interfaces neither have constructors nor destructors. So, how does one go about instantiating an interface? Omniverse interfaces have three methods to instantiate an interface:
1. Via omni::createType<>.
2. Via a method of an already instantiated interface.
3. Via an exported function in the global scope.
In the following sections we’ll cover each method.
#### omni::createType<>()
`omni::core::createType()` is an API style wrapper around the ABI function `omni::core::ITypeFactory::createType_abi(omni::core::TypeId`
<p>
<code class="docutils literal notranslate">
<span class="pre">
ITypeFactory
is essentially a mapping from a type id to a creation function that returns an instance of the type.
Said differently,
<code class="docutils literal notranslate">
<span class="pre">
ITypeFactory
will map a type id to a function that knows how to call the constructor for the
implementation of a type.
<p>
It is up to the application to populate this mapping from type id to creation function. While there are a myriad ways
to do this (config files, explicitly calling an implementation specific registration function, plugin discovery, passing
a module name to
<code class="docutils literal notranslate">
<span class="pre">
omni::core::createType()
, etc), all methods boil down to calling
<code class="docutils literal notranslate">
<span class="pre">
omni::core::ITypeFactory::registerInterfaceImplementations_abi()
, which accepts a list of
<code class="docutils literal notranslate">
<span class="pre">
InterfaceImplementation
objects.
<p>
As an example,
<code class="docutils literal notranslate">
<span class="pre">
IWindowSystem
uses the following code to describe its interface (see
<span class="doc">
glfw.cpp
):
<div class="highlight-c++ notranslate">
<div class="highlight">
<pre><span>
<span class="p">{
<span class="w">
<span class="w">
<span class="w">
<span class="w">
<span class="w">
<span class="w">
<span class="w">
<span class="w">
<span class="w">
<span class="w">
<span class="w">
<span class="p">}
<p>
Above, we see that we’re describing the concrete class
<code class="docutils literal notranslate">
<span class="pre">
WindowSystem
. We’re assigning
<code class="docutils literal notranslate">
<span class="pre">
WindowSystem
a type id of
<em>
“windowing.IWindowSystem-glfw”
and denoting that this is the first version of the
<em>
implementation
.
<code class="docutils literal notranslate">
<span class="pre">
WindowSystem
implements a single interface:
<code class="docutils literal notranslate">
<span class="pre">
windowing.IWindowSystem
. We can see this from the definition of
the
<code class="docutils literal notranslate">
<span class="pre">
WindowSystem
class in
<span class="doc">
glfw.cpp
:
<div class="highlight-c++ notranslate">
<div class="highlight">
<pre><span>
<span class="p">{
<span class="w">
<span class="p">}
<p>
If the implementation had implemented other interfaces, the
<code class="docutils literal notranslate">
<span class="pre">
interfacesImplemented
array would be larger.
<p>
Once this mapping is stored in
<code class="docutils literal notranslate">
<span class="pre">
ITypeFactory
, it becomes clear how it is used (from
<span class="doc">
omni/core/IObject.h
):
<div class="highlight-c++ notranslate">
<div class="highlight">
<pre><span>
<span class="kr">inline
{
auto obj = steal(omniGetTypeFactoryWithoutAcquire()->createType(T::kTypeId, moduleName, version));
return obj.as<T>();
}
// ...
ObjectPtr<IWindowSystem> windowSystem = omni::core::createType<IWindowSystem>();
```
The `createType` API asks the given type for its type id, calls `ITypeFactory::createType` with the given type id, and then casts the returned `IObject` to the desired interface type. Under the hood, `ITypeFactory` is simply calling the creation function associated with the given type id. In this case, `windowing::IWindowSystem` has been mapped to the lambda we provided in `getInterfaceImplementations` that will create a `WindowSystem` object.
Above, we instantiated an implementation of an interface. However, interfaces can have many implementations. How does `ITypeFactory` resolve which implementation to instantiate if multiple implementations of an interface are registered? In short, when calling `createType()`:
1. If the given type id is a type id for an implementation, instantiate the highest registered version of the implementation.
2. If the given type id is a type id for an interface:
- If the app has set a preferred implementation for the interface, use it.
- If no preferred implementation is set, instantiate the first registered implementation.
Fairly simple logic. However, the caller (and even the app) can set creation constraints such as “the implementation must come from a specific DLL” or “the implementation must match a given version”. Specifying these constraints will likely be rare but it is important to note that they can be set and will follow a known set of rules to resolve which implementation should be instantiated. See `omni::core::ITypeFactory` for more details.
A final note on `ITypeFactory`: not all implementations should be registered with `ITypeFactory`. For example, in `glfw.cpp`, we see that only `WindowSystem` is registered. Other interface implementations such as `Mouse`, `Keyboard`, `Gamepad`, etc are not registered. For these GLFW implementations of the interfaces, this makes sense. Consider:
```c++
ObjectPtr<IMouse> mouse = omni::createType<IMouse>(); // returns nullptr
```
In the GLFW implementation of `IMouse`, the mouse must be associated with a GLFW window. The call to `createType()` simply doesn’t have enough information to create a GLFW implementation of `IMouse` and associate it with a GLFW window.
That’s not to say there couldn’t be an implementation of `IMouse` that could be instantiated via `omni::core::createType`. For example, we could write an implementation of `IMouse` that directly talked to the OS’s HID system. In this case, it may make sense to register the implementation with `ITypeFactory`.
IMouse
IWindow::getMouse()
```
is called.
How did
```
IWindow::getMouse()
```
know which constructor to call to create an
```
IMouse
```
? Well, that’s an implementation detail. As a practical example, looking at `glfw.cpp` reveals that the GLFW wrappers
```
Window
```
and
```
Mouse
```
know about each other and are able to work together to implement both
```
IWindow
```
and
```
IMouse
```
.
### Instantiation via Global Functions
The use of
```
ITypeFactory
```
is optional.
```
ITypeFactory
```
is not necessary for ABI-safety. It’s just a centralized mapping of type id’s to creation functions.
The creation functions are necessary for ABI-safety. Interfaces cannot have constructors because constructors must know about the implementation details of the object (memory layout, how to initialize members, etc). If interfaces had constructors, the constructors would need to know about implementation details, which means the interfaces would no longer be ABI-safe.
Creation functions get around this issue. Callers simply have to call a creation function which returns a fully instantiated object. No implementation details are exposed. They’re all hidden away in the implementation of the creation function.
What is the creation function doing? It’s more than likely calling the constructor of a concrete implementation of an interface. The implementation of the creation function is free to know all about the details of an interface implementation. What’s important is that none of the details leak outside the function. What is returned is an ABI-safe interface pointer.
Some implementations of interfaces may choose to expose this creation function directly to callers via a global function. For example, `example-glfw.dynamic.dll` exports:
```c++
OMNI_API IWindowSystem* exampleCreateGlfwWindowSystem();
```
If an application implicitly links to `example-glfw.dynamic.dll`, they can simply call
```
exampleCreateGlfwWindowSystem()
```
to instantiate the
```
IWindowSystem
```
implementation `example-glfw.dynamic.dll` provides. The same is true when statically linking to libraries (e.g. `example-glfw.a`). `example.windowing.no.plugin.app` shows how binary interfaces can be both statically and implicitly linked.
To demonstrate, notice that the implicitly linked version of the app grabs its
```
IWindowSystem
```
implementation from `example-glfw.dynamic.dll`:
```shell
> _build\windows-x86_64\debug\example.windowing.implicit.linking.app.exe
IWindowSystem provided by: 'c:/Users/ncournia/dev/carbonite/_build/windows-x86_64/debug/example-glfw.dynamic.dll'
```
The statically linked version of the app gets its
```
IWindowSystem
```
from within the .exe since the library was statically linked:
```shell
> _build\windows-x86_64\debug\example.windowing.static.linking.app.exe
IWindowSystem provided by: 'c:/Users/ncournia/dev/carbonite/_build/windows-x86_64/debug/example.windowing.static.linking.app.exe'
```
The explicitly loaded version of the app (i.e. the plugin version) grabs
```
IWindowSystem
```
from the plugin DLL:
```shell
>_build\windows-x86_64\debug\example.windowing.native.app.exe
IWindowSystem provided by: 'c:/users/ncournia/dev/carbonite/_build/windows-x86_64/debug/example-glfw.plugin.dll'
```
Even with global creation functions, applications are still free to additionally register creation functions with
```
ITypeFactory
```
. Doing so will enable other chunks of code (outside of the core application) to still use functions like
```
omni::core::createType<>()
```
. For example, `example-glfw.dynamic.dll` exports
```
exampleRegisterGlfwInterfaceImplementations()
```
to allow applications to explicitly register interface implementations in `omni-glfw.dynamic.dll`.
### Destroying an Interface
In the previous sections, we covered how there’s no ABI-safe way to call a constructor and covered the different ways users can safely instantiate objects via creation functions.
Like constructors, destructors are also not ABI-safe. Destructors must know about the memory layout of an object, an ABI-safety sin. Like creation functions, the details of destruction must be hidden away in a function to make destruction ABI-safe.
## ABI Interface Design
The `destroy_abi` method is designed for `IObject`. However, we already have a similar method: `IObject::release_abi()`. The `release_abi()` method decrements the reference count and destroys the object if the count hits 0. The details of destruction are hidden in `release_abi()` (behind the ABI).
Implementers should use the `Implements<>` template, which provides a reasonable implementation of `release_abi()`. Here’s its implementation:
```cpp
virtual void release_abi() noexcept override
{
if (0 == m_refCount.fetch_sub(1, std::memory_order_release) - 1)
{
std::atomic_thread_fence(std::memory_order_acquire);
delete this;
}
}
```
It’s safe for `release_abi()` to call its own destructor via `delete this`.
## Minimal SDK
ABI-safety allows code to be compiled once and work across multiple tool chains, SDK releases, etc. Omniverse interfaces define a simple ABI standard via `omni::core::IObject` and the rules outlined in [ABI Interface Design](#abi-interface-design).
The concept of the *Minimal SDK* builds upon Omniverse’s ABI-safe philosophy, providing a minimal feature set useful to nearly all applications. It includes:
- Interface instantiation (via `ITypeFactory`).
- Module loading.
- Module discovery.
- Logging.
- Interop to Carbonite and Kit interfaces.
Note that core ABI-safe concepts like `IObject`, `Inherits<>`, `Implements<>`, etc., do not depend on the Minimal SDK; rather, the Minimal SDK depends upon them. The Minimal SDK is provided by *carb.dll*.
### Dissecting *carb.dll*
We can examine what *carb.dll* provides using *dumpbin.exe*:
```shell
> dumpbin.exe /exports _build\windows-x86_64\debug\carb.dll
ordinal hint RVA name
1 0 0002BC40 acquireFramework = acquireFramework
2 1 0002BEC0 carbGetSdkVersion = carbGetSdkVersion
3 2 000AD5F0 carbReallocate = carbReallocate
4 3 0002BE70 isFrameworkValid = isFrameworkValid
5 4 000D0410 omniCoreStart = omniCoreStart
6 5 000D09D0 omniCoreStop = omniCoreStop
7 6 000CF080 omniCreateLog = omniCreateLog
8 7 000E0F60 omniCreateTypeFactory = omniCreateTypeFactory
9 8 000D01A0 omniGetBuiltInWithoutAcquire = omniGetBuiltInWithoutAcquire
10 9 000D0240 omniGetLogWithoutAcquire = omniGetLogWithoutAcquire
11 A 000D0370 omniGetModuleDirectory = omniGetModuleDirectory
```
12 B 000D0270 omniGetModuleFilename = omniGetModuleFilename
13 C 000D0340 omniGetStructuredLogWithoutAcquire = omniGetStructuredLogWithoutAcquire
14 D 000D11A0 omniGetTelemetryWithoutAcquire = omniGetTelemetryWithoutAcquire
15 E 000D0310 omniGetTypeFactoryWithoutAcquire = omniGetTypeFactoryWithoutAcquire
16 F 0002BF90 quickReleaseFrameworkAndTerminate = quickReleaseFrameworkAndTerminate
17 10 0002BEE0 releaseFramework = releaseFramework
We see carb.dll provides functionality for both Carbonite interfaces and Omniverse interfaces.
acquireFramework()
```
and
```
releaseFramework()
```
handle the initialization and shutdown of the Carbonite portion of the library. Internally,
```
acquireFramework()
```
instantiates a pre-determined implementation of
```
IFramework
```
, which it returns. It is the application’s responsibility to set the
```
g_carbFramework
```
variable, which many of Carbonite’s inline functions depend upon.
Likewise,
```
omniCoreStart()
```
and
```
omniCoreStop()
```
do the same for the Omniverse portion, except this time the goal is to create an instance of
```
ITypeFactory
```
. Here the approach differs from
```
tryAcquireInterface()
```
.
```
omniCoreStart()
```
accepts pointers to all of the interfaces needed by the Minimal SDK. If those pointers are
```
NULL
```
, default implementations are instantiated. Applications can call functions like
```
omniCreateTypeFactory()
```
to instantiate the needed inputs to
```
omniCoreStart
```
, though they’re free to provide their own implementations.
Omniverse relies on known function names rather than global variables. Many built-in interfaces such as
```
ITypeFactory
```
are accessed through a common function–
```
omniGetBuiltInWithoutAcquire()
```
–but every built-in interface has a specific accessor function around it. To access the application’s
```
ITypeFactory
```
, call
```
omniGetTypeFactoryWithoutAcquire()
```
. The benefit of using functions rather than a global variables is that the loader can link function symbols when statically or implicitly linking. Explicit linking provides its own challenges and is covered in Explicit Linking of Modules. Furthermore, the global variables are actually instanced per Carbonite module. By using an exported function in a dynamic library, the entire application can easily share the same instance of these built-in interfaces.
## Initializing the Minimal SDK
The Minimal SDK needs several global symbols. Each app should call
```
OMNI_APP_GLOBALS()
```
to declare the globals.
App’s should also initialize the Carbonite and Omniverse portions of carb.dll. This is easily done via the
```
OMNI_CORE_INIT()
```
macro:
```c++
#include <omni/core/Omni.h>
OMNI_APP_GLOBALS();
int main(int argc, char** argv)
{
OMNI_CORE_INIT(argc, argv);
/* ... */
}
```
The `OMNI_CORE_INIT()` macro handles several common tasks:
1. Instantiates `IFramework` and `ITypeFactory`.
2. Parses command-line arguments and populates global settings.
3. Loads an application specific configuration file.
4. Ensures objects like `IFramework` and `ITypeFactory` are properly destroyed upon program exit.
Use of `OMNI_APP_GLOBALS` and `OMNI_CORE_INIT` is optional. Applications are free to declare Carbonite’s needed globals and initialize
**carb.dll** in any way they see fit.
## Explicit Linking of Modules
An application is able to link to code in three different ways:
- **Static Linking**: Code is linked to an application at compile time.
- **Implicit Linking**: Shared code (e.g. .dll or .so) is implicitly loaded by the OS when the program starts.
- **Explicit Linking**: The application explicitly, while running, decides to call a function like `dlopen()` or `LoadLibrary()` to dynamically load code into its address space.
In previous sections, we covered how Omniverse interfaces supports static and implicit linking. In short:
- Implementations can provide a global function to register themselves with `ITypeFactory`. For example, `exampleGetGlfwInterfaceImplementations()`. This enables the application (and any modules it is utilizing) to use functions like `omni::core::createType<>()`.
- Implementations can provide global “creation” functions that hide the implementation details of instantiating an interface. For example, `exampleCreateGlfwWindowSystem()`.
With these two approaches, applications must, at compile time, utilize one (or both) of these approaches to access code in a static or dynamic library.
Explicit linking of modules (in Carbonite terminology “plugins”) is more involved but also more dynamic. The basic idea is simple: given a module name, `ITypeFactory` will open the module and call an exported function to get a list of the module’s capabilities and needs. We can see what functions are exported by a module with `dumpbin.exe`:
```shell
> dumpbin.exe /exports _build\windows-x86_64\debug\example-glfw.plugin.dll
ordinal hint RVA name
1 0 000034F0 omniModuleGetExports = omniModuleGetExports
```
Looking at `omniModuleGetExports`:
```c++
using ModuleGetExportsFn = Result(ModuleExports* out);
```
where `ModuleExports` is:
```c++
struct ModuleExports
{
//! Magic number. Used for sanity checking.
uint16_t magic;
//! Version of this structure. Changing this will break most modules.
uint16_t version;
//! Size of this structure. Here the size is sizeof(ModuleExports) + any extra space allocated at the end of this
//! struct for ModuleExportEntry's.
uint32_t byteCount;
//! Pointer to the first byte of the first ModuleExportEntry.
uint8_t* exportsBegin;
//! Pointer to the byte after the end of the last ModuleExportEntry.
uint8_t* exportsEnd;
/* inline methods omitted... */
};
```
When a module is loaded, `ITypeFactory` allocates a buffer and fills the beginning of the buffer with an initialized `ModuleExports` structure. `exportsBegin` points to the beginning of a key/value database used by the module to communicate its capabilities and needs. The module populates this database with macros such as `MODULE_EXPORTS_SET_EXPORTS()`. For example `glfw.cpp` has the following definition of `omniModuleGetExports()`:
```c++
OMNI_MODULE_API omni::Result omniModuleGetExports(omni::ModuleExports* out)
{
OMNI_MODULE_SET_EXPORTS(out);
OMNI_MODULE_ON_MODULE_LOAD(out, onLoad);
return omni::kResultSuccess;
}
```
Above,
```cpp
OMNI_MODULE_ON_MODULE_LOAD()
```
adds the following entry to the exports database:
```cpp
struct ModuleExportEntryOnModuleLoad
{
const char* type;
ModuleExportEntryFlag flags;
uint32_t byteCount;
onModuleLoadFn* onModuleLoad;
};
```
```cpp
ITypeFactory
```
will read the database and attempt to handle each key/value pair. For example, when the
```cpp
ModuleExportEntryOnModuleLoad
```
entry is encountered,
```cpp
ITypeFactory
```
will call
```cpp
onModuleLoad
```
to grab a list of public implementations from the module.
If
```cpp
ITypeFactory
```
encounters a key it does not recognize, it will be ignored unless the key’s
```cpp
flags
```
field has the
```cpp
fModuleExportEntryFlagRequired
```
bit set, in which case the module load is aborted. Likewise, if the module does not provide a key
```cpp
ITypeFactory
```
expects, it can abort loading the module.
The
```cpp
ModuleExports
```
structure allows for easy interop with Carbonite and Kit interfaces. In order to support Carbonite facilities such as
```cpp
g_carbFramework
```
in a module, the user should call one of the
```cpp
OMNI_MODULE_REQUIRE_CARB_*()
```
macros. For example, here’s how
test::IBar
uses the macros:
```cpp
OMNI_MODULE_GLOBALS();
CARB_GLOBALS("test.bar.plugin"); // declares carbonite globals g_carbFramework
OMNI_MODULE_API omni::Result omniModuleGetExports(omni::ModuleExports* out)
{
OMNI_MODULE_SET_EXPORTS(out);
OMNI_MODULE_ON_MODULE_LOAD(out, onLoad);
OMNI_MODULE_ON_MODULE_STARTED(out, onStarted);
OMNI_MODULE_ON_MODULE_CAN_UNLOAD(out, onCanUnload);
OMNI_MODULE_ON_MODULE_UNLOAD(out, onUnload);
OMNI_MODULE_REQUIRE_CARB_CLIENT_NAME(out); // tells ITypeFactory that g_carbClientName _must_ be defined
OMNI_MODULE_REQUIRE_CARB_FRAMEWORK(out);
return omni::kResultSuccess;
}
```
Above,
```cpp
OMNI_MODULE_REQUIRE_CARB_CLIENT_NAME
```
and
```cpp
OMNI_MODULE_REQUIRE_CARB_FRAMEWORK
```
are used to tell the loading
```cpp
ITypeFactory
```
that if it’s unable to fill the
```cpp
g_carbClientName
```
or
```cpp
g_carbFramework
```
pointers, the module load should fail.
### Module Life-Cycle
The life-cycle of a module is as follows:
| → Time → |
|-----------|
| omniModuleGetExports |
| onLoad |
| onStarted<br/>impl1->createFn<br/>impl2->createFn<br/>impl3->createFn |
| onCanUnload |
| onUnload |
Time flows from left-to-right.
```cpp
omniModuleGetExports
```
is first called to grab pointers to the other functions.
```cpp
omniModuleGetExports
```
will only be
called once.
onLoad is called to get a mapping of type id’s to creation functions. During the onLoad call, ITypeFactory is not accessible by the module. onLoad will only be called once.
Once onLoad returns, the registered creation functions can be called by the application and other modules.
In the diagram, functions within a column can be called in parallel. This leads to an oddity: the onStarted function may be called during, even after, a call to one of the module’s creation functions! It is up to the module to handle this race. A simple approach is to not define onStarted and lazily perform any one time initialization. onStarted, if defined, will only be called once.
If onCanUnload is defined, it will be called by ITypeFactory when the module is requested to be unloaded. If true is returned, onUnload is called, after which the module is unloaded from the application’s process space. onUnload, if defined, is only called once.
onCanUnload may be called multiple times (never in parallel). Once onCanUnload returns true it will never be called again.
onCanUnload and onUnload may not be called under certain circumstances. See Module Unloading for details.
## Module Unloading
A module’s onUnload method can be used to clean up any resources before the module is unmapped from the address space of the process.
onUnload is invoked via calls like omni::core:unregisterInterfaceImplementationsFromModule or the owning ITypeFactory’s destructor.
If onUnload is called, it is only ever called once. However, onUnload is not guaranteed to be called during the module’s lifetime. Following are cases where onUnload will not be called:
- onCanUnload is not exported.
- onCanUnload returns false.
- The owning ITypeFactory is destructed after main has returned and its stack frame has been popped (i.e. destructors in main()’s stack frame have run.
- The process abnormally exits (e.g TerminateProcess).
onUnload has access to the owning ITypeFactory. However, if onUnload is being called during the owning ITypeFactory’s destructor, the module will not be able to load additional modules.
## Module Example
In glfw.cpp, we can see the following module code:
```c++
OMNI_MODULE_GLOBALS()
namespace
{
omni::Result onLoad(const omni::InterfaceImplementation** out, uint32_t* outCount)
```
```c++
OMNI_LOG_ADD_CHANNEL(OMNI_LOG_CHANNEL);
static const char* interfacesImplemented[] = { "windowing.IWindowSystem" };
static omni::InterfaceImplementation impls[] = {
{
"windowing.IWindowSystem-glfw",
[]() { return static_cast<omni::IObject*>(new WindowSystem); },
1, // version
interfacesImplemented,
CARB_COUNTOF32(interfacesImplemented)
}
};
*out = impls;
*outCount = CARB_COUNTOF32(impls);
return omni::kResultSuccess;
```
```c++
OMNI_MODULE_API omni::Result omniModuleGetExports(omni::ModuleExports* out)
{
OMNI_MODULE_SET_EXPORTS(out);
OMNI_MODULE_ON_MODULE_LOAD(out, onLoad);
return omni::kResultSuccess;
}
```
Above we see:
- `OMNI_MODULE_GLOBALS` is called in the global scope to define needed globals.
- `omniModuleGetExports` is exported and given C-linkage via `OMNI_MODULE_API`.
- `OMNI_MODULE_ON_MODULE_LOAD` is called to tell the loading `ITypeFactory` about where to find implementation creation functions.
### Module Discovery
Module discovery, the process of finding modules to tell `ITypeFactory` about, is the job of the application. This can be as simple as explicitly registering a module:
```c++
omni::registerInterfaceImplementationsFromModule("c:/Users/ncournia/myApp/MyModule.dll");
```
In practice, many applications use the discovery mechanisms used by existing Carbonite interfaces, such as config files or Kit extensions.
### Versioning
Both interfaces and interface implementations can be independently “versioned”. Let’s start with interfaces.
#### Interface Versioning
The main idea behind Omniverse interface versioning is simple: an interface’s ABI is immutable. Once an interface like `IWindowSystem` is publicly released, its ABI will never change. Never. Methods cannot be added, removed, or reordered. Method signatures cannot change. Helper structs used to pass parameters in and out of the ABI are immutable as well.
This is powerful in its simplicity. Throughout time and space, given a `IWindowSystem` pointer, a user will always know the binary layout of the interface. There’s no guess work. There’s no version checks. There’s no fear of backwards and forwards compatibility. `IWindowSystem`’s binary layout is a universal constant. We call this versioning approach “customer oriented versioning” because it indexes on making it easier for customers to use Omniverse interfaces.
#### Adding Methods
If an interface’s ABI is immutable, how does one go about changing the interface? Again the answer is simple: you create a new interface. Let’s add a new method to `IWindowSystem` that controls the OS’s “night light” mode:
```c++
```
```c++
// new: we've added the IWindowSystem2 interface which inherits from IWindowSystem
class IWindowSystem2_abi : public omni::core::Inherits<IWindowSystem, OMNI_TYPE_ID("windowing.IWindowSystem2")>
{
protected:
virtual void setNightLightModeEnabled_abi(bool enable) noexcept = 0;
virtual bool isNightLightModeEnabled_abi() noexcept = 0;
};
```
Here we created a new interface `IWindowSystem2` which inherits all of the functionality of `IWindowSystem` but adds new night light methods.
We can now update our implementation of `IWindowSystem` in `glfw.cpp`:
```c++
// new: WindowSystem now implements IWindowSystem2 instead of IWindowSystem
class WindowSystem : public omni::Implements<omni::IWindowSystem2>
{
/* ... */
};
void getInterfaceImplementations(const omni::InterfaceImplementation** out, uint32_t* outCount)
{
// new: we denote that WindowSystem now implements both
// "windowing.IWindowSystem" and "windowing.IWindowSystem2"
static const char* interfacesImplemented[] = {
"windowing.IWindowSystem",
"windowing.IWindowSystem2" // new
};
static omni::InterfaceImplementation impls[] = {
{
"windowing.IWindowSystem-glfw",
[]() { return static_cast<omni::IObject*>(new WindowSystem); },
2, // new: bump version number
interfacesImplemented, CARB_COUNTOF32(interfacesImplemented)
}
};
*out = impls;
*outCount = CARB_COUNTOF32(impls);
}
```
Our interface registration function, `getInterfaceImplementations`, has now updated the `interfaceImplemented` field to denote that if the user requests either an `windowing.IWindowSystem` or an `windowing.IWindowSystem2` be created, then instantiating a `WindowSystem` is appropriate. We also chose to increment the implementation’s `version` fields. More on that later when we get to implementation versioning.
From a user’s point of view, the new functionality can be accessed in several ways.
```c++
// we can directly instantiate an IWindowSystem2
omni::ObjectPtr<IWindowSystem2> windowSystem = omni::createType<IWindowSystem2>();
// if we're given an IWindowSystem, we check to see if it's really an IWindowSystem2 via a call to cast<>()
```
```c++
void doWindowSystemStuff(IWindowSystem* windowSystem)
{
omni::ObjectPtr<IWindowSystem2> windowSystem2 = omni::cast<IWindowSystem2>(windowSystem);
if (windowSystem2)
{
windowSystem2->setNightLightModeEnabled(true);
}
}
```
An alternative approach to creating `IWindowSystem2` would be to create a new stand-alone interface:
```c++
// new: INightLightMode interface
class INightLightMode_abi :
public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("windowing.INightLightMode")>
{
protected:
virtual void setNightLightModeEnabled_abi(bool enable) noexcept = 0;
virtual bool isNightLightModeEnabled_abi() noexcept = 0;
};
```
This interface does not inherit from `IWindowSystem`, rather it’s a whole new interface unrelated to `IWindowSystem`.
Looking at the implementation:
```c++
// new: use multiple inheritance to implement both IWindowSystem and INightLightMode
class WindowSystem : public omni::Implements<IWindowSystem, INightLightMode>
{
/* ... */
};
void getInterfaceImplementations(const omni::InterfaceImplementation** out, uint32_t* outCount)
{
// new: we denote that WindowSystem now implements both
// "windowing.IWindowSystem" and "windowing.INightLightMode"
static const char* interfacesImplemented[] = {
"windowing.IWindowSystem",
"windowing.INightLightMode" // new
};
static omni::InterfaceImplementation impls[] = {
{
"windowing.IWindowSystem-glfw",
// note the intermediate cast to IWindowSystem to disambiguate conversion to IObject
[]() { return static_cast<omni::IObject*>(static_cast<IWindowSystem*>(new WindowSystem())); },
2, // new: bump version number
interfacesImplemented, CARB_COUNTOF32(interfacesImplemented)
}
};
*out = impls;
*outCount = CARB_COUNTOF32(impls);
}
```
The concrete `IWindowSystem` class is now using multiple inheritance to provide night light mode functionality.
User’s can use the interface as follows:
```c++
// we can directly instantiate an INightLightMode
omni::ObjectPtr<INightLightMode> nightLight = omni::createType<INightLightMode>();
// if we're given an IWindowSystem (or really any interface), we can check to
// see if it implements INightLightMode
void doWindowSystemStuff(IWindowSystem* windowSystem)
{
omni::ObjectPtr<INightLightMode> nightLight = omni::cast<INightLightMode>(windowSystem);
if (nightLight)
{
nightLight->setNightLightModeEnabled(true);
}
}
```
### Removing/Changing Methods
When removing/changing the functionality provided by an interface’s ABI, an entirely new interface must be created. You can’t inherit from the old interface. You have to duplicate it and remove/change the ABI functionality you don’t like.
The alternative, removing/changing a method in the ABI and not creating a new interface, causes chaos. You’ve changed a universal constant: the interface’s ABI. As a consequence, users are forced to perform version checks everywhere to make sure an interface like `IWindowSystem` really is the version of the interface they want.
All of this is a pain. Removing/changing functionality can be incredibly disruptive. We’ve purposely designed the versioning scheme to discourage it.
Rather than removing/changing functionality, consider adding new/alternative functionality and deprecating the old functionality.
### Pragmatic Interface Versioning
We’re all human. We change our minds. This is particularly true during the creative process. During the initial design phase of an interface, methods will be added, removed and changed. Creating a new interface for each of these changes would quickly lead to interface names like `IWindowSystem26`.
To avoid `IWindowSystem26`, we establish a simple engineering policy:
> Once published, an interface is immutable.
The goal of this versioning policy is reduce customer risk and ultimately make Omniverse a more attractive ecosystem.
### API Versioning
Surprisingly, an interface’s API is not versioned. Only the ABI is “versioned”.
We’re able to get away with this because the API is entirely inlined code. Users of an interface are free to fork interface header files and update the API at will. The API does not, and will never, affect the ABI.
### Implementation Versioning
Imagine releasing a DLL, `myContainers.plugin.dll`, which contains two implementations:
1. “my.List” which implements `IList`.
2. “my.HashTable” which implements `IHashTable`.
Later, you decide to release a new version of the DLL, `myContainers.2.plugin.dll`, this time with a bug fix to “my.List” and “my.HashTable” removed.
You notice that users are loading both `myContainers.plugin.dll` and `myContainers.2.plugin.dll` within the same application. They load `myContainers.2.plugin.dll` for the bug fix and `myContainers.plugin.dll` for the “my.HashTable” implementation.
`ITypeFactory` has a dilemma. There are two implementations of `IList` named “my.List”. Which one should be preferred?
As the implementation author, you can set a preference by setting the version number on the implementation:
```c++
void getInterfaceImplementations(const omni::InterfaceImplementation** out, uint32_t* outCount)
{
static const char* interfacesImplemented[] = { "IList" };
static omni::InterfaceImplementation impls[] = {
{
"IList",
"my.List",
"myContainers.2.plugin.dll",
2, // version
},
};
*outCount = sizeof(impls) / sizeof(impls[0]);
*out = impls;
}
```
```cpp
{
"my.List",
[]() { return static_cast<omni::IObject*>(new List); },
2, // version is 2
interfacesImplemented,
CARB_COUNTOF32(interfacesImplemented)
};
```
*out = impls;
*outCount = CARB_COUNTOF32(impls);
}
```
If an
**implementation**
has multiple entries, by default, the highest version is preferred.
Of course, there are multiple ways for users to override this behavior:
```cpp
// explicitly load version 1 of my.List
auto list = omni::createType<IList>(OMNI_TYPE_ID("my.List"), nullptr, 1));
// explicitly load the highest version of "my.List" from "myContainers.plugin.dll"
auto list = omni::createType<IList>(OMNI_TYPE_ID("my.List"), "myContainers.plugin.dll"));
// by default, when instantiating the IList interface, prefer the highest
// version of "my.List" from "myContainers.plugin.dll"
omni::setInterfaceDefaults<IList>(OMNI_TYPE_ID("my.List"), "myContainers.plugin.dll");
// will instantiate highest version of "myList" in "myContainers.plugin.dll"
auto list = omni::createType<IList>();
```
This gives implementation authors the ability to set a preferred implementation while giving the applications
fine-grained control over which implementation should be instantiated.
In Omniverse,
**implementations**
have a version number.
**Interfaces**
do not have a version number.
### Alternative Versioning Approaches Considered
During the design process of Omniverse Native Interfaces, several versioning schemes were considered.
#### Semantic Versioning
Carbonite’s interface versioning scheme uses Semantic Versioning. In practice, this approach is fraught with peril.
Consider, the following interface:
```cpp
namespace carb
{
struct Window; // opaque "context"
// interface method table
struct IWindowing
{
CARB_PLUGIN_INTERFACE("carb::windowing::IWindowing", 1, 0)
Window*(CARB_ABI* createWindow)(const WindowDesc& desc);
void(CARB_ABI* setWindowTitle)(Window* window, const char* title);
};
}
```
Happy with this interface, we compile and ship **carb.windowing.plugin.dll**.
A day later, we decide it would be nice to also get the window title:
```cpp
namespace carb
{
struct Window; // opaque "context"
// interface method table
struct IWindowing
{
// new: we bumped the minor version
CARB_PLUGIN_INTERFACE("carb::windowing::IWindowing", 1, 1)
// ... rest of the interface ...
};
}
```
Window* (CARB_ABI* createWindow)(const WindowDesc& desc);
void (CARB_ABI* setWindowTitle)(Window* window, const char* title);
// new
const char* (CARB_ABI* getWindowTitle)(Window* window);
};
};
Again, we compile and ship **carb.windowing.plugin.dll**.
The following day we decide we don’t like window titles at all, so we remove all of the window title functions:
namespace carb
{
struct Window; // opaque "context"
// interface method table
struct IWindowing
{
// new: we bumped the major version
CARB_PLUGIN_INTERFACE("carb::windowing::IWindowing", 2, 0)
Window* (CARB_ABI* createWindow)(const WindowDesc& desc);
// new: remove window title methods
};
};
A new day, a new **carb.windowing.plugin.dll**.
**myApp.exe** loads one of the three DLLs and instantiates the `IWindowing` interface:
IWindowing* windowing = carb::tryAcquireInterface<carb::IWindowing>();
Window* window = windowing->createWindow({ 640, 480 });
Which version of `IWindowing` was instantiated? We don’t know at compile time. A runtime check must be performed. `carb::tryAcquireInterface` does just that. After loading the DLL, `carb::tryAcquireInterface` checks to see if the loaded interface has a version compatible with the header used to compile the .exe.
Let’s create a new DLL, **windowUser.dll** that uses the generated Window context object:
void doWindowStuff(Window* window)
{
// ...
IWindowing* windowing = carb::tryAcquireInterface<carb::IWindowing>();;
printf("title: %s\n", windowing->getWindowTitle(window)); // crashes!
// ...
}
The DLL crashes. Why? `carb::tryAcquireInterface` performs a version check to make sure that the returned interface is compatible with the header used to compile **windowUser.dll**. Shouldn’t that be enough?
No. There’s no guarantee that the opaque `Window` context is compatible with the interface. Here ‘’Window’’ was created by another DLL that implements version 2.0 of the interface. The window title simply isn’t in the context.
A common way around this is to always keep the interface and context pointers together:
void doWindowStuff(IWindowing* windowing, Window* window)
{
// ...
printf("title: %s\n", windowing->getWindowTitle(window)); // still crashes!
// ...
}
```c++
// ...
```
```c++
}
```
Still a crash. Here, when
```c++
getWindowTitle
```
was called, it was assumed by
**windowUser.dll**
that the
**IWindowing**
pointer was a version of the interface that defined
```c++
getWindowTitle
```
. In the case above, the version was 2.0, which means the call to
```c++
getWindowTitle
```
points to garbage. Boom.
There’s a solution to this as well. Perform another runtime version check:
```c++
void doWindowStuff(IWindowing* windowing, Window* window)
{
// ...
if (carb::verifyInterface(windowing))
{
printf("title: %s\n", windowing->getWindowTitle(window)); // safe
}
// ...
}
```
Searching through existing code, you’ll find few instances where this pattern is used.
Another gotcha with semantic versioning is locking users into requiring the latest interface. Consider:
```c++
void doWindowStuff(IWindowing* windowing, Window* window)
{
// ...
if (carb::verifyInterface(windowing))
{
windowing->setWindowTitle("My Window"); // safe
}
// ...
}
```
The user originally writes this code during version 1.0 of the interface’s life and everything is great.
Let’s say the interface author releases version 1.1 of the interface (the version that added the
```c++
getWindowTitle
```
method). The user decides to recompile the code above and finds that his code no longer works with older clients! By recompiling the user code above, version 1.1 became a hard requirement, even though the code doesn’t use any version 1.1 functionality.
There’s too much burden put on interface users when using semantic labelling. Version checks have to be performed everywhere and evidence shows user simply aren’t performing those checks. Likewise, its easy to bake unneeded interface requirements into user code, causing perfectly fine code to stop working with older clients.
Omniverse interfaces take a different approach. Interfaces aren’t really “versioned”. They exist… immutable.
```c++
IWindow
```
is a known quantity. It’s ABI is guaranteed. Forever. There’s no guess work needed if some of the methods exist or don’t exist. No version checks are required.
But what about the
```c++
IWindowSystem2
```
example above? Isn’t that a different version of the
```c++
IWindowSystem
```
interface? No. It’s a different interface that happens to be compatible with
```c++
IWindowSystem
```
.
Isn’t
```c++
omni::cast<>()
```
a version check? No.
```c++
omni::cast<>()
```
is for checking if an interface pointer implements an interface. It’s not a version check, it’s a more akin to a
```c++
dynamic_cast
```
.
### Generated Smart Pointers
A criticism of Omniverse Native Interfaces is that in order to access desired functionality you need to know the proper pointer type. For example, given an
```c++
IWindowSystem
```
pointer, if you want to access the aforementioned night light functionality you must cast to the proper pointer type:
```c++
omni::ObjectPtr<IWindowSystem> ws = /* ... */
auto ws2 = omni::cast<IWindowSystem2>(ws); // cast to IWindowSystem2 to access setNightLightEnabled()
if (ws2)
{
ws2->setNightLightEnabled(false);
}
```
A different approach is to hide the cast in a helper class. Here, we define `WindowSystemPtr`:
```cpp
class WindowSystemPtr : public omni::core::ObjectPtr<IWindowSystem>
{
public:
// constructors omitted...
WindowPtr createWindow(uint32_t w, uint32_t h)
{
// since createWindow is an IWindowSystem method, no interface check is needed
return m_ptr->createWindow(w, h);
}
void setNightLightEnabled(bool en)
{
// m_ptr is a IWindowSystem. see if it implements IWindowSystem2
auto ws2 = omni::cast<IWindowSystem2>(m_ptr);
if (ws2)
{
ws2->setNightLightEnabled(en);
}
else
{
throw omni::core::InvalidInterface();
}
}
// other IWindowSystem2 methods omitted...
};
```
`WindowSystemPtr` is essentially `omni::core::ObjectPtr` but with wrappers to call all of the methods in the `IWindowSystem` class hierarchy. A tool like *omni.bind* could be updated to generate these interface specific smart pointers.
One thing to note with this approach is that “customer oriented versioning” is still required. ABI methods will still accept raw interface pointers like `IWindowSystem2` and the ABI is still defined as outlined in this document. Fundamentally, this approach is additional syntactic sugar in the API layer and compatible with the approach outlined in this document.
*Generated smart pointers* is promising and merits future investigation.
## Sharing Implementations
We’ve covered how Omniverse interfaces can take advantage of inheritance to gain the functionality of another interface. This not only reduces code duplication, it also enables rich interface hierarchies.
Interfaces are just contracts that describe the layout of a binary blob. To be useful things, you not only need the description, you also need the blob. You need an implementation.
At times it’s advantageous to create a novel implementation by inheriting from an existing implementation. Consider:
```cpp
// IComputeNode.h
class IComputeNode_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("graph.IComputeNode")>
{
protected:
virtual void setInput_abi(const char* name, IComputeNode* input) noexcept = 0;
virtual int compute_abi() noexcept = 0;
};
class IIntNode : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("graph.IIntNode")>
{
protected:
virtual void setInt_abi(int i) noexcept = 0;
};
```
// MyComputeNodes.cpp
template <typename T>
class BaseComputeNode : public omni::core::Implements<T>
{
protected:
virtual void setInput_abi(const char* name, IComputeNode* input) noexcept override
{
return m_inputs[name].borrow(input);
}
public:
int getInputValue(const char* name)
{
auto& input = m_inputs[name];
if (input)
{
return input->compute();
}
else
{
return 0;
}
}
private:
std::map<std::string, omni::core::ObjectPtr<IComputeNode>> m_inputs;
};
class IntNode : public BaseComputeNode<IIntNode>
{
protected:
virtual void setInt_abi(int i) noexcept override
{
m_int = i;
}
virtual int compute_abi() noexcept override
{
return m_int;
}
private:
int m_int = 0;
};
class AddNode : public BaseComputeNode<IComputeNode>
{
protected:
virtual int compute_abi() noexcept override
{
int a = getInputValue("a");
int b = getInputValue("b");
return a + b;
}
};
class MultiplyAddNode : public BaseComputeNode<IComputeNode>
{
protected:
virtual int compute_abi() noexcept override
{
int a = getInputValue("a");
int b = getInputValue("b");
// Additional logic here
}
};
```cpp
int c = getInputValue("c");
return a * b + c;
}
}
// main.cpp
auto a = createNode<IIntNode>();
a->setInt(1);
auto b = createNode<IIntNode>();
b->setInt(2);
auto add = createNode<IComputeNode>("add");
add->setInput("a", a);
add->setInput("b", b);
printf("a+b -> %d\n", add->compute());
```
In the example above, concrete implementations of `IComputeNode` were able to share a base implemention of an `IComputeNode` via the `BaseComputeNode` template. The author of `BaseComptueNode` could easily ship the `BaseComputeNode` implementation as an inline header.
### Carbonite / Omniverse Interop
When using the `OMNI_CORE_INIT` macro and linking to `carb.dll`, applications are able to use each of Carbonite, Kit, and Omniverse interfaces. Carbonite plugins are able to call Omniverse code and visa-versa. In fact, this feature is a part of the strategy to transition from Carbonite and Kit interfaces to Omniverse interfaces.
As an example, consider `source/omni.core/LogImpl.cpp`. Here we see that the `omni::log::ILog` implementation is a wrapper over `LogSystem`. Looking at `source/framework/LoggingPlugin.cpp` we see that `carb::logging::ILogging` also points to `LogSystem`. In short, we have two different interfaces pointing to the same implementation, meaning messages logged with `OMNI_LOG` are able to be written to the same log as messages logged with `CARB_LOG`. Calls to `CARB_LOG` can be removed over time in favor of `OMNI_LOG`.
### Conclusion
We’ve presented a new way to bring binary safe native interfaces to Omniverse. The approach presented has the following advantages over the current Carbonite interfaces:
- Safer code via tightly coupled data and methods
- Code reuse through inheritance
- Familiar C++-like usage
- Implicit linking in addition to static and explicit linking
- DLL’s can contain multiple implementations of an interface
- DLL’s can contain multiple versions of an implementation
- No runtime version checks
- Automatic generation of boiler-plate code and language bindings
- Inspired by COM, a known industry standard
We’ve also shown that Omniverse binary interfaces can:
- Wrap Carbonite interfaces.
- Replace Carbonite interfaces.
- Live along side Carbonite interfaces. | 80,250 |
on-apply-handler_Overview.md | # Overview — Omniverse Kit 2.10.33 documentation
## Overview
The file picker extension provides a standardized dialog for picking files. It is a wrapper around the `FileBrowserWidget`, but with reasonable defaults for common settings, so it’s a higher-level entry point to that interface. Nevertheless, users will still have the ability to customize some parts but we’ve boiled them down to just the essential ones. Why you should use this extension:
- Checkpoints fully supported if available on the server.
## Quickstart
You can pop-up a dialog in just 2 steps. First, create a dialog.
```cpp
dialog = FilePickerDialog("Demo Filepicker");
```
Then, invoke its show_window method.
```cpp
dialog.show();
```
## Customizing the Dialog
You can customize these parts of the dialog.
- Title - The title of the dialog.
- Collections - Which of these collections, ["bookmarks", "omniverse", "my-computer"] to display.
- Filename Url - Url of the file to process.
- Postfix options - Show only files of these content types.
- Extension options - Show only files with these filename extensions.
- Apply label - Label for the apply button.
- Apply handler - User provided callback to handle the apply process.
Note that these settings are applied when you show the window. Therefore, each time it’s displayed, the dialog can be tailored to the use case.
## Filter files by type
The user has the option to filter what files get shown in the list view.
```python
def on_filter_item(dialog: FilePickerDialog, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if dialog.current_filter_option == 0:
# Show only files with listed extensions
_, ext = os.path.splitext(item.path)
if ext in [".usd", ".usda", ".usdc", ".usdz"]:
```
<section id="file-picker-dialog">
<h2>
File Picker Dialog
<a class="headerlink" href="#file-picker-dialog" title="Permalink to this heading">
<p>
The file picker dialog allows users to select files.
<div class="highlight-python notranslate">
<div class="highlight">
<pre><span>
<span class="k">if
<span class="c1"># Show All Files (*)
<span class="k">return
<span class="k">else
<span class="k">return
<section id="options">
<h2>
Options
<a class="headerlink" href="#options" title="Permalink to this heading">
<p>
A common need is to provide user options for the file picker.
<div class="highlight-python notranslate">
<div class="highlight">
<pre><span>
<span class="k">with
<span class="k">with
<span class="n">ui
<span class="k">return
<section id="on-apply-handler">
<h2>
On apply handler
<a class="headerlink" href="#on-apply-handler" title="Permalink to this heading">
<p>
Provide a handler for when the ok button is clicked.
<div class="highlight-python notranslate">
<div class="highlight">
<pre><span>
<span class="sd">"""
<span class="sd"> The meat of the App is done in this callback when the user clicks 'Accept'. This is
<span class="sd"> a potentially costly operation so we implement it as an async operation. The inputs
<span class="sd"> are the filename and directory name. Together they form the fullpath to the selected
<span class="sd"> file.
<span class="sd"> """
<span class="c1"># Normally, you'd want to hide the dialog
<span class="c1"># dialog.hide()
<span class="n">dirname
<span class="k">if
<span class="n">dirname
<span class="n">fullpath
<span class="nb">print
<section id="demo-app">
<h2>
Demo app
<a class="headerlink" href="#demo-app" title="Permalink to this heading">
<p>
A complete demo, that includes the code snippets above, is included with this extension at
Python
.
| 3,921 |
OniWalkthrough.md | # Creating a New Omniverse Native Interface
## Warning
A common misconception is that Omniverse Native Interfaces can be changed over time, but this is **not correct**. Once created and released, Omniverse Native Interfaces are **immutable**. To add functionality, an Interface can be inherited into a new Interface that adds functionality, or a new separate Interface can be created. The process of doing this is also described in [Extending an Omniverse Native Interface](#extending-oni-interfaces-label).
## Warning
Omniverse Native Interfaces are Beta software and can be difficult to use. Active development by the Carbonite team has paused. If other contributors wish to develop improvements, the Carbonite team is willing to evaluate Merge Requests. [Carbonite Interfaces](#carbonite-interfaces) are actively supported.
Setting up the projects and definitions of a new interface can be a daunting prospect. This will be clarified by following the steps below. Below we will walk through the creation of a set of interfaces in a (pointless) plugin called `omni.meals`. These don’t do anything particularly useful, but should at least be instructional.
## Project Definitions
The first step is to create a new set of projects in a premake file (ie: `premake5.lua`). There will typically be three new projects added for any new Omniverse interface - the interface generator project, the C++ implementation project for the interface, and the python bindings project for the interface.
### Interface Generator Project
The interface generator project definition typically looks along the lines of the listing below. This project is responsible for performing the code generation tasks by running each listed header through `omni.bind`. The resulting header files will be generated at the listed locations. Any time one of the C++ interface headers is modified, this project will regenerate the other headers automatically. It is important that this project be dependent on `omni.core.interfaces` and that all other projects for the new set of interfaces be dependent on this project. Note that if python bindings aren’t needed for this interface, the `py=` parts of each line can be omitted.
```lua
project "omni.meals.interfaces"
location (workspaceDir.."/"%{prj.name}")
omnibind {
{ file="include/omni/meals/IBreakfast.h", api="include/omni/meals/IBreakfast.gen.h", py="source/bindings/python/omni.meals/PyIBreakfast.gen.h" },
{ file="include/omni/meals/ILunch.h", api="include/omni/meals/ILunch.gen.h", py="source/bindings/python/omni.meals/PyILunch.gen.h" },
{ file="include/omni/meals/IDinner.h", api="include/omni/meals/IDinner.gen.h", py="source/bindings/python/omni.meals/PyIDinner.gen.h" },
-- add one more line for each other interface header in the project.
}
dependson { "omni.core.interfaces" }
```
Note that calling the `omnibind` function will implicitly make your project have the “StaticLib” kind under premake. For this reason it is a good idea to keep the code generation projects separate from other projects that depend on it. However, It is possible to make an `omnibind` call inside a project that also builds other code (ie: in cases where only one project depends on the interface’s generated code). The only fallout from it will be that the project’s ‘kind’ will have to be reset after the `omnibind` call(s) if it is not intended to be a static library.
### C++ Implementation Project
The C++ implementation project definition looks very similar to any other C++ plugin project in Carbonite. This simply defines the important folders for the plugin’s implementation files, any dependent projects that need to be built first, and any additional platform specific SDKs, includes, build settings, etc. This should look similar to the listing below at its simplest. Initially the project does not need any implementation files. All of the .cpp files will be added later.
```lua
project "omni.meals.plugin"
define_plugin { ifaces = "include/omni/meals", impl = "source/plugins/omni.meals" }
dependson { "omni.meals.interfaces" }
```
### Python Bindings Project
If needed, the python bindings project defines the location and source files for the generated python bindings. Note that `omni.bind` does not generate a .cpp that creates and exports the bindings. Instead it generates a header file that contains a set of inlined helper functions that define the bindings. It is the responsibility of the project implementor to call each of those inlined helpers inside a `PYBIND11_MODULE(_moduleName, m)` block somewhere in the project. This is left up to the implementor so that they can also add extra custom members or values to the bindings if needed. Each generated inline helper function will return a `pybind11` class or enum object that can have other symbols, functions, values, or documentation added to them as needed.
```lua
project "omni.meals.python"
define_bindings_python {
name = "_meals", -- must match the module name in the PYBIND11_MODULE() block.
folder = "source/bindings/python/omni.meals",
namespace = "omni/meals"
}
dependson { "omni.meals.interfaces" }
```
### Creating the C++ Interface Header(s)
Once the projects have been added, all of the C++ header files that were listed in the `omni.meals.interfaces` project need to be added to the tree and filled in. The headers that need to be created are specific to your new interface. Continuing with our example here, these headers should be created:
```c++
// file 'include/omni/meals/ILunch.h'
#pragma once
#include <omni/core/IObject.h>
namespace omni
{
namespace meals
{
// we must always forward declare each interface that will be referenced here.
class ILunch;
// the interface's name must end in '_abi'.
class ILunch_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.meals.ILunch")>
{
protected: // all ABI functions must always be 'protected' and must end in '_abi'.
virtual bool isTime_abi() noexcept = 0;
virtual void prepare_abi(OMNI_ATTR("c_str, in") const char* dish) noexcept = 0;
virtual void eat_abi(OMNI_ATTR("c_str, in") const char* dish) noexcept = 0;
};
} // namespace meals
} // namespace omni
```cpp
#include <omni/meals/IDinner.h>
namespace omni
{
namespace meals
{
class Breakfast : public omni::core::Implements<omni::meals::IBreakfast>
{
public:
Breakfast();
~Breakfast();
// ... other internal declarations here ...
protected: // all ABI functions must always be overridden.
bool isTime_abi() noexcept override;
void prepare_abi(const char* dish) noexcept override;
void eat_abi(const char* dish) noexcept override;
private:
bool _needToast();
bool m_withToast;
};
// ... repeat for other internal implementation class declarations here ...
} // namespace meals
} // namespace omni
```
In the above example, each class is implemented separately internally. This is perfectly acceptable. However, all related objects may also be implemented with a single internal class if it makes logical sense or saves on code duplication. In this case, merging the implementations into a single class does not work since all of the interfaces need to implement the same three methods. However, if all the interfaces being implemented have mutually exclusive function names, a single class that simply inherits from all of the interfaces could be used. The only modification to the above example would be to add multiple API class names to the omni::core::Implements invocation in the class declaration.
## Module Startup Source
The task of the module startup source file is to define startup and shutdown helper functions, define any additional callbacks such as ‘on started’ and ‘can unload’, and define the module exports table. These can be done with code along these lines:
```cpp
// file 'source/plugins/omni.meals/Interfaces.cpp'.
#include "Meals.h"
OMNI_MODULE_GLOBALS("omni.meals.plugin", "plain text brief omni.meals plugin description");
namespace // anonymous namespace to avoid unnecessary exports.
{
omni::core::Result onLoad(const omni::core::InterfaceImplementation** out, uint32_t* outCount)
{
// clang-format off
static const char* breakfastInterfaces[] = { "omni.meals.IBreakfast" };
static const char* lunchInterfaces[] = { "omni.meals.ILunch" };
static const char* dinnerInterfaces[] = { "omni.meals.IDinner" };
static omni::core::InterfaceImplementation impls[] =
{
{
"omni.meals.breakfast",
[]() { return static_cast<omni::core::IObject*>(new Breakfast); },
1, // version
breakfastInterfaces, CARB_COUNTOF32(breakfastInterfaces)
},
// ... repeat for other meals ...
};
*out = impls;
*outCount = CARB_COUNTOF32(impls);
return omni::core::Result::Success;
}
} // anonymous namespace
```
{
"omni.meals.lunch",
[],() { return static_cast<omni::core::IObject*>(new Lunch); },
1, // version
lunchInterfaces, CARB_COUNTOF32(lunchInterfaces)
},
{
"omni.meals.dinner",
[],() { return static_cast<omni::core::IObject*>(new Dinner); },
1, // version
dinnerInterfaces, CARB_COUNTOF32(dinnerInterfaces)
};
*out = impls;
*outCount = CARB_COUNTOF32(impls);
return omni::core::kResultSuccess;
void onStarted()
{
// ... do necessary one-time startup tasks ...
}
bool onCanUnload()
{
// ... return true if unloading the module is safe ...
}
void onUnload()
{
// ... do necessary one-time shutdown tasks ...
}
};
OMNI_MODULE_API omni::core::Result omniModuleGetExports(omni::core::ModuleExports* out)
{
OMNI_MODULE_SET_EXPORTS(out);
OMNI_MODULE_ON_MODULE_LOAD(out, onLoad);
OMNI_MODULE_ON_MODULE_STARTED(out, onStarted);
OMNI_MODULE_ON_MODULE_CAN_UNLOAD(out, onCanUnload);
OMNI_MODULE_ON_MODULE_UNLOAD(out, onUnload);
// the following two lines are needed for Carbonite interface interop. This includes any implicit use of
// other Carbonite interfaces such as logging, assertions, or acquiring other interfaces. If no Carbonite
// interface functionality is used, these can be omitted.
OMNI_MODULE_REQUIRE_CARB_CLIENT_NAME(out);
OMNI_MODULE_REQUIRE_CARB_FRAMEWORK(out);
return omni::core::kResultSuccess;
}
```
## C++ Interface Implementation Files
All that remains is to add the actual implementation file(s) for your new interface(s). These should not export
anything, but should just provide the required functionality for the external ABI. The details of the implementation
will be left as an exercise here since they are specific to the particular interface being defined.
## Loading an Omniverse Interface Module
An Omniverse interface module can be loaded as any other Carbonite plugin would be loaded. This includes searching
for and loading wildcard modules during framework startup, or loading a specific library directly. Once loaded, the
interfaces offered in the library should be registered with the core type factory automatically. The various
objects offered in the library can then be created using the
`omni::core::createType<>()` helper template.
## Troubleshooting
When creating a new Omniverse interface and all of its related projects, there are some common problems that can come
up. This section looks to address some of those potential problems:
- G041F212F:
class
template
specialization
of
'Generated'
not
in
a
namespace
enclosing
'core'
is
a
Microsoft
extension
[-Wmicrosoft-template]
: this warning on MSVC is caused by including the generated C++ header from inside
the namespace of the object(s) being declared. The generated header should always be included from the global
namespace scope level.
- when moving an interface declaration from one header to another or renaming a header,
omni.bind
will error out
on the first build because it wants to process the previous API implementation first to check for changes. It will
report that the deleted interface no longer exists. However, in this case the new header will still be generated
correctly and the rest of the project will still build successfully. Running the build again, including the
omni.bind
step, will succeed. Since an existing ABI should never be removed, the only legitimate use case for
this situation is in changes during initial development or in splitting up a header that originally declared multiple
interfaces.
- structs that are passed into omni interface methods as parameters may not have any members with default initializers.
If a member of the struct has a default initializer,
omni.bind
will give an error stating that the use of the
struct is not ABI safe. This is because the struct no longer has a trivial layout when it has a default initializer
and is therefore not ABI safe. | 12,880 |
Open.md | # Welcome screen: OPEN
## Open Stage
Quick new stage from templates or open recent stage.
- to switch list view and grid view for recent stages
## Open Sample
View samples and quick open.
## Open File
View files and quick open. | 231 |
options_Overview.md | # Overview — Omniverse Kit 2.10.33 documentation
## Overview
The file picker extension provides a standardized dialog for picking files. It is a wrapper around the `FileBrowserWidget`, but with reasonable defaults for common settings, so it’s a higher-level entry point to that interface. Nevertheless, users will still have the ability to customize some parts but we’ve boiled them down to just the essential ones. Why you should use this extension:
- Checkpoints fully supported if available on the server.
## Quickstart
You can pop-up a dialog in just 2 steps. First, create a dialog.
```cpp
dialog = FilePickerDialog("Demo Filepicker");
```
Then, invoke its show_window method.
```cpp
dialog.show();
```
## Customizing the Dialog
You can customize these parts of the dialog.
- Title - The title of the dialog.
- Collections - Which of these collections, ["bookmarks", "omniverse", "my-computer"] to display.
- Filename Url - Url of the file to process.
- Postfix options - Show only files of these content types.
- Extension options - Show only files with these filename extensions.
- Apply label - Label for the apply button.
- Apply handler - User provided callback to handle the apply process.
Note that these settings are applied when you show the window. Therefore, each time it’s displayed, the dialog can be tailored to the use case.
## Filter files by type
The user has the option to filter what files get shown in the list view.
```python
def on_filter_item(dialog: FilePickerDialog, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if dialog.current_filter_option == 0:
# Show only files with listed extensions
_, ext = os.path.splitext(item.path)
if ext in [".usd", ".usda", ".usdc", ".usdz"]:
```
```python
def show_files_fn():
if ui.Button("Show All Files").clicked():
return True
else:
return False
else:
# Show All Files (*)
return True
```
## Options
A common need is to provide user options for the file picker.
```python
def options_pane_build_fn(selected_items):
with ui.CollapsibleFrame("Reference Options"):
with ui.HStack(height=0, spacing=2):
ui.Label("Prim Path", width=0)
return True
```
## On apply handler
Provide a handler for when the ok button is clicked.
```python
def on_click_open(dialog: FilePickerDialog, filename: str, dirname: str):
"""
The meat of the App is done in this callback when the user clicks 'Accept'. This is
a potentially costly operation so we implement it as an async operation. The inputs
are the filename and directory name. Together they form the fullpath to the selected
file.
"""
# Normally, you'd want to hide the dialog
# dialog.hide()
dirname = dirname.strip()
if dirname and not dirname.endswith("/"):
dirname += "/"
fullpath = f"{dirname}{filename}"
print(f"Opened file '{fullpath}'.")
```
## Demo app
A complete demo, that includes the code snippets above, is included with this extension at
Python. | 3,061 |
Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create a C++ widget for omni.ui that has a property and draws a simple rectangle. | 209 |
overview_external.md | # Launcher Overview
The NVIDIA Omniverse™ Launcher is your first step into the Omniverse. Giving you immediate access to all the apps, connectors and other downloads the Omniverse Launcher is your gateway to the Omniverse. You can download the launcher here.
![Omniverse Launcher Screenshot](_images/launcher_exchange_overview.png)
Click [here](installing_launcher.html) for Launcher installation instructions.
## Features
### Quick Access to Omniverse Apps
With an intuitive Interface, Launcher allows a lightning quick experience for opening Omniverse Apps.
### Updating Made Easy
Staying current is easy with Omniverse Apps and Connectors. The Launcher provides all you need to download, install, and update Omniverse Apps and Connectors through an elegant user interface.
![Omniverse Launcher interface](_images/launcher_updates_overview.png)
When you see a green bell icon next to an app, that means a new version is available. Click the hamburger icon next to “Launch” to open the version dropdown, then click the green “Install/bell icon” to install the latest version.
![Omniverse Launcher new app version alert](_images/ov_user_interface_bell_update.png)
### Learning Content
With quick easy access links, the Launcher puts all the help you need front and center. Learn via video tutorials, documentation or other Omniverse users on the Omniverse Forums. Whatever way you wish to learn, Launcher makes available.
![Learning content inside the Omniverse Launcher](_images/launcher_learning_overview.png)
### Get Connected
Entering the Omniverse is much easier when you do so through tools you are already familiar with. Launcher offers quick access to download and install Omniverse Connectors. These Connectors allow applications like Maya, 3Ds-Max, Revit and many other DCC Applications to contribute to an Omniverse project.
Interested in learning more?
Open the Omniverse Launcher documentation portal | 1,926 |
package.md | # Package a Build
At the conclusion of your development and testing phases, packaging your project is often necessary in preparation for publishing. While some extensions may not require this step, it becomes essential for applications and more complex extensions involving advanced features. The packaging process organizes and structures your project assets for delivery and deployment. The specifics of the packaging step depend on your desired method of distribution.
## Introduction
Please ensure that you are following the NVIDIA Omniverse License Agreement when developing your project. If you intend to distribute your project outside your company, it must use thin packaging.
**Important Notes:**
- Packaging is OS dependent. Linux is required for Linux packages and Windows is required for Windows packages.
- Packaging requires a build of the desired Project. See Build a Project for additional details.
- Instructions provided here assume use of Repo tooling.
Packages are a collection of all the files that compose your Project. Although it is possible to manually assemble your package by creating an archive with the necessary files and folders, Omniverse conveniently offers a more efficient alternative via the Repo Package tool. This tool verifies that you have all the essential config files and that your build folder is accurately configured.
## Packaging Extensions
It’s important to note that sometimes, specifically with simpler extensions, you may only need to manually copy the files into the destination directory for distribution. Generally, the repo package method is best used for projects that contain a `premake5.lua` file and result in a `_build` folder.
## Packaging Applications
### Lock Extension Versions
Before packaging, it is advised to lock your Extension versions. While iterative development typically benefits from using the latest versions without specifying one, it’s good practice to lock Extension versions for distributed Applications. This ensures that end users install and experience the fully tested and developed version.
The following steps apply if you’re working on a Kit project that includes the Repo tool, like the kit-app-template, for example.
To lock Extension versions:
1. Build the Project
2. Open the `repo.toml` file (most likely in the root directory of the project) and insert a reference to the application
1. Add the `.kit` file to the `[repo_precache_exts]` section:
```
[repo_precache_exts]
```
2. Code block:
```c++
[repo_precache_exts]
# Apps to run and precache
apps = [
"${root}/source/apps/my_company.my_app.kit",
]
```
3. Run the command `repo precache_exts -u`.
4. Open the `.kit` file. There should be a section labeled `BEGIN GENERATED PART`. This is where Extension versions have been locked.
### 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.
Open `.\kit-app-template\premake5.lua`.
Note this section:
```console
-- 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"
})
```
Run a build.
A `my_company.usd_explorer.warmup.bat.sh` file was created in the build directory.
To prepare for a Launcher package, open `.kit-app-templatesourcelauncherlauncher.toml`.
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"
...
```
### Create the Package
There are primarily two types of packages: ‘Fat’ and ‘Thin’.
- **‘Fat’ Package**: Includes all the necessary components to run the app, encompassing both the Kit Kernel and all Extensions. This is the package type you should opt for if you don’t want end users to download anything during installation. It is particularly useful in environments without access to public repositories, such as air-gapped organizations.
- **‘Thin’ Package**: Contains the bare essentials needed for an installation, necessitating the download of the Kit Kernel and Extensions during app installation. Thin packages optimize the use of local storage by only downloading components that other thin packaged apps haven’t already downloaded. However, this package type isn’t suitable for air-gapped environments.
Both ‘fat’ and ‘thin’ packages come as zip-archives and can be directly shared with end users.
A variant is the ‘Launcher’ Package. This type includes either a ‘fat’ or ‘thin’ application package along with additional resources, enabling the application to be listed in the Omniverse Launcher.
Both fat and thin packages can be renamed - nothing inside the package depends on the package name.
#### Fat Package
1. Build the Project
2. Execute `repo package`.
3. Package is created in the `.\_build\package` directory.
#### Thin Package
1. Build the Project
2. Execute `repo package`.
3. Package is created in the `.\_build\package` directory.
## Build the Project
1. Build the Project
2. Execute `repo package --thin`.
3. Package is created in the `.\_build\package` directory.
## Connectors
**Note**
There is no set method for packaging connectors. Please reference the **Connect Sample** and associated documentation for best practices. | 6,325 |
packaging-and-publishing_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 `repo.bat list_published`.
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
```markdown
### 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. | 19,950 |
Packaging.md | # Packaging
All packaging and related operations are handled by packman. This repo contains the version of packman you should be using when working with the repo. It can be found under tools/packman. To execute packman simply run from Linux or Windows shell:
```bash
tools/packman/packman
```
from the root of the repo (or change directory to that path). This guide focuses on the specific operations you will be doing with packman in conjunction with this repo. If you want more information please consult the packman repo or use the packman help command, i.e. execute `packman help`.
> **NOTE:** Never replace a package by overwriting it on the remote server unless you are the only person that has ever used that package. You can overwrite a package on the server by providing the `--force` argument but only use this when you know that nobody else has consumed the older package. If you cannot be certain of this please just bump the version number. If there is no actual change to the package other than fixes (maybe missed some files first time you packaged) then just add another version number at the end and set it to 1. For example: busted package had version 1.2.3 - your patched package is 1.2.3-1. It should also be noted that we use AWS CloudFront which is a proper CDN so even if you overwrite a package in good faith (because you have been the only consumer of it) it may take the CDN up to 24 hours to flush its cache and pick up your altered package.
## Staging dependencies
Before you package your dependency, like a third party library, you should stage it within the packman packages cache. This cache is located in a central place on your system. The environment variable `PM_PACKAGES_ROOT` will inform you where it is. The best way to stage a dependency is to create a folder under `PM_PACKAGES_ROOT` that is named after the dependency and then a subfolder in there that is named after the version.
Depending on the nature and size of the dependency you may want to create a universal package, i.e one that works for all OSs and architectures or split it up into three packages, one for each OS and CPU architecture. The choice is yours. The only requirement is that if you create separate packages you specify exactly the platform by including one of:
- windows-x86_64
- linux-x86_64
- linux-aarch64
in the package name or version.
Let’s take doctest as an example. This is a universal package so it does not have a platform qualifier in its name. If you were to stage this package for packaging you would have put the contents inside the folder:
```bash
$PM_PACKAGES_ROOT/doctest/2.3.5-0b0a374
```
This assumes the version we are using is 2.3.5-0b0a374. We will elaborate on version numbers a bit later (section 6).
After doing so you can now refer to the dependency in your dependency file. These files are stored under the `deps` folder in this repo. There is a target-deps if you want to see what they look like. Here is what it could look like:
```xml
<project toolsVersion="6.11" chroniclePath="../_build/chronicles">
<dependency name="doctest" linkPath="../_build/target-deps/doctest">
<package name="doctest" version="2.3.5-0b0a374" />
```
```xml
<dependency name="vulkansdk" linkPath="../_build/target-deps/vulkansdk">
<package name="vulkansdk" version="1.1.73.0-win" platforms="windows-x86_64" />
<package name="vulkansdk" version="1.1.73.0-linux-x86_64" platforms="linux-x86_64" />
<package name="vulkansdk" version="1.1.73.0-linux-aarch64" platforms="linux-aarch64" />
When packman is run with this updated deps.packman.xml file it will find the package already in your local packman cache and will therefore not look for it on the remote server (where it doesn’t yet exist).
This example is rather trivial because DocTest is a library that works for all platforms. A more complex example would be the Vulkan SDK. This is what the dependency specification looks for Vulkan SDK:
```xml
<dependency name="vulkansdk" linkPath="../_build/target-deps/vulkansdk">
<package name="vulkansdk" version="1.1.73.0-win" platforms="windows-x86_64" />
<package name="vulkansdk" version="1.1.73.0-linux-x86_64" platforms="linux-x86_64" />
<package name="vulkansdk" version="1.1.73.0-linux-aarch64" platforms="linux-aarch64" />
```
There are a few things to highlight here. Firstly, we only user lower case letters in package names since packman is case sensitive and so is the Linux file system. Secondly, the packages above were correctly versioned for both Linux architectures but not for Windows - should have been versioned as `version="1.1.73.0-windows-x86_64"`. If that had been the case the dependency could have been simplified to the following:
```xml
<dependency name="vulkansdk" linkPath="../_build/package-links/vulkansdk">
<package name="vulkansdk" version="1.1.73.0-${platform}" />
```
In this case we are taking advantage of packman’s variable substitution capability to insert the platform name into the version. Let’s say that in this example you are working on Linux and targeting `linux-x86_64`. You have already staged the corresponding Vulkan SDK in `$PM_PACKAGES_ROOT/vulkansdk/1.1.73.0-linux-x86_64`. When you run the build script to target this platform packman will find the version of the package which you have already staged. This will prevent packman from going out to the remote server and try to find the package there. Instead it will happily move on and perform the folder linking that is instructed by the `linkPath` attribute in the xml file above. In other words, packman will create a file system link from its internal cache, where you staged the dependency, to the target directory `_build/package-links/vulkansdk`. This allows you to test your dependency and make sure everything works as expected. Once that is done you can move to the next step.
## Licensing
Please read the Package Licensing for packman and follow the steps in there - otherwise your package will fail license validation during the CI build process.
## Packaging dependencies
It is assumed you have followed the steps in item 1. If the package is already available on a public HTTP(S) server, like GitHub, and can be consumed directly (zip/7z) there is no need to package it. You can simply configure a HTTP(s) remote server in the packman dependency file. This is for instance done with slang, like this:
```xml
<remote name="github-slang" type="https" packageLocation="github.com/shader-slang/slang/releases/download/v${version}/slang-${version}-win64.zip" />
<dependency name="slang" linkPath="../_build/package-links/slang">
<package name="slang" version="0.10.29" platforms="windows-x86_64" remotes="github-slang" />
```
And you are done! You can stop reading this guide.
If this is not the case you need to package your dependency. This is simply done with the following command:
```bash
./packman pack <path-to-version-folder>
```
In the example from item 1 this would be:
```bash
./packman pack $PM_PACKAGES_ROOT/doctest/2.3.5-0b0a374
```
Packman will tell you where the resulting package was placed (for more options on pack command simply run `packman pack -h` or get the detailed help by running `packman help pack`).
## Pushing dependencies
You now want to push your package to remote storage. This allows others to get your package. Before you can do this you must configure credentials in your packman user settings that allow you to write to remote storage. The packman command will launch this information for you automatically if you attempt upload without proper credentials but here is the direct link. Once you have completed that configuration you can upload this way:
```bash
./packman push <path-to-package> --remote mycloudfront
```
This will upload the package to our CDN that is configured for Carbonite.
NOTE: If you feel really solid about this process you can perform packaging and pushing in one step, using
the
```code
publish
```
command. Execute
```code
packman publish -h
```
to learn more.
## Verification
Move the staged version of the dependency to a different location on your system or rename the version folder.
When you run the project generation or build process the dependencies will be fetched and written to the packages
cache. Note that they go under a ‘chk’ folder inside the PM_PACKAGES_ROOT. This is simply because packman has now
generated a checksum for the package during unpacking so it can verified as intact later.
## Capturing for traceability and maintenance
For legal reasons we need to capture the software in source control to simplify auditing. This is also beneficial
when we are forced to make modifications to the external package, be it source code or build process. This way we can
track the changes and reapply them when we upgrade to newer releases of the third party library.
We collect these libraries under the omniverse/externals subgroup in GitLab. For historical reasons we also have some captured under
Carbonite-externals.
The process is straight-forward:
- Create a repo named after the third party library (preferably all in lowercase, matching the package name)
- Seed this repo via a mirror from GitLab.com or GitHub.com or simply with a copy of the source code
- Create a branch where all NVIDIA modifications are made, this branch should have `nvidia` or `nv` in the branch name,
for example: `nvidia` and `nv-main` are both acceptable branch names.
- Often times we need to weed out runtime dependencies that are leaking out of the library, see Architecture for details.
- You must create a build.{bat|sh} script that builds the software, preferably not requiring any manually installed
external dependencies (use packman to automatically provision them). You are exempt from this rule if the package is
header-only.
- You must create a package.{bat|sh} script that packages the software, ready for pushing to packman remote server.
- Look at imgui repo for a good example of how to do this.
- If you are not using a mirror then upgrading to a newer version of the third party library is simply done by switching
to the `main` branch, deleting all the files (except for the .git folder) and copy in the new snapshot. Commit those changes.
Then merge that branch into your nvidia branch and resolve, picking up the changes that you had previously made on the
older version.
You will notice from the above that we capture the packaging script as well in the repo and this makes it easier for
others to produce a new version of the package after updating the repository. | 10,563 |
parse-messages-as-json-and-push-to-message-bus_Overview.md | # Parse messages as json and push to message bus
Provides json messaging functionality between Kit and the web client using generic messaging such as omni.kit.gfn or omni.kit.streamsdk.plugins.
It takes a message bus event of event_type `omni.kit.livestream.receive_message` and payload `{"event_type": "SetColor", "payload": {...}}` and parses the payload as json and pushes a new event on the bus with event_type `SetColor` and the `payload` unpacked to the event payload dictionary.
It also provides an API to register custom event types to listen to for sending to the client using the generic `omni.kit.livestream.send_message` event type.
```python
import omni.kit.livestream.messaging as messaging
messaging.register_event_type_to_send("SetColor")
```
``` | 766 |
PassCreation.md | # Pass Creation
This is a practitioner’s guide to using the Execution Framework. Before continuing, it is recommended you first review the Execution Framework Overview along with basic topics such as Graphs Concepts, Pass Concepts, and Execution Concepts.
There are two parts to adding a new pass to the pass pipeline. First, we need to define the new pass and then we need to register it.
There are multiple types of passes supported in EF. A full list can be found at PassType. To create a pass, we start by implementing the relevant pass type’s interface. In practice, this will be either IPopulatePass or IPartitionPass. In rare cases, a pass may inherit from IGlobalPass, but such a pass is discouraged for performance reasons. Implementing population and partition passes is covered below.
Once a pass is implemented, it must be registered with one of the following macros: OMNI_GRAPH_EXEC_REGISTER_POPULATE_PASS(), OMNI_GRAPH_EXEC_REGISTER_PARTITION_PASS(), OMNI_GRAPH_EXEC_REGISTER_GLOBAL_PASS().
## Registration code for different pass types. These macros should be called at global scope.
```cpp
// Register MyPopulatePass against a symbol (node or node graph def) name
OMNI_GRAPH_EXEC_REGISTER_POPULATE_PASS(MyPopulatePass, "symbol_name");
// Register MyPartitionPass with a given priority
OMNI_GRAPH_EXEC_REGISTER_PARTITION_PASS(MyPartitionPass, 1);
// Register MyGlobalPass
```
# Implementing a Populate Pass
The example below implements a new populate pass that will instantiate a new `MyInstancedDef` definition and attach it to any node or definition that matches the name given during registration.
```c++
class TestPopulateInstances : public Implements<IPopulatePass>
{
public:
TestPopulateInstances(IGraphBuilder*) noexcept
{
}
void run_abi(IGraphBuilder* builder, INode* node) noexcept override
{
omni::core::ObjectPtr<TestNodeGraphDef> nodeGraphDef{ TestNodeGraphDef::create(builder, "MyInstancedDef") };
builder->setNodeGraphDef(node, nodeGraphDef);
}
};
```
Here, we register the pass, telling EF that this pass should be run on nodes named “my.special.node”.
```c++
OMNI_GRAPH_EXEC_REGISTER_POPULATE_PASS(TestPopulateInstances, "my.special.node");
```
We can also register the pass to run on nodes with a definition named “my.def.special” already attached to the node.
```c++
OMNI_GRAPH_EXEC_REGISTER_POPULATE_PASS(TestPopulateInstances, "my.def.special");
```
Above, we see that the name given during registration can match either the node name or definition name. See [Pass Concepts](#ef-pass-concepts) to better understand EF’s algorithm for running population passes.
# Implementing a Partition Pass
In this example, we will be partitioning the following graph using either manual or automatic partition generation
```c++
// ┌───────────────────┐
// │┌─────── B ───────┐│
// ││┌────┐ ┌────┐││
// │││ Ax ├─┬──►│ Bx │││
// ││└────┘ │ └────┘││
// ││ │ ┌────┐││
// ││ └──►│ Cx │││
// ││ └────┘││ ┌────┐
// ┌──────►│└─────────────────┘│ ┌─►│ I ├─┐
// │ └───────────────────┘ │ └────┘ │
// ┌────┐ │ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │ ▼ ┌────┐
// │ A ├──┬─┴──────►│ Cx ├─┬──►│ Dx │────┬──►│ A2 ├───►│ H ├─┬┴─────────┴─►│ J │
// └────┘ │ └─┬──┘ │ └────┘ │ └────┘ └────┘ │ └────┘
// │ │ │ ┌────┐ │ │ ┌────┐
// │ │ └──►│ Ex │ │ └────────────►│ K │
// │ │ └────┘ │ └────┘
// │ └──────────────────┘
// │ ┌────┐ ┌────┐
// └─────►│ Fy ├────►│ Gy │
```
// └────┘ └────┘
//
// Nodes with matching definition (B/Ax, Cx, Fy, H), (B/Bx, Dx, Gy, J), (B/Cx, Ex, K)
//
```
```markdown
The task for our first partition pass will be to recognize two clusters of nodes
(B/Ax, B/Bx, B/Cx)
and
(Cx, Dx, Ex)
, but not recognize
(H, J, K)
since node I causes the cluster to form a cycle after replacing. The following implementation will do this manually from the
```
```cpp
run_abi()
```
```markdown
method.
```
```markdown
Listing 22: An example implementation of a partitioning pass forming clusters manually
```
```cpp
class TestPartitionPassX : public Implements<IPartitionPass>
{
public:
TestPartitionPassX(IGraphBuilder*) noexcept
{
}
bool initialize_abi(ITopology* topology) noexcept override
{
return true;
}
void run_abi(INode* node) noexcept override
{
if (!isMatch(node, TestDefType::eType1))
return;
INode* nodeType2{ nullptr };
INode* nodeType3{ nullptr };
for (auto* child : node->getChildren())
{
if (isMatch(child, TestDefType::eType2))
nodeType2 = child;
else if (isMatch(child, TestDefType::eType3))
nodeType3 = child;
else if (!isMatch(child, TestDefType::eType4))
return;
}
if (nodeType2 && nodeType3)
{
std::array<INode*, 3> partition{ node, nodeType2, nodeType3 };
m_manualPartitions.emplace_back(std::move(partition));
}
}
void commit_abi(IGraphBuilder* builder) noexcept override
{
for (const auto& partition : m_manualPartitions)
{
// Verify partition pattern (trivial check in this case)
if (partition.size() != 3)
```cpp
continue; // LCOV_EXCL_LINE
// Create override definition. Note that we exclude the definition from code coverage
// because the graph is never executed in this unit test.
NodeDefPtr nodeDef{ NodeDefLambda::create(
"PatternX", [](ExecutionTask& info) -> Status { return Status::eSuccess; }, // LCOV_EXCL_LINE
SchedulingInfo::eSerial)};
// Commit the change
builder->replacePartition(NodePartition(partition.data(), partition.size()), nodeDef.get());
}
private:
std::vector<std::array<INode*, 3>> m_manualPartitions;
};
```
Now let’s implement the same partitioning strategy but leverage the `quickPartitioning()` utility to forming clusters.
```cpp
class TestPartitionPassX : public Implements<IPartitionPass>
{
public:
TestPartitionPassX(IGraphBuilder*) noexcept
{
}
bool initialize_abi(ITopology* topology) noexcept override
{
m_selectedNodes.reserve(topology->getMaxNodeIndex());
return true;
}
void run_abi(INode* node) noexcept override
{
if (isMatch(node, TestDefType::eType1) || isMatch(node, TestDefType::eType2) ||
isMatch(node, TestDefType::eType3))
{
m_selectedNodes.push_back(node);
}
}
void commit_abi(IGraphBuilder* builder) noexcept override
{
quickPartitioning(
builder->getTopology(), Span<INode*>(m_selectedNodes.data(), m_selectedNodes.size()),
[builder](INode** begin, uint64_t size)
{
// For the test, we will only allow partitions of size 3
if (size != 3)
return;
// Create override definition. Note that we exclude the definition from code coverage
// because the graph is never executed in this unit test.
NodeDefPtr nodeDef{ NodeDefLambda::create(
"PatternX", [](ExecutionTask& info) -> Status { return Status::eSuccess; }, // LCOV_EXCL_LINE
SchedulingInfo::eSerial) };
// Mutate the graph
builder->replacePartition(NodePartition(begin, size), nodeDef.get());
});
}
private:
std::vector<INode*> m_selectedNodes;
};
Finally, we have to remember to register our new pass.
```cpp
OMNI_GRAPH_EXEC_REGISTER_PARTITION_PASS(TestPartitionPassX, 1);
```
## Implementing a Global Pass
Users are discouraged from authoring global passes as they can severely slow down graph construction and/or create
ordering issues if a specific execution order is required. For all these reasons, users should try implementing new
functionality with the pass types above rather than global passes.
The following is a complete implementation of a global pass that EF uses to detect cycles in the graph.
```cpp
class PassStronglyConnectedComponents : public Implements<IGlobalPass>
{
public:
static omni::core::ObjectPtr<PassStronglyConnectedComponents> create(
omni::core::ObjectParam<exec::unstable::IGraphBuilder> builder)
{
return omni::core::steal(new PassStronglyConnectedComponents(builder.get()));
}
protected:
PassStronglyConnectedComponents(IGraphBuilder*)
{
}
void run_abi(IGraphBuilder* builder) noexcept override
{
_detectCycles(builder, builder->getTopology());
}
private:
void _detectCycles(IGraphBuilder* builder, ITopology* topology)
{
}
};
```
```cpp
struct SCC_NodeData {
size_t index{0};
size_t lowLink{0};
uint32_t cycleParentCount{0};
bool onStack{false};
};
size_t globalIndex = 0;
std::stack<INode*> globalStack;
traverseDepthFirst<VisitAll, SCC_NodeData>(
topology->getRoot(),
[this, builder, &globalIndex, &globalStack](auto info, INode* prev, INode* curr)
{
auto pushStack = [&globalStack](INode* node, SCC_NodeData& data)
{
data.onStack = true;
globalStack.push(node);
};
auto popStack = [builder, &info, &globalStack]()
{
auto* top = globalStack.top();
globalStack.pop();
auto& userData = info.userData(top);
userData.onStack = false;
auto node = exec::unstable::cast<exec::unstable::IGraphBuilderNode>(top);
node->setCycleParentCount(userData.cycleParentCount);
return top;
};
auto& userData = info.userData(curr);
auto& userDataPrev = info.userData(prev);
if (info.isFirstVisit())
{
userData.index = userData.lowLink = globalIndex++;
pushStack(curr, userData);
info.continueVisit(curr);
userDataPrev.lowLink = std::min(userDataPrev.lowLink, userData.lowLink);
}
}
);
```
```cpp
if (userData.lowLink == userData.index) {
auto* top = popStack();
if (top != curr) {
while (top != curr) {
top = popStack();
}
}
}
auto nodeGraph = curr->getNodeGraphDef();
if (nodeGraph) {
this->_detectCycles(builder, nodeGraph->getTopology());
}
```
if (userData.onStack) {
userDataPrev.lowLink = std::min(userDataPrev.lowLink, userData.index);
userData.cycleParentCount++;
}
```
## Next Steps
Pass creation is often the first step to adding new functionality to EF. The next logical steps often involve adding custom definitions, graph traversals, and executors. See Definition Creation, Graph Traversal Guide, and Executor Creation for details. | 11,048 |
Pcp.md | # Pcp module
Summary: The PrimCache Population module implements core scenegraph composition semantics - behaviors informally referred to as Layering & Referencing.
## Classes:
- **ArcType**
- **Cache**
- PcpCache is the context required to make requests of the Pcp composition algorithm and cache the results.
- **Dependency**
- Description of a dependency.
- **DependencyType**
- **DynamicFileFormatDependencyData**
- Contains the necessary information for storing a prim index's dependency on dynamic file format arguments and determining if a field change affects the prim index.
- **ErrorArcCycle**
- Arcs between PcpNodes that form a cycle.
- **ErrorArcPermissionDenied**
- Arcs that were not made between PcpNodes because of permission restrictions.
- **ErrorBase**
- Base class for all error types.
- **ErrorCapacityExceeded**
- Exceeded the capacity for composition arcs at a single site.
- **ErrorInconsistentAttributeType**
- **ErrorInconsistentAttributeType**
Attributes that have specs with conflicting definitions.
- **ErrorInconsistentAttributeVariability**
Attributes that have specs with conflicting variability.
- **ErrorInconsistentPropertyType**
Properties that have specs with conflicting definitions.
- **ErrorInvalidAssetPath**
Invalid asset paths used by references or payloads.
- **ErrorInvalidAssetPathBase**
- **ErrorInvalidExternalTargetPath**
Invalid target or connection path in some scope that points to an object outside of that scope.
- **ErrorInvalidInstanceTargetPath**
Invalid target or connection path authored in an inherited class that points to an instance of that class.
- **ErrorInvalidPrimPath**
Invalid prim paths used by references or payloads.
- **ErrorInvalidReferenceOffset**
References or payloads that use invalid layer offsets.
- **ErrorInvalidSublayerOffset**
Sublayers that use invalid layer offsets.
- **ErrorInvalidSublayerOwnership**
Sibling layers that have the same owner.
- **ErrorInvalidSublayerPath**
Asset paths that could not be both resolved and loaded.
- **ErrorInvalidTargetPath**
Invalid target or connection path.
- **ErrorMutedAssetPath**
Muted asset paths used by references or payloads.
- **ErrorOpinionAtRelocationSource**
Opinions were found at a relocation source path.
- **ErrorPrimPermissionDenied**
Layers with illegal opinions about private prims.
- **ErrorPropertyPermissionDenied**
- Layers with illegal opinions about private properties.
- **ErrorSublayerCycle**
- Layers that recursively sublayer themselves.
- **ErrorTargetPathBase**
- Base class for composition errors related to target or connection paths.
- **ErrorTargetPermissionDenied**
- Paths with illegal opinions about private targets.
- **ErrorType**
-
- **ErrorUnresolvedPrimPath**
- Asset paths that could not be both resolved and loaded.
- **InstanceKey**
- A PcpInstanceKey identifies instanceable prim indexes that share the same set of opinions.
- **LayerStack**
- Represents a stack of layers that contribute opinions to composition.
- **LayerStackIdentifier**
- Arguments used to identify a layer stack.
- **LayerStackSite**
- A site specifies a path in a layer stack of scene description.
- **MapExpression**
- An expression that yields a PcpMapFunction value.
- **MapFunction**
- A function that maps values from one namespace (and time domain) to another.
- **NodeRef**
- PcpNode represents a node in an expression tree for compositing scene description.
- **PrimIndex**
- PcpPrimIndex is an index of the all sites of scene description that contribute opinions to a specific prim, under composition semantics.
- **PropertyIndex**
- PcpPropertyIndex is an index of all sites in scene description that contribute opinions to a specific property, under composition semantics.
- **Site**
- A site specifies a path in a layer stack of scene description.
### pxr.Pcp.ArcType
**Methods:**
| Method | Description |
|--------|-------------|
## GetValueFromName
## allValues
### Attributes:
### Methods:
#### ComputeAttributeConnectionPaths(...)
Compute the attribute connection paths for the attribute at `attributePath` into `paths`.
#### ComputeLayerStack(identifier, allErrors)
Returns the layer stack for `identifier` if it exists, otherwise creates a new layer stack for `identifier`.
#### ComputePrimIndex(primPath, allErrors)
Compute and return a reference to the cached result for the prim index for the given path.
#### ComputePropertyIndex(propPath, allErrors)
Compute and return a reference to the cached result for the property index for the given path.
Compute and return a reference to the cached result for the property index for the given path.
ComputeRelationshipTargetPaths
Compute the relationship target paths for the relationship at `relationshipPath` into `paths`.
FindAllLayerStacksUsingLayer (layer)
Returns every computed & cached layer stack that includes `layer`.
FindPrimIndex (primPath)
Returns a pointer to the cached computed prim index for the given path, or None if it has not been computed.
FindPropertyIndex (propPath)
Returns a pointer to the cached computed property index for the given path, or None if it has not been computed.
FindSiteDependencies (siteLayerStack, ...)
Returns dependencies on the given site of scene description, as discovered by the cached index computations.
GetDynamicFileFormatArgumentDependencyData (...)
Returns the dynamic file format dependency data object for the prim index with the given `primIndexPath`.
GetLayerStackIdentifier ()
Get the identifier of the layerStack used for composition.
GetMutedLayers ()
Returns the list of canonical identifiers for muted layers in this cache.
GetUsedLayers ()
Returns set of all layers used by this cache.
GetUsedLayersRevision ()
Return a number that can be used to determine whether or not the set of layers used by this cache may have changed or not.
GetVariantFallbacks ()
Get the list of fallbacks to attempt to use when evaluating variant sets that lack an authored selection.
HasAnyDynamicFileFormatArgumentDependencies ()
Returns true if any prim index in this cache has a dependency on a dynamic file format argument field.
HasRootLayerStack (layerStack)
Return true if this cache's root layer stack is `layerStack`.
```
```markdown
| LayerStack |
|------------|
| LayerStack |
```
```markdown
### ComputeAttributeConnectionPaths
```
```markdown
Compute the attribute connection paths for the attribute at `attributePath` into `paths`.
If `localOnly` is `true` then this will compose attribute connections from local nodes only. If `stopProperty` is not `None` then this will stop composing attribute connections at `stopProperty`, including `stopProperty` iff `includeStopProperty` is `true`. If not `None`, `deletedPaths` will be populated with connection paths whose deletion contributed to the computed result. `allErrors` will contain any errors encountered while performing this operation.
#### Parameters
- **attributePath** (`Path`) –
- **paths** (`list[SdfPath]`) –
- **localOnly** (`bool`) –
- **stopProperty** (`Spec`) –
- **includeStopProperty** (`bool`) –
- **deletedPaths** (`list[SdfPath]`) –
- **allErrors** (`list[PcpError]`) –
```
```markdown
### ComputeLayerStack
```
```markdown
ComputeLayerStack(identifier, allErrors) → LayerStack
Returns the layer stack for `identifier` if it exists, otherwise creates a new layer stack for `identifier`.
This returns `None` if `identifier` is invalid (i.e. its root layer is `None`). `allErrors` will contain any errors encountered while creating a new layer stack. It’ll be unchanged if the layer stack already existed.
**Parameters**
- **identifier** (LayerStackIdentifier) –
- **allErrors** (list[PcpError]) –
Compute and return a reference to the cached result for the prim index for the given path.
`allErrors` will contain any errors encountered while performing this operation.
**Parameters**
- **primPath** (Path) –
- **allErrors** (list[PcpError]) –
Compute and return a reference to the cached result for the property index for the given path.
`allErrors` will contain any errors encountered while performing this operation.
**Parameters**
- **propPath** (Path) –
- **allErrors** (list[PcpError]) –
Compute and return a reference to the cached result for the relationship target paths for the given relationship path.
`allErrors` will contain any errors encountered while performing this operation.
**Parameters**
- **relationshipPath** –
- **paths** –
- **localOnly** –
<em class="sig-param">
<span class="n">
<span class="pre">
stopProperty
,
<em class="sig-param">
<span class="n">
<span class="pre">
includeStopProperty
,
<em class="sig-param">
<span class="n">
<span class="pre">
deletedPaths
,
<em class="sig-param">
<span class="n">
<span class="pre">
allErrors
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
None
<dd>
<p>
Compute the relationship target paths for the relationship at
`relationshipPath`
into
`paths`
.
<p>
If
`localOnly`
is
`true`
then this will compose relationship targets from local nodes only. If
`stopProperty`
is not
`None`
then this will stop composing relationship targets at
`stopProperty`
, including
`stopProperty`
iff
`includeStopProperty`
is
`true`
.
If not
`None`
,
`deletedPaths`
will be populated with target paths whose deletion contributed to the computed result.
`allErrors`
will contain any errors encountered while performing this operation.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul>
<li>
<p>
<strong>
relationshipPath
(
Path
) –
<li>
<p>
<strong>
paths
(
list
[
SdfPath
]
) –
<li>
<p>
<strong>
localOnly
(
bool
) –
<li>
<p>
<strong>
stopProperty
(
Spec
) –
<li>
<p>
<strong>
includeStopProperty
(
bool
) –
<li>
<p>
<strong>
deletedPaths
(
list
[
SdfPath
]
) –
<li>
<p>
<strong>
allErrors
(
list
[
PcpError
]
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Pcp.Cache.FindAllLayerStacksUsingLayer">
<span class="sig-name descname">
<span class="pre">
FindAllLayerStacksUsingLayer
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
layer
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
list
[
PcpLayerStackPtr
]
<dd>
<p>
Returns every computed & cached layer stack that includes
`layer`
.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
layer
(
Layer
) –
### FindPrimIndex
- **Parameters**:
- **primPath** (Path) –
- **Returns**: → PrimIndex
- **Description**: Returns a pointer to the cached computed prim index for the given path, or None if it has not been computed.
### FindPropertyIndex
- **Parameters**:
- **propPath** (Path) –
- **Returns**: → PropertyIndex
- **Description**: Returns a pointer to the cached computed property index for the given path, or None if it has not been computed.
### FindSiteDependencies
- **Parameters**:
- **siteLayerStack** (LayerStack) –
- **sitePath** (Path) –
- **depMask** (PcpDependencyFlags) –
- **recurseOnSite** (bool) –
- **recurseOnIndex** (bool) –
- **filterForExistingCachesOnly** (bool) –
- **Returns**: → list[PcpDependency]
- **Description**: Returns dependencies on the given site of scene description, as discovered by the cached index computations.
- depMask specifies what classes of dependency to include; see PcpDependencyFlags for details.
- recurseOnSite includes incoming dependencies on children of sitePath.
- recurseOnIndex extends the result to include all PcpCache child indexes below discovered results.
- filterForExistingCachesOnly filters the results to only paths representing computed prim and property index caches; otherwise a recursively-expanded result can include un-computed paths that are expected to depend on the site.
will check every layer stack using that layer, and apply any relevant
sublayer offsets to the map functions in the returned
PcpDependencyVector.
See the other method for parameter details.
Parameters
----------
- **siteLayer** (`Layer`) –
- **sitePath** (`Path`) –
- **depMask** (`PcpDependencyFlags`) –
- **recurseOnSite** (`bool`) –
- **recurseOnIndex** (`bool`) –
- **filterForExistingCachesOnly** (`bool`) –
GetDynamicFileFormatArgumentDependencyData
-------------------------------------------
```python
GetDynamicFileFormatArgumentDependencyData(primIndexPath)
```
Returns the dynamic file format dependency data object for the prim index with the given `primIndexPath`.
This will return an empty dependency data if either there is no cache prim index for the path or if the prim index has no dynamic file formats that it depends on.
Parameters
----------
- **primIndexPath** (`Path`) –
GetLayerStackIdentifier
-----------------------
```python
GetLayerStackIdentifier()
```
Get the identifier of the layerStack used for composition.
GetMutedLayers
--------------
```python
GetMutedLayers()
```
Returns the list of canonical identifiers for muted layers in this cache.
See documentation on RequestLayerMuting for more details.
GetUsedLayers
-------------
```python
GetUsedLayers()
```
Returns set of all layers used by this cache.
GetUsedLayersRevision
---------------------
```python
GetUsedLayersRevision()
```
Return a number that can be used to determine whether or not the set of layers used by this cache may have changed or not.
again, if the number is unchanged, then GetUsedLayers() is guaranteed
to be unchanged as well.
## GetVariantFallbacks
Get the list of fallbacks to attempt to use when evaluating variant
sets that lack an authored selection.
## HasAnyDynamicFileFormatArgumentDependencies
Returns true if any prim index in this cache has a dependency on a
dynamic file format argument field.
## HasRootLayerStack
Return true if this cache’s root layer stack is `layerStack` , false
otherwise.
This is functionally equivalent to comparing against the result of
GetLayerStack() , but does not require constructing a TfWeakPtr or any
refcount operations.
### Parameters
**layerStack** (`LayerStack`) –
HasRootLayerStack(layerStack) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
### Parameters
**layerStack** (`LayerStack`) –
## IsInvalidAssetPath
Returns true if `resolvedAssetPath` was used by a prim (e.g.
in a reference) but did not resolve to a valid asset. This is
functionally equivalent to examining the values in the map returned by
GetInvalidAssetPaths, but more efficient.
### Parameters
**resolvedAssetPath** (`str`) –
## IsInvalidSublayerIdentifier
Returns true if `identifier` was used as a sublayer path in a layer
stack but did not identify a valid layer.
This is functionally equivalent to examining the values in the vector
returned by GetInvalidSublayerIdentifiers, but more efficient.
### Parameters
**identifier** (`str`) –
### IsLayerMuted
```python
def IsLayerMuted(layerIdentifier) -> bool
```
Returns true if the layer specified by `layerIdentifier` is muted in this cache, false otherwise.
If `layerIdentifier` is relative, it is assumed to be relative to this cache’s root layer. See documentation on RequestLayerMuting for more details.
#### Parameters
- **layerIdentifier** (`str`) –
---
### IsLayerMuted
```python
def IsLayerMuted(anchorLayer, layerIdentifier, canonicalMutedLayerIdentifier) -> bool
```
Returns true if the layer specified by `layerIdentifier` is muted in this cache, false otherwise.
If `layerIdentifier` is relative, it is assumed to be relative to `anchorLayer`. If `canonicalMutedLayerIdentifier` is supplied, it will be populated with the canonical identifier of the muted layer if this function returns true. See documentation on RequestLayerMuting for more details.
#### Parameters
- **anchorLayer** (`Layer`) –
- **layerIdentifier** (`str`) –
- **canonicalMutedLayerIdentifier** (`str`) –
---
### IsPayloadIncluded
```python
def IsPayloadIncluded(path) -> bool
```
Return true if the payload is included for the given path.
#### Parameters
- **path** (`Path`) –
---
### IsPossibleDynamicFileFormatArgumentField
```python
def IsPossibleDynamicFileFormatArgumentField(field) -> bool
```
Returns true if the given `field` is the name of a field that was composed while generating dynamic file format arguments for any prim index in this cache.
#### Parameters
- **field** (`str`) –
---
### PrintStatistics
```python
def PrintStatistics() -> None
```
Prints various statistics about the data stored in this cache.
---
### Reload
```python
def Reload(changes) -> None
```
Reloads the cache with the specified changes.
#### Parameters
- **changes** –
```
### Reload the layers of the layer stack, except session layers and sublayers of session layers.
This will also try to load sublayers in this cache’s layer stack that could not be loaded previously. It will also try to load any referenced or payloaded layer that could not be loaded previously. Clients should subsequently
```
```markdown
Apply()
```
```markdown
changes
```
to use any now-valid layers.
**Parameters**
- **changes** (`PcpChanges`) –
### RequestLayerMuting(layersToMute, layersToUnmute, changes, newLayersMuted, newLayersUnmuted)
Request layers to be muted or unmuted in this cache.
Muted layers are ignored during composition and do not appear in any layer stacks. The root layer of this stage may not be muted; attempting to do so will generate a coding error. If the root layer of a reference or payload layer stack is muted, the behavior is as if the muted layer did not exist, which means a composition error will be generated.
A canonical identifier for each layer in
```markdown
layersToMute
```
will be computed using ArResolver::CreateIdentifier using the cache’s root layer as the anchoring asset. Any layer encountered during composition with the same identifier will be considered muted and ignored.
Note that muting a layer will cause this cache to release all references to that layer. If no other client is holding on to references to that layer, it will be unloaded. In this case, if there are unsaved edits to the muted layer, those edits are lost. Since anonymous layers are not serialized, muting an anonymous layer will cause that layer and its contents to be lost in this case.
If
```markdown
changes
```
is not
```markdown
nullptr
```
, it is adjusted to reflect the changes necessary to see the change in muted layers. Otherwise, those changes are applied immediately.
```markdown
newLayersMuted
```
and
```markdown
newLayersUnmuted
```
contains the pruned vector of layers which are muted or unmuted by this call to RequestLayerMuting.
**Parameters**
- **layersToMute** (`list[str]`) –
- **layersToUnmute** (`list[str]`) –
- **changes** (`PcpChanges`) –
- **newLayersMuted** (`list[str]`) –
- **newLayersUnmuted** (`list[str]`) –
### RequestPayloads(pathsToInclude, pathsToExclude, changes)
### RequestPayloads
Request payloads to be included or excluded from composition.
- **pathsToInclude** (SdfPathSet) –
- **pathsToExclude** (SdfPathSet) –
- **changes** (PcpChanges) –
If not `None`, is adjusted to reflect the changes necessary to see the change in payloads; otherwise those changes are applied immediately.
If a path is listed in both pathsToInclude and pathsToExclude, it will be treated as an inclusion only.
### SetVariantFallbacks
Set the list of fallbacks to attempt to use when evaluating variant sets that lack an authored selection.
- **map** (PcpVariantFallbackMap) –
- **changes** (PcpChanges) –
If `changes` is not `None` then it’s adjusted to reflect the changes necessary to see the change in standin preferences, otherwise those changes are applied immediately.
### UsesLayerStack
Return true if `layerStack` is used by this cache in its composition, false otherwise.
- **layerStack** (LayerStack) –
### fileFormatTarget
str
Returns the file format target this cache is configured for.
- **Type**
- type
### layerStack
LayerStack
Get the layer stack for GetLayerStackIdentifier().
Note that this will neither compute the layer stack nor report errors. So if the layer stack has not been computed yet this will return `None`. Use ComputeLayerStack() if you need to compute the layer stack if it hasn’t been computed already and/or get errors caused by computing the layer stack.
- **Type**
- LayerStack
### type
### pxr.Pcp.Dependency
class Dependency
Description of a dependency.
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| indexPath | |
| mapFunc | |
| sitePath | |
### pxr.Pcp.Dependency.indexPath
property indexPath
### pxr.Pcp.Dependency.mapFunc
property mapFunc
### pxr.Pcp.Dependency.sitePath
property sitePath
### pxr.Pcp.DependencyType
class DependencyType
**Methods:**
| Method | Description |
|--------|-------------|
| GetValueFromName | |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| allValues | |
### pxr.Pcp.DependencyType.GetValueFromName
static method GetValueFromName
### pxr.Pcp.DependencyType.allValues
attribute allValues = (Pcp.DependencyTypeNone, Pcp.DependencyTypeRoot, Pcp.DependencyTypePurelyDirect, Pcp.DependencyTypePartlyDirect, Pcp.DependencyTypeDirect, Pcp.DependencyTypeAncestral, Pcp.DependencyTypeVirtual, Pcp.DependencyTypeNonVirtual, Pcp.DependencyTypeAnyNonVirtual, Pcp.DependencyTypeAnyIncludingVirtual)
Contains the necessary information for storing a prim index’s dependency on dynamic file format arguments and determining if a field change affects the prim index. This data structure does not store the prim index or its path itself and is expected to be the data in some other data structure that maps prim indexes to its dependencies.
**Methods:**
| Method | Description |
|--------|-------------|
| `CanFieldChangeAffectFileFormatArguments` | Given a field name and the changed field values in oldAndNewValues this return whether this change can affect any of the file format arguments generated by any of the contexts stored in this dependency. |
| `GetRelevantFieldNames` | Returns a list of field names that were composed for any of the dependency contexts that were added to this dependency. |
| `IsEmpty` | Returns whether this dependency data is empty. |
**CanFieldChangeAffectFileFormatArguments**
Given a field name and the changed field values in oldAndNewValues this return whether this change can affect any of the file format arguments generated by any of the contexts stored in this dependency.
**Parameters**
- **fieldName** (str) –
- **oldValue** (VtValue) –
- **newValue** (VtValue) –
**GetRelevantFieldNames**
Returns a list of field names that were composed for any of the dependency contexts that were added to this dependency.
**IsEmpty**
Returns whether this dependency data is empty.
### pxr.Pcp.ErrorArcCycle
Arcs between PcpNodes that form a cycle.
### pxr.Pcp.ErrorArcPermissionDenied
Arcs that were not made between PcpNodes because of permission restrictions.
### pxr.Pcp.ErrorBase
Base class for all error types.
**Attributes:**
| Attribute | Description |
|-----------------|-------------|
| `errorType` | |
### pxr.Pcp.ErrorCapacityExceeded
Exceeded the capacity for composition arcs at a single site.
### pxr.Pcp.ErrorInconsistentAttributeType
Attributes that have specs with conflicting definitions.
### pxr.Pcp.ErrorInconsistentAttributeVariability
Attributes that have specs with conflicting variability.
### pxr.Pcp.ErrorInconsistentPropertyType
Properties that have specs with conflicting definitions.
### pxr.Pcp.ErrorInvalidAssetPath
Invalid asset paths used by references or payloads.
### pxr.Pcp.ErrorInvalidAssetPathBase
### pxr.Pcp.ErrorInvalidExternalTargetPath
Invalid target or connection path in some scope that points to an object outside of that scope.
Invalid target or connection path authored in an inherited class that points to an instance of that class.
Invalid prim paths used by references or payloads.
References or payloads that use invalid layer offsets.
Sublayers that use invalid layer offsets.
Sibling layers that have the same owner.
Asset paths that could not be both resolved and loaded.
Invalid target or connection path.
Muted asset paths used by references or payloads.
Opinions were found at a relocation source path.
Layers with illegal opinions about private prims.
Layers with illegal opinions about private properties.
Sublayers that use invalid layer offsets.
### pxr.Pcp.ErrorSublayerCycle
Layers that recursively sublayer themselves.
### pxr.Pcp.ErrorTargetPathBase
Base class for composition errors related to target or connection paths.
### pxr.Pcp.ErrorTargetPermissionDenied
Paths with illegal opinions about private targets.
### pxr.Pcp.ErrorType
**Methods:**
| Method | Description |
|--------|-------------|
| GetValueFromName | |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| allValues | (Pcp.ErrorType_ArcCycle, Pcp.ErrorType_ArcPermissionDenied, Pcp.ErrorType_IndexCapacityExceeded, Pcp.ErrorType_ArcCapacityExceeded, Pcp.ErrorType_ArcNamespaceDepthCapacityExceeded, Pcp.ErrorType_InconsistentPropertyType, Pcp.ErrorType_InconsistentAttributeType, Pcp.ErrorType_InconsistentAttributeVariability, Pcp.ErrorType_InternalAssetPath, Pcp.ErrorType_InvalidPrimPath, Pcp.ErrorType_InvalidAssetPath, Pcp.ErrorType_InvalidInstanceTargetPath, Pcp.ErrorType_InvalidExternalTargetPath, Pcp.ErrorType_InvalidTargetPath, Pcp.ErrorType_InvalidReferenceOffset, Pcp.ErrorType_InvalidSublayerOffset, Pcp.ErrorType_InvalidSublayerOwnership, Pcp.ErrorType_InvalidSublayerPath, Pcp.ErrorType_InvalidVariantSelection, Pcp.ErrorType_OpinionAtRelocationSource, Pcp.ErrorType_PrimPermissionDenied, Pcp.ErrorType_PropertyPermissionDenied, Pcp.ErrorType_SublayerCycle, Pcp.ErrorType_TargetPermissionDenied, Pcp.ErrorType_UnresolvedPrimPath) |
### pxr.Pcp.ErrorUnresolvedPrimPath
Asset paths that could not be both resolved and loaded.
A PcpInstanceKey identifies instanceable prim indexes that share the same set of opinions. Instanceable prim indexes with equal instance keys are guaranteed to have the same opinions for name children and properties beneath those name children. They are NOT guaranteed to have the same opinions for direct properties of the prim indexes themselves.
Represents a stack of layers that contribute opinions to composition.
Each PcpLayerStack is identified by a PcpLayerStackIdentifier. This identifier contains all of the parameters needed to construct a layer stack, such as the root layer, session layer, and path resolver context.
PcpLayerStacks are constructed and managed by a Pcp_LayerStackRegistry.
**Attributes:**
- `expired`: True if this object has expired, False otherwise.
- `identifier`: LayerStackIdentifier
- `incrementalRelocatesSourceToTarget`: SdfRelocatesMap
- `incrementalRelocatesTargetToSource`: SdfRelocatesMap
- `layerOffsets`:
- `layerTree`: LayerTree
- `layers`: list[SdfLayerRefPtr]
- `localErrors`: list[PcpError]
- `mutedLayers`: set[str]
- `pathsToPrimsWithRelocates`: list[SdfPath]
- `relocatesSourceToTarget`: SdfRelocatesMap
- `relocatesTargetToSource`: SdfRelocatesMap
### expired
- **Description**: True if this object has expired, False otherwise.
### identifier
- **Description**: LayerStackIdentifier
- **Description**: Returns the identifier for this layer stack.
- **Type**: type
### incrementalRelocatesSourceToTarget
- **Description**: SdfRelocatesMap
- **Description**: Returns incremental relocation source-to-target mapping for this layer stack.
- **Description**: This map contains the individual relocation entries found across all layers in this layer stack; it does not combine ancestral entries with descendant entries. For instance, if this layer stack contains relocations { /A: /B} and { /A/C: /A/D}, this map will contain { /A: /B} and { /A/C: /A/D}.
- **Type**: type
### incrementalRelocatesTargetToSource
- **Description**: SdfRelocatesMap
- **Description**: Returns incremental relocation target-to-source mapping for this layer stack.
- **Description**: See GetIncrementalRelocatesTargetToSource for more details.
- **Type**: type
### layerOffsets
### layerTree
- **Description**: LayerTree
- **Description**: Returns the layer tree representing the structure of this layer stack.
- **Type**: type
### layers
- **Description**: list[SdfLayerRefPtr]
- **Description**: Returns the layers in this layer stack in strong-to-weak order.
- **Description**: Note that this is only the local layer stack — it does not include any layers brought in by references inside prims.
- **Type**: type
### localErrors
- **Description**: list[PcpError]
- **Description**: Return the list of errors local to this layer stack.
- **Type**: type
### mutedLayers
- **Description**: set[str]
- **Description**: Returns the set of layers that were muted in this layer stack.
- **Type**: type
### pathsToPrimsWithRelocates
- **Type**: list[SdfPath]
- **Description**: Returns a list of paths to all prims across all layers in this layer stack that contained relocates.
### relocatesSourceToTarget
- **Type**: SdfRelocatesMap
- **Description**: Returns relocation source-to-target mapping for this layer stack.
- This map combines the individual relocation entries found across all layers in this layer stack; multiple entries that affect a single prim will be combined into a single entry. For instance, if this layer stack contains relocations { /A: /B} and { /A/C: /A/D}, this map will contain { /A: /B} and { /B/C: /B/D}. This allows consumers to go from unrelocated namespace to relocated namespace in a single step.
### relocatesTargetToSource
- **Type**: SdfRelocatesMap
- **Description**: Returns relocation target-to-source mapping for this layer stack.
- See GetRelocatesSourceToTarget for more details.
### LayerStackIdentifier
- **Description**: Arguments used to identify a layer stack. Objects of this type are immutable.
- **Attributes**:
- pathResolverContext
- rootLayer
- sessionLayer
### LayerStackSite
- **Description**: A site specifies a path in a layer stack of scene description.
- **Attributes**:
- (Attributes table not provided in HTML snippet)
| layerStack |
|------------|
| path |
|------------|
### layerStack
**property**
### path
**property**
### MapExpression
**class**
An expression that yields a PcpMapFunction value.
Expressions comprise constant values, variables, and operators applied to sub-expressions. Expressions cache their computed values internally. Assigning a new value to a variable automatically invalidates the cached values of dependent expressions. Common (sub-)expressions are automatically detected and shared.
PcpMapExpression exists solely to support efficient incremental handling of relocates edits. It represents a tree of the namespace mapping operations and their inputs, so we can narrowly redo the computation when one of the inputs changes.
**Methods:**
| Method | Description |
|-------------------------------|--------------------------------------------------------------------------------------------------|
| AddRootIdentity() | Return a new expression representing this expression with an added (if necessary) mapping from</>to</>. |
| Compose(f) | Create a new PcpMapExpression representing the application of f's value, followed by the application of this expression's value. |
| Constant(constValue) -> MapExpression | classmethod |
| Evaluate() | Evaluate this expression, yielding a PcpMapFunction value. |
| Identity() -> MapExpression | classmethod |
| Inverse() | Create a new PcpMapExpression representing the inverse of f. |
| MapSourceToTarget(path) | Map a path in the source namespace to the target. |
| MapTargetToSource(path) | Map a path in the target namespace to the source. |
**Attributes:**
| isIdentity | bool |
|------------|------|
| isNull | bool |
| timeOffset | LayerOffset |
### AddRootIdentity()
Return a new expression representing this expression with an added (if necessary) mapping from</>to</>.
### Compose(f)
Create a new PcpMapExpression representing the application of f’s value, followed by the application of this expression’s value.
- Parameters:
- f (MapExpression) –
### Constant(constValue)
Create a new constant.
- Parameters:
- constValue (Value) –
### Evaluate()
Evaluate this expression, yielding a PcpMapFunction value.
The computed result is cached. The return value is a reference to the internal cached value. The cache is automatically invalidated as needed.
### Identity()
Return an expression representing PcpMapFunction::Identity().
### Inverse()
Return an expression representing the inverse of this expression.
### Create a new PcpMapExpression representing the inverse of f.
### MapSourceToTarget
```python
MapSourceToTarget(path) → Path
```
Map a path in the source namespace to the target.
If the path is not in the domain, returns an empty path.
**Parameters**
- **path** (Path) –
### MapTargetToSource
```python
MapTargetToSource(path) → Path
```
Map a path in the target namespace to the source.
If the path is not in the co-domain, returns an empty path.
**Parameters**
- **path** (Path) –
### isIdentity
```python
property isIdentity
```
bool
Return true if the evaluated map function is the identity function.
For identity, MapSourceToTarget() always returns the path unchanged.
**Type**
- type
### isNull
```python
property isNull
```
bool
Return true if this is a null expression.
**Type**
- type
### timeOffset
```python
property timeOffset
```
LayerOffset
The time offset of the mapping.
**Type**
- type
### MapFunction
```python
class pxr.Pcp.MapFunction
```
A function that maps values from one namespace (and time domain) to another. It represents the transformation that an arc such as a reference arc applies as it incorporates values across the arc.
Take the example of a reference arc, where a source path
Map functions have a specific _domain_, or set of values they can operate on. Any values outside the domain cannot be mapped. The domain precisely tracks what areas of namespace can be referred to across various forms of arcs.
Map functions can be chained to represent a series of map operations applied in sequence. The map function represent the cumulative effect as efficiently as possible. For example, in the case of a chained reference from
Map functions can be **inverted**. Formally, map functions are bijections (one-to-one and onto), which ensures that they can be inverted. Put differently, no information is lost by applying a map function to set of values within its domain; they retain their distinct identities and can always be mapped back.
One analogy that may or may not be helpful: In the same way a geometric transform maps a model’s points in its rest space into the world coordinates for a particular instance, a PcpMapFunction maps values about a referenced model into the composed scene for a particular instance of that model. But rather than translating and rotating points, the map function shifts the values in namespace (and time).
**Methods:**
| Method | Description |
|--------|-------------|
| `Compose(f)` | Compose this map over the given map function. |
| `ComposeOffset(newOffset)` | Compose this map function over a hypothetical map function that has an identity path mapping and `offset`. |
| `GetInverse()` | Return the inverse of this map function. |
| `Identity` | `classmethod Identity() -> MapFunction` |
| `IdentityPathMap` | `classmethod IdentityPathMap() -> PathMap` |
| `MapSourceToTarget(path)` | Map a path in the source namespace to the target. |
| `MapTargetToSource(path)` | Map a path in the target namespace to the source. |
**Attributes:**
| Attribute | Type |
|-----------|------|
| `isIdentity` | bool |
| `isIdentityPathMapping` | bool |
| `isNull` | bool |
| `sourceToTargetMap` | PathMap |
| `timeOffset` | LayerOffset |
## MapFunction
### Compose
Compose this map over the given map function.
The result will represent the application of f followed by the application of this function.
**Parameters**
- **f** (`MapFunction`) –
### ComposeOffset
Compose this map function over a hypothetical map function that has an identity path mapping and `offset`.
This is equivalent to building such a map function and invoking Compose(), but is faster.
**Parameters**
- **newOffset** (`LayerOffset`) –
### GetInverse
Return the inverse of this map function.
This returns a true inverse `inv:` for any path p in this function’s domain that it maps to p’, inv(p’) -> p.
### Identity
**classmethod** Identity() -> MapFunction
Construct an identity map function.
### IdentityPathMap
**classmethod** IdentityPathMap() -> PathMap
Returns an identity path mapping.
### MapSourceToTarget
Map a path in the source namespace to the target.
If the path is not in the domain, returns an empty path.
**Parameters**
- **path** (`Path`) –
### MapTargetToSource
Map a path in the target namespace to the source.
If the path is not in the domain, returns an empty path.
**Parameters**
- **path** (`Path`) –
## Map a path in the target namespace to the source.
If the path is not in the co-domain, returns an empty path.
### Parameters
- **path** (`Path`) –
## property isIdentity
- bool
- Return true if the map function is the identity function.
- The identity function has an identity path mapping and time offset.
### Type
- type
## property isIdentityPathMapping
- bool
- Return true if the map function uses the identity path mapping.
- If true, MapSourceToTarget() always returns the path unchanged. However, this map function may have a non-identity time offset.
### Type
- type
## property isNull
- bool
- Return true if this map function is the null function.
- For a null function, MapSourceToTarget() always returns an empty path.
### Type
- type
## property sourceToTargetMap
- PathMap
- The set of path mappings, from source to target.
### Type
- type
## property timeOffset
- LayerOffset
- The time offset of the mapping.
### Type
- type
## class pxr.Pcp.NodeRef
PcpNode represents a node in an expression tree for compositing scene description.
A node represents the opinions from a particular site. In addition, it may have child nodes, representing nested expressions that are composited over/under this node.
Child nodes are stored and composited in strength order.
Each node holds information about the arc to its parent. This captures both the relative strength of the sub-expression as well as any value-mapping needed, such as to rename opinions from a model to use in a particular instance.
### Methods:
- **CanContributeSpecs()**
- Returns true if this node is allowed to contribute opinions for composition, false otherwise.
| Method | Description |
|--------|-------------|
| GetIntroPath() | Get the path that introduced this node. |
| GetOriginRootNode() | Walk up to the root origin node for this node. |
| GetPathAtIntroduction() | Returns the path for this node's site when it was introduced. |
| GetRootNode() | Walk up to the root node of this expression. |
| IsDueToAncestor() | |
| IsRootNode() | Returns true if this node is the root node of the prim index graph. |
**Attributes:**
| Attribute | Description |
|-----------|-------------|
| arcType | ArcType |
| children | |
| hasSpecs | None |
| hasSymmetry | None |
| isCulled | bool |
| isInert | bool |
| isRestricted | bool |
| layerStack | LayerStack |
| mapToParent | MapExpression |
| mapToRoot | MapExpression |
| Property | Type | Description |
|----------|------|-------------|
| `namespaceDepth` | int | - |
| `origin` | - | - |
| `parent` | - | - |
| `path` | Path | - |
| `permission` | Permission | - |
| `siblingNumAtOrigin` | int | - |
| `site` | LayerStackSite | - |
### Methods
#### `CanContributeSpecs()`
Returns true if this node is allowed to contribute opinions for composition, false otherwise.
#### `GetDepthBelowIntroduction()`
Return the number of levels of namespace this node’s site is below the level at which it was introduced by an arc.
#### `GetIntroPath()`
Get the path that introduced this node.
Specifically, this is the path the parent node had at the level of namespace where this node was added as a child. For a root node, this returns the absolute root path. See also GetDepthBelowIntroduction().
#### `GetOriginRootNode()`
Walk up to the root origin node for this node.
This is the very first node that caused this node to be added to the graph. For instance, the root origin node of an implied inherit is the original inherit node.
#### `GetPathAtIntroduction()`
Get the path at the time this node was introduced.
Specifically, this is the path the parent node had at the level of namespace where this node was added as a child. For a root node, this returns the absolute root path. See also GetDepthBelowIntroduction().
Returns the path for this node’s site when it was introduced.
GetRootNode() → NodeRef
Walk up to the root node of this expression.
IsDueToAncestor() → bool
IsRootNode() → bool
Returns true if this node is the root node of the prim index graph.
property arcType
ArcType
Returns the type of arc connecting this node to its parent node.
Type: type
property children
property hasSpecs
None
Returns true if this node has opinions authored for composition, false otherwise.
Type: type
property hasSymmetry
None
Get/set whether this node provides any symmetry opinions, either directly or from a namespace ancestor.
Type: type
property isCulled
bool
Type: type
property isInert
bool
Type: type
property isRestricted
bool
Type: type
### layerStack
**Description:** Returns the layer stack for the site this node represents.
**Type:** type
### mapToParent
**Description:** Returns mapping function used to translate paths and values from this node to its parent node.
**Type:** type
### mapToRoot
**Description:** Returns mapping function used to translate paths and values from this node directly to the root node.
**Type:** type
### namespaceDepth
**Description:** Returns the absolute namespace depth of the node that introduced this node.
**Note:** This does not count any variant selections.
**Type:** type
### origin
### parent
### path
**Description:** Returns the path for the site this node represents.
**Type:** type
### permission
**Description:** Get/set the permission for this node. This indicates whether specs on this node can be accessed from other nodes.
**Type:** type
### siblingNumAtOrigin
**Description:** Returns this node’s index among siblings with the same arc type at this node’s origin.
**Type:** type
### site
### LayerStackSite
Get the site this node represents.
#### Type
- Type: type
### pxr.Pcp.PrimIndex
PcpPrimIndex is an index of the all sites of scene description that contribute opinions to a specific prim, under composition semantics.
PcpComputePrimIndex() builds an index (“indexes”) the given prim site. At any site there may be scene description values expressing arcs that represent instructions to pull in further scene description. PcpComputePrimIndex() recursively follows these arcs, building and ordering the results.
**Methods:**
- ComposeAuthoredVariantSelections()
- Compose the authored prim variant selections.
- ComputePrimChildNames(nameOrder, ...)
- Compute the prim child names for the given path.
- ComputePrimPropertyNames(nameOrder)
- Compute the prim property names for the given path.
- DumpToDotGraph(filename, ...)
- Dump the prim index in dot format to the file named `filename`.
- DumpToString(includeInheritOriginInfo, ...)
- Dump the prim index contents to a string.
- GetNodeProvidingSpec(primSpec)
- Returns the node that brings opinions from `primSpec` into this prim index.
- GetSelectionAppliedForVariantSet(variantSet)
- Return the variant selection applied for the named variant set.
- IsInstanceable()
- Returns true if this prim index is instanceable.
- IsValid()
- Return true if this index is valid.
- PrintStatistics()
- Prints various statistics about this prim index.
**Attributes:**
- hasAnyPayloads
-
| localErrors | list[PcpError] |
|-------------|---------------|
| primStack | |
| rootNode | NodeRef |
### ComposeAuthoredVariantSelections()
- **Description:** Compose the authored prim variant selections. These are the variant selections expressed in scene description. Note that these selections may not have actually been applied, if they are invalid. This result is not cached, but computed each time.
### ComputePrimChildNames(nameOrder, prohibitedNameSet)
- **Description:** Compute the prim child names for the given path.
- **Parameters:**
- nameOrder (list[TfToken])
- prohibitedNameSet (PcpTokenSet)
### ComputePrimPropertyNames(nameOrder)
- **Description:** Compute the prim property names for the given path. The nameOrder vector must not contain any duplicate entries.
- **Parameters:**
- nameOrder (list[TfToken])
### DumpToDotGraph(filename, includeInheritOriginInfo, includeMaps)
- **Description:** Dump the prim index to a DOT graph.
- **Parameters:**
- filename
- includeInheritOriginInfo
- includeMaps
Dump the prim index in dot format to the file named `filename`.
See Dump(...) for information regarding arguments.
**Parameters**
- **filename** (`str`) –
- **includeInheritOriginInfo** (`bool`) –
- **includeMaps** (`bool`) –
Dump the prim index contents to a string.
If `includeInheritOriginInfo` is `true`, output for implied inherit nodes will include information about the originating inherit node. If `includeMaps` is `true`, output for each node will include the mappings to the parent and root node.
**Parameters**
- **includeInheritOriginInfo** (`bool`) –
- **includeMaps** (`bool`) –
Returns the node that brings opinions from `primSpec` into this prim index.
If no such node exists, returns an invalid PcpNodeRef.
**Parameters**
- **primSpec** (`PrimSpec`) –
GetNodeProvidingSpec(layer, path) -> NodeRef
Returns the node that brings opinions from the Sd prim spec at `layer` and `path` into this prim index.
If no such node exists, returns an invalid PcpNodeRef.
**Parameters**
- **layer** (`Layer`) –
- **path** (`Path`) –
GetSelectionAppliedForVariantSet(variantSet) -> str
Returns the selection applied for the given variant set.
**Parameters**
- **variantSet** –
Return the variant selection applied for the named variant set.
If none was applied, this returns an empty string. This can be different from the authored variant selection; for example, if the authored selection is invalid.
Parameters
----------
variantSet (str) –
IsInstanceable
--------------
Returns true if this prim index is instanceable.
Instanceable prim indexes with the same instance key are guaranteed to have the same set of opinions, but may not have local opinions about name children.
PcpInstanceKey
IsValid
-------
Return true if this index is valid.
A default-constructed index is invalid.
PrintStatistics
---------------
Prints various statistics about this prim index.
hasAnyPayloads
--------------
localErrors
-----------
list[PcpError]
Return the list of errors local to this prim.
Type
----
type
primStack
---------
rootNode
--------
NodeRef
Returns the root node of the prim index graph.
Type
----
type
PropertyIndex
-------------
PcpPropertyIndex is an index of all sites in scene description that contribute opinions to a specific property, under composition semantics.
Attributes:
------------
localErrors
-----------
list[PcpError]
localPropertyStack
-------------------
## pxr.Pcp.PropertyIndex.localErrors
- **Type**: list[PcpError]
- **Description**: Return the list of errors local to this property.
## pxr.Pcp.PropertyIndex.localPropertyStack
## pxr.Pcp.PropertyIndex.propertyStack
## pxr.Pcp.Site
- **Description**: A site specifies a path in a layer stack of scene description.
- **Attributes**:
- **layerStack**:
- **path**:
## pxr.Pcp.Site.layerStack
## pxr.Pcp.Site.path | 48,810 |
PerformanceTips.md | # Performance Optimization Tips
## Implementing a `computeVectorized` function
When using instancing, the framework organizes the data for all instances of a given graph in contiguous arrays per attributes in order to improve performance. This organization not only provides data locality which reduces cache misses and improve performance, but also gives the ability to write the compute function in a vectorized way. Doing so, the node writer will receive a full batch of instances. This allows computation in a vectorized way, treating several instances at the same time (by using SIMD instructions for example), but also to factorize invariant computations for all instances and write tight and efficient loops around the heart of the actual computation. Such technique brings tremendous performance gains, and makes any addition of new instances extremely cheap to compute. Details on how to write a `computeVectorized` function can be found here [Writing a computeVectorized function](#). | 996 |
PhysicsSchemaTools.md | # PhysicsSchemaTools module
Summary: Omniverse-specific: The Physics Schema Tools provides tools for the representation of physics properties and behaviors in a 3D scene, such as gravity, collisions, and rigid body dynamics.
## Classes
| Class | Description |
|-------|-------------|
| Path (*args, **kwargs) | PurePath subclass that can make system calls. |
## Functions
| Function | Description |
|----------|-------------|
| addActor | |
| addBoxCollisionShape | |
| addCollisionShape | |
| addDensity | |
| addDisplayColor | |
| addGroundPlane | |
| addGroundTriMesh | |
| addOrientation | |
<p>
<code>addPhysicsScene
<p>
<p>
<code>addPosition
<p>
<p>
<code>addRigidBody
<p>
<p>
<code>addRigidBox
<p>
<p>
<code>addRigidBoxForInstancing
<p>
<p>
<code>addRigidCapsule
<p>
<p>
<code>addRigidCone
<p>
<p>
<code>addRigidCylinder
<p>
<p>
<code>addRigidSphere
<p>
<p>
<code>addVelocity
<p>
<p>
<code>createMesh
<p>
<p>
<code>createMeshBox
<p>
<p>
<code>createMeshCapsule
<p>
<p>
<code>createMeshCylinder
<p>
<p>
<code>createMeshSphere
<p>
<p>
<code>createMeshSquare
<p>
<p>
<code>decodeSdfPath
<p>
<p>
<code>encodeSdfPath
<p>
<p>
<code>getMassSpaceInertia
<dl class="py class">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path">
<em class="property">
<span class="pre">
class
<span class="w">
<span class="sig-prename descclassname">
<span class="pre">
pxr.PhysicsSchemaTools.
<span class="sig-name descname">
<span class="pre">
Path
<span class="sig-paren">
(
<em class="sig-param">
<span class="o">
<span class="pre">
*
<span class="n">
<span class="pre">
args
,
<em class="sig-param">
<span class="o">
<span class="pre">
**
<span class="n">
<span class="pre">
kwargs
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.PhysicsSchemaTools.Path" title="Permalink to this definition">
<dd>
<p>
PurePath subclass that can make system calls.
<p>
Path represents a filesystem path but unlike PurePath, also offers
methods to do system calls on path objects. Depending on your system,
instantiating a Path will return either a PosixPath or a WindowsPath
object. You can also instantiate a PosixPath or WindowsPath directly,
but cannot instantiate a WindowsPath on a POSIX system or vice versa.
<p>
<strong>
Methods:
<table class="autosummary longtable docutils align-default">
<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
<tbody>
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.absolute" title="pxr.PhysicsSchemaTools.Path.absolute">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
absolute
()
<td>
<p>
Return an absolute version of this path.
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.chmod" title="pxr.PhysicsSchemaTools.Path.chmod">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
chmod
(mode, *[, follow_symlinks])
<td>
<p>
Change the permissions of the path, like os.chmod().
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.cwd" title="pxr.PhysicsSchemaTools.Path.cwd">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
cwd
()
<td>
<p>
Return a new path pointing to the current working directory (as returned by os.getcwd()).
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.exists" title="pxr.PhysicsSchemaTools.Path.exists">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
exists
()
<td>
<p>
Whether this path exists.
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.expanduser" title="pxr.PhysicsSchemaTools.Path.expanduser">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
expanduser
()
<td>
<p>
Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.glob" title="pxr.PhysicsSchemaTools.Path.glob">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
glob
(pattern)
<td>
<p>
Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.group" title="pxr.PhysicsSchemaTools.Path.group">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
group
()
<td>
<p>
Return the group name of the file gid.
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.hardlink_to" title="pxr.PhysicsSchemaTools.Path.hardlink_to">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
hardlink_to
(target)
<td>
<p>
Make this path a hard link pointing to the same file as
<em>
target
.
<tr class="row-odd">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.home" title="pxr.PhysicsSchemaTools.Path.home">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
home
()
<td>
<p>
Return a new path pointing to the user's home directory (as returned by os.path.expanduser('~')).
<tr class="row-even">
<td>
<p>
<a class="reference internal" href="#pxr.PhysicsSchemaTools.Path.is_block_device" title="pxr.PhysicsSchemaTools.Path.is_block_device">
<code class="xref py py-obj docutils literal notranslate">
<span class="pre">
is_block_device
- `is_block_device()`
- Whether this path is a block device.
- `is_char_device()`
- Whether this path is a character device.
- `is_dir()`
- Whether this path is a directory.
- `is_fifo()`
- Whether this path is a FIFO.
- `is_file()`
- Whether this path is a regular file (also True for symlinks pointing to regular files).
- `is_mount()`
- Check if this path is a POSIX mount point
- `is_socket()`
- Whether this path is a socket.
- `is_symlink()`
- Whether this path is a symbolic link.
- `iterdir()`
- Iterate over the files in this directory.
- `lchmod(mode)`
- Like chmod(), except if the path points to a symlink, the symlink's permissions are changed, rather than its target's.
- `link_to(target)`
- Make the target path a hard link pointing to this path.
- `lstat()`
- Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's.
- `mkdir([mode, parents, exist_ok])`
- Create a new directory at this given path.
- `open([mode, buffering, encoding, errors, ...])`
- Open the file pointed by this path and return a file object, as the built-in open() function does.
- `owner()`
- Return the login name of the file owner.
- `read_bytes()`
- Open the file in bytes mode, read it, and close the file.
| Method Name | Description |
|-------------|-------------|
| `read_text([encoding, errors])` | Open the file in text mode, read it, and close the file. |
| `readlink()` | Return the path to which the symbolic link points. |
| `rename(target)` | Rename this path to the target path. |
| `replace(target)` | Rename this path to the target path, overwriting if that path exists. |
| `resolve([strict])` | Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows). |
| `rglob(pattern)` | Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree. |
| `rmdir()` | Remove this directory. |
| `samefile(other_path)` | Return whether other_path is the same or not as this file (as returned by os.path.samefile()). |
| `stat(*[, follow_symlinks])` | Return the result of the stat() system call on this path, like os.stat() does. |
| `symlink_to(target[, target_is_directory])` | Make this path a symlink pointing to the target path. |
| `touch([mode, exist_ok])` | Create this file with the given access mode, if it doesn't exist. |
| `unlink([missing_ok])` | Remove this file or link. |
| `write_bytes(data)` | Open the file in bytes mode, write to it, and close the file. |
| `write_text(data[, encoding, errors, newline])` | Open the file in text mode, write to it, and close the file. |
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.chmod">
<span class="sig-name descname">
<span class="pre">
chmod
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
mode
,
<em class="sig-param">
<span class="o">
<span class="pre">
*
,
<em class="sig-param">
<span class="n">
<span class="pre">
follow_symlinks
<span class="o">
<span class="pre">
=
<span class="default_value">
<span class="pre">
True
<span class="sig-paren">
)
<dd>
<p>
Change the permissions of the path, like os.chmod().
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.cwd">
<em class="property">
<span class="pre">
classmethod
<span class="w">
<span class="sig-name descname">
<span class="pre">
cwd
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
Return a new path pointing to the current working directory
(as returned by os.getcwd()).
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.exists">
<span class="sig-name descname">
<span class="pre">
exists
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
Whether this path exists.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.expanduser">
<span class="sig-name descname">
<span class="pre">
expanduser
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.glob">
<span class="sig-name descname">
<span class="pre">
glob
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
pattern
<span class="sig-paren">
)
<dd>
<p>
Iterate over this subtree and yield all existing files (of any
kind, including directories) matching the given relative pattern.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.group">
<span class="sig-name descname">
<span class="pre">
group
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
Return the group name of the file gid.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.hardlink_to">
<span class="sig-name descname">
<span class="pre">
hardlink_to
<span class="sig-paren">
(
<em class="sig-param">
<span class="n">
<span class="pre">
target
<span class="sig-paren">
)
<dd>
<p>
Make this path a hard link pointing to the same file as
<em>
target
.
<p>
Note the order of arguments (self, target) is the reverse of os.link’s.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.home">
<em class="property">
<span class="pre">
classmethod
<span class="w">
<span class="sig-name descname">
<span class="pre">
home
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
Return a new path pointing to the user’s home directory (as
returned by os.path.expanduser(‘~’)).
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.is_block_device">
<span class="sig-name descname">
<span class="pre">
is_block_device
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
Whether this path is a block device.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.is_char_device">
<span class="sig-name descname">
<span class="pre">
is_char_device
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
Whether this path is a character device.
<dl class="py method">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.Path.is_dir">
<span class="sig-name descname">
<span class="pre">
is_dir
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<p>
Whether this path is a directory.
## is_dir
Whether this path is a directory.
## is_fifo
Whether this path is a FIFO.
## is_file
Whether this path is a regular file (also True for symlinks pointing to regular files).
## is_mount
Check if this path is a POSIX mount point
## is_socket
Whether this path is a socket.
## is_symlink
Whether this path is a symbolic link.
## iterdir
Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.
## lchmod
Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.
## link_to
Make the target path a hard link pointing to this path.
Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.
Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.
## lstat
Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.
## mkdir
Like mkdir(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.
Create a new directory at this given path.
Open the file pointed by this path and return a file object, as the built-in open() function does.
Return the login name of the file owner.
Open the file in bytes mode, read it, and close the file.
Open the file in text mode, read it, and close the file.
Return the path to which the symbolic link points.
Rename this path to the target path.
The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.
Returns the new Path instance pointing to the target path.
Rename this path to the target path, overwriting if that path exists.
The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.
Returns the new Path instance pointing to the target path.
### resolve
```python
resolve(strict=False)
```
Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).
### rglob
```python
rglob(pattern)
```
Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.
### rmdir
```python
rmdir()
```
Remove this directory. The directory must be empty.
### samefile
```python
samefile(other_path)
```
Return whether other_path is the same or not as this file (as returned by os.path.samefile()).
### stat
```python
stat(*, follow_symlinks=True)
```
Return the result of the stat() system call on this path, like os.stat() does.
### symlink_to
```python
symlink_to(target, target_is_directory=False)
```
Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.
### touch
```python
touch(mode=438, exist_ok=True)
```
Create this file with the given access mode, if it doesn’t exist.
### unlink
```python
unlink(missing_ok=False)
```
Remove this file or link. If the path is a directory, use rmdir() instead.
### write_bytes
```python
write_bytes(data)
```
Write the given bytes to this file.
## Functions and Methods
### write_bytes
```python
def write_bytes(data):
"""
Open the file in bytes mode, write to it, and close the file.
"""
```
### write_text
```python
def write_text(data, encoding=None, errors=None, newline=None):
"""
Open the file in text mode, write to it, and close the file.
"""
```
### addActor
```python
def addActor():
"""
Add an actor to the scene.
"""
```
### addBoxCollisionShape
```python
def addBoxCollisionShape():
"""
Add a box collision shape to the scene.
"""
```
### addCollisionShape
```python
def addCollisionShape():
"""
Add a collision shape to the scene.
"""
```
### addDensity
```python
def addDensity():
"""
Add density information to the object.
"""
```
### addDisplayColor
```python
def addDisplayColor():
"""
Add display color to the object.
"""
```
### addGroundPlane
```python
def addGroundPlane():
"""
Add a ground plane to the scene.
"""
```
### addGroundTriMesh
```python
def addGroundTriMesh():
"""
Add a ground triangle mesh to the scene.
"""
```
### addOrientation
```python
def addOrientation():
"""
Add orientation to the object.
"""
```
### addPhysicsScene
```python
def addPhysicsScene():
"""
Add a physics scene to the environment.
"""
```
### addPosition
```python
def addPosition():
"""
Add position to the object.
"""
```
### pxr.PhysicsSchemaTools.addPosition()
### pxr.PhysicsSchemaTools.addRigidBody()
### pxr.PhysicsSchemaTools.addRigidBox()
### pxr.PhysicsSchemaTools.addRigidBoxForInstancing()
### pxr.PhysicsSchemaTools.addRigidCapsule()
### pxr.PhysicsSchemaTools.addRigidCone()
### pxr.PhysicsSchemaTools.addRigidCylinder()
### pxr.PhysicsSchemaTools.addRigidSphere()
### pxr.PhysicsSchemaTools.addVelocity()
### pxr.PhysicsSchemaTools.createMesh()
### pxr.PhysicsSchemaTools.createMeshBox()
### pxr.PhysicsSchemaTools.createMeshCapsule()
### pxr.PhysicsSchemaTools.createMeshCylinder()
### pxr.PhysicsSchemaTools.createMeshSphere()
<dl class="py function">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.createMeshSphere">
<span class="sig-prename descclassname">
<span class="pre">
pxr.PhysicsSchemaTools.
<span class="sig-name descname">
<span class="pre">
createMeshSphere
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<dl class="py function">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.createMeshSquare">
<span class="sig-prename descclassname">
<span class="pre">
pxr.PhysicsSchemaTools.
<span class="sig-name descname">
<span class="pre">
createMeshSquare
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<dl class="py function">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.decodeSdfPath">
<span class="sig-prename descclassname">
<span class="pre">
pxr.PhysicsSchemaTools.
<span class="sig-name descname">
<span class="pre">
decodeSdfPath
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<dl class="py function">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.encodeSdfPath">
<span class="sig-prename descclassname">
<span class="pre">
pxr.PhysicsSchemaTools.
<span class="sig-name descname">
<span class="pre">
encodeSdfPath
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<dl class="py function">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.getMassSpaceInertia">
<span class="sig-prename descclassname">
<span class="pre">
pxr.PhysicsSchemaTools.
<span class="sig-name descname">
<span class="pre">
getMassSpaceInertia
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<dl class="py function">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.intToSdfPath">
<span class="sig-prename descclassname">
<span class="pre">
pxr.PhysicsSchemaTools.
<span class="sig-name descname">
<span class="pre">
intToSdfPath
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
<dl class="py function">
<dt class="sig sig-object py" id="pxr.PhysicsSchemaTools.sdfPathToInt">
<span class="sig-prename descclassname">
<span class="pre">
pxr.PhysicsSchemaTools.
<span class="sig-name descname">
<span class="pre">
sdfPathToInt
<span class="sig-paren">
(
<span class="sig-paren">
)
<dd>
| 24,094 |
planning.md | # Planning Your Installation
Whether you are looking for a way to install a single Omniverse foundation application for a user to test, or want to deploy an entire suite of Omniverse apps and content for your internal users to work and collaborate with, you should review and plan accordingly based on the requirements and options below to ensure your internal infrastructure is at the desired level of readiness.
## System Requirements
- Ensure you have identified at least one computer with the ability to connect to the Internet to download the various installation files, applications and content archives from NVIDIA servers. All of these files are available for both Windows and Linux operating systems (except for the Enterprise Nucleus Server, which is only available for Linux via Docker) and it is up to you to determine which operating systems your users’ workstations need to be supported.
- Confirm that you have hardware within your company firewall with ample disk space (100-500GB) where you can “stage” many of these downloaded files so they can be accessed as part of the installation or deployment process.
- If you don’t have connected staging hardware that is accessible by users’ workstations (they are completely isolated from a network and Internet connections), you should have some form of portable media device (100-500GB) to manually move the downloaded files from one location to another.
- Make sure to update the OS systems that will be utilized and installed upon (ie. Windows Update, etc.) so they are up to date
- Verify that all orchestrations (if needed) have the correct versions in support of Omniverse deployed GPUs etc.
## Configuration Options
- Ensure evaluation of Omniverse application and configuration needs for each internal customer group.
- Create a topology of how Omniverse on internal customer systems (virtual or local) are connected to each other, Nucleus Server / Workstation, etc.
- You can learn about Reference Architectures here.
- You can learn about Virtualized Topologies here.
- Omniverse currently does not support LDAP however, services like Microsoft InTune may be used to support hybrid and remote teams with disparate resources.
## Omniverse Readiness
- Review and identify all internal customer requirements starting from application resource needs (Omniverse + other installed applications) working your way through to confirming your network, servers, and workstations meet these requirements for the collective requirements in deployment.
- Pre-check that available Omniverse installation software are the correct versions required.
- Ensure required Omniverse quantities of licensing are secured.
- Download all necessary files from the Omniverse Enterprise Web Portal and transfer them to an easily accessible local networked system that will act as a staging area.
- Ensure all necessary ports that need to be open for Omniverse applications to communicate with each other are configured properly.
## Permissions
- Ensure that all extensions are downloaded/staged into IT managed **public** folders such as `D:/omniverse/data`. IT organizations tend to lock down non-user folders (anything sans `%USER_ROOT%`) will want to ensure that they have installed “all required” files in the read-only areas for workstation users.
As a first step, you **must** install the **IT Managed Launcher** to your users’ workstations. | 3,404 |
Plug.md | # Plug module
**Summary:** Provides a plug-in framework implementation. Define interfaces, discover, register, and apply plug-in modules to nodes.
## Module: pxr.Plug
This package defines facilities for dealing with plugins.
**Classes:**
| Class | Description |
|-------|-------------|
| [Notice](#pxr.Plug.Notice) | Notifications sent by the Plug module. |
| [Plugin](#pxr.Plug.Plugin) | Defines an interface to registered plugins. |
| [Registry](#pxr.Plug.Registry) | Defines an interface for registering plugins. |
### Class: pxr.Plug.Notice
Notifications sent by the Plug module.
**Classes:**
| Class | Description |
|-------|-------------|
| [Base](#pxr.Plug.Notice.Base) | |
| [DidRegisterPlugins](#pxr.Plug.Notice.DidRegisterPlugins) | |
### Class: pxr.Plug.Notice.Base
### Class: pxr.Plug.Notice.DidRegisterPlugins
## Methods:
### GetNewPlugins()
### DeclaresType(type, includeSubclasses)
Returns true if `type` is declared by this plugin.
### FindPluginResource(path, verify)
Find a plugin resource by absolute or relative path optionally verifying that file exists.
### GetMetadataForType(type)
Returns the metadata sub-dictionary for a particular type.
### Load()
Loads the plugin.
### MakeResourcePath(path)
Build a plugin resource path by returning a given absolute path or combining the plugin's resource path with a given relative path.
## Attributes:
### expired
True if this object has expired, False otherwise.
### isLoaded
bool
### isPythonModule
bool
### isResource
bool
### metadata
| Property | Type |
|----------------|--------|
| `name` | str |
| `path` | str |
| `resourcePath` | str |
### DeclaresType
```python
DeclaresType(type, includeSubclasses) -> bool
```
Returns true if `type` is declared by this plugin. If `includeSubclasses` is specified, also returns true if any subclasses of `type` have been declared.
**Parameters:**
- **type** (Type) –
- **includeSubclasses** (bool) –
### FindPluginResource
```python
FindPluginResource(path, verify) -> str
```
Find a plugin resource by absolute or relative path optionally verifying that file exists. If verification fails an empty path is returned. Relative paths are relative to the plugin’s resource path.
**Parameters:**
- **path** (str) –
- **verify** (bool) –
### GetMetadataForType
```python
GetMetadataForType(type) -> JsObject
```
Returns the metadata sub-dictionary for a particular type.
**Parameters:**
- **type** (Type) –
### Load
```python
Load() -> bool
```
Loads the plugin.
This is a noop if the plugin is already loaded.
```python
MakeResourcePath(path) -> str
```
Build a plugin resource path by returning a given absolute path or combining the plugin’s resource path with a given relative path.
**Parameters**
- **path** (str) –
```python
property expired
```
True if this object has expired, False otherwise.
```python
property isLoaded
```
bool
Returns `true` if the plugin is currently loaded.
Resource plugins always report as loaded.
**Type**
- type
```python
property isPythonModule
```
bool
Returns `true` if the plugin is a python module.
**Type**
- type
```python
property isResource
```
bool
Returns `true` if the plugin is resource-only.
**Type**
- type
```python
property metadata
```
JsObject
Returns the dictionary containing meta-data for the plugin.
**Type**
- type
```python
property name
```
str
Returns the plugin’s name.
**Type**
- type
```python
property path
```
str
Returns the plugin’s filesystem path.
**Type**
- type
```python
property resourcePath
```
<p>str
<p>Returns the plugin’s resources filesystem path.
<dl class="field-list simple">
<dt class="field-odd">Type
<dd class="field-odd">
<p>type
<p>Defines an interface for registering plugins.
<p>PlugRegistry maintains a registry of plug-ins known to the system and provides an interface for base classes to load any plug-ins required to instantiate a subclass of a given type.
<section id="defining-a-base-class-api">
<h2>Defining a Base Class API
<p>In order to use this facility you will generally provide a module which defines the API for a plug-in base class. This API will be sufficient for the application or framework to make use of custom subclasses that will be written by plug-in developers.
<p>For example, if you have an image processing application, you might want to support plug-ins that implement image filters. You can define an abstract base class for image filters that declares the API your application will require image filters to implement; perhaps something simple like C++ Code Example 1 (Doxygen only).
<p>People writing custom filters would write a subclass of ImageFilter that overrides the two methods, implementing their own special filtering behavior.
<section id="enabling-plug-in-loading-for-the-base-class">
<h2>Enabling Plug-in Loading for the Base Class
<p>In order for ImageFilter to be able to load plug-ins that implement these custom subclasses, it must be registered with the TfType system.
<p>The ImageFilter base class, as was mentioned earlier, should be made available in a module that the application links with. This is done so that plug-ins that want to provide ImageFilters can also link with the module allowing them to subclass ImageFilter.
<section id="registering-plug-ins">
<h2>Registering Plug-ins
<p>A plug-in developer can now write plug-ins with ImageFilter subclasses. Plug-ins can be implemented either as native dynamic modules (either regular dynamic modules or framework bundles) or as Python modules.
<p>Plug-ins must be registered with the registry. All plugins are registered via RegisterPlugins(). Plug-in Python modules must be directly importable (in other words they must be able to be found in Python’s module path.) Plugins are registered by providing a path or paths to JSON files that describe the location, structure and contents of the plugin. The standard name for these files in plugInfo.json.
<p>Typically, the application that hosts plug-ins will locate and register plug-ins at startup.
<p>The plug-in facility is lazy. It does not dynamically load code from plug-in bundles until that code is required.
<section id="pluginfo-json">
<h2>plugInfo.json
<p>A plugInfo.json file has the following structure:
<div class="highlight-text notranslate">
<div class="highlight">
<pre>{
# Comments are allowed and indicated by a hash at the start of a
# line or after spaces and tabs. They continue to the end of line.
# Blank lines are okay, too.
# This is optional. It may contain any number of strings.
# Paths may be absolute or relative.
# Paths ending with slash have plugInfo.json appended automatically.
# '\*' may be used anywhere to match any character except slash.
# '\*\*' may be used anywhere to match any character including slash.
"Includes": [
"/absolute/path/to/plugInfo.json",
"/absolute/path/to/custom.filename",
"/absolute/path/to/directory/with/plugInfo/",
"relative/path/to/plugInfo.json",
"relative/path/to/directory/with/plugInfo/",
"glob\*/pa\*th/\*to\*/\*/plugInfo.json",
"recursive/pa\*\*th/\*\*/"
],
# This is optional. It may contain any number of objects.
"Plugins": [
{
# Type is required and may be "module", "python" or "resource".
"Type": "module",
# Name is required. It should be the Python module name,
# the shared module name, or a unique resource name.
"Name": "myplugin",
# Root is optional. It defaults to ".".
# This gives the path to the plugin as a whole if the plugin
# has substructure. For Python it should be the directory
# with the __init__.py file. The path is usually relative.
"Root": ".",
# LibraryPath is required by Type "module" and unused
# otherwise. It gives the path to the shared module
# object, either absolute or relative to Root.
"LibraryPath": "libmyplugin.so",
# ResourcePath is option. It defaults to ".".
# This gives the path to the plugin's resources directory.
# The path is either absolute or relative to Root.
"ResourcePath": "resources",
# Info is required. It's described below.
"Info": {
# Plugin contents.
}
}
]
}
<p>As a special case, if a plugInfo.json contains an object that doesn’t have either the”Includes”or”Plugins”keys then it’s as if the object was in a”Plugins”array.
<section id="advertising-a-plug-in-s-contents">
<h2>Advertising a Plug-in’s Contents
<p>Once the plug-ins are registered, the plug-in facility must also be able to tell what they contain. Specifically, it must be able to find out what subclasses of what plug-in base classes each plug-in contains. Plug-ins must advertise this information through their plugInfo.json file in the”Info”key. In the”Info”object there should be a key”Types”holding an object.
<p>This”Types”object’s keys are names of subclasses and its values are yet more objects (the subclass meta-data objects). The meta-data objects can contain arbitrary key-value pairs. The plug-in mechanism will look for a meta-data key called”displayName”whose value should be the display name of the subclass. The plug-in mechanism will look for a meta-data key called”bases”whose value should be an array of base class type names.
<p>For example, a bundle that contains a subclass of ImageFilter might have a plugInfo.json that looks like the following example.
<div class="highlight-text notranslate">
<div class="highlight">
<pre>{
"Types": {
"MyCustomCoolFilter" : {
"bases": ["ImageFilter"],
"displayName": "Add Coolness to Image"
# other arbitrary metadata for MyCustomCoolFilter here
}
}
}
<p>What this says is that the plug-in contains a type called MyCustomCoolFilter which has a base class ImageFilter and that this subclass should be called”Add Coolness to Image”in user-visible contexts.
<p>In addition to the”displayName”meta-data key which is actually known to the plug-in facility, you may put whatever other information you want into a class’meta-data dictionary. If your plug-in base class wants to define custom keys that it requires all subclasses to provide, you can do that. Or, if a plug-in writer wants to define
# Working with Subclasses of a Plug-in Base Class
Most code with uses types defined in plug-ins doesn’t deal with the Plug API directly. Instead, the TfType interface is used to lookup types and to manufacture instances. The TfType interface will take care to load any required plugins.
To wrap up our example, the application that wants to actually use ImageFilter plug-ins would probably do a couple of things. First, it would get a list of available ImageFilters to present to the user. This could be accomplished as shown in Python Code Example 2 (Doxygen only).
Then, when the user picks a filter from the list, it would manufacture an instance of the filter as shown in Python Code Example 3 (Doxygen only).
As was mentioned earlier, this plug-in facility tries to be as lazy as possible about loading the code associated with plug-ins. To that end, loading of a plugin will be deferred until an instance of a type is manufactured which requires the plugin.
# Multiple Subclasses of Multiple Plug-in Base Classes
It is possible for a bundle to implement multiple subclasses for a plug-in base class if desired. If you want to package half a dozen ImageFilter subclasses in one bundle, that will work fine. All must be declared in the plugInfo.json.
It is possible for there to be multiple classes in your application or framework that are plug-in base classes. Plug-ins that implement subclasses of any of these base classes can all coexist. And, it is possible to have subclasses of multiple plug-in base classes in the same bundle.
When putting multiple subclasses (of the same or different base classes) in a bundle, keep in mind that dynamic loading happens for the whole bundle the first time any subclass is needed, the whole bundle will be loaded. But this is generally not a big concern.
For example, say the example application also has a plug-in base class "ImageCodec" that allows people to add support for reading and writing other image formats. Imagine that you want to supply a plug-in that has two codecs and a filter all in a single plug-in. Your plugInfo.json "Info" object might look something like this example.
```json
{
"Types": {
"MyTIFFCodec": {
"bases": ["ImageCodec"],
"displayName": "TIFF Image"
},
"MyJPEGCodec": {
"bases": ["ImageCodec"],
"displayName": "JPEG Image"
},
"MyCustomCoolFilter" : {
"bases": ["ImageFilter"],
"displayName": "Add Coolness to Image"
}
}
}
```
# Dependencies on Other Plug-ins
If you write a plug-in that has dependencies on another plug-in that you cannot (or do not want to) link against statically, you can declare the dependencies in your plug-in’s plugInfo.json. A plug-in declares dependencies on other classes with a PluginDependencies key whose value is a dictionary. The keys of the dictionary are plug-in base class names and the values are arrays of subclass names.
The following example contains an example of a plug-in that depends on two classes from the plug-in in the previous example.
```json
{
"Types": {
"UltraCoolFilter": {
"bases": ["MyCustomCoolFilter"],
"displayName": "Add Unbelievable Coolness to Image"
# A subclass of MyCustomCoolFilter that also uses MyTIFFCodec
}
},
"PluginDependencies": {
"ImageFilter": ["MyCustomCoolFilter"],
"ImageCodec": ["MyTIFFCodec"]
}
}
```
The ImageFilter provided by the plug-in in this example depends on the other ImageFilter MyCoolImageFilter and the ImageCodec MyTIFFCodec. Before loading this plug-in, the plug-in facility will ensure that those two classes are present, loading the plug-in that contains them if needed.
**Methods:**
- **classmethod** FindDerivedTypeByName(base, typeName) -> Type
- **classmethod** FindTypeByName(typeName) -> Type
- **classmethod** GetAllDerivedTypes(base, result) -> None
- Returns all registered plug-ins.
- **classmethod** GetDirectlyDerivedTypes(base) -> list[Type]
- Returns the plug-in for the given type, or a null pointer if there is no registered plug-in.
| 属性 | 描述 |
| --- | --- |
| `GetPluginWithName(name)` | Returns a plugin with the specified module name. |
| `GetStringFromPluginMetaData(type, key)` | Looks for a string associated with `type` and `key` and returns it, or an empty string if `type` or `key` are not found. |
| `RegisterPlugins(pathToPlugInfo)` | Registers all plug-ins discovered at `pathToPlugInfo`. |
**Attributes:**
| 属性 | 描述 |
| --- | --- |
| `expired` | True if this object has expired, False otherwise. |
**classmethod FindDerivedTypeByName(base, typeName) -> Type**
Retrieve the `TfType` that derives from `base` and has the given alias or type name `typeName`.
See the documentation for `TfType::FindDerivedByName` for more information. Use this function if you expect that the derived type may be provided by a plugin. Calling this function will incur plugin discovery (but not loading) if plugin discovery has not yet occurred.
Note that additional plugins may be registered during program runtime.
**Parameters**
- **base** (`Type`) –
- **typeName** (`str`) –
**classmethod FindTypeByName(typeName) -> Type**
Retrieve the `TfType` that has the given alias or type name `typeName`.
See the documentation for `TfType::FindDerivedByName` for more information. Use this function if you expect that the derived type may be provided by a plugin. Calling this function will incur plugin discovery (but not loading) if plugin discovery has not yet occurred.
Note that additional plugins may be registered during program runtime.
**Parameters**
- **typeName** (`str`) –
<span class="pre">
TfType
corresponding to the given
<code class="docutils literal notranslate">
<span class="pre">
name
.
<p>
See the documentation for
<code class="docutils literal notranslate">
<span class="pre">
TfType::FindByName
for more information.
Use this function if you expect that
<code class="docutils literal notranslate">
<span class="pre">
name
may name a type provided
by a plugin. Calling this function will incur plugin discovery (but
not loading) if plugin discovery has not yet occurred.
<p>
Note that additional plugins may be registered during program runtime.
<p>
Plug-In Discovery & Registration
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
typeName
(
<em>
str
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Plug.Registry.GetAllDerivedTypes">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
GetAllDerivedTypes
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Plug.Registry.GetAllDerivedTypes" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
GetAllDerivedTypes(base, result) -> None
<p>
Return the set of all types derived (directly or indirectly) from
<em>
base
.
<p>
Use this function if you expect that plugins may provide types derived
from
<em>
base
. Otherwise, use
<em>
TfType::GetAllDerivedTypes
.
<p>
Note that additional plugins may be registered during program runtime.
<p>
Plug-In Discovery & Registration
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<ul class="simple">
<li>
<p>
<strong>
base
(
<a class="reference internal" href="Tf.html#pxr.Tf.Type" title="pxr.Tf.Type">
<em>
Type
) –
<li>
<p>
<strong>
result
(
<em>
set
<em>
[
<a class="reference internal" href="Tf.html#pxr.Tf.Type" title="pxr.Tf.Type">
<em>
Type
<em>
]
) –
<hr class="docutils"/>
<p>
GetAllDerivedTypes(result) -> None
<p>
Return the set of all types derived (directly or indirectly) from
<em>
Base
.
<p>
Use this function if you expect that plugins may provide types derived
from
<em>
base
. Otherwise, use
<em>
TfType::GetAllDerivedTypes
.
<p>
Note that additional plugins may be registered during program runtime.
<p>
Plug-In Discovery & Registration
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
result
(
<em>
set
<em>
[
<a class="reference internal" href="Tf.html#pxr.Tf.Type" title="pxr.Tf.Type">
<em>
Type
<em>
]
) –
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Plug.Registry.GetAllPlugins">
<span class="sig-name descname">
<span class="pre">
GetAllPlugins
<span class="sig-paren">
(
<span class="sig-paren">
)
<span class="sig-return">
<span class="sig-return-icon">
→
<span class="sig-return-typehint">
<span class="pre">
list
<span class="p">
<span class="pre">
[
<span class="pre">
PlugPluginPtr
<span class="p">
<span class="pre">
]
<a class="headerlink" href="#pxr.Plug.Registry.GetAllPlugins" title="Permalink to this definition">
<dd>
<p>
Returns all registered plug-ins.
<p>
Note that additional plugins may be registered during program runtime.
<p>
Plug-In Discovery & Registration
<dl class="py method">
<dt class="sig sig-object py" id="pxr.Plug.Registry.GetDirectlyDerivedTypes">
<em class="property">
<span class="pre">
static
<span class="w">
<span class="sig-name descname">
<span class="pre">
GetDirectlyDerivedTypes
<span class="sig-paren">
(
<span class="sig-paren">
)
<a class="headerlink" href="#pxr.Plug.Registry.GetDirectlyDerivedTypes" title="Permalink to this definition">
<dd>
<p>
<strong>
classmethod
GetDirectlyDerivedTypes(base) -> list[Type]
<p>
Return a vector of types derived directly from
<em>
base
.
<p>
Use this function if you expect that plugins may provide types derived
from
<em>
base
. Otherwise, use
<em>
TfType::GetDirectlyDerivedTypes
.
<dl class="field-list simple">
<dt class="field-odd">
Parameters
<dd class="field-odd">
<p>
<strong>
base
(
<a class="reference internal" href="Tf.html#pxr.Tf.Type" title="pxr.Tf.Type">
<em>
Type
) –
### GetPluginForType
```python
GetPluginForType(t) -> Plugin
```
Returns the plug-in for the given type, or a null pointer if there is no registered plug-in.
**Parameters**
- **t** (`Type`) –
### GetPluginWithName
```python
GetPluginWithName(name) -> Plugin
```
Returns a plugin with the specified module name.
Note that additional plugins may be registered during program runtime.
**Parameters**
- **name** (`str`) –
### GetStringFromPluginMetaData
```python
GetStringFromPluginMetaData(type, key) -> str
```
Looks for a string associated with `type` and `key` and returns it, or an empty string if `type` or `key` are not found.
**Parameters**
- **type** (`Type`) –
- **key** (`str`) –
### RegisterPlugins
```python
RegisterPlugins(pathToPlugInfo) -> list[PlugPluginPtr]
```
Registers all plug-ins discovered at `pathToPlugInfo`.
Sends PlugNotice::DidRegisterPlugins with any newly registered plugins.
**Parameters**
- **pathToPlugInfo** (`str`) –
RegisterPlugins(pathsToPlugInfo) -> list[PlugPluginPtr]
Registers all plug-ins discovered in any of `pathsToPlugInfo`.
Sends PlugNotice::DidRegisterPlugins with any newly registered plugins.
**Parameters**
- **pathsToPlugInfo** (`list[str]`) –
True if this object has expired, False otherwise. | 21,775 |