file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.actions/docs/Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create actions in C++ that can then be executed from either C++ or Python.
See the omni.kit.actions.core extension for extensive documentation about actions themselves.
# C++ Usage Examples
## Defining Custom Actions
```
using namespace omni::kit::actions::core;
class ExampleCustomAction : public Action
{
public:
static carb::ObjectPtr<IAction> create(const char* extensionId,
const char* actionId,
const MetaData* metaData)
{
return carb::stealObject<IAction>(new ExampleCustomAction(extensionId, actionId, metaData));
}
ExampleCustomAction(const char* extensionId, const char* actionId, const MetaData* metaData)
: Action(extensionId, actionId, metaData), m_executionCount(0)
{
}
carb::variant::Variant execute(const carb::variant::Variant& args = {},
const carb::dictionary::Item* kwargs = nullptr) override
{
++m_executionCount;
printf("Executing %s (execution count = %d).\n", getActionId(), m_executionCount);
return carb::variant::Variant(m_executionCount);
}
void invalidate() override
{
resetExecutionCount();
}
uint32_t getExecutionCount() const
{
return m_executionCount;
}
protected:
void resetExecutionCount()
{
m_executionCount = 0;
}
private:
uint32_t m_executionCount = 0;
};
```
## Creating and Registering Custom Actions
```
// Example of creating and registering a custom action from C++.
Action::MetaData metaData;
metaData.displayName = "Example Custom Action Display Name";
metaData.description = "Example Custom Action Description.";
carb::ObjectPtr<IAction> exampleCustomAction =
ExampleCustomAction::create("omni.example.cpp.actions", "example_custom_action_id", &metaData);
carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>()->registerAction(exampleCustomAction);
```
## Creating and Registering Lambda Actions
```
auto actionRegistry = carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>();
// Example of creating and registering a lambda action from C++.
omni::kit::actions::core::IAction::MetaData metaData;
metaData.displayName = "Example Lambda Action Display Name";
metaData.description = "Example Lambda Action Description.";
carb::ObjectPtr<IAction> exampleLambdaAction =
omni::kit::actions::core::LambdaAction::create(
"omni.example.cpp.actions", "example_lambda_action_id", &metaData,
[this](const carb::variant::Variant& args = {}, const carb::dictionary::Item* kwargs = nullptr) {
printf("Executing example_lambda_action_id.\n");
return carb::variant::Variant();
}));
carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>()->registerAction(exampleLambdaAction);
```
```
// Example of creating and registering (at the same time) a lambda action from C++.
carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>()->registerAction(
"omni.example.cpp.actions", "example_lambda_action_id",
[](const carb::variant::Variant& args = {}, const carb::dictionary::Item* kwargs = nullptr) {
printf("Executing example_lambda_action_id.\n");
return carb::variant::Variant();
},
"Example Lambda Action Display Name",
"Example Lambda Action Description.");
```
## Discovering Actions
```
auto registry = carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>();
// Retrieve an action that has been registered using the registering extension id and the action id.
carb::ObjectPtr<IAction> action = registry->getAction("omni.example.cpp.actions", "example_custom_action_id");
// Retrieve all actions that have been registered by a specific extension id.
std::vector<carb::ObjectPtr<IAction>> actions = registry->getAllActionsForExtension("example");
// Retrieve all actions that have been registered by any extension.
std::vector<carb::ObjectPtr<IAction>> actions = registry->getAllActions();
```
## Deregistering Actions
```
auto actionRegistry = carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>();
// Deregister an action directly...
actionRegistry->deregisterAction(exampleCustomAction);
// or using the registering extension id and the action id...
actionRegistry->deregisterAction("omni.example.cpp.actions", "example_custom_action_id");
// or deregister all actions that were registered by an extension.
actionRegistry->deregisterAllActionsForExtension("omni.example.cpp.actions");
```
## Executing Actions
```
auto actionRegistry = carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>();
// Execute an action after retrieving it from the action registry.
auto action = actionRegistry->getAction("omni.example.cpp.actions", "example_custom_action_id");
action->execute();
// Execute an action indirectly (retrieves it internally).
actionRegistry->executeAction("omni.example.cpp.actions", "example_custom_action_id");
// Execute an action that was stored previously.
exampleCustomAction->execute();
```
Note: All of the above will find any actions that have been registered from either Python or C++,
and you can interact with them without needing to know anything about where they were registered.
| 5,460 | Markdown | 32.503067 | 110 | 0.712088 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/README.md | # omni.ui.scene Kit Extension Samples
## [Object Info (omni.example.ui_scene.object_info)](exts/omni.example.ui_scene.object_info)
[](exts/omni.example.ui_scene.object_info)
### About
This extension uses the omni.ui.scene API to add simple graphics and labels in the viewport above your selected prim. The labels provide the prim path of the selected prim and the prim path of its assigned material.
### [README](exts/omni.example.ui_scene.object_info)
See the [README for this extension](exts/omni.example.ui_scene.object_info) to learn more about it including how to use it.
### [Tutorial](exts/omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md)
Follow a [step-by-step tutorial](exts/omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
## [Widget Info (omni.example.ui_scene.widget_info)](exts/omni.example.ui_scene.object_info)
[](exts/omni.example.ui_scene.widget_info)
### About
This extension uses the omni.ui.scene API to add a widget in the viewport, just above your selected prim. The widget provides the prim path of your selection and a scale slider.
### [README](exts/omni.example.ui_scene.widget_info)
See the [README for this extension](exts/omni.example.ui_scene.widget_info) to learn more about it including how to use it.
### [Tutorial](exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md)
Follow a [step-by-step tutorial](exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
## [Light Manipulator (omni.example.ui_scene.light_manipulator)](exts/omni.example.ui_scene.light_manipulator)
[](exts/omni.example.ui_scene.light_manipulator)
### About
This extension add a custom manipulator for RectLights that allows you to control the width, height, and intensity of RectLights by clicking and dragging in the viewport.
### [README](exts/omni.example.ui_scene.light_manipulator)
See the [README for this extension](exts/omni.example.ui_scene.light_manipulator) to learn more about it including how to use it.
### [Tutorial](exts/omni.example.ui_scene.light_manipulator/tutorial/tutorial.md)
Follow a [step-by-step tutorial](exts/omni.example.ui_scene.light_manipulator/tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
## [Slider Manipulator (omni.example.ui_scene.slider_manipulator)](exts/omni.example.ui_scene.slider_manipulator)
[](exts/omni.example.ui_scene.slider_manipulator)
### About
This extension add a custom slider manipulator above you selected prim that controls the scale of the prim when you click and drag the slider.
### [README](exts/omni.example.ui_scene.slider_manipulator)
See the [README for this extension](exts/omni.example.ui_scene.slider_manipulator) to learn more about it including how to use it.
### [Tutorial](exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md)
Follow a [step-by-step tutorial](exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
# Adding These Extensions
To add these extensions to your Omniverse app:
1. Go into: Extension Manager -> Gear Icon -> Extension Search Path
2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene?branch=main&dir=exts`
## Linking with an Omniverse app
For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included.
Run:
```bash
> link_app.bat
```
There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```bash
> link_app.bat --app code
```
You can also just pass a path to create link to:
```bash
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3"
```
Running this command adds a symlink to Omniverse Code. This makes intellisense work and lets you easily run the app from the terminal.
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 4,736 | Markdown | 52.224719 | 215 | 0.776394 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/scripts/link_app.py | import os
import argparse
import sys
import json
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,813 | Python | 32.5 | 133 | 0.562389 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import zipfile
import tempfile
import sys
import shutil
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(
package_src_path, allowZip64=True
) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning(
"Directory %s already present, packaged installation aborted" % package_dst_path
)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,888 | Python | 31.568965 | 103 | 0.68697 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md | 
# How to make a Slider Manipulator
In this guide you will learn how to draw a 3D slider in the viewport that overlays on the top of the bounding box of the selected prim. This slider will control the scale of the prim with a custom manipulator, model, and gesture. When the slider is changed, the manipulator processes the custom gesture that changes the data in the model, which changes the data directly in the USD stage.

# Learning Objectives
- Create an extension
- Import omni.ui and USD
- Set up Model and Manipulator
- Create Gestures
- Create a working scale slider
# Prerequisites
To help understand the concepts used in this guide, it is recommended that you complete the following:
- [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial)
- [Spawning Prims Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims)
- [Display Object Info Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/tree/main/exts/omni.example.ui_scene.object_info)
:exclamation: <span style="color:red"><b>WARNING:</b> Check that Viewport Utility Extension is turned ON in the Extensions Manager: </span>

# Step 1: Create the extension
In this section, you will create a new extension in Omniverse Code.
## Step 1.1: Create new extension template
In Omniverse Code navigate to the `Extensions` tab and create a new extension by clicking the ➕ icon in the upper left corner and select `New Extension Template Project`.


<br>
A new extension template window and Visual Studio Code will open after you have selected the folder location, folder name, and extension ID.
## Step 1.2: Naming your extension
In the extension manager, you may have noticed that each extension has a title and description:

You can change this in the `extension.toml` file by navigating to `VS Code` and editing the file there. It is important that you give your extension a detailed title and summary for the end user to understand what your extension will accomplish or display. Here is how to change it for this guide:
```python
# The title and description fields are primarily for displaying extension info in UI
title = "UI Scene Slider Manipulator"
description="Interactive example of the slider manipulator with omni.ui.scene"
```
## Step 2: Model module
In this step you will be creating the `slider_model.py` module where you will be tracking the current selected prim, listening to stage events, and getting the position directly from USD.
This module will be made up of many lines so be sure to review the <b>":memo:Code Checkpoint"</b> for updated code of the module at various steps.
### Step 2.1: Import omni.ui and USD
After creating `slider_model.py` in the same folder as `extension.py`, import `scene` from `omni.ui` and the necessary USD modules, as follows:
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
```
### Step 2.2: `SliderModel` and `PositionItem` Classes
Next, let's set up your `SliderModel` and `PositionItem` classes. `SliderModel` tracks the position and scale of the selected prim and `PositionItem` stores the position value.
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
# NEW
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# END NEW
```
## Step 2.3: Current Selection and Tracking Selection
In this section, you will be setting the variables for the current selection and tracking the selected prim, where you will also set parameters for the stage event later on.
```python
...
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# NEW
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
# END NEW
```
>:memo: Code Checkpoint
<details>
<summary> Click here for the updated <b>SliderModel</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
```
</details>
## Step 2.4: Define `on_stage_event()`
With your selection variables set, you now define the `on_stage_event()` call back to get the selected prim and its position on selection changes. You will start the new function for these below module previous code:
```python
...
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
```
>:memo: Code Checkpoint
<details>
<summary> Click here for the updated <b>SliderModel</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
```
</details>
<br>
## Step 2.5: `Tf.Notice` callback
In the previous step, you registered a callback to be called when objects in the stage change. [Click here for more information on Tf.Notice.](https://graphics.pixar.com/usd/dev/api/page_tf__notification.html) Now, you will define the callback function. You want to update the stored position of the selected prim. You can add that as follows:
```python
...
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
```
## Step 2.6: Set the Position Identifier and return Position
Let's define the identifier for position like so:
```python
...
def get_item(self, identifier):
if identifier == "position":
return self.position
```
And now, you will set item to return the position and get the value from the item:
```python
...
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
```
>:memo: Code Checkpoint
<details>
<summary> Click here for the updated <b>SliderModel</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
```
</details>
### Step 2.7: Position from USD
In this last section of `slider_model.py`, you will be defining `get_position` to compute position directly from USD, like so:
```python
...
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
>:memo: Code Checkpoint
<details>
<summary> Click here for the full <b>slider_model.py</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
</details>
## Step 3: Manipulator Module
In this step, you will be creating `slider_manipulator.py` in the same folder as `slider_model.py`. The Manipulator class will define `on_build()` as well as create the `Label` and regenerate the model.
### Step 3.1: Import omni.ui
After creating `slider_manipulator.py`, import `omni.ui` as follows:
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
```
### Step 3.2: Create `SliderManipulator` class
Now, you will begin the `SliderManipulator` class and define the `__init__()`:
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
```
### Step 3.3: Define `on_build()` and create the `Label`
`on_build()` is called when the model is changed and it will rebuild the slider. You will also create the `Label` for the slider and position it more towards the top of the screen.
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
```
### Step 3.4: Regenerate the Manipulator
Finally, let's define `on_model_updated()` to regenerate the manipulator:
```python
...
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the full <b>slider_manipulator.py</b> </summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
<br>
<br>
## Step 4: Registry Module
In this step, you will create `slider_registry.py` in the same location as the `slider_manipulator.py`. You will use `slider_registry.py` to have the number display on the screen when the prim is selected.
### Step 4.1: Import from Model and Manipulator
After creating `slider_registry.py`, import from the `SliderModel` and `SliderManipulator`, as well as `import typing` for type hinting, like so:
```python
from .slider_model import SliderModel
from .slider_manipulator import SliderManipulator
from typing import Any
from typing import Dict
from typing import Optional
```
### Step 4.2: Disable Selection in Viewport Legacy
Your first class will address disabling the selection in viewport legacy but you may encounter a bug that will not set your focused window to `True`. As a result, you will operate all `Viewport` instances for a given usd_context instead:
```python
...
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact the focused window!
# And there's no good solution to this when multiple Viewport-1 instances are open; so you just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
```
### Step 4.3: `SliderChangedGesture` Class
Under your previously defined `ViewportLegacyDisableSelection` class, you will define `SliderChangedGesture` class. In this class you will start with `__init__()` and then define `on_began()`, which will disable the selection rect when the user drags the slider:
```python
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, you don't want to see the selection rect
self.__disable_selection = ViewportLegacyDisableSelection()
```
Next in this class, you will define `on_changed()`, which will be called when the user moves the slider. This will update the mesh as the scale of the model is changed. You will also define `on_ended()` to re-enable the selection rect when the slider is not being dragged.
```python
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
```
>:memo: Code Checkpoint
<details>
<summary>Click here for <b>slider_registry.py</b> up to this point</summary>
```python
from .slider_model import SliderModel
from .slider_manipulator import SliderManipulator
from typing import Any
from typing import Dict
from typing import Optional
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact the focused window!
# And there's no good solution to this when multiple Viewport-1 instances are open; so you just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, you don't want to see the selection rect
self.__disable_selection = ViewportLegacyDisableSelection()
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
```
</details>
### Step 4.4: `SliderRegistry` Class
Now create `SliderRegistry` class after your previous functions.
This class is created by `omni.kit.viewport.registry` or `omni.kit.manipulator.viewport` per viewport and will keep the manipulator and some other properties that are needed in the viewport. You will set the `SliderRegistry` class after the class you made in the previous step. Included in this class are the `__init__()` methods for your manipulator and some getters and setters:
```python
...
class SliderRegistry:
"""
Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per
viewport. Keeps the manipulator and some properties that are needed to the
viewport.
"""
def __init__(self, description: Optional[Dict[str, Any]] = None):
self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture())
def destroy(self):
if self.__slider_manipulator:
self.__slider_manipulator.destroy()
self.__slider_manipulator = None
# PrimTransformManipulator & TransformManipulator don't have their own visibility
@property
def visible(self):
return True
@visible.setter
def visible(self, value):
pass
@property
def categories(self):
return ("manipulator",)
@property
def name(self):
return "Example Slider Manipulator"
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the full <b>slider_registry.py</b> </summary>
```python
from .slider_model import SliderModel
from .slider_manipulator import SliderManipulator
from typing import Any
from typing import Dict
from typing import Optional
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so you just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, you don't want to see the selection rect
self.__disable_selection = ViewportLegacyDisableSelection()
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
class SliderRegistry:
"""
Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per
viewport. Keeps the manipulator and some properties that are needed to the
viewport.
"""
def __init__(self, description: Optional[Dict[str, Any]] = None):
self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture())
def destroy(self):
if self.__slider_manipulator:
self.__slider_manipulator.destroy()
self.__slider_manipulator = None
# PrimTransformManipulator & TransformManipulator don't have their own visibility
@property
def visible(self):
return True
@visible.setter
def visible(self, value):
pass
@property
def categories(self):
return ("manipulator",)
@property
def name(self):
return "Example Slider Manipulator"
```
</details>
<br>
<br>
## Step 5: Update `extension.py`
You still have the default code in `extension.py` so now you will update the code to reflect the the modules you made. You can locate the `extension.py` in the `exts` folder hierarchy where you created `slider_model.py` and `slider_manipulator.py`.
### Step 5.1: New `extension.py` Imports
Let's begin by updating the imports at the top of `extension.py` to include `ManipulatorFactory`, `RegisterScene`, and `SliderRegistry` so that you can use them later on:
```python
import omni.ext
# NEW
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.viewport.registry import RegisterScene
from .slider_registry import SliderRegistry
# END NEW
```
### Step 5.2: References in on_startup
In this step, you will remove the default code in `on_startup` and replace it with a reference to the `slider_registry` and `slider_factory`, like so:
```python
...
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
# NEW
self.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider")
self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry)
# END NEW
```
### Step 5.3: Update on_shutdown
Now, you need to properly shutdown the extension. Let's remove the print statement and replace it with:
```python
...
def on_shutdown(self):
# NEW
ManipulatorFactory.destroy_manipulator(self.slider_factory)
self.slider_factory = None
self.slider_registry.destroy()
self.slider_registry = None
# END NEW
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the full <b>extension.py</b></summary>
```python
import omni.ext
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.viewport.registry import RegisterScene
from .slider_registry import SliderRegistry
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider")
self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry)
def on_shutdown(self):
ManipulatorFactory.destroy_manipulator(self.slider_factory)
self.slider_factory = None
self.slider_registry.destroy()
self.slider_registry = None
```
</details>
This is what you should see at this point in the viewport:

## Step 6: Creating the Slider Widget
Now that you have all of the variables and necessary properties referenced, let's start to create the slider widget. You will begin by creating the geometry needed for the widget, like the line, and then you will add a circle to the line.
### Step 6.1: Geometry Properties
You are going to begin by adding new geometry to `slider_manipulator.py`. You will set the geometry properties in the `__init__()` like so:
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# NEW
# Geometry properties
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
# END NEW
```
### Step 6.2: Create the line
Next, you will create a line above the selected prim. Let's add this to `on_build()`:
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# NEW
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# END NEW
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
```
This should be the result in your viewport:

### Step 6.3: Create the circle
You are still working in `slider_manipulator.py` and now you will be adding the circle on the line for the slider. This will also be added to `on_build()` like so:
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self.radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# NEW
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# END NEW
...
```
Now, your line in your viewport should look like this:

<details>
<summary>Click here for the full <b>slider_manipulatory.py</b></summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Geometry properties
self.width = 100
self.thickness = 5
self.radius = 5
self.radius_hovered = 7
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
<br>
## Step 7: Set up the Model
For this step, you will need to set up `SliderModel` to hold the information you need for the size of the selected prim. You will later use this information to connect it to the Manipulator.
### Step 7.1: Import Omniverse Command Library
First, let's start by importing the Omniverse Command Library in `slider_model.py`
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
# NEW IMPORT
import omni.kit.commands
# END NEW
```
### Step 7.2: ValueItem Class
Next, you will add a new Manipulator Item class, which you will name `ValueItem`, like so:
```python
...
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
# NEW MANIPULATOR ITEM
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
# END NEW
...
```
You will use this new class to create the variables for the min and max of the scale:
```python
...
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self) -> None:
super().__init__()
# NEW
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
# END NEW
self.position = SliderModel.PositionItem()
...
```
### Step 7.3: Set Scale to Stage
With the new variables for the scale, populate them in `on_stage_event()` like so:
```python
...
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# NEW
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# END NEW
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
...
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the updated <b>slider_model.py</b> at this point </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
import omni.kit.commands
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self) -> None:
super().__init__()
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
</details>
### Step 7.4: Define Identifiers
Just as you defined the identifier for position, you must do the same for value, min, and max. You will add these to `get_item`:
```python
...
def get_item(self, identifier):
if identifier == "position":
return self.position
# NEW
if identifier == "value":
return self.scale
if identifier == "min":
return self.min
if identifier == "max":
return self.max
# END NEW
...
```
### Step 7.5: Set Floats
Previously, you called `set_floats()`, now define it after `get_item()`. In this function, you will set the scale when setting the value, set directly to the item, and update the manipulator:
```python
def set_floats(self, item, value):
if not self.current_path:
return
if not value or not item or item.value == value:
return
if item == self.scale:
# Set the scale when setting the value.
value[0] = min(max(value[0], self.min.value[0]), self.max.value[0])
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(
self.stage.GetPrimAtPath(self.current_path)
)
omni.kit.commands.execute(
"TransformPrimSRTCommand",
path=self.current_path,
new_translation=old_translation,
new_rotation_euler=old_rotation_euler,
new_scale=Gf.Vec3d(value[0], value[0], value[0]),
)
# Set directly to the item
item.value = value
# This makes the manipulator updated
self._item_changed(item)
```
<details>
<summary>Click here for the full <b>slider_model.py</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
import omni.kit.commands
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self) -> None:
super().__init__()
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
if identifier == "value":
return self.scale
if identifier == "min":
return self.min
if identifier == "max":
return self.max
def set_floats(self, item, value):
if not self.current_path:
return
if not value or not item or item.value == value:
return
if item == self.scale:
# Set the scale when setting the value.
value[0] = min(max(value[0], self.min.value[0]), self.max.value[0])
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(
self.stage.GetPrimAtPath(self.current_path)
)
omni.kit.commands.execute(
"TransformPrimSRTCommand",
path=self.current_path,
new_translation=old_translation,
new_rotation_euler=old_rotation_euler,
new_scale=Gf.Vec3d(value[0], value[0], value[0]),
)
# Set directly to the item
item.value = value
# This makes the manipulator updated
self._item_changed(item)
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
</details>
## Step 8: Add Gestures
For your final step, you will be updating `slider_manipulator.py` to add the gestures needed to connect what you programmed in the Model. This will include checking that the gesture is not prevented during drag, calling the gesture, restructure the geometry properties, and update the Line and Circle.
### Step 8.1: `SliderDragGesturePayload` Class
Begin by creating a new class that the user will access to get the current value of the slider, like so:
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
# NEW
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
## END NEW
...
```
### Step 8.2 `SliderChangedGesture` Class
Next, you will create another new class that the user will reimplement to process the manipulator's callbacks, in addition to a new `__init__()`:
```python
...
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
# NEW
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
# END NEW
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
...
```
Nested inside of the `SliderChangedGesture` class, define `process()` directly after the `__init__()` definition of this class:
```python
...
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
# NEW
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# END NEW
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
```
>:memo:Code Checkpoint
<details>
<summary>Click here for the updated <b>slider_manipulator.py</b> at this point </summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
Now, you need to define a few of the Public API functions after the `process` function:
```python
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# NEW
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
# END NEW
```
### Step 8.3 `_ArcGesturePrioritize` Class
You will be adding an `_ArcGesture` class in the next step that needs the manager `_ArcGesturePrioritize` to make it the priority gesture. You will add the manager first to make sure the drag of the slider is not prevented during drag. You will slot this new class after your Public API functions:
```python
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
# NEW
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
# END NEW
```
### Step 8.4: `_ArcGesture` Class
Now, create the class `_ArcGesture` where you will set the new slider value and redirect to `SliderChangedGesture` class you made previously. This new class will be after the `ArcGesturePrioritize` manager class.
```python
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
# NEW
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
# END NEW
```
>:memo:Code Checkpoint
<details>
<summary>Click here for the updated <b>slider_manipulator.py</b> at this point </summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
### Step 8.5: Restructure Geometry Parameters
For this step, you will be adding to `__init__()` that nests your Geometry properties, such as `width`,`thickness`,`radius`, and `radius_hovered`.
>:bulb: Tip: If you are having trouble locating the geometry properties, be reminded that this `__init__()` is after the new classes you added in the previous steps. You should find it under "_ArcGesture"
Start by defining `set_radius()` for the circle so that you can change it on hover later, and also set the parameters for arc_gesture to make sure it's active when the object is recreated:
```python
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Geometry properties
self._width = 100
self._thickness = 5
self._radius = 5
self._radius_hovered = 7
# NEW
def set_radius(circle, radius):
circle.radius = radius
# You don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
# END NEW
```
### Step 8.6: Add Hover Gestures
Now that you have set the geometry properties for when you hover over them, create the `HoverGesture` instance. You will set this within an `if` statement under the parameters for `self._arc_gesture`:
```python
# You don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
# NEW
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
# END NEW
```
## Step 8.7: UI Getters and Setters
Before moving on, you need to add a few Python decorators for the UI, such as `@property`,`@width.setter` and `@height.setter`. These can be added after the `HoverGesture` statement from the step above:
```python
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the updated <b>slider_manipulator.py</b> at this point</summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def set_radius(circle, radius):
circle.radius = radius
# You don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
### Step 8.8: Update `on_build()`
For your final step in the Manipulator module, you will update `on_build()` to update the min and max values of the model, update the line and circle, and update the label.
Start with replacing the `value` variable you had before with a new set of variables for `_min`,`_max`, new `value`, and `value_normalized`.
```python
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
### REPLACE ####
value = 0.0
### WITH ####
_min = self.model.get_as_floats(self.model.get_item("min"))[0]
_max = self.model.get_as_floats(self.model.get_item("max"))[0]
value = float(self.model.get_as_floats(self.model.get_item("value"))[0])
value_normalized = (value - _min) / (_max - _min)
value_normalized = max(min(value_normalized, 1.0), 0.0)
# END NEW
position = self.model.get_as_floats(self.model.get_item("position"))
```
Now, you will add a new line to the slider so that you have a line for when the slider is moved to the left and to the right. Locate just below your previously set parameters the `Left Line` you created in `Step 6.2`.
Before you add the new line, replace the `1` in `line_to` with your new parameter `value_normalized`.
Then add the `Right Line` below the `Left Line`, as so:
```python
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * value_normalized - self._radius # REPLACED THE 1 WITH value_normalized
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# NEW: same as left line but flipped
# Right line
line_from = -self.width * 0.5 + self.width * value_normalized + self._radius
line_to = self.width * 0.5
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# END NEW
```
Next, update the circle to add the `hover_gesture`. This will increase the circle in size when hovered over. Also change the `1` value like you did for `Line` to `value_normalized` and also add the gesture to `sc.Arc`:
```python
# Circle
# NEW : Changed 1 value to value_normalized
circle_position = -self.width * 0.5 + self.width * value_normalized
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
# NEW: Added Gesture when hovering over the circle it will increase in size
gestures = [self._arc_gesture]
if self._hover_gesture:
gestures.append(self._hover_gesture)
if self._hover_gesture.state == sc.GestureState.CHANGED:
radius = self._radius_hovered
sc.Arc(radius, axis=2, color=cl.gray, gestures=gestures)
# END NEW
```
Last of all, update the `Label` below your circle to add more space between the slider and the label:
```python
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# NEW: Added more space between the slider and the label
# Move it to the top
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)):
# END NEW
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the full <b>slider_manipulator.py</b></summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def set_radius(circle, radius):
circle.radius = radius
# You don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
_min = self.model.get_as_floats(self.model.get_item("min"))[0]
_max = self.model.get_as_floats(self.model.get_item("max"))[0]
value = float(self.model.get_as_floats(self.model.get_item("value"))[0])
value_normalized = (value - _min) / (_max - _min)
value_normalized = max(min(value_normalized, 1.0), 0.0)
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * value_normalized - self._radius # REPLACED THE 1 WITH value_normalized
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# NEW: same as left line but flipped
# Right line
line_from = -self.width * 0.5 + self.width * value_normalized + self._radius
line_to = self.width * 0.5
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * value_normalized
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
gestures = [self._arc_gesture]
if self._hover_gesture:
gestures.append(self._hover_gesture)
if self._hover_gesture.state == sc.GestureState.CHANGED:
radius = self._radius_hovered
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# NEW: Added more space between the slider and the label
# Move it to the top
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)):
# END NEW
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
<br>
<br>
>:exclamation: If you are running into any errors in the Console, disable `Autoload` in the `Extension Manager` and restart Omniverse Code.
### Step 8.9: Completion
Congratulations! You have completed the guide `How to make a Slider Manipulator` and now have a working scale slider!
| 93,815 | Markdown | 33.605681 | 389 | 0.614923 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_manipulator.py | from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def set_radius(circle, radius):
circle.radius = radius
# We don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
_min = self.model.get_as_floats(self.model.get_item("min"))[0]
_max = self.model.get_as_floats(self.model.get_item("max"))[0]
value = float(self.model.get_as_floats(self.model.get_item("value"))[0])
value_normalized = (value - _min) / (_max - _min)
value_normalized = max(min(value_normalized, 1.0), 0.0)
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * value_normalized - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# NEW: same as left line but flipped
# Right line
line_from = -self.width * 0.5 + self.width * value_normalized + self._radius
line_to = self.width * 0.5
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * value_normalized
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
# NEW: Added Gesture when hovering over the circle it will increase in size
gestures = [self._arc_gesture]
if self._hover_gesture:
gestures.append(self._hover_gesture)
if self._hover_gesture.state == sc.GestureState.CHANGED:
radius = self._radius_hovered
sc.Arc(radius, axis=2, color=cl.gray, gestures=gestures)
# END NEW
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# NEW: Added more space between the slider and the label
# Move it to the top
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)):
# END NEW
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate() | 7,610 | Python | 37.439394 | 108 | 0.574244 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_registry.py | from .slider_model import SliderModel
from .slider_manipulator import SliderManipulator
from typing import Any
from typing import Dict
from typing import Optional
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, we don't want to see the selection rect
self.__disable_selection = ViewportLegacyDisableSelection()
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
class SliderRegistry:
"""
Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per
viewport. Keeps the manipulator and some properties that are needed to the
viewport.
"""
def __init__(self, description: Optional[Dict[str, Any]] = None):
self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture())
def destroy(self):
if self.__slider_manipulator:
self.__slider_manipulator.destroy()
self.__slider_manipulator = None
# PrimTransformManipulator & TransformManipulator don't have their own visibility
@property
def visible(self):
return True
@visible.setter
def visible(self, value):
pass
@property
def categories(self):
return ("manipulator",)
@property
def name(self):
return "Example Slider Manipulator" | 3,144 | Python | 34.738636 | 114 | 0.640585 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/extension.py | import omni.ext
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.viewport.registry import RegisterScene
from .slider_registry import SliderRegistry
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider")
self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry)
def on_shutdown(self):
ManipulatorFactory.destroy_manipulator(self.slider_factory)
self.slider_factory = None
self.slider_registry.destroy()
self.slider_registry = None
| 785 | Python | 40.368419 | 119 | 0.75414 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_model.py | from omni.ui import scene as sc
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
import omni.kit.commands
from pxr import Gf
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because we take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self) -> None:
super().__init__()
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, we don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
if identifier == "value":
return self.scale
if identifier == "min":
return self.min
if identifier == "max":
return self.max
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def set_floats(self, item, value):
if not self.current_path:
return
if not value or not item or item.value == value:
return
if item == self.scale:
# Set the scale when setting the value.
value[0] = min(max(value[0], self.min.value[0]), self.max.value[0])
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(
self.stage.GetPrimAtPath(self.current_path)
)
omni.kit.commands.execute(
"TransformPrimSRTCommand",
path=self.current_path,
new_translation=old_translation,
new_rotation_euler=old_rotation_euler,
new_scale=Gf.Vec3d(value[0], value[0], value[0]),
)
# Set directly to the item
item.value = value
# This makes the manipulator updated
self._item_changed(item)
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
| 5,473 | Python | 34.089743 | 121 | 0.576466 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/config/extension.toml | [package]
version = "1.2.1"
authors = ["Victor Yudin <[email protected]>"]
title = "Omni.UI Scene Slider Example"
description="The interactive example of the slider manipulator with omni.ui.scene"
readme = "docs/README.md"
repository="https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene"
category = "Documentation"
keywords = ["ui", "example", "scene", "docs", "documentation", "slider"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.kit.manipulator.viewport" = {}
"omni.kit.viewport.registry" = {}
"omni.ui.scene" = {}
"omni.usd" = {}
[[python.module]]
name = "omni.example.ui_scene.slider_manipulator"
| 686 | TOML | 30.227271 | 82 | 0.718659 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/slider_manipulator.py | ## Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ["SliderManipulator"]
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Geometry properties
self._width = 100
self._thickness = 5
self._radius = 5
self._radius_hovered = 7
def set_radius(circle, radius):
circle.radius = radius
# We don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
# Compatibility with old versions of ui.scene
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
def on_build(self):
"""Called when the model is chenged and rebuilds the whole slider"""
if not self.model:
return
_min = self.model.get_as_floats(self.model.get_item("min"))[0]
_max = self.model.get_as_floats(self.model.get_item("max"))[0]
value = float(self.model.get_as_floats(self.model.get_item("value"))[0])
value_normalized = (value - _min) / (_max - _min)
value_normalized = max(min(value_normalized, 1.0), 0.0)
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * value_normalized - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Right line
line_from = -self.width * 0.5 + self.width * value_normalized + self._radius
line_to = self.width * 0.5
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * value_normalized
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
gestures = [self._arc_gesture]
if self._hover_gesture:
gestures.append(self._hover_gesture)
if self._hover_gesture.state == sc.GestureState.CHANGED:
radius = self._radius_hovered
sc.Arc(radius, axis=2, color=cl.gray, gestures=gestures)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# Move it to the top
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the mesh
self.invalidate()
| 7,805 | Python | 37.835821 | 112 | 0.586931 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/slider_registry.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["SliderRegistry"]
from .slider_manipulator import SliderManipulator
from .slider_model import SliderModel
from typing import Any
from typing import Dict
from typing import Optional
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact is the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, we don't want to see the selection
# rect. In Viewport Next, it works well automatically because the
# selection rect is a manipulator with its gesture, and we add the
# slider manipulator to the same SceneView.
# In Viewport Legacy, the selection rect is not a manipulator. Thus it's
# not disabled automatically, and we need to disable it with the code.
self.__disable_selection = ViewportLegacyDisableSelection()
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
class SliderRegistry:
"""
Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per
viewport. Keeps the manipulator and some properties that are needed to the
viewport.
"""
def __init__(self, description: Optional[Dict[str, Any]] = None):
self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture())
def destroy(self):
if self.__slider_manipulator:
self.__slider_manipulator.destroy()
self.__slider_manipulator = None
# PrimTransformManipulator & TransformManipulator don't have their own visibility
@property
def visible(self):
return True
@visible.setter
def visible(self, value):
pass
@property
def categories(self):
return ("manipulator",)
@property
def name(self):
return "Example Slider Manipulator"
| 3,948 | Python | 36.609523 | 117 | 0.664894 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["SliderExtension"]
from .slider_extension import SliderExtension
| 510 | Python | 41.58333 | 76 | 0.8 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/slider_extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["SliderExtension"]
from .slider_registry import SliderRegistry
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.viewport.registry import RegisterScene
import omni.ext
class SliderExtension(omni.ext.IExt):
"""The entry point to the extension"""
def on_startup(self, ext_id):
# Viewport Next: omni.kit.viewport.window
self._slider_registry = RegisterScene(SliderRegistry, "omni.example.ui_scene.slider_manipulator")
# Viewport Legacy: omni.kit.window.viewport
self._slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry)
def on_shutdown(self):
ManipulatorFactory.destroy_manipulator(self._slider_factory)
self._slider_factory = None
self._slider_registry.destroy()
self._slider_registry = None
| 1,255 | Python | 38.249999 | 105 | 0.753785 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/slider_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["SliderModel"]
from omni.ui import scene as sc
from pxr import Gf
from pxr import UsdGeom
from pxr import Usd
import omni.usd
import omni.kit.commands
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because we take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self):
super().__init__()
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
self.position = SliderModel.PositionItem()
# The distance from the bounding box to the position the model returns
self._offset = 10
# Current selection
self._current_path = ""
usd_context = omni.usd.get_context()
self._stage: Usd.Stage = None
# Track selection
self._selection = usd_context.get_selection()
self._events = usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="Slider Selection Update"
)
def get_item(self, identifier):
if identifier == "value":
return self.scale
if identifier == "position":
return self.position
if identifier == "min":
return self.min
if identifier == "max":
return self.max
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self._get_position()
if item:
# Get the value directly from the item
return item.value
return []
def set_floats(self, item, value):
if not self._current_path:
return
if not value or not item or item.value == value:
return
if item == self.scale:
# Set the scale when setting the value.
value[0] = min(max(value[0], self.min.value[0]), self.max.value[0])
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(
self._stage.GetPrimAtPath(self._current_path)
)
omni.kit.commands.execute(
"TransformPrimSRTCommand",
path=self._current_path,
new_translation=old_translation,
new_rotation_euler=old_rotation_euler,
new_scale=Gf.Vec3d(value[0], value[0], value[0]),
)
# Set directly to the item
item.value = value
# This makes the manipulator updated
self._item_changed(item)
def _get_stage(self):
if not self._stage:
usd_context = omni.usd.get_context()
self._stage: Usd.Stage = usd_context.get_stage()
return self._stage
def _on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_kit_selection_changed()
def _on_kit_selection_changed(self):
prim_paths = self._selection.get_selected_prim_paths()
if not prim_paths:
return
prim = self._get_stage().GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self._current_path = prim_paths[0]
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# Position is changed
self._item_changed(self.position)
def _get_position(self):
"""Returns position of currently selected object"""
if not self._current_path:
return [0, 1e38, 0]
# Get position directly from USD
prim = self._get_stage().GetPrimAtPath(self._current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + self._offset, (bboxMin[2] + bboxMax[2]) * 0.5]
return position
| 5,372 | Python | 32.792453 | 117 | 0.602755 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/docs/CHANGELOG.md | # Changelog
omni.example.ui_scene.slider_manipulator
## [1.2.1] - 2022-06-17
### Added
- Documentation
## [1.2.0] - 2022-06-01
### Changed
- Full refactoring
## [1.1.1] - 2021-12-22
### Changed
- Fixes for tests on 103.0+release.679.1bc9fadb
## [1.1.0] - 2021-12-06
### Changed
- Using the model-based SceneView
### Added
- Support for HoverGesture
## [1.0.1] - 2021-11-25
### Changed
- Default aspect ratio to match Kit Viewport
- Renamed Intersection to GesturePayload (need omni.ui.scene 1.1.0)
## [1.0.0] - 2021-11-19
### Added
- The initial documentation
| 567 | Markdown | 17.32258 | 67 | 0.66843 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/docs/README.md | # Slider Manipulator (omni.example.ui_scene.slider_manipulator)

## Overview
We provide the End-to-End example that draws a 3D slider in the viewport overlay
on the top of the bounding box of the selected imageable. The slider controls
the scale of the prim. It has a custom manipulator, model, and gesture. When the
slider's value is changed, the manipulator processes the custom gesture that
changes the data in the model, which changes the data directly in the USD stage.
The viewport overlay is synchronized with the viewport using `Tf.Notice` that
watches the USD Camera.
### Manipulator
The manipulator is a very basic implementation of the slider in 3D space. The
main feature of the manipulator is that it redraws and recreates all the
children once the model is changed. It makes the code straightforward. It takes
the position and the slider value from the model, and when the user changes the
slider position, it processes a custom gesture. It doesn't write to the model
directly to let the user decide what to do with the new data and how the
manipulator should react to the modification. For example, if the user wants to
implement the snapping to the round value, it would be handy to do it in the
custom gesture.
### Model
The model contains the following named items:
- `value` - the current value of the slider
- `min` - the minimum value of the slider
- `max` - the maximum value of the slider
- `position` - the position of the slider in 3D space
The model demonstrates two main strategies working with the data.
The first strategy is that the model is the bridge between the manipulator and
the data, and it doesn't keep and doesn't duplicate the data. When the
manipulator requests the position from the model, the model computes the
position using USD API and returns it to the manipulator.
The first strategy is that the model can be a container of the data. For
example, the model pre-computes min and max values and passes them to the
manipulator once the selection is changed.
## [Tutorial](../Tutorial/slider_Manipulator_Tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions.
In the tutorial you will learn how to create an extension from the Extension Manager in Omniverse Code, set up your files, and use Omniverse's Library. Additionally, the tutorial has a `Final Scripts` folder to use as a reference as you go along.
[Get started with the tutorial here.](../Tutorial/slider_Manipulator_Tutorial.md)
## Usage
Once the extension is enabled in the `Extension Manager`, go to your `Viewport` and right-click to create a primitive - such as a cube, sphere, cylinder, etc. Then, left-click/select the primitive to view and manipulate the slider.
| 2,943 | Markdown | 48.898304 | 247 | 0.783554 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/docs/index.rst | omni.example.ui_scene.slider_manipulator
########################################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 171 | reStructuredText | 13.333332 | 40 | 0.549708 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/config/extension.toml | [package]
version = "1.1.1"
authors = ["NVIDIA"]
title = "Omni.UI Scene Sample For Manipulating Select Light"
description = "This example show an 3D manipulator for a selected light"
readme = "docs/README.md"
repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene"
category = "Documentation"
keywords = ["ui", "example", "scene", "docs", "documentation", "light"]
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui.scene" = { }
"omni.usd" = { }
"omni.kit.viewport.utility" = { }
"omni.kit.commands" = { }
[[python.module]]
name = "omni.example.ui_scene.light_manipulator"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/app/viewport/forceHideFps=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.test_helpers_gfx",
"omni.kit.viewport.utility",
"omni.kit.window.viewport"
]
| 1,030 | TOML | 26.131578 | 82 | 0.667961 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["LightManipulatorExtension"]
import carb
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportScene
class LightManipulatorExtension(omni.ext.IExt):
def __init__(self):
self._viewport_scene = None
def on_startup(self, ext_id):
# Get the active (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# Issue an error if there is no Viewport
if not viewport_window:
carb.log_error(f"No Viewport Window to add {ext_id} scene to")
return
# Build out the scene
self._viewport_scene = ViewportScene(viewport_window, ext_id)
def on_shutdown(self):
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
| 1,294 | Python | 33.078946 | 76 | 0.705564 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/viewport_scene.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportScene"]
from omni.ui import scene as sc
from .light_model import LightModel
from .light_manipulator import LightManipulator
class ViewportScene:
"""The light Manipulator, placed into a Viewport"""
def __init__(self, viewport_window, ext_id: str):
self._scene_view = None
self._viewport_window = viewport_window
# Create a unique frame for our SceneView
with self._viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self._scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self._scene_view.scene:
LightManipulator(model=LightModel())
# Register the SceneView with the Viewport to get projection and view updates
self._viewport_window.viewport_api.add_scene_view(self._scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self._scene_view:
# Empty the SceneView of any elements it may have
self._scene_view.scene.clear()
# Be a good citizen, and un-register the SceneView from Viewport updates
if self._viewport_window:
self._viewport_window.viewport_api.remove_scene_view(self._scene_view)
# Remove our references to these objects
self._viewport_window = None
self._scene_view = None
| 1,871 | Python | 37.999999 | 89 | 0.676109 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/__init__.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import *
from .light_manipulator import LightManipulator
from .light_model import LightModel
| 537 | Python | 43.83333 | 76 | 0.81378 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["LightModel"]
import carb
from omni.ui import scene as sc
import omni.usd
from pxr import Usd, UsdGeom, UsdLux, Tf, Gf
def _flatten_matrix(matrix: Gf.Matrix4d):
m0, m1, m2, m3 = matrix[0], matrix[1], matrix[2], matrix[3]
return [
m0[0],
m0[1],
m0[2],
m0[3],
m1[0],
m1[1],
m1[2],
m1[3],
m2[0],
m2[1],
m2[2],
m2[3],
m3[0],
m3[1],
m3[2],
m3[3],
]
class LightModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the attributes of the selected light.
"""
class MatrixItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the tranformation. It doesn't contain anything
because we take the tranformation directly from USD when requesting.
"""
identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
def __init__(self):
super().__init__()
self.value = self.identity.copy()
class FloatItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value about some attibute"""
def __init__(self, value=0.0):
super().__init__()
self.value = value
class StringItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single string value about some attibute"""
def __init__(self, value=""):
super().__init__()
self.value = value
def __init__(self):
super().__init__()
self.prim_path = LightModel.StringItem()
self.transform = LightModel.MatrixItem()
self.intensity = LightModel.FloatItem()
self.width = LightModel.FloatItem()
self.height = LightModel.FloatItem()
# Save the UsdContext name (we currently only work with single Context)
self._usd_context_name = ""
# Current selection
self._light = None
self._stage_listener = None
# Track selection change
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="Light Manipulator Selection Change"
)
def __del__(self):
self._invalidate_object()
@property
def _usd_context(self) -> Usd.Stage:
# Get the UsdContext we are attached to
return omni.usd.get_context(self._usd_context_name)
@property
def _current_path(self):
return self.prim_path.value
@property
def _time(self):
return Usd.TimeCode.Default()
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice. When USD data changes, we update the ui"""
light_path = self.prim_path.value
if not light_path:
return
changed_items = set()
for p in notice.GetChangedInfoOnlyPaths():
prim_path = p.GetPrimPath().pathString
if prim_path != light_path:
# Update on any parent transformation changes too
if light_path.startswith(prim_path):
if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name):
changed_items.add(self.transform)
continue
if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name):
changed_items.add(self.transform)
elif self.width and p.name == "width":
changed_items.add(self.width)
elif self.height and p.name == "height":
changed_items.add(self.height)
elif self.intensity and p.name == "intensity":
changed_items.add(self.intensity)
for item in changed_items:
self._item_changed(item)
def get_as_floats(self, item):
"""get the item value directly from USD"""
if item == self.transform:
return self._get_transform(self._time)
if item == self.intensity:
return self._get_intensity(self._time)
if item == self.width:
return self._get_width(self._time)
if item == self.height:
return self._get_height(self._time)
if item:
# Get the value directly from the item
return item.value
return None
def set_floats_commands(self, item, value):
"""set the item value to USD using commands, this is useful because it supports undo/redo"""
if not self._current_path:
return
if not value or not item:
return
# we get the previous value from the model instead of USD
if item == self.height:
prev_value = self.height.value
if prev_value == value:
return
height_attr = self._light.GetHeightAttr()
omni.kit.commands.execute('ChangeProperty', prop_path=height_attr.GetPath(), value=value, prev=prev_value)
elif item == self.width:
prev_value = self.width.value
if prev_value == value:
return
width_attr = self._light.GetWidthAttr()
omni.kit.commands.execute('ChangeProperty', prop_path=width_attr.GetPath(), value=value, prev=prev_value)
elif item == self.intensity:
prev_value = self.intensity.value
if prev_value == value:
return
intensity_attr = self._light.GetIntensityAttr()
omni.kit.commands.execute('ChangeProperty', prop_path=intensity_attr.GetPath(), value=value, prev=prev_value)
# This makes the manipulator updated
self._item_changed(item)
def set_item_value(self, item, value):
""" This is used to set the model value instead of the usd. This is used to record previous value for
omni.kit.commands """
item.value = value
def set_floats(self, item, value):
"""set the item value directly to USD. This is useful when we want to update the usd but not record it in commands"""
if not self._current_path:
return
if not value or not item:
return
pre_value = self.get_as_floats(item)
# no need to update if the updated value is the same
if pre_value == value:
return
if item == self.height:
self._set_height(self._time, value)
elif item == self.width:
self._set_width(self._time, value)
elif item == self.intensity:
self._set_intensity(self._time, value)
def _on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_kit_selection_changed()
def _invalidate_object(self, settings):
# Revoke the Tf.Notice listener, we don't need to update anything
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
# Reset original Viewport gizmo line width
settings.set("/persistent/app/viewport/gizmo/lineWidth", 0)
# Clear any cached UsdLux.Light object
self._light = None
# Set the prim_path to empty
self.prim_path.value = ""
self._item_changed(self.prim_path)
def _on_kit_selection_changed(self):
# selection change, reset it for now
self._light = None
# Turn off any native selected light drawing
settings = carb.settings.get_settings()
settings.set("/persistent/app/viewport/gizmo/lineWidth", 0)
usd_context = self._usd_context
if not usd_context:
return self._invalidate_object(settings)
stage = usd_context.get_stage()
if not stage:
return self._invalidate_object(settings)
prim_paths = usd_context.get_selection().get_selected_prim_paths() if usd_context else None
if not prim_paths:
return self._invalidate_object(settings)
prim = stage.GetPrimAtPath(prim_paths[0])
if prim and prim.IsA(UsdLux.RectLight):
self._light = UsdLux.RectLight(prim)
if not self._light:
return self._invalidate_object(settings)
selected_path = self._light.GetPrim().GetPath().pathString
if selected_path != self.prim_path.value:
self.prim_path.value = selected_path
self._item_changed(self.prim_path)
# Add a Tf.Notice listener to update the light attributes
if not self._stage_listener:
self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage)
def _get_transform(self, time: Usd.TimeCode):
"""Returns world transform of currently selected object"""
if not self._light:
return LightModel.MatrixItem.identity.copy()
# Compute matrix from world-transform in USD
world_xform = self._light.ComputeLocalToWorldTransform(time)
# Flatten Gf.Matrix4d to list
return _flatten_matrix(world_xform)
def _get_intensity(self, time: Usd.TimeCode):
"""Returns intensity of currently selected light"""
if not self._light:
return 0.0
# Get intensity directly from USD
return self._light.GetIntensityAttr().Get(time)
def _set_intensity(self, time: Usd.TimeCode, value):
"""set intensity of currently selected light"""
if not self._light:
return
# set height dirctly to USD
self._light.GetIntensityAttr().Set(value, time=time)
def _get_width(self, time: Usd.TimeCode):
"""Returns width of currently selected light"""
if not self._light:
return 0.0
# Get radius directly from USD
return self._light.GetWidthAttr().Get(time)
def _set_width(self, time: Usd.TimeCode, value):
"""set width of currently selected light"""
if not self._light:
return
# set height dirctly to USD
self._light.GetWidthAttr().Set(value, time=time)
def _get_height(self, time: Usd.TimeCode):
"""Returns height of currently selected light"""
if not self._light:
return 0.0
# Get height directly from USD
return self._light.GetHeightAttr().Get(time)
def _set_height(self, time: Usd.TimeCode, value):
"""set height of currently selected light"""
if not self._light:
return
# set height dirctly to USD
self._light.GetHeightAttr().Set(value, time=time)
| 11,040 | Python | 33.07716 | 125 | 0.600272 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_manipulator.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
__all__ = ["LightManipulator"]
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.kit
import omni.kit.commands
INTENSITY_SCALE = 500.0
ARROW_WIDTH = 0.015
ARROW_HEIGHT = 0.1
ARROW_P = [
[ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, -ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, ARROW_WIDTH, 0],
[ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[ARROW_WIDTH, -ARROW_WIDTH, 0],
]
ARROW_VC = [3, 3, 3, 3, 4]
ARROW_VI = [i for i in range(sum(ARROW_VC))]
class _ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact is the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class _DragGesture(sc.DragGesture):
""""Gesture to disable rectangle selection in the viewport legacy"""
def __init__(self, manipulator, orientation, flag):
super().__init__()
self._manipulator = manipulator
# record this _previous_ray_point to get the mouse moved vector
self._previous_ray_point = None
# this defines the orientation of the move, 0 means x, 1 means y, 2 means z. It's a list so that we can move a selection
self.orientations = orientation
# global flag to indicate if the manipulator changes all the width, height and intensity, rectangle manipulator
# in the example
self.is_global = len(self.orientations) > 1
# this defines the negative or positive of the move. E.g. when we move the positive x line to the right, it
# enlarges the width, and when we move the negative line to the left, it also enlarges the width
# 1 means positive and -1 means negative. It's a list so that we can reflect list orientation
self.flag = flag
def on_began(self):
# When the user drags the slider, we don't want to see the selection
# rect. In Viewport Next, it works well automatically because the
# selection rect is a manipulator with its gesture, and we add the
# slider manipulator to the same SceneView.
# In Viewport Legacy, the selection rect is not a manipulator. Thus it's
# not disabled automatically, and we need to disable it with the code.
self.__disable_selection = _ViewportLegacyDisableSelection()
# initialize the self._previous_ray_point
self._previous_ray_point = self.gesture_payload.ray_closest_point
# record the previous value for the model
self.model = self._manipulator.model
if 0 in self.orientations:
self.width_item = self.model.width
self._manipulator.model.set_item_value(self.width_item, self.model.get_as_floats(self.width_item))
if 1 in self.orientations:
self.height_item = self.model.height
self._manipulator.model.set_item_value(self.height_item, self.model.get_as_floats(self.height_item))
if 2 in self.orientations or self.is_global:
self.intensity_item = self.model.intensity
self._manipulator.model.set_item_value(self.intensity_item, self.model.get_as_floats(self.intensity_item))
def on_changed(self):
object_ray_point = self.gesture_payload.ray_closest_point
# calculate the ray moved vector
moved = [a - b for a, b in zip(object_ray_point, self._previous_ray_point)]
# transfer moved from world to object space, [0] to make it a normal, not point
moved = self._manipulator._x_xform.transform_space(sc.Space.WORLD, sc.Space.OBJECT, moved + [0])
# 2.0 because `_shape_xform.transform` is a scale matrix and it means
# the width of the rectangle is twice the scale matrix.
moved_x = moved[0] * 2.0 * self.flag[0]
moved_y = moved[1] * 2.0 * (self.flag[1] if self.is_global else self.flag[0])
moved_z = moved[2] * self.flag[0]
# update the self._previous_ray_point
self._previous_ray_point = object_ray_point
# since self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
# when we want to update the manipulator, we are actually updating self._manipulator._shape_xform.transform[0]
# for width and self._manipulator._shape_xform.transform[5] for height and
# self._manipulator._shape_xform.transform[10] for intensity
width = self._manipulator._shape_xform.transform[0]
height = self._manipulator._shape_xform.transform[5]
intensity = self._manipulator._shape_xform.transform[10]
self.width_new = width + moved_x
self.height_new = height + moved_y
# update the USD as well as update the ui
if 0 in self.orientations:
# update the data in the model
self.model.set_floats(self.width_item, self.width_new)
self._manipulator._shape_xform.transform[0] = self.width_new
if 1 in self.orientations:
# update the data in the model
self.model.set_floats(self.height_item, self.height_new)
self._manipulator._shape_xform.transform[5] = self.height_new
if 2 in self.orientations:
self._manipulator._shape_xform.transform[10] += moved_z
self.intensity_new = self._manipulator._shape_xform.transform[10] * INTENSITY_SCALE
self.model.set_floats(self.intensity_item, self.intensity_new)
if self.is_global:
# need to update the intensity in a different way
intensity_new = intensity * width * height / (self.width_new * self.height_new)
self._manipulator._shape_xform.transform[10] = intensity_new
self.intensity_new = intensity_new * INTENSITY_SCALE
self.model.set_floats(self.intensity_item, self.intensity_new)
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
if self.is_global:
# start group command
omni.kit.undo.begin_group()
if 0 in self.orientations:
self.model.set_floats_commands(self.width_item, self.width_new)
if 1 in self.orientations:
self.model.set_floats_commands(self.height_item, self.height_new)
if 2 in self.orientations or self.is_global:
self.model.set_floats_commands(self.intensity_item, self.intensity_new)
if self.is_global:
# end group command
omni.kit.undo.end_group()
class LightManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._shape_xform = None
def __del__(self):
self.model = None
def _build_shape(self):
if not self.model:
return
if self.model.width and self.model.height and self.model.intensity:
x = self.model.get_as_floats(self.model.width)
y = self.model.get_as_floats(self.model.height)
# this INTENSITY_SCALE is too make the transform a reasonable length with large intensity number
z = self.model.get_as_floats(self.model.intensity) / INTENSITY_SCALE
self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1]
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
model = self.model
if not model:
return
# if we don't have selection then just return
prim_path_item = model.prim_path
prim_path = prim_path_item.value if prim_path_item else None
if not prim_path:
return
# Style settings, as kwargs
thickness = 1
hover_thickness = 3
color = cl.yellow
shape_style = {"thickness": thickness, "color": color}
def set_thickness(sender, shapes, thickness):
for shape in shapes:
shape.thickness = thickness
self.__root_xf = sc.Transform(model.get_as_floats(model.transform))
with self.__root_xf:
self._x_xform = sc.Transform()
with self._x_xform:
self._shape_xform = sc.Transform()
# Build the shape's transform
self._build_shape()
with self._shape_xform:
# Build the shape geomtery as unit-sized
h = 0.5
z = -1.0
# the rectangle
shape1 = sc.Line((-h, h, 0), (h, h, 0), **shape_style)
shape2 = sc.Line((-h, -h, 0), (h, -h, 0), **shape_style)
shape3 = sc.Line((h, h, 0), (h, -h, 0), **shape_style)
shape4 = sc.Line((-h, h, 0), (-h, -h, 0), **shape_style)
# add gesture to the lines of the rectangle to update width or height of the light
vertical_hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_thickness(sender, [shape1, shape2], hover_thickness),
on_ended_fn=lambda sender: set_thickness(sender, [shape1, shape2], thickness),
)
shape1.gestures = [_DragGesture(self, [1], [1]), vertical_hover_gesture]
shape2.gestures = [_DragGesture(self, [1], [-1]), vertical_hover_gesture]
horizontal_hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_thickness(sender, [shape3, shape4], hover_thickness),
on_ended_fn=lambda sender: set_thickness(sender, [shape3, shape4], thickness),
)
shape3.gestures = [_DragGesture(self, [0], [1]), horizontal_hover_gesture]
shape4.gestures = [_DragGesture(self, [0], [-1]), horizontal_hover_gesture]
# create z-axis to indicate the intensity
z1 = sc.Line((h, h, 0), (h, h, z), **shape_style)
z2 = sc.Line((-h, -h, 0), (-h, -h, z), **shape_style)
z3 = sc.Line((h, -h, 0), (h, -h, z), **shape_style)
z4 = sc.Line((-h, h, 0), (-h, h, z), **shape_style)
def make_arrow(translate):
vert_count = len(ARROW_VI)
with sc.Transform(
transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])
* sc.Matrix44.get_rotation_matrix(0, -180, 0, True)
):
return sc.PolygonMesh(ARROW_P, [color] * vert_count, ARROW_VC, ARROW_VI, visible=False)
# arrows on the z-axis
arrow_1 = make_arrow((h, h, z))
arrow_2 = make_arrow((-h, -h, z))
arrow_3 = make_arrow((h, -h, z))
arrow_4 = make_arrow((-h, h, z))
# the line underneath the arrow which is where the gesture applies
z1_arrow = sc.Line((h, h, z), (h, h, z - ARROW_HEIGHT), **shape_style)
z2_arrow = sc.Line((-h, -h, z), (-h, -h, z - ARROW_HEIGHT), **shape_style)
z3_arrow = sc.Line((h, -h, z), (h, -h, z - ARROW_HEIGHT), **shape_style)
z4_arrow = sc.Line((-h, h, z), (-h, h, z - ARROW_HEIGHT), **shape_style)
def set_visible(sender, shapes, thickness, arrows, visible):
set_thickness(sender, shapes, thickness)
for arrow in arrows:
arrow.visible = visible
thickness_group = [z1, z1_arrow, z2, z2_arrow, z3, z3_arrow, z4, z4_arrow]
visible_group = [arrow_1, arrow_2, arrow_3, arrow_4]
visible_arrow_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_visible(sender, thickness_group, hover_thickness, visible_group, True),
on_ended_fn=lambda sender: set_visible(sender, thickness_group, thickness, visible_group, False),
)
gestures = [_DragGesture(self, [2], [-1]), visible_arrow_gesture]
z1_arrow.gestures = gestures
z2_arrow.gestures = gestures
z3_arrow.gestures = gestures
z4_arrow.gestures = gestures
# create 4 rectangles at the corner, and add gesture to update width, height and intensity at the same time
s = 0.03
def make_corner_rect(translate):
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])):
return sc.Rectangle(s, s, color=0x0)
r1 = make_corner_rect((h - 0.5 * s, -h + 0.5 * s, 0))
r2 = make_corner_rect((h - 0.5 * s, h - 0.5 * s, 0))
r3 = make_corner_rect((-h + 0.5 * s, h - 0.5 * s, 0))
r4 = make_corner_rect((-h + 0.5 * s, -h + 0.5 * s, 0))
def set_color_and_visible(sender, shapes, thickness, arrows, visible, rects, color):
set_visible(sender, shapes, thickness, arrows, visible)
for rect in rects:
rect.color = color
highlight_group = [shape1, shape2, shape3, shape4] + thickness_group
color_group = [r1, r2, r3, r4]
hight_all_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_color_and_visible(sender, highlight_group, hover_thickness, visible_group, True, color_group, color),
on_ended_fn=lambda sender: set_color_and_visible(sender, highlight_group, thickness, visible_group, False, color_group, 0x0),
)
r1.gestures = [_DragGesture(self, [0, 1], [1, -1]), hight_all_gesture]
r2.gestures = [_DragGesture(self, [0, 1], [1, 1]), hight_all_gesture]
r3.gestures = [_DragGesture(self, [0, 1], [-1, 1]), hight_all_gesture]
r4.gestures = [_DragGesture(self, [0, 1], [-1, -1]), hight_all_gesture]
def on_model_updated(self, item):
# Regenerate the mesh
if not self.model:
return
if item == self.model.transform:
# If transform changed, update the root transform
self.__root_xf.transform = self.model.get_as_floats(item)
elif item == self.model.prim_path:
# If prim_path or width or height or intensity changed, redraw everything
self.invalidate()
elif item == self.model.width or item == self.model.height or item == self.model.intensity:
# Interpret None as changing multiple light shape settings
self._build_shape()
| 16,572 | Python | 48.471642 | 156 | 0.57573 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/tests/test_manipulator.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
import omni.kit
import omni.kit.app
import omni.kit.test
from omni.example.ui_scene.light_manipulator import LightManipulator, LightModel
import omni.usd
from omni.ui import scene as sc
from pxr import UsdLux, UsdGeom
from omni.kit.viewport.utility import next_viewport_frame_async
from omni.kit.viewport.utility.tests import setup_vieport_test_window
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.example.ui_scene.light_manipulator}/data"))
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
class TestLightManipulator(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def setup_viewport(self, resolution_x: int = 800, resolution_y: int = 600):
await self.create_test_area(resolution_x, resolution_y)
return await setup_vieport_test_window(resolution_x, resolution_y)
async def test_manipulator_transform(self):
viewport_window = await self.setup_viewport()
viewport = viewport_window.viewport_api
await omni.usd.get_context().new_stage_async()
stage = omni.usd.get_context().get_stage()
# Wait until the Viewport has delivered some frames
await next_viewport_frame_async(viewport, 2)
with viewport_window.get_frame(0):
# Create a default SceneView (it has a default camera-model)
scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with scene_view.scene:
LightManipulator(model=LightModel())
omni.kit.commands.execute(
"CreatePrim",
prim_path="/RectLight",
prim_type="RectLight",
select_new_prim=True,
attributes={},
)
rect_light = UsdLux.RectLight(stage.GetPrimAtPath("/RectLight"))
# change light attribute
rect_light.GetHeightAttr().Set(100)
rect_light.GetWidthAttr().Set(200)
rect_light.GetIntensityAttr().Set(10000)
# rotate the light to have a better angle
rect_light_x = UsdGeom.Xformable(rect_light)
rect_light_x.ClearXformOpOrder()
rect_light_x.AddRotateXOp().Set(30)
rect_light_x.AddRotateYOp().Set(45)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 3,133 | Python | 37.219512 | 114 | 0.684966 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/tests/__init__.py | from .test_manipulator import TestLightManipulator | 50 | Python | 49.99995 | 50 | 0.9 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/docs/CHANGELOG.md | # Changelog
omni.example.ui_scene.light_manipulator
## [1.1.1] - 2022-6-21
### Added
- Documentation
## [1.1.0] - 2022-6-06
### Changed
- Removed other lights except RectLight
- Added gesture to the RectLight so that users can drag the manipulator to change the width, height and intensity
- The drag gesture can be just on the width (x-axis line) or height (y-axis line) or intensity (z-axis line) or all of
them when drag the corner rectangles
- Added test for the extension
## [1.0.0] - 2022-5-26
### Added
- The initial version
| 536 | Markdown | 25.849999 | 118 | 0.720149 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/docs/README.md | # Light Manipulator (omni.example.ui_scene.light_manipulator)
## Overview
We provide an End-to-End example of a light manipulator extension, which adds manipulators to RectLight.
There are 6 types of lights in Omniverse, shown in the image below. Here is the link of how to add a light: https://www.youtube.com/watch?v=c7qyI8pZvF4. In this example, we only create manipulators to RectLight.

It contains the LightModel which stores the light attribute values. Focused on "width", "height" and "intensity" in this example. It also plays the role of communication with the USD data, reading and writing updated attributes from and to USD.
LightManipulator defines 4 types of manipulators which separately control the light's width, height, intensity and all of the three.
## [Tutorial](../tutorial/tutorial.md)
Follow this [step-by-step guide](../tutorial/tutorial.md) to learn how this extension was created.
## Manipulator
The manipulator contains a rectangle and 4 lines perpendicular to the rectangle face. The manipulator is generated in a unit size, and the update of the look is through the parent transform of the manipulator.
- When you hover over the rectangle's width or height of the manipulator, you will see the line representation of the width or height highlighted and you can drag and move the manipulator. When you drag and move the height or width of the rectangle of the manipulator, you will see the width or height attributes of the RectLight in the property window are updated.
 
- When you hover over on the tip of any line perpendicular to the rectangle face, you will see the 4 lines will be highlighted and the arrow on the tip will reveal. When you drag and move the arrow, you will see the intensity attribute of the RectLight is updated.

- When you hover over to the corner of the rectangle (slightly inside the rectangle), you will see the entire manipulator is highlighted, and there will be 4 small rectangles revealed at the corner of the rectangle. When you drag and move the small rectangle, you will see all of the width, height and intensity attributes of the RectLight are updated.

- When you change the attributes (Width, height and intensity) of the RectLight in the property window, you will see the manipulator appearance updates.

## Gesture
The example defined a customized `_DragGesture` for the manipulator. This is how the gesture is implemented:
- `on_began`: the start attributes data is restored into the model, so that we have a record of previous values later for running `omni.kit.commands`.
- `on_changed`: update the attributes into the model, and the model will directly write the value to the USD without keeping it since we want to see the real-time updating of attribute value in the property window
- `on_ended`: update the attributes into the model, and the model will call `omni.kit.commands` to change the property since we want to support the undo/redo for the dragging. The previous value from `on_began` is used here.
## Model
The model contains the following named items:
- width - the width attribute of the RectLight
- height - the height attribute of the RectLight
- intensity - the intensity attribute of the RectLight
- prim_path - the USD prim path of the RectLight.
- transform - the transform of the RectLight.
The model is the bridge between the manipulator and the attributes data. The manipulator subscribes to the model change to update the look. All the attributes values are directly coming from USD data.
We use `Tf.Notice` to watch the rectLight and update the model. The model itself doesn't keep and doesn't duplicate the USD data, except the previous value when a gesture starts.
- When the model's `width`, `height` or `intensity` changes, the manipulator's parent transform is updated.
- The model's `prim_path` is subscribed to `omni.usd.StageEventType.SELECTION_CHANGED`, so when the selection of RectLight is changed, the entire manipulator is redrawn.
- When the model's `transform` is changed, the root transform of the manipulator is updated.
For width, height and intensity, the model demonstrates two strategies working with the data.
It keeps the attribute data during the manipulating, so that the manipulator has the only one truth of data from the model. When the manipulator requests the attributes from the model, the model computes the position using USD API and returns it to the manipulator.
## Overlaying with the viewport
We use `sc.Manipulator` to draw the manipulator in 3D view. To show it in the viewport, we overlay `sc.SceneView` with our `sc.Manipulator`
on top of the viewport window.
```python
from omni.kit.viewport.utility import get_active_viewport_window
viewport_window = get_active_viewport_window()
# Create a unique frame for our SceneView
with viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self._scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self._scene_view.scene:
LightManipulator(model=LightModel())
```
To synchronize the projection and view matrices, `omni.kit.viewport.utility` has
the method `add_scene_view`, which replaces the camera model, and the
manipulator visually looks like it's in the main viewport.
```python
# Register the SceneView with the Viewport to get projection and view updates
viewport_window.viewport_api.add_scene_view(self._scene_view)
``` | 5,614 | Markdown | 64.290697 | 366 | 0.773245 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/docs/index.rst | omni.example.ui_scene.light_manipulator
########################################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 170 | reStructuredText | 13.249999 | 40 | 0.547059 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md | # How to make an extension to display Object Info
The object info extension displays the selected prim’s Path and Type. This guide is great for first time extension builders.
> NOTE: Visual Studio Code is the preferred IDE, hence forth we will be referring to it throughout this guide.
# Learning Objectives
In this tutorial you learn how to:
- Create an extension in Omniverse Code
- Use the omni.ui.scene API
- Display object info in the viewport
- Translate from World space to Local space
# Prerequisites
We recommend that you complete these tutorials before moving forward:
- [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial)
- [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims)
> :exclamation: <span style="color:red"><b> WARNING: Check that Viewport Utility Extension is turned ON in the extension manager: </b></span> <br> 
# Step 1: Create an Extension
> **Note:** This is a review, if you know how to create an extension, feel free to skip this step.
For this guide, we will briefly go over how to create an extension. If you have not completed [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) we recommend you pause here and complete that before moving forward.
## Step 1.1: Create the extension template
In Omniverse Code navigate to the `Extensions` tab and create a new extension by clicking the ➕ icon in the upper left corner and select `New Extension Template Project`.
<br>

<br>
<icon> | <new template>
:-------------------------:|:-------------------------:
 | 
<br>
A new extension template window and Visual Studio Code will open after you have selected the folder location, folder name, and extension ID.
## Step 1.2: Naming your extension
Before beginning to code, navigate into `VS Code` and change how the extension is viewed in the **Extension Manager**. It's important to give your extension a title and description for the end user to understand the extension's purpose.
<br>
Inside of the `config` folder, locate the `extension.toml` file:

<br>
> **Note:** `extension.toml` is located inside of the `exts` folder you created for your extension. <br> 
<br>
Inside of this file, there is a title and description for how the extension will look in the **Extension Manager**. Change the title and description for the object info extension. Here is an example of how it looks in `VS code` and how it looks in the **Extension Manager**:

<br>

# Step 2: Get the active viewport
In this section, you import `omni.kit.viewport.utility` into `extension.py`. Then, you use it to store the active viewport. Finally, you will print the name of the active viewport to the console.
## Step 2.1: Navigate to `extension.py`
Navigate to `extension.py`:

This module contains boilerplate code for building a new extension:

## Step 2.2: Import the `omni.kit.viewport.utility`
Import the viewport utility:
```python
import omni.ext
import omni.ui as ui
# NEW: Import function to get the active viewport
from omni.kit.viewport.utility import get_active_viewport_window
```
Now that you've imported the viewport utility library, begin adding to the `MyExtension` class.
## Step 2.3: Get the activate viewport window
In `on_startup()` set the `viewport_window` variable to the active viewport:
```python
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[company.hello.world] MyExtension startup")
# NEW: Get the active Viewport
viewport_window = get_active_viewport_window()
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
def on_click():
print("clicked!")
ui.Button("Click Me", clicked_fn=lambda: on_click())
...
```
At startup the active window is the default Viewport.
## Step 2.4: Print the active viewport
In `on_click()`, print the active viewport:
```python
def on_click():
print(viewport_window)
```
Here, `on_click()` is acting as a convenience method that ensures you stored the active viewport
## Step 2.5: Review your changes
Navigate to Omniverse Code, click the **Click Me** button inside of *My Window*, and locate "Viewport" in the *Console*.

Here you see the result of the print statement you added in the last step.
> **Tip:** If you encounter an error in your console, please refer to the [Viewport Utility tip in Prerequisites](#prerequisites)
<br>
## Step 2.6: Create `object_info_model.py`
In this new module, you will create the necessary information for the object information to be called, such as the selected prim and tracking when the selection changes.
Create a file in the same file location as `extension.py` and name it `object_info_model.py`.
<br>
# Step 3: `object_info_model.py` Code
> **Note:** Work in the `object_info_model.py` module for this section.
<br>
The objective of this step is to get the basic information that the `Manipulator` and `Viewport` will need to display on the selected prim.
## Step 3.1: Import scene from `omni.ui`
As with `extension.py`, import `scene` from `omni.ui` to utilize scene related utilities. Also import `omni.usd`.
```python
from omni.ui import scene as sc
import omni.usd
```
## Step 3.2: Begin setting up variables
Next, create a new class and begin setting variables. Create the `ObjInfoModel` below the imports:
```python
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
```
## Step 3.3: Initialize `ObjInfoModel`
Use `__init__()` inside this class to initialize the object and events. In `__init__()`, set the variable for the current selected prim:
```python
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.position = [0, 0, 0]
```
## Step 3.4: Use UsdContext to listen for selection changes
Finally, get the `UsdContext` ([see here for more information on UsdContext](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.usd/docs/index.html#omni.usd.UsdContext)) to track when the selection changes and create a stage event callback function to be used later on:
```python
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.position = [0, 0, 0]
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
print("A stage event has occurred")
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
<br>
It's important to include `destroy()` in the model class. You want to unsubscribed from events when the model is destroyed.
<br>
## Step 4: Work on the object model
> **Note:** Work in `extension.py` for this section.
Now that you have created `object_info_model.py`, you need to do a few things in `extension.py` use the object model, such as import the model class, create an instance when the extension startsup, and then destroy the model when the extension is shutdown.
## Step 4.1: Import ObjInfoModel
Import ObjInfoModel into `extension.py` from `object_info_model.py`:
```python
import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
# NEW: import model class
from .object_info_model import ObjInfoModel
...
```
## Step 4.2: Create a variable for the object model
Create a variable for object model in `__init()__` of the `MyExtension` Class:
```python
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
# NEW: Reference to the objModel when created so we can destroy it later
def __init__(self) -> None:
super().__init__()
self.obj_model = None
...
```
## Step 4.3: Manage the object model
You should then create the object in `on_startup()` and destroy it later on in `on_shutdown()`:
```python
def on_startup(self, ext_id):
print("[omni.objInfo.tutorial] MyExtension startup")
# Get the active Viewport (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# NEW: create the object
self.obj_model = ObjInfoModel()
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
def on_click():
# Print to see that we did grab the active viewport
print(viewport_window)
ui.Button("Click Me", clicked_fn=lambda: on_click())
def on_shutdown(self):
"""Called when the extension is shutting down."""
print("[omni.objInfo.tutorial] MyExtension shutdown")
# NEW: Destroy the model when created
self.obj_model.destroy()
```
<details>
<summary>Click here for the updated <b>extension.py</b> module </summary>
```python
import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .object_info_model import ObjInfoModel
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self) -> None:
super().__init__()
self.obj_model = None
def on_startup(self, ext_id):
"""Called when the extension is starting up.
Args:
ext_id: Extension ID provided by Kit.
"""
print("[omni.objInfo.tutorial] MyExtension startup")
# Get the active Viewport (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# create the object
self.obj_model = ObjInfoModel()
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
def on_click():
# Print to see that we did grab the active viewport
print(viewport_window)
ui.Button("Click Me", clicked_fn=lambda: on_click())
def on_shutdown(self):
"""Called when the extension is shutting down."""
print("[omni.objInfo.tutorial] MyExtension shutdown")
# Destroy the model when created
self.obj_model.destroy()
```
</details>
<br>
# Step 5: Get the selected prim's data
At this point, there is nothing viewable in Omniverse Code as you the code is not doing anything yet when stage events occur. In this section, you will fill in the logic for the stage event callback to get the selected object's information. By the end of Step 5 you should be able to view the object info in the console.
> **Note:** Work in `object_info_model.py` for this section.
At this point, you have created the start of the `on_stage_event()` callback in `object_info_model.py` but there is nothing happening in the event.
Replace what's in `on_stage_event()` with the variable for the prim path and where that path information is located:
```python
def on_stage_event(self, event):
"""Called by stage_event_stream."""
# NEW
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
self.prim = prim
self.current_path = prim_path[0]
print("prim: " + str(prim))
...
```
You can check that this is working by navigating back to Omniverse Code and create a prim in the viewport. When the prim is created, it's path should display at the bottom.

