file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
selinaxiao/MeshToUsd/exts/mesh.to.usd/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "mesh to usd"
description="A simple python extension example to use as a starting point for your extensions."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import mesh.to.usd".
[[python.module]]
name = "mesh.to.usd"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,559 | TOML | 31.499999 | 118 | 0.741501 |
selinaxiao/MeshToUsd/exts/mesh.to.usd/mesh/to/usd/extension.py | import omni.ext
import omni.ui as ui
import omni.usd
#from .MeshGen.sdf_to_mesh import mc_result
from pxr import Gf, Sdf
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[mesh.to.usd] some_public_function was called with x: ", x)
return x ** x
# 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 MeshToUsdExtension(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("[mesh.to.usd] mesh to usd startup")
self._count = 0
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
label = ui.Label("")
def process(path):
infile = open(path,'r')
lines = infile.readlines()
for i in range(len(lines)):
lines[i] = lines[i].replace('\n','').split(' ')[1:]
if [] in lines:
lines.remove([])
idx1 = lines.index(['Normals'])
verts = lines[1:idx1]
float_verts = []
for i in range(len(verts)):
float_verts.append(Gf.Vec3f(float(verts[i][0]), float(verts[i][1]), float(verts[i][2])))
idx2 = lines.index(['Faces'])
normals = lines[idx1+1:idx2]
float_norms = []
print(normals)
for i in range(len(normals)):
float_norms.append(Gf.Vec3f(float(normals[i][0]), float(normals[i][1]), float(normals[i][2])))
float_norms.append(Gf.Vec3f(float(normals[i][0]), float(normals[i][1]), float(normals[i][2])))
float_norms.append(Gf.Vec3f(float(normals[i][0]), float(normals[i][1]), float(normals[i][2])))
faces = lines[idx2+1:]
int_faces = []
for i in range(len(faces)):
int_faces.append(int(faces[i][0]) - 1)
int_faces.append(int(faces[i][1]) - 1)
int_faces.append(int(faces[i][2]) - 1)
print(type(float_verts))
print(float_verts)
return float_verts, int_faces, float_norms
def assemble():
stage = omni.usd.get_context().get_stage()
if(not stage.GetPrimAtPath(Sdf.Path('/World/Trial')).IsValid()):
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
prim_path=None,
select_new_prim=True,
prepend_default_prim=True)
omni.kit.commands.execute('MovePrim',
path_from='/World/Cube',
path_to='/World/Trial',
destructive=False)
cube_prim = stage.GetPrimAtPath('/World/Trial')
verts, faces, normals = process('C:/users/labuser/desktop/data transfer/meshtousd/exts/mesh.to.usd/mesh/to/usd/whyyyyyyyareumeaningless.obj')
face_vert_count = [3]*(len(faces)//3)
primvar = [(0,0)]*len(faces)
print(type(cube_prim.GetAttribute('faceVertexIndices').Get()))
print(cube_prim.GetAttribute('faceVertexIndices').Get())
print(type(face_vert_count))
cube_prim.GetAttribute('faceVertexCounts').Set(face_vert_count)
cube_prim.GetAttribute('faceVertexIndices').Set(faces)
cube_prim.GetAttribute('normals').Set(normals)
cube_prim.GetAttribute('points').Set(verts)
cube_prim.GetAttribute('primvars:st').Set(primvar)
with ui.HStack():
ui.Button("TRANSFORMERS!!!", clicked_fn=assemble)
def on_shutdown(self):
print("[mesh.to.usd] mesh to usd shutdown")
| 4,616 | Python | 40.223214 | 161 | 0.513865 |
selinaxiao/MeshToUsd/exts/mesh.to.usd/mesh/to/usd/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
selinaxiao/MeshToUsd/exts/mesh.to.usd/mesh/to/usd/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
selinaxiao/MeshToUsd/exts/mesh.to.usd/mesh/to/usd/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import mesh.to.usd
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = mesh.to.usd.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,658 | Python | 34.297872 | 142 | 0.679131 |
selinaxiao/MeshToUsd/exts/mesh.to.usd/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
selinaxiao/MeshToUsd/exts/mesh.to.usd/docs/README.md | # Python Extension Example [mesh.to.usd]
This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
| 170 | Markdown | 33.199993 | 126 | 0.776471 |
selinaxiao/MeshToUsd/exts/mesh.to.usd/docs/index.rst | mesh.to.usd
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"mesh.to.usd"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 323 | reStructuredText | 14.428571 | 43 | 0.600619 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/README.md | # Info
This tool is provided by Loupe.
https://loupe.team
[email protected]
1-800-240-7042
# Description
This is an extension that connects Beckhoff PLCs into the Omniverse ecosystem. It leverages [pyads](https://github.com/stlehmann/pyads) to set up an ADS client for communicating with PLCs.
# Documentation
Detailed documentation can be found in the extension readme file [here](exts/loupe.simulation.beckhoff_bridge/docs/README.md).
# Licensing
This software contains source code provided by NVIDIA Corporation. This code is subject to the terms of the [NVIDIA Omniverse License Agreement](https://docs.omniverse.nvidia.com/isaacsim/latest/common/NVIDIA_Omniverse_License_Agreement.html). Files are licensed as follows:
### Files created entirely by Loupe ([MIT License](LICENSE)):
* `ads_driver.py`
* `BeckhoffBridge.py`
### Files including Nvidia-generated code and modifications by Loupe (Nvidia Omniverse License Agreement AND MIT License; use must comply to whichever is most restrictive for any attribute):
* `__init__.py`
* `extension.py`
* `global_variables.py`
* `ui_builder.py`
This software is intended for use with NVIDIA Omniverse apps, which are subject to the [NVIDIA Omniverse License Agreement](https://docs.omniverse.nvidia.com/isaacsim/latest/common/NVIDIA_Omniverse_License_Agreement.html) for use and distribution.
This software also relies on [pyads](https://github.com/stlehmann/pyads), which is licensed under the MIT license.
| 1,470 | Markdown | 44.968749 | 274 | 0.782313 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/exts/loupe.simulation.beckhoff_bridge/loupe/simulation/beckhoff_bridge/global_variables.py | # This software contains source code provided by NVIDIA Corporation.
# Copyright (c) 2022-2023, 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.
#
EXTENSION_TITLE = "Beckhoff Bridge"
EXTENSION_NAME = "loupe.simulation.beckhoff_bridge"
EXTENSION_DESCRIPTION = "Bridge to Beckhoff PLCs"
| 643 | Python | 39.249998 | 76 | 0.804044 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/exts/loupe.simulation.beckhoff_bridge/loupe/simulation/beckhoff_bridge/ads_driver.py | '''
File: **ads_driver.py**
Copyright (c) 2024 Loupe
https://loupe.team
This file is part of Omniverse_Beckhoff_Bridge_Extension, licensed under the MIT License.
'''
import pyads
class AdsDriver():
"""
A class that represents an ADS driver. It contains a list of variables to read from the target device and provides methods to read and write data.
Args:
ams_net_id (str): The AMS Net ID of the target device.
Attributes:
ams_net_id (str): The AMS Net ID of the target device.
_read_names (list): A list of names for reading data.
_read_struct_def (dict): A dictionary that maps names to structure definitions.
"""
def __init__(self, ams_net_id):
"""
Initializes an instance of the AdsDriver class.
Args:
ams_net_id (str): The AMS Net ID of the target device.
"""
self.ams_net_id = ams_net_id
self._read_names = list()
self._read_struct_def = dict()
def add_read(self, name : str, structure_def = None):
"""
Adds a variable to the list of data to read.
Args:
name (str): The name of the data to be read. "my_struct.my_array[0].my_var"
structure_def (optional): The structure definition of the data.
"""
if name not in self._read_names:
self._read_names.append(name)
if structure_def is not None:
if name not in self._read_struct_def:
self._read_struct_def[name] = structure_def
def write_data(self, data : dict ):
"""
Writes data to the target device.
Args:
data (dict): A dictionary containing the data to be written to the PLC
e.g.
data = {'MAIN.b_Execute': False, 'MAIN.str_TestString': 'Goodbye World', 'MAIN.r32_TestReal': 54.321}
"""
self._connection.write_list_by_name(data)
def read_data(self):
"""
Reads all variables from the cyclic read list.
Returns:
dict: A dictionary containing the parsed data.
"""
if self._read_names.__len__() > 0:
data = self._connection.read_list_by_name(self._read_names, structure_defs=self._read_struct_def)
parsed_data = dict()
for name in data.keys():
parsed_data = self._parse_name(parsed_data, name, data[name])
else:
parsed_data = dict()
return parsed_data
def _parse_name(self, name_dict, name, value):
"""
Convert a variable from a flat name to a dictionary based structure.
"my_struct.my_array[0].my_var: value" -> {"my_struct": {"my_array": [{"my_var": value}]}}
Args:
name_dict (dict): The dictionary to store the parsed data.
name (str): The name of the data item.
value: The value of the data item.
Returns:
dict: The updated name_dict.
"""
name_parts = name.split(".")
if len(name_parts) > 1:
if name_parts[0] not in name_dict:
name_dict[name_parts[0]] = dict()
if "[" in name_parts[1]:
array_name, index = name_parts[1].split("[")
index = int(index[:-1])
if array_name not in name_dict[name_parts[0]]:
name_dict[name_parts[0]][array_name] = []
if index >= len(name_dict[name_parts[0]][array_name]):
name_dict[name_parts[0]][array_name].extend([None] * (index - len(name_dict[name_parts[0]][array_name]) + 1))
name_dict[name_parts[0]][array_name][index] = self._parse_name(name_dict[name_parts[0]][array_name], "[" + str(index) + "]" + ".".join(name_parts[2:]), value)
else:
name_dict[name_parts[0]] = self._parse_name(name_dict[name_parts[0]], ".".join(name_parts[1:]), value)
else:
if "[" in name_parts[0]:
array_name, index = name_parts[0].split("[")
index = int(index[:-1])
if index >= len(name_dict):
name_dict.extend([None] * (index - len(name_dict) + 1))
name_dict[index] = value
return name_dict[index]
else:
name_dict[name_parts[0]] = value
return name_dict
def connect(self, ams_net_id = None):
"""
Connects to the target device.
Args:
ams_net_id (str): The AMS Net ID of the target device. This does not need to be provided if it was provided in the constructor and has not changed.
"""
if ams_net_id is not None:
self.ams_net_id = ams_net_id
self._connection = pyads.Connection(self.ams_net_id, pyads.PORT_TC3PLC1)
self._connection.open()
def disconnect(self):
"""
Disconnects from the target device.
"""
self._connection.close()
def is_connected(self):
"""
Returns the connection state.
Returns:
bool: True if the connection is open, False otherwise.
"""
try:
adsState, deviceState = self._connection.read_state()
return True
except Exception as e:
return False
| 5,344 | Python | 32.40625 | 174 | 0.54491 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/exts/loupe.simulation.beckhoff_bridge/loupe/simulation/beckhoff_bridge/extension.py | # This software contains source code provided by NVIDIA Corporation.
# Copyright (c) 2022-2023, 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.
#
import weakref
import asyncio
import gc
import omni
import omni.ui as ui
import omni.usd
import omni.timeline
import omni.kit.commands
from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription
from omni.usd import StageEventType
import omni.physx as _physx
from .global_variables import EXTENSION_TITLE, EXTENSION_DESCRIPTION
from .ui_builder import UIBuilder
"""
This file serves as a basic template for the standard boilerplate operations
that make a UI-based extension appear on the toolbar.
This implementation is meant to cover most use-cases without modification.
Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py
Most users will be able to make their desired UI extension by interacting solely with
UIBuilder.
This class sets up standard useful callback functions in UIBuilder:
on_menu_callback: Called when extension is opened
on_timeline_event: Called when timeline is stopped, paused, or played
on_stage_event: Called when stage is opened or closed
cleanup: Called when resources such as physics subscriptions should be cleaned up
build_ui: User function that creates the UI they want.
"""
class TestExtension(omni.ext.IExt):
def on_startup(self, ext_id: str):
"""Initialize extension and UI elements"""
# Events
self._usd_context = omni.usd.get_context()
# Build Window
self._window = ui.Window(
title=EXTENSION_TITLE, width=600, height=500, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.set_visibility_changed_fn(self._on_window)
# UI
self._models = {}
self._ext_id = ext_id
self._menu_items = [
MenuItemDescription(name="Open Bridge Settings", onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())
]
add_menu_items(self._menu_items, EXTENSION_TITLE)
# Filled in with User Functions
self.ui_builder = UIBuilder()
# Events
self._usd_context = omni.usd.get_context()
self._physxIFace = _physx.acquire_physx_interface()
self._physx_subscription = None
self._stage_event_sub = None
self._timeline = omni.timeline.get_timeline_interface()
def on_shutdown(self):
self._models = {}
remove_menu_items(self._menu_items, EXTENSION_TITLE)
if self._window:
self._window = None
self.ui_builder.cleanup()
gc.collect()
def _on_window(self, visible):
if self._window.visible:
# Subscribe to Stage and Timeline Events
self._usd_context = omni.usd.get_context()
events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = events.create_subscription_to_pop(self._on_stage_event)
stream = self._timeline.get_timeline_event_stream()
self._timeline_event_sub = stream.create_subscription_to_pop(self._on_timeline_event)
self._build_ui()
else:
self._usd_context = None
self._stage_event_sub = None
self._timeline_event_sub = None
def _build_ui(self):
with self._window.frame:
with ui.VStack(spacing=5, height=0):
self._build_extension_ui()
async def dock_window():
await omni.kit.app.get_app().next_update_async()
def dock(space, name, location, pos=0.5):
window = omni.ui.Workspace.get_window(name)
if window and space:
window.dock_in(space, location, pos)
return window
tgt = ui.Workspace.get_window("Viewport")
dock(tgt, EXTENSION_TITLE, omni.ui.DockPosition.LEFT, 0.33)
await omni.kit.app.get_app().next_update_async()
self._task = asyncio.ensure_future(dock_window())
#################################################################
# Functions below this point call user functions
#################################################################
def _menu_callback(self):
self._window.visible = not self._window.visible
self.ui_builder.on_menu_callback()
def _on_timeline_event(self, event):
self.ui_builder.on_timeline_event(event)
def _on_stage_event(self, event):
if event.type == int(StageEventType.OPENED) or event.type == int(StageEventType.CLOSED):
# stage was opened or closed, cleanup
self._physx_subscription = None
self.ui_builder.on_stage_event(event)
def _build_extension_ui(self):
# Call user function for building UI
self.ui_builder.build_ui()
| 5,199 | Python | 36.410072 | 121 | 0.647625 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/exts/loupe.simulation.beckhoff_bridge/loupe/simulation/beckhoff_bridge/__init__.py | # This software contains source code provided by NVIDIA Corporation.
# Copyright (c) 2022-2023, 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 *
| 528 | Python | 43.08333 | 76 | 0.806818 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/exts/loupe.simulation.beckhoff_bridge/loupe/simulation/beckhoff_bridge/BeckhoffBridge.py | '''
File: **BeckhoffBridge.py**
Copyright (c) 2024 Loupe
https://loupe.team
This file is part of Omniverse_Beckhoff_Bridge_Extension, licensed under the MIT License.
'''
from typing import Callable
import carb.events
import omni.kit.app
EVENT_TYPE_DATA_INIT = carb.events.type_from_string("loupe.simulation.beckhoff_bridge.DATA_INIT")
EVENT_TYPE_DATA_READ = carb.events.type_from_string("loupe.simulation.beckhoff_bridge.DATA_READ")
EVENT_TYPE_DATA_READ_REQ = carb.events.type_from_string("loupe.simulation.beckhoff_bridge.DATA_READ_REQ")
EVENT_TYPE_DATA_WRITE_REQ = carb.events.type_from_string("loupe.simulation.beckhoff_bridge.DATA_WRITE_REQ")
class Manager:
"""
BeckhoffBridge class provides an interface for interacting with the Beckhoff Bridge Extension.
It can be used in Python scripts to read and write variables.
Methods:
register_init_callback( callback : Callable[[carb.events.IEvent], None] ): Registers a callback function for the DATA_INIT event.
register_data_callback( callback : Callable[[carb.events.IEvent], None] ): Registers a callback function for the DATA_READ event.
add_cyclic_read_variables( variable_name_array : list[str]): Adds variables to the cyclic read list.
write_variable( name : str, value : any ): Writes a variable value to the Beckhoff Bridge.
"""
def __init__(self):
"""
Initializes the BeckhoffBridge object.
"""
self._event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._callbacks = []
def __del__(self):
"""
Cleans up the event subscriptions.
"""
for callback in self._callbacks:
self._event_stream.remove_subscription(callback)
def register_init_callback( self, callback : Callable[[carb.events.IEvent], None] ):
"""
Registers a callback function for the DATA_INIT event.
The callback is triggered when the Beckhoff Bridge is initialized.
The user should use this event to add cyclic read variables.
This event may get called multiple times in normal operation due to the nature of how extensions are loaded.
Args:
callback (function): The callback function to be registered.
Returns:
None
"""
self._callbacks.append(self._event_stream.create_subscription_to_push_by_type(EVENT_TYPE_DATA_INIT, callback))
callback(None)
def register_data_callback( self, callback : Callable[[carb.events.IEvent], None] ):
"""
Registers a callback function for the DATA_READ event.
The callback is triggered when the Beckhoff Bridge receives new data. The payload contains the updated variables.
Args:
callback (Callable): The callback function to be registered.
example callback:
def on_message( event ):
data = event.payload['data']['MAIN']['custom_struct']['var_array']
Returns:
None
"""
self._callbacks.append(self._event_stream.create_subscription_to_push_by_type(EVENT_TYPE_DATA_READ, callback))
def add_cyclic_read_variables(self, variable_name_array : list[str]):
"""
Adds variables to the cyclic read list.
Variables in the cyclic read list are read from the Beckhoff Bridge at a fixed interval.
Args:
variableList (list): List of variables to be added. ["MAIN.myStruct.myvar1", "MAIN.var2", ...]
Returns:
None
"""
self._event_stream.push(event_type=EVENT_TYPE_DATA_READ_REQ, payload={'variables': variable_name_array})
def write_variable(self, name : str, value : any ):
"""
Writes a variable value to the Beckhoff Bridge.
Args:
name (str): The name of the variable. "MAIN.myStruct.myvar1"
value (basic type): The value to be written. 1, 2.5, "Hello", ...
Returns:
None
"""
payload = {"variables": [{'name': name, 'value': value}]}
self._event_stream.push(event_type=EVENT_TYPE_DATA_WRITE_REQ, payload=payload)
| 4,182 | Python | 37.731481 | 137 | 0.649211 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/exts/loupe.simulation.beckhoff_bridge/loupe/simulation/beckhoff_bridge/ui_builder.py | # This software contains source code provided by NVIDIA Corporation.
# Copyright (c) 2022-2023, 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.
#
import omni.ui as ui
import omni.timeline
from carb.settings import get_settings
from .ads_driver import AdsDriver
from .global_variables import EXTENSION_NAME
from .BeckhoffBridge import EVENT_TYPE_DATA_READ, EVENT_TYPE_DATA_READ_REQ, EVENT_TYPE_DATA_WRITE_REQ, EVENT_TYPE_DATA_INIT
import threading
from threading import RLock
import json
import time
class UIBuilder:
def __init__(self):
# UI elements created using a UIElementWrapper instance
self.wrapped_ui_elements = []
# Get access to the timeline to control stop/pause/play programmatically
self._timeline = omni.timeline.get_timeline_interface()
# Get the settings interface
self.settings_interface = get_settings()
# Internal status flags.
self._thread_is_alive = True
self._communication_initialized = False
self._ui_initialized = False
# Configuration parameters for the extension.
# These are exposed on the UI.
self._enable_communication = self.get_setting( 'ENABLE_COMMUNICATION', False )
self._refresh_rate = self.get_setting( 'REFRESH_RATE', 20 )
# Data stream where the extension will dump the data that it reads from the PLC.
self._event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._ads_connector = AdsDriver(self.get_setting( 'PLC_AMS_NET_ID', '127.0.0.1.1.1'))
self.write_queue = dict()
self.write_lock = RLock()
self.read_req = self._event_stream.create_subscription_to_push_by_type(EVENT_TYPE_DATA_READ_REQ, self.on_read_req_event)
self.write_req = self._event_stream.create_subscription_to_push_by_type(EVENT_TYPE_DATA_WRITE_REQ, self.on_write_req_event)
self._event_stream.push(event_type=EVENT_TYPE_DATA_INIT, payload={'data': {}})
self._thread = threading.Thread(target=self._update_plc_data)
self._thread.start()
###################################################################################
# The Functions Below Are Called Automatically By extension.py
###################################################################################
def on_menu_callback(self):
"""Callback for when the UI is opened from the toolbar.
This is called directly after build_ui().
"""
self._event_stream.push(event_type=EVENT_TYPE_DATA_INIT, payload={'data': {}})
if(not self._thread_is_alive):
self._thread_is_alive = True
self._thread = threading.Thread(target=self._update_plc_data)
self._thread.start()
def on_timeline_event(self, event):
"""Callback for Timeline events (Play, Pause, Stop)
Args:
event (omni.timeline.TimelineEventType): Event Type
"""
if(event.type == int(omni.timeline.TimelineEventType.STOP)):
pass
elif(event.type == int(omni.timeline.TimelineEventType.PLAY)):
pass
elif(event.type == int(omni.timeline.TimelineEventType.PAUSE)):
pass
def on_stage_event(self, event):
"""Callback for Stage Events
Args:
event (omni.usd.StageEventType): Event Type
"""
pass
def cleanup(self):
"""
Called when the stage is closed or the extension is hot reloaded.
Perform any necessary cleanup such as removing active callback functions
"""
self.read_req.unsubscribe()
self.write_req.unsubscribe()
self._thread_is_alive = False
self._thread.join()
def build_ui(self):
"""
Build a custom UI tool to run your extension.
This function will be called any time the UI window is closed and reopened.
"""
with ui.CollapsableFrame("Configuration", collapsed=False):
with ui.VStack(spacing=5, height=0):
with ui.HStack(spacing=5, height=0):
ui.Label("Enable ADS Client")
self._enable_communication_checkbox = ui.CheckBox(ui.SimpleBoolModel(self._enable_communication))
self._enable_communication_checkbox.model.add_value_changed_fn(self._toggle_communication_enable)
with ui.HStack(spacing=5, height=0):
ui.Label("Refresh Rate (ms)")
self._refresh_rate_field = ui.IntField(ui.SimpleIntModel(self._refresh_rate))
self._refresh_rate_field.model.set_min(10)
self._refresh_rate_field.model.set_max(10000)
self._refresh_rate_field.model.add_value_changed_fn(self._on_refresh_rate_changed)
with ui.HStack(spacing=5, height=0):
ui.Label("PLC AMS Net Id")
self._plc_ams_net_id_field = ui.StringField(ui.SimpleStringModel(self._ads_connector.ams_net_id))
self._plc_ams_net_id_field.model.add_value_changed_fn(self._on_plc_ams_net_id_changed)
with ui.HStack(spacing=5, height=0):
ui.Label("Settings")
ui.Button("Load", clicked_fn=self.load_settings)
ui.Button("Save", clicked_fn=self.save_settings)
with ui.CollapsableFrame("Status", collapsed=False):
with ui.VStack(spacing=5, height=0):
with ui.HStack(spacing=5, height=0):
ui.Label("Status")
self._status_field = ui.StringField(ui.SimpleStringModel("n/a"), read_only=True)
with ui.CollapsableFrame("Monitor", collapsed=False):
with ui.VStack(spacing=5, height=0):
with ui.HStack(spacing=5, height=100):
ui.Label("Variables")
self._monitor_field = ui.StringField(ui.SimpleStringModel("{}"), multiline=True, read_only=True)
self._ui_initialized = True
####################################
####################################
# UTILITY FUNCTIONS
####################################
####################################
def on_read_req_event(self, event ):
event_data = event.payload
variables : list = event_data['variables']
for name in variables:
self._ads_connector.add_read(name)
def on_write_req_event(self, event ):
variables = event.payload["variables"]
for variable in variables:
self.queue_write(variable['name'], variable['value'])
def queue_write(self, name, value):
with self.write_lock:
self.write_queue[name] = value
def _update_plc_data(self):
thread_start_time = time.time()
status_update_time = time.time()
while self._thread_is_alive:
# Sleep for the refresh rate
sleepy_time = self._refresh_rate/1000 - (time.time() - thread_start_time)
if sleepy_time > 0:
time.sleep(sleepy_time)
else:
time.sleep(0.1)
thread_start_time = time.time()
# Check if the communication is enabled
if not self._enable_communication:
if self._ui_initialized:
self._status_field.model.set_value("Disabled")
self._monitor_field.model.set_value("{}")
continue
# Catch exceptions and log them to the status field
try:
# Start the communication if it is not initialized
if (not self._communication_initialized) and (self._enable_communication):
self._ads_connector.connect()
self._communication_initialized = True
elif (self._communication_initialized) and (not self._ads_connector.is_connected()):
self._ads_connector.disconnect()
if status_update_time < time.time():
if self._ads_connector.is_connected():
self._status_field.model.set_value("Connected")
else:
self._status_field.model.set_value("Attempting to connect...")
# Write data to the PLC if there is data to write
# If there is an exception, log it to the status field but continue reading data
try:
if self.write_queue:
with self.write_lock:
values = self.write_queue
self.write_queue = dict()
self._ads_connector.write_data(values)
except Exception as e:
if self._ui_initialized:
self._status_field.model.set_value(f"Error writing data to PLC: {e}")
status_update_time = time.time() + 1
# Read data from the PLC
self._data = self._ads_connector.read_data()
# Push the data to the event stream
self._event_stream.push(event_type=EVENT_TYPE_DATA_READ, payload={'data': self._data})
# Update the monitor field
if self._ui_initialized:
json_formatted_str = json.dumps(self._data, indent=4)
self._monitor_field.model.set_value(json_formatted_str)
except Exception as e:
if self._ui_initialized:
self._status_field.model.set_value(f"Error reading data from PLC: {e}")
status_update_time = time.time() + 1
time.sleep(1)
####################################
####################################
# Manage Settings
####################################
####################################
def get_setting(self, name, default_value=None ):
setting = self.settings_interface.get("/persistent/" + EXTENSION_NAME + "/" + name)
if setting is None:
setting = default_value
self.settings_interface.set("/persistent/" + EXTENSION_NAME + "/" + name, setting)
return setting
def set_setting(self, name, value ):
self.settings_interface.set("/persistent/" + EXTENSION_NAME + "/" + name, value)
def _on_plc_ams_net_id_changed(self, value):
self._ads_connector.ams_net_id = value.get_value_as_string()
self._communication_initialized = False
def _on_refresh_rate_changed(self, value):
self._refresh_rate = value.get_value_as_int()
def _toggle_communication_enable(self, state):
self._enable_communication = state.get_value_as_bool()
if not self._enable_communication:
self._communication_initialized = False
def save_settings(self):
self.set_setting('REFRESH_RATE', self._refresh_rate)
self.set_setting('PLC_AMS_NET_ID', self._ads_connector.ams_net_id)
self.set_setting('ENABLE_COMMUNICATION', self._enable_communication)
def load_settings(self):
self._refresh_rate = self.get_setting('REFRESH_RATE')
self._ads_connector.ams_net_id = self.get_setting('PLC_AMS_NET_ID')
self._enable_communication = self.get_setting('ENABLE_COMMUNICATION')
self._refresh_rate_field.model.set_value(self._refresh_rate)
self._plc_ams_net_id_field.model.set_value(self._ads_connector.ams_net_id)
self._enable_communication_checkbox.model.set_value(self._enable_communication)
self._communication_initialized = False
| 12,107 | Python | 41.335664 | 131 | 0.572148 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/exts/loupe.simulation.beckhoff_bridge/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "0.1.0"
category = "simulation"
title = "Beckhoff Bridge"
description = "A bridge for connecting Omniverse to Beckhoff PLCs over ADS"
authors = ["Loupe"]
repository = "https://github.com/loupeteam/Omniverse_Beckhoff_Bridge_Extension"
keywords = ["Beckhoff", "Digital Twin", "ADS", "PLC"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.kit.uiapp" = {}
[python.pipapi]
requirements = ['pyads']
use_online_index = true
[[python.module]]
name = "loupe.simulation.beckhoff_bridge"
public = true | 639 | TOML | 21.857142 | 79 | 0.716745 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/exts/loupe.simulation.beckhoff_bridge/docs/CHANGELOG.md | Changelog
[0.1.0]
- Created with based functionality to setup a connection and send/receive messages with other extensions. | 125 | Markdown | 30.499992 | 105 | 0.8 |
loupeteam/Omniverse_Beckhoff_Bridge_Extension/exts/loupe.simulation.beckhoff_bridge/docs/README.md | # Beckhoff Bridge
The Beckhoff Bridge is an [NVIDIA Omniverse](https://www.nvidia.com/en-us/omniverse/) extension for communicating with [Beckhoff PLCs](https://www.beckhoff.com/en-en/) using the [ADS protocol](https://infosys.beckhoff.com/english.php?content=../content/1033/cx8190_hw/5091854987.html&id=).
# Installation
### Install from registry
This is the preferred method. Open up the extensions manager by navigating to `Window / Extensions`. The extension is available as a "Third Party" extension. Search for `Beckhoff Bridge`, and click the slider to Enable it. Once enabled, the extension will be available as an option in the top menu banner of the Omniverse app.
### Install from source
You can also install from source instead. In order to do so, follow these steps:
- Clone the repo [here](https://github.com/loupeteam/Omniverse_Beckhoff_Bridge_Extension).
- In your Omniverse app, open the extensions manager by navigating to `Window / Extensions`.
- Open the general extension settings, and add a new entry into the `Extension Search Paths` table. This should be the local path to the root of the repo that was just cloned.
- Back in the extensions manager, search for `BECKHOFF BRIDGE`, and enable it.
- Once enabled, the extension will show up as an option in the top menu banner.
# Configuration
You can open the extension by clicking on `Beckhoff Bridge / Open Bridge Settings` from the top menu. The following configuration options are available:
- Enable ADS Client: Enable or disable the ADS client from reading or writing data to the PLC.
- Refresh Rate: The rate at which the ADS client will read data from the PLC in milliseconds.
- PLC AMS Net ID: The AMS Net ID of the PLC to connect to.
- Settings commands: These commands are used to load and save the extension settings as permanent parameters. The Save button backs up the current parameters, and the Load button restores them from the last saved values.
# Usage
Once the extension is enabled, the Beckhoff Bridge will attempt to connect to the PLC.
### Monitoring Extension Status
The status of the extension can be viewed in the `Status` field. Here are the possible messages and their meaning:
- `Disabled`: the enable checkbox is unchecked, and no communication is attempted.
- `Attempting to connect...`: the ADS client is trying to connect to the PLC. Staying in this state for more than a few seconds indicates that there is a problem with the connection.
- `Connected`: the ADS client has successfully established a connection with the PLC.
- `Error writing data to the PLC: [...]`: an error occurred while performing an ADS variable write.
- `Error reading data from the PLC: [...]`: an error occurred while performing an ADS variable read.
### Monitoring Variable Values
Once variable reads are occurring, the `Monitor` pane will show a JSON string with the names and values of the variables being read. This is helpful for troubleshooting.
### Performing read/write operations
The variables on the PLC that should be read or written are specified in a custom user extension or app that uses the API available from the `loupe.simulation.beckhoff_bridge` module.
```python
from loupe.simulation.beckhoff_bridge import BeckhoffBridge
# Instantiate the bridge and register lifecycle subscriptions
beckhoff_bridge = BeckhoffBridge.Manager()
beckhoff_bridge.register_init_callback(on_beckoff_init)
beckhoff_bridge.register_data_callback(on_message)
# This function gets called once on init, and should be used to subscribe to cyclic reads.
def on_beckoff_init( event ):
# Create a list of variable names to be read cyclically, and add to Manager
variables = [ 'MAIN.custom_struct.var1',
'MAIN.custom_struct.var_array[0]',
'MAIN.custom_struct.var_array[1]']
beckhoff_bridge.add_cyclic_read_variables(variables)
# This function is called every time the bridge receives new data
def on_message( event ):
# Read the event data, which includes values for the PLC variables requested
data = event.payload['data']['MAIN']['custom_struct']['var_array']
# In the app's cyclic logic, writes can be performed as follows:
def cyclic():
# Write the value `1` to PLC variable 'MAIN.custom_struct.var1'
beckhoff_bridge.write_variable('MAIN.custom_struct.var1', 1)
``` | 4,351 | Markdown | 55.51948 | 326 | 0.759136 |
claudia6657/Omniverse-Extension-Sample-UI/README.md | #Modify by Claudia
# 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,756 | Markdown | 51.274725 | 215 | 0.776283 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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") == "":
self._window = None
return
elif "WindowTrigger" in self.model.get_item("name"):
print("selected!")
self._window = ui.Window("Control Panel", width=300, height=200, flags=ui.WINDOW_FLAGS_NO_TITLE_BAR)
self._window.frame.set_style({
"Window":{
"background_color": 0xB7000000,
}
})
return
else:
self._window = None
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,572 | Python | 43.111111 | 112 | 0.603024 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
claudia6657/Omniverse-Extension-Sample-UI/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 |
shazanfazal/Test-omniverse/README.md | # Extension Project Template
This project was automatically generated.
- `app` - It is a folder link to the location of your *Omniverse Kit* based app.
- `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path).
Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better.
Look for "shazan.extension" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately.
Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.:
```
> app\omni.code.bat --ext-folder exts --enable company.hello.world
```
# App Link Setup
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
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:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Sharing Your Extensions
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
| 2,040 | Markdown | 37.509433 | 258 | 0.757353 |
shazanfazal/Test-omniverse/tools/scripts/link_app.py | import argparse
import json
import os
import sys
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,814 | Python | 32.117647 | 133 | 0.562189 |
shazanfazal/Test-omniverse/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 |
shazanfazal/Test-omniverse/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 shutil
import sys
import tempfile
import zipfile
__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,844 | Python | 33.166666 | 108 | 0.703362 |
shazanfazal/Test-omniverse/exts/shazan.extension/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "shazan extension"
description="A simple python extension example to use as a starting point for your extensions."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import shazan.extension".
[[python.module]]
name = "shazan.extension"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,574 | TOML | 31.812499 | 118 | 0.74587 |
shazanfazal/Test-omniverse/exts/shazan.extension/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
shazanfazal/Test-omniverse/exts/shazan.extension/docs/README.md | # Python Extension Example [shazan.extension]
This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
| 175 | Markdown | 34.199993 | 126 | 0.788571 |
shazanfazal/Test-omniverse/exts/shazan.extension/docs/index.rst | shazan.extension
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"shazan.extension"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 333 | reStructuredText | 14.904761 | 43 | 0.618619 |
shazanfazal/Test-omniverse/exts/shazan.extension/shazan/extension/extension.py | import omni.ext
import omni.ui as ui
import omni.kit.commands as command
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[shazan.extension] some_public_function was called with x: ", x)
return x ** x
# 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 ShazanExtensionExtension(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("[shazan.extension] shazan extension startup")
self._window = ui.Window("Learning Extension", width=300, height=300)
with self._window.frame:
with ui.VStack():
def on_click(prim_type):
command.execute("CreateMeshPrimWithDefaultXform",prim_type=prim_type)
ui.Label("Create me the following")
ui.Button("Create a Cone",clicked_fn=lambda: on_click("Cone"))
ui.Button("Create a Cube",clicked_fn=lambda: on_click("Cube"))
ui.Button("Create a Cylinder",clicked_fn=lambda: on_click("Cylinder"))
ui.Button("Create a Disk",clicked_fn=lambda: on_click("Disk"))
ui.Button("Create a Plane",clicked_fn=lambda: on_click("Plane"))
ui.Button("Create a Sphere",clicked_fn=lambda: on_click("Sphere"))
ui.Button("Create a Torus",clicked_fn=lambda: on_click("Torus"))
def on_shutdown(self):
print("[shazan.extension] shazan extension shutdown")
| 1,884 | Python | 47.333332 | 119 | 0.663482 |
shazanfazal/Test-omniverse/exts/shazan.extension/shazan/extension/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
shazanfazal/Test-omniverse/exts/shazan.extension/shazan/extension/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
shazanfazal/Test-omniverse/exts/shazan.extension/shazan/extension/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import shazan.extension
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = shazan.extension.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,668 | Python | 34.510638 | 142 | 0.682254 |
pascal-roth/orbit_envs/README.md | <div style="display: flex;">
<img src="docs/example_matterport.png" alt="Matterport Mesh" style="width: 48%; padding: 5px;">
<img src="docs/example_carla.png" alt="Unreal Engine / Carla Mesh" style="width: 48%; padding: 5px;">
</div>
---
# Omniverse Matterport3D and Unreal Engine Assets Extensions
[](https://docs.omniverse.nvidia.com/isaacsim/latest/overview.html)
[](https://docs.python.org/3/whatsnew/3.10.html)
[](https://releases.ubuntu.com/20.04/)
[](https://pre-commit.com/)
[](https://opensource.org/licenses/BSD-3-Clause)
This repository contains the extensions for Matterport3D and Unreal Engine Assets.
The extensions enable the easy loading of assets into Isaac Sim and have access to the semantic labels.
They are developed as part of the ViPlanner project ([Paper](https://arxiv.org/abs/2310.00982) | [Code](https://github.com/leggedrobotics/viplanner))
and are based on the [Orbit](https://isaac-orbit.github.io/) framework.
**Attention:**
The central part of the extensions is currently updated to the latest orbit version.
This repo contains a temporary solution sufficient for the demo script included in ViPlanner, found [here](https://github.com/leggedrobotics/viplanner/tree/main/omniverse).
An updated version will be available soon.
## Installation
To install the extensions, follow these steps:
1. Install Isaac Sim using the [Orbit installation guide](https://isaac-orbit.github.io/orbit/source/setup/installation.html).
2. Clone the orbit repo and link the extension.
```
git clone [email protected]:NVIDIA-Omniverse/orbit.git
cd orbit/source/extensions
ln -s {ORBIT_ENVS_PROJECT_DIR}/extensions/omni.isaac.matterport .
ln -s {ORBIT_ENVS_PROJECT_DIR}/extensions/omni.isaac.carla .
```
4. Then run the orbit installer script.
```
./orbit.sh -i -e
```
## Usage
For the Matterport extension, a GUI interface is available. To use it, start the simulation:
```
./orbit.sh -s
```
Then, in the GUI, go to `Window -> Extensions` and type `Matterport` in the search bar. You should see the Matterport3D extension.
Enable it to open the GUI interface.
To use both as part of an Orbit workflow, please refer to the [ViPlanner Demo](https://github.com/leggedrobotics/viplanner/tree/main/omniverse).
## <a name="CitingViPlanner"></a>Citing
If you use this code in a scientific publication, please cite the following [paper](https://arxiv.org/abs/2310.00982):
```
@article{roth2023viplanner,
title ={ViPlanner: Visual Semantic Imperative Learning for Local Navigation},
author ={Pascal Roth and Julian Nubert and Fan Yang and Mayank Mittal and Marco Hutter},
journal = {2024 IEEE International Conference on Robotics and Automation (ICRA)},
year = {2023},
month = {May},
}
```
### License
This code belongs to the Robotic Systems Lab, ETH Zurich.
All right reserved
**Authors: [Pascal Roth](https://github.com/pascal-roth)<br />
Maintainer: Pascal Roth, [email protected]**
This repository contains research code, except that it changes often, and any fitness for a particular purpose is disclaimed.
| 3,457 | Markdown | 40.66265 | 172 | 0.74718 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/setup.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Installation script for the 'omni.isaac.matterport' python package."""
from setuptools import setup
# Minimum dependencies required prior to installation
INSTALL_REQUIRES = [
# generic
"trimesh",
"PyQt5",
"matplotlib>=3.5.0",
"pandas",
]
# Installation operation
setup(
name="omni-isaac-matterport",
author="Pascal Roth",
author_email="[email protected]",
version="0.0.1",
description="Extension to include Matterport 3D Datasets into Isaac (taken from https://niessner.github.io/Matterport/).",
keywords=["robotics"],
include_package_data=True,
python_requires=">=3.7",
install_requires=INSTALL_REQUIRES,
packages=["omni.isaac.matterport"],
classifiers=["Natural Language :: English", "Programming Language :: Python :: 3.7"],
zip_safe=False,
)
# EOF
| 967 | Python | 24.473684 | 126 | 0.688728 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/config/extension.toml | [package]
version = "0.0.1"
title = "Matterport extension"
description="Extension to include Matterport 3D Datasets into Isaac"
authors =["Pascal Roth"]
repository = "https://github.com/leggedrobotics/omni_isaac_orbit"
category = "robotics"
keywords = ["kit", "robotics"]
readme = "docs/README.md"
[dependencies]
"omni.kit.uiapp" = {}
"omni.isaac.ui" = {}
"omni.isaac.core" = {}
"omni.isaac.orbit" = {}
# Main python module this extension provides.
[[python.module]]
name = "omni.isaac.matterport"
[[python.module]]
name = "omni.isaac.matterport.scripts"
| 559 | TOML | 23.347825 | 68 | 0.710197 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/domains/__init__.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import os
DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../data"))
from .matterport_importer import MatterportImporter
from .matterport_raycast_camera import MatterportRayCasterCamera
from .matterport_raycaster import MatterportRayCaster
from .raycaster_cfg import MatterportRayCasterCfg
__all__ = [
"MatterportRayCasterCamera",
"MatterportImporter",
"MatterportRayCaster",
"MatterportRayCasterCfg",
"DATA_DIR",
]
# EoF
| 617 | Python | 23.719999 | 87 | 0.73906 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/domains/matterport_raycast_camera.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import os
from typing import ClassVar, Sequence
import carb
import numpy as np
import omni.isaac.orbit.utils.math as math_utils
import pandas as pd
import torch
import trimesh
import warp as wp
from omni.isaac.matterport.domains import DATA_DIR
from omni.isaac.orbit.sensors import RayCasterCamera, RayCasterCameraCfg
from omni.isaac.orbit.utils.warp import raycast_mesh
from tensordict import TensorDict
class MatterportRayCasterCamera(RayCasterCamera):
UNSUPPORTED_TYPES: ClassVar[dict] = {
"rgb",
"instance_id_segmentation",
"instance_segmentation",
"skeleton_data",
"motion_vectors",
"bounding_box_2d_tight",
"bounding_box_2d_loose",
"bounding_box_3d",
}
"""Data types that are not supported by the ray-caster."""
face_id_category_mapping: ClassVar[dict] = {}
"""Mapping from face id to semantic category id."""
def __init__(self, cfg: RayCasterCameraCfg):
# initialize base class
super().__init__(cfg)
def _check_supported_data_types(self, cfg: RayCasterCameraCfg):
# check if there is any intersection in unsupported types
# reason: we cannot obtain this data from simplified warp-based ray caster
common_elements = set(cfg.data_types) & MatterportRayCasterCamera.UNSUPPORTED_TYPES
if common_elements:
raise ValueError(
f"RayCasterCamera class does not support the following sensor types: {common_elements}."
"\n\tThis is because these sensor types cannot be obtained in a fast way using ''warp''."
"\n\tHint: If you need to work with these sensor types, we recommend using the USD camera"
" interface from the omni.isaac.orbit.sensors.camera module."
)
def _initialize_impl(self):
super()._initialize_impl()
# load categort id to class mapping (name and id of mpcat40 redcued class set)
# More Information: https://github.com/niessner/Matterport/blob/master/data_organization.md#house_segmentations
mapping = pd.read_csv(DATA_DIR + "/mappings/category_mapping.tsv", sep="\t")
self.mapping_mpcat40 = torch.tensor(mapping["mpcat40index"].to_numpy(), device=self._device, dtype=torch.long)
self._color_mapping()
def _color_mapping(self):
# load defined colors for mpcat40
mapping_40 = pd.read_csv(DATA_DIR + "/mappings/mpcat40.tsv", sep="\t")
color = mapping_40["hex"].to_numpy()
self.color = torch.tensor(
[(int(color[i][1:3], 16), int(color[i][3:5], 16), int(color[i][5:7], 16)) for i in range(len(color))],
device=self._device,
dtype=torch.uint8,
)
def _initialize_warp_meshes(self):
# check if mesh is already loaded
for mesh_prim_path in self.cfg.mesh_prim_paths:
if (
mesh_prim_path in MatterportRayCasterCamera.meshes
and mesh_prim_path in MatterportRayCasterCamera.face_id_category_mapping
):
continue
# find ply
if os.path.isabs(mesh_prim_path):
file_path = mesh_prim_path
assert os.path.isfile(mesh_prim_path), f"No .ply file found under absolute path: {mesh_prim_path}"
else:
file_path = os.path.join(DATA_DIR, mesh_prim_path)
assert os.path.isfile(
file_path
), f"No .ply file found under relative path to extension data: {file_path}"
# load ply
curr_trimesh = trimesh.load(file_path)
if mesh_prim_path not in MatterportRayCasterCamera.meshes:
# Convert trimesh into wp mesh
mesh_wp = wp.Mesh(
points=wp.array(curr_trimesh.vertices.astype(np.float32), dtype=wp.vec3, device=self._device),
indices=wp.array(curr_trimesh.faces.astype(np.int32).flatten(), dtype=int, device=self._device),
)
# save mesh
MatterportRayCasterCamera.meshes[mesh_prim_path] = mesh_wp
if mesh_prim_path not in MatterportRayCasterCamera.face_id_category_mapping:
# create mapping from face id to semantic categroy id
# get raw face information
faces_raw = curr_trimesh.metadata["_ply_raw"]["face"]["data"]
carb.log_info(f"Raw face information of type {faces_raw.dtype}")
# get face categories
face_id_category_mapping = torch.tensor(
[single_face[3] for single_face in faces_raw], device=self._device
)
# save mapping
MatterportRayCasterCamera.face_id_category_mapping[mesh_prim_path] = face_id_category_mapping
def _update_buffers_impl(self, env_ids: Sequence[int]):
"""Fills the buffers of the sensor data."""
# increment frame count
self._frame[env_ids] += 1
# compute poses from current view
pos_w, quat_w = self._compute_camera_world_poses(env_ids)
# update the data
self._data.pos_w[env_ids] = pos_w
self._data.quat_w_world[env_ids] = quat_w
# note: full orientation is considered
ray_starts_w = math_utils.quat_apply(quat_w.repeat(1, self.num_rays), self.ray_starts[env_ids])
ray_starts_w += pos_w.unsqueeze(1)
ray_directions_w = math_utils.quat_apply(quat_w.repeat(1, self.num_rays), self.ray_directions[env_ids])
# ray cast and store the hits
# TODO: Make ray-casting work for multiple meshes?
# necessary for regular dictionaries.
self.ray_hits_w, ray_depth, ray_normal, ray_face_ids = raycast_mesh(
ray_starts_w,
ray_directions_w,
mesh=RayCasterCamera.meshes[self.cfg.mesh_prim_paths[0]],
max_dist=self.cfg.max_distance,
return_distance=any(
[name in self.cfg.data_types for name in ["distance_to_image_plane", "distance_to_camera"]]
),
return_normal="normals" in self.cfg.data_types,
return_face_id="semantic_segmentation" in self.cfg.data_types,
)
# update output buffers
if "distance_to_image_plane" in self.cfg.data_types:
# note: data is in camera frame so we only take the first component (z-axis of camera frame)
distance_to_image_plane = (
math_utils.quat_apply(
math_utils.quat_inv(quat_w).repeat(1, self.num_rays),
(ray_depth[:, :, None] * ray_directions_w),
)
)[:, :, 0]
self._data.output["distance_to_image_plane"][env_ids] = distance_to_image_plane.view(-1, *self.image_shape)
if "distance_to_camera" in self.cfg.data_types:
self._data.output["distance_to_camera"][env_ids] = ray_depth.view(-1, *self.image_shape)
if "normals" in self.cfg.data_types:
self._data.output["normals"][env_ids] = ray_normal.view(-1, *self.image_shape, 3)
if "semantic_segmentation" in self._data.output.keys(): # noqa: SIM118
# get the category index of the hit faces (category index from unreduced set = ~1600 classes)
face_id = MatterportRayCasterCamera.face_id_category_mapping[self.cfg.mesh_prim_paths[0]][
ray_face_ids.flatten().type(torch.long)
]
# map category index to reduced set
face_id_mpcat40 = self.mapping_mpcat40[face_id.type(torch.long) - 1]
# get the color of the face
face_color = self.color[face_id_mpcat40]
# reshape and transpose to get the correct orientation
self._data.output["semantic_segmentation"][env_ids] = face_color.view(-1, *self.image_shape, 3)
def _create_buffers(self):
"""Create the buffers to store data."""
# prepare drift
self.drift = torch.zeros(self._view.count, 3, device=self.device)
# create the data object
# -- pose of the cameras
self._data.pos_w = torch.zeros((self._view.count, 3), device=self._device)
self._data.quat_w_world = torch.zeros((self._view.count, 4), device=self._device)
# -- intrinsic matrix
self._data.intrinsic_matrices = torch.zeros((self._view.count, 3, 3), device=self._device)
self._data.intrinsic_matrices[:, 2, 2] = 1.0
self._data.image_shape = self.image_shape
# -- output data
# create the buffers to store the annotator data.
self._data.output = TensorDict({}, batch_size=self._view.count, device=self.device)
self._data.info = [{name: None for name in self.cfg.data_types}] * self._view.count
for name in self.cfg.data_types:
if name in ["distance_to_image_plane", "distance_to_camera"]:
shape = (self.cfg.pattern_cfg.height, self.cfg.pattern_cfg.width)
dtype = torch.float32
elif name in ["normals"]:
shape = (self.cfg.pattern_cfg.height, self.cfg.pattern_cfg.width, 3)
dtype = torch.float32
elif name in ["semantic_segmentation"]:
shape = (self.cfg.pattern_cfg.height, self.cfg.pattern_cfg.width, 3)
dtype = torch.uint8
else:
raise ValueError(f"Unknown data type: {name}")
# store the data
self._data.output[name] = torch.zeros((self._view.count, *shape), dtype=dtype, device=self._device)
| 9,752 | Python | 46.808823 | 119 | 0.608901 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/domains/raycaster_cfg.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.sensors.ray_caster import RayCasterCfg
from omni.isaac.orbit.utils import configclass
from .matterport_raycaster import MatterportRayCaster
@configclass
class MatterportRayCasterCfg(RayCasterCfg):
"""Configuration for the ray-cast sensor for Matterport Environments."""
class_type = MatterportRayCaster
"""Name of the specific matterport ray caster class."""
| 539 | Python | 27.421051 | 76 | 0.779221 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/domains/matterport_importer.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import builtins
# python
import os
from typing import TYPE_CHECKING
# omni
import carb
import omni.isaac.core.utils.prims as prim_utils
import omni.isaac.core.utils.stage as stage_utils
# isaac-orbit
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.core.simulation_context import SimulationContext
from omni.isaac.orbit.terrains import TerrainImporter
if TYPE_CHECKING:
from omni.isaac.matterport.config import MatterportImporterCfg
# omniverse
from omni.isaac.core.utils import extensions
extensions.enable_extension("omni.kit.asset_converter")
import omni.kit.asset_converter as converter
class MatterportConverter:
def __init__(self, input_obj: str, context: converter.impl.AssetConverterContext) -> None:
self._input_obj = input_obj
self._context = context
# setup converter
self.task_manager = converter.extension.AssetImporterExtension()
return
async def convert_asset_to_usd(self) -> None:
# get usd file path and create directory
base_path, _ = os.path.splitext(self._input_obj)
# set task
task = self.task_manager.create_converter_task(
self._input_obj, base_path + ".usd", asset_converter_context=self._context
)
success = await task.wait_until_finished()
# print error
if not success:
detailed_status_code = task.get_status()
detailed_status_error_string = task.get_error_message()
carb.log_error(
f"Failed to convert {self._input_obj} to {base_path + '.usd'} "
f"with status {detailed_status_code} and error {detailed_status_error_string}"
)
return
class MatterportImporter(TerrainImporter):
"""
Default stairs environment for testing
"""
cfg: MatterportImporterCfg
def __init__(self, cfg: MatterportImporterCfg) -> None:
"""
:param
"""
# store inputs
self.cfg = cfg
self.device = SimulationContext.instance().device
# create a dict of meshes
self.meshes = dict()
self.warp_meshes = dict()
self.env_origins = None
self.terrain_origins = None
# import the world
if not self.cfg.terrain_type == "matterport":
raise ValueError(
"MatterportImporter can only import 'matterport' data. Given terrain type "
f"'{self.cfg.terrain_type}'is not supported."
)
if builtins.ISAAC_LAUNCHED_FROM_TERMINAL is False:
self.load_world()
else:
carb.log_info("[INFO]: Loading in extension mode requires calling 'load_world_async'")
if isinstance(self.cfg.num_envs, int):
self.configure_env_origins()
# set initial state of debug visualization
self.set_debug_vis(self.cfg.debug_vis)
# Converter
self.converter: MatterportConverter = MatterportConverter(self.cfg.obj_filepath, self.cfg.asset_converter)
return
async def load_world_async(self) -> None:
"""Function called when clicking load button"""
# create world
await self.load_matterport()
# update stage for any remaining process.
await stage_utils.update_stage_async()
# Now we are ready!
carb.log_info("[INFO]: Setup complete...")
return
def load_world(self) -> None:
"""Function called when clicking load button"""
# create world
self.load_matterport_sync()
# update stage for any remaining process.
stage_utils.update_stage()
# Now we are ready!
carb.log_info("[INFO]: Setup complete...")
return
async def load_matterport(self) -> None:
_, ext = os.path.splitext(self.cfg.obj_filepath)
# if obj mesh --> convert to usd
if ext == ".obj":
await self.converter.convert_asset_to_usd()
# add mesh to stage
self.load_matterport_sync()
def load_matterport_sync(self) -> None:
base_path, _ = os.path.splitext(self.cfg.obj_filepath)
assert os.path.exists(base_path + ".usd"), (
"Matterport load sync can only handle '.usd' files not obj files. "
"Please use the async function to convert the obj file to usd first (accessed over the extension in the GUI)"
)
self._xform_prim = prim_utils.create_prim(
prim_path=self.cfg.prim_path + "/Matterport", translation=(0.0, 0.0, 0.0), usd_path=base_path + ".usd"
)
# apply collider properties
collider_cfg = sim_utils.CollisionPropertiesCfg(collision_enabled=True)
sim_utils.define_collision_properties(self._xform_prim.GetPrimPath(), collider_cfg)
# create physics material
physics_material_cfg: sim_utils.RigidBodyMaterialCfg = self.cfg.physics_material
# spawn the material
physics_material_cfg.func(f"{self.cfg.prim_path}/physicsMaterial", self.cfg.physics_material)
sim_utils.bind_physics_material(self._xform_prim.GetPrimPath(), f"{self.cfg.prim_path}/physicsMaterial")
# add colliders and physics material
if self.cfg.groundplane:
ground_plane_cfg = sim_utils.GroundPlaneCfg(physics_material=self.cfg.physics_material)
ground_plane = ground_plane_cfg.func("/World/GroundPlane", ground_plane_cfg)
ground_plane.visible = False
return
| 5,626 | Python | 33.734568 | 121 | 0.640775 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/domains/matterport_raycaster.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import os
from typing import TYPE_CHECKING
import numpy as np
import trimesh
import warp as wp
from omni.isaac.matterport.domains import DATA_DIR
from omni.isaac.orbit.sensors.ray_caster import RayCaster
if TYPE_CHECKING:
from .raycaster_cfg import MatterportRayCasterCfg
class MatterportRayCaster(RayCaster):
"""A ray-casting sensor for matterport meshes.
The ray-caster uses a set of rays to detect collisions with meshes in the scene. The rays are
defined in the sensor's local coordinate frame. The sensor can be configured to ray-cast against
a set of meshes with a given ray pattern.
The meshes are parsed from the list of primitive paths provided in the configuration. These are then
converted to warp meshes and stored in the `warp_meshes` list. The ray-caster then ray-casts against
these warp meshes using the ray pattern provided in the configuration.
.. note::
Currently, only static meshes are supported. Extending the warp mesh to support dynamic meshes
is a work in progress.
"""
cfg: MatterportRayCasterCfg
"""The configuration parameters."""
def __init__(self, cfg: MatterportRayCasterCfg):
"""Initializes the ray-caster object.
Args:
cfg (MatterportRayCasterCfg): The configuration parameters.
"""
# initialize base class
super().__init__(cfg)
def _initialize_warp_meshes(self):
# check if mesh is already loaded
for mesh_prim_path in self.cfg.mesh_prim_paths:
if mesh_prim_path in MatterportRayCaster.meshes:
continue
# find ply
if os.path.isabs(mesh_prim_path):
file_path = mesh_prim_path
assert os.path.isfile(mesh_prim_path), f"No .ply file found under absolute path: {mesh_prim_path}"
else:
file_path = os.path.join(DATA_DIR, mesh_prim_path)
assert os.path.isfile(
file_path
), f"No .ply file found under relative path to extension data: {file_path}"
# load ply
curr_trimesh = trimesh.load(file_path)
# Convert trimesh into wp mesh
mesh_wp = wp.Mesh(
points=wp.array(curr_trimesh.vertices.astype(np.float32), dtype=wp.vec3, device=self._device),
indices=wp.array(curr_trimesh.faces.astype(np.int32).flatten(), dtype=int, device=self._device),
)
# save mesh
MatterportRayCaster.meshes[mesh_prim_path] = mesh_wp
| 2,745 | Python | 35.131578 | 114 | 0.654281 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/scripts/matterport_domains.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from typing import Dict
import carb
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import omni
import torch
from omni.isaac.matterport.domains.matterport_raycast_camera import (
MatterportRayCasterCamera,
)
from omni.isaac.orbit.sensors.camera import CameraData
from omni.isaac.orbit.sensors.ray_caster import RayCasterCfg
from omni.isaac.orbit.sim import SimulationContext
from .ext_cfg import MatterportExtConfig
mpl.use("Qt5Agg")
class MatterportDomains:
"""
Load Matterport3D Semantics and make them available to Isaac Sim
"""
def __init__(self, cfg: MatterportExtConfig):
"""
Initialize MatterportSemWarp
Args:
path (str): path to Matterport3D Semantics
"""
self._cfg: MatterportExtConfig = cfg
# setup camera list
self.cameras: Dict[str, MatterportRayCasterCamera] = {}
# setup camera visualization
self.figures = {}
# internal parameters
self.callback_set = False
self.vis_init = False
self.prev_position = torch.zeros(3)
self.prev_orientation = torch.zeros(4)
# add callbacks for stage play/stop
physx_interface = omni.physx.acquire_physx_interface()
self._initialize_handle = physx_interface.get_simulation_event_stream_v2().create_subscription_to_pop_by_type(
int(omni.physx.bindings._physx.SimulationEvent.RESUMED), self._initialize_callback
)
self._invalidate_initialize_handle = (
physx_interface.get_simulation_event_stream_v2().create_subscription_to_pop_by_type(
int(omni.physx.bindings._physx.SimulationEvent.STOPPED), self._invalidate_initialize_callback
)
)
return
##
# Public Methods
##
def register_camera(self, cfg: RayCasterCfg):
"""
Register a camera to the MatterportSemWarp
"""
# append to camera list
self.cameras[cfg.prim_path] = MatterportRayCasterCamera(cfg)
##
# Callback Setup
##
def _invalidate_initialize_callback(self, val):
if self.callback_set:
self._sim.remove_render_callback("matterport_update")
self.callback_set = False
def _initialize_callback(self, val):
if self.callback_set:
return
# check for camera
if len(self.cameras) == 0:
carb.log_warn("No cameras added! Add cameras first, then enable the callback!")
return
# get SimulationContext
if SimulationContext.instance():
self._sim: SimulationContext = SimulationContext.instance()
else:
carb.log_error("No Simulation Context found! Matterport Callback not attached!")
# add callback
self._sim.add_render_callback("matterport_update", callback_fn=self._update)
self.callback_set = True
##
# Callback Function
##
def _update(self, dt: float):
for camera in self.cameras.values():
camera.update(dt.payload["dt"])
if self._cfg.visualize:
vis_prim = self._cfg.visualize_prim if self._cfg.visualize_prim else list(self.cameras.keys())[0]
if torch.all(self.cameras[vis_prim].data.pos_w.cpu() == self.prev_position) and torch.all(
self.cameras[vis_prim].data.quat_w_world.cpu() == self.prev_orientation
):
return
self._update_visualization(self.cameras[vis_prim].data)
self.prev_position = self.cameras[vis_prim].data.pos_w.clone().cpu()
self.prev_orientation = self.cameras[vis_prim].data.quat_w_world.clone().cpu()
##
# Private Methods (Helper Functions)
##
# Visualization helpers ###
def _init_visualization(self, data: CameraData):
"""Initializes the visualization plane."""
# init depth figure
self.n_bins = 500 # Number of bins in the colormap
self.color_array = mpl.colormaps["gist_rainbow"](np.linspace(0, 1, self.n_bins)) # Colormap
if "semantic_segmentation" in data.output.keys(): # noqa: SIM118
# init semantics figure
fg_sem = plt.figure()
ax_sem = fg_sem.gca()
ax_sem.set_title("Semantic Segmentation")
img_sem = ax_sem.imshow(data.output["semantic_segmentation"][0].cpu().numpy())
self.figures["semantics"] = {"fig": fg_sem, "axis": ax_sem, "img": img_sem}
if "distance_to_image_plane" in data.output.keys(): # noqa: SIM118
# init semantics figure
fg_depth = plt.figure()
ax_depth = fg_depth.gca()
ax_depth.set_title("Distance To Image Plane")
img_depth = ax_depth.imshow(self.convert_depth_to_color(data.output["distance_to_image_plane"][0]))
self.figures["depth"] = {"fig": fg_depth, "axis": ax_depth, "img": img_depth}
if len(self.figures) > 0:
plt.ion()
# update flag
self.vis_init = True
def _update_visualization(self, data: CameraData) -> None:
"""
Updates the visualization plane.
"""
if self.vis_init is False:
self._init_visualization(data)
else:
# SEMANTICS
if "semantic_segmentation" in data.output.keys(): # noqa: SIM118
self.figures["semantics"]["img"].set_array(data.output["semantic_segmentation"][0].cpu().numpy())
self.figures["semantics"]["fig"].canvas.draw()
self.figures["semantics"]["fig"].canvas.flush_events()
# DEPTH
if "distance_to_image_plane" in data.output.keys(): # noqa: SIM118
# cam_data.img_depth.set_array(cam_data.render_depth)
self.figures["depth"]["img"].set_array(
self.convert_depth_to_color(data.output["distance_to_image_plane"][0])
)
self.figures["depth"]["fig"].canvas.draw()
self.figures["depth"]["fig"].canvas.flush_events()
plt.pause(1e-6)
def convert_depth_to_color(self, depth_img):
depth_img = depth_img.cpu().numpy()
depth_img[~np.isfinite(depth_img)] = depth_img.max()
depth_img_flattend = np.clip(depth_img.flatten(), a_min=0, a_max=depth_img.max())
depth_img_flattend = np.round(depth_img_flattend / depth_img.max() * (self.n_bins - 1)).astype(np.int32)
depth_colors = self.color_array[depth_img_flattend]
depth_colors = depth_colors.reshape(depth_img.shape[0], depth_img.shape[1], 4)
return depth_colors
| 6,788 | Python | 35.5 | 118 | 0.610784 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/scripts/ext_cfg.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# python
from dataclasses import dataclass
from omni.isaac.matterport.config.importer_cfg import MatterportImporterCfg
@dataclass
class MatterportExtConfig:
# config classes
importer: MatterportImporterCfg = MatterportImporterCfg()
# semantic and depth information (can be changed individually for each camera)
visualize: bool = False
visualize_prim: str = None
# set value functions
def set_friction_dynamic(self, value: float):
self.importer.physics_material.dynamic_friction = value
def set_friction_static(self, value: float):
self.importer.physics_material.static_friction = value
def set_restitution(self, value: float):
self.importer.physics_material.restitution = value
def set_friction_combine_mode(self, value: int):
self.importer.physics_material.friction_combine_mode = value
def set_restitution_combine_mode(self, value: int):
self.importer.physics_material.restitution_combine_mode = value
def set_improved_patch_friction(self, value: bool):
self.importer.physics_material.improve_patch_friction = value
def set_obj_filepath(self, value: str):
self.importer.obj_filepath = value
def set_prim_path(self, value: str):
self.importer.prim_path = value
def set_visualize(self, value: bool):
self.visualize = value
def set_visualization_prim(self, value: str):
self.visualize_prim = value
| 1,596 | Python | 30.313725 | 82 | 0.716165 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/scripts/__init__.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from .matterport_ext import MatterPortExtension
__all__ = ["MatterPortExtension"]
| 225 | Python | 21.599998 | 53 | 0.746667 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/scripts/matterport_ext.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import asyncio
import gc
# python
import os
import carb
# omni
import omni
import omni.client
import omni.ext
import omni.isaac.core.utils.prims as prim_utils
import omni.isaac.core.utils.stage as stage_utils
# isaac-core
import omni.ui as ui
from omni.isaac.matterport.domains import MatterportImporter
from omni.isaac.orbit.sensors.ray_caster import RayCasterCfg, patterns
from omni.isaac.orbit.sim import SimulationCfg, SimulationContext
# omni-isaac-ui
from omni.isaac.ui.ui_utils import (
btn_builder,
cb_builder,
dropdown_builder,
float_builder,
get_style,
int_builder,
setup_ui_headers,
str_builder,
)
# omni-isaac-matterport
from .ext_cfg import MatterportExtConfig
from .matterport_domains import MatterportDomains
EXTENSION_NAME = "Matterport Importer"
def is_mesh_file(path: str) -> bool:
_, ext = os.path.splitext(path.lower())
return ext in [".obj", ".usd"]
def is_ply_file(path: str) -> bool:
_, ext = os.path.splitext(path.lower())
return ext in [".ply"]
def on_filter_obj_item(item) -> bool:
if not item or item.is_folder:
return not (item.name == "Omniverse" or item.path.startswith("omniverse:"))
return is_mesh_file(item.path)
def on_filter_ply_item(item) -> bool:
if not item or item.is_folder:
return not (item.name == "Omniverse" or item.path.startswith("omniverse:"))
return is_ply_file(item.path)
class MatterPortExtension(omni.ext.IExt):
"""Extension to load Matterport 3D Environments into Isaac Sim"""
def on_startup(self, ext_id):
self._ext_id = ext_id
self._usd_context = omni.usd.get_context()
self._window = omni.ui.Window(
EXTENSION_NAME, width=400, height=500, visible=True, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
# init config class and get path to extension
self._config = MatterportExtConfig()
self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
# set additional parameters
self._input_fields: dict = {} # dictionary to store values of buttion, float fields, etc.
self.domains: MatterportDomains = None # callback class for semantic rendering
self.ply_proposal: str = ""
# build ui
self.build_ui()
return
##
# UI Build functions
##
def build_ui(self, build_cam: bool = False, build_viz: bool = False):
with self._window.frame:
with ui.VStack(spacing=5, height=0):
self._build_info_ui()
self._build_import_ui()
if build_cam:
self._build_camera_ui()
if build_viz:
self._build_viz_ui()
async def dock_window():
await omni.kit.app.get_app().next_update_async()
def dock(space, name, location, pos=0.5):
window = omni.ui.Workspace.get_window(name)
if window and space:
window.dock_in(space, location, pos)
return window
tgt = ui.Workspace.get_window("Viewport")
dock(tgt, EXTENSION_NAME, omni.ui.DockPosition.LEFT, 0.33)
await omni.kit.app.get_app().next_update_async()
self._task = asyncio.ensure_future(dock_window())
def _build_info_ui(self):
title = EXTENSION_NAME
doc_link = "https://github.com/leggedrobotics/omni_isaac_orbit"
overview = "This utility is used to import Matterport3D Environments into Isaac Sim. "
overview += "The environment and additional information are available at https://github.com/niessner/Matterport"
overview += "\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
return
def _build_import_ui(self):
frame = ui.CollapsableFrame(
title="Import Dataset",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
# PhysicsMaterial
self._input_fields["friction_dynamic"] = float_builder(
"Dynamic Friction",
default_val=self._config.importer.physics_material.dynamic_friction,
tooltip=f"Sets the dynamic friction of the physics material (default: {self._config.importer.physics_material.dynamic_friction})",
)
self._input_fields["friction_dynamic"].add_value_changed_fn(
lambda m, config=self._config: config.set_friction_dynamic(m.get_value_as_float())
)
self._input_fields["friction_static"] = float_builder(
"Static Friction",
default_val=self._config.importer.physics_material.static_friction,
tooltip=f"Sets the static friction of the physics material (default: {self._config.importer.physics_material.static_friction})",
)
self._input_fields["friction_static"].add_value_changed_fn(
lambda m, config=self._config: config.set_friction_static(m.get_value_as_float())
)
self._input_fields["restitution"] = float_builder(
"Restitution",
default_val=self._config.importer.physics_material.restitution,
tooltip=f"Sets the restitution of the physics material (default: {self._config.importer.physics_material.restitution})",
)
self._input_fields["restitution"].add_value_changed_fn(
lambda m, config=self._config: config.set_restitution(m.get_value_as_float())
)
friction_restitution_options = ["average", "min", "multiply", "max"]
dropdown_builder(
"Friction Combine Mode",
items=friction_restitution_options,
default_val=friction_restitution_options.index(
self._config.importer.physics_material.friction_combine_mode
),
on_clicked_fn=lambda mode_str, config=self._config: config.set_friction_combine_mode(mode_str),
tooltip=f"Sets the friction combine mode of the physics material (default: {self._config.importer.physics_material.friction_combine_mode})",
)
dropdown_builder(
"Restitution Combine Mode",
items=friction_restitution_options,
default_val=friction_restitution_options.index(
self._config.importer.physics_material.restitution_combine_mode
),
on_clicked_fn=lambda mode_str, config=self._config: config.set_restitution_combine_mode(mode_str),
tooltip=f"Sets the friction combine mode of the physics material (default: {self._config.importer.physics_material.restitution_combine_mode})",
)
cb_builder(
label="Improved Patch Friction",
tooltip=f"Sets the improved patch friction of the physics material (default: {self._config.importer.physics_material.improve_patch_friction})",
on_clicked_fn=lambda m, config=self._config: config.set_improved_patch_friction(m),
default_val=self._config.importer.physics_material.improve_patch_friction,
)
# Set prim path for environment
self._input_fields["prim_path"] = str_builder(
"Prim Path of the Environment",
tooltip="Prim path of the environment",
default_val=self._config.importer.prim_path,
)
self._input_fields["prim_path"].add_value_changed_fn(
lambda m, config=self._config: config.set_prim_path(m.get_value_as_string())
)
# read import location
def check_file_type(model=None):
path = model.get_value_as_string()
if is_mesh_file(path):
self._input_fields["import_btn"].enabled = True
self._make_ply_proposal(path)
self._config.set_obj_filepath(path)
else:
self._input_fields["import_btn"].enabled = False
carb.log_warn(f"Invalid path to .obj file: {path}")
kwargs = {
"label": "Input File",
"default_val": self._config.importer.obj_filepath,
"tooltip": "Click the Folder Icon to Set Filepath",
"use_folder_picker": True,
"item_filter_fn": on_filter_obj_item,
"bookmark_label": "Included Matterport3D meshs",
"bookmark_path": f"{self._extension_path}/data/mesh",
"folder_dialog_title": "Select .obj File",
"folder_button_title": "*.obj, *.usd",
}
self._input_fields["input_file"] = str_builder(**kwargs)
self._input_fields["input_file"].add_value_changed_fn(check_file_type)
self._input_fields["import_btn"] = btn_builder(
"Import", text="Import", on_clicked_fn=self._start_loading
)
self._input_fields["import_btn"].enabled = False
return
def _build_camera_ui(self):
frame = ui.CollapsableFrame(
title="Add Camera",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
# get import location and save directory
kwargs = {
"label": "Input ply File",
"default_val": self.ply_proposal,
"tooltip": "Click the Folder Icon to Set Filepath",
"use_folder_picker": True,
"item_filter_fn": on_filter_ply_item,
"bookmark_label": "Included Matterport3D Point-Cloud with semantic labels",
"bookmark_path": f"{self._extension_path}/data/mesh",
"folder_dialog_title": "Select .ply Point-Cloud File",
"folder_button_title": "Select .ply Point-Cloud",
}
self._input_fields["input_ply_file"] = str_builder(**kwargs)
# data fields parameters
self._input_fields["camera_semantics"] = cb_builder(
label="Enable Semantics",
tooltip="Enable access to the semantics information of the mesh (default: True)",
default_val=True,
)
self._input_fields["camera_depth"] = cb_builder(
label="Enable Distance to Camera Frame",
tooltip="Enable access to the depth information of the mesh - no additional compute effort (default: True)",
default_val=True,
)
# add camera sensor for which semantics and depth should be rendered
kwargs = {
"label": "Camera Prim Path",
"type": "stringfield",
"default_val": "",
"tooltip": "Enter Camera Prim Path",
"use_folder_picker": False,
}
self._input_fields["camera_prim"] = str_builder(**kwargs)
self._input_fields["camera_prim"].add_value_changed_fn(self.activate_load_camera)
self._input_fields["cam_height"] = int_builder(
"Camera Height in Pixels",
default_val=480,
tooltip="Set the height of the camera image plane in pixels (default: 480)",
)
self._input_fields["cam_width"] = int_builder(
"Camera Width in Pixels",
default_val=640,
tooltip="Set the width of the camera image plane in pixels (default: 640)",
)
self._input_fields["load_camera"] = btn_builder(
"Add Camera", text="Add Camera", on_clicked_fn=self._register_camera
)
self._input_fields["load_camera"].enabled = False
return
def _build_viz_ui(self):
frame = ui.CollapsableFrame(
title="Visualization",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
cb_builder(
label="Visualization",
tooltip=f"Visualize Semantics and/or Depth (default: {self._config.visualize})",
on_clicked_fn=lambda m, config=self._config: config.set_visualize(m),
default_val=self._config.visualize,
)
dropdown_builder(
"Shown Camera Prim",
items=list(self.domains.cameras.keys()),
default_val=0,
on_clicked_fn=lambda mode_str, config=self._config: config.set_visualization_prim(mode_str),
tooltip="Select the camera prim shown in the visualization window",
)
##
# Shutdown Helpers
##
def on_shutdown(self):
if self._window:
self._window = None
gc.collect()
stage_utils.clear_stage()
if self.domains is not None and self.domains.callback_set:
self.domains.set_domain_callback(True)
##
# Path Helpers
##
def _make_ply_proposal(self, path: str) -> None:
"""use default matterport datastructure to make proposal about point-cloud file
- "env_id"
- matterport_mesh
- "id_nbr"
- "id_nbr".obj
- house_segmentations
- "env_id".ply
"""
file_dir, file_name = os.path.split(path)
ply_dir = os.path.join(file_dir, "../..", "house_segmentations")
env_id = file_dir.split("/")[-3]
try:
ply_file = os.path.join(ply_dir, f"{env_id}.ply")
os.path.isfile(ply_file)
carb.log_verbose(f"Found ply file: {ply_file}")
self.ply_proposal = ply_file
except FileNotFoundError:
carb.log_verbose("No ply file found in default matterport datastructure")
##
# Load Mesh and Point-Cloud
##
async def load_matterport(self):
# simulation settings
# check if simulation context was created earlier or not.
if SimulationContext.instance():
SimulationContext.clear_instance()
carb.log_warn("SimulationContext already loaded. Will clear now and init default SimulationContext")
# create new simulation context
self.sim = SimulationContext(SimulationCfg())
# initialize simulation
await self.sim.initialize_simulation_context_async()
# load matterport
self._matterport = MatterportImporter(self._config.importer)
await self._matterport.load_world_async()
# reset the simulator
# note: this plays the simulator which allows setting up all the physics handles.
await self.sim.reset_async()
await self.sim.pause_async()
def _start_loading(self):
path = self._config.importer.obj_filepath
if not path:
return
# find obj, usd file
if os.path.isabs(path):
file_path = path
assert os.path.isfile(file_path), f"No .obj or .usd file found under absolute path: {file_path}"
else:
file_path = os.path.join(self._extension_path, "data", path)
assert os.path.isfile(
file_path
), f"No .obj or .usd file found under relative path to extension data: {file_path}"
self._config.set_obj_filepath(file_path) # update config
carb.log_verbose("MatterPort 3D Mesh found, start loading...")
asyncio.ensure_future(self.load_matterport())
carb.log_info("MatterPort 3D Mesh loaded")
self.build_ui(build_cam=True)
self._input_fields["import_btn"].enabled = False
##
# Register Cameras
##
def activate_load_camera(self, val):
self._input_fields["load_camera"].enabled = True
def _register_camera(self):
ply_filepath = self._input_fields["input_ply_file"].get_value_as_string()
if not is_ply_file(ply_filepath):
carb.log_error("Given ply path is not valid! No camera created!")
camera_path = self._input_fields["camera_prim"].get_value_as_string()
if not prim_utils.is_prim_path_valid(camera_path): # create prim if no prim found
prim_utils.create_prim(camera_path, "Xform")
camera_semantics = self._input_fields["camera_semantics"].get_value_as_bool()
camera_depth = self._input_fields["camera_depth"].get_value_as_bool()
camera_width = self._input_fields["cam_width"].get_value_as_int()
camera_height = self._input_fields["cam_height"].get_value_as_int()
# Setup camera sensor
data_types = []
if camera_semantics:
data_types += ["semantic_segmentation"]
if camera_depth:
data_types += ["distance_to_image_plane"]
camera_pattern_cfg = patterns.PinholeCameraPatternCfg(
focal_length=24.0,
horizontal_aperture=20.955,
height=camera_height,
width=camera_width,
data_types=data_types,
)
camera_cfg = RayCasterCfg(
prim_path=camera_path,
mesh_prim_paths=[ply_filepath],
update_period=0,
offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 0.0), rot=(1.0, 0.0, 0.0, 0.0)),
debug_vis=True,
pattern_cfg=camera_pattern_cfg,
)
if self.domains is None:
self.domains = MatterportDomains(self._config)
# register camera
self.domains.register_camera(camera_cfg)
# initialize physics handles
self.sim.reset()
# allow for tasks
self.build_ui(build_cam=True, build_viz=True)
return
| 19,441 | Python | 40.190678 | 163 | 0.569621 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/config/importer_cfg.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from omni.isaac.core.utils import extensions
from omni.isaac.matterport.domains import MatterportImporter
from omni.isaac.orbit.terrains import TerrainImporterCfg
from omni.isaac.orbit.utils import configclass
from typing_extensions import Literal
extensions.enable_extension("omni.kit.asset_converter")
from omni.kit.asset_converter.impl import AssetConverterContext
# NOTE: hopefully will be soon changed to dataclass, then initialization can be improved
asset_converter_cfg: AssetConverterContext = AssetConverterContext()
asset_converter_cfg.ignore_materials = False
# Don't import/export materials
asset_converter_cfg.ignore_animations = False
# Don't import/export animations
asset_converter_cfg.ignore_camera = False
# Don't import/export cameras
asset_converter_cfg.ignore_light = False
# Don't import/export lights
asset_converter_cfg.single_mesh = False
# By default, instanced props will be export as single USD for reference. If
# this flag is true, it will export all props into the same USD without instancing.
asset_converter_cfg.smooth_normals = True
# Smoothing normals, which is only for assimp backend.
asset_converter_cfg.export_preview_surface = False
# Imports material as UsdPreviewSurface instead of MDL for USD export
asset_converter_cfg.use_meter_as_world_unit = True
# Sets world units to meters, this will also scale asset if it's centimeters model.
asset_converter_cfg.create_world_as_default_root_prim = True
# Creates /World as the root prim for Kit needs.
asset_converter_cfg.embed_textures = True
# Embedding textures into output. This is only enabled for FBX and glTF export.
asset_converter_cfg.convert_fbx_to_y_up = False
# Always use Y-up for fbx import.
asset_converter_cfg.convert_fbx_to_z_up = True
# Always use Z-up for fbx import.
asset_converter_cfg.keep_all_materials = False
# If it's to remove non-referenced materials.
asset_converter_cfg.merge_all_meshes = False
# Merges all meshes to single one if it can.
asset_converter_cfg.use_double_precision_to_usd_transform_op = False
# Uses double precision for all transform ops.
asset_converter_cfg.ignore_pivots = False
# Don't export pivots if assets support that.
asset_converter_cfg.disabling_instancing = False
# Don't export instancing assets with instanceable flag.
asset_converter_cfg.export_hidden_props = False
# By default, only visible props will be exported from USD exporter.
asset_converter_cfg.baking_scales = False
# Only for FBX. It's to bake scales into meshes.
@configclass
class MatterportImporterCfg(TerrainImporterCfg):
class_type: type = MatterportImporter
"""The class name of the terrain importer."""
terrain_type: Literal["matterport"] = "matterport"
"""The type of terrain to generate. Defaults to "matterport".
"""
prim_path: str = "/World/Matterport"
"""The absolute path of the Matterport Environment prim.
All sub-terrains are imported relative to this prim path.
"""
obj_filepath: str = MISSING
asset_converter: AssetConverterContext = asset_converter_cfg
groundplane: bool = True
| 3,241 | Python | 38.536585 | 88 | 0.779081 |
pascal-roth/orbit_envs/extensions/omni.isaac.matterport/omni/isaac/matterport/config/__init__.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from .importer_cfg import AssetConverterContext, MatterportImporterCfg
__all__ = ["MatterportImporterCfg", "AssetConverterContext"]
| 275 | Python | 26.599997 | 70 | 0.770909 |
pascal-roth/orbit_envs/extensions/omni.isaac.carla/setup.py | # Copyright (c) 2024 ETH Zurich (Robotic Systems Lab)
# Author: Pascal Roth
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Installation script for the 'omni.isaac.carla' python package."""
from setuptools import setup
# Minimum dependencies required prior to installation
INSTALL_REQUIRES = [
# generic
"opencv-python-headless",
"PyQt5",
]
# Installation operation
setup(
name="omni-isaac-carla",
author="Pascal Roth",
author_email="[email protected]",
version="0.0.1",
description="Extension to include 3D Datasets from the Carla Simulator.",
keywords=["robotics"],
include_package_data=True,
python_requires=">=3.7",
install_requires=INSTALL_REQUIRES,
packages=["omni.isaac.carla"],
classifiers=["Natural Language :: English", "Programming Language :: Python :: 3.7"],
zip_safe=False,
)
| 872 | Python | 24.67647 | 89 | 0.692661 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.