file_path
stringlengths
21
224
content
stringlengths
0
80.8M
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.1.0" # The title and description fields are primarily for displaying extension info in UI title = "API Connect Sample" description="A sample extension that demonstrate how to connect to an API. In this sample we use the HueMint.com API to generate a set of colors." # 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"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.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 omni.example.apiconnect". [[python.module]] name = "omni.example.apiconnect" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/extension.py
# SPDX-License-Identifier: Apache-2.0 import asyncio import aiohttp import carb import omni.ext import omni.ui as ui class APIWindowExample(ui.Window): def __init__(self, title: str, **kwargs) -> None: """ Initialize the widget. Args: title : Title of the widget. This is used to display the window title on the GUI. """ super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) # async function to get the color palette from huemint.com and print it async def get_colors_from_api(self, color_widgets): """ Get colors from HueMint API and store them in color_widgets. Args: color_widgets : List of widgets to """ # Create the task for progress indication and change button text self.button.text = "Loading" task = asyncio.create_task(self.run_forever()) # Create a aiohttp session to make the request, building the url and the data to send # By default it will timeout after 5 minutes. # See more here: https://docs.aiohttp.org/en/latest/client_quickstart.html async with aiohttp.ClientSession() as session: url = "https://api.huemint.com/color" data = { "mode": "transformer", # transformer, diffusion or random "num_colors": "5", # max 12, min 2 "temperature": "1.2", # max 2.4, min 0 "num_results": "1", # max 50 for transformer, 5 for diffusion "adjacency": ["0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0", ], # nxn adjacency matrix as a flat array of strings "palette": ["-", "-", "-", "-", "-"], # locked colors as hex codes, or '-' if blank } # make the request try: async with session.post(url, json=data) as resp: # get the response as json result = await resp.json(content_type=None) # get the palette from the json palette = result["results"][0]["palette"] # apply the colors to the color widgets await self.apply_colors(palette, color_widgets) # Cancel the progress indication and return the button to the original text task.cancel() self.button.text = "Refresh" except Exception as e: carb.log_info(f"Caught Exception {e}") # Cancel the progress indication and return the button to the original text task.cancel() self.button.text = "Connection Timed Out \nClick to Retry" # apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): """ Apply the colors to the ColorWidget. This is a helper method to allow us to get the color values from the API and set them in the color widgets Args: palette : The palette that we want to apply color_widgets : The list of color widgets """ colors = [palette[i] for i in range(5)] index = 0 # This will fetch the RGB colors from the color widgets and set them to the color of the color widget. for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() # we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) # we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 async def run_forever(self): """ Run the loop until we get a response from omni. """ count = 0 dot_count = 0 # Update the button text. while True: # Reset the button text to Loading if count % 10 == 0: # Reset the text for the button # Add a dot after Loading. if dot_count == 3: self.button.text = "Loading" dot_count = 0 # Add a dot after Loading else: self.button.text += "." dot_count += 1 count += 1 await omni.kit.app.get_app().next_update_async() # hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): """ Convert hex values to floating point numbers. This is useful for color conversion to a 3 or 5 digit hex value Args: h : RGB string in the format 0xRRGGBB Returns: float tuple of ( r g b ) where r g b are floats between 0 and 1 and b """ # Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i : i + 2], 16) / 255.0 for i in (1, 3, 5)) # skip '#' def _build_fn(self): """ Build the function to call the api when the app starts. """ with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): # Get the run loop run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette", height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1, 1, 1) for i in range(5)] def on_click(): """ Get colors from API and run task in run_loop. This is called when user clicks the button """ run_loop.create_task(self.get_colors_from_api(color_widgets)) # create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) # we execute the api call once on startup run_loop.create_task(self.get_colors_from_api(color_widgets)) # 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 on_startup(self, ext_id): """ Called when the extension is started. Args: ext_id - id of the extension """ print("[omni.example.apiconnect] MyExtension startup") # create a new window self._window = APIWindowExample("API Connect Demo - HueMint", width=260, height=270) def on_shutdown(self): """ Called when the extension is shut down. Destroys the window if it exists and sets it to None """ print("[omni.example.apiconnect] MyExtension shutdown") # Destroys the window and releases the reference to the window. if self._window: self._window.destroy() self._window = None
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/__init__.py
# SPDX-License-Identifier: Apache-2.0 from .extension import *
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/tests/__init__.py
from .test_hello_world import *
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/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 omni.example.apiconnect # 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 = omni.example.apiconnect.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")
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2022-10-07 ### Added - Initial version of extension ## [1.1.0] - 2023-10-17 ### Added - Step by Step tutorial - APIWindowExample class - Progress indicator when the API is being called - `next_update_async()` to prevent the App from hanging ### Changed - Updated README - Sizing of UI is dynamic rather than static - Using `create_task` rather than `ensure_future` - Moved Window functionality into it's own class - Moved outer functions to Window Class ### Removed - Unused imports
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/docs/README.md
# API Connection (omni.example.apiconnect) ![](../data/preview.gif) ​ ## Overview This Extension makes a single API call and updates UI elements. It demonstrates how to make API calls without interfering with the main loop of Omniverse. See [Adding the Extension](../../../README.md#adding-this-extension) on how to add the extension to your project. ​ ## [Tutorial](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 that calls an API and use that information to update components within Omniverse. ​[Get started with the tutorial here.](tutorial.md) ## Usage Once the extension is enabled in the *Extension Manager*, you should see a similar line inside the viewport like in the to the image before [Overview section](#overview). Clicking on the *Refresh* button will send a request to [HueMint.com](https://huemint.com/) API. HueMint then sends back a palette of colors which is used to update the 5 color widgets in the UI. Hovering over each color widget will display the values used to define the color. The color widgets can also be clicked on which opens a color picker UI.
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/docs/tutorial.md
# Connecting API to Omniverse Extension The API Connection extension shows how to communicate with an API within Omniverse. This guide is great for extension builders who want to start using their own API tools or external API tools within Omniverse. > NOTE: Visual Studio Code is the preferred IDE, hence forth we will be referring to it throughout this guide. > NOTE: Omniverse Code is the preferred platform, hence forth we will be referring to it throughout this guide. # Learning Objectives In this tutorial you learn how to: - Use `asyncio` - Use `aiohttp` calls - Send an API Request - Use Results from API Request - Use async within Omniverse # 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) - [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_window/tutorial/tutorial.md) # 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`. Name the project to `kit-ext-apiconnect` and the extension name to `my.api.connect`. ![](./images/ext_tab.png) > **Note:** If you don't see the *Extensions* Window, enable **Window > Extensions**: > > ![Show the Extensions panel](images/window_extensions.png) <icon> | <new template> :-------------------------:|:-------------------------: ![icon](./images/icon_create.png "Plus Icon") | ![new template](./images/new_template.png "New Extension Template") 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. Inside of the `config` folder, locate the `extension.toml` file: > **Note:** `extension.toml` is located inside of the `exts` folder you created for your extension. ![](./images/fileStructTOML.PNG) 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 extension. ``` python title = "API Connection" description="Example on how to make an API response in Omniverse" ``` # Step 2: Set Up Window All coding will be contained within `extension.py`. Before setting up the API request, the first step is to get a window. The UI contained in the window will have a button to call the API and color widgets whose values will be updated based on the API's response. ## Step 2.1: Replace with Boilerplate Code With *VS Code* open, **go to** `extension.py` and replace all the code inside with the following: ```python import omni.ext import omni.ui as ui # 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 on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None ``` If you were to save `extension.py` it would throw an error since we have not defined `APIWindowExample`. This step is to setup a starting point for which our window can be created and destroyed when starting up or shutting down the extension. `APIWindowExample` will be the class we work on throughout the rest of the tutorial. ## Step 2.2: Create `APIWindowExample` class At the bottom of `extension.py`, **create** a new class called `APIWindowExample()` ```python class APIWindowExample(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) ``` Save `extension.py` and go back to Omniverse. Right now, the Window should only have a label. ![](./images/step2-2.png) ## Step 2.3: Add Color Widgets Color Widgets are buttons that display a color and can open a picker window. In `extension.py`, **add** the following code block under `ui.Label()`: ```python with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] #create a button to trigger the api call self.button = ui.Button("Refresh") ``` Make sure `with ui.HStack()` is at the same indentation as `ui.Label()`. Here we create a Horizontal Stack that will contain 5 Color Widgets. Below that will be a button labeled Refresh. **Save** `extension.py` and go back to Omniverse. The Window will now have 5 white boxes. When hovered it will show the color values and when clicked on it will open a color picker window. ![](./images/step2-3.gif) After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui # 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 on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] #create a button to trigger the api call self.button = ui.Button("Refresh") ``` # Step 3: Create API Request To make an API Request we use the `aiohttp` library. This comes packaged in the Python environment with Omniverse. We use the `asyncio` library as well to avoid the user interface freezing when there are very expensive Python operations. Async is a single threaded / single process design because it's using cooperative multitasking. ## Step 3.1: Create a Task 1. **Add** `import asyncio` at the top of `extension.py`. 2. In `APIWindowExample` class, **add** the following function: ```python #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): print("a") await asyncio.sleep(1) print("b") ``` This function contains the keyword `async` in front, meaning we cannot call it statically. To call this function we first need to grab the current event loop. 3. Before `ui.Label()` **add** the following line: - `run_loop = asyncio.get_event_loop()` Now we can use the event loop to create a task that runs concurrently. 4. Before `self.button`, **add** the following block of code: ```python def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) ``` `create_task` takes a coroutine, where coroutine is an object with the keyword async. 5. To connect it together **add** the following parameter in `self.button`: - `clicked_fn=on_click` After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio # 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 on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): print("a") await asyncio.sleep(1) print("b") def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. Now when we click on the Refresh button, in the Console tab it will print 'a' and after one second it will print 'b'. ![](./images/step3-1.gif) ## Step 3.2: Make API Request To **create** the API Request, we first need to create an `aiohttp` session. 1. Add `import aiohttp` at the top of `extension.py`. 2. In `get_colors_from_api()` remove: ```python print("a") await asyncio.sleep(1) print("b") ``` and **add** the following: - `async with aiohttp.ClientSession() as session:` With the session created, we can build the URL and data to send to the API. For this example we are using the [HueMint.com](https://huemint.com/) API. 3. Under `aiohttp.ClientSession()`, **add** the following block of code: ```python url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } ``` > **Note:** If you are using a different URL make sure the data passed is correct. 4. Based on HueMint.com we will create a POST request. **Add** the following code block under `data`: ```python try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] print(palette) except Exception as e: import carb carb.log_info(f"Caught Exception {e}") ``` The `try / except` is used to catch when a Timeout occurs. To read more about Timeouts see [aiohttp Client Quick Start](https://docs.aiohttp.org/en/latest/client_quickstart.html). After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio import aiohttp # 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 on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): async with aiohttp.ClientSession() as session: url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] print(palette) except Exception as e: import carb carb.log_info(f"Caught Exception {e}") def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. When clicking on the Refresh button our Extension will now call the API, grab the JSON response, and store it in `palette`. We can see the value for `palette` in the Console Tab. ![](./images/step3-3.gif) # Step 4: Apply Results Now that the API call is returning a response, we can now take that response and apply it to our color widgets in the Window. ## Step 4.1: Setup `apply_colors()` To apply the colors received from the API, **create** the following two functions inside of `APIWindowExample`: ```python #apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): colors = [palette[i] for i in range(5)] index = 0 for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() #we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) #we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 #hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): #Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#' ``` In Kit there is a special awaitable: `await omni.kit.app.get_app().next_update_async()` - This waits for the next frame within Omniverse to run. It is used when you want to execute something with a one-frame delay. - Why do we need this? - Without this, running Python code that is expensive can cause the user interface to freeze ## Step 4.2: Link it together Inside `get_colors_from_api()` **replace** `print()` with the following line: - `await self.apply_colors(palette, color_widgets)` After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio import aiohttp # 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 on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): async with aiohttp.ClientSession() as session: url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] await self.apply_colors(palette, color_widgets) except Exception as e: import carb carb.log_info(f"Caught Exception {e}") #apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): colors = [palette[i] for i in range(5)] index = 0 for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() #we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) #we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 #hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): #Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#' def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. When clicking on the Refresh button our color widgets in the window will now update based on the results given by the API response. ![](./images/step4-2.gif) # Step 5: Visualize Progression Some API responses might not be as quick to return a result. Visual indicators can be added to indicate to the user that the extension is waiting for an API response. Examples can be loading bars, spinning circles, percent numbers, etc. For this example, we are going to change "Refresh" to "Loading" and as time goes on it will add up to three periods after Loading before resetting. How it looks when cycling: - Loading - Loading. - Loading.. - Loading... - Loading ## Step 5.1: Run Forever Task Using `async`, we can create as many tasks to run concurrently. One task so far is making a request to the API and our second task will be running the Loading visuals. **Add** the following code block in `APIWindowExample`: ```python async def run_forever(self): count = 0 dot_count = 0 while True: if count % 10 == 0: if dot_count == 3: self.button.text = "Loading" dot_count = 0 else: self.button.text += "." dot_count += 1 count += 1 await omni.kit.app.get_app().next_update_async() ``` > **Note:** This function will run forever. When creating coroutines make sure there is a way to end the process or cancel it to prevent it from running the entire time. Again we use `next_update_async()` to prevent the user interface from freezing. ## Step 5.2: Cancelling Tasks As noted before this coroutine runs forever so after we apply the colors we will cancel that task to stop it from running. 1. At the front of `get_colors_from_api()` **add** the following lines: ```python self.button.text = "Loading" task = asyncio.create_task(self.run_forever()) ``` To cancel a task we need a reference to the task that was created. 2. In `get_colors_from_api()` and after `await self.apply_colors()` **add** the following lines: ```python task.cancel() self.button.text = "Refresh" ``` 3. After `carb.log_info()`, **add** the following lines: ```python task.cancel() self.button.text = "Connection Timed Out \nClick to Retry" ``` After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio import aiohttp # 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 on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): self.button.text = "Loading" task = asyncio.create_task(self.run_forever()) async with aiohttp.ClientSession() as session: url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] await self.apply_colors(palette, color_widgets) task.cancel() self.button.text = "Refresh" except Exception as e: import carb carb.log_info(f"Caught Exception {e}") task.cancel() self.button.text = "Connection Timed Out \nClick to Retry" #apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): colors = [palette[i] for i in range(5)] index = 0 for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() #we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) #we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 async def run_forever(self): count = 0 dot_count = 0 while True: if count % 10 == 0: if dot_count == 3: self.button.text = "Loading" dot_count = 0 else: self.button.text += "." dot_count += 1 count += 1 await omni.kit.app.get_app().next_update_async() #hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): #Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#' def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. Clicking the Refresh Button now will display a visual progression to let the user know that the program is running. Once the program is done the button will revert back to displaying "Refresh" instead of "Loading". ![](./images/step5-2.gif)
NVIDIA-Omniverse/kit-extension-sample-reticle/link_app.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) cd "$SCRIPT_DIR" exec "tools/packman/python.sh" tools/scripts/link_app.py $@
NVIDIA-Omniverse/kit-extension-sample-reticle/link_app.bat
@echo off call "%~dp0tools\packman\python.bat" %~dp0tools\scripts\link_app.py %* if %errorlevel% neq 0 ( goto Error ) :Success exit /b 0 :Error exit /b %errorlevel%
NVIDIA-Omniverse/kit-extension-sample-reticle/README.md
# Viewport Reticle Kit Extension Sample ## [Viewport Reticle (omni.example.reticle)](exts/omni.example.reticle) ![Camera Reticle Preview](exts/omni.example.reticle/data/preview.png) ### About This extension shows how to build a viewport reticle extension. The focus of this sample extension is to show how to use omni.ui.scene to draw additional graphical primitives on the viewport. ### [README](exts/omni.example.reticle) See the [README for this extension](exts/omni.example.reticle) to learn more about it including how to use it. ### [Tutorial](tutorial/tutorial.md) Follow a [step-by-step tutorial](tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## Adding This Extension To add this extension 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-reticle?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" ``` ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
NVIDIA-Omniverse/kit-extension-sample-reticle/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!")
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/python.sh
#!/bin/bash # Copyright 2019-2020 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. set -e PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi source "$PACKMAN_CMD" init export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}" export PYTHONNOUSERSITE=1 # workaround for our python not shipping with certs if [[ -z ${SSL_CERT_DIR:-} ]]; then export SSL_CERT_DIR=/etc/ssl/certs/ fi "${PM_PYTHON}" -u "$@"
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/python.bat
:: Copyright 2019-2020 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. @echo off setlocal call "%~dp0\packman" init set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%" set PYTHONNOUSERSITE=1 "%PM_PYTHON%" -u %*
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/packman.cmd
:: Reset errorlevel status (don't inherit from caller) [xxxxxxxxxxx] @call :ECHO_AND_RESET_ERROR :: You can remove the call below if you do your own manual configuration of the dev machines call "%~dp0\bootstrap\configure.bat" if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Everything below is mandatory if not defined PM_PYTHON goto :PYTHON_ENV_ERROR if not defined PM_MODULE goto :MODULE_ENV_ERROR :: Generate temporary path for variable file for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile ^ -File "%~dp0bootstrap\generate_temp_file_name.ps1"') do set PM_VAR_PATH=%%a if %1.==. ( set PM_VAR_PATH_ARG= ) else ( set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%" ) "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG% if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Marshall environment variables into the current environment if they have been generated and remove temporary file if exist "%PM_VAR_PATH%" ( for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) if exist "%PM_VAR_PATH%" ( del /F "%PM_VAR_PATH%" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) set PM_VAR_PATH= goto :eof :: Subroutines below :PYTHON_ENV_ERROR @echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat. exit /b 1 :MODULE_ENV_ERROR @echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat. exit /b 1 :VAR_ERROR @echo Error while processing and setting environment variables! exit /b 1 :ECHO_AND_RESET_ERROR @echo off if /I "%PM_VERBOSITY%"=="debug" ( @echo on ) exit /b 0
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/bootstrap/generate_temp_file_name.ps1
<# 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. #> $out = [System.IO.Path]::GetTempFileName() Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEE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JEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCCHEAmNNj2zWjWYRfEi4FgzZvrI16kv/U2b9b3oHw6UVDANBgkqhkiG # 9w0BAQEFAASCAQCdefEKh6Qmwx7xGCkrYi/A+/Cla6LdnYJp38eMs3fqTTvjhyDw # HffXrwdqWy5/fgW3o3qJXqa5o7hLxYIoWSULOCpJRGdt+w7XKPAbZqHrN9elAhWJ # vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V # mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo # PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof # wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU # SIG # End signature block
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/bootstrap/configure.bat
:: 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. set PM_PACKMAN_VERSION=6.33.2 :: Specify where packman command is rooted set PM_INSTALL_PATH=%~dp0.. :: The external root may already be configured and we should do minimal work in that case if defined PM_PACKAGES_ROOT goto ENSURE_DIR :: If the folder isn't set we assume that the best place for it is on the drive that we are currently :: running from set PM_DRIVE=%CD:~0,2% set PM_PACKAGES_ROOT=%PM_DRIVE%\packman-repo :: We use *setx* here so that the variable is persisted in the user environment echo Setting user environment variable PM_PACKAGES_ROOT to %PM_PACKAGES_ROOT% setx PM_PACKAGES_ROOT %PM_PACKAGES_ROOT% if %errorlevel% neq 0 ( goto ERROR ) :: The above doesn't work properly from a build step in VisualStudio because a separate process is :: spawned for it so it will be lost for subsequent compilation steps - VisualStudio must :: be launched from a new process. We catch this odd-ball case here: if defined PM_DISABLE_VS_WARNING goto ENSURE_DIR if not defined VSLANG goto ENSURE_DIR echo The above is a once-per-computer operation. Unfortunately VisualStudio cannot pick up environment change echo unless *VisualStudio is RELAUNCHED*. echo If you are launching VisualStudio from command line or command line utility make sure echo you have a fresh launch environment (relaunch the command line or utility). echo If you are using 'linkPath' and referring to packages via local folder links you can safely ignore this warning. echo You can disable this warning by setting the environment variable PM_DISABLE_VS_WARNING. echo. :: Check for the directory that we need. Note that mkdir will create any directories :: that may be needed in the path :ENSURE_DIR if not exist "%PM_PACKAGES_ROOT%" ( echo Creating directory %PM_PACKAGES_ROOT% mkdir "%PM_PACKAGES_ROOT%" ) if %errorlevel% neq 0 ( goto ERROR_MKDIR_PACKAGES_ROOT ) :: The Python interpreter may already be externally configured if defined PM_PYTHON_EXT ( set PM_PYTHON=%PM_PYTHON_EXT% goto PACKMAN ) set PM_PYTHON_VERSION=3.7.9-windows-x86_64 set PM_PYTHON_BASE_DIR=%PM_PACKAGES_ROOT%\python set PM_PYTHON_DIR=%PM_PYTHON_BASE_DIR%\%PM_PYTHON_VERSION% set PM_PYTHON=%PM_PYTHON_DIR%\python.exe if exist "%PM_PYTHON%" goto PACKMAN if not exist "%PM_PYTHON_BASE_DIR%" call :CREATE_PYTHON_BASE_DIR set PM_PYTHON_PACKAGE=python@%PM_PYTHON_VERSION%.cab for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME%.zip call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_PYTHON_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching python from CDN !!! goto ERROR ) for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_folder.ps1" -parentPath "%PM_PYTHON_BASE_DIR%"') do set TEMP_FOLDER_NAME=%%a echo Unpacking Python interpreter ... "%SystemRoot%\system32\expand.exe" -F:* "%TARGET%" "%TEMP_FOLDER_NAME%" 1> nul del "%TARGET%" :: Failure during extraction to temp folder name, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error unpacking python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :: If python has now been installed by a concurrent process we need to clean up and then continue if exist "%PM_PYTHON%" ( call :CLEAN_UP_TEMP_FOLDER goto PACKMAN ) else ( if exist "%PM_PYTHON_DIR%" ( rd /s /q "%PM_PYTHON_DIR%" > nul ) ) :: Perform atomic rename rename "%TEMP_FOLDER_NAME%" "%PM_PYTHON_VERSION%" 1> nul :: Failure during move, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error renaming python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :PACKMAN :: The packman module may already be externally configured if defined PM_MODULE_DIR_EXT ( set PM_MODULE_DIR=%PM_MODULE_DIR_EXT% ) else ( set PM_MODULE_DIR=%PM_PACKAGES_ROOT%\packman-common\%PM_PACKMAN_VERSION% ) set PM_MODULE=%PM_MODULE_DIR%\packman.py if exist "%PM_MODULE%" goto ENSURE_7ZA set PM_MODULE_PACKAGE=packman-common@%PM_PACKMAN_VERSION%.zip for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME% call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_MODULE_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching packman from CDN !!! goto ERROR ) echo Unpacking ... "%PM_PYTHON%" -S -s -u -E "%~dp0\install_package.py" "%TARGET%" "%PM_MODULE_DIR%" if %errorlevel% neq 0 ( echo !!! Error unpacking packman !!! goto ERROR ) del "%TARGET%" :ENSURE_7ZA set PM_7Za_VERSION=16.02.4 set PM_7Za_PATH=%PM_PACKAGES_ROOT%\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END set PM_7Za_PATH=%PM_PACKAGES_ROOT%\chk\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" pull "%PM_MODULE_DIR%\deps.packman.xml" if %errorlevel% neq 0 ( echo !!! Error fetching packman dependencies !!! goto ERROR ) goto END :ERROR_MKDIR_PACKAGES_ROOT echo Failed to automatically create packman packages repo at %PM_PACKAGES_ROOT%. echo Please set a location explicitly that packman has permission to write to, by issuing: echo. echo setx PM_PACKAGES_ROOT {path-you-choose-for-storing-packman-packages-locally} echo. echo Then launch a new command console for the changes to take effect and run packman command again. exit /B %errorlevel% :ERROR echo !!! Failure while configuring local machine :( !!! exit /B %errorlevel% :CLEAN_UP_TEMP_FOLDER rd /S /Q "%TEMP_FOLDER_NAME%" exit /B :CREATE_PYTHON_BASE_DIR :: We ignore errors and clean error state - if two processes create the directory one will fail which is fine md "%PM_PYTHON_BASE_DIR%" > nul 2>&1 exit /B 0 :END
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/bootstrap/fetch_file_from_packman_bootstrap.cmd
:: 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. :: You need to specify <package-name> <target-path> as input to this command @setlocal @set PACKAGE_NAME=%1 @set TARGET_PATH=%2 @echo Fetching %PACKAGE_NAME% ... @powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0download_file_from_url.ps1" ^ -source "http://bootstrap.packman.nvidia.com/%PACKAGE_NAME%" -output %TARGET_PATH% :: A bug in powershell prevents the errorlevel code from being set when using the -File execution option :: We must therefore do our own failure analysis, basically make sure the file exists and is larger than 0 bytes: @if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED @if %~z2==0 goto ERROR_DOWNLOAD_FAILED @endlocal @exit /b 0 :ERROR_DOWNLOAD_FAILED @echo Failed to download file from S3 @echo Most likely because endpoint cannot be reached or file %PACKAGE_NAME% doesn't exist @endlocal @exit /b 1
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/bootstrap/download_file_from_url.ps1
<# 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. #> param( [Parameter(Mandatory=$true)][string]$source=$null, [string]$output="out.exe" ) $filename = $output $triesLeft = 3 do { $triesLeft -= 1 try { Write-Host "Downloading from bootstrap.packman.nvidia.com ..." $wc = New-Object net.webclient $wc.Downloadfile($source, $fileName) $triesLeft = 0 } catch { Write-Host "Error downloading $source!" Write-Host $_.Exception|format-list -force } } while ($triesLeft -gt 0)
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/bootstrap/generate_temp_folder.ps1
<# 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. #> param( [Parameter(Mandatory=$true)][string]$parentPath=$null ) [string] $name = [System.Guid]::NewGuid() $out = Join-Path $parentPath $name New-Item -ItemType Directory -Path ($out) | Out-Null Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCB29nsqMEu+VmSF # 7ckeVTPrEZ6hsXjOgPFlJm9ilgHUB6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0 # IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg # U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow # gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT # YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL # DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI # hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP # YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH # jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa # HJjJvE7KNY9G4AZXxjSt8CXS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K # EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNV # BAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBpbmcgQ0ECEA1C # SuC+Ooj/YEAhzhQA8N0wDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZIhvcNAQkDMQ0G # CyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCDvFxQ6lYLr8vB+9czUl19rjCw1pWhhUXw/SqOmvIa/VDANBgkqhkiG # 9w0BAQEFAASCAQB9ox2UrcUXQsBI4Uycnhl4AMpvhVXJME62tygFMppW1l7QftDy # LvfPKRYm2YUioak/APxAS6geRKpeMkLvXuQS/Jlv0kY3BjxkeG0eVjvyjF4SvXbZ # 3JCk9m7wLNE+xqOo0ICjYlIJJgRLudjWkC5Skpb1NpPS8DOaIYwRV+AWaSOUPd9P # O5yVcnbl7OpK3EAEtwDrybCVBMPn2MGhAXybIHnth3+MFp1b6Blhz3WlReQyarjq # 1f+zaFB79rg6JswXoOTJhwICBP3hO2Ua3dMAswbfl+QNXF+igKLJPYnaeSVhBbm6 # VCu2io27t4ixqvoD0RuPObNX/P3oVA38afiM # SIG # End signature block
NVIDIA-Omniverse/kit-extension-sample-reticle/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])
NVIDIA-Omniverse/kit-extension-sample-reticle/tutorial/tutorial.md
![NVIDIA Omniverse Logo](images/logo.png) # Create a Reusable Reticle with Omniverse Kit Extensions Camera [reticles](https://en.wikipedia.org/wiki/Reticle) are patterns and lines you use to line up a camera to a scene. In this tutorial, you learn how to make a reticle extension. You'll test it in Omniverse Code, but it can be used in any Omniverse Application. ## Learning Objectives In this guide, you learn how to: * Create an Omniverse Extension * Include your Extension in Omniverse Code * Draw a line on top of the [viewport](https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_viewport.html) * Divide the viewport with multiple lines * Create a crosshair and letterboxes ## Prerequisites Before you begin, install [Omniverse Code](https://docs.omniverse.nvidia.com/app_code/app_code/overview.html) version 2022.1.2 or higher. We recommend that you understand the concepts in the following tutorial before proceeding: * [How to make an extension by spawning primitives](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) ## Step 1: Familiarize Yourself with the Starter Project In this section, you download and familiarize yourself with the starter project you use throughout this tutorial. ### Step 1.1: Clone the Repository Clone the `tutorial-start` branch of the `kit-extension-sample-reticle` [github repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-reticle/tree/tutorial-start): ```shell git clone -b tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-reticle.git ``` This repository contains the assets you use in this tutorial ### Step 1.2: Navigate to `views.py` From the root directory of the project, navigate to `exts/omni.example.reticle/omni/example/reticle/views.py`. ### Step 1.3: Familiarize Yourself with `build_viewport_overlay()` In `views.py`, navigate to `build_viewport_overlay()`: ```python def build_viewport_overlay(self, *args): """Build all viewport graphics and ReticleMenu button.""" if self.vp_win is not None: self.vp_win.frame.clear() with self.vp_win.frame: with ui.ZStack(): # Set the aspect ratio policy depending if the viewport is wider than it is taller or vice versa. if self.vp_win.width / self.vp_win.height > self.get_aspect_ratio_flip_threshold(): self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL) else: self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL) # Build all the scene view guidelines with self.scene_view.scene: if self.model.composition_mode.as_int == CompositionGuidelines.THIRDS: self._build_thirds() elif self.model.composition_mode.as_int == CompositionGuidelines.QUAD: self._build_quad() elif self.model.composition_mode.as_int == CompositionGuidelines.CROSSHAIR: self._build_crosshair() if self.model.action_safe_enabled.as_bool: self._build_safe_rect(self.model.action_safe_percentage.as_float / 100.0, color=cl.action_safe_default) if self.model.title_safe_enabled.as_bool: self._build_safe_rect(self.model.title_safe_percentage.as_float / 100.0, color=cl.title_safe_default) if self.model.custom_safe_enabled.as_bool: self._build_safe_rect(self.model.custom_safe_percentage.as_float / 100.0, color=cl.custom_safe_default) if self.model.letterbox_enabled.as_bool: self._build_letterbox() # Build ReticleMenu button with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() self.reticle_menu = ReticleMenu(self.model) ``` Here, `self.vp_win` is the [viewport](https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_viewport.html) on which you'll build your reticle overlay. If there is no viewport, there's nothing to build on, so execution stops here: ```python if self.vp_win is not None: ``` If there is a viewport, you create a clean slate by calling [`clear()`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Container.clear) on the [frame](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Frame): ```python self.vp_win.frame.clear() ``` Next, you create a [ZStack](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Stack): ```python with self.vp_win.frame: with ui.ZStack(): ``` ZStack is a type of [Stack](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Stack) that orders elements along the Z axis (forward and backward from the camera, as opposed to up and down or left and right). After that, you create a [SceneView](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.SceneView), a widget that renders the [Scene](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Scene): ```python if self.vp_win.width / self.vp_win.height > self.get_aspect_ratio_flip_threshold(): self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL) else: self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL) ``` When doing this, you make a calculation to determine what the appropriate `aspect_ratio_policy`, which defines how to handle a [Camera](https://docs.omniverse.nvidia.com/app_create/prod_materials-and-rendering/cameras.html) with an aspect ratio different than the SceneView. The SceneView does not consider non-rendered areas such as [letterboxes](https://en.wikipedia.org/wiki/Letterboxing_(filming)), hence `get_aspect_ratio_flip_threshold()`. Further down in `build_viewport_overlay()`, there are a number of `if` statements: ```python with self.scene_view.scene: if self.model.composition_mode.as_int == CompositionGuidelines.THIRDS: self._build_thirds() elif self.model.composition_mode.as_int == CompositionGuidelines.QUAD: self._build_quad() elif self.model.composition_mode.as_int == CompositionGuidelines.CROSSHAIR: self._build_crosshair() if self.model.action_safe_enabled.as_bool: self._build_safe_rect(self.model.action_safe_percentage.as_float / 100.0, color=cl.action_safe_default) if self.model.title_safe_enabled.as_bool: self._build_safe_rect(self.model.title_safe_percentage.as_float / 100.0, color=cl.title_safe_default) if self.model.custom_safe_enabled.as_bool: self._build_safe_rect(self.model.custom_safe_percentage.as_float / 100.0, color=cl.custom_safe_default) if self.model.letterbox_enabled.as_bool: self._build_letterbox() # Build ReticleMenu button with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() self.reticle_menu = ReticleMenu(self.model) ``` These are the different modes and tools the user can select from the **ReticleMenu**. Throughout this tutorial, you write the logic for the following functions: - `self._build_quad()` - `self._build_thirds()` - `self._build_crosshair()` - `self._build_crosshair()` - `_build_safe_rect()` - `_build_letterbox()` Before you do that, you need to import your custom Extension into Omniverse Code. ## Step 2: Import your Extension into Omniverse Code In order to use and test your Extension, you need to add it to Omniverse Code. > **Important:** Make sure you're using Code version 2022.1.2 or higher. ### Step 2.1: Navigate to the Extensions List In Omniverse Code, navigate to the *Extensions* panel: ![Click the Extensions panel](images/extensions_panel.png) Here, you see a list of Omniverse Extensions that you can activate and use in Code. > **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**: > > ![Show the Extensions panel](images/window_extensions.png) ### Step 2.2: Import your Extension Click the **gear** icon to open *Extension Search Paths*: ![Click the gear icon](images/extension_search_paths.png) In this panel, you can add your custom Extension to the Extensions list. ### Step 2.3: Create a New Search Path Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field: ![New search path](images/new_search_path.png) When you submit your new search path, you should be able to find your extension in the *Extensions* list. Activate it: ![Reticle extensions list](images/reticle_extensions_list.png) Now that your Extension is imported and active, you can make changes to the code and see them in your Application. ## Step 3: Draw a Single Line The first step to building a camera reticle is drawing a line. Once you can do that, you can construct more complex shapes using the line as a foundation. For example, you can split the viewport into thirds or quads using multiple lines. ### Step 3.1: Familiarize Yourself with Some Useful Modules At the top of `views.py`, review the following imported modules: ```py from omni.ui import color as cl from omni.ui import scene ``` - `omni.ui.color` offers color functionality. - [`omni.ui.scene`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html) offers a number of useful classes including [Line](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Line). ### Step 3.2: Draw a Line in `build_viewport_overlay()` In `build_viewport_overlay()`, create a line, providing a start, stop, and color: ```python with self.scene_view.scene: start_point = [0, -1, 0] # [x, y, z] end_point = [0, 1, 0] line_color = cl.white scene.Line(start_point, end_point, color=line_color) ``` In the Code viewport, you'll see the white line: ![Viewport line](images/white_line.png) > **Optional Challenge:** Change the `start_point`, `end_point`, and `line_color` values to see how it renders in Code. ### Step 3.3: Remove the Line Now that you've learned how to use `omni.ui.scene` to draw a line, remove it to prepare your viewport for more meaningful shapes. ## Step 4: Draw Quadrants Now that you know how to draw a line, implement `_build_quad()` to construct four quadrants. In other words, split the view into four zones: ![Break the Viewport into quadrants](images/quad.png) ### Step 4.1: Draw Two Dividers Draw your quadrant dividers in `_build_quad()`: ```python def _build_quad(self): """Build the scene ui graphics for the Quad composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, -1, 0], [0, 1, 0], color=line_color) scene.Line([-aspect_ratio, 0, 0], [aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, -inverse_ratio, 0], [0, inverse_ratio, 0], color=line_color) scene.Line([-1, 0, 0], [1, 0, 0], color=line_color) ``` To divide the viewport into quadrants, you only need two lines, so why are there four lines in this code? Imagine the aspect ratio can grow and shrink in the horizontal direction, but the vertical height is static. That would preserve the vertical aspect ratio as with [scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL). In this case, a vertical position in the viewport is bound between -1 and 1, but the horizontal position bounds are determined by the aspect ratio. Conversely, if your horizontal width bounds are static and the vertical height bounds can change, you would need the inverse of the aspect ratio (`inverse_ratio`). ### Step 4.2: Review Your Change In Omniverse Code, select **Quad** from the **Reticle** menu: ![Select quad](images/select_quad.png) With this option selected, the viewport is divided into quadrants. ## Step 5: Draw Thirds The [Rule of Thirds](https://en.wikipedia.org/wiki/Rule_of_thirds) is a theory in photography that suggests the best way to align elements in an image is like this: ![Break the Viewport into nine zones](images/thirds.png) Like you did in the last section, here you draw a number of lines. This time, though, you use four lines to make nine zones in your viewport. But like before, these lines depend on the [Aspect Ratio Policy](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.AspectRatioPolicy). ### Step 5.1: Draw Four Dividers Draw your dividers in `_build_thirds()`: ```python def _build_thirds(self): """Build the scene ui graphics for the Thirds composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([-0.333 * aspect_ratio, -1, 0], [-0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([0.333 * aspect_ratio, -1, 0], [0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([-aspect_ratio, -0.333, 0], [aspect_ratio, -0.333, 0], color=line_color) scene.Line([-aspect_ratio, 0.333, 0], [aspect_ratio, 0.333, 0], color=line_color) else: scene.Line([-1, -0.333 * inverse_ratio, 0], [1, -0.333 * inverse_ratio, 0], color=line_color) scene.Line([-1, 0.333 * inverse_ratio, 0], [1, 0.333 * inverse_ratio, 0], color=line_color) scene.Line([-0.333, -inverse_ratio, 0], [-0.333, inverse_ratio, 0], color=line_color) scene.Line([0.333, -inverse_ratio, 0], [0.333, inverse_ratio, 0], color=line_color) ``` > **Optional Challenge:** Currently, you call `scene.Line` eight times to draw four lines based on two situations. Optimize this logic so you only call `scene.Line` four times to draw four lines, regardless of the aspect ratio. > > **Hint:** You may need to define new variables. > > <details> > <summary>One Possible Solution</summary> > > is_preserving_aspect_vertical = scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL > > x, y = aspect_ratio, 1 if is_preserving_aspect_vertical else 1, inverse_ratio > x1, x2, y1, y2 = .333 * x, 1 * x, 1 * y, .333 * y > > scene.Line([-x1, -y1, 0], [-x1, y1, 0], color=line_color) > scene.Line([x1, -y1, 0], [x1, y1, 0], color=line_color) > scene.Line([-x2, -y2, 0], [x2, -y2, 0], color=line_color) > scene.Line([-x2, y2, 0], [x2, y2, 0], color=line_color) > </details> ### Step 5.2: Review Your Change In Omniverse Code, select **Thirds** from the **Reticle** menu: ![Select thirds](images/select_thirds.png) With this option selected, the viewport is divided into nine zones. ## Step 6: Draw a Crosshair A crosshair is a type of reticle commonly used in [first-person shooter](https://en.wikipedia.org/wiki/First-person_shooter) games to designate a projectile's expected position. For the purposes of this tutorial, you draw a crosshair at the center of the screen. To do this, you draw four small lines about the center of the viewport, based on the Aspect Ratio Policy. ### Step 6.1: Draw Your Crosshair Draw your crosshair in `_build_crosshair()`: ```python def _build_crosshair(self): """Build the scene ui graphics for the Crosshair composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, 0.05 * aspect_ratio, 0], [0, 0.1 * aspect_ratio, 0], color=line_color) scene.Line([0, -0.05 * aspect_ratio, 0], [0, -0.1 * aspect_ratio, 0], color=line_color) scene.Line([0.05 * aspect_ratio, 0, 0], [0.1 * aspect_ratio, 0, 0], color=line_color) scene.Line([-0.05 * aspect_ratio, 0, 0], [-0.1 * aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, 0.05 * 1, 0], [0, 0.1 * 1, 0], color=line_color) scene.Line([0, -0.05 * 1, 0], [0, -0.1 * 1, 0], color=line_color) scene.Line([0.05 * 1, 0, 0], [0.1 * 1, 0, 0], color=line_color) scene.Line([-0.05 * 1, 0, 0], [-0.1 * 1, 0, 0], color=line_color) scene.Points([[0.00005, 0, 0]], sizes=[2], colors=[line_color]) ``` This implementation is similar to your previous reticles except for the addition of a [point](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Points) at the true center of the crosshair. > **Optional Challenge:** Express the crosshair length as a variable. ### Step 6.2: Review Your Change In Omniverse Code, select **Crosshair** from the **Reticle** menu: ![Select crosshair](images/select_crosshair.png) With this option selected, the viewport shows a centered crosshair. ## Step 7: Draw Safe Area Rectangles Different televisions or monitors may display video in different ways, cutting off the edges. To account for this, producers use [Safe Areas](https://en.wikipedia.org/wiki/Safe_area_(television)) to make sure text and graphics are rendered nicely regardless of the viewer's hardware. In this section, you implement three rectangles: - **Title Safe:** This helps align text so that it's not too close to the edge of the screen. - **Action Safe:** This helps align graphics such as news tickers and logos. - **Custom Safe:** This helps the user define their own alignment rectangle. ### Step 7.1: Draw Your Rectangle Draw your safe [rectangle](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Rectangle) in `_build_safe_rect()`: ```python def _build_safe_rect(self, percentage, color): """Build the scene ui graphics for the safe area rectangle Args: percentage (float): The 0-1 percentage the render target that the rectangle should fill. color: The color to draw the rectangle wireframe with. """ aspect_ratio = self.get_aspect_ratio() inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Rectangle(aspect_ratio*2*percentage, 1*2*percentage, thickness=1, wireframe=True, color=color) else: scene.Rectangle(1*2*percentage, inverse_ratio*2*percentage, thickness=1, wireframe=True, color=color) ``` Like before, you draw two different rectangles based on how the aspect is preserved. You draw them from the center after defining the width and height. Since the center is at `[0, 0, 0]` and either the horizontal or vertical axis goes from -1 to 1 (as opposed to from 0 to 1), you multiply the width and height by two. ### Step 7.2: Review Your Change In Omniverse Code, select your **Safe Areas** from the **Reticle** menu: ![Select safe areas](images/select_safe_areas.png) With these option selected, the viewport shows your safe areas. ## Step 8: Draw Letterboxes [Letterboxes](https://en.wikipedia.org/wiki/Letterboxing_(filming)) are large rectangles (typically black), on the edges of a screen used to help fit an image or a movie constructed with one aspect ratio into another. It can also be used for dramatic effect to give something a more theatrical look. ### Step 8.1 Draw Your Letterbox Helper Write a function to draw and place a [rectangle](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Rectangle): ```python def _build_letterbox(self): def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) ``` The [scene.Matrix44.get_translation_matrix](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Matrix44.get_translation_matrix) creates a 4x4 matrix that can be multiplied with a point to offset it by an x, y, or z amount. Since you don't need to move your rectangles toward or away from the camera, the z value is 0. > **Further Reading:** To learn more about the math behind this operation, please check out [this article](https://medium.com/swlh/understanding-3d-matrix-transforms-with-pixijs-c76da3f8bd8). `build_letterbox_helper()` first defines the coordinates of where you expect to rectangle to be placed with `move`. Then, it creates a rectangle with that [transform](https://medium.com/swlh/understanding-3d-matrix-transforms-with-pixijs-c76da3f8bd8). Finally, it repeats the same steps to place and create a rectangle in the opposite direction of the first. Now that you have your helper function, you it to construct your letterboxes. ### Step 8.2: Review Your Potential Aspect Ratios Consider the following situations: ![Letterbox ratio diagram](images/letterbox_ratio.png) In this case, the viewport height is static, but the horizontal width can change. Additionally, the letterbox ratio is larger than the aspect ratio, meaning the rendered area is just as wide as the viewport, but not as tall. Next, write your logic to handle this case. ### Step 8.3: Build Your First Letterbox Build your letterbox to handle the case you analyzed in the last step: ```python def _build_letterbox(self): """Build the scene ui graphics for the letterbox.""" aspect_ratio = self.get_aspect_ratio() letterbox_color = cl.letterbox_default letterbox_ratio = self.model.letterbox_ratio.as_float def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: if letterbox_ratio >= aspect_ratio: height = 1 - aspect_ratio / letterbox_ratio rect_height = height / 2 rect_offset = 1 - rect_height build_letterbox_helper(aspect_ratio, rect_height, 0, rect_offset) ``` Here, you can think of the `height` calculated above as the percentage of the viewport height to be covered by the letterboxes. If the `aspect_ratio` is 2 to 1, but the `letterbox_ratio` is 4 to 1, then `aspect_ratio / letterbox_ratio` is .5, meaning the letterboxes will cover half of the height. However, this is split by both the top and bottom letterboxes, so you divide the `height` by 2 to get the rectangle height (`rect_height`), which, with our example above, is .25. Now that you know the height of the rectangle, you need to know where to place it. Thankfully, the vertical height is bound from -1 to 1, and since you're mirroring the letterboxes along both the top and bottom, so you can subtract `rect_height` from the maximum viewport height (1). ### Step 8.4: Build The Other Letterboxes Using math similar to that explained in the last step, write the `_build_letterbox()` logic for the other three cases: ```python def _build_letterbox(self): """Build the scene ui graphics for the letterbox.""" aspect_ratio = self.get_aspect_ratio() letterbox_color = cl.letterbox_default letterbox_ratio = self.model.letterbox_ratio.as_float def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: if letterbox_ratio >= aspect_ratio: height = 1 - aspect_ratio / letterbox_ratio rect_height = height / 2 rect_offset = 1 - rect_height build_letterbox_helper(aspect_ratio, rect_height, 0, rect_offset) else: width = aspect_ratio - letterbox_ratio rect_width = width / 2 rect_offset = aspect_ratio - rect_width build_letterbox_helper(rect_width, 1, rect_offset, 0) else: inverse_ratio = 1 / aspect_ratio if letterbox_ratio >= aspect_ratio: height = inverse_ratio - 1 / letterbox_ratio rect_height = height / 2 rect_offset = inverse_ratio - rect_height build_letterbox_helper(1, rect_height, 0, rect_offset) else: width = (aspect_ratio - letterbox_ratio) * inverse_ratio rect_width = width / 2 rect_offset = 1 - rect_width build_letterbox_helper(rect_width, inverse_ratio, rect_offset, 0) ``` ## 8. Congratulations! Great job completing this tutorial! Interested in improving your skills further? Check out the [Omni.ui.scene Example](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene). ![NVIDIA Omniverse Logo](images/logo.png)
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/config/extension.toml
[package] version = "1.3.1" title = "Example Viewport Reticle" description="An example kit extension of a viewport reticle using omni.ui.scene." authors=["Matias Codesal <[email protected]>"] readme = "docs/README.md" changelog="docs/CHANGELOG.md" repository = "" category = "Rendering" keywords = ["camera", "reticle", "viewport"] preview_image = "data/preview.png" icon = "icons/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.viewport.utility" = {} "omni.ui.scene" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.example.reticle"
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/styles.py
from pathlib import Path import omni.ui as ui from omni.ui import color as cl CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.joinpath("icons") cl.action_safe_default = cl(1.0, 0.0, 0.0) cl.title_safe_default = cl(1.0, 1.0, 0.0) cl.custom_safe_default = cl(0.0, 1.0, 0.0) cl.letterbox_default = cl(0.0, 0.0, 0.0, 0.75) cl.comp_lines_default = cl(1.0, 1.0, 1.0, 0.6) safe_areas_group_style = { "Label:disabled": { "color": cl(1.0, 1.0, 1.0, 0.2) }, "FloatSlider:enabled": { "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl(0.75, 0.75, 0.75, 1), "color": cl.black }, "FloatSlider:disabled": { "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl(0.75, 0.75, 0.75, 0.2), "color": cl(0.0, 0.0, 1.0, 0.2) }, "CheckBox": { "background_color": cl(0.75, 0.75, 0.75, 1), "color": cl.black }, "Rectangle::ActionSwatch": { "background_color": cl.action_safe_default }, "Rectangle::TitleSwatch": { "background_color": cl.title_safe_default }, "Rectangle::CustomSwatch": { "background_color": cl.custom_safe_default } } comp_group_style = { "Button.Image::Off": { "image_url": str(ICON_PATH / "off.png") }, "Button.Image::Thirds": { "image_url": str(ICON_PATH / "thirds.png") }, "Button.Image::Quad": { "image_url": str(ICON_PATH / "quad.png") }, "Button.Image::Crosshair": { "image_url": str(ICON_PATH / "crosshair.png") }, "Button:checked": { "background_color": cl(1.0, 1.0, 1.0, 0.2) } }
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/constants.py
"""Constants used by the CameraReticleExtension""" import enum class CompositionGuidelines(enum.IntEnum): """Enum representing all of the composition modes.""" OFF = 0 THIRDS = 1 QUAD = 2 CROSSHAIR = 3 DEFAULT_ACTION_SAFE_PERCENTAGE = 93 DEFAULT_TITLE_SAFE_PERCENTAGE = 90 DEFAULT_CUSTOM_SAFE_PERCENTAGE = 85 DEFAULT_LETTERBOX_RATIO = 2.35 DEFAULT_COMPOSITION_MODE = CompositionGuidelines.OFF SETTING_RESOLUTION_WIDTH = "/app/renderer/resolution/width" SETTING_RESOLUTION_HEIGHT = "/app/renderer/resolution/height" SETTING_RESOLUTION_FILL = "/app/runLoops/rendering_0/fillResolution"
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/extension.py
import carb import omni.ext from omni.kit.viewport.utility import get_active_viewport_window from . import constants from .models import ReticleModel from .views import ReticleOverlay class ExampleViewportReticleExtension(omni.ext.IExt): def on_startup(self, ext_id): carb.log_info("[omni.example.reticle] ExampleViewportReticleExtension startup") # Reticle should ideally be used with "Fill Viewport" turned off. settings = carb.settings.get_settings() settings.set(constants.SETTING_RESOLUTION_FILL, False) viewport_window = get_active_viewport_window() if viewport_window is not None: reticle_model = ReticleModel() self.reticle = ReticleOverlay(reticle_model, viewport_window, ext_id) self.reticle.build_viewport_overlay() def on_shutdown(self): """ Executed when the extension is disabled.""" carb.log_info("[omni.example.reticle] ExampleViewportReticleExtension shutdown") self.reticle.destroy()
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/__init__.py
from .extension import ExampleViewportReticleExtension
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/models.py
"""Models used by the CameraReticleExtension""" import omni.ui as ui from . import constants class ReticleModel: """Model containing all of the data used by the ReticleOverlay and ReticleMenu The ReticleOverlay and ReticleMenu classes need to share the same data and stay in sync with updates from user input. This is achieve by passing the same ReticleModel object to both classes. """ def __init__(self): self.composition_mode = ui.SimpleIntModel(constants.DEFAULT_COMPOSITION_MODE) self.action_safe_enabled = ui.SimpleBoolModel(False) self.action_safe_percentage = ui.SimpleFloatModel(constants.DEFAULT_ACTION_SAFE_PERCENTAGE, min=0, max=100) self.title_safe_enabled = ui.SimpleBoolModel(False) self.title_safe_percentage = ui.SimpleFloatModel(constants.DEFAULT_TITLE_SAFE_PERCENTAGE, min=0, max=100) self.custom_safe_enabled = ui.SimpleBoolModel(False) self.custom_safe_percentage = ui.SimpleFloatModel(constants.DEFAULT_CUSTOM_SAFE_PERCENTAGE, min=0, max=100) self.letterbox_enabled = ui.SimpleBoolModel(False) self.letterbox_ratio = ui.SimpleFloatModel(constants.DEFAULT_LETTERBOX_RATIO, min=0.001) self._register_submodel_callbacks() self._callbacks = [] def _register_submodel_callbacks(self): """Register to listen to when any submodel values change.""" self.composition_mode.add_value_changed_fn(self._reticle_changed) self.action_safe_enabled.add_value_changed_fn(self._reticle_changed) self.action_safe_percentage.add_value_changed_fn(self._reticle_changed) self.title_safe_enabled.add_value_changed_fn(self._reticle_changed) self.title_safe_percentage.add_value_changed_fn(self._reticle_changed) self.custom_safe_enabled.add_value_changed_fn(self._reticle_changed) self.custom_safe_percentage.add_value_changed_fn(self._reticle_changed) self.letterbox_enabled.add_value_changed_fn(self._reticle_changed) self.letterbox_ratio.add_value_changed_fn(self._reticle_changed) def _reticle_changed(self, model): """Executes all registered callbacks of this model. Args: model (Any): The submodel that has changed. [Unused] """ for callback in self._callbacks: callback() def add_reticle_changed_fn(self, callback): """Add a callback to be executed whenever any ReticleModel submodel data changes. This is useful for rebuilding the overlay whenever any data changes. Args: callback (function): The function to call when the reticle model changes. """ self._callbacks.append(callback)
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/views.py
from functools import partial import carb import omni.ui as ui from omni.ui import color as cl from omni.ui import scene from . import constants from .constants import CompositionGuidelines from .models import ReticleModel from . import styles class ReticleOverlay: """The reticle viewport overlay. Build the reticle graphics and ReticleMenu button on the given viewport window. """ _instances = [] def __init__(self, model: ReticleModel, vp_win: ui.Window, ext_id: str): """ReticleOverlay constructor Args: model (ReticleModel): The reticle model vp_win (Window): The viewport window to build the overlay on. ext_id (str): The extension id. """ self.model = model self.vp_win = vp_win self.ext_id = ext_id # Rebuild the overlay whenever the viewport window changes self.vp_win.set_height_changed_fn(self.on_window_changed) self.vp_win.set_width_changed_fn(self.on_window_changed) self._view_change_sub = None try: # VP2 resolution change sub self._view_change_sub = self.vp_win.viewport_api.subscribe_to_view_change(self.on_window_changed) except AttributeError: carb.log_info("Using Viewport Legacy: Reticle will not automatically update on resolution changes.") # Rebuild the overlay whenever the model changes self.model.add_reticle_changed_fn(self.build_viewport_overlay) ReticleOverlay._instances.append(self) resolution = self.vp_win.viewport_api.get_texture_resolution() self._aspect_ratio = resolution[0] / resolution[1] @classmethod def get_instances(cls): """Get all created instances of ReticleOverlay""" return cls._instances def __del__(self): self.destroy() def destroy(self): self._view_change_sub = None self.scene_view.scene.clear() self.scene_view = None self.reticle_menu.destroy() self.reticle_menu = None self.vp_win = None def on_window_changed(self, *args): """Update aspect ratio and rebuild overlay when viewport window changes.""" if self.vp_win is None: return settings = carb.settings.get_settings() if type(self.vp_win).__name__ == "LegacyViewportWindow": fill = settings.get(constants.SETTING_RESOLUTION_FILL) else: fill = self.vp_win.viewport_api.fill_frame if fill: width = self.vp_win.frame.computed_width + 8 height = self.vp_win.height else: width, height = self.vp_win.viewport_api.resolution self._aspect_ratio = width / height self.build_viewport_overlay() def get_aspect_ratio_flip_threshold(self): """Get magic number for aspect ratio policy. Aspect ratio policy doesn't seem to swap exactly when window_aspect_ratio == window_texture_aspect_ratio. This is a hack that approximates where the policy changes. """ return self.get_aspect_ratio() - self.get_aspect_ratio() * 0.05 def build_viewport_overlay(self, *args): """Build all viewport graphics and ReticleMenu button.""" if self.vp_win is not None: # Create a unique frame for our overlay with self.vp_win.get_frame(self.ext_id): with ui.ZStack(): # Set the aspect ratio policy depending if the viewport is wider than it is taller or vice versa. if self.vp_win.width / self.vp_win.height > self.get_aspect_ratio_flip_threshold(): self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL) else: self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL) # Build all the scene view guidelines with self.scene_view.scene: if self.model.composition_mode.as_int == CompositionGuidelines.THIRDS: self._build_thirds() elif self.model.composition_mode.as_int == CompositionGuidelines.QUAD: self._build_quad() elif self.model.composition_mode.as_int == CompositionGuidelines.CROSSHAIR: self._build_crosshair() if self.model.action_safe_enabled.as_bool: self._build_safe_rect(self.model.action_safe_percentage.as_float / 100.0, color=cl.action_safe_default) if self.model.title_safe_enabled.as_bool: self._build_safe_rect(self.model.title_safe_percentage.as_float / 100.0, color=cl.title_safe_default) if self.model.custom_safe_enabled.as_bool: self._build_safe_rect(self.model.custom_safe_percentage.as_float / 100.0, color=cl.custom_safe_default) if self.model.letterbox_enabled.as_bool: self._build_letterbox() # Build ReticleMenu button with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() self.reticle_menu = ReticleMenu(self.model) def _build_thirds(self): """Build the scene ui graphics for the Thirds composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([-0.333 * aspect_ratio, -1, 0], [-0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([0.333 * aspect_ratio, -1, 0], [0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([-aspect_ratio, -0.333, 0], [aspect_ratio, -0.333, 0], color=line_color) scene.Line([-aspect_ratio, 0.333, 0], [aspect_ratio, 0.333, 0], color=line_color) else: scene.Line([-1, -0.333 * inverse_ratio, 0], [1, -0.333 * inverse_ratio, 0], color=line_color) scene.Line([-1, 0.333 * inverse_ratio, 0], [1, 0.333 * inverse_ratio, 0], color=line_color) scene.Line([-0.333, -inverse_ratio, 0], [-0.333, inverse_ratio, 0], color=line_color) scene.Line([0.333, -inverse_ratio, 0], [0.333, inverse_ratio, 0], color=line_color) def _build_quad(self): """Build the scene ui graphics for the Quad composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, -1, 0], [0, 1, 0], color=line_color) scene.Line([-aspect_ratio, 0, 0], [aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, -inverse_ratio, 0], [0, inverse_ratio, 0], color=line_color) scene.Line([-1, 0, 0], [1, 0, 0], color=line_color) def _build_crosshair(self): """Build the scene ui graphics for the Crosshair composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, 0.05 * aspect_ratio, 0], [0, 0.1 * aspect_ratio, 0], color=line_color) scene.Line([0, -0.05 * aspect_ratio, 0], [0, -0.1 * aspect_ratio, 0], color=line_color) scene.Line([0.05 * aspect_ratio, 0, 0], [0.1 * aspect_ratio, 0, 0], color=line_color) scene.Line([-0.05 * aspect_ratio, 0, 0], [-0.1 * aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, 0.05 * 1, 0], [0, 0.1 * 1, 0], color=line_color) scene.Line([0, -0.05 * 1, 0], [0, -0.1 * 1, 0], color=line_color) scene.Line([0.05 * 1, 0, 0], [0.1 * 1, 0, 0], color=line_color) scene.Line([-0.05 * 1, 0, 0], [-0.1 * 1, 0, 0], color=line_color) scene.Points([[0.00005, 0, 0]], sizes=[2], colors=[line_color]) def _build_safe_rect(self, percentage, color): """Build the scene ui graphics for the safe area rectangle Args: percentage (float): The 0-1 percentage the render target that the rectangle should fill. color: The color to draw the rectangle wireframe with. """ aspect_ratio = self.get_aspect_ratio() inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Rectangle(aspect_ratio*2*percentage, 1*2*percentage, thickness=1, wireframe=True, color=color) else: scene.Rectangle(1*2*percentage, inverse_ratio*2*percentage, thickness=1, wireframe=True, color=color) def _build_letterbox(self): """Build the scene ui graphics for the letterbox.""" aspect_ratio = self.get_aspect_ratio() letterbox_color = cl.letterbox_default letterbox_ratio = self.model.letterbox_ratio.as_float def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: if letterbox_ratio >= aspect_ratio: height = 1 - aspect_ratio / letterbox_ratio rect_height = height / 2 rect_offset = 1 - rect_height build_letterbox_helper(aspect_ratio, rect_height, 0, rect_offset) else: width = aspect_ratio - letterbox_ratio rect_width = width / 2 rect_offset = aspect_ratio - rect_width build_letterbox_helper(rect_width, 1, rect_offset, 0) else: inverse_ratio = 1 / aspect_ratio if letterbox_ratio >= aspect_ratio: height = inverse_ratio - 1 / letterbox_ratio rect_height = height / 2 rect_offset = inverse_ratio - rect_height build_letterbox_helper(1, rect_height, 0, rect_offset) else: width = (aspect_ratio - letterbox_ratio) * inverse_ratio rect_width = width / 2 rect_offset = 1 - rect_width build_letterbox_helper(rect_width, inverse_ratio, rect_offset, 0) def get_aspect_ratio(self): """Get the aspect ratio of the viewport. Returns: float: The viewport aspect ratio. """ return self._aspect_ratio class ReticleMenu: """The popup reticle menu""" def __init__(self, model: ReticleModel): """ReticleMenu constructor Stores the model and builds the Reticle button. Args: model (ReticleModel): The reticle model """ self.model = model self.button = ui.Button("Reticle", width=0, height=0, mouse_pressed_fn=self.show_reticle_menu, style={"margin": 10, "padding": 5, "color": cl.white}) self.reticle_menu = None def destroy(self): self.button.destroy() self.button = None self.reticle_menu = None def on_group_check_changed(self, safe_area_group, model): """Enables/disables safe area groups When a safe area checkbox state changes, all the widgets of the respective group should be enabled/disabled. Args: safe_area_group (HStack): The safe area group to enable/disable model (SimpleBoolModel): The safe group checkbox model. """ safe_area_group.enabled = model.as_bool def on_composition_mode_changed(self, guideline_type): """Sets the selected composition mode. When a composition button is clicked, it should be checked on and the other buttons should be checked off. Sets the composition mode on the ReticleModel too. Args: guideline_type (_type_): _description_ """ self.model.composition_mode.set_value(guideline_type) self.comp_off_button.checked = guideline_type == CompositionGuidelines.OFF self.comp_thirds_button.checked = guideline_type == CompositionGuidelines.THIRDS self.comp_quad_button.checked = guideline_type == CompositionGuidelines.QUAD self.comp_crosshair_button.checked = guideline_type == CompositionGuidelines.CROSSHAIR def show_reticle_menu(self, x, y, button, modifier): """Build and show the reticle menu popup.""" self.reticle_menu = ui.Menu("Reticle", width=400, height=200) self.reticle_menu.clear() with self.reticle_menu: with ui.Frame(width=0, height=100): with ui.HStack(): with ui.VStack(): ui.Label("Composition", alignment=ui.Alignment.LEFT, height=30) with ui.VGrid(style=styles.comp_group_style, width=150, height=0, column_count=2, row_height=75): current_comp_mode = self.model.composition_mode.as_int with ui.HStack(): off_checked = current_comp_mode == CompositionGuidelines.OFF callback = partial(self.on_composition_mode_changed, CompositionGuidelines.OFF) self.comp_off_button = ui.Button("Off", name="Off", checked=off_checked, width=70, height=70, clicked_fn=callback) with ui.HStack(): thirds_checked = current_comp_mode == CompositionGuidelines.THIRDS callback = partial(self.on_composition_mode_changed, CompositionGuidelines.THIRDS) self.comp_thirds_button = ui.Button("Thirds", name="Thirds", checked=thirds_checked, width=70, height=70, clicked_fn=callback) with ui.HStack(): quad_checked = current_comp_mode == CompositionGuidelines.QUAD callback = partial(self.on_composition_mode_changed, CompositionGuidelines.QUAD) self.comp_quad_button = ui.Button("Quad", name="Quad", checked=quad_checked, width=70, height=70, clicked_fn=callback) with ui.HStack(): crosshair_checked = current_comp_mode == CompositionGuidelines.CROSSHAIR callback = partial(self.on_composition_mode_changed, CompositionGuidelines.CROSSHAIR) self.comp_crosshair_button = ui.Button("Crosshair", name="Crosshair", checked=crosshair_checked, width=70, height=70, clicked_fn=callback) ui.Spacer(width=10) with ui.VStack(style=styles.safe_areas_group_style): ui.Label("Safe Areas", alignment=ui.Alignment.LEFT, height=30) with ui.HStack(width=0): ui.Spacer(width=20) cb = ui.CheckBox(model=self.model.action_safe_enabled) action_safe_group = ui.HStack(enabled=self.model.action_safe_enabled.as_bool) callback = partial(self.on_group_check_changed, action_safe_group) cb.model.add_value_changed_fn(callback) with action_safe_group: ui.Spacer(width=10) ui.Label("Action Safe", alignment=ui.Alignment.TOP) ui.Spacer(width=14) with ui.VStack(): ui.FloatSlider(self.model.action_safe_percentage, width=100, format="%.0f%%", min=0, max=100, step=1) ui.Rectangle(name="ActionSwatch", height=5) ui.Spacer() with ui.HStack(width=0): ui.Spacer(width=20) cb = ui.CheckBox(model=self.model.title_safe_enabled) title_safe_group = ui.HStack(enabled=self.model.title_safe_enabled.as_bool) callback = partial(self.on_group_check_changed, title_safe_group) cb.model.add_value_changed_fn(callback) with title_safe_group: ui.Spacer(width=10) ui.Label("Title Safe", alignment=ui.Alignment.TOP) ui.Spacer(width=25) with ui.VStack(): ui.FloatSlider(self.model.title_safe_percentage, width=100, format="%.0f%%", min=0, max=100, step=1) ui.Rectangle(name="TitleSwatch", height=5) ui.Spacer() with ui.HStack(width=0): ui.Spacer(width=20) cb = ui.CheckBox(model=self.model.custom_safe_enabled) custom_safe_group = ui.HStack(enabled=self.model.custom_safe_enabled.as_bool) callback = partial(self.on_group_check_changed, custom_safe_group) cb.model.add_value_changed_fn(callback) with custom_safe_group: ui.Spacer(width=10) ui.Label("Custom Safe", alignment=ui.Alignment.TOP) ui.Spacer(width=5) with ui.VStack(): ui.FloatSlider(self.model.custom_safe_percentage, width=100, format="%.0f%%", min=0, max=100, step=1) ui.Rectangle(name="CustomSwatch", height=5) ui.Spacer() ui.Label("Letterbox", alignment=ui.Alignment.LEFT, height=30) with ui.HStack(width=0): ui.Spacer(width=20) cb = ui.CheckBox(model=self.model.letterbox_enabled) letterbox_group = ui.HStack(enabled=self.model.letterbox_enabled.as_bool) callback = partial(self.on_group_check_changed, letterbox_group) cb.model.add_value_changed_fn(callback) with letterbox_group: ui.Spacer(width=10) ui.Label("Letterbox Ratio", alignment=ui.Alignment.TOP) ui.Spacer(width=5) ui.FloatDrag(self.model.letterbox_ratio, width=35, min=0.001, step=0.01) self.reticle_menu.show_at(x - self.reticle_menu.width, y - self.reticle_menu.height)
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. ## [Unreleased] ## [1.3.1] - 2022-09-09 ### Changed - Fixed on_window_changed callback for VP2 ## [1.3.0] - 2022-09-09 ### Changed - Fixed bad use of viewport window frame for VP2 - Now using ViewportAPI.subscribe_to_view_change() to update reticle on resolution changes. ## [1.2.0] - 2022-06-24 ### Changed - Refactored to omni.example.reticle - Updated preview.png - Cleaned up READMEs ### Removed - menu.png ## [1.1.0] - 2022-06-22 ### Changed - Refactored reticle.py to views.py - Fixed bug where Viewport Docs was being treated as viewport. - Moved Reticle button to bottom right of viewport to not overlap axes decorator. ### Removed - All mutli-viewport logic. ## [1.0.0] - 2022-05-25 ### Added - Initial add of the Sample Viewport Reticle extension.
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/docs/README.md
# Viewport Reticle (omni.example.reticle) ![Camera Reticle Preview](../data/preview.png) ## Overview The Viewport Reticle Sample extension adds a new menu button at the bottom, right of the viewport. From this menu, users can enable and configure: 1. Composition Guidelines 2. Safe Area Guidelines 3. Letterbox ## [Tutorial](../../../tutorial/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. [Get started with the tutorial.](../../../tutorial/tutorial.md) ## Usage ### Composition Guidelines * Click on the **Thirds**, **Quad**, or **Crosshair** button to enable a different composition mode. * Use the guidelines to help frame your shots. Click on the **Off** button to disable the composition guidelines. ### Safe Area Guidelines * Click on the checkbox for the safe area that you are interested in to enable the safe area guidelines. * Use the slider to adjust the area percentage for the respective safe areas. * NOTE: The sliders are disabled if their respective checkbox is unchecked. ### Letterbox * Check on **Letterbox Ratio** to enable the letterbox. * Enter a value or drag on the **Letterbox Ratio** field to adjust the letterbox ratio.
NVIDIA-Omniverse/kit-extension-sample-ui-window/link_app.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) cd "$SCRIPT_DIR" exec "tools/packman/python.sh" tools/scripts/link_app.py $@
NVIDIA-Omniverse/kit-extension-sample-ui-window/link_app.bat
@echo off call "%~dp0tools\packman\python.bat" %~dp0tools\scripts\link_app.py %* if %errorlevel% neq 0 ( goto Error ) :Success exit /b 0 :Error exit /b %errorlevel%
NVIDIA-Omniverse/kit-extension-sample-ui-window/README.md
# omni.ui Kit Extension Samples ## [Generic Window (omni.example.ui_window)](exts/omni.example.ui_window) ![Object Info](exts/omni.example.ui_window/data/preview.png) ### About This extension provides an end-to-end example and general recommendations on creating a simple window using `omni.ui`. It contains the best practices of building an extension, a menu item, a window itself, a custom widget, and a generic style. ### [README](exts/omni.example.ui_window) See the [README for this extension](exts/omni.example.ui_window) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_window/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_window/tutorial/tutorial.md) that walks you through how to use omni.ui to build this extension. ## [Julia Modeler (omni.example.ui_julia_modeler)](exts/omni.example.ui_julia_modeler) ![Julia Modeler](exts/omni.example.ui_julia_modeler/data/preview.png) ### About This extension is an example of a more advanced window with custom styling and custom widgets. Study this example to learn more about applying styles to `omni.ui` widgets and building your own custom widgets. ### [README](exts/omni.example.ui_julia_modeler/) See the [README for this extension](exts/omni.example.ui_julia_modeler/) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_julia_modeler/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_julia_modeler/tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## [Gradient Window (omni.example.ui_gradient_window)](exts/omni.example.ui_gradient_window/) ![Gradient Window](exts/omni.example.ui_gradient_window/data/Preview.png) ### About This extension shows how to build a Window that applys gradient styles to widgets. The focus of this sample extension is to show how to use omni.ui to create gradients with `ImageWithProvider`. ### [README](exts/omni.example.ui_gradient_window/) See the [README for this extension](exts/omni.example.ui_gradient_window/) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_gradient_window/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_gradient_window/tutorial/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-window?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" ``` ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
NVIDIA-Omniverse/kit-extension-sample-ui-window/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!")
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/python.sh
#!/bin/bash # Copyright 2019-2020 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. set -e PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi source "$PACKMAN_CMD" init export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}" export PYTHONNOUSERSITE=1 # workaround for our python not shipping with certs if [[ -z ${SSL_CERT_DIR:-} ]]; then export SSL_CERT_DIR=/etc/ssl/certs/ fi "${PM_PYTHON}" -u "$@"
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/python.bat
:: Copyright 2019-2020 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. @echo off setlocal call "%~dp0\packman" init set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%" set PYTHONNOUSERSITE=1 "%PM_PYTHON%" -u %*
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/packman.cmd
:: Reset errorlevel status (don't inherit from caller) [xxxxxxxxxxx] @call :ECHO_AND_RESET_ERROR :: You can remove the call below if you do your own manual configuration of the dev machines call "%~dp0\bootstrap\configure.bat" if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Everything below is mandatory if not defined PM_PYTHON goto :PYTHON_ENV_ERROR if not defined PM_MODULE goto :MODULE_ENV_ERROR :: Generate temporary path for variable file for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile ^ -File "%~dp0bootstrap\generate_temp_file_name.ps1"') do set PM_VAR_PATH=%%a if %1.==. ( set PM_VAR_PATH_ARG= ) else ( set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%" ) "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG% if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Marshall environment variables into the current environment if they have been generated and remove temporary file if exist "%PM_VAR_PATH%" ( for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) if exist "%PM_VAR_PATH%" ( del /F "%PM_VAR_PATH%" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) set PM_VAR_PATH= goto :eof :: Subroutines below :PYTHON_ENV_ERROR @echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat. exit /b 1 :MODULE_ENV_ERROR @echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat. exit /b 1 :VAR_ERROR @echo Error while processing and setting environment variables! exit /b 1 :ECHO_AND_RESET_ERROR @echo off if /I "%PM_VERBOSITY%"=="debug" ( @echo on ) exit /b 0
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/bootstrap/generate_temp_file_name.ps1
<# 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. #> $out = [System.IO.Path]::GetTempFileName() Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAK+Ewup1N0/mdf # 1l4R58rxyumHgZvTmEhrYTb2Zf0zd6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEd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A+/Cla6LdnYJp38eMs3fqTTvjhyDw # HffXrwdqWy5/fgW3o3qJXqa5o7hLxYIoWSULOCpJRGdt+w7XKPAbZqHrN9elAhWJ # vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V # mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo # PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof # wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU # SIG # End signature block
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/bootstrap/configure.bat
:: 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. set PM_PACKMAN_VERSION=6.33.2 :: Specify where packman command is rooted set PM_INSTALL_PATH=%~dp0.. :: The external root may already be configured and we should do minimal work in that case if defined PM_PACKAGES_ROOT goto ENSURE_DIR :: If the folder isn't set we assume that the best place for it is on the drive that we are currently :: running from set PM_DRIVE=%CD:~0,2% set PM_PACKAGES_ROOT=%PM_DRIVE%\packman-repo :: We use *setx* here so that the variable is persisted in the user environment echo Setting user environment variable PM_PACKAGES_ROOT to %PM_PACKAGES_ROOT% setx PM_PACKAGES_ROOT %PM_PACKAGES_ROOT% if %errorlevel% neq 0 ( goto ERROR ) :: The above doesn't work properly from a build step in VisualStudio because a separate process is :: spawned for it so it will be lost for subsequent compilation steps - VisualStudio must :: be launched from a new process. We catch this odd-ball case here: if defined PM_DISABLE_VS_WARNING goto ENSURE_DIR if not defined VSLANG goto ENSURE_DIR echo The above is a once-per-computer operation. Unfortunately VisualStudio cannot pick up environment change echo unless *VisualStudio is RELAUNCHED*. echo If you are launching VisualStudio from command line or command line utility make sure echo you have a fresh launch environment (relaunch the command line or utility). echo If you are using 'linkPath' and referring to packages via local folder links you can safely ignore this warning. echo You can disable this warning by setting the environment variable PM_DISABLE_VS_WARNING. echo. :: Check for the directory that we need. Note that mkdir will create any directories :: that may be needed in the path :ENSURE_DIR if not exist "%PM_PACKAGES_ROOT%" ( echo Creating directory %PM_PACKAGES_ROOT% mkdir "%PM_PACKAGES_ROOT%" ) if %errorlevel% neq 0 ( goto ERROR_MKDIR_PACKAGES_ROOT ) :: The Python interpreter may already be externally configured if defined PM_PYTHON_EXT ( set PM_PYTHON=%PM_PYTHON_EXT% goto PACKMAN ) set PM_PYTHON_VERSION=3.7.9-windows-x86_64 set PM_PYTHON_BASE_DIR=%PM_PACKAGES_ROOT%\python set PM_PYTHON_DIR=%PM_PYTHON_BASE_DIR%\%PM_PYTHON_VERSION% set PM_PYTHON=%PM_PYTHON_DIR%\python.exe if exist "%PM_PYTHON%" goto PACKMAN if not exist "%PM_PYTHON_BASE_DIR%" call :CREATE_PYTHON_BASE_DIR set PM_PYTHON_PACKAGE=python@%PM_PYTHON_VERSION%.cab for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME%.zip call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_PYTHON_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching python from CDN !!! goto ERROR ) for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_folder.ps1" -parentPath "%PM_PYTHON_BASE_DIR%"') do set TEMP_FOLDER_NAME=%%a echo Unpacking Python interpreter ... "%SystemRoot%\system32\expand.exe" -F:* "%TARGET%" "%TEMP_FOLDER_NAME%" 1> nul del "%TARGET%" :: Failure during extraction to temp folder name, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error unpacking python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :: If python has now been installed by a concurrent process we need to clean up and then continue if exist "%PM_PYTHON%" ( call :CLEAN_UP_TEMP_FOLDER goto PACKMAN ) else ( if exist "%PM_PYTHON_DIR%" ( rd /s /q "%PM_PYTHON_DIR%" > nul ) ) :: Perform atomic rename rename "%TEMP_FOLDER_NAME%" "%PM_PYTHON_VERSION%" 1> nul :: Failure during move, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error renaming python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :PACKMAN :: The packman module may already be externally configured if defined PM_MODULE_DIR_EXT ( set PM_MODULE_DIR=%PM_MODULE_DIR_EXT% ) else ( set PM_MODULE_DIR=%PM_PACKAGES_ROOT%\packman-common\%PM_PACKMAN_VERSION% ) set PM_MODULE=%PM_MODULE_DIR%\packman.py if exist "%PM_MODULE%" goto ENSURE_7ZA set PM_MODULE_PACKAGE=packman-common@%PM_PACKMAN_VERSION%.zip for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME% call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_MODULE_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching packman from CDN !!! goto ERROR ) echo Unpacking ... "%PM_PYTHON%" -S -s -u -E "%~dp0\install_package.py" "%TARGET%" "%PM_MODULE_DIR%" if %errorlevel% neq 0 ( echo !!! Error unpacking packman !!! goto ERROR ) del "%TARGET%" :ENSURE_7ZA set PM_7Za_VERSION=16.02.4 set PM_7Za_PATH=%PM_PACKAGES_ROOT%\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END set PM_7Za_PATH=%PM_PACKAGES_ROOT%\chk\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" pull "%PM_MODULE_DIR%\deps.packman.xml" if %errorlevel% neq 0 ( echo !!! Error fetching packman dependencies !!! goto ERROR ) goto END :ERROR_MKDIR_PACKAGES_ROOT echo Failed to automatically create packman packages repo at %PM_PACKAGES_ROOT%. echo Please set a location explicitly that packman has permission to write to, by issuing: echo. echo setx PM_PACKAGES_ROOT {path-you-choose-for-storing-packman-packages-locally} echo. echo Then launch a new command console for the changes to take effect and run packman command again. exit /B %errorlevel% :ERROR echo !!! Failure while configuring local machine :( !!! exit /B %errorlevel% :CLEAN_UP_TEMP_FOLDER rd /S /Q "%TEMP_FOLDER_NAME%" exit /B :CREATE_PYTHON_BASE_DIR :: We ignore errors and clean error state - if two processes create the directory one will fail which is fine md "%PM_PYTHON_BASE_DIR%" > nul 2>&1 exit /B 0 :END
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/bootstrap/fetch_file_from_packman_bootstrap.cmd
:: 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. :: You need to specify <package-name> <target-path> as input to this command @setlocal @set PACKAGE_NAME=%1 @set TARGET_PATH=%2 @echo Fetching %PACKAGE_NAME% ... @powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0download_file_from_url.ps1" ^ -source "http://bootstrap.packman.nvidia.com/%PACKAGE_NAME%" -output %TARGET_PATH% :: A bug in powershell prevents the errorlevel code from being set when using the -File execution option :: We must therefore do our own failure analysis, basically make sure the file exists and is larger than 0 bytes: @if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED @if %~z2==0 goto ERROR_DOWNLOAD_FAILED @endlocal @exit /b 0 :ERROR_DOWNLOAD_FAILED @echo Failed to download file from S3 @echo Most likely because endpoint cannot be reached or file %PACKAGE_NAME% doesn't exist @endlocal @exit /b 1
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/bootstrap/download_file_from_url.ps1
<# 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. #> param( [Parameter(Mandatory=$true)][string]$source=$null, [string]$output="out.exe" ) $filename = $output $triesLeft = 3 do { $triesLeft -= 1 try { Write-Host "Downloading from bootstrap.packman.nvidia.com ..." $wc = New-Object net.webclient $wc.Downloadfile($source, $fileName) $triesLeft = 0 } catch { Write-Host "Error downloading $source!" Write-Host $_.Exception|format-list -force } } while ($triesLeft -gt 0)
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/bootstrap/generate_temp_folder.ps1
<# 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. #> param( [Parameter(Mandatory=$true)][string]$parentPath=$null ) [string] $name = [System.Guid]::NewGuid() $out = Join-Path $parentPath $name New-Item -ItemType Directory -Path ($out) | Out-Null Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorB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EEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCDvFxQ6lYLr8vB+9czUl19rjCw1pWhhUXw/SqOmvIa/VDANBgkqhkiG # 9w0BAQEFAASCAQB9ox2UrcUXQsBI4Uycnhl4AMpvhVXJME62tygFMppW1l7QftDy # LvfPKRYm2YUioak/APxAS6geRKpeMkLvXuQS/Jlv0kY3BjxkeG0eVjvyjF4SvXbZ # 3JCk9m7wLNE+xqOo0ICjYlIJJgRLudjWkC5Skpb1NpPS8DOaIYwRV+AWaSOUPd9P # O5yVcnbl7OpK3EAEtwDrybCVBMPn2MGhAXybIHnth3+MFp1b6Blhz3WlReQyarjq # 1f+zaFB79rg6JswXoOTJhwICBP3hO2Ua3dMAswbfl+QNXF+igKLJPYnaeSVhBbm6 # VCu2io27t4ixqvoD0RuPObNX/P3oVA38afiM # SIG # End signature block
NVIDIA-Omniverse/kit-extension-sample-ui-window/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])
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/tutorial/tutorial.md
![](images/logo.png) # Gradient Style Window Tutorial In this tutorial we will cover how we can create a gradient style that will be used in various widgets. This tutorial will cover how to create a gradient image / style that can be applied to UI. ## Learning Objectives - How to use `ImageWithProvider` to create Image Widgets - Create functions to interpolate between colors - Apply custom styles to widgets ## Prerequisites - [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/Tutorial/exts/omni.example.ui_window/tutorial/tutorial.md) - Omniverse Code version 2022.1.2 or higher ## Step 1: Add the Extension ### Step 1.1: Clone the repository Clone the `gradient-tutorial-start` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/gradient-tutorial-start): ```shell git clone -b gradient-tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git ``` This repository contains the assets you use in this tutorial. ### Step 1.2: Open Extension Search Paths Go to *Extension Manager -> Gear Icon -> Extension Search Path*: ![cog](images/extension_search_paths.png#center) ### Step 1.3: Add the Path Create a new search path to the exts directory of your Extension by clicking the green plus icon and double-clicking on the path field: ![search path](images/new_search_path.png#center) When you submit your new search path, you should be able to find your extension in the Extensions list. ### Step 1.4: Enable the Extension ![enable](images/enable%20extension.png#center) After Enabling the extension the following window will appear: <center> ![png1](images/tut-png1.PNG#center) </center> Unlike the main repo, this extension is missing quite a few things that we will need to add, mainly the gradient. Moving forward we will go into detail on how to create the gradient style and apply it to our UI Window. ## Step 2: Familiarize Yourself with Interpolation What is interpolation? [Interpolation](https://en.wikipedia.org/wiki/Interpolation) a way to find or estimate a point based on a range of discrete set of known data points. For our case we interpolate between colors to appropriately set the slider handle color. Let's say the start point is black and our end point is white. What is a color that is in between black and white? Gray is what most would say. Using interpolation we can get more than just gray. Here's a picture representation of what it looks like to interpolate between black and white: ![png2](images/tut-png2.PNG) We can also use blue instead of black. It would then look something like this: ![png3](images/tut-png3.PNG) Interpolation can also be used with a spectrum of colors: ![png4](images/tut-png4.PNG) ## Step 3: Set up the Gradients Hexadecimal (Hex) is a base 16 numbering system where `0-9` represents their base 10 counterparts and `A-F` represent the base 10 values `10-15`. A Hex color is written as `#RRGGBB` where `RR` is red, `GG` is green and `BB` is blue. The hex values have the range `00` - `ff` which is equivalent to `0` - `255` in base 10. So to write the hex value to a color for red it would be: `#ff0000`. This is equivalent to saying `R=255, G=0, B=0`. To flesh out the `hex_to_color` function we will use bit shift operations to convert the hex value to color. ### Step 3.1: Navigate to `style.py` Open the project in VS Code and open the `style.py` file inside of `omni.example.ui_gradient_window\omni\example\ui_gradient_window` > **Tip:** Remember to open up any extension in VS Code by browsing to that extension in the `Extension` tab, then select the extension and click on the VS Code logo. Locate the function `hex_to_color` towards the bottom of the file. There will be other functions that are not yet filled out: ``` python def hex_to_color(hex: int) -> tuple: # YOUR CODE HERE pass def generate_byte_data(colors): # YOUR CODE HERE pass def _interpolate_color(hex_min: int, hex_max: int, intep): # YOUR CODE HERE pass def get_gradient_color(value, max, colors): # YOUR CODE HERE pass def build_gradient_image(colors, height, style_name): # YOUR CODE HERE pass ``` Currently we have the `pass` statement in each of the functions because each function needs at least one statement to run. > **Warning:** Removing the pass in these functions without adding any code will break other features of this extension! ### Step 3.2: Add Red to `hex_to_color` Replace `pass` with `red = hex & 255`: ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 ``` > **Warning:** Don't save yet! We must return a tuple before our function will run. ### Step 3.3: Add Green to `hex_to_color` Underneath where we declared `red`, add the following line `green = (hex >> 8) & 255`: ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 ``` > **Note:** 255 in binary is 0b11111111 (8 set bits) ### Step 3.4: Add the remaining colors to `hex_to_color` Try to fill out the rest of the following code for `blue` and `alpha`: ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = # YOUR CODE alpha = # YOUR CODE rgba_values = [red, green, blue, alpha] return rgba_values ``` <details> <summary>Click for solution</summary> ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = (hex >> 16) & 255 alpha = (hex >> 24) & 255 rgba_values = [red, green, blue, alpha] return rgba_values ``` </details> ## Step 4: Create `generate_byte_data` We will now be filling out the function `generate_byte_data`. This function will take our colors and generate byte data that we can use to make an image using `ImageWithProvider`. Here is the function we will be editing: ``` python def generate_byte_data(colors): # YOUR CODE HERE pass ``` ### Step 4.1: Create an Array for Color Values Replace `pass` with `data = []`. This will contain the color values: ``` python def generate_byte_data(colors): data = [] ``` ### Step 4.2: Loop Through the Colors Next we will loop through all provided colors in hex form to color form and add it to `data`. This will use `hex_to_color` created previously: ``` python def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) ``` ### Step 4.3: Loop Through the Colors Use [ByteImageProvider](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html?highlight=byteimage#omni.ui.ByteImageProvider) to set the sequence as byte data that will be used later to generate the image: ``` python def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) _byte_provider = ui.ByteImageProvider() _byte_provider.set_bytes_data(data [len(colors), 1]) return _byte_provider ``` ## Step 5: Build the Image Now that we have our data we can use it to create our image. ### Step 5.1: Locate `build_gradient_image()` In `style.py`, navigate to `build_gradient_image()`: ``` python def build_gradient_image(colors, height, style_name): # YOUR CODE HERE pass ``` ### Step 5.2: Create Byte Sequence Replace `pass` with `byte_provider = generate_byte_data(colors)`: ``` python def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ``` ### Step 5.3: Transform Bytes into the Gradient Image Use [ImageWithProvider](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html?highlight=byteimage#omni.ui.ImageWithProvider) to transform our sequence of bytes to an image. ``` python def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name) return byte_provider ``` Save `style.py` and take a look at our window. It should look like the following: <center> ![png5](images/tut-png5.PNG) </center> > **Note:** If the extension does not look like the following, close down Code and try to relaunch. ### Step 5.4: How are the Gradients Used? Head over to `color_widget.py`, then scroll to around line 90: ``` python self.color_button_gradient_R = build_gradient_image([cl_attribute_dark, cl_attribute_red], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_G = build_gradient_image([cl_attribute_dark, cl_attribute_green], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_B = build_gradient_image([cl_attribute_dark, cl_attribute_blue], 22, "button_background_gradient") ``` This corresponds to the widgets that look like this: <center> ![png6](images/tut-png6.PNG) </center> ### Step 5.5: Experiment - Change the red to pink Go to `style.py`, locate the pre-defined constants, change `cl_attribute_red`'s value to `cl("#fc03be")` ``` python # Pre-defined constants. It's possible to change them runtime. fl_attr_hspacing = 10 fl_attr_spacing = 1 fl_group_spacing = 5 cl_attribute_dark = cl("#202324") cl_attribute_red = cl("#fc03be") # previously was cl("#ac6060") cl_attribute_green = cl("#60ab7c") cl_attribute_blue = cl("#35889e") cl_line = cl("#404040") cl_text_blue = cl("#5eb3ff") cl_text_gray = cl("#707070") cl_text = cl("#a1a1a1") cl_text_hovered = cl("#ffffff") cl_field_text = cl("#5f5f5f") cl_widget_background = cl("#1f2123") cl_attribute_default = cl("#505050") cl_attribute_changed = cl("#55a5e2") cl_slider = cl("#383b3e") cl_combobox_background = cl("#252525") cl_main_background = cl("#2a2b2c") cls_temperature_gradient = [cl("#fe0a00"), cl("#f4f467"), cl("#a8b9ea"), cl("#2c4fac"), cl("#274483"), cl("#1f334e")] cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")] cls_tint_gradient = [cl("#1D1D92"), cl("#7E7EC9"), cl("#FFFFFF")] cls_grey_gradient = [cl("#020202"), cl("#525252"), cl("#FFFFFF")] cls_button_gradient = [cl("#232323"), cl("#656565")] ``` > **Tip:** Storing colors inside of the style.py file will help with reusing those values for other widgets. The value only has to change in one location, inside of style.py, rather than everywhere that the hex value was hard coded. <center> ![png7](images/tut-png7.PNG) </center> The colors for the sliders can be changed the same way. ## Step 6: Get the Handle of the Slider to Show the Color as it's Moved Currently, the handle on the slider turns to black when interacting with it. <center> ![gif1](images/gif1.gif) </center> This is because we need to let it know what color we are on. This can be a bit tricky since the sliders are simple images. However, using interpolation we can approximate the color we are on. During this step we will be filling out `_interpolate_color` function inside of `style.py`. ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): pass ``` ### Step 6.1: Set the color range Define `max_color` and `min_color`. Then remove `pass`. ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) ``` ### Step 6.2: Calculate the color ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)] ``` ### Step 6.3: Return the interpolated color ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)] return (color[3] << 8 * 3) + (color[2] << 8 * 2) + (color[1] << 8 * 1) + color[0] ``` ## Step 7: Getting the Gradient Color Now that we can interpolate between two colors we can grab the color of the gradient in which the slider is on. To do this we will be using value which is the position of the slider along the gradient image, max being the maximum number the value can be, and a list of all the colors. After calculating the step size between the colors that made up the gradient image, we can then grab the index to point to the appropriate color in our list of colors that our slider is closest to. From that we can interpolate between the first color reference in the list and the next color in the list based on the index. ### Step 7.1: Locate `get_gradient_color` function ``` python def get_gradient_color(value, max, colors): pass ``` ### Step 7.2: Declare `step_size` and `step` ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) ``` ### Step 7.3: Declare `percentage` and `idx` ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) ``` ### Step 7.4: Check to see if our index is equal to our step size, to prevent an Index out of bounds exception ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) if idx == step_size: color = colors[-1] ``` ### Step 7.5: Else interpolate between the current index color and the next color in the list. Return the result afterwards. ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) if idx == step_size: color = colors[-1] else: color = _interpolate_color(colors[idx], colors[idx+1], percentage) return color ``` Save the file and head back into Omniverse to test out the slider. Now when moving the slider it will update to the closest color within the color list. <center> ![gif2](images/gif2.gif) </center> ## Conclusion This was a tutorial about how to create gradient styles in the Window. Check out the complete code in the main branch to see how other styles were created. To learn more about how to create custom widgets check out the [Julia Modeler](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/main/exts/omni.example.ui_julia_modeler) example. As a challenge, try to use the color that gets set by the slider to update something in the scene.
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/config/extension.toml
[package] title = "omni.ui Gradient Window Example" description = "The full end to end example of the window" version = "1.0.1" category = "Example" authors = ["Min Jiang"] repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows" keywords = ["example", "window", "ui"] changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.example.ui_gradient_window" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/style.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__ = ["main_window_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. fl_attr_hspacing = 10 fl_attr_spacing = 1 fl_group_spacing = 5 cl_attribute_dark = cl("#202324") cl_attribute_red = cl("#ac6060") cl_attribute_green = cl("#60ab7c") cl_attribute_blue = cl("#35889e") cl_line = cl("#404040") cl_text_blue = cl("#5eb3ff") cl_text_gray = cl("#707070") cl_text = cl("#a1a1a1") cl_text_hovered = cl("#ffffff") cl_field_text = cl("#5f5f5f") cl_widget_background = cl("#1f2123") cl_attribute_default = cl("#505050") cl_attribute_changed = cl("#55a5e2") cl_slider = cl("#383b3e") cl_combobox_background = cl("#252525") cl_main_background = cl("#2a2b2c") cls_temperature_gradient = [cl("#fe0a00"), cl("#f4f467"), cl("#a8b9ea"), cl("#2c4fac"), cl("#274483"), cl("#1f334e")] cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")] cls_tint_gradient = [cl("#1D1D92"), cl("#7E7EC9"), cl("#FFFFFF")] cls_grey_gradient = [cl("#020202"), cl("#525252"), cl("#FFFFFF")] cls_button_gradient = [cl("#232323"), cl("#656565")] # The main style dict main_window_style = { "Button::add": {"background_color": cl_widget_background}, "Field::add": { "font_size": 14, "color": cl_text}, "Field::search": { "font_size": 16, "color": cl_field_text}, "Field::path": { "font_size": 14, "color": cl_field_text}, "ScrollingFrame::main_frame": {"background_color": cl_main_background}, # for CollapsableFrame "CollapsableFrame::group": { "margin_height": fl_group_spacing, "background_color": 0x0, "secondary_color": 0x0, }, "CollapsableFrame::group:hovered": { "margin_height": fl_group_spacing, "background_color": 0x0, "secondary_color": 0x0, }, # for Secondary CollapsableFrame "Circle::group_circle": { "background_color": cl_line, }, "Line::group_line": {"color": cl_line}, # all the labels "Label::collapsable_name": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text }, "Label::attribute_bool": { "alignment": ui.Alignment.LEFT_BOTTOM, "margin_height": fl_attr_spacing, "margin_width": fl_attr_hspacing, "color": cl_text }, "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_CENTER, "margin_height": fl_attr_spacing, "margin_width": fl_attr_hspacing, "color": cl_text }, "Label::attribute_name:hovered": {"color": cl_text_hovered}, "Label::header_attribute_name": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text }, "Label::details": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text_blue, "font_size": 19, }, "Label::layers": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text_gray, "font_size": 19, }, "Label::attribute_r": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_attribute_red }, "Label::attribute_g": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_attribute_green }, "Label::attribute_b": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_attribute_blue }, # for Gradient Float Slider "Slider::float_slider":{ "background_color": cl_widget_background, "secondary_color": cl_slider, "border_radius": 3, "corner_flag": ui.CornerFlag.ALL, "draw_mode": ui.SliderDrawMode.FILLED, }, # for color slider "Circle::slider_handle":{"background_color": 0x0, "border_width": 2, "border_color": cl_combobox_background}, # for Value Changed Widget "Rectangle::attribute_changed": {"background_color":cl_attribute_changed, "border_radius": 2}, "Rectangle::attribute_default": {"background_color":cl_attribute_default, "border_radius": 1}, # all the images "Image::pin": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/Pin.svg"}, "Image::expansion": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/Details_options.svg"}, "Image::transform": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/offset_dark.svg"}, "Image::link": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/link_active_dark.svg"}, "Image::on_off": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/on_off.svg"}, "Image::header_frame": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/head.png"}, "Image::checked": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/checked.svg"}, "Image::unchecked": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/unchecked.svg"}, "Image::separator":{"image_url": f"{EXTENSION_FOLDER_PATH}/icons/separator.svg"}, "Image::collapsable_opened": {"color": cl_text, "image_url": f"{EXTENSION_FOLDER_PATH}/icons/closed.svg"}, "Image::collapsable_closed": {"color": cl_text, "image_url": f"{EXTENSION_FOLDER_PATH}/icons/open.svg"}, "Image::combobox": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/combobox_bg.svg"}, # for Gradient Image "ImageWithProvider::gradient_slider":{"border_radius": 4, "corner_flag": ui.CornerFlag.ALL}, "ImageWithProvider::button_background_gradient": {"border_radius": 3, "corner_flag": ui.CornerFlag.ALL}, # for Customized ComboBox "ComboBox::dropdown_menu":{ "color": cl_text, # label color "background_color": cl_combobox_background, "secondary_color": 0x0, # button background color }, } def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = (hex >> 16) & 255 alpha = (hex >> 24) & 255 rgba_values = [red, green, blue, alpha] return rgba_values def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)] return (color[3] << 8 * 3) + (color[2] << 8 * 2) + (color[1] << 8 * 1) + color[0] def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) if idx == step_size: color = colors[-1] else: color = _interpolate_color(colors[idx], colors[idx+1], percentage) return color def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) _byte_provider = ui.ByteImageProvider() _byte_provider.set_bytes_data(data, [len(colors), 1]) return _byte_provider def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name) return byte_provider
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/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__ = ["ExampleWindowExtension"] from .window import PropertyWindowExample from functools import partial import asyncio import omni.ext import omni.kit.ui import omni.ui as ui class ExampleWindowExtension(omni.ext.IExt): """The entry point for Gradient Style Window Example""" WINDOW_NAME = "Gradient Style Window Example" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Put the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(ExampleWindowExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user pressed "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = PropertyWindowExample(ExampleWindowExtension.WINDOW_NAME, width=450, height=900) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/__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__ = ["ExampleWindowExtension", "PropertyWindowExample"] from .extension import ExampleWindowExtension from .window import PropertyWindowExample
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/collapsable_widget.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__ = ["CustomCollsableFrame"] import omni.ui as ui def build_collapsable_header(collapsed, title): """Build a custom title of CollapsableFrame""" with ui.HStack(): ui.Spacer(width=10) ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=16, height=16) class CustomCollsableFrame: """The compound widget for color input""" def __init__(self, frame_name, collapsed=False): with ui.ZStack(): self.collapsable_frame = ui.CollapsableFrame( frame_name, name="group", build_header_fn=build_collapsable_header, collapsed=collapsed) with ui.VStack(): ui.Spacer(height=29) with ui.HStack(): ui.Spacer(width=20) ui.Image(name="separator", fill_policy=ui.FillPolicy.STRETCH, height=15) ui.Spacer(width=20)
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/color_widget.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__ = ["ColorWidget"] from ctypes import Union from typing import List, Optional import omni.ui as ui from .style import build_gradient_image, cl_attribute_red, cl_attribute_green, cl_attribute_blue, cl_attribute_dark SPACING = 16 class ColorWidget: """The compound widget for color input""" def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = args self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.__multifield: Optional[ui.MultiFloatDragField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__draw_colorpicker = kwargs.pop("draw_colorpicker", True) self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__model = None self.__multifield = None self.__colorpicker = None self.__frame = None def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__root_frame, attr) @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__multifield: return self.__multifield.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__multifield.model = value self.__colorpicker.model = value def _build_fn(self): def _on_value_changed(model, rect_changed, rect_default): if model.get_item_value_model().get_value_as_float() != 0: rect_changed.visible = False rect_default.visible = True else: rect_changed.visible = True rect_default.visible = False def _restore_default(model, rect_changed, rect_default): items = model.get_item_children() for id, item in enumerate(items): model.get_item_value_model(item).set_value(self.__defaults[id]) rect_changed.visible = False rect_default.visible = True with ui.HStack(spacing=SPACING): # The construction of multi field depends on what the user provided, # defaults or a model if self.__model: # the user provided a model self.__multifield = ui.MultiFloatDragField( min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color" ) model = self.__model else: # the user provided a list of default values with ui.ZStack(): with ui.HStack(): self.color_button_gradient_R = build_gradient_image([cl_attribute_dark, cl_attribute_red], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_G = build_gradient_image([cl_attribute_dark, cl_attribute_green], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_B = build_gradient_image([cl_attribute_dark, cl_attribute_blue], 22, "button_background_gradient") ui.Spacer(width=2) with ui.HStack(): with ui.VStack(): ui.Spacer(height=1) self.__multifield = ui.MultiFloatDragField( *self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color") ui.Spacer(width=3) with ui.HStack(spacing=22): labels = ["R", "G", "B"] if self.__draw_colorpicker else ["X", "Y", "Z"] ui.Label(labels[0], name="attribute_r") ui.Label(labels[1], name="attribute_g") ui.Label(labels[2], name="attribute_b") model = self.__multifield.model if self.__draw_colorpicker: self.__colorpicker = ui.ColorWidget(model, width=0) rect_changed, rect_default = self.__build_value_changed_widget() model.add_item_changed_fn(lambda model, i: _on_value_changed(model, rect_changed, rect_default)) rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(model, rect_changed, rect_default)) def __build_value_changed_widget(self): with ui.VStack(width=0): ui.Spacer(height=3) rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False) ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=3) rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True) return rect_changed, rect_default
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/window.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved./icons/ # # 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__ = ["PropertyWindowExample"] from ast import With from ctypes import alignment import omni.kit import omni.ui as ui from .style import main_window_style, get_gradient_color, build_gradient_image from .style import cl_combobox_background, cls_temperature_gradient, cls_color_gradient, cls_tint_gradient, cls_grey_gradient, cls_button_gradient from .color_widget import ColorWidget from .collapsable_widget import CustomCollsableFrame, build_collapsable_header LABEL_WIDTH = 120 SPACING = 10 def _get_plus_glyph(): return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg") def _get_search_glyph(): return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_search.svg") class PropertyWindowExample(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = main_window_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def _build_transform(self): """Build the widgets of the "Calculations" group""" with ui.ZStack(): with ui.VStack(): ui.Spacer(height=5) with ui.HStack(): ui.Spacer() ui.Image(name="transform", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=24, height=24) ui.Spacer(width=30) ui.Spacer() with CustomCollsableFrame("TRANSFORMS").collapsable_frame: with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=2) self._build_vector_widget("Position", 70) self._build_vector_widget("Rotation", 70) with ui.ZStack(): self._build_vector_widget("Scale", 85) with ui.HStack(): ui.Spacer(width=42) ui.Image(name="link", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20) def _build_path(self): CustomCollsableFrame("PATH", collapsed=True) def _build_light_properties(self): """Build the widgets of the "Parameters" group""" with CustomCollsableFrame("LIGHT PROPERTIES").collapsable_frame: with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=2) self._build_combobox("Type", ["Sphere Light", "Disk Light", "Rect Light"]) self.color_gradient_data, self.tint_gradient_data, self.grey_gradient_data = self._build_color_widget("Color") self._build_color_temperature() self.diffuse_button_data = self._build_gradient_float_slider("Diffuse Multiplier") self.exposture_button_data = self._build_gradient_float_slider("Exposture") self.intensity_button_data = self._build_gradient_float_slider("Intensity", default_value=3000, min=0, max=6000) self._build_checkbox("Normalize Power", False) self._build_combobox("Purpose", ["Default", "Customized"]) self.radius_button_data = self._build_gradient_float_slider("Radius") self._build_shaping() self.specular_button_data = self._build_gradient_float_slider("Specular Multiplier") self._build_checkbox("Treat As Point") def _build_line_dot(self, line_width, height): with ui.HStack(): ui.Spacer(width=10) with ui.VStack(width=line_width): ui.Spacer(height=height) ui.Line(name="group_line", alignment=ui.Alignment.TOP) with ui.VStack(width=6): ui.Spacer(height=height-2) ui.Circle(name="group_circle", width=6, height=6, alignment=ui.Alignment.BOTTOM) def _build_shaping(self): """Build the widgets of the "SHAPING" group""" with ui.ZStack(): with ui.HStack(): ui.Spacer(width=3) self._build_line_dot(10, 17) with ui.HStack(): ui.Spacer(width=13) with ui.VStack(): ui.Spacer(height=17) ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0) ui.Spacer(height=80) with ui.CollapsableFrame(" SHAPING", name="group", build_header_fn=build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): self.angle_button_data = self._build_gradient_float_slider("Cone Angle") self.softness_button_data = self._build_gradient_float_slider("Cone Softness") self.focus_button_data = self._build_gradient_float_slider("Focus") self.focus_color_data, self.focus_tint_data, self.focus_grey_data = self._build_color_widget("Focus Tint") def _build_vector_widget(self, widget_name, space): with ui.HStack(): ui.Label(widget_name, name="attribute_name", width=0) ui.Spacer(width=space) # The custom compound widget ColorWidget(1.0, 1.0, 1.0, draw_colorpicker=False) ui.Spacer(width=10) def _build_color_temperature(self): with ui.ZStack(): with ui.HStack(): ui.Spacer(width=10) with ui.VStack(): ui.Spacer(height=8) ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0) with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): self._build_line_dot(10, 8) ui.Label("Enable Color Temperature", name="attribute_name", width=0) ui.Spacer() ui.Image(name="on_off", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20) rect_changed, rect_default = self.__build_value_changed_widget() self.temperature_button_data = self._build_gradient_float_slider(" Color Temperature", default_value=6500.0) self.temperature_slider_data = self._build_slider_handle(cls_temperature_gradient) with ui.HStack(): ui.Spacer(width=10) ui.Line(name="group_line", alignment=ui.Alignment.TOP) def _build_color_widget(self, widget_name): with ui.ZStack(): with ui.HStack(): ui.Spacer(width=10) with ui.VStack(): ui.Spacer(height=8) ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0) with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): self._build_line_dot(40, 9) ui.Label(widget_name, name="attribute_name", width=0) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) ui.Spacer(width=10) color_data = self._build_slider_handle(cls_color_gradient) tint_data = self._build_slider_handle(cls_tint_gradient) grey_data = self._build_slider_handle(cls_grey_gradient) with ui.HStack(): ui.Spacer(width=10) ui.Line(name="group_line", alignment=ui.Alignment.TOP) return color_data, tint_data, grey_data def _build_slider_handle(self, colors): handle_Style = {"background_color": colors[0], "border_width": 2, "border_color": cl_combobox_background} def set_color(placer, handle, offset): # first clamp the value max = placer.computed_width - handle.computed_width if offset < 0: placer.offset_x = 0 elif offset > max: placer.offset_x = max color = get_gradient_color(placer.offset_x.value, max, colors) handle_Style.update({"background_color": color}) handle.style = handle_Style with ui.HStack(): ui.Spacer(width=18) with ui.ZStack(): with ui.VStack(): ui.Spacer(height=3) byte_provider = build_gradient_image(colors, 8, "gradient_slider") with ui.HStack(): handle_placer = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=0) with handle_placer: handle = ui.Circle(width=15, height=15, style=handle_Style) handle_placer.set_offset_x_changed_fn(lambda offset: set_color(handle_placer, handle, offset.value)) ui.Spacer(width=22) return byte_provider def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(name="main_frame"): with ui.VStack(height=0, spacing=SPACING): self._build_head() self._build_transform() self._build_path() self._build_light_properties() ui.Spacer(height=30) def _build_head(self): with ui.ZStack(): ui.Image(name="header_frame", height=150, fill_policy=ui.FillPolicy.STRETCH) with ui.HStack(): ui.Spacer(width=12) with ui.VStack(spacing=8): self._build_tabs() ui.Spacer(height=1) self._build_selection_widget() self._build_stage_path_widget() self._build_search_field() ui.Spacer(width=12) def _build_tabs(self): with ui.HStack(height=35): ui.Label("DETAILS", width=ui.Percent(17), name="details") with ui.ZStack(): ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35) with ui.HStack(): ui.Spacer(width=15) ui.Label("LAYERS | ", name="layers", width=0) ui.Label(f"{_get_plus_glyph()}", width=0) ui.Spacer() ui.Image(name="pin", width=20) def _build_selection_widget(self): with ui.HStack(height=20): add_button = ui.Button(f"{_get_plus_glyph()} Add", width=60, name="add") ui.Spacer(width=14) ui.StringField(name="add").model.set_value("(2 models selected)") ui.Spacer(width=8) ui.Image(name="expansion", width=20) def _build_stage_path_widget(self): with ui.HStack(height=20): ui.Spacer(width=3) ui.Label("Stage Path", name="header_attribute_name", width=70) ui.StringField(name="path").model.set_value("/World/environment/tree") def _build_search_field(self): with ui.HStack(): ui.Spacer(width=2) # would add name="search" style, but there is a bug to use glyph together with style # make sure the test passes for now ui.StringField(height=23).model.set_value(f"{_get_search_glyph()} Search") def _build_checkbox(self, label_name, default_value=True): def _restore_default(rect_changed, rect_default): image.name = "checked" if default_value else "unchecked" rect_changed.visible = False rect_default.visible = True def _on_value_changed(image, rect_changed, rect_default): image.name = "unchecked" if image.name == "checked" else "checked" if (default_value and image.name == "unchecked") or (not default_value and image.name == "checked"): rect_changed.visible = True rect_default.visible = False else: rect_changed.visible = False rect_default.visible = True with ui.HStack(): ui.Label(label_name, name=f"attribute_bool", width=self.label_width, height=20) name = "checked" if default_value else "unchecked" image =ui.Image(name=name, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=18, width=18) ui.Spacer() rect_changed, rect_default = self.__build_value_changed_widget() image.set_mouse_pressed_fn(lambda x, y, b, m: _on_value_changed(image, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(rect_changed, rect_default)) def __build_value_changed_widget(self): with ui.VStack(width=20): ui.Spacer(height=3) rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False) ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=3) rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True) return rect_changed, rect_default def _build_gradient_float_slider(self, label_name, default_value=0, min=0, max=1): def _on_value_changed(model, rect_changed, rect_defaul): if model.as_float == default_value: rect_changed.visible = False rect_defaul.visible = True else: rect_changed.visible = True rect_defaul.visible = False def _restore_default(slider): slider.model.set_value(default_value) with ui.HStack(): ui.Label(label_name, name=f"attribute_name", width=self.label_width) with ui.ZStack(): button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient") with ui.VStack(): ui.Spacer(height=1.5) with ui.HStack(): slider = ui.FloatSlider(name="float_slider", height=0, min=min, max=max) slider.model.set_value(default_value) ui.Spacer(width=1.5) ui.Spacer(width=4) rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider)) return button_background_gradient def _build_combobox(self, label_name, options): def _on_value_changed(model, rect_changed, rect_defaul): index = model.get_item_value_model().get_value_as_int() if index == 0: rect_changed.visible = False rect_defaul.visible = True else: rect_changed.visible = True rect_defaul.visible = False def _restore_default(combo_box): combo_box.model.get_item_value_model().set_value(0) with ui.HStack(): ui.Label(label_name, name=f"attribute_name", width=self.label_width) with ui.ZStack(): ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35) with ui.HStack(): ui.Spacer(width=10) with ui.VStack(): ui.Spacer(height=10) option_list = list(options) combo_box = ui.ComboBox(0, *option_list, name="dropdown_menu") with ui.VStack(width=0): ui.Spacer(height=10) rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes combo_box.model.add_item_changed_fn(lambda m, i: _on_value_changed(m, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(combo_box))
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/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_window import TestWindow
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/tests/test_window.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__ = ["TestWindow"] from omni.example.ui_gradient_window import PropertyWindowExample 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 TestWindow(OmniUiTest): async def test_general(self): """Testing general look of section""" window = PropertyWindowExample("Test") await omni.kit.app.get_app().next_update_async() await self.docked_test_window( window=window, width=450, height=600, ) # Wait for images for _ in range(20): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-22 ### Changed - Added README.md - Clean up the style a bit and change some of the widgets function name ## [1.0.0] - 2022-06-09 ### Added - Initial window
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/README.md
# Gradient Window (omni.example.ui_gradient_window) ![](../data/preview.png) # Overview In this example, we create a window which heavily uses graident style in various widgets. The window is build using `omni.ui`. It contains the best practices of how to build customized widgets and leverage to reuse them without duplicating the code. ## [Tutorial](../tutorial/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. [Get started with the tutorial.](../tutorial/tutorial.md) # Customized Widgets A customized widget can be a class or a function. It's not required to derive from anything. We build customized widget so that we can use them just like default `omni.ui` widgets which allows us to reuse the code and saves us from reinventing the wheel again and again. ## Gradient Image Gradient images are used a lot in this example. It is used in the customized slider and field background. Therefore, we encapsulate it into a function `build_gradient_image` which is a customized `ui.ImageWithProvider` under the hood. The `ImageWithProvider` has a source data which is generated by `ui.ByteImageProvider`. We define how to generate the byte data into a function called `generate_byte_data`. We use one pixel height data to generate the image data. For users' conveniences, we provide the function signature as an array of hex colors, so we provided a function to achieve `hex_to_color` conversion. ``` def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = (hex >> 16) & 255 alpha = (hex >> 24) & 255 rgba_values = [red, green, blue, alpha] return rgba_values def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) _byte_provider = ui.ByteImageProvider() _byte_provider.set_bytes_data(data, [len(colors), 1]) return _byte_provider def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name) return byte_provider ``` With this, the user will be able to generate gradient image easily which also allows flexibly set the height and style. Here are a couple of examples used in the example: ``` colors = cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")] byte_provider = build_gradient_image(colors, 8, "gradient_slider") cls_button_gradient = [cl("#232323"), cl("#656565")] button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient") ``` ![](../data/gradient_img.png) ## Value Changed Widget In this example, almost every attribute has got a widget which indicates whether the value has been changed or not. By default, the widget is a small gray rectangle, while the value has been changed it becomes a bigger blue rectangle. We wrapped this up into a function called `__build_value_changed_widget` and returns both rectangles so that the caller can switch the visiblity of them. It is not only an indicator of value change, it is also a button. While you click on it when the value has changed, it has the callback to restore the default value for the attribute. Since different attribute has different data model, the restore callbacks are added into different widgets instead of the value change widget itself. ## Gradient Float Slider Almost all the numeric attribute in this example is using gradient float slider which is defined by `_build_gradient_float_slider`. This customized float slider are consisted of three parts: the label, the float slider, and the value-changed-widget. The label is just a usual `ui.Label`. The slider is a normal `ui.FloatSlider` with a gradient image, composed by `ui.ZStack`. We also added the `add_value_changed_fn` callback for slider model change to trigger the value-changed-widget change visiblity and `rect_changed.set_mouse_pressed_fn` to add the callback to restore the default value of the silder. ``` rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider)) ``` ![](../data/gradient_float_slider.png) ## Customized CheckBox The customized Checkbox is defined by `_build_checkbox`. It is also consisted of three parts: the label, the check box, and the value-changed-widget. The label is just a usual `ui.Label`. For the check box, since we have completely two different images for the checked and unchecked status. Therefore, we use `ui.Image` as the base for the customized CheckBox. The `name` of the image is used to switch between the corresponding styles which changes the `image_url` for the image. The callbacks of value-changed-widget are added similarly as gradient float slider. ![](../data/checked.png) ![](../data/unchecked.png) ## Customized ComboBox The customized ComboBox is defined by `_build_combobox`. It is also consisted of three parts: the label, the ComnoBox, and the value-changed-widget. The label is just a usual `ui.Label`. The ComboBox is a normal `ui.ComboBox` with a gradient image, composed by `ui.ZStack`. The callbacks of value-changed-widget are added similarly as gradient float slider. ![](../data/combobox.png) ![](../data/combobox2.png) ## Customized CollsableFrame The customized CollsableFrame is wrapped in `CustomCollsableFrame` class. It is a normal `ui.CollapsableFrame` with a customized header. It is the main widget groups other widgets as a collapsable frame. ![](../data/collapse_frame.png) ## Customized ColorWidget The customized ColorWidget is wrapped in `ColorWidget` class. ![](../data/color_widget.png) The RGB values `self.__multifield` is represented by a normal `ui.MultiFloatDragField`, composed with three gradient images of red, green and blue using `ui.ZStack`, as well as the lable and circle dots in between the three values. The colorpicker is just a normal `ui.ColorWidget`, which shares the same model of `self.__multifield`, so that these two widgets are connected. We also added the `add_item_changed_fn` callback for the shared model. When the model item changes, it will trigger the value-changed-widget to switch the visiblity and `rect_changed.set_mouse_pressed_fn` to add the callback to restore the default value for the shared model. # Style We kept all the styles of all the widgets in `style.py`. One advantage is that specific style or colors could be reused without duplication. The other advantage is that users don't need to go through the lengthy widgets code to change the styles. All the styles are recommended to be arranged and named in a self-explanatory way. # Window It's handy to derive a custom window from the class `ui.Window`. The UI can be defined right in __init__, so it's created immediately or it can be defined in a `set_build_fn` callback and it will be created when the window is visible. The later one is used in this example. ``` class PropertyWindowExample(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) ``` Inside the `self._build_fn`, we use the customized widgets to match the design layout for the window. # Extension When the extension starts up, we register a new menu item that controls the window and shows the window. A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit. ``` ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) ``` When the extension shuts down, we remove the menu item and deregister the window callback.
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/index.rst
omni.example.ui_gradient_window ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/tutorial/tutorial.md
# How to Understand and Navigate Omniverse Code from Other Developers This tutorial teaches how to access, navigate and understand source code from extensions written by other developers. This is done by opening an extension, navigating to its code and learning how its user interface is put together. It also teaches how custom widgets are organized. With this information developers can find user interface elements in other developers' extensions and re-use or extend them. The extension itself is a UI mockup for a [julia quaternion modeling tool](http://paulbourke.net/fractals/quatjulia/). ## Learning Objectives - Access Source of Omniverse Extensions - Understand UI Code Structure - Re-use Widget Code from Other Developers ## Prerequisites - [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_window/tutorial/tutorial.md) - [UI Gradient Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_gradient_window/tutorial/tutorial.md) - Omniverse Code version 2022.1.1 or higher - Working understanding of GitHub - Visual Studio Code ## Step 1: Clone the Repository Clone the `main` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window): ```shell git clone https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git ``` This repository contains the code you use in this tutorial. ## Step 2: Add the Extension to Omniverse Code In order to use and test your Extension, you need to add it to Omniverse Code. ### Step 2.1: Navigate to the Extensions List In Omniverse Code, navigate to the *Extensions* panel: ![Click the Extensions panel](Images/extensions_panel.png) Here, you see a list of Omniverse Extensions that you can activate and use in Code. > **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**: > > ![Show the Extensions panel](Images/window_extensions.png) ### Step 2.2: Navigate to the *Extension Search Paths* Click the **gear** icon to open *Extension Search Paths*: ![Click the gear icon](Images/extension_search_paths.png) In this panel, you can add your custom Extension to the Extensions list. ### Step 2.3: Create a New Search Path Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field: ![New search path](Images/new_search_path_ui-window.png) When you submit your new search path, you should be able to find your extension in the *Extensions* list. Search for "omni.example.ui_" to filter down the list. Activate the "OMNI.UI JULIA QUATERNION MO..." Extension: ![Reticle extensions list](Images/window_extensions_list_ui-julia.png) Now that your Extension is added and enabled, you can make changes to the code and see them in your Application. You will see the user interface pictured below: <p align="center"> <img src="Images/JuliaUI.png" width=25%> <p> ## Step 3: View the User Interface and Source Code ### Step 3.1: Review the User Interface Take a moment to think like a connoisseur of excellent user interface elements. What aspects of this user interface are worth collecting? Notice the styling on the collapsable frames, the backgrounds on the sliders. Edit some of the values and notice that the arrow on the right is now highlighted in blue. Click on that arrow and notice that the slider returns to a default value. Focus on the best aspects because you can collect those and leave the lesser features behind. ### Step 3.2: Access the Source Code Now, go back to the extensions window and navigate to the `Julia` extension. Along the top of its details window lies a row of icons as pictured below: <p align="center"> <img src="Images/VisualStudioIcon.png" width=75%> <p> Click on the Visual Studio icon to open the Extension's source in Visual Studio. This is a great way to access extension source code and learn how they were written. ## Step 4: Find `extension.py` This section explains how to start navigation of an extension's source code. ### Step 4.1: Access the Extension Source Code Open the Visual Studio window and expand the `exts` folder. The image below will now be visible: <p align="center"> <img src="Images/FolderStructure.png" width=35%> <p> Click on `omni\example\ui_julia_modeler` to expand it and see the files in that folder as shown below: <p align="center"> <img src="Images/DevFiles.png" width=35%> <p> ### Step 4.2: Open `extension.py` The file named `extension.py` is a great place to start. It contains a class that derives from `omni.ext.IExt`. ### Step 4.3: Find the `on_startup` Function Look for the `on_startup`. This function runs when the extension first starts and is where the UI should be built. It has been included below: ```Python def on_startup(self): # The ability to show the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None)) # Add the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( JuliaModelerExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(JuliaModelerExtension.WINDOW_NAME) ``` This function does a few steps that are common for a window-based extension. Not all extensions will be written in exactly this way, but these are best practices and are good things to look for. 1. It registers a `show` function with the application. 2. It adds the extension to the `Window` application menu. 3. It requests that the window be shown using the `show` function registered before. ### Step 4.4: Find the Function that Builds the Window What function has been registered to show the `Julia` extension window? It is `self.show_window()`. Scroll down until you find it in `extension.py`. It has been included below for convenience: ```Python def show_window(self, menu, value): if value: self._window = JuliaModelerWindow( JuliaModelerExtension.WINDOW_NAME, width=WIN_WIDTH, height=WIN_HEIGHT) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False ``` In this function `value` is a boolean that is `True` if the window should be shown and `False` if the window should be hidden. Take a look at the code block that will run if `value` is `True` and you will see that `self._window` is set equal to a class constructor. ### Step 4.5: Navigate to the Window Class To find out where this class originates, hold the `ctrl` button and click on `JuliaModelerWindow` in the third line of the function. This will navigate to that symbol's definition. In this case it opens the `window.py` file and takes the cursor to definition of the `JuliaModelerWindow` class. The next section explores this class and how the window is built. ## Step 5: Explore `JuliaModelerWindow` This sections explores the `JuliaModelerWindow` class, continuing the exploration of this extension, navigating the code that builds the UI from the top level towards specific elements. ### Step 5.1: Read `show_window()` The `show_window()` function in the previous section called the constructor from the `JuliaModelerWindow` class. The constructor in Python is the `__init__()` function and is copied below: ```Python def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = ATTR_LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = julia_modeler_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) ``` The first statement simply sets a label width. The next statement calls `super().__init__()`. This initializes all base classes of `JuliaModelerWindow`. This has to do with inheritance, a topic that will be briefly covered later in this tutorial. The third statement sets the window style, which is useful information, but is the topic of another tutorial. These styles are contained in `style.py` for the curious. Finally, the function registers the `self._build_fn` callback as the frame's build function. This is the function of interest. ### Step 5.2: Navigate to `_build_fn()` Hold ctrl and click on `self._build_fn` which has been reproduced below: ```Python def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(name="window_bg", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): self._build_title() self._build_calculations() self._build_parameters() self._build_light_1() self._build_scene() ``` This function builds an outer scrolling frame, a vertical stack, and then builds a few sections to add to that stack. Each of these methods has useful information worth taking a look at, but this tutorial will focus on `_build_parameters()`. ### Step 5.3: Navigate to `_build_parameters()` Navigate to `_build_parameters` using ctrl+click. As usual, it is duplicated below: ```Python def _build_parameters(self): """Build the widgets of the "Parameters" group""" with ui.CollapsableFrame("Parameters".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=-2, max=2, display_range=True, label="Iterations", default_val=0.75) CustomSliderWidget(min=0, max=2, display_range=True, label="i", default_val=0.65) CustomSliderWidget(min=0, max=2, display_range=True, label="j", default_val=0.25) CustomSliderWidget(min=0, max=2, display_range=True, label="k", default_val=0.55) CustomSliderWidget(min=0, max=3.14, display_range=True, label="Theta", default_val=1.25) ``` Here is a collapsable frame, a vertical stack, and then instead of the horizontal stacks with combinations of labels and controls seen in the `UI_Window` tutorial, there is a list of custom controls. In fact, scrolling up and down the class to look at the other build functions reveals quite a few custom controls. These custom controls are what gives the user interface a variety of controls, maintains a consistent look and feel, and gives them all the same functionality to restore a default value. Taking a closer at constructor for each `CustomSliderWidget` above reveals that each sets a default value for its respective widget. ### Step 5.4: Identify Custom Widgets In the folder structure are a few files that look like they contain custom widgets, namely: - `custom_base_widget.py` - `custom_bool_widget.py` - `custom_color_widget.py` - `custom_combobox_widget.py` - `custom_multifield_widget.py` - `custom_path_widget.py` - `custom_radio_widget.py` - `custom_slider_widget.py` ### Step 5.5: Recognize Hierarchical Class Structure `custom_base_widget.py` contains `CustomBaseWidget` which many of the other widgets `inherit` from. For example, open one of the widget modules such as `custom_slider_widget.py` and take a look at its class declaration: ```Python class CustomSliderWidget(CustomBaseWidget): ``` There, in parentheses is `CustomBaseWidget`, confirming that this is a hierarchical class structure with the specific widgets inheriting from `CustomBaseWidget`. For those unfamiliar with inheritance, a quick explanation in the next section is in order. ## Step 6: Inheritance In Python (and other programming languages) it is possible to group classes together if they have some things in common but are different in other ways and this is called inheritance. With inheritance, a base class is made containing everything in common, and sub-classes are made that contain the specific elements of each object. 2D Shapes are a classic example. <p align="center"> <img src="Images/Shape.svg" width=35%> <p> In this case all shapes have a background color, you can get their area, and you can get their perimeter. Circles, however have a radius where rectangles have a length and a width. When you use inheritance, the common code can be in a single location in the base class where the sub-classes contain the specific code. The next step is to look at `CustomBaseWidget` to see what all of the custom widgets have in common. Either navigate to `custom_base_widget.py` or ctrl+click on `CustomBaseWidget` in any of the sub-classes. Inheritance is one element of object-oriented programming (OOP). To learn more about OOP, check out [this video](https://www.youtube.com/watch?v=pTB0EiLXUC8). To learn more about inheritance syntax in Python, check out [this article](https://www.w3schools.com/Python/Python_inheritance.asp). ## Step 7: Explore `custom_base_widget.py` This section explores the code in `custom_base_widget.py` ### Step 7.1: Identify Code Patterns The developer who wrote this extension has a consistent style, so you should see a lot in common between this class and `JuliaModelerWindow` class. It starts with `__init__()` and `destroy()` functions and further down has a few `_build` functions: `_build_head()`, `_build_body()`, `_build_tail()`, and `_build_fn()`. The `_build_fn()` function is called from the constructor and in turn calls each of the other build functions. ### Step 7.2: Characterize Custom Widget Layout From this it can be determined that each of the custom widgets has a head, body and tail and if we look at the controls in the UI this makes sense as illustrated below: <p align="center"> <img src="Images/HeadBodyTail.png" width=35%> <p> This image shows a vertical stack containing 5 widgets. Each widget is a collection of smaller controls. The first highlighted column contains the head of each widget, the second contains their content and the third holds each tail. This tutorial will now look at how the head, content, and tail are created in turn. ### Step 7.3: Inspect `_build_head()` `_build_head()` is as follows: ```Python def _build_head(self): """Build the left-most piece of the widget line (label in this case)""" ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) ``` It has a single label that displays the text passed into the widget's constructor. This makes sense when looking at the UI, each control has a label and they are all aligned. ### Step 7.4: Inspect `_build_body()` `_build_body()` is as follows: ```Python def _build_body(self): """Build the custom part of the widget. Most custom widgets will override this method, as it is where the meat of the custom widget is. """ ui.Spacer() ``` In the comments it says that most widgets will override this method. This has to do with the inheritance mentioned before. Just like with `GetArea()` in the shape class, each shape has an area, but that area is calculated differently. In this situation, the function is placed in the base class but each sub-class implements that function in its own way. In this case `_build_body()` is essentially empty, and if you look at each custom widget sub-class, they each have their own `_build_body()` function that runs in place of the one in `CustomBaseWidget`. ### Step 7.5: Inspect `_build_tail()` Finally, the `_build_tail()` function contains the following code: ```Python def _build_tail(self): """Build the right-most piece of the widget line. In this case, we have a Revert Arrow button at the end of each widget line. """ with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # call back for revert_img click, to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) ``` This function draws the reverse arrow that lets a user revert a control to a default value and is the same for every custom control. In this way the author of this extension has ensured that all of the custom widgets are well aligned, have a consistent look and feel and don't have the same code repeated in each class. They each implemented their own body, but other than that are the same. The next section will show how the widget body is implmeneted in the `CustomSliderWidget` class. ## Step 8: Explore `custom_slider_widget.py` To view the `CustomSliderWidget` class open `custom_slider_widget.py` and take a look at the `build_body()` function which contains the following code: ```Python def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() ``` This function is significantly longer than others in this tutorial and could be overwhelming at first glance. This is the perfect situation to take advantage of code folding. If you hover over the blank column between the line numbers and the code window inside visual studio, downward carrats will appear next to code blocks. Click on the carrats next to the two vertical stacks to collapse those blocks of code and make the function easier to navigate. <p align="center"> <img src="Images/FoldedCode.png" width=75%> <p> Now it's clear that this function creates an outer horizontal stack which contains two vertical stacks. If you dig deeper you will find that the first vertical stack contains a float slider with an image background. In order to learn how to create an image background like this, check out the [UI Gradient Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_gradient_window/tutorial/tutorial.md). The second vertical stack contains a number field which displays the number set by the float slider. If you take a look at the other custom widgets, you will see that each of them has its own `_build_body` function. Exploring these is a great way to get ideas on how to create your own user interface. ## Step 9: Reusing UI code By exploring extensions in this manner, developers can get a head start creating their own user interfaces. This can range from copying and pasting controls from other extensions, to creating new sub-classes on top of existing base classes, to simply reading and understanding the code written by others to learn from it. Hopefully this tutorial has given you a few tips and tricks as you navigate code written by others. ## Conclusion This tutorial has explained how to navigate the file and logical structure of a typical Omniverse extension. In addition it has explained how custom widgets work, even when they are part of a hieararchical inheritance structure.
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/config/extension.toml
[package] title = "omni.ui Julia Quaternion Modeler Example" description = "A window example with custom UI elements" version = "1.0.1" category = "Example" authors = ["Alan Cheney"] repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows" keywords = ["example", "window", "ui", "julia_modeler"] changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.menu.utils" = {} "omni.kit.window.popup_dialog" = {} [[python.module]] name = "omni.example.ui_julia_modeler" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_radio_collection.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__ = ["CustomRadioCollection"] from typing import List, Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH SPACING = 5 class CustomRadioCollection: """A custom collection of radio buttons. The group_name is on the first line, and each label and radio button are on subsequent lines. This one does not inherit from CustomBaseWidget because it doesn't have the same Head label, and doesn't have a Revert button at the end. """ def __init__(self, group_name: str, labels: List[str], model: ui.AbstractItemModel = None, default_value: bool = True, **kwargs): self.__group_name = group_name self.__labels = labels self.__default_val = default_value self.__images = [] self.__selection_model = ui.SimpleIntModel(default_value) self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__images = [] self.__selection_model = None self.__frame = None @property def model(self) -> Optional[ui.AbstractValueModel]: """The widget's model""" if self.__selection_model: return self.__selection_model @model.setter def model(self, value: int): """The widget's model""" self.__selection_model.set(value) def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__frame, attr) def _on_value_changed(self, index: int = 0): """Set states of all radio buttons so only one is On.""" self.__selection_model.set_value(index) for i, img in enumerate(self.__images): img.checked = i == index img.name = "radio_on" if img.checked else "radio_off" def _build_fn(self): """Main meat of the widget. Draw the group_name label, label and radio button for each row, and set up callbacks to keep them updated. """ with ui.VStack(spacing=SPACING): ui.Spacer(height=2) ui.Label(self.__group_name.upper(), name="radio_group_name", width=ATTR_LABEL_WIDTH) for i, label in enumerate(self.__labels): with ui.HStack(): ui.Label(label, name="attribute_name", width=ATTR_LABEL_WIDTH) with ui.HStack(): with ui.VStack(): ui.Spacer(height=2) self.__images.append( ui.Image( name=("radio_on" if self.__default_val == i else "radio_off"), fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) ) ui.Spacer() ui.Spacer(height=2) # Set up a mouse click callback for each radio button image for i in range(len(self.__labels)): self.__images[i].set_mouse_pressed_fn( lambda x, y, b, m, i=i: self._on_value_changed(i))
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/style.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__ = ["julia_modeler_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) ATTR_LABEL_WIDTH = 150 BLOCK_HEIGHT = 22 TAIL_WIDTH = 35 WIN_WIDTH = 400 WIN_HEIGHT = 930 # Pre-defined constants. It's possible to change them at runtime. cl.window_bg_color = cl(0.2, 0.2, 0.2, 1.0) cl.window_title_text = cl(.9, .9, .9, .9) cl.collapsible_header_text = cl(.8, .8, .8, .8) cl.collapsible_header_text_hover = cl(.95, .95, .95, 1.0) cl.main_attr_label_text = cl(.65, .65, .65, 1.0) cl.main_attr_label_text_hover = cl(.9, .9, .9, 1.0) cl.multifield_label_text = cl(.65, .65, .65, 1.0) cl.combobox_label_text = cl(.65, .65, .65, 1.0) cl.field_bg = cl(0.18, 0.18, 0.18, 1.0) cl.field_border = cl(1.0, 1.0, 1.0, 0.2) cl.btn_border = cl(1.0, 1.0, 1.0, 0.4) cl.slider_fill = cl(1.0, 1.0, 1.0, 0.3) cl.revert_arrow_enabled = cl(.25, .5, .75, 1.0) cl.revert_arrow_disabled = cl(.35, .35, .35, 1.0) cl.transparent = cl(0, 0, 0, 0) fl.main_label_attr_hspacing = 10 fl.attr_label_v_spacing = 3 fl.collapsable_group_spacing = 2 fl.outer_frame_padding = 15 fl.tail_icon_width = 15 fl.border_radius = 3 fl.border_width = 1 fl.window_title_font_size = 18 fl.field_text_font_size = 14 fl.main_label_font_size = 14 fl.multi_attr_label_font_size = 14 fl.radio_group_font_size = 14 fl.collapsable_header_font_size = 13 fl.range_text_size = 10 url.closed_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/closed.svg" url.open_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/opened.svg" url.revert_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/revert_arrow.svg" url.checkbox_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_on.svg" url.checkbox_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_off.svg" url.radio_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_on.svg" url.radio_btn_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_off.svg" url.diag_bg_lines_texture = f"{EXTENSION_FOLDER_PATH}/icons/diagonal_texture_screenshot.png" # The main style dict julia_modeler_style = { "Button::tool_button": { "background_color": cl.field_bg, "margin_height": 0, "margin_width": 6, "border_color": cl.btn_border, "border_width": fl.border_width, "font_size": fl.field_text_font_size, }, "CollapsableFrame::group": { "margin_height": fl.collapsable_group_spacing, "background_color": cl.transparent, }, # TODO: For some reason this ColorWidget style doesn't respond much, if at all (ie, border_radius, corner_flag) "ColorWidget": { "border_radius": fl.border_radius, "border_color": cl(0.0, 0.0, 0.0, 0.0), }, "Field": { "background_color": cl.field_bg, "border_radius": fl.border_radius, "border_color": cl.field_border, "border_width": fl.border_width, }, "Field::attr_field": { "corner_flag": ui.CornerFlag.RIGHT, "font_size": 2, # fl.field_text_font_size, # Hack to allow for a smaller field border until field padding works }, "Field::attribute_color": { "font_size": fl.field_text_font_size, }, "Field::multi_attr_field": { "padding": 4, # TODO: Hacky until we get padding fix "font_size": fl.field_text_font_size, }, "Field::path_field": { "corner_flag": ui.CornerFlag.RIGHT, "font_size": fl.field_text_font_size, }, "HeaderLine": {"color": cl(.5, .5, .5, .5)}, "Image::collapsable_opened": { "color": cl.collapsible_header_text, "image_url": url.open_arrow_icon, }, "Image::collapsable_opened:hovered": { "color": cl.collapsible_header_text_hover, "image_url": url.open_arrow_icon, }, "Image::collapsable_closed": { "color": cl.collapsible_header_text, "image_url": url.closed_arrow_icon, }, "Image::collapsable_closed:hovered": { "color": cl.collapsible_header_text_hover, "image_url": url.closed_arrow_icon, }, "Image::radio_on": {"image_url": url.radio_btn_on_icon}, "Image::radio_off": {"image_url": url.radio_btn_off_icon}, "Image::revert_arrow": { "image_url": url.revert_arrow_icon, "color": cl.revert_arrow_enabled, }, "Image::revert_arrow:disabled": {"color": cl.revert_arrow_disabled}, "Image::checked": {"image_url": url.checkbox_on_icon}, "Image::unchecked": {"image_url": url.checkbox_off_icon}, "Image::slider_bg_texture": { "image_url": url.diag_bg_lines_texture, "border_radius": fl.border_radius, "corner_flag": ui.CornerFlag.LEFT, }, "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_TOP, "margin_height": fl.attr_label_v_spacing, "margin_width": fl.main_label_attr_hspacing, "color": cl.main_attr_label_text, "font_size": fl.main_label_font_size, }, "Label::attribute_name:hovered": {"color": cl.main_attr_label_text_hover}, "Label::collapsable_name": {"font_size": fl.collapsable_header_font_size}, "Label::multi_attr_label": { "color": cl.multifield_label_text, "font_size": fl.multi_attr_label_font_size, }, "Label::radio_group_name": { "font_size": fl.radio_group_font_size, "alignment": ui.Alignment.CENTER, "color": cl.main_attr_label_text, }, "Label::range_text": { "font_size": fl.range_text_size, }, "Label::window_title": { "font_size": fl.window_title_font_size, "color": cl.window_title_text, }, "ScrollingFrame::window_bg": { "background_color": cl.window_bg_color, "padding": fl.outer_frame_padding, "border_radius": 20 # Not obvious in a window, but more visible with only a frame }, "Slider::attr_slider": { "draw_mode": ui.SliderDrawMode.FILLED, "padding": 0, "color": cl.transparent, # Meant to be transparent, but completely transparent shows opaque black instead. "background_color": cl(0.28, 0.28, 0.28, 0.01), "secondary_color": cl.slider_fill, "border_radius": fl.border_radius, "corner_flag": ui.CornerFlag.LEFT, # TODO: Not actually working yet OM-53727 }, # Combobox workarounds "Rectangle::combobox": { # TODO: remove when ComboBox can have a border "background_color": cl.field_bg, "border_radius": fl.border_radius, "border_color": cl.btn_border, "border_width": fl.border_width, }, "ComboBox::dropdown_menu": { "color": cl.combobox_label_text, # label color "padding_height": 1.25, "margin": 2, "background_color": cl.field_bg, "border_radius": fl.border_radius, "font_size": fl.field_text_font_size, "secondary_color": cl.transparent, # button background color }, "Rectangle::combobox_icon_cover": {"background_color": cl.field_bg} }
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/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__ = ["JuliaModelerExtension"] import asyncio from functools import partial import omni.ext import omni.kit.ui import omni.ui as ui from .style import WIN_WIDTH, WIN_HEIGHT from .window import JuliaModelerWindow class JuliaModelerExtension(omni.ext.IExt): """The entry point for Julia Modeler Example Window.""" WINDOW_NAME = "Julia Quaternion Modeler" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None)) # Add the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( JuliaModelerExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(JuliaModelerExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(JuliaModelerExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user presses "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating a new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = JuliaModelerWindow( JuliaModelerExtension.WINDOW_NAME, width=WIN_WIDTH, height=WIN_HEIGHT) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/__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. # from .extension import JuliaModelerExtension
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_bool_widget.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__ = ["CustomBoolWidget"] import omni.ui as ui from .custom_base_widget import CustomBaseWidget class CustomBoolWidget(CustomBaseWidget): """A custom checkbox or switch widget""" def __init__(self, model: ui.AbstractItemModel = None, default_value: bool = True, **kwargs): self.__default_val = default_value self.__bool_image = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__bool_image = None def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.__bool_image.checked = self.__default_val self.__bool_image.name = ( "checked" if self.__bool_image.checked else "unchecked" ) self.revert_img.enabled = False def _on_value_changed(self): """Swap checkbox images and set revert_img to correct state.""" self.__bool_image.checked = not self.__bool_image.checked self.__bool_image.name = ( "checked" if self.__bool_image.checked else "unchecked" ) self.revert_img.enabled = self.__default_val != self.__bool_image.checked def _build_body(self): """Main meat of the widget. Draw the appropriate checkbox image, and set up callback. """ with ui.HStack(): with ui.VStack(): # Just shift the image down slightly (2 px) so it's aligned the way # all the other rows are. ui.Spacer(height=2) self.__bool_image = ui.Image( name="checked" if self.__default_val else "unchecked", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) # Let this spacer take up the rest of the Body space. ui.Spacer() self.__bool_image.set_mouse_pressed_fn( lambda x, y, b, m: self._on_value_changed())
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_multifield_widget.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__ = ["CustomMultifieldWidget"] from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget class CustomMultifieldWidget(CustomBaseWidget): """A custom multifield widget with a variable number of fields, and customizable sublabels. """ def __init__(self, model: ui.AbstractItemModel = None, sublabels: Optional[List[str]] = None, default_vals: Optional[List[float]] = None, **kwargs): self.__field_labels = sublabels or ["X", "Y", "Z"] self.__default_vals = default_vals or [0.0] * len(self.__field_labels) self.__multifields = [] # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__multifields = [] @property def model(self, index: int = 0) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__multifields: return self.__multifields[index].model @model.setter def model(self, value: ui.AbstractItemModel, index: int = 0): """The widget's model""" self.__multifields[index].model = value def _restore_default(self): """Restore the default values.""" if self.revert_img.enabled: for i in range(len(self.__multifields)): model = self.__multifields[i].model model.as_float = self.__default_vals[i] self.revert_img.enabled = False def _on_value_changed(self, val_model: ui.SimpleFloatModel, index: int): """Set revert_img to correct state.""" val = val_model.as_float self.revert_img.enabled = self.__default_vals[index] != val def _build_body(self): """Main meat of the widget. Draw the multiple Fields with their respective labels, and set up callbacks to keep them updated. """ with ui.HStack(): for i, (label, val) in enumerate(zip(self.__field_labels, self.__default_vals)): with ui.HStack(spacing=3): ui.Label(label, name="multi_attr_label", width=0) model = ui.SimpleFloatModel(val) # TODO: Hopefully fix height after Field padding bug is merged! self.__multifields.append( ui.FloatField(model=model, name="multi_attr_field")) if i < len(self.__default_vals) - 1: # Only put space between fields and not after the last one ui.Spacer(width=15) for i, f in enumerate(self.__multifields): f.model.add_value_changed_fn(lambda v: self._on_value_changed(v, i))
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_color_widget.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__ = ["CustomColorWidget"] from ctypes import Union import re from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget from .style import BLOCK_HEIGHT COLOR_PICKER_WIDTH = ui.Percent(35) FIELD_WIDTH = ui.Percent(65) COLOR_WIDGET_NAME = "color_block" SPACING = 4 class CustomColorWidget(CustomBaseWidget): """The compound widget for color input. The color picker widget model converts its 3 RGB values into a comma-separated string, to display in the StringField. And vice-versa. """ def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = [a for a in args if a is not None] self.__strfield: Optional[ui.StringField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__color_sub = None self.__strfield_sub = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__strfield = None self.__colorpicker = None self.__color_sub = None self.__strfield_sub = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__colorpicker: return self.__colorpicker.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__colorpicker.model = value @staticmethod def simplify_str(val): s = str(round(val, 3)) s_clean = re.sub(r'0*$', '', s) # clean trailing 0's s_clean = re.sub(r'[.]$', '', s_clean) # clean trailing . s_clean = re.sub(r'^0', '', s_clean) # clean leading 0 return s_clean def set_color_stringfield(self, item_model: ui.AbstractItemModel, children: List[ui.AbstractItem]): """Take the colorpicker model that has 3 child RGB values, convert them to a comma-separated string, and set the StringField value to that string. Args: item_model: Colorpicker model children: child Items of the colorpicker """ field_str = ", ".join([self.simplify_str(item_model.get_item_value_model(c).as_float) for c in children]) self.__strfield.model.set_value(field_str) if self.revert_img: self._on_value_changed() def set_color_widget(self, str_model: ui.SimpleStringModel, children: List[ui.AbstractItem]): """Parse the new StringField value and set the ui.ColorWidget component items to the new values. Args: str_model: SimpleStringModel for the StringField children: Child Items of the ui.ColorWidget's model """ joined_str = str_model.get_value_as_string() for model, comp_str in zip(children, joined_str.split(",")): comp_str_clean = comp_str.strip() try: self.__colorpicker.model.get_item_value_model(model).as_float = float(comp_str_clean) except ValueError: # Usually happens in the middle of typing pass def _on_value_changed(self, *args): """Set revert_img to correct state.""" default_str = ", ".join([self.simplify_str(val) for val in self.__defaults]) cur_str = self.__strfield.model.as_string self.revert_img.enabled = default_str != cur_str def _restore_default(self): """Restore the default values.""" if self.revert_img.enabled: field_str = ", ".join([self.simplify_str(val) for val in self.__defaults]) self.__strfield.model.set_value(field_str) self.revert_img.enabled = False def _build_body(self): """Main meat of the widget. Draw the colorpicker, stringfield, and set up callbacks to keep them updated. """ with ui.HStack(spacing=SPACING): # The construction of the widget depends on what the user provided, # defaults or a model if self.existing_model: # the user provided a model self.__colorpicker = ui.ColorWidget( self.existing_model, width=COLOR_PICKER_WIDTH, height=BLOCK_HEIGHT, name=COLOR_WIDGET_NAME ) color_model = self.existing_model else: # the user provided a list of default values self.__colorpicker = ui.ColorWidget( *self.__defaults, width=COLOR_PICKER_WIDTH, height=BLOCK_HEIGHT, name=COLOR_WIDGET_NAME ) color_model = self.__colorpicker.model self.__strfield = ui.StringField(width=FIELD_WIDTH, name="attribute_color") self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn( lambda m, _, children=color_model.get_item_children(): self.set_color_stringfield(m, children)) self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn( lambda m, children=color_model.get_item_children(): self.set_color_widget(m, children)) # show data at the start self.set_color_stringfield(self.__colorpicker.model, children=color_model.get_item_children())
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_combobox_widget.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__ = ["CustomComboboxWidget"] from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget from .style import BLOCK_HEIGHT class CustomComboboxWidget(CustomBaseWidget): """A customized combobox widget""" def __init__(self, model: ui.AbstractItemModel = None, options: List[str] = None, default_value=0, **kwargs): self.__default_val = default_value self.__options = options or ["1", "2", "3"] self.__combobox_widget = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__options = None self.__combobox_widget = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__combobox_widget: return self.__combobox_widget.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__combobox_widget.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" model = self.__combobox_widget.model index = model.get_item_value_model().get_value_as_int() self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.__combobox_widget.model.get_item_value_model().set_value( self.__default_val) self.revert_img.enabled = False def _build_body(self): """Main meat of the widget. Draw the Rectangle, Combobox, and set up callbacks to keep them updated. """ with ui.HStack(): with ui.ZStack(): # TODO: Simplify when borders on ComboBoxes work in Kit! # and remove style rule for "combobox" Rect # Use the outline from the Rectangle for the Combobox ui.Rectangle(name="combobox", height=BLOCK_HEIGHT) option_list = list(self.__options) self.__combobox_widget = ui.ComboBox( 0, *option_list, name="dropdown_menu", # Abnormal height because this "transparent" combobox # has to fit inside the Rectangle behind it height=10 ) # Swap for different dropdown arrow image over current one with ui.HStack(): ui.Spacer() # Keep it on the right side with ui.VStack(width=0): # Need width=0 to keep right-aligned ui.Spacer(height=5) with ui.ZStack(): ui.Rectangle(width=15, height=15, name="combobox_icon_cover") ui.Image(name="collapsable_closed", width=12, height=12) ui.Spacer(width=2) # Right margin ui.Spacer(width=ui.Percent(30)) self.__combobox_widget.model.add_item_changed_fn(self._on_value_changed)
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_path_button.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__ = ["CustomPathButtonWidget"] from typing import Callable, Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH, BLOCK_HEIGHT class CustomPathButtonWidget: """A compound widget for holding a path in a StringField, and a button that can perform an action. TODO: Get text ellision working in the path field, to start with "..." """ def __init__(self, label: str, path: str, btn_label: str, btn_callback: Callable): self.__attr_label = label self.__pathfield: ui.StringField = None self.__path = path self.__btn_label = btn_label self.__btn = None self.__callback = btn_callback self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__pathfield = None self.__btn = None self.__callback = None self.__frame = None @property def model(self) -> Optional[ui.AbstractItem]: """The widget's model""" if self.__pathfield: return self.__pathfield.model @model.setter def model(self, value: ui.AbstractItem): """The widget's model""" self.__pathfield.model = value def get_path(self): return self.model.as_string def _build_fn(self): """Draw all of the widget parts and set up callbacks.""" with ui.HStack(): ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) self.__pathfield = ui.StringField( name="path_field", height=BLOCK_HEIGHT, width=ui.Fraction(2), ) # TODO: Add clippingType=ELLIPSIS_LEFT for long paths self.__pathfield.model.set_value(self.__path) self.__btn = ui.Button( self.__btn_label, name="tool_button", height=BLOCK_HEIGHT, width=ui.Fraction(1), clicked_fn=lambda path=self.get_path(): self.__callback(path), )
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_slider_widget.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__ = ["CustomSliderWidget"] from typing import Optional import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl from .custom_base_widget import CustomBaseWidget NUM_FIELD_WIDTH = 50 SLIDER_WIDTH = ui.Percent(100) FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18 SPACING = 4 TEXTURE_NAME = "slider_bg_texture" class CustomSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=1.0, default_val=0.0, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed)
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_base_widget.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__ = ["CustomBaseWidget"] from typing import Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH class CustomBaseWidget: """The base widget for custom widgets that follow the pattern of Head (Label), Body Widgets, Tail Widget""" def __init__(self, *args, model=None, **kwargs): self.existing_model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.revert_img = None self.__attr_label: Optional[str] = kwargs.pop("label", "") self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.existing_model = None self.revert_img = None self.__attr_label = None self.__frame = None def __getattr__(self, attr): """Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__frame, attr) def _build_head(self): """Build the left-most piece of the widget line (label in this case)""" ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) def _build_body(self): """Build the custom part of the widget. Most custom widgets will override this method, as it is where the meat of the custom widget is. """ ui.Spacer() def _build_tail(self): """Build the right-most piece of the widget line. In this case, we have a Revert Arrow button at the end of each widget line. """ with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # call back for revert_img click, to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) def _build_fn(self): """Puts the 3 pieces together.""" with ui.HStack(): self._build_head() self._build_body() self._build_tail()
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/window.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__ = ["JuliaModelerWindow"] import omni.ui as ui from omni.kit.window.popup_dialog import MessageDialog from .custom_bool_widget import CustomBoolWidget from .custom_color_widget import CustomColorWidget from .custom_combobox_widget import CustomComboboxWidget from .custom_multifield_widget import CustomMultifieldWidget from .custom_path_button import CustomPathButtonWidget from .custom_radio_collection import CustomRadioCollection from .custom_slider_widget import CustomSliderWidget from .style import julia_modeler_style, ATTR_LABEL_WIDTH SPACING = 5 class JuliaModelerWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = ATTR_LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = julia_modeler_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) def destroy(self): # Destroys all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def on_export_btn_click(self, path): """Sample callback that is used when the Export button is pressed.""" dialog = MessageDialog( title="Button Pressed Dialog", message=f"Export Button was clicked with path inside: {path}", disable_cancel_button=True, ok_handler=lambda dialog: dialog.hide() ) dialog.show() def _build_title(self): with ui.VStack(): ui.Spacer(height=10) ui.Label("JULIA QUATERNION MODELER - 1.0", name="window_title") ui.Spacer(height=10) def _build_collapsable_header(self, collapsed, title): """Build a custom title of CollapsableFrame""" with ui.VStack(): ui.Spacer(height=8) with ui.HStack(): ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, width=10, height=10) ui.Spacer(height=8) ui.Line(style_type_name_override="HeaderLine") def _build_calculations(self): """Build the widgets of the "Calculations" group""" with ui.CollapsableFrame("Calculations".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=0, max=20, num_type="int", label="Precision", default_val=6) CustomSliderWidget(min=0, max=20, num_type="int", label="Iterations", default_val=10) def _build_parameters(self): """Build the widgets of the "Parameters" group""" with ui.CollapsableFrame("Parameters".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=-2, max=2, display_range=True, label="Iterations", default_val=0.75) CustomSliderWidget(min=0, max=2, display_range=True, label="i", default_val=0.65) CustomSliderWidget(min=0, max=2, display_range=True, label="j", default_val=0.25) CustomSliderWidget(min=0, max=2, display_range=True, label="k", default_val=0.55) CustomSliderWidget(min=0, max=3.14, display_range=True, label="Theta", default_val=1.25) def _build_light_1(self): """Build the widgets of the "Light 1" group""" with ui.CollapsableFrame("Light 1".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomMultifieldWidget( label="Orientation", default_vals=[0.0, 0.0, 0.0] ) CustomSliderWidget(min=0, max=1.75, label="Intensity", default_val=1.75) CustomColorWidget(1.0, 0.875, 0.5, label="Color") CustomBoolWidget(label="Shadow", default_value=True) CustomSliderWidget(min=0, max=2, label="Shadow Softness", default_val=.1) def _build_scene(self): """Build the widgets of the "Scene" group""" with ui.CollapsableFrame("Scene".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=0, max=160, display_range=True, num_type="int", label="Field of View", default_val=60) CustomMultifieldWidget( label="Orientation", default_vals=[0.0, 0.0, 0.0] ) CustomSliderWidget(min=0, max=2, label="Camera Distance", default_val=.1) CustomBoolWidget(label="Antialias", default_value=False) CustomBoolWidget(label="Ambient Occlusion", default_value=True) CustomMultifieldWidget( label="Ambient Distance", sublabels=["Min", "Max"], default_vals=[0.0, 200.0] ) CustomComboboxWidget(label="Ambient Falloff", options=["Linear", "Quadratic", "Cubic"]) CustomColorWidget(.6, 0.62, 0.9, label="Background Color") CustomRadioCollection("Render Method", labels=["Path Traced", "Volumetric"], default_value=1) CustomPathButtonWidget( label="Export Path", path=".../export/mesh1.usd", btn_label="Export", btn_callback=self.on_export_btn_click, ) ui.Spacer(height=10) def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(name="window_bg", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): self._build_title() self._build_calculations() self._build_parameters() self._build_light_1() self._build_scene()
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-23 ### Added - Readme ## [1.0.0] - 2022-06-22 ### Added - Initial window
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/README.md
# Julia Modeler (omni.example.ui_julia_modeler) ![](../data/preview.png) ## Overview In this example, we create a window which uses custom widgets that follow a similar pattern. The window is built using `omni.ui`. It contains the best practices of how to build customized widgets and reuse them without duplicating the code. The structure is very similar to that of `omni.example.ui_window`, so we won't duplicate all of that same documentation here. ## [Tutorial](../tutorial/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. [Get started with the tutorial.](../tutorial/tutorial.md) ## Usage This is just a UI demo. You can interact with the various controls, but they have not additional effect in the Application. ## Explanations ### Custom Widgets Because this design had a pattern for most of its attribute rows, like: `<head><body><tail>` where "head" is always the same kind of attribute label, the "body" is the customized part of the widget, and then the "tail" is either a revert arrow button, or empty space, we decided it would be useful to make a base class for all of the similar custom widgets, to reduce code duplication, and to make sure that the 3 parts always line up in the UI. ![](../data/similar_widget_structure.png) By structuring the base class with 3 main methods for building the 3 sections, child classes can focus on just building the "body" section, by implementing `_build_body()`. These are the 3 main methods in the base class, and the `_build_fn()` method that puts them all together: ```python def _build_head(self): # The main attribute label ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) def _build_body(self): # Most custom widgets will override this method, # as it is where the meat of the custom widget is ui.Spacer() def _build_tail(self): # In this case, we have a Revert Arrow button # at the end of each widget line with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # add call back to revert_img click to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) def _build_fn(self): # Put all the parts together with ui.HStack(): self._build_head() self._build_body() self._build_tail() ``` and this is an example of implementing `_build_body()` in a child class: ```python def _build_body(self): with ui.HStack(): with ui.VStack(): ui.Spacer(height=2) self.__bool_image = ui.Image( name="checked" if self.__default_val else "unchecked", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) ui.Spacer() self.__bool_image.set_mouse_pressed_fn( lambda x, y, b, m: self._on_value_changed()) ``` #### Value Changed "Revert" Widget In this example, almost every attribute row has a widget which indicates whether the value has been changed or not. By default, the revert arrow button is disabled and gray, and when the value has been changed it turns light blue and is enabled. Most of the functionality for this widget lives in the CustomBaseWidget class. The base class also calls a _restore_value method that needs to be implemented in the child class. Each child class can handle attribute values differently, so the logic of how to revert back needs to live at that level. The child class also takes care of enabling the revert button when the value has changed, turning it blue. ![](../data/revert_enabled.png) ![](../data/revert_disabled.png) #### Custom Int/Float Slider ![](../data/custom_float_slider.png) At a high level, this custom widget is just the combination of a `ui.FloatSlider` or `ui.IntSlider` and a `ui.FloatField` or `ui.IntField`. But there are a few more aspects that make this widget interesting: - The background of the slider has a diagonal lines texture. To accomplish that, a tiled image of that texture is placed behind the rest of the widget using a ZStack. A Slider is placed over top, almost completely transparent. The background color is transparent and the text is transparent. The foreground color, called the `secondary_color` is light gray with some transparency to let the texture show through. - Immediately below the slider is some optional tiny text that denotes the range of the slider. If both min and max are positive or both are negative, only the endpoints are shown. If the min is negative, and the max is positive, however, the 0 point is also added in between, based on where it would be. That tiny text is displayed by using `display_range=True` when creating a `CustomSliderWidget`. - There was a bug with sliders and fields around how the padding worked. It is fixed and will be available in the next version of Kit, but until then, there was a workaround to make things look right: a ui.Rectangle with the desired border is placed behind a ui.FloatField. The Field has a transparent background so all that shows up from it is the text. That way the Slider and Field can line up nicely and the text in the Field can be the same size as with other widgets in the UI. #### Customized ColorWidget The customized ColorWidget wraps a `ui.ColorWidget` widget and a `ui.StringField` widget in a child class of CustomBaseWidget. ![](../data/custom_color_widget.png) The colorpicker widget is a normal `ui.ColorWidget`, but the text part is really just a `ui.StringField` with comma-separated values, rather than a `ui.MultiFloatDragField` with separate R, G, and B values. So it wasn't as easy to just use the same model for both. Instead, to make them connect in both directions, we set up a callback for each widget, so that each would update the other one on any changes: ```python self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn( lambda m, _, children=color_model.get_item_children(): self.set_color_stringfield(m, children)) self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn( lambda m, children=color_model.get_item_children(): self.set_color_widget(m, children)) ``` #### Custom Path & Button Widget The Custom Path & Button widget doesn't follow quite the same pattern as most of the others, because it doesn't have a Revert button at the end, and the Field and Button take different proportions of the space. ![](../data/custom_path_button.png) In the widget's `_build_fn()` method, we draw the entire row all in one place. There's the typical label on the left, a StringField in the middle, and a Button at the end: ```python with ui.HStack(): ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) self.__pathfield = ui.StringField( name="path_field", height=BLOCK_HEIGHT, width=ui.Fraction(2), ) self.__pathfield.model.set_value(self.__path) self.__btn = ui.Button( self.__btn_label, name="tool_button", height=BLOCK_HEIGHT, width=ui.Fraction(1), clicked_fn=lambda path=self.get_path(): self.__callback(path), ) ``` All of those strings for labels and paths are customizable when creating the Widget. In window.py, this is how we instantiate the Export-style version: _(Note: In a real situation we would use the entire path, but we added the "..." ellipsis to show an ideal way to clip the text in the future.)_ ```python CustomPathButtonWidget( label="Export Path", path=".../export/mesh1.usd", btn_label="Export", btn_callback=self.on_export_btn_click, ) ``` And we show a sample callback hooked up to the button -- `self.on_export_btn_click`, which for this example, just pops up a MessageDialog telling the user what the path was that is in the Field: ```python def on_export_btn_click(self, path): """Sample callback that is used when the Export button is pressed.""" dialog = MessageDialog( title="Button Pressed Dialog", message=f"Export Button was clicked with path inside: {path}", disable_cancel_button=True, ok_handler=lambda dialog: dialog.hide() ) dialog.show() ``` ### Style Although the style can be applied to any widget, we recommend keeping the style dictionary in one location, such as `styles.py`. One comment on the organization of the styles. You may notice named constants that seem redundant, that could be consolidated, such as multiple font type sizes that are all `14`. ```python fl.window_title_font_size = 18 fl.field_text_font_size = 14 fl.main_label_font_size = 14 fl.multi_attr_label_font_size = 14 fl.radio_group_font_size = 14 fl.collapsable_header_font_size = 13 fl.range_text_size = 10 ``` While you definitely _could_ combine all of those into a single constant, it can be useful to break them out by type of label/text, so that if you later decide that you want just the Main Labels to be `15` instead of `14`, you can adjust just the one constant, without having to break out all of the other types of text that were using the same font size by coincidence. This same organization applies equally well to color assignments also. ### Window It's handy to derive a custom window from the class `ui.Window`. The UI can be defined right in `__init__`, so it's created immediately or it can be defined in a `set_build_fn` callback and it will be created when the window is visible. The later one is used in this example. ```python class PropertyWindowExample(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = julia_modeler_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) ``` Inside the `self._build_fn`, we use the customized widgets to match the design layout for the window. ### Extension When the extension starts up, we register a new menu item that controls the window and shows the window. A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit. ```python ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None)) ``` When the extension shuts down, we remove the menu item and deregister the window callback.
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/index.rst
omni.example.ui_julia_modeler ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/tutorial/tutorial.md
# UI Window Tutorial In this tutorial, you learn how to create an Omniverse Extension that has a window and user interface (UI) elements inside that window. ## Learning Objectives * Create a window. * Add it to the **Window** menu. * Add various control widgets into different collapsable group with proper layout and alignment. ## Step 1: Clone the Repository Clone the `ui-window-tutorial-start` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/ui-window-tutorial-start): ```shell git clone -b ui-window-tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git ``` This repository contains the starting code you use in this tutorial. ## Step 2: Add the Extension to Omniverse Code In order to use and test your Extension, you need to add it to Omniverse Code. ### Step 2.1: Navigate to the Extensions List In Omniverse Code, navigate to the *Extensions* panel: ![Click the Extensions panel](Images/extensions_panel.png) Here, you see a list of Omniverse Extensions that you can activate and use in Code. > **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**: > > ![Show the Extensions panel](Images/window_extensions.png) ### Step 2.2: Navigate to the *Extension Search Paths* Click the **gear** icon to open *Extension Search Paths*: ![Click the gear icon](Images/extension_search_paths.png) In this panel, you can add your custom Extension to the Extensions list. ### Step 2.3: Create a New Search Path Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field: ![New search path](Images/new_search_path_ui-window.png) When you submit your new search path, you should be able to find your extension in the *Extensions* list. Search for "omni.example.ui_" to filter down the list. Activate the "OMNI.UI WINDOW EXAMPLE" Extension: ![Reticle extensions list](Images/window_extensions_list_ui-window.png) Now that your Extension is added and enabled, you can make changes to the code and see them in your Application. ## Step 3: Create A Window In this section, you create an empty window that you can hide and show and is integrated into the **Application** menu. This window incorporates a few best practices so that it's well-connected with Omniverse and feels like a natural part of the application it's being used from. You do all of this in the `extension.py` file. ### Step 3.1: Support Hide/Show Windows can be hidden and shown from outside the window code that you write. If you would like Omniverse to be able to show a window after it has been hidden, you must register a callback function to run when the window visibility changes. To do this, open the `extension.py` file, go to the `on_startup()` definition, and edit the function to match the following code: ```python def on_startup(self): # The ability to show the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Add a Menu Item for the window # Show the window through the 'set_show_window_fn' you wired up above # It will call `self.show_window` ``` The added line registers the `self.show_window` callback to be run whenever the visibility of your extension is changed. The `pass` line of code is deleted because it is no longer necessary. It was only included because all code had been removed from that function. ### Step 3.2: Add a Menu Item It is helpful to add extensions to the application menu so that if a user closes a window they can reopen it. This is done by adding the following code to `on_startup()`: ```python def on_startup(self): # The ability to show the window if the system requires it. # You use it in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Add a Menu Item for the window editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window through the 'set_show_window_fn' you wired up above # It will call `self.show_window` ``` The first added line grabs a reference to the application menu. The second new line adds a new menu item where `MENU_PATH` determines where the menu item will appear in the menu system, and `self.show_window` designates the function to run when the user toggles the window visibility by clicking on the menu item. ### Step 3.3: Show the Window To finish with `on_startup()`, add the following: ```python def on_startup(self): # The ability to show the window if the system requires it. # You use it in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Add a Menu Item for the window editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window through the 'set_show_window_fn' you wired up above # It will call `self.show_window` ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME) ``` This calls `show_window()` through the registration you set up earlier. ### Step 3.4: Call the Window Constructor Finally, in the `extension.py` file, scroll down to the `show_window` method which is currently the code below: ```python def show_window(self, menu, value): #value is true if the window should be shown if value: #call our custom window constructor #Handles the change in visibility of the window gracefuly self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False ``` Add the following line to this function: ```python def show_window(self, menu, value): #value is true if the window should be shown if value: #call our custom window constructor self._window = ExampleWindow(ExampleWindowExtension.WINDOW_NAME, width=300, height=365) #Handles the change in visibility of the window gracefuly self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False ``` This calls the constructor of the custom window class in `window.py` and assigns it to the extension `self._window`. ## Step 4: Custom Window The custom window class can be found in `window.py`. It is possible to simply build all of your user interface in `extension.py`, but this is only a good practice for very simple extensions. More complex extensions should be broken into managable pieces. It is a good practice to put your user interface into its own file. Note that `window.py` contains a class that inherits from `ui.Window`. Change the `__init__()` function to include the line added below: ```python def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) ``` This line registers the `self._build_fn` callback to run when the window is visible, which is where you will build the user interface for this tutorial. ### Step 4.1: Create a Scrolling Frame Now scroll down to `_build_fn` at the bottom of `window.py` and edit it to match the following: ```python def _build_fn(self): # The method that is called to build all the UI once the window is visible. with ui.ScrollingFrame(): pass ``` The `with` statement begins a context block and you are creating a `ScrollingFrame`. What this means is that everything intended below the `with` will be a child of the `ScrollingFrame`. A [ScrollingFrame](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.ScrollingFrame) is an area within your user interface with a scroll bar. By creating one first, if the user makes the window small, a scrollbar will appear, allowing the user to still access all content in the user interface. ### Step 4.2: Create a Vertical Stack Next edit the `_build_fn()` definition by replacing the `pass` line with the following context block and put a `pass` keyword inside the new context block as shown below: ```python def _build_fn(self): # The method that is called to build all the UI once the window is visible. with ui.ScrollingFrame(): with ui.VStack(height=0): pass ``` Here you added a `VStack`, which stacks its children vertically. The first item is at the top and each subsequent item is placed below the previous item as demonstrated in the schematic below: <p align="center"> <img src="Images/VerticalStack.png" width=25%> <p> This will be used to organize the controls into rows. ### Step 4.3: Break the Construction into Chunks While it would be possible to create the entire user interface in this tutorial directly in `_build_fn()`, as a user interface gets large it can be unwieldly to have it entirely within one function. In order to demonstrate best practices, this tutorial builds each item in the vertical stack above in its own function. Go ahead and edit your code to match the block below: ```python def _build_fn(self): # The method that is called to build all the UI once the window is visible. with ui.ScrollingFrame(): with ui.VStack(height=0): self._build_calculations() self._build_parameters() self._build_light_1() ``` Each of these functions: `_build_calculations()`, `_build_parameters()`, and `_build_light_1()` builds an item in the vertical stack. Each of those items is a group of well-organized controls made with a consistent look and layout. If you save `window.py` it will `hot reload`, but will not look any different from before. That is because both `ScrollingFrame` and `VStack` are layout controls. This means that they are meant to organize content within them, not be displayed themselves. A `ScrollingFrame` can show a scroll bar, but only if it has content to be scrolled. ## Step 5: Build Calculations The first group you will create is the `Calculations group`. In this section `CollapsableFrame`, `HStack`, `Label`, and `IntSlider` will be introduced. Scroll up to the `_build_calculations` which looks like the following block of code: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group # A VStack is a vertical stack and aligns widgets vertically one after the other # An HStack is a horizontal stack and aligns widgets horizontally one after the other # A label displays text # An IntSlider lets a user choose an integer by sliding a bar back and forth # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider pass ``` In the remaining sub-sections you will fill this in and create your first group of controls. ### Step 5.1: Create a Collapsable Frame Edit `_build_calculations()` to match the following: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other # An HStack is a horizontal stack and aligns widgets horizontally one after the other # A label displays text # An IntSlider lets a user choose an integer by sliding a bar back and forth # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider pass ``` A `CollapsableFrame` is a control that you can expand and contract by clicking on its header, which will show or hide its content. The first argument passed into its constructor is the title string. The second argument is its name and the final argument is a reference to the function that builds its header. You can write this function to give the header whatever look you want. At this point if you save `window.py` and then test in Omniverse Code you will see a change in your extension's window. The `CollapsableFrame` will be visible and should look like this: <p align="center"> <img src="Images/CollapsableFrame.png" width=25%> <p> Next we will add content inside this `CollapsableFrame`. ### Step 5.2: Create a Horizontal Stack The next three steps demonstrate a very common user interface pattern, which is to have titled controls that are well aligned. A common mistake is to create a user interface that looks like this: <p align="center"> <img src="Images/BadUI.png" width=25%> <p> The controls have description labels, but they have inconsistent positions and alignments. The following is a better design: <p align="center"> <img src="Images/GoodUI.png" width=25%> <p> Notice that the description labels are all to the left of their respective controls, the labels are aligned, and the controls have a consistent width. This will be demonstrated twice within a `VStack` in this section. Add a `VStack` and then to create this common description-control layout, add an `HStack` to the user interface as demonstrated in the following code block: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text # An IntSlider allows a user choose an integer by sliding a bar back and forth pass # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider pass ``` An `HStack` is very similar to a `VStack` except that it stacks its content horizontally rather than vertically. Note that a `pass` you added to the `VStack` simply so that the code will run until you add more controls to this context. ### Step 5.3: Create a Label Next add a `Label` to the `HStack`: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text ui.Label("Precision", name="attribute_name", width=self.label_width) # An IntSlider allows a user choose an integer by sliding a bar back and forth # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider ``` If you save the file and go to `Code` you will see that the `Label` appears in the user interface. Take special note of the `width` attribute passed into the constructor. By making all of the labels the same width inside their respective `HStack` controls, the labels and the controls they describe will be aligned. Note also that all contexts now have code, so we have removed the `pass` statements. ### Step 5.4: Create an IntSlider Next add an `IntSlider` as shown below: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text ui.Label("Precision", name="attribute_name", width=self.label_width) # An IntSlider allows a user choose an integer by sliding a bar back and forth ui.IntSlider(name="attribute_int") # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider ``` An `IntSlider` is a slider bar that a user can click and drag to control an integer value. If you save your file and go to Omniverse Code, your user interface should now look like this: <p align="center"> <img src="Images/IntSlider.png" width=25%> <p> Go ahead and add a second label/control pair by adding the following code: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text ui.Label("Precision", name="attribute_name", width=self.label_width) # An IntSlider allows a user choose an integer by sliding a bar back and forth ui.IntSlider(name="attribute_int") # Pairing a label with a control is a common UI comb with ui.HStack(): # The label makes the purpose of the control clear ui.Label("Iterations", name="attribute_name", width=self.label_width) # You can set the min and max value on an IntSlider ui.IntSlider(name="attribute_int", min=0, max=5) ``` You have added another `HStack`. This one has a `Label` set to the same width as the first `Label`. This gives the group consistent alignment. `min` and `max` values have also been set on the second `IntSlider` as a demonstration. Save `window.py` and test the extension in Omniverse Code. Expand and collapse the `CollapsableFrame`, resize the window, and change the integer values. It is a good practice to move and resize your extension windows as you code to make sure that the layout looks good no matter how the user resizes it. ## Step 6: Build Parameters In this section you will introduce the `FloatSlider` and demonstrate how to keep the UI consistent across multiple groups. You will be working in the `_build_parameters()` definition which starts as shown below: ```python def _build_parameters(self): # Build the widgets of the "Parameters" group # A Float Slider is similar to an Int Slider # controls a 'float' which is a number with a decimal point (A Real number) # You can set the min and max of a float slider as well # Setting the labels all to the same width gives the UI a nice alignment # A few more examples of float sliders pass ``` Hopefullly this is starting to feel a bit more familiar. You have an empty function that has a `pass` command at the end as a placeholder until you add code to all of its contexts. ### Step 6.1: Create a FloatSlider A `FloatSlider` is very similar to an `IntSlider`. The difference is that it controls a `float` number rather than an `integer`. Match the code below to add one to your extension: ```python def _build_parameters(self): # Build the widgets of the "Parameters" group with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Value", name="attribute_name", width=self.label_width) # A Float Slider is similar to an Int Slider # controls a 'float' which is a number with a decimal point (A Real number) ui.FloatSlider(name="attribute_float") # You can set the min and max of a float slider as well # Setting the labels all to the same width gives the UI a nice alignment # A few more examples of float sliders ``` Here you added a second `CollapsableFrame` with a `VStack` inside of it. This will allow you to add as many label/control pairs as you want to this group. Note that the `Label` has the same width as the label above. Save `window.py` and you should see the following in Omniverse Code: <p align="center"> <img src="Images/SecondGroup.png" width=25%> <p> Note that the description labels and controls in the first and second group are aligned with each other. ### Step 6.2: Make a Consistent UI By using these description control pairs inside of collapsable groups, you can add many controls to a window while maintaining a clean, easy to navigate experience. The following code adds a few more `FloatSlider` controls to the user interface: ```python def _build_parameters(self): # Build the widgets of the "Parameters" group with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Value", name="attribute_name", width=self.label_width) # A Float Slider is similar to an Int Slider # controls a 'float' which is a number with a decimal point (A Real number) ui.FloatSlider(name="attribute_float") with ui.HStack(): ui.Label("i", name="attribute_name", width=self.label_width) # You can set the min and max of a float slider as well ui.FloatSlider(name="attribute_float", min=-1, max=1) # Setting the labels all to the same width gives the UI a nice alignment with ui.HStack(): ui.Label("j", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) # A few more examples of float sliders with ui.HStack(): ui.Label("k", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("Theta", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") ``` Save `window.py` and take a look in Omniverse Code. Your window should look like this: <p align="center"> <img src="Images/SecondGroupComplete.png" width=25%> <p> Note that a few of the sliders have `min` and `max` values and they they are all well-aligned. ## Step 7: Build Light In your final group you will add a few other control types to help give you a feel for what can be done in an extension UI. This will also be well-arranged, even though they are different control types to give the overall extension a consistent look and feel, even though it has a variety of control types. You will be working in `_build_light_1()`, which starts as shown below: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group # A multi float drag field lets you control a group of floats # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel #Feel free to copy this color widget and use it in your own UIs # The custom compound widget #An example of a checkbox pass ``` First you will add a `MultiFloatDragField` to it, then a custom color picker widget and finally a `Checkbox`. ### Step 7.1: Create a MultiFloatDragField Edit `_build_light_1` to match the following: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) # A multi float drag field allows you control a group of floats (Real numbers) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") #Feel free to copy this color widget and use it in your own UIs # The custom compound widget #An example of a checkbox ``` This adds a third `CollapsableFrame` with a `VStack` to hold its controls. Then it adds a label/control pair with a `MultiFloatDragField`. A `MultiFloatDragField` lets a user edit as many values as you put into its constructor, and is commonly used to edit 3-component vectors such as position and rotation. You also added a second label and control pair with a `FloatSlider` similar to the one you added in [section 5.1](#51-create-a-floatslider). ### Step 7.2: Add a Custom Widget Developers can create custom widgets and user interface elements. The color picker added in this section is just such an example. Add it to your extension with the following code: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) # A multi float drag field lets you control a group of floats (Real numbers) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") #Feel free to copy this color widget and use it in your own UIs with ui.HStack(): ui.Label("Color", name="attribute_name", width=self.label_width) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) #An example of a checkbox ``` This widget lets users click and then select a color. Feel free to use this widget in your own applications and feel free to write and share your own widgets. Over time you will have a wide variety of useful widgets and controls for everyone to use in their extensions. ### Step 7.3: Add a Checkbox Finally, edit `_build_light_1()` to match the following: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) # A multi float drag field lets you control a group of floats (Real numbers) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") #Feel free to copy this color widget and use it in your own UIs with ui.HStack(): ui.Label("Color", name="attribute_name", width=self.label_width) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) #An example of a checkbox with ui.HStack(): ui.Label("Shadow", name="attribute_name", width=self.label_width) ui.CheckBox(name="attribute_bool") ``` This adds a label/control pair with a `CheckBox`. A `CheckBox` control allows a user to set a boolean value. Save your `window.py` file and open Omniverse Code. Your user interface should look like this if you collapse the `Parameters` section: <p align="center"> <img src="Images/Complete.png" width=25%> <p> There are three collapsable groups, each with a variety of controls with a variety of settings and yet they are all well-aligned with a consistent look and feel. ## Conclusion In this tutorial you created an extension user interface using coding best practices to integrate it into an Omniverse application. It contains a variety of controls that edit integers, float, colors and more. These controls are well organized so that a user can easily find their way around the window. We look forward to seeing the excellent extensions you come up with and how you can help Omniverse users accomplish things that were hard or even impossible to do before you wrote an extension to help them.
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/config/extension.toml
[package] title = "omni.ui Window Example" description = "The full end to end example of the window" version = "1.0.1" category = "Example" authors = ["Victor Yudin"] repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows" keywords = ["example", "window", "ui"] changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.example.ui_window" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/style.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__ = ["example_window_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. cl.example_window_attribute_bg = cl("#1f2124") cl.example_window_attribute_fg = cl("#0f1115") cl.example_window_hovered = cl("#FFFFFF") cl.example_window_text = cl("#CCCCCC") fl.example_window_attr_hspacing = 10 fl.example_window_attr_spacing = 1 fl.example_window_group_spacing = 2 url.example_window_icon_closed = f"{EXTENSION_FOLDER_PATH}/data/closed.svg" url.example_window_icon_opened = f"{EXTENSION_FOLDER_PATH}/data/opened.svg" # The main style dict example_window_style = { "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_CENTER, "margin_height": fl.example_window_attr_spacing, "margin_width": fl.example_window_attr_hspacing, }, "Label::attribute_name:hovered": {"color": cl.example_window_hovered}, "Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER}, "Slider::attribute_int:hovered": {"color": cl.example_window_hovered}, "Slider": { "background_color": cl.example_window_attribute_bg, "draw_mode": ui.SliderDrawMode.HANDLE, }, "Slider::attribute_float": { "draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": cl.example_window_attribute_fg, }, "Slider::attribute_float:hovered": {"color": cl.example_window_hovered}, "Slider::attribute_vector:hovered": {"color": cl.example_window_hovered}, "Slider::attribute_color:hovered": {"color": cl.example_window_hovered}, "CollapsableFrame::group": {"margin_height": fl.example_window_group_spacing}, "Image::collapsable_opened": {"color": cl.example_window_text, "image_url": url.example_window_icon_opened}, "Image::collapsable_closed": {"color": cl.example_window_text, "image_url": url.example_window_icon_closed}, }
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/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__ = ["ExampleWindowExtension"] from .window import ExampleWindow from functools import partial import asyncio import omni.ext import omni.kit.ui import omni.ui as ui class ExampleWindowExtension(omni.ext.IExt): """The entry point for Example Window""" WINDOW_NAME = "Example Window" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Put the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(ExampleWindowExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user pressed "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = ExampleWindow(ExampleWindowExtension.WINDOW_NAME, width=300, height=365) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/__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__ = ["ExampleWindowExtension", "ExampleWindow"] from .extension import ExampleWindowExtension from .window import ExampleWindow
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/color_widget.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__ = ["ColorWidget"] from ctypes import Union from typing import List, Optional import omni.ui as ui COLOR_PICKER_WIDTH = 20 SPACING = 4 class ColorWidget: """The compound widget for color input""" def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = args self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.__multifield: Optional[ui.MultiFloatDragField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__model = None self.__multifield = None self.__colorpicker = None self.__frame = None def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__root_frame, attr) @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__multifield: return self.__multifield.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__multifield.model = value self.__colorpicker.model = value def _build_fn(self): with ui.HStack(spacing=SPACING): # The construction of multi field depends on what the user provided, # defaults or a model if self.__model: # the user provided a model self.__multifield = ui.MultiFloatDragField( min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color" ) model = self.__model else: # the user provided a list of default values self.__multifield = ui.MultiFloatDragField( *self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color" ) model = self.__multifield.model self.__colorpicker = ui.ColorWidget(model, width=COLOR_PICKER_WIDTH)
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/window.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__ = ["ExampleWindow"] import omni.ui as ui from .style import example_window_style from .color_widget import ColorWidget LABEL_WIDTH = 120 SPACING = 4 class ExampleWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def _build_collapsable_header(self, collapsed, title): """Build a custom title of CollapsableFrame""" with ui.HStack(): ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, width=20, height=20) def _build_calculations(self): """Build the widgets of the "Calculations" group""" with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Precision", name="attribute_name", width=self.label_width) ui.IntSlider(name="attribute_int") with ui.HStack(): ui.Label("Iterations", name="attribute_name", width=self.label_width) ui.IntSlider(name="attribute_int", min=0, max=5) def _build_parameters(self): """Build the widgets of the "Parameters" group""" with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Value", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") with ui.HStack(): ui.Label("i", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("j", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("k", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("Theta", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") def _build_light_1(self): """Build the widgets of the "Light 1" group""" with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") with ui.HStack(): ui.Label("Color", name="attribute_name", width=self.label_width) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) with ui.HStack(): ui.Label("Shadow", name="attribute_name", width=self.label_width) ui.CheckBox(name="attribute_bool") def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(): with ui.VStack(height=0): self._build_calculations() self._build_parameters() self._build_light_1()
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/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_window import TestWindow
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/tests/test_window.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__ = ["TestWindow"] from omni.example.ui_window import ExampleWindow 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 TestWindow(OmniUiTest): async def test_general(self): """Testing general look of section""" window = ExampleWindow("Test") await omni.kit.app.get_app().next_update_async() await self.docked_test_window( window=window, width=300, height=385, ) # Wait for images for _ in range(20): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-22 ### Added - Readme ## [1.0.0] - 2022-06-05 ### Added - Initial window
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/docs/README.md
# Generic Window (omni.example.ui_window) ![](../data/preview.png) ## Overview This extension provides an end-to-end example and general recommendations on creating a simple window using `omni.ui`. It contains the best practices of building an extension, a menu item, a window itself, a custom widget, and a generic style. ## [Tutorial](../tutorial/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. [Get started with the tutorial.](../tutorial/tutorial.md) ## Usage This is just a UI demo. You can interact with the various controls, but they have not additional effect in the Application. ## Explanations ### Extension When the extension starts up, we register a new menu item that controls the window and shows the window. A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit. ``` # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) ``` When the extension shuts down, we remove the menu item and deregister the window callback. ### Window It's handy to derive a custom window from the class `ui.Window`. The UI can be defined right in __init__, so it's created immediately. Or it can be defined in a callback and it will be created when the window is visible. ``` class ExampleWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) ``` ### Custom Widget A custom widget can be a class or a function. It's not required to derive anything. It's only necessary to create sub-widgets. ``` class ColorWidget: """The compound widget for color input""" def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = args self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.__multifield: Optional[ui.MultiFloatDragField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__frame = ui.Frame() with self.__frame: self._build_fn() ``` ### Style Although the style can be applied to any widget, we recommend keeping the style dictionary in one location. There is an exception to this recommendation. It's recommended to use styles directly on the widgets to hide a part of the widget. For example, it's OK to set {"color": cl.transparent} on a slider to hide the text. Or "background_color": cl.transparent to disable background on a field.
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/docs/index.rst
omni.example.ui_window ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
NVIDIA-Omniverse/kit-extension-template/link_app.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) cd "$SCRIPT_DIR" exec "tools/packman/python.sh" tools/scripts/link_app.py $@
NVIDIA-Omniverse/kit-extension-template/link_app.bat
@echo off call "%~dp0tools\packman\python.bat" %~dp0tools\scripts\link_app.py %* if %errorlevel% neq 0 ( goto Error ) :Success exit /b 0 :Error exit /b %errorlevel%
NVIDIA-Omniverse/kit-extension-template/README.md
# *Omniverse Kit* Extensions Project Template This project is a template for developing extensions for *Omniverse Kit*. # Getting Started ## Install Omniverse and some Apps 1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download) 2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*. ## Add a new extension to your *Omniverse App* 1. Fork and clone this repo, for example in `C:\projects\kit-extension-template` 2. In the *Omniverse App* open extension manager: *Window* &rarr; *Extensions*. 3. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar. 4. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `exts` subfolder there as another search path: `C:\projects\kit-extension-template\exts` ![Extension Manager Window](/images/add-ext-search-path.png) 5. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it. 6. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload. ### Few tips * Now that `exts` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*. * Look at the *Console* window for warnings and errors. It also has a small button to open current log file. * All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`. * Extension name is a folder name in `exts` folder, in this example: `omni.hello.world`. * Most important thing extension has is a config file: `extension.toml`, take a peek. ## Next Steps: Alternative way to add a new extension To get a better understanding and learn a few other things, we recommend following next steps: 1. Remove search path added in the previous section. 1. Open this cloned repo using Visual Studio Code: `code C:\projects\kit-extension-template`. It will suggest installing a few extensions to improve python experience. 2. In the terminal (CTRL + \`) run `link_app.bat` (more in [Linking with an *Omniverse* app](#linking-with-an-omniverse-app) section). 3. Run this app with `exts` folder added as an extensions search path and new extension enabled: ```bash > app\omni.code.bat --ext-folder exts --enable omni.hello.world ``` - `--ext-folder [path]` - adds new folder to the search path - `--enable [extension]` - enables an extension on startup. Use `-h` for help: ```bash > app\omni.code.bat -h ``` 4. After the *App* started you should see: * new "My Window" window popup. * extension search paths in *Extensions* window as in the previous section. * extension enabled in the list of extensions. 5. If you look inside `omni.code.bat` or any other *Omniverse App*, they all run *Omniverse Kit* (`kit.exe`). *Omniverse Kit* is the Omniverse Application runtime that powers *Apps* build out of extensions. Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Code*: ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world ``` It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!): ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world --enable omni.kit.window.extensions ``` You should see a menu in the top left. From here you can enable more extensions from the UI. ### Few tips * In the *Extensions* window, press *Bread* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be: all extensions and dependencies. * Extensions system documentation: http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/extensions.html # Running Tests To run tests we run a new process where only the tested extension (and it's dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests: 1. Run: `app\kit\test_ext.bat omni.hello.world --ext-folder exts` That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code! 2. Alternatively, in *Extension Manager* (*Window &rarr; Extensions*) find your extension, click on *TESTS* tab, click *Run Test* For more information about testing refer to: [testing doc](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/ext_testing.html). # 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 ``` 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 create ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Adding a new extension Adding a new extension is as simple as copying and renaming existing one: 1. copy `exts/omni.hello.world` to `exts/[new extension name]` 2. rename python module (namespace) in `exts/[new extension name]/omni/hello/world` to `exts/[new extension name]/[new python module]` 3. update `exts/[new extension name]/config/extension.toml`, most importantly specify new python module to load: ```toml [[python.module]] name = "[new python module]" ``` No restart is needed, you should be able to find and enable `[new extension name]` in extension manager. # Sharing extensions To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). 1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery. 2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes. # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
NVIDIA-Omniverse/kit-extension-template/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!")
NVIDIA-Omniverse/kit-extension-template/tools/packman/python.sh
#!/bin/bash # Copyright 2019-2020 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. set -e PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi source "$PACKMAN_CMD" init export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}" export PYTHONNOUSERSITE=1 # workaround for our python not shipping with certs if [[ -z ${SSL_CERT_DIR:-} ]]; then export SSL_CERT_DIR=/etc/ssl/certs/ fi "${PM_PYTHON}" -u "$@"
NVIDIA-Omniverse/kit-extension-template/tools/packman/python.bat
:: Copyright 2019-2020 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. @echo off setlocal call "%~dp0\packman" init set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%" set PYTHONNOUSERSITE=1 "%PM_PYTHON%" -u %*
NVIDIA-Omniverse/kit-extension-template/tools/packman/packman.cmd
:: Reset errorlevel status (don't inherit from caller) [xxxxxxxxxxx] @call :ECHO_AND_RESET_ERROR :: You can remove the call below if you do your own manual configuration of the dev machines call "%~dp0\bootstrap\configure.bat" if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Everything below is mandatory if not defined PM_PYTHON goto :PYTHON_ENV_ERROR if not defined PM_MODULE goto :MODULE_ENV_ERROR :: Generate temporary path for variable file for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile ^ -File "%~dp0bootstrap\generate_temp_file_name.ps1"') do set PM_VAR_PATH=%%a if %1.==. ( set PM_VAR_PATH_ARG= ) else ( set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%" ) "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG% if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Marshall environment variables into the current environment if they have been generated and remove temporary file if exist "%PM_VAR_PATH%" ( for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) if exist "%PM_VAR_PATH%" ( del /F "%PM_VAR_PATH%" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) set PM_VAR_PATH= goto :eof :: Subroutines below :PYTHON_ENV_ERROR @echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat. exit /b 1 :MODULE_ENV_ERROR @echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat. exit /b 1 :VAR_ERROR @echo Error while processing and setting environment variables! exit /b 1 :ECHO_AND_RESET_ERROR @echo off if /I "%PM_VERBOSITY%"=="debug" ( @echo on ) exit /b 0
NVIDIA-Omniverse/kit-extension-template/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
NVIDIA-Omniverse/kit-extension-template/tools/packman/bootstrap/generate_temp_file_name.ps1
<# 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. #> $out = [System.IO.Path]::GetTempFileName() Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAK+Ewup1N0/mdf # 1l4R58rxyumHgZvTmEhrYTb2Zf0zd6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0 # I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7XKPAbZqHrN9elAhWJ # vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V # mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo # PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof # wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU # SIG # End signature block
NVIDIA-Omniverse/kit-extension-template/tools/packman/bootstrap/configure.bat
:: 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. set PM_PACKMAN_VERSION=6.33.2 :: Specify where packman command is rooted set PM_INSTALL_PATH=%~dp0.. :: The external root may already be configured and we should do minimal work in that case if defined PM_PACKAGES_ROOT goto ENSURE_DIR :: If the folder isn't set we assume that the best place for it is on the drive that we are currently :: running from set PM_DRIVE=%CD:~0,2% set PM_PACKAGES_ROOT=%PM_DRIVE%\packman-repo :: We use *setx* here so that the variable is persisted in the user environment echo Setting user environment variable PM_PACKAGES_ROOT to %PM_PACKAGES_ROOT% setx PM_PACKAGES_ROOT %PM_PACKAGES_ROOT% if %errorlevel% neq 0 ( goto ERROR ) :: The above doesn't work properly from a build step in VisualStudio because a separate process is :: spawned for it so it will be lost for subsequent compilation steps - VisualStudio must :: be launched from a new process. We catch this odd-ball case here: if defined PM_DISABLE_VS_WARNING goto ENSURE_DIR if not defined VSLANG goto ENSURE_DIR echo The above is a once-per-computer operation. Unfortunately VisualStudio cannot pick up environment change echo unless *VisualStudio is RELAUNCHED*. echo If you are launching VisualStudio from command line or command line utility make sure echo you have a fresh launch environment (relaunch the command line or utility). echo If you are using 'linkPath' and referring to packages via local folder links you can safely ignore this warning. echo You can disable this warning by setting the environment variable PM_DISABLE_VS_WARNING. echo. :: Check for the directory that we need. Note that mkdir will create any directories :: that may be needed in the path :ENSURE_DIR if not exist "%PM_PACKAGES_ROOT%" ( echo Creating directory %PM_PACKAGES_ROOT% mkdir "%PM_PACKAGES_ROOT%" ) if %errorlevel% neq 0 ( goto ERROR_MKDIR_PACKAGES_ROOT ) :: The Python interpreter may already be externally configured if defined PM_PYTHON_EXT ( set PM_PYTHON=%PM_PYTHON_EXT% goto PACKMAN ) set PM_PYTHON_VERSION=3.7.9-windows-x86_64 set PM_PYTHON_BASE_DIR=%PM_PACKAGES_ROOT%\python set PM_PYTHON_DIR=%PM_PYTHON_BASE_DIR%\%PM_PYTHON_VERSION% set PM_PYTHON=%PM_PYTHON_DIR%\python.exe if exist "%PM_PYTHON%" goto PACKMAN if not exist "%PM_PYTHON_BASE_DIR%" call :CREATE_PYTHON_BASE_DIR set PM_PYTHON_PACKAGE=python@%PM_PYTHON_VERSION%.cab for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME%.zip call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_PYTHON_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching python from CDN !!! goto ERROR ) for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_folder.ps1" -parentPath "%PM_PYTHON_BASE_DIR%"') do set TEMP_FOLDER_NAME=%%a echo Unpacking Python interpreter ... "%SystemRoot%\system32\expand.exe" -F:* "%TARGET%" "%TEMP_FOLDER_NAME%" 1> nul del "%TARGET%" :: Failure during extraction to temp folder name, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error unpacking python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :: If python has now been installed by a concurrent process we need to clean up and then continue if exist "%PM_PYTHON%" ( call :CLEAN_UP_TEMP_FOLDER goto PACKMAN ) else ( if exist "%PM_PYTHON_DIR%" ( rd /s /q "%PM_PYTHON_DIR%" > nul ) ) :: Perform atomic rename rename "%TEMP_FOLDER_NAME%" "%PM_PYTHON_VERSION%" 1> nul :: Failure during move, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error renaming python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :PACKMAN :: The packman module may already be externally configured if defined PM_MODULE_DIR_EXT ( set PM_MODULE_DIR=%PM_MODULE_DIR_EXT% ) else ( set PM_MODULE_DIR=%PM_PACKAGES_ROOT%\packman-common\%PM_PACKMAN_VERSION% ) set PM_MODULE=%PM_MODULE_DIR%\packman.py if exist "%PM_MODULE%" goto ENSURE_7ZA set PM_MODULE_PACKAGE=packman-common@%PM_PACKMAN_VERSION%.zip for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME% call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_MODULE_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching packman from CDN !!! goto ERROR ) echo Unpacking ... "%PM_PYTHON%" -S -s -u -E "%~dp0\install_package.py" "%TARGET%" "%PM_MODULE_DIR%" if %errorlevel% neq 0 ( echo !!! Error unpacking packman !!! goto ERROR ) del "%TARGET%" :ENSURE_7ZA set PM_7Za_VERSION=16.02.4 set PM_7Za_PATH=%PM_PACKAGES_ROOT%\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END set PM_7Za_PATH=%PM_PACKAGES_ROOT%\chk\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" pull "%PM_MODULE_DIR%\deps.packman.xml" if %errorlevel% neq 0 ( echo !!! Error fetching packman dependencies !!! goto ERROR ) goto END :ERROR_MKDIR_PACKAGES_ROOT echo Failed to automatically create packman packages repo at %PM_PACKAGES_ROOT%. echo Please set a location explicitly that packman has permission to write to, by issuing: echo. echo setx PM_PACKAGES_ROOT {path-you-choose-for-storing-packman-packages-locally} echo. echo Then launch a new command console for the changes to take effect and run packman command again. exit /B %errorlevel% :ERROR echo !!! Failure while configuring local machine :( !!! exit /B %errorlevel% :CLEAN_UP_TEMP_FOLDER rd /S /Q "%TEMP_FOLDER_NAME%" exit /B :CREATE_PYTHON_BASE_DIR :: We ignore errors and clean error state - if two processes create the directory one will fail which is fine md "%PM_PYTHON_BASE_DIR%" > nul 2>&1 exit /B 0 :END
NVIDIA-Omniverse/kit-extension-template/tools/packman/bootstrap/fetch_file_from_packman_bootstrap.cmd
:: 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. :: You need to specify <package-name> <target-path> as input to this command @setlocal @set PACKAGE_NAME=%1 @set TARGET_PATH=%2 @echo Fetching %PACKAGE_NAME% ... @powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0download_file_from_url.ps1" ^ -source "http://bootstrap.packman.nvidia.com/%PACKAGE_NAME%" -output %TARGET_PATH% :: A bug in powershell prevents the errorlevel code from being set when using the -File execution option :: We must therefore do our own failure analysis, basically make sure the file exists and is larger than 0 bytes: @if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED @if %~z2==0 goto ERROR_DOWNLOAD_FAILED @endlocal @exit /b 0 :ERROR_DOWNLOAD_FAILED @echo Failed to download file from S3 @echo Most likely because endpoint cannot be reached or file %PACKAGE_NAME% doesn't exist @endlocal @exit /b 1
NVIDIA-Omniverse/kit-extension-template/tools/packman/bootstrap/download_file_from_url.ps1
<# 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. #> param( [Parameter(Mandatory=$true)][string]$source=$null, [string]$output="out.exe" ) $filename = $output $triesLeft = 3 do { $triesLeft -= 1 try { Write-Host "Downloading from bootstrap.packman.nvidia.com ..." $wc = New-Object net.webclient $wc.Downloadfile($source, $fileName) $triesLeft = 0 } catch { Write-Host "Error downloading $source!" Write-Host $_.Exception|format-list -force } } while ($triesLeft -gt 0)