# Step 6: Object Path Name in Scene
In this step you create another `__init__()` method in a new class to represent the position. This position will be taken directly from USD when requested.
## Step 6.1: Nest the `PositionItem` class
Nest the new `PositionItem` class inside of the `ObjInfoModel` class as so:
```python
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
# NEW: needed for when we call item changed
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
...
```
## Step 6.2: Set path and position
Set the current path and update the position from `[0,0,0]` to store a `PositionItem`:
```python
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
#NEW: set to current path.
self.current_path = ""
# NEW: update to hold position obj created
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
...
```
## Step 6.3: Check the stage
After updating the position, check the stage when the selection of an object is changed. Do this with an `if` statement in `on_stage_event()`, like so:
```python
def on_stage_event(self, event):
# NEW: if statement to only check when selection changed
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
self.prim = prim
self.current_path = prim_path[0]
# NEW: Update on item change
# Position is changed because new selected object has a different position
self._item_changed(self.position)
...
```
## Step 6.4: Set identifiers
Finally, create a new function underneath `on_stage_event()` to set the identifiers:
```python
# NEW: function to get identifiers from the model
def get_item(self, identifier):
if identifier == "name":
return self.current_path
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
<details>
<summary>Click here for the updated <b>object_info_model.py</b> module </summary>
```python
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.position = ObjInfoModel.PositionItem()
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
</details>
<br>
# Step 7: The Manipulator Class
In this step you will create a new module for the manipulator class for the object info, which will be displayed in the viewport in another step ([see here for more information on the Manipulator Class in Omniverse](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Manipulator.html)).<br>
## Step 7.1: Create `object_info_manipulator.py`
Similar to when you created `object_info_model.py`, create a new module in the same folder and name it `object_info_manipulator.py`.
The objective of this module is to getf the object model's details, such as name and path, and display it in the viewport through using `on_build()`. This is important as it connects the nested data in `object_info_model.py`.
## Step 7.2: Import ui
import from omni.ui:
```python
from omni.ui import scene as sc
import omni.ui as ui
```
## Step 7.3: Create `ObjectInfoManipilator`
Create the `ObjInfoManipulator` class:
```python
...
class ObjInfoManipulator(sc.Manipulator):
"""Manipulator that displays the object path and material assignment
with a leader line to the top of the object's bounding box.
"""
```
## Step 7.4 Populate `ObjInfoManipulator`
Populate the `ObjInfoManipulator` class with `on_build()`:
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
position = [0, 0, 0]
sc.Label(f"Path: {self.model.get_item('name')}")
```
This method checks if there is a selection and creates a label for the path.
## Step 7.5 Invalidate the manipulator on model update
Before moving on from `object_info_manipulator.py`, navigate to the end of the file and call `invalidate()`.
```python
...
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
This method purges old memory when the model is updated.
<details>
<summary>Click here for the full <b>object_info_manipulator.py</b> module </summary>
```python
from omni.ui import scene as sc
import omni.ui as ui
class ObjInfoManipulator(sc.Manipulator):
"""Manipulator that displays the object path and material assignment
with a leader line to the top of the object's bounding box.
"""
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
position = [0, 0, 0]
sc.Label(f"Path: {self.model.get_item('name')}")
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
<br>
# Step 8: Displaying information in the viewport
In this step, you will create a new module that uses the gathered information from other modules and displays them in the active viewport.
## Step 8.1: Create new file
Add this module to the same folder and name it `viewport_scene.py`.
Import the `scene` from `omni.ui`, `ObjInfoModel`, and `ObjInfoManipulator`:
```python
from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjInfoManipulator
from .object_info_model import ObjInfoModel
```
## Step 8.2 Create new class
Create the `ViewportSceneInfo` class and define the `__init__()`:
```python
...
class ViewportSceneInfo():
"""The Object Info Manipulator, placed into a Viewport"""
def __init__(self, viewport_window, ext_id) -> None:
self.scene_view = None
self.viewport_window = viewport_window
```
## Step 8.3 Display object information
To display the information, set the default SceneView. Then add the manipulator into the SceneView's scene and register it with the Viewport:
```python
...
class ViewportSceneInfo():
"""The Object Info Manipulator, placed into a Viewport"""
def __init__(self, viewport_window, ext_id) -> None:
self.scene_view = None
self.viewport_window = viewport_window
# NEW: Create a unique frame for our SceneView
with self.viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self.scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self.scene_view.scene:
ObjInfoManipulator(model=ObjInfoModel())
# Register the SceneView with the Viewport to get projection and view updates
self.viewport_window.viewport_api.add_scene_view(self.scene_view)
```
## Step 8.4: Clean up scene and viewport memory
Before closing out on `viewport_scene.py` don't forget to call `destroy()` to clear the scene and un-register our unique SceneView from the Viewport.
```python
...
def __del__(self):
self.destroy()
def destroy(self):
if self.scene_view:
# Empty the SceneView of any elements it may have
self.scene_view.scene.clear()
# un-register the SceneView from Viewport updates
if self.viewport_window:
self.viewport_window.viewport_api.remove_scene_view(self.scene_view)
# Remove our references to these objects
self.viewport_window = None
self.scene_view = None
```
<details>
<summary>Click here for the full <b>viewport_scene.py</b> module </summary>
```python
from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjInfoManipulator
from .object_info_model import ObjInfoModel
class ViewportSceneInfo():
"""The Object Info Manipulator, placed into a Viewport"""
def __init__(self, viewport_window, ext_id) -> None:
self.scene_view = None
self.viewport_window = viewport_window
# Create a unique frame for our SceneView
with self.viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self.scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self.scene_view.scene:
ObjInfoManipulator(model=ObjInfoModel())
# Register the SceneView with the Viewport to get projection and view updates
self.viewport_window.viewport_api.add_scene_view(self.scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self.scene_view:
# Empty the SceneView of any elements it may have
self.scene_view.scene.clear()
# un-register the SceneView from Viewport updates
if self.viewport_window:
self.viewport_window.viewport_api.remove_scene_view(self.scene_view)
# Remove our references to these objects
self.viewport_window = None
self.scene_view = None
```
</details>
<br>
# Step 9: Cleaning up `extension.py`
> **Note:** Work in `extension.py` for this section.
Now that you've have established a Viewport, you need to clean up `extension.py` to reflect these changes. You will remove some of code from previous steps and ensure that the viewport is flushed out on shutdown.
## Step 9.1: Import class
Import `ViewportSceneInfo`:
```python
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
# NEW:
from .viewport_scene import ViewportSceneInfo
```
## Step 9.2: Remove `ObjInfoModel`
Remove the import from the `object_info_model` module as it will no longer be used:
```python
# REMOVE
from .object_info_model import ObjInfoModel
```
## Step 9.3: Remove reference
As you removed the import from `ObjInfoModel` import, remove its reference in the `__init__()` method and replace it with the `viewport_scene`:
```python
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self) -> None:
super().__init__()
# NEW: removed reference to objmodelinfo and replaced with viewportscene
self.viewport_scene = None
```
## Step 9.4: Remove start up code
Remove the start up code that constructs the `ObjInfoModel` object and the code following it that creates the extension window and **Click Me** button:
```python
...
def on_startup(self, ext_id):
# # # !REMOVE! # # #
print("[omni.objInfo.tutorial] MyExtension startup")
viewport_window = get_active_viewport_window()
self.obj_model = ObjInfoModel()
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
def on_click():
print(viewport_window)
ui.Button("Click Me", clicked_fn=lambda: on_click())
# # # END # # #
# # # !REPLACE WITH! # # #
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
# # # END # # #
```
<details>
<summary>Click to view final <b>on_startup</b> code</summary>
```python
def on_startup(self, ext_id):
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
```
</details>
<br>
## Step 9.5: Clean up viewport memory
Finally, update `on_shutdown()` to clean up the viewport:
```python
...
def on_shutdown(self):
"""Called when the extension is shutting down."""
# NEW: updated to destroy viewportscene
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None
```
<details>
<summary>Click to view the updated <b>extension.py</b> </summary>
```python
import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportSceneInfo
class MyExtension(omni.ext.IExt):
"""Creates an extension which will display object info in 3D
over any object in a UI Scene.
"""
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self) -> None:
super().__init__()
self.viewport_scene = None
def on_startup(self, ext_id):
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
def on_shutdown(self):
"""Called when the extension is shutting down."""
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None
```
</details>
<br>
## Congratulations!
You should be able to create a prim in the viewport and view the Object Info at the world position `[0,0,0]`.

>💡 Tip: If you are logging any errors in the Console in Omniverse Code after updating `extention.py` try refreshing the application.
<br>
# Step 10: Displaying Object Info in Local Space
At this stage, the Object Info is displaying in the viewport but it is displayed at the origin. This means that regardless of where your object is located in the World, the info will always be displayed at [0,0,0]. In the next few steps you will convert this into Local Space. By the end of step 4 the Object Info should follow the object.
## Step 10.1: Import USD
> **Note:** Work in `object_info_model.py` for this section.
In this step and the following steps, we will be doing a little bit of math. Before we jump into that though, let's import what we need to make this work into `object_info_model.py`. We will be importing primarily what we need from USD and we will place these imports at the top of the file:
```python
# NEW IMPORTS
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
```
## Step 10.2: Add identifier
Add a new identifier for the position in `get_item()`:
```python
...
def get_item(self, identifier):
if identifier == "name":
return self.current_path
# NEW: new identifier
elif identifier == "position":
return self.position
```
## Step 10.3: Add `get_as_floats()`
After adding to `get_item()`, create a new function to get the position of the prim. Call this function `get_as_floats()`:
```python
...
# NEW: new function to get position of prim
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
```
This function requests the position and value from the item.
## Step 10.4: Define `get_position()`:
Although you created this new function to get the position, you've yet to define the position. The position will be defined in a new function based on the bounding box we will compute for the prim. Name the new function `get_position()` and get a reference to the stage:
```python
...
# NEW: new function that defines the position based on the bounding box of the prim
def get_position(self):
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
```
## Step 10.5: Get the position
Use `get_position()` to get the position directly form USD using the bounding box:
```python
...
def get_position(self):
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin() #bbox stands for bounding box
bboxMax = range.GetMax()
```
## Step 10.6: Find the top center
Finally, find the top center of the bounding box. Additionally, add a small offset upward so that the information is not overlapping our prim. Append this code to `get_position()`:
```python
...
def get_position(self):
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin() #bbox stands for bounding box
bboxMax = range.GetMax()
# NEW
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
<details>
<summary>Click here for the final <b>object_info_model.py</b> code for this step.</summary>
```python
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
elif identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
# defines the position based on the bounding box of the prim
def get_position(self):
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin() #bbox stands for bounding box
bboxMax = range.GetMax()
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
</details>
<br>
# Step 11: Updating `ObjInfoManipulator`
> **Note:** You are working in `object_info_manipulator.py` for this section.
In this step, you need to update the position value and to position the Object Info at the object's origin and then offset it in the up-direction. You'll also want to make sure that it is scaled properly in the viewport.
Fortunately, this does not require a big alteration to our existing code. You merely need to add onto the `on_build` function in the `object_info_manipulator.py` module:
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
# NEW: update to position value and added transform functions to position the Label at the object's origin and +5 in the up direction
# we also want to make sure it is scaled properly
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
with sc.Transform(scale_to=sc.Space.SCREEN):
sc.Label(f"Path: {self.model.get_item('name')}")
sc.Label(f"Path: {self.model.get_item('name')}")
...
```
# Step 12: Moving the Label with the prim
In the viewport, the text does not follow our object despite positioning the label at the top center of the bounding box of the object. The text also remains in the viewport even when the object is no longer selected. This is because we are reacting to all stage events and not only when a prim is selected. In this final step we will be guiding you to cleaning up these issues.
> **Note:** Work in `object_info_model.py` for this section
## 12.1: Import `Tf`
Place one more import into `object_info_model.py` at the top of the file, as so:
```python
# NEW
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
```
You will use `Tf` to receive notifications of any selection changes.
### 12.2: Store the stage listener
Add a new variable to store the stage listener under the second `__init__()` method:
```python
...
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
# NEW: new variable
self.stage_listener = None
self.position = ObjInfoModel.PositionItem()
...
```
### 12.3: Handle prim selection events
Now, you need to add some code to `on_stage_event()`.
You need to do a few things in this function, such as checking if the `prim_path` exists, turn off the manipulator if it does not, then check if the selected item is a `UsdGeom.Imageable` and remove the stage listener if not. Additionally, notice a change with the stage listener when the selection has changed.
```python
...
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
# NEW: if prim path doesn't exist we want to make sure nothing shows up because that means we do not have a prim selected
if not prim_path:
# This turns off the manipulator when everything is deselected
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
# NEW: if the selected item is not a prim we need to revoke the stagelistener since we don't need to update anything
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
# Revoke the Tf.Notice listener, we don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
# NEW: Register a notice when objects in the scene have changed
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
```
<details>
<summary>Click here for the full <b>on_stage_event</b> function </summary>
```python
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
```
</details>
## 12.4: Setup `notice_changed()` callback
In the final step, create a new function that will be called when any objects change. It will loop through all changed prim paths until the selected one is found and get the latest position for the selected prim. After this, the path should follow the selected object.:
```python
...
# NEW: function that will get called when objects change in the scene. We only care about our selected object so we loop through all notices that get passed along until we find ours
def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None:
"""Called by Tf.Notice. Used when the current selected object changes in some way."""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
...
```
<details>
<summary>Click here for the final <b>object_info_model.py</b> code </summary>
```python
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.stage_listener = None
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
elif identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
# loop through all notices that get passed along until we find selected
def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None:
"""Called by Tf.Notice. Used when the current selected object changes in some way."""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
</details>
# Congratulations!
Your viewport should now display the object info above the selected object and move with the prim in the scene. You have successfully created the Object Info Extension!
 | 47,854 | Markdown | 32.748237 | 378 | 0.663623 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/extension.py | import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportSceneInfo
class MyExtension(omni.ext.IExt):
"""Creates an extension which will display object info in 3D
over any object in a UI Scene.
"""
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self) -> None:
super().__init__()
self.viewport_scene = None
def on_startup(self, ext_id):
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
def on_shutdown(self):
"""Called when the extension is shutting down."""
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None | 915 | Python | 34.230768 | 119 | 0.679781 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/viewport_scene.py | from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjInfoManipulator
from .object_info_model import ObjInfoModel
class ViewportSceneInfo():
def __init__(self, viewportWindow, ext_id) -> None:
self.sceneView = None
self.viewportWindow = viewportWindow
with self.viewportWindow.get_frame(ext_id):
self.sceneView = sc.SceneView()
with self.sceneView.scene:
ObjInfoManipulator(model=ObjInfoModel())
self.viewportWindow.viewport_api.add_scene_view(self.sceneView)
def __del__(self):
self.destroy()
def destroy(self):
if self.sceneView:
self.sceneView.scene.clear()
if self.viewportWindow:
self.viewportWindow.viewport_api.remove_scene_view(self.sceneView)
self.viewportWindow = None
self.sceneView = None | 921 | Python | 27.812499 | 82 | 0.641694 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/object_info_model.py | from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.stage_listener = None
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
elif identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
# loop through all notices that get passed along until we find selected
def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None:
"""Called by Tf.Notice. Used when the current selected object changes in some way."""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe() | 4,115 | Python | 34.482758 | 111 | 0.598056 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/object_info_manipulator.py | from omni.ui import scene as sc
import omni.ui as ui
class ObjInfoManipulator(sc.Manipulator):
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
# NEW: update to position value and added transform functions to position the Label at the object's origin and +5 in the up direction
# we also want to make sure it is scaled properly
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
with sc.Transform(scale_to=sc.Space.SCREEN):
# END NEW
sc.Label(f"Path: {self.model.get_item('name')}")
sc.Label(f"Path: {self.model.get_item('name')}")
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate() | 1,050 | Python | 35.241378 | 141 | 0.626667 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/config/extension.toml | [package]
version = "1.0.0"
authors = ["NVIDIA"]
title = "Omni UI Scene Object Info Example"
description = "This example shows a 3D info popover-type tool tip scene object"
readme = "docs/README.md"
repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene"
category = "Documentation"
keywords = ["ui", "example", "scene", "docs", "documentation", "popover"]
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui.scene" = { }
"omni.usd" = { }
"omni.kit.viewport.utility" = { }
[[python.module]]
name = "omni.example.ui_scene.object_info"
[[test]]
args = ["--/renderer/enabled=pxr", "--/renderer/active=pxr", "--no-window"]
dependencies = ["omni.hydra.pxr", "omni.kit.window.viewport"]
| 775 | TOML | 30.039999 | 82 | 0.689032 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ObjectInfoExtension"]
import carb
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportScene
class ObjectInfoExtension(omni.ext.IExt):
"""Creates an extension which will display object info in 3D
over any object in a UI Scene.
"""
def __init__(self):
self._viewport_scene = None
def on_startup(self, ext_id: str) -> None:
"""Called when the extension is starting up.
Args:
ext_id: Extension ID provided by Kit.
"""
# Get the active Viewport (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# Issue an error if there is no Viewport
if not viewport_window:
carb.log_error(f"No Viewport Window to add {ext_id} scene to")
return
# Build out the scene
self._viewport_scene = ViewportScene(viewport_window, ext_id)
def on_shutdown(self) -> None:
"""Called when the extension is shutting down."""
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
| 1,609 | Python | 32.541666 | 76 | 0.679925 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/viewport_scene.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportScene"]
from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjectInfoManipulator
from .object_info_model import ObjectInfoModel
class ViewportScene():
"""The Object Info Manipulator, placed into a Viewport"""
def __init__(self, viewport_window: ui.Window, ext_id: str) -> None:
self._scene_view = None
self._viewport_window = viewport_window
# Create a unique frame for our SceneView
with self._viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self._scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self._scene_view.scene:
ObjectInfoManipulator(model=ObjectInfoModel())
# Register the SceneView with the Viewport to get projection and view updates
self._viewport_window.viewport_api.add_scene_view(self._scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self._scene_view:
# Empty the SceneView of any elements it may have
self._scene_view.scene.clear()
# Be a good citizen, and un-register the SceneView from Viewport updates
if self._viewport_window:
self._viewport_window.viewport_api.remove_scene_view(self._scene_view)
# Remove our references to these objects
self._viewport_window = None
self._scene_view = None
| 1,951 | Python | 38.836734 | 89 | 0.680677 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/__init__.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import *
| 453 | Python | 44.399996 | 76 | 0.80574 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/object_info_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ObjectInfoModel"]
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from pxr import UsdShade
from omni.ui import scene as sc
import omni.usd
# The distance to raise above the top of the object's bounding box
TOP_OFFSET = 5
class ObjectInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self):
super().__init__()
# Current selected prim and material
self._prim = None
self._current_path = ""
self._material_name = ""
self._stage_listener = None
self.position = ObjectInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
usd_context = self._get_context()
# Track selection changes
self._events = usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="Object Info Selection Update"
)
def _get_context(self) -> Usd.Stage:
# Get the UsdContext we are attached to
return omni.usd.get_context()
def _notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None:
"""Called by Tf.Notice. Used when the current selected object changes in some way."""
for p in notice.GetChangedInfoOnlyPaths():
if self._current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
if identifier == "name":
return self._current_path
if identifier == "material":
return self._material_name
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self._get_position()
if item:
# Get the value directly from the item
return item.value
return []
def _on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_kit_selection_changed()
def _on_kit_selection_changed(self):
"""Called when a selection has changed."""
# selection change, reset it for now
self._current_path = ""
usd_context = self._get_context()
stage = usd_context.get_stage()
if not stage:
return
prim_paths = usd_context.get_selection().get_selected_prim_paths()
if not prim_paths:
# This turns off the manipulator when everything is deselected
self._item_changed(self.position)
return
prim = stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
self._prim = None
# Revoke the Tf.Notice listener, we don't need to update anything
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
return
if not self._stage_listener:
# This handles camera movement
self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage)
material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
if material:
self._material_name = str(material.GetPath())
else:
self._material_name = "N/A"
self._prim = prim
self._current_path = prim_paths[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def _get_position(self):
"""Returns position of currently selected object"""
stage = self._get_context().get_stage()
if not stage or not self._current_path:
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self._current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
# Find the top center of the bounding box and add a small offset upward.
position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + TOP_OFFSET, (bboxMin[2] + bboxMax[2]) * 0.5]
return position
| 5,294 | Python | 35.020408 | 110 | 0.626181 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/object_info_manipulator.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
__all__ = ["ObjectInfoManipulator"]
from omni.ui import color as cl
from omni.ui import scene as sc
import omni.ui as ui
LEADER_LINE_CIRCLE_RADIUS = 2
LEADER_LINE_THICKNESS = 2
LEADER_LINE_SEGMENT_LENGTH = 20
VERTICAL_MULT = 1.5
HORIZ_TEXT_OFFSET = 5
LINE1_OFFSET = 3
LINE2_OFFSET = 0
class ObjectInfoManipulator(sc.Manipulator):
"""Manipulator that displays the object path and material assignment
with a leader line to the top of the object's bounding box.
"""
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
position = self.model.get_as_floats(self.model.get_item("position"))
# Move everything to where the object is
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Rotate everything to face the camera
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# Leader lines with a small circle on the end
sc.Arc(LEADER_LINE_CIRCLE_RADIUS, axis=2, color=cl.yellow)
sc.Line([0, 0, 0], [0, LEADER_LINE_SEGMENT_LENGTH, 0],
color=cl.yellow, thickness=LEADER_LINE_THICKNESS)
sc.Line([0, LEADER_LINE_SEGMENT_LENGTH, 0],
[LEADER_LINE_SEGMENT_LENGTH, LEADER_LINE_SEGMENT_LENGTH * VERTICAL_MULT, 0],
color=cl.yellow, thickness=LEADER_LINE_THICKNESS)
# Shift text to the end of the leader line with some offset
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(
LEADER_LINE_SEGMENT_LENGTH + HORIZ_TEXT_OFFSET,
LEADER_LINE_SEGMENT_LENGTH * VERTICAL_MULT,
0)):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Offset each Label vertically in screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, LINE1_OFFSET, 0)):
sc.Label(f"Path: {self.model.get_item('name')}",
alignment=ui.Alignment.LEFT_BOTTOM)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, LINE2_OFFSET, 0)):
sc.Label(f"Material: {self.model.get_item('material')}",
alignment=ui.Alignment.LEFT_TOP)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
| 3,114 | Python | 44.808823 | 108 | 0.621387 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/docs/CHANGELOG.md | # Changelog
omni.example.ui_scene.object_info
## [1.0.0] - 2022-5-1
### Added
- The initial version
| 102 | Markdown | 11.874999 | 33 | 0.666667 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/docs/README.md | # Object Info (omni.example.ui_scene.object_info)

## Overview
This Extension displays the selected prim's Path and Type.
## [Tutorial](../Tutorial/object_info.tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions.
Learn how to create an extension from the Extension Manager in Omniverse Code, set up your files, and use Omniverse's Library. Additionally, the tutorial has a `Final Scripts` folder to use as a reference as you go along.
[Get started with the tutorial here.](../Tutorial/object_info.tutorial.md)
## Usage
Once the extension is enabled in the *Extension Manager*, go to your *Viewport* and right-click to create a prim - such as a cube, sphere, cyclinder, etc. Then, left-click/select it to view the Object Info.
| 1,003 | Markdown | 51.842103 | 222 | 0.768694 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/docs/index.rst | omni.example.ui_scene.object_info
########################################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 164 | reStructuredText | 12.749999 | 40 | 0.530488 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md | # How to make a Object Info Widget Extension
This guide will provide you with a starting point for displaying Object Info and nesting these modules into a Widget. A Widget is a useful utility in `Omniverse Kit` that can be used to add features such as buttons and sliders.
# Learning Objectives
In this guide you will learn how to:
- Create a Widget Extension
- Use Omniverse UI Framework
- Create a label
- (optional) Create a toggle button feature
- (optional) Create a slider
# Prerequisites
It is recommended that you have completed the following:
- [Extension Enviroment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial)
- [How to make an extension to display Object Info](../../omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md)
# Step 1: Create a Widget Module
In this series of steps, you will be setting up your Extension to create a module needed for a widget.
## Step 1.1: Clone Slider Tutorial Branch
Clone the `slider-tutorial-start` branch of the `kit-extension-sample-ui-scene` [github respositiory](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene) to get the assets needed for this hands-on lab.
## Step 1.2: Add Extension Path to Extension Manager
Open the `Extensions Manager` in `Omniverse Code`
Select gear icon to display `Extension Search Paths`.
Use the <span style="color:green">green</span> :heavy_plus_sign: to add the path to `exts/slider-tutorial-start` from the cloned directory.

:memo: Check that the `UI Scene Object Info` Extension is enabled in the `Extensions Manager` and working by creating a new primitive in the `Viewport` and selecting it, the object's path and info should be displayed above the object.
## Step 1.3 Open VS Code with Shortcut
Open `VS Code` directly from the `Extension Manager`

:bulb:If you would like to know more about how to create the modules for displaying Object Info, [check out the guide here.](../../omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md)
## Step 1.4: Create the Module
Create a new module called `object_info_widget.py` in the `exts` hierarchy that our other modules are located in.
This will be our widget module.
`object_info_widget.py` will be building off the Object Info modules provided for you. You will see these modules as `object_info_manipulator.py`, `object_info_model.py`, `viewport_scene.py`, and an updated `extension.py`.
:memo: Visual Studio Code (VS Code) is our preferred IDE, hence forth referred to throughout this guide.
## Step 1.5: Set up Widget Class
Inside of the `object_info_widget.py`, import `omni.ui` then create the `WidgetInfoManipulator` class to nest our functions. After, initialize our methods, as so:
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class WidgetInfoManipulator(sc.Manipulator):
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self.destroy()
def destroy(self):
self._root = None
self._name_label = None
```
This widget will house our widget info to make the information contrasted in the viewport and add other utilities later on.
You will accomplish this by creating a box for the label with a background color.
## Step 1.6: Build the widget
Let's define this as `on_build_widgets` and use the `Omniverse UI Framework` to create the label for this widget in a `ZStack`. [See here for more documentation on Omniverse UI Framework](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html).
```python
...
def on_build_widgets(self):
with ui.ZStack():
```
Once you have established the UI layout, you can create the background for the widget using `ui.Rectangle` and set the border attributes and background color. You can then create the `ui.Label` and set its alignment, as so:
```python
...
def on_build_widgets(self):
with ui.ZStack():
ui.Rectangle(style={
"background_color": cl(0.2),
"border_color": cl(0.7),
"border_width": 2,
"border_radius": 4,
})
self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER)
```
## Step 1.7: Create Manipulator Functions
With a Manipulator, you need to define an `on_build` function.
This function is called when the model is changed so that the widget is rebuilt. [You can find more information about the Manipulator here.](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Manipulator.html)
```python
...
self.on_model_updated(None)
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
self._root = sc.Transform(visible=False)
with self._root:
with sc.Transform(scale_to=sc.Space.SCREEN):
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)):
self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED)
self._widget.frame.set_build_fn(self.on_build_widgets)
```
Now define `on_model_updated()` that was called above. In this function you need to establish what happens if nothing is selected, when to update the prims, and when to update the prim name, as so:
```python
...
def on_model_updated(self, _):
# if you don't have selection then show nothing
if not self.model or not self.model.get_item("name"):
self._root.visible = False
return
# Update the shapes
position = self.model.get_as_floats(self.model.get_item("position"))
if self._root:
self._root.transform = sc.Matrix44.get_translation_matrix(*position)
self._root.visible = True
# Update the shape name
if self._name_label:
self._name_label.text = f"Prim:{self.model.get_item('name')}"
```
<details>
<summary>Click here for the end code of <b>widget_info_manipulator.py</b></summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class WidgetInfoManipulator(sc.Manipulator):
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self.destroy()
def destroy(self):
self._root = None
self._name_label = None
def on_build_widgets(self):
with ui.ZStack():
ui.Rectangle(style={
"background_color": cl(0.2),
"border_color": cl(0.7),
"border_width": 2,
"border_radius": 4,
})
self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER)
self.on_model_updated(None)
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
self._root = sc.Transform(visible=False)
with self._root:
with sc.Transform(scale_to=sc.Space.SCREEN):
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)):
self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED)
self._widget.frame.set_build_fn(self.on_build_widgets)
def on_model_updated(self, _):
# if you don't have selection then show nothing
if not self.model or not self.model.get_item("name"):
self._root.visible = False
return
# Update the shapes
position = self.model.get_as_floats(self.model.get_item("position"))
if self._root:
self._root.transform = sc.Matrix44.get_translation_matrix(*position)
self._root.visible = True
# Update the shape name
if self._name_label:
self._name_label.text = f"Prim:{self.model.get_item('name')}"
```
</details>
# Step 2: Update Viewport and Extension
Now that you have created a new module, it is important for us to bring this information into `viewport_scene.py` and update `extension.py` to reflect these new changes.
## Step 2.1: Import Widget Info
Begin by updating `viewport_scene.py` and importing `WidgetInfoManipulator` at the top of the file with the other imports.
```python
from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjInfoManipulator
from .object_info_model import ObjInfoModel
# NEW
from .widget_info_manipulator import WidgetInfoManipulator
# END NEW
```
### Step 2.2: Add Display Widget
Inside the `ViewportSceneInfo` class, you will add a `display_widget` parameter to `__init__()`:
```python
...
class ViewportSceneInfo():
# NEW PARAMETER: display_widget
def __init__(self, viewport_window, ext_id, display_widget) -> None:
self.scene_view = None
self.viewport_window = viewport_window
...
```
### Step 2.3: Use `display_widget`
Use `display_widget` to control whether to show `WidgetInfoManipulator` or `ObjInfoManipulator` as so:
```python
...
class ViewportSceneInfo():
# NEW PARAMETER: display_widget
def __init__(self, viewport_window, ext_id, display_widget) -> None:
self.scene_view = None
self.viewport_window = viewport_window
with self.viewport_window.get_frame(ext_id):
self.scene_view = sc.SceneView()
with self.scene_view.scene:
# NEW
if display_widget:
WidgetInfoManipulator(model=ObjInfoModel())
else:
# END NEW
ObjInfoManipulator(model=ObjInfoModel())
...
```
<details>
<summary>Click here for the updated <b>viewport_scene.py</b></summary>
```python
from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjInfoManipulator
from .object_info_model import ObjInfoModel
from .widget_info_manipulator import WidgetInfoManipulator
class ViewportSceneInfo():
def __init__(self, viewport_window, ext_id, display_widget) -> None:
self.scene_view = None
self.viewport_window = viewport_window
with self.viewport_window.get_frame(ext_id):
self.scene_view = sc.SceneView()
with self.scene_view.scene:
if display_widget:
WidgetInfoManipulator(model=ObjInfoModel())
else:
ObjInfoManipulator(model=ObjInfoModel())
self.viewport_window.viewport_api.add_scene_view(self.scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self.scene_view:
self.scene_view.scene.clear()
if self.viewport_window:
self.viewport_window.viewport_api.remove_scene_view(self.scene_view)
self.viewport_window = None
self.scene_view = None
```
</details>
<br>
## Step 3: Update `extension.py`
Now that you have created the widget and passed it into the viewport, you need to call this in the `extension.py` module for it to function.
### Step 3.1: Edit the Class Name
Start by changing the class name of `extension.py` from `MyExtension` to something more descriptive, like `ObjectInfoWidget`:
```python
...
## Replace ##
class MyExtension(omni.ext.IExt):
## With ##
class ObjectInfoWidget(omni.ext.IExt):
## END ##
def __init__(self) -> None:
super().__init__()
self.viewportScene = None
```
### Step 3.2: Pass the Parameter
Pass the new parameter in `on_startup()` as follows:
```python
...
def on_startup(self, ext_id):
#Grab a reference to the viewport
viewport_window = get_active_viewport_window()
# NEW PARAMETER PASSED
self.viewportScene = ViewportSceneInfo(viewport_window, ext_id, True)
...
```
<details>
<summary>Click here for the updated <b>extension.py</b> module </summary>
```python
import omni.ext
import omni.ui as ui
from omni.ui import scene as sc
from omni.ui import color as cl
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportSceneInfo
class ObjectInfoWidget(omni.ext.IExt):
def __init__(self) -> None:
super().__init__()
self.viewportScene = None
def on_startup(self, ext_id):
#Grab a reference to the viewport
viewport_window = get_active_viewport_window()
self.viewportScene = ViewportSceneInfo(viewport_window, ext_id, True)
def on_shutdown(self):
if self.viewportScene:
self.viewportScene.destroy()
self.viewportScene = None
```
</details>
Excellent, You should now see these updates in Omniverse Code at this point.

## Step 4: Create a Toggle Button
In this section you will create a button that enables us to turn the object info widget on and off in the viewport. This feature is built in `extension.py` and is an optional section. If you do not want the toggle button, feel free to skip this part.
## Step 4.1: Add the button to `extension.py`
First define new properties in `extension.py` for `viewport_scene`,`widget_view`, and `ext_id`, as follows:
```python
...
class ObjectInfoWidget(omni.ext.IExt):
def __init__(self) -> None:
super().__init__()
# NEW VALUES
self.viewport_scene = None
self.widget_view_on = False
self.ext_id = None
# END NEW
```
### Step 4.2 Update Startup
Update `on_startup()` to create a new window for the button.
### Step 4.3 Passs `self.widget_view_on` into ViewportSceneInfo
```python
...
def on_startup(self, ext_id):
# NEW: Window with a label and button to toggle the widget / info
self.window = ui.Window("Toggle Widget View", width=300, height=300)
self.ext_id = ext_id
with self.window.frame:
with ui.HStack(height=0):
ui.Label("Toggle Widget View", alignment=ui.Alignment.CENTER_TOP, style={"margin": 5})
ui.Button("Toggle Widget", clicked_fn=self.toggle_view)
# END NEW
#Grab a reference to the viewport
viewport_window = get_active_viewport_window()
# NEW: passed in our new value self.widget_view_on
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id, self.widget_view_on)
...
```
### Step 4.4 Create the Toggle
Define `toggle_view()`.
This function will be bound to the button's clicked function, thus requiring an `if` statement to check when the button is on/off:
```python
...
# NEW: New function that is binded to our button's clicked_fn
def toggle_view(self):
self.reset_viewport_scene()
self.widget_view_on = not self.widget_view_on
if self.widget_view_on:
self._toggle_button.text = "Toggle Widget Info Off"
else:
self._toggle_button.text = "Toggle Widget Info On"
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, self.ext_id, self.widget_view_on)
# END NEW
...
```
### Step 4.5: Create Reset Viewport Scene Function
This button is used in more than one spot, therefore define `reset_viewport_scene()`.
This function will purge our viewport scene when the button is reset.
```python
...
# NEW: New function for resetting the viewport scene (since this will be used in more than one spot)
def reset_viewport_scene(self):
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None
# END NEW
...
```
### Step 4.6: Reset Viewport Scene on Shutdown
Update `on_shutdown` to remove the `viewport_scene` parameters you moved into the reset function and then call that function.
```python
...
def on_shutdown(self):
# NEW: Moved code block to a function and call it
self.reset_viewport_scene()
# END NEW
```
<br>
<details>
<summary>Click here for the updated <b>extension.py</b> module </summary>
```python
import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportSceneInfo
class ObjectInfoWidget(omni.ext.IExt):
def __init__(self) -> None:
super().__init__()
self.viewport_scene = None
self.widget_view_on = False
self.ext_id = None
def on_startup(self, ext_id):
self.window = ui.Window("Toggle Widget View", width=300, height=300)
self.ext_id = ext_id
with self.window.frame:
with ui.HStack(height=0):
ui.Label("Toggle Widget View", alignment=ui.Alignment.CENTER_TOP, style={"margin": 5})
ui.Button("Toggle Widget", clicked_fn=self.toggle_view)
#Grab a reference to the viewport
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id, self.widget_view_on)
def toggle_view(self):
self.reset_viewport_scene()
self.widget_view_on = not self.widget_view_on
if self.widget_view_on:
self._toggle_button.text = "Toggle Widget Info Off"
else:
self._toggle_button.text = "Toggle Widget Info On"
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, self.ext_id, self.widget_view_on)
def reset_viewport_scene(self):
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None
def on_shutdown(self):
self.reset_viewport_scene()
```
</details>
<br>
Here is what you should see in the viewport at this point:
<br>

## Step 5: Add a Slider
In this step, you will be adding a slider to the widget. This slider will change the scale of the object. This is an optional step and may be skipped as it is just to showcase a simple addition of what a widget can do. For a more complex slider, [check out the guide to `Slider Manipulator` here.](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md)
### Step 5.1: Add to `widget_info_manipulator.py`
Use `omni.ui` to build the framework for the slider in the function `on_build_widgets()`.
This slider is an optional feature to the widget but is a great way to add utility.
```python
...
def on_build_widgets(self):
with ui.ZStack():
ui.Rectangle(style={
"background_color": cl(0.2),
"border_color": cl(0.7),
"border_width": 2,
"border_radius": 4,
})
# NEW: Adding the Slider to the widget in the scene
with ui.VStack(style={"font_size": 24}):
self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER)
# setup some model, just for simple demonstration here
self._slider_model = ui.SimpleFloatModel()
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer(width=10)
ui.Label("scale", height=0, width=0)
ui.Spacer(width=5)
ui.FloatSlider(self._slider_model)
ui.Spacer(width=5)
ui.Spacer(height=5)
# END NEW
self.on_model_updated(None)
...
```
### Step 5.2: Update the Scale with a Slider Function
Add a new function that will scale the model when the slider is dragged.
Define this function after `on_model_updated` and name it `update_scale`.
```python
...
def on_model_updated(self, _):
# if you don't have selection then show nothing
if not self.model or not self.model.get_item("name"):
self._root.visible = False
return
# Update the shapes
position = self.model.get_as_floats(self.model.get_item("position"))
if self._root:
self._root.transform = sc.Matrix44.get_translation_matrix(*position)
self._root.visible = True
# NEW
# Update the slider
def update_scale(prim_name, value):
print(f"changing scale of {prim_name}, {value}")
stage = self.model.usd_context.get_stage()
prim = stage.GetPrimAtPath(self.model.current_path)
scale = prim.GetAttribute("xformOp:scale")
scale.Set(Gf.Vec3d(value, value, value))
if self._slider_model:
self._slider_subscription = None
self._slider_model.as_float = 1.0
self._slider_subscription = self._slider_model.subscribe_value_changed_fn(
lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float)
)
# END NEW
...
```
<details>
<summary>Click here for the updated <b>widget_info_manipulator.py</b> module </summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
from pxr import Gf
class WidgetInfoManipulator(sc.Manipulator):
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self.destroy()
def destroy(self):
self._root = None
self._name_label = None
self._slider_model = None
def on_build_widgets(self):
with ui.ZStack():
ui.Rectangle(style={
"background_color": cl(0.2),
"border_color": cl(0.7),
"border_width": 2,
"border_radius": 4,
})
with ui.VStack():
self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER)
# setup some model, just for simple demonstration here
self._slider_model = ui.SimpleFloatModel()
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer(width=10)
ui.Label("scale", height=0, width=0)
ui.Spacer(width=5)
ui.FloatSlider(self._slider_model)
ui.Spacer(width=5)
ui.Spacer(height=5)
self.on_model_updated(None)
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
self._root = sc.Transform(visibile=False)
with self._root:
with sc.Transform(scale_to=sc.Space.SCREEN):
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)):
self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED)
self._widget.frame.set_build_fn(self.on_build_widgets)
def on_model_updated(self, _):
# if you don't have selection then show nothing
if not self.model or not self.model.get_item("name"):
self._root.visible = False
return
# Update the shapes
position = self.model.get_as_floats(self.model.get_item("position"))
if self._root:
self._root.transform = sc.Matrix44.get_translation_matrix(*position)
self._root.visible = True
# Update the slider
def update_scale(prim_name, value):
print(f"changing scale of {prim_name}, {value}")
stage = self.model.usd_context.get_stage()
prim = stage.GetPrimAtPath(self.model.current_path)
scale = prim.GetAttribute("xformOp:scale")
scale.Set(Gf.Vec3d(value, value, value))
if self._slider_model:
self._slider_subscription = None
self._slider_model.as_float = 1.0
self._slider_subscription = self._slider_model.subscribe_value_changed_fn(
lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float)
)
# Update the shape name
if self._name_label:
self._name_label.text = f"Prim:{self.model.get_item('name')}"
```
</details>
<br>
Here is what is created in the viewport of Omniverse Code:
<br>

# Congratulations!
You have successfully created a Widget Info Extension! | 24,282 | Markdown | 33.201408 | 460 | 0.640763 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/config/extension.toml | [package]
version = "1.0.1"
authors = ["NVIDIA"]
title = "Omni.UI Scene Object Info with Widget Example"
description = "This example show an 3d info pophover type tool tip scene object"
readme = "docs/README.md"
repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene"
category = "Documentation"
keywords = ["ui", "example", "scene", "docs", "documentation", "popover"]
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.kit.viewport.utility" = { }
"omni.ui.scene" = { }
"omni.usd" = { }
[[python.module]]
name = "omni.example.ui_scene.widget_info"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.core",
"omni.kit.renderer.capture",
]
| 845 | TOML | 25.437499 | 82 | 0.678107 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_manipulator.py | ## Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ["WidgetInfoManipulator"]
from omni.ui import color as cl
from omni.ui import scene as sc
import omni.ui as ui
class _ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact is the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class _DragPrioritize(sc.GestureManager):
"""Refuses preventing _DragGesture."""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _DragGesture(sc.DragGesture):
""""Gesture to disable rectangle selection in the viewport legacy"""
def __init__(self):
super().__init__(manager=_DragPrioritize())
def on_began(self):
# When the user drags the slider, we don't want to see the selection
# rect. In Viewport Next, it works well automatically because the
# selection rect is a manipulator with its gesture, and we add the
# slider manipulator to the same SceneView.
# In Viewport Legacy, the selection rect is not a manipulator. Thus it's
# not disabled automatically, and we need to disable it with the code.
self.__disable_selection = _ViewportLegacyDisableSelection()
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
class WidgetInfoManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.destroy()
self._radius = 2
self._distance_to_top = 5
self._thickness = 2
self._radius_hovered = 20
def destroy(self):
self._root = None
self._slider_subscription = None
self._slider_model = None
self._name_label = None
def _on_build_widgets(self):
with ui.ZStack():
ui.Rectangle(
style={
"background_color": cl(0.2),
"border_color": cl(0.7),
"border_width": 2,
"border_radius": 4,
}
)
with ui.VStack(style={"font_size": 24}):
ui.Spacer(height=4)
with ui.ZStack(style={"margin": 1}, height=30):
ui.Rectangle(
style={
"background_color": cl(0.0),
}
)
ui.Line(style={"color": cl(0.7), "border_width": 2}, alignment=ui.Alignment.BOTTOM)
ui.Label("Hello world, I am a scene.Widget!", height=0, alignment=ui.Alignment.CENTER)
ui.Spacer(height=4)
self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER)
# setup some model, just for simple demonstration here
self._slider_model = ui.SimpleFloatModel()
ui.Spacer(height=10)
with ui.HStack():
ui.Spacer(width=10)
ui.Label("scale", height=0, width=0)
ui.Spacer(width=5)
ui.FloatSlider(self._slider_model)
ui.Spacer(width=10)
ui.Spacer(height=4)
ui.Spacer()
self.on_model_updated(None)
# Additional gesture that prevents Viewport Legacy selection
self._widget.gestures += [_DragGesture()]
def on_build(self):
"""Called when the model is chenged and rebuilds the whole slider"""
self._root = sc.Transform(visible=False)
with self._root:
with sc.Transform(scale_to=sc.Space.SCREEN):
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)):
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED)
self._widget.frame.set_build_fn(self._on_build_widgets)
def on_model_updated(self, _):
# if we don't have selection then show nothing
if not self.model or not self.model.get_item("name"):
self._root.visible = False
return
# Update the shapes
position = self.model.get_as_floats(self.model.get_item("position"))
self._root.transform = sc.Matrix44.get_translation_matrix(*position)
self._root.visible = True
# Update the slider
def update_scale(prim_name, value):
print(f"changing scale of {prim_name}, {value}")
if self._slider_model:
self._slider_subscription = None
self._slider_model.as_float = 1.0
self._slider_subscription = self._slider_model.subscribe_value_changed_fn(
lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float)
)
# Update the shape name
if self._name_label:
self._name_label.text = f"Prim:{self.model.get_item('name')}"
| 6,631 | Python | 38.011764 | 117 | 0.58513 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["WidgetInfoExtension"]
from .widget_info_scene import WidgetInfoScene
from omni.kit.viewport.utility import get_active_viewport_window
import carb
import omni.ext
class WidgetInfoExtension(omni.ext.IExt):
"""The entry point to the extension"""
def on_startup(self, ext_id):
# Get the active (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# Issue an error if there is no Viewport
if not viewport_window:
carb.log_warn(f"No Viewport Window to add {ext_id} scene to")
self._widget_info_viewport = None
return
# Build out the scene
self._widget_info_viewport = WidgetInfoScene(viewport_window, ext_id)
def on_shutdown(self):
if self._widget_info_viewport:
self._widget_info_viewport.destroy()
self._widget_info_viewport = None
| 1,340 | Python | 35.243242 | 77 | 0.706716 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/__init__.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["WidgetInfoExtension"]
from .widget_info_extension import WidgetInfoExtension
| 518 | Python | 42.249996 | 76 | 0.803089 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_scene.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["WidgetInfoScene"]
import omni.ui as ui
from omni.ui import scene as sc
from .widget_info_model import WidgetInfoModel
from .widget_info_manipulator import WidgetInfoManipulator
class WidgetInfoScene():
"""The Object Info Manupulator, placed into a Viewport"""
def __init__(self, viewport_window, ext_id: str):
self._scene_view = None
self._viewport_window = viewport_window
# Create a unique frame for our SceneView
with self._viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self._scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self._scene_view.scene:
WidgetInfoManipulator(model=WidgetInfoModel())
# Register the SceneView with the Viewport to get projection and view updates
self._viewport_window.viewport_api.add_scene_view(self._scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self._scene_view:
# Empty the SceneView of any elements it may have
self._scene_view.scene.clear()
# Be a good citizen, and un-register the SceneView from Viewport updates
if self._viewport_window:
self._viewport_window.viewport_api.remove_scene_view(self._scene_view)
# Remove our references to these objects
self._viewport_window = None
self._scene_view = None
| 1,936 | Python | 38.530611 | 89 | 0.681818 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["WidgetInfoModel"]
from omni.ui import scene as sc
from pxr import Gf
from pxr import UsdGeom
from pxr import Usd
from pxr import UsdShade
from pxr import Tf
from pxr import UsdLux
import omni.usd
import omni.kit.commands
class WidgetInfoModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because we take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value about some attibute"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self):
super().__init__()
self.material_name = ""
self.position = WidgetInfoModel.PositionItem()
# The distance from the bounding box to the position the model returns
self._offset = 0
# Current selection
self._prim = None
self._current_path = ""
self._stage_listener = None
# Save the UsdContext name (we currently only work with single Context)
self._usd_context_name = ''
usd_context = self._get_context()
# Track selection
self._events = usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="Object Info Selection Update"
)
def _get_context(self) -> Usd.Stage:
# Get the UsdContext we are attached to
return omni.usd.get_context(self._usd_context_name)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self._current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
if identifier == "name":
return self._current_path
if identifier == "material":
return self.material_name
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self._get_position()
if item:
# Get the value directly from the item
return item.value
return []
def set_floats(self, item, value):
if not self._current_path:
return
if not value or not item or item.value == value:
return
# Set directly to the item
item.value = value
# This makes the manipulator updated
self._item_changed(item)
def _on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_kit_selection_changed()
def _on_kit_selection_changed(self):
# selection change, reset it for now
self._current_path = ""
usd_context = self._get_context()
stage = usd_context.get_stage()
if not stage:
return
prim_paths = usd_context.get_selection().get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, we don't need to update anything
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
return
prim = stage.GetPrimAtPath(prim_paths[0])
if prim.IsA(UsdLux.Light):
print("Light")
self.material_name = "I am a Light"
elif prim.IsA(UsdGeom.Imageable):
material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
if material:
self.material_name = str(material.GetPath())
else:
self.material_name = "N/A"
else:
self._prim = None
return
self._prim = prim
self._current_path = prim_paths[0]
# Add a Tf.Notice listener to update the position
if not self._stage_listener:
self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage)
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
# Position is changed
self._item_changed(self.position)
def _get_position(self):
"""Returns position of currently selected object"""
stage = self._get_context().get_stage()
if not stage or not self._current_path:
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self._current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + self._offset, (bboxMin[2] + bboxMax[2]) * 0.5]
return position
| 5,858 | Python | 32.867052 | 117 | 0.612496 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/tests/test_info.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TestInfo"]
from omni.example.ui_scene.widget_info.widget_info_manipulator import WidgetInfoManipulator
from omni.ui import scene as sc
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.kit.app
import omni.kit.test
EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class WidgetInfoTestModelItem(sc.AbstractManipulatorItem):
pass
class WidgetInfoTestModel(sc.AbstractManipulatorModel):
def __init__(self):
super().__init__()
self.position = WidgetInfoTestModelItem()
def get_item(self, identifier):
if identifier == "position":
return self.position
if identifier == "name":
return "Name"
if identifier == "material":
return "Material"
def get_as_floats(self, item):
if item == self.position:
return [0, 0, 0]
class TestInfo(OmniUiTest):
async def test_general(self):
"""Testing general look of the item"""
window = await self.create_test_window(width=256, height=256)
with window.frame:
# Camera matrices
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, -2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, 0)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
# The manipulator
model = WidgetInfoTestModel()
WidgetInfoManipulator(model=model)
await omni.kit.app.get_app().next_update_async()
model._item_changed(None)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(threshold=100, golden_img_dir=TEST_DATA_PATH, golden_img_name="general.png")
| 2,430 | Python | 32.763888 | 115 | 0.653909 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/tests/__init__.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .test_info import TestInfo | 459 | Python | 50.111106 | 76 | 0.810458 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/docs/CHANGELOG.md | # Changelog
omni.ui.scene.object_info
## [1.0.1] - 2022-06-01
### Changed
- It doesn't recreate sc.Widget to avoid crash
## [1.0.0] - 2022-5-1
### Added
- The initial version
| 178 | Markdown | 13.916666 | 46 | 0.646067 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/docs/README.md | # Widget Info (omni.example.ui_scene.widget_info)

## Overview
In the example, we show how to leverage `ui.scene.Widget` item to create a
`ui.Widget` that is in 3D space. The Widget can have any type of `omni.ui` element,
including being interactive, as shown with the slider.
## [Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions.
In the tutorial you will learn how to build from existing modules to create a Widget. A Widget is a useful utility in `Omniverse Kit` that can be used to add features such as buttons and sliders.
[Get started with the tutorial here.](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md)
## Usage
Once the extension is enabled in the `Extension Manager`, go to your `Viewport` and right-click to create a primitive - such as a cube, sphere, cyclinder, etc. Then, left-click/select the primitive to view the Object Info. The Path and Type of the Object will be displayed inside of a Widget.
## The extension showcases view concepts
Similarly to the other `ui.scene` example it shows you how to set up the viewport
scene in `viewport_scene.py`. Then there is the Manipulator object that manages
the presentation of the item `widget_info_manipulator.py`. Finally, the
`widget_info_model.py` contains the model that connects the world with the
manipulator.
## Overlaying with the viewport
We use `sc.Manipulator` with `sc.Widget` to draw `omni.ui` widgets in 3D view.
To show it in the viewport, we overlay `sc.SceneView` with our `sc.Manipulator`
on top of the viewport window.
```python
from omni.kit.viewport.utility import get_active_viewport_window
viewport_window = get_active_viewport_window()
# Create a unique frame for our SceneView
with viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self._scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self._scene_view.scene:
WidgetInfoManipulator(model=WidgetInfoModel())
```
To synchronize the projection and view matrices, `omni.kit.viewport.utility` has
the method `add_scene_view`, which replaces the camera model, and the
manipulator visually looks like it's in the main viewport.
```python
# Register the SceneView with the Viewport to get projection and view updates
viewport_window.viewport_api.add_scene_view(self._scene_view)
```
| 2,840 | Markdown | 47.982758 | 292 | 0.772183 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/docs/index.rst | omni.example.ui_scene.widget_info
########################################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 164 | reStructuredText | 12.749999 | 40 | 0.530488 |
NVIDIA-Omniverse/IsaacSim-Automator/CONTRUBUTING.md |
# Isaac Automation OSS Contribution Rules
- [Development Tips](#development-tips)
- [Updating Pre-Built VM Images](#updating-pre-built-vm-images)
- [Azure](#azure)
- [Issue Tracking](#issue-tracking)
- [Coding Guidelines](#coding-guidelines)
- [Formatting and Linting](#formatting-and-linting)
- [General](#general)
- [Pull Requests](#pull-requests)
- [Signing Your Work](#signing-your-work)
## Development Tips
### Updating Pre-Built VM Images
Pre-built VM images are created using [Packer](https://www.packer.io/) and can be used to accelerate deployment of the app instances by skipping the time-consuming installation and configuration steps. To use pre-built images, add `--from-image` flag to the `deploy-*` commands.
```sh
#### AWS
Refer to [../src/packer/aws/README.md](src/packer/aws/README.md) for pre-requisites. Then:
```sh
packer build -force /app/src/packer/aws/isaac
...
```
#### Azure
Refer to [../src/packer/azure/README.md](src/packer/azure/README.md) for pre-requisites. Then:
```sh
packer build -force /app/src/packer/azure/isaac
...
```
## Issue Tracking
- All enhancement, bugfix, or change requests must begin with the creation of a [Isaac Automation Issue Request](https://github.com/nvidia/Isaac-Automation/issues).
- The issue request must be reviewed by Isaac Automation engineers and approved prior to code review.
## Coding Guidelines
Please follow the existing conventions in the relevant file, submodule, module, and project when you add new code or when you extend/fix existing functionality.
### Formatting and Linting
- Make sure your editor is using the included `.editorconfig` file for indentation, line endings, etc.
- Use the following formatters and linting tools for the respective languages:
- Python: [black](<https://github.com/psf/black>), [isort](<https://github.com/pycqa/isort/>), [flake8](https://github.com/pycqa/flake8)
- Terraform: [terraform fmt](<https://www.terraform.io/docs/commands/fmt.html>)
- Ansible: [ansible-lint](<https://github.com/ansible/ansible-lint>)
- Packer: [packer fmt](<https://www.packer.io/docs/commands/fmt.html>)
Project includes settings and recommended extensions for [Visual Studio Code](https://code.visualstudio.com/) which make it easier following the formatting linting and guidelines.
### General
- Avoid introducing unnecessary complexity into existing code so that maintainability and readability are preserved.
- Try to keep pull requests (PRs) as concise as possible:
- Avoid committing commented-out code.
- Wherever possible, each PR should address a single concern. If there are several otherwise-unrelated things that should be fixed to reach a desired endpoint, our recommendation is to open several PRs and indicate the dependencies in the description. The more complex the changes are in a single PR, the more time it will take to review those changes.
- Write commit titles using imperative mood and [these rules](https://chris.beams.io/posts/git-commit/), and reference the Issue number corresponding to the PR. Following is the recommended format for commit texts:
```text
#<Issue Number> - <Commit Title>
<Commit Body>
```
- All OSS components must contain accompanying documentation (READMEs) describing the functionality, dependencies, and known issues.
- Accompanying tests are highly desireable and recommended. If the test is not possible or not feasible to implement, please provide a sample usage information.
- Make sure that you can contribute your work to open source (no license and/or patent conflict is introduced by your code). You will need to [`sign`](#signing-your-work) your commit.
- Thanks in advance for your patience as we review your contributions; we do appreciate them!
## Pull Requests
Developer workflow for code contributions is as follows:
1. Developers must first [fork](https://help.github.com/en/articles/fork-a-repo) the [upstream](https://github.com/nvidia/Isaac-Automation) Isaac Automation OSS repository.
1. Git clone the forked repository and push changes to the personal fork.
```bash
git clone https://github.com/YOUR_USERNAME/YOUR_FORK.git Isaac-Automation
# Checkout the targeted branch and commit changes
# Push the commits to a branch on the fork (remote).
git push -u origin <local-branch>:<remote-branch>
```
1. Once the code changes are staged on the fork and ready for review, a [Pull Request](https://help.github.com/en/articles/about-pull-requests) (PR) can be [requested](https://help.github.com/en/articles/creating-a-pull-request) to merge the changes from a branch of the fork into a selected branch of upstream.
## Signing Your Work
- We require that all contributors "sign-off" on their commits. This certifies that the contribution is your original work, or you have rights to submit it under the same license, or a compatible license.
- Any contribution which contains commits that are not Signed-Off will not be accepted.
- To sign off on a commit you simply use the `--signoff` (or `-s`) option when committing your changes:
```bash
git commit -s -m "Add cool feature."
```
This will append the following to your commit message:
```text
Signed-off-by: Your Name <[email protected]>
```
- Full text of the DCO:
```text
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or
(b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or
(c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it.
(d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved.
```
| 6,699 | Markdown | 44.578231 | 385 | 0.754292 |
NVIDIA-Omniverse/IsaacSim-Automator/README.md | # Isaac Sim Automator
- [Installation](#installation)
- [Installing Docker](#installing-docker)
- [Obtaining NGC API Key](#obtaining-ngc-api-key)
- [Building the Container](#building-the-container)
- [Usage](#usage)
- [Tip: Running the Automator Commands](#tip-running-the-automator-commands)
- [Deploying Isaac Sim](#deploying-isaac-sim)
- [AWS](#aws)
- [GCP](#gcp)
- [Azure](#azure)
- [Alibaba Cloud](#alibaba-cloud)
- [Connecting to Deployed Instances](#connecting-to-deployed-instances)
- [Running Applications](#running-applications)
- [Isaac Sim](#isaac-sim)
- [Shell in Isaac Sim Container](#shell-in-isaac-sim-container)
- [Omniverse Isaac Gym Environments](#omniverse-isaac-gym-environments)
- [Isaac Orbit](#isaac-orbit)
- [Mapped Folders](#mapped-folders)
- [Pausing and Resuming](#pausing-and-resuming)
- [Uploading Data](#uploading-data)
- [Downloading Data](#downloading-data)
- [Repairing](#repairing)
- [Destroying](#destroying)
This tool automates deployment of [Isaac Sim](https://developer.nvidia.com/isaac-sim) to public clouds.
## Installation
### Installing Docker
`docker` should be present on your system. Visit <https://docs.docker.com/engine/install/> for installation instructions.
### Obtaining NGC API Key
**NGC API Key** allows you to download docker images from <https://ngc.nvidia.com/>. Please prepare one or obtain it at <https://ngc.nvidia.com/setup/api-key>.
### Building the Container
Please enter the following command in the project root directory to build the container:
```sh
./build
```
This will build the Isaac Sim Automator container and tag it as `isa`.
## Usage
### Tip: Running the Automator Commands
There are two ways to run the automator commands:
1. First enter the automator container and then run the command inside the container:
```sh
# enter the automator container
./run
# inside container:
./someconnad
```
2. Simply prepend the command with `./run` like so:
```sh
./run ./somecommand <parameters>
```
for example:
```sh
./run ./deploy-aws
./run ./destroy my-deployment
```
### Deploying Isaac Sim
#### AWS
<details>
<a name="#aws-permissions"></a>
<summary>Enabling Access Permissions</summary>
You need _AmazonEC2FullAccess_ permissions enabled for your AWS user. You can enable those in [Identity and Access Management (IAM) Section](https://console.aws.amazon.com/iamv2/home#/home) in AWS console like so:
1. Go to <https://console.aws.amazon.com/iamv2/home#/home>
2. Click "Access Management" \> "Users" in the left menu
3. Search for your user name
4. Under "Permissions" tab click "Add permissions"
5. Choose "Attach existing policies directly"
6. Search for _AmazonEC2FullAccess_, check the box next to it, click "Next"
7. Click "Add permissions"
</details>
<details>
<a name="#aws-access-creds"></a>
<summary>Getting Access Credentials</summary>
You will need _AWS Access Key_ and _AWS Secret Key_ for an existing account. You can obtain those in <a href="https://console.aws.amazon.com/iamv2/home#/home">Identity and Access Management (IAM) Section</a> in the AWS console.
</details>
If yoou have completed the above steps or already have your permissions and credentials set up, run the following command in the project root directory:
```sh
# enter the automator container
./run
# inside container:
./deploy-aws
```
Tip: Run `./deploy-aws --help` to see more options.
#### GCP
```sh
# enter the automator container
./run
# inside container:
./deploy-gcp
```
Tip: Run `./deploy-gcp --help` to see more options.
#### Azure
If You Have Single Subscription:
```sh
# enter the automator container
./run
# inside container:
./deploy-azure
```
If You Have Multiple Subscriptions:
```sh
# enter the automator container
./run
# inside container:
az login # login
az account show --output table # list subscriptions
az account set --subscription "<subscription_name>"
./deploy-azure --no-login
```
Tip: Run `./deploy-azure --help` to see more options.
#### Alibaba Cloud
<details>
<a name="#alicloud-access-creds"></a>
<summary>Getting Access Credentials</summary>
You will need <i>Access Key</i> and <i>Secret Key</i> for an existing AliCloud account. You can obtain those in <a href="https://usercenter.console.aliyun.com/#/manage/ak">AccessKey Management</a> section in the Alibaba Cloud console.
</details>
Once you have prepared the access credentials, run the following command in the project root directory:
```sh
# enter the automator container
./run
# inside container:
./deploy-alicloud
```
Tip: Run `./deploy-alicloud --help` to see more options.
GPU-accelerated instances with NVIDIA A100, A10 and T4 GPUs are supported. You can find the complete list of instance types, availability and pricing at <https://www.alibabacloud.com/help/en/ecs/user-guide/gpu-accelerated-compute-optimized-and-vgpu-accelerated-instance-families-1>. Please note that vGPU instances are not supported.
### Connecting to Deployed Instances
Deployed Isaac Sim instances can be accessed via:
- SSH
- noVNC (browser-based VNC client)
- NoMachine (remote desktop client)
Look for the connection instructions at the end of the deploymnt command output. Additionally, this info is saved in `state/<deployment-name>/info.txt` file.
You can view available arguments with `--help` switch for the start scripts, in most cases you wouldn't need to change the defaults.
Tip: You can use `./connect <deployment-name>` helper command to connect to the deployed instance via ssh.
### Running Applications
To use installed applications, connect to the deployed instance using noVNC or NoMachine. You can find the connection instructions at the end of the deployment command output. Additionally, this info is saved in `state/<deployment-name>/info.txt` file.
#### Isaac Sim
Isaac Sim will be automatically started when cloud VM is deployed. Alternatively you can click "Isaac Sim" icon on the desktop or run the following command in the terminal on the deployed instance or launch it from the terminal as follows:
```sh
~/Desktop/isaacsim.sh
```
#### Shell in Isaac Sim Container
To get a shell inside Isaac Sim container, click "Isaac Sim Shell" icon on the desktop. Alternatively you can run the following command in the terminal on the deployed instance:
```sh
~/Desktop/isaacsim-shell.sh
```
#### Omniverse Isaac Gym Environments
[Omniverse Isaac Gym Reinforcement Learning Environments for Isaac Sim](https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs) ("Omni Isaac Gym Envs") can be pre-installed on the deployed Isaac instances.
To run Omniverse Isaac Gym Environments click "Omni Isaac Gym Envs" icon on the desktop or run the following command in the terminal:
```sh
~/Desktop/omni-isaac-gym-envs.sh
```
Default output directory (`/OmniIsaacGymEnvs/omniisaacgymenvs/runs`) in the OmniIsaacGymEnvs contaner will be linked to the default results directory (`/home/ubuntu/results`) on the deployed instance. You can download the contents of this directory to your local machine using `./download <deployment_name>` command.
Tip: To install a specific git reference of OmniIsaacGymEnvs, provide valid reference from <https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs> as a value of `--oige` parameter to the deployment command. For example, to install `devel` branch on an AWS instance, run the following command:
```sh
./deploy-aws --oige devel
```
#### Isaac Orbit
*Isaac Orbit is still experimental and intended for preview purposes only.*
[Isaac Orbit](https://isaac-orbit.github.io/orbit/index.html) can be pre-installed on the deployed Isaac instances.
To run Isaac Orbit click "Isaac Orbit" icon on the desktop or run the following command in the terminal:
```sh
~/Desktop/isaac-orbit.sh
```
Tip: To install a specific git reference of Isaac Orbit, provide valid git reference from <https://github.com/NVIDIA-Omniverse/Orbit> as a value of `--orbit` parameter to the deployment command. For example, to install `devel` branch on an AWS instance, run the following command:
```sh
./deploy-aws --orbit devel
```
### Mapped Folders
The following folders are mapped to the running Isaac Sim container by default (container paths may be different for specific applications):
- `/home/ubuntu/uploads` (host) --> `/uploads` (container) - user data uploaded to the deployment with `./upload` command or automatically from local `uploads/` folder
- `/home/ubuntu/results` (host) --> `/results` (container) - results of the applications run on the deployment, can be downloaded from the deployed machine with `./download` command
- `/home/ubuntu/workspace` (host) --> `/workspace` (container) - workspace folder, can be used to exchange data between the host and the container.
### Pausing and Resuming
You can stop and re-start instances to save on cloud costs. To do so, run the following commands:
```sh
# enter the automator container
./run
# inside container:
./stop <deployment-name>
./start <deployment-name>
```
### Uploading Data
You can upload user data from `uploads/` folder (in the project root) to the deployment by running the following command:
```sh
# enter the automator container
./run
# inside container:
./upload <deployment-name>
```
Data will be uploaded to `/home/ubuntu/uploads` directory by default to all deployed instances. You can change this by passing `--remote-dir` argument to the command. Run `./upload --help` to see more options.
### Downloading Data
You can download user data to `results/` folder (in the project root) from deployed instances by running the following command:
```sh
# enter the automator container
./run
# inside container:
./download <deployment-name>
```
Data will be downloaded from `/home/ubuntu/results` directory by default. You can change this by passing `--remote-dir` argument to the command. Run `./download --help` to see more options.
### Repairing
If for some reason the deployment cloud resouces or software configuration get corrupted, you can attempt to repair the deployment by running the following command:
```sh
# run both terraform and ansible
./repair <deployment-name>
# just run terraform to try fixing the cloud resources
./repair <deployment-name> --no-ansible
# just run ansible to try fixing the software configuration
./repair <deployment-name> --no-terraform
```
### Destroying
To destroy a deployment, run the following command:
```sh
# enter the automator container
./run
# inside container:
./destroy <deployment-name>
```
You will be prompted to enter the deployment name to destroy.
*Please note that information about the deployed cloud resources is stored in `state/` directory. Do not delete this directory ever.*
| 10,734 | Markdown | 33.187898 | 333 | 0.74483 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/isaac.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Wait for the instance to become available
hosts: isaac
gather_facts: false
tasks:
- wait_for_connection: timeout=300
tags:
# packer checks connectivity beforehand
- skip_in_image
- on_stop_start
- name: Deploy Isaac Sim
hosts: isaac
gather_facts: true
vars:
in_china: False
application_name: isaac
prompt_ansi_color: 36 # cyan
roles:
- isaac
handlers:
- include: roles/rdesktop/handlers/main.yml
- include: roles/system/handlers/main.yml
| 1,119 | YAML | 27.717948 | 74 | 0.726542 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/ovami.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Wait for the instance to become available
hosts: ovami
gather_facts: false
tasks:
- wait_for_connection: timeout=300
tags:
# packer checks connectivity beforehand
- skip_in_ovami
- name: OV AMI
hosts: ovami
gather_facts: true
vars:
in_china: False
application_name: ovami
prompt_ansi_color: 34 # bright blue
roles:
- ovami
handlers:
- include: roles/rdesktop/handlers/main.yml
- include: roles/system/handlers/main.yml
| 1,096 | YAML | 27.86842 | 74 | 0.729015 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/ngc.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
- name: Install packages
apt: name={{ item }}
state=latest
update_cache=yes
with_items:
- unzip
- name: Download and extract NGC client
unarchive:
src: https://ngc.nvidia.com/downloads/ngccli_cat_linux.zip
dest: /opt
remote_src: yes
- name: Add ngc cli to PATH
lineinfile:
dest: "/etc/profile.d/ngc-cli.sh"
line: export PATH="$PATH:/opt/ngc-cli"
create: yes
| 1,022 | YAML | 27.416666 | 74 | 0.716243 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/nvidia-docker.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
- name: Add repository
shell: "rm -f /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg && rm -f /etc/apt/sources.list.d/nvidia-container-toolkit.list && distribution=$(. /etc/os-release;echo $ID$VERSION_ID) && curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg && curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list | sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list"
- name: Install nvidia-docker2
apt: name={{ item }}
state=latest
update_cache=yes
with_items:
- nvidia-docker2
- name: Restart docker service
service: >
name=docker
state=restarted
| 1,461 | YAML | 44.687499 | 610 | 0.742642 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/nvidia-driver.azure.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
# @see https://learn.microsoft.com/en-us/azure/virtual-machines/linux/n-series-driver-setup#install-grid-drivers-on-nv-or-nvv3-series-vms
- name: Azure / Prerequisites (APT)
apt: name={{ item }}
state=latest
update_cache=yes
install_recommends=no
with_items:
- build-essential
- ubuntu-desktop
- linux-azure
# reqd by asible get_url
- python3-pip
# reqd by driver runfile
- pkg-config
- libglvnd-dev
- name: Azure /Prerequisites (PIP)
pip:
# older version is needed by ansible get_url for some reason
name: requests==2.20.1
executable: pip3
- name: Azure / Blacklist nouveau
kernel_blacklist: name={{ item }}
state=present
with_items:
- nouveau
- lbs-nouveau
- name: Azure / Fix 3818429
kernel_blacklist: name=hyperv_drm state=present
- name: Azure / Check if reboot required
stat:
path: /var/run/reboot-required
register: reboot_required_file
- name: Azure / Reboot and wait
reboot:
post_reboot_delay: 5
connect_timeout: 3
reboot_timeout: 600
when: reboot_required_file.stat.exists == true
# download driver, timeout 3 min, 5 retries
# @see https://github.com/Azure/azhpc-extensions/blob/master/NvidiaGPU/resources.json#L275
- name: Azure / Download GRID driver
get_url:
url: https://go.microsoft.com/fwlink/?linkid=874272
dest: /tmp/nvidia_grid_azure_driver.run
mode: "0755"
timeout: 180
retries: 5
- name: Azure / Install GRID driver
shell: "/tmp/nvidia_grid_azure_driver.run --run-nvidia-xconfig --disable-nouveau --no-questions --silent"
- name: Azure / Enable persistent mode for the driver
shell: nvidia-smi -pm ENABLED
- name: Azure / Copy grid.conf
copy: >
src=/etc/nvidia/gridd.conf.template
dest=/etc/nvidia/gridd.conf
remote_src=true
force=no
- name: Azure / Update GRID config [1]
lineinfile:
path: /etc/nvidia/gridd.conf
line: "{{ item }}"
state: present
with_items:
- "IgnoreSP=FALSE"
- "EnableUI=FALSE"
- name: Azure / Update GRID config [2]
lineinfile:
path: /etc/nvidia/gridd.conf
regexp: "^FeatureType=(.*)$"
line: '# FeatureType=\1'
state: present
backrefs: yes
| 2,805 | YAML | 26.509804 | 137 | 0.693761 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/nvidia-driver.gcp.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# @see https://cloud.google.com/compute/docs/gpus/install-grid-drivers
- name: GCP / Prerequisites (APT)
apt: name={{ item }}
state=latest
update_cache=yes
install_recommends=no
with_items:
- build-essential
- python3-pip # required by asible get_url
- name: GCP / Prerequisites (PIP)
pip:
# older version is needed by ansible get_url for some reason
name: requests==2.20.1
executable: pip3
# download driver
- name: GCP / Download GRID driver
get_url:
url: "{{ gcp_driver_url }}"
dest: /tmp/nvidia_driver.run
mode: 0755
- name: GCP / Install GRID driver
shell: "/tmp/nvidia_driver.run \
--x-module-path=/usr/lib/xorg/modules/drivers \
--run-nvidia-xconfig \
--disable-nouveau \
--no-questions \
--silent"
- name: GCP / Enable persistent mode for the driver
shell: nvidia-smi -pm ENABLED
- name: GCP / Copy gridd.conf
copy: >
src=/etc/nvidia/gridd.conf.template
dest=/etc/nvidia/gridd.conf
remote_src=true
force=no
- name: GCP / Update GRID config [1]
lineinfile:
path: /etc/nvidia/gridd.conf
line: "{{ item }}"
state: present
with_items:
- "IgnoreSP=FALSE"
- "EnableUI=TRUE"
- name: GCP / Update GRID config [2]
lineinfile:
path: /etc/nvidia/gridd.conf
regexp: "^FeatureType=(.*)$"
line: 'FeatureType=\2'
state: present
backrefs: yes
| 1,998 | YAML | 25.653333 | 74 | 0.680681 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
# driver
- name: Detect if the driver is already installed
shell: lsmod | grep nvidia_drm | wc -l
register: driver_installed
- import_tasks: nvidia-driver.azure.yml
when: driver_installed.stdout == "0" and cloud == "azure"
- import_tasks: nvidia-driver.generic.yml
when: driver_installed.stdout == "0" and (cloud == "aws" or cloud == "alicloud")
- import_tasks: nvidia-driver.gcp.yml
when: driver_installed.stdout == "0" and cloud == "gcp"
# Disable ECC
# Needs to be done after restoring from image or from scratch
- name: Detect ECC status
shell: nvidia-smi --query-gpu="ecc.mode.current" --format="csv,noheader" -i 0
register: ecc_status
tags: on_stop_start
- debug:
msg: "ECC status: {{ ecc_status.stdout }}"
#
- name: Disable ECC
shell: nvidia-smi --ecc-config=0
when: ecc_status.stdout == 'Enabled'
tags: on_stop_start
#
- name: Reboot and wait
reboot: post_reboot_delay=5 connect_timeout=3 reboot_timeout=600
when: ecc_status.stdout == 'Enabled'
tags: on_stop_start
# nvidia-docker2
- package_facts: manager=apt
- import_tasks: nvidia-docker.yml
when: '"nvidia-docker2" not in ansible_facts.packages'
| 1,768 | YAML | 29.499999 | 82 | 0.721154 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/nvidia-driver.generic.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
- name: NVIDIA GPU Driver / Add CUDA keyring
apt:
deb: https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-keyring_1.1-1_all.deb
- name: NVIDIA GPU Driver / Blacklist the nouveau driver module
kernel_blacklist: name=nouveau
state=present
- name: NVIDIA GPU Driver / Install pre-requisites
apt: name={{ item }}
state=latest
update_cache=yes
with_items:
- xserver-xorg
- "{{ generic_driver_apt_package }}"
- name: NVIDIA GPU Driver / Enable persistent mode
shell: nvidia-smi -pm ENABLED
- name: NVIDIA GPU Driver / Check if reboot is needed
stat:
path: /var/run/reboot-required
register: reboot_required_file
- name: AWS / Reboot and wait
reboot:
post_reboot_delay: 5
connect_timeout: 3
reboot_timeout: 600
when: reboot_required_file.stat.exists == true
| 1,461 | YAML | 29.458333 | 110 | 0.726899 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/defaults/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# driver package when installed from apt
# nvidia-driver-470-server
# nvidia-driver-510-server
nvidia_driver_package:
| 732 | YAML | 33.90476 | 74 | 0.770492 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/meta/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
galaxy_info:
role_name: nvidia_runtime
author: NVIDIA Corporation
description: NVIDIA driver and docker
standalone: false
dependencies:
- { role: system }
| 783 | YAML | 30.359999 | 74 | 0.757344 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/icon.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Make sure dirs exist
file:
path: "{{ item }}"
state: directory
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0755
with_items:
- /home/{{ ansible_user }}/Pictures
- /home/{{ ansible_user }}/Desktop
- name: Upload icon
copy:
src: "{{ item }}"
dest: /home/{{ ansible_user }}/Pictures/isaacsim-{{ item }}
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0644
with_items:
- icon.png
- icon-shell.png
- name: Create desktop icon
copy:
src: "{{ item }}"
dest: /home/{{ ansible_user }}/Desktop/{{ item }}
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0644
with_items:
- isaacsim.desktop
- isaacsim-shell.desktop
- name: Allow execution of desktop icon
shell: gio set /home/{{ ansible_user }}/Desktop/{{ item }} metadata::trusted true
become_user: "{{ ansible_user }}"
with_items:
- isaacsim.desktop
- isaacsim-shell.desktop
- name: Set permissions for desktop icon
file:
path: /home/{{ ansible_user }}/Desktop/{{ item }}
mode: 0755
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
with_items:
- isaacsim.desktop
- isaacsim-shell.desktop
| 1,845 | YAML | 26.969697 | 83 | 0.645528 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/wallpaper.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Make sure wallpaper dir exists
file:
path: /home/{{ ansible_user }}/Pictures
state: directory
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0755
- name: Upload wallpaper
copy:
src: wallpaper.png
dest: /home/{{ ansible_user }}/Pictures/wallpaper.png
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0644
- name: Set wallpaper
shell: gsettings set org.gnome.desktop.background picture-uri file:///home/{{ ansible_user }}/Pictures/wallpaper.png
become_user: "{{ ansible_user }}"
| 1,177 | YAML | 31.722221 | 118 | 0.705183 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/orbit.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Create directory for Orbit
file:
path: "{{ orbit_dir }}"
state: directory
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0755
- name: Upload Orbit setup files [1]
template: src={{ item }}
dest="{{ orbit_dir }}/{{ item }}"
mode=755
owner=ubuntu
group=ubuntu
with_items:
- orbit.dockerfile
tags: __orbit_dockerfile
- name: Upload Orbit setup files [2]
template: src="{{ item }}"
dest="/home/{{ ansible_user }}/Desktop"
mode=755
owner=ubuntu
group=ubuntu
with_items:
- orbit.sh
- name: Desktop icon for Orbit
copy:
src: "{{ item }}"
dest: "/home/{{ ansible_user }}/Desktop/{{ item }}"
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0644
with_items:
- orbit.desktop
- name: Allow execution of desktop icon for Orbit
shell: gio set "/home/{{ ansible_user }}/Desktop/{{ item }}" metadata::trusted true
become_user: "{{ ansible_user }}"
with_items:
- orbit.desktop
- name: Set permissions for Orbit desktop icon
file:
path: "/home/{{ ansible_user }}/Desktop/{{ item }}"
mode: 0755
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
with_items:
- orbit.desktop
- name: Build Orbit
shell: docker build -t orbit -f "{{ orbit_dir }}/orbit.dockerfile" "{{ orbit_dir }}"
become_user: "{{ ansible_user }}"
tags:
- skip_in_ovami
| 2,021 | YAML | 26.324324 | 86 | 0.646215 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/isaac_app.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Create cache directory
file:
path: "{{ isaac_cache_dir }}"
state: directory
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0777
- name: Launch scripts [1]
file:
path: /home/ubuntu/Desktop
state: directory
owner: ubuntu
group: ubuntu
- name: Launch scripts [2]
template: src={{ item }}
dest=/home/ubuntu/Desktop/{{ item }}
mode=755
owner=ubuntu
group=ubuntu
with_items:
- isaacsim.sh
- isaacsim-shell.sh
- name: Log into nvcr.io
shell: until docker login -u "\$oauthtoken" --password "{{ ngc_api_key }}" nvcr.io; do sleep 10; done
ignore_errors: true
become_user: "{{ item }}"
with_items:
- root
- ubuntu
timeout: 60 # for each item
when: ngc_api_key != "none"
tags:
- skip_in_ovami
- name: Pull Isaac Sim image
docker_image:
name: "{{ isaac_image }}"
repository: nvcr.io
source: pull
ignore_errors: true
when: ngc_api_key != "none"
tags:
- skip_in_ovami
- name: Log out from nvcr.io
shell: docker logout nvcr.io
become_user: "{{ item }}"
with_items:
- root
- ubuntu
when: ngc_api_key != "none"
tags:
- never
- cleanup
- name: Start Isaac Sim
shell: |
export DISPLAY=":0"
gnome-terminal -- bash -c "./isaacsim.sh; exec bash"
args:
chdir: /home/{{ ansible_user }}/Desktop
become_user: "{{ ansible_user }}"
when: ngc_api_key != "none"
tags:
- skip_in_image
- on_stop_start
| 2,087 | YAML | 23.279069 | 103 | 0.647341 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/omni_isaac_gym_envs.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Create directory for OmniIsaacGymEnvs
file:
path: "{{ omni_isaac_gym_envs_dir }}"
state: directory
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0755
- name: Upload OmniIsaacGymEnvs setup files [1]
template: src={{ item }}
dest="{{ omni_isaac_gym_envs_dir }}/{{ item }}"
mode=755
owner=ubuntu
group=ubuntu
with_items:
- omni-isaac-gym-envs.dockerfile
- name: Upload OmniIsaacGymEnvs setup files [2]
template: src="{{ item }}"
dest="/home/{{ ansible_user }}/Desktop"
mode=755
owner=ubuntu
group=ubuntu
with_items:
- omni-isaac-gym-envs.sh
- name: Desktop icon for OmniIsaacGymEnvs
copy:
src: "{{ item }}"
dest: "/home/{{ ansible_user }}/Desktop/{{ item }}"
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0644
with_items:
- omni-isaac-gym-envs.desktop
- name: Allow execution of desktop icon for OmniIsaacGymEnvs
shell: gio set "/home/{{ ansible_user }}/Desktop/{{ item }}" metadata::trusted true
become_user: "{{ ansible_user }}"
with_items:
- omni-isaac-gym-envs.desktop
- name: Set permissions for OmniIsaacGymEnvs desktop icon
file:
path: "/home/{{ ansible_user }}/Desktop/{{ item }}"
mode: 0755
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
with_items:
- omni-isaac-gym-envs.desktop
- name: Build OmniIsaacGymEnvs
shell: docker build -t omni-isaac-gym-envs -f "{{ omni_isaac_gym_envs_dir }}/omni-isaac-gym-envs.dockerfile" "{{ omni_isaac_gym_envs_dir }}"
become_user: "{{ ansible_user }}"
tags:
- skip_in_ovami
| 2,225 | YAML | 29.49315 | 142 | 0.667416 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Prerequisites
apt:
name: "{{ item }}"
state: latest
with_items:
- libvulkan-dev
- name: Wallpaper
import_tasks: wallpaper.yml
- name: Desktop Icon
import_tasks: icon.yml
- name: Isaac App
import_tasks: isaac_app.yml
# https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs
- name: Omni Isaac Gym Envs
import_tasks: omni_isaac_gym_envs.yml
when: omni_isaac_gym_envs_git_checkpoint != 'no'
# https://isaac-orbit.github.io/orbit/index.html
- name: Orbit
import_tasks: orbit.yml
when: orbit_git_checkpoint != 'no'
tags: __orbit
- name: Restart NX server
meta: noop
notify: nx_restart
| 1,243 | YAML | 25.468085 | 74 | 0.726468 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/defaults/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
deployment_name:
isaac_image:
isaac_cache_dir: /home/{{ ansible_user }}/isaac
# OmniIsaacGymEnvs
omni_isaac_gym_envs_dir: /opt/omni-isaac-gym-envs
omni_isaac_gym_envs_git_checkpoint: main
# Orbit
orbit_dir: /opt/orbit
orbit_git_checkpoint: devel
# "none" skips login/pull
ngc_api_key:
# directory to output results to
results_dir: /home/{{ ansible_user }}/results
workspace_dir: /home/{{ ansible_user }}/results
uploads_dir: /home/{{ ansible_user }}/uploads
omniverse_user:
omniverse_password:
nucleus_uri:
| 1,128 | YAML | 25.880952 | 74 | 0.75266 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/meta/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
galaxy_info:
role_name: isaac
author: NVIDIA Corporation
description: Isaac Sim installation
standalone: false
dependencies:
- { role: system }
- { role: docker }
- { role: nvidia }
- { role: rdesktop }
| 837 | YAML | 28.92857 | 74 | 0.735962 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/nice_dcv.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# install nice dcv
# @see https://docs.aws.amazon.com/dcv/latest/adminguide/setting-up-installing-linux-prereq.html
# @see https://docs.aws.amazon.com/dcv/latest/adminguide/setting-up-installing-linux-server.html
# prerequisites
- name: Install prerequisites for NICE DCV
apt:
name: "{{ item }}"
state: latest
with_items:
- rpm # needed for rpm_key ansible module
- mesa-utils
# import GPG key
- name: Import GPG key for NICE DCV
rpm_key:
key: https://d1uj6qtbmh3dt5.cloudfront.net/NICE-GPG-KEY
state: present
# download nice dcv
- name: Download NICE DCV
get_url:
url: https://d1uj6qtbmh3dt5.cloudfront.net/nice-dcv-ubuntu{{ ansible_distribution_version | replace('.', '') }}-{{ ansible_machine }}.tgz
dest: /tmp/nice-dcv.tgz
mode: 0644
# download and unzip nice dcv
- name: Unarchive NICE DCV
unarchive:
src: /tmp/nice-dcv.tgz
remote_src: yes
dest: /tmp
extra_opts: [--strip-components=1]
# find .deb for nice dcv installer
- name: Find .deb for NICE DCV Server installer
find:
paths: /tmp
patterns: "nice-dcv-server*.deb"
register: nice_dcv_deb
# install nice dcv .deb file
- name: Install NICE DCV Server
apt:
deb: "{{ nice_dcv_deb.files[0].path }}"
state: present
# find .deb for nice xdcv
- name: Find .deb for NICE XDCV
find:
paths: /tmp
patterns: "nice-xdcv*.deb"
register: nice_xdcv_deb
# install nice xdcv
- name: Install NICE XDCV
apt:
deb: "{{ nice_xdcv_deb.files[0].path }}"
state: present
# print nice_dcv_unarchive
- name: Print nice_dcv_unarchive
debug:
msg: "{{ nice_dcv_deb.files[0].path }}"
# add the dcv user to the video group
- name: Add "dcv" user to "video" group
user:
name: dcv
groups: video
append: yes
# find nice-dcv-gl .deb file
- name: Find .deb for NICE DCV GL
find:
paths: /tmp
patterns: "nice-dcv-gl*.deb"
register: nice_dcv_gl_deb
# print nice_dcv_gl_deb
- name: Print nice_dcv_gl_deb
debug:
msg: "{{ nice_dcv_gl_deb.files[0].path }}"
# install nice-dcv-gl from .deb file
- name: Install NICE DCV GL
apt:
deb: "{{ nice_dcv_gl_deb.files[0].path }}"
state: present
# post-install steps
# @see https://docs.aws.amazon.com/dcv/latest/adminguide/setting-up-installing-linux-checks.html
# configure dcvgladmin
- name: Post-install confgiuration of NICE DCV GL
shell: |
systemctl isolate multi-user.target
dcvgladmin disable
dcvgladmin enable
systemctl isolate graphical.target
# configure dcvserver
- name: Configure NICE DCV Server
ini_file:
section: "{{ item.section }}"
path: /etc/dcv/dcv.conf
option: "{{ item.key }}"
value: "{{ item.value }}"
no_extra_spaces: true
with_items:
- {
section: "security",
key: "authentication",
value: "{{ dcv_authentication_method }}",
}
- { section: "session-management", key: "create-session", value: "true" }
- {
section: "session-management/automatic-console-session",
key: "owner",
value: "{{ ansible_user }}",
}
- {
section: "display",
key: "default-layout",
value: "[{'w':<1920>, 'h':<1200>, 'x':<0>,'y':<0>}]",
}
# start dcvserver, reboot
- name: Start/Restart/Enable NICE DCV Server
systemd:
name: dcvserver
state: restarted
enabled: yes
- name: Reboot
reboot: post_reboot_delay=5 connect_timeout=3 reboot_timeout=600
| 4,042 | YAML | 25.424836 | 141 | 0.664028 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/vscode.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# @see https://code.visualstudio.com/docs/setup/linux
- name: Prerequisites for VS Code
apt:
name: "{{ item }}"
state: latest
with_items:
- wget
- gpg
- apt-transport-https
- name: Install VSC sources
shell: |
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg
install -D -o root -g root -m 644 packages.microsoft.gpg /etc/apt/keyrings/packages.microsoft.gpg
sh -c 'echo "deb [arch=amd64,arm64,armhf signed-by=/etc/apt/keyrings/packages.microsoft.gpg] https://packages.microsoft.com/repos/code stable main" > /etc/apt/sources.list.d/vscode.list'
args:
creates: /etc/apt/sources.list.d/vscode.list
- name: Install VS Code
apt:
name: code
update_cache: yes
state: latest
- name: Add desktop icon
copy:
src: /usr/share/applications/code.desktop
remote_src: yes
dest: /home/{{ ansible_user }}/Desktop/code.desktop
mode: 0644
- name: Allow execution of VSC desktop icon
shell: gio set /home/{{ ansible_user }}/Desktop/{{ item }} metadata::trusted true
become_user: "{{ ansible_user }}"
with_items:
- code.desktop
- name: Set permissions for VSC desktop icon
file:
path: /home/{{ ansible_user }}/Desktop/{{ item }}
mode: 0755
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
with_items:
- code.desktop
| 1,983 | YAML | 30.492063 | 190 | 0.695411 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/wallpaper.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Make sure wallpaper dir exists
file:
path: /home/{{ ansible_user }}/Pictures
state: directory
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0755
- name: Upload wallpaper
copy:
src: ov-wallpaper.jpeg
dest: /home/{{ ansible_user }}/Pictures/
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0644
- name: Set wallpaper
shell: gsettings set org.gnome.desktop.background picture-uri file:///home/{{ ansible_user }}/Pictures/ov-wallpaper.jpeg
become_user: "{{ ansible_user }}"
| 1,172 | YAML | 31.583332 | 122 | 0.703072 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/cloud_init.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Preserve user password when starting from image
lineinfile:
path: /etc/cloud/cloud.cfg
regexp: ".*lock_passwd:.*"
line: " lock_passwd: False"
state: present
| 801 | YAML | 33.869564 | 74 | 0.739076 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/ov_launcher.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Make sure dirs exist
file:
path: "{{ item }}"
state: directory
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0755
with_items:
- /home/{{ ansible_user }}/Pictures
- /home/{{ ansible_user }}/Desktop
- name: Upload OV Icon
copy:
src: "{{ item }}"
dest: "/home/{{ ansible_user }}/Pictures/{{ item }}"
mode: 0644
with_items:
- ov-icon.png
- name: Download OV Launcher
get_url:
url: https://install.launcher.omniverse.nvidia.com/installers/omniverse-launcher-linux.AppImage
dest: "/home/{{ ansible_user }}/Omniverse.AppImage"
mode: 0755
become_user: "{{ ansible_user }}"
- name: Create desktop icon
copy:
content: |
[Desktop Entry]
Name=Omniverse Launcher
Comment=Omniverse Launcher
Exec=/home/{{ ansible_user }}/Omniverse.AppImage
Icon=/home/{{ ansible_user }}/Pictures/ov-icon.png
Terminal=false
Type=Application
Categories=Utility;
dest: /home/{{ ansible_user }}/Desktop/ovl.desktop
mode: 0644
- name: Allow execution of OVL desktop icon
shell: gio set /home/{{ ansible_user }}/Desktop/{{ item }} metadata::trusted true
become_user: "{{ ansible_user }}"
with_items:
- ovl.desktop
- name: Set permissions for OVL desktop icon
file:
path: /home/{{ ansible_user }}/Desktop/{{ item }}
mode: 0755
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
with_items:
- ovl.desktop
| 2,078 | YAML | 28.28169 | 99 | 0.662656 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# this role is meant to be executed while creating
# the OV AMI, so no skip tags are present
# for NV-use only, don't try to make too much sense of it
- name: Prerequisites
apt:
name: "{{ item }}"
state: latest
with_items:
- libvulkan-dev
- firefox
- xdg-utils
- name: NICE DCV
import_tasks: nice_dcv.yml
- name: OV Launcher
import_tasks: ov_launcher.yml
- name: Install VS Code
import_tasks: vscode.yml
- name: Set wallpaper
import_tasks: wallpaper.yml
- name: Configure cloud-init
import_tasks: cloud_init.yml
| 1,167 | YAML | 24.955555 | 74 | 0.725793 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/defaults/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# "none" or "system"
dcv_authentication_method: system
| 669 | YAML | 34.263156 | 74 | 0.763827 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/meta/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
galaxy_info:
role_name: ovami
author: NVIDIA Corporation
description: Omniverse AMI
standalone: false
dependencies:
- { role: system }
- { role: docker }
- { role: nvidia }
- { role: rdesktop }
| 828 | YAML | 28.607142 | 74 | 0.7343 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/docker/tasks/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
- name: Add Docker apt key
apt_key: url="https://download.docker.com/linux/ubuntu/gpg"
state=present
- name: Add Docker apt package repository
apt_repository:
repo="deb https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable"
state=present
mode=644
- name: Install docker packages
apt: name={{ item }}
state=latest
update_cache=yes
with_items:
- docker-ce
- docker-ce-cli
- docker-compose
- name: Create docker group
group: name=docker
state=present
- name: Add user ubuntu to docker group
user: name=ubuntu
groups=docker
append=yes
state=present
- name: Reset connection so docker group is picked up
meta: reset_connection
| 1,340 | YAML | 26.367346 | 97 | 0.724627 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/handlers/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# reboot
- name: Reboot and wait
reboot: post_reboot_delay=5 connect_timeout=3 reboot_timeout=600
listen: reboot
| 732 | YAML | 32.31818 | 74 | 0.762295 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/id.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
# change color of the bash prompt
- name: Enable color of the bash prompt
lineinfile:
path: /home/{{ ansible_user }}/.bashrc
line: "force_color_prompt=yes"
insertbefore: if \[ \-n \"\$force_color_prompt\"
backup: yes
- name: Change color of the bash prompt
lineinfile:
path: /home/{{ ansible_user }}/.bashrc
regexp: "^ PS1='\\${debian_chroot:\\+\\(\\$debian_chroot\\)}\\\\\\[\\\\033\\[01;32m\\\\\\]\\\\u@\\\\h\\\\\\[\\\\033\\[00m\\\\\\]:\\\\\\[\\\\033\\[01;34m\\\\\\]\\\\w\\\\\\[\\\\033\\[00m\\\\\\]\\\\\\$ '"
line: " PS1='${debian_chroot:+($debian_chroot)}\\[\\033[01;{{ prompt_ansi_color }}m\\]\\u\\[\\033[01;{{ prompt_ansi_color }}m\\]@\\h\\[\\033[00m\\]:\\[\\033[01;34m\\]\\w\\[\\033[00m\\]\\$ '"
backup: yes
# set hostname
- set_fact:
hostname: "{{ (application_name + '-' + deployment_name) | replace('_', '-') }}"
- debug:
msg: "hostname: {{ hostname }}"
- name: Set hostname [1]
hostname:
name: "{{ hostname }}"
- name: Set hostname [2]
lineinfile:
path: /etc/hosts
line: "127.0.0.1 {{ hostname }}"
| 1,698 | YAML | 32.979999 | 208 | 0.61013 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/swap.yml | - name: Disable swap and remove /swapfile
shell: "[[ -f /swapfile ]] && (swapoff -a && rm -f /swapfile) || echo 'no swap file found'"
- name: Create /swapfile
shell: "fallocate -l {{ swap_size }} /swapfile"
- name: Set permissions on /swapfile
shell: "chmod 600 /swapfile"
- name: Make swap in /swapfile
shell: "mkswap /swapfile"
- name: Add /swapfile to fstab
lineinfile:
path: /etc/fstab
line: "/swapfile none swap sw 0 0"
- name: Enable swap
shell: "swapon -a"
| 489 | YAML | 23.499999 | 93 | 0.648262 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/password.yml | # set ubuntu user password to "ubuntu"
# this is supposed to change with userdata
- name: Create password hash
shell: python3 -c "import crypt; print(crypt.crypt('{{ system_user_password }}'))"
register: system_user_password_hash
- name: Set password for "{{ ansible_user }}" user
user:
name: "{{ ansible_user }}"
password: "{{ system_user_password_hash.stdout }}"
| 381 | YAML | 30.833331 | 84 | 0.682415 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
- name: Check OS name and version
assert: that="ansible_distribution == 'Ubuntu'"
# add extra ssh ports
- name: Change SSH port to {{ ssh_port }}
include: custom_ssh.yml
when: ssh_port != 22
- name: Upgrade the OS (apt-get dist-upgrade)
apt: upgrade=dist
update_cache=yes
- name: Set OS user password
include: password.yml
- name: Disable IPv6 for apt-get
copy:
dest: /etc/apt/apt.conf.d/99force-ipv4
src: etc.apt.apt.conf.d.99force-ipv4
mode: 0644
- name: Disable unattended upgrades
copy:
src: etc.apt.apt.conf.d.20auto-upgrades
dest: /etc/apt/apt.conf.d/20auto-upgrades
mode: 0644
# add packages for convinience
- name: Install common apt packages
apt: name=htop
state=latest
- name: Add user ubuntu to sudo group
user: name=ubuntu
groups=sudo
append=yes
state=present
- name: Check if reboot required
stat:
path: /var/run/reboot-required
register: reboot_required_file
- name: Reboot and wait
reboot:
post_reboot_delay: 5
connect_timeout: 3
reboot_timeout: 600
when: reboot_required_file.stat.exists == true
# - set hostname
# - set prompt color and hostname
- include: id.yml
# swap
- name: Check if swap is enabled
shell: "swapon -s | wc -l"
register: swap_enabled
tags:
- skip_in_image
- import_tasks: swap.yml
when: swap_enabled.stdout | int == 0
tags:
- skip_in_image
| 2,012 | YAML | 22.964285 | 74 | 0.704274 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/custom_ssh.yml | # change ssh port to custom value
- name: Set SSH port to {{ ssh_port }}
lineinfile:
path: /etc/ssh/sshd_config
line: "Port {{ item }}"
state: present
mode: 0644
with_items:
- "22"
- "{{ ssh_port }}"
- name: Create ufw profile for the custom ssh port
template: src=custom_ssh.ufwprofile
dest=/etc/ufw/applications.d/custom_ssh
mode=644
- name: Allow incoming connections to the custom ssh port
ufw: rule=allow name=custom_ssh
- name: Restart sshd
service: name=sshd state=restarted
- name: Make Ansible to use new ssh port
set_fact:
ansible_port: "{{ ssh_port }}"
| 617 | YAML | 21.888888 | 57 | 0.659643 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/defaults/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# ssh port (in addition to 22)
ssh_port: 22
# format that is accepted by fallocate
swap_size: 32G
# password for the system user
system_user_password:
| 767 | YAML | 29.719999 | 74 | 0.761408 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/handlers/main.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Restart NX server
service: >
name=nxserver
state=restarted
listen: nx_restart
| 712 | YAML | 31.409089 | 74 | 0.754213 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/novnc.yml | # Install noVNC
- name: Prerequisites
apt:
name: snapd
state: latest
# Install noVNC via snap package
- name: Install noVNC
snap:
name: novnc
state: present
- name: Add noVNC systemd config
template: src=novnc.service
dest=/etc/systemd/system
mode=0444
owner=root
group=root
- name: Start noVNC
systemd: name=novnc
daemon_reload=yes
enabled=yes
state=restarted
| 417 | YAML | 15.076922 | 32 | 0.676259 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/busid.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# update BusID in xorg.conf before GDM start
# executed from /etc/gdm3/PreSession/Default
- name: Create BusID updater
copy:
content: |
#!/bin/bash
BUS_ID=$(nvidia-xconfig --query-gpu-info | grep 'PCI BusID' | head -n 1 | cut -c15-)
sed -i "s/BusID.*$/BusID \"$BUS_ID\"/" /etc/X11/xorg.conf
dest: /opt/update-busid
mode: 0755
# add /opt/update-busid to /etc/gdm3/PreSession/Default
- name: Add BusID updater to /etc/gdm3/PreSession/Default
lineinfile:
path: /etc/gdm3/PreSession/Default
line: /opt/update-busid
insertafter: EOF
state: present
| 1,209 | YAML | 32.61111 | 90 | 0.715467 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/vnc.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
- name: Prerequisites (PIP packages)
pip:
name: "{{ item }}"
state: latest
with_items:
- pexpect
- name: Install x11vnc and helper util
apt: name={{ item }}
update_cache=yes
state=latest
with_items:
- x11vnc
- expect
- name: Add x11vnc systemd config
template: src=x11vnc-ubuntu.service
dest=/etc/systemd/system
mode=0444
owner=root
group=root
- name: Start x11vnc
systemd: name=x11vnc-ubuntu
daemon_reload=yes
enabled=yes
state=restarted
- name: Clear VNC password
file:
path: /home/ubuntu/.vnc/passwd
state: absent
- name: Set VNC password
expect:
command: /usr/bin/x11vnc -storepasswd
responses:
(?i).*password:.*: "{{ vnc_password }}\r"
(?i)write.*: "y\r"
creates: /home/ubuntu/.vnc/passwd
become_user: ubuntu
tags:
- skip_in_image
- name: Cleanup VNC password
file:
path: /home/ubuntu/.vnc/passwd
state: absent
tags:
- never
- cleanup
| 1,596 | YAML | 22.144927 | 74 | 0.679825 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/utils.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
# install extra packages
- name: Install extra packages
apt: name={{ item }}
state=latest
update_cache=yes
install_recommends=no
with_items:
- eog # EOG image viewer (https://help.gnome.org/users/eog/stable/)
| 843 | YAML | 32.759999 | 74 | 0.742586 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/vscode.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
- name: Prerequisites
apt:
name: snapd
state: latest
# install visual studio code
- name: Install Visual Studio Code
snap:
name: code
state: present
classic: yes
# install remote development extension pack
- name: Install Remote Development extension pack
shell: code --install-extension ms-vscode-remote.vscode-remote-extensionpack
become_user: "{{ ansible_user }}"
# make sure desktop directory exists
- name: Make sure desktop directory exists
file:
path: /home/{{ ansible_user }}/Desktop
state: directory
mode: 0755
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
# create a desktop shortcut for visual studio code
- name: Create desktop shortcut for Visual Studio Code
copy:
dest: /home/{{ ansible_user }}/Desktop/vscode.desktop
mode: 0755
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
content: |
[Desktop Entry]
Version=1.0
Type=Application
Name=Visual Studio Code
GenericName=Text Editor
Comment=Edit text files
Exec=/snap/bin/code --no-sandbox --unity-launch %F
Icon=/snap/code/current/meta/gui/vscode.png
StartupWMClass=Code
StartupNotify=true
Terminal=false
Categories=Utility;TextEditor;Development;IDE;
MimeType=text/plain;inode/directory;
Actions=new-empty-window;
Keywords=vscode;
become_user: "{{ ansible_user }}"
- name: Allow execution of desktop icon for Orbit
shell: gio set "/home/{{ ansible_user }}/Desktop/{{ item }}" metadata::trusted true
become_user: "{{ ansible_user }}"
with_items:
- vscode.desktop
| 2,237 | YAML | 29.657534 | 85 | 0.698257 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/nomachine.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
# @see https://downloads.nomachine.com/download/?id=2 for new versions
- name: Download NoMachine server
get_url:
url: https://download.nomachine.com/download/8.9/Linux/nomachine_8.9.1_1_amd64.deb
dest: /tmp/nomachine.deb
mode: 0644
timeout: 600 # 10 minutes
- name: Install NoMachine server
apt:
deb: /tmp/nomachine.deb
state: present
- name: Create NX config dir
file: >
path=/home/ubuntu/.nx/config
state=directory
owner=ubuntu
group=ubuntu
- name: Link authorized keys to NX config
file: >
src=/home/ubuntu/.ssh/authorized_keys
dest=/home/ubuntu/.nx/config/authorized.crt
state=link
owner=ubuntu
group=ubuntu
notify: nx_restart
# add env var DISPLAY to /usr/lib/systemd/system/nxserver.service
- name: Add DISPLAY env var to nxserver.service
lineinfile:
path: /usr/lib/systemd/system/nxserver.service
line: Environment="DISPLAY=:0"
insertafter: "\\[Service\\]"
state: present
# restart nxserver.service on GDM init (fix for "no display detected" error)
- name: Restart nxserver.service on GDM init
lineinfile:
path: /etc/gdm3/PreSession/Default
line: (/usr/bin/sleep 5 && /usr/bin/systemctl restart nxserver.service) &
insertafter: EOF
state: present
- name: Do daemon-reload
systemd:
daemon_reload: yes
| 1,946 | YAML | 28.059701 | 86 | 0.717883 |
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/virtual-display.yml | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
---
- name: Copy EDID file
template: src=vdisplay.edid
dest=/etc/X11/vdisplay.edid
mode=644
notify: reboot
- name: Get PCI Bus ID of the first GPU
shell: nvidia-xconfig --query-gpu-info | grep 'PCI BusID' | head -n 1 | cut -c15-
register: GPU0_PCI_BUS_ID
- name: Write X11 config
template: src=xorg.conf
dest=/etc/X11/xorg.conf
mode=644
notify: reboot
- name: Create Xauthority file
file:
path: /home/{{ ansible_user }}/.Xauthority
state: touch
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: 0666
| 1,179 | YAML | 27.780487 | 83 | 0.706531 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